A clamp only works if its range exists
Cookie jumps onto your windows and must never land near a corner. The line that kept her safe had two quiet bugs, and one of them only appeared on narrow windows.
From building Cookie
Cookie is a tiny cat that walks along the top of your windows. Before she jumps to a new one, the planner picks a landing point, and that point has to stay at least 25 points from either corner, or she appears to stand on nothing. Here's the line that was meant to guarantee it:
let clampedX = max(surface.bounds.minX + inset, min(surface.bounds.maxX - inset, startPoint.x))Two bugs in one line
The first is what it clamps. startPoint.x is where she's standing now. If the target window is off to one side, her position is outside its range, so the clamp pins her to the nearest allowed spot: exactly 25 points from the corner, every time. The rule meant to keep her away from the edge was sending her as close to it as it allowed.
The second is hiding in the bounds. A clamp assumes the lower bound is below the upper one. On a window narrower than 50 points, minX + inset is past maxX - inset, the range doesn't exist, and the expression still returns a number. It just isn't a safe one.
The fix
Clamp the landing point the surface already chose, which is the middle of the window's top edge, and only when the corridor really exists. On a window too narrow to have one, the middle is the best answer anyway:
let minX = surface.bounds.minX + inset
let maxX = surface.bounds.maxX - inset
if minX <= maxX {
landingPt.x = max(minX, min(maxX, surface.landingPoint.x))
}What I took from it
Every clamp has a precondition nobody writes down: low must not exceed high. When the bounds are computed from something the user controls, like the size of their windows, it's worth checking. And when a value keeps landing exactly on a limit, the limit is probably working and the input is probably wrong.
