Skip to content

Instantly share code, notes, and snippets.

@arturaz
Created April 9, 2012 18:16
Show Gist options
  • Save arturaz/2345182 to your computer and use it in GitHub Desktop.
Save arturaz/2345182 to your computer and use it in GitHub Desktop.
private void nearest(
final int index, final float x, final float y, final int depth,
final Result result
) {
if (index == -1) return;
final Node node = nodes[index];
// final Node node = (Node) unsafe.getObject(
// nodes, Unsafe.ARRAY_OBJECT_BASE_OFFSET +
// Unsafe.ARRAY_OBJECT_INDEX_SCALE * index
// );
final float ad = depth % 2 == 0 ? x - node.x : y - node.y;
// recurse near, and perhaps far as well
int near, far;
if (ad <= 0) {
near = node.left;
far = node.right;
}
else {
near = node.right;
far = node.left;
}
nearest(near, x, y, depth + 1, result);
if (ad * ad < result.distance) {
nearest(far, x, y, depth + 1, result);
}
// do we beat the old distance?
final float distanceX = (x - node.x) * (x - node.x);
if (distanceX < result.distance) {
final float distance = distanceX + (y - node.y) * (y - node.y);
if (distance < result.distance) {
result.index = index;
result.distance = distance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment