Fix the quadrant overlap test in a quadtree
Your task
Your collision culling uses a quadtree: each node splits into four child quadrants, and a range query descends into every child the range overlaps. Objects on a divider or an edge went missing from queries. The fix computes the four child boxes and tests each one against the range.
An assistant wrote overlapping_quadrants(node, range_box). It is in the editor. It has a bug. Find it and fix it.
Input and output:
node: the node's box,[x, y, w, h], with y growing downward. All values are integers.range_box: the query box,[rx, ry, rw, rh].- Return the indexes of the children the range overlaps, in ascending order: 0 top left, 1 top right, 2 bottom left, 3 bottom right.
Rules the tests check:
- If either list does not have exactly 4 items, or any width or height is negative, return
[]. - Split at
midx = x + floor(w / 2)andmidy = y + floor(h / 2). - The children, each as
[cx, cy, cw, ch]:- 0:
[x, y, midx - x, midy - y] - 1:
[midx, y, x + w - midx, midy - y] - 2:
[x, midy, midx - x, y + h - midy] - 3:
[midx, midy, x + w - midx, y + h - midy]
- 0:
- So when a size is odd, the right and bottom children are 1 larger, and the four children cover the node exactly.
- A child overlaps the range when
rx <= cx + cwandrx + rw >= cx, andry <= cy + chandry + rh >= cy. Touching edges count.
Examples
overlapping_quadrants(node: list[int], range_box: list[int]) -> list[int]Example 1
Input
overlapping_quadrants([0, 0, 100, 100], [10, 10, 5, 5])Output
[0]Example 2
Input
overlapping_quadrants([0, 0, 100, 100], [50, 50, 0, 0])Output
[0, 1, 2, 3]