Refactor: lay the repo out by section (core, collection, analysis, planner, site) (#8)

Moves only; no behaviour changes. Every file now lives under the part of the project it
belongs to, each section has a README, and docs/PRIVACY.md collects the rules all parts follow.

  core/        engine.js, graph.js, solver.js, python/clean.py
  collection/  sources/ (form, register, PDF check, daily update), bot/ (importer)
  analysis/    stats/ (Python statistics), network/ (build-graph.js), reports/ (POLICY.md)
  planner/     build-policy.js, policy-report.js
  site/        atlas/ (the page), build.js, qa/
  tests/       core/ (unit), parity/ (JS vs Python), fixtures/

Checked against the previous layout: tests pass; coded runs, test outputs, graph.json and
policy.json are byte-identical; the built site differs only in comments that name file paths.
The published file names Ken's bot downloads (solver.js, graph.js, data/policy.json) are unchanged.

Also removes the undefined/ folder of QA screenshots committed by mistake (the QA scripts now
default to a temp folder) and test.txt, and drops the unused npm workspaces.


Claude-Session: https://claude.ai/code/session_01UCzTd31GphpMXDhQqWrCMQ

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ekcSchiano
2026-11-03 19:46:33 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent dcd5117373
commit 432e04c2c7
66 changed files with 201 additions and 2695 deletions
+704
View File
@@ -0,0 +1,704 @@
/* app.js — renders the Threshing Route Atlas from engine.js results. All numbers come from ThreshEngine. */
(function () {
"use strict";
const E = window.ThreshEngine;
const $ = (s, el = document) => el.querySelector(s);
const $$ = (s, el = document) => [...el.querySelectorAll(s)];
const NS = "http://www.w3.org/2000/svg";
const state = {
raw: null, bundled: null, allRuns: [], runs: [], res: null, missing: [],
filters: { source: "all", goal: "all", excludeFlagged: false },
target: "bond_any", widthMode: "traffic", minN: 10, conds: {},
fxOutcome: "blue_meadow", fxFactor: "resolution", rtTarget: "see_Blue", rtMin: 10,
};
// ------------------------------------------------------------ formatting
const pct = (p, d = 1) => (p === null || p === undefined || isNaN(p) ? "–" : (p * 100).toFixed(p > 0 && p < 0.001 ? 2 : d) + "%");
const ci = (w, d = 1) => (w && w.n ? `${pct(w.lo, d)}–${pct(w.hi, d)}` : "–");
const fmtOR = (x) => (x === null || x === undefined || !isFinite(x) ? "–" : x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2));
const fmtP = (p) => (p === null || p === undefined ? "–" : p < 0.0001 ? "<0.0001" : p < 0.001 ? p.toExponential(1) : p.toFixed(p < 0.01 ? 3 : 2));
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const kn = (w) => (w ? `${w.k}/${w.n}` : "–");
const rateTxt = (w, d = 1) => (w && w.n ? `${pct(w.p, d)} (${kn(w)}; 95% CI ${ci(w, d)})` : "no data");
function cssVar(name) { return getComputedStyle(document.documentElement).getPropertyValue(name).trim(); }
function rgb(c) {
c = c.trim();
if (c.startsWith("#")) {
const h = c.length === 4 ? c.slice(1).split("").map((x) => x + x).join("") : c.slice(1);
return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
}
const m = c.match(/\d+(\.\d+)?/g);
return m ? m.slice(0, 3).map(Number) : [128, 128, 128];
}
function mix(a, b, t) {
const A = rgb(a), B = rgb(b);
return `rgb(${A.map((v, i) => Math.round(v + (B[i] - v) * t)).join(",")})`;
}
const DRAGON_VAR = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const dragonColor = (c) => cssVar(DRAGON_VAR[c] || "--dr-any");
const targetColor = (t) => dragonColor(E.TARGETS[t].color);
function svgEl(tag, attrs = {}, parent) {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) if (v !== null && v !== undefined) e.setAttribute(k, v);
if (parent) parent.appendChild(e);
return e;
}
function toast(msg) {
const t = document.createElement("div");
t.className = "toast"; t.textContent = msg; document.body.appendChild(t);
setTimeout(() => t.remove(), 2200);
}
async function copyText(text, label) {
try { await navigator.clipboard.writeText(text); toast(`Copied ${label}`); }
catch (e) {
const ta = document.createElement("textarea");
ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select();
let ok = false; try { ok = document.execCommand("copy"); } catch (_) { /* ignore */ }
ta.remove(); toast(ok ? `Copied ${label}` : "Copy was blocked here. Select the text manually instead.");
}
}
// ------------------------------------------------------------ tooltip
const tip = $("#tip");
function showTip(evt, html) {
tip.innerHTML = html; tip.hidden = false;
const x = evt.clientX ?? (evt.touches && evt.touches[0].clientX) ?? 0, y = evt.clientY ?? 0;
const r = tip.getBoundingClientRect();
tip.style.left = Math.min(window.innerWidth - r.width - 8, x + 14) + "px";
tip.style.top = Math.min(window.innerHeight - r.height - 8, y + 14) + "px";
}
const hideTip = () => (tip.hidden = true);
// ------------------------------------------------------------ data loading
async function loadBundled() {
const resp = await fetch("data/form_responses.json");
const raw = await resp.json();
state.bundled = raw;
useRaw(raw, `bundled snapshot (${raw.source_file}, exported ${raw.exported})`);
}
function useRaw(raw, label) {
const { runs, missing } = E.codeRows(raw.rows, raw.headers);
state.raw = raw; state.allRuns = runs; state.missing = missing; state.dataLabel = label;
state.conds = {};
recompute();
}
$("#upload").addEventListener("change", async (e) => {
const f = e.target.files[0];
if (!f) return;
try {
const buf = await f.arrayBuffer();
const wb = XLSX.read(buf, { type: "array", cellDates: true });
const name = wb.SheetNames.find((n) => /form responses/i.test(n)) || wb.SheetNames[0];
const ws = wb.Sheets[name];
const headers = (XLSX.utils.sheet_to_json(ws, { header: 1, blankrows: false })[0] || []).map(String);
const rows = XLSX.utils.sheet_to_json(ws, { defval: null, raw: true });
useRaw({ rows, headers, source_file: f.name, exported: new Date().toISOString().slice(0, 10) }, `uploaded file ${f.name} (sheet "${name}")`);
$("#btn-reset-data").hidden = false;
toast(`Loaded ${rows.length} rows from ${f.name}`);
} catch (err) {
toast("That file could not be read. Export the responses sheet as .xlsx or .csv and try again.");
console.error(err);
}
e.target.value = "";
});
$("#btn-reset-data").addEventListener("click", () => { useRaw(state.bundled, `bundled snapshot (${state.bundled.source_file}, exported ${state.bundled.exported})`); $("#btn-reset-data").hidden = true; });
function recompute() {
state.runs = E.applyFilters(state.allRuns, state.filters);
state.res = E.analyse(state.allRuns, state.filters);
renderAll();
}
// ------------------------------------------------------------ header
function renderStatus() {
const m = state.res.meta;
const src = Object.entries(m.sources).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k} ${v.toLocaleString()}`).join(" · ");
const filt = [];
if (state.filters.source !== "all") filt.push(state.filters.source === "form" ? "form submissions only" : "bulk logs only");
if (state.filters.goal !== "all") filt.push(state.filters.goal === "exclude_rare" ? "not chasing Blue/Black" : "chasing Blue/Black");
if (state.filters.excludeFlagged) filt.push("flagged rows dropped");
$("#data-status").innerHTML = `
<span><b>${state.res.n.toLocaleString()}</b> runs${state.res.n !== state.allRuns.length ? ` of ${state.allRuns.length.toLocaleString()}` : ""}</span>
<span>${esc(src)}</span>
<span>Form dates ${m.date_min || "?"} → ${m.date_max || "?"}</span>
<span class="pill">${esc(state.dataLabel)}</span>
${filt.length ? `<span class="pill warn">Filtered: ${esc(filt.join(", "))}</span>` : ""}
${state.missing.length ? `<span class="pill warn">Questions not found in this file: ${esc(state.missing.join(", "))}</span>` : ""}`;
}
// ------------------------------------------------------------ findings
function stratumRate(chance, keyPart) {
const e = Object.entries(chance.by_stratum).find(([k]) => k.startsWith(keyPart));
return e ? e[1] : null;
}
const ROUTE_FACTORS = ["direction", "first_sighting", "resolution", "company"];
const NOT_A_CHOICE = /^(Unsure|Unknown|Multiple|\(not recorded\)|Unknown\/lost count|Unsure\/unknown)/;
function buildFindings() {
const r = state.res, out = [];
const cb = r.chance.blue_meadow, cs = r.chance.shadow;
const bulkB = stratumRate(cb, "Bulk"), chaseB = stratumRate(cb, "Form: chasing Blue"), otherB = stratumRate(cb, "Form: other");
const encBlue = r.encounters.find((e) => e.context === "Blue (meadow)");
const encBlack = r.encounters.find((e) => e.context === "Black (shadow)");
if (cb.overall.n) {
const biasShown = chaseB && bulkB && chaseB.n >= 20 && bulkB.n >= 20 && chaseB.lo > bulkB.hi;
let t;
if (biasShown) {
t = `<p><b>The meadow Blue appeared in ${rateTxt(cb.overall)} of logged meadow visits, but that figure is inflated.</b> Players chasing a rare dragon report it in ${pct(chaseB.p)} of their visits. Bulk logs, which record every run, show ${rateTxt(bulkB)}. The game cannot see what you are chasing, so that gap comes from which runs get reported.</p>`;
t += `<p>A realistic expectation is nearer the bulk-log rate, about one meadow visit in ${Math.round(1 / Math.max(bulkB.p, 0.001))}, than the headline figure.${otherB ? ` Form players who were not chasing a Blue report ${pct(otherB.p)}, which still carries some selective reporting.` : ""}</p>`;
} else {
t = `<p><b>The meadow Blue appeared in ${rateTxt(cb.overall)} of logged meadow visits in the current selection.</b> Compare the data-source filter settings to see how much this depends on who logged the runs.</p>`;
}
out.push(["bias", "Reporting bias", t]);
}
const mb = r.models.blue_meadow;
if (mb) {
const sig = mb.terms.filter((t) => ROUTE_FACTORS.includes(t.factor) && t.p < 0.05 && !NOT_A_CHOICE.test(t.level));
const rk = E.rankRoutes(state.runs, "see_Blue", state.rtMin);
const adjSig = rk.rows.filter((x) => x.mh_q !== undefined && x.mh_q < 0.05);
let t = sig.length
? `<p><b>After adjusting for reporting bias, ${sig.length === 1 ? "one recorded choice was" : sig.length + " recorded choices were"} linked to the Blue appearing:</b> ${sig.map((s) => `${esc(labelFactor(s.factor))}: ${esc(s.level)} (OR ${fmtOR(s.or)}, 95% CI ${fmtOR(s.lo)}–${fmtOR(s.hi)}, p = ${fmtP(s.p)})`).join("; ")}.</p>`
: `<p><b>No recorded route choice changed the chance of the Blue appearing once reporting bias is held fixed.</b> Direction, first sighting, how you handled the cadet and who you entered with all have adjusted odds ratios whose 95% intervals include 1 (n = ${mb.n} meadow visits).</p>`;
t += `<p>Of ${rk.n_routes_tested} full routes with at least ${state.rtMin} meadow visits, ${adjSig.length} beat the others after adjustment and correction for multiple testing. The "precise pathways" shared on Reddit may still matter through choices the form does not record, such as the answers given inside each encounter.</p>`;
out.push(["blue", "Blue", t]);
}
if (encBlue && encBlue.overall.n) {
out.push(["blue", "Blue", `<p><b>Reaching the Blue is not enough. Only ${rateTxt(encBlue.overall)} of Blue attempts ended in a bond</b> (${pct(encBlue.intent_matched.p)} when the player wanted a Blue). The community PDF's step-by-step survival rates multiply out to about 25% for the standard answers. Expect several Blue encounters per bond, and do not treat one death as proof that an answer is wrong.</p>`]);
}
if (cs.overall.n) {
const bulkS = stratumRate(cs, "Bulk"), formS = Object.entries(cs.by_stratum).filter(([k]) => k.startsWith("Form"));
const fk = formS.reduce((a, [, w]) => a + w.k, 0), fn = formS.reduce((a, [, w]) => a + w.n, 0);
const fw = E.wilson(fk, fn);
let t = `<p><b>The tree shadow showed up in ${rateTxt(cs.overall)} of logged tree climbs.</b>${fn ? ` Form submissions: ${rateTxt(fw)}.` : ""}`;
if (bulkS && bulkS.n >= 30 && fn >= 30 && fw.lo > bulkS.hi) t += ` Bulk logs: ${rateTxt(bulkS)}. Those two cannot both be the true rate for the same game. The form figure is the one exposed to selective reporting, so the true rate is probably nearer the bulk logs, whose 95% upper bound is ${pct(bulkS.hi)} per climb.`;
t += `</p>`;
if (encBlack && encBlack.overall.n) t += `<p>Once the Black appears it is the easiest dragon to bond: ${rateTxt(encBlack.overall)}.</p>`;
out.push(["black", "Black", t]);
}
// leads: unadjusted factor rows with q < 0.05 on route-type factors, for the shadow
const leadF = ["post_path", "attempt_group", "direction", "first_sighting", "resolution", "company", "combat_first"];
const sh = r.factors.shadow.rows.filter((x) => leadF.includes(x.factor) && x.q !== undefined && x.q < 0.05 && x.or > 1 && !NOT_A_CHOICE.test(x.level));
if (sh.length) {
const ms = r.models.shadow;
let t = `<p><b>Shadow leads to test, not established:</b> ${sh.map((x) => `<i>${esc(labelFactor(x.factor))}: ${esc(x.level)}</i> had the shadow in ${rateTxt(x)} vs the rest (OR ${fmtOR(x.or)}, q = ${fmtP(x.q)})`).join("; ")}.</p>`;
const att = ms && ms.terms.find((tm) => tm.factor === "attempt" && tm.level === "First attempt");
if (att) t += `<p>The first-attempt pattern survives adjustment for data source, chase goal and direction (OR ${fmtOR(att.or)}, 95% CI ${fmtOR(att.lo)}–${fmtOR(att.hi)}). That matches a theory on Reddit that a fresh account rolls the shadow more often, but players who strike lucky on a first run may also be more likely to submit the form.</p>`;
t += `<p>The cheapest test is a bulk log that records every tree climb, including the dull ones, with these choices noted.</p>`;
out.push(["lead", "Lead", t]);
}
// common dragons
const common = r.encounters.filter((e) => ["Red (valley)", "Green (two Greens)", "Orange (meadow)", "Brown (meadow)", "Red (tree, descend quickly)"].includes(e.context) && e.intent_matched.n >= 10);
if (common.length) {
out.push(["", "Common", `<p><b>For the common colours, intent matters more than route.</b> Among players who wanted that colour: ${common.map((e) => `${esc(e.context)} ${pct(e.intent_matched.p, 0)} (${kn(e.intent_matched)})`).join(", ")}. The tree Red is the hardest bond in the game.</p>`]);
}
return out;
}
function renderFindings() {
$("#findings-list").innerHTML = buildFindings().map(([cls, tag, html], i) =>
`<div class="finding ${cls}"><span class="mark">${i + 1}</span><div><span class="tag">${esc(tag)}</span>${html}</div></div>`).join("");
}
const FACTOR_LABEL = { company: "Company", direction: "Direction", first_sighting: "First sighting", scream: "Scream choice", resolution: "Cadet encounter",
combat_first: "First combat move", post_path: "Fork in the road", hour: "After an hour", wing: "Wing", squad: "Squad",
attempt_group: "Attempt", source: "Data source", goal: "Chasing", attempt: "Attempt", period: "Date",
sighting_action: "Reaction to the first dragon", combat_second: "Second combat move", malek_intent: "Planned to seek Malek", };
const labelFactor = (f) => FACTOR_LABEL[f] || f;
// ------------------------------------------------------------ route map
// first row: bonding each dragon (all six treated alike); second row: the two rare sightings
const RARE_T = ["bond_Red", "bond_Orange", "bond_Brown", "bond_Green", "bond_Blue", "bond_Black", "bond_any"];
const OTHER_T = ["see_Blue", "see_shadow"];
function renderTargets() {
const chip = (t, featured) => {
const c = E.TARGETS[t].color ? DRAGON_VAR[E.TARGETS[t].color] : "--dr-any";
return `<button type="button" class="tchip${featured ? " featured" : ""}" data-t="${t}" aria-pressed="${state.target === t}" style="--c: var(${c})"><span class="sw"></span>${esc(E.TARGETS[t].label)}</button>`;
};
$("#targets-rare").innerHTML = RARE_T.map((t) => chip(t, false)).join("");
$("#targets-other").innerHTML = OTHER_T.map((t) => chip(t, false)).join("");
$$(".tchip[data-t]").forEach((b) => b.addEventListener("click", () => { state.target = b.dataset.t; $("#best-routes").innerHTML = ""; renderTargets(); renderMap(); }));
}
const ORDER = {
company: ["Alone", "1 Squadmate", "2 Squadmates"],
direction: ["East", "Center", "West"],
first_sighting: ["Red", "Orange", "Brown", "Green"],
post_path: ["Forest", "West", "East", "(no fork)"],
hour: ["Climb the tree", "Valley centre"],
encounter: ["Tree: Red below", "Tree: two Greens", "Tree: shadow → Blue/Black", "Valley: bond the Red", "Meadow: Orange", "Meadow: Brown", "Meadow: Orange/Brown", "Meadow: Blue", "Meadow (no attempt recorded)"],
end: ["Bonded Red", "Bonded Green", "Bonded Orange", "Bonded Brown", "Bonded Blue", "Bonded Black", "Incinerated", "Died before the hour"],
};
const SHORT = {
"Help → Killed the bullies yourself": "Help · killed bullies", "Help → Squadmate's revenge": "Help · squadmate's revenge",
"Help → Left bullies to the dragons": "Help · left to dragons", "Help → DIED in combat": "Help · died in combat", "Help → Unknown": "Help · unknown",
"Ignore the scream → Tourniquet": "Ignore · tourniquet", "Ignore the scream → Left injured cadet": "Ignore · left cadet",
"Ignore the scream → Took their weapons": "Ignore · took weapons", "Investigate & leave → Left them to it": "Investigate · walked away",
"Tree: shadow → Blue/Black": "Tree: shadow (Blue→Black)", "Meadow (no attempt recorded)": "Meadow: none recorded", "Unknown → Unknown": "Unknown",
};
const short = (v) => SHORT[v] || v;
const condSets = () => Object.fromEntries(Object.entries(state.conds).map(([k, v]) => [k, new Set(v)]));
function renderMap() {
const svg = $("#map");
svg.innerHTML = "";
const runs = state.runs;
const base = E.buildGraph(runs, state.target, {});
const sel = E.buildGraph(runs, state.target, condSets());
const hasSel = Object.values(state.conds).some((v) => v.length);
const selNode = new Map(sel.nodes.map((n) => [n.id, n]));
const minN = state.minN;
const tcol = targetColor(state.target), low = cssVar("--link-low"), surface = cssVar("--raised");
const shell = $(".map-scroll");
const W = Math.max(1440, shell.clientWidth || 1440), H = 660, top = 40, bottom = 16, left = 10, right = 168, nodeW = 12;
svg.setAttribute("width", W); svg.setAttribute("height", H); svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
const S = E.STAGES.length;
const colX = (i) => left + (i * (W - left - right - nodeW)) / (S - 1);
const cols = E.STAGES.map((s, i) => {
const ns = base.nodes.filter((n) => n.stage === i);
const ord = ORDER[s.key];
ns.sort((a, b) => {
const ia = ord ? ord.indexOf(a.value) : -1, ib = ord ? ord.indexOf(b.value) : -1;
if (ia !== -1 || ib !== -1) return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib);
return b.n - a.n;
});
return ns;
});
const pad = 7;
const maxTotal = Math.max(...cols.map((c) => c.reduce((s, n) => s + n.n, 0)));
const maxCount = Math.max(...cols.map((c) => c.length));
const scale = (H - top - bottom - pad * (maxCount - 1)) / maxTotal;
const pos = new Map();
cols.forEach((ns, i) => {
const hTot = ns.reduce((s, n) => s + Math.max(2, n.n * scale), 0) + pad * (ns.length - 1);
let y = top + (H - top - bottom - hTot) / 2;
ns.forEach((n) => { const h = Math.max(2, n.n * scale); pos.set(n.id, { x: colX(i), y, h, n }); y += h + pad; });
});
// colour scale: anchored on the route steps, not on the outcome column (where the target node is 100% by definition)
const lastStage = S - 1;
const stageOf = (id) => +id.split("|")[0];
const eligible = sel.links.filter((l) => l.n >= minN && stageOf(l.target) < lastStage);
const pmax = Math.max(0.005, ...eligible.map((l) => l.p), ...sel.nodes.filter((n) => n.n >= minN && n.stage < lastStage).map((n) => n.p));
const colorFor = (o) => (o.n < minN ? low : mix(low, tcol, Math.pow(Math.min(1, o.p / pmax), 0.75)));
// stage headers
E.STAGES.forEach((s, i) => {
const chance = s.key === "first_sighting" || s.key === "encounter";
const t = svgEl("text", { x: colX(i), y: 18, class: "stage-label" + (chance ? " stage-chance" : "") }, svg);
t.textContent = s.label;
if (chance) { const r = svgEl("text", { x: colX(i), y: 31, class: "stage-label stage-chance" }, svg); r.textContent = "game roll"; }
});
// links
const gLinks = svgEl("g", {}, svg);
const outOff = new Map(), inOff = new Map();
const linksSorted = sel.links.slice().sort((a, b) => pos.get(a.source).y - pos.get(b.source).y || pos.get(a.target).y - pos.get(b.target).y);
// order out-links by target y and in-links by source y for clean stacking
const byOut = {}, byIn = {};
linksSorted.forEach((l) => { (byOut[l.source] = byOut[l.source] || []).push(l); (byIn[l.target] = byIn[l.target] || []).push(l); });
Object.values(byOut).forEach((ls) => ls.sort((a, b) => pos.get(a.target).y - pos.get(b.target).y));
Object.values(byIn).forEach((ls) => ls.sort((a, b) => pos.get(a.source).y - pos.get(b.source).y));
const offOut = {}, offIn = {};
Object.entries(byOut).forEach(([id, ls]) => { let o = 0; ls.forEach((l) => { offOut[l.id] = o; o += l.n * scale; }); });
Object.entries(byIn).forEach(([id, ls]) => { let o = 0; ls.forEach((l) => { offIn[l.id] = o; o += l.n * scale; }); });
const drawOrder = state.widthMode === "prob" ? sel.links.slice().sort((a, b) => (a.n >= minN) - (b.n >= minN) || a.p - b.p) : linksSorted;
drawOrder.forEach((l) => {
const s = pos.get(l.source), t = pos.get(l.target);
if (!s || !t) return;
const x0 = s.x + nodeW, x1 = t.x, xm = (x0 + x1) / 2;
let el;
if (state.widthMode === "traffic") {
const w = Math.max(0.6, l.n * scale);
const y0 = s.y + offOut[l.id], y1 = t.y + offIn[l.id];
el = svgEl("path", {
d: `M${x0},${y0}C${xm},${y0} ${xm},${y1} ${x1},${y1}L${x1},${y1 + w}C${xm},${y1 + w} ${xm},${y0 + w} ${x0},${y0 + w}Z`,
fill: colorFor(l), "fill-opacity": l.n >= minN ? 0.62 : 0.3, class: "link",
}, gLinks);
} else {
const y0 = s.y + s.h / 2, y1 = t.y + t.h / 2;
const w = l.n >= minN ? 1.2 + 18 * (l.p / pmax) : 1;
el = svgEl("path", { d: `M${x0},${y0}C${xm},${y0} ${xm},${y1} ${x1},${y1}`, fill: "none", stroke: colorFor(l), "stroke-width": w, "stroke-opacity": l.n >= minN ? 0.8 : 0.3, "stroke-linecap": "round", class: "link" }, gLinks);
}
const sv = pos.get(l.source).n.value, tv = pos.get(l.target).n.value;
el.addEventListener("mousemove", (e) => showTip(e, `<div class="t">${esc(sv)} → ${esc(tv)}</div>${l.n} runs${hasSel ? " (in your selection)" : ""}<br>${esc(E.TARGETS[state.target].label)}: <b>${pct(l.p)}</b> (${kn(l)})<br>95% CI ${ci(l)}${l.n < minN ? "<br><i>Too few runs to read</i>" : ""}`));
el.addEventListener("mouseleave", hideTip);
});
// nodes
const gNodes = svgEl("g", {}, svg);
cols.forEach((ns, i) => {
let lastLabelBottom = -1e9;
ns.forEach((bn) => {
const p = pos.get(bn.id), sn = selNode.get(bn.id);
const isSel = (state.conds[E.STAGES[i].key] || []).includes(bn.value);
const g = svgEl("g", { class: "node" + (isSel ? " sel" : "") + (hasSel && !sn ? " dim" : ""), tabindex: 0, role: "button", "aria-label": `${E.STAGES[i].label}: ${bn.value}, ${bn.n} runs` }, gNodes);
const shown = sn || { n: 0, k: 0, p: null };
svgEl("rect", { x: p.x, y: p.y, width: nodeW, height: p.h, rx: 2, fill: sn ? colorFor(sn) : low }, g);
const lx = p.x + nodeW + 5, ly = p.y + p.h / 2 + 4;
if (ly - 11 > lastLabelBottom || isSel) {
const t = svgEl("text", { x: lx, y: ly, "paint-order": "stroke", stroke: surface, "stroke-width": 3, "stroke-linejoin": "round" }, g);
const lab = short(bn.value), maxC = i === S - 1 ? 30 : Math.floor((colX(1) - colX(0) - nodeW - 36) / 5.8);
t.textContent = lab.length > maxC ? lab.slice(0, maxC - 1) + "…" : lab;
const t2 = svgEl("tspan", { fill: cssVar("--muted"), dx: 4 }, t);
t2.textContent = sn && sn.n >= minN ? pct(sn.p, 0) : sn ? `n=${sn.n}` : "";
lastLabelBottom = ly;
}
const html = () => `<div class="t">${esc(E.STAGES[i].label)}: ${esc(bn.value)}</div>${hasSel ? `${shown.n} of ${bn.n} runs in your selection` : `${bn.n} runs`}<br>${esc(E.TARGETS[state.target].label)}: <b>${pct(shown.p)}</b> (${shown.k}/${shown.n})<br>95% CI ${ci(sn)}<br><span class="muted">Click to ${isSel ? "remove from" : "add to"} the selection</span>`;
g.addEventListener("mousemove", (e) => showTip(e, html()));
g.addEventListener("mouseleave", hideTip);
const toggle = () => {
const k = E.STAGES[i].key, cur = new Set(state.conds[k] || []);
cur.has(bn.value) ? cur.delete(bn.value) : cur.add(bn.value);
state.conds[k] = [...cur];
if (!state.conds[k].length) delete state.conds[k];
hideTip(); renderMap();
};
g.addEventListener("click", toggle);
g.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggle(); } });
});
});
renderCondChips(); renderSelSummary(sel); renderLegend(pmax, tcol, low);
}
function renderCondChips() {
const entries = Object.entries(state.conds).filter(([, v]) => v.length);
$("#cond-chips").innerHTML = entries.length
? entries.map(([k, vals]) => vals.map((v) => `<span class="cchip">${esc(E.STAGES.find((s) => s.key === k).label)}: ${esc(v)}<button type="button" aria-label="Remove ${esc(v)}" data-k="${esc(k)}" data-v="${esc(v)}">×</button></span>`).join("")).join("")
: `<span class="small muted">Showing all runs. Click a box to follow only the runs through it.</span>`;
$$("#cond-chips button").forEach((b) => b.addEventListener("click", () => {
state.conds[b.dataset.k] = (state.conds[b.dataset.k] || []).filter((v) => v !== b.dataset.v);
if (!state.conds[b.dataset.k].length) delete state.conds[b.dataset.k];
renderMap();
}));
}
function renderSelSummary(sel) {
const T = E.TARGETS[state.target];
const cs = condSets();
const inSel = (r) => Object.entries(cs).every(([k, set]) => !set.size || set.has(E.stageValue(r, k)));
const pool = state.runs.filter(T.pool);
const A = pool.filter(inSel), B = pool.filter((r) => !inSel(r));
const wa = E.wilson(A.filter(T.fn).length, A.length), wb = E.wilson(B.filter(T.fn).length, B.length);
const hasSel = Object.keys(state.conds).length > 0;
let cmp = "";
if (hasSel && A.length && B.length) {
const o = E.oddsRatio(wa.k, wa.n - wa.k, wb.k, wb.n - wb.k);
cmp = `<div>Everyone else: ${pct(wb.p)} (${kn(wb)}). Odds ratio ${fmtOR(o.or)} (95% CI ${fmtOR(o.or_lo)}–${fmtOR(o.or_hi)}), Fisher p = ${fmtP(o.fisher_p)}. This is unadjusted: if your selection mixes in a lot of Blue-chasers, expect it to look better than it is.</div>`;
}
$("#sel-summary").innerHTML = `
<span class="eyebrow">${hasSel ? "Your selection" : "All runs"} · ${esc(T.label)}</span>
<div><span class="big">${pct(wa.p)}</span> <span class="muted">${kn(wa)} runs that could reach it · 95% CI ${ci(wa)}</span></div>
${cmp}`;
}
function renderLegend(pmax, tcol, low) {
$("#legend").innerHTML = `
<span>${state.widthMode === "traffic" ? "Band width = number of runs" : "Line width = chance of the outcome"}</span>
<span style="display:inline-flex;gap:6px;align-items:center">0% <span class="ramp" style="background:linear-gradient(90deg, ${low}, ${tcol})"></span> ${pct(pmax, 0)}</span>
<span>Grey = fewer than ${state.minN} runs</span>
<span><span style="color:var(--accent)">Gold headings</span> = steps the game rolls, not you</span>`;
}
function renderBestRoutes() {
const rk = E.rankRoutes(state.runs, state.target, state.minN);
const rows = rk.rows.slice(0, 8);
const sigN = rk.rows.filter((r) => r.mh_q !== undefined && r.mh_q < 0.05 && r.mh_or > 1).length;
$("#best-routes").innerHTML = `<div class="panel">
<h3>Top routes for "${esc(E.TARGETS[state.target].label)}" <span class="small muted">routes with ≥ ${state.minN} runs, ranked by the lower end of the 95% interval</span></h3>
<p class="small">${rows.length ? `Overall rate in the comparison group: ${rateTxt(rk.overall)}. <b>${sigN} of ${rk.n_routes_tested} routes are better than the rest after adjusting for reporting bias and multiple testing.</b> ${sigN === 0 ? "Treat the ordering below as noise unless a newer export changes this." : ""}` : "No route has enough runs at this threshold. Lower the minimum."}</p>
${rows.length ? `<div class="tbl-wrap"><table><thead><tr><th>Route (choices up to the hour)</th><th class="num">Runs</th><th class="num">Rate</th><th class="num">95% CI</th><th class="num">Adj. OR</th><th class="num">Adj. q</th><th></th></tr></thead><tbody>
${rows.map((r, i) => `<tr class="${r.mh_q < 0.05 && r.mh_or > 1 ? "sig" : ""}"><td class="route-cell">${esc(r.route)}</td><td class="num">${r.n}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td class="num">${fmtOR(r.mh_or)}</td><td class="num">${fmtP(r.mh_q)}</td><td><button type="button" data-i="${i}">Follow</button></td></tr>`).join("")}
</tbody></table></div>` : ""}</div>`;
$$("#best-routes button[data-i]").forEach((b) => b.addEventListener("click", () => {
const r = rows[+b.dataset.i];
state.conds = {};
E.STAGES.slice(0, 6).forEach((s, i) => { if (r.values[i]) state.conds[s.key] = [r.values[i]]; });
renderMap();
$("#map-sec").scrollIntoView({ behavior: "smooth" });
}));
}
// ------------------------------------------------------------ small charts
// Horizontal rate bars with 95% CI whiskers.
function ciBars(el, rows, opts = {}) {
const W = 640, rowH = opts.rowH || 26, lw = opts.labelW || 190, top = 8, bottom = 26;
const H = top + bottom + rows.length * rowH;
const xmax = opts.max || Math.min(1, Math.max(0.05, ...rows.map((r) => r.hi || 0)) * 1.08);
const x = (v) => lw + (v / xmax) * (W - lw - 120);
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const ticks = niceTicks(xmax);
const ga = svgEl("g", { class: "axis" }, svg);
ticks.forEach((t) => {
svgEl("line", { x1: x(t), x2: x(t), y1: top, y2: H - bottom + 4 }, ga);
const tx = svgEl("text", { x: x(t), y: H - 8, "text-anchor": "middle" }, ga); tx.textContent = pct(t, 0);
});
rows.forEach((r, i) => {
const y = top + i * rowH + rowH / 2;
const lab = svgEl("text", { x: lw - 8, y: y + 4, "text-anchor": "end" }, svg); lab.textContent = r.label;
if (r.indent) lab.setAttribute("fill", cssVar("--muted"));
if (!r.n) { const t = svgEl("text", { x: lw, y: y + 4, fill: cssVar("--faint") }, svg); t.textContent = "no runs"; return; }
const col = r.color || cssVar("--muted");
svgEl("rect", { x: lw, y: y - 7, width: Math.max(1, x(r.p) - lw), height: 14, fill: col, "fill-opacity": 0.28, rx: 2 }, svg);
svgEl("line", { x1: x(r.lo), x2: x(r.hi), y1: y, y2: y, stroke: col, "stroke-width": 2 }, svg);
svgEl("line", { x1: x(r.lo), x2: x(r.lo), y1: y - 5, y2: y + 5, stroke: col, "stroke-width": 2 }, svg);
svgEl("line", { x1: x(r.hi), x2: x(r.hi), y1: y - 5, y2: y + 5, stroke: col, "stroke-width": 2 }, svg);
svgEl("circle", { cx: x(r.p), cy: y, r: 4, fill: col }, svg);
const v = svgEl("text", { x: x(r.hi) + 6, y: y + 4, "font-family": "var(--font-data)" }, svg);
v.textContent = `${pct(r.p)} · ${r.k}/${r.n}`;
});
el.innerHTML = ""; el.appendChild(svg);
}
function niceTicks(max) {
const steps = [0.01, 0.02, 0.05, 0.1, 0.2, 0.25];
const step = steps.find((s) => max / s <= 6) || 0.25;
const out = []; for (let v = 0; v <= max + 1e-9; v += step) out.push(+v.toFixed(4)); return out;
}
// Forest plot of odds ratios on a log axis.
function forest(el, terms, opts = {}) {
const W = 640, rowH = 22, lw = opts.labelW || 290, top = 8, bottom = 28;
const H = top + bottom + Math.max(1, terms.length) * rowH;
const lo = 0.05, hi = 20;
const x = (v) => lw + ((Math.log(Math.min(hi, Math.max(lo, v))) - Math.log(lo)) / (Math.log(hi) - Math.log(lo))) * (W - lw - 60);
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const ga = svgEl("g", { class: "axis" }, svg);
[0.1, 0.25, 0.5, 1, 2, 4, 10].forEach((t) => {
svgEl("line", { x1: x(t), x2: x(t), y1: top, y2: H - bottom + 4, "stroke-dasharray": t === 1 ? "" : "2 3", "stroke-width": t === 1 ? 1.5 : 1 }, ga);
const tx = svgEl("text", { x: x(t), y: H - 10, "text-anchor": "middle" }, ga); tx.textContent = t;
});
terms.forEach((t, i) => {
const y = top + i * rowH + rowH / 2;
const sig = t.p !== undefined ? t.p < 0.05 : t.q < 0.05;
const col = sig ? cssVar("--accent") : cssVar("--muted");
const lab = svgEl("text", { x: lw - 8, y: y + 4, "text-anchor": "end" }, svg);
lab.textContent = (t.label.length > 40 ? t.label.slice(0, 39) + "…" : t.label) + (t.n !== undefined ? ` (n=${t.n})` : "");
svgEl("line", { x1: x(t.lo), x2: x(t.hi), y1: y, y2: y, stroke: col, "stroke-width": 2 }, svg);
svgEl("rect", { x: x(t.or) - 4, y: y - 4, width: 8, height: 8, fill: col }, svg);
const v = svgEl("text", { x: W - 4, y: y + 4, "text-anchor": "end", "font-family": "var(--font-data)", fill: cssVar("--muted") }, svg);
v.textContent = fmtOR(t.or);
});
el.innerHTML = ""; el.appendChild(svg);
}
// ------------------------------------------------------------ rare section
const STRATUM_ORDER = ["Bulk logs (imports)", "Form: other/blank goal", "Form: chasing Black", "Form: chasing Blue", "Form: chasing Blue or Black"];
function renderRare() {
const r = state.res;
const blueCol = dragonColor("Blue"), blackCol = dragonColor("Black");
const strataRows = (c, col) => [{ label: "All rows", ...c.overall, color: cssVar("--ink") }].concat(
STRATUM_ORDER.filter((s) => c.by_stratum[s]).map((s) => ({ label: s, ...c.by_stratum[s], color: col })),
Object.entries(c.by_attempt).filter(([k]) => !E.isMissing(k)).map(([k, w]) => ({ label: k, ...w, color: cssVar("--accent") })));
ciBars($("#ch-blue-strata"), strataRows(r.chance.blue_meadow, blueCol), { labelW: 180 });
ciBars($("#ch-shadow-strata"), strataRows(r.chance.shadow, blackCol), { labelW: 180 });
const termsOf = (m, skip = []) => (m ? m.terms.filter((t) => t.n >= 5 && !skip.includes(t.factor) && !E.isMissing(t.level)) /* the "goal not asked" stratum stays in the model as an adjustment, but is not a finding */.map((t) => ({ label: `${labelFactor(t.factor)}: ${t.level}`, or: t.or, lo: t.lo, hi: t.hi, p: t.p, n: t.n })) : []);
const mb = r.models.blue_meadow, ms = r.models.shadow;
forest($("#ch-model-blue"), termsOf(mb));
forest($("#ch-model-shadow"), termsOf(ms));
const refTxt = (m) => (m ? `Reference answers: ${Object.entries(m.refs).map(([f, v]) => `${labelFactor(f)} = ${v}`).join(", ")}. n = ${m.n}, events = ${m.events}. Gold = p < 0.05 (not corrected for the number of terms).` : "Not enough data.");
$("#model-blue-note").textContent = refTxt(mb);
$("#model-shadow-note").textContent = refTxt(ms);
renderDaily();
const enc = r.encounters.filter((e) => ["Blue (meadow)", "Blue (shadow)", "Black (shadow)"].includes(e.context));
ciBars($("#ch-rare-bond"), enc.flatMap((e) => [
{ label: e.context, ...e.overall, color: dragonColor(e.color) },
{ label: "↳ players who wanted it", ...e.intent_matched, color: dragonColor(e.color), indent: true }]), { labelW: 200, max: 1 });
renderPdfSteps();
}
function renderDaily() {
const d = state.res.daily.filter((x) => x.meadow_n + x.tree_n > 0);
const el = $("#ch-daily");
if (!d.length) { el.textContent = "No dated runs in the current filter."; return; }
const W = 640, H = 250, l = 44, rgt = 24, top = 16, mid = 125, bottom = 30;
const svg = svgEl("svg", { viewBox: `0 0 ${W} ${H}`, width: W, height: H, role: "img" });
const x = (i) => l + (d.length === 1 ? (W - l - rgt) / 2 : (i * (W - l - rgt)) / (d.length - 1));
const panels = [
{ y0: top, y1: mid - 14, k: "blue_k", n: "meadow_n", col: dragonColor("Blue"), name: "Blue in meadow" },
{ y0: mid + 6, y1: H - bottom, k: "shadow_k", n: "tree_n", col: dragonColor("Black"), name: "Shadow at tree" },
];
panels.forEach((P) => {
const vals = d.map((r) => E.wilson(r[P.k], r[P.n]));
const ymax = Math.min(1, Math.max(0.05, ...vals.filter((v) => v.n >= 5).map((v) => v.hi)));
const y = (v) => P.y1 - (v / ymax) * (P.y1 - P.y0);
const ga = svgEl("g", { class: "axis" }, svg);
[0, ymax / 2, ymax].forEach((t) => { svgEl("line", { x1: l, x2: W - rgt, y1: y(t), y2: y(t) }, ga); const tx = svgEl("text", { x: l - 6, y: y(t) + 3, "text-anchor": "end" }, ga); tx.textContent = pct(t, 0); });
const nm = svgEl("text", { x: l + 4, y: P.y0 + 10, fill: P.col, "font-weight": 600 }, svg); nm.textContent = P.name;
const yc = (v) => y(Math.min(ymax, v));
vals.forEach((v, i) => {
if (v.n < 3) return;
svgEl("line", { x1: x(i), x2: x(i), y1: yc(v.lo), y2: yc(v.hi), stroke: P.col, "stroke-opacity": 0.45, "stroke-width": 1.5 }, svg);
const c = svgEl("circle", { cx: x(i), cy: yc(v.p), r: 2 + Math.sqrt(v.n) / 2.2, fill: P.col, "fill-opacity": 0.85 }, svg);
c.addEventListener("mousemove", (e) => showTip(e, `<div class="t">${d[i].date} · ${P.name}</div>${pct(v.p)} (${kn(v)})<br>95% CI ${ci(v)}`));
c.addEventListener("mouseleave", hideTip);
});
});
const ga = svgEl("g", { class: "axis" }, svg);
d.forEach((r, i) => { if (i % Math.ceil(d.length / 8) === 0 || i === d.length - 1) { const t = svgEl("text", { x: x(i), y: H - 10, "text-anchor": "middle" }, ga); t.textContent = r.date.slice(5); } });
el.innerHTML = ""; el.appendChild(svg);
}
function renderPdfSteps() {
const blue = [["Approach the Blue: “Absolutely…”", "90%"], ["Hold the Blue's glare and advance", "80%"], ["Do nothing (it seizes the other cadet)", "82%"], ["Hold glare and watch", "84%"], ["Straighten your spine", "83%"], ["Launch yourself right (boulder)", "93%"], ["“Bring down an empire”", "81%"], ["Move slowly forward, wait for an invitation", "81%"]];
const prod = [0.9, 0.8, 0.82, 0.84, 0.83, 0.93, 0.81, 0.81].reduce((a, b) => a * b, 1);
$("#pdf-steps").innerHTML = `<p class="small muted">As published in the community PDF (u/ClumsyBadger, u/Old_Regular3018). These come from hand-coded free-text answers. The underlying counts are not shown there, and many cells rest on fewer than 10 runs.</p>
<div class="tbl-wrap"><table><thead><tr><th>Meadow Blue, standard answers</th><th class="num">Survived step</th></tr></thead><tbody>${blue.map(([a, b]) => `<tr><td>${a}</td><td class="num">${b}</td></tr>`).join("")}
<tr><td><b>All eight steps (product)</b></td><td class="num"><b>${pct(prod, 0)}</b></td></tr></tbody></table></div>
<p class="small">The product, about ${pct(prod, 0)}, agrees with the form's own Blue bond rate (${rateTxt(state.res.encounters.find((e) => e.context === "Blue (meadow)").overall)}), which is a useful cross-check.</p>
<div class="tbl-wrap"><table><thead><tr><th>Black (after the shadow and the tree Blue)</th><th class="num">PDF outcome</th></tr></thead><tbody>
<tr><td>Turn to face the threat → hold its gaze</td><td class="num">66% bonded · 33% incinerated</td></tr>
<tr><td>Turn to face the threat → lower your eyes → try to mount → meet its gaze</td><td class="num">100% bonded (very few runs)</td></tr></tbody></table></div>`;
}
// ------------------------------------------------------------ every dragon
function renderDragons() {
const r = state.res;
const order = ["Red (valley)", "Red (tree, descend quickly)", "Green (two Greens)", "Orange (meadow)", "Brown (meadow)", "Blue (meadow)", "Blue (shadow)", "Black (shadow)"];
const rows = order.map((c) => r.encounters.find((e) => e.context === c)).filter(Boolean).flatMap((e) => [
{ label: `${e.context}`, ...e.overall, color: dragonColor(e.color) },
{ label: "↳ players who wanted it", ...e.intent_matched, color: dragonColor(e.color), indent: true }]);
const box = $("#ch-encounters");
box.innerHTML = `<h3>Bond rate once the encounter starts</h3><div class="chart" id="ch-enc-inner"></div>`;
ciBars($("#ch-enc-inner"), rows, { labelW: 220, max: 1, rowH: 22 });
const g = r.green_rescue;
const parts = [["Bonded a Green", g.bonded_green, dragonColor("Green")], ["Rescued, bonded the Orange", g.rescued_orange, dragonColor("Orange")], ["Rescued, bonded the Brown", g.rescued_brown, dragonColor("Brown")], ["Incinerated", g.incinerated, cssVar("--faint")], ["No outcome recorded", g.green_encounters - g.bonded_green - g.rescued_orange - g.rescued_brown - g.incinerated, cssVar("--line")]];
const tot = g.green_encounters || 1;
$("#green-rescue").innerHTML = `<p class="small muted">${g.green_encounters} tree runs that descended slowly to the two Greens. A wrong answer sometimes brings an Orange or Brown swooping in to bond you instead.</p>
<div style="display:flex;height:16px;border-radius:3px;overflow:hidden;border:1px solid var(--line)">${parts.map(([, n, c]) => `<span style="width:${(100 * n) / tot}%;background:${c}"></span>`).join("")}</div>
<div class="tbl-wrap"><table><tbody>${parts.map(([l, n, c]) => { const w = E.wilson(n, g.green_encounters); return `<tr><td><span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:${c};margin-right:6px"></span>${l}</td><td class="num">${n}</td><td class="num">${pct(w.p)}</td><td class="num">${ci(w)}</td></tr>`; }).join("")}</tbody></table></div>`;
// "Unsure" / blank first sightings are missing information, not a colour: left out of the table and its totals
const cols = ["Red", "Orange", "Brown", "Green"];
const POOL = { "Alone|East": ["Red", "Orange"], "Alone|West": ["Red", "Brown", "Green"], "Alone|Center": ["Red", "Brown"], "1 Squadmate|East": ["Green", "Orange", "Red"], "1 Squadmate|West": ["Red", "Brown", "Green"], "1 Squadmate|Center": ["Red", "Brown"], "2 Squadmates|East": ["Red", "Orange"], "2 Squadmates|West": ["Green", "Brown", "Red"], "2 Squadmates|Center": ["Red", "Brown"] };
$("#tbl-first").innerHTML = `<table><thead><tr><th>Company · direction</th>${cols.map((c) => `<th class="num">${c}</th>`).join("")}<th class="num">Runs</th></tr></thead><tbody>${r.first_sighting.map((x) => ({ ...x, n: cols.reduce((t, c) => t + (x.colors[c] || 0), 0), gap: (x.colors.Unsure || 0) + (x.colors.Unknown || 0) })).filter((x) => x.n >= 3).map((x) => `<tr><td>${esc(x.key.replace("|", " · "))}</td>${cols.map((c) => { const n = x.colors[c] || 0; const off = n && POOL[x.key] && !POOL[x.key].includes(c); return `<td class="num" style="${off ? "color:var(--warn);font-weight:600" : n ? "" : "color:var(--faint)"}" title="${off ? "Outside the documented pool" : ""}">${n ? `${n}<span class="muted"> · ${pct(n / x.n, 0)}</span>` : "·"}</td>`; }).join("")}<td class="num">${x.n}${x.gap ? `<span class="muted" title="Riders who were not sure which dragon they saw, left out"> +${x.gap} unsure</span>` : ""}</td></tr>`).join("")}</tbody></table>`;
}
// ------------------------------------------------------------ route table
function renderRouteTable() {
const sel = $("#rt-target");
if (!sel.options.length) {
sel.innerHTML = Object.entries(E.TARGETS).map(([k, t]) => `<option value="${k}">${esc(t.label)}</option>`).join("");
sel.value = state.rtTarget;
sel.addEventListener("change", () => { state.rtTarget = sel.value; renderRouteTable(); });
$("#rt-min").addEventListener("change", (e) => { state.rtMin = Math.max(1, +e.target.value || 10); renderRouteTable(); renderFindings(); });
}
const rk = E.rankRoutes(state.runs, state.rtTarget, state.rtMin);
const sig = rk.rows.filter((x) => x.mh_q < 0.05 && x.mh_or > 1).length;
$("#rt-note").innerHTML = `${rk.n_routes_tested} routes tested · comparison group ${rateTxt(rk.overall)} · <b>${sig}</b> clearly better after adjustment`;
const bar = (w) => `<span class="cibar" aria-hidden="true"><i style="left:${w.lo * 90}px;width:${Math.max(1, (w.hi - w.lo) * 90)}px"></i><b style="left:${w.p * 90 - 1}px"></b></span>`;
$("#tbl-routes").innerHTML = rk.rows.length ? `<table><thead><tr><th>#</th><th>Route (choices up to the hour)</th><th class="num">Runs</th><th class="num">Hits</th><th class="num">Rate</th><th class="num">95% CI</th><th></th><th class="num">Crude OR</th><th class="num">q</th><th class="num">Adj. OR</th><th class="num">Adj. q</th></tr></thead><tbody>
${rk.rows.map((r, i) => `<tr class="${r.mh_q < 0.05 && r.mh_or > 1 ? "sig" : ""}${r.n < 20 ? " thin" : ""}"><td class="num">${i + 1}</td><td class="route-cell">${esc(r.route)}</td><td class="num">${r.n}</td><td class="num">${r.k}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td>${bar(r)}</td><td class="num">${fmtOR(r.or)}</td><td class="num">${fmtP(r.q)}</td><td class="num">${fmtOR(r.mh_or)}</td><td class="num">${fmtP(r.mh_q)}</td></tr>`).join("")}
</tbody></table>` : `<p class="small muted" style="padding:12px">No routes reach the minimum. Lower it.</p>`;
}
// ------------------------------------------------------------ factor explorer
function renderFactors() {
const so = $("#fx-outcome"), sf = $("#fx-factor");
if (!so.options.length) {
so.innerHTML = Object.entries(E.OUTCOMES).map(([k, o]) => `<option value="${k}">${esc(o.label)}</option>`).join("");
sf.innerHTML = E.FACTORS.map((f) => `<option value="${f}">${esc(labelFactor(f))}</option>`).join("");
so.value = state.fxOutcome; sf.value = state.fxFactor;
so.addEventListener("change", () => { state.fxOutcome = so.value; renderFactors(); });
sf.addEventListener("change", () => { state.fxFactor = sf.value; renderFactors(); });
}
const ft = state.res.factors[state.fxOutcome];
const rows = ft.rows.filter((r) => r.factor === state.fxFactor);
$("#tbl-factors").innerHTML = `<table><thead><tr><th>${esc(labelFactor(state.fxFactor))}</th><th class="num">Hits/runs</th><th class="num">Rate</th><th class="num">95% CI</th><th class="num">OR vs rest</th><th class="num">p</th><th class="num">q</th></tr></thead><tbody>
<tr><td><i>All</i></td><td class="num">${kn(ft.overall)}</td><td class="num">${pct(ft.overall.p)}</td><td class="num">${ci(ft.overall)}</td><td></td><td></td><td></td></tr>
${rows.map((r) => `<tr class="${r.q < 0.05 ? "sig" : ""}${r.or === undefined ? " thin" : ""}"><td>${esc(r.level)}</td><td class="num">${kn(r)}</td><td class="num">${pct(r.p)}</td><td class="num">${ci(r)}</td><td class="num">${r.or !== undefined ? `${fmtOR(r.or)} <span class="muted">(${fmtOR(r.or_lo)}–${fmtOR(r.or_hi)})</span>` : "too few"}</td><td class="num">${fmtP(r.fisher_p)}</td><td class="num">${r.q !== undefined ? `<span class="qbadge${r.q < 0.05 ? " s" : ""}">${fmtP(r.q)}</span>` : ""}</td></tr>`).join("")}
</tbody></table>${ft.missing && ft.missing[state.fxFactor] ? `<p class="small muted">${ft.missing[state.fxFactor].toLocaleString()} runs with no usable answer to this question ("unsure", blank, or not asked on that version of the form) are left out of these comparisons rather than treated as a choice.</p>` : ""}`;
forest($("#ch-factor"), rows.filter((r) => r.or !== undefined).map((r) => ({ label: r.level, or: r.or, lo: r.or_lo, hi: r.or_hi, q: r.q, p: undefined, n: r.n })), { labelW: 220 });
}
// ------------------------------------------------------------ quality
function renderQuality() {
const r = state.res, m = r.meta;
const flags = Object.entries(m.flag_counts).sort((a, b) => b[1] - a[1]);
const outs = Object.entries(m.outcomes).sort((a, b) => b[1] - a[1]);
$("#quality-panels").innerHTML = `
<div class="panel"><h3>Who logged the runs</h3><div class="tbl-wrap"><table><thead><tr><th>Source</th><th class="num">Runs</th><th class="num">Blue in meadow</th><th class="num">Shadow at tree</th></tr></thead><tbody>
${Object.entries(m.sources).sort((a, b) => b[1] - a[1]).map(([s, n]) => { const b = sourceRate("blue_meadow", s), t = sourceRate("shadow", s); return `<tr><td>${esc(s)}</td><td class="num">${n}</td><td class="num">${pct(b.p)} <span class="muted">${kn(b)}</span></td><td class="num">${pct(t.p)} <span class="muted">${kn(t)}</span></td></tr>`; }).join("")}
</tbody></table></div><p class="small">Bulk logs come from players who recorded every run, so they are the least selective rows. Their rare-dragon rates are several times lower than the form's, which is the strongest sign of reporting bias in this data.</p></div>
<div class="panel"><h3>Rows flagged for contradictions</h3><p class="small muted">${m.n_flagged} of ${r.n} rows (${pct(m.n_flagged / r.n)}). Flagged rows stay in unless you drop them above.</p><div class="tbl-wrap"><table><tbody>${flags.map(([f, n]) => `<tr><td>${esc(f)}</td><td class="num">${n}</td></tr>`).join("") || `<tr><td>None</td></tr>`}</tbody></table></div></div>
<div class="panel"><h3>How runs ended</h3><div class="tbl-wrap"><table><tbody>${outs.map(([f, n]) => `<tr><td>${esc(f)}</td><td class="num">${n}</td><td class="num">${pct(n / r.n)}</td></tr>`).join("")}</tbody></table></div><p class="small muted">"No outcome recorded" rows reached the hour but the form shows no Bonded or Incinerated. They count toward reaching a branch but not toward bond rates.</p></div>
<div class="panel"><h3>Independence</h3><p class="small">The form has no player ID. One player's 50 runs count as 50 independent runs, so intervals are somewhat narrower than they should be. ${pct((r.n - (m.sources["Form"] || 0)) / r.n, 0)} of rows arrived as bulk imports, each probably one player's or one group's log.</p></div>
<div class="panel"><h3>What the form does not ask</h3><p class="small">The redesigned form asks how you reacted to the first dragon (answered in ${r.factors.reach_hour.rows.filter((x) => x.factor === "sighting_action" && !["Unknown", "(not asked)"].includes(x.level)).reduce((a, x) => a + x.n, 0)} rows; most riders answer "Unsure") and how the bully fight went (${r.factors.reach_hour.rows.filter((x) => x.factor === "combat_first" && x.level !== "(not recorded)").reduce((a, x) => a + x.n, 0)} rows). It still does not record most choices inside the bonding encounters. Theories that rely on those choices cannot be confirmed or refuted here.</p></div>`;
}
function sourceRate(outKey, source) {
const O = E.OUTCOMES[outKey];
const D = state.runs.filter((r) => r.source === source).filter(O.denom);
return E.wilson(D.filter(O.event).length, D.length);
}
// ------------------------------------------------------------ share
function redditPost() {
const r = state.res, cb = r.chance.blue_meadow, cs = r.chance.shadow;
const bulkB = stratumRate(cb, "Bulk"), chaseB = stratumRate(cb, "Form: chasing Blue"), bulkS = stratumRate(cs, "Bulk");
const encB = r.encounters.find((e) => e.context === "Blue (meadow)"), encK = r.encounters.find((e) => e.context === "Black (shadow)");
const mb = r.models.blue_meadow;
const sigRoute = mb ? mb.terms.filter((t) => ROUTE_FACTORS.includes(t.factor) && t.p < 0.05 && !NOT_A_CHOICE.test(t.level)) : [];
const rk = E.rankRoutes(state.runs, "see_Blue", state.rtMin);
const adjSig = rk.rows.filter((x) => x.mh_q < 0.05 && x.mh_or > 1).length;
const leads = r.factors.shadow.rows.filter((x) => ["post_path", "attempt_group"].includes(x.factor) && x.q < 0.05 && x.or > 1 && !NOT_A_CHOICE.test(x.level));
const L = [];
L.push(`# I ran the numbers on ${r.n.toLocaleString()} logged threshing runs. Here's what holds up (and what doesn't)`);
L.push("");
L.push(`*Per the megathread rules, anything that names a specific route is behind spoiler tags.*`);
L.push("");
L.push(`Data: the community Threshing Routes form/spreadsheet (thanks u/ClumsyBadger, u/Old_Regular3018, u/Smart_Trifle_2099 and everyone who logged runs). ${Object.entries(r.meta.sources).map(([k, v]) => `${v} ${k === "Form" ? "form submissions" : k}`).join(", ")}; form dates ${r.meta.date_min} to ${r.meta.date_max}. Every rate below has a 95% confidence interval.`);
L.push("");
L.push(`**TL;DR**`);
L.push("");
L.push(`* **The meadow Blue shows up a lot less than the spreadsheet suggests.** Runs logged by Blue-chasers show it ${pct(chaseB && chaseB.p)} of the time, but bulk logs (people who recorded *every* run) show ${bulkB ? `${pct(bulkB.p)} (${kn(bulkB)})` : "n/a"}. The game can't know what you're chasing, so that gap is reporting bias. Expect something closer to the bulk-log number.`);
L.push(`* **${sigRoute.length ? "Only these route choices mattered for the Blue appearing" : "No recorded route choice changed the Blue's odds"}** once you account for that bias${sigRoute.length ? `: ${sigRoute.map((s) => s.term).join("; ")}` : ""} (direction, first dragon, how you handled the cadet, company). ${adjSig} of ${rk.n_routes_tested} full routes beat the rest after correcting for multiple testing. The "precise pathways" might still matter through choices the form doesn't record (like how you react to the first dragon), but the form can't confirm them.`);
L.push(`* **Getting the Blue to show up is only half of it.** Only ${encB ? `${pct(encB.overall.p)} (${kn(encB.overall)})` : "n/a"} of Blue attempts bonded, which matches the PDF's step-by-step numbers (~25%). Dying with the "right" answer is normal.`);
L.push(`* **The tree shadow (→ Black) is rarer than the spreadsheet suggests.** All rows: ${pct(cs.overall.p)} (${kn(cs.overall)}), but bulk logs show ${bulkS ? `${kn(bulkS)} (upper 95% bound ${pct(bulkS.hi)})` : "n/a"}. ${bulkS && bulkS.n ? `Plan on roughly 1 in ${Math.round(1 / Math.max(bulkS.hi, 0.001) / 10) * 10} climbs at best.` : ""} Once you get the Black, it bonds ${encK ? `${pct(encK.overall.p)} (${kn(encK.overall)})` : "n/a"} of the time.`);
if (leads.length) L.push(`* **Leads worth testing (not proven):** >!${leads.map((x) => `${labelFactor(x.factor)} = ${x.level}: shadow in ${pct(x.p)} (${kn(x)}) vs the rest`).join("; ")}!<. If you bulk-log your tree climbs *including the boring ones*, we can settle this.`);
L.push("");
L.push(`**How to help:** log every run in the form, including the ones where nothing rare happened. Those dull runs are what make the rates trustworthy.`);
L.push("");
L.push(`Interactive route map, full methods, and code to reproduce every number: [Threshing Route Atlas](LINK)`);
L.push("");
L.push(`*Caveats: self-reported data, no player IDs (so runs from one person aren't independent), and the form doesn't record every in-game choice. The author has said there's a ~10% chaos roll, so nothing is guaranteed.*`);
return L.join("\n");
}
function runsCSV() {
const cols = Object.keys(state.runs[0] || {});
const q = (v) => { if (v === null || v === undefined) return ""; const s = String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
return [cols.join(","), ...state.runs.map((r) => cols.map((c) => q(r[c])).join(","))].join("\n");
}
$("#cp-reddit").addEventListener("click", () => copyText(redditPost(), "Reddit post"));
$("#cp-csv").addEventListener("click", () => copyText(runsCSV(), `${state.runs.length} coded runs`));
$("#cp-json").addEventListener("click", () => copyText(JSON.stringify(state.res, null, 1), "results JSON"));
$$("button[data-src]").forEach((b) => b.addEventListener("click", async () => {
const pre = $("#srcview");
try { const t = await (await fetch(b.dataset.src)).text(); pre.textContent = t; pre.hidden = false; pre.scrollTop = 0; }
catch (e) { pre.textContent = "Could not load " + b.dataset.src; pre.hidden = false; }
}));
// ------------------------------------------------------------ controls
$$("#width-mode button").forEach((b) => b.addEventListener("click", () => {
state.widthMode = b.dataset.v;
$$("#width-mode button").forEach((x) => x.setAttribute("aria-pressed", x === b));
renderMap();
}));
$("#minn").addEventListener("change", (e) => { state.minN = Math.max(1, +e.target.value || 10); renderMap(); });
$("#f-source").addEventListener("change", (e) => { state.filters.source = e.target.value; recompute(); });
$("#f-goal").addEventListener("change", (e) => { state.filters.goal = e.target.value; recompute(); });
$("#f-flag").addEventListener("change", (e) => { state.filters.excludeFlagged = e.target.checked; recompute(); });
$("#btn-clear").addEventListener("click", () => { state.conds = {}; renderMap(); $("#best-routes").innerHTML = ""; });
$("#btn-best").addEventListener("click", renderBestRoutes);
function renderAll() {
renderStatus(); renderFindings(); renderTargets(); renderMap(); renderRare(); renderDragons(); renderRouteTable(); renderFactors(); renderQuality();
if ($("#best-routes").innerHTML) renderBestRoutes();
if (window.AtlasUI) window.AtlasUI.render(state);
}
// re-colour when the theme changes
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const rerender = () => state.res && renderAll();
mq.addEventListener && mq.addEventListener("change", rerender);
new MutationObserver(rerender).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });
let rz; window.addEventListener("resize", () => { clearTimeout(rz); rz = setTimeout(() => state.res && renderMap(), 200); });
window.ThreshAtlas = { state, redditPost, runsCSV };
if (window.DragonRegister) window.DragonRegister.mount({ copy: copyText, toast });
loadBundled().catch((e) => { $("#data-status").innerHTML = `<span class="pill warn">The bundled data could not load (${esc(e.message)}). Use "Load a newer export" to load the responses file.</span>`; console.error(e); });
})();
+308
View File
@@ -0,0 +1,308 @@
/* dragons.js — original dragon silhouettes for the valley map.
* Each pose is built from simple parts (tapered tubes, a scalloped wing membrane, a head with horns, spines,
* a spaded tail), so every dragon is drawn the same way but stands differently. Drawn facing right in a
* 200 x 160 box; flip with scale(-1, 1). Works in the browser (window.DragonArt) and in Node. */
(function (root, factory) {
if (typeof module === "object" && module.exports) module.exports = factory();
else root.DragonArt = factory();
})(typeof self !== "undefined" ? self : this, function () {
"use strict";
const f = (n) => Math.round(n * 10) / 10;
const lerp = (a, b, t) => a + (b - a) * t;
/** Points along a cubic Bezier given as [p0, c1, c2, p1] (each [x, y]). */
function bez(P, n = 28) {
const out = [];
for (let i = 0; i <= n; i++) {
const t = i / n, u = 1 - t;
out.push([
u * u * u * P[0][0] + 3 * u * u * t * P[1][0] + 3 * u * t * t * P[2][0] + t * t * t * P[3][0],
u * u * u * P[0][1] + 3 * u * u * t * P[1][1] + 3 * u * t * t * P[2][1] + t * t * t * P[3][1],
]);
}
return out;
}
/** A tube along a Bezier whose half-width goes from r0 to r1 (r can also be a function of t). */
function tube(P, r0, r1, n = 28) {
const pts = bez(P, n), L = [], R = [];
pts.forEach((p, i) => {
const a = pts[Math.max(0, i - 1)], b = pts[Math.min(pts.length - 1, i + 1)];
let dx = b[0] - a[0], dy = b[1] - a[1];
const len = Math.hypot(dx, dy) || 1;
dx /= len; dy /= len;
const t = i / n, r = typeof r0 === "function" ? r0(t) : lerp(r0, r1, t);
L.push([p[0] - dy * r, p[1] + dx * r]);
R.push([p[0] + dy * r, p[1] - dx * r]);
});
const ring = L.concat(R.reverse());
return "M" + ring.map((p) => `${f(p[0])} ${f(p[1])}`).join(" L") + " Z";
}
const poly = (pts) => "M" + pts.map((p) => `${f(p[0])} ${f(p[1])}`).join(" L") + " Z";
const ell = (cx, cy, rx, ry, rot = 0) => {
const pts = [];
for (let i = 0; i < 36; i++) {
const a = (i / 36) * Math.PI * 2, x = rx * Math.cos(a), y = ry * Math.sin(a), c = Math.cos(rot), s = Math.sin(rot);
pts.push([cx + x * c - y * s, cy + x * s + y * c]);
}
return poly(pts);
};
/**
* Wing membrane: a leading-edge bone shoulder -> wrist -> tip, finger tips along the trailing edge, and
* scalloped membrane between them, back to the root on the body.
*/
function wing({ shoulder, wrist, tip, fingers, root, bow = 0.28, bone = 4 }) {
const d = [tube([shoulder, [lerp(shoulder[0], wrist[0], 0.4), lerp(shoulder[1], wrist[1], 0.4) - 6], [lerp(shoulder[0], wrist[0], 0.8), lerp(shoulder[1], wrist[1], 0.8)], wrist], bone, bone * 0.8),
tube([wrist, [lerp(wrist[0], tip[0], 0.3), lerp(wrist[1], tip[1], 0.3)], [lerp(wrist[0], tip[0], 0.7), lerp(wrist[1], tip[1], 0.7)], tip], bone * 0.8, 0.8)];
const edge = [tip].concat(fingers, [root]);
let m = `M${f(shoulder[0])} ${f(shoulder[1])} L${f(wrist[0])} ${f(wrist[1])} L${f(tip[0])} ${f(tip[1])}`;
for (let i = 1; i < edge.length; i++) {
const a = edge[i - 1], b = edge[i];
// scallop: control point pulled toward the wrist
const mx = (a[0] + b[0]) / 2, my = (a[1] + b[1]) / 2;
const cx = lerp(mx, wrist[0], bow), cy = lerp(my, wrist[1], bow);
m += ` Q${f(cx)} ${f(cy)} ${f(b[0])} ${f(b[1])}`;
}
m += ` L${f(shoulder[0])} ${f(shoulder[1])} Z`;
d.push(m);
// finger bones from the wrist (thin, add texture at the edge)
fingers.forEach((p) => d.push(tube([wrist, [lerp(wrist[0], p[0], 0.33), lerp(wrist[1], p[1], 0.33)], [lerp(wrist[0], p[0], 0.66), lerp(wrist[1], p[1], 0.66)], p], 1.6, 0.6, 10)));
return d;
}
/** Head pointing along `ang` (radians, 0 = right) from the neck end, with horns and an open or closed jaw. */
function head({ at, ang = 0, size = 1, open = 0, horns = 2 }) {
const c = Math.cos(ang), s = Math.sin(ang);
const T = (x, y) => [at[0] + (x * c - y * s) * size, at[1] + (x * s + y * c) * size];
const d = [];
// skull and upper snout
d.push(poly([T(-8, 2), T(-6, -9), T(4, -12), T(14, -8), T(26, -5), T(31, -2), T(30, 1), T(18, 2 + open * 0.3), T(8, 6)]));
// jaw (drops when open)
d.push(poly([T(-6, 3), T(10, 4), T(28, 3 + open), T(26, 6 + open), T(12, 10 + open * 0.4), T(-4, 9)]));
// horns sweeping back
for (let i = 0; i < horns; i++) {
const y0 = -9 + i * 4, len = 18 - i * 6;
d.push(tube([T(2 - i * 3, y0), T(-6 - i * 2, y0 - 6), T(-14 - i * 3, y0 - 8 - i), T(-12 - len * 0.6 - i * 3, y0 - 14 + i * 3)], 2.6 * size - i * 0.4, 0.4, 10));
}
// brow spike and cheek frill
d.push(poly([T(-4, 4), T(-14, 8), T(-5, 8)]));
return { d, eye: T(8, -5), eyeR: 1.9 * size };
}
/** Small triangular spines along a list of points (pointing away from `side` normal). */
function spines(pts, size, side = -1, every = 2) {
const d = [];
for (let i = 1; i < pts.length - 1; i += every) {
const a = pts[i - 1], b = pts[i + 1], p = pts[i];
let dx = b[0] - a[0], dy = b[1] - a[1];
const len = Math.hypot(dx, dy) || 1;
dx /= len; dy /= len;
const nx = -dy * side, ny = dx * side, k = typeof size === "function" ? size(i / pts.length) : size;
d.push(poly([[p[0] - dx * k * 0.6, p[1] - dy * k * 0.6], [p[0] + nx * k * 1.5 - dx * k * 0.5, p[1] + ny * k * 1.5 - dy * k * 0.5], [p[0] + dx * k * 0.6, p[1] + dy * k * 0.6]]));
}
return d;
}
/** Tail as a tapering tube ending in a spade. */
function tail(P, r0) {
const d = [tube(P, (t) => Math.max(0.9, r0 * (1 - t) ** 1.1), null, 36)];
const pts = bez(P, 36), a = pts[pts.length - 3], b = pts[pts.length - 1];
let dx = b[0] - a[0], dy = b[1] - a[1];
const len = Math.hypot(dx, dy) || 1;
dx /= len; dy /= len;
const nx = -dy, ny = dx, k = Math.max(4, r0 * 0.9);
d.push(poly([[b[0] - dx * k * 0.6, b[1] - dy * k * 0.6], [b[0] + nx * k, b[1] + ny * k], [b[0] + dx * k * 1.6, b[1] + dy * k * 1.6], [b[0] - nx * k, b[1] - ny * k]]));
return { d, pts };
}
/** Leg: hip -> knee -> foot with three claws. */
function leg(hip, knee, foot, r, toe = 1) {
const d = [tube([hip, [lerp(hip[0], knee[0], 0.6), lerp(hip[1], knee[1], 0.6)], knee, [lerp(knee[0], foot[0], 0.5), lerp(knee[1], foot[1], 0.5)]], r, r * 0.6, 14),
tube([[lerp(knee[0], foot[0], 0.4), lerp(knee[1], foot[1], 0.4)], [lerp(knee[0], foot[0], 0.6), lerp(knee[1], foot[1], 0.6)], [lerp(knee[0], foot[0], 0.85), lerp(knee[1], foot[1], 0.85)], foot], r * 0.6, r * 0.45, 10)];
for (let i = -1; i <= 1; i++) d.push(poly([[foot[0] - 2, foot[1] - 2], [foot[0] + toe * (6 + i * 1.5), foot[1] + 1 + i * 2.2], [foot[0] + 1, foot[1] + 2.5]]));
return d;
}
/* ---------- poses ---------- */
const POSES = {
// seated and watchful, one wing raised, tail curled round the feet
sitting() {
const d = [];
d.push(...wing({ shoulder: [88, 74], wrist: [62, 18], tip: [24, 30], fingers: [[14, 66], [30, 98], [56, 116]], root: [76, 112], bow: 0.3 }));
d.push(ell(92, 104, 26, 36, -0.25));
d.push(tube([[90, 80], [96, 58], [110, 42], [116, 34]], 13, 7));
const t = tail([[76, 132], [56, 150], [110, 158], [168, 150]], 9);
d.push(...t.d);
d.push(...leg([84, 120], [70, 136], [86, 152], 12, 1));
d.push(...leg([102, 104], [110, 124], [114, 150], 7, 1));
const h = head({ at: [114, 34], ang: -0.05, size: 1.05 });
d.push(...h.d);
d.push(...spines(bez([[86, 84], [84, 62], [100, 44], [110, 36]], 10), 4, -1, 2));
d.push(...spines(t.pts.slice(0, 26), (u) => 4 * (1 - u), 1, 3));
return { d, eye: h.eye, eyeR: h.eyeR };
},
// low and stalking, head forward, wings folded
prowling() {
const d = [];
d.push(...wing({ shoulder: [92, 92], wrist: [70, 64], tip: [118, 52], fingers: [[136, 70], [130, 90]], root: [104, 100], bow: 0.25, bone: 3.4 }));
d.push(ell(96, 108, 38, 18, 0.05));
d.push(tube([[124, 104], [140, 98], [152, 92], [162, 94]], 11, 7));
const t = tail([[62, 108], [36, 106], [22, 128], [6, 120]], 11);
d.push(...t.d);
d.push(...leg([72, 112], [60, 128], [70, 146], 11));
d.push(...leg([84, 116], [94, 130], [92, 146], 8));
d.push(...leg([118, 112], [126, 128], [124, 146], 8));
d.push(...leg([128, 110], [140, 126], [146, 146], 7));
const h = head({ at: [160, 94], ang: 0.12, size: 1 });
d.push(...h.d);
d.push(...spines(bez([[66, 92], [90, 84], [130, 86], [156, 88]], 14), 3.6, -1, 2));
d.push(...spines(t.pts.slice(0, 26), (u) => 3.6 * (1 - u), -1, 3));
return { d, eye: h.eye, eyeR: h.eyeR };
},
// in flight, both wings spread
flying() {
const d = [];
d.push(...wing({ shoulder: [96, 84], wrist: [70, 36], tip: [40, 6], fingers: [[30, 40], [44, 66], [70, 80]], root: [92, 94], bow: 0.32 }));
d.push(...wing({ shoulder: [110, 84], wrist: [140, 30], tip: [190, 14], fingers: [[178, 52], [160, 76], [134, 90]], root: [114, 96], bow: 0.32 }));
d.push(ell(104, 96, 30, 13, 0.2));
d.push(tube([[128, 92], [142, 86], [150, 76], [158, 72]], 9, 6));
const t = tail([[78, 92], [54, 98], [40, 120], [12, 116]], 8);
d.push(...t.d);
d.push(...leg([94, 102], [96, 116], [108, 124], 6));
d.push(...leg([116, 102], [122, 114], [132, 118], 5));
const h = head({ at: [156, 72], ang: -0.2, size: 0.9, open: 2 });
d.push(...h.d);
return { d, eye: h.eye, eyeR: h.eyeR };
},
// reared up and roaring, wings half open
roaring() {
const d = [];
d.push(...wing({ shoulder: [94, 68], wrist: [52, 40], tip: [30, 2], fingers: [[16, 46], [34, 78], [66, 96]], root: [90, 98], bow: 0.3 }));
d.push(ell(98, 100, 22, 40, 0.2));
d.push(tube([[104, 70], [112, 50], [126, 34], [136, 24]], 13, 7));
const t = tail([[86, 136], [60, 156], [30, 150], [14, 132]], 10);
d.push(...t.d);
d.push(...leg([90, 124], [104, 138], [96, 154], 12));
d.push(...leg([108, 86], [124, 92], [132, 82], 6, 1));
d.push(...leg([102, 92], [116, 104], [126, 98], 6, 1));
const h = head({ at: [134, 24], ang: -0.55, size: 1.05, open: 7 });
d.push(...h.d);
d.push(...spines(bez([[94, 86], [100, 60], [116, 40], [130, 28]], 10), 4, -1, 2));
return { d, eye: h.eye, eyeR: h.eyeR };
},
// coiled, as if wrapped around something, head lifted
coiled() {
const d = [];
const t = tail([[100, 120], [30, 150], [20, 80], [80, 74]], 15);
d.push(...t.d);
d.push(tube([[100, 120], [150, 130], [170, 96], [140, 70]], 16, 12));
d.push(tube([[140, 70], [124, 52], [128, 34], [146, 26]], 12, 7));
d.push(...wing({ shoulder: [134, 76], wrist: [106, 36], tip: [72, 26], fingers: [[64, 52], [80, 70], [104, 82]], root: [124, 90], bow: 0.28, bone: 3.4 }));
d.push(...leg([150, 116], [164, 126], [170, 142], 8));
d.push(...leg([116, 124], [114, 138], [122, 150], 8));
const h = head({ at: [144, 26], ang: 0.1, size: 1 });
d.push(...h.d);
d.push(...spines(t.pts, (u) => 3.5 * (1 - u * 0.7), -1, 3));
return { d, eye: h.eye, eyeR: h.eyeR };
},
// lying down at rest, head up
resting() {
const d = [];
d.push(...wing({ shoulder: [90, 108], wrist: [66, 84], tip: [112, 70], fingers: [[134, 88], [124, 108]], root: [100, 118], bow: 0.25, bone: 3.2 }));
d.push(ell(92, 126, 42, 18, 0));
d.push(tube([[124, 120], [140, 112], [146, 92], [158, 82]], 12, 7));
const t = tail([[54, 130], [24, 140], [20, 152], [70, 152]], 11);
d.push(...t.d);
d.push(...leg([120, 132], [132, 142], [150, 146], 8));
d.push(...leg([70, 134], [82, 144], [96, 148], 10));
const h = head({ at: [156, 84], ang: 0.05, size: 1 });
d.push(...h.d);
d.push(...spines(bez([[60, 112], [90, 104], [130, 106], [152, 88]], 14), 3.4, -1, 2));
return { d, eye: h.eye, eyeR: h.eyeR };
},
};
const cache = {};
/** SVG markup for one dragon: <g> with the silhouette in `fill` and a small eye in `eyeFill`. */
function svg(pose, { fill = "#2a2230", eyeFill = "#f6e6c4", flip = false } = {}) {
if (!cache[pose]) cache[pose] = POSES[pose]();
const p = cache[pose];
const tf = flip ? ' transform="translate(200 0) scale(-1 1)"' : "";
// one path per part: parts wind in different directions, so a single combined path would punch holes
return `<g${tf}><g fill="${fill}">${p.d.map((d) => `<path d="${d}"/>`).join("")}</g><circle cx="${f(p.eye[0])}" cy="${f(p.eye[1])}" r="${p.eyeR}" fill="${eyeFill}"/></g>`;
}
/* ---------- cadets and the thorn bush (same building blocks, 100 x 140 box, feet near y = 132) ---------- */
const line = (a, b, r0, r1 = r0) => tube([a, [lerp(a[0], b[0], 0.33), lerp(a[1], b[1], 0.33)], [lerp(a[0], b[0], 0.66), lerp(a[1], b[1], 0.66)], b], r0, r1, 8);
/** A cadet from joint positions; `cloak` adds a short flying cape, weapons are drawn from the hands. */
function cadet(j, { cloak = true, sword = null, dagger = null, size = 1 } = {}) {
const d = [];
if (cloak) d.push(poly([j.neck, [j.neck[0] - 4, j.neck[1] + 2], [j.hip[0] - 14 * (j.face || 1), j.hip[1] + 16], [j.hip[0] - 2 * (j.face || 1), j.hip[1] + 8], [j.neck[0] + 3, j.neck[1] + 4]]));
d.push(line(j.neck, j.hip, 7.5 * size, 6.5 * size)); // torso
d.push(line(j.hip, j.lKnee, 4.6 * size, 4 * size), line(j.lKnee, j.lFoot, 3.8 * size, 3 * size));
d.push(line(j.hip, j.rKnee, 4.6 * size, 4 * size), line(j.rKnee, j.rFoot, 3.8 * size, 3 * size));
d.push(poly([[j.lFoot[0] - 3, j.lFoot[1] - 2], [j.lFoot[0] + 7 * (j.face || 1), j.lFoot[1] - 1], [j.lFoot[0] + 7 * (j.face || 1), j.lFoot[1] + 2], [j.lFoot[0] - 3, j.lFoot[1] + 2]]));
d.push(poly([[j.rFoot[0] - 3, j.rFoot[1] - 2], [j.rFoot[0] + 7 * (j.face || 1), j.rFoot[1] - 1], [j.rFoot[0] + 7 * (j.face || 1), j.rFoot[1] + 2], [j.rFoot[0] - 3, j.rFoot[1] + 2]]));
const sh = [j.neck[0], j.neck[1] + 3];
d.push(line(sh, j.lElbow, 3.4 * size, 3), line(j.lElbow, j.lHand, 3, 2.4));
d.push(line(sh, j.rElbow, 3.4 * size, 3), line(j.rElbow, j.rHand, 3, 2.4));
d.push(ell(j.head[0], j.head[1], 7.2 * size, 8 * size, 0)); // head
d.push(ell(j.head[0] - 2 * (j.face || 1), j.head[1] - 3, 7 * size, 5 * size, 0)); // hair
d.push(line([(j.neck[0] + j.head[0]) / 2, (j.neck[1] + j.head[1]) / 2 + 2], j.neck, 3.2, 3.6)); // neck
const blade = (hand, ang, len, w) => {
const tip = [hand[0] + Math.cos(ang) * len, hand[1] + Math.sin(ang) * len];
const nx = -Math.sin(ang), ny = Math.cos(ang);
return [poly([[hand[0] + nx * w, hand[1] + ny * w], [tip[0] + nx * w * 0.4, tip[1] + ny * w * 0.4], [tip[0] + Math.cos(ang) * 4, tip[1] + Math.sin(ang) * 4], [tip[0] - nx * w * 0.4, tip[1] - ny * w * 0.4], [hand[0] - nx * w, hand[1] - ny * w]]),
line([hand[0] + nx * 6, hand[1] + ny * 6], [hand[0] - nx * 6, hand[1] - ny * 6], 1.4)];
};
if (sword) d.push(...blade(j[sword.hand], sword.ang, sword.len || 44, 1.9));
if (dagger) d.push(...blade(j[dagger.hand], dagger.ang, dagger.len || 16, 1.6));
return d;
}
const FIGURES = {
// your squadmate, braced, sword raised high
defender: () => cadet({ face: 1, head: [42, 30], neck: [44, 42], hip: [46, 84], lKnee: [36, 106], lFoot: [28, 130], rKnee: [58, 104], rFoot: [64, 130],
lElbow: [56, 50], lHand: [62, 34], rElbow: [56, 56], rHand: [62, 38] }, { sword: { hand: "lHand", ang: -1.15, len: 46 } }),
// the bigger bully, lunging with a sword
lunging: () => cadet({ face: -1, head: [56, 34], neck: [54, 46], hip: [58, 86], lKnee: [42, 104], lFoot: [30, 130], rKnee: [70, 108], rFoot: [82, 130],
lElbow: [40, 56], lHand: [26, 60], rElbow: [44, 60], rHand: [30, 64] }, { sword: { hand: "lHand", ang: Math.PI + 0.12, len: 42 }, size: 1.12 }),
// the smaller bully, dagger raised to throw
throwing: () => cadet({ face: -1, head: [50, 46], neck: [50, 57], hip: [52, 92], lKnee: [42, 110], lFoot: [36, 130], rKnee: [62, 110], rFoot: [68, 130],
lElbow: [40, 66], lHand: [36, 80], rElbow: [64, 52], rHand: [70, 38] }, { dagger: { hand: "rHand", ang: -0.9 }, size: 0.88 }),
// the wounded cadet, lying on the ground, a belt tied above the knee
lying: () => {
const d = cadet({ face: 1, head: [16, 118], neck: [26, 120], hip: [62, 122], lKnee: [80, 116], lFoot: [96, 126], rKnee: [80, 126], rFoot: [84, 128],
lElbow: [34, 108], lHand: [40, 96], rElbow: [38, 128], rHand: [52, 130] }, { cloak: false });
d.push(poly([[2, 132], [98, 132], [96, 136], [4, 136]])); // the ground line
return d;
},
// a thorn bush: arching branches with thorns and a few leaves
thorns: () => {
const d = [], R = (() => { let s = 7; return () => ((s = (s * 1103515245 + 12345) % 2147483648) / 2147483648); })();
// a low mound of leaves, then arching thorny canes
[[22, 128, 18, 9], [50, 124, 24, 12], [78, 128, 18, 9], [36, 118, 14, 8], [64, 118, 14, 8]].forEach(([x, y, rx, ry]) => d.push(ell(x, y, rx, ry, 0)));
for (let k = 0; k < 11; k++) {
const a = Math.PI * (0.08 + 0.84 * (k / 10)) + (R() - 0.5) * 0.2, len = 50 + R() * 34;
const sx = 50 + (R() - 0.5) * 24, sy = 124;
const ex = sx - Math.cos(a) * len, ey = sy - Math.sin(a) * len * 0.95;
const b = [[sx, sy], [sx - Math.cos(a) * len * 0.35, sy - Math.sin(a) * len * 0.75], [ex + Math.cos(a) * 6, ey - 10], [ex, ey + 4]];
d.push(tube(b, 2.6, 0.8, 18));
bez(b, 12).slice(2, -1).forEach((p, i) => {
const side = i % 2 ? 1 : -1, l = 3.5 + R() * 3;
d.push(poly([[p[0] - 1.2, p[1]], [p[0] + side * l, p[1] - l * 0.7], [p[0] + 1.2, p[1]]]));
if (i % 3 === 1) d.push(ell(p[0] - side * 5, p[1] - 1, 4.2, 2.2, side * 0.6));
});
}
return d;
},
};
const fcache = {};
/** SVG markup for a figure (cadets, the thorn bush) in one ink colour. */
function figure(name, { fill = "#3b2416", flip = false } = {}) {
if (!fcache[name]) fcache[name] = FIGURES[name]();
const tf = flip ? ' transform="translate(100 0) scale(-1 1)"' : "";
return `<g${tf}><g fill="${fill}">${fcache[name].map((d) => `<path d="${d}"/>`).join("")}</g></g>`;
}
return { svg, figure, poses: Object.keys(POSES), figures: Object.keys(FIGURES) };
});
+872
View File
@@ -0,0 +1,872 @@
/* explorer.js — The Valley: the landing page.
*
* Progressive disclosure, in four levels:
* 0 the painted valley, its landmarks, and the dragons where riders meet them (faint = rarely met). No routes.
* 1 hover or focus a dragon or landmark: a short note (riders who met it, bond chance there).
* 2 choose a dragon: every route to every place that dragon can be bonded, drawn at once. Line width = chance you
* are still on the route at that point (it narrows at every roll of the dice and every risk); the better route
* is solid and opaque, weaker ones fade and turn dashed, then dotted.
* 3 click a choice point on the highlighted route: its other options branch off, each with the chance it gives.
* Picking one re-plans the route from there.
* 4 "Why this route?" in the side panel: intervals, how often the choice stays best, low-bias numbers, risks.
* A toggle adds the community's actual traffic underneath. The URL keeps the selection (#valley/blue/meadow-Blue).
*/
(function () {
"use strict";
const S = window.ThreshSolver, V = window.ValleyMap, D = window.DragonArt;
if (!S || !V || !D) return;
const $ = (q, el = document) => el.querySelector(q);
const $$ = (q, el = document) => [...el.querySelectorAll(q)];
const NS = "http://www.w3.org/2000/svg";
const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const pct = (p) => (p == null || isNaN(p) ? "–" : p === 0 ? "0%" : p < 0.001 ? "<0.1%" : (p * 100).toFixed(p < 0.1 ? 1 : 0) + "%");
const L = V.places, INK = V.INK, PAPER = V.PAPER;
const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const COLOURS = ["Red", "Orange", "Brown", "Green", "Blue", "Black"];
const GATE = { x: 500, y: 770, name: "The entrance" };
function el(tag, attrs = {}, parent) {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) if (v !== null && v !== undefined) e.setAttribute(k, v);
if (parent) parent.appendChild(e);
return e;
}
/* ---------- the cast: where each dragon is met, in what pose ---------- */
const ENC_NAME = {
"valley-Red": "The valley Red", "tree-Red": "The Red below the tree", "tree-Greens": "The two Greens",
"meadow-Orange": "The meadow Orange", "meadow-Brown": "The meadow Brown", "meadow-Blue": "The meadow Blue",
"shadow-Blue": "The Blue at the redwood", "shadow-Black": "The Black (the shadow)",
};
const RESCUE = { Orange: "tree-Greens", Brown: "tree-Greens" };
const SPOTS = [
{ place: "treeRed", enc: "tree-Red", colour: "Red", pose: "prowling", flip: true, sc: 0.36 },
{ place: "greens", enc: "tree-Greens", colour: "Green", pose: "resting", sc: 0.3, dx: -16 },
{ place: "greens", enc: "tree-Greens", colour: "Green", pose: "sitting", flip: true, sc: 0.27, dx: 20, dy: -4, twin: true },
{ place: "black", enc: "shadow-Black", colour: "Black", pose: "flying", flip: true, sc: 0.38 },
{ place: "redwood", enc: "shadow-Blue", colour: "Blue", pose: "coiled", sc: 0.3 },
{ place: "valleyRed", enc: "valley-Red", colour: "Red", pose: "roaring", sc: 0.36, dy: -12 },
{ place: "meadow:Orange", enc: "meadow-Orange", colour: "Orange", pose: "sitting", flip: true, sc: 0.3 },
{ place: "meadow:Brown", enc: "meadow-Brown", colour: "Brown", pose: "resting", sc: 0.32 },
{ place: "meadow:Blue", enc: "meadow-Blue", colour: "Blue", pose: "sitting", sc: 0.32 },
];
const FIRST_POSE = { Red: "roaring", Brown: "sitting", Green: "prowling", Orange: "flying" };
Object.keys(L).filter((k) => k.startsWith("see:")).forEach((k) => {
const c = L[k].colour;
SPOTS.push({ place: k, first: true, colour: c, pose: FIRST_POSE[c], sc: 0.2, flip: L[k].x > 500 });
});
// Progressive disclosure: the idle map shows only the key moments. Clicking one reveals the choices made there
// (and the best route to every dragon from it); a picked dragon shows only its path and the choices taken on it.
const KEY = ["dir:West", "dir:Center", "dir:East", "scream", "bully", "wounded", "hour", "tree", "valley", "meadow", "stream"];
const FATES = ["res:Killed the bullies yourself", "res:Squadmate's revenge", "res:Left bullies to the dragons"];
const FORKS = ["fork:West", "fork:Forest", "fork:East"];
const CHILDREN = {
gate: ["comp:Alone", "comp:1 Squadmate", "comp:2 Squadmates"],
bully: ["away"].concat(FATES),
wounded: ["res:Tourniquet", "res:Left injured cadet", "res:Took their weapons"],
...Object.fromEntries(FATES.map((f) => [f, FORKS])),
};
const PARENT = {};
for (const [p, kids] of Object.entries(CHILDREN)) kids.forEach((k) => { if (!PARENT[k]) PARENT[k] = p; });
/** Places drawn on the idle map: the key moments, plus the choices at (and around) the place you picked. */
function visiblePlaces() {
const ids = new Set(KEY);
let p = st.point;
if (p) {
ids.add(p);
(CHILDREN[p] || []).forEach((k) => ids.add(k));
// the way here: each earlier choice point with its alternatives, so you can switch
for (let q = PARENT[p]; q; q = PARENT[q]) { ids.add(q); (CHILDREN[q] || []).forEach((k) => ids.add(k)); }
}
return ids;
}
const LANDMARK_NAME = { gate: "The entrance", "dir:West": "West, toward the scent", "dir:Center": "Forest centre", "dir:East": "East, toward the roar", "fork:Forest": "The fork" };
/* ---------- state ---------- */
const st = {
point: null, // a place picked before any dragon: show the best way from there to every dragon
policy: null, runs: null, counts: {}, colour: null, focus: null, expanded: null, over: {},
objective: "eventually", sample: "all", traffic: false, cache: new Map(), pendingHash: null, info: null,
};
const model = () => st.policy.samples[st.sample];
function advisorFor(enc, colour = st.colour) {
const k = `${st.sample}|${colour}|${st.objective}|${enc}`;
if (!st.cache.has(k)) st.cache.set(k, S.advisor(model(), colour, st.objective, { only: [enc] }));
return st.cache.get(k);
}
let encParams = null;
const encOutcome = (enc) => {
if (!encParams || encParams.sample !== st.sample) encParams = { sample: st.sample, p: S.makeParams(model().model.tables, { alphas: model().model.alphas }) };
return encParams.p.encounter(enc);
};
/* ---------- starting from a place ---------- */
// What being at a place means: the choices (and, for the shadow, the roll) that put you there, and the step you
// face next ("at"). Choices before it that are not listed stay free, and the best play is assumed for them.
const INV = "Investigate the scream", HELPC = "Help your squadmate";
const POINTS = {
gate: { force: {}, at: "company" },
"comp:Alone": { force: { company: "Alone" }, at: "direction" },
"comp:1 Squadmate": { force: { company: "1 Squadmate" }, at: "direction" },
"comp:2 Squadmates": { force: { company: "2 Squadmates" }, at: "direction" },
"dir:West": { force: { direction: "West" }, at: "fs" },
"dir:Center": { force: { direction: "Center" }, at: "fs" },
"dir:East": { force: { direction: "East" }, at: "fs" },
scream: { force: {}, at: "scream" },
bully: { force: { scream: INV, clearing: HELPC }, at: "fight", note: "You stepped in to help your squadmate. Each dragon's chance assumes your best first move in the fight (pause to assess) and includes the risk of being killed there; charging straight in kills about a third of riders. Walking away instead leads to the hour's walk." },
wounded: { force: { scream: "Keep walking" }, at: "wounded" },
away: { force: { scream: INV, clearing: "Walk away" }, at: "hour" },
"res:Killed the bullies yourself": { force: { scream: INV, clearing: HELPC, fate: "Killed the bullies yourself" }, at: "post" },
"res:Squadmate's revenge": { force: { scream: INV, clearing: HELPC, fate: "Squadmate's revenge" }, at: "post" },
"res:Left bullies to the dragons": { force: { scream: INV, clearing: HELPC, fate: "Left bullies to the dragons" }, at: "post" },
"res:Tourniquet": { force: { scream: "Keep walking", wounded: "Tourniquet" }, at: "hour" },
"res:Left injured cadet": { force: { scream: "Keep walking", wounded: "Left injured cadet" }, at: "hour" },
"res:Took their weapons": { force: { scream: "Keep walking", wounded: "Took their weapons" }, at: "hour" },
"fork:West": { force: { scream: INV, clearing: HELPC, post: "West" }, at: "hour" },
"fork:Forest": { force: { scream: INV, clearing: HELPC, post: "Forest" }, at: "hour" },
"fork:East": { force: { scream: INV, clearing: HELPC, post: "East" }, at: "hour" },
hour: { force: {}, at: "hour" },
tree: { force: { hour: "Tree" }, at: "shadow" },
valley: { force: { hour: "Valley" }, at: "valley" },
stream: { force: { hour: "Tree", shadow: "yes" }, at: "shadowColour" },
meadow: { force: { hour: "Valley", valley: "Pass the Red (meadow)" }, at: "meadow" },
};
/**
* Chance of bonding the advisor's colour once you are at a place: everything before it that the place implies is
* fixed, earlier rolls are averaged over the ways of getting there, and from there on the best play is used.
* Returns null when the place cannot lead to that dragon.
*/
function valueFrom(adv, pt) {
const rec = (h, reached) => {
const s = adv.step(h);
if (s.kind === "end") return { x: 0, w: reached ? 1 : 0 };
const live = reached && s.risk ? 1 - s.risk.p : 1;
const atPoint = !reached && s.var === pt.at && Object.keys(pt.force).every((k) => h[k] != null || k === pt.at);
const live2 = atPoint && pt.risk && s.risk ? 1 - s.risk.p : live;
if (reached || atPoint) {
if (s.kind === "decision") return { x: live2 * Math.max(...Object.values(s.options).map((v) => v.pX)), w: 1 };
let x = 0;
for (const [b, p] of Object.entries(s.probs)) if (p) x += p * rec({ ...h, [s.var]: b }, true).x;
return { x: live2 * x, w: 1 };
}
const forced = pt.force[s.var];
if (s.kind === "decision") {
const o = forced != null ? forced : s.choice;
if (!s.options[o]) return { x: 0, w: 0 };
const r = rec({ ...h, [s.var]: o }, false);
return { x: r.x, w: r.w * (s.risk ? 1 - s.risk.p : 1) };
}
// a roll before the place: only branches that can still get there count
let xw = 0, w = 0;
for (const [b, p] of Object.entries(s.probs)) {
if (!p || (forced != null && b !== forced)) continue;
const r = rec({ ...h, [s.var]: b }, false);
xw += p * r.w * r.x; w += p * r.w;
}
return { x: w ? xw / w : 0, w: w * (s.risk ? 1 - s.risk.p : 1) };
};
const r = rec({}, false);
return r.w > 1e-9 ? r.x : null;
}
/** For a picked place: per colour, the encounter with the best chance from there, and its route. */
function routesFrom(id) {
const pt = POINTS[id];
return COLOURS.map((c) => {
let best = null;
// the Greens rescue only counts for Orange/Brown when their own meadow is out of reach from here
const encs = S.ENCOUNTERS[c].filter((e) => RESCUE[c] !== e || c === "Green");
for (const pass of [encs, S.ENCOUNTERS[c].filter((e) => !encs.includes(e))]) {
for (const enc of pass) {
const v = valueFrom(advisorFor(enc, c), pt);
if (v != null && v > 0 && (!best || v > best.v)) best = { enc, v };
}
if (best) break;
}
if (!best) return { colour: c, v: null };
const r = walk(best.enc, c, pt.force);
r.geo = routePoints(r);
return { colour: c, enc: best.enc, v: best.v, route: r };
}).sort((a, b) => (b.v || 0) - (a.v || 0));
}
/* ---------- walking one route ---------- */
const encColour = (enc) => (enc === "tree-Greens" ? "Green" : enc.split("-")[1]);
function defaultOutcome(s, enc) {
const ent = Object.entries(s.probs).sort((a, b) => b[1] - a[1]);
if (s.var === "shadow") return enc.startsWith("shadow-") ? "yes" : "no";
if (s.var === "shadowColour" || s.var === "meadow") { const c = encColour(enc); if (s.probs[c] != null) return c; }
return ent[0][0];
}
function walk(enc, colour = st.colour, over = st.over[colour] || {}) {
const adv = advisorFor(enc, colour), steps = [], h = {};
for (let i = 0; i < 20; i++) {
const s = adv.step(h);
s.before = { ...h };
steps.push(s);
if (s.kind === "end") break;
const key = s.var;
const ok = s.kind === "decision" ? over[key] && s.options[over[key]] : over[key] && s.probs[over[key]] != null;
s.taken = ok ? over[key] : s.kind === "decision" ? s.choice : defaultOutcome(s, enc);
s.userSet = !!ok;
h[key] = s.taken;
}
const end = steps[steps.length - 1];
// a route your choices can no longer reach (e.g. you chose the tree, so the meadow is out)
const reachable = end.kind === "end" && end.encounter === enc && end.action !== "Die on purpose";
return { enc, adv, steps, reachable, value: Object.keys(over).length ? routeValue(adv, over) : adv.value };
}
/**
* Value of a route when the rider follows their own choices (overrides) and plays the best route everywhere else:
* expectimax over the rolls, using the overridden option where one is set. Option values already include the
* best play after them, so recursion stops as soon as no override is left to apply.
*/
function routeValue(adv, over) {
const keys = Object.keys(over);
const rec = (h) => {
const s = adv.step(h);
if (s.kind === "end") return { x: 0, o: 0 };
const live = s.risk ? 1 - s.risk.p : 1;
if (s.kind === "chance") {
return Object.entries(s.probs).reduce((acc, [b, p]) => {
if (!p) return acc;
const v = rec({ ...h, [s.var]: b });
return { x: acc.x + p * v.x, o: acc.o + p * v.o };
}, { x: 0, o: 0 });
}
const o = over[s.var] && s.options[over[s.var]] ? over[s.var] : s.choice;
const pending = keys.some((k) => h[k] == null && k !== s.var);
if (!pending) { const v = s.options[o]; return { x: live * v.pX, o: live * v.pOther }; }
const v = rec({ ...h, [s.var]: o });
return { x: live * v.x, o: live * v.o };
};
return rec({});
}
/** The route as points on the map, each with the chance of still being on it, plus where decisions are made. */
function routePoints(route) {
const pts = [{ id: "gate", P: GATE, flow: 1 }], marks = [], rolls = [];
let flow = 1;
const push = (id) => { if (L[id]) pts.push({ id, P: L[id], flow }); };
const last = () => pts[pts.length - 1];
route.steps.forEach((s, i) => {
if (s.risk) flow *= 1 - s.risk.p;
if (s.kind === "chance") flow *= s.probs[s.taken] || 0;
if (s.kind === "end") return;
if (s.kind === "decision") marks.push({ i, s, at: last() });
const before = pts.length;
const v = s.taken, h = s.before;
switch (s.var) {
case "company": push("comp:" + v); break;
case "leave": case "react": break; // made where you stand (the start, the first dragon)
case "direction": push("dir:" + v); break;
case "fs": push(`see:${h.direction}:${v}`); break;
// the cadet encounter, step by step: you hear the scream, then either investigate (the clearing with your
// squadmate and the bullies) or keep walking (the wounded cadet)
case "scream": push("scream"); marks[marks.length - 1].at = last(); push(v === "Keep walking" ? "wounded" : "bully"); break;
case "clearing": if (v === "Walk away") push("away"); break;
case "fate": case "wounded": push("res:" + v); break;
case "post": push("fork:" + v); break;
case "hour": push("hour"); marks[marks.length - 1].at = last(); push(v === "Tree" ? "tree" : "valley"); break;
case "shadow": if (v === "yes") push("stream"); break;
case "shadowColour": push(v === "Black" ? "black" : "redwood"); break;
case "descend": push(v.startsWith("Quickly") ? "treeRed" : "greens"); break;
case "red": if (!v.startsWith("Jump")) push("greens"); break;
case "valley": push(v === "Face the Red" ? "valleyRed" : "meadow"); break;
case "meadow": push("meadow:" + v); break;
default: break;
}
// a roll is labelled on the segment it leads into (or at the current point when nothing moves)
if (s.kind === "chance") rolls.push({ s, at: pts.length > before ? pts.length - 1 : null, P: last().P });
});
return { pts, marks, rolls, endFlow: flow };
}
// where each option of a decision leads on the map (for expanded choice points)
const optionPlace = (s, v) => ({
company: "comp:" + v, direction: "dir:" + v, post: "fork:" + v,
scream: v === "Keep walking" ? "wounded" : "bully",
clearing: v === "Walk away" ? "away" : "bully",
fight: "bully", dagger: "bully", leave: null, react: null,
red: v.startsWith("Jump") ? "treeRed" : "greens",
fate: "res:" + v, wounded: "res:" + v,
hour: v === "Tree" ? "tree" : "valley", descend: v.startsWith("Quickly") ? "treeRed" : "greens",
valley: v === "Face the Red" ? "valleyRed" : "meadow",
}[s.var]);
/* ---------- drawing ---------- */
let base = null; // painted valley, cached as markup
function paintBase(svg) {
if (!base) {
const tmp = document.createElementNS(NS, "svg");
V.paintBase(tmp);
base = tmp.innerHTML.replace(/vm-/g, "ex-");
}
svg.innerHTML = base;
}
function curve(A, B, bend = 0.08, off = 0) {
const dx = B.x - A.x, dy = B.y - A.y, len = Math.hypot(dx, dy) || 1, nx = -dy / len * off, ny = dx / len * off;
const a = { x: A.x + nx, y: A.y + ny }, b = { x: B.x + nx, y: B.y + ny };
return `M${a.x} ${a.y} Q${(a.x + b.x) / 2 - dy * bend} ${(a.y + b.y) / 2 + dx * bend} ${b.x} ${b.y}`;
}
const mid = (A, B, t = 0.5, bend = 0.08) => {
const mx = (A.x + B.x) / 2 - (B.y - A.y) * bend, my = (A.y + B.y) / 2 + (B.x - A.x) * bend;
return { x: (1 - t) ** 2 * A.x + 2 * (1 - t) * t * mx + t * t * B.x, y: (1 - t) ** 2 * A.y + 2 * (1 - t) * t * my + t * t * B.y };
};
// label text is always dark ink (light dragon colours like Orange are unreadable as text on paper);
// the dragon's colour goes on the border instead
let pills = []; // every label drawn this render, so overlapping ones can be pushed apart afterwards
function pill(g0, x, y, text, { ink = PAPER.ink, edge = null, strong = false, bg = PAPER.halo } = {}) {
const w = 10 + text.length * (strong ? 7.2 : 6.4), h = strong ? 20 : 17;
const g = el("g", {}, g0);
pills.push({ g, x, y, w, h, dy: 0 });
el("rect", { x: x - w / 2, y: y - h / 2, width: w, height: h, rx: h / 2, fill: bg, "fill-opacity": 0.95, stroke: edge || ink, "stroke-opacity": edge ? 0.95 : 0.4, "stroke-width": edge ? 2 : 1 }, g);
el("text", { x, y: y + (strong ? 4.5 : 4), "text-anchor": "middle", "font-size": strong ? 12.5 : 11, "font-weight": strong ? 700 : 500, fill: ink, "font-family": "var(--font-data)" }, g).textContent = text;
}
function drawDragons(g, routesOn) {
const maxN = Math.max(1, ...SPOTS.filter((s) => !s.first).map((s) => st.counts[s.place] || 0));
const maxF = Math.max(1, ...SPOTS.filter((s) => s.first).map((s) => st.counts[s.place] || 0));
SPOTS.forEach((sp) => {
const P = L[sp.place];
if (!P) return;
const n = st.counts[sp.place];
// faint = rarely met, but never so faint it disappears (bonding dragons keep a higher floor)
let op = n == null ? 0.85 : (sp.first ? 0.35 : 0.5) + (sp.first ? 0.65 : 0.5) * Math.sqrt(n / (sp.first ? maxF : maxN));
const isTarget = st.colour && !sp.first && (encColour(sp.enc) === st.colour || RESCUE[st.colour] === sp.enc);
if (st.colour && !isTarget) op = Math.max(0.3, op * 0.5); // faded, but never lost
if (isTarget) op = Math.max(op, 0.9);
const w = 200 * sp.sc, hgt = 160 * sp.sc;
const x = P.x - w / 2 + (sp.dx || 0), y = P.y - hgt * 0.7 + (sp.dy || 0);
const gg = el("g", { class: "ex-dragon", transform: `translate(${x} ${y}) scale(${sp.sc})`, opacity: op.toFixed(2), tabindex: sp.twin ? null : 0, role: sp.twin ? null : "button",
"aria-label": sp.first ? `${sp.colour} dragon, first sighting` : `${ENC_NAME[sp.enc]}. Show the routes to it.` }, g);
if (isTarget && routesOn) el("ellipse", { cx: 100, cy: 140, rx: 80, ry: 16, fill: INK[sp.colour], "fill-opacity": 0.25 }, gg);
// a soft paper-coloured halo keeps dark dragons readable on the dark canopy
gg.innerHTML += `<g stroke="${PAPER.halo}" stroke-width="9" stroke-linejoin="round" opacity="0.55">${D.svg(sp.pose, { fill: PAPER.halo, eyeFill: PAPER.halo, flip: sp.flip })}</g>`;
gg.innerHTML += D.svg(sp.pose, { fill: INK[sp.colour], flip: sp.flip });
el("rect", { x: 0, y: 0, width: 200, height: 160, fill: "transparent" }, gg);
if (sp.twin) return;
const tipHtml = () => {
if (sp.first) return `<b>${sp.colour} dragon</b><br>One of the first dragons you can meet here. This is a roll of the dice, not a bonding.${n != null ? `<br>${n.toLocaleString()} riders met it here` : ""}`;
const o = st.policy ? encOutcome(sp.enc) : null;
const c = encColour(sp.enc);
const bond = o ? (sp.enc === "tree-Greens" ? `Green ${pct(o.Green)}, rescue by Orange ${pct(o.Orange || 0)} or Brown ${pct(o.Brown || 0)}` : pct(o[c])) : "–";
return `<b>${ENC_NAME[sp.enc]}</b>${n != null ? `<br>${n.toLocaleString()} riders met it here` : ""}<br>Bond chance when attempted: ${bond}`;
};
gg.addEventListener("mouseenter", (e) => showTip(e, tipHtml()));
gg.addEventListener("mousemove", (e) => moveTip(e));
gg.addEventListener("mouseleave", hideTip);
gg.addEventListener("focus", () => { const r = gg.getBoundingClientRect(); showTip({ clientX: r.right, clientY: r.top }, tipHtml()); });
gg.addEventListener("blur", hideTip);
const go = () => {
hideTip();
if (sp.first) { st.info = sp; render(); return; }
select(encColour(sp.enc) === "Green" && st.colour && RESCUE[st.colour] === sp.enc ? st.colour : encColour(sp.enc), sp.enc);
};
gg.addEventListener("click", go);
gg.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } });
});
}
/* ---------- the people (and the thorn) of the valley ---------- */
const SCENERY = [
{ at: "bully", fig: "defender", dx: -150, dy: 62, sc: 0.42, tip: "The bully fight", text: "Your squadmate holds off two cadets who have bullied them since Parapet. Help them, or walk away." },
{ at: "bully", fig: "lunging", dx: -126, dy: 62, sc: 0.42, tip: "The bully fight", text: "The bigger cadet swings a sword; the smaller one has a dagger ready to throw." },
{ at: "bully", fig: "throwing", dx: -98, dy: 62, sc: 0.42, tip: "The bully fight", text: "Pause to assess, charge the smaller cadet, or get between your squadmate and the bigger one. After pausing, the smaller cadet's dagger. Then the bullies' fate." },
{ at: "wounded", fig: "lying", dx: -72, dy: 4, sc: 0.56, tip: "The wounded cadet", text: "Ignore the scream and you find a badly wounded cadet. Tie a tourniquet, leave them, or take their weapons." },
{ at: "hour", fig: "thorns", dx: -66, dy: 6, sc: 0.44, tip: "An hour's walk", text: "No dragon for an hour, and a thorn cuts the back of your hand. Then: climb the tallest tree, or walk on to the valley centre." },
];
function drawScenery(g, onRoute) {
SCENERY.forEach((sc) => {
const P = L[sc.at];
if (!P) return;
const faded = st.colour && !onRoute.has(sc.at);
const x = P.x + (sc.dx || 0) - 50 * sc.sc, y = P.y + (sc.dy || 0) - 136 * sc.sc;
const gg = el("g", { class: "ex-scene", transform: `translate(${x} ${y}) scale(${sc.sc})`, opacity: faded ? 0.35 : 0.88 }, g);
gg.innerHTML = D.figure(sc.fig, { fill: sc.fig === "thorns" ? "#4a3a22" : PAPER.ink, flip: !!sc.flip });
el("rect", { x: 0, y: 0, width: 100, height: 140, fill: "transparent" }, gg);
const html = `<b>${esc(sc.tip)}</b><br>${esc(sc.text)}`;
gg.addEventListener("mouseenter", (e) => showTip(e, html));
gg.addEventListener("mousemove", (e) => moveTip(e));
gg.addEventListener("mouseleave", hideTip);
});
}
function drawLandmarks(g, onRoute) {
// with a dragon picked: only the places on its routes (opened choices add theirs)
const ids = st.colour ? new Set() : visiblePlaces();
onRoute.forEach((id) => { if (L[id] && L[id].kind !== "dragon") ids.add(id); });
ids.forEach((id) => {
const P = L[id];
if (!P || P.kind === "dragon") return;
const strong = onRoute.has(id);
el("circle", { cx: P.x, cy: P.y, r: strong ? 6 : 4.5, fill: PAPER.ink, "fill-opacity": strong ? 0.95 : 0.7, stroke: PAPER.halo, "stroke-width": 2 }, g);
// small choice points sit close together, so they honour "above" as well as left/right
const pos = P.kind === "small" && P.lab === "above" ? "above" : (P.lab || "right") === "left" ? "left" : "right";
const t = el("text", { x: P.x + (pos === "right" ? 10 : pos === "left" ? -10 : 0), y: P.y + (pos === "above" ? -10 : 4), "text-anchor": pos === "right" ? "start" : pos === "left" ? "end" : "middle", "font-family": "var(--font-display)", "font-size": strong ? 14 : 13,
fill: PAPER.ink, "fill-opacity": strong ? 1 : 0.8, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3.5, "stroke-linejoin": "round" }, g);
t.textContent = LANDMARK_NAME[id] || P.name;
// before a dragon is chosen, any place can be a starting point: "from here, how do I reach each dragon?"
if (!st.colour && POINTS[id] && st.policy) {
if (st.point === id) el("circle", { cx: P.x, cy: P.y, r: 11, fill: "none", stroke: PAPER.ink, "stroke-width": 2.5 }, g);
const hit = el("g", { class: "ex-place", tabindex: 0, role: "button", "aria-label": `${t.textContent}: show the best way from here to every dragon` }, g);
el("circle", { cx: P.x, cy: P.y, r: 14, fill: "transparent" }, hit);
hit.appendChild(t);
el("title", {}, hit).textContent = `${t.textContent}: from here to every dragon`;
const go = () => { st.point = st.point === id ? null : id; st.info = null; writeHash(); render(); };
hit.addEventListener("click", go);
hit.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } });
}
});
const gt = el("text", { x: GATE.x, y: GATE.y + 14, "text-anchor": "middle", "font-size": 11, "letter-spacing": "0.16em", fill: PAPER.ink, "font-family": "var(--font-label)", "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3 }, g);
gt.textContent = "ENTER THE VALLEY";
if (!st.colour && st.policy) {
// the entrance is a key moment too: who you go in with
const hit = el("g", { class: "ex-place", tabindex: 0, role: "button", "aria-label": "The entrance: who you enter with, and the best way to every dragon" }, g);
el("rect", { x: GATE.x - 70, y: GATE.y - 2, width: 140, height: 22, fill: "transparent" }, hit);
hit.appendChild(gt);
el("title", {}, hit).textContent = "The entrance: who you enter with";
const go = () => { st.point = st.point === "gate" ? null : "gate"; st.info = null; writeHash(); render(); };
hit.addEventListener("click", go);
hit.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } });
}
}
function drawTraffic(g) {
if (!st.runs) return;
const edges = new Map();
st.runs.forEach((r) => {
const seq = V.path(r);
for (let i = 1; i < seq.length; i++) {
const k = seq[i - 1] + ">" + seq[i];
edges.set(k, (edges.get(k) || 0) + 1);
}
});
const max = Math.max(1, ...edges.values());
[...edges.entries()].sort((a, b) => b[1] - a[1]).forEach(([k, n]) => {
const [a, b] = k.split(">");
if (!L[a] || !L[b]) return;
el("path", { d: curve(L[a], L[b], 0.05), fill: "none", stroke: "#6b4a33", "stroke-opacity": 0.32, "stroke-width": 1.5 + 18 * Math.sqrt(n / max), "stroke-linecap": "round" }, g);
});
}
function drawRoutes(gRoute, gLab, routes) {
const best = Math.max(1e-12, ...routes.map((r) => r.value.x));
const onRoute = new Set();
const tc = INK[st.colour];
const cards = [];
// weaker routes first so the best one sits on top
[...routes].sort((a, b) => a.value.x - b.value.x).forEach((r) => {
const rel = r.value.x / best;
const focus = r.enc === st.focus;
const dash = rel >= 0.5 ? null : rel >= 0.1 ? "14 9" : "3 9";
const op = (0.3 + 0.65 * rel) * (focus ? 1 : 0.85);
const off = (routes.indexOf(r) - (routes.length - 1) / 2) * 7;
const { pts, marks } = r.geo;
pts.forEach((p) => onRoute.add(p.id));
for (let i = 1; i < pts.length; i++) {
const A = pts[i - 1].P, B = pts[i].P, w = 3 + 22 * pts[i].flow;
const d = curve(A, B, 0.08, off);
if (focus) el("path", { d, fill: "none", stroke: "#fff1c9", "stroke-width": w + 6, "stroke-opacity": 0.55, "stroke-linecap": "round" }, gRoute);
el("path", { d, fill: "none", stroke: tc, "stroke-width": w, "stroke-opacity": op, "stroke-linecap": dash ? "butt" : "round", "stroke-dasharray": dash, class: "ex-route" }, gRoute);
}
// rolls of the dice: the odds where the route narrows (focused route only)
if (focus) r.geo.rolls.forEach((ro) => {
const p = ro.s.probs[ro.s.taken];
if (p > 0.995) return;
// the last roll leads straight into the dragon, whose own label sits there: put the roll under the fork point
const at = !ro.at ? { x: ro.P.x + 34, y: ro.P.y - 22 } : ro.at === pts.length - 1 ? { x: pts[ro.at - 1].P.x, y: pts[ro.at - 1].P.y + 24 } : mid(pts[ro.at - 1].P, pts[ro.at].P, 0.38);
pill(gLab, at.x, at.y, ro.s.var === "shadow" ? (ro.s.taken === "yes" ? `shadow ${pct(p)}` : `no shadow ${pct(p)}`) : `roll ${pct(p)}`);
});
// destination label
const end = pts[pts.length - 1];
pill(gLab, end.P.x, end.P.y + 30, `${pct(r.value.x)} per attempt`, { edge: tc, strong: rel === 1 });
// choice points on the focused route: one diamond per place, even when several choices are made there
// (at the bully fight: help or walk away, your first move, the dagger, then the bullies' fate)
if (focus) {
const groups = [];
marks.forEach((m) => {
if (!m.at || m.s.var === "encounter") return;
const g0 = groups.find((x) => x.at.id === m.at.id);
if (g0) g0.list.push(m); else groups.push({ at: m.at, list: [m] });
});
groups.forEach((grp) => {
const P = grp.at.P, vars = grp.list.map((m) => m.s.var), open = vars.includes(st.expanded);
const label = grp.list.map((m) => `${m.s.label}: ${m.s.taken}`).join("; ");
const g = el("g", { class: "ex-mark", tabindex: 0, role: "button", "aria-label": `${label}. Show the other options.`, "aria-expanded": open }, gLab);
el("path", { d: `M${P.x} ${P.y - 9} L${P.x + 9} ${P.y} L${P.x} ${P.y + 9} L${P.x - 9} ${P.y} Z`, fill: open ? tc : PAPER.halo, stroke: tc, "stroke-width": 2.5 }, g);
if (grp.list.length > 1) {
const t = el("text", { x: P.x + 11, y: P.y - 8, "font-size": 10, "font-weight": 700, fill: tc, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3, "font-family": "var(--font-data)" }, g);
t.textContent = grp.list.length;
}
el("title", {}, g).textContent = `${label} (click for the other options)`;
const go = () => { st.expanded = open ? null : vars[0]; render(); };
g.addEventListener("click", go);
g.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); } });
if (!open) return;
const rows = [];
grp.list.forEach((m) => {
const opts = Object.entries(m.s.options);
const best2 = Math.max(1e-12, ...opts.map(([, v]) => v.pX));
// a choice made right here (no other place to point at) is listed in a small card
const here = opts.some(([v]) => { const pid = optionPlace(m.s, v); return !pid || !L[pid] || L[pid] === P; });
if (here) { rows.push(m); return; }
opts.forEach(([v, val]) => {
const pid = optionPlace(m.s, v);
if (!pid || !L[pid] || v === m.s.taken) return;
const B = L[pid], rel2 = val.pX / best2;
const pth = el("path", { d: curve(P, B, 0.1), fill: "none", stroke: tc, "stroke-width": 2 + 4 * rel2, "stroke-opacity": 0.35 + 0.5 * rel2, "stroke-dasharray": "6 6", "stroke-linecap": "round", class: "ex-alt", tabindex: 0, role: "button", "aria-label": `${v}: ${pct(val.pX)}. Take this instead.` }, gLab);
// the option's own place is labelled on the map, so its chance sits just under that place
onRoute.add(pid);
pill(gLab, B.x, B.y + 17, pct(val.pX));
const pick = () => choose(m.s.var, v);
pth.addEventListener("click", pick);
pth.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pick(); } });
});
});
if (rows.length) cards.push({ P, rows, tc });
});
}
});
cards.forEach((c) => drawCard(gLab, c));
return onRoute;
}
// short names for the choice card (the panel keeps the full ones)
const SHORT = {
"Help your squadmate": "Help them", "Walk away": "Walk away",
"Pause to assess": "Pause to assess", "Charge the smaller cadet": "Charge the smaller one",
"Charge between the bigger cadet and your squadmate": "Get between them",
"Engage the smaller cadet": "Engage the smaller one", "Charge the bigger cadet anyway": "Charge the bigger one",
};
const CAPTION = { leave: "Your squadmates", react: "When the first dragon appears", clearing: "Your squadmate vs two bullies", fight: "Your first move", dagger: "The smaller cadet has a dagger" };
/**
* The choices made at one place, in the game's order, as a small card beside it: one row per choice, every
* option with its chance (the one on this route is filled). Clicking an option takes it instead.
*/
function drawCard(g0, { P, rows, tc }) {
const W = 300, pad = 10, gap = 6, rowH = 22, capH = 15;
const lay = rows.map((m) => {
const items = [];
let x = 0, y = 0;
Object.entries(m.s.options).forEach(([v, val]) => {
const text = `${SHORT[v] || v} ${pct(val.pX)}`, w = 14 + text.length * 6.3;
if (x && x + w > W - 2 * pad) { x = 0; y += rowH; }
items.push({ v, val, text, w, x, y }); x += w + gap;
});
return { m, items, h: capH + y + rowH };
});
const H = pad + lay.reduce((a, r) => a + r.h + 6, 0) + pad - 6;
let x0 = P.x + 22, y0 = P.y - H / 2;
if (x0 + W > 992) x0 = P.x - 22 - W;
y0 = Math.max(8, Math.min(782 - H, y0));
const g = el("g", { class: "ex-card-map" }, g0);
el("rect", { x: x0, y: y0, width: W, height: H, rx: 10, fill: PAPER.halo, "fill-opacity": 0.97, stroke: tc, "stroke-width": 2 }, g);
let y = y0 + pad;
lay.forEach(({ m, items, h }) => {
el("text", { x: x0 + pad, y: y + 10, "font-size": 10.5, "font-weight": 700, "letter-spacing": ".06em", fill: PAPER.ink, "fill-opacity": 0.75, "font-family": "var(--font-data)" }, g)
.textContent = (CAPTION[m.s.var] || m.s.label).toUpperCase();
items.forEach((it) => {
const on = it.v === m.s.taken, bx = x0 + pad + it.x, by = y + capH + it.y;
const b = el("g", { class: "ex-alt", tabindex: 0, role: "button", "aria-pressed": on, "aria-label": `${m.s.label}: ${it.v}, ${pct(it.val.pX)}${on ? " (on this route)" : ". Take this instead."}` }, g);
el("rect", { x: bx, y: by, width: it.w, height: 18, rx: 9, fill: on ? tc : PAPER.halo, stroke: tc, "stroke-width": 1.5 }, b);
el("text", { x: bx + it.w / 2, y: by + 13, "text-anchor": "middle", "font-size": 11, "font-weight": on ? 700 : 500, fill: on ? "#fff" : PAPER.ink, "font-family": "var(--font-data)" }, b).textContent = it.text;
el("title", {}, b).textContent = it.v;
if (!on) {
const pick = () => choose(m.s.var, it.v);
b.addEventListener("click", pick);
b.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); pick(); } });
}
});
y += h + 6;
});
}
/** Push overlapping labels apart vertically (a few relaxation passes), so no two chances sit on top of each other. */
function spreadPills() {
const gap = 3;
for (let pass = 0; pass < 30; pass++) {
let moved = false;
for (let i = 0; i < pills.length; i++) for (let j = i + 1; j < pills.length; j++) {
const a = pills[i], b = pills[j];
const ox = Math.min(a.x + a.w / 2, b.x + b.w / 2) - Math.max(a.x - a.w / 2, b.x - b.w / 2);
const ay = a.y + a.dy, by = b.y + b.dy;
const oy = Math.min(ay + a.h / 2, by + b.h / 2) - Math.max(ay - a.h / 2, by - b.h / 2);
if (ox > 0 && oy > -gap) {
const push = (oy + gap) / 2, down = by >= ay ? 1 : -1;
a.dy -= push * down; b.dy += push * down; moved = true;
}
}
if (!moved) break;
}
pills.forEach((p) => { if (p.dy) p.g.setAttribute("transform", `translate(0 ${p.dy.toFixed(1)})`); });
}
/** All six dragons from one place: the way there in ink, then one line per dragon in its colour. */
function drawFrom(gRoute, gLab, list) {
const onRoute = new Set([st.point]);
const ok = list.filter((x) => x.route);
if (!ok.length) return onRoute;
const best = Math.max(1e-12, ...ok.map((x) => x.v));
// the way to the place (from the most likely dragon's route)
const lead = ok[0].route.geo.pts;
const at = lead.findIndex((p) => p.id === st.point);
for (let i = 1; i <= at; i++) {
el("path", { d: curve(lead[i - 1].P, lead[i].P, 0.08), fill: "none", stroke: PAPER.ink, "stroke-width": 4, "stroke-opacity": 0.55, "stroke-dasharray": "2 8", "stroke-linecap": "round" }, gRoute);
onRoute.add(lead[i].id);
}
[...ok].reverse().forEach((x, k) => {
const pts = x.route.geo.pts, i0 = pts.findIndex((p) => p.id === st.point);
if (i0 < 0) return;
const f0 = pts[i0].flow || 1, rel = x.v / best, off = (COLOURS.indexOf(x.colour) - 2.5) * 5;
for (let i = i0 + 1; i < pts.length; i++) {
const w = 2.5 + 12 * Math.min(1, pts[i].flow / f0);
el("path", { d: curve(pts[i - 1].P, pts[i].P, 0.08, off), fill: "none", stroke: INK[x.colour], "stroke-width": w, "stroke-opacity": 0.45 + 0.45 * rel, "stroke-linecap": "round" }, gRoute);
onRoute.add(pts[i].id);
}
const end = pts[pts.length - 1];
pill(gLab, end.P.x, end.P.y + 30, `${x.colour} ${pct(x.v)}`, { edge: INK[x.colour], strong: rel === 1 });
});
return onRoute;
}
/* ---------- tooltip ---------- */
function showTip(e, html) { const t = $("#ex-tip"); t.innerHTML = html; t.hidden = false; moveTip(e); }
function moveTip(e) {
const t = $("#ex-tip"), box = $(".ex-map-wrap").getBoundingClientRect(), r = t.getBoundingClientRect();
t.style.left = Math.min(box.width - r.width - 8, Math.max(8, e.clientX - box.left + 14)) + "px";
t.style.top = Math.min(box.height - r.height - 8, Math.max(8, e.clientY - box.top + 14)) + "px";
}
const hideTip = () => { const t = $("#ex-tip"); if (t) t.hidden = true; };
/* ---------- panel ---------- */
const mini = (c, pose = "sitting") => `<svg viewBox="0 0 200 160" aria-hidden="true">${D.svg(pose, { fill: `var(${DV[c]})`, eyeFill: "var(--bg)" })}</svg>`;
const POSE_OF = { Red: "roaring", Orange: "flying", Brown: "resting", Green: "prowling", Blue: "coiled", Black: "flying" };
const trafficToggle = () => `<label class="ex-toggle"><input type="checkbox" id="ex-traffic"${st.traffic ? " checked" : ""}> Show where riders actually went</label>`;
function chooser() {
return `<div class="ex-choose">${COLOURS.map((c) => `<button type="button" class="ex-dchip" data-c="${c}" aria-pressed="${st.colour === c}" style="--c: var(${DV[c]})">${mini(c, POSE_OF[c])}<span>${c}</span></button>`).join("")}</div>`;
}
function panelIdle() {
let info = "";
if (st.info) {
const sp = st.info, dir = sp.place.split(":")[1];
const fs = st.policy ? S.makeParams(model().model.tables, { alphas: model().model.alphas }).chance("fs", { direction: dir }) : null;
info = `<div class="ex-card"><span class="eyebrow">First sighting · ${dir === "Center" ? "forest centre" : dir.toLowerCase()}</span>
<p class="small">The first dragon is a roll of the dice: nobody bonds here, it decides what you face next.${fs ? ` Going ${dir === "Center" ? "to the forest centre" : dir.toLowerCase()}, riders met: ${Object.entries(fs).sort((a, b) => b[1] - a[1]).filter(([, p]) => p > 0.005).map(([k, p]) => `${k} ${pct(p)}`).join(", ")}.` : ""}</p></div>`;
}
return `<span class="eyebrow">Unofficial atlas · built from ${st.runs ? st.runs.length.toLocaleString() : "thousands of"} logged runs</span>
<h2 id="h-valley">The valley</h2>
<p class="small muted">Every dragon is drawn where riders meet it. The fainter it is, the fewer riders reach it. Choose one to see its best route and the choices on it. Or click a key moment on the map, including the entrance, to see the choices you make there and your best chance at each dragon from it.</p>
${chooser()}${info}
${trafficToggle()}
<p class="small muted">Prefer the numbers? <a href="#odds">The Odds</a> has the statistics behind the map.</p>`;
}
const placeName = (id) => LANDMARK_NAME[id] || (L[id] && L[id].name) || id;
/** The choices made at the picked place, each a further place to start from, and the way back up. */
function choicesHere() {
const kids = (CHILDREN[st.point] || []).filter((k) => POINTS[k]);
const up = PARENT[st.point];
if (!kids.length && !up) return "";
return `<div class="ex-here">${kids.length ? `<span class="eyebrow">Your choices here</span>
<div class="ex-here-row">${kids.map((k) => `<button type="button" class="ex-chip" data-pt="${esc(k)}">${esc((L[k] && L[k].name) || placeName(k))}</button>`).join("")}</div>` : ""}
${up ? `<button type="button" class="linklike" data-pt="${esc(up)}">← Back to ${esc(placeName(up).toLowerCase())}</button>` : ""}</div>`;
}
function panelFrom(list) {
const name = LANDMARK_NAME[st.point] || (L[st.point] && L[st.point].name) || st.point;
const top = Math.max(1e-12, ...list.map((x) => x.v || 0));
const rows = list.map((x) => x.v == null
? `<div class="ex-from-row off" style="--c: var(${DV[x.colour]})">${mini(x.colour, POSE_OF[x.colour])}<span class="nm">${x.colour}</span><small>not reachable from here</small></div>`
: `<button type="button" class="ex-from-row" data-c="${x.colour}" data-enc="${x.enc}" style="--c: var(${DV[x.colour]}); --w: ${(100 * x.v / top).toFixed(1)}%">${mini(x.colour, POSE_OF[x.colour])}
<span class="nm">${x.colour}<small>${esc(ENC_NAME[x.enc])}${RESCUE[x.colour] === x.enc && x.colour !== "Green" ? " (rescue)" : ""}</small></span><b>${pct(x.v)}</b><i></i></button>`).join("");
return `<div class="ex-head"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="5" fill="var(--accent)"/><circle cx="12" cy="12" r="10" fill="none" stroke="var(--accent)" stroke-width="2"/></svg>
<div><span class="eyebrow">Starting from</span><h2 id="h-valley">${esc(name)}</h2></div>
<button type="button" class="ex-close" id="ex-clear-point" aria-label="Back to the whole valley">×</button></div>
${POINTS[st.point].note ? `<p class="small">${esc(POINTS[st.point].note)}</p>` : ""}
<p class="small muted">From here, this is your best chance of bonding each dragon from here on, playing the best route after this point. Earlier rolls are averaged over the ways of getting here. Pick a dragon to follow its route step by step.</p>
${choicesHere()}
<div class="ex-from">${rows}</div>
<div class="seg" role="group" aria-label="Goal"><button type="button" data-o="eventually" aria-pressed="${st.objective === "eventually"}">Only this dragon</button><button type="button" data-o="thisAttempt" aria-pressed="${st.objective === "thisAttempt"}">Best odds this run</button></div>
${trafficToggle()}`;
}
function panelRoutes(routes) {
const best = Math.max(1e-12, ...routes.map((r) => r.value.x));
const T = model().targets[st.colour], b = T[st.objective];
const focus = routes.find((r) => r.enc === st.focus) || routes[0];
const card = (r) => {
const rel = r.value.x / best, o = encOutcome(r.enc), c = encColour(r.enc);
const n = r.adv.attempts(r.enc);
const bond = r.enc === "tree-Greens" && st.colour !== "Green" ? `rescue by ${st.colour}: ${pct(o[st.colour] || 0)}` : `bond chance there: ${pct(o[c])}`;
const style = rel >= 0.5 ? "solid" : rel >= 0.1 ? "dashed" : "dotted";
return `<button type="button" class="ex-route-card${r.enc === focus.enc ? " on" : ""}" data-enc="${r.enc}" aria-pressed="${r.enc === focus.enc}">
<i class="ex-swatch ${style}" style="--c: var(${DV[st.colour]}); opacity:${(0.3 + 0.7 * rel).toFixed(2)}"></i>
<span class="nm">${esc(ENC_NAME[r.enc])}${RESCUE[st.colour] === r.enc && st.colour !== "Green" ? " <em>(rescue)</em>" : ""}</span>
<b>${pct(r.value.x)}</b><small>per attempt · ${bond}${n < 30 ? ` · only ${n} attempts logged` : ""}${r.value.o > 0.005 ? ` · ends on another dragon ${pct(r.value.o)}` : ""}</small></button>`;
};
const steps = focus.steps.filter((s) => s.kind === "decision" || s.kind === "chance").map((s) => {
if (s.kind === "chance") return `<li class="chance"><span>${esc(s.label)}</span><b>${esc(String(s.taken))}</b><small>roll ${pct(s.probs[s.taken])}</small></li>`;
const open = st.expanded === s.var;
const opts = open ? `<div class="ex-opts">${Object.entries(s.options).sort((a, c) => c[1].pX - a[1].pX).map(([v, val]) =>
`<button type="button" class="ex-opt${v === s.taken ? " on" : ""}" data-var="${s.var}" data-v="${esc(v)}"><span>${esc(v)}${v === s.choice ? ' <em class="rec">best</em>' : ""}</span><b>${pct(val.pX)}</b></button>`).join("")}</div>` : "";
return `<li class="dec${open ? " open" : ""}"><button type="button" class="ex-step" data-var="${s.var}" aria-expanded="${open}"><span>${esc(s.label)}</span><b>${esc(String(s.taken))}</b><small>${s.userSet ? "your choice" : "best"} · ${s.var === "encounter" ? pct(s.options[s.taken].pX) : pct(s.options[s.taken].pX)}</small></button>${opts}</li>`;
}).join("");
const risks = focus.steps.filter((s) => s.risk && s.risk.p > 0.0005).map((s) => `${s.risk.label.toLowerCase()} ${pct(s.risk.p)}`);
const lb = st.policy.samples.lowBias.targets[st.colour].thisAttempt;
return `<div class="ex-head" style="--c: var(${DV[st.colour]})">${mini(st.colour, POSE_OF[st.colour])}<div><span class="eyebrow">Routes to a</span><h2 id="h-valley">${st.colour} dragon</h2></div>
<button type="button" class="ex-close" id="ex-clear" aria-label="Back to the whole valley">×</button></div>
${chooser()}
<div class="seg" role="group" aria-label="Goal"><button type="button" data-o="eventually" aria-pressed="${st.objective === "eventually"}" title="Die on purpose and try again whenever it goes wrong; never risk ending on another dragon">Only this dragon</button><button type="button" data-o="thisAttempt" aria-pressed="${st.objective === "thisAttempt"}" title="Best chance on this one run">Best odds this run</button></div>
${st.blocked ? `<p class="small ex-warn">Your choices so far can't reach a ${st.colour} dragon. <button type="button" class="linklike" id="ex-reset-route">Reset your choices</button></p>` : ""}
<div class="ex-routes">${routes.map(card).join("")}</div>
<p class="small muted ex-key"><span class="solid"></span> best route <span class="dashed"></span> under half as likely <span class="dotted"></span> under a tenth · line width: chance you are still on the route</p>
<span class="eyebrow">${esc(ENC_NAME[focus.enc])}: step by step</span>
<ol class="ex-steps">${steps}</ol>
<p class="small muted">Diamonds on the map are choices: click one to see where the other options lead. ${st.blocked ? "" : `Your choices apply to every route to this dragon. Changed your mind? <button type="button" class="linklike" id="ex-reset-route">Reset your choices</button>`}</p>
<details class="ex-why"><summary>Why this route?</summary>
<p class="small">Best route for any ${st.colour}: <b>${pct(b.pX.mean)}</b> per attempt (95% interval ${pct(b.pX.lo)}–${pct(b.pX.hi)}), about ${isFinite(b.expectedAttempts.mean) ? Math.round(b.expectedAttempts.mean) : "–"} attempts. Riders who logged every run suggest ${pct(lb.pX.mean)}.</p>
<p class="small">Each roll's odds may depend on your earlier choices, as far as the data support it. Choices marked "no clear winner" in <a href="#deep">Deep Dive</a> are within the noise.${risks.length ? ` Risks on this route: ${risks.join(", ")}.` : ""}</p>
<p class="small">The bond chance at each encounter is the community average: the form does not record the answers riders gave there.</p>
<div class="seg" role="group" aria-label="Data"><button type="button" data-s="all" aria-pressed="${st.sample === "all"}">All runs</button><button type="button" data-s="lowBias" aria-pressed="${st.sample === "lowBias"}">Low-bias</button></div>
</details>
${trafficToggle()}`;
}
function bindPanel() {
const p = $("#ex-panel");
$$(".ex-dchip", p).forEach((b) => b.addEventListener("click", () => select(b.dataset.c === st.colour ? null : b.dataset.c)));
$$(".ex-route-card", p).forEach((b) => b.addEventListener("click", () => { st.focus = b.dataset.enc; st.expanded = null; render(); }));
$$(".ex-step", p).forEach((b) => b.addEventListener("click", () => { st.expanded = st.expanded === b.dataset.var ? null : b.dataset.var; render(); }));
$$(".ex-opt", p).forEach((b) => b.addEventListener("click", () => choose(b.dataset.var, b.dataset.v)));
$$("[data-o]", p).forEach((b) => b.addEventListener("click", () => { st.objective = b.dataset.o; render(); }));
$$("[data-s]", p).forEach((b) => b.addEventListener("click", () => { st.sample = b.dataset.s; render(); }));
const tr = $("#ex-traffic", p); if (tr) tr.addEventListener("change", () => { st.traffic = tr.checked; render(); });
const cl = $("#ex-clear", p); if (cl) cl.addEventListener("click", () => select(null));
$$("[data-pt]", p).forEach((b) => b.addEventListener("click", () => { st.point = b.dataset.pt; writeHash(); render(); }));
const cp = $("#ex-clear-point", p); if (cp) cp.addEventListener("click", () => { st.point = null; writeHash(); render(); });
$$(".ex-from-row[data-c]", p).forEach((b) => b.addEventListener("click", () => {
// follow that dragon's route, keeping this place on it
st.over[b.dataset.c] = { ...POINTS[st.point].force };
select(b.dataset.c, b.dataset.enc);
}));
const rr = $("#ex-reset-route", p); if (rr) rr.addEventListener("click", () => { delete st.over[st.colour]; st.expanded = null; render(); });
}
/* ---------- actions ---------- */
function select(colour, enc) {
st.colour = colour; st.info = null; st.expanded = null;
if (colour) st.point = null;
st.focus = colour ? enc || null : null;
writeHash();
render();
}
function choose(v, val) {
const route = walk(st.focus);
const order = route.steps.map((s) => s.var);
const over = { ...(st.over[st.colour] || {}) };
// keep choices before this one, drop the ones after it
const idx = order.indexOf(v);
order.slice(idx + 1).forEach((k) => delete over[k]);
// the path up to here is the one you are looking at: keep its earlier choices too, so switching to another
// route to this dragon (e.g. the tree instead of the valley) never changes where you have already been
route.steps.slice(0, Math.max(0, idx)).forEach((s) => { if (s.kind === "decision" && over[s.var] == null) over[s.var] = s.taken; });
over[v] = val;
// your choices hold for every route to this dragon: a later choice never sends the route back through another place
st.over[st.colour] = over;
st.expanded = null;
render();
}
function writeHash() {
if (!$("#panel-valley") || $("#panel-valley").hidden) return;
const h = "#valley" + (st.colour ? "/" + st.colour.toLowerCase() + (st.focus ? "/" + st.focus : "")
: st.point ? "/at/" + encodeURIComponent(st.point) : "");
try { history.replaceState(null, "", h); } catch (e) { /* ignore */ }
}
function fromHash() {
const parts = (location.hash || "").replace(/^#/, "").split("/");
if (parts[0] !== "valley") return;
if (parts[1] === "at") {
const id = decodeURIComponent(parts.slice(2).join("/"));
if (POINTS[id]) { st.colour = null; st.focus = null; st.point = id; if (st.policy) render(); }
return;
}
const c = parts[1] ? COLOURS.find((x) => x.toLowerCase() === parts[1].toLowerCase()) : null;
const enc = parts[2] && c && S.ENCOUNTERS[c].includes(parts[2]) ? parts[2] : null;
// plain "#valley" (e.g. the tab itself) keeps whatever the reader was looking at
if (!c) { writeHash(); return; }
if (!st.policy) { st.pendingHash = { c, enc }; return; }
// a link to a dragon opens its most probable route, fresh: no earlier detours, nothing expanded
st.colour = c; st.focus = enc; st.expanded = null; st.info = null;
delete st.over[c];
render();
}
/* ---------- render ---------- */
function render() {
const svg = $("#ex-map");
if (!svg) return;
paintBase(svg);
el("rect", { x: 0, y: 0, width: 1000, height: 790, fill: "#f6e6c4", "fill-opacity": st.colour ? 0.32 : 0.12 }, svg);
const gTraffic = el("g", { filter: "url(#ex-brush)" }, svg);
const gRoute = el("g", { filter: "url(#ex-brush)" }, svg);
const gLand = el("g", {}, svg), gScene = el("g", {}, svg), gDrag = el("g", {}, svg), gLab = el("g", {}, svg);
if (st.traffic) drawTraffic(gTraffic);
let routes = [], onRoute = new Set();
if (st.colour && st.policy) {
routes = S.ENCOUNTERS[st.colour].map((enc) => {
const r = walk(enc);
r.geo = routePoints(r);
return r;
}).sort((a, b) => b.value.x - a.value.x);
// drop the routes your choices rule out; if every one is ruled out, keep them so the panel can say so
const open = routes.filter((r) => r.reachable);
st.blocked = !open.length;
if (open.length) routes = open;
if (!st.focus || !routes.some((r) => r.enc === st.focus)) st.focus = routes[0].enc;
pills = [];
onRoute = drawRoutes(gRoute, gLab, routes);
spreadPills();
} else if (st.point && st.policy && POINTS[st.point]) {
pills = [];
st.fromList = routesFrom(st.point);
onRoute = drawFrom(gRoute, gLab, st.fromList);
spreadPills();
}
drawLandmarks(gLand, onRoute);
drawScenery(gScene, onRoute);
drawDragons(gDrag, !!st.colour);
// the paper texture and vignette go on top
const fin = document.createElementNS(NS, "svg");
V.finish(fin);
svg.insertAdjacentHTML("beforeend", fin.innerHTML.replace(/vm-/g, "ex-"));
$("#ex-hint").hidden = !!st.colour || !!st.point || !st.policy;
$("#ex-shell").style.setProperty("--vt", st.colour ? `var(${DV[st.colour]})` : "var(--accent)");
// the panel scrolls inside the map's height on wide screens (see .ex-scroll)
$("#ex-panel").innerHTML = `<div class="ex-scroll">${st.colour && st.policy ? panelRoutes(routes) : st.point && st.fromList ? panelFrom(st.fromList) : panelIdle()}</div>`;
bindPanel();
writeHash();
// on narrow screens the map scrolls sideways: start centred rather than at the far west
const wrap = $(".ex-map-wrap");
if (wrap && !wrap.dataset.centred && wrap.scrollWidth > wrap.clientWidth) { wrap.scrollLeft = (wrap.scrollWidth - wrap.clientWidth) / 2; wrap.dataset.centred = "1"; }
}
function setRuns(state) {
st.runs = state.runs;
st.counts = {};
state.runs.forEach((r) => V.path(r).forEach((id) => (st.counts[id] = (st.counts[id] || 0) + 1)));
render();
}
function init() {
render();
fetch("data/policy.json").then((r) => r.json()).then((p) => {
st.policy = p;
if (st.pendingHash) { st.colour = st.pendingHash.c; st.focus = st.pendingHash.enc; st.pendingHash = null; }
render();
}).catch(() => { $("#ex-panel").innerHTML = '<p class="small muted">The route model (data/policy.json) could not be loaded.</p>'; });
}
window.ValleyExplorer = { setRuns, fromHash, state: st, render };
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init();
})();
+704
View File
@@ -0,0 +1,704 @@
<title>Threshing Route Atlas</title>
<meta name="claude:viewport-fit-sides" content="cover">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Marcellus&family=Josefin+Sans:wght@400;600&family=Alegreya+Sans:ital,wght@0,400;0,500;0,700;1,400&family=IBM+Plex+Mono:wght@400;500&display=swap">
<style>
/* Layout: a field atlas — one wide route chart flanked by narrow reading columns; numbers set in mono, dragons carry their own colours. */
/* Layout: a dusk-lit field atlas — arched, deco-framed panels on deep plum; gold line work; each dragon tints its own frame; deaths turn steel and ember. Single dark world by design. */
:root {
color-scheme: dark;
--bg: #170911; --surface: #210f19; --raised: #2a1420; --ink: #f6e8d6; --muted: #cba890; --faint: #8e7069; --line: #4b2a36;
--accent: #e8b483; --accent-ink: #1d0a12; --good: #8fc98a; --warn: #f0a55a; --bad: #ef6b6b;
--dr-red: #e8435e; --dr-green: #3fc0a8; --dr-orange: #ff9533; --dr-brown: #d1a47a; --dr-blue: #7ea6ff; --dr-black: #e0d8ea; /* checked for colour-blind separation (see docs/COLOURS.md) */ --dr-any: #e0a9c6;
--link-low: #4f2f3c; --death: #9fb6c3; --ember: #e3692f; --death-bg: #1b0811; --frame: var(--accent);
--font-display: "Marcellus", "Iowan Old Style", Georgia, serif;
--font-crest: "Marcellus", "Iowan Old Style", Georgia, serif;
--font-label: "Josefin Sans", "Gill Sans", "Trebuchet MS", sans-serif;
--font-body: "Alegreya Sans", "Segoe UI", system-ui, sans-serif;
--font-data: "IBM Plex Mono", ui-monospace, "SFMono-Regular", Menlo, monospace;
--hero-bg: #1a0912; --hero-bg2: #3a1526; --hero-ink: #f6e8d6; --hero-muted: #d2b096; --hero-line: #6b4148;
--map-ground: #2a1420; --map-ground2: #34192a; --map-forest: #4b2b3b; --map-forest2: #3b2030; --map-rock: #5e3d4a; --map-water: #6f90a5; --map-path: #e8b483; --map-label: #f6e8d6; --map-halo: #1c0a13;
--step--1: 0.84rem; --step-0: 1rem; --step-1: 1.18rem; --step-2: 1.6rem; --step-3: 2.3rem; --radius: 10px;
}
* { box-sizing: border-box; }
body { background: var(--bg); color: var(--ink); font-family: var(--font-body); font-size: var(--step-0); line-height: 1.55; }
.wrap { max-width: 1260px; margin: 0 auto; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); padding-block: 0; }
h1, h2, h3 { font-family: var(--font-display); font-weight: 650; line-height: 1.15; text-wrap: balance; margin: 0; }
h1 { font-size: var(--step-3); letter-spacing: -0.01em; }
h2 { font-size: var(--step-2); }
h3 { font-size: var(--step-1); font-family: var(--font-body); font-weight: 600; }
p { margin: 0; max-width: 68ch; }
a { color: var(--accent); }
code, .num, .mono { font-family: var(--font-data); font-variant-numeric: tabular-nums; }
.eyebrow { font-family: var(--font-data); font-size: var(--step--1); letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); }
.muted { color: var(--muted); }
.small { font-size: var(--step--1); }
header.top { border-bottom: 1px solid var(--line); background: var(--surface); }
header.top .wrap { display: grid; gap: 14px; padding-block: 28px 22px; }
.title-row { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px; }
.lede { color: var(--muted); max-width: 72ch; }
.data-status { display: flex; flex-wrap: wrap; gap: 8px 18px; font-size: var(--step--1); color: var(--muted); align-items: center; }
.data-status b { color: var(--ink); font-weight: 600; }
.pill { display: inline-flex; align-items: center; gap: 6px; padding: 2px 9px; border-radius: 999px; border: 1px solid var(--line); background: var(--raised); font-size: var(--step--1); white-space: nowrap; }
.data-status .pill { white-space: normal; overflow-wrap: anywhere; max-width: 100%; }
.data-status > span { min-width: 0; overflow-wrap: anywhere; }
.pill.warn { border-color: color-mix(in srgb, var(--warn) 55%, var(--line)); color: var(--warn); }
nav.toc { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: var(--step--1); }
nav.toc a { color: var(--muted); text-decoration: none; border-bottom: 1px solid transparent; }
nav.toc a:hover, nav.toc a:focus-visible { color: var(--ink); border-bottom-color: var(--accent); }
main { display: grid; gap: 44px; padding-block: 30px 60px; }
section { display: grid; gap: 16px; scroll-margin-top: 16px; }
.section-head { display: grid; gap: 6px; }
/* controls */
.controls { display: flex; flex-wrap: wrap; gap: 12px 22px; align-items: end; padding: 14px 16px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); }
.ctl { display: grid; gap: 4px; min-width: 0; }
.ctl label, .ctl .lbl { font-size: var(--step--1); color: var(--muted); }
select, input[type="number"], button, .filebtn { font: inherit; font-size: var(--step--1); color: var(--ink); background: var(--raised); border: 1px solid var(--line); border-radius: 5px; padding: 6px 10px; }
input[type="number"] { width: 5.5em; }
button, .filebtn { cursor: pointer; }
button:hover, .filebtn:hover { border-color: var(--accent); }
button:focus-visible, select:focus-visible, input:focus-visible, .filebtn:focus-within, a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
button.primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); font-weight: 600; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 6px; overflow: hidden; }
.seg button { border: 0; border-radius: 0; border-right: 1px solid var(--line); }
.seg button:last-child { border-right: 0; }
.seg button[aria-pressed="true"] { background: var(--ink); color: var(--bg); }
.check { display: inline-flex; gap: 6px; align-items: center; font-size: var(--step--1); }
.targets { display: flex; flex-wrap: wrap; gap: 8px; }
.tchip { display: inline-flex; align-items: center; gap: 7px; padding: 6px 11px; border-radius: 999px; border: 1px solid var(--line); background: var(--raised); font-size: var(--step--1); cursor: pointer; }
.tchip .sw { width: 11px; height: 11px; border-radius: 50%; background: var(--c, var(--faint)); box-shadow: 0 0 0 1px color-mix(in srgb, var(--ink) 25%, transparent); }
.tchip[aria-pressed="true"] { border-color: var(--c, var(--ink)); box-shadow: inset 0 0 0 1px var(--c, var(--ink)); font-weight: 600; }
.tchip.featured { padding: 7px 14px; font-size: var(--step-0); }
.target-group { display: grid; gap: 6px; }
/* map */
.map-shell { border: 1px solid var(--line); border-radius: var(--radius); background: var(--raised); overflow: hidden; }
.map-top { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; justify-content: space-between; padding: 10px 14px; border-bottom: 1px solid var(--line); background: var(--surface); }
.cond-chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; min-width: 0; }
.cchip { display: inline-flex; gap: 6px; align-items: center; padding: 2px 4px 2px 9px; border: 1px solid var(--accent); color: var(--ink); border-radius: 999px; font-size: var(--step--1); background: color-mix(in srgb, var(--accent) 10%, var(--raised)); }
.cchip button { border: 0; background: transparent; padding: 0 6px; line-height: 1; font-size: 1rem; color: var(--muted); }
.map-scroll { overflow-x: auto; }
#map { display: block; }
#map text { font-family: var(--font-body); font-size: 11px; fill: var(--ink); }
#map .stage-label { font-family: var(--font-data); font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; fill: var(--muted); }
#map .stage-chance { fill: var(--accent); }
#map .node rect { stroke: color-mix(in srgb, var(--ink) 40%, transparent); stroke-width: 0.6; cursor: pointer; }
#map .node.sel rect { stroke: var(--accent); stroke-width: 2.4; }
#map .node.dim { opacity: 0.35; }
#map .link { mix-blend-mode: normal; }
#map .link:hover { opacity: 1 !important; }
#map .node:focus-visible rect { stroke: var(--accent); stroke-width: 3; }
.map-foot { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); gap: 18px; padding: 14px; border-top: 1px solid var(--line); background: var(--surface); }
@media (max-width: 820px) { .map-foot { grid-template-columns: minmax(0, 1fr); } }
.legend { display: flex; flex-wrap: wrap; gap: 10px 18px; align-items: center; font-size: var(--step--1); color: var(--muted); }
.ramp { width: 150px; height: 10px; border-radius: 3px; border: 1px solid var(--line); }
.sel-summary { display: grid; gap: 6px; font-size: var(--step--1); }
.sel-summary .big { font-family: var(--font-data); font-size: var(--step-2); color: var(--ink); }
#tip { position: fixed; z-index: 50; pointer-events: none; background: var(--raised); color: var(--ink); border: 1px solid var(--line); border-radius: 6px; padding: 8px 10px; font-size: var(--step--1); box-shadow: 0 6px 20px rgba(0,0,0,0.18); max-width: 300px; }
#tip .t { font-weight: 600; }
/* cards & grids */
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 420px), 1fr)); gap: 18px; }
.grid3 { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 18px; }
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 16px; display: grid; gap: 10px; min-width: 0; align-content: start; }
.panel h3 { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; }
.chart { width: 100%; overflow-x: auto; }
.chart svg { display: block; width: 100%; max-width: 760px; min-width: 540px; height: auto; }
.chart svg text { font-family: var(--font-body); font-size: 11px; fill: var(--ink); }
.chart svg .axis text { fill: var(--muted); font-family: var(--font-data); font-size: 10px; }
.chart svg .axis line, .chart svg .grid line { stroke: var(--line); }
.findings { display: grid; gap: 12px; counter-reset: f; }
.finding { display: grid; grid-template-columns: 26px minmax(0, 1fr); gap: 10px; padding: 12px 14px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); }
.finding .mark { width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-family: var(--font-data); font-size: 11px; color: var(--accent-ink); background: var(--muted); }
.finding.blue .mark { background: var(--dr-blue); color: #fff; }
.finding.black .mark { background: var(--dr-black); color: var(--bg); }
.finding.bias .mark { background: var(--warn); color: #fff; }
.finding.lead .mark { background: var(--accent); }
.finding p + p { margin-top: 4px; }
.finding .tag { font-family: var(--font-data); font-size: 10.5px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); }
/* tables */
.tbl-wrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); background: var(--raised); }
table { border-collapse: collapse; width: 100%; font-size: var(--step--1); }
th, td { padding: 6px 10px; text-align: left; border-bottom: 1px solid var(--line); vertical-align: top; }
th { font-weight: 600; color: var(--muted); background: var(--surface); position: sticky; top: 0; white-space: nowrap; }
th[data-sort] { cursor: pointer; }
th[data-sort]:hover { color: var(--ink); }
td.num, th.num { text-align: right; font-family: var(--font-data); font-variant-numeric: tabular-nums; white-space: nowrap; }
tr.sig td { background: color-mix(in srgb, var(--accent) 9%, transparent); }
tr.thin td { color: var(--faint); }
.route-cell { min-width: 280px; }
.cibar { display: inline-block; position: relative; width: 90px; height: 10px; vertical-align: middle; }
.cibar i { position: absolute; top: 4px; height: 2px; background: var(--muted); }
.cibar b { position: absolute; top: 1px; width: 2px; height: 8px; background: var(--ink); }
.qbadge { font-family: var(--font-data); font-size: 10.5px; padding: 1px 6px; border-radius: 4px; border: 1px solid var(--line); }
.qbadge.s { border-color: var(--accent); color: var(--accent); }
.method { display: grid; gap: 14px; }
.method p, .method li { max-width: 74ch; }
.method ul, .method ol { margin: 0; padding-left: 1.2em; display: grid; gap: 4px; }
.formula { font-family: var(--font-data); font-size: var(--step--1); background: var(--surface); border: 1px solid var(--line); border-left: 3px solid var(--accent); padding: 10px 12px; border-radius: 4px; overflow-x: auto; white-space: pre; }
details.fold { border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); }
details.fold > summary { cursor: pointer; padding: 10px 14px; font-weight: 600; }
details.fold > div { padding: 0 14px 14px; display: grid; gap: 10px; }
.btnrow { display: flex; flex-wrap: wrap; gap: 8px; }
#srcview { white-space: pre; overflow: auto; max-height: 420px; font-family: var(--font-data); font-size: 12px; background: var(--raised); border: 1px solid var(--line); border-radius: 4px; padding: 10px; }
.toast { position: fixed; bottom: calc(16px + env(safe-area-inset-bottom, 0px)); left: 50%; transform: translateX(-50%); background: var(--ink); color: var(--bg); padding: 8px 14px; border-radius: 6px; font-size: var(--step--1); z-index: 60; }
.loading { padding: 40px 0; color: var(--muted); }
footer { border-top: 1px solid var(--line); padding-block: 22px 40px; color: var(--muted); font-size: var(--step--1); }
@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
/* ---------- hero, tabs, overview, valley map, gallery ---------- */
body::before { content: ""; position: fixed; inset: 0 0 auto; height: env(safe-area-inset-top, 0px); z-index: 10; background: var(--hero-bg); }
.hero { background: radial-gradient(120% 140% at 70% 0%, var(--hero-bg2), var(--hero-bg) 60%); color: var(--hero-ink); position: relative; overflow: hidden; }
.hero .wrap { position: relative; z-index: 1; display: grid; gap: 14px; padding-block: 34px 0; }
.hero-art { position: absolute; inset: auto 0 0 0; height: 100%; width: 100%; z-index: 0; pointer-events: none; }
.hero h1 { font-family: var(--font-crest); font-weight: 700; font-size: clamp(1.9rem, 4.6vw, 3.1rem); letter-spacing: 0.04em; color: var(--hero-ink); }
.hero .kicker { font-family: var(--font-data); font-size: var(--step--1); letter-spacing: 0.14em; text-transform: uppercase; color: var(--hero-muted); }
.hero .tagline { color: var(--hero-muted); max-width: 60ch; font-size: var(--step-1); }
.hero .unofficial { display: inline-block; font-size: var(--step--1); color: var(--hero-muted); border: 1px solid var(--hero-line); border-radius: 999px; padding: 2px 10px; width: fit-content; }
.tabs { display: flex; gap: 2px; overflow-x: auto; margin-top: 18px; scrollbar-width: none; }
.tabs::-webkit-scrollbar { display: none; }
.tab { font-family: var(--font-crest); font-weight: 700; letter-spacing: 0.06em; font-size: 0.9rem; color: var(--hero-muted); background: transparent; border: 0; border-radius: 8px 8px 0 0; padding: 12px 16px 11px; white-space: nowrap; cursor: pointer; border-top: 2px solid transparent; }
.tab:hover { color: var(--hero-ink); }
.tab[aria-selected="true"] { background: var(--bg); color: var(--ink); border-top-color: var(--accent); }
.tab:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.tabpanel { display: grid; gap: 44px; }
.tabpanel > section, .tabpanel > section > * { min-width: 0; }
select { max-width: 100%; }
.tabpanel[hidden] { display: none !important; }
section h2 { font-family: var(--font-crest); letter-spacing: 0.03em; }
.odds { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 230px), 1fr)); gap: 16px; }
.odd { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 16px; display: grid; gap: 10px; align-content: start; position: relative; overflow: hidden; }
.odd .big { font-family: var(--font-crest); font-weight: 700; font-size: 2.1rem; line-height: 1; color: var(--c, var(--ink)); }
.odd .what { font-weight: 600; }
.odd .how { font-size: var(--step--1); color: var(--muted); }
.odd svg { display: block; width: 100%; max-width: 220px; height: auto; }
.odd::before { content: ""; position: absolute; inset: 0 auto 0 0; width: 4px; background: var(--c, var(--line)); }
.combo { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr)); gap: 16px; }
.combo .odd { grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 14px; }
.journey { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap: 0; counter-reset: st; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: var(--surface); }
.stop { padding: 14px; display: grid; gap: 6px; align-content: start; border-right: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.stop .n { font-family: var(--font-crest); font-weight: 700; color: var(--accent); font-size: 1.3rem; }
.stop .t { font-weight: 600; }
.stop .d { font-size: var(--step--1); color: var(--muted); }
.stop .verdict { font-size: var(--step--1); border-top: 1px dashed var(--line); padding-top: 6px; }
.stop.roll .n::after { content: " · roll"; font-family: var(--font-data); font-size: 10px; letter-spacing: 0.1em; color: var(--muted); }
.truths { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); gap: 16px; }
.truth { padding: 18px; border-radius: 10px; background: var(--surface); border: 1px solid var(--line); display: grid; gap: 8px; align-content: start; }
.truth h3 { font-family: var(--font-crest); font-size: 1.05rem; letter-spacing: 0.02em; }
.cta { display: flex; flex-wrap: wrap; gap: 10px; }
.cta button { font-size: var(--step-0); padding: 9px 16px; }
.lore { border-left: 3px solid var(--accent); padding: 4px 0 4px 14px; color: var(--muted); font-size: var(--step--1); max-width: 70ch; }
.valley-shell { border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: var(--map-ground); }
.valley-wrap { overflow-x: auto; }
#valley { display: block; width: 100%; min-width: 820px; height: auto; background: #d9b07a; }
#valley .loc { cursor: pointer; }
#valley .loc:focus-visible circle.ring { stroke: var(--accent); stroke-width: 4; }
#valley text { font-family: var(--font-body); }
#valley .place { font-family: var(--font-crest); font-weight: 700; font-size: 15px; letter-spacing: 0.04em; fill: var(--map-label); paint-order: stroke; stroke: var(--map-halo); stroke-width: 4px; stroke-linejoin: round; }
#valley .sub { font-size: 12px; fill: var(--map-label); opacity: 0.85; paint-order: stroke; stroke: var(--map-halo); stroke-width: 3px; }
#valley .trail { fill: none; stroke-linecap: round; }
#valley .flow { fill: none; stroke-linecap: round; stroke-dasharray: 2 14; animation: march 1.6s linear infinite; }
@keyframes march { to { stroke-dashoffset: -32; } }
@media (prefers-reduced-motion: reduce) { #valley .flow { animation: none; } }
.valley-foot { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); gap: 18px; padding: 14px; border-top: 1px solid var(--line); background: var(--surface); }
@media (max-width: 820px) { .valley-foot { grid-template-columns: minmax(0, 1fr); } }
.loc-card { display: grid; gap: 6px; font-size: var(--step--1); }
.loc-card h3 { font-family: var(--font-crest); font-size: 1.1rem; }
.bars { display: grid; gap: 4px; }
.bar { display: grid; grid-template-columns: 120px minmax(0, 1fr) 96px; gap: 8px; align-items: center; font-size: var(--step--1); }
.bar i { display: block; height: 10px; border-radius: 3px; background: var(--c, var(--muted)); min-width: 2px; }
.bar span:last-child { text-align: right; font-family: var(--font-data); white-space: nowrap; }
.gallery { display: grid; gap: 22px; }
.gal-group { display: grid; gap: 10px; }
.gal-group h3 { font-family: var(--font-crest); display: flex; gap: 10px; align-items: center; font-size: 1.15rem; }
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 168px), 1fr)); gap: 10px; }
.dcard { background: var(--surface); border: 1px solid var(--line); border-radius: 10px; padding: 12px; display: grid; gap: 6px; justify-items: center; text-align: center; position: relative; }
.dcard svg { width: 64px; height: 64px; }
.dcard .nm { font-family: var(--font-crest); font-weight: 700; font-size: 1rem; letter-spacing: 0.03em; overflow-wrap: anywhere; }
.dcard .meta { font-size: 12px; color: var(--muted); line-height: 1.35; }
.dcard .age { position: absolute; top: 34px; right: 16px; font-family: var(--font-data); font-size: 11px; color: var(--muted); }
.viewtoggle { display: inline-flex; }
/* ---------- dusk & gold theme layer ---------- */
body { background: radial-gradient(140% 90% at 50% -10%, #2b0f1f 0%, var(--bg) 55%) fixed, var(--bg); }
.eyebrow, .kicker, .lbl, .tab, .tchip, button, .filebtn, th, .stage-label { font-family: var(--font-label); letter-spacing: 0.12em; text-transform: uppercase; }
.eyebrow { font-size: 0.72rem; color: var(--accent); }
h1, h2, h3 { font-family: var(--font-display); font-weight: 400; }
h2 { font-size: var(--step-2); letter-spacing: 0.04em; }
.panel h3, .truth h3, .gal-group h3, .loc-card h3 { font-family: var(--font-display); font-weight: 400; letter-spacing: 0.03em; }
button, .filebtn { border-radius: 999px; border: 1px solid color-mix(in srgb, var(--accent) 70%, transparent); background: color-mix(in srgb, var(--raised) 80%, #000); color: var(--ink); font-size: 0.74rem; padding: 8px 16px; box-shadow: inset 0 0 0 1px rgba(0,0,0,0.35), 0 0 12px rgba(232,180,131,0.08); }
button:hover, .filebtn:hover { border-color: var(--accent); box-shadow: inset 0 0 0 1px rgba(0,0,0,0.35), 0 0 14px rgba(232,180,131,0.25); }
button.primary { background: var(--accent); color: var(--accent-ink); }
select, input[type="number"], input[type="search"] { background: var(--raised) !important; color: var(--ink) !important; border: 1px solid var(--line) !important; border-radius: 8px !important; }
.seg { border-radius: 999px; border-color: color-mix(in srgb, var(--accent) 60%, transparent); }
.seg button { border-radius: 0; box-shadow: none; }
.seg button[aria-pressed="true"] { background: var(--accent); color: var(--accent-ink); }
.tchip { border-radius: 999px; border: 1px solid color-mix(in srgb, var(--c, var(--accent)) 55%, var(--line)); background: color-mix(in srgb, var(--raised) 85%, #000); font-size: 0.72rem; padding: 7px 14px; }
.tchip[aria-pressed="true"] { background: color-mix(in srgb, var(--c, var(--accent)) 22%, var(--raised)); box-shadow: 0 0 14px color-mix(in srgb, var(--c, var(--accent)) 35%, transparent), inset 0 0 0 1px var(--c, var(--accent)); }
.tchip.featured { font-size: 0.8rem; }
/* deco frame: double line + sunburst corners, tinted by --frame */
.deco { position: relative; border: 1px solid color-mix(in srgb, var(--frame) 75%, transparent); box-shadow: inset 0 0 0 4px var(--surface), inset 0 0 0 5px color-mix(in srgb, var(--frame) 40%, transparent); }
.deco::before, .deco::after { content: ""; position: absolute; width: 46px; height: 46px; pointer-events: none; background: var(--frame); opacity: 0.55;
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 46 46'%3E%3Cg stroke='black' stroke-width='1' fill='none'%3E%3Cpath d='M2 2 L44 9 M2 2 L40 16 M2 2 L35 22 M2 2 L29 28 M2 2 L22 35 M2 2 L16 40 M2 2 L9 44'/%3E%3Cpath d='M2 14 A12 12 0 0 0 14 2' stroke-width='1.4'/%3E%3C/g%3E%3C/svg%3E") no-repeat;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 46 46'%3E%3Cg stroke='black' stroke-width='1' fill='none'%3E%3Cpath d='M2 2 L44 9 M2 2 L40 16 M2 2 L35 22 M2 2 L29 28 M2 2 L22 35 M2 2 L16 40 M2 2 L9 44'/%3E%3Cpath d='M2 14 A12 12 0 0 0 14 2' stroke-width='1.4'/%3E%3C/g%3E%3C/svg%3E") no-repeat; }
.deco::before { top: 6px; left: 6px; }
.deco::after { bottom: 6px; right: 6px; transform: rotate(180deg); }
.panel, .odd, .truth, .finding, .controls, .map-shell, .valley-shell, .journey, .dcard, .tbl-wrap { border-color: color-mix(in srgb, var(--frame) 30%, var(--line)); }
.panel, .odd, .truth { background: linear-gradient(180deg, color-mix(in srgb, var(--surface) 92%, var(--frame) 8%), var(--surface)); }
.controls { background: color-mix(in srgb, var(--surface) 80%, #000); }
.odd::before { display: none; }
.odd { border-radius: 120px 120px 14px 14px / 60px 60px 14px 14px; padding-top: 26px; text-align: center; justify-items: center; }
.odd .big { font-family: var(--font-display); font-weight: 400; text-shadow: 0 0 18px color-mix(in srgb, var(--c) 45%, transparent); }
.combo .odd { border-radius: 14px; text-align: left; justify-items: start; }
.truth { border-radius: 14px; }
table { background: transparent; }
th { background: color-mix(in srgb, var(--surface) 70%, #000); color: var(--accent); font-size: 0.7rem; }
td { border-bottom-color: color-mix(in srgb, var(--line) 70%, transparent); }
.tbl-wrap { background: color-mix(in srgb, var(--raised) 60%, var(--bg)); }
.formula { background: var(--death-bg); border-left-color: var(--accent); }
#tip { background: #2a1420; border-color: var(--accent); box-shadow: 0 6px 24px rgba(0,0,0,0.5), 0 0 12px rgba(232,180,131,0.15); }
.toast { background: var(--accent); color: var(--accent-ink); }
.pill { background: color-mix(in srgb, var(--raised) 70%, #000); }
.lore { border-left-color: var(--accent); font-style: italic; }
/* hero: arched title card over a dusk forest */
.hero { background: radial-gradient(90% 120% at 50% 0%, var(--hero-bg2), var(--hero-bg) 70%); }
.hero .wrap { justify-items: center; text-align: center; padding-block: 28px 0; }
.arch { --frame: var(--accent); position: relative; padding: 34px clamp(18px, 5vw, 64px) 26px; border-radius: 260px 260px 18px 18px / 150px 150px 18px 18px; border: 1px solid color-mix(in srgb, var(--accent) 80%, transparent);
box-shadow: inset 0 0 0 5px rgba(26,9,18,0.9), inset 0 0 0 6px color-mix(in srgb, var(--accent) 45%, transparent), 0 0 40px rgba(0,0,0,0.45);
background: radial-gradient(70% 80% at 50% 40%, rgba(40,10,26,0.92), rgba(22,7,15,0.95)); display: grid; gap: 10px; justify-items: center; max-width: 760px; width: 100%; }
.arch .crest { width: 120px; height: 34px; margin-top: -8px; }
.hero h1 { font-family: var(--font-display); font-weight: 400; letter-spacing: 0.08em; text-transform: uppercase; font-size: clamp(1.7rem, 5vw, 3rem); text-shadow: 0 0 22px rgba(232,180,131,0.25); }
.hero .kicker { font-family: var(--font-label); color: var(--accent); letter-spacing: 0.22em; font-size: 0.7rem; }
.hero .tagline { color: var(--hero-muted); font-size: var(--step-1); }
.hero .unofficial { border-color: var(--hero-line); color: var(--hero-muted); }
.tabs { justify-content: flex-start; gap: 6px; margin-top: 22px; padding-bottom: 14px; flex-wrap: nowrap; width: fit-content; max-width: 100%; }
.tab { border-radius: 999px; border: 1px solid color-mix(in srgb, var(--accent) 45%, transparent); padding: 9px 16px; font-size: 0.7rem; color: var(--hero-muted); background: rgba(20,6,13,0.6); border-top-width: 1px; }
.tab[aria-selected="true"] { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); box-shadow: 0 0 16px rgba(232,180,131,0.35); }
.embers { position: absolute; inset: 0; pointer-events: none; z-index: 0; overflow: hidden; }
.embers i { position: absolute; bottom: -10px; width: 4px; height: 4px; border-radius: 50%; background: var(--ember); box-shadow: 0 0 8px var(--ember); opacity: 0; animation: rise linear infinite; }
@keyframes rise { 0% { transform: translateY(0); opacity: 0; } 10% { opacity: 0.9; } 100% { transform: translateY(-340px) translateX(20px); opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .embers i { animation: none; opacity: 0.5; bottom: auto; } }
/* death palette: steel frame, ember glow */
.death { --frame: var(--death); background: radial-gradient(80% 90% at 50% 30%, #2a0b19, var(--death-bg)) !important; color: #efe6f2; }
.death .big { color: #efe6f2 !important; text-shadow: 0 0 22px rgba(227,105,47,0.45), 0 0 4px rgba(255,255,255,0.4) !important; font-family: var(--font-display); text-transform: uppercase; letter-spacing: 0.04em; }
.death .how, .death p { color: #c8bcc9; }
.arch::before { top: auto; bottom: 6px; left: 6px; transform: rotate(270deg); }
.odds { grid-template-columns: repeat(auto-fit, minmax(min(100%, 300px), 1fr)); }
@media (max-width: 600px) { .hero .tagline { font-size: var(--step-0); } }
/* dragon-tinted frames */
.dcard { --frame: var(--dc, var(--accent)); border-radius: 60px 60px 12px 12px / 34px 34px 12px 12px; border: 1px solid color-mix(in srgb, var(--frame) 60%, transparent); box-shadow: inset 0 0 0 3px var(--surface), inset 0 0 0 4px color-mix(in srgb, var(--frame) 30%, transparent); padding-top: 16px; }
.dcard .nm { font-family: var(--font-display); font-weight: 400; }
.gal-group h3 { color: var(--ink); }
.loc-card { --frame: var(--lc, var(--accent)); }
.valley-shell { --frame: var(--vt, var(--accent)); border-color: color-mix(in srgb, var(--frame) 60%, transparent); box-shadow: 0 0 0 4px var(--bg), 0 0 0 5px color-mix(in srgb, var(--frame) 40%, transparent), 0 0 30px color-mix(in srgb, var(--frame) 15%, transparent); }
#panel-rare .panel:nth-child(odd) { --frame: var(--dr-blue); }
#panel-rare .panel:nth-child(even) { --frame: var(--dr-black); }
.stop .n { font-family: var(--font-display); font-weight: 400; color: var(--accent); }
.journey { background: color-mix(in srgb, var(--surface) 85%, #000); }
footer { border-top-color: var(--line); }
/* the valley explorer (landing page) */
.explorer { gap: 0; }
.ex-shell { display: grid; grid-template-columns: minmax(0, 1fr) minmax(300px, 360px); border: 1px solid var(--line); border-radius: 12px; overflow: hidden; background: var(--surface);
--frame: var(--vt, var(--accent)); border-color: color-mix(in srgb, var(--frame) 55%, transparent); box-shadow: 0 0 0 4px var(--bg), 0 0 0 5px color-mix(in srgb, var(--frame) 35%, transparent), 0 0 36px color-mix(in srgb, var(--frame) 14%, transparent); transition: box-shadow .3s; }
@media (max-width: 980px) { .ex-shell { grid-template-columns: minmax(0, 1fr); } }
.ex-map-wrap { position: relative; overflow-x: auto; background: #d9b07a; }
#ex-map { display: block; width: 100%; min-width: 720px; height: auto; }
#ex-map text { font-family: var(--font-body); }
.ex-dragon { cursor: pointer; transition: opacity .25s; }
.ex-dragon:focus-visible, .ex-mark:focus-visible, .ex-alt:focus-visible { outline: none; filter: drop-shadow(0 0 4px #fff); }
.ex-mark, .ex-alt { cursor: pointer; }
.ex-hint { position: absolute; left: 50%; top: 10px; transform: translateX(-50%); padding: 8px 16px; border-radius: 999px; background: color-mix(in srgb, #1d0a12 78%, transparent); color: #f6e6c4; font-family: var(--font-label); letter-spacing: .14em; text-transform: uppercase; font-size: .72rem; pointer-events: none; white-space: nowrap; }
.ex-tip { position: absolute; z-index: 3; max-width: 260px; padding: 8px 10px; border-radius: 8px; background: #fbf0d6; color: #3b2416; font-size: 13px; line-height: 1.35; box-shadow: 0 4px 18px #0006; pointer-events: none; }
.ex-panel { position: relative; border-left: 1px solid var(--line); }
.ex-scroll { position: absolute; inset: 0; overflow: auto; display: grid; gap: 12px; align-content: start; padding: 18px; }
@media (max-width: 980px) { .ex-panel { border-left: 0; border-top: 1px solid var(--line); } .ex-scroll { position: static; } }
.ex-panel h2 { font-family: var(--font-display); font-weight: 400; font-size: 1.6rem; margin: 0; }
.ex-choose { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
.ex-dchip { display: grid; justify-items: center; gap: 2px; padding: 6px 4px 8px; border-radius: 10px; border: 1px solid color-mix(in srgb, var(--c) 45%, var(--line)); background: color-mix(in srgb, var(--raised) 85%, #000); color: var(--ink); font-size: .68rem; }
.ex-dchip svg { width: 58px; height: 46px; }
.ex-dchip[aria-pressed="true"] { background: color-mix(in srgb, var(--c) 22%, var(--raised)); box-shadow: 0 0 14px color-mix(in srgb, var(--c) 35%, transparent), inset 0 0 0 1px var(--c); }
.ex-card { padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--raised); }
.ex-toggle { display: flex; gap: 8px; align-items: center; font-size: var(--step--1); color: var(--muted); }
.ex-head { display: grid; grid-template-columns: 64px minmax(0, 1fr) auto; gap: 10px; align-items: center; }
.ex-head svg { width: 64px; height: 52px; }
.ex-head h2 { color: var(--c); }
.ex-place { cursor: pointer; }
.ex-place:hover text, .ex-place:focus-visible text { text-decoration: underline; fill-opacity: 1; }
.ex-place:focus { outline: none; }
.ex-here { display: grid; gap: 6px; margin: 10px 0 4px; justify-items: start; }
.ex-here-row { display: flex; flex-wrap: wrap; gap: 6px; }
.ex-chip { padding: 5px 12px; border-radius: 999px; border: 1px solid var(--accent); background: transparent; color: var(--ink); font-size: .85rem; }
.ex-chip:hover, .ex-chip:focus-visible { background: color-mix(in srgb, var(--accent) 22%, transparent); }
.ex-from { display: grid; gap: 6px; margin: 12px 0; }
.ex-from-row { position: relative; display: grid; grid-template-columns: 44px minmax(0, 1fr) auto; gap: 10px; align-items: center; padding: 6px 12px 10px 6px; border-radius: 10px; border: 1px solid color-mix(in srgb, var(--c) 45%, var(--line)); background: color-mix(in srgb, var(--raised) 85%, #000); color: var(--ink); text-align: left; overflow: hidden; }
.ex-from-row svg { width: 44px; height: 36px; }
.ex-from-row .nm { display: grid; font-weight: 700; color: var(--c); min-width: 0; }
.ex-from-row .nm small { font-weight: 400; color: var(--muted); }
.ex-from-row b { font-size: 1.1rem; }
.ex-from-row i { position: absolute; left: 0; bottom: 0; height: 4px; width: var(--w); background: var(--c); }
.ex-from-row.off { opacity: .55; }
.ex-from-row.off small { grid-column: 3; color: var(--muted); }
button.ex-from-row:hover { border-color: var(--c); }
.ex-close { width: 32px; height: 32px; border-radius: 50%; padding: 0; font-size: 1.1rem; line-height: 1; }
.ex-routes { display: grid; gap: 8px; }
.ex-route-card { display: grid; grid-template-columns: 34px minmax(0, 1fr) auto; gap: 2px 10px; align-items: center; text-align: left; padding: 10px 12px; border-radius: 10px; border: 1px solid var(--line); background: var(--raised); color: var(--ink); font-family: var(--font-body); text-transform: none; letter-spacing: normal; font-size: var(--step--1); }
.ex-route-card.on { border-color: color-mix(in srgb, var(--accent) 60%, var(--line)); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent); }
.ex-route-card .nm { font-family: var(--font-display); font-size: 1rem; }
.ex-route-card .nm em { font-style: normal; color: var(--muted); font-size: .8rem; }
.ex-route-card b { font-family: var(--font-display); font-weight: 400; font-size: 1.35rem; }
.ex-route-card small { grid-column: 2 / 4; color: var(--muted); }
.ex-swatch { grid-row: 1 / 3; width: 30px; height: 0; border-top: 6px solid var(--c); }
.ex-swatch.dashed { border-top-style: dashed; } .ex-swatch.dotted { border-top-style: dotted; }
.ex-key { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; }
.ex-key span { display: inline-block; width: 22px; border-top: 4px solid var(--muted); }
.ex-key .dashed { border-top-style: dashed; } .ex-key .dotted { border-top-style: dotted; }
.ex-steps { list-style: none; margin: 0; padding: 0; display: grid; gap: 4px; }
.ex-steps li { border-radius: 8px; }
.ex-steps li.chance { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0 8px; padding: 6px 10px; border: 1px dashed var(--line); font-size: var(--step--1); }
.ex-steps li.chance small { grid-column: 1 / 3; color: var(--muted); font-family: var(--font-data); }
.ex-step { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0 8px; width: 100%; text-align: left; padding: 6px 10px; border-radius: 8px; border: 1px solid var(--line); background: var(--raised); color: var(--ink); font-family: var(--font-body); text-transform: none; letter-spacing: normal; font-size: var(--step--1); }
.ex-step small { grid-column: 1 / 3; color: var(--muted); font-family: var(--font-data); }
.ex-steps li.open .ex-step { border-color: var(--accent); }
.ex-opts { display: grid; gap: 2px; padding: 6px 0 4px 10px; }
.ex-opt { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; text-align: left; padding: 4px 8px; border: 0; border-radius: 6px; background: transparent; color: var(--ink); font-family: var(--font-body); text-transform: none; letter-spacing: normal; font-size: var(--step--1); }
.ex-opt:hover { background: color-mix(in srgb, var(--ink) 7%, transparent); }
.ex-opt.on { background: color-mix(in srgb, var(--accent) 16%, transparent); }
.ex-opt b { font-family: var(--font-data); }
.ex-opt .rec { font-style: normal; font-size: 9.5px; font-family: var(--font-label); letter-spacing: .1em; text-transform: uppercase; color: var(--bg); background: var(--accent); border-radius: 999px; padding: 1px 6px; margin-left: 4px; }
.ex-why summary { cursor: pointer; font-family: var(--font-label); letter-spacing: .12em; text-transform: uppercase; font-size: .72rem; color: var(--accent); }
.ex-why { display: grid; gap: 6px; }
.linklike { background: none; border: 0; padding: 0; color: var(--accent); text-decoration: underline; font: inherit; text-transform: none; letter-spacing: normal; cursor: pointer; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 999px; overflow: hidden; width: fit-content; }
.seg button { border: 0; border-radius: 0; background: transparent; padding: 7px 13px; color: var(--muted); font-size: 0.7rem; }
.seg button[aria-pressed="true"] { background: color-mix(in srgb, var(--accent) 22%, var(--raised)); color: var(--ink); }
/* the odds, per dragon */
.odds-colours { grid-template-columns: repeat(3, minmax(0, 1fr)); }
@media (max-width: 900px) { .odds-colours { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 560px) { .odds-colours { grid-template-columns: minmax(0, 1fr); } }
.odd-colour { color: inherit; text-decoration: none; transition: transform .15s, box-shadow .15s; border-color: color-mix(in srgb, var(--c) 45%, var(--line)); }
.odd-colour:hover, .odd-colour:focus-visible { transform: translateY(-2px); box-shadow: 0 0 22px color-mix(in srgb, var(--c) 30%, transparent); }
.odd-art { width: 110px; height: 88px; max-width: none; }
.odd .go { font-family: var(--font-label); letter-spacing: .12em; text-transform: uppercase; font-size: .68rem; color: var(--c); }
.ladder { padding: 16px 18px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); display: grid; gap: 10px; }
.ladder ol { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
.ladder li { display: grid; grid-template-columns: 70px minmax(0, 1fr) 48px; gap: 10px; align-items: center; font-size: var(--step--1); }
.ladder li i { display: block; height: 10px; border-radius: 4px; width: var(--w); background: var(--c); }
.ladder li b { font-family: var(--font-data); text-align: right; }
.combo { grid-template-columns: minmax(0, 1fr); }
/* prose uses the full width of its column (it looked cramped on wide screens) */
p, .lede, .lore, .method p, .method li { max-width: none; }
footer p + p { margin-top: 8px; }
a { color: var(--accent); text-underline-offset: 2px; }
/* methods as tabs */
.mtabs { display: flex; flex-wrap: wrap; gap: 6px; border-bottom: 1px solid var(--line); padding-bottom: 10px; }
.mtab { border-radius: 999px; padding: 7px 14px; font-size: .7rem; background: transparent; }
.mtab[aria-selected="true"] { background: color-mix(in srgb, var(--accent) 22%, var(--raised)); border-color: var(--accent); color: var(--ink); }
.mpanel { padding: 18px 20px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); }
.mpanel[hidden] { display: none; }
.mpanel h3 { margin: 0; }
</style>
<header class="hero">
<svg class="hero-art" id="hero-art" viewBox="0 0 1200 420" preserveAspectRatio="xMidYMax slice" aria-hidden="true"></svg>
<div class="embers" id="embers" aria-hidden="true"></div>
<div class="wrap">
<div class="arch deco">
<svg class="crest" viewBox="0 0 120 34" aria-hidden="true"><g fill="none" stroke="#e8b483" stroke-width="1.1"><path d="M4 20 H44 M76 20 H116"/><path d="M60 4 L68 17 L60 30 L52 17 Z"/><path d="M60 10 L64 17 L60 24 L56 17 Z" fill="#e8b483"/><path d="M44 20 C50 12, 54 12, 52 17 M76 20 C70 12, 66 12, 68 17"/><circle cx="4" cy="20" r="2" fill="#e8b483"/><circle cx="116" cy="20" r="2" fill="#e8b483"/></g></svg>
<span class="kicker">Basgiath · Riders Quadrant · Threshing</span>
<h1>Threshing Route Atlas</h1>
<p class="tagline" id="hero-tagline">Every path through the valley, mapped from the runs riders logged.</p>
<span class="unofficial">Unofficial fan atlas for readers of Rebecca Yarros's <i>Fourth Wing</i> · not affiliated with Dragonkind</span>
</div>
<nav class="tabs" role="tablist" aria-label="Atlas pages">
<button class="tab" role="tab" id="tab-valley" aria-controls="panel-valley" aria-selected="true">The Valley</button>
<button class="tab" role="tab" id="tab-odds" aria-controls="panel-odds" aria-selected="false">The Odds</button>
<button class="tab" role="tab" id="tab-dragons" aria-controls="panel-dragons" aria-selected="false">The Dragons</button>
<button class="tab" role="tab" id="tab-deep" aria-controls="panel-deep" aria-selected="false">Deep Dive</button>
<button class="tab" role="tab" id="tab-data" aria-controls="panel-data" aria-selected="false">Data &amp; Methods</button>
</nav>
</div>
</header>
<div class="wrap">
<main>
<div class="tabpanel" id="panel-valley" role="tabpanel" aria-labelledby="tab-valley">
<section id="valley-sec" aria-labelledby="h-valley" class="explorer">
<div class="ex-shell deco" id="ex-shell">
<div class="ex-map-wrap"><svg id="ex-map" viewBox="0 0 1000 790" role="application" aria-label="Map of the threshing valley. Choose a dragon to see the routes to it."></svg>
<div class="ex-hint" id="ex-hint">Pick a dragon, or a key moment</div>
<div class="ex-tip" id="ex-tip" hidden></div>
</div>
<aside class="ex-panel" id="ex-panel" aria-live="polite"></aside>
</div>
</section>
</div>
<div class="tabpanel" id="panel-odds" role="tabpanel" aria-labelledby="tab-odds" hidden>
<section id="overview" aria-label="The odds">
<div class="odds" id="odds"></div>
<div class="odds odds-colours" id="odds-colours"></div>
</section>
<section aria-labelledby="h-journey">
<div class="section-head">
<span class="eyebrow">Seven steps, two of them pure luck</span>
<h2 id="h-journey">How a run unfolds</h2>
</div>
<div class="journey" id="journey"></div>
<p class="lore">In the books, first-years who survive to Threshing walk into a valley of unbonded dragons, and the dragons do the choosing. The <a href="https://dragonkind.com" target="_blank" rel="noopener">Dragonkind</a> site recreates that: every choice can end with you incinerated, and the author has said there is a 10% chance of that no matter what you pick.</p>
<div class="cta"><button type="button" class="primary" data-go="valley">Walk the valley map</button><button type="button" data-go="deep">Dig into the statistics</button><button type="button" data-go="dragons">Meet the bonded dragons</button></div>
</section>
</div>
<div class="tabpanel" id="panel-dragons" role="tabpanel" aria-labelledby="tab-dragons" hidden>
<section id="register" aria-labelledby="h-register">
<div class="section-head">
<span class="eyebrow">Bonded dragons, as riders registered them</span>
<h2 id="h-register">The bonded dragons</h2>
<p class="muted small">Every bonded dragon we could collect, sorted by colour, then tail, then lineage, then oldest first. Most come from ClumsyBadger's Unofficial Dragon Register form, and the rest from dragonkind.com result pages linked in the megathreads. Rider names and photos are left out. Misspelled lineages are corrected when they are within two letters of a lineage seen at least three times for the same colour. The original spelling is kept in the notes.</p>
</div>
<div class="data-status" id="reg-status"></div>
<div class="grid2">
<div class="panel"><h3>Colour × tail</h3><div class="tbl-wrap" id="reg-matrix"></div></div>
<div class="panel"><h3>Lineages</h3><div class="tbl-wrap" id="reg-lineages" style="max-height:340px"></div></div>
</div>
<div class="controls">
<div class="ctl"><label for="reg-colour">Colour</label><select id="reg-colour"></select></div>
<div class="ctl"><label for="reg-tail">Tail</label><select id="reg-tail"></select></div>
<div class="ctl"><label for="reg-lineage">Lineage</label><select id="reg-lineage"></select></div>
<div class="ctl"><label for="reg-sex">Sex</label><select id="reg-sex"></select></div>
<div class="ctl"><label for="reg-q">Search names</label><input id="reg-q" type="search" placeholder="Dragon or lineage" style="font:inherit;font-size:var(--step--1);padding:6px 10px;border:1px solid var(--line);border-radius:5px;background:var(--raised);color:var(--ink)"></div>
<div class="ctl"><span class="lbl">View</span><div class="seg" id="reg-view"><button type="button" data-v="cards" aria-pressed="true">Cards</button><button type="button" data-v="table" aria-pressed="false">Table</button></div></div>
<div class="btnrow" style="align-self:end"><button type="button" id="reg-copy">Copy as CSV</button><label class="filebtn" for="reg-upload">Load a newer register export…<input id="reg-upload" type="file" accept=".xlsx,.csv" hidden></label></div>
<span class="small muted" id="reg-count" style="align-self:center"></span>
</div>
<div class="gallery" id="reg-gallery"></div>
<div class="tbl-wrap" id="reg-table" style="max-height:640px" hidden></div>
</section>
</div>
<div class="tabpanel" id="panel-deep" role="tabpanel" aria-labelledby="tab-deep" hidden>
<section id="map-sec" aria-labelledby="h-map">
<div class="section-head">
<span class="eyebrow">Interactive</span>
<h2 id="h-map">Route map</h2>
<p class="muted small">Pick an outcome. Click any box to keep only the runs that passed through it, and click more boxes to narrow further. Hover or tap a box or band for its numbers.</p>
</div>
<div class="controls" id="map-controls">
<div class="target-group">
<span class="lbl small muted">Bond a dragon</span>
<div class="targets" id="targets-rare"></div>
</div>
<div class="target-group">
<span class="lbl small muted">Rare sightings</span>
<div class="targets" id="targets-other"></div>
</div>
</div>
<div class="controls">
<div class="ctl"><span class="lbl">Band width shows</span>
<div class="seg" id="width-mode"><button type="button" data-v="traffic" aria-pressed="true">How many runs</button><button type="button" data-v="prob" aria-pressed="false">Chance of outcome</button></div></div>
<div class="ctl"><label for="minn">Grey out steps with fewer runs than</label><input id="minn" type="number" min="1" max="200" value="10"></div>
<div class="ctl"><label for="f-source">Data source</label>
<select id="f-source"><option value="all">All rows</option><option value="form">Form submissions only</option><option value="bulk">Bulk logs only (imports)</option></select></div>
<div class="ctl"><label for="f-goal">Players chasing</label>
<select id="f-goal"><option value="all">Any goal</option><option value="exclude_rare">Not chasing Blue/Black</option><option value="only_rare">Chasing Blue/Black</option></select></div>
<label class="check" for="f-flag"><input id="f-flag" type="checkbox"> Drop rows with data-quality flags</label>
</div>
<div class="map-shell deco">
<div class="map-top">
<div class="cond-chips" id="cond-chips"><span class="small muted">Showing all runs. Click a box to follow only the runs through it.</span></div>
<div class="btnrow"><button type="button" id="btn-best">Show top routes for this outcome</button><button type="button" id="btn-clear">Clear selection</button></div>
</div>
<div class="map-scroll"><svg id="map" role="img" aria-label="Route map"></svg></div>
<div class="map-foot">
<div class="sel-summary" id="sel-summary"></div>
<div class="legend" id="legend"></div>
</div>
</div>
<div id="best-routes"></div>
</section>
<section id="bondrates" aria-labelledby="h-dragons">
<div class="section-head">
<span class="eyebrow">Statistics · all six colours</span>
<h2 id="h-dragons">Every dragon: how often the attempt ends in a bond</h2>
<p class="muted small">A run counts here when the player reached that dragon's bonding encounter and the form shows Bonded or Incinerated. Many players die on purpose to reroll, which drags the raw rate down. "Wanted it" keeps only runs where the player said they were after that colour, or any dragon.</p>
</div>
<div class="chart panel" id="ch-encounters"></div>
<div class="grid2">
<div class="panel"><h3>The two Greens</h3><div id="green-rescue"></div></div>
<div class="panel"><h3>First sighting: what the game rolls</h3><p class="small muted">Which dragon met the cadet first, by company and direction. Pools come from the community PDF, and cells outside them are counted as data-quality flags.</p><div class="tbl-wrap" id="tbl-first"></div></div>
</div>
</section>
<section id="rare" aria-labelledby="h-rare">
<div class="section-head">
<span class="eyebrow">Blue &amp; Black</span>
<h2 id="h-rare">The rare dragons</h2>
<p class="muted small">Two separate rolls. The meadow Blue can join the Orange and Brown after you turn down the valley Red. The tree's shadow option leads to a Blue and then a Black.</p>
</div>
<div class="grid2">
<div class="panel"><h3>Does the Blue show up in the meadow?</h3><p class="small muted">Share of meadow visits where a Blue was attempted, by who logged the run. The game cannot know which dragon a player is chasing, so gaps between these bars come from how people report, not from the game.</p><div class="chart" id="ch-blue-strata"></div></div>
<div class="panel"><h3>Does the shadow show up at the tree?</h3><p class="small muted">Share of tree climbs where the shadow option led to a Blue and/or Black.</p><div class="chart" id="ch-shadow-strata"></div></div>
</div>
<div class="grid2">
<div class="panel"><h3>What changes the Blue's appearance, once reporting bias is held fixed?</h3><p class="small muted">Adjusted odds ratios from one logistic model: route choices plus data source and chase goal. Bars that cross 1 mean no detectable effect.</p><div class="chart" id="ch-model-blue"></div><p class="small muted" id="model-blue-note"></p></div>
<div class="panel"><h3>What changes the shadow's appearance?</h3><p class="small muted">Same approach for the shadow. With so few shadows, intervals are wide.</p><div class="chart" id="ch-model-shadow"></div><p class="small muted" id="model-shadow-note"></p></div>
</div>
<div class="grid2">
<div class="panel"><h3>Day by day (form submissions)</h3><p class="small muted">Bulk imports carry no dates, so they are left out here. Dots are sized by the number of runs, and whiskers show 95% intervals.</p><div class="chart" id="ch-daily"></div></div>
<div class="panel"><h3>Bonding once you reach them</h3><div class="chart" id="ch-rare-bond"></div>
<details class="fold"><summary>Step-by-step survival inside the encounter (from the community PDF)</summary><div id="pdf-steps"></div></details>
</div>
</div>
</section>
<section id="findings" aria-labelledby="h-findings">
<div class="section-head">
<span class="eyebrow">What the data supports</span>
<h2 id="h-findings">Findings</h2>
<p class="muted small">These sentences are generated from the current data and filters, so they update when the data does. "Lead" means a pattern worth testing that is not yet established.</p>
</div>
<div class="findings" id="findings-list"></div>
</section>
<section id="routes" aria-labelledby="h-routes">
<div class="section-head">
<span class="eyebrow">Ranked</span>
<h2 id="h-routes">Route table</h2>
<p class="muted small">A route here means every choice up to the hour. Routes are ranked by the lower end of their 95% interval, so a route needs both a high rate and enough runs to rank high. Each route is compared with every other route that could reach the same outcome. "Adjusted" holds data source and chase goal fixed (Mantel–Haenszel). q-values correct for testing many routes at once.</p>
</div>
<div class="controls"><div class="ctl"><label for="rt-target">Outcome</label><select id="rt-target"></select></div><div class="ctl"><label for="rt-min">Minimum runs per route</label><input id="rt-min" type="number" min="1" max="200" value="10"></div><p class="small muted" id="rt-note" style="align-self:center"></p></div>
<div class="tbl-wrap" id="tbl-routes"></div>
</section>
<section id="factors" aria-labelledby="h-factors">
<div class="section-head">
<span class="eyebrow">One choice at a time</span>
<h2 id="h-factors">Factor explorer</h2>
<p class="muted small">Each row compares runs with that answer against runs with any other answer to the same question, using Fisher's exact test. These comparisons are unadjusted, so check the adjusted models above before trusting a difference. Shaded rows have q &lt; 0.05 after correcting for every comparison in this table.</p>
</div>
<div class="controls"><div class="ctl"><label for="fx-outcome">Outcome</label><select id="fx-outcome"></select></div><div class="ctl"><label for="fx-factor">Question</label><select id="fx-factor"></select></div></div>
<div class="grid2"><div class="tbl-wrap" id="tbl-factors"></div><div class="panel"><h3>Odds ratios</h3><div class="chart" id="ch-factor"></div></div></div>
</section>
<section id="quality" aria-labelledby="h-quality">
<div class="section-head">
<span class="eyebrow">Read this before quoting a number</span>
<h2 id="h-quality">Data quality and bias</h2>
</div>
<div class="grid3" id="quality-panels"></div>
</section>
</div>
<div class="tabpanel" id="panel-data" role="tabpanel" aria-labelledby="tab-data" hidden>
<section aria-labelledby="h-truths">
<div class="section-head"><span class="eyebrow" id="h-truths-kicker">What the runs say</span><h2 id="h-truths">Three things worth knowing</h2></div>
<div class="truths" id="truths"></div>
</section>
<section id="data-sec" aria-labelledby="h-data">
<div class="section-head"><span class="eyebrow">Where the numbers come from</span><h2 id="h-data">Data</h2></div>
<div class="data-status" id="data-status"><span class="loading">Loading data…</span></div>
<div class="btnrow"><label class="filebtn" for="upload">Load a newer route export…<input id="upload" type="file" accept=".xlsx,.csv" hidden></label><button id="btn-reset-data" type="button" hidden>Back to bundled data</button></div>
</section>
<section id="share" aria-labelledby="h-share">
<div class="section-head"><span class="eyebrow">Open by design</span><h2 id="h-share">Share &amp; reproduce</h2>
<p class="muted small">Everything on this page is recomputed in your browser from the raw form export. To update it, download the latest responses sheet (File → Download → Microsoft Excel) and load it with "Load a newer route export" above. Column order does not matter, because questions are matched by their wording.</p></div>
<div class="grid2">
<div class="panel"><h3>Copy the outputs</h3>
<div class="btnrow"><button type="button" id="cp-reddit" class="primary">Copy Reddit post (Markdown)</button><button type="button" id="cp-csv">Copy coded runs (CSV)</button><button type="button" id="cp-json">Copy all results (JSON)</button></div>
<p class="small muted">The Reddit post is written from the current numbers and filters.</p></div>
<div class="panel"><h3>Read the code</h3>
<div class="btnrow"><button type="button" data-src="engine.js">engine.js (all rules and statistics)</button><button type="button" data-src="app.js">app.js (this page)</button><button type="button" data-src="python/clean.py">clean.py</button><button type="button" data-src="python/analyze.py">analyze.py</button><button type="button" data-src="python/stats_core.py">stats_core.py</button><button type="button" data-src="solver.js">solver.js (best routes)</button><button type="button" data-src="explorer.js">explorer.js (the valley map)</button><button type="button" data-src="register.js">register.js</button><button type="button" data-src="README.md">README</button></div>
<p class="small muted">The Python files are an independent second implementation. The test scripts confirm that both produce identical coded runs and identical odds ratios, p-values and model estimates.</p>
<pre id="srcview" hidden></pre></div>
</div>
</section>
<section id="methods" aria-labelledby="h-methods" class="method">
<div class="section-head"><span class="eyebrow">How every number is made</span><h2 id="h-methods">Methods</h2></div>
<div class="mtabs" role="tablist" aria-label="Methods"><button type="button" role="tab" class="mtab" id="mt-0" aria-controls="mt-0-panel" aria-selected="true" tabindex="0">1. Runs</button><button type="button" role="tab" class="mtab" id="mt-1" aria-controls="mt-1-panel" aria-selected="false" tabindex="-1">2. Rates</button><button type="button" role="tab" class="mtab" id="mt-2" aria-controls="mt-2-panel" aria-selected="false" tabindex="-1">3. Comparisons</button><button type="button" role="tab" class="mtab" id="mt-3" aria-controls="mt-3-panel" aria-selected="false" tabindex="-1">4. Reporting bias</button><button type="button" role="tab" class="mtab" id="mt-4" aria-controls="mt-4-panel" aria-selected="false" tabindex="-1">5. Limits</button><button type="button" role="tab" class="mtab" id="mt-5" aria-controls="mt-5-panel" aria-selected="false" tabindex="-1">6. Best routes</button><button type="button" role="tab" class="mtab" id="mt-6" aria-controls="mt-6-panel" aria-selected="false" tabindex="-1">Missing answers</button></div>
<div class="mpanel method" role="tabpanel" id="mt-0-panel" aria-labelledby="mt-0">
<h3>1. From form answers to runs</h3>
<p>Each row of the <a href="https://docs.google.com/spreadsheets/d/1gnw1AdRg1XT4JsOfRM6QTA0jSaS3n9ZF-rPWnYewzv0" target="_blank" rel="noopener">"Threshing Routes" form</a> (and each row pasted in from players' own logs) is one threshing run. The page reads the raw export and codes every row with the same fixed rules, which are visible in <code>engine.js</code>:</p>
<ul>
<li><b>Source.</b> Rows with a real timestamp are form submissions. Rows labelled "Data Import", "Manual Upload" or "Historical import" were bulk-pasted from players' own run logs and are called <i>bulk logs</i> here.</li>
<li><b>Cadet encounter.</b> Split into the scream choice (help, investigate and leave, or ignore) and its resolution (killed the bullies, squadmate's revenge, left them to the dragons, tourniquet, left the cadet, took their weapons). The fork in the road only exists after helping, so other branches are coded "(no fork)".</li>
<li><b>Encounter branch.</b> A tree run with a Blue or Black recorded took the shadow. A tree run with Greens recorded descended slowly, and one with only a Red descended quickly. A valley run with an Orange, Brown or Blue recorded (or a Red marked "Changed my mind") passed the Red and reached the meadow.</li>
<li><b>Outcome.</b> Bonded to the one dragon marked "Bonded!". Otherwise incinerated by the last dragon marked "Incinerated" in encounter order, or died before the hour. "Saved by another" on the Greens plus a bonded Orange or Brown counts as a rescue bond.</li>
<li><b>Flags.</b> Rows are flagged, not deleted, when answers contradict each other: several directions or wings, Greens in the valley, two bonds, or a first sighting outside the documented pool. You can drop flagged rows with the checkbox on Deep Dive's route map.</li>
</ul>
</div>
<div class="mpanel method" role="tabpanel" id="mt-1-panel" aria-labelledby="mt-1" hidden>
<h3>2. Rates and their uncertainty</h3>
<p>A rate is k events out of n runs that could have had that event. The denominator matters. The meadow Blue rate divides by runs that reached the meadow, not by all runs. Intervals are <b>95% <a href="https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval" target="_blank" rel="noopener">Wilson score intervals</a></b>, which behave well for small n and for rates near 0%:</p>
<div class="formula">p̂ = k / n, z = 1.96
centre = (p̂ + z²/2n) / (1 + z²/n)
half = z·√(p̂(1−p̂)/n + z²/4n²) / (1 + z²/n)
CI = centre ± half</div>
<p>With 0 events in n runs, the upper end is still informative. For example, 0 shadows in a few hundred bulk-log tree climbs still gives an upper bound near 1%.</p>
</div>
<div class="mpanel method" role="tabpanel" id="mt-2-panel" aria-labelledby="mt-2" hidden>
<h3>3. Comparing choices</h3>
<p>For one answer against the rest, the 2×2 table is [a b; c d] = [event, no event] × [this answer, other answers].</p>
<div class="formula">OR = (a·d) / (b·c)
95% CI = exp( ln OR ± 1.96·√(1/a + 1/b + 1/c + 1/d) )
(0.5 is added to every cell when any cell is 0)
p = Fisher's exact test, two-sided
q = Benjamini–Hochberg: sort p, q(i) = min over j≥i of p(j)·m/j</div>
<p>Comparisons use the <b><a href="https://en.wikipedia.org/wiki/Odds_ratio" target="_blank" rel="noopener">odds ratio</a></b>, <b><a href="https://en.wikipedia.org/wiki/Fisher%27s_exact_test" target="_blank" rel="noopener">Fisher's exact test</a></b> and <b><a href="https://en.wikipedia.org/wiki/False_discovery_rate#Benjamini%E2%80%93Hochberg_procedure" target="_blank" rel="noopener">Benjamini–Hochberg q-values</a></b>. An odds ratio of 2 means the odds of the outcome are twice as high with that answer. q-values control the false-discovery rate. With dozens of comparisons, some p &lt; 0.05 results are expected by chance, so a "real" difference needs q &lt; 0.05.</p>
</div>
<div class="mpanel method" role="tabpanel" id="mt-3-panel" aria-labelledby="mt-3" hidden>
<h3>4. Adjusting for who reports what</h3>
<p>Players chasing a rare dragon log runs where they saw a Blue far more often than other players do. Bulk loggers record every run, including dull ones. To separate route effects from reporting effects, the page fits a <b><a href="https://en.wikipedia.org/wiki/Logistic_regression" target="_blank" rel="noopener">logistic regression</a></b> with every route choice plus data source and chase goal:</p>
<div class="formula">logit P(event) = β₀ + Σ βⱼ·xⱼ (x = 0/1 indicators; reference = most common answer)
fitted by Newton–Raphson with a small ridge penalty λ = 1 on the slopes
adjusted OR = exp(βⱼ), 95% CI = exp(βⱼ ± 1.96·SEⱼ)</div>
<p>The <a href="https://en.wikipedia.org/wiki/Ridge_regression" target="_blank" rel="noopener">ridge penalty</a> keeps estimates finite when an answer has 0 events. It shrinks extreme odds ratios slightly toward 1, which makes the model more cautious. Route rankings use the <b><a href="https://en.wikipedia.org/wiki/Cochran%E2%80%93Mantel%E2%80%93Haenszel_statistics" target="_blank" rel="noopener">Mantel–Haenszel odds ratio</a></b> across strata of data source and chase goal (bulk logs; form runs chasing Blue, Black, or "Blue or Black" on the newer form; everything else) for the same reason.</p>
</div>
<div class="mpanel method" role="tabpanel" id="mt-4-panel" aria-labelledby="mt-4" hidden>
<h3>5. What this data cannot tell you</h3>
<ul>
<li>It is self-reported and self-selected. Runs worth bragging about are over-represented, and that inflates every rare-dragon rate. Bulk logs are the least selected rows.</li>
<li>Runs are not independent. One player may log dozens of runs, and the form has no player ID, so intervals are somewhat too narrow.</li>
<li>The form records mostly stage-level choices. The newer form asks how you reacted to the first dragon, but most riders answer "unsure", and it does not record the answers given inside a bonding encounter, so route claims that depend on those cannot be tested here.</li>
<li>The form records dragons you <i>attempted</i>. A player who saw the Blue but chose the Orange would not record the Blue, so Blue sightings are slightly undercounted.</li>
<li>Step-by-step survival inside an encounter comes from the <a href="https://drive.google.com/file/d/17o72ehHsSPW4UdsKF-sXTxMLEuinWeEg/view" target="_blank" rel="noopener">community PDF</a>, which coded the free-text answers by hand. It is shown as published and cannot be recomputed here.</li>
</ul>
</div>
<div class="mpanel method" role="tabpanel" id="mt-5-panel" aria-labelledby="mt-5" hidden>
<h3>6. Best routes, the valley map and The Odds</h3>
<p>The valley map and The Odds come from a solver (<code>solver.js</code>) that treats a run as a decision tree. Your choices are decisions (company and, with squadmates, whether you later leave them; direction; how you react when the first dragon appears; the cadet encounter in the game's order — investigate the scream or keep walking, help your squadmate or walk away, your first move in the fight (pause to assess, charge the smaller cadet, or get between your squadmate and the bigger one) and, after pausing, what to do about the smaller cadet's dagger, then the bullies' fate or what to do for the wounded cadet — the fork, tree or valley, how to climb down, whether to jump onto the Red below the tree or let it pass and go on to the two Greens, whether to face the valley Red, and at every bonding encounter whether to attempt the bond or die on purpose). The game's rolls are chance events: which dragon appears first, whether you die at the sighting, in the fight or before the hour, whether the shadow appears and which dragon it is, which dragon waits in the meadow, and how the bonding encounter ends.</p>
<p>Each roll's probability may depend on the choices before it. It is estimated with <b>hierarchical <a href="https://en.wikipedia.org/wiki/Dirichlet-multinomial_distribution" target="_blank" rel="noopener">Dirichlet</a> back-off</b>: the estimate for a full history is pulled toward the estimate for a shorter history, which is pulled toward the overall rate. How strongly is chosen from the data for each roll (<a href="https://en.wikipedia.org/wiki/Empirical_Bayes_method" target="_blank" rel="noopener">empirical Bayes</a>), so the solver does not chase noise in small groups. The best route is then found by <b><a href="https://en.wikipedia.org/wiki/Backward_induction" target="_blank" rel="noopener">backward induction</a></b>, for two goals: the chance of bonding the dragon on this attempt, and, for riders who die on purpose whenever a run goes wrong, the chance that the account eventually ends on that dragon rather than another (maximised by <a href="https://en.wikipedia.org/wiki/Fractional_programming" target="_blank" rel="noopener">Dinkelbach iteration</a>). Ranges come from 200 posterior draws; "stays best in N%" is how often the recommended choice is still best across those draws.</p>
<p>Encounter outcomes use only <b>genuine attempts</b>: runs where the rider wanted that colour, any dragon, or said they would not seek Malek. The two summary cards on The Odds use the same rule in reverse: runs where the rider died on purpose at an encounter they did not want are left out, so they describe cadets who went into the valley and either bonded or died. The "low-bias" numbers use only bulk logs and form runs from riders who were not chasing a rare dragon.</p>
<p><b>Starting from a place.</b> Clicking a place on the map before choosing a dragon shows your chance of each dragon <i>from there on</i>. Choices before that place are the ones that lead to it (or the solver's best, where several do); rolls before it are averaged over the outcomes that can still reach it, weighted by how often they happen and by survival. From the place onward the solver plays the best route for each dragon. A dragon is "not reachable from here" when no logged run went from that place to it. Clicking the bully fight means you stepped in to help: the chances assume your best first move and include the risk of dying in the fight. The move matters: about 3 in 10 riders who charged straight in were killed, against almost none who paused to assess. Several choices made at one place (as at the bully fight) share one diamond on the map, which opens a small card with each choice in order. For Orange and Brown, the Greens rescue is used only when their own meadow is out of reach.</p>
<p><b>Choices that are not modelled yet.</b> The answers you give at the bonding encounters themselves (for example which way to turn for the two Greens, or when to jump onto the Red) are not recorded by the community form, so every encounter uses its average bond chance. Ken's bot records every option it picks, so these can be added once enough bot runs come in. Letting the Red pass is rarely logged on its own; its chance is taken from the two Greens' encounter, which has plenty of data. Reactions to the first dragon use the form's categories, and only those logged at least 20 times for that dragon are offered. On the map, a choice you make holds for every route to that dragon, and routes it rules out are hidden.</p>
</div>
<div class="mpanel method" role="tabpanel" id="mt-6-panel" aria-labelledby="mt-6" hidden>
<h3>Missing answers</h3>
<p>"Unsure", blank answers, conflicting answers and questions an older version of the form did not ask are treated as <b>missing information, never as a choice</b>. Each comparison uses the runs that answered that question; models use runs that answered every question in them (<a href="https://en.wikipedia.org/wiki/Listwise_deletion" target="_blank" rel="noopener">complete cases</a>). "I've lost count" counts as a later attempt. The only exception is the chase goal used to adjust for reporting bias: runs from before that question existed stay in the models as their own adjustment group, but that group is not shown as a finding. The solver and the valley map ignore missing steps in the same way.</p>
</div>
</section>
</div>
</main>
</div>
<footer><div class="wrap"><p><b>Data:</b> the community <a href="https://docs.google.com/spreadsheets/d/1gnw1AdRg1XT4JsOfRM6QTA0jSaS3n9ZF-rPWnYewzv0" target="_blank" rel="noopener">"Threshing Routes" responses</a> compiled by <a href="https://www.reddit.com/user/ClumsyBadger/" target="_blank" rel="noopener">u/ClumsyBadger</a>, with percentages in the <a href="https://drive.google.com/file/d/17o72ehHsSPW4UdsKF-sXTxMLEuinWeEg/view" target="_blank" rel="noopener">route PDF</a> by <a href="https://www.reddit.com/user/ClumsyBadger/" target="_blank" rel="noopener">u/ClumsyBadger</a>, <a href="https://www.reddit.com/user/Old_Regular3018/" target="_blank" rel="noopener">u/Old_Regular3018</a> and <a href="https://www.reddit.com/user/Smart_Trifle_2099/" target="_blank" rel="noopener">u/Smart_Trifle_2099</a>; the <a href="https://docs.google.com/spreadsheets/d/1KMiE9sec0l597Pzue1OhGYf07NF4howtQ_lPeqx7jXQ" target="_blank" rel="noopener">Unofficial Dragon Register</a>; and the r/fourthwing bonding megathreads (<a href="https://www.reddit.com/r/fourthwing/comments/1wvwfp9/" target="_blank" rel="noopener">Part 3</a>, <a href="https://www.reddit.com/r/fourthwing/comments/1wz5cnj/" target="_blank" rel="noopener">Part 4</a>). Code and data: <a href="https://github.com/ekcSchiano/threshing-atlas" target="_blank" rel="noopener">github.com/ekcSchiano/threshing-atlas</a> (MIT, data CC BY 4.0).</p>
<p><b>Unofficial fan analysis,</b> not affiliated with <a href="https://dragonkind.com" target="_blank" rel="noopener">Dragonkind</a> or its authors. A 10% "chaos" chance of incineration on any choice has been described by the author, so <b>no route guarantees a bond</b>.</p></div></footer>
<div id="tip" hidden></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="engine.js"></script>
<script src="solver.js"></script>
<script src="register.js"></script>
<script src="app.js"></script>
<script src="valley.js"></script>
<script src="dragons.js"></script>
<script src="explorer.js"></script>
<script src="ui.js"></script>
+205
View File
@@ -0,0 +1,205 @@
/* register.js — the Dragon Register section: clean, merge, sort and display bonded dragons.
* Works in the browser (window.DragonRegister) and in Node (module.exports) for testing. */
(function (root, factory) {
if (typeof module === "object" && module.exports) module.exports = factory();
else root.DragonRegister = factory();
})(typeof self !== "undefined" ? self : this, function () {
"use strict";
const COLOUR_ORDER = ["Red", "Orange", "Brown", "Green", "Blue", "Black"];
const TAILS = ["Clubtail", "Daggertail", "Morningstartail", "Scorpiontail", "Swordtail"];
const KEYS = {
timestamp: ["timestamp"], cadet: ["cadet name"], wing: ["assignment - wing"], section: ["assignment - section"],
squad: ["assignment - squad"], name: ["dragon", "name"], lineage: ["lineage"], colour: ["colour"], tail: ["tail"],
sex: ["sex"], age: [/\bage\b/],
};
const str = (v) => (v === null || v === undefined ? null : String(v).trim() || null);
const title = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1).toLowerCase() : s);
function findCols(headers) {
const C = {};
for (const [k, words] of Object.entries(KEYS)) {
const h = headers.find((x) => words.every((w) => (w instanceof RegExp ? w.test(String(x).toLowerCase()) : String(x).toLowerCase().includes(w))) && !(k === "name" && /cadet/i.test(x)));
if (h) C[k] = h;
}
return C;
}
function tailOf(v) {
const t = (str(v) || "").toLowerCase().replace(/[^a-z]/g, "");
return TAILS.find((x) => x.toLowerCase() === t || x.toLowerCase().replace("tail", "") === t) || (t ? title(t) : "Unknown");
}
function lev(a, b) {
const m = a.length, n = b.length, d = Array.from({ length: m + 1 }, (_, i) => [i, ...new Array(n).fill(0)]);
for (let j = 1; j <= n; j++) d[0][j] = j;
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++)
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
return d[m][n];
}
const lkey = (s) => (str(s) || "").toLowerCase().replace(/[^a-z]/g, "");
// rows: raw register form rows; extra: dragons from other sources (already structured)
function build(raw) {
const C = findCols(raw.headers || Object.keys(raw.rows[0] || {}));
const items = raw.rows.map((r, i) => ({
source: "Register form", source_url: null, submitted: str(r[C.timestamp]),
cadet: str(r[C.cadet]), wing: str(r[C.wing]), section: str(r[C.section]), squad: str(r[C.squad]),
// names typed in capitals ("RAERNUAL") are shown as names ("Raernual")
name: ((n) => (n && n.length > 1 && n === n.toUpperCase() ? n[0] + n.slice(1).toLowerCase() : n))(str(r[C.name])), lineage_raw: str(r[C.lineage]), colour: title(str(r[C.colour])), tail: tailOf(r[C.tail]),
sex: title(str(r[C.sex])), age: parseInt(r[C.age], 10), flags: [],
}));
(raw.extra || []).forEach((e) => items.push({
source: "Reddit (dragonkind.com result page)", source_url: e.url, submitted: null, cadet: null, wing: null, section: null, squad: null,
name: str(e.name), lineage_raw: str(e.lineage), colour: title(e.colour), tail: tailOf(e.tail), sex: title(e.sex), age: parseInt(e.age, 10), flags: [],
}));
// lineage spelling: spellings used 3+ times are canonical; others snap to a canonical of the same colour within 2 edits
const counts = {};
items.forEach((it) => { const k = lkey(it.lineage_raw); if (k) counts[k] = (counts[k] || 0) + 1; });
// spellings confirmed by an official dragonkind.com result page also count as canonical
const official = new Set(items.filter((it) => it.source_url).map((it) => lkey(it.lineage_raw)));
const canon = Object.keys(counts).filter((k) => counts[k] >= 3 || official.has(k));
const colourOfKey = {};
items.forEach((it) => { const k = lkey(it.lineage_raw); if (canon.includes(k)) (colourOfKey[k] = colourOfKey[k] || new Set()).add(it.colour); });
items.forEach((it) => {
let k = lkey(it.lineage_raw);
if (k && !canon.includes(k)) {
const best = canon.filter((c) => colourOfKey[c] && colourOfKey[c].has(it.colour)).map((c) => [c, lev(k, c)]).sort((a, b) => a[1] - b[1])[0];
if (best && best[1] <= 2) { it.flags.push(`lineage spelled "${it.lineage_raw}"`); k = best[0]; }
else it.flags.push("lineage seen fewer than 3 times");
}
it.lineage = k ? title(k) : "Unknown";
if (!Number.isFinite(it.age)) { it.age = null; it.flags.push("age missing"); }
if (!COLOUR_ORDER.includes(it.colour)) it.flags.push("unrecognised colour");
});
// a lineage should belong to one colour
const lc = {};
items.forEach((it) => (lc[it.lineage] = lc[it.lineage] || new Set()).add(it.colour));
items.forEach((it) => { if (lc[it.lineage].size > 1) it.flags.push(`lineage also recorded under ${[...lc[it.lineage]].filter((c) => c !== it.colour).join("/")}`); });
// duplicates: same dragon name + colour + tail + sex + age + lineage
const seen = new Map(), out = [];
items.forEach((it) => {
const key = [it.name && it.name.toLowerCase(), it.colour, it.tail, it.sex, it.age, it.lineage].join("|");
if (seen.has(key)) {
const first = seen.get(key);
first.duplicates = (first.duplicates || 0) + 1;
if (!first.also.includes(it.source) && it.source !== first.source) first.also.push(it.source);
if (it.source_url && !first.source_url) first.source_url = it.source_url;
return;
}
it.also = []; seen.set(key, it); out.push(it);
});
out.sort(compare);
return out;
}
function compare(a, b) {
const ci = (c) => (COLOUR_ORDER.indexOf(c) + 1 || 99);
return ci(a.colour) - ci(b.colour) || a.tail.localeCompare(b.tail) || a.lineage.localeCompare(b.lineage) ||
(b.age ?? -1) - (a.age ?? -1) || (a.name || "").localeCompare(b.name || "");
}
// ---------------------------------------------------------------- browser UI
function mount(opts) {
const $ = (q) => document.querySelector(q);
const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const cssVar = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const st = { all: [], label: "", f: { colour: "", tail: "", lineage: "", sex: "", q: "" }, bundled: null };
function load(raw, label) { st.all = build(raw); st.label = label; st.f = { colour: "", tail: "", lineage: "", sex: "", q: "" }; ["reg-colour", "reg-tail", "reg-lineage", "reg-sex", "reg-q"].forEach((id) => ($("#" + id).value = "")); render(); }
const filtered = () => st.all.filter((d) => (!st.f.colour || d.colour === st.f.colour) && (!st.f.tail || d.tail === st.f.tail) &&
(!st.f.lineage || d.lineage === st.f.lineage) && (!st.f.sex || d.sex === st.f.sex) &&
(!st.f.q || [d.name, d.lineage].join(" ").toLowerCase().includes(st.f.q.toLowerCase())));
const sw = (c) => `<span style="display:inline-block;width:10px;height:10px;border-radius:50%;background:var(${DV[c] || "--faint"});margin-right:6px;vertical-align:-1px;box-shadow:0 0 0 1px color-mix(in srgb, var(--ink) 25%, transparent)"></span>`;
const median = (a) => { const s = a.slice().sort((x, y) => x - y); const m = s.length >> 1; return s.length ? (s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2) : null; };
function fillSelect(id, values, label) {
const el = $("#" + id), cur = el.value;
el.innerHTML = `<option value="">${label}</option>` + values.map((v) => `<option>${esc(v)}</option>`).join("");
el.value = values.includes(cur) ? cur : "";
}
function render() {
const all = st.all, rows = filtered();
const colours = COLOUR_ORDER.filter((c) => all.some((d) => d.colour === c));
fillSelect("reg-colour", colours, "All colours");
fillSelect("reg-tail", TAILS.filter((t) => all.some((d) => d.tail === t)), "All tails");
fillSelect("reg-lineage", [...new Set(all.filter((d) => !st.f.colour || d.colour === st.f.colour).map((d) => d.lineage))].sort(), "All lineages");
fillSelect("reg-sex", [...new Set(all.map((d) => d.sex).filter(Boolean))].sort(), "Any sex");
const src = {}; all.forEach((d) => (src[d.source] = (src[d.source] || 0) + 1));
$("#reg-status").innerHTML = `<b>${all.length}</b> bonded dragons · ${Object.entries(src).map(([k, v]) => `${esc(k)} ${v}`).join(" · ")} · <span class="pill">${esc(st.label)}</span>`;
// colour x tail matrix
$("#reg-matrix").innerHTML = `<table><thead><tr><th>Colour</th>${TAILS.map((t) => `<th class="num">${t.replace("tail", "")}</th>`).join("")}<th class="num">Total</th></tr></thead><tbody>${colours.map((c) => {
const cs = rows.filter((d) => d.colour === c);
return `<tr><td>${sw(c)}${c}</td>${TAILS.map((t) => { const n = cs.filter((d) => d.tail === t).length; return `<td class="num"${n ? "" : ' style="color:var(--faint)"'}>${n || "·"}</td>`; }).join("")}<td class="num"><b>${cs.length}</b></td></tr>`;
}).join("")}</tbody></table>`;
// lineages
const lin = {};
rows.forEach((d) => { const k = d.colour + "|" + d.lineage; (lin[k] = lin[k] || []).push(d); });
$("#reg-lineages").innerHTML = `<table><thead><tr><th>Colour</th><th>Lineage</th><th class="num">Dragons</th><th class="num">Ages</th><th class="num">Median</th><th class="num">F / M</th></tr></thead><tbody>${Object.keys(lin).sort((a, b) => COLOUR_ORDER.indexOf(a.split("|")[0]) - COLOUR_ORDER.indexOf(b.split("|")[0]) || a.localeCompare(b)).map((k) => {
const g = lin[k], ages = g.map((d) => d.age).filter(Number.isFinite), [c, l] = k.split("|");
return `<tr><td>${sw(c)}${c}</td><td>${esc(l)}</td><td class="num">${g.length}</td><td class="num">${ages.length ? Math.min(...ages) + "–" + Math.max(...ages) : "–"}</td><td class="num">${ages.length ? median(ages) : "–"}</td><td class="num">${g.filter((d) => d.sex === "Female").length} / ${g.filter((d) => d.sex === "Male").length}</td></tr>`;
}).join("")}</tbody></table>`;
// main table, grouped by colour then tail
let lastGroup = "";
$("#reg-table").innerHTML = rows.length ? `<table><thead><tr><th>Colour</th><th>Tail</th><th>Lineage</th><th class="num">Age</th><th>Sex</th><th>Dragon</th><th>Rider's assignment</th><th>Source</th><th>Notes</th></tr></thead><tbody>${rows.map((d) => {
const g = d.colour + "|" + d.tail, head = g !== lastGroup; lastGroup = g;
return `<tr${head ? ' style="border-top:2px solid var(--line)"' : ""}><td>${sw(d.colour)}${esc(d.colour)}</td><td>${esc(d.tail)}</td><td>${esc(d.lineage)}</td><td class="num">${d.age ?? "–"}</td><td>${esc(d.sex)}</td><td><b>${esc(d.name)}</b></td><td class="small">${[d.wing, d.section, d.squad].filter(Boolean).map(esc).join(" · ") || "–"}</td><td class="small">${[d.source === "Register form" || d.also.includes("Register form") ? "form" : null, d.source_url ? `<a href="${esc(d.source_url)}" target="_blank" rel="noopener">result page</a>` : null].filter(Boolean).join(" + ")}${d.duplicates ? ` <span class="muted">(${d.duplicates + 1} entries merged)</span>` : ""}</td><td class="small muted">${esc(d.flags.join("; "))}</td></tr>`;
}).join("")}</tbody></table>` : `<p class="small muted" style="padding:12px">No dragons match these filters.</p>`;
$("#reg-count").textContent = `${rows.length} shown`;
renderGallery(rows);
}
// tail glyphs (24-unit box), drawn as simple original marks
const TAIL_GLYPH = {
Clubtail: '<path d="M5 19 L14 10" stroke-width="2.4"/><circle cx="16" cy="8" r="3.6" stroke="none" fill="currentColor"/>',
Daggertail: '<path d="M5 19 L8.5 15.5" stroke-width="2.4"/><path d="M7 14 L10 17" stroke-width="1.8"/><path d="M8.5 15.5 L19 5 L13.5 15.5 Z" fill="currentColor" stroke="none"/>',
Morningstartail: '<path d="M5 19 L11 13" stroke-width="2.4"/><circle cx="14.5" cy="9.5" r="3.4" fill="currentColor" stroke="none"/><path d="M14.5 3.5v2.5M14.5 13v2.5M8.5 9.5h2.5M18 9.5h2.5M10.3 5.3l1.8 1.8M16.9 11.9l1.8 1.8M18.7 5.3l-1.8 1.8M12.1 11.9l-1.8 1.8" stroke-width="1.6"/>',
Scorpiontail: '<path d="M5 19 C5 10 11 5.5 17 6.5 C20.5 7.2 20.5 11.5 17.5 12.5" stroke-width="2.2"/><path d="M17.5 12.5 L14.5 11 L16.2 15 Z" fill="currentColor" stroke="none"/>',
Swordtail: '<path d="M5 19 L19 5" stroke-width="2.6"/><path d="M6.5 13.5 L10.5 17.5" stroke-width="2"/><path d="M19 5 L16 6 L18 8 Z" fill="currentColor" stroke="none"/>',
};
function emblem(d) {
const col = cssVar(DV[d.colour] || "--faint");
const rgbv = (col.match(/[0-9a-f]{2}/gi) || ["80", "80", "80"]).slice(0, 3).map((h) => parseInt(h, 16));
const lum = col.startsWith("#") ? (0.299 * rgbv[0] + 0.587 * rgbv[1] + 0.114 * rgbv[2]) / 255 : 0.4;
const ink = lum > 0.6 ? "#14181d" : "#f4f1ea";
return `<svg viewBox="0 0 64 64" aria-hidden="true"><defs><radialGradient id="g${d.colour}" cx="35%" cy="30%" r="80%"><stop offset="0" stop-color="${col}" stop-opacity="0.85"/><stop offset="1" stop-color="${col}"/></radialGradient></defs>
<path d="M32 3 L57 17 L57 47 L32 61 L7 47 L7 17 Z" fill="url(#g${d.colour})" stroke="var(--ink)" stroke-opacity="0.25"/>
<path d="M32 9 L52 20 L52 44 L32 55 L12 44 L12 20 Z" fill="none" stroke="${ink}" stroke-opacity="0.35"/>
<g transform="translate(16 16) scale(1.35)" stroke="${ink}" fill="none" stroke-linecap="round" style="color:${ink}">${TAIL_GLYPH[d.tail] || ""}</g></svg>`;
}
function renderGallery(rows) {
const g = $("#reg-gallery");
if (!g) return;
const byC = {};
rows.forEach((d) => (byC[d.colour] = byC[d.colour] || []).push(d));
g.innerHTML = Object.keys(byC).sort((a, b) => COLOUR_ORDER.indexOf(a) - COLOUR_ORDER.indexOf(b)).map((c) => `
<div class="gal-group"><h3>${sw(c)}${esc(c)} dragons <span class="small muted" style="font-family:var(--font-body);letter-spacing:0">${byC[c].length}</span></h3>
<div class="cards">${byC[c].map((d) => `<div class="dcard" style="--dc: var(${DV[d.colour] || "--accent"})" title="${esc(d.flags.join("; "))}"><span class="age">${d.age ?? "?"} yrs</span>${emblem(d)}<span class="nm">${esc(d.name)}</span><span class="meta">${esc(d.sex || "")} ${esc(d.tail)}<br>${esc(d.lineage)} lineage${d.source_url ? `<br><a href="${esc(d.source_url)}" target="_blank" rel="noopener">result page</a>` : ""}</span></div>`).join("")}</div></div>`).join("") || `<p class="small muted">No dragons match these filters.</p>`;
}
document.querySelectorAll("#reg-view button").forEach((b) => b.addEventListener("click", () => {
document.querySelectorAll("#reg-view button").forEach((x) => x.setAttribute("aria-pressed", x === b));
$("#reg-gallery").hidden = b.dataset.v !== "cards";
$("#reg-table").hidden = b.dataset.v !== "table";
}));
function csv() {
const cols = ["colour", "tail", "lineage", "age", "sex", "name", "wing", "section", "squad", "source", "source_url", "lineage_raw", "flags"];
const q = (v) => { if (v === null || v === undefined) return ""; const s = Array.isArray(v) ? v.join("; ") : String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
return [cols.join(","), ...filtered().map((d) => cols.map((c) => q(d[c])).join(","))].join("\n");
}
[["reg-colour", "colour"], ["reg-tail", "tail"], ["reg-lineage", "lineage"], ["reg-sex", "sex"]].forEach(([id, k]) =>
$("#" + id).addEventListener("change", (e) => { st.f[k] = e.target.value; if (k === "colour") st.f.lineage = ""; render(); }));
$("#reg-q").addEventListener("input", (e) => { st.f.q = e.target.value.trim(); render(); });
$("#reg-copy").addEventListener("click", () => opts.copy(csv(), "register CSV"));
$("#reg-upload").addEventListener("change", async (e) => {
const f = e.target.files[0]; if (!f) return;
try {
const wb = XLSX.read(await f.arrayBuffer(), { type: "array", cellDates: true });
const ws = wb.Sheets[wb.SheetNames.find((n) => /form responses/i.test(n)) || wb.SheetNames[0]];
const headers = (XLSX.utils.sheet_to_json(ws, { header: 1, blankrows: false })[0] || []).map(String);
const rows = XLSX.utils.sheet_to_json(ws, { defval: null, raw: true });
load({ headers, rows, extra: st.bundled.extra }, `uploaded ${f.name} + Reddit result pages`);
opts.toast(`Loaded ${rows.length} register rows`);
} catch (err) { opts.toast("That file could not be read. Export the register sheet as .xlsx or .csv."); console.error(err); }
e.target.value = "";
});
fetch("data/register.json").then((r) => r.json()).then((raw) => { st.bundled = raw; load(raw, `bundled snapshot (${raw.source_file}, exported ${raw.exported})`); })
.catch((e) => ($("#reg-status").textContent = "The register data could not load."));
}
return { build, compare, mount, COLOUR_ORDER, TAILS, lev };
});
+248
View File
@@ -0,0 +1,248 @@
/* ui.js — tabs, hero art, the plain-language overview and the illustrated valley map.
* Reads the same coded runs and results as the rest of the page (window.ThreshAtlas.state). */
(function () {
"use strict";
const E = window.ThreshEngine;
const $ = (q, el = document) => el.querySelector(q);
const $$ = (q, el = document) => [...el.querySelectorAll(q)];
const NS = "http://www.w3.org/2000/svg";
const cssVar = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const pct = (p, d = 0) => (p === null || p === undefined || isNaN(p) ? "–" : (p * 100).toFixed(d) + "%");
const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
const oneIn = (p) => (p > 0 ? Math.max(1, Math.round(1 / p)) : null);
function el(tag, attrs = {}, parent) {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) if (v !== null && v !== undefined) e.setAttribute(k, v);
if (parent) parent.appendChild(e);
return e;
}
function rgb(c) {
c = (c || "").trim();
if (c.startsWith("#")) { const h = c.length === 4 ? [...c.slice(1)].map((x) => x + x).join("") : c.slice(1); return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)); }
const m = c.match(/\d+(\.\d+)?/g); return m ? m.slice(0, 3).map(Number) : [128, 128, 128];
}
const mix = (a, b, t) => { const A = rgb(a), B = rgb(b); return `rgb(${A.map((v, i) => Math.round(v + (B[i] - v) * t)).join(",")})`; };
function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
// ------------------------------------------------------------ tabs
const TABS = ["valley", "odds", "dragons", "deep", "data"];
// old links (#overview, #flow, #planner ...) still land somewhere sensible
const ALIAS = { overview: "odds", planner: "valley", flow: "deep", rare: "deep", share: "data" };
const tabOf = (hash) => { const t = (hash || "").replace(/^#/, "").split("/")[0]; return TABS.includes(t) ? t : ALIAS[t] || null; };
function showTab(name, focus, keepHash) {
if (!TABS.includes(name)) name = ALIAS[name] || "valley";
TABS.forEach((t) => {
const on = t === name;
$("#tab-" + t).setAttribute("aria-selected", on);
$("#tab-" + t).tabIndex = on ? 0 : -1;
$("#panel-" + t).hidden = !on;
});
if (focus) $("#tab-" + name).focus();
try { $("#tab-" + name).scrollIntoView({ block: "nearest", inline: "center" }); } catch (e) { /* ignore */ }
if (!keepHash) { try { history.replaceState(null, "", "#" + name); } catch (e) { /* ignore */ } }
if (name === "valley" && window.ValleyExplorer) window.ValleyExplorer.fromHash();
if (name === "deep" && window.ThreshAtlas && window.ThreshAtlas.state.res) window.dispatchEvent(new Event("resize"));
}
TABS.forEach((t, i) => {
const b = $("#tab-" + t);
b.addEventListener("click", () => showTab(t));
b.addEventListener("keydown", (e) => {
if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
const j = (i + (e.key === "ArrowRight" ? 1 : TABS.length - 1)) % TABS.length;
showTab(TABS[j], true); e.preventDefault();
}
});
});
$$("[data-go]").forEach((b) => b.addEventListener("click", () => { showTab(b.dataset.go); window.scrollTo({ top: 0, behavior: "smooth" }); }));
// in-page links that point at sections inside other tabs
document.addEventListener("click", (e) => {
const a = e.target.closest('a[href^="#"]');
if (!a) return;
const id = a.getAttribute("href").slice(1);
if (tabOf(id)) {
// keep sub-paths such as #valley/blue so the destination can open on that selection
e.preventDefault();
try { history.replaceState(null, "", "#" + id); } catch (err) { /* ignore */ }
showTab(tabOf(id), false, true);
window.scrollTo({ top: 0, behavior: "smooth" });
return;
}
const target = document.getElementById(id);
const panel = target && target.closest(".tabpanel");
if (panel && panel.hidden) { e.preventDefault(); showTab(panel.id.replace("panel-", "")); target.scrollIntoView({ behavior: "smooth" }); }
});
// #valley/blue/meadow-Blue keeps its sub-path (the explorer reads it)
window.addEventListener("hashchange", () => { const t = tabOf(location.hash); if (t) showTab(t, false, t === "valley"); });
const initial = tabOf(location.hash);
showTab(initial || "valley", false, initial === "valley");
// ------------------------------------------------------------ methods tabs (arrow keys move between them)
const mtabs = $$(".mtab");
const showM = (b, focus) => {
mtabs.forEach((t) => { const on = t === b; t.setAttribute("aria-selected", on); t.tabIndex = on ? 0 : -1; $("#" + t.getAttribute("aria-controls")).hidden = !on; });
if (focus) b.focus();
};
mtabs.forEach((b, i) => {
b.addEventListener("click", () => showM(b));
b.addEventListener("keydown", (e) => {
if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return;
e.preventDefault();
showM(mtabs[(i + (e.key === "ArrowRight" ? 1 : mtabs.length - 1)) % mtabs.length], true);
});
});
// ------------------------------------------------------------ hero art (original, generic silhouettes)
function drawHero() {
const svg = $("#hero-art");
svg.innerHTML = "";
const g = el("g", {}, svg);
el("path", { d: "M0 330 L120 250 L210 290 L330 200 L430 270 L560 180 L690 260 L800 210 L930 280 L1040 220 L1200 290 L1200 420 L0 420 Z", fill: "#2c1120" }, g);
el("path", { d: "M0 360 L160 300 L300 330 L470 270 L620 330 L780 285 L960 335 L1100 300 L1200 330 L1200 420 L0 420 Z", fill: "#220a17" }, g);
// tree line
const R = rng(3); let tl = "M0 420 L0 380";
for (let x = 0; x <= 1200; x += 14) { const h = 18 + R() * 30; tl += ` L${x + 7} ${392 - h} L${x + 14} ${392 - R() * 6}`; }
el("path", { d: tl + " L1200 420 Z", fill: "#16060e" }, g);
// a generic cliff-top keep, right side
const keep = el("g", { fill: "#1a0812", transform: "translate(0 40)" }, g);
el("path", { d: "M930 360 L930 250 L960 240 L990 250 L1010 236 L1040 250 L1070 232 L1100 250 L1130 245 L1150 360 Z" }, keep);
[[952, 196, 20, 58], [1000, 180, 22, 70], [1058, 190, 18, 60], [1098, 205, 16, 46]].forEach(([x, y, w, h]) => {
el("rect", { x, y, width: w, height: h }, keep);
el("path", { d: `M${x - 3} ${y} L${x + w / 2} ${y - 18} L${x + w + 3} ${y} Z` }, keep);
});
// distant riders: simple winged silhouettes
const shape = "M50 30 L18 6 L27 21 L3 16 L25 32 Z M50 30 L82 6 L73 21 L97 16 L75 32 Z M37 30 Q50 23 63 30 Q50 37 37 30 Z M63 30 L76 26 L80 28 L73 31 Z M37 30 Q24 37 10 34 Q22 33 36 31 Z";
[[700, 70, 0.9, 0.9], [560, 120, 0.55, 0.7], [820, 130, 0.42, 0.55], [380, 95, 0.32, 0.45]].forEach(([x, y, s, o]) =>
el("path", { d: shape, transform: `translate(${x} ${y}) scale(${s})`, fill: "#0f040a", "fill-opacity": o }, g));
const em = $("#embers");
if (em && !em.childElementCount) {
const R2 = rng(11);
for (let i = 0; i < 26; i++) {
const e = document.createElement("i");
e.style.left = (R2() * 100).toFixed(1) + "%";
e.style.animationDuration = (6 + R2() * 7).toFixed(1) + "s";
e.style.animationDelay = (-R2() * 12).toFixed(1) + "s";
const sz = (2 + R2() * 3).toFixed(1); e.style.width = e.style.height = sz + "px";
if (matchMedia("(prefers-reduced-motion: reduce)").matches) e.style.top = (10 + R2() * 80).toFixed(1) + "%";
em.appendChild(e);
}
}
}
drawHero();
// ------------------------------------------------------------ overview
function stratum(c, prefix) { const e = Object.entries(c.by_stratum).find(([k]) => k.startsWith(prefix)); return e ? e[1] : null; }
function dots(k, n, color, total = 100) {
const p = n ? k / n : 0, filled = p * total;
const cols = 20, r = 4, gap = 11, rows = Math.ceil(total / cols);
const svg = el("svg", { viewBox: `0 0 ${cols * gap} ${rows * gap}`, role: "img", "aria-label": `${pct(p, 1)} shown as ${total} dots` });
for (let i = 0; i < total; i++) {
const x = (i % cols) * gap + gap / 2, y = Math.floor(i / cols) * gap + gap / 2;
const on = i < Math.floor(filled), part = i === Math.floor(filled) && filled % 1 > 0.05;
el("circle", { cx: x, cy: y, r, fill: on ? color : "none", stroke: on || part ? color : cssVar("--line"), "stroke-width": 1.2, "fill-opacity": part ? 0.35 : 1 }, svg);
if (part) el("circle", { cx: x, cy: y, r: r * Math.sqrt(filled % 1), fill: color }, svg);
}
return svg.outerHTML;
}
// The odds for all six dragons come from the route model (data/policy.json); fetched once.
let policyP = null;
const getPolicy = () => policyP || (policyP = fetch("data/policy.json").then((r) => r.json()).catch(() => null));
const ENC_OF = { Red: "valley-Red", Orange: "meadow-Orange", Brown: "meadow-Brown", Green: "tree-Greens", Blue: "meadow-Blue", Black: "shadow-Black" };
const ENC_LABEL = { "valley-Red": "the valley Red", "meadow-Orange": "the meadow Orange", "meadow-Brown": "the meadow Brown", "tree-Greens": "the two Greens", "meadow-Blue": "the meadow Blue", "shadow-Black": "the Black after the shadow" };
const POSE = { Red: "roaring", Orange: "flying", Brown: "resting", Green: "prowling", Blue: "coiled", Black: "flying" };
function renderColourOdds(policy) {
if (!policy) { $("#odds-colours").innerHTML = '<p class="small muted">The route model could not be loaded.</p>'; return; }
const lb = policy.samples.lowBias, all = policy.samples.all;
const cols = ["Red", "Green", "Orange", "Brown", "Blue", "Black"]
.map((c) => ({ c, p: lb.targets[c].eventually.pX.mean, pAll: all.targets[c].eventually.pX.mean, lo: lb.targets[c].eventually.pX.lo, hi: lb.targets[c].eventually.pX.hi }))
.sort((a, b) => b.p - a.p);
const enc = (c) => { const e = (all.model.tables.encounter || {})[ENC_OF[c]] || { outcomes: {} }; const n = Object.values(e.outcomes).reduce((a, b) => a + b, 0); return { k: e.outcomes[c] || 0, n }; };
const art = (c) => window.DragonArt ? `<svg class="odd-art" viewBox="0 0 200 160" aria-hidden="true">${window.DragonArt.svg(POSE[c], { fill: `var(${DV[c]})`, eyeFill: "var(--bg)" })}</svg>` : "";
$("#odds-colours").innerHTML = cols.map(({ c, p, pAll, lo, hi }) => {
const e = enc(c);
return `<a class="odd odd-colour" href="#valley/${c.toLowerCase()}" style="--c: var(${DV[c]})">${art(c)}
<span class="big">${p >= 0.5 ? pct(p) : `1 in ${oneIn(p)}`}</span><span class="what">${p >= 0.5 ? "of runs" : "runs"} end bonded to ${/^[AEIOU]/.test(c) ? "an" : "a"} ${c}, on the best route</span>
${dots(Math.round(p * 1000), 1000, cssVar(DV[c]))}
<span class="how"><b>${pct(p, p < 0.1 ? 1 : 0)}</b> per attempt (95% ${pct(lo, 1)}–${pct(hi, 1)}), from riders who logged every run${Math.abs(pAll - p) / p > 0.25 ? `; all form posts suggest ${pct(pAll, 1)}` : ""}. At ${ENC_LABEL[ENC_OF[c]]}, <b>${e.k} of ${e.n}</b> genuine attempts bonded.</span>
<span class="go">See the route →</span></a>`;
}).join("");
const meadowAlpha = all.model.alphas.meadow, shadowAlpha = all.model.alphas.shadow;
const t2 = $("#truth-history");
if (t2) t2.innerHTML = `<h3>Earlier choices barely change who waits</h3><p class="small">${meadowAlpha >= 10000 ? "Which dragon waits in the meadow shows no link to anything you chose before." : "Which dragon waits in the meadow depends only a little on earlier choices."} ${shadowAlpha >= 500 ? "The shadow at the tree depends on them only weakly." : "The shadow at the tree shows some dependence on earlier choices, but the evidence is thin."} The model lets every roll depend on your history, and measured how much it does. Choices the form doesn't record (what you answered inside an encounter) might still matter.</p>`;
const t3 = $("#truth-burn");
if (t3) {
const rates = cols.map(({ c }) => ({ c, ...enc(c) })).filter((x) => x.n >= 20).map((x) => ({ ...x, p: x.k / x.n })).sort((a, b) => a.p - b.p);
t3.innerHTML = `<h3>The right answer can still burn</h3><p class="small">Even with the community's best answers, bond chances at the encounter run from ${pct(rates[0].p)} (${esc(ENC_LABEL[ENC_OF[rates[0].c]])}) to ${pct(rates[rates.length - 1].p)} (${esc(ENC_LABEL[ENC_OF[rates[rates.length - 1].c]])}). One death with the "right" answer doesn't mean the answer was wrong.</p>`;
}
}
function renderOverview(state) {
const r = state.res;
const reach = r.factors.reach_hour.overall;
const cb = r.chance.blue_meadow;
const bulkB = stratum(cb, "Bulk");
const tag = (txt) => `<span class="how">${txt}</span>`;
// A cadet who walks in and either dies or bonds. Deliberate deaths are left out: a rider burned at a bonding
// encounter they did not genuinely attempt (they were after another colour and planned to seek Malek). Runs with
// no recorded outcome are left out too. Same rule the solver uses for encounter odds (ThreshSolver.genuineAttempt).
const S = window.ThreshSolver;
const ended = state.runs.filter((x) => ["Bonded", "Incinerated", "Died before the hour"].includes(x.outcome));
const deliberate = (x) => { if (x.outcome !== "Incinerated" || !S) return false; const v = S.prepareRun(x); return !!v.encCtx && !S.genuineAttempt(x, v.encCtx); };
const cadets = ended.filter((x) => !deliberate(x));
const nDeliberate = ended.length - cadets.length;
const bonded = cadets.filter((x) => x.outcome === "Bonded").length;
const dead = cadets.length - bonded;
const earlyDeaths = cadets.filter((x) => x.outcome === "Died before the hour").length;
const cards = [
{ c: "--accent", big: pct(bonded / cadets.length), what: "become a rider", how: `${bonded.toLocaleString()} of ${cadets.length.toLocaleString()} cadets bonded a dragon. ${pct(1 - earlyDeaths / cadets.length)} made it to the tree-or-valley choice alive.`, w: { k: bonded, n: cadets.length } },
{ c: "--death", big: dead.toLocaleString(), what: "riders sent to Malek", how: `${pct(dead / cadets.length)} of cadets were burned or killed. Deliberate deaths (${nDeliberate.toLocaleString()} runs where the rider chose to die and try again) are not counted.`, w: { k: dead, n: cadets.length }, death: true },
];
$("#odds").innerHTML = cards.map((c) => `<div class="odd${c.death ? " death deco" : ""}" style="--c: var(${c.c})"><span class="big">${esc(c.big)}</span><span class="what">${esc(c.what)}</span>${dots(c.w.k, c.w.n, cssVar(c.c))}${tag(c.how)}</div>`).join("");
getPolicy().then(renderColourOdds);
// journey
const fr = r.factors.reach_hour.rows;
const lvl = (f, l) => fr.find((x) => x.factor === f && x.level === l);
const alone = lvl("company", "Alone"), two = lvl("company", "2 Squadmates");
const helpK = lvl("resolution", "DIED in combat");
const greens = r.green_rescue;
const stops = [
{ t: "Choose company", d: "Go in alone, or with one or two squadmates.", v: alone && two ? `Alone, ${pct(alone.p)} reached the hour. With two squadmates, ${pct(two.p)} did.` : "" },
{ t: "Pick a direction", d: "East toward the roar, west toward the scent, or the forest centre.", v: "Direction decides which first dragon can find you." },
{ t: "The first dragon", d: "A dragon finds you. Which colour is the game's roll, not yours.", v: "Keep your eyes down. This one is about surviving, not bonding.", roll: true },
{ t: "The scream", d: "Help the squadmate fighting two cadets, walk away, or ignore it and find a wounded cadet.", v: helpK ? `${helpK.n} logged runs died in the fight.` : "" },
{ t: "Fork in the road", d: "After the fight: west, deeper into the forest, or east.", v: "Only the bully path has a fork." },
{ t: "Tree or valley", d: "Climb the tallest tree, or walk to the valley centre.", v: "The tree holds a Red, two Greens and the rare shadow. The valley holds a Red, then the meadow's Orange, Brown and sometimes a Blue." },
{ t: "The bonding", d: "Who is waiting is partly luck. Then every answer is a test.", v: greens.green_encounters ? `At the two Greens, ${pct((greens.rescued_orange + greens.rescued_brown) / greens.green_encounters)} were rescued by an Orange or Brown.` : "", roll: true },
];
$("#journey").innerHTML = stops.map((s, i) => `<div class="stop${s.roll ? " roll" : ""}"><span class="n">${["I", "II", "III", "IV", "V", "VI", "VII"][i]}</span><span class="t">${esc(s.t)}</span><span class="d">${esc(s.d)}</span>${s.v ? `<span class="verdict">${esc(s.v)}</span>` : ""}</div>`).join("");
const chase = stratum(cb, "Form: chasing Blue");
$("#truths").innerHTML = `
<div class="truth"><h3>Lucky runs get shared</h3><p class="small">Riders hunting a rare dragon logged a Blue in ${pct(chase ? chase.p : null)} of their meadow visits. Riders who logged every run saw it in ${pct(bulkB ? bulkB.p : null)}. The game can't know what you're chasing, so the difference is who chose to write in. The Odds page leans on the riders who logged every run.</p></div>
<div class="truth" id="truth-history"></div>
<div class="truth" id="truth-burn"></div>`;
$("#h-truths-kicker").textContent = `What ${r.n.toLocaleString()} runs say`;
$("#hero-tagline").textContent = `Every path through the valley, mapped from ${r.n.toLocaleString()} runs riders logged.`;
}
// tooltip shared with app.js
const tipEl = $("#tip");
function tip(e, html) {
tipEl.innerHTML = html; tipEl.hidden = false;
const r = tipEl.getBoundingClientRect();
tipEl.style.left = Math.min(window.innerWidth - r.width - 8, e.clientX + 14) + "px";
tipEl.style.top = Math.min(window.innerHeight - r.height - 8, e.clientY + 14) + "px";
}
const hideTip = () => (tipEl.hidden = true);
window.AtlasUI = {
render(state) {
renderOverview(state);
if (window.ValleyExplorer) window.ValleyExplorer.setRuns(state);
},
showTab,
};
if (window.ThreshAtlas && window.ThreshAtlas.state && window.ThreshAtlas.state.res) window.AtlasUI.render(window.ThreshAtlas.state);
})();
+390
View File
@@ -0,0 +1,390 @@
/* valley.js — the watercolour valley map.
* Every place on the map is a step in a run. Trails are drawn from the coded runs (engine.js):
* thickness = riders who walked it, colour = share of those riders who reached the chosen outcome.
* Dashed trails are routes the community has described but the form does not record. */
(function () {
"use strict";
const E = window.ThreshEngine;
const $ = (q, el = document) => el.querySelector(q);
const $$ = (q, el = document) => [...el.querySelectorAll(q)];
const NS = "http://www.w3.org/2000/svg";
const cssVar = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
const esc = (x) => String(x ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const pct = (p, d = 0) => (p === null || p === undefined || isNaN(p) ? "–" : (p * 100).toFixed(d) + "%");
const DV = { Red: "--dr-red", Green: "--dr-green", Orange: "--dr-orange", Brown: "--dr-brown", Blue: "--dr-blue", Black: "--dr-black" };
// painted-map dragon inks (darker than the UI tones so they read on gold paper)
// chosen so every pair stays distinguishable under common colour-vision deficiencies (docs/COLOURS.md)
const INK = { Red: "#cc3346", Green: "#2f8f6f", Orange: "#e08a2a", Brown: "#4e3020", Blue: "#2a58b8", Black: "#22182a" };
const PAPER = { ink: "#3b2416", halo: "#f6e6c4", trailLow: "#8a6446", death: "#c4471c" };
function el(tag, attrs = {}, parent) {
const e = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) if (v !== null && v !== undefined) e.setAttribute(k, v);
if (parent) parent.appendChild(e);
return e;
}
function rgb(c) {
c = (c || "").trim();
if (c.startsWith("#")) { const h = c.length === 4 ? [...c.slice(1)].map((x) => x + x).join("") : c.slice(1); return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)); }
const m = c.match(/\d+(\.\d+)?/g); return m ? m.slice(0, 3).map(Number) : [128, 128, 128];
}
const mix = (a, b, t) => { const A = rgb(a), B = rgb(b); return `rgb(${A.map((v, i) => Math.round(v + (B[i] - v) * t)).join(",")})`; };
function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
// ------------------------------------------------------------ places
// kind: start | way (a choice point) | dragon (a dragon is met here) | small (a choice made here)
const L = {
"comp:Alone": { x: 500, y: 736, name: "Alone", kind: "start", lab: "below", desc: "Enter the valley alone. The most common start, and the one that survives most often." },
"comp:1 Squadmate": { x: 380, y: 740, name: "One squadmate", kind: "start", lab: "below", desc: "Enter with one squadmate. You can later leave them and go on alone." },
"comp:2 Squadmates": { x: 620, y: 740, name: "Two squadmates", kind: "start", lab: "below", desc: "Enter with two squadmates. The first dragon is often deadlier for a group." },
"dir:West": { x: 190, y: 662, name: "West", sub: "toward the scent", kind: "way", lab: "left", desc: "Follow a scent west. A Brown, Green or Red finds you first." },
"dir:Center": { x: 500, y: 668, name: "Forest centre", kind: "way", lab: "right", desc: "Straight into the forest. Alone, a Red or a Brown finds you first." },
"dir:East": { x: 810, y: 662, name: "East", sub: "toward the roar", kind: "way", lab: "right", desc: "Toward the roar. Alone, a Red or an Orange finds you first. With one squadmate, a Green or an Orange." },
// first sightings (game roll)
"see:West:Red": { x: 110, y: 598, colour: "Red", kind: "dragon", first: true },
"see:West:Brown": { x: 185, y: 584, colour: "Brown", kind: "dragon", first: true },
"see:West:Green": { x: 262, y: 598, colour: "Green", kind: "dragon", first: true },
"see:Center:Red": { x: 448, y: 600, colour: "Red", kind: "dragon", first: true },
"see:Center:Brown": { x: 552, y: 600, colour: "Brown", kind: "dragon", first: true },
"see:East:Red": { x: 738, y: 598, colour: "Red", kind: "dragon", first: true },
"see:East:Orange": { x: 815, y: 584, colour: "Orange", kind: "dragon", first: true },
"see:East:Green": { x: 892, y: 598, colour: "Green", kind: "dragon", first: true },
scream: { x: 500, y: 512, name: "The scream", kind: "way", lab: "right", desc: "A scream in the trees. Help the squadmate fighting two cadets, walk away, or ignore it." },
bully: { x: 318, y: 462, name: "The bully fight", kind: "way", lab: "left", desc: "A squadmate is cornered by two cadets. Assess, even the numbers, or put yourself in the middle." },
"res:Killed the bullies yourself": { x: 222, y: 410, name: "Kill them", kind: "small", lab: "left", desc: "End the bullies yourself." },
"res:Squadmate's revenge": { x: 312, y: 398, name: "Squadmate's revenge", kind: "small", lab: "above", desc: "Let your squadmate take revenge." },
"res:Left bullies to the dragons": { x: 404, y: 410, name: "Dragons decide", kind: "small", lab: "right", desc: "Leave the bullies to the dragons." },
away: { x: 500, y: 440, name: "Walked away", kind: "small", lab: "right", desc: "Investigated the scream, then left them to it." },
wounded: { x: 684, y: 462, name: "The wounded cadet", kind: "way", lab: "right", desc: "Ignore the scream and you trip over a cadet missing a leg." },
"res:Tourniquet": { x: 616, y: 410, name: "Tourniquet", kind: "small", lab: "left", desc: "Use their belt as a tourniquet." },
"res:Left injured cadet": { x: 690, y: 398, name: "Leave them", kind: "small", lab: "above", desc: "Leave them to die." },
"res:Took their weapons": { x: 780, y: 410, name: "Take their weapons", kind: "small", lab: "right", desc: "Take their weapons and go." },
"fork:West": { x: 196, y: 336, name: "West fork", kind: "way", lab: "left", desc: "After the fight, the path splits: west." },
"fork:Forest": { x: 318, y: 318, name: "Deeper in", kind: "way", lab: "above", desc: "After the fight: deeper into the forest. Most recorded shadows came after this choice." },
"fork:East": { x: 432, y: 336, name: "East fork", kind: "way", lab: "right", desc: "After the fight, the path splits: east." },
hour: { x: 520, y: 272, name: "An hour's walk", sub: "the thorn", kind: "way", lab: "right", desc: "An hour of walking, and a thorn draws blood. No dragon bonds before this point." },
tree: { x: 316, y: 204, name: "The tallest tree", kind: "way", lab: "right", desc: "Climb for a view: a Red below, two Greens in a clearing and, very rarely, a shadow moving west." },
valley: { x: 694, y: 204, name: "Valley centre", kind: "way", lab: "left", desc: "Walk on to the valley centre." },
treeRed: { x: 168, y: 250, name: "The Red below", colour: "Red", kind: "dragon", lab: "left", desc: "Descend quickly onto a Red prowling under the tree. The hardest bond in the game." },
greens: { x: 124, y: 140, name: "Two Greens", colour: "Green", kind: "dragon", lab: "below", desc: "Two Greens in a clearing test you. A wrong answer sometimes brings an Orange or Brown to the rescue." },
stream: { x: 372, y: 142, name: "The shadow", sub: "a stream, a claw print", kind: "way", lab: "right", desc: "The rare third option at the tree. Follow the shadow west, past a stream and a claw print." },
redwood: { x: 452, y: 84, name: "Blue at the redwood", colour: "Blue", kind: "dragon", lab: "above", desc: "A Blue coiled around a redwood. Hold still and let it pass to reach the Black." },
black: { x: 262, y: 70, name: "Behind you", colour: "Black", kind: "dragon", lab: "left", desc: "A branch snaps behind you. Turn to face the threat." },
valleyRed: { x: 846, y: 250, name: "The valley Red", colour: "Red", kind: "dragon", lab: "below", desc: "A Red that has just incinerated another cadet. Most who choose to bond it succeed. Say it isn't your dragon to walk on to the meadow." },
meadow: { x: 742, y: 146, name: "The meadow", kind: "way", lab: "below", desc: "A meadow where an Orange and a Brown wait. Sometimes a Blue joins them." },
"meadow:Orange": { x: 652, y: 100, name: "Orange", colour: "Orange", kind: "dragon", lab: "left", desc: "The meadow Orange." },
"meadow:Brown": { x: 744, y: 80, name: "Brown", colour: "Brown", kind: "dragon", lab: "above", desc: "The meadow Brown." },
"meadow:Blue": { x: 836, y: 100, name: "Meadow Blue", colour: "Blue", kind: "dragon", lab: "right", desc: "The rare meadow Blue. Most riders who approach it are burned, even with the community's best answers." },
};
// routes described by the community that the form does not record
const KNOWN = [
["treeRed", "greens", "Wait and pursue the Green"],
["redwood", "greens", "Retreat, then find the Green"],
["redwood", "valley", "Retreat toward the valley"],
["comp:1 Squadmate", "comp:Alone", "Leave your squadmate"],
["comp:2 Squadmates", "comp:Alone", "Leave your squadmates"],
];
const SIGHT_NODES = new Set(Object.keys(L).filter((k) => k.startsWith("see:")));
function path(r) {
const s = [];
if (L["comp:" + r.company]) s.push("comp:" + r.company);
if (!["East", "West", "Center"].includes(r.direction)) return s;
s.push("dir:" + r.direction);
const sight = `see:${r.direction}:${r.first_sighting}`;
if (SIGHT_NODES.has(sight)) s.push(sight);
if (r.scream === "DIED at first sighting" || r.scream === "Unknown") return s;
s.push("scream");
if (r.scream === "Investigate & help") {
s.push("bully");
if (L["res:" + r.resolution]) s.push("res:" + r.resolution);
if (r.resolution.startsWith("DIED")) return s;
if (["Forest", "West", "East"].includes(r.post_path)) s.push("fork:" + r.post_path);
} else if (r.scream === "Ignore the scream") {
s.push("wounded");
if (L["res:" + r.resolution]) s.push("res:" + r.resolution);
} else if (r.scream === "Investigate & leave") s.push("away");
if (r.hour !== "Tree" && r.hour !== "Valley") return s;
s.push("hour");
if (r.hour === "Tree") {
s.push("tree");
if (r.branch === "Descend quickly: Red") s.push("treeRed");
else if (r.branch === "Descend slowly: two Greens") s.push("greens");
else if (r.branch === "Shadow (rare)") { s.push("stream"); if (r.enc_Blue || r.enc_Black) s.push("redwood"); if (r.enc_Black) s.push("black"); }
} else {
s.push("valley");
if (r.branch === "Valley Red") s.push("valleyRed");
else if (r.branch === "Passed the Red: meadow") {
s.push("meadow");
const tried = r.enc_Blue ? "Blue" : (r.outcome_color === "Orange" || r.outcome_color === "Brown") ? r.outcome_color : r.enc_Orange ? "Orange" : r.enc_Brown ? "Brown" : null;
if (tried) s.push("meadow:" + tried);
}
}
return s;
}
// ------------------------------------------------------------ painting
function defs(svg) {
const d = el("defs", {}, svg);
d.innerHTML = `
<linearGradient id="vm-sky" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#f3d69c"/><stop offset="0.35" stop-color="#e9c88f"/><stop offset="0.7" stop-color="#d9b07a"/><stop offset="1" stop-color="#c8955f"/>
</linearGradient>
<radialGradient id="vm-sun" cx="0.62" cy="0.12" r="0.55"><stop offset="0" stop-color="#fff3d1" stop-opacity="0.9"/><stop offset="1" stop-color="#fff3d1" stop-opacity="0"/></radialGradient>
<radialGradient id="vm-vignette" cx="0.5" cy="0.5" r="0.72"><stop offset="0.6" stop-color="#2a0f1c" stop-opacity="0"/><stop offset="1" stop-color="#2a0f1c" stop-opacity="0.55"/></radialGradient>
<filter id="vm-wash" x="-10%" y="-10%" width="120%" height="120%">
<feTurbulence type="fractalNoise" baseFrequency="0.022" numOctaves="3" seed="4" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="16" xChannelSelector="R" yChannelSelector="G" result="d"/>
<feGaussianBlur in="d" stdDeviation="0.7"/>
</filter>
<filter id="vm-wash2" x="-10%" y="-10%" width="120%" height="120%">
<feTurbulence type="fractalNoise" baseFrequency="0.05" numOctaves="2" seed="9" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="8" xChannelSelector="R" yChannelSelector="G"/>
</filter>
<filter id="vm-brush" x="-5%" y="-5%" width="110%" height="110%">
<feTurbulence type="fractalNoise" baseFrequency="0.09" numOctaves="2" seed="3" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="4" xChannelSelector="R" yChannelSelector="G"/>
</filter>
<filter id="vm-paper" x="0" y="0" width="100%" height="100%">
<feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="1" result="g"/>
<feColorMatrix in="g" type="matrix" values="0 0 0 0 0.36 0 0 0 0 0.24 0 0 0 0 0.14 0 0 0 0.55 -0.18"/>
</filter>
<filter id="vm-haze"><feGaussianBlur stdDeviation="10"/></filter>`;
}
function blob(g, x, y, r, fill, op, R) {
// irregular canopy blob from a few overlapping circles
for (let i = 0; i < 3; i++) el("circle", { cx: x + (R() - 0.5) * r * 0.9, cy: y + (R() - 0.5) * r * 0.6, r: r * (0.6 + R() * 0.45), fill, "fill-opacity": op }, g);
}
function paint(svg) {
const R = rng(21);
el("rect", { x: 0, y: 0, width: 1000, height: 780, fill: "url(#vm-sky)" }, svg);
el("rect", { x: 0, y: 0, width: 1000, height: 780, fill: "url(#vm-sun)" }, svg);
// far ridge and hazy hills
const far = el("g", { filter: "url(#vm-wash)" }, svg);
let d = "M-20 120";
for (let x = -20; x <= 1020; x += 60) d += ` Q${x + 30} ${40 + R() * 40} ${x + 60} ${90 + R() * 40}`;
el("path", { d: d + " L1020 -10 L-20 -10 Z", fill: "#c99a72", "fill-opacity": 0.55 }, far);
el("path", { d: "M-20 150 Q200 90 420 140 T820 120 T1020 150 L1020 200 L-20 200 Z", fill: "#d4a677", "fill-opacity": 0.45 }, far);
// forest: three depth tiers of canopy washes, kept out of the clearings
const clear = [[742, 100, 150, 85], [124, 140, 92, 58], [694, 205, 80, 44], [520, 272, 70, 32], [846, 250, 70, 40], [500, 740, 190, 46], [318, 455, 120, 60], [684, 455, 120, 60], [500, 660, 80, 30]];
const inClear = (x, y) => clear.some(([cx, cy, rx, ry]) => ((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2 < 1);
const tiers = [
{ y0: 120, y1: 330, n: 150, r: [10, 20], cols: ["#b39a63", "#a99158"], op: 0.32 },
{ y0: 300, y1: 560, n: 170, r: [12, 24], cols: ["#8e8a54", "#7f7e4b"], op: 0.4 },
{ y0: 520, y1: 780, n: 170, r: [14, 30], cols: ["#6c6b40", "#5b5c37", "#6b5a35"], op: 0.45 },
];
tiers.forEach((t, ti) => {
const g = el("g", { filter: "url(#vm-wash)" }, svg);
// tall pale trunks, like a sunlit wood
for (let i = 0; i < t.n * 0.25; i++) {
const x = R() * 1000, y = t.y0 + R() * (t.y1 - t.y0);
if (inClear(x, y)) continue;
el("rect", { x, y: y - 50 - ti * 10, width: 2 + ti * 1.5, height: 60 + ti * 14, fill: "#7a5c3c", "fill-opacity": 0.18 + ti * 0.07 }, g);
}
for (let i = 0; i < t.n; i++) {
const x = R() * 1000, y = t.y0 + R() * (t.y1 - t.y0);
if (inClear(x, y)) continue;
blob(g, x, y, t.r[0] + R() * (t.r[1] - t.r[0]), t.cols[Math.floor(R() * t.cols.length)], t.op, R);
}
});
// clearings: warm ochre light
const cg = el("g", { filter: "url(#vm-wash)" }, svg);
clear.forEach(([cx, cy, rx, ry]) => el("ellipse", { cx, cy, rx: rx * 0.85, ry: ry * 0.8, fill: "#f0cf93", "fill-opacity": 0.55 }, cg));
// mist bands
const mg = el("g", { filter: "url(#vm-haze)" }, svg);
[[230, 0.35], [380, 0.2], [560, 0.18]].forEach(([y, o]) => el("rect", { x: -40, y, width: 1080, height: 26, fill: "#fbe9c4", "fill-opacity": o }, mg));
// the stream
const sg = el("g", { filter: "url(#vm-wash2)" }, svg);
const stream = "M560 -10 C 520 40, 470 70, 420 112 S 330 170, 270 150 S 170 120, 110 220 S 40 320, -10 350";
el("path", { d: stream, fill: "none", stroke: "#7fa3a6", "stroke-width": 13, "stroke-opacity": 0.65, "stroke-linecap": "round" }, sg);
el("path", { d: stream, fill: "none", stroke: "#cfe1dc", "stroke-width": 3, "stroke-opacity": 0.6, "stroke-linecap": "round" }, sg);
// rock outcrop for the valley Red, standing stones by the meadow
const rk = el("g", { filter: "url(#vm-wash2)" }, svg);
el("path", { d: "M800 272 L826 236 L862 230 L892 262 L880 284 L812 288 Z", fill: "#6e5c63", "fill-opacity": 0.75 }, rk);
el("path", { d: "M826 236 L862 230 L870 246 L834 252 Z", fill: "#9b8790", "fill-opacity": 0.6 }, rk);
// the tallest tree and the redwood
const big = el("g", { filter: "url(#vm-wash2)" }, svg);
el("rect", { x: 312, y: 150, width: 9, height: 70, fill: "#5a3f28", "fill-opacity": 0.85 }, big);
[[316, 150, 30], [302, 172, 22], [332, 168, 22], [316, 124, 22]].forEach(([x, y, r]) => el("circle", { cx: x, cy: y, r, fill: "#46502e", "fill-opacity": 0.75 }, big));
el("rect", { x: 446, y: 40, width: 11, height: 56, fill: "#8a4430", "fill-opacity": 0.85 }, big);
[[452, 40, 20], [440, 54, 14], [464, 54, 14]].forEach(([x, y, r]) => el("circle", { cx: x, cy: y, r, fill: "#3f4a2b", "fill-opacity": 0.7 }, big));
}
function overlay(svg) {
el("rect", { x: 0, y: 0, width: 1000, height: 780, filter: "url(#vm-paper)", opacity: 0.45, style: "mix-blend-mode:multiply", "pointer-events": "none" }, svg);
el("rect", { x: 0, y: 0, width: 1000, height: 780, fill: "url(#vm-vignette)", "pointer-events": "none" }, svg);
}
// tiny original winged glyph for dragon places
const WING = "M50 30 L18 6 L27 21 L3 16 L25 32 Z M50 30 L82 6 L73 21 L97 16 L75 32 Z M37 30 Q50 23 63 30 Q50 37 37 30 Z M63 30 L76 26 L80 28 L73 31 Z M37 30 Q24 37 10 34 Q22 33 36 31 Z";
// ------------------------------------------------------------ rendering
let target = "bond_Blue", selected = "meadow:Blue", lastState = null, tipEl = null;
const TGT = ["bond_Blue", "bond_Black", "see_Blue", "see_shadow", "bond_Red", "bond_Green", "bond_Orange", "bond_Brown", "bond_any"];
function tip(e, html) {
tipEl = tipEl || $("#tip");
tipEl.innerHTML = html; tipEl.hidden = false;
const r = tipEl.getBoundingClientRect();
tipEl.style.left = Math.min(window.innerWidth - r.width - 8, e.clientX + 14) + "px";
tipEl.style.top = Math.min(window.innerHeight - r.height - 8, e.clientY + 14) + "px";
}
const hideTip = () => { if (tipEl) tipEl.hidden = true; };
function renderTargets() {
$("#valley-targets").innerHTML = TGT.map((t) => {
const c = E.TARGETS[t].color ? DV[E.TARGETS[t].color] : "--dr-any";
return `<button type="button" class="tchip${t.startsWith("bond_B") ? " featured" : ""}" data-vt="${t}" aria-pressed="${t === target}" style="--c: var(${c})"><span class="sw"></span>${esc(E.TARGETS[t].label)}</button>`;
}).join("");
$$("#valley-targets .tchip").forEach((b) => b.addEventListener("click", () => { target = b.dataset.vt; render(lastState); }));
}
function curve(A, B, bend) {
const mx = (A.x + B.x) / 2, my = (A.y + B.y) / 2, dx = B.x - A.x, dy = B.y - A.y;
return `M${A.x} ${A.y} Q${mx - dy * bend} ${my + dx * bend} ${B.x} ${B.y}`;
}
const isDeath = (r) => r.outcome === "Incinerated" || r.outcome === "Died before the hour";
function render(state) {
if (!state || !state.res || !$("#valley")) return;
lastState = state;
renderTargets();
const svg = $("#valley");
svg.setAttribute("viewBox", "0 0 1000 790");
svg.innerHTML = "";
defs(svg); paint(svg);
const T = E.TARGETS[target].fn;
const nodes = new Map(), edges = new Map();
state.runs.forEach((r) => {
const seq = path(r), hit = T(r) ? 1 : 0;
seq.forEach((id, i) => {
const n = nodes.get(id) || { id, n: 0, k: 0, runs: [], endDeaths: 0 };
n.n++; n.k += hit; n.runs.push(r);
if (i === seq.length - 1 && isDeath(r)) n.endDeaths++;
nodes.set(id, n);
if (i) { const key = seq[i - 1] + ">" + id; const e = edges.get(key) || { a: seq[i - 1], b: id, n: 0, k: 0 }; e.n++; e.k += hit; edges.set(key, e); }
});
});
const minN = state.minN || 10;
const ES = [...edges.values()];
const maxN = Math.max(1, ...ES.map((e) => e.n));
const pmax = Math.max(0.005, ...ES.filter((e) => e.n >= minN).map((e) => e.k / e.n));
const tcol = E.TARGETS[target].color ? INK[E.TARGETS[target].color] : "#8a3f6e";
$(".valley-shell").style.setProperty("--vt", cssVar(E.TARGETS[target].color ? DV[E.TARGETS[target].color] : "--dr-any"));
const colourOf = (e) => (e.n < minN ? "#a58a70" : mix(PAPER.trailLow, tcol, Math.pow(Math.min(1, e.k / e.n / pmax), 0.7)));
// known-but-untracked routes
const gK = el("g", { "pointer-events": "stroke" }, svg);
KNOWN.forEach(([a, b, label]) => {
const A = L[a], B = L[b];
const p = el("path", { d: curve(A, B, 0.18), fill: "none", stroke: PAPER.ink, "stroke-opacity": 0.45, "stroke-width": 2, "stroke-dasharray": "2 7", "stroke-linecap": "round" }, gK);
p.addEventListener("mousemove", (ev) => tip(ev, `<div class="t">${esc(label)}</div>A route the community has described. The form doesn't record it, so it has no numbers.`));
p.addEventListener("mouseleave", hideTip);
});
// trails
const gT = el("g", { filter: "url(#vm-brush)" }, svg);
ES.sort((a, b) => b.n - a.n).forEach((e) => {
const A = L[e.a], B = L[e.b];
if (!A || !B) return;
const w = 2 + 24 * Math.sqrt(e.n / maxN);
const d = curve(A, B, 0.08);
el("path", { d, fill: "none", stroke: PAPER.halo, "stroke-width": w + 3, "stroke-opacity": 0.45, "stroke-linecap": "round" }, gT);
const p = el("path", { d, fill: "none", stroke: colourOf(e), "stroke-width": w, "stroke-opacity": e.n >= minN ? 0.85 : 0.45, "stroke-linecap": "round" }, gT);
p.addEventListener("mousemove", (ev) => tip(ev, `<div class="t">${esc(name(e.a))} → ${esc(name(e.b))}</div>${e.n.toLocaleString()} riders<br>${esc(E.TARGETS[target].label)}: <b>${pct(e.k / e.n, 1)}</b> (${e.k}/${e.n})${e.n < minN ? "<br><i>Too few riders to read</i>" : ""}`));
p.addEventListener("mouseleave", hideTip);
});
// places
const gN = el("g", {}, svg);
const total = Math.max(1, ...[...nodes.values()].map((n) => n.n));
Object.entries(L).forEach(([id, P]) => {
const nd = nodes.get(id) || { n: 0, k: 0, runs: [], endDeaths: 0 };
const g = el("g", { class: "loc", tabindex: 0, role: "button", "aria-label": `${name(id)}: ${nd.n} riders` }, gN);
const sel = id === selected;
if (P.kind === "dragon") {
const r = 11 + 9 * Math.sqrt(nd.n / total);
el("circle", { cx: P.x, cy: P.y, r: r + 4, fill: PAPER.halo, "fill-opacity": 0.85, stroke: sel ? "#1d0a12" : INK[P.colour], "stroke-width": sel ? 3 : 1.6 }, g);
el("circle", { cx: P.x, cy: P.y, r, fill: "#fbf0d6", stroke: INK[P.colour], "stroke-width": 2.2 }, g);
el("path", { d: WING, fill: INK[P.colour], transform: `translate(${P.x - r * 0.82} ${P.y - r * 0.5}) scale(${(r * 1.64) / 100})` }, g);
} else if (P.kind === "start") {
el("path", { d: `M${P.x} ${P.y - 11} L${P.x + 9} ${P.y} L${P.x} ${P.y + 11} L${P.x - 9} ${P.y} Z`, fill: sel ? "#1d0a12" : PAPER.ink, stroke: PAPER.halo, "stroke-width": 2 }, g);
} else {
const r = P.kind === "small" ? 5 : 7 + 5 * Math.sqrt(nd.n / total);
el("circle", { cx: P.x, cy: P.y, r: r + 2.5, fill: PAPER.halo, stroke: sel ? "#1d0a12" : "none", "stroke-width": 2.5 }, g);
el("circle", { cx: P.x, cy: P.y, r, fill: P.kind === "small" ? "#7a5236" : PAPER.ink }, g);
}
// deaths that ended here
if (nd.endDeaths) {
const bx = P.x + (P.kind === "dragon" ? 18 : 10), by = P.y - (P.kind === "dragon" ? 16 : 10);
el("circle", { cx: bx, cy: by, r: 8.5, fill: PAPER.death, stroke: PAPER.halo, "stroke-width": 1.4 }, g);
const t = el("text", { x: bx, y: by + 3.2, "text-anchor": "middle", "font-size": 8.5, fill: "#fff3e0", "font-family": "var(--font-data)" }, g);
t.textContent = nd.endDeaths > 999 ? Math.round(nd.endDeaths / 100) / 10 + "k" : nd.endDeaths;
}
// labels (first sightings are labelled by their dragon glyph and tooltip only)
if (!P.first) {
const pos = P.lab || "right", off = P.kind === "dragon" ? 24 : 12;
let x = P.x, y = P.y + 4, anchor = "middle";
if (pos === "right") { x = P.x + off; anchor = "start"; }
else if (pos === "left") { x = P.x - off; anchor = "end"; }
else if (pos === "below") y = P.y + off + 12;
else if (pos === "above") y = P.y - off - 18;
const t1 = el("text", { x, y, "text-anchor": anchor, "font-family": "var(--font-display)", "font-size": P.kind === "small" ? 12.5 : 15, fill: PAPER.ink, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3.5, "stroke-linejoin": "round" }, g);
t1.textContent = P.name;
if (P.kind !== "small") {
const t2 = el("text", { x, y: y + 14, "text-anchor": anchor, "font-size": 11, fill: PAPER.ink, "fill-opacity": 0.85, "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3, "font-family": "var(--font-body)" }, g);
t2.textContent = `${nd.n.toLocaleString()} riders${P.sub ? " · " + P.sub : ""}`;
}
}
const pick = () => { selected = id; render(state); };
g.addEventListener("click", pick);
g.addEventListener("keydown", (ev) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); pick(); } });
g.addEventListener("mousemove", (ev) => tip(ev, `<div class="t">${esc(name(id))}</div>${nd.n.toLocaleString()} riders${nd.endDeaths ? ` · ${nd.endDeaths} died here` : ""}<br>${esc(E.TARGETS[target].label)}: ${pct(nd.n ? nd.k / nd.n : null, 1)}`));
g.addEventListener("mouseleave", hideTip);
});
// sighting captions per direction
["West", "Center", "East"].forEach((dname) => {
const xs = Object.keys(L).filter((k) => k.startsWith(`see:${dname}:`)).map((k) => L[k]);
const cx = xs.reduce((a, p) => a + p.x, 0) / xs.length, cy = Math.min(...xs.map((p) => p.y)) - 26;
const t = el("text", { x: cx, y: cy, "text-anchor": "middle", "font-size": 10.5, "letter-spacing": "0.12em", fill: PAPER.ink, "fill-opacity": 0.8, "font-family": "var(--font-label)", "paint-order": "stroke", stroke: PAPER.halo, "stroke-width": 3 }, svg);
t.textContent = "FIRST DRAGON · ROLL";
});
// compass
const cr = el("g", { transform: "translate(52 726)", "aria-hidden": "true" }, svg);
el("circle", { r: 24, fill: PAPER.halo, "fill-opacity": 0.7, stroke: PAPER.ink, "stroke-opacity": 0.5 }, cr);
el("path", { d: "M0 -20 L5 0 L0 20 L-5 0 Z", fill: PAPER.ink }, cr);
const nT = el("text", { y: -28, "text-anchor": "middle", "font-size": 11, fill: PAPER.ink, "font-family": "var(--font-display)" }, cr); nT.textContent = "N";
overlay(svg);
renderCard(nodes, edges);
$("#valley-legend").innerHTML = `<span>Trail width = riders who walked it</span>
<span style="display:inline-flex;gap:6px;align-items:center">0% <span class="ramp" style="background:linear-gradient(90deg, ${PAPER.trailLow}, ${tcol})"></span> ${pct(pmax)}</span>
<span><span style="display:inline-block;width:12px;height:12px;border-radius:50%;background:${PAPER.death};vertical-align:-2px"></span> riders who died at that spot</span>
<span>Dotted = described by the community, not tracked by the form</span>
<span>Faded = fewer than ${minN} riders · positions are illustrative</span>`;
}
function name(id) {
const P = L[id];
if (!P) return id;
if (P.first) { const [, d, c] = id.split(":"); return `${c} dragon (first sighting, ${d === "Center" ? "forest centre" : d.toLowerCase()})`; }
return P.name;
}
function renderCard(nodes, edges) {
const P = L[selected], nd = nodes.get(selected) || { n: 0, k: 0, runs: [], endDeaths: 0 };
const card = $("#loc-card");
card.style.setProperty("--lc", P.colour ? cssVar(DV[P.colour]) : cssVar("--accent"));
const w = E.wilson(nd.k, nd.n);
const out = [...edges.values()].filter((e) => e.a === selected).sort((a, b) => b.n - a.n);
const outN = out.reduce((a, e) => a + e.n, 0);
const ends = {};
nd.runs.forEach((r) => {
const k = r.outcome === "Bonded" ? "Bonded " + r.outcome_color : r.outcome === "Incinerated" ? "Incinerated" : r.outcome === "Died before the hour" ? "Died before the hour" : "Not recorded";
ends[k] = (ends[k] || 0) + 1;
});
const order = ["Bonded Red", "Bonded Orange", "Bonded Brown", "Bonded Green", "Bonded Blue", "Bonded Black", "Incinerated", "Died before the hour", "Not recorded"];
const bar = (label, n, of, c) => `<div class="bar" style="--c:${c}"><span>${esc(label)}</span><i style="width:${(100 * n) / Math.max(1, of)}%"></i><span>${n} · ${pct(n / Math.max(1, nd.n))}</span></div>`;
const maxEnd = Math.max(1, ...Object.values(ends));
const P2 = P.first ? { desc: "The game rolls which dragon finds you first. Lower your eyes and keep still." } : P;
card.innerHTML = `<span class="eyebrow">${P.kind === "dragon" ? "A dragon waits here" : "Selected place"}</span><h3>${esc(name(selected))}</h3>
<p class="small muted">${esc(P2.desc || "")}</p>
<p class="small"><b>${nd.n.toLocaleString()}</b> logged runs reached this spot${nd.endDeaths ? `, and <b style="color:var(--ember)">${nd.endDeaths}</b> died here` : ""}. ${esc(E.TARGETS[target].label)}: <b>${pct(w.p, 1)}</b> of them (95% CI ${pct(w.lo, 1)}–${pct(w.hi, 1)}).</p>
${out.length ? `<span class="eyebrow">Where they went next</span><div class="bars">${out.map((e) => bar(name(e.b).replace(/ \(first sighting.*\)/, " first"), e.n, out[0].n, L[e.b].colour ? `var(${DV[L[e.b].colour]})` : "var(--accent)")).join("")}</div>` : ""}
<span class="eyebrow">How those runs ended</span><div class="bars">${order.filter((k) => ends[k]).map((k) => bar(k, ends[k], maxEnd, k.startsWith("Bonded") ? `var(${DV[k.split(" ")[1]]})` : k === "Incinerated" ? "var(--ember)" : "var(--faint)")).join("") || '<span class="small muted">No runs.</span>'}</div>`;
}
// shared with the route planner (planner.js), which paints the same valley and draws the solver's options on it
const paintBase = (svg) => { defs(svg); paint(svg); };
window.ValleyMap = { render, path, places: L, paintBase, finish: overlay, name, curve, INK, PAPER, WING };
})();
+32
View File
@@ -0,0 +1,32 @@
// Assemble the static Atlas site into dist/ (no dependencies).
// node site/build.js [outDir]
const fs = require("fs");
const path = require("path");
const root = path.resolve(__dirname, "..");
const out = path.resolve(root, process.argv[2] || "dist");
const copy = (from, to) => {
fs.mkdirSync(path.dirname(path.join(out, to)), { recursive: true });
fs.copyFileSync(path.join(root, from), path.join(out, to));
};
fs.rmSync(out, { recursive: true, force: true });
for (const f of fs.readdirSync(path.join(root, "site/atlas"))) copy(`site/atlas/${f}`, f);
// The page is written as an Artifact body (the artifact host adds the document skeleton). For GitHub Pages and
// local serving, give it its own doctype, charset and viewport.
{
const p = path.join(out, "index.html");
const html = fs.readFileSync(p, "utf8");
if (!/^\s*<!doctype/i.test(html))
fs.writeFileSync(p, `<!doctype html>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n${html}`);
}
copy("core/engine.js", "engine.js");
copy("core/graph.js", "graph.js");
copy("core/solver.js", "solver.js");
for (const f of ["form_responses.json", "register.json", "graph.json", "policy.json"]) copy(`data/public/${f}`, `data/${f}`);
// Source files shown in the page's "view the code" panel
copy("core/python/clean.py", "python/clean.py");
for (const f of ["analyze.py", "stats_core.py"]) copy(`analysis/stats/${f}`, `python/${f}`);
copy("README.md", "README.md");
fs.writeFileSync(path.join(out, ".nojekyll"), "");
console.log(`Site built in ${path.relative(root, out) || "."}`);
+42
View File
@@ -0,0 +1,42 @@
"""check_colours.py: are the dragon colours (valley.js INK, index.html --dr-*) still distinguishable?
python site/qa/check_colours.py
"""
"""Pairwise CIEDE2000 between dragon colours, normal vision and simulated colour-vision deficiencies (Machado 2009, severity 1),
plus contrast against the backgrounds they sit on."""
import itertools, sys
import numpy as np
from skimage.color import rgb2lab, deltaE_ciede2000
MAP = {"Red": "#cc3346", "Orange": "#e08a2a", "Brown": "#4e3020", "Green": "#2f8f6f", "Blue": "#2a58b8", "Black": "#22182a"}
UI = {"Red": "#e8435e", "Orange": "#ff9533", "Brown": "#d1a47a", "Green": "#3fc0a8", "Blue": "#7ea6ff", "Black": "#e0d8ea"}
if len(sys.argv) > 1: # candidate palettes passed as name=hex,...
for arg in sys.argv[1:]:
k, v = arg.split(":", 1)
d = dict(x.split("=") for x in v.split(","))
(MAP if k == "map" else UI).update(d)
BG = {"map paper": "#e9c88f", "map canopy": "#6c6b40", "ui dark": "#210f19"}
M = { # Machado et al. 2009, severity 1.0, applied in linear RGB
"protan": [[0.152286, 1.052583, -0.204868], [0.114503, 0.786281, 0.099216], [-0.003882, -0.048116, 1.051998]],
"deutan": [[0.367322, 0.860646, -0.227968], [0.280085, 0.672501, 0.047413], [-0.011820, 0.042940, 0.968881]],
"tritan": [[1.255528, -0.076749, -0.178779], [-0.078411, 0.930809, 0.147602], [0.004733, 0.691367, 0.303900]],
}
def rgb(h): h = h.lstrip("#"); return np.array([int(h[i:i + 2], 16) for i in (0, 2, 4)]) / 255
def lin(c): return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
def unlin(c): c = np.clip(c, 0, 1); return np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1 / 2.4) - 0.055)
def sim(c, kind): return c if kind == "normal" else unlin(np.array(M[kind]) @ lin(c))
def lab(c): return rgb2lab(c.reshape(1, 1, 3)).reshape(3)
def de(a, b): return float(deltaE_ciede2000(lab(a), lab(b)))
def lum(c): l = lin(c); return 0.2126 * l[0] + 0.7152 * l[1] + 0.0722 * l[2]
def contrast(a, b): x, y = sorted([lum(a), lum(b)], reverse=True); return (x + 0.05) / (y + 0.05)
for name, P in [("MAP (on paper)", MAP), ("UI (on dark)", UI)]:
print(f"\n== {name}: pairs with CIEDE2000 < 20 under any vision (flag), worst first")
rows = []
for a, b in itertools.combinations(P, 2):
ds = {k: de(sim(rgb(P[a]), k), sim(rgb(P[b]), k)) for k in ["normal", "protan", "deutan", "tritan"]}
rows.append((min(ds.values()), a, b, ds))
for m, a, b, ds in sorted(rows):
if m < 20: print(f" {a:6} vs {b:6} " + " ".join(f"{k} {v:5.1f}" for k, v in ds.items()))
print(" contrast vs backgrounds:")
for c in P:
print(f" {c:6} " + " ".join(f"{bg} {contrast(rgb(P[c]), rgb(h)):.1f}" for bg, h in BG.items() if (bg.startswith('map') if P is MAP else bg.startswith('ui'))))
+72
View File
@@ -0,0 +1,72 @@
// QA crawl: every tab, text dump, links, buttons, console errors. node crawl.js <outdir>
const { chromium } = require("playwright");
const fs = require("fs");
// screenshots and logs go to the folder given, or a temp folder (never a folder named "undefined" in the repo)
const OUT = process.argv[2] || require("path").join(require("os").tmpdir(), "atlas-qa");
require("fs").mkdirSync(OUT, { recursive: true });
const BASE = "http://localhost:8765/";
(async () => {
const b = await chromium.launch();
const log = { errors: [], links: [], buttons: [], tabs: {} };
for (const [vpName, vp] of [["desktop", { width: 1440, height: 1000 }], ["phone", { width: 390, height: 844 }]]) {
const p = await b.newPage({ viewport: vp });
p.on("pageerror", (e) => log.errors.push(`${vpName} pageerror: ${e.message}`));
p.on("console", (m) => { if (m.type() === "error" && !/net::ERR|Failed to load resource/.test(m.text())) log.errors.push(`${vpName} console: ${m.text()}`); });
for (const t of ["valley", "odds", "dragons", "deep", "data"]) {
await p.goto(BASE + "#" + t); await p.waitForTimeout(t === "valley" ? 2500 : 1800);
// open every <details> so hidden text is reviewed too
await p.$$eval(`#panel-${t} details`, (ds) => ds.forEach((d) => (d.open = true)));
await p.waitForTimeout(300);
await p.screenshot({ path: `${OUT}/${vpName}-${t}.png`, fullPage: true });
if (vpName === "desktop") {
log.tabs[t] = await p.evaluate((t) => document.querySelector("#panel-" + t).innerText, t);
const links = await p.$$eval(`#panel-${t} a[href], header a[href], footer a[href]`, (as) => as.map((a) => ({ text: a.innerText.trim().slice(0, 60), href: a.getAttribute("href") })));
links.forEach((l) => log.links.push({ tab: t, ...l }));
const btns = await p.$$eval(`#panel-${t} button`, (bs) => bs.map((x) => x.innerText.trim().replace(/\s+/g, " ").slice(0, 50)));
log.buttons.push({ tab: t, n: btns.length, sample: [...new Set(btns)].slice(0, 40) });
}
// overflow check
const sw = await p.evaluate(() => document.documentElement.scrollWidth);
if (sw > vp.width + 1) log.errors.push(`${vpName} ${t}: horizontal overflow ${sw}px`);
}
await p.close();
}
// click every button in every tab (desktop), checking for errors after each
const p = await b.newPage({ viewport: { width: 1440, height: 1000 } });
p.on("pageerror", (e) => log.errors.push(`click pageerror: ${e.message}`));
for (const t of ["valley", "odds", "dragons", "deep", "data"]) {
await p.goto(BASE + "#" + t); await p.waitForTimeout(2000);
const n = await p.$$eval(`#panel-${t} button`, (bs) => bs.length);
let clicked = 0;
for (let i = 0; i < Math.min(n, 120); i++) {
const bs = await p.$$(`#panel-${t} button`);
if (!bs[i]) continue;
const vis = await bs[i].isVisible();
if (!vis) continue;
const label = (await bs[i].innerText()).trim().slice(0, 40);
if (/download|copy/i.test(label)) continue;
try { await bs[i].click({ timeout: 1500 }); clicked++; await p.waitForTimeout(120); } catch (e) { log.errors.push(`${t}: could not click "${label}": ${e.message.split("\n")[0]}`); }
const cur = await p.evaluate(() => location.hash);
if (!cur.startsWith("#" + t)) { await p.goto(BASE + "#" + t); await p.waitForTimeout(1200); }
}
log.tabs[t + "_clicked"] = clicked;
}
// in-page links
await p.goto(BASE); await p.waitForTimeout(2000);
for (const l of log.links.filter((x) => x.href.startsWith("#"))) {
await p.goto(BASE + "#" + l.tab); await p.waitForTimeout(800);
const el = await p.$(`#panel-${l.tab} a[href="${l.href}"]`);
if (!el || !(await el.isVisible())) continue;
await el.click(); await p.waitForTimeout(800);
const sel = await p.evaluate(() => document.querySelector("[role=tab][aria-selected=true]").id);
const target = l.href.slice(1).split("/")[0];
const exists = await p.evaluate((id) => !!document.getElementById(id) || ["valley","odds","dragons","deep","data"].includes(id), target);
l.result = `${sel}${exists ? "" : " MISSING TARGET"}`;
}
fs.writeFileSync(`${OUT}/log.json`, JSON.stringify(log, null, 1));
for (const [t, txt] of Object.entries(log.tabs)) if (typeof txt === "string") fs.writeFileSync(`${OUT}/text-${t}.txt`, txt);
console.log("errors:", log.errors.length, log.errors.slice(0, 20));
console.log("clicked:", Object.entries(log.tabs).filter(([k]) => k.endsWith("_clicked")));
console.log("links:"); log.links.forEach((l) => console.log(" ", l.tab, "|", l.text, "|", l.href, "|", l.result || ""));
await b.close();
})();
+44
View File
@@ -0,0 +1,44 @@
// Valley map QA: for idle and every dragon/route, find text or labels that overlap, fall outside the map, or are too faint.
const { chromium } = require("playwright");
// screenshots and logs go to the folder given, or a temp folder (never a folder named "undefined" in the repo)
const OUT = process.argv[2] || require("path").join(require("os").tmpdir(), "atlas-qa");
require("fs").mkdirSync(OUT, { recursive: true });
(async () => {
const b = await chromium.launch();
const p = await b.newPage({ viewport: { width: 1440, height: 1000 } });
const states = [["idle", "#valley"]];
for (const c of ["red", "orange", "brown", "green", "blue", "black"]) states.push([c, "#valley/" + c]);
const extra = { blue: ["shadow-Blue"], red: ["tree-Red"], orange: ["tree-Greens"], brown: ["tree-Greens"] };
for (const id of (process.env.POINTS || "dir:Center,comp:Alone,scream,bully,wounded,hour,tree,valley,stream,meadow").split(",")) states.push(["at-" + id, "#valley/at/" + encodeURIComponent(id)]);
for (const [c, encs] of Object.entries(extra)) encs.forEach((e) => states.push([c + "/" + e, `#valley/${c}/${e}`]));
for (const [name, hash] of states) {
await p.goto("http://localhost:8765/" + hash); await p.waitForTimeout(1800);
const res = await p.evaluate(() => {
const svg = document.querySelector("#ex-map"), S = svg.getBoundingClientRect();
const items = [];
svg.querySelectorAll("text").forEach((t) => {
const r = t.getBoundingClientRect();
if (!r.width) return;
// walk up for opacity
let op = 1; for (let e = t; e && e !== svg; e = e.parentElement) op *= parseFloat(getComputedStyle(e).opacity || 1) * parseFloat(e.getAttribute("fill-opacity") || 1);
items.push({ kind: "text", txt: t.textContent.trim(), r: { l: r.left, t: r.top, rr: r.right, b: r.bottom }, op });
});
const out = [], over = [];
items.forEach((a) => { if (a.r.l < S.left - 1 || a.r.rr > S.right + 1 || a.r.t < S.top - 1 || a.r.b > S.bottom + 1) out.push(a.txt); });
for (let i = 0; i < items.length; i++) for (let j = i + 1; j < items.length; j++) {
const A = items[i].r, B = items[j].r;
const ix = Math.min(A.rr, B.rr) - Math.max(A.l, B.l), iy = Math.min(A.b, B.b) - Math.max(A.t, B.t);
if (ix > 3 && iy > 3 && items[i].txt !== items[j].txt) over.push(`"${items[i].txt}" × "${items[j].txt}"`);
}
const dragons = [...svg.querySelectorAll(".ex-dragon")].map((d) => ({ l: d.getAttribute("aria-label") || "twin", op: +d.getAttribute("opacity") })).filter((d) => d.op < 0.3);
const card = document.querySelector(".ex-route-card.on") || (document.querySelector(".ex-from") && document.querySelector(".ex-from"));
return { out, over, faint: dragons.map((d) => `${d.l.split(".")[0]} ${d.op}`), focus: card ? card.innerText.replace(/\s+/g, " ").slice(0, 160) : "" };
});
console.log(`\n[${name}] ${res.focus}`);
if (res.out.length) console.log(" outside:", res.out.join(" | "));
if (res.over.length) console.log(" overlaps:", [...new Set(res.over)].join(" | "));
if (res.faint.length) console.log(" faint (<0.3):", res.faint.join(" | "));
await p.locator("#ex-map").screenshot({ path: `${OUT}/map-${name.replace(/[/:]/g, "_")}.png` });
}
await b.close();
})();