|
@@ -0,0 +1,208 @@
|
|
|
|
|
+"""Route equivalence and synthetic many-NPC chase-stage benchmarks."""
|
|
|
|
|
+import ast
|
|
|
|
|
+import argparse
|
|
|
|
|
+import json
|
|
|
|
|
+from pathlib import Path
|
|
|
|
|
+import random
|
|
|
|
|
+import statistics
|
|
|
|
|
+import sys
|
|
|
|
|
+import time
|
|
|
|
|
+from types import SimpleNamespace as NS
|
|
|
|
|
+import unittest
|
|
|
|
|
+
|
|
|
|
|
+ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
+sys.path.insert(0, str(ROOT))
|
|
|
|
|
+
|
|
|
|
|
+import numpy as np
|
|
|
|
|
+from client_local.algo.navigation import invalidate_navigation
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def load_search(path, scene):
|
|
|
|
|
+ tree = ast.parse(path.read_text(encoding='utf-8-sig'))
|
|
|
|
|
+ tree.body = [n for n in tree.body if not (isinstance(n, ast.ImportFrom)
|
|
|
|
|
+ and n.module == 'client_local.level')]
|
|
|
|
|
+ scope = {'level': NS(current_level=scene)}
|
|
|
|
|
+ exec(compile(tree, str(path), 'exec'), scope)
|
|
|
|
|
+ return NS(**scope)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def scene(width=12, height=10):
|
|
|
|
|
+ value = NS(map_x=width, map_y=height,
|
|
|
|
|
+ block=np.zeros((2, width + 1, height + 1), dtype=np.int64), bombs=set(),
|
|
|
|
|
+ recal_npc_paths=True, me=NS(x=width - 2, y=height // 2),
|
|
|
|
|
+ district_square_grid={'x1': 0, 'y1': 0, 'x2': width - 1, 'y2': height - 1})
|
|
|
|
|
+ value.get_bomb_instance = lambda x, y: [1] if (x, y) in value.bombs else []
|
|
|
|
|
+ return value
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def searches(value):
|
|
|
|
|
+ return (load_search(ROOT / 'tests/navigation_reference.py', value),
|
|
|
|
|
+ load_search(ROOT / 'client_local/algo/aStar.py', value))
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class NavigationTests(unittest.TestCase):
|
|
|
|
|
+ def test_all_small_wall_and_bomb_combinations(self):
|
|
|
|
|
+ cl = scene(2, 2)
|
|
|
|
|
+ old, new = searches(cl)
|
|
|
|
|
+ edges = [(0, 0, 1), (0, 1, 1), (1, 1, 0), (1, 1, 1)]
|
|
|
|
|
+ points = [(x, y) for x in range(2) for y in range(2)]
|
|
|
|
|
+ for wall_bits in range(16):
|
|
|
|
|
+ for bit, (plane, x, y) in enumerate(edges):
|
|
|
|
|
+ cl.block[plane][x][y] = (wall_bits >> bit) & 1
|
|
|
|
|
+ invalidate_navigation(cl)
|
|
|
|
|
+ for bomb_bits in range(16):
|
|
|
|
|
+ cl.bombs = {point for bit, point in enumerate(points) if bomb_bits & (1 << bit)}
|
|
|
|
|
+ for start in points:
|
|
|
|
|
+ for target in points:
|
|
|
|
|
+ self.assertEqual(old.cal_path(start, target, (0, 0), (1, 1)),
|
|
|
|
|
+ new.cal_path(start, target, (0, 0), (1, 1)))
|
|
|
|
|
+
|
|
|
|
|
+ def test_random_routes_match_exactly(self):
|
|
|
|
|
+ for seed in range(80):
|
|
|
|
|
+ rng = random.Random(seed)
|
|
|
|
|
+ cl = scene(9, 7)
|
|
|
|
|
+ cl.block[:] = np.array([rng.choice((0, 0, 0, 1, 2, -1))
|
|
|
|
|
+ for _ in range(cl.block.size)]).reshape(cl.block.shape)
|
|
|
|
|
+ cl.bombs = {(rng.randrange(9), rng.randrange(7)) for _ in range(10)}
|
|
|
|
|
+ old, new = searches(cl)
|
|
|
|
|
+ for _ in range(15):
|
|
|
|
|
+ start, target = [(rng.randrange(9), rng.randrange(7)) for _ in range(2)]
|
|
|
|
|
+ lower = rng.randrange(9), rng.randrange(7)
|
|
|
|
|
+ upper = rng.randrange(lower[0], 9), rng.randrange(lower[1], 7)
|
|
|
|
|
+ with self.subTest(seed=seed, start=start, target=target):
|
|
|
|
|
+ self.assertEqual(old.cal_path(start, target, lower, upper),
|
|
|
|
|
+ new.cal_path(start, target, lower, upper))
|
|
|
|
|
+
|
|
|
|
|
+ def test_obstacle_hooks_invalidate_connectivity(self):
|
|
|
|
|
+ cl = scene(5, 3)
|
|
|
|
|
+ old, new = searches(cl)
|
|
|
|
|
+ args = (0, 1), (4, 1), (0, 0), (4, 2)
|
|
|
|
|
+ self.assertTrue(new.cal_path(*args))
|
|
|
|
|
+ tree = ast.parse((ROOT / 'client_local/sprite/obstacle_instance.py').read_text(encoding='utf-8-sig'))
|
|
|
|
|
+ cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'ObstacleInstance')
|
|
|
|
|
+ obstacle = NS(x=2, y=0, obstacle={'BLOCK': [[[0] * 4 for _ in range(2)], [[1] * 3]] ,
|
|
|
|
|
+ 'BLOCK_FLAME': [[[0] * 4 for _ in range(2)], [[0] * 3]]})
|
|
|
|
|
+ cl.block_flame = cl.block.copy()
|
|
|
|
|
+ for method_name, expected in (('setup', False), ('uninstall', True)):
|
|
|
|
|
+ method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == method_name)
|
|
|
|
|
+ nodes = []
|
|
|
|
|
+ for node in method.body:
|
|
|
|
|
+ dumped = ast.dump(node)
|
|
|
|
|
+ if ('navigation_changed' in dumped or 'invalidate_navigation' in dumped
|
|
|
|
|
+ or isinstance(node, ast.For) and 'block_flame' in dumped):
|
|
|
|
|
+ nodes.append(node)
|
|
|
|
|
+ exec(compile(ast.Module(body=nodes, type_ignores=[]), '<obstacle-hooks>', 'exec'),
|
|
|
|
|
+ {'self': obstacle, 'level': NS(current_level=cl)})
|
|
|
|
|
+ self.assertEqual(bool(new.cal_path(*args)), expected)
|
|
|
|
|
+ self.assertEqual(new.cal_path(*args), old.cal_path(*args))
|
|
|
|
|
+ self.assertTrue(cl.recal_npc_paths)
|
|
|
|
|
+ self.assertEqual(cl._npc_navigation.builds, 3)
|
|
|
|
|
+
|
|
|
|
|
+ def test_bomb_move_throw_remove_and_map_reload_have_no_stale_answers(self):
|
|
|
|
|
+ cl = scene(7, 1)
|
|
|
|
|
+ old, new = searches(cl)
|
|
|
|
|
+ args = (0, 0), (6, 0), (0, 0), (6, 0)
|
|
|
|
|
+ for bombs in ({(3, 0)}, set(), {(4, 0)}, set(), {(0, 0)}, set()):
|
|
|
|
|
+ cl.bombs = bombs
|
|
|
|
|
+ self.assertEqual(old.cal_path(*args), new.cal_path(*args))
|
|
|
|
|
+ self.assertEqual(cl._npc_navigation.builds, 1)
|
|
|
|
|
+ cl.block = cl.block.copy()
|
|
|
|
|
+ cl.block[1][3][0] = 1
|
|
|
|
|
+ self.assertEqual(old.cal_path(*args), new.cal_path(*args))
|
|
|
|
|
+ self.assertEqual(cl._npc_navigation.builds, 2)
|
|
|
|
|
+
|
|
|
|
|
+ def test_dynamic_wall_and_bomb_mutations(self):
|
|
|
|
|
+ cl = scene(9, 7)
|
|
|
|
|
+ old, new = searches(cl)
|
|
|
|
|
+ rng = random.Random(3007)
|
|
|
|
|
+ for _ in range(1200):
|
|
|
|
|
+ plane, x, y = rng.randrange(2), rng.randrange(9), rng.randrange(7)
|
|
|
|
|
+ cl.block[plane][x][y] = rng.choice((0, 1, 2, -1))
|
|
|
|
|
+ invalidate_navigation(cl)
|
|
|
|
|
+ cl.bombs = {(rng.randrange(9), rng.randrange(7)) for _ in range(4)}
|
|
|
|
|
+ args = (rng.randrange(9), rng.randrange(7)), (rng.randrange(9), rng.randrange(7)), (0, 0), (8, 6)
|
|
|
|
|
+ self.assertEqual(old.cal_path(*args), new.cal_path(*args))
|
|
|
|
|
+
|
|
|
|
|
+ def test_ghosts_same_point_and_boundary_queries_match(self):
|
|
|
|
|
+ cl = scene(7, 6)
|
|
|
|
|
+ cl.block[1][3][:6] = 1
|
|
|
|
|
+ old, new = searches(cl)
|
|
|
|
|
+ for ghost in (True, False):
|
|
|
|
|
+ for start, target, lower, upper in (
|
|
|
|
|
+ ((0, 0), (6, 5), (0, 0), (6, 5)),
|
|
|
|
|
+ ((2, 2), (2, 2), (0, 0), (6, 5)),
|
|
|
|
|
+ ((0, 0), (1, 0), (-1, 0), (6, 5))):
|
|
|
|
|
+ self.assertEqual(old.cal_path(start, target, lower, upper, ghost),
|
|
|
|
|
+ new.cal_path(start, target, lower, upper, ghost))
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def chase_function(search, cl):
|
|
|
|
|
+ tree = ast.parse((ROOT / 'client_local/sprite/npc.py').read_text(encoding='utf-8-sig'))
|
|
|
|
|
+ cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Npc')
|
|
|
|
|
+ method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == 'chase_hero')
|
|
|
|
|
+ scope = {'aStar': search, 'level': NS(current_level=cl)}
|
|
|
|
|
+ exec(compile(ast.Module(body=[method], type_ignores=[]), '<real-chase>', 'exec'), scope)
|
|
|
|
|
+ return scope['chase_hero']
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def benchmark(output):
|
|
|
|
|
+ results = []
|
|
|
|
|
+ for kind, count in [('open', 80), ('open', 240), ('wall', 80), ('wall', 240),
|
|
|
|
|
+ ('bomb', 160), ('dynamic-wall', 160), ('mixed', 160)]:
|
|
|
|
|
+ cl = scene(40, 30)
|
|
|
|
|
+ if kind in ('wall', 'mixed', 'dynamic-wall'):
|
|
|
|
|
+ cl.block[1][20][:30] = 1
|
|
|
|
|
+ if kind == 'bomb':
|
|
|
|
|
+ cl.bombs = {(20, y) for y in range(30)}
|
|
|
|
|
+ old, new = searches(cl)
|
|
|
|
|
+ rng = random.Random(441)
|
|
|
|
|
+ units = []
|
|
|
|
|
+ for i in range(count):
|
|
|
|
|
+ x = rng.randrange(1, 19) if kind != 'mixed' or i % 2 else rng.randrange(21, 38)
|
|
|
|
|
+ npc = NS(x=x, y=rng.randrange(1, 29), resentful=True, mocking=False, friendly=False,
|
|
|
|
|
+ imitating=False, speed=1, original_speed=1, free_chasing=False,
|
|
|
|
|
+ chasing_monster=False, is_ghost=False, chase_path={}, motion=None)
|
|
|
|
|
+ npc.set_motion = lambda motion=None, npc=npc: setattr(npc, 'motion', motion)
|
|
|
|
|
+ units.append(npc)
|
|
|
|
|
+ samples = {'before': [], 'after': []}
|
|
|
|
|
+ cold = {}
|
|
|
|
|
+ snapshots = {}
|
|
|
|
|
+ for cycle in range(3):
|
|
|
|
|
+ for name, search in ((('before', old), ('after', new)) if cycle % 2 == 0 else
|
|
|
|
|
+ (('after', new), ('before', old))):
|
|
|
|
|
+ cl._npc_navigation = None
|
|
|
|
|
+ chase = chase_function(search, cl)
|
|
|
|
|
+ states = []
|
|
|
|
|
+ for frame in range(5):
|
|
|
|
|
+ if kind == 'dynamic-wall':
|
|
|
|
|
+ cl.block[1][20][15] = frame % 2
|
|
|
|
|
+ invalidate_navigation(cl)
|
|
|
|
|
+ started = time.perf_counter()
|
|
|
|
|
+ for npc in units:
|
|
|
|
|
+ chase(npc)
|
|
|
|
|
+ elapsed = (time.perf_counter() - started) * 1000
|
|
|
|
|
+ if frame == 0:
|
|
|
|
|
+ cold.setdefault(name, []).append(elapsed)
|
|
|
|
|
+ samples[name].append(elapsed)
|
|
|
|
|
+ states.append([(npc.motion, npc.chase_path.copy()) for npc in units])
|
|
|
|
|
+ if cycle == 0:
|
|
|
|
|
+ snapshots[name] = states
|
|
|
|
|
+ assert snapshots['before'] == snapshots['after'], (kind, count)
|
|
|
|
|
+ before, after = (statistics.median(samples[name]) for name in ('before', 'after'))
|
|
|
|
|
+ row = dict(scene=kind, npcs=count, before_ms=round(before, 3), after_ms=round(after, 3),
|
|
|
|
|
+ speedup=round(before / after, 2), cold_before_ms=round(statistics.median(cold['before']), 3),
|
|
|
|
|
+ cold_after_ms=round(statistics.median(cold['after']), 3), identical=True)
|
|
|
|
|
+ results.append(row)
|
|
|
|
|
+ print(json.dumps(row), flush=True)
|
|
|
|
|
+ Path(output).parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
+ Path(output).write_text(json.dumps(results, indent=2), encoding='utf-8')
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+if __name__ == '__main__':
|
|
|
|
|
+ import sys
|
|
|
|
|
+ if '--benchmark' in sys.argv:
|
|
|
|
|
+ parser = argparse.ArgumentParser()
|
|
|
|
|
+ parser.add_argument('--benchmark', required=True)
|
|
|
|
|
+ benchmark(parser.parse_args().benchmark)
|
|
|
|
|
+ else:
|
|
|
|
|
+ unittest.main()
|