From 2ed790a5c68940350fb025feb3adbf6bb74aa0f1 Mon Sep 17 00:00:00 2001 From: Zoey Rose Date: Sat, 14 Nov 2026 15:25:19 -0600 Subject: [PATCH 1/5] feat(farming-analyzer): charge the approach maps to a spot's safety A circuit could rate safety 0.69-0.99 while the only way in crossed a far deadlier map: Sera (level 36, no fire/acid/poison protection) died five times on the Underground City entrance, whose level-32 puddings and jellies the analyzer never scored because it looked only at the circuit's own maps. Build a map graph from authored exits, tile_path_N headers and walkable coordinate-map seams, and run a bounded, deterministic bottleneck search from the nearest origin (surface world tile, savebed map or the new --approach-origin) to each spot. Each crossed map is charged for its worst aggressive encounter with the existing monster, damage and protection model, cached per map. safety_score becomes the lower of the spot and approach safeties; the spot-only value stays in spot_safety_score, and new approach_* fields expose the path, origin, worst map, danger and flags. --ignore-approach restores the spot-only score and --max-approach-maps bounds the search. Co-Authored-By: Claude Opus 5.5 --- farming_analyzer/README.md | 58 ++++- farming_analyzer/analyzer.py | 274 +++++++++++++++++++++++- farming_analyzer/cli.py | 12 ++ farming_analyzer/config.py | 2 + farming_analyzer/models.py | 13 ++ farming_analyzer/presentation.py | 22 +- farming_analyzer/sources.py | 3 + farming_analyzer/tests/test_approach.py | 251 ++++++++++++++++++++++ 8 files changed, 623 insertions(+), 12 deletions(-) create mode 100644 farming_analyzer/tests/test_approach.py diff --git a/farming_analyzer/README.md b/farming_analyzer/README.md index ee39d37..10d4e9f 100644 --- a/farming_analyzer/README.md +++ b/farming_analyzer/README.md @@ -234,6 +234,58 @@ attempt gate rather than an exponential renewal curve. Randomized spawn phases are averaged analytically, then readiness, partial-lap combat, mana use, and rest time are solved together. +## Approach danger + +A spot is only as safe as the maps crossed to reach it. Before scoring, the +analyzer builds a map graph from authored `type 66` exits (their `slaying` +destination, resolved relative to the map like the server does), header +`tile_path_N` links, and walkable seams between cardinally adjacent +coordinate maps at the same depth. Origins are surface `world_X_Y` tiles +(depth 0), every map holding a savebed (`type 106`), and each repeatable +`--approach-origin MAP`, for example the character's current savebed map. +The `--path` filter and `--exclude-region` do not hide approach maps. + +A bottleneck search walks backwards from the spot's maps to the nearest +origin, minimizing the most dangerous map on the way, then the number of +maps, then the map names, so the result is deterministic. It crosses at most +`--max-approach-maps` maps (default 16). Origins and the spot's own maps are +not charged. Each crossed map is charged for its worst aggressive encounter, +reusing the spot's monster, damage and protection model: the summed `danger` +of the aggressive spawns whose own detection radius reaches one pull point. +Directly placed monsters count even without `--include-static`, because they +are present when a traveller loads the map; passive monsters are skipped. +Without `--max-health`, the worst single aggressive spawn is charged instead, +matching the relative per-monster safety model. Each map's threat is cached +for the current options. + +The approach safety uses the same reference as the spot: `max_health / +approach_danger` with `--max-health`, otherwise the least dangerous eligible +spot's danger divided by `approach_danger`, capped at one. The reported +`safety_score`, and therefore the balanced score and `--ranking safety`, is +the lower of the spot and approach safeties. Scripted teleports, keys, locked +doors, and running past monsters are not modeled. `--ignore-approach` +restores the spot-only score. + +Each result (`results`, `groups[].representative`, and `rankings`) adds these +JSON fields; existing fields keep their names and types: + +- `spot_safety_score`: the spot-only safety previously reported as + `safety_score`; +- `approach_status`: `path` (approach maps found), `origin` (a member map is + an origin or is entered straight from one), `unreachable` (no authored path + within the limit; safety is the spot's own), or `disabled`; +- `approach_origin`: content-relative origin map, empty unless `path` or a + directly entered `origin`; +- `approach_maps`: content-relative maps crossed, ordered from the origin + towards the spot; +- `approach_danger`: the charged danger of the worst approach map; +- `approach_safety_score`: 0 to 1, or 1 without approach maps; +- `approach_worst_map`: the map that sets `approach_danger`; +- `approach_danger_flags`: attack and behaviour flags of the monsters in each + approach map's worst encounter (for example `fire×3`), plus a + `MAP L > allowed L` entry for any approach map whose monsters + exceed the `--max-level-gap` allowance. + ## Profiles, rankings, diagnostics, and training Save validated character arguments and reuse them: @@ -469,7 +521,7 @@ analyzer stays standard-library only. Consumers supply `--content-root` and Run the focused regression suite from the repository root: ```sh -python3 -m unittest tools.test_farming_analyzer +python3 -m unittest discover -s farming_analyzer/tests -t . -v ``` The fixtures are current authored maps and server tables. Tests cover the @@ -480,4 +532,6 @@ monsters, AoE clear-time and mana/crystal fight-rest cycles, Meditation's server-derived refill ramp, damage/delay DPS derivation, partially populated steady-state patrol laps, the deepest Old Outpost map, hierarchical region exclusions, depth-safe world-map circuits, the four-tile Strakewood swamp -circuit, and the two-tile Forgotten Graveyard circuit. +circuit, and the two-tile Forgotten Graveyard circuit. A synthetic world checks +that a safe circuit behind a dangerous entry map loses safety and reports +approach flags, while the same circuit behind a safe entry is unchanged. diff --git a/farming_analyzer/analyzer.py b/farming_analyzer/analyzer.py index 9fab88b..81440da 100644 --- a/farming_analyzer/analyzer.py +++ b/farming_analyzer/analyzer.py @@ -1,19 +1,24 @@ """Source-derived farming location analysis.""" +import heapq import math +import posixpath import re from collections import Counter, defaultdict, deque +from dataclasses import dataclass from pathlib import Path from typing import Iterable from .config import ( CONSUMABLE_TYPES, + EXIT_TYPE, GEAR_TYPES, MONEY_TYPE, MONSTER_TYPE, PHYSICAL_ATTACKS, RANDOM_DROP_TYPE, ROOT, + SAVEBED_TYPE, SERVER_ATTACK_TYPES, SERVER_ROOT, SPAWN_POINT_MOB_TYPE, @@ -46,6 +51,16 @@ from .treasure import Loot, TreasureModel +@dataclass(frozen=True) +class ApproachThreat: + """Danger of walking through one map on the way to a farming spot.""" + + pack_danger: float + spawn_danger: float + max_level: int + flags: tuple[str, ...] + + class FarmingAnalyzer: def __init__(self, root: Path = ROOT, server_root: Path = SERVER_ROOT): self.root = root @@ -60,6 +75,10 @@ def __init__(self, root: Path = ROOT, server_root: Path = SERVER_ROOT): self.tick_seconds = self._constant("MAX_TIME", 125000) / 1_000_000.0 self.default_reset = self._constant("MAP_DEFAULTRESET", 7200) self._world_graph = None + self._world_links: tuple[dict[str, tuple[str, ...]], + frozenset[str]] | None = None + self._threat_options: AnalysisOptions | None = None + self._threat_cache: dict[str, ApproachThreat] = {} self._npc_factions = self._load_npc_factions() self.rejections: list[tuple[str, str]] = [] @@ -317,7 +336,13 @@ def _world(self): _integer(one(header["attrs"], "width")), _integer(one(header["attrs"], "height")), ) - graph.nodes["/" + path.relative_to(self.map_root).as_posix()] = node + key = "/" + path.relative_to(self.map_root).as_posix() + graph.nodes[key] = node + for name, values in header["attrs"].items(): + if re.fullmatch(r"tile_path_\d+", name) and values: + target = self._resolve_map_path(key, values[-1]) + if target is not None: + node.exits.add(target) for obj, parent in flatten(parsed["objects"]): attrs = merged_attrs(obj, self.archetypes) x = _integer(one( @@ -331,6 +356,15 @@ def _world(self): terrain = _integer(attrs.get("terrain_type")) if terrain: node.terrain[(x, y)] = node.terrain.get((x, y), 0) | terrain + obj_type = _integer(attrs.get("type")) + # Only exits placed on the map, not carried in an + # inventory or spawn template, lead the player elsewhere. + if parent is None and obj_type == EXIT_TYPE and attrs.get("slaying"): + target = self._resolve_map_path(key, attrs["slaying"]) + if target is not None: + node.exits.add(target) + elif obj_type == SAVEBED_TYPE: + node.savebed = True # Doors, exits, and teleporters are traversable server-side. if attrs.get("no_pass") == "1" and attrs.get("type") not in ( "20", "64", "66"): @@ -338,6 +372,207 @@ def _world(self): self._world_graph = graph return self._world_graph + @staticmethod + def _resolve_map_path(source: str, target: str) -> str | None: + """Resolve an authored exit or tile path the way map paths nest.""" + target = target.strip() + if not target: + return None + if not target.startswith("/"): + target = posixpath.join(posixpath.dirname(source), target) + return posixpath.normpath(target) + + @staticmethod + def _seam_walkable(source: TerrainMap, target: TerrainMap, + dx: int, dy: int) -> bool: + """Return whether any tile pair across a coordinate-map seam is walkable.""" + if dx: + source_x = source.width - 1 if dx > 0 else 0 + target_x = 0 if dx > 0 else target.width - 1 + return any( + source.walkable(source_x, y) and target.walkable(target_x, y) + for y in range(min(source.height, target.height))) + source_y = source.height - 1 if dy > 0 else 0 + target_y = 0 if dy > 0 else target.height - 1 + return any( + source.walkable(x, source_y) and target.walkable(x, target_y) + for x in range(min(source.width, target.width))) + + def _links(self) -> tuple[dict[str, tuple[str, ...]], frozenset[str]]: + """Return reverse map connectivity and the default approach origins. + + A map links to another through an authored exit (``type 66`` with a + ``slaying`` destination), a header ``tile_path_N``, or a walkable seam + between cardinally adjacent coordinate maps at the same depth. The + returned mapping lists, for every map, the maps that lead into it. + Surface ``world_X_Y`` tiles and maps holding a savebed are origins. + """ + if self._world_links is None: + graph = self._world() + predecessors: dict[str, set[str]] = defaultdict(set) + grid: dict[tuple[str, str, int, int, int], str] = {} + origins = set() + for key, node in graph.nodes.items(): + for target in node.exits: + if target in graph.nodes and target != key: + predecessors[target].add(key) + coordinates = LocationIndex.world_coordinates(posixpath.basename(key)) + if coordinates is not None: + prefix, x, y, z = coordinates + grid[(posixpath.dirname(key), prefix, x, y, z)] = key + if prefix == "world" and z == 0: + origins.add(key) + if node.savebed: + origins.add(key) + for (parent, prefix, x, y, z), key in grid.items(): + for dx, dy in ((0, -1), (1, 0), (0, 1), (-1, 0)): + other = grid.get((parent, prefix, x + dx, y + dy, z)) + if other is not None and self._seam_walkable( + graph.nodes[key], graph.nodes[other], dx, dy): + predecessors[other].add(key) + self._world_links = ( + {key: tuple(sorted(values)) for key, values in predecessors.items()}, + frozenset(origins), + ) + return self._world_links + + def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat: + """Measure the worst aggressive encounter met while crossing one map. + + Every hostile spawn point and directly placed monster is included, + whatever --include-static says, because a traveller meets them when + the map is loaded. Monster danger reuses the spot model, including the + character's AC and protections; passive monsters are not engaged. + """ + if self._threat_options != options: + self._threat_options = options + self._threat_cache = {} + cached = self._threat_cache.get(key) + if cached is not None: + return cached + threat = ApproachThreat(0.0, 0.0, 0, ()) + path = self.map_root / key.lstrip("/") + parsed = parse_blocks(path) if path.is_file() else {"header": None} + header = parsed.get("header") + if header is not None: + spawns, _competitors = self._collect_spawns( + parsed, options, include_static=True) + weights = [ + sum(probability * profile.danger + for probability, profile in spawn.candidates + if "passive" not in profile.flags) + for spawn in spawns + ] + best_pack: list[int] = [] + pack_danger = 0.0 + for target in spawns: + pack = [ + index for index, spawn in enumerate(spawns) + if weights[index] > 0.0 and + max(abs(target.x - spawn.x), abs(target.y - spawn.y)) <= + spawn.weighted("aggro_radius") + ] + danger = sum(weights[index] for index in pack) + if danger > pack_danger or not best_pack and pack: + pack_danger = danger + best_pack = pack + flag_counts: Counter[str] = Counter() + for index in best_pack: + for probability, profile in spawns[index].candidates: + if "passive" in profile.flags: + continue + for flag in profile.flags: + flag_counts[flag] += probability + levels = [ + profile.level for index, spawn in enumerate(spawns) + if weights[index] > 0.0 + for _probability, profile in spawn.candidates + if "passive" not in profile.flags + ] + threat = ApproachThreat( + pack_danger, max(weights, default=0.0), max(levels, default=0), + tuple(f"{flag}×{amount:g}" for flag, amount in sorted( + flag_counts.items(), key=lambda item: (-item[1], item[0])))) + self._threat_cache[key] = threat + return threat + + def _apply_approach(self, result: MapResult, options: AnalysisOptions) -> None: + """Find the least dangerous authored approach from an origin. + + A bottleneck search walks backwards from the spot's maps and minimizes + the most dangerous intermediate map, then the number of maps, then the + path names for determinism. Origins themselves are not charged. + """ + if not options.model_approach: + return + predecessors, default_origins = self._links() + origins = default_origins | { + "/" + origin.strip().removeprefix("maps/").lstrip("/") + for origin in options.approach_origins if origin.strip() + } + map_prefix = self.map_root.relative_to(self.root).as_posix() + members = {"/" + path.removeprefix(map_prefix + "/") for path in result.map_paths} + if members & origins: + result.approach_status = "origin" + return + use_packs = options.max_health > 0.0 + + def metric(key: str) -> float: + threat = self._approach_threat(key, options) + return threat.pack_danger if use_packs else threat.spawn_danger + + heap: list[tuple[float, int, tuple[str, ...], str]] = [ + (0.0, 0, (), member) for member in sorted(members)] + settled: set[str] = set() + found = None + while heap: + bottleneck, hops, path, node = heapq.heappop(heap) + if node in settled: + continue + settled.add(node) + if node in origins: + found = bottleneck, path, node + break + for previous in predecessors.get(node, ()): + if previous in members or previous in settled: + continue + if previous in origins: + heapq.heappush(heap, (bottleneck, hops, path, previous)) + elif hops < options.max_approach_maps: + heapq.heappush(heap, ( + max(bottleneck, metric(previous)), hops + 1, + path + (previous,), previous)) + if found is None: + result.approach_status = "unreachable" + return + bottleneck, path, origin = found + ordered = tuple(reversed(path)) + result.approach_status = "path" if ordered else "origin" + result.approach_origin = map_prefix + origin + result.approach_maps = tuple(map_prefix + key for key in ordered) + result.approach_danger = bottleneck + survival_level = max(options.player_level, options.character_level) + flags: Counter[str] = Counter() + worst = None + for key in ordered: + threat = self._approach_threat(key, options) + if worst is None or metric(key) > metric(worst): + worst = key + for rendered in threat.flags: + label, _separator, amount = rendered.rpartition("×") + flags[label] += _number(amount, 1.0) + if worst is not None and metric(worst) > 0.0: + result.approach_worst_map = map_prefix + worst + level_flags = tuple( + f"{Path(key).name} L{self._approach_threat(key, options).max_level} > " + f"allowed L{survival_level + options.max_level_gap}" + for key in ordered + if self._approach_threat(key, options).max_level > + survival_level + options.max_level_gap) + result.approach_danger_flags = tuple( + f"{flag}×{amount:g}" for flag, amount in sorted( + flags.items(), key=lambda item: (-item[1], item[0]))) + level_flags + def _maneuverability( self, relpath: str, spawn_points: list[tuple[int, int]], @@ -1003,13 +1238,11 @@ def _max_aggro_pack(spawns: list[SpawnProfile]) -> float: maximum = max(maximum, direct) return maximum - def analyze_map(self, path: Path, options: AnalysisOptions) -> MapResult | None: - relpath = str(path.relative_to(self.root)) - parsed = parse_blocks(path) - header = parsed.get("header") - if header is None: - return None - header_attrs = header["attrs"] + def _collect_spawns( + self, parsed: dict, options: AnalysisOptions, *, include_static: bool, + ) -> tuple[list[SpawnProfile], list[CompetitorProfile]]: + """Return hostile spawn profiles and NPC competitors of a parsed map.""" + header_attrs = parsed["header"]["attrs"] difficulty = _integer(one(header_attrs, "difficulty", 1), 1) reset_timeout = _integer(one(header_attrs, "reset_timeout", self.default_reset), self.default_reset) @@ -1025,10 +1258,22 @@ def analyze_map(self, path: Path, options: AnalysisOptions) -> MapResult | None: competitor = self._competitor_spawn(node, options) if competitor is not None: competitors.append(competitor) - elif options.include_static and parent is None and obj_type == MONSTER_TYPE: + elif include_static and parent is None and obj_type == MONSTER_TYPE: spawn = self._static_monster(node, difficulty, reset_timeout, options) if spawn is not None: spawns.append(spawn) + return spawns, competitors + + def analyze_map(self, path: Path, options: AnalysisOptions) -> MapResult | None: + relpath = str(path.relative_to(self.root)) + parsed = parse_blocks(path) + header = parsed.get("header") + if header is None: + return None + header_attrs = header["attrs"] + difficulty = _integer(one(header_attrs, "difficulty", 1), 1) + spawns, competitors = self._collect_spawns( + parsed, options, include_static=options.include_static) if len(spawns) < options.minimum_spawns: self.rejections.append((relpath, f"{len(spawns)} spawns < minimum {options.minimum_spawns}")) @@ -1463,6 +1708,16 @@ def _score(results: list[MapResult], options: AnalysisOptions) -> list[MapResult else: safety = (min(1.0, safest / max(result.danger, 0.001)) if math.isfinite(result.danger) else 0.0) + result.spot_safety_score = safety + if result.approach_maps: + # Approach maps use the same health budget, or the same + # least-dangerous-spot reference, as the spot itself. + reference = (options.max_health if options.max_health > 0.0 + else safest) + result.approach_safety_score = ( + min(1.0, reference / max(result.approach_danger, 0.001)) + if math.isfinite(result.approach_danger) else 0.0) + safety = min(safety, result.approach_safety_score) result.safety_score = safety components = { "xp": result.xp_hour / maxima["xp"], @@ -1505,4 +1760,5 @@ def scan(self, options: AnalysisOptions) -> list[MapResult]: for result in combined: result.location, result.nearby_landmarks = self.locations.describe( result.map_paths, result.region, result.name) + self._apply_approach(result, options) return self._score(combined, options) diff --git a/farming_analyzer/cli.py b/farming_analyzer/cli.py index 2c30f7d..6a03de7 100644 --- a/farming_analyzer/cli.py +++ b/farming_analyzer/cli.py @@ -119,6 +119,13 @@ def build_parser() -> argparse.ArgumentParser: parser.add_argument("--path", dest="path_pattern", help="case-insensitive map-path regex") parser.add_argument("--exclude-region", action="append", default=[], metavar="NAME", help="exclude a region/island ID or name; may be repeated") + parser.add_argument("--approach-origin", action="append", default=[], metavar="MAP", + help="extra map the character starts from, such as its savebed map; " + "may be repeated (surface world tiles and savebed maps are always origins)") + parser.add_argument("--max-approach-maps", type=int, default=16, + help="longest approach, in maps between origin and spot (default: 16)") + parser.add_argument("--ignore-approach", dest="model_approach", action="store_false", + help="score only the spot's own maps, not the maps crossed to reach it") parser.add_argument("--include-static", action="store_true", help="include monsters that only return after map reset/unload") parser.add_argument("--json", action="store_true", help="emit machine-readable results") @@ -254,6 +261,8 @@ def main(argv: list[str] | None = None) -> int: raise SystemExit("passive-pull-efficiency must be between 0 and 1") if not (1 <= args.circuit_size <= 8): raise SystemExit("circuit-size must be between 1 and 8") + if not (1 <= args.max_approach_maps <= 64): + raise SystemExit("max-approach-maps must be between 1 and 64") if not (1 <= args.group_level_span <= 50): raise SystemExit("group-level-span must be between 1 and 50") if not (1 <= character_level <= maximum_level): @@ -304,6 +313,9 @@ def main(argv: list[str] | None = None) -> int: args.passive_pull_efficiency, args.group_results, args.group_level_span, + model_approach=args.model_approach, + approach_origins=tuple(args.approach_origin), + max_approach_maps=args.max_approach_maps, ) results = analyzer.scan(options) initial_rejections = list(analyzer.rejections) diff --git a/farming_analyzer/config.py b/farming_analyzer/config.py index 084f06a..2c60173 100644 --- a/farming_analyzer/config.py +++ b/farming_analyzer/config.py @@ -28,6 +28,8 @@ def _find_workspace_root() -> Path: MONSTER_TYPE = 80 SPAWN_POINT_MOB_TYPE = 83 RANDOM_DROP_TYPE = 102 +EXIT_TYPE = 66 +SAVEBED_TYPE = 106 GEAR_TYPES = { 3, 13, 14, 15, 16, 33, 34, 35, 39, 70, 87, 99, 100, 104, 109, 113, } diff --git a/farming_analyzer/models.py b/farming_analyzer/models.py index 65f86dd..a6e5823 100644 --- a/farming_analyzer/models.py +++ b/farming_analyzer/models.py @@ -140,6 +140,16 @@ class MapResult: pack_target_capacity: float = 1.0 min_monster_level: int = 0 avg_monster_level: float = 0.0 + # Approach: the least dangerous authored path from an origin (surface + # world tile, savebed map, or --approach-origin) to the spot's maps. + spot_safety_score: float = 0.0 + approach_status: str = "disabled" + approach_origin: str = "" + approach_maps: tuple[str, ...] = () + approach_danger: float = 0.0 + approach_safety_score: float = 1.0 + approach_worst_map: str = "" + approach_danger_flags: tuple[str, ...] = () @dataclass(frozen=True) @@ -188,6 +198,9 @@ class AnalysisOptions: passive_pull_efficiency: float = 0.20 group_results: bool = True group_level_span: int = 10 + model_approach: bool = True + approach_origins: tuple[str, ...] = () + max_approach_maps: int = 16 @property def simulate_melee(self) -> bool: diff --git a/farming_analyzer/presentation.py b/farming_analyzer/presentation.py index 951e0ed..cbf7f04 100644 --- a/farming_analyzer/presentation.py +++ b/farming_analyzer/presentation.py @@ -5,6 +5,7 @@ import re from collections import Counter, defaultdict from dataclasses import dataclass +from pathlib import Path from .config import SERVER_ATTACK_TYPES from .experience import ExperienceModel @@ -320,6 +321,21 @@ def render_text(results: list[MapResult], options: AnalysisOptions, limit: int, f" danger: {', '.join(result.danger_flags) or 'ordinary melee'}; " f"sources: {', '.join(result.sources)}", )) + if result.approach_status == "path": + lines.append( + f" approach: {len(result.approach_maps)} map(s) from " + f"{result.approach_origin} via " + f"{' -> '.join(Path(path).name for path in result.approach_maps)}; " + f"worst {Path(result.approach_worst_map).name or 'none'} " + f"(danger {result.approach_danger:.0f}, safety " + f"{result.approach_safety_score * 100.0:.0f}% vs spot " + f"{result.spot_safety_score * 100.0:.0f}%); " + f"{', '.join(result.approach_danger_flags) or 'ordinary melee'}" + ) + elif result.approach_status == "unreachable": + lines.append( + " approach: no authored exit path from a surface tile, savebed, " + "or --approach-origin; scored on the spot alone") if options.character_speed > 0.0: lines.append( f" route: ~{result.route_steps:,} authored walkable tile steps = " @@ -374,7 +390,11 @@ def render_text(results: list[MapResult], options: AnalysisOptions, limit: int, "application. Crystal applications are treated as instant optimal inputs. The supplied " "skill level is held constant. Spawn-point respawn is " "source-derived; map-reset-only monsters require the map to unload and are excluded unless " - "--include-static is used.", + "--include-static is used. Safety is also capped by the least dangerous authored approach: " + "exits, tile paths, and walkable coordinate seams from a surface world tile, savebed map, or " + "--approach-origin, charging the worst aggressive pack on each map crossed (including " + "map-reset monsters). Scripted teleports, keys, locked doors, and fleeing past monsters are " + "not modeled; --ignore-approach scores the spot alone.", )) if warnings: lines.append(f"Treasure-model warnings: {len(warnings)} (use --json to inspect derived values).") diff --git a/farming_analyzer/sources.py b/farming_analyzer/sources.py index 79928e5..c4db9e6 100644 --- a/farming_analyzer/sources.py +++ b/farming_analyzer/sources.py @@ -170,6 +170,9 @@ class TerrainMap: height: int terrain: dict[tuple[int, int], int] = field(default_factory=dict) blocked: set[tuple[int, int]] = field(default_factory=set) + # Map-root paths ("/region/map") named by authored exits and tile paths. + exits: set[str] = field(default_factory=set) + savebed: bool = False def walkable(self, x: int, y: int) -> bool: return ( diff --git a/farming_analyzer/tests/test_approach.py b/farming_analyzer/tests/test_approach.py new file mode 100644 index 0000000..96a2823 --- /dev/null +++ b/farming_analyzer/tests/test_approach.py @@ -0,0 +1,251 @@ +"""Approach-path danger on a synthetic authored world.""" + +from __future__ import annotations + +import io +import json +import tempfile +import unittest +from dataclasses import replace +from pathlib import Path +from unittest.mock import patch + +from farming_analyzer import ( + SERVER_ROOT, + AnalysisOptions, + FarmingAnalyzer, + MapResult, + main, +) + +ARCHETYPES = """\ +Object floor +terrain_type 1 +end +Object wall +no_pass 1 +end +Object exit +type 66 +end +Object bed_save +type 106 +end +Object spawn_point +type 81 +last_grace 1 +speed -0.01 +end +Object rat +name rat +type 80 +monster 1 +level 10 +maxhp 20 +dam 2 +wc 1 +ac 1 +speed 0.5 +weapon_speed 1 +item_power 2 +exp 200 +end +Object pudding +name cave pudding +type 80 +monster 1 +level 32 +maxhp 8 +dam 12 +wc 30 +ac 10 +speed 0.5 +weapon_speed 1 +item_power 6 +attack_fire 50 +attack_acid 50 +exp 2000 +end +""" + +SIZE = 6 +ROOM = "underground_city" +DANGER = "circuit[underground_city_0_0 + underground_city_1_0]" +SAFE = "circuit[underground_city_5_0 + underground_city_6_0]" + + +def _map(name: str, region: str, *, spawns: tuple[tuple[str, int, int], ...] = (), + exits: tuple[tuple[str, int, int], ...] = (), extra: str = "") -> str: + lines = [ + "arch map", f"name {name}", f"width {SIZE}", f"height {SIZE}", + "difficulty 10", f"region {region}", "end", + ] + for y in range(SIZE): + for x in range(SIZE): + lines += ["arch floor", f"x {x}", f"y {y}", "end"] + for monster, x, y in spawns: + lines += ["arch spawn_point", f"x {x}", f"y {y}", + f"arch {monster}", "type 83", "end", "end"] + for target, x, y in exits: + lines += ["arch exit", f"x {x}", f"y {y}", f"slaying {target}", "end"] + return "\n".join(lines) + "\n" + extra + + +class ApproachDangerTest(unittest.TestCase): + """A safe circuit is only as safe as the map crossed to reach it.""" + + @classmethod + def setUpClass(cls): + cls.directory = tempfile.TemporaryDirectory() + root = Path(cls.directory.name) + (root / "arch").mkdir() + (root / "arch" / "test.arc").write_text(ARCHETYPES) + maps = root / "maps" + (maps / "danger").mkdir(parents=True) + (maps / "safe").mkdir() + (maps / "regions.reg").write_text( + "region surface\nlongname Surface\nend\n" + "region dungeon\nlongname Dungeon\nend\n") + # The surface world tile is an origin; it leads into both dungeons. + (maps / "world_0_0").write_text(_map( + "Surface", "surface", + exits=(("danger/entry", 1, 1), ("/safe/entry", 4, 4)))) + rats = (("rat", 1, 1), ("rat", 4, 4)) + for dungeon, x, entry_spawns in ( + ("danger", 0, (("pudding", 2, 2), ("pudding", 3, 2), + ("pudding", 2, 3))), + ("safe", 5, ())): + first, second = f"{ROOM}_{x}_0", f"{ROOM}_{x + 1}_0" + (maps / dungeon / "entry").write_text(_map( + f"{dungeon} entry", "dungeon", spawns=entry_spawns, + exits=(("../world_0_0", 0, 0), (first, 5, 5)))) + # Two seam-adjacent coordinate rooms form the farming circuit. + # Only the first has an authored exit from the entry map. + (maps / dungeon / first).write_text(_map( + f"{dungeon} cave", "dungeon", spawns=rats, + exits=(("entry", 0, 0),))) + (maps / dungeon / second).write_text(_map( + f"{dungeon} cave", "dungeon", spawns=rats)) + cls.analyzer = FarmingAnalyzer(root, SERVER_ROOT) + + @classmethod + def tearDownClass(cls): + cls.directory.cleanup() + + @staticmethod + def options(**changes) -> AnalysisOptions: + options = AnalysisOptions( + player_level=10, dps=40.0, seconds_per_kill=2.0, + seconds_per_map=10.0, shop_sell_fraction=0.20, at_minute=12 * 60, + attack_type="physical_average", minimum_spawns=1, + minimum_xp_fraction=0.0, max_level_gap=5, circuit_size=4, + path_pattern=ROOM, include_static=False, character_level=10, + player_ac=10, player_protections=(), melee_damage=None, + weapon_class=None, weapon_speed=None, weapon_class_range=20, + player_attacks=(("impact", 25), ("cleave", 25), + ("slash", 25), ("pierce", 25)), + damage_per_attack=40.0, attack_delay=1.0, max_health=300.0, + ) + return replace(options, **changes) + + def results(self, options: AnalysisOptions) -> dict[str, MapResult]: + return {result.path: result for result in self.analyzer.scan(options)} + + def test_dangerous_approach_lowers_safety_and_is_reported(self): + results = self.results(self.options()) + danger = results[DANGER] + self.assertEqual("path", danger.approach_status) + self.assertEqual("maps/world_0_0", danger.approach_origin) + self.assertEqual(("maps/danger/entry",), danger.approach_maps) + self.assertEqual("maps/danger/entry", danger.approach_worst_map) + self.assertEqual(1.0, danger.spot_safety_score) + self.assertGreater(danger.approach_danger, 300.0) + self.assertAlmostEqual(300.0 / danger.approach_danger, + danger.approach_safety_score) + self.assertEqual(danger.approach_safety_score, danger.safety_score) + self.assertIn("fire×3", danger.approach_danger_flags) + self.assertIn("acid×3", danger.approach_danger_flags) + self.assertIn("entry L32 > allowed L15", danger.approach_danger_flags) + + def test_approach_threat_applies_character_protections(self): + bare = self.results(self.options())[DANGER] + protected = self.results(self.options( + player_protections=(("acid", 50), ("fire", 50))))[DANGER] + self.assertLess(protected.approach_danger, bare.approach_danger) + self.assertGreater(protected.safety_score, bare.safety_score) + + def test_safe_approach_leaves_identical_circuit_unchanged(self): + results = self.results(self.options()) + danger = results[DANGER] + safe = results[SAFE] + self.assertEqual(("maps/safe/entry",), safe.approach_maps) + self.assertEqual(0.0, safe.approach_danger) + self.assertEqual((), safe.approach_danger_flags) + self.assertEqual(1.0, safe.approach_safety_score) + self.assertEqual(safe.spot_safety_score, safe.safety_score) + self.assertEqual(danger.spot_safety_score, safe.spot_safety_score) + self.assertGreater(safe.safety_score, danger.safety_score) + self.assertGreater(safe.score, danger.score) + + def test_coordinate_seams_extend_the_approach(self): + results = self.results(self.options(circuit_size=1)) + far_room = next(result for result in results.values() + if result.map_paths == ("maps/danger/underground_city_1_0",)) + self.assertEqual(("maps/danger/entry", "maps/danger/underground_city_0_0"), + far_room.approach_maps) + self.assertLess(far_room.safety_score, 1.0) + + def test_relative_safety_mode_also_charges_the_approach(self): + results = self.results(self.options(max_health=0.0)) + danger = results[DANGER] + self.assertLess(danger.safety_score, danger.spot_safety_score) + + def test_ignore_approach_and_explicit_origin(self): + ignored = self.results(self.options(model_approach=False)) + danger = ignored[DANGER] + self.assertEqual("disabled", danger.approach_status) + self.assertEqual((), danger.approach_maps) + self.assertEqual(danger.spot_safety_score, danger.safety_score) + + savebed = self.results(self.options( + approach_origins=("maps/danger/underground_city_0_0",))) + danger = savebed[DANGER] + self.assertEqual("origin", danger.approach_status) + self.assertEqual(danger.spot_safety_score, danger.safety_score) + + def test_unreachable_spot_keeps_its_own_safety(self): + results = self.results(self.options( + max_approach_maps=0)) + danger = results[DANGER] + self.assertEqual("unreachable", danger.approach_status) + self.assertEqual(danger.spot_safety_score, danger.safety_score) + + def test_cli_json_exposes_approach_fields_and_options(self): + def run(*extra: str) -> dict: + stdout = io.StringIO() + with patch("sys.stdout", stdout): + main([ + "10", "--damage-per-attack", "40", "--attack-delay", "1", + "--max-health", "300", "--min-spawns", "1", + "--min-xp-fraction", "0", "--path", ROOM, + "--show-all-routes", "--json", + "--content-root", self.directory.name, + "--server-root", str(SERVER_ROOT), *extra, + ]) + return {item["path"]: item for item in json.loads( + stdout.getvalue())["results"]} + + danger = run()[DANGER] + self.assertEqual(["maps/danger/entry"], danger["approach_maps"]) + self.assertEqual("maps/world_0_0", danger["approach_origin"]) + self.assertLess(danger["safety_score"], danger["spot_safety_score"]) + self.assertIn("fire×3", danger["approach_danger_flags"]) + origin = run("--approach-origin", "/danger/underground_city_0_0")[DANGER] + self.assertEqual("origin", origin["approach_status"]) + ignored = run("--ignore-approach")[DANGER] + self.assertEqual("disabled", ignored["approach_status"]) + self.assertEqual(ignored["spot_safety_score"], ignored["safety_score"]) + + +if __name__ == "__main__": + unittest.main() From b65349d991ff2fc2e7c991048545606e15540616 Mon Sep 17 00:00:00 2001 From: Zoey Rose Date: Sat, 14 Nov 2026 15:45:10 -0600 Subject: [PATCH 2/5] fix(farming-analyzer): tighten approach search, tiling and origins Address review of the approach-danger change: - Charge an approach pack by sequential exposure: every engaged monster keeps attacking until it dies, killed in Smith's-rule order. The Underground City entrance slime cluster rises from ~127 to ~288 expected damage for a Sera-like level 36 profile. - Re-expand a map reached with fewer hops so a long zero-danger path can no longer block a shorter, more dangerous one inside the hop limit. - Flag unreachable spots with approach_unknown and add the opt-in --unreachable-approach-safety cap. - Derive tiling as the server's derive_map_filename_tiles() does: any basename with two or three short numeric words, eight same-depth directions including diagonal corners. - Charge surface entrance tiles when crossed; savebed and explicit origins stay free. Add --approach-origins-only, normalize and validate --approach-origin, and ignore savebeds carried in containers. - Test the reviewer's hop-limit repro, disconnected maps, tile paths, savebeds, relative/absolute slaying, nested exits, missing targets, depth-only and diagonal seams, plus a content-gated Underground City regression. Co-Authored-By: Claude Opus 5.5 --- farming_analyzer/README.md | 105 +++++++---- farming_analyzer/analyzer.py | 202 +++++++++++++++------ farming_analyzer/cli.py | 16 ++ farming_analyzer/models.py | 2 + farming_analyzer/presentation.py | 11 +- farming_analyzer/tests/test_approach.py | 232 +++++++++++++++++++++++- 6 files changed, 474 insertions(+), 94 deletions(-) diff --git a/farming_analyzer/README.md b/farming_analyzer/README.md index 10d4e9f..c3aa5f7 100644 --- a/farming_analyzer/README.md +++ b/farming_analyzer/README.md @@ -237,54 +237,86 @@ rest time are solved together. ## Approach danger A spot is only as safe as the maps crossed to reach it. Before scoring, the -analyzer builds a map graph from authored `type 66` exits (their `slaying` -destination, resolved relative to the map like the server does), header -`tile_path_N` links, and walkable seams between cardinally adjacent -coordinate maps at the same depth. Origins are surface `world_X_Y` tiles -(depth 0), every map holding a savebed (`type 106`), and each repeatable -`--approach-origin MAP`, for example the character's current savebed map. -The `--path` filter and `--exclude-region` do not hide approach maps. - -A bottleneck search walks backwards from the spot's maps to the nearest -origin, minimizing the most dangerous map on the way, then the number of -maps, then the map names, so the result is deterministic. It crosses at most -`--max-approach-maps` maps (default 16). Origins and the spot's own maps are -not charged. Each crossed map is charged for its worst aggressive encounter, -reusing the spot's monster, damage and protection model: the summed `danger` -of the aggressive spawns whose own detection radius reaches one pull point. -Directly placed monsters count even without `--include-static`, because they -are present when a traveller loads the map; passive monsters are skipped. -Without `--max-health`, the worst single aggressive spawn is charged instead, -matching the relative per-monster safety model. Each map's threat is cached -for the current options. +analyzer builds a map graph from: + +- authored `type 66` exits placed directly on a map (not ones carried in a + spawn point or container), following their `slaying` destination relative + to the map, or from the map root when it starts with `/`; +- header `tile_path_N` links; +- horizontal tiling derived from map names as `derive_map_filename_tiles()` + in classic `server/src/server/map.c` does: any basename with two or three + numeric words of at most three characters (`cave_2_1_-1`) tiles with the + eight same-depth neighbours whose derived names exist, when a tile on each + side of the shared edge or corner is walkable. + +This approximates the server's tiling. Explicit tile paths do not replace the +derived neighbour in that direction, and the server's derived up/down tiles +are not linked: depth changes only follow authored exits and tile paths. +Missing destinations are ignored. + +Origins are surface `world_X_Y` tiles (depth 0) and every map holding a +placed savebed (`type 106`), plus each repeatable `--approach-origin MAP`. +`MAP` may be written `/region/map`, `region/map`, or `maps/region/map`; an +unknown map is an error. `--approach-origins-only` uses only the +`--approach-origin` maps, for example "I start from my savebed". A savebed or +explicit origin is where the character starts and is free. A surface tile is +charged its own danger, because the character must cross it to use its +entrance. The `--path` filter and `--exclude-region` do not hide approach +maps. + +A bottleneck search walks backwards from the spot's maps to an origin, +minimizing the most dangerous map crossed, then the number of maps, then the +map names, so the result is deterministic. It crosses at most +`--max-approach-maps` maps between origin and spot (default 16). A map is +expanded again when reached with fewer maps, so a long safe path cannot block +a shorter one that fits the limit. + +Each crossed map is charged for its worst aggressive encounter, reusing the +spot's monster, damage, hit-chance, kill-time and protection model. Spawns +whose own detection radius reaches one pull point fight together. That pack +is charged by sequential exposure: every living monster keeps attacking until +it dies, killed in the order that minimizes damage (ascending kill time per +incoming DPS), plus each monster's secondary-risk bonus. Without +`--max-health`, the worst single aggressive spawn is charged instead, +matching the relative per-monster safety model. Directly placed monsters +count even without `--include-static`, because they are present when a +traveller loads the map. Passive monsters are skipped. AoE is not credited +on the approach. Each map's threat is cached for the current options. The approach safety uses the same reference as the spot: `max_health / approach_danger` with `--max-health`, otherwise the least dangerous eligible spot's danger divided by `approach_danger`, capped at one. The reported `safety_score`, and therefore the balanced score and `--ranking safety`, is -the lower of the spot and approach safeties. Scripted teleports, keys, locked -doors, and running past monsters are not modeled. `--ignore-approach` -restores the spot-only score. +the lower of the spot and approach safeties. A spot with no authored path +from an origin within the limit keeps its own safety and gets the +`approach_unknown` flag; `--unreachable-approach-safety SAFETY` (0 to 1) +caps such spots instead. Scripted teleports, keys, locked doors, and running +past monsters are not modeled. Neither is the variance of a fight, nor the +server's poisoning pulses (`attack_perform_poison()`: five to ten pulses of +up to a third of maximum HP) beyond the secondary-risk heuristic, so a pack +whose expected damage is just inside one health bar still reports full +safety. `--ignore-approach` restores the spot-only score. Each result (`results`, `groups[].representative`, and `rankings`) adds these JSON fields; existing fields keep their names and types: - `spot_safety_score`: the spot-only safety previously reported as `safety_score`; -- `approach_status`: `path` (approach maps found), `origin` (a member map is - an origin or is entered straight from one), `unreachable` (no authored path - within the limit; safety is the spot's own), or `disabled`; -- `approach_origin`: content-relative origin map, empty unless `path` or a - directly entered `origin`; +- `approach_status`: `path` (an origin was found; `approach_maps` may be + empty when a charged surface tile leads straight in), `origin` (a member + map is itself an origin), `unreachable`, or `disabled`; +- `approach_origin`: content-relative origin map, empty unless `path`; - `approach_maps`: content-relative maps crossed, ordered from the origin - towards the spot; -- `approach_danger`: the charged danger of the worst approach map; -- `approach_safety_score`: 0 to 1, or 1 without approach maps; + towards the spot, excluding the origin; +- `approach_danger`: the charged danger of the worst approach map, including + a charged surface origin; +- `approach_safety_score`: 0 to 1; 1 without a charged approach, or the + `--unreachable-approach-safety` cap; - `approach_worst_map`: the map that sets `approach_danger`; - `approach_danger_flags`: attack and behaviour flags of the monsters in each - approach map's worst encounter (for example `fire×3`), plus a - `MAP L > allowed L` entry for any approach map whose monsters - exceed the `--max-level-gap` allowance. + charged map's worst encounter (for example `fire×3`), a + `MAP L > allowed L` entry for any charged map whose monsters + exceed the `--max-level-gap` allowance, or `approach_unknown`. ## Profiles, rankings, diagnostics, and training @@ -534,4 +566,7 @@ steady-state patrol laps, the deepest Old Outpost map, hierarchical region exclusions, depth-safe world-map circuits, the four-tile Strakewood swamp circuit, and the two-tile Forgotten Graveyard circuit. A synthetic world checks that a safe circuit behind a dangerous entry map loses safety and reports -approach flags, while the same circuit behind a safe entry is unchanged. +approach flags, while the same circuit behind a safe entry is unchanged, and +covers exits, tile paths, tiling, origins, and the bounded search. When the +content checkout is present, a Sera-like level 36 profile checks the +Underground City entrance's slime cluster. diff --git a/farming_analyzer/analyzer.py b/farming_analyzer/analyzer.py index 81440da..aaf1d4b 100644 --- a/farming_analyzer/analyzer.py +++ b/farming_analyzer/analyzer.py @@ -76,7 +76,7 @@ def __init__(self, root: Path = ROOT, server_root: Path = SERVER_ROOT): self.default_reset = self._constant("MAP_DEFAULTRESET", 7200) self._world_graph = None self._world_links: tuple[dict[str, tuple[str, ...]], - frozenset[str]] | None = None + frozenset[str], frozenset[str]] | None = None self._threat_options: AnalysisOptions | None = None self._threat_cache: dict[str, ApproachThreat] = {} self._npc_factions = self._load_npc_factions() @@ -363,7 +363,7 @@ def _world(self): target = self._resolve_map_path(key, attrs["slaying"]) if target is not None: node.exits.add(target) - elif obj_type == SAVEBED_TYPE: + elif parent is None and obj_type == SAVEBED_TYPE: node.savebed = True # Doors, exits, and teleporters are traversable server-side. if attrs.get("no_pass") == "1" and attrs.get("type") not in ( @@ -382,10 +382,40 @@ def _resolve_map_path(source: str, target: str) -> str | None: target = posixpath.join(posixpath.dirname(source), target) return posixpath.normpath(target) + @staticmethod + def _tile_coordinates(basename: str) -> tuple[str, int, int, int] | None: + """Mirror derive_map_filename_tiles() in classic server/map.c. + + Underscore-separated words longer than three characters are ignored + (old ``map_0101`` names); up to three numeric words, optionally + negative, are coordinates. Two or more make the map tiled, and the + server forms neighbour names by removing that many trailing + characters and appending the shifted coordinates. + """ + coordinates: list[int] = [] + length = 0 + for word in basename.split("_"): + if not word or len(word) > 3: + continue + if re.fullmatch(r"-?\d+", word): + coordinates.append(int(word)) + length += len(word) + 1 + if len(coordinates) >= 3: + break + if len(coordinates) < 2: + return None + z = coordinates[2] if len(coordinates) > 2 else 0 + return basename[:max(0, len(basename) - length)], coordinates[0], coordinates[1], z + @staticmethod def _seam_walkable(source: TerrainMap, target: TerrainMap, dx: int, dy: int) -> bool: - """Return whether any tile pair across a coordinate-map seam is walkable.""" + """Return whether a tile pair across a tiled-map edge or corner is walkable.""" + if dx and dy: + return (source.walkable(source.width - 1 if dx > 0 else 0, + source.height - 1 if dy > 0 else 0) and + target.walkable(0 if dx > 0 else target.width - 1, + 0 if dy > 0 else target.height - 1)) if dx: source_x = source.width - 1 if dx > 0 else 0 target_x = 0 if dx > 0 else target.width - 1 @@ -398,51 +428,94 @@ def _seam_walkable(source: TerrainMap, target: TerrainMap, source.walkable(x, source_y) and target.walkable(x, target_y) for x in range(min(source.width, target.width))) - def _links(self) -> tuple[dict[str, tuple[str, ...]], frozenset[str]]: - """Return reverse map connectivity and the default approach origins. + def _links(self) -> tuple[dict[str, tuple[str, ...]], frozenset[str], frozenset[str]]: + """Return reverse map connectivity, surface origins, and savebed maps. A map links to another through an authored exit (``type 66`` with a - ``slaying`` destination), a header ``tile_path_N``, or a walkable seam - between cardinally adjacent coordinate maps at the same depth. The - returned mapping lists, for every map, the maps that lead into it. - Surface ``world_X_Y`` tiles and maps holding a savebed are origins. + ``slaying`` destination), a header ``tile_path_N``, or a walkable + edge or corner between maps the server tiles horizontally from their + coordinate names (same depth, all eight directions). Depth changes + only follow authored exits and tile paths. The returned mapping lists, + for every map, the maps that lead into it. """ if self._world_links is None: graph = self._world() predecessors: dict[str, set[str]] = defaultdict(set) - grid: dict[tuple[str, str, int, int, int], str] = {} - origins = set() + surface = set() + savebeds = set() for key, node in graph.nodes.items(): for target in node.exits: if target in graph.nodes and target != key: predecessors[target].add(key) - coordinates = LocationIndex.world_coordinates(posixpath.basename(key)) - if coordinates is not None: - prefix, x, y, z = coordinates - grid[(posixpath.dirname(key), prefix, x, y, z)] = key - if prefix == "world" and z == 0: - origins.add(key) if node.savebed: - origins.add(key) - for (parent, prefix, x, y, z), key in grid.items(): - for dx, dy in ((0, -1), (1, 0), (0, 1), (-1, 0)): - other = grid.get((parent, prefix, x + dx, y + dy, z)) - if other is not None and self._seam_walkable( - graph.nodes[key], graph.nodes[other], dx, dy): + savebeds.add(key) + world = LocationIndex.world_coordinates(posixpath.basename(key)) + if world is not None and world[0] == "world" and world[3] == 0: + surface.add(key) + tiled = self._tile_coordinates(posixpath.basename(key)) + if tiled is None: + continue + prefix, x, y, z = tiled + parent = posixpath.dirname(key) + for dx, dy in ((0, -1), (1, 0), (0, 1), (-1, 0), + (1, -1), (1, 1), (-1, 1), (-1, -1)): + name = f"{prefix}_{x + dx}_{y + dy}" + (f"_{z}" if z else "") + other = posixpath.join(parent, name) + if other != key and other in graph.nodes and self._seam_walkable( + node, graph.nodes[other], dx, dy): predecessors[other].add(key) self._world_links = ( {key: tuple(sorted(values)) for key, values in predecessors.items()}, - frozenset(origins), + frozenset(surface), + frozenset(savebeds), ) return self._world_links + def resolve_map_key(self, path: str) -> str | None: + """Resolve a user-supplied map path to an authored map, or None. + + Accepts map-root paths (``/region/map``), content-relative paths + (``maps/region/map``), and either form with a leading slash. + """ + text = path.strip().lstrip("/") + if not text: + return None + nodes = self._world().nodes + for candidate in (text, text.removeprefix("maps/")): + key = posixpath.normpath("/" + candidate) + if key in nodes: + return key + return None + + @staticmethod + def _sequential_exposure(fighters: list[tuple[float, float, float]]) -> float: + """Expected damage while killing an engaged pack one at a time. + + Each fighter is (incoming DPS, kill seconds, secondary-risk bonus). + Every living monster keeps attacking until it dies, so a monster's DPS + is charged for the time until its own kill. Killing in ascending + kill-seconds/DPS order (Smith's rule) minimizes that total. + """ + total = 0.0 + elapsed = 0.0 + damaging = sorted( + (item for item in fighters if item[0] > 0.0), + key=lambda item: item[1] / item[0]) + for dps, kill_seconds, bonus in damaging: + elapsed += kill_seconds + total += dps * elapsed + bonus + total += sum(bonus for dps, _kill, bonus in fighters if dps <= 0.0) + return total + def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat: """Measure the worst aggressive encounter met while crossing one map. Every hostile spawn point and directly placed monster is included, whatever --include-static says, because a traveller meets them when - the map is loaded. Monster danger reuses the spot model, including the - character's AC and protections; passive monsters are not engaged. + the map is loaded. Monster damage, hit chance and kill time reuse the + spot model, including the character's AC and protections; passive + monsters are not engaged. Spawns whose own detection radius reaches + one pull point fight together, charged by sequential exposure. """ if self._threat_options != options: self._threat_options = options @@ -453,16 +526,29 @@ def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat threat = ApproachThreat(0.0, 0.0, 0, ()) path = self.map_root / key.lstrip("/") parsed = parse_blocks(path) if path.is_file() else {"header": None} - header = parsed.get("header") - if header is not None: + if parsed.get("header") is not None: spawns, _competitors = self._collect_spawns( parsed, options, include_static=True) - weights = [ - sum(probability * profile.danger - for probability, profile in spawn.candidates - if "passive" not in profile.flags) - for spawn in spawns - ] + fighters: list[tuple[float, float, float]] = [] + weights: list[float] = [] + for spawn in spawns: + active = [(probability, profile) + for probability, profile in spawn.candidates + if "passive" not in profile.flags] + weights.append(sum(probability * profile.danger + for probability, profile in active)) + dps = sum(probability * profile.damage_second + for probability, profile in active) + kill = sum(probability * profile.kill_seconds + for probability, profile in active) + # An unkillable monster with a damaging attack never stops. + bonus = sum( + probability * (profile.danger - profile.damage_taken) + for probability, profile in active + if math.isfinite(profile.damage_taken)) + if not math.isfinite(kill) and dps > 0.0: + bonus = math.inf + fighters.append((dps, kill if math.isfinite(kill) else 0.0, bonus)) best_pack: list[int] = [] pack_danger = 0.0 for target in spawns: @@ -472,7 +558,7 @@ def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat max(abs(target.x - spawn.x), abs(target.y - spawn.y)) <= spawn.weighted("aggro_radius") ] - danger = sum(weights[index] for index in pack) + danger = self._sequential_exposure([fighters[i] for i in pack]) if danger > pack_danger or not best_pack and pack: pack_danger = danger best_pack = pack @@ -500,16 +586,21 @@ def _apply_approach(self, result: MapResult, options: AnalysisOptions) -> None: """Find the least dangerous authored approach from an origin. A bottleneck search walks backwards from the spot's maps and minimizes - the most dangerous intermediate map, then the number of maps, then the - path names for determinism. Origins themselves are not charged. + the most dangerous map crossed, then the number of maps, then the path + names for determinism. A savebed or --approach-origin map is where the + character starts and is free; a surface tile is charged its own + danger because the character must cross it to use its entrance. """ if not options.model_approach: return - predecessors, default_origins = self._links() - origins = default_origins | { - "/" + origin.strip().removeprefix("maps/").lstrip("/") - for origin in options.approach_origins if origin.strip() + predecessors, surface, savebeds = self._links() + explicit = { + key for key in map(self.resolve_map_key, options.approach_origins) + if key is not None } + free = explicit if options.approach_origins_only else savebeds | explicit + charged = frozenset() if options.approach_origins_only else surface - free + origins = free | charged map_prefix = self.map_root.relative_to(self.root).as_posix() members = {"/" + path.removeprefix(map_prefix + "/") for path in result.map_paths} if members & origins: @@ -523,38 +614,43 @@ def metric(key: str) -> float: heap: list[tuple[float, int, tuple[str, ...], str]] = [ (0.0, 0, (), member) for member in sorted(members)] - settled: set[str] = set() + # A map popped again with fewer hops may still reach an origin within + # the limit, so prune by hops rather than settling maps once. + best_hops: dict[str, int] = {} found = None while heap: bottleneck, hops, path, node = heapq.heappop(heap) - if node in settled: - continue - settled.add(node) if node in origins: found = bottleneck, path, node break + if hops >= best_hops.get(node, math.inf): + continue + best_hops[node] = hops for previous in predecessors.get(node, ()): - if previous in members or previous in settled: + if previous in members or previous in path: continue if previous in origins: - heapq.heappush(heap, (bottleneck, hops, path, previous)) + cost = metric(previous) if previous in charged else 0.0 + heapq.heappush(heap, (max(bottleneck, cost), hops, path, previous)) elif hops < options.max_approach_maps: heapq.heappush(heap, ( max(bottleneck, metric(previous)), hops + 1, path + (previous,), previous)) if found is None: result.approach_status = "unreachable" + result.approach_danger_flags = ("approach_unknown",) return bottleneck, path, origin = found ordered = tuple(reversed(path)) - result.approach_status = "path" if ordered else "origin" + charged_maps = ((origin,) if origin in charged else ()) + ordered + result.approach_status = "path" result.approach_origin = map_prefix + origin result.approach_maps = tuple(map_prefix + key for key in ordered) result.approach_danger = bottleneck survival_level = max(options.player_level, options.character_level) flags: Counter[str] = Counter() worst = None - for key in ordered: + for key in charged_maps: threat = self._approach_threat(key, options) if worst is None or metric(key) > metric(worst): worst = key @@ -566,7 +662,7 @@ def metric(key: str) -> float: level_flags = tuple( f"{Path(key).name} L{self._approach_threat(key, options).max_level} > " f"allowed L{survival_level + options.max_level_gap}" - for key in ordered + for key in charged_maps if self._approach_threat(key, options).max_level > survival_level + options.max_level_gap) result.approach_danger_flags = tuple( @@ -1709,7 +1805,7 @@ def _score(results: list[MapResult], options: AnalysisOptions) -> list[MapResult safety = (min(1.0, safest / max(result.danger, 0.001)) if math.isfinite(result.danger) else 0.0) result.spot_safety_score = safety - if result.approach_maps: + if result.approach_status == "path": # Approach maps use the same health budget, or the same # least-dangerous-spot reference, as the spot itself. reference = (options.max_health if options.max_health > 0.0 @@ -1718,6 +1814,10 @@ def _score(results: list[MapResult], options: AnalysisOptions) -> list[MapResult min(1.0, reference / max(result.approach_danger, 0.001)) if math.isfinite(result.approach_danger) else 0.0) safety = min(safety, result.approach_safety_score) + elif (result.approach_status == "unreachable" and + options.unreachable_approach_safety is not None): + result.approach_safety_score = options.unreachable_approach_safety + safety = min(safety, result.approach_safety_score) result.safety_score = safety components = { "xp": result.xp_hour / maxima["xp"], diff --git a/farming_analyzer/cli.py b/farming_analyzer/cli.py index 6a03de7..7506e9e 100644 --- a/farming_analyzer/cli.py +++ b/farming_analyzer/cli.py @@ -124,6 +124,10 @@ def build_parser() -> argparse.ArgumentParser: "may be repeated (surface world tiles and savebed maps are always origins)") parser.add_argument("--max-approach-maps", type=int, default=16, help="longest approach, in maps between origin and spot (default: 16)") + parser.add_argument("--approach-origins-only", action="store_true", + help="use only --approach-origin maps as origins, not surface tiles or savebeds") + parser.add_argument("--unreachable-approach-safety", type=float, metavar="SAFETY", + help="cap safety (0..1) of spots with no authored approach; default: no cap") parser.add_argument("--ignore-approach", dest="model_approach", action="store_false", help="score only the spot's own maps, not the maps crossed to reach it") parser.add_argument("--include-static", action="store_true", @@ -263,6 +267,16 @@ def main(argv: list[str] | None = None) -> int: raise SystemExit("circuit-size must be between 1 and 8") if not (1 <= args.max_approach_maps <= 64): raise SystemExit("max-approach-maps must be between 1 and 64") + if (args.unreachable_approach_safety is not None and + not (0.0 <= args.unreachable_approach_safety <= 1.0)): + raise SystemExit("unreachable-approach-safety must be between 0 and 1") + if args.approach_origins_only and not args.approach_origin: + raise SystemExit("--approach-origins-only requires at least one --approach-origin") + unknown_origins = [ + origin for origin in args.approach_origin + if analyzer.resolve_map_key(origin) is None] + if unknown_origins: + raise SystemExit("unknown approach origin map: " + ", ".join(unknown_origins)) if not (1 <= args.group_level_span <= 50): raise SystemExit("group-level-span must be between 1 and 50") if not (1 <= character_level <= maximum_level): @@ -316,6 +330,8 @@ def main(argv: list[str] | None = None) -> int: model_approach=args.model_approach, approach_origins=tuple(args.approach_origin), max_approach_maps=args.max_approach_maps, + approach_origins_only=args.approach_origins_only, + unreachable_approach_safety=args.unreachable_approach_safety, ) results = analyzer.scan(options) initial_rejections = list(analyzer.rejections) diff --git a/farming_analyzer/models.py b/farming_analyzer/models.py index a6e5823..0b53837 100644 --- a/farming_analyzer/models.py +++ b/farming_analyzer/models.py @@ -201,6 +201,8 @@ class AnalysisOptions: model_approach: bool = True approach_origins: tuple[str, ...] = () max_approach_maps: int = 16 + approach_origins_only: bool = False + unreachable_approach_safety: float | None = None @property def simulate_melee(self) -> bool: diff --git a/farming_analyzer/presentation.py b/farming_analyzer/presentation.py index cbf7f04..d7b5b29 100644 --- a/farming_analyzer/presentation.py +++ b/farming_analyzer/presentation.py @@ -325,7 +325,7 @@ def render_text(results: list[MapResult], options: AnalysisOptions, limit: int, lines.append( f" approach: {len(result.approach_maps)} map(s) from " f"{result.approach_origin} via " - f"{' -> '.join(Path(path).name for path in result.approach_maps)}; " + f"{' -> '.join(Path(path).name for path in result.approach_maps) or 'its exit'}; " f"worst {Path(result.approach_worst_map).name or 'none'} " f"(danger {result.approach_danger:.0f}, safety " f"{result.approach_safety_score * 100.0:.0f}% vs spot " @@ -333,9 +333,12 @@ def render_text(results: list[MapResult], options: AnalysisOptions, limit: int, f"{', '.join(result.approach_danger_flags) or 'ordinary melee'}" ) elif result.approach_status == "unreachable": + capped = options.unreachable_approach_safety lines.append( - " approach: no authored exit path from a surface tile, savebed, " - "or --approach-origin; scored on the spot alone") + " approach: unknown (approach_unknown) — no authored exit path from an " + "origin within --max-approach-maps; " + + ("scored on the spot alone" if capped is None else + f"safety capped at {capped * 100.0:.0f}%")) if options.character_speed > 0.0: lines.append( f" route: ~{result.route_steps:,} authored walkable tile steps = " @@ -393,7 +396,7 @@ def render_text(results: list[MapResult], options: AnalysisOptions, limit: int, "--include-static is used. Safety is also capped by the least dangerous authored approach: " "exits, tile paths, and walkable coordinate seams from a surface world tile, savebed map, or " "--approach-origin, charging the worst aggressive pack on each map crossed (including " - "map-reset monsters). Scripted teleports, keys, locked doors, and fleeing past monsters are " + "map-reset monsters and the entrance surface tile) by sequential exposure. Scripted teleports, keys, locked doors, and fleeing past monsters are " "not modeled; --ignore-approach scores the spot alone.", )) if warnings: diff --git a/farming_analyzer/tests/test_approach.py b/farming_analyzer/tests/test_approach.py index 96a2823..999864c 100644 --- a/farming_analyzer/tests/test_approach.py +++ b/farming_analyzer/tests/test_approach.py @@ -6,14 +6,16 @@ import json import tempfile import unittest -from dataclasses import replace +from dataclasses import MISSING, fields, replace from pathlib import Path from unittest.mock import patch +from farming_analyzer.analyzer import ApproachThreat from farming_analyzer import ( SERVER_ROOT, AnalysisOptions, FarmingAnalyzer, + ROOT, MapResult, main, ) @@ -72,13 +74,15 @@ ROOM = "underground_city" DANGER = "circuit[underground_city_0_0 + underground_city_1_0]" SAFE = "circuit[underground_city_5_0 + underground_city_6_0]" +LOST = "underground_city_9_9" def _map(name: str, region: str, *, spawns: tuple[tuple[str, int, int], ...] = (), - exits: tuple[tuple[str, int, int], ...] = (), extra: str = "") -> str: + exits: tuple[tuple[str, int, int], ...] = (), extra: str = "", + header: tuple[str, ...] = ()) -> str: lines = [ "arch map", f"name {name}", f"width {SIZE}", f"height {SIZE}", - "difficulty 10", f"region {region}", "end", + "difficulty 10", f"region {region}", *header, "end", ] for y in range(SIZE): for x in range(SIZE): @@ -126,6 +130,9 @@ def setUpClass(cls): exits=(("entry", 0, 0),))) (maps / dungeon / second).write_text(_map( f"{dungeon} cave", "dungeon", spawns=rats)) + # Rats behind no authored exit at all. + (maps / "lost").mkdir() + (maps / "lost" / LOST).write_text(_map("lost cave", "dungeon", spawns=rats)) cls.analyzer = FarmingAnalyzer(root, SERVER_ROOT) @classmethod @@ -218,8 +225,22 @@ def test_unreachable_spot_keeps_its_own_safety(self): max_approach_maps=0)) danger = results[DANGER] self.assertEqual("unreachable", danger.approach_status) + self.assertEqual(("approach_unknown",), danger.approach_danger_flags) self.assertEqual(danger.spot_safety_score, danger.safety_score) + def test_disconnected_spot_is_flagged_and_optionally_capped(self): + lost = self.results(self.options())[f"maps/lost/{LOST}"] + self.assertEqual("unreachable", lost.approach_status) + self.assertEqual(("approach_unknown",), lost.approach_danger_flags) + self.assertEqual(lost.spot_safety_score, lost.safety_score) + capped = self.results(self.options( + unreachable_approach_safety=0.3))[f"maps/lost/{LOST}"] + self.assertEqual(0.3, capped.approach_safety_score) + self.assertEqual(min(0.3, capped.spot_safety_score), capped.safety_score) + reachable = self.results(self.options( + unreachable_approach_safety=0.3))[SAFE] + self.assertEqual(reachable.spot_safety_score, reachable.safety_score) + def test_cli_json_exposes_approach_fields_and_options(self): def run(*extra: str) -> dict: stdout = io.StringIO() @@ -240,12 +261,215 @@ def run(*extra: str) -> dict: self.assertEqual("maps/world_0_0", danger["approach_origin"]) self.assertLess(danger["safety_score"], danger["spot_safety_score"]) self.assertIn("fire×3", danger["approach_danger_flags"]) - origin = run("--approach-origin", "/danger/underground_city_0_0")[DANGER] + origin = run("--approach-origin", "/maps/danger/underground_city_0_0")[DANGER] self.assertEqual("origin", origin["approach_status"]) + with self.assertRaises(SystemExit) as raised: + run("--approach-origin", "danger/nowhere") + self.assertIn("danger/nowhere", str(raised.exception)) + with self.assertRaises(SystemExit): + run("--approach-origins-only") + lost = run("--unreachable-approach-safety", "0.25")[f"maps/lost/{LOST}"] + self.assertEqual(0.25, lost["approach_safety_score"]) ignored = run("--ignore-approach")[DANGER] self.assertEqual("disabled", ignored["approach_status"]) self.assertEqual(ignored["spot_safety_score"], ignored["safety_score"]) +class ApproachGraphTest(unittest.TestCase): + """Authored connectivity, origin handling and the bounded search.""" + + @classmethod + def setUpClass(cls): + cls.directory = tempfile.TemporaryDirectory() + root = Path(cls.directory.name) + (root / "arch").mkdir() + (root / "arch" / "test.arc").write_text(ARCHETYPES) + maps = root / "maps" + (maps / "g").mkdir(parents=True) + (maps / "t" / "sub").mkdir(parents=True) + (maps / "regions.reg").write_text("region r\nlongname R\nend\n") + + def write(path: str, **kwargs) -> None: + (maps / path).write_text(_map(path, "r", **kwargs)) + + # Reviewer repro: O->N->M->x2->x1->S at danger 0 and M->Y(50)->S. + for source, targets in { + "O": ("N",), "N": ("M",), "M": ("x2", "Y"), "x2": ("x1",), + "x1": ("S",), "Y": ("S",), "S": ()}.items(): + write(f"g/{source}", exits=tuple((target, 0, 0) for target in targets)) + # Origins: a charged surface tile and a free savebed map. + write("world_0_0", exits=(("t/via_world", 0, 0), ("t/only_world", 0, 0))) + write("t/bedroom", exits=(("via_world", 0, 0),), + extra="arch bed_save\nx 2\ny 2\nend\n") + write("t/via_world") + write("t/only_world") + # A bed_save carried in a container does not make a savebed map. + write("t/storeroom", extra="arch wall\nx 1\ny 1\n" + "arch bed_save\nend\nend\n") + # Path resolution, tile paths, nested exits and missing targets. + write("t/sub/deep", exits=(("../up", 0, 0), ("/t/abs_target", 1, 1), + ("nowhere", 2, 2)), + header=("tile_path_2 ../tiled_east",)) + write("t/up") + write("t/abs_target") + write("t/tiled_east") + write("t/nest", spawns=(("rat", 1, 1),), + extra="arch spawn_point\nx 3\ny 3\n" + "arch exit\nslaying hidden\nend\nend\n" + "arch wall\nx 4\ny 4\narch exit\nslaying hidden\nend\nend\n") + write("t/hidden") + # Server-style tiling for any prefix: diagonals link, depths do not. + write("t/cave_1_1") + write("t/cave_2_2") + write("t/cave_2_1_-1") + write("t/cave_1_1_-1") + cls.analyzer = FarmingAnalyzer(root, SERVER_ROOT) + cls.template = ApproachDangerTest.options(path_pattern=None) + + @classmethod + def tearDownClass(cls): + cls.directory.cleanup() + + def predecessors(self, key: str) -> tuple[str, ...]: + return self.analyzer._links()[0].get(key, ()) + + def approach(self, spot: str, threats: dict[str, float], **changes) -> MapResult: + options = replace(self.template, **changes) + required = { + item.name: 0 for item in fields(MapResult) + if item.default is MISSING and item.default_factory is MISSING} + required.update(path=spot, name=spot, region="r") + result = MapResult(**required, map_paths=(f"maps{spot}",)) + + def threat(key, _options): + danger = threats.get(key, 0.0) + return ApproachThreat(danger, danger, 1, ("fire×1",) if danger else ()) + + with patch.object(self.analyzer, "_approach_threat", side_effect=threat): + self.analyzer._apply_approach(result, options) + return result + + def test_hop_limited_search_keeps_a_shorter_more_dangerous_path(self): + result = self.approach( + "/g/S", {"/g/Y": 50.0}, max_approach_maps=3, + approach_origins=("/g/O",), approach_origins_only=True) + self.assertEqual("path", result.approach_status) + self.assertEqual(("maps/g/N", "maps/g/M", "maps/g/Y"), result.approach_maps) + self.assertEqual(50.0, result.approach_danger) + self.assertEqual("maps/g/Y", result.approach_worst_map) + unlimited = self.approach( + "/g/S", {"/g/Y": 50.0}, approach_origins=("maps/g/O",), + approach_origins_only=True) + self.assertEqual(0.0, unlimited.approach_danger) + self.assertEqual(("maps/g/N", "maps/g/M", "maps/g/x2", "maps/g/x1"), + unlimited.approach_maps) + + def test_surface_entrances_are_charged_and_savebeds_are_free(self): + threats = {"/world_0_0": 70.0, "/t/bedroom": 90.0} + only_world = self.approach("/t/only_world", threats) + self.assertEqual("path", only_world.approach_status) + self.assertEqual((), only_world.approach_maps) + self.assertEqual("maps/world_0_0", only_world.approach_origin) + self.assertEqual(70.0, only_world.approach_danger) + self.assertEqual("maps/world_0_0", only_world.approach_worst_map) + self.assertEqual(("fire×1",), only_world.approach_danger_flags) + via_bed = self.approach("/t/via_world", threats) + self.assertEqual("maps/t/bedroom", via_bed.approach_origin) + self.assertEqual(0.0, via_bed.approach_danger) + explicit = self.approach( + "/t/only_world", threats, approach_origins=("/world_0_0",), + approach_origins_only=True) + self.assertEqual(0.0, explicit.approach_danger) + self.assertEqual( + "unreachable", + self.approach("/t/via_world", threats, approach_origins=("/g/O",), + approach_origins_only=True).approach_status) + + def test_savebed_detection_ignores_carried_beds(self): + _predecessors, surface, savebeds = self.analyzer._links() + self.assertEqual(frozenset({"/world_0_0"}), surface) + self.assertEqual(frozenset({"/t/bedroom"}), savebeds) + + def test_exit_and_tile_path_resolution(self): + self.assertEqual(("/t/sub/deep",), self.predecessors("/t/up")) + self.assertEqual(("/t/sub/deep",), self.predecessors("/t/abs_target")) + self.assertEqual(("/t/sub/deep",), self.predecessors("/t/tiled_east")) + self.assertNotIn("/t/sub/nowhere", self.analyzer._links()[0]) + self.assertEqual("/t/up", FarmingAnalyzer._resolve_map_path( + "/t/sub/deep", "../up")) + self.assertEqual("/t/abs_target", FarmingAnalyzer._resolve_map_path( + "/t/sub/deep", "/t/abs_target")) + self.assertIsNone(FarmingAnalyzer._resolve_map_path("/t/sub/deep", " ")) + + def test_exits_carried_in_spawn_points_or_containers_are_ignored(self): + self.assertEqual((), self.predecessors("/t/hidden")) + self.assertEqual("unreachable", self.approach("/t/hidden", {}).approach_status) + + def test_server_tiling_links_diagonals_but_not_depths(self): + self.assertEqual(("/t/cave_2_2",), self.predecessors("/t/cave_1_1")) + self.assertEqual(("/t/cave_1_1",), self.predecessors("/t/cave_2_2")) + self.assertEqual(("/t/cave_1_1_-1",), self.predecessors("/t/cave_2_1_-1")) + self.assertEqual(("/t/cave_2_1_-1",), self.predecessors("/t/cave_1_1_-1")) + self.assertEqual(("cave", 2, 1, -1), + FarmingAnalyzer._tile_coordinates("cave_2_1_-1")) + self.assertIsNone(FarmingAnalyzer._tile_coordinates("ruins_0101")) + self.assertIsNone(FarmingAnalyzer._tile_coordinates("cave_1")) + + def test_resolve_map_key_accepts_content_and_map_root_paths(self): + for spelling in ("/t/up", "t/up", "maps/t/up", "/maps/t/up"): + self.assertEqual("/t/up", self.analyzer.resolve_map_key(spelling)) + self.assertIsNone(self.analyzer.resolve_map_key("/t/missing")) + + +UNDERGROUND_CITY = (ROOT / "maps" / "shattered_islands" / "strakewood_island" / + "underground_city") + + +@unittest.skipUnless((UNDERGROUND_CITY / "underground_city_0_0").is_file(), + "requires the sibling content checkout") +class UndergroundCityEntranceTest(unittest.TestCase): + """Regression for the 2026-11-14 deaths on the Underground City entrance.""" + + @classmethod + def setUpClass(cls): + cls.analyzer = FarmingAnalyzer() + + @staticmethod + def sera(max_health: float, **changes) -> AnalysisOptions: + """Level 36 slash melee, no fire, acid or poison protection.""" + options = replace( + ApproachDangerTest.options(path_pattern=None), + player_level=36, character_level=36, player_ac=59, dps=0.0, + damage_per_attack=0.0, attack_delay=0.0, melee_damage=65, + weapon_class=46, weapon_speed=1.0, player_attacks=(("slash", 100),), + player_protections=(("cleave", 46), ("cold", 9), ("impact", 42), + ("pierce", 41), ("slash", 57)), + max_health=max_health) + return replace(options, **changes) + + def test_entrance_slime_cluster_is_one_sequential_encounter(self): + threat = self.analyzer._approach_threat( + "/shattered_islands/strakewood_island/underground_city/" + "underground_city_0_0", self.sera(322.0)) + # Three brown cave puddings and an ochre cave jelly at (17-23, 1-3) + # all reach one pull point; killed in turn they deal ~288 damage. + self.assertEqual(("fire×3", "acid×1", "poison×1"), threat.flags) + self.assertGreater(threat.pack_danger, 244.0) + self.assertLess(threat.pack_danger, 322.0) + + def test_spot_behind_the_entrance_loses_safety_at_measured_health(self): + results = self.analyzer.scan(self.sera( + 244.0, circuit_size=1, path_pattern=r"underground_city_4_2$")) + spot = next(result for result in results + if result.map_paths[0].endswith("underground_city_4_2")) + self.assertIn( + "maps/shattered_islands/strakewood_island/underground_city/" + "underground_city_0_0", spot.approach_maps) + self.assertEqual(1.0, spot.spot_safety_score) + self.assertLess(spot.safety_score, 0.9) + for flag in ("fire×3", "acid×1", "poison×1"): + self.assertIn(flag, spot.approach_danger_flags) + + if __name__ == "__main__": unittest.main() From 4512a52b8b18314e5eeaf943e6f2b2cd171e5648 Mon Sep 17 00:00:00 2001 From: Zoey Rose Date: Sat, 14 Nov 2026 21:25:28 -0600 Subject: [PATCH 3/5] fix(farming-analyzer): search approaches over walkable map components MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Linking whole maps credited exits a character cannot stand next to. The world_2_69 exit_green sits on a two-tile pocket reachable only from inside the Underground City, so 81 city results took that phantom entrance and stayed at safety 1.0 for a Sera-like profile at 244 HP. - Search over (map, 8-neighbour walkable component) nodes, computed lazily and cached. Exits leave from their tile or an adjacent walkable tile and land at hp/sp, enter_x/enter_y when out of range, or an adjacent free tile; stairs without slaying follow last_heal through the tile table; same-map exits move between components. - Seams join only the edge and corner tiles they connect, using the server's tile table (header tile_path_N first, then derived names). - Origins are components: placed savebeds and every part of an explicit origin are free; surface components are charged origins only when their surface-seam group touches a savebed or an exit to or from a savebed map, so islets and pockets entered from below are not origins. - Charge a spawn that is aggressive with probability p by p, not p², in sequential exposure; document why crossing a pack costs about (n+1)/2 times farming it. - Replace the approach_unknown flag with a boolean field, and document path results with no approach maps. - Test islets, surface pockets, dungeon dead ends, enter_x/enter_y arrival and seam components, plus a content-gated check that the city circuits now approach through 0_0. Co-Authored-By: Claude Opus 5.5 --- farming_analyzer/README.md | 135 +++++--- farming_analyzer/analyzer.py | 436 ++++++++++++++++++------ farming_analyzer/cli.py | 8 +- farming_analyzer/models.py | 1 + farming_analyzer/presentation.py | 8 +- farming_analyzer/sources.py | 10 +- farming_analyzer/tests/test_approach.py | 175 ++++++++-- 7 files changed, 576 insertions(+), 197 deletions(-) diff --git a/farming_analyzer/README.md b/farming_analyzer/README.md index c3aa5f7..974efcd 100644 --- a/farming_analyzer/README.md +++ b/farming_analyzer/README.md @@ -236,87 +236,110 @@ rest time are solved together. ## Approach danger -A spot is only as safe as the maps crossed to reach it. Before scoring, the -analyzer builds a map graph from: - -- authored `type 66` exits placed directly on a map (not ones carried in a - spawn point or container), following their `slaying` destination relative - to the map, or from the map root when it starts with `/`; -- header `tile_path_N` links; -- horizontal tiling derived from map names as `derive_map_filename_tiles()` - in classic `server/src/server/map.c` does: any basename with two or three - numeric words of at most three characters (`cave_2_1_-1`) tiles with the - eight same-depth neighbours whose derived names exist, when a tile on each - side of the shared edge or corner is walkable. - -This approximates the server's tiling. Explicit tile paths do not replace the -derived neighbour in that direction, and the server's derived up/down tiles -are not linked: depth changes only follow authored exits and tile paths. -Missing destinations are ignored. - -Origins are surface `world_X_Y` tiles (depth 0) and every map holding a -placed savebed (`type 106`), plus each repeatable `--approach-origin MAP`. -`MAP` may be written `/region/map`, `region/map`, or `maps/region/map`; an -unknown map is an error. `--approach-origins-only` uses only the -`--approach-origin` maps, for example "I start from my savebed". A savebed or -explicit origin is where the character starts and is free. A surface tile is -charged its own danger, because the character must cross it to use its -entrance. The `--path` filter and `--exclude-region` do not hide approach -maps. - -A bottleneck search walks backwards from the spot's maps to an origin, -minimizing the most dangerous map crossed, then the number of maps, then the -map names, so the result is deterministic. It crosses at most -`--max-approach-maps` maps between origin and spot (default 16). A map is -expanded again when reached with fewer maps, so a long safe path cannot block -a shorter one that fits the limit. +A spot is only as safe as the maps crossed to reach it. The approach search +runs over walkable components rather than whole maps: each map's walkable +tiles are split into 8-neighbour connected components, computed lazily for +the maps the search reaches and cached. A character can move: + +- through a placed `type 66` exit (not one carried in a spawn point or + container) from its own tile, or from an adjacent walkable tile when the + exit tile is blocked. It lands at the exit's `hp`/`sp`, at the target's + `enter_x`/`enter_y` when those are out of range (such as `-1`), or on an + adjacent free tile when the landing tile is blocked, as + `object_enter_map()` does. `slaying` resolves relative to the map, or from + the map root when it starts with `/`. Stairs without `slaying` use + `last_heal` (9 up, 10 down, or a horizontal direction) to pick the tiled + map and keep their own position; an exit without `slaying` but with + `hp`/`sp` moves within its own map. Paired `sub_type` exits, scripts, keys + and locks are not followed; doors count as open; +- across a tiled map edge or corner from an edge tile to the walkable tile + beyond it. Tiling follows `derive_map_filename_tiles()` in classic + `server/src/server/map.c`: header `tile_path_N` (direction `N - 1`) wins, + otherwise any basename with two or three numeric words of at most three + characters (`cave_2_1_-1`) derives its neighbours' names when those maps + exist. Only the eight same-depth directions are walked; up/down tiles are + used only by stairs, not as seams. + +Origins are components: + +- each placed savebed's component (free); +- every walkable component of each `--approach-origin MAP` (free). `MAP` may + be written `/region/map`, `region/map`, or `maps/region/map`; an unknown + map is an error. `--approach-origins-only` uses only these, for example + "I start from my savebed"; +- town-connected surface components (charged). Surface components (depth-0 + `world_X_Y` tiles) are grouped by walking seams between surface tiles + only. A group is town-connected when one of its components holds a + savebed or is joined by an exit to or from a savebed map, such as an inn + door. Islets, ship-only islands, and surface pockets entered only from + below are therefore not origins. A charged surface origin costs its map's + own danger, because the character must cross it to use its entrance. + +The `--path` filter and `--exclude-region` do not hide approach maps. + +A bottleneck search walks backwards from the components holding the spot's +spawns to an origin, minimizing the most dangerous map crossed, then the +number of components crossed, then their names, so the result is +deterministic. It crosses at most `--max-approach-maps` components between +origin and spot (default 16). A component is expanded again when reached +with fewer crossings, so a long safe path cannot block a shorter one that +fits the limit. Other components of the spot's own maps are free and are not +listed, because the spot's safety already covers them. Each crossed map is charged for its worst aggressive encounter, reusing the spot's monster, damage, hit-chance, kill-time and protection model. Spawns whose own detection radius reaches one pull point fight together. That pack is charged by sequential exposure: every living monster keeps attacking until it dies, killed in the order that minimizes damage (ascending kill time per -incoming DPS), plus each monster's secondary-risk bonus. Without -`--max-health`, the worst single aggressive spawn is charged instead, -matching the relative per-monster safety model. Directly placed monsters -count even without `--include-static`, because they are present when a -traveller loads the map. Passive monsters are skipped. AoE is not credited -on the approach. Each map's threat is cached for the current options. +incoming DPS), plus each monster's secondary-risk bonus. A spawn that is +aggressive with probability `p` is charged `p` times its conditional damage +and adds `p` times its kill time to the monsters after it. For `n` identical +monsters this charges `n(n + 1)/2` kills' worth of exposure, about +`(n + 1)/2` times the farming model's `n` (danger times pack size). That is +deliberate: a farmer chooses pulls and fights one monster at a time, while a +traveller crossing the map meets the whole pack at once and every monster +still alive keeps hitting. Without `--max-health`, the worst single +aggressive spawn is charged instead, matching the relative per-monster +safety model. Directly placed monsters count even without +`--include-static`, because they are present when a traveller loads the +map. Passive monsters are skipped. AoE is not credited on the approach. +Each map's threat is cached for the current options. The approach safety uses the same reference as the spot: `max_health / approach_danger` with `--max-health`, otherwise the least dangerous eligible spot's danger divided by `approach_danger`, capped at one. The reported `safety_score`, and therefore the balanced score and `--ranking safety`, is -the lower of the spot and approach safeties. A spot with no authored path -from an origin within the limit keeps its own safety and gets the -`approach_unknown` flag; `--unreachable-approach-safety SAFETY` (0 to 1) -caps such spots instead. Scripted teleports, keys, locked doors, and running -past monsters are not modeled. Neither is the variance of a fight, nor the -server's poisoning pulses (`attack_perform_poison()`: five to ten pulses of -up to a third of maximum HP) beyond the secondary-risk heuristic, so a pack -whose expected damage is just inside one health bar still reports full -safety. `--ignore-approach` restores the spot-only score. +the lower of the spot and approach safeties. A spot with no path from an +origin within the limit keeps its own safety and sets `approach_unknown`; +`--unreachable-approach-safety SAFETY` (0 to 1) caps such spots instead. +Running past monsters, fight variance, and the server's poisoning pulses +(`attack_perform_poison()`: five to ten pulses of up to a third of maximum +HP) beyond the secondary-risk heuristic are not modeled, so a pack whose +expected damage is just inside one health bar still reports full safety. +`--ignore-approach` restores the spot-only score. Each result (`results`, `groups[].representative`, and `rankings`) adds these JSON fields; existing fields keep their names and types: - `spot_safety_score`: the spot-only safety previously reported as `safety_score`; -- `approach_status`: `path` (an origin was found; `approach_maps` may be - empty when a charged surface tile leads straight in), `origin` (a member - map is itself an origin), `unreachable`, or `disabled`; +- `approach_status`: `path` (an origin was found), `origin` (a spawn's + component is itself an origin), `unreachable`, or `disabled`. `path` can + come with an empty `approach_maps` when a charged surface origin leads + straight into the spot; `approach_danger` is then that origin's danger; +- `approach_unknown`: true exactly when `approach_status` is `unreachable`; - `approach_origin`: content-relative origin map, empty unless `path`; - `approach_maps`: content-relative maps crossed, ordered from the origin - towards the spot, excluding the origin; + towards the spot, excluding the origin and the spot's own maps; - `approach_danger`: the charged danger of the worst approach map, including a charged surface origin; - `approach_safety_score`: 0 to 1; 1 without a charged approach, or the `--unreachable-approach-safety` cap; - `approach_worst_map`: the map that sets `approach_danger`; - `approach_danger_flags`: attack and behaviour flags of the monsters in each - charged map's worst encounter (for example `fire×3`), a - `MAP L > allowed L` entry for any charged map whose monsters - exceed the `--max-level-gap` allowance, or `approach_unknown`. + charged map's worst encounter, summed over those maps (for example + `fire×3`), plus a `MAP L > allowed L` entry for any charged + map whose monsters exceed the `--max-level-gap` allowance. ## Profiles, rankings, diagnostics, and training diff --git a/farming_analyzer/analyzer.py b/farming_analyzer/analyzer.py index aaf1d4b..ddc80b2 100644 --- a/farming_analyzer/analyzer.py +++ b/farming_analyzer/analyzer.py @@ -61,6 +61,12 @@ class ApproachThreat: flags: tuple[str, ...] +# Server map_tiled_coords order (server/src/server/map.c); 8 and 9 are up/down. +TILE_DIRECTIONS = ((0, -1), (1, 0), (0, 1), (-1, 0), (1, -1), (1, 1), (-1, 1), (-1, -1)) +TILE_INDEX = {direction: index for index, direction in enumerate(TILE_DIRECTIONS)} +TILED_UP, TILED_DOWN = 8, 9 + + class FarmingAnalyzer: def __init__(self, root: Path = ROOT, server_root: Path = SERVER_ROOT): self.root = root @@ -75,8 +81,14 @@ def __init__(self, root: Path = ROOT, server_root: Path = SERVER_ROOT): self.tick_seconds = self._constant("MAX_TIME", 125000) / 1_000_000.0 self.default_reset = self._constant("MAP_DEFAULTRESET", 7200) self._world_graph = None - self._world_links: tuple[dict[str, tuple[str, ...]], - frozenset[str], frozenset[str]] | None = None + self._map_index_cache: tuple[dict[str, frozenset[str]], frozenset[str]] | None = None + self._tile_cache: dict[str, dict[int, str]] = {} + self._component_cache: dict[str, dict[tuple[int, int], int]] = {} + self._edge_cache: dict[str, tuple[tuple[int, str, int, bool], ...]] = {} + self._predecessor_cache: dict[tuple[str, int], tuple[tuple[str, int], ...]] = {} + self._surface_region: dict[tuple[str, int], int] = {} + self._region_has_town: list[bool] = [] + self._town_nodes: frozenset[tuple[str, int]] | None = None self._threat_options: AnalysisOptions | None = None self._threat_cache: dict[str, ApproachThreat] = {} self._npc_factions = self._load_npc_factions() @@ -338,11 +350,14 @@ def _world(self): ) key = "/" + path.relative_to(self.map_root).as_posix() graph.nodes[key] = node + node.enter = (_integer(one(header["attrs"], "enter_x", 0)), + _integer(one(header["attrs"], "enter_y", 0))) for name, values in header["attrs"].items(): - if re.fullmatch(r"tile_path_\d+", name) and values: + match = re.fullmatch(r"tile_path_(\d+)", name) + if match and values and 1 <= int(match.group(1)) <= len(TILE_DIRECTIONS) + 2: target = self._resolve_map_path(key, values[-1]) if target is not None: - node.exits.add(target) + node.tile_paths[int(match.group(1)) - 1] = target for obj, parent in flatten(parsed["objects"]): attrs = merged_attrs(obj, self.archetypes) x = _integer(one( @@ -359,12 +374,14 @@ def _world(self): obj_type = _integer(attrs.get("type")) # Only exits placed on the map, not carried in an # inventory or spawn template, lead the player elsewhere. - if parent is None and obj_type == EXIT_TYPE and attrs.get("slaying"): - target = self._resolve_map_path(key, attrs["slaying"]) - if target is not None: - node.exits.add(target) + if parent is None and obj_type == EXIT_TYPE: + slaying = attrs.get("slaying", "") + node.exits.append(( + x, y, self._resolve_map_path(key, slaying), + _integer(attrs.get("hp")), _integer(attrs.get("sp")), + _integer(attrs.get("last_heal")))) elif parent is None and obj_type == SAVEBED_TYPE: - node.savebed = True + node.savebeds.append((x, y)) # Doors, exits, and teleporters are traversable server-side. if attrs.get("no_pass") == "1" and attrs.get("type") not in ( "20", "64", "66"): @@ -407,69 +424,234 @@ def _tile_coordinates(basename: str) -> tuple[str, int, int, int] | None: z = coordinates[2] if len(coordinates) > 2 else 0 return basename[:max(0, len(basename) - length)], coordinates[0], coordinates[1], z - @staticmethod - def _seam_walkable(source: TerrainMap, target: TerrainMap, - dx: int, dy: int) -> bool: - """Return whether a tile pair across a tiled-map edge or corner is walkable.""" - if dx and dy: - return (source.walkable(source.width - 1 if dx > 0 else 0, - source.height - 1 if dy > 0 else 0) and - target.walkable(0 if dx > 0 else target.width - 1, - 0 if dy > 0 else target.height - 1)) - if dx: - source_x = source.width - 1 if dx > 0 else 0 - target_x = 0 if dx > 0 else target.width - 1 - return any( - source.walkable(source_x, y) and target.walkable(target_x, y) - for y in range(min(source.height, target.height))) - source_y = source.height - 1 if dy > 0 else 0 - target_y = 0 if dy > 0 else target.height - 1 - return any( - source.walkable(x, source_y) and target.walkable(x, target_y) - for x in range(min(source.width, target.width))) - - def _links(self) -> tuple[dict[str, tuple[str, ...]], frozenset[str], frozenset[str]]: - """Return reverse map connectivity, surface origins, and savebed maps. - - A map links to another through an authored exit (``type 66`` with a - ``slaying`` destination), a header ``tile_path_N``, or a walkable - edge or corner between maps the server tiles horizontally from their - coordinate names (same depth, all eight directions). Depth changes - only follow authored exits and tile paths. The returned mapping lists, - for every map, the maps that lead into it. + def _tiles(self, key: str) -> dict[int, str]: + """Return a map's tiled neighbours by server direction index. + + Header ``tile_path_N`` entries win; otherwise the neighbour is derived + from the coordinate name, as derive_map_filename_tiles() does, when + that map exists. """ - if self._world_links is None: - graph = self._world() - predecessors: dict[str, set[str]] = defaultdict(set) + cached = self._tile_cache.get(key) + if cached is not None: + return cached + nodes = self._world().nodes + tiles = dict(nodes[key].tile_paths) + coordinates = self._tile_coordinates(posixpath.basename(key)) + if coordinates is not None: + prefix, x, y, z = coordinates + parent = posixpath.dirname(key) + + def name(cx: int, cy: int, cz: int) -> str: + return posixpath.join( + parent, f"{prefix}_{cx}_{cy}" + (f"_{cz}" if cz else "")) + + for index, (dx, dy) in enumerate(TILE_DIRECTIONS): + tiles.setdefault(index, name(x + dx, y + dy, z)) + tiles.setdefault(TILED_UP, name(x, y, z + 1)) + tiles.setdefault(TILED_DOWN, name(x, y, z - 1)) + tiles = {index: target for index, target in tiles.items() + if target in nodes and target != key} + self._tile_cache[key] = tiles + return tiles + + def _components(self, key: str) -> dict[tuple[int, int], int]: + """Label a map's walkable tiles by 8-neighbour connected component.""" + cached = self._component_cache.get(key) + if cached is not None: + return cached + node = self._world().nodes[key] + labels: dict[tuple[int, int], int] = {} + label = -1 + for start_y in range(node.height): + for start_x in range(node.width): + if (start_x, start_y) in labels or not node.walkable(start_x, start_y): + continue + label += 1 + labels[(start_x, start_y)] = label + frontier = [(start_x, start_y)] + while frontier: + x, y = frontier.pop() + for dx in (-1, 0, 1): + for dy in (-1, 0, 1): + tile = (x + dx, y + dy) + if tile not in labels and node.walkable(*tile): + labels[tile] = label + frontier.append(tile) + self._component_cache[key] = labels + return labels + + def _land(self, key: str, x: int, y: int) -> tuple[int, ...]: + """Components a character occupies at (x, y), or next to it when blocked. + + Mirrors object_enter_map(): out-of-map coordinates fall back to the + map's enter_x/enter_y, and a blocked tile uses the adjacent free spots. + """ + node = self._world().nodes[key] + if not (0 <= x < node.width and 0 <= y < node.height): + x, y = node.enter + labels = self._components(key) + if (x, y) in labels: + return (labels[(x, y)],) + return tuple(sorted({ + labels[(x + dx, y + dy)] for dx in (-1, 0, 1) for dy in (-1, 0, 1) + if (x + dx, y + dy) in labels})) + + def _exit_destination(self, key: str, exit_object: tuple[int, int, str | None, int, int, int] + ) -> tuple[str, int, int] | None: + """Resolve a placed exit like exit.c insert_map_func() and object_enter_map().""" + nodes = self._world().nodes + x, y, destination, hp, sp, last_heal = exit_object + if destination is None: + tiles = self._tiles(key) + if 0 < last_heal <= len(TILE_DIRECTIONS) + 2 and last_heal - 1 in tiles: + destination, hp, sp = tiles[last_heal - 1], x, y + elif hp != -1 and sp != -1: + destination = key + else: + return None + if destination not in nodes: + return None + return destination, hp, sp + + def _out_edges(self, key: str) -> tuple[tuple[int, str, int, bool], ...]: + """Return (component, target map, target component, is_seam) moves. + + Exits are taken from their own tile, or an adjacent walkable tile when + the exit tile is blocked, and land at their hp/sp destination (the + target's enter_x/enter_y when out of range). Seams join edge tiles to + the walkable tile across the edge or corner, 8-neighbour style. + """ + cached = self._edge_cache.get(key) + if cached is not None: + return cached + nodes = self._world().nodes + node = nodes[key] + labels = self._components(key) + edges: set[tuple[int, str, int, bool]] = set() + for exit_object in node.exits: + resolved = self._exit_destination(key, exit_object) + if resolved is None: + continue + destination, hp, sp = resolved + for source in self._land(key, exit_object[0], exit_object[1]): + for arrival in self._land(destination, hp, sp): + if (destination, arrival) != (key, source): + edges.add((source, destination, arrival, False)) + tiles = self._tiles(key) + for (x, y), label in labels.items(): + if 0 < x < node.width - 1 and 0 < y < node.height - 1: + continue + for dx in (-1, 0, 1): + for dy in (-1, 0, 1): + nx, ny = x + dx, y + dy + tx = (nx >= node.width) - (nx < 0) + ty = (ny >= node.height) - (ny < 0) + if not tx and not ty: + continue + other = tiles.get(TILE_INDEX[(tx, ty)]) + if other is None: + continue + target = nodes[other] + mx = nx - node.width if tx > 0 else target.width + nx if tx < 0 else nx + my = ny - node.height if ty > 0 else target.height + ny if ty < 0 else ny + arrival = self._components(other).get((mx, my)) + if arrival is not None: + edges.add((label, other, arrival, True)) + result = tuple(sorted(edges)) + self._edge_cache[key] = result + return result + + def _map_index(self) -> tuple[dict[str, frozenset[str]], frozenset[str]]: + """Return the maps that can lead into each map, and surface tiles.""" + if self._map_index_cache is None: + nodes = self._world().nodes + incoming: dict[str, set[str]] = defaultdict(set) surface = set() - savebeds = set() - for key, node in graph.nodes.items(): - for target in node.exits: - if target in graph.nodes and target != key: - predecessors[target].add(key) - if node.savebed: - savebeds.add(key) + for key, node in nodes.items(): + for exit_object in node.exits: + resolved = self._exit_destination(key, exit_object) + if resolved is not None: + incoming[resolved[0]].add(key) + for index, target in self._tiles(key).items(): + if index < len(TILE_DIRECTIONS): + incoming[target].add(key) world = LocationIndex.world_coordinates(posixpath.basename(key)) if world is not None and world[0] == "world" and world[3] == 0: surface.add(key) - tiled = self._tile_coordinates(posixpath.basename(key)) - if tiled is None: - continue - prefix, x, y, z = tiled - parent = posixpath.dirname(key) - for dx, dy in ((0, -1), (1, 0), (0, 1), (-1, 0), - (1, -1), (1, 1), (-1, 1), (-1, -1)): - name = f"{prefix}_{x + dx}_{y + dy}" + (f"_{z}" if z else "") - other = posixpath.join(parent, name) - if other != key and other in graph.nodes and self._seam_walkable( - node, graph.nodes[other], dx, dy): - predecessors[other].add(key) - self._world_links = ( - {key: tuple(sorted(values)) for key, values in predecessors.items()}, - frozenset(surface), - frozenset(savebeds), - ) - return self._world_links + self._map_index_cache = ( + {key: frozenset(values) for key, values in incoming.items()}, + frozenset(surface)) + return self._map_index_cache + + def _predecessors(self, node: tuple[str, int]) -> tuple[tuple[str, int], ...]: + """Return the (map, component) nodes with a move into ``node``.""" + cached = self._predecessor_cache.get(node) + if cached is not None: + return cached + incoming, _surface = self._map_index() + key, label = node + result = tuple(sorted({ + (source, source_label) + for source in incoming.get(key, ()) + for source_label, target, target_label, _seam in self._out_edges(source) + if target == key and target_label == label and (source, source_label) != node + })) + self._predecessor_cache[node] = result + return result + + def _savebed_nodes(self) -> frozenset[tuple[str, int]]: + return frozenset( + (key, label) + for key, node in self._world().nodes.items() + for x, y in node.savebeds + for label in self._land(key, x, y)) + + def _surface_origin(self, node: tuple[str, int]) -> bool: + """Whether a surface component can be walked to from a town. + + A town is a surface component that holds a savebed or is joined by an + exit to or from a map that holds one, for example an inn door. Surface + components are grouped by walking seams between surface tiles only, so + islets, ship-only islands, and surface pockets entered only from + below do not count. + """ + _incoming, surface = self._map_index() + if node[0] not in surface: + return False + if self._town_nodes is None: + incoming, _surface = self._map_index() + savebed_maps = {key for key, value in self._world().nodes.items() + if value.savebeds} + towns = set(self._savebed_nodes()) + for key in savebed_maps: + for _label, target, target_label, _seam in self._out_edges(key): + towns.add((target, target_label)) + for source in incoming.get(key, ()): + for label, target, _target_label, _seam in self._out_edges(source): + if target == key: + towns.add((source, label)) + self._town_nodes = frozenset(towns) + region = self._surface_region.get(node) + if region is None: + region = len(self._region_has_town) + self._region_has_town.append(False) + self._surface_region[node] = region + frontier = [node] + while frontier: + current = frontier.pop() + if current in self._town_nodes: + self._region_has_town[region] = True + for label, target, target_label, seam in self._out_edges(current[0]): + if not seam or label != current[1] or target not in surface: + continue + neighbour = (target, target_label) + known = self._surface_region.get(neighbour) + if known is None: + self._surface_region[neighbour] = region + frontier.append(neighbour) + elif known != region and self._region_has_town[known]: + self._region_has_town[region] = True + return self._region_has_town[region] def resolve_map_key(self, path: str) -> str | None: """Resolve a user-supplied map path to an authored map, or None. @@ -488,23 +670,26 @@ def resolve_map_key(self, path: str) -> str | None: return None @staticmethod - def _sequential_exposure(fighters: list[tuple[float, float, float]]) -> float: + def _sequential_exposure(fighters: list[tuple[float, float, float, float]]) -> float: """Expected damage while killing an engaged pack one at a time. - Each fighter is (incoming DPS, kill seconds, secondary-risk bonus). - Every living monster keeps attacking until it dies, so a monster's DPS - is charged for the time until its own kill. Killing in ascending - kill-seconds/DPS order (Smith's rule) minimizes that total. + Each fighter is (probability it is an aggressive monster, incoming DPS, + kill seconds, expected secondary-risk bonus), DPS and kill time being + conditional on that monster being present. Every living monster keeps + attacking until it dies, so its DPS is charged until its own kill; + killing in ascending kill-seconds/DPS order (Smith's rule) minimizes + that total. Presence is independent, so each monster pays + ``p * dps * (own kill + expected earlier kills)``. """ total = 0.0 elapsed = 0.0 damaging = sorted( - (item for item in fighters if item[0] > 0.0), - key=lambda item: item[1] / item[0]) - for dps, kill_seconds, bonus in damaging: - elapsed += kill_seconds - total += dps * elapsed + bonus - total += sum(bonus for dps, _kill, bonus in fighters if dps <= 0.0) + (item for item in fighters if item[1] > 0.0), + key=lambda item: item[2] / item[1]) + for probability, dps, kill_seconds, bonus in damaging: + total += probability * dps * (elapsed + kill_seconds) + bonus + elapsed += probability * kill_seconds + total += sum(item[3] for item in fighters if item[1] <= 0.0) return total def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat: @@ -529,7 +714,7 @@ def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat if parsed.get("header") is not None: spawns, _competitors = self._collect_spawns( parsed, options, include_static=True) - fighters: list[tuple[float, float, float]] = [] + fighters: list[tuple[float, float, float, float]] = [] weights: list[float] = [] for spawn in spawns: active = [(probability, profile) @@ -537,10 +722,14 @@ def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat if "passive" not in profile.flags] weights.append(sum(probability * profile.danger for probability, profile in active)) + present = sum(probability for probability, _profile in active) + if present <= 0.0: + fighters.append((0.0, 0.0, 0.0, 0.0)) + continue dps = sum(probability * profile.damage_second - for probability, profile in active) + for probability, profile in active) / present kill = sum(probability * profile.kill_seconds - for probability, profile in active) + for probability, profile in active) / present # An unkillable monster with a damaging attack never stops. bonus = sum( probability * (profile.danger - profile.damage_taken) @@ -548,7 +737,7 @@ def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat if math.isfinite(profile.damage_taken)) if not math.isfinite(kill) and dps > 0.0: bonus = math.inf - fighters.append((dps, kill if math.isfinite(kill) else 0.0, bonus)) + fighters.append((present, dps, kill if math.isfinite(kill) else 0.0, bonus)) best_pack: list[int] = [] pack_danger = 0.0 for target in spawns: @@ -585,25 +774,47 @@ def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat def _apply_approach(self, result: MapResult, options: AnalysisOptions) -> None: """Find the least dangerous authored approach from an origin. - A bottleneck search walks backwards from the spot's maps and minimizes - the most dangerous map crossed, then the number of maps, then the path - names for determinism. A savebed or --approach-origin map is where the - character starts and is free; a surface tile is charged its own - danger because the character must cross it to use its entrance. + The search runs over (map, walkable component) nodes, so an exit only + counts from tiles the character can actually stand next to. It walks + backwards from the components holding the spot's spawns and minimizes + the most dangerous map crossed, then the number of nodes, then the + node names for determinism. Savebed and --approach-origin origins are + where the character starts and are free; a town-connected surface + component is charged its map's danger because the character must + cross it to use its entrance. """ if not options.model_approach: return - predecessors, surface, savebeds = self._links() + nodes = self._world().nodes explicit = { - key for key in map(self.resolve_map_key, options.approach_origins) + (key, label) + for key in map(self.resolve_map_key, options.approach_origins) if key is not None + for label in set(self._components(key).values()) } - free = explicit if options.approach_origins_only else savebeds | explicit - charged = frozenset() if options.approach_origins_only else surface - free - origins = free | charged + free = explicit if options.approach_origins_only else ( + self._savebed_nodes() | explicit) + + def is_origin(node: tuple[str, int]) -> bool: + return node in free or ( + not options.approach_origins_only and self._surface_origin(node)) + map_prefix = self.map_root.relative_to(self.root).as_posix() - members = {"/" + path.removeprefix(map_prefix + "/") for path in result.map_paths} - if members & origins: + + def key_of(path: str) -> str: + return "/" + path.removeprefix(map_prefix + "/") + + member_maps = {key_of(path) for path in result.map_paths} & set(nodes) + targets = { + (key_of(path), label) + for path, x, y in result.spawn_points + if key_of(path) in nodes + for label in self._land(key_of(path), x, y) + } or { + (key, label) for key in member_maps + for label in set(self._components(key).values()) + } + if any(is_origin(node) for node in targets): result.approach_status = "origin" return use_packs = options.max_health > 0.0 @@ -612,39 +823,44 @@ def metric(key: str) -> float: threat = self._approach_threat(key, options) return threat.pack_danger if use_packs else threat.spawn_danger - heap: list[tuple[float, int, tuple[str, ...], str]] = [ - (0.0, 0, (), member) for member in sorted(members)] - # A map popped again with fewer hops may still reach an origin within - # the limit, so prune by hops rather than settling maps once. - best_hops: dict[str, int] = {} + heap: list[tuple[float, int, tuple[tuple[str, int], ...], tuple[str, int]]] = [ + (0.0, 0, (), node) for node in sorted(targets)] + # A node popped again with fewer hops may still reach an origin within + # the limit, so prune by hops rather than settling nodes once. + best_hops: dict[tuple[str, int], int] = {} found = None while heap: bottleneck, hops, path, node = heapq.heappop(heap) - if node in origins: + if is_origin(node): found = bottleneck, path, node break if hops >= best_hops.get(node, math.inf): continue best_hops[node] = hops - for previous in predecessors.get(node, ()): - if previous in members or previous in path: + for previous in self._predecessors(node): + if previous in targets or previous in path: continue - if previous in origins: - cost = metric(previous) if previous in charged else 0.0 + if is_origin(previous): + cost = 0.0 if previous in free else metric(previous[0]) heapq.heappush(heap, (max(bottleneck, cost), hops, path, previous)) elif hops < options.max_approach_maps: + # Other parts of the spot's own maps are the spot's danger. + cost = 0.0 if previous[0] in member_maps else metric(previous[0]) heapq.heappush(heap, ( - max(bottleneck, metric(previous)), hops + 1, - path + (previous,), previous)) + max(bottleneck, cost), hops + 1, path + (previous,), previous)) if found is None: result.approach_status = "unreachable" - result.approach_danger_flags = ("approach_unknown",) + result.approach_unknown = True return bottleneck, path, origin = found - ordered = tuple(reversed(path)) - charged_maps = ((origin,) if origin in charged else ()) + ordered + ordered: list[str] = [] + for key, _label in reversed(path): + if key not in member_maps and (not ordered or ordered[-1] != key): + ordered.append(key) + charged_maps = ([origin[0]] if origin not in free else []) + [ + key for key in dict.fromkeys(ordered) if key != origin[0]] result.approach_status = "path" - result.approach_origin = map_prefix + origin + result.approach_origin = map_prefix + origin[0] result.approach_maps = tuple(map_prefix + key for key in ordered) result.approach_danger = bottleneck survival_level = max(options.player_level, options.character_level) diff --git a/farming_analyzer/cli.py b/farming_analyzer/cli.py index 7506e9e..7660cac 100644 --- a/farming_analyzer/cli.py +++ b/farming_analyzer/cli.py @@ -120,10 +120,12 @@ def build_parser() -> argparse.ArgumentParser: parser.add_argument("--exclude-region", action="append", default=[], metavar="NAME", help="exclude a region/island ID or name; may be repeated") parser.add_argument("--approach-origin", action="append", default=[], metavar="MAP", - help="extra map the character starts from, such as its savebed map; " - "may be repeated (surface world tiles and savebed maps are always origins)") + help="extra map the character starts from, such as its savebed map; any of " + "its walkable parts counts; may be repeated (savebeds and town-connected " + "surface tiles are also origins unless --approach-origins-only)") parser.add_argument("--max-approach-maps", type=int, default=16, - help="longest approach, in maps between origin and spot (default: 16)") + help="longest approach, in walkable map components between origin " + "and spot (default: 16)") parser.add_argument("--approach-origins-only", action="store_true", help="use only --approach-origin maps as origins, not surface tiles or savebeds") parser.add_argument("--unreachable-approach-safety", type=float, metavar="SAFETY", diff --git a/farming_analyzer/models.py b/farming_analyzer/models.py index 0b53837..aebcaee 100644 --- a/farming_analyzer/models.py +++ b/farming_analyzer/models.py @@ -150,6 +150,7 @@ class MapResult: approach_safety_score: float = 1.0 approach_worst_map: str = "" approach_danger_flags: tuple[str, ...] = () + approach_unknown: bool = False @dataclass(frozen=True) diff --git a/farming_analyzer/presentation.py b/farming_analyzer/presentation.py index d7b5b29..2e675ab 100644 --- a/farming_analyzer/presentation.py +++ b/farming_analyzer/presentation.py @@ -335,8 +335,8 @@ def render_text(results: list[MapResult], options: AnalysisOptions, limit: int, elif result.approach_status == "unreachable": capped = options.unreachable_approach_safety lines.append( - " approach: unknown (approach_unknown) — no authored exit path from an " - "origin within --max-approach-maps; " + " approach: unknown — no walkable authored path from a savebed, town " + "surface, or --approach-origin within --max-approach-maps; " + ("scored on the spot alone" if capped is None else f"safety capped at {capped * 100.0:.0f}%")) if options.character_speed > 0.0: @@ -394,8 +394,8 @@ def render_text(results: list[MapResult], options: AnalysisOptions, limit: int, "skill level is held constant. Spawn-point respawn is " "source-derived; map-reset-only monsters require the map to unload and are excluded unless " "--include-static is used. Safety is also capped by the least dangerous authored approach: " - "exits, tile paths, and walkable coordinate seams from a surface world tile, savebed map, or " - "--approach-origin, charging the worst aggressive pack on each map crossed (including " + "exits, tile paths, and walkable coordinate seams between walkable components, from a " + "savebed, a town-connected surface tile, or --approach-origin, charging the worst aggressive pack on each map crossed (including " "map-reset monsters and the entrance surface tile) by sequential exposure. Scripted teleports, keys, locked doors, and fleeing past monsters are " "not modeled; --ignore-approach scores the spot alone.", )) diff --git a/farming_analyzer/sources.py b/farming_analyzer/sources.py index c4db9e6..794a9b0 100644 --- a/farming_analyzer/sources.py +++ b/farming_analyzer/sources.py @@ -170,9 +170,13 @@ class TerrainMap: height: int terrain: dict[tuple[int, int], int] = field(default_factory=dict) blocked: set[tuple[int, int]] = field(default_factory=set) - # Map-root paths ("/region/map") named by authored exits and tile paths. - exits: set[str] = field(default_factory=set) - savebed: bool = False + # Placed exits as (x, y, destination map-root path or None, hp, sp, + # last_heal); header tile_path_N links by server direction index N - 1; + # the header entry point; and placed savebed positions. + exits: list[tuple[int, int, str | None, int, int, int]] = field(default_factory=list) + tile_paths: dict[int, str] = field(default_factory=dict) + enter: tuple[int, int] = (0, 0) + savebeds: list[tuple[int, int]] = field(default_factory=list) def walkable(self, x: int, y: int) -> bool: return ( diff --git a/farming_analyzer/tests/test_approach.py b/farming_analyzer/tests/test_approach.py index 999864c..f62f3db 100644 --- a/farming_analyzer/tests/test_approach.py +++ b/farming_analyzer/tests/test_approach.py @@ -78,20 +78,30 @@ def _map(name: str, region: str, *, spawns: tuple[tuple[str, int, int], ...] = (), - exits: tuple[tuple[str, int, int], ...] = (), extra: str = "", - header: tuple[str, ...] = ()) -> str: + exits: tuple[tuple, ...] = (), extra: str = "", + header: tuple[str, ...] = (), wall_x: int | None = None, + wall_y: int | None = None) -> str: + """Write a fully floored map; ``wall_x``/``wall_y`` leave a column/row bare. + + Exits are (target, x, y) or (target, x, y, hp, sp); without hp/sp the + test exit archetype lands on the target's (0, 0). + """ lines = [ "arch map", f"name {name}", f"width {SIZE}", f"height {SIZE}", "difficulty 10", f"region {region}", *header, "end", ] for y in range(SIZE): for x in range(SIZE): - lines += ["arch floor", f"x {x}", f"y {y}", "end"] + if x != wall_x and y != wall_y: + lines += ["arch floor", f"x {x}", f"y {y}", "end"] for monster, x, y in spawns: lines += ["arch spawn_point", f"x {x}", f"y {y}", f"arch {monster}", "type 83", "end", "end"] - for target, x, y in exits: - lines += ["arch exit", f"x {x}", f"y {y}", f"slaying {target}", "end"] + for target, x, y, *arrival in exits: + lines += ["arch exit", f"x {x}", f"y {y}", f"slaying {target}"] + if arrival: + lines += [f"hp {arrival[0]}", f"sp {arrival[1]}"] + lines += ["end"] return "\n".join(lines) + "\n" + extra @@ -110,10 +120,14 @@ def setUpClass(cls): (maps / "regions.reg").write_text( "region surface\nlongname Surface\nend\n" "region dungeon\nlongname Dungeon\nend\n") - # The surface world tile is an origin; it leads into both dungeons. + # The surface tile has an inn door, so it is a town origin; it leads + # into both dungeons. (maps / "world_0_0").write_text(_map( "Surface", "surface", - exits=(("danger/entry", 1, 1), ("/safe/entry", 4, 4)))) + exits=(("danger/entry", 1, 1), ("/safe/entry", 4, 4), ("inn", 0, 5)))) + (maps / "inn").write_text(_map( + "Inn", "surface", exits=(("world_0_0", 0, 0),), + extra="arch bed_save\nx 2\ny 2\nend\n")) rats = (("rat", 1, 1), ("rat", 4, 4)) for dungeon, x, entry_spawns in ( ("danger", 0, (("pudding", 2, 2), ("pudding", 3, 2), @@ -225,13 +239,14 @@ def test_unreachable_spot_keeps_its_own_safety(self): max_approach_maps=0)) danger = results[DANGER] self.assertEqual("unreachable", danger.approach_status) - self.assertEqual(("approach_unknown",), danger.approach_danger_flags) + self.assertTrue(danger.approach_unknown) + self.assertEqual((), danger.approach_danger_flags) self.assertEqual(danger.spot_safety_score, danger.safety_score) def test_disconnected_spot_is_flagged_and_optionally_capped(self): lost = self.results(self.options())[f"maps/lost/{LOST}"] self.assertEqual("unreachable", lost.approach_status) - self.assertEqual(("approach_unknown",), lost.approach_danger_flags) + self.assertTrue(lost.approach_unknown) self.assertEqual(lost.spot_safety_score, lost.safety_score) capped = self.results(self.options( unreachable_approach_safety=0.3))[f"maps/lost/{LOST}"] @@ -297,12 +312,39 @@ def write(path: str, **kwargs) -> None: "O": ("N",), "N": ("M",), "M": ("x2", "Y"), "x2": ("x1",), "x1": ("S",), "Y": ("S",), "S": ()}.items(): write(f"g/{source}", exits=tuple((target, 0, 0) for target in targets)) - # Origins: a charged surface tile and a free savebed map. - write("world_0_0", exits=(("t/via_world", 0, 0), ("t/only_world", 0, 0))) - write("t/bedroom", exits=(("via_world", 0, 0),), + # Town: the bedroom's door joins the surface tile world_0_0, which is + # therefore a charged origin; the savebed itself is free. + write("world_0_0", exits=( + ("t/via_world", 0, 0), ("t/only_world", 0, 1), ("t/bedroom", 0, 2), + ("t/hall", 0, 3), ("t/vault", 0, 4, 1, 1), ("t/split", 0, 5, -1, -1), + ("t/cave_7_0", 1, 0, 1, 1))) + write("t/bedroom", exits=(("via_world", 0, 0), ("../world_0_0", 1, 1)), extra="arch bed_save\nx 2\ny 2\nend\n") write("t/via_world") write("t/only_world") + # An islet: a surface tile with no seam to a town. Its exit leads to + # t/under, which is otherwise only reachable through the hall. + write("world_5_5", exits=(("t/under", 2, 2),)) + write("t/under", exits=(("../world_5_5", 1, 1),)) + write("t/hall", exits=(("under", 1, 1),)) + # A walled-off surface pocket on a town tile: only its west half is + # joined to the inn, the east half is entered from below. + write("world_3_0", wall_x=3, exits=(("t/inn2", 1, 1), ("t/pocket", 5, 5))) + write("t/inn2", exits=(("../world_3_0", 0, 0, 1, 1),), + extra="arch bed_save\nx 2\ny 2\nend\n") + write("t/pocket", exits=(("../world_3_0", 0, 0, 5, 5),)) + # A dungeon dead end: the vault's east half holds the only exit to + # the secret room, but arrivals land in its west half. + write("t/vault", wall_x=3, exits=(("secret", 5, 5),)) + write("t/secret", exits=(("vault", 0, 0, 5, 5),)) + # Arrival by enter_x/enter_y when the exit's hp/sp is -1. + write("t/split", wall_x=3, header=("enter_x 5", "enter_y 5"), + exits=(("east_spot", 5, 4), ("west_spot", 1, 1))) + write("t/east_spot") + write("t/west_spot") + # Seams join only the components that touch across the edge. + write("t/cave_7_0", wall_y=3) + write("t/cave_8_0", wall_y=3) # A bed_save carried in a container does not make a savebed map. write("t/storeroom", extra="arch wall\nx 1\ny 1\n" "arch bed_save\nend\nend\n") @@ -331,7 +373,12 @@ def tearDownClass(cls): cls.directory.cleanup() def predecessors(self, key: str) -> tuple[str, ...]: - return self.analyzer._links()[0].get(key, ()) + """Maps with a move into any walkable part of ``key``.""" + labels = set(self.analyzer._components(key).values()) + return tuple(sorted({ + source for label in labels + for source, _label in self.analyzer._predecessors((key, label)) + if source != key})) def approach(self, spot: str, threats: dict[str, float], **changes) -> MapResult: options = replace(self.template, **changes) @@ -380,21 +427,76 @@ def test_surface_entrances_are_charged_and_savebeds_are_free(self): "/t/only_world", threats, approach_origins=("/world_0_0",), approach_origins_only=True) self.assertEqual(0.0, explicit.approach_danger) - self.assertEqual( - "unreachable", - self.approach("/t/via_world", threats, approach_origins=("/g/O",), - approach_origins_only=True).approach_status) + unreachable = self.approach( + "/t/via_world", threats, approach_origins=("/g/O",), + approach_origins_only=True) + self.assertEqual("unreachable", unreachable.approach_status) + self.assertTrue(unreachable.approach_unknown) + + def test_islet_surface_exit_does_not_count(self): + self.assertFalse(self.analyzer._surface_origin(("/world_5_5", 0))) + self.assertTrue(self.analyzer._surface_origin(("/world_0_0", 0))) + under = self.approach("/t/under", {"/t/hall": 80.0}) + self.assertEqual("maps/world_0_0", under.approach_origin) + self.assertEqual(("maps/t/hall",), under.approach_maps) + self.assertEqual(80.0, under.approach_danger) + + def test_surface_pocket_entered_only_from_below_does_not_count(self): + labels = self.analyzer._components("/world_3_0") + west, east = labels[(1, 1)], labels[(5, 5)] + self.assertNotEqual(west, east) + self.assertTrue(self.analyzer._surface_origin(("/world_3_0", west))) + self.assertFalse(self.analyzer._surface_origin(("/world_3_0", east))) + pocket = self.approach("/t/pocket", {}) + self.assertEqual("unreachable", pocket.approach_status) + + def test_dungeon_dead_end_reachable_only_from_inside(self): + secret = self.approach("/t/secret", {}) + self.assertEqual("unreachable", secret.approach_status) + vault = self.analyzer._components("/t/vault") + self.assertIn(("/t/secret", 0), self.analyzer._predecessors( + ("/t/vault", vault[(5, 5)]))) + self.assertEqual((), tuple( + node for node in self.analyzer._predecessors(("/t/vault", vault[(5, 5)])) + if node[0] != "/t/secret")) + + def test_exit_arrival_uses_enter_x_and_enter_y(self): + east = self.approach("/t/east_spot", {"/t/split": 5.0}) + self.assertEqual("path", east.approach_status) + self.assertEqual(("maps/t/split",), east.approach_maps) + self.assertEqual("unreachable", self.approach("/t/west_spot", {}).approach_status) + + def test_seams_join_only_touching_components(self): + west, east = (self.analyzer._components(f"/t/cave_{x}_0") for x in (7, 8)) + north = (west[(1, 1)], "/t/cave_8_0", east[(1, 1)], True) + south = (west[(1, 5)], "/t/cave_8_0", east[(1, 5)], True) + edges = self.analyzer._out_edges("/t/cave_7_0") + self.assertIn(north, edges) + self.assertIn(south, edges) + self.assertNotIn((west[(1, 1)], "/t/cave_8_0", east[(1, 5)], True), edges) + self.assertEqual("path", self.approach("/t/cave_8_0", {}).approach_status) + south_spot = replace(self.template) + required = { + item.name: 0 for item in fields(MapResult) + if item.default is MISSING and item.default_factory is MISSING} + required.update(path="s", name="s", region="r") + result = MapResult(**required, map_paths=("maps/t/cave_8_0",), + spawn_points=(("maps/t/cave_8_0", 1, 5),)) + self.analyzer._apply_approach(result, south_spot) + self.assertEqual("unreachable", result.approach_status) def test_savebed_detection_ignores_carried_beds(self): - _predecessors, surface, savebeds = self.analyzer._links() - self.assertEqual(frozenset({"/world_0_0"}), surface) - self.assertEqual(frozenset({"/t/bedroom"}), savebeds) + self.assertEqual( + {"/t/bedroom", "/t/inn2"}, + {key for key, _label in self.analyzer._savebed_nodes()}) + self.assertEqual(frozenset({"/world_0_0", "/world_3_0", "/world_5_5"}), + self.analyzer._map_index()[1]) def test_exit_and_tile_path_resolution(self): self.assertEqual(("/t/sub/deep",), self.predecessors("/t/up")) self.assertEqual(("/t/sub/deep",), self.predecessors("/t/abs_target")) self.assertEqual(("/t/sub/deep",), self.predecessors("/t/tiled_east")) - self.assertNotIn("/t/sub/nowhere", self.analyzer._links()[0]) + self.assertNotIn("/t/sub/nowhere", self.analyzer._map_index()[0]) self.assertEqual("/t/up", FarmingAnalyzer._resolve_map_path( "/t/sub/deep", "../up")) self.assertEqual("/t/abs_target", FarmingAnalyzer._resolve_map_path( @@ -415,6 +517,14 @@ def test_server_tiling_links_diagonals_but_not_depths(self): self.assertIsNone(FarmingAnalyzer._tile_coordinates("ruins_0101")) self.assertIsNone(FarmingAnalyzer._tile_coordinates("cave_1")) + def test_sequential_exposure_counts_partial_aggression_once(self): + # Two certain monsters: the second is charged while the first dies. + self.assertEqual(30.0, FarmingAnalyzer._sequential_exposure( + [(1.0, 1.0, 10.0, 0.0), (1.0, 1.0, 10.0, 0.0)])) + # A monster that is aggressive half the time costs half as much. + self.assertEqual(5.0, FarmingAnalyzer._sequential_exposure( + [(0.5, 1.0, 10.0, 0.0)])) + def test_resolve_map_key_accepts_content_and_map_root_paths(self): for spelling in ("/t/up", "t/up", "maps/t/up", "/maps/t/up"): self.assertEqual("/t/up", self.analyzer.resolve_map_key(spelling)) @@ -470,6 +580,29 @@ def test_spot_behind_the_entrance_loses_safety_at_measured_health(self): for flag in ("fire×3", "acid×1", "poison×1"): self.assertIn(flag, spot.approach_danger_flags) + def test_circuits_no_longer_use_the_inside_only_lake_exit(self): + results = self.analyzer.scan(self.sera( + 244.0, path_pattern=r"underground_city_[0-4]_[0-4]$")) + city = [result for result in results + if "underground_city" in result.path and result.approach_status == "path"] + self.assertTrue(city) + # world_2_69's exit_green stands on a two-tile pocket reached only + # from inside the city, so it is not an origin. + self.assertFalse(any(result.approach_origin.endswith("/world_2_69") + for result in city)) + prefix = ("maps/shattered_islands/strakewood_island/underground_city/" + "underground_city_") + for members in (("2_2", "2_3", "3_1", "3_2"), ("0_4", "1_2", "1_3", "1_4")): + circuit = next( + result for result in results + if sorted(result.map_paths) == [prefix + member for member in members]) + self.assertTrue( + prefix + "0_0" in circuit.approach_maps or + prefix + "5_2_-1" in circuit.approach_maps, circuit.approach_maps) + self.assertLess(circuit.safety_score, 0.9) + labels = {flag.split("×")[0] for flag in circuit.approach_danger_flags} + self.assertLessEqual({"fire", "acid", "poison"}, labels) + if __name__ == "__main__": unittest.main() From 50fd6fbc87c19b91032655be98f59fb54b2c2cf7 Mon Sep 17 00:00:00 2001 From: Zoey Rose Date: Sat, 14 Nov 2026 21:39:09 -0600 Subject: [PATCH 4/5] fix(farming-analyzer): follow paired exits and charge crossed components - Record exit sub_type and follow auto-linked exits (no path, hp/sp -1, non-zero sub_type) to every same-sub_type exit within five tiles, across tiled neighbours, as exit_find() does. - Charge an approach node only for the spawns standing in its walkable component, cached per (map, component); a spawn with no walkable tile nearby stays charged everywhere. - Group surface components once with union-find over seams in either direction, so town connectivity no longer depends on visit order. - Document that the content-gated Underground City test is skipped without a content checkout and so does not run in CI. Co-Authored-By: Claude Opus 5.5 --- farming_analyzer/README.md | 22 ++- farming_analyzer/analyzer.py | 196 +++++++++++++++--------- farming_analyzer/sources.py | 7 +- farming_analyzer/tests/test_approach.py | 43 +++++- 4 files changed, 182 insertions(+), 86 deletions(-) diff --git a/farming_analyzer/README.md b/farming_analyzer/README.md index 974efcd..334d839 100644 --- a/farming_analyzer/README.md +++ b/farming_analyzer/README.md @@ -250,8 +250,10 @@ the maps the search reaches and cached. A character can move: the map root when it starts with `/`. Stairs without `slaying` use `last_heal` (9 up, 10 down, or a horizontal direction) to pick the tiled map and keep their own position; an exit without `slaying` but with - `hp`/`sp` moves within its own map. Paired `sub_type` exits, scripts, keys - and locks are not followed; doors count as open; + `hp`/`sp` moves within its own map. An auto-linked exit (no path, `hp`/`sp` + of -1, non-zero `sub_type`) may lead to any exit of the same `sub_type` + within five tiles, including on tiled neighbours, as `exit_find()` does. + Scripts, keys and locks are not followed; doors count as open; - across a tiled map edge or corner from an edge tile to the walkable tile beyond it. Tiling follows `derive_map_filename_tiles()` in classic `server/src/server/map.c`: header `tile_path_N` (direction `N - 1`) wins, @@ -268,8 +270,8 @@ Origins are components: map is an error. `--approach-origins-only` uses only these, for example "I start from my savebed"; - town-connected surface components (charged). Surface components (depth-0 - `world_X_Y` tiles) are grouped by walking seams between surface tiles - only. A group is town-connected when one of its components holds a + `world_X_Y` tiles) are grouped once, with union-find over seams between + surface tiles in either direction. A group is town-connected when one of its components holds a savebed or is joined by an exit to or from a savebed map, such as an inn door. Islets, ship-only islands, and surface pockets entered only from below are therefore not origins. A charged surface origin costs its map's @@ -286,7 +288,9 @@ with fewer crossings, so a long safe path cannot block a shorter one that fits the limit. Other components of the spot's own maps are free and are not listed, because the spot's safety already covers them. -Each crossed map is charged for its worst aggressive encounter, reusing the +Each crossed component is charged for its map's worst aggressive encounter +among the spawns standing in that component (a spawn with no walkable tile +nearby is charged in every component), reusing the spot's monster, damage, hit-chance, kill-time and protection model. Spawns whose own detection radius reaches one pull point fight together. That pack is charged by sequential exposure: every living monster keeps attacking until @@ -303,7 +307,7 @@ aggressive spawn is charged instead, matching the relative per-monster safety model. Directly placed monsters count even without `--include-static`, because they are present when a traveller loads the map. Passive monsters are skipped. AoE is not credited on the approach. -Each map's threat is cached for the current options. +Threats are cached per map and component for the current options. The approach safety uses the same reference as the spot: `max_health / approach_danger` with `--max-health`, otherwise the least dangerous eligible @@ -591,5 +595,7 @@ circuit, and the two-tile Forgotten Graveyard circuit. A synthetic world checks that a safe circuit behind a dangerous entry map loses safety and reports approach flags, while the same circuit behind a safe entry is unchanged, and covers exits, tile paths, tiling, origins, and the bounded search. When the -content checkout is present, a Sera-like level 36 profile checks the -Underground City entrance's slime cluster. +content checkout is present, `UndergroundCityEntranceTest` checks a +Sera-like level 36 profile against the Underground City entrance's slime +cluster and approach routes. It is skipped without that checkout, so CI, +which checks out only this repository, does not run it. diff --git a/farming_analyzer/analyzer.py b/farming_analyzer/analyzer.py index ddc80b2..362d733 100644 --- a/farming_analyzer/analyzer.py +++ b/farming_analyzer/analyzer.py @@ -86,11 +86,11 @@ def __init__(self, root: Path = ROOT, server_root: Path = SERVER_ROOT): self._component_cache: dict[str, dict[tuple[int, int], int]] = {} self._edge_cache: dict[str, tuple[tuple[int, str, int, bool], ...]] = {} self._predecessor_cache: dict[tuple[str, int], tuple[tuple[str, int], ...]] = {} - self._surface_region: dict[tuple[str, int], int] = {} - self._region_has_town: list[bool] = [] - self._town_nodes: frozenset[tuple[str, int]] | None = None + self._surface_groups: dict[tuple[str, int], tuple[str, int]] = {} + self._town_groups: frozenset[tuple[str, int]] | None = None self._threat_options: AnalysisOptions | None = None - self._threat_cache: dict[str, ApproachThreat] = {} + self._threat_cache: dict[tuple[str, int | None], ApproachThreat] = {} + self._spawn_cache: dict[str, list[SpawnProfile]] = {} self._npc_factions = self._load_npc_factions() self.rejections: list[tuple[str, str]] = [] @@ -379,7 +379,8 @@ def _world(self): node.exits.append(( x, y, self._resolve_map_path(key, slaying), _integer(attrs.get("hp")), _integer(attrs.get("sp")), - _integer(attrs.get("last_heal")))) + _integer(attrs.get("last_heal")), + _integer(attrs.get("sub_type")))) elif parent is None and obj_type == SAVEBED_TYPE: node.savebeds.append((x, y)) # Doors, exits, and teleporters are traversable server-side. @@ -496,11 +497,16 @@ def _land(self, key: str, x: int, y: int) -> tuple[int, ...]: labels[(x + dx, y + dy)] for dx in (-1, 0, 1) for dy in (-1, 0, 1) if (x + dx, y + dy) in labels})) - def _exit_destination(self, key: str, exit_object: tuple[int, int, str | None, int, int, int] + def _exit_destination(self, key: str, + exit_object: tuple[int, int, str | None, int, int, int, int] ) -> tuple[str, int, int] | None: - """Resolve a placed exit like exit.c insert_map_func() and object_enter_map().""" + """Resolve a placed exit like exit.c insert_map_func() and object_enter_map(). + + Paired exits (no path, a non-zero ``sub_type``) have several possible + destinations and are handled by _paired_exits(). + """ nodes = self._world().nodes - x, y, destination, hp, sp, last_heal = exit_object + x, y, destination, hp, sp, last_heal, _sub_type = exit_object if destination is None: tiles = self._tiles(key) if 0 < last_heal <= len(TILE_DIRECTIONS) + 2 and last_heal - 1 in tiles: @@ -513,6 +519,44 @@ def _exit_destination(self, key: str, exit_object: tuple[int, int, str | None, i return None return destination, hp, sp + def _paired_exits(self, key: str, + exit_object: tuple[int, int, str | None, int, int, int, int] + ) -> tuple[tuple[str, int, int], ...]: + """Return the exits an auto-linked exit can teleport to. + + Mirrors exit_find() in classic types/exit.c: an exit without a path + and with a non-zero ``sub_type`` picks a random exit of the same + ``sub_type`` within five tiles, across tiled neighbours via + get_map_from_coord(), and the character lands on that exit's tile. + """ + x, y, destination, hp, sp, last_heal, sub_type = exit_object + if destination is not None or not sub_type or ( + self._exit_destination(key, exit_object) is not None): + return () + nodes = self._world().nodes + node = nodes[key] + tiles = self._tiles(key) + found = [] + for dx in range(-5, 6): + for dy in range(-5, 6): + if not dx and not dy: + continue + tx_, ty_ = x + dx, y + dy + tx = (tx_ >= node.width) - (tx_ < 0) + ty = (ty_ >= node.height) - (ty_ < 0) + target_key = key + if tx or ty: + target_key = tiles.get(TILE_INDEX[(tx, ty)]) + if target_key is None: + continue + target = nodes[target_key] + tx_ = tx_ - node.width if tx > 0 else target.width + tx_ if tx < 0 else tx_ + ty_ = ty_ - node.height if ty > 0 else target.height + ty_ if ty < 0 else ty_ + for other in nodes[target_key].exits: + if other[0] == tx_ and other[1] == ty_ and other[6] == sub_type: + found.append((target_key, tx_, ty_)) + return tuple(found) + def _out_edges(self, key: str) -> tuple[tuple[int, str, int, bool], ...]: """Return (component, target map, target component, is_seam) moves. @@ -530,13 +574,13 @@ def _out_edges(self, key: str) -> tuple[tuple[int, str, int, bool], ...]: edges: set[tuple[int, str, int, bool]] = set() for exit_object in node.exits: resolved = self._exit_destination(key, exit_object) - if resolved is None: - continue - destination, hp, sp = resolved - for source in self._land(key, exit_object[0], exit_object[1]): - for arrival in self._land(destination, hp, sp): - if (destination, arrival) != (key, source): - edges.add((source, destination, arrival, False)) + destinations = ((resolved,) if resolved is not None else + self._paired_exits(key, exit_object)) + for destination, hp, sp in destinations: + for source in self._land(key, exit_object[0], exit_object[1]): + for arrival in self._land(destination, hp, sp): + if (destination, arrival) != (key, source): + edges.add((source, destination, arrival, False)) tiles = self._tiles(key) for (x, y), label in labels.items(): if 0 < x < node.width - 1 and 0 < y < node.height - 1: @@ -572,6 +616,8 @@ def _map_index(self) -> tuple[dict[str, frozenset[str]], frozenset[str]]: resolved = self._exit_destination(key, exit_object) if resolved is not None: incoming[resolved[0]].add(key) + for target, _x, _y in self._paired_exits(key, exit_object): + incoming[target].add(key) for index, target in self._tiles(key).items(): if index < len(TILE_DIRECTIONS): incoming[target].add(key) @@ -611,15 +657,12 @@ def _surface_origin(self, node: tuple[str, int]) -> bool: A town is a surface component that holds a savebed or is joined by an exit to or from a map that holds one, for example an inn door. Surface - components are grouped by walking seams between surface tiles only, so - islets, ship-only islands, and surface pockets entered only from - below do not count. + components are grouped once, with union-find over seams between + surface tiles taken in either direction, so islets, ship-only islands, + and surface pockets entered only from below do not count. """ - _incoming, surface = self._map_index() - if node[0] not in surface: - return False - if self._town_nodes is None: - incoming, _surface = self._map_index() + if self._town_groups is None: + incoming, surface = self._map_index() savebed_maps = {key for key, value in self._world().nodes.items() if value.savebeds} towns = set(self._savebed_nodes()) @@ -630,28 +673,29 @@ def _surface_origin(self, node: tuple[str, int]) -> bool: for label, target, _target_label, _seam in self._out_edges(source): if target == key: towns.add((source, label)) - self._town_nodes = frozenset(towns) - region = self._surface_region.get(node) - if region is None: - region = len(self._region_has_town) - self._region_has_town.append(False) - self._surface_region[node] = region - frontier = [node] - while frontier: - current = frontier.pop() - if current in self._town_nodes: - self._region_has_town[region] = True - for label, target, target_label, seam in self._out_edges(current[0]): - if not seam or label != current[1] or target not in surface: - continue - neighbour = (target, target_label) - known = self._surface_region.get(neighbour) - if known is None: - self._surface_region[neighbour] = region - frontier.append(neighbour) - elif known != region and self._region_has_town[known]: - self._region_has_town[region] = True - return self._region_has_town[region] + parent: dict[tuple[str, int], tuple[str, int]] = {} + + def find(item: tuple[str, int]) -> tuple[str, int]: + parent.setdefault(item, item) + while parent[item] != item: + parent[item] = parent[parent[item]] + item = parent[item] + return item + + for key in sorted(surface): + for label in set(self._components(key).values()): + find((key, label)) + for label, target, target_label, seam in self._out_edges(key): + if seam and target in surface: + left, right = find((key, label)), find((target, target_label)) + if left != right: + parent[max(left, right)] = min(left, right) + self._surface_groups = {item: find(item) for item in parent} + self._town_groups = frozenset( + self._surface_groups[item] for item in towns + if item in self._surface_groups) + group = self._surface_groups.get(node) + return group is not None and group in self._town_groups def resolve_map_key(self, path: str) -> str | None: """Resolve a user-supplied map path to an authored map, or None. @@ -692,9 +736,14 @@ def _sequential_exposure(fighters: list[tuple[float, float, float, float]]) -> f total += sum(item[3] for item in fighters if item[1] <= 0.0) return total - def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat: + def _approach_threat(self, key: str, options: AnalysisOptions, + component: int | None = None) -> ApproachThreat: """Measure the worst aggressive encounter met while crossing one map. + With ``component``, only spawns standing in (or, when blocked, next + to) that walkable component are charged; a spawn with no walkable + tile nearby is charged everywhere, conservatively. + Every hostile spawn point and directly placed monster is included, whatever --include-static says, because a traveller meets them when the map is loaded. Monster damage, hit chance and kill time reuse the @@ -705,15 +754,22 @@ def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat if self._threat_options != options: self._threat_options = options self._threat_cache = {} - cached = self._threat_cache.get(key) + self._spawn_cache = {} + cached = self._threat_cache.get((key, component)) if cached is not None: return cached threat = ApproachThreat(0.0, 0.0, 0, ()) - path = self.map_root / key.lstrip("/") - parsed = parse_blocks(path) if path.is_file() else {"header": None} - if parsed.get("header") is not None: - spawns, _competitors = self._collect_spawns( - parsed, options, include_static=True) + spawns = self._spawn_cache.get(key) + if spawns is None: + path = self.map_root / key.lstrip("/") + parsed = parse_blocks(path) if path.is_file() else {"header": None} + spawns = [] if parsed.get("header") is None else self._collect_spawns( + parsed, options, include_static=True)[0] + self._spawn_cache[key] = spawns + if component is not None and key in self._world().nodes: + spawns = [spawn for spawn in spawns + if component in (self._land(key, spawn.x, spawn.y) or (component,))] + if spawns: fighters: list[tuple[float, float, float, float]] = [] weights: list[float] = [] for spawn in spawns: @@ -768,7 +824,7 @@ def _approach_threat(self, key: str, options: AnalysisOptions) -> ApproachThreat pack_danger, max(weights, default=0.0), max(levels, default=0), tuple(f"{flag}×{amount:g}" for flag, amount in sorted( flag_counts.items(), key=lambda item: (-item[1], item[0])))) - self._threat_cache[key] = threat + self._threat_cache[(key, component)] = threat return threat def _apply_approach(self, result: MapResult, options: AnalysisOptions) -> None: @@ -819,8 +875,8 @@ def key_of(path: str) -> str: return use_packs = options.max_health > 0.0 - def metric(key: str) -> float: - threat = self._approach_threat(key, options) + def metric(node: tuple[str, int]) -> float: + threat = self._approach_threat(node[0], options, node[1]) return threat.pack_danger if use_packs else threat.spawn_danger heap: list[tuple[float, int, tuple[tuple[str, int], ...], tuple[str, int]]] = [ @@ -841,11 +897,11 @@ def metric(key: str) -> float: if previous in targets or previous in path: continue if is_origin(previous): - cost = 0.0 if previous in free else metric(previous[0]) + cost = 0.0 if previous in free else metric(previous) heapq.heappush(heap, (max(bottleneck, cost), hops, path, previous)) elif hops < options.max_approach_maps: # Other parts of the spot's own maps are the spot's danger. - cost = 0.0 if previous[0] in member_maps else metric(previous[0]) + cost = 0.0 if previous[0] in member_maps else metric(previous) heapq.heappush(heap, ( max(bottleneck, cost), hops + 1, path + (previous,), previous)) if found is None: @@ -857,33 +913,31 @@ def metric(key: str) -> float: for key, _label in reversed(path): if key not in member_maps and (not ordered or ordered[-1] != key): ordered.append(key) - charged_maps = ([origin[0]] if origin not in free else []) + [ - key for key in dict.fromkeys(ordered) if key != origin[0]] + charged = ([origin] if origin not in free else []) + [ + node for node in dict.fromkeys(reversed(path)) if node[0] not in member_maps] result.approach_status = "path" result.approach_origin = map_prefix + origin[0] result.approach_maps = tuple(map_prefix + key for key in ordered) result.approach_danger = bottleneck survival_level = max(options.player_level, options.character_level) + allowed = survival_level + options.max_level_gap flags: Counter[str] = Counter() worst = None - for key in charged_maps: - threat = self._approach_threat(key, options) - if worst is None or metric(key) > metric(worst): - worst = key + level_flags: dict[str, None] = {} + for node in charged: + threat = self._approach_threat(node[0], options, node[1]) + if worst is None or metric(node) > metric(worst): + worst = node for rendered in threat.flags: label, _separator, amount = rendered.rpartition("×") flags[label] += _number(amount, 1.0) + if threat.max_level > allowed: + level_flags[f"{Path(node[0]).name} L{threat.max_level} > allowed L{allowed}"] = None if worst is not None and metric(worst) > 0.0: - result.approach_worst_map = map_prefix + worst - level_flags = tuple( - f"{Path(key).name} L{self._approach_threat(key, options).max_level} > " - f"allowed L{survival_level + options.max_level_gap}" - for key in charged_maps - if self._approach_threat(key, options).max_level > - survival_level + options.max_level_gap) + result.approach_worst_map = map_prefix + worst[0] result.approach_danger_flags = tuple( f"{flag}×{amount:g}" for flag, amount in sorted( - flags.items(), key=lambda item: (-item[1], item[0]))) + level_flags + flags.items(), key=lambda item: (-item[1], item[0]))) + tuple(level_flags) def _maneuverability( self, relpath: str, diff --git a/farming_analyzer/sources.py b/farming_analyzer/sources.py index 794a9b0..c6b91b1 100644 --- a/farming_analyzer/sources.py +++ b/farming_analyzer/sources.py @@ -171,9 +171,10 @@ class TerrainMap: terrain: dict[tuple[int, int], int] = field(default_factory=dict) blocked: set[tuple[int, int]] = field(default_factory=set) # Placed exits as (x, y, destination map-root path or None, hp, sp, - # last_heal); header tile_path_N links by server direction index N - 1; - # the header entry point; and placed savebed positions. - exits: list[tuple[int, int, str | None, int, int, int]] = field(default_factory=list) + # last_heal, sub_type); header tile_path_N links by server direction + # index N - 1; the header entry point; and placed savebed positions. + exits: list[tuple[int, int, str | None, int, int, int, int]] = field( + default_factory=list) tile_paths: dict[int, str] = field(default_factory=dict) enter: tuple[int, int] = (0, 0) savebeds: list[tuple[int, int]] = field(default_factory=list) diff --git a/farming_analyzer/tests/test_approach.py b/farming_analyzer/tests/test_approach.py index f62f3db..2f4ecb9 100644 --- a/farming_analyzer/tests/test_approach.py +++ b/farming_analyzer/tests/test_approach.py @@ -317,7 +317,7 @@ def write(path: str, **kwargs) -> None: write("world_0_0", exits=( ("t/via_world", 0, 0), ("t/only_world", 0, 1), ("t/bedroom", 0, 2), ("t/hall", 0, 3), ("t/vault", 0, 4, 1, 1), ("t/split", 0, 5, -1, -1), - ("t/cave_7_0", 1, 0, 1, 1))) + ("t/cave_7_0", 1, 0, 1, 1), ("t/paired", 1, 2, 1, 1))) write("t/bedroom", exits=(("via_world", 0, 0), ("../world_0_0", 1, 1)), extra="arch bed_save\nx 2\ny 2\nend\n") write("t/via_world") @@ -342,6 +342,19 @@ def write(path: str, **kwargs) -> None: exits=(("east_spot", 5, 4), ("west_spot", 1, 1))) write("t/east_spot") write("t/west_spot") + # Auto-linked exits: no path, hp/sp -1 and a shared sub_type. The pair + # on t/paired joins its two halves; another pairs across a tile seam. + def paired(x: int, y: int, sub_type: int) -> str: + return (f"arch exit\nx {x}\ny {y}\nsub_type {sub_type}\n" + "hp -1\nsp -1\nend\n") + + write("t/paired", wall_x=3, exits=(("beyond", 5, 5),), + extra=paired(1, 1, 7) + paired(5, 1, 7) + paired(1, 4, 8)) + write("t/beyond") + write("t/pair_0_0", extra=paired(5, 2, 3)) + write("t/pair_1_0", extra=paired(1, 2, 3) + paired(2, 2, 4)) + # Only the half a traveller stands in is charged. + write("t/halves", wall_x=3, spawns=(("pudding", 5, 1), ("pudding", 5, 2))) # Seams join only the components that touch across the edge. write("t/cave_7_0", wall_y=3) write("t/cave_8_0", wall_y=3) @@ -388,7 +401,7 @@ def approach(self, spot: str, threats: dict[str, float], **changes) -> MapResult required.update(path=spot, name=spot, region="r") result = MapResult(**required, map_paths=(f"maps{spot}",)) - def threat(key, _options): + def threat(key, _options, _component=None): danger = threats.get(key, 0.0) return ApproachThreat(danger, danger, 1, ("fire×1",) if danger else ()) @@ -485,6 +498,28 @@ def test_seams_join_only_touching_components(self): self.analyzer._apply_approach(result, south_spot) self.assertEqual("unreachable", result.approach_status) + def test_paired_exits_link_same_sub_type_within_five_tiles(self): + labels = self.analyzer._components("/t/paired") + west, east = labels[(1, 1)], labels[(5, 1)] + edges = self.analyzer._out_edges("/t/paired") + self.assertIn((west, "/t/paired", east, False), edges) + self.assertIn((east, "/t/paired", west, False), edges) + self.assertEqual("path", self.approach("/t/beyond", {}).approach_status) + self.assertEqual( + (("/t/pair_1_0", 1, 2),), + self.analyzer._paired_exits( + "/t/pair_0_0", self.analyzer._world().nodes["/t/pair_0_0"].exits[0])) + + def test_threat_charges_only_the_crossed_component(self): + labels = self.analyzer._components("/t/halves") + options = self.template + west = self.analyzer._approach_threat("/t/halves", options, labels[(1, 1)]) + east = self.analyzer._approach_threat("/t/halves", options, labels[(5, 1)]) + whole = self.analyzer._approach_threat("/t/halves", options) + self.assertEqual(0.0, west.pack_danger) + self.assertGreater(east.pack_danger, 0.0) + self.assertEqual(whole.pack_danger, east.pack_danger) + def test_savebed_detection_ignores_carried_beds(self): self.assertEqual( {"/t/bedroom", "/t/inn2"}, @@ -577,8 +612,8 @@ def test_spot_behind_the_entrance_loses_safety_at_measured_health(self): "underground_city_0_0", spot.approach_maps) self.assertEqual(1.0, spot.spot_safety_score) self.assertLess(spot.safety_score, 0.9) - for flag in ("fire×3", "acid×1", "poison×1"): - self.assertIn(flag, spot.approach_danger_flags) + labels = {flag.split("×")[0] for flag in spot.approach_danger_flags} + self.assertLessEqual({"fire", "acid", "poison"}, labels) def test_circuits_no_longer_use_the_inside_only_lake_exit(self): results = self.analyzer.scan(self.sera( From 450bf75c091082cf8315e13c5e961d24aa72fd2b Mon Sep 17 00:00:00 2001 From: Zoey Rose Date: Sat, 14 Nov 2026 21:49:51 -0600 Subject: [PATCH 5/5] fix(farming-analyzer): charge spawns whose aggro reaches a crossed component Filtering an approach component's threat to spawns standing in it dropped casters, archers, flyers and swimmers behind rock, tree or water lines that block walking but not engagement. Charge every spawn whose own detection radius reaches a tile of the component by Chebyshev distance, alongside spawns standing in it, so only genuinely distant components stay separate. Test a caster behind a walk-blocking line and a pocket beyond its radius. Co-Authored-By: Claude Opus 5.5 --- farming_analyzer/README.md | 5 ++- farming_analyzer/analyzer.py | 21 +++++++--- farming_analyzer/tests/test_approach.py | 52 +++++++++++++++++++------ 3 files changed, 60 insertions(+), 18 deletions(-) diff --git a/farming_analyzer/README.md b/farming_analyzer/README.md index 334d839..cc8b918 100644 --- a/farming_analyzer/README.md +++ b/farming_analyzer/README.md @@ -289,8 +289,9 @@ fits the limit. Other components of the spot's own maps are free and are not listed, because the spot's safety already covers them. Each crossed component is charged for its map's worst aggressive encounter -among the spawns standing in that component (a spawn with no walkable tile -nearby is charged in every component), reusing the +among the spawns standing in that component or whose own detection radius +reaches one of its tiles by Chebyshev distance, so casters, archers, flyers +and swimmers behind rock, tree or water lines still count, reusing the spot's monster, damage, hit-chance, kill-time and protection model. Spawns whose own detection radius reaches one pull point fight together. That pack is charged by sequential exposure: every living monster keeps attacking until diff --git a/farming_analyzer/analyzer.py b/farming_analyzer/analyzer.py index 362d733..37d5272 100644 --- a/farming_analyzer/analyzer.py +++ b/farming_analyzer/analyzer.py @@ -740,9 +740,11 @@ def _approach_threat(self, key: str, options: AnalysisOptions, component: int | None = None) -> ApproachThreat: """Measure the worst aggressive encounter met while crossing one map. - With ``component``, only spawns standing in (or, when blocked, next - to) that walkable component are charged; a spawn with no walkable - tile nearby is charged everywhere, conservatively. + With ``component``, a spawn is charged when it stands in (or, when + blocked, next to) that walkable component, or when its own detection + radius reaches a tile of the component by Chebyshev distance. Casters, + archers, flyers and swimmers can engage across rock, tree or water + lines that only block walking; components far apart stay distinct. Every hostile spawn point and directly placed monster is included, whatever --include-static says, because a traveller meets them when @@ -767,8 +769,17 @@ def _approach_threat(self, key: str, options: AnalysisOptions, parsed, options, include_static=True)[0] self._spawn_cache[key] = spawns if component is not None and key in self._world().nodes: - spawns = [spawn for spawn in spawns - if component in (self._land(key, spawn.x, spawn.y) or (component,))] + tiles = [tile for tile, label in self._components(key).items() + if label == component] + + def reaches(spawn: SpawnProfile) -> bool: + if component in self._land(key, spawn.x, spawn.y): + return True + radius = spawn.weighted("aggro_radius") + return any(max(abs(spawn.x - x), abs(spawn.y - y)) <= radius + for x, y in tiles) + + spawns = [spawn for spawn in spawns if reaches(spawn)] if spawns: fighters: list[tuple[float, float, float, float]] = [] weights: list[float] = [] diff --git a/farming_analyzer/tests/test_approach.py b/farming_analyzer/tests/test_approach.py index 2f4ecb9..0fff2c4 100644 --- a/farming_analyzer/tests/test_approach.py +++ b/farming_analyzer/tests/test_approach.py @@ -68,6 +68,21 @@ attack_acid 50 exp 2000 end +Object caster +name dragon caster +type 80 +monster 1 +level 40 +maxhp 30 +dam 20 +wc 30 +ac 10 +speed 0.5 +weapon_speed 1 +item_power 3 +can_cast_spell 1 +exp 2000 +end """ SIZE = 6 @@ -353,8 +368,18 @@ def paired(x: int, y: int, sub_type: int) -> str: write("t/beyond") write("t/pair_0_0", extra=paired(5, 2, 3)) write("t/pair_1_0", extra=paired(1, 2, 3) + paired(2, 2, 4)) - # Only the half a traveller stands in is charged. - write("t/halves", wall_x=3, spawns=(("pudding", 5, 1), ("pudding", 5, 2))) + # Walk-blocking lines at x=1 and x=10 split t/wide into three parts. + # A caster at (3, 2) with detection radius 3 reaches across the first + # line but not the far part. + wide = ["arch map", "name wide", "width 16", f"height {SIZE}", + "difficulty 10", "region r", "end"] + for y in range(SIZE): + for x in range(16): + if x not in (1, 10): + wide += ["arch floor", f"x {x}", f"y {y}", "end"] + wide += ["arch spawn_point", "x 3", "y 2", "arch caster", "type 83", + "end", "end"] + (maps / "t" / "wide").write_text("\n".join(wide) + "\n") # Seams join only the components that touch across the edge. write("t/cave_7_0", wall_y=3) write("t/cave_8_0", wall_y=3) @@ -510,15 +535,20 @@ def test_paired_exits_link_same_sub_type_within_five_tiles(self): self.analyzer._paired_exits( "/t/pair_0_0", self.analyzer._world().nodes["/t/pair_0_0"].exits[0])) - def test_threat_charges_only_the_crossed_component(self): - labels = self.analyzer._components("/t/halves") - options = self.template - west = self.analyzer._approach_threat("/t/halves", options, labels[(1, 1)]) - east = self.analyzer._approach_threat("/t/halves", options, labels[(5, 1)]) - whole = self.analyzer._approach_threat("/t/halves", options) - self.assertEqual(0.0, west.pack_danger) - self.assertGreater(east.pack_danger, 0.0) - self.assertEqual(whole.pack_danger, east.pack_danger) + def test_threat_charges_spawns_whose_radius_reaches_the_component(self): + labels = self.analyzer._components("/t/wide") + west, middle, east = labels[(0, 0)], labels[(4, 4)], labels[(12, 0)] + self.assertEqual(3, len({west, middle, east})) + threat = self.analyzer._approach_threat + behind_line = threat("/t/wide", self.template, west) + own = threat("/t/wide", self.template, middle) + far = threat("/t/wide", self.template, east) + self.assertGreater(behind_line.pack_danger, 0.0) + self.assertEqual(own.pack_danger, behind_line.pack_danger) + self.assertIn("caster×1", behind_line.flags) + self.assertEqual(0.0, far.pack_danger) + self.assertEqual(own.pack_danger, + threat("/t/wide", self.template).pack_danger) def test_savebed_detection_ignores_carried_beds(self): self.assertEqual(