navigation.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Static connectivity rejection; reachable A* paths remain unchanged."""
  2. def invalidate_navigation(level):
  3. level.npc_topology_revision = getattr(level, 'npc_topology_revision', 0) + 1
  4. level.recal_npc_paths = True
  5. class NavigationCache:
  6. def __init__(self):
  7. self.block = None
  8. self.signature = None
  9. self.labels = None
  10. self.builds = 0
  11. self.rejections = 0
  12. def disconnected(self, level, start, target, lower, upper):
  13. width, height = level.map_x, level.map_y
  14. # Legacy searches can extend outside map bounds; do not prune those.
  15. if not all(len(p) == 2 and all(isinstance(v, int) for v in p)
  16. and 0 <= p[0] < width and 0 <= p[1] < height
  17. for p in (start, target, lower, upper)):
  18. return False
  19. signature = (width, height, getattr(level, 'npc_topology_revision', 0))
  20. if self.block is not level.block or self.signature != signature:
  21. self.block, self.signature = level.block, signature
  22. self._build(width, height)
  23. if self.labels[start[0]][start[1]] != self.labels[target[0]][target[1]]:
  24. self.rejections += 1
  25. return True
  26. return False
  27. def _build(self, width, height):
  28. horizontal, vertical = self.block
  29. labels = [[-1] * height for _ in range(width)]
  30. component = 0
  31. for x in range(width):
  32. for y in range(height):
  33. if labels[x][y] != -1:
  34. continue
  35. labels[x][y] = component
  36. pending = [(x, y)]
  37. while pending:
  38. cx, cy = pending.pop()
  39. for nx, ny, edge in (
  40. (cx, cy - 1, horizontal[cx][cy]),
  41. (cx + 1, cy, vertical[cx + 1][cy]),
  42. (cx, cy + 1, horizontal[cx][cy + 1]),
  43. (cx - 1, cy, vertical[cx][cy])):
  44. if (edge <= 0 and 0 <= nx < width and 0 <= ny < height
  45. and labels[nx][ny] == -1):
  46. labels[nx][ny] = component
  47. pending.append((nx, ny))
  48. component += 1
  49. self.labels = labels
  50. self.builds += 1