// De rode stip loopt over de geplande lijn, niet in een sprong tussen twee metingen. function penRouteFrom (strokes, home) { const pts = []; const push = (x, y) => { const last = pts[pts.length - 1]; if (last && Math.hypot(last[0] - x, last[1] - y) < 0.05) return; pts.push([x, y]); }; if (home) push(home[0], home[1]); for (const stroke of strokes || []) { for (const point of stroke || []) push(point[0], point[1]); } if (home) push(home[0], home[1]); if (pts.length < 2) return null; const cum = [0]; for (let i = 1; i < pts.length; i++) { cum.push(cum[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1])); } return { pts, cum }; } function penProject (route, x, y, hint) { const pts = route.pts; const cum = route.cum; let best = { along: 0, err: Infinity }; let ahead = null; for (let i = 0; i < pts.length - 1; i++) { const ax = pts[i][0]; const ay = pts[i][1]; const bx = pts[i + 1][0]; const by = pts[i + 1][1]; const dx = bx - ax; const dy = by - ay; const len2 = dx * dx + dy * dy; let t = len2 < 1e-9 ? 0 : ((x - ax) * dx + (y - ay) * dy) / len2; if (t < 0) t = 0; else if (t > 1) t = 1; const px = ax + dx * t; const py = ay + dy * t; const err = Math.hypot(x - px, y - py); const along = cum[i] + Math.hypot(px - ax, py - ay); if (err < best.err) best = { along, err }; if (along + 1e-6 >= hint - 1 && (!ahead || err < ahead.err)) ahead = { along, err }; } if (ahead && ahead.err <= Math.max(2.5, best.err + 0.4)) return ahead; return best; } function penAt (route, along) { const pts = route.pts; const cum = route.cum; const total = cum[cum.length - 1]; const dist = Math.max(0, Math.min(total, along)); let lo = 1; let hi = cum.length - 1; while (lo < hi) { const mid = (lo + hi) >> 1; if (cum[mid] < dist) lo = mid + 1; else hi = mid; } const span = cum[lo] - cum[lo - 1]; const t = span > 1e-6 ? (dist - cum[lo - 1]) / span : 0; return [ pts[lo - 1][0] + (pts[lo][0] - pts[lo - 1][0]) * t, pts[lo - 1][1] + (pts[lo][1] - pts[lo - 1][1]) * t, ]; } function penStep (along, goal, mmPerMin, dt) { const gap = goal - along; if (Math.abs(gap) < 0.02) return goal; const step = Math.min(Math.abs(gap), Math.max(1, mmPerMin) / 60 * dt); return along + Math.sign(gap) * step; }