distToSegment function
Calculates the shortest distance from point p to the segment v-w.
Implementation
@pragma('vm:prefer-inline')
double distToSegment(Offset p, Offset v, Offset w) {
final l2 = (v - w).distanceSquared;
if (l2 == 0) return (p - v).distance;
final t = ((p - v).dx * (w - v).dx + (p - v).dy * (w - v).dy) / l2;
// Clamping t to [0,1] ensures we find distance to segment, not line
final clampedT = math.max(0, math.min(1, t));
final proj =
Offset(v.dx + clampedT * (w - v).dx, v.dy + clampedT * (w - v).dy);
return (p - proj).distance;
}