/* HK Landscape Sheets: UI wiring. The screen is one A1 sheet; the four drawings are flipped
from the drawing register in the title strip. Engines: site.js, tree.js, board.js; drawings: sheet.js. */
'use strict';
const $ = s => document.querySelector(s);
const $$ = s => Array.from(document.querySelectorAll(s));
const LS_KEY = 'hkpb.v1', LS_WORK = 'hkpb.v1.work'; // unchanged keys, so work saved in v1 still opens
const SHEETS = {
site: { no: 'LP-01', zh: '地盤分析', en: 'SITE ANALYSIS' },
board: { no: 'LP-02', zh: '種植平面', en: 'PLANTING PLAN' },
tree: { no: 'LP-03', zh: '樹種圖則', en: 'TREE STUDIES' },
why: { no: 'LP-04', zh: '生長解構', en: 'GROWTH ANATOMY' },
};
const ORDER = ['site', 'board', 'tree', 'why'];
const MONTH_EN = ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'];
const S = {
tab: 'site', comp: null, sun: null, scales: {}, mview: { site: 0, board: 0, tree: 0, why: 0 },
siteUi: { layer: 'shadow', wind: true, viewMode: 'off', doy: 355, time: 10 },
tree: { sp: 'bombax', age: 25, seed: 42, month: 3, lean: 0, bend: 0, irr: 0, jit: 0, light: 0, laz: 0, miss: 0, style: 'wash', fol: 0.7, int: 0.7 },
why: { sp: 'bombax', mode: 'both', fade: 0.35, idx: 0 },
board: { sel: null, ghost: null, ghostFrom: null, highlight: [], hoverNote: null, rtab: 'check', filter: 'all', q: '', checks: [], notes: [], codes: null, tool: 'select', armed: null, measure: null, pal: 'plants' },
};
const isMob = () => window.innerWidth <= 760;
/* ---------- utilities ---------- */
function fit(cv) {
const dpr = Math.min(2, window.devicePixelRatio || 1);
let w, h;
if (isMob() && cv.closest('.cvwrap')) { w = Math.max(50, cv.clientWidth || cv.parentElement.clientWidth); h = Math.round(w * parseFloat(cv.dataset.arm || 0.7)); cv.style.height = h + 'px'; }
else { cv.style.height = ''; const p = cv.parentElement; w = Math.max(50, p.clientWidth); h = Math.max(50, p.clientHeight); }
if (cv.width !== Math.round(w * dpr) || cv.height !== Math.round(h * dpr)) { cv.width = Math.round(w * dpr); cv.height = Math.round(h * dpr); }
const ctx = cv.getContext('2d'); ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
return { ctx, w, h };
}
function fitFixed(cv) { // small canvases with a fixed CSS size (mini scale bar, north point)
const dpr = Math.min(2, window.devicePixelRatio || 1), w = cv.clientWidth || cv.width, h = cv.clientHeight || cv.height;
cv.width = Math.round(w * dpr); cv.height = Math.round(h * dpr);
const ctx = cv.getContext('2d'); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, w, h);
return { ctx, w, h };
}
function toast(msg) { let t = $('.toast'); if (!t) { t = document.createElement('div'); t.className = 'toast'; document.body.appendChild(t); } t.textContent = msg; t.classList.add('on'); clearTimeout(t._h); t._h = setTimeout(() => t.classList.remove('on'), 2600); }
function esc(s) { return String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); }
function srcLink(k) { const s = SOURCES[k]; if (!s) return ''; const t = esc(s.url ? (s.en || s.t) : s.t); return s.url ? `${t}` : `${t}`; }
function doyToMD(doy) { const d = new Date(Date.UTC(2026, 0, doy)); return [d.getUTCMonth() + 1, d.getUTCDate()]; }
function hhmm(h) { const m = Math.round(h * 60); return `${String(Math.floor(m / 60)).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`; }
function segInit(id, cb) { $$(`#${id} button`).forEach(b => b.addEventListener('click', () => { $$(`#${id} button`).forEach(x => x.classList.toggle('on', x === b)); cb(b.dataset.v); })); }
function segSet(id, v) { $$(`#${id} button`).forEach(x => x.classList.toggle('on', x.dataset.v === v)); }
function lsGet(k) { try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : null; } catch (e) { return null; } }
function lsSet(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); return true; } catch (e) { return false; } }
function ymd(iso) { const [y, m, d] = (iso || new Date().toISOString()).slice(0, 10).split('-'); return `${d}.${m}.${y}`; }
/* the standard scale a drawing of this on-screen size would take on the printed A1 sheet */
function scaleLabel(cv, pxPerM) {
const sheetW = $('#sheet').clientWidth || 1200, wpx = cv.parentElement.clientWidth || cv.clientWidth;
if (isMob()) return '1:' + niceScale(wpx / pxPerM, 841 * 0.5) + ' @A1';
return '1:' + niceScale(wpx / pxPerM, wpx / sheetW * 841) + ' @A1';
}
function drawMini(barId, northId, pxPerM, north) {
const b = $(barId); if (b) { const { ctx } = fitFixed(b); scaleBar(ctx, 4, 12, pxPerM, isMob() ? 100 : 140); }
const n = $(northId); if (n) { const { ctx, w, h } = fitFixed(n); northPoint(ctx, w / 2, h / 2 + 3, 8, north); }
}
/* ---------- composition state ---------- */
/* v2 saves have site.W/D + four sides; v3 saves have site.poly + buildings. Both load (setComp migrates). */
function validComp(c) { return !!(c && c.site && Array.isArray(c.items) && c.eye && (typeof c.site.W === 'number' || (Array.isArray(c.site.poly) && c.site.poly.length >= 3))); }
function defaultSection(c) {
const main = c.items.find(i => i.role === 'main' && plantOf(i)), y = main ? main.y : c.site.D / 2;
return { x1: -0.8, y1: y, x2: c.site.W + 0.8, y2: y };
}
function setComp(c) {
S.comp = c; S.board.sel = null; S.board.ghost = null; S.board.measure = null;
c.items.forEach(i => { if (!i.uid) i.uid = newUid(); if (i.kind === 'plant' && !libById(i.id)) i.id = 'blakeana'; });
c.site.views = c.site.views || [];
migrateSite(c.site); normalizeComp(c);
SE.sel = null; SE.selV = null; SE.draft = null; SE.drag = null; SE.frozen = null;
if (!c.section) c.section = defaultSection(c);
if (!c.created) c.created = new Date().toISOString().slice(0, 10);
recomputeSun(); syncSiteInputs(); syncBoardInputs();
}
let _sunT = null;
function recomputeSun() { S.sun = computeSun(S.comp.site); }
function recomputeSunSoon(after) { clearTimeout(_sunT); _sunT = setTimeout(() => { recomputeSun(); after && after(); }, 120); }
function saveWork() { lsSet(LS_WORK, S.comp); }
/* ---------- pop-overs ---------- */
function closePops(except) { $$('.pop').forEach(p => { if (p.id !== except) p.hidden = true; }); }
function openPop(id, x, y) {
closePops(id); const p = $('#' + id); p.hidden = false;
if (isMob()) return p;
const r = p.getBoundingClientRect(), W = window.innerWidth, H = window.innerHeight;
let left = x + 16, top = y - 14;
if (left + r.width > W - 8) left = x - r.width - 16;
if (top + r.height > H - 8) top = H - r.height - 8;
p.style.left = Math.max(8, left) + 'px'; p.style.top = Math.max(8, top) + 'px';
return p;
}
function popAtEl(id, el) { const r = el.getBoundingClientRect(); return openPop(id, r.right - 10, r.bottom + 10); }
/* ================= LP-01 SITE ANALYSIS ================= */
/* Site editing works like a CAD tool: V select (drag vertices, click an edge's + to insert, right-click or × to delete),
B draw boundary, H place building. Coordinates in plan metres; the polygon is re-normalised to start at (0,0). */
const SE = { sel: null, selV: null, hot: null, draft: null, drag: null, cursor: null, snapped: false, tip: '', lastDown: null, frozen: null };
const SNAP = { grid: true, ang: false };
const SITE_TIP = {
off: '', good: '好景:按花園的邊加標記;再按標記可刪除', screen: '遮擋:按花園的邊加標記;再按標記可刪除',
boundary: '畫地界:逐點按,雙擊、按回 P1 或按 Enter 完成;按住拖可畫矩形。Esc 取消',
bldg: '放建築:按住拖畫矩形,或逐點按畫多邊形(雙擊或 Enter 完成)。Esc 取消',
};
const isCoarse = () => isMob() || (window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
const handleR = () => isCoarse() ? 13 : 7;
const shapeOf = sel => !sel ? null : sel === 'site' ? S.comp.site.poly : ((S.comp.site.buildings.find(b => b.id === sel) || {}).poly || null);
const bldgById = id => S.comp.site.buildings.find(b => b.id === id);
function bldgGap(b) {
const s = S.comp.site;
if (b.poly.some(([x, y]) => inSite(s, x, y)) || s.poly.some(([x, y]) => pointInPoly(x, y, b.poly))) return 0;
const g = polyGap(b.poly, s.poly); return g ? g.d : 0;
}
function syncSiteInputs() {
const s = S.comp.site;
$('#s-W').value = s.W; $('#s-D').value = s.D; $('#s-north').value = s.north; $('#s-north-o').textContent = s.north + '°';
$('#s-podium').checked = !!s.podium; $('#s-soil').value = s.soil; $('#s-level').value = s.level ?? 0;
$('#s-area').textContent = `面積 ${Math.abs(polyArea(s.poly)).toFixed(1)} m²,${s.poly.length} 點,周界 ${polyPerim(s.poly).toFixed(1)} m`;
const E = siteEdges(s);
$('#s-verts').innerHTML = s.poly.map(([x, y], i) => `
| ${ptLabel(i)} | | | ${fmt(E[i].len)} | |
`).join('');
$$('#s-verts input').forEach(inp => inp.addEventListener('change', () => {
const v = parseFloat(inp.value); if (!isFinite(v)) { syncSiteInputs(); return; }
const P = S.comp.site.poly.map(p => p.slice()); P[+inp.dataset.i][+inp.dataset.c] = v; setSitePoly(P);
}));
$$('#s-verts button[data-del]').forEach(b => b.addEventListener('click', () => delVertex('site', +b.dataset.del)));
$('#s-bldgs').innerHTML = s.buildings.map(b => ` | | ${fmt(bldgGap(b))} | |
`).join('') || '| 未有建築。用「放建築」工具畫。 |
';
$$('#s-bldgs tr[data-id]').forEach(tr => {
const b = bldgById(tr.dataset.id);
tr.querySelectorAll('input').forEach(inp => inp.addEventListener('change', () => {
if (inp.dataset.f === 'h') { const v = parseFloat(inp.value); b.h = isFinite(v) ? Math.max(0, Math.min(400, v)) : 0; inp.value = b.h; siteChanged(); }
else { b.name = inp.value.trim() || b.name; siteChanged(true); }
}));
tr.querySelector('button').addEventListener('click', () => delBuilding(b.id));
tr.addEventListener('mouseenter', () => { SE.hot = b.id; if (S.tab === 'site') drawSiteOnly(); });
tr.addEventListener('mouseleave', () => { SE.hot = null; if (S.tab === 'site') drawSiteOnly(); });
});
}
function siteChanged(noSun) {
saveWork();
const after = () => { renderTab(S.tab); updateTitleBlock(); };
if (noSun) after(); else recomputeSunSoon(after);
}
/* geometry edits keep the polygon normalised, the plants inside it and each view on its nearest edge */
function reattachViews(site, pts) { site.views.forEach((v, k) => { const c = closestOnPoly(site.poly, pts[k][0], pts[k][1]); v.edge = c.edge; v.t = Math.max(0.05, Math.min(0.95, c.t)); }); }
function geometryDone() {
const c = S.comp; normalizeComp(c);
c.items.forEach(i => { [i.x, i.y] = clampIn(c.site, i.x, i.y, 0.1); });
[c.eye.x, c.eye.y] = clampIn(c.site, c.eye.x, c.eye.y, 0);
syncSiteInputs(); siteChanged();
}
function setSitePoly(P, keepViews = true) {
const s = S.comp.site;
if (polySelfX(P)) { toast('地界的邊不可以交叉'); syncSiteInputs(); return false; }
const vp = s.views.map(v => viewPos(s, v));
s.poly = orientPos(P.map(p => [+p[0], +p[1]]));
if (keepViews) reattachViews(s, vp);
geometryDone(); return true;
}
function delVertex(sel, i) {
const P = shapeOf(sel); if (!P || P.length <= 3) { toast('最少要 3 點'); return; }
const Q = P.filter((_, k) => k !== i); SE.selV = null;
if (sel === 'site') { if (setSitePoly(Q)) toast(`已刪除 ${ptLabel(i)}`); }
else { bldgById(sel).poly = Q; syncSiteInputs(); siteChanged(); toast('已刪除一點'); }
}
function insertVertex(sel, i, p) {
if (sel === 'site') { const s = S.comp.site, vp = s.views.map(v => viewPos(s, v)); s.poly.splice(i + 1, 0, p); reattachViews(s, vp); }
else bldgById(sel).poly.splice(i + 1, 0, p);
}
function delBuilding(id) {
const s = S.comp.site, b = bldgById(id); if (!b) return;
s.buildings = s.buildings.filter(q => q.id !== id); if (SE.sel === id) { SE.sel = null; SE.selV = null; }
closePops(); syncSiteInputs(); siteChanged(); toast(`已刪除 ${b.name}`);
}
function rotateBuilding(id, deg) { const b = bldgById(id); if (!b) return; b.poly = rotatePoly(b.poly, deg).map(([x, y]) => [Math.round(x * 1000) / 1000, Math.round(y * 1000) / 1000]); syncSiteInputs(); siteChanged(); }
function setSiteTool(v) {
S.siteUi.viewMode = v; segSet('s-viewmode', v); SE.draft = null; SE.tip = ''; SE.drag = null; SE.frozen = null;
if (v !== 'off') { SE.selV = null; }
$('#site-plan').style.cursor = v === 'off' ? 'default' : 'crosshair';
$('#s-tip').textContent = SITE_TIP[v] || '';
if (S.tab === 'site' && S.comp) drawSiteOnly();
}
/* snapping: existing vertices (8 px), then 15-degree angles from the previous point, then the 0.5 m grid */
function snapPt(x, y, from, tx, skip) {
SE.snapped = false;
const r = (isCoarse() ? 12 : 8) / tx.sc, site = S.comp.site, lists = [site.poly, ...site.buildings.map(b => b.poly)];
if (SE.draft) lists.push(SE.draft.pts.slice(0, -1));
for (const P of lists) for (let k = 0; k < P.length; k++) { if (skip && skip.P === P && skip.i === k) continue; const q = P[k]; if (Math.hypot(q[0] - x, q[1] - y) < r) { SE.snapped = true; return [q[0], q[1]]; } }
if (SNAP.ang && from) {
let a = Math.atan2(y - from[1], x - from[0]), L = Math.hypot(x - from[0], y - from[1]);
a = Math.round(a / (15 * D2R)) * 15 * D2R; L = SNAP.grid ? Math.round(L * 2) / 2 : Math.round(L * 100) / 100;
return [Math.round((from[0] + Math.cos(a) * L) * 1000) / 1000, Math.round((from[1] + Math.sin(a) * L) * 1000) / 1000];
}
if (SNAP.grid) return [Math.round(x * 2) / 2, Math.round(y * 2) / 2];
return [Math.round(x * 100) / 100, Math.round(y * 100) / 100];
}
const angOf = (a, b) => ((Math.atan2(-(b[1] - a[1]), b[0] - a[0]) / D2R) + 360) % 360; // drawing convention: from +x, anticlockwise
const segTip = (a, b) => `L ${mmTxt(Math.hypot(b[0] - a[0], b[1] - a[1]))} mm\n∠ ${angOf(a, b).toFixed(1)}°`;
function editOverlay() {
const tool = S.siteUi.viewMode, ed = { handles: [], draft: SE.draft, cursor: null, tip: SE.tip, snapped: SE.snapped };
if (tool === 'off' && SE.sel) { const P = shapeOf(SE.sel); if (P) ed.handles.push({ P, selV: SE.selV, r: handleR() }); }
if ((tool === 'boundary' || tool === 'bldg' || (SE.drag && SE.drag.kind === 'vertex')) && SE.cursor) ed.cursor = SE.cursor;
if (!ed.cursor) ed.tip = '';
return ed;
}
function draftDown(px, py, x, y, tool) {
const tx = S._siteTx, now = performance.now(), D = SE.draft;
if (!D) { const p = snapPt(x, y, null, tx); SE.draft = { tool, pts: [p], cur: p, down: [px, py], pressed: true, rect: false }; SE.lastDown = { t: now, px, py }; SE.tip = segTip(p, p); return; }
D.pressed = true;
const f = D.pts[0], near1 = Math.hypot(tx.x(f[0]) - px, tx.y(f[1]) - py) < (isCoarse() ? 16 : 10);
const dbl = SE.lastDown && now - SE.lastDown.t < 380 && Math.hypot(SE.lastDown.px - px, SE.lastDown.py - py) < 6;
SE.lastDown = { t: now, px, py };
if ((near1 || dbl) && D.pts.length >= 3) { finishDraft(); return; }
if (dbl) return;
const last = D.pts[D.pts.length - 1], p = snapPt(x, y, last, tx);
if (Math.hypot(p[0] - last[0], p[1] - last[1]) < 0.05) return;
D.pts.push(p); D.cur = p;
}
function draftMove(px, py, x, y) {
const tx = S._siteTx, D = SE.draft;
if (!D) { const p = snapPt(x, y, null, tx); SE.tip = `${fmt(p[0])}, ${fmt(p[1])} m`; return; }
const last = D.pts[D.pts.length - 1];
if (D.pressed && D.pts.length === 1 && Math.hypot(px - D.down[0], py - D.down[1]) > 6) D.rect = true;
const p = snapPt(x, y, D.rect ? null : last, tx); D.cur = p;
const f = D.pts[0]; D.closeHint = !D.rect && D.pts.length >= 3 && Math.hypot(tx.x(f[0]) - px, tx.y(f[1]) - py) < (isCoarse() ? 16 : 10);
SE.tip = D.rect ? `W ${mmTxt(Math.abs(p[0] - f[0]))} × D ${mmTxt(Math.abs(p[1] - f[1]))} mm\n${fmt(Math.abs((p[0] - f[0]) * (p[1] - f[1])))} m²` : segTip(last, p) + (D.closeHint ? '\n按一下完成' : '');
}
function draftUp() {
const D = SE.draft; if (!D) return; D.pressed = false;
if (D.rect) finishDraft();
}
function finishDraft() {
const D = SE.draft; if (!D) return; SE.draft = null; SE.tip = '';
let P = D.pts;
if (D.rect) { const a = D.pts[0], b = D.cur; P = rectPoly(Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.max(a[0], b[0]), Math.max(a[1], b[1])); }
if (P.length < 3 || Math.abs(polyArea(P)) < 1) { toast('形狀太細(少於 1 m²),未加入'); drawSiteOnly(); return; }
if (polySelfX(P)) { toast('邊不可以交叉,請重畫'); drawSiteOnly(); return; }
if (D.tool === 'boundary') {
if (setSitePoly(P)) { SE.sel = 'site'; SE.selV = null; setSiteTool('off'); toast(`已畫地界:${S.comp.site.poly.length} 點,${Math.abs(polyArea(S.comp.site.poly)).toFixed(1)} m²`); }
} else {
const s = S.comp.site, b = { id: newBid(), name: `建築 ${s.buildings.length + 1}`, h: 20, poly: orientPos(P) };
s.buildings.push(b); SE.sel = b.id; SE.selV = null; setSiteTool('off'); syncSiteInputs(); siteChanged();
const cv = $('#site-plan').getBoundingClientRect(), c = polyCentroid(b.poly), tx = S._siteTx;
openBldgPop(b, cv.left + tx.x(c[0]), cv.top + tx.y(c[1]));
toast(`已加入 ${b.name}(${Math.abs(polyArea(b.poly)).toFixed(1)} m²),請輸入高度`);
}
}
function viewMark(px, py, x, y, mode) {
const site = S.comp.site, tx = S._siteTx;
const hit = site.views.findIndex(v => { const [vx, vy] = viewPos(site, v); return Math.hypot(tx.x(vx) - px, tx.y(vy) - py) < 14; });
if (hit >= 0) { site.views.splice(hit, 1); siteChanged(true); return; }
const c = closestOnPoly(site.poly, x, y);
if (c.d * tx.sc > 28) { toast('請按花園的邊線加景觀標記'); return; }
site.views.push({ edge: c.edge, t: Math.max(0.05, Math.min(0.95, c.t)), type: mode });
siteChanged(true);
}
function initSite() {
const s = () => S.comp.site;
const num = (id, f, lo, hi) => $(id).addEventListener('change', e => {
let v = parseFloat(e.target.value); if (!isFinite(v)) v = lo; v = Math.max(lo, Math.min(hi, v)); e.target.value = v;
if (f === 'W' || f === 'D') { if (isSiteRect(s().poly, s().W, s().D)) { const W = f === 'W' ? v : s().W, D = f === 'D' ? v : s().D; setSitePoly(rectPoly(0, 0, W, D)); S.comp.section = defaultSection(S.comp); } return; }
s()[f] = v; siteChanged(f === 'soil' || f === 'level');
});
num('#s-W', 'W', 3, 120); num('#s-D', 'D', 3, 120); num('#s-soil', 'soil', 0.1, 3); num('#s-level', 'level', 0, 200);
$('#s-rect').addEventListener('click', () => {
const W = Math.max(3, Math.min(120, parseFloat($('#s-W').value) || 10)), D = Math.max(3, Math.min(120, parseFloat($('#s-D').value) || 7));
if (setSitePoly(rectPoly(0, 0, W, D))) { S.comp.section = defaultSection(S.comp); saveWork(); toast(`地界改為 ${W} × ${D} m 矩形`); }
});
$('#s-addv').addEventListener('click', () => { const E = siteEdges(s()), e = E.reduce((a, b) => b.len > a.len ? b : a); insertVertex('site', e.i, [(e.a[0] + e.b[0]) / 2, (e.a[1] + e.b[1]) / 2]); SE.sel = 'site'; SE.selV = e.i + 1; geometryDone(); toast(`已在最長的邊加 ${ptLabel(e.i + 1)},可拖動`); });
$('#s-addb').addEventListener('click', () => {
const site = s(), W = site.W, b = { id: newBid(), name: `建築 ${site.buildings.length + 1}`, h: 20, poly: rectPoly(W / 2 - 4, -11, W / 2 + 4, -3) };
site.buildings.push(b); SE.sel = b.id; SE.selV = null; syncSiteInputs(); siteChanged(); toast(`已在地盤北面(圖上方)加 ${b.name},可拖動`);
});
$('#s-north').addEventListener('change', e => { let v = Math.round(parseFloat(e.target.value)); if (!isFinite(v)) v = 0; v = ((v % 360) + 360) % 360; e.target.value = v; s().north = v; $('#s-north-o').textContent = v + '°'; siteChanged(); });
$('#s-podium').addEventListener('change', e => { s().podium = e.target.checked; siteChanged(true); });
segInit('s-layer', v => { S.siteUi.layer = v; renderSite(); });
segInit('s-viewmode', v => { setSiteTool(v); if (v === 'good' || v === 'screen') toast(SITE_TIP[v]); });
$('#s-snap').checked = SNAP.grid; $('#s-snap15').checked = SNAP.ang;
$('#s-snap').addEventListener('change', e => { SNAP.grid = e.target.checked; });
$('#s-snap15').addEventListener('change', e => { SNAP.ang = e.target.checked; });
$('#s-wind').addEventListener('change', e => { S.siteUi.wind = e.target.checked; renderSite(); });
$('#s-date').value = S.siteUi.doy; $('#s-time').value = S.siteUi.time;
$('#s-date').addEventListener('input', e => { S.siteUi.doy = +e.target.value; renderSiteTime(); });
$('#s-time').addEventListener('input', e => { S.siteUi.time = +e.target.value; renderSiteTime(); });
$$('#s-keyd button').forEach(b => b.addEventListener('click', () => { S.siteUi.doy = +b.dataset.doy; $('#s-date').value = S.siteUi.doy; renderSiteTime(); }));
$('#tool-sitedata').addEventListener('click', e => popAtEl('pop-site', e.currentTarget));
initSitePointer();
}
function initSitePointer() {
const cv = $('#site-plan'); cv.style.cursor = 'default';
const pos = ev => { const r = cv.getBoundingClientRect(); return [ev.clientX - r.left, ev.clientY - r.top]; };
const hitR = ev => ev.pointerType === 'touch' || isCoarse() ? 18 : 9;
const startDrag = (ev, d) => { SE.drag = d; SE.frozen = S._siteTx; try { cv.setPointerCapture(ev.pointerId); } catch (err) { /* synthetic events */ } ev.preventDefault(); };
const vertexAt = (P, px, py, R, tx) => P ? P.findIndex(q => Math.hypot(tx.x(q[0]) - px, tx.y(q[1]) - py) < R) : -1;
cv.addEventListener('pointerdown', ev => {
if (!S._siteTx || ev.button === 2) return;
const [px, py] = pos(ev), tx = S._siteTx, site = S.comp.site, tool = S.siteUi.viewMode, x = tx.ix(px), y = tx.iy(py), R = hitR(ev);
SE.cursor = [px, py];
if (tool === 'boundary' || tool === 'bldg') { draftDown(px, py, x, y, tool); try { cv.setPointerCapture(ev.pointerId); } catch (err) { /* synthetic */ } ev.preventDefault(); drawSiteOnly(); return; }
if (tool === 'good' || tool === 'screen') { viewMark(px, py, x, y, tool); return; }
const P = shapeOf(SE.sel);
if (P) {
if (SE.selV != null && P.length > 3 && P[SE.selV]) { // the small × next to the selected vertex
const v = P[SE.selV], r = handleR(), bx = tx.x(v[0]) + r / 2 + 5, by = tx.y(v[1]) - r / 2 - 15;
if (px >= bx - 4 && px <= bx + 17 && py >= by - 4 && py <= by + 17) { delVertex(SE.sel, SE.selV); return; }
}
const vi = vertexAt(P, px, py, R, tx);
if (vi >= 0) { SE.selV = vi; startDrag(ev, { kind: 'vertex', shape: SE.sel, i: vi, geo: true }); drawSiteOnly(); return; }
for (let i = 0; i < P.length; i++) {
const a = P[i], b = P[(i + 1) % P.length], mx = (a[0] + b[0]) / 2, my = (a[1] + b[1]) / 2;
if (Math.hypot(tx.x(b[0]) - tx.x(a[0]), tx.y(b[1]) - tx.y(a[1])) >= 26 && Math.hypot(tx.x(mx) - px, tx.y(my) - py) < R) {
insertVertex(SE.sel, i, [Math.round(mx * 1000) / 1000, Math.round(my * 1000) / 1000]); SE.selV = i + 1;
startDrag(ev, { kind: 'vertex', shape: SE.sel, i: i + 1, geo: true, moved: true }); drawSiteOnly(); return;
}
}
}
const b = [...site.buildings].reverse().find(q => pointInPoly(x, y, q.poly));
if (b) { SE.sel = b.id; SE.selV = null; startDrag(ev, { kind: 'move', id: b.id, orig: b.poly.map(p => p.slice()), x0: x, y0: y, geo: true, cx: ev.clientX, cy: ev.clientY }); drawSiteOnly(); return; }
if (inSite(site, x, y)) { const again = SE.sel === 'site'; SE.sel = 'site'; SE.selV = null; SE.drag = { kind: 'site', cx: ev.clientX, cy: ev.clientY, again }; drawSiteOnly(); return; }
SE.sel = null; SE.selV = null; closePops(); drawSiteOnly();
});
cv.addEventListener('pointermove', ev => {
if (!S._siteTx) return;
const [px, py] = pos(ev), tool = S.siteUi.viewMode, D = SE.drag; SE.cursor = [px, py];
const tx = SE.frozen || S._siteTx, x = tx.ix(px), y = tx.iy(py);
if (tool === 'boundary' || tool === 'bldg') { draftMove(px, py, x, y); drawSiteOnly(); return; }
if (!D) { // hover cursor (mouse only)
if (tool !== 'off') return;
const P = shapeOf(SE.sel), site = S.comp.site;
cv.style.cursor = vertexAt(P, px, py, 9, tx) >= 0 ? 'move' : site.buildings.some(q => pointInPoly(x, y, q.poly)) ? 'move' : inSite(site, x, y) ? 'pointer' : 'default';
return;
}
if (D.kind === 'vertex') {
const P = shapeOf(D.shape), n = P.length, prev = P[(D.i + n - 1) % n];
P[D.i] = snapPt(x, y, prev, tx, { P, i: D.i }); D.moved = true;
SE.tip = `${ptLabel(D.i)} ${fmt(P[D.i][0])}, ${fmt(P[D.i][1])} m\n` + segTip(prev, P[D.i]);
if (D.shape === 'site') { const sh = normalizeComp(S.comp); if (sh[0] || sh[1]) SE.frozen = txFrom(tx.sc, tx.ox - sh[0] * tx.sc, tx.oy - sh[1] * tx.sc); }
} else if (D.kind === 'move') {
if (Math.hypot(ev.clientX - D.cx, ev.clientY - D.cy) > 4) D.moved = true;
if (D.moved) {
let dx = x - D.x0, dy = y - D.y0; if (SNAP.grid) { dx = Math.round(dx * 2) / 2; dy = Math.round(dy * 2) / 2; }
const b = bldgById(D.id); b.poly = translatePoly(D.orig, dx, dy); SE.tip = `移動 ${fmt(dx)}, ${fmt(dy)} m`;
}
} else return;
drawSiteOnly();
});
const end = ev => {
if (SE.draft) { draftUp(); drawSiteOnly(); return; }
const D = SE.drag; if (!D) return; SE.drag = null; SE.frozen = null; SE.tip = '';
if (D.kind === 'vertex') { if (D.moved) { if (D.shape === 'site') geometryDone(); else { syncSiteInputs(); siteChanged(); } } else drawSiteOnly(); }
else if (D.kind === 'move') { const b = bldgById(D.id); if (D.moved) { syncSiteInputs(); siteChanged(); } else { drawSiteOnly(); openBldgPop(b, D.cx, D.cy); } }
else if (D.kind === 'site') { drawSiteOnly(); if (!isMob() || D.again) openPop('pop-site', D.cx, D.cy); }
};
cv.addEventListener('pointerup', end); cv.addEventListener('pointercancel', end);
cv.addEventListener('pointerleave', () => { if (!SE.drag && S.siteUi.viewMode !== 'off') { SE.cursor = null; drawSiteOnly(); } });
cv.addEventListener('contextmenu', ev => { // right-click: finish a draft, or delete the vertex under the cursor
ev.preventDefault(); if (!S._siteTx) return;
if (SE.draft) { if (SE.draft.pts.length >= 3) finishDraft(); return; }
const [px, py] = pos(ev), tx = S._siteTx;
for (const sel of [SE.sel, 'site'].filter(Boolean)) { const i = vertexAt(shapeOf(sel), px, py, 10, tx); if (i >= 0) { delVertex(sel, i); return; } }
});
}
function openBldgPop(b, cx, cy) {
if (!b) return;
$('#pop-bldg-t').innerHTML = `BUILDING ${esc(b.name)}`;
$('#pop-bldg-b').innerHTML = `
距地盤 ${fmt(bldgGap(b))} m,平面 ${Math.abs(polyArea(b.poly)).toFixed(1)} m²,${b.poly.length} 點。拖動可移動;選取後拖角點改形狀。高度 0 = 只作參考,不計陰影。
`;
$('#bl-h').addEventListener('change', () => { const v = parseFloat($('#bl-h').value); b.h = isFinite(v) ? Math.max(0, Math.min(400, v)) : 0; $('#bl-h').value = b.h; syncSiteInputs(); siteChanged(); });
$('#bl-name').addEventListener('change', () => { b.name = $('#bl-name').value.trim() || b.name; $('#pop-bldg-t i').textContent = b.name; syncSiteInputs(); siteChanged(true); });
$('#bl-rotl').addEventListener('click', () => rotateBuilding(b.id, -15));
$('#bl-rotr').addEventListener('click', () => rotateBuilding(b.id, 15));
$('#bl-del').addEventListener('click', () => delBuilding(b.id));
openPop('pop-bldg', cx, cy);
}
function drawSiteOnly() {
if (!S.comp || !S.sun) return null;
const cv = $('#site-plan'), { ctx, w, h } = fit(cv), [m, d] = doyToMD(S.siteUi.doy);
const r = drawSitePlan(ctx, w, h, S.comp.site, S.sun, {
md: [m, d], time: S.siteUi.time, layer: S.siteUi.layer, wind: S.siteUi.wind,
tx: SE.frozen, dragging: !!(SE.drag && SE.drag.geo && SE.drag.moved), edit: editOverlay(), selB: SE.hot || (SE.sel !== 'site' ? SE.sel : null),
});
S._siteTx = r.tx; S._siteLast = r; return r;
}
/* the parts that follow the date and time: the plan, the legend, the sun path and its caption */
function renderSiteSun(r) {
const site = S.comp.site, [m, d] = doyToMD(S.siteUi.doy), hr = S.siteUi.time;
$('#s-date-o').textContent = `${m}月${d}日`; $('#s-time-o').textContent = hhmm(hr);
$('#s-legend').innerHTML = esc(r.legend) + (S.siteUi.wind ? '
風向箭嘴:藍灰為東北季候風/東風(約 9–5 月),赭色為西南季候風(約 6–8 月),約值。' : '');
const sc = $('#sunpath'), f2 = fit(sc); drawSunPath(f2.ctx, f2.w, f2.h, site, { m, d, h: hr });
const sp = r.sp;
$('#s-sunnow').innerHTML = `━ 冬至 ━ 春分/秋分 ━ 夏至(點為 07–17 時)
` +
(sp.alt > 0 ? `${m}月${d}日 ${hhmm(hr)}:太陽高度 ${sp.alt.toFixed(1)}°,方位 ${sp.az.toFixed(0)}°(${compass(sp.az)})。正午最高:冬至約 44°,夏至約 89°。` : `${m}月${d}日 ${hhmm(hr)}:太陽未出或已落山。`);
}
/* time slider / date: only what changes (kept well under 100 ms) */
function renderSiteTime() {
if (!S.comp || !S.sun) return;
const t0 = performance.now(), r = drawSiteOnly(); if (r) renderSiteSun(r);
S.perfSite = performance.now() - t0;
}
function renderSite() {
if (!S.comp || !S.sun) return;
const site = S.comp.site, cv = $('#site-plan'), r = drawSiteOnly();
renderSiteSun(r);
S.scales.site = scaleLabel(cv, r.tx.sc); $('#s-scale').textContent = S.scales.site;
drawMini('#s-bar', '#s-north-mini', r.tx.sc, site.north);
const dd = designDirection(site, S.sun), KZ = { sun: '日照', wind: '風', view: '景觀', soil: '泥土' };
$('#s-dir').innerHTML = dd.list.map(x => `${KZ[x.kind]}${esc(x.text)}`).join('');
const zc = z => ZONE_COL[z].replace(/0\.3\d\)/, '0.8)');
$('#s-qtable').innerHTML = `| 角落 CORNER | 冬至 h | 夏至 h | 平均 h | 分區 ZONE |
` +
dd.qStat.map(q => { const z = zoneOfHours(q.avg); return `| ${q.dir}角(圖${q.name}) | ${q.dec.toFixed(1)} | ${q.jun.toFixed(1)} | ${q.avg.toFixed(1)} | ${ZONE_ZH[z]} |
`; }).join('') +
`| 只計地盤範圍內(${Math.abs(polyArea(site.poly)).toFixed(1)} m²)。平均 = (冬至 + 2 × 春秋分 + 夏至) ÷ 4。分區門檻屬本工具的設計假設。 |
`;
}
/* ================= LP-03 TREE STUDIES ================= */
const TREE_NUM = { age: 't-age', seed: 't-seed', lean: 't-lean', bend: 't-bend', irr: 't-irr', jit: 't-jit', light: 't-light', laz: 't-laz', miss: 't-miss', fol: 't-fol', int: 't-int' };
function clampInput(el, v) { const lo = parseFloat(el.min), hi = parseFloat(el.max); if (isFinite(lo)) v = Math.max(lo, v); if (isFinite(hi)) v = Math.min(hi, v); return v; }
function syncTreeInputs() { for (const [k, id] of Object.entries(TREE_NUM)) $('#' + id).value = S.tree[k]; $('#t-species').value = S.tree.sp; $$('input[name=tstyle]').forEach(r => r.checked = r.value === S.tree.style); }
function initTree() {
const sel = $('#t-species'); sel.innerHTML = SPECIES.map(s => ``).join('');
sel.value = S.tree.sp;
sel.addEventListener('change', () => { S.tree.sp = sel.value; const sp = speciesById(sel.value); S.tree.month = sp.phen.findIndex(x => x === 'F' || x === 'LF') + 1 || 6; drawStyleSwatches(); renderTree(); });
for (const [k, id] of Object.entries(TREE_NUM)) {
const el = $('#' + id); el.value = S.tree[k];
el.addEventListener('input', () => { const v = parseFloat(el.value); if (!isFinite(v)) return; S.tree[k] = clampInput(el, v); renderTree(); });
el.addEventListener('change', () => { el.value = S.tree[k]; });
}
$$('.stp button').forEach(b => b.addEventListener('click', () => {
const el = $('#' + b.dataset.for), st = parseFloat(el.step) || 1, dec = (String(el.step).split('.')[1] || '').length;
const v = clampInput(el, (parseFloat(el.value) || 0) + st * +b.dataset.d); el.value = v.toFixed(dec); el.dispatchEvent(new Event('input'));
}));
$('#t-styles').innerHTML = STYLES.map(s => ``).join('');
$$('input[name=tstyle]').forEach(r => r.addEventListener('change', () => { S.tree.style = r.value; renderTree(); }));
$('#t-months').innerHTML = MONTH_EN.map((m, i) => ``).join('');
$$('#t-months button').forEach(b => b.addEventListener('click', () => { S.tree.month = +b.dataset.m; renderTree(); }));
$('#t-reset').addEventListener('click', () => { Object.assign(S.tree, { lean: 0, bend: 0, irr: 0, jit: 0, light: 0, miss: 0 }); syncTreeInputs(); renderTree(); toast('已回到標準樹形(所有偏差為 0)'); });
$('#t-random').addEventListener('click', () => renderVariants(true));
drawStyleSwatches();
}
function drawStyleSwatches() {
const sp = speciesById(S.tree.sp), sz = sizeAtAge(sp, 15), tree = buildTree(sp, { H: sz.H, S: sz.S, seed: 3, budget: 700 });
$$('#t-styles canvas').forEach(cv => {
const ctx = cv.getContext('2d'); ctx.clearRect(0, 0, 34, 30);
const sc = Math.min(26 / (sz.H * 1.1), 30 / (sz.S * 1.3));
drawTree(ctx, tree, sp, { bx: 17, by: 29, sc, style: cv.dataset.style, month: 6, state: 'L', seed: 3, foliage: 0.75, intensity: 0.75, noShadow: true });
});
}
function treeOpts(t, sp) {
const sz = sizeAtAge(sp, t.age);
return { H: sz.H, S: sz.S, seed: t.seed, lean: t.lean, bend: t.bend, irregular: t.irr, jitter: t.jit, light: t.light, lightAz: t.laz, missing: t.miss };
}
function treeBase(ctx, w, h, by) {
ctx.fillStyle = PAPER; ctx.fillRect(0, 0, w, h);
ctx.fillStyle = '#efe8d8'; ctx.fillRect(8, by, w - 16, 9);
hatchIn(ctx, c => c.rect(8, by, w - 16, 9), { sp: 5, ang: -45, col: '#8b7d62', lw: 0.5 });
ctx.strokeStyle = INK; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(8, by); ctx.lineTo(w - 8, by); ctx.stroke();
}
const PHEN_ZH = { L: '有葉', N: '新葉', F: '先花後葉', LF: '開花', B: '落葉', A: '紅葉' };
function renderTree() {
const t = S.tree, sp = speciesById(t.sp);
const outs = { age: t.age + ' 年', seed: String(t.seed).padStart(3, '0'), lean: t.lean + '°', bend: t.bend + '°', irr: '', jit: '', light: '', laz: t.laz + '°', miss: Math.round(t.miss * 100) + '%', fol: '', int: '' };
for (const [k, v] of Object.entries(outs)) { const o = $('#t-' + k + '-o'); if (o) o.textContent = v; }
$$('#t-months button').forEach((b, i) => { b.classList.toggle('on', i + 1 === t.month); b.querySelector('i').className = 'ph-' + sp.phen[i]; b.title = `${i + 1} 月:${PHEN_ZH[sp.phen[i]]}`; });
$('#t-month-o').textContent = `${t.month} 月:${PHEN_ZH[sp.phen[t.month - 1]]}`;
const o = treeOpts(t, sp), tree = buildTree(sp, o), st = sp.phen[t.month - 1];
// 1 specimen elevation, with level scale, clear stem, height and spread dimensions and a scale figure
{
const cv = $('#t-render'), { ctx, w, h } = fit(cv);
const padL = 48, padR = 58, padT = 30, padB = 30, by = h - padB;
const sc = Math.min((h - padT - padB) / (o.H * 1.08), (w - padL - padR) / (o.S * 1.35)), bx = padL + (w - padL - padR) / 2;
treeBase(ctx, w, h, by);
const step = o.H > 15 ? 5 : o.H > 6 ? 2 : 1;
ctx.font = fnt(8, 400, F_MONO); ctx.textAlign = 'right'; ctx.textBaseline = 'middle';
for (let m = step; m < o.H * 1.08; m += step) { const y = by - m * sc; ctx.strokeStyle = HAIR; ctx.lineWidth = 0.5; ctx.setLineDash([2, 4]); ctx.beginPath(); ctx.moveTo(padL - 4, y); ctx.lineTo(w - 10, y); ctx.stroke(); ctx.setLineDash([]); ctx.fillStyle = LIGHT; ctx.fillText('+' + m.toFixed(1), padL - 7, y); }
drawTree(ctx, tree, sp, { bx, by, sc, style: t.style, month: t.month, state: st, seed: t.seed, foliage: t.fol, intensity: t.int, lightAz: t.light > 0 ? (Math.cos(t.laz * D2R) >= 0 ? 20 : 160) : 30 });
const xs = tree.tips.map(q => q.p[0]), ex0 = Math.min(...xs), ex1 = Math.max(...xs), top = Math.max(...tree.tips.map(q => q.p[1]), o.H * 0.9);
const xr = Math.min(w - 16, bx + ex1 * sc + 26);
dimLine(ctx, xr, by, xr, by - top * sc, `H ${top.toFixed(1)} m`, 0, { col: INK });
dimLine(ctx, bx + ex0 * sc, by - top * sc - 12, bx + ex1 * sc, by - top * sc - 12, `S ${(ex1 - ex0).toFixed(1)} m`, 0, { col: INK });
if (tree.crownBase > 0.3) {
const yc = by - tree.crownBase * sc, xl = Math.max(padL + 6, bx + ex0 * sc - 18);
ctx.save(); ctx.strokeStyle = LIGHT; ctx.setLineDash([6, 3]); ctx.lineWidth = 0.7; ctx.beginPath(); ctx.moveTo(xl, yc); ctx.lineTo(bx + 8, yc); ctx.stroke(); ctx.restore();
dimLine(ctx, xl, by, xl, yc, `淨幹 ${tree.crownBase.toFixed(1)} m`, 0, { col: GRAPH, size: 8.5 });
}
const im = FIG_IMG['office_milktea']; if (im && im.complete && im.naturalWidth) { const hh = 1.65 * sc, ww = im.naturalWidth / im.naturalHeight * hh; ctx.drawImage(im, Math.min(w - ww - 60, bx + ex1 * sc * 0.55 + 6), by - hh, ww, hh); }
S.scales.tree = scaleLabel(cv, sc); $('#t-scale').textContent = S.scales.tree;
}
// 2 branch order diagram
{
const { ctx, w, h } = fit($('#t-skel')), by = h - 16;
treeBase(ctx, w, h, by);
const sc = Math.min((h - 30) / (o.H * 1.1), (w - 20) / (o.S * 1.35));
drawSkeleton(ctx, tree, { bx: w / 2, by, sc });
}
const crownH = tree.H - tree.crownBase;
$('#t-title').textContent = window.LANG === 'en' ? sp.en : `${sp.zh} 立面`;
$('#t-stats').innerHTML = `樹高 ${o.H.toFixed(1)} m 冠幅 ${o.S.toFixed(1)} m 冠幅/樹高 ${(o.S / o.H).toFixed(2)} 樹冠高/樹高 ${(crownH / tree.H).toFixed(2)} ${t.month} 月:${PHEN_ZH[st]}(旁邊人物 1.65 m)`;
$('#t-model').innerHTML = `樹形模式:${esc(sp.model)} ${TAG_ZH[sp.modelTag]}`;
const lib = libById(sp.id);
$('#t-note').innerHTML = `${window.LANG === 'en' ? `${sp.en} ${sp.sci}` : `${sp.zh} ${sp.sci}
${sp.en}`}
${esc(sp.note)}
- 成熟尺寸:高 ${lib.h[0]}–${lib.h[1]} m、冠幅 ${lib.s[0]}–${lib.s[1]} m。${lib.sizeSrc === 'stsg' ? '高度及冠幅:' + srcLink('stsg') : (lib.hSrc ? '高度:' + srcLink(lib.hSrc) + ';冠幅為估計值(未核實)' : '高度及冠幅為估計值(未核實)')}。
- ${nativeLabel(lib)}。日照需要:${lib.light.map(l => LIGHT_ZH[l]).join('/')}。
- 樹形模式:${esc(sp.model)} ${TAG_ZH[sp.modelTag]}。骨架規則參考 ${srcLink('halle')}、${srcLink('barth')};每個品種歸入哪個模式是本工具的判斷。
- 立面的樹高及冠幅按「樹齡」由生長曲線推算,屬本工具的假設,不是苗圃規格。
${lib.warn.map(w => `- ${WARN[w.k].zh}:${esc(w.note)}
`).join('')}
`;
renderVariants(false);
}
let _variantSeeds = null;
function renderVariants(newOnes) {
const t = S.tree, sp = speciesById(t.sp), box = $('#t-variants');
if (newOnes || !_variantSeeds || _variantSeeds.sp !== t.sp) {
const R = rng(Date.now() % 100000);
_variantSeeds = { sp: t.sp, list: Array.from({ length: 6 }, () => ({ seed: 1 + Math.floor(R() * 998), lean: Math.round((R() - .5) * 16), bend: Math.round((R() - .5) * 24), irr: +(R() * 0.6).toFixed(2), jit: +(R() * 0.5).toFixed(2), light: +(R() * 0.7).toFixed(2), laz: Math.floor(R() * 36) * 10, miss: +(R() * 0.3).toFixed(2) })) };
}
if (box.children.length !== 6) {
box.innerHTML = '';
for (let i = 0; i < 6; i++) { const d = document.createElement('div'); d.className = 'v'; d.innerHTML = `3${'ABCDEF'[i]}`; d.title = '按一下,把這株的偏差套用到規格卡'; box.appendChild(d); d.addEventListener('click', () => { const v = _variantSeeds.list[i]; Object.assign(S.tree, v); syncTreeInputs(); renderTree(); toast(`已套用樣本 3${'ABCDEF'[i]}`); }); }
}
_variantSeeds.list.forEach((v, i) => {
const d = box.children[i], cv = d.querySelector('canvas'), dpr = Math.min(2, window.devicePixelRatio || 1);
const W = Math.max(60, d.clientWidth), H = Math.max(60, d.clientHeight);
cv.width = W * dpr; cv.height = H * dpr; const ctx = cv.getContext('2d'); ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const tt = Object.assign({}, t, v), o = treeOpts(tt, sp), tree = buildTree(sp, Object.assign(o, { budget: 1500 }));
ctx.fillStyle = PAPER; ctx.fillRect(0, 0, W, H); ctx.strokeStyle = INK; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.moveTo(6, H - 12); ctx.lineTo(W - 6, H - 12); ctx.stroke();
const sc = Math.min((H - 30) / (o.H * 1.1), (W - 12) / (o.S * 1.35));
drawTree(ctx, tree, sp, { bx: W / 2, by: H - 12, sc, style: t.style, month: t.month, state: sp.phen[t.month - 1], seed: v.seed, foliage: t.fol, intensity: t.int });
d.querySelector('em').textContent = `#${v.seed} 傾${v.lean}° 缺${Math.round(v.miss * 100)}%`;
});
}
/* ================= LP-04 GROWTH ANATOMY ================= */
const PHOTO_IMG = {};
function initWhy() {
$('#w-species').addEventListener('change', e => { S.why.sp = e.target.value; S.why.idx = 0; renderWhy(); });
segInit('w-mode', v => { S.why.mode = v; renderWhy(); });
$('#w-fade').addEventListener('input', e => { S.why.fade = +e.target.value; renderWhy(); });
$('#w-prev').addEventListener('click', () => { const n = WHY[S.why.sp].points.length; S.why.idx = (S.why.idx + n - 1) % n; renderWhy(); });
$('#w-next').addEventListener('click', () => { const n = WHY[S.why.sp].points.length; S.why.idx = (S.why.idx + 1) % n; renderWhy(); });
$('#w-canvas').addEventListener('click', ev => {
if (!S._whyHits) return; const r = ev.currentTarget.getBoundingClientRect(), x = ev.clientX - r.left, y = ev.clientY - r.top;
const i = S._whyHits.findIndex(q => (x >= q.x0 && x <= q.x1 && y >= q.y0 && y <= q.y1) || Math.hypot(q.px - x, q.py - y) < 12);
if (i >= 0) { S.why.idx = i; renderWhy(); }
});
}
function wrapChars(ctx, text, maxW, maxLines = 2) {
const lines = []; let cur = '';
if (window.LANG === 'en') { // translate first, then wrap on words
text = window.tr(text);
const words = text.split(' '); let n = 0;
for (const w of words) {
const t = cur ? cur + ' ' + w : w;
if (ctx.measureText(t).width > maxW && cur) { lines.push(cur); cur = w; if (lines.length === maxLines) break; } else cur = t;
n++;
}
if (lines.length < maxLines && cur) lines.push(cur);
if (n < words.length || (lines.length === maxLines && lines.join(' ').length < text.length)) lines[lines.length - 1] = lines[lines.length - 1].replace(/\s*\S*$/, '') + '…';
return lines;
}
for (const ch of text) { if (ctx.measureText(cur + ch).width > maxW && cur) { lines.push(cur); cur = ch; if (lines.length === maxLines) break; } else cur += ch; }
if (lines.length < maxLines && cur) lines.push(cur);
const used = lines.join('').length; if (used < text.length) lines[lines.length - 1] = lines[lines.length - 1].slice(0, -1) + '…';
return lines;
}
function renderWhy() {
const key = S.why.sp, W = WHY[key], cr = PHOTO_CREDITS[key];
const cv = $('#w-canvas'), { ctx, w, h } = fit(cv);
let im = PHOTO_IMG[key];
if (!im) { im = PHOTO_IMG[key] = new Image(); im.onload = () => { if (S.tab === 'why') renderWhy(); }; im.src = 'assets/photos/' + cr.file; }
const EN = window.LANG === 'en', M = w < 520 ? (EN ? 92 : 70) : (EN ? 132 : 100), k = Math.min((w - 2 * M) / cr.w, (h - 8) / cr.h), pw = cr.w * k, ph = cr.h * k, x0 = (w - pw) / 2, y0 = (h - ph) / 2;
ctx.fillStyle = PAPER; ctx.fillRect(0, 0, w, h);
if (S.why.mode !== 'skel' && im.complete && im.naturalWidth) {
ctx.drawImage(im, x0, y0, pw, ph);
if (S.why.mode === 'both') { ctx.fillStyle = `rgba(251,250,246,${S.why.fade})`; ctx.fillRect(x0, y0, pw, ph); }
}
ctx.strokeStyle = INK; ctx.lineWidth = 1; ctx.strokeRect(x0, y0, pw, ph);
const wt = whyTree(key, cr), tb = cr.tree_box;
const bx = x0 + tb.base_x * k, by = y0 + tb.base_y * k, sc = wt.sc * k;
if (S.why.mode !== 'photo') {
drawSkeleton(ctx, wt.tree, { bx, by, sc, alpha: S.why.mode === 'both' ? 0.92 : 1 });
const xs = wt.tree.tips.map(t => t.p[0]), ys = wt.tree.tips.map(t => t.p[1]);
const ex0 = Math.min(...xs), ex1 = Math.max(...xs), ey0 = Math.min(...ys), ey1 = Math.max(...ys);
ctx.save(); ctx.setLineDash([12, 3, 2, 3]); ctx.strokeStyle = INK; ctx.lineWidth = 1;
ctx.beginPath(); ctx.ellipse(bx + (ex0 + ex1) / 2 * sc, by - (ey0 + ey1) / 2 * sc, (ex1 - ex0) / 2 * sc + 8, (ey1 - ey0) / 2 * sc + 8, 0, 0, 6.283); ctx.stroke();
ctx.setLineDash([2, 3]); ctx.strokeStyle = '#4f6d8f'; ctx.lineWidth = 0.8; ctx.strokeRect(x0 + tb.x0 * k, y0 + tb.y0 * k, (tb.x1 - tb.x0) * k, (tb.y1 - tb.y0) * k);
ctx.restore();
}
// keynote tags in the margins, leaders to the tree
const pts = W.points.map((p, i) => ({ i, px: Math.max(x0 + 6, Math.min(x0 + pw - 6, bx + p.at[0] * wt.S * sc)), py: Math.max(y0 + 6, Math.min(y0 + ph - 6, by - p.at[1] * wt.H * sc)) }));
const tagH = EN ? 42 : 34, hits = new Array(pts.length);
ctx.font = fnt(10, 500);
for (const side of ['L', 'R']) {
const grp = pts.filter(q => (q.px < w / 2) === (side === 'L')).sort((a, b) => a.py - b.py);
let yPrev = -1e9; const ys = grp.map(q => { const y = Math.max(q.py - tagH / 2, yPrev + tagH + 4, 4); yPrev = y; return y; });
const over = ys.length ? ys[ys.length - 1] + tagH - (h - 4) : 0; if (over > 0) for (let j = ys.length - 1; j >= 0; j--) { ys[j] -= over; if (j && ys[j] < ys[j - 1] + tagH + 4) continue; break; }
for (let j = ys.length - 1; j > 0; j--) if (ys[j - 1] > ys[j] - tagH - 4) ys[j - 1] = ys[j] - tagH - 4;
grp.forEach((q, j) => {
const on = q.i === S.why.idx, ty = ys[j], tx0 = side === 'L' ? 4 : w - M + 6, tx1 = side === 'L' ? M - 6 : w - 4;
const ax = side === 'L' ? tx1 : tx0, ay = ty + 9;
ctx.strokeStyle = on ? ACCENT : GRAPH; ctx.lineWidth = on ? 1.4 : 0.7;
ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(side === 'L' ? x0 - 6 : x0 + pw + 6, ay); ctx.lineTo(q.px, q.py); ctx.stroke();
ctx.beginPath(); ctx.arc(q.px, q.py, on ? 4.5 : 3.5, 0, 6.283); ctx.fillStyle = on ? ACCENT : PAPER; ctx.fill(); ctx.strokeStyle = on ? ACCENT : INK; ctx.lineWidth = 1.2; ctx.stroke();
const nx = side === 'L' ? tx0 : tx0;
ctx.fillStyle = on ? INK : PAPER; ctx.fillRect(nx, ty, 18, 18); ctx.strokeStyle = INK; ctx.lineWidth = 1.1; ctx.strokeRect(nx, ty, 18, 18);
ctx.fillStyle = on ? PAPER : INK; ctx.font = fnt(10, 600, F_MONO); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(String(q.i + 1), nx + 9, ty + 9.5);
ctx.font = fnt(EN ? 8.8 : 9.5, on ? 600 : 500); ctx.textAlign = 'left'; ctx.textBaseline = 'top'; ctx.fillStyle = INK;
wrapChars(ctx, W.points[q.i].title, tx1 - tx0 - 22, EN ? 3 : 2).forEach((ln, li) => ctx.fillText(ln, nx + 22, ty + 1 + li * (EN ? 10.6 : 12)));
hits[q.i] = { x0: tx0, x1: tx1, y0: ty, y1: ty + tagH - 6, px: q.px, py: q.py };
});
}
S._whyHits = hits;
// 2 architectural model diagram
{
const { ctx: c2, w: w2, h: h2 } = fit($('#w-diag')), gy = h2 - 22;
treeBase(c2, w2, h2, gy);
const s2 = Math.min((h2 - 34) / (wt.H * 1.05), (w2 - 30) / (wt.S * 1.2));
drawSkeleton(c2, wt.tree, { bx: w2 / 2, by: gy, sc: s2 });
const p = W.points[S.why.idx], qx = w2 / 2 + p.at[0] * wt.S * s2, qy = gy - p.at[1] * wt.H * s2;
c2.fillStyle = ACCENT; c2.beginPath(); c2.arc(qx, qy, 5, 0, 6.283); c2.fill();
c2.fillStyle = PAPER; c2.font = fnt(7.5, 700, F_MONO); c2.textAlign = 'center'; c2.textBaseline = 'middle'; c2.fillText(String(S.why.idx + 1), qx, qy + 0.5);
const sp = speciesById(key); c2.fillStyle = GRAPH; c2.font = fnt(8.5, 500, F_MONO); c2.textAlign = 'left'; c2.textBaseline = 'top'; c2.fillText(sp.model.replace(/(.*)/, ''), 8, 6);
}
$('#w-intro').textContent = W.intro;
$('#w-nums').innerHTML = W.points.map((p, i) => `${esc(p.title)} ${p.tags.map(t => `${TAG_ZH[t]}`).join('')}`).join('');
$$('#w-nums li').forEach(li => li.addEventListener('click', () => { S.why.idx = +li.dataset.i; renderWhy(); }));
const p = W.points[S.why.idx];
$('#w-detail').innerHTML = `${S.why.idx + 1}${esc(p.title)}
${p.tags.map(t => `${TAG_ZH[t]}`).join('')}
${esc(p.plain)}
- 理論
- ${esc(p.theory)}
- 程式做法
- ${esc(p.how)}
- 參數
${esc(p.param)}- 出處
- ${p.src.length ? p.src.map(srcLink).join(';') : '照片量度(本工具)'}
`;
$('#w-credit').innerHTML = `相片:${esc(cr.title.replace(/^File:/, ''))},作者 ${esc(cr.author)},${esc(cr.licence)},經 Wikimedia Commons;拍攝地點:${esc(cr.location)}。已縮細並加上疊圖。骨架由本工具生成,按相片中樹的外框(藍灰虛線)校準高度及冠幅;點劃線為樹冠外包線。`;
}
/* ================= LP-02 PLANTING PLAN ================= */
function syncBoardInputs() {
const c = S.comp;
$('#b-years').value = c.years; $('#b-style').value = c.style; $('#b-name').value = c.name || '';
$('#b-years-o').textContent = c.years === 0 ? 'Y0 剛種植' : `Y${c.years} 種植後 ${c.years} 年`;
$('#b-month-o').textContent = MONTHS_ZH[c.month - 1];
$$('#b-stops button').forEach(b => b.classList.toggle('on', +b.dataset.y === c.years));
$$('#b-months button').forEach((b, i) => b.classList.toggle('on', i + 1 === c.month));
}
const TOOL_TIP = {
select: '', place: '', measure: '量度:在平面上拖一條線(單位毫米)', section: '剖切:拖出 A-A 剖切線;三角箭嘴指向觀看方向',
view: '視點:按一下放 V1,按住拖動定方向',
};
function setTool(v) {
S.board.tool = v; segSet('b-tool', v);
$('#b-plan').style.cursor = v === 'select' ? 'default' : 'crosshair';
if (v === 'place') { const p = S.board.armed && libById(S.board.armed); $('#b-tip').textContent = p ? `放植物:按平面放置 ${p.zh}(可連續放;Esc 結束)` : '放植物:先在配置表選一行'; if (!p) openDrawer(); }
else $('#b-tip').textContent = TOOL_TIP[v] || '';
if (v !== 'place') { S.board.armed = null; $$('#b-cards tr.pc').forEach(r => r.classList.remove('armed')); }
}
function openDrawer() { $('#drawer').hidden = false; renderLib(); }
function closeDrawer() { $('#drawer').hidden = true; if (S.board.tool === 'place' && !S.board.armed) setTool('select'); }
function initBoard() {
$('#b-style').innerHTML = STYLES.map(s => ``).join('');
$('#b-years').addEventListener('input', e => { S.comp.years = +e.target.value; syncBoardInputs(); renderBoard(); });
$$('#b-stops button').forEach(b => b.addEventListener('click', () => { S.comp.years = +b.dataset.y; syncBoardInputs(); renderBoard(); }));
$('#b-months').innerHTML = MONTH_EN.map((m, i) => ``).join('');
$$('#b-months button').forEach(b => b.addEventListener('click', () => { S.comp.month = +b.dataset.m; syncBoardInputs(); renderBoard(); if (!$('#drawer').hidden) renderLib(); }));
$('#b-style').addEventListener('change', e => { S.comp.style = e.target.value; renderBoard(); if (!$('#drawer').hidden) renderLib(); });
['#b-zones', '#b-grid', '#b-keys', '#b-clouds'].forEach(id => $(id).addEventListener('change', () => renderBoard()));
$('#tool-layers').addEventListener('click', e => popAtEl('pop-layers', e.currentTarget));
$('#tool-palette').addEventListener('click', () => { $('#drawer').hidden ? openDrawer() : closeDrawer(); });
$('#drawer-close').addEventListener('click', closeDrawer);
segInit('b-tool', setTool);
segInit('pal-tab', v => { S.board.pal = v; $('#pal-plants').hidden = v !== 'plants'; $('#pal-figs').hidden = v !== 'figs'; $('#b-search').hidden = v !== 'plants'; $('#b-type').style.display = v === 'plants' ? '' : 'none'; });
$('#b-name').addEventListener('change', e => { S.comp.name = e.target.value; saveWork(); updateTitleBlock(); });
segInit('b-rtab', v => { S.board.rtab = v; $('#b-check').hidden = v !== 'check'; $('#b-src').hidden = v !== 'src'; if (v === 'src') renderSources(); });
segInit('b-type', v => { S.board.filter = v; renderLib(); });
$('#b-search').addEventListener('input', e => { S.board.q = e.target.value.trim().toLowerCase(); renderLib(); });
$('#tb-project').addEventListener('click', e => { renderSaved(); popAtEl('pop-file', e.currentTarget); const p = $('#pop-file'); if (!isMob()) { const r = e.currentTarget.getBoundingClientRect(); p.style.left = Math.max(8, r.left - p.offsetWidth - 10) + 'px'; p.style.top = Math.max(8, Math.min(window.innerHeight - p.offsetHeight - 8, r.top - 40)) + 'px'; } });
$('#b-save').addEventListener('click', saveVersion);
$('#b-new').addEventListener('click', () => { const c = { name: '新構圖', years: 5, month: S.comp.month, style: S.comp.style, site: JSON.parse(JSON.stringify(S.comp.site)), eye: { x: S.comp.site.W / 2, y: S.comp.site.D - 0.4, dir: 0, fov: 64, h: 1.6 }, items: [] }; [c.eye.x, c.eye.y] = clampIn(c.site, c.eye.x, c.eye.y, 0.4); setComp(c); saveWork(); renderAll(); toast('已開新構圖(沿用現有地盤)'); });
$('#b-example').addEventListener('click', () => { setComp(exampleComposition()); saveWork(); renderAll(); toast('已載入示範構圖'); });
$('#b-example2').addEventListener('click', () => { setComp(exampleComposition2()); saveWork(); renderAll(); toast('已載入示範二:L 形平台花園'); });
$('#b-export').addEventListener('click', () => {
const blob = new Blob([JSON.stringify({ app: 'hk-landscape-sheets', version: 3, exported: new Date().toISOString(), composition: S.comp }, null, 1)], { type: 'application/json' });
const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = (S.comp.name || 'composition').replace(/[\\/:*?"<>|]/g, '_') + '.json'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 2000);
});
$('#b-import').addEventListener('change', e => {
const f = e.target.files[0]; if (!f) return; const rd = new FileReader();
rd.onload = () => { try { const j = JSON.parse(rd.result), c = j.composition || j; if (!validComp(c)) throw new Error('格式不符'); setComp(c); saveWork(); renderAll(); toast('已匯入:' + (c.name || f.name)); } catch (err) { toast('匯入失敗:' + err.message); } e.target.value = ''; };
rd.readAsText(f);
});
$('#b-figs').innerHTML = FIGURES.map(f => ``).join('');
$$('#b-figs button').forEach(b => b.addEventListener('click', () => { const e = S.comp.eye, a = e.dir * D2R; const [x, y] = clampIn(S.comp.site, e.x + Math.sin(a) * 2.5 + (Math.random() - .5), e.y - Math.cos(a) * 2.5); S.comp.items.push({ uid: newUid(), kind: 'figure', id: b.dataset.id, x, y }); afterEdit(); toast('已加入人物,可在平面拖動'); }));
initPlanPointer();
renderSaved();
}
function afterEdit() { saveWork(); renderBoard(); }
function initPlanPointer() {
const cv = $('#b-plan'); let drag = null;
const pos = ev => { const r = cv.getBoundingClientRect(); return [ev.clientX - r.left, ev.clientY - r.top]; };
cv.addEventListener('pointerdown', ev => {
if (!S._planTx) return; const [px, py] = pos(ev), tx = S._planTx.tx, c = S.comp, e = c.eye, hd = S._planTx.handle, tool = S.board.tool;
const x = tx.ix(px), y = tx.iy(py);
if (tool === 'place') {
const p = S.board.armed && libById(S.board.armed);
if (!p) { toast('先在植物配置表選一行植物'); openDrawer(); return; }
const [cx, cy] = clampIn(c.site, x, y, 0.1); addPlant(p, cx, cy); return;
}
if (tool === 'measure') { S.board.measure = { x1: x, y1: y, x2: x, y2: y }; drag = { kind: 'measure' }; }
else if (tool === 'section') { drag = { kind: 'section', old: c.section }; c.section = { x1: x, y1: y, x2: x, y2: y }; }
else if (tool === 'view') { [e.x, e.y] = clampIn(c.site, x, y, 0); drag = { kind: 'dir', moved: true }; }
else if (Math.hypot(tx.x(hd.x) - px, tx.y(hd.y) - py) < 12) drag = { kind: 'dir' };
else if (Math.hypot(tx.x(e.x) - px, tx.y(e.y) - py) < 12) drag = { kind: 'eye' };
else {
let best = null;
for (const it of c.items) {
const p = plantOf(it), rr = p ? Math.max(9, Math.min(sizeAtYears(p, c.years).S / 2 * tx.sc, 40)) : 10, d = Math.hypot(tx.x(it.x) - px, tx.y(it.y) - py);
if (d < rr && (!best || d < best.d)) best = { it, d };
}
if (best) { drag = { kind: 'item', it: best.it, cx: ev.clientX, cy: ev.clientY }; S.board.sel = best.it.uid; }
else { S.board.sel = null; closePops(); }
}
if (drag) { try { cv.setPointerCapture(ev.pointerId); } catch (err) { /* synthetic events */ } ev.preventDefault(); }
drawPlanOnly();
});
cv.addEventListener('pointermove', ev => {
if (!drag) return; const [px, py] = pos(ev), tx = S._planTx.tx, c = S.comp;
const x = tx.ix(px), y = tx.iy(py);
if (drag.kind === 'dir') c.eye.dir = Math.round((Math.atan2(x - c.eye.x, -(y - c.eye.y)) / D2R + 360) % 360);
else if (drag.kind === 'eye') { [c.eye.x, c.eye.y] = clampIn(c.site, x, y, 0); }
else if (drag.kind === 'measure') { S.board.measure.x2 = x; S.board.measure.y2 = y; }
else if (drag.kind === 'section') { c.section.x2 = x; c.section.y2 = y; }
else { [drag.it.x, drag.it.y] = clampIn(c.site, x, y, 0.1); closePops(); }
drag.moved = true; drawPlanOnly(); if (drag.kind !== 'measure') scheduleViews();
});
const end = ev => {
if (!drag) return;
const c = S.comp;
if (drag.kind === 'section') { const L = Math.hypot(c.section.x2 - c.section.x1, c.section.y2 - c.section.y1); if (L < 0.8) { c.section = drag.old; toast('剖切線太短,請拖長一點'); } else toast('已更新剖切線 A-A'); afterEdit(); }
else if (drag.kind === 'measure') { const M = S.board.measure, L = Math.hypot(M.x2 - M.x1, M.y2 - M.y1); if (L > 0.05) toast(`量度:${Math.round(L * 1000)} mm`); }
else if (drag.kind === 'item' && !drag.moved) { openItemPop(drag.it, drag.cx, drag.cy); }
else if (drag.moved) afterEdit();
drag = null;
};
cv.addEventListener('pointerup', end); cv.addEventListener('pointercancel', end);
cv.addEventListener('dragover', ev => ev.preventDefault());
cv.addEventListener('drop', ev => {
ev.preventDefault(); const id = ev.dataTransfer.getData('text/plain'); const p = libById(id); if (!p || !S._planTx) return;
const [px, py] = pos(ev), tx = S._planTx.tx; const [x, y] = clampIn(S.comp.site, tx.ix(px), tx.iy(py), 0.1);
addPlant(p, x, y);
});
}
function addPlant(p, x, y) {
const c = S.comp;
if (x === undefined) { // free spot: most distant from other items, preferring the right sun zone
let best = null;
for (let gx = 0.6; gx < c.site.W; gx += 0.5) for (let gy = 0.6; gy < c.site.D; gy += 0.5) {
if (!spotOk(c.site, gx, gy)) continue;
const d = Math.min(99, ...c.items.map(i => Math.hypot(i.x - gx, i.y - gy)));
const zoneOk = p.light.includes(zoneOfHours(sunAt(c.site, S.sun, gx, gy)));
const score = d + (zoneOk ? 2 : 0); if (!best || score > best.s) best = { x: gx, y: gy, s: score };
}
if (!best) { [x, y] = clampIn(c.site, c.site.W / 2, c.site.D / 2, 0.3); } else { x = best.x; y = best.y; }
}
const it = { uid: newUid(), kind: 'plant', id: p.id, x, y, role: isTreeLike(p) ? 'sec' : 'ter', seed: Math.floor(Math.random() * 1e4) };
c.items.push(it); S.board.sel = it.uid; afterEdit(); toast(`已加入 ${p.zh},位置 ${ptxt(x, y)}`);
}
let _viewsRaf = null;
function scheduleViews() { if (_viewsRaf) return; _viewsRaf = requestAnimationFrame(() => { _viewsRaf = null; drawViews(); }); }
function drawPlanOnly() {
const cv = $('#b-plan'), { ctx, w, h } = fit(cv), grid = $('#b-grid').checked;
S._planTx = drawPlantingPlan(ctx, w, h, S.comp, S.sun, {
zones: $('#b-zones').checked, grid, dims: grid, keys: $('#b-keys').checked, sel: S.board.sel,
ghost: S.board.ghost, ghostFrom: S.board.ghostFrom, notes: $('#b-clouds').checked ? S.board.notes : [], hoverNote: S.board.hoverNote,
section: S.comp.section, measure: S.board.measure, codes: S.board.codes, sheetNo: 'LP-02',
});
S.scales.board = scaleLabel(cv, S._planTx.tx.sc); $('#b-scale').textContent = S.scales.board;
drawMini('#b-bar', '#b-north-mini', S._planTx.tx.sc, S.comp.site.north);
if (S.tab === 'board') $('#tb-scale').textContent = S.scales.board;
}
function drawViews() {
const cs = $('#b-sect'); let f = fit(cs);
const r = drawSection(f.ctx, f.w, f.h, S.comp, S.comp.section, { codes: S.board.codes });
$('#b-sect-sc').textContent = scaleLabel(cs, r.sc);
f = fit($('#b-persp')); drawPerspective(f.ctx, f.w, f.h, S.comp);
}
function renderBoard() {
if (!S.comp || !S.sun) return;
S.board.checks = runChecks(S.comp, S.sun);
S.board.codes = plantCodes(S.comp);
renderChecks(); drawPlanOnly(); drawViews(); renderSchedule(); renderMonthDots(); syncBoardInputs();
const it = S.comp.items.find(i => i.uid === S.board.sel);
if (!$('#pop-item').hidden) { if (it) fillItemPop(it); else closePops(); }
}
function renderMonthDots() {
const sp = {}; S.comp.items.forEach(i => { const p = plantOf(i); if (p) sp[p.id] = p; });
$$('#b-months button').forEach((b, i) => {
const fl = Object.values(sp).filter(p => p.fl.includes(i + 1)).slice(0, 4);
b.querySelector('.dots').innerHTML = fl.map(p => ``).join('');
b.title = `${i + 1} 月` + (fl.length ? `:${fl.map(p => p.zh).join('、')} 開花` : '');
});
}
function renderSchedule() {
const C = S.board.codes, yrs = S.comp.years, NAT = p => p.native === true ? 'Y' : p.native === false ? 'N' : '?';
const rows = C.rows.map(r => {
const p = r.p, s0 = sizeAtYears(p, 0), sn = sizeAtYears(p, yrs), star = p.sizeSrc === 'stsg' ? '' : '*';
const warn = p.warn.map(w => `${WARN[w.k].icon}${esc(WARN[w.k].zh.replace(/(.*)/, ''))}`).join(' ');
return `| ${r.code} | ${p.zh}${esc(p.sci)} | ${r.qty} | ${fmt(s0.H)} × ${fmt(s0.S)} | ${fmt(sn.H)} × ${fmt(sn.S)}${star} | ${NAT(p)} | ${warn || '無'} |
`;
}).join('');
$('#b-sched').innerHTML = `| CODE | 品種 SPECIES | QTY | 種植 H×S m | Y${yrs} H×S m | 本地 | 留意 NOTES |
${rows || '| 未有植物。用「放植物」工具加入。 |
'}
| 共 ${S.comp.items.filter(i => plantOf(i)).length} 株/叢。種植時及 Y${yrs} 尺寸由本工具的生長曲線推算(假設)。* 成熟尺寸未全部核實。本地:Y 原生、N 外來、? 待核實。 |
`;
}
function renderChecks() {
const R = S.board.checks, n = { fail: 0, warn: 0, pass: 0 }; R.forEach(r => n[r.status]++);
const order = { fail: 0, warn: 1, pass: 2 };
const open = R.filter(r => r.status !== 'pass').sort((a, b) => order[a.status] - order[b.status]), passed = R.filter(r => r.status === 'pass');
S.board.notes = open.map((r, i) => ({ n: i + 1, id: r.id, items: r.items || [], status: r.status }));
$('#b-check').innerHTML = `✗ ${n.fail} 未符合 · ⚠ ${n.warn} 需要留意 · ✓ ${n.pass} 符合
紅筆雲線編號對應以下註記。設計原則本工具自訂,不是法規;香港指引引用政府或醫學文獻;地盤分析來自 LP-01。
` +
open.map((r, i) => `${i + 1}${esc(r.title)}
${RULE_TAG[r.tag]}${r.id} · ${srcLink(r.src)}${SOURCES[r.src] && SOURCES[r.src].unverified ? '(未核實)' : ''}
${esc(r.msg)}
${r.items && r.items.length ? `
${[...new Set(r.items)].slice(0, 6).map(u => { const it = S.comp.items.find(q => q.uid === u); return it ? `${(S.board.codes.map[it.id] || '')} ${esc(nameOf(it))} ${ptxt(it.x, it.y)}` : ''; }).filter(Boolean).join(';')}
` : ''}
${r.fix ? `
${r.fix.verb}建議:${esc(r.fix.label)}
` : ''}
`).join('') +
(passed.length ? `✓ 其餘 ${passed.length} 條符合
${passed.map(r => `- ${r.id} ${esc(r.title)}
`).join('')}
` : '');
$$('#b-check .cn').forEach(row => {
const r = R[+row.dataset.i], nn = +row.dataset.n;
row.addEventListener('mouseenter', () => { row.classList.add('hot'); S.board.hoverNote = nn; S.board.ghost = r.fix && r.fix.ghost ? r.fix.ghost : null; S.board.ghostFrom = r.fix && r.fix.from || null; drawPlanOnly(); });
row.addEventListener('mouseleave', () => { row.classList.remove('hot'); S.board.hoverNote = null; S.board.ghost = null; S.board.ghostFrom = null; drawPlanOnly(); });
});
$$('#b-check .apply').forEach(b => b.addEventListener('click', () => {
const r = R[+b.dataset.i], soil0 = S.comp.site.soil;
r.fix.apply(S.comp); S.board.ghost = null; S.board.ghostFrom = null; S.board.hoverNote = null;
if (S.comp.site.soil !== soil0) syncSiteInputs();
saveWork(); renderBoard();
const after = S.board.checks.find(x => x.id === r.id);
toast(`已套用:${r.fix.label}${after ? `(${r.id} 現在 ${{ fail: '✗', warn: '⚠', pass: '✓' }[after.status]})` : ''}`);
}));
}
function openItemPop(it, cx, cy) { fillItemPop(it); openPop('pop-item', cx, cy); }
function fillItemPop(it) {
const box = $('#b-selinfo'), p = plantOf(it);
if (!p) {
$('#pop-item-t').innerHTML = 'SCALE FIGURE 比例人物';
box.innerHTML = `${esc(nameOf(it))}
| 位置 x, y | ${ptxt(it.x, it.y)} m |
|---|
`;
} else {
const sz = sizeAtYears(p, S.comp.years), s0 = sizeAtYears(p, 0), z = zoneOfHours(sunAt(S.comp.site, S.sun, it.x, it.y)), code = S.board.codes && S.board.codes.map[p.id];
$('#pop-item-t').innerHTML = `SPECIMEN ${TYPE_ZH[p.type]}`;
box.innerHTML = `${code || ''}${window.LANG === 'en' ? esc(p.en) : p.zh}
${esc(p.sci)}${window.LANG === 'en' ? '' : ' · ' + esc(p.en)}
| 本地/外來 | ${nativeLabel(p)} |
| 日照需要 | ${p.light.map(l => LIGHT_ZH[l]).join('/')} |
| 位置 x, y | ${ptxt(it.x, it.y)} m,${ZONE_ZH[z]} |
| 種植時 H×S | ${fmt(s0.H)} × ${fmt(s0.S)} m |
| Y${S.comp.years} H×S | ${fmt(sz.H)} × ${fmt(sz.S)} m |
| 成熟 H×S | ${p.h[0]}–${p.h[1]} × ${p.s[0]}–${p.s[1]} m${p.sizeSrc === 'stsg' ? '' : '(未全部核實)'} |
${p.warn.map(w => `${WARN[w.k].icon} ${WARN[w.k].zh}:${esc(w.note)}
`).join('')}
`;
$('#sel-role').addEventListener('change', e => { it.role = e.target.value; afterEdit(); });
$('#sel-dup').addEventListener('click', () => { const [x, y] = clampIn(S.comp.site, it.x + 1, it.y + 0.6); const n = Object.assign({}, it, { uid: newUid(), x, y, seed: Math.floor(Math.random() * 1e4) }); S.comp.items.push(n); S.board.sel = n.uid; afterEdit(); fillItemPop(n); });
}
$('#sel-del').addEventListener('click', () => { S.comp.items = S.comp.items.filter(q => q.uid !== it.uid); S.board.sel = null; closePops(); afterEdit(); });
}
function renderLib() {
const q = S.board.q, f = S.board.filter, c = S.comp;
const list = LIB.filter(p => (f === 'all' || (f === 'native' ? p.native === true : f === 'tree' ? isTreeLike(p) : f === 'ground' ? (p.type === 'ground' || p.type === 'climber') : p.type === f))
&& (!q || (p.zh + p.en + p.sci).toLowerCase().includes(q)));
const box = $('#b-cards'); box.innerHTML = '';
list.forEach(p => {
const bad = p.warn.filter(w => w.k === 'invasive' || w.k === 'flagged').length, wn = p.warn.length - bad;
const tr = document.createElement('tr'); tr.className = 'pc' + (S.board.armed === p.id ? ' armed' : ''); tr.draggable = true; tr.dataset.id = p.id;
const est = p.sizeSrc === 'stsg' ? '' : p.hSrc ? ' *' : ' 未核實';
tr.innerHTML = ` |
${window.LANG === 'en' ? esc(p.en) : p.zh} ${p.native === true ? '本地' : ''} ${esc(p.sci)} ${window.LANG === 'en' ? '' : `${esc(p.en)} `} |
${TYPE_ZH[p.type]} | ${p.h[0]}–${p.h[1]} m${est} | ${p.s[0]}–${p.s[1]} m | ${p.fl.length ? flRange(p.fl) : '不顯眼'} | ${p.light.map(l => LIGHT_ZH[l]).join('/')} |
${p.native === true ? 'Y' : p.native === false ? 'N' : '?'} | ${bad ? `✗${bad}` : wn ? `⚠${wn}` : ''} |
| `;
tr.title = p.warn.map(w => `${WARN[w.k].zh}:${w.note}`).join('\n') || `${p.zh}:${nativeLabel(p)}`;
tr.addEventListener('dragstart', ev => ev.dataTransfer.setData('text/plain', p.id));
tr.addEventListener('click', () => { S.board.armed = p.id; $$('#b-cards tr.pc').forEach(r => r.classList.toggle('armed', r === tr)); setTool('place'); $('#drawer').hidden = true; toast(`已選 ${p.zh}:按平面放置`); });
tr.querySelector('.add').addEventListener('click', ev => { ev.stopPropagation(); addPlant(p); });
box.appendChild(tr);
requestAnimationFrame(() => {
const cv = tr.querySelector('canvas'), ctx = cv.getContext('2d');
const sp = plantSprite(p, 30, c.month, c.style, 7, 40), k = Math.min(104 / sp.cv.width, 70 / sp.cv.height);
ctx.fillStyle = PAPER; ctx.fillRect(0, 0, 112, 76); ctx.strokeStyle = INK; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(4, 73); ctx.lineTo(108, 73); ctx.stroke();
ctx.drawImage(sp.cv, 56 - sp.ax * k, 73 - sp.ay * k, sp.cv.width * k, sp.cv.height * k);
});
});
if (!list.length) box.innerHTML = '| 找不到相符的植物。 |
';
}
function flRange(fl) { const s = fl.slice().sort((a, b) => a - b); if (s.length === 12) return '全年'; return s.length <= 2 ? s.map(m => m + '月').join('、') : `${s[0]}–${s[s.length - 1]}月${s.length !== s[s.length - 1] - s[0] + 1 ? '(間斷)' : ''}`; }
function renderSources() {
$('#b-src').innerHTML = `本工具以香港政府公開指引及文獻為本。未核實的數值:大部分灌木及地被的尺寸、多數喬木的冠幅(香港資料一般只列樹高)、黃花風鈴木的樹高、大葉合歡及火焰木的「易斷枝」標示。植物配置表標「未核實」或「*」者即屬此類。
${Object.keys(SOURCES).map(k => { const s = SOURCES[k]; return `- ${s.url ? `${esc(s.t)}` : esc(s.t)}${s.unverified ? '(未核實)' : ''}
${esc(s.en)} `; }).join('')}
尺寸欄:「街道樹木選種名錄附錄 B」為高度及冠幅均已核實;「20 種常見市區樹木」只核實樹高;其餘為一般園藝參考估值。原生/外來:附錄 B、附錄 E、植物標本室資料庫。
`;
}
/* saved compositions */
function savedDB() { return lsGet(LS_KEY) || { comps: [] }; }
function saveVersion() {
const db = savedDB(), name = ($('#b-name').value || S.comp.name || '未命名').trim(); S.comp.name = name;
let e = db.comps.find(c => c.name === name); if (!e) { e = { name, versions: [] }; db.comps.unshift(e); }
e.versions.unshift({ ts: new Date().toISOString(), data: JSON.parse(JSON.stringify(S.comp)) }); e.versions = e.versions.slice(0, 20);
if (lsSet(LS_KEY, db)) toast(`已儲存「${name}」第 ${e.versions.length} 版`); else toast('瀏覽器不允許儲存(私密模式?)。請用「匯出 JSON」。');
renderSaved(); updateTitleBlock();
}
function renderSaved() {
const db = savedDB(), box = $('#b-saved');
if (!db.comps.length) { box.innerHTML = '未有已儲存的構圖。
'; return; }
box.innerHTML = db.comps.map((c, i) => `${esc(c.name)}${c.versions.length} 個版本,最新 ${c.versions[0].ts.slice(0, 16).replace('T', ' ')}
`).join('');
$$('#b-saved .it').forEach(el => {
const sel = el.querySelector('select'); sel.addEventListener('click', ev => ev.stopPropagation());
const load = () => { const c = db.comps[+el.dataset.i], v = c.versions[+sel.value]; setComp(JSON.parse(JSON.stringify(v.data))); saveWork(); renderAll(); renderSaved(); toast(`已載入「${c.name}」版本 ${c.versions.length - +sel.value}`); };
el.addEventListener('click', load); sel.addEventListener('change', load);
});
}
/* ================= sheets, title block & boot ================= */
function updateTitleBlock() {
const sh = SHEETS[S.tab];
$('#tb-proj-name').textContent = S.comp.name || '未命名';
$('#tb-title-zh').textContent = window.LANG === 'en' ? sh.en : sh.zh; $('#tb-title-en').textContent = window.LANG === 'en' ? '' : sh.en;
$('#tb-no').textContent = sh.no; $('#tb-scale').textContent = S.scales[S.tab] || 'NTS';
$('#tb-date').textContent = ymd(S.comp.created);
$('#m-no').textContent = sh.no; $('#m-title').textContent = sh.zh;
$$('.reg').forEach(b => b.classList.toggle('on', b.dataset.sheet === S.tab));
const n = $('#tb-north'); if (n) { const { ctx, w, h } = fitFixed(n); northPoint(ctx, w / 2, h / 2 + 5, 10, S.comp.site.north); }
}
function renderTab(t) {
if (t === 'site') renderSite();
if (t === 'tree') renderTree();
if (t === 'why') renderWhy();
if (t === 'board') { renderBoard(); if (!$('#drawer').hidden) renderLib(); }
}
function renderAll() { renderTab(S.tab); renderSaved(); updateTitleBlock(); }
function showTab(t) {
if (!SHEETS[t]) t = 'site';
S.tab = t; $('#sheet').dataset.sheet = t;
const pl = $('#plate-' + t); pl.classList.remove('flip'); void pl.offsetWidth; pl.classList.add('flip');
closePops(); if (t !== 'board') { $('#drawer').hidden = true; if (S.board.tool === 'place') setTool('select'); }
$('#register').classList.remove('open'); $('#m-cur').setAttribute('aria-expanded', 'false');
try { history.replaceState(null, '', '#' + SHEETS[t].no); } catch (e) { /* file:// */ }
applyMView(t); renderTab(t); updateTitleBlock();
}
/* phones: one drawing at a time */
function initMobileSwitch() {
for (const t of ORDER) {
const pl = $('#plate-' + t), items = Array.from(pl.querySelectorAll(':scope > .dwg, :scope > .spec'));
const sw = document.createElement('div'); sw.className = 'dswitch'; sw.setAttribute('role', 'tablist');
sw.innerHTML = items.map((d, i) => ``).join('');
pl.insertBefore(sw, pl.firstChild.nextSibling);
sw.querySelectorAll('button').forEach(b => b.addEventListener('click', () => { S.mview[t] = +b.dataset.i; applyMView(t); renderTab(t); }));
}
}
function applyMView(t) {
const pl = $('#plate-' + t), items = Array.from(pl.querySelectorAll(':scope > .dwg, :scope > .spec'));
items.forEach((d, i) => d.classList.toggle('mon', i === S.mview[t]));
pl.querySelectorAll('.dswitch button').forEach((b, i) => b.classList.toggle('on', i === S.mview[t]));
}
function boot() {
const work = lsGet(LS_WORK);
const c = validComp(work) ? work : exampleComposition();
S.comp = c; setComp(c);
initSite(); initTree(); initWhy(); initBoard(); initMobileSwitch();
syncSiteInputs(); syncBoardInputs();
$$('.reg').forEach(b => b.addEventListener('click', () => showTab(b.dataset.sheet)));
$('#m-cur').addEventListener('click', () => { const r = $('#register'), open = !r.classList.contains('open'); r.classList.toggle('open', open); $('#m-cur').setAttribute('aria-expanded', String(open)); });
$$('.pop [data-close]').forEach(b => b.addEventListener('click', () => { b.closest('.pop').hidden = true; if (b.closest('#pop-item')) { S.board.sel = null; drawPlanOnly(); } }));
document.addEventListener('pointerdown', ev => {
const t = ev.target;
if (t.closest('.pop') || t.closest('.toolbar') || t.closest('canvas') || t.closest('#tb-project') || t.closest('.drawer')) return;
closePops();
});
document.addEventListener('keydown', ev => {
const typing = /input|select|textarea/i.test(ev.target.tagName);
if (ev.key === 'Escape') {
if (S.tab === 'site' && SE.draft) { SE.draft = null; SE.tip = ''; drawSiteOnly(); return; }
closePops(); if (!$('#drawer').hidden) closeDrawer(); if (S.board.tool !== 'select') setTool('select'); if (S.siteUi.viewMode !== 'off') setSiteTool('off'); $('#register').classList.remove('open'); return;
}
if (typing) return;
if (S.tab === 'site') {
if (ev.key === 'Enter' && SE.draft && SE.draft.pts.length >= 3) { finishDraft(); return; }
if ((ev.key === 'Delete' || ev.key === 'Backspace') && SE.sel) { if (SE.selV != null) delVertex(SE.sel, SE.selV); else if (SE.sel !== 'site') delBuilding(SE.sel); ev.preventDefault(); return; }
const k = { v: 'off', b: 'boundary', h: 'bldg' }[ev.key.toLowerCase()]; if (k && !ev.ctrlKey && !ev.metaKey) setSiteTool(k);
}
const i = ORDER.indexOf(S.tab);
if (ev.key === ']' || ev.key === 'PageDown') showTab(ORDER[(i + 1) % 4]);
if (ev.key === '[' || ev.key === 'PageUp') showTab(ORDER[(i + 3) % 4]);
if (S.tab === 'board') { const k = { v: 'select', p: 'place', m: 'measure', s: 'section', e: 'view' }[ev.key.toLowerCase()]; if (k && !ev.ctrlKey && !ev.metaKey) setTool(k); }
});
let rt; window.addEventListener('resize', () => { clearTimeout(rt); rt = setTimeout(() => { closePops(); renderTab(S.tab); updateTitleBlock(); }, 150); });
loadFigures(() => { if (S.tab === 'board' || S.tab === 'tree') renderTab(S.tab); });
const hsh = decodeURIComponent((location.hash || '').slice(1)), byNo = ORDER.find(k => SHEETS[k].no === hsh);
showTab(byNo || (SHEETS[hsh] ? hsh : 'site'));
if (document.fonts && document.fonts.ready) document.fonts.ready.then(() => renderTab(S.tab));
}
document.addEventListener('DOMContentLoaded', boot);