import {createDirectWalk} from '../direct.mjs'; import {createRouteFollower} from '../../line/route-follower.mjs'; const NEAR_GATE_M = 35; const MAX_GAP_MS = 6000; const SNAP_TOLERANCE_M = 2; const validPoint = p => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite) && Math.abs(p[0]) <= 180 && Math.abs(p[1]) <= 90; export function createGateHandoff(plan, maths, compass) { const gate = plan.gate; const metres = (a, b) => maths.distanceKm(...a, ...b) * 1000; const field = createDirectWalk(maths, compass); field.setTargets(plan.fieldPins); const pins = [gate.centre, ...plan.fieldPins.map(pin => pin.coordinate)]; const fieldLengthM = pins.slice(1).reduce((sum, at, i) => sum + metres(pins[i], at), 0); const axis = validPoint(gate.fieldSide) && metres(gate.centre, gate.fieldSide) >= 3 ? maths.initialBearingDeg(...gate.centre, ...gate.fieldSide) : null; function position(at) { const distance = metres(gate.centre, at); const angle = (maths.initialBearingDeg(...gate.centre, ...at) - axis) * Math.PI / 180; return {along: distance * Math.cos(angle), across: distance * Math.sin(angle), distance}; } let route = null, roadLengthM = null, leg = 'road', lastTime = -Infinity; let stage = 'approach', enteredBy = null; function setRoad(saved) { route = null; roadLengthM = null; stage = 'approach'; const response = saved?.response; const geometry = response?.routes?.[0]?.geometry; const coords = geometry?.coordinates; const snaps = response?.waypoints; if (!gate.agreed || !validPoint(gate.roadside) || saved?.gateId !== gate.id || response?.code !== 'Ok' || !Array.isArray(coords) || coords.length < 2 || !Array.isArray(snaps) || snaps.length !== 2) return false; const endpoints = [plan.roadStart, gate.roadside]; const tips = [coords[0], coords.at(-1)]; if (!endpoints.every((at, i) => validPoint(at) && validPoint(tips[i]) && validPoint(snaps[i]?.location) && metres(at, tips[i]) <= SNAP_TOLERANCE_M && metres(at, snaps[i].location) <= SNAP_TOLERANCE_M)) return false; try { route = createRouteFollower(geometry, maths); } catch { return false; } roadLengthM = coords.slice(1).reduce((sum, at, i) => sum + metres(coords[i], at), 0); return true; } function enterField(reason) { if (leg !== 'road' || !gate.agreed || gate.locked) return false; leg = 'field'; enteredBy = reason; field.restart(); return true; } function restart() { leg = 'road'; enteredBy = null; lastTime = -Infinity; stage = 'approach'; field.restart(); } const roadEnd = validPoint(gate.roadside) && axis !== null ? position(gate.roadside) : null; function observe(at, fix) { const p = position(at); if (!route || axis === null || !Number.isFinite(gate.widthM) || gate.widthM <= 0 || !roadEnd || roadEnd.along >= -1 || roadEnd.distance > NEAR_GATE_M || Math.abs(roadEnd.across) > gate.widthM / 2 || p.distance > NEAR_GATE_M || Math.abs(p.across) + fix.accuracyM > gate.widthM / 2) { stage = 'approach'; return; } const uncertainty = Math.max(1, fix.accuracyM); if (p.along < -uncertainty) stage = 'roadside'; else if (Math.abs(p.along) <= uncertainty) { if (stage === 'roadside') stage = 'opening'; } else { if (stage === 'opening' && p.along >= uncertainty + 2) { enterField('crossing'); stage = 'approach'; } else if (stage !== 'opening') stage = 'approach'; } } function locate(fix, now = Date.now()) { const quality = compass.fixQuality(fix, now); const at = fix ? [fix.longitude, fix.latitude] : null; const fresh = quality === 'usable'; const nearby = validPoint(at) && ['usable', 'poor'].includes(quality) && metres(gate.centre, at) <= NEAR_GATE_M; let sampleQuality = quality; if (!fresh) stage = 'approach'; if (Number.isFinite(fix?.timestampMs) && fix.timestampMs <= now) { if (fix.timestampMs < lastTime) { sampleQuality = 'out-of-order'; stage = 'approach'; } else if (fix.timestampMs > lastTime) { if (fix.timestampMs - lastTime > MAX_GAP_MS) stage = 'approach'; lastTime = fix.timestampMs; if (fresh && leg === 'road' && gate.agreed && !gate.locked) observe(at, fix); } } const measured = sampleQuality === 'usable'; if (leg === 'field') { const result = measured ? field.locate(fix, now) : {status:'waiting'}; const target = plan.fieldPins[result.targetIndex ?? 0]; return {leg, enteredBy, quality: sampleQuality, status: result.status, target: target?.name, remainingM: result.status === 'complete' ? 0 : result.remainingM, bearingDeg: result.bearingDeg}; } const projection = measured && route ? route(fix, now) : null; return {leg, quality: sampleQuality, nearby, target: gate.name, roadAvailable: Boolean(route), roadLengthM, roadRemainingM: projection?.status === 'ok' && !projection.offRoute ? projection.remainingM : null, gateDistanceM: measured ? metres(at, gate.centre) : null, fieldLengthM, locked: Boolean(gate.locked), agreed: Boolean(gate.agreed)}; } return {locate, setRoad, startField: () => enterField('manual'), restart}; }