queryMap method

Map<int, Rect> queryMap(
  1. Rect rect
)

Query the QuadTree for objects that intersect with the given rect. Returns a map of object identifiers and their bounds.

Implementation

Map<int, ui.Rect> queryMap(ui.Rect rect) {
  //if (rect.isEmpty) return const {};

  final root = _root;
  if (root == null) return const {};

  var offset = 0;
  final objects = _objects;
  final results = HashMap<int, ui.Rect>();

  // If the query rectangle fully contains the QuadTree boundary.
  // Return all objects in the QuadTree.
  if (rect.left <= boundary.left &&
      rect.top <= boundary.top &&
      rect.right >= boundary.right &&
      rect.bottom >= boundary.bottom) {
    if (root._subdivided) {
      for (var i = 0; i < _nextObjectId; i++) {
        if (_id2node[i] == 0) continue;
        offset = i * _objectSize;
        results[i] = ui.Rect.fromLTWH(
          objects[offset + 0],
          objects[offset + 1],
          objects[offset + 2],
          objects[offset + 3],
        );
      }
    } else {
      final rootIds = root._ids;
      for (final id in rootIds) {
        offset = id * _objectSize;
        results[id] = ui.Rect.fromLTWH(
          objects[offset + 0],
          objects[offset + 1],
          objects[offset + 2],
          objects[offset + 3],
        );
      }
    }
    return results;
  }

  // Visit all suitable nodes in the QuadTree and collect objects.
  final queue = Queue<QuadTree$Node>()..add(root);
  while (queue.isNotEmpty) {
    final node = queue.removeFirst();
    if (!_overlaps(node.boundary, rect)) continue;
    if (node.subdivided) {
      queue
        ..add(node._northWest!)
        ..add(node._northEast!)
        ..add(node._southWest!)
        ..add(node._southEast!);
    } else {
      for (final id in node._ids) {
        offset = id * _objectSize;
        final left = objects[offset + 0],
            top = objects[offset + 1],
            width = objects[offset + 2],
            height = objects[offset + 3];
        if (_overlapsLTWH(rect, left, top, width, height))
          results[id] = ui.Rect.fromLTWH(left, top, width, height);
      }
    }
  }
  return results;
}