diff --git a/.github/workflows/native-build.yml b/.github/workflows/native-build.yml new file mode 100644 index 0000000..bc28c19 --- /dev/null +++ b/.github/workflows/native-build.yml @@ -0,0 +1,81 @@ +name: native-build + +on: + workflow_dispatch: + pull_request: + branches: [main] + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: native-build-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + name: ${{ matrix.platform.name }} / Python ${{ matrix.python }} + runs-on: ${{ matrix.platform.runner }} + strategy: + fail-fast: false + matrix: + python: ['3.12'] + platform: + - {name: linux-x64, runner: ubuntu-22.04} + - {name: windows-x64, runner: windows-latest} + - {name: macos-arm64, runner: macos-15} + - {name: macos-x64, runner: macos-15-intel} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - uses: dtolnay/rust-toolchain@stable + - name: Install import dependency + run: python -m pip install "numpy>=1.26,<3" + - name: Build engine, feature kernels and parallel slots + shell: python + run: | + import os + import subprocess + import sys + + env = dict(os.environ, PYO3_PYTHON=sys.executable) + for args in ( + ['-p', 'arkguard-python'], + ['--manifest-path', 'arkguardrl_core/native/Cargo.toml'], + ['--manifest-path', 'benchmarks/native_slots/Cargo.toml'], + ): + subprocess.run(['cargo', 'build', '--release', '--locked', *args], env=env, check=True) + - name: Collect and import all modules + shell: python + run: | + import importlib + import pathlib + import shutil + import sys + import sysconfig + + artifacts = pathlib.Path('artifacts') + artifacts.mkdir() + prefix = '' if sys.platform == 'win32' else 'lib' + suffix = {'win32': '.dll', 'darwin': '.dylib'}.get(sys.platform, '.so') + for directory, name in ( + ('target/release', '_native'), + ('arkguardrl_core/native/target/release', '_rust_routes'), + ('benchmarks/native_slots/target/release', '_native_slots'), + ): + source = pathlib.Path(directory) / f'{prefix}{name}{suffix}' + shutil.copy2(source, artifacts / f'{name}{sysconfig.get_config_var("EXT_SUFFIX")}') + sys.path.insert(0, str(artifacts.resolve())) + for name in ('_native', '_rust_routes', '_native_slots'): + module = importlib.import_module(name) + assert pathlib.Path(module.__file__).resolve().parent == artifacts.resolve() + print(f'Imported {module.__file__}') + - uses: actions/upload-artifact@v4 + with: + name: native-py${{ matrix.python }}-${{ matrix.platform.name }} + path: artifacts/* + if-no-files-found: error diff --git a/AGENTS.md b/AGENTS.md index 804e991..ef2f78f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,10 +1,13 @@ # Scope Core owns environment/runtime performance; ArkGuardRL owns strategy research. +Maintain only Desperation mode (`mode_single_abyss`). Scope migration work, +new content and acceptance to this mode; other modes are not maintenance targets. +Do not add standard-mode-only content such as enemy-debuff tactical cards. Keep code and documentation small. Do not add source manifests, binary fingerprints, release checklists or source-bound checkpoint gates. Preserve model/input compatibility, memory bounds and valid rollout semantics. Do not run games or training merely to clean up files or edit documentation. -`main` is frozen at `6af66bf`. Keep multi-env scheduling experiments on -`codex/multi-env-worker`; do not advance or merge into main without user direction. +Multi-environment execution and vectorized runtime work are part of Core and +may be included in PRs targeting main. Continue vectorization work in Core. diff --git a/Cargo.lock b/Cargo.lock index db893b7..e217215 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -16,6 +16,8 @@ dependencies = [ "arkguard-engine", "pyo3", "pyo3-build-config", + "serde", + "serde_json", ] [[package]] @@ -192,6 +194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", + "serde_derive", ] [[package]] diff --git a/README.md b/README.md index c825e4b..ced6d17 100644 --- a/README.md +++ b/README.md @@ -3,30 +3,34 @@ [![Python](https://img.shields.io/badge/python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org/) [![Rust](https://img.shields.io/badge/rust-PyO3%200.27-dea584?style=flat-square&logo=rust&logoColor=white)](https://www.rust-lang.org/) [![Gymnasium](https://img.shields.io/badge/gymnasium-%E2%89%A51.1-4B8BBE?style=flat-square)](https://gymnasium.farama.org/) -[![Engine](https://img.shields.io/badge/engine-app%200.3.1-lightgrey?style=flat-square)](https://github.com/sganggs/Stronghold-Protocol) +[![Engine](https://img.shields.io/badge/engine-app%200.3.3-lightgrey?style=flat-square)](https://github.com/sganggs/Stronghold-Protocol) [![License](https://img.shields.io/badge/license-GPL--3.0--or--later-blue?style=flat-square)](LICENSE) [![Status](https://img.shields.io/badge/status-pre--release-orange?style=flat-square)](docs/NATIVE-033.md) [Stronghold Protocol](https://github.com/sganggs/Stronghold-Protocol) 的 Gymnasium 环境。 -## 安装 +当前维护与原生迁移范围仅限绝境(`mode_single_abyss`),进度见 [迁移文档](docs/NATIVE-033.md)。 -Python 3.10+、Node 22+ -```sh -python -m pip install -e '.[gym]' -``` +## 安装与使用 -引擎与数据单独准备:[Stronghold-Protocol](https://github.com/sganggs/Stronghold-Protocol) -`c9d804f470b8d7422ae04eb66faf671cef21ad52`(app 0.3.1) +Python 3.10+、Rust stable,以及另行准备的 Stronghold Protocol 0.3.3 数据目录。 本仓库不含游戏素材、数据、权重或轨迹。 -## 使用 +```sh +python -m pip install -e '.[gym]' +PYO3_PYTHON="$(command -v python)" cargo build --release --locked -p arkguard-python +``` ```python import gymnasium as gym -import arkguardrl_core.gym_env # 注册 ArkGuardRL-v0 - -with gym.make("ArkGuardRL-v0", engine_root="/path/to/engine") as env: +import arkguardrl_core.native_gym + +with gym.make( + "ArkGuardRL-v1", + data_root="/path/to/0.3.3/data", + core="band_sarkazb", # band_amiya / band_sarkazb / band_chen / band_sciurus + native_library="target/release/lib_native.dylib", +) as env: obs, info = env.reset(seed=42) done = False while not done: @@ -35,6 +39,8 @@ with gym.make("ArkGuardRL-v0", engine_root="/path/to/engine") as env: done = terminated or truncated ``` +Linux 动态库后缀为 `.so`,CI 提供 Linux x64、Windows x64、macOS Intel/Apple Silicon 的 CPython 3.12 原生模块,详见[构建说明](benchmarks/README.md#跨平台构建)。原生运行时读取数据目录,核心由构造参数指定。`banned` 接受禁用干员 ID,`tick_budget` 控制每次战斗续跑的帧数。 + 观测是 NumPy `Dict`,动作是**当前候选行索引**: | 字段 | 形状 / 类型 | 含义 | @@ -44,7 +50,7 @@ with gym.make("ArkGuardRL-v0", engine_root="/path/to/engine") as env: | `schedules` / `experts` | `(max_candidates,) int64` | 候选分组 | | `action_mask` | `(max_candidates,) int8` | 有效候选行 | -- 候选由公开信息构造;引擎仍可能拒绝合法候选,结果见 `info["accepted"]`。 +- 候选由公开参数域构造,游戏规则可能拒绝提交的动作,结果见 `info["accepted"]`。 - padding 或越界索引抛 `InvalidAction`,不替换动作、不推进游戏。 - 候选容量默认 16384,超限报错,不裁剪动作域。 - 自然结束为 `terminated`;`max_decisions` / `max_advances` / `wall_seconds` 耗尽为 @@ -55,23 +61,15 @@ with gym.make("ArkGuardRL-v0", engine_root="/path/to/engine") as env: 通用 `check_env()` 的无掩码随机动作会选中 padding,请按掩码采样。 - 难度与预算只能在构造时配置,`reset(options=...)` 不接受其他选项。 -## 并行与测量 - -支持 `SyncVectorEnv` / `AsyncVectorEnv`。Async 使用 `spawn` 和共享内存,入口需要 -`if __name__ == "__main__"`。每个 env 独占一个 Node 进程,默认填充观测约 2.98 MB/env。 +## 并行与回放 -```sh -python benchmarks/gym_env.py --engine-root /path/to/engine \ - --vector async --envs 4 --steps 256 --repeats 3 --out artifacts/gym-async-4.json -``` +Gym 支持 `SyncVectorEnv`/`AsyncVectorEnv`,每个环境拥有独立原生会话;Async 使用 `spawn` 时需要 `if __name__ == "__main__"` 入口。Rust slots 支持 1–64 个环境、显式局部 reset 和部分槽位推进。 -## 测试 +公开地图与当前模板路线通过 `env.unwrapped.public_spatial()` 读取,增量入口为 `public_spatial_update(key)`。真实记录回归、渲染回放和吞吐命令见[性能与验收说明](benchmarks/README.md)。 -原生集成测试需显式提供引擎路径,会实际运行对局: +## Node 兼容入口 -```sh -ARKGUARD_ENGINE_ROOT=/path/to/engine python -m unittest discover -s tests -p test_gym_env.py -v -``` +旧研究调用可通过 `import arkguardrl_core.gym_env` 注册 `ArkGuardRL-v0`,构造时传入 `engine_root`。该路径使用 Node 22+ 及对应的 0.3.1 引擎/数据;观测与候选布局见上表。 ## 文档 diff --git a/arkguardrl/candidates.py b/arkguardrl/candidates.py index 42a7f2c..16049e5 100644 --- a/arkguardrl/candidates.py +++ b/arkguardrl/candidates.py @@ -187,9 +187,12 @@ def record(self, state, action, *, result): if state["phase"] == "PREP" and action["t"] != "g.choice": self.prep_used += 1 - def snapshot(self, state): + def _check(self, state): if self.progress is None or self.progress["observation_id"] != fingerprint(state): raise ValueError("Initialize/update history with the real environment result before encoding") + + def snapshot(self, state): + self._check(state) key = self._sync(state) return {"schema": self.schema, "progress": deepcopy(self.progress), "used": self.prep_used, "limit": PREP_ACTION_LIMIT, "blocked_count": len(self.attempts.get(key, ()))} @@ -210,13 +213,17 @@ class Decision: history_json: bytes | None = field(default=None, repr=False, compare=False) -def build_decision(state, catalog, history): +def build_decision(state, catalog, history, *, encoder=None, candidate_encoder=None, state_copy=None): locations, occupied, cells = public_context(state, catalog) own, public = state["own"], state["public"] if not isinstance(history, DecisionHistory): raise ValueError("Explicit native DecisionHistory required") - blocked, actions, seen = history.blocked(state), [], set() + blocked = history.blocked(state) if candidate_encoder is None else () + actions, seen, prepared = [], set(), None def add(action): + if candidate_encoder is not None: + actions.append(action) + return key = action_id(action) if key in blocked or key in seen: return @@ -284,16 +291,23 @@ def add(action): add({"t": "g.freeze"}) if shop["level"] < shop["maxLevel"] and own["funds"] >= shop["upgradePrice"]: add({"t": "g.levelUp"}) - from arkguardrl_core.env_actions import piece_actions - for action in piece_actions(state, catalog, (locations, occupied, cells), recovery=recovery): - add(action) + from arkguardrl_core.env_actions import piece_actions, piece_inputs + if candidate_encoder is not None: + prepared = piece_inputs(state, catalog, (locations, occupied, cells), recovery=recovery) + else: + for action in piece_actions(state, catalog, (locations, occupied, cells), recovery=recovery): + add(action) else: raise CandidateBlocked("Unsupported actionable native phase") - if not actions: + if not actions and (candidate_encoder is None or prepared is None): raise CandidateBlocked("History/public domain exhausted; no fallback wait or forced Ready") snapshot = history.snapshot(state) - observation, features, schedules, experts = encode_decision(state, actions, catalog, snapshot) + if candidate_encoder is not None: + actions, observation, features, schedules, experts = candidate_encoder( + state, actions, catalog, snapshot, prepared) + else: + observation, features, schedules, experts = (encoder or encode_decision)(state, actions, catalog, snapshot) # Retain the exact history used for the feature tensors, independently of # subsequent history advancement. Bytes cannot alias mutable progress. - return Decision(deepcopy(state), observation, features, tuple(actions), schedules, experts, + return Decision((state_copy or deepcopy)(state), observation, features, tuple(actions), schedules, experts, state["personalEnded"], history_json=canonical(snapshot)) diff --git a/arkguardrl/catalog.py b/arkguardrl/catalog.py index 1b9356b..aaf61dc 100644 --- a/arkguardrl/catalog.py +++ b/arkguardrl/catalog.py @@ -51,11 +51,22 @@ def unique(pairs): raise ValueError("Public catalog/session data identity mismatch") if set(loaded) != {"bands", "chess", "items", "tokens", "config", "bonds", "garrisons", "enemies", "choices", "effects"}: raise ValueError("Missing explicit public catalog files") + self._initialize(loaded) + + @classmethod + def from_native(cls, native_catalog): + """Use the engine-owned external definitions, without a source-checkout gate.""" + obj = cls.__new__(cls) + obj.data_sha256 = None + obj._initialize(json.loads(native_catalog.public_tables())) + return obj + + def _initialize(self, loaded): self._data = loaded # The learning API exposes small public projections, not every artwork, # description, skill implementation or future-wave table in the dataset. fields = ("id", "chessId", "tokenId", "bandId", "baseId", "goldenId", "tier", "isGolden", - "position", "placeOnRanged", "isDiy", "itemType", "kind", "rangedTilesOnly", + "position", "placeOnRanged", "isDiy", "diyFor", "itemType", "kind", "rangedTilesOnly", "ownerRange", "ownerRangeOutside", "rangeGrid", "upgradeNum", "bonds") self._views = {} for kind, table in (("chess", "chess"), ("item", "items"), ("token", "tokens"), ("band", "bands")): @@ -135,8 +146,8 @@ def _record(self, kind, identifier): row = self._views.get(kind, {}).get(identifier) if not isinstance(row, dict): raise UnsupportedPublicState(f"Unknown public {kind} identity: {identifier!r}") - if kind == "chess" and row.get("isDiy"): - raise UnsupportedPublicState("Custom DIY records require a separate catalog contract") + if kind == "chess" and row.get("isDiy") and row.get("diyFor") not in self._data.get("diy", {}): + raise UnsupportedPublicState("DIY identity has no resolved operator configuration") return row def validate_identity(self, kind, identifier): @@ -246,7 +257,9 @@ def validate_state(self, state): or public.get("modeId") not in self._data["config"]["modes"] or public.get("modeId") != "mode_single_" + public["difficulty"].lower()): raise UnsupportedPublicState("Plugins/custom modes are outside this vanilla catalog") - for name in ("diy", "loadout", "ops"): + if own.get("diy") != self._data.get("diy", {}): + raise UnsupportedPublicState("DIY configuration differs from the resolved public catalog") + for name in ("loadout", "ops"): if own.get(name) != {}: raise UnsupportedPublicState(f"Nondefault or unknown {name} is unsupported") if own.get("standIns") != []: diff --git a/arkguardrl/decision_session.py b/arkguardrl/decision_session.py index 97bc8d4..dfc3b02 100644 --- a/arkguardrl/decision_session.py +++ b/arkguardrl/decision_session.py @@ -32,7 +32,8 @@ def reset(self, **kwargs): def decision(self): if self.result is None: raise RuntimeError("Reset before constructing a decision") - return build_decision(self.result.observation, self.catalog, self.history) + return build_decision(self.result.observation, self.catalog, self.history, + encoder=getattr(self.environment, 'numeric_encoder', None)) def step(self, action): if self.result is None: @@ -50,4 +51,9 @@ def step(self, action): def observation_features(self): if self.result is None: raise RuntimeError("Reset before encoding a successor") + encoder = getattr(self.environment, 'numeric_encoder', None) + if encoder is not None: + state = self.result.observation + self.catalog.validate_state(state) + return encoder(state, (), self.catalog, self.history.snapshot(state))[0] return encode_observation(self.result.observation, self.catalog, self.history) diff --git a/arkguardrl_core/env_actions.py b/arkguardrl_core/env_actions.py index 2da50c8..2ab0384 100644 --- a/arkguardrl_core/env_actions.py +++ b/arkguardrl_core/env_actions.py @@ -5,11 +5,15 @@ def piece_actions(state, catalog, context, *, recovery): + return kernel().prep_piece_actions(*piece_inputs(state, catalog, context, recovery=recovery)) + + +def piece_inputs(state, catalog, context, *, recovery): from arkguardrl.candidates import empty_deployment_allowed own = state['own'] if recovery and own['canReady']: - return [] + return ([], 0, own['deployCount'] >= own['deployCap'], recovery, True) locations, _, cells = context terrain = {'all': 0, 'melee': 0, 'high': 0} for (row, col), kind in cells.items(): @@ -40,5 +44,5 @@ def piece_actions(state, catalog, context, *, recovery): pieces.append((uid, {'board': 0, 'hand': 1, 'temp': 2}[area], kind, cell, direction, mask, [item['uid'] for item in piece['items']])) empty_hand = sum(1 << i for i, piece in enumerate(own['hand']) if piece is None) - return kernel().prep_piece_actions(pieces, empty_hand, + return (pieces, empty_hand, own['deployCount'] >= own['deployCap'], recovery, own['canReady']) diff --git a/arkguardrl_core/gym_env.py b/arkguardrl_core/gym_env.py index 452dd72..e6e5bef 100644 --- a/arkguardrl_core/gym_env.py +++ b/arkguardrl_core/gym_env.py @@ -50,10 +50,27 @@ def __init__(self, engine_root, *, expected_data_sha256=None, difficulty="ABYSS" self.catalog = None # Gym inputs do not consume route geometry. Keep explicit geometry() # available on demand without projecting paths on every decision. - self._pool = RouteSessionPool(inline_geometry=False) + self._pool = self._make_pool() self._session = self._decision = self._result = None self._done = True + def _make_pool(self): + return RouteSessionPool(inline_geometry=False) + + def _load_catalog(self): + return PublicCatalog(self.engine_root, self.expected_data_sha256) + + def _make_environment(self): + return RouteEnv(self.engine_root, session_pool=self._pool, deadline=float("inf"), + expected_data_sha256=self.catalog.data_sha256, timeout=self.timeout, + max_decisions=self.max_decisions, max_advances=self.max_advances) + + def _make_decision_session(self, environment): + return DecisionSession(environment, self.catalog) + + def _make_reward(self): + return NativeProgressCore() + def _close_episode(self, error=False): if self._session is not None: session, self._session = self._session, None @@ -69,18 +86,16 @@ def reset(self, *, seed=None, options=None): started = time.perf_counter() try: if self.catalog is None: - self.catalog = PublicCatalog(self.engine_root, self.expected_data_sha256) + self.catalog = self._load_catalog() # Gym seeds include zero and arbitrarily large integers. The engine # accepts nonzero uint32; derive it from Gym's reproducible RNG stream. self._engine_seed = int(self.np_random.integers(1, 2**32)) - environment = RouteEnv(self.engine_root, session_pool=self._pool, deadline=float("inf"), - expected_data_sha256=self.catalog.data_sha256, timeout=self.timeout, - max_decisions=self.max_decisions, max_advances=self.max_advances) - self._session = DecisionSession(environment, self.catalog) + environment = self._make_environment() + self._session = self._make_decision_session(environment) self._session.__enter__() self._result = self._session.reset(seed=self._engine_seed, difficulty=self.difficulty) engine_seconds = time.perf_counter()-started - self._reward = NativeProgressCore() + self._reward = self._make_reward() self._reward.reset(self._result.observation) observation, info = self._observe(self._result.reason) if self.profile: @@ -107,7 +122,7 @@ def _observe(self, reason): self._decision, count = None, 0 features = self._session.observation_features() observation = { - "observation": np.asarray(features, dtype=np.float32), + "observation": np.array(features, dtype=np.float32, copy=True), "candidates": np.zeros((self.max_candidates, ACTION_DIM), dtype=np.float32), "schedules": np.zeros(self.max_candidates, dtype=np.int64), "experts": np.zeros(self.max_candidates, dtype=np.int64), @@ -135,7 +150,9 @@ def step(self, action): try: before = self._result.observation started = time.perf_counter() - self._result = self._session.step(self._decision.actions[int(action)]) + indexed = getattr(self._session, 'step_index', None) + self._result = (indexed(int(action)) if indexed is not None + else self._session.step(self._decision.actions[int(action)])) engine_seconds = time.perf_counter()-started started = time.perf_counter() reward = self._reward.step(before, self._result.observation) diff --git a/arkguardrl_core/native/Cargo.lock b/arkguardrl_core/native/Cargo.lock index 6203841..64723b0 100644 --- a/arkguardrl_core/native/Cargo.lock +++ b/arkguardrl_core/native/Cargo.lock @@ -8,6 +8,7 @@ version = "0.1.0" dependencies = [ "numpy", "pyo3", + "pyo3-build-config", ] [[package]] diff --git a/arkguardrl_core/native/Cargo.toml b/arkguardrl_core/native/Cargo.toml index 37f50cc..9fe7f78 100644 --- a/arkguardrl_core/native/Cargo.toml +++ b/arkguardrl_core/native/Cargo.toml @@ -1,3 +1,5 @@ +[workspace] + [package] name = "arkguardrl-route-kernels" version = "0.1.0" @@ -14,6 +16,9 @@ crate-type = ["cdylib"] pyo3 = { version = "=0.27.2", features = ["extension-module"] } numpy = "=0.27.1" +[build-dependencies] +pyo3-build-config = "=0.27.2" + [profile.release] lto = "thin" codegen-units = 1 diff --git a/arkguardrl_core/native/build.rs b/arkguardrl_core/native/build.rs new file mode 100644 index 0000000..dace4a9 --- /dev/null +++ b/arkguardrl_core/native/build.rs @@ -0,0 +1,3 @@ +fn main() { + pyo3_build_config::add_extension_module_link_args(); +} diff --git a/arkguardrl_core/native/src/prep.rs b/arkguardrl_core/native/src/prep.rs index 51d1120..42c12a0 100644 --- a/arkguardrl_core/native/src/prep.rs +++ b/arkguardrl_core/native/src/prep.rs @@ -6,86 +6,9 @@ use pyo3::{ types::{PyDict, PyList}, }; -// UID, area (board/hand/temp), kind (chess/token/equip/magic), cell, -// direction, permitted terrain/token cells, equipped item UIDs. -type Piece = (u64, u8, u8, i8, i8, u64, Vec); -const MASK: u64 = (1 << 36) - 1; - -enum Action { - Sell(u64), - Destroy(u64), - Hand(u64, usize), - Board(u64, usize, usize), - Equip(u64, u64, Option), - Art(u64, usize, usize), -} - -fn enumerate( - pieces: &[Piece], - empty_hand: u16, - full: bool, - recovery: bool, - ready: bool, -) -> Vec { - let mut actions = Vec::new(); - if recovery && ready { - return actions; - } - let chess_cells = pieces - .iter() - .filter(|p| p.1 == 0 && p.2 == 0) - .fold(0_u64, |mask, p| mask | (1 << p.3)); - for &(uid, area, kind, cell, direction, allowed, _) in pieces { - if kind == 0 { - actions.push(Action::Sell(uid)); - } else if kind >= 2 && (!recovery || area == 2) { - actions.push(Action::Destroy(uid)); - } - if recovery && area != 2 { - continue; - } - if area != 1 { - for slot in 0..10 { - if !recovery || empty_hand & (1 << slot) != 0 { - actions.push(Action::Hand(uid, slot)); - } - } - } - if kind <= 1 { - for target in 0..36 { - if allowed & (1 << target) == 0 { - continue; - } - if area != 0 && kind == 0 && full && chess_cells & (1 << target) == 0 { - continue; - } - for facing in 0..4 { - if area == 0 && target == cell as usize && facing == direction as usize { - continue; - } - actions.push(Action::Board(uid, target, facing)); - } - } - } else if kind == 2 { - for target in pieces.iter().filter(|p| p.2 == 0) { - actions.push(Action::Equip(uid, target.0, None)); - if target.6.len() >= 2 { - for &old in &target.6 { - actions.push(Action::Equip(uid, target.0, Some(old))); - } - } - } - } else { - // Magic targets the whole protocol field, including nondeployable cells. - for target in 0..36 { - for facing in 0..4 { - actions.push(Action::Art(uid, target, facing)); - } - } - } - } - actions -} +#[path = "prep_domain.rs"] +mod domain; +use domain::{enumerate, Action, Piece, MASK}; #[pyfunction] pub fn prep_piece_actions<'py>( diff --git a/arkguardrl_core/native/src/prep_domain.rs b/arkguardrl_core/native/src/prep_domain.rs new file mode 100644 index 0000000..4be9eab --- /dev/null +++ b/arkguardrl_core/native/src/prep_domain.rs @@ -0,0 +1,81 @@ +// Public PREP intent domain shared by the Python kernel and native session. +// UID, area (board/hand/temp), kind (chess/token/equip/magic), cell, +// direction, permitted terrain/token cells, equipped item UIDs. +pub type Piece = (u64, u8, u8, i8, i8, u64, Vec); +pub const MASK: u64 = (1 << 36) - 1; + +pub enum Action { + Sell(u64), + Destroy(u64), + Hand(u64, usize), + Board(u64, usize, usize), + Equip(u64, u64, Option), + Art(u64, usize, usize), +} + +pub fn enumerate( + pieces: &[Piece], + empty_hand: u16, + full: bool, + recovery: bool, + ready: bool, +) -> Vec { + let mut actions = Vec::new(); + if recovery && ready { + return actions; + } + let chess_cells = pieces + .iter() + .filter(|p| p.1 == 0 && p.2 == 0) + .fold(0_u64, |mask, p| mask | (1 << p.3)); + for &(uid, area, kind, cell, direction, allowed, _) in pieces { + if kind == 0 { + actions.push(Action::Sell(uid)); + } else if kind >= 2 && (!recovery || area == 2) { + actions.push(Action::Destroy(uid)); + } + if recovery && area != 2 { + continue; + } + if area != 1 { + for slot in 0..10 { + if !recovery || empty_hand & (1 << slot) != 0 { + actions.push(Action::Hand(uid, slot)); + } + } + } + if kind <= 1 { + for target in 0..36 { + if allowed & (1 << target) == 0 { + continue; + } + if area != 0 && kind == 0 && full && chess_cells & (1 << target) == 0 { + continue; + } + for facing in 0..4 { + if area == 0 && target == cell as usize && facing == direction as usize { + continue; + } + actions.push(Action::Board(uid, target, facing)); + } + } + } else if kind == 2 { + for target in pieces.iter().filter(|p| p.2 == 0) { + actions.push(Action::Equip(uid, target.0, None)); + if target.6.len() >= 2 { + for &old in &target.6 { + actions.push(Action::Equip(uid, target.0, Some(old))); + } + } + } + } else { + // Magic targets the whole protocol field, including nondeployable cells. + for target in 0..36 { + for facing in 0..4 { + actions.push(Action::Art(uid, target, facing)); + } + } + } + } + actions +} diff --git a/arkguardrl_core/native_env.py b/arkguardrl_core/native_env.py new file mode 100644 index 0000000..a121894 --- /dev/null +++ b/arkguardrl_core/native_env.py @@ -0,0 +1,157 @@ +"""In-process Rust decisions using the existing public feature/history contract. + +Transport validates and owns each decoded observation. Internal progress consumes +that owned snapshot. Public transitions are decoded independently from the same +transport JSON, preserving caller isolation without Python recursive deepcopy. +""" +from copy import deepcopy +import importlib.machinery +import importlib.util +import json +from pathlib import Path + +from arkguardrl.contracts import action_id +from arkguardrl.environment import Transition +from arkguardrl.feedback import PublicProgress +from arkguardrl.observation import validate_state + + +def load_native(library=None): + if library is None: + try: + from . import _native + return _native + except ImportError as exc: + raise RuntimeError("Build crates/python and pass its dynamic library as native_library") from exc + path = str(Path(library).resolve(strict=True)) + loader = importlib.machinery.ExtensionFileLoader("_native", path) + spec = importlib.util.spec_from_file_location("_native", path, loader=loader) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class NativePool: + """Own definitions once. Episodes share definitions, never mutable game state.""" + def __init__(self, data_root, core, banned, library, diy=None): + native = load_native(library) + self.catalog = native.NativeCatalog(str(Path(data_root).resolve()), 64 << 20) + if diy: + self.catalog = self.catalog.with_diy(json.dumps(diy)) + self.session = native.NativeSolo(self.catalog, core, list(banned)) + + def close(self): + self.session.close() + + +class NativeDecisionEnv: + def __init__(self, pool, *, max_decisions, max_advances, tick_budget, policy_catalog=None): + self.session = pool.session + self.numeric_encoder = None + if policy_catalog is not None: + from .native_policy import metadata + if getattr(pool, '_policy_catalog', None) is not policy_catalog: + self.session.configure_policy(metadata(policy_catalog)) + pool._policy_catalog = policy_catalog + self._policy_catalog = policy_catalog + self.numeric_encoder = self._encode_numeric + self.max_decisions, self.max_advances = max_decisions, max_advances + self.tick_budget = tick_budget + self._state = None + self._raw = None + self._progress = PublicProgress() + self._decisions = self._advances = 0 + self._reason = None + self._closed = False + + def __enter__(self): + return self + + def public_spatial(self): + """Public map/template geometry bound to the current decision revision.""" + if self._closed or self._state is None: + raise RuntimeError("Reset required") + return json.loads(self.session.public_spatial(self._state['revision'])) + + def public_spatial_update(self, geometry_key=None): + """Return (key, optional geometry JSON, current dynamic JSON). + + Reuse keys only with the same immutable catalog. The consumer owns its + decoded geometry and must validate each dynamic packet's revision. + """ + if self._closed or self._state is None: + raise RuntimeError("Reset required") + incremental = getattr(self.session, 'public_spatial_update', None) + if incremental is None: + return None, self.session.public_spatial(self._state['revision']), '{}' + return incremental(geometry_key, self._state['revision']) + + def _encode_numeric(self, state, actions, catalog, history): + from .native_policy import encode + if catalog is not self._policy_catalog or state != self._state: + raise ValueError('Numeric encoding requires the current public snapshot and catalog') + return encode(self.session, state, actions, history) + + def _observe(self): + # Validate once at the transport boundary; progress consumes the owned mapping. + raw = self.session.observation() + state = json.loads(raw) + validate_state(state) + self._state, self._raw = state, raw + return state + + def _track(self, state, *, action=None, reply=None): + """Progress consumes this validated transport snapshot without copying it.""" + return self._progress._observe_validated(state, action=action, reply=reply) + + def _result(self, accepted=None, execution=None, aid=None): + # A second decode of the same transport bytes is an exact, isolated copy; + # it is far cheaper than recursively copying the parsed public state. + observation = json.loads(self._raw) + return Transition(observation, observation["personalEnded"], + bool(self._reason and not observation["personalEnded"]), self._reason, + accepted=accepted, action_id=aid, execution=execution, + progress=self._progress.snapshot(self._state)) + + def reset(self, *, seed, difficulty="ABYSS"): + if difficulty != "ABYSS" or self._state is not None or self._closed: + raise ValueError("Reset once per live Desperation decision session") + self.session.reset(seed) + self._track(self._observe()) + return self._result() + + def step(self, action): + if self._closed or self._state is None or self._reason or self._state["personalEnded"]: + raise RuntimeError("Reset required") + # Keep the immediate action receipt distinct from automatic combat. + intent = deepcopy(action) + receipt = json.loads(self.session.step(json.dumps(intent, allow_nan=False), 0)) + accepted = receipt["accepted"] + reply = {"accepted": accepted, "result": {"ok": accepted}} + if not accepted: + reply["result"]["error"] = receipt["rejection"] + execution = self._track(self._observe(), action=intent, reply=reply) + self._decisions += 1 + while receipt["budgetExhausted"]: + if self._advances >= self.max_advances: + # A half-finished battle has no action-value bootstrap state. + # Fail the call instead of returning a spurious terminal/truncation. + self.close(error=True) + raise RuntimeError("Combat budget exhausted before a decision boundary") + receipt = json.loads(self.session.advance(self.tick_budget)) + self._advances += 1 + if not receipt["budgetExhausted"]: + self._track(self._observe()) + if not self._state["personalEnded"]: + if self._decisions >= self.max_decisions: + self._reason = "decision-budget" + elif self._advances >= self.max_advances: + self._reason = "advance-budget" + return self._result(accepted, execution, action_id(intent)) + + def close(self, *, error=False): + self.session.close() + self._closed = True + + def __exit__(self, *_): + self.close() diff --git a/arkguardrl_core/native_gym.py b/arkguardrl_core/native_gym.py new file mode 100644 index 0000000..d98d839 --- /dev/null +++ b/arkguardrl_core/native_gym.py @@ -0,0 +1,72 @@ +"""Desperation-only Gym adapter for the in-process Rust simulator.""" +import gymnasium as gym +from arkguardrl.catalog import PublicCatalog +from .gym_env import ArkGuardEnv +from .native_env import NativePool, NativeDecisionEnv + + +class ArkGuardNativeEnv(ArkGuardEnv): + """Existing dynamic feature shapes and candidate-mask semantics, native execution. + + core selects band_amiya, band_sarkazb, band_chen, or band_sciurus. + No core-selection actions are added. native_library is a development-build + path; omit it when arkguardrl_core._native is installed. + """ + def __init__(self, data_root, *, core, banned=(), native_library=None, diy=None, + tick_budget=4096, numeric_observations=True, native_ledger=True, **kwargs): + if type(tick_budget) is not int or not 1 <= tick_budget <= 108000: + raise ValueError("tick_budget must be an integer in 1..108000") + if kwargs.get("difficulty", "ABYSS") != "ABYSS": + raise ValueError("Only Desperation (ABYSS) is maintained") + if kwargs.get("expected_data_sha256") is not None: + raise ValueError("Native data is configured by directory, without a source identity gate") + if type(numeric_observations) is not bool: + raise ValueError('numeric_observations must be boolean') + if type(native_ledger) is not bool: + raise ValueError('native_ledger must be boolean') + self.native_ledger = native_ledger + self.numeric_observations = numeric_observations + self.core, self.banned = core, tuple(banned) + self.diy = diy + self.native_library, self.tick_budget = native_library, tick_budget + super().__init__(data_root, **kwargs) + + def _make_pool(self): + return NativePool(self.engine_root, self.core, self.banned, self.native_library, self.diy) + + def _load_catalog(self): + return PublicCatalog.from_native(self._pool.catalog) + + def _make_environment(self): + environment = NativeDecisionEnv + if self.native_ledger: + from .native_ledger import NativeLedgerEnv + environment = NativeLedgerEnv + return environment(self._pool, max_decisions=self.max_decisions, + max_advances=self.max_advances, tick_budget=self.tick_budget, + policy_catalog=self.catalog if self.numeric_observations else None) + + def _make_decision_session(self, environment): + if self.native_ledger: + from .native_ledger import NativeLedgerSession + return NativeLedgerSession(environment, self.catalog) + return super()._make_decision_session(environment) + + def public_spatial(self): + if self._session is None: + raise gym.error.ResetNeeded("Reset before reading public spatial information") + return self._session.environment.public_spatial() + + def public_spatial_update(self, geometry_key=None): + if self._session is None: + raise gym.error.ResetNeeded("Reset before reading public spatial information") + return self._session.environment.public_spatial_update(geometry_key) + + def _make_reward(self): + if self.native_ledger: + from .native_ledger import NativeLedgerReward + return NativeLedgerReward(self._session.environment) + return super()._make_reward() + + +gym.register("ArkGuardRL-v1", entry_point="arkguardrl_core.native_gym:ArkGuardNativeEnv") diff --git a/arkguardrl_core/native_ledger.py b/arkguardrl_core/native_ledger.py new file mode 100644 index 0000000..5ce011a --- /dev/null +++ b/arkguardrl_core/native_ledger.py @@ -0,0 +1,198 @@ +"""Gym bridge to the public progress, history and reward owned by NativeSolo.""" +from copy import deepcopy +import json +from numbers import Integral +from uuid import uuid4 + +from arkguardrl.candidates import CandidateBlocked, Decision, DecisionHistory, build_decision +from arkguardrl.contracts import fingerprint, canonical +from arkguardrl.decision_session import DecisionSession +from arkguardrl.environment import Transition +from .native_env import NativeDecisionEnv + + +class NativeLedgerHistory(DecisionHistory): + def __init__(self, environment): + self.environment = environment + + @property + def progress(self): + return self.environment._ledger['history']['progress'] + + @property + def prep_used(self): + return self.environment._ledger['history']['used'] + + def _check(self, state): + if fingerprint(state) != self.progress['observation_id']: + raise ValueError('Initialize/update history with the real environment result before encoding') + + def blocked(self, state): + self._check(state) + return frozenset(self.environment._ledger['blocked']) + + def snapshot(self, state): + self._check(state) + return deepcopy(self.environment._ledger['history']) + + +class NativeLedgerSession(DecisionSession): + def __init__(self, environment, catalog): + self.environment, self.catalog = environment, catalog + self.history = NativeLedgerHistory(environment) + self.result = self._decision = None + + def reset(self, **kwargs): + if self.result is not None: + raise RuntimeError('Reset once per decision session') + self.result = self.environment.reset(**kwargs) + return self.result + + def step(self, action): + if self.result is None: + raise RuntimeError('Reset before stepping') + if fingerprint(self.result.observation) != self.history.progress['observation_id']: + raise ValueError('Decision snapshot was mutated; no command executed') + self.result = self.environment.step(action) + self._decision = None + return self.result + + def decision(self): + if self.result is None: + raise RuntimeError('Reset before constructing a decision') + if self.environment.numeric_encoder is None: + self._decision = super().decision() + return self._decision + if self.catalog is not self.environment._policy_catalog: + raise ValueError('Numeric encoding requires the current public snapshot and catalog') + if not hasattr(self.environment.session, 'build_current_policy'): + self._decision = build_decision(self.result.observation, self.catalog, self.history, + candidate_encoder=self.environment._encode_candidates, + state_copy=self.environment._copy_state) + else: + from .native_policy import decode + state = self.result.observation + snapshot = self.history.snapshot(state) + try: + token, raw, buffers = self.environment.session.build_current_policy(state['revision']) + except ValueError as error: + if str(error) in ('Native candidate hard cap exceeded; domain was not sliced', + 'History/public domain exhausted; no fallback wait or forced Ready'): + raise CandidateBlocked(str(error)) from None + raise + actions = tuple(json.loads(raw)) + observation, features, schedules, experts = decode(buffers, len(actions)) + self._decision = Decision(self.environment._copy_state(state), observation, features, + actions, schedules, experts, state['personalEnded'], + history_json=canonical(snapshot)) + self.environment._policy_token = token + return self._decision + + def step_index(self, index): + if self._decision is None: + raise RuntimeError('Construct a current decision before selecting its index') + if (not isinstance(index, Integral) or isinstance(index, bool) + or not 0 <= index < len(self._decision.actions)): + raise ValueError('Select a current unpadded candidate index') + if getattr(self.environment, '_policy_token', None) is None: + return self.step(self._decision.actions[index]) + if fingerprint(self.result.observation) != self.history.progress['observation_id']: + raise ValueError('Decision snapshot was mutated; no command executed') + self.result = self.environment._step(index=int(index)) + self._decision = None + return self.result + + +class NativeLedgerEnv(NativeDecisionEnv): + def _copy_state(self, state): + # Decode the committed native packet for an independently owned snapshot. + return json.loads(self._raw)['observation'] + + def _encode_candidates(self, state, prefix, catalog, history, prepared): + from .native_policy import decode + if catalog is not self._policy_catalog or history != self._ledger['history']: + raise ValueError('Numeric encoding requires the current public snapshot and catalog') + # build_decision just bound this snapshot once through history.snapshot(). + try: + raw_actions, *buffers = self.session.build_ledger_policy( + state['revision'], canonical(prefix), prepared) + except ValueError as error: + if str(error) in ( + 'Native candidate hard cap exceeded; domain was not sliced', + 'History/public domain exhausted; no fallback wait or forced Ready'): + raise CandidateBlocked(str(error)) from None + raise + actions = json.loads(raw_actions) + return actions, *decode(buffers, len(actions)) + + def _encode_numeric(self, state, actions, catalog, history): + from .native_policy import encode + if catalog is not self._policy_catalog or history != self._ledger['history']: + raise ValueError('Numeric encoding requires the current public snapshot and catalog') + return encode(self.session, state, actions, history, native_history=True) + + def _consume(self, raw): + ledger = json.loads(raw) + state = ledger['observation'] + # NativeProgressCore validates this exact owned state before committing it. + self._raw = raw + self._policy_token = None + self._ledger = ledger + self._state = state + self._advances += ledger['advances'] + if not state['personalEnded']: + if self._decisions >= self.max_decisions: + self._reason = 'decision-budget' + elif self._advances >= self.max_advances: + self._reason = 'advance-budget' + execution = ledger['execution'] + return Transition(state, state['personalEnded'], + bool(self._reason and not state['personalEnded']), self._reason, + accepted=execution['accepted'] if execution else None, + action_id=execution['action_id'] if execution else None, + execution=deepcopy(execution), + progress=deepcopy(ledger['history']['progress'])) + + def reset(self, *, seed, difficulty='ABYSS'): + if difficulty != 'ABYSS' or self._state is not None or self._closed: + raise ValueError('Reset once per live Desperation decision session') + return self._consume(self.session.reset_decision(seed, uuid4().hex)) + + def step(self, action): + return self._step(action=action) + + def _step(self, *, action=None, index=None): + if self._closed or self._state is None or self._reason or self._state['personalEnded']: + raise RuntimeError('Reset required') + self._previous = self._state + try: + if index is None: + raw = self.session.step_decision(json.dumps(action, allow_nan=False), self.tick_budget, + self.max_advances - self._advances) + else: + raw = self.session.step_index(self._state['revision'], self._policy_token, index, + self.tick_budget, self.max_advances - self._advances) + self._decisions += 1 + result = self._consume(raw) + self._reward_consumed = False + return result + except BaseException: + self.close(error=True) + raise + + +class NativeLedgerReward: + """Consume the reward already committed with the current native transition.""" + def __init__(self, environment): + self.environment = environment + + def reset(self, state): + if state is not self.environment._state: + raise ValueError('Reward reset requires the native reset observation') + + def step(self, before, after): + env = self.environment + if env._reward_consumed or before is not env._previous or after is not env._state: + raise ValueError('Disconnected or already-ended reward episode') + env._reward_consumed = True + return env._ledger['reward'] diff --git a/arkguardrl_core/native_policy.py b/arkguardrl_core/native_policy.py new file mode 100644 index 0000000..aa46879 --- /dev/null +++ b/arkguardrl_core/native_policy.py @@ -0,0 +1,71 @@ +"""Compile public policy metadata once; numerical projection lives in Rust. + +This is a model-layout bridge, not a source identity gate. Raw observations and +public progress remain available for the existing history/reward contracts. +""" +import json +import numpy as np +from arkguardrl.contracts import canonical, fingerprint +from arkguardrl.dynamic import OBS_DIM, ACTION_DIM +from arkguardrl.feedback import PROGRESS_SCHEMA + + +def metadata(catalog): + cached = getattr(catalog, '_native_policy_metadata', None) + if cached is not None: + return cached + from arkguardrl import structured as layout + if (len(catalog.entity_ids) >= layout.ENTITY_VOCAB + or len(catalog.mechanism_ids) >= layout.MECHANISM_VOCAB + or len(catalog.enemy_ids) >= layout.ENEMY_VOCAB): + raise ValueError('Catalog vocabulary exceeds structured embedding contract') + bank, _, indices = catalog.definitions() + air_column = (layout.ENTITY_PREFIX + len(layout.KINDS) + len(layout.AREAS) + + layout.ENTITY_NUMBERS.index('can_hit_fly')) + definitions = [] + for i, (kind, identifier) in enumerate(bank['keys']): + record = catalog._views.get(kind, {}).get(identifier, {}) + definitions.append(dict(kind=kind, id=identifier, index=indices[kind, identifier], + ranges=catalog.attack_range({'kind': kind, 'id': identifier}) if kind == 'chess' else (), + air=bool(bank['entities'][i][air_column]), base=record.get('baseId', identifier), + isGolden=bool(record.get('isGolden', False)), upgradeNum=record.get('upgradeNum', 0), + domain=dict(placement=catalog.placement_class({'kind': kind, 'id': identifier}) + if kind in ('chess', 'token') and record.get('position') in ('MELEE', 'RANGED', 'ALL') else None, + itemType=record.get('itemType'), ownerRange=record.get('ownerRange'), + ownerRangeOutside=record.get('ownerRangeOutside')))) + compiled = dict(definitions=definitions, band_ids=list(catalog.band_ids), + entities=[dict(kind=k, id=i, index=n) for (k, i), n in catalog._entity_indices.items()], + enemies=[dict(id=i, index=n) for i, n in catalog._enemy_indices.items()], + config=catalog._data['config'], diy=catalog._data.get('diy', {}), + choices=[dict(rec, kind=k, id=i) for (k, i), rec in catalog._choices.items()]) + cached = json.dumps(compiled, ensure_ascii=False, allow_nan=False, + separators=(',', ':')).encode('utf-8') + catalog._native_policy_metadata = cached + return cached + + +def encode(session, state, actions, history, *, native_history=False): + progress = history.get('progress') + if (not isinstance(progress, dict) or progress.get('schema') != PROGRESS_SCHEMA + or progress.get('observation_id') != fingerprint(state)): + raise ValueError('Structured v7 requires observation-bound public progress') + # Public history remains independently owned; no callbacks or Python state + # traversal occur inside the numerical encoder. + if native_history: + buffers = session.encode_ledger_policy(state['revision'], canonical(actions)) + else: + buffers = session.encode_policy(state['revision'], canonical(history), canonical(actions)) + return decode(buffers, len(actions)) + + +def decode(buffers, count): + observation = np.frombuffer(buffers[0], dtype='-<平台>`。 -4 env 的 Sync/Async 动作、奖励和结束标志摘要一致,每次均自然结束 18 局、截断 0 局; -剩余轨迹不一定结束,因此不能用总耗时除以结束局数估算单局耗时。 -Async 相对同负载 Sync 吞吐为 2.18 倍。单 env 的约 2.24 毫秒/步包含观测、奖励及 Gym 开销。 -默认填充观测为每 env 2,984,640 字节;本次最多 401 个候选,不代表所有对局的候选上限。 +Linux 使用 Ubuntu 22.04(glibc 2.35)作为构建基线。迁移 AutoDL 时选择匹配 Python 版本与架构的产物,将三个模块放入同一目录,分别向运行时传入 `_native` 与 `_native_slots` 的路径;特征模块放入 `arkguardrl_core` 包目录。外部 0.3.3 数据另行配置。不同 Python ABI 或更旧的 glibc 环境可在目标机器执行以下构建命令。 + +```sh +export PYO3_PYTHON="$(command -v python)" +cargo build --release --locked -p arkguard-python +cargo build --release --locked --manifest-path arkguardrl_core/native/Cargo.toml +cargo build --release --locked --manifest-path benchmarks/native_slots/Cargo.toml +``` diff --git a/benchmarks/ab_slots.py b/benchmarks/ab_slots.py new file mode 100644 index 0000000..c60a0d1 --- /dev/null +++ b/benchmarks/ab_slots.py @@ -0,0 +1,142 @@ +"""Interleaved A/B: Gym Async processes vs Rust-owned slots. + +Alternates order each repeat and records the load average around each block, +so a machine-load spike is visible instead of being read as a backend result. +""" +import argparse +import json +import os +import statistics +import time +from functools import partial + +import gymnasium as gym +import numpy as np +from arkguardrl_core.native_gym import ArkGuardNativeEnv +from bench_slots import Policy +from native_batch_slots import NativeSlotBatch + +REFERENCE_LIBRARY = None + + +def load(): + """Load average where the platform reports one; Windows reports CPU instead.""" + try: + return {'load': round(os.getloadavg()[0], 2)} + except (AttributeError, OSError): + pass + try: + import psutil + return {'cpu_percent': psutil.cpu_percent(interval=0.2)} + except Exception: + return {} + + +def scheduling(cpus=None, priority=None): + import psutil + process = psutil.Process() + if cpus is not None: + process.cpu_affinity(cpus) + if priority is not None: + if os.name != 'nt': + raise ValueError('Explicit priority is supported only on Windows') + process.nice({'normal': psutil.NORMAL_PRIORITY_CLASS, + 'high': psutil.HIGH_PRIORITY_CLASS}[priority]) + return dict(pid=process.pid, affinity=process.cpu_affinity() if hasattr(process, 'cpu_affinity') else None, + priority=int(process.nice())) + + +def make_worker(data_root, core, library, cpus, priority): + actual = scheduling(cpus, priority) + env = ArkGuardNativeEnv(data_root, core=core, native_library=library) + env._benchmark_scheduling = actual + return env + + +def gym_block(n, steps): + envs = gym.vector.AsyncVectorEnv( + [partial(make_worker, ARGS.data_root, ARGS.core, REFERENCE_LIBRARY, + ARGS.cpus, ARGS.priority) for _ in range(n)], + context='spawn', shared_memory=True, + autoreset_mode=gym.vector.AutoresetMode.DISABLED) + try: + obs, _ = envs.reset(seed=42) + policy = Policy(n) + policy.reset() + started = time.perf_counter() + for _ in range(steps): + obs, _, terminated, truncated, _ = envs.step(policy.choose(obs, n)) + done = terminated | truncated + if done.any(): + obs, _ = envs.reset(options={'reset_mask': done}) + policy.reset(done) + return n * steps / (time.perf_counter() - started) + finally: + envs.close() + + +def slot_block(n, steps, threads): + with NativeSlotBatch(ARGS.data_root, core=ARGS.core, num_envs=n, threads=threads, + native_library=ARGS.slots_library) as batch: + obs, _ = batch.reset(seed=42) + policy = Policy(n) + policy.reset() + started = time.perf_counter() + for _ in range(steps): + obs, _, terminated, truncated, _ = batch.step(policy.choose(obs, n)) + done = terminated | truncated + if done.any(): + obs, _ = batch.reset(reset_mask=done) + policy.reset(done) + return n * steps / (time.perf_counter() - started) + + +def main(): + global ARGS, REFERENCE_LIBRARY + parser = argparse.ArgumentParser() + parser.add_argument('--data-root', required=True) + parser.add_argument('--core', default='band_chen') + parser.add_argument('--reference-library', required=True) + parser.add_argument('--slots-library', required=True) + parser.add_argument('--envs', type=int, default=4) + parser.add_argument('--threads', type=int, default=4) + parser.add_argument('--steps', type=int, default=192) + parser.add_argument('--repeats', type=int, default=4) + parser.add_argument('--cpus', help="Comma separated CPU indexes applied to every measured process") + parser.add_argument('--priority', choices=('normal', 'high'), + help='Process priority applied to every measured process (Windows)') + parser.add_argument('--out') + ARGS = parser.parse_args() + ARGS.cpus = [int(c) for c in ARGS.cpus.split(',')] if ARGS.cpus else None + REFERENCE_LIBRARY = ARGS.reference_library + n = ARGS.envs + records = {'gym': [], 'slots': []} + for repeat in range(ARGS.repeats): + order = ('gym', 'slots') if repeat % 2 == 0 else ('slots', 'gym') + for name in order: + before = load() + if name == 'gym': + value = gym_block(n, ARGS.steps) + else: + scheduling(ARGS.cpus, ARGS.priority) + value = slot_block(n, ARGS.steps, ARGS.threads) + after = load() + records[name].append({'decisions_per_second': value, 'before': before, 'after': after}) + print(json.dumps({name: round(value, 1), 'repeat': repeat, + 'before': before, 'after': after}), flush=True) + summary = {name: statistics.median(row['decisions_per_second'] for row in rows) + for name, rows in records.items()} + summary['slots_over_gym_pct'] = 100 * (summary['slots'] / summary['gym'] - 1) + summary = {k: round(v, 1) for k, v in summary.items()} + print(json.dumps(summary), flush=True) + if ARGS.out: + with open(ARGS.out, 'w') as handle: + handle.write(json.dumps(dict( + scope='Interleaved A/B, scripted numeric policy, masked reset, resets in loop, ' + 'no model/training; load average recorded per block', + envs=n, threads=ARGS.threads, steps=ARGS.steps, repeats=ARGS.repeats, + summary=summary, records=records), indent=2) + '\n') + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/benchmarks/bench_slots.py b/benchmarks/bench_slots.py new file mode 100644 index 0000000..a64392c --- /dev/null +++ b/benchmarks/bench_slots.py @@ -0,0 +1,117 @@ +"""Compare Rust-owned slots with Gym vectors on the same scripted policy. + +Run with the current Core on PYTHONPATH plus this directory. No model/training. +""" +import argparse +from contextlib import closing +from functools import partial +import json +import statistics +import time + +import gymnasium as gym +import numpy as np +from arkguardrl_core.native_gym import ArkGuardNativeEnv +from native_batch_slots import NativeSlotBatch + + +class Policy: + def __init__(self, n): + self.bought = [set() for _ in range(n)] + + def reset(self, mask=np.zeros(0, bool)): + for i in np.flatnonzero(mask) if len(mask) else range(len(self.bought)): + self.bought[i].clear() + + def choose(self, obs, n): + out = [] + for i in range(n): + mask = obs['action_mask'][i] + count = int(mask.sum()) + if not count: + out.append(0) + continue + cand = obs['candidates'][i, :count] + types = 5 + 4 + rows = lambda kind: np.flatnonzero(cand[:, types + kind]) # noqa: E731 + choice = rows(2) + if len(choice): + out.append(int(choice[0])) + continue + moves = np.flatnonzero((cand[:, types + 14] != 0) & (cand[:, 5] != 0)) + if len(moves): + out.append(int(moves[-1])) + continue + buys = rows(3) + round_key = float(obs['observation'][i, 0]) + if round_key not in self.bought[i] and len(buys): + self.bought[i].add(round_key) + out.append(int(buys[0])) + continue + ready = rows(13) + out.append(int(ready[0]) if len(ready) else 0) + return np.asarray(out, dtype=np.int64) + + +def measure(batch_step, batch_reset, n, steps, reps): + rates = [] + for rep in range(reps + 1): + obs, _ = batch_reset() + policy = Policy(n) + policy.reset() + started = time.perf_counter() + for _ in range(steps): + obs, _, terminated, truncated, _ = batch_step(policy.choose(obs, n)) + done = terminated | truncated + if done.any(): + obs, _ = batch_reset(done) + policy.reset(done) + if rep: + rates.append(n * steps / (time.perf_counter() - started)) + return statistics.median(rates) + + +def gym_async(data_root, core, n, steps, reps, native_library): + factories = [partial(ArkGuardNativeEnv, data_root, core=core, + native_library=native_library) for _ in range(n)] + + with closing(gym.vector.AsyncVectorEnv( + factories, context='spawn', shared_memory=True, + autoreset_mode=gym.vector.AutoresetMode.DISABLED)) as env: + def reset(mask=None): + return env.reset(options={'reset_mask': mask} if mask is not None else None) + return measure(env.step, reset, n, steps, reps) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--data-root', required=True) + parser.add_argument('--reference-library', required=True) + parser.add_argument('--slots-library', required=True) + parser.add_argument('--steps', type=int, default=192) + parser.add_argument('--repeats', type=int, default=3) + parser.add_argument('--envs', type=int, nargs='+', default=[4]) + parser.add_argument('--out') + args = parser.parse_args() + out = {} + for n in args.envs: + out[f'gym-async-{n}'] = gym_async( + args.data_root, 'band_chen', n, args.steps, args.repeats, args.reference_library) + for threads in sorted({min(n, threads) for threads in (1, 2, 4)}): + with NativeSlotBatch(args.data_root, core='band_chen', num_envs=n, threads=threads, + native_library=args.slots_library) as batch: + reset = lambda mask=None: batch.reset(reset_mask=mask) # noqa: E731 + rate = measure(batch.step, reset, n, args.steps, args.repeats) + out[f'slots-{n}-t{threads}'] = rate + print(json.dumps({f'slots-{n}-t{threads}': round(rate, 1), + f'gym-async-{n}': round(out[f"gym-async-{n}"], 1)}), flush=True) + if args.out: + with open(args.out, 'w') as handle: + handle.write(json.dumps(dict(scope='Scripted numeric policy, masked reset, ' + 'resets in loop, no model/training', steps=args.steps, + repeats=args.repeats, results=out), indent=2) + '\n') + print(json.dumps({k: round(v, 1) for k, v in out.items()}, indent=1)) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/benchmarks/human_records.py b/benchmarks/human_records.py new file mode 100644 index 0000000..e1f16c2 --- /dev/null +++ b/benchmarks/human_records.py @@ -0,0 +1,183 @@ +"""Replay complete human solo Desperation records and compare decision state. + +Checks phase/round, inventory, economy, deployment, bonds, choices, shop and final +victory/round count/hidden progress. Display metadata and combat floating-point +accounting are outside this comparison. No source revision gate is applied. +""" +import argparse +from collections import Counter +import json +from pathlib import Path + +from arkguardrl_core.native_env import load_native + +CORES = {'band_chen', 'band_amiya', 'band_sarkazb', 'band_sciurus'} +OWN_FIELDS = ('alive', 'lp', 'funds', 'bandId', 'ready', 'canReady', 'deployCap', + 'deployCount', 'board', 'hand', 'temp', 'bonds', 'personalChoice') +SHOP_FIELDS = ('level', 'maxLevel', 'upgradePrice', 'refreshPrice', 'freeRefreshes', 'frozen') +SLOT_FIELDS = ('kind', 'id', 'price', 'sold', 'frozen') +OUTCOME_FIELDS = ('victory', 'roundsPassed', 'hiddenReached', 'hiddenCleared') + + +def first_difference(expected, actual, path): + if expected == actual: + return None + if isinstance(expected, dict) and isinstance(actual, dict): + for key in sorted(expected.keys() | actual.keys()): + difference = first_difference(expected.get(key, ''), + actual.get(key, ''), f'{path}.{key}') + if difference is not None: + return difference + if isinstance(expected, list) and isinstance(actual, list): + if len(expected) != len(actual): + return dict(field=path+'.length', expected=len(expected), actual=len(actual)) + for index, (left, right) in enumerate(zip(expected, actual)): + difference = first_difference(left, right, f'{path}[{index}]') + if difference is not None: + return difference + return dict(field=path, expected=expected, actual=actual) + + +def decision_state(state): + own = state['own'] + shop = own['shop'] + result = {key: own.get(key) for key in OWN_FIELDS} + result['shop'] = {key: shop.get(key) for key in SHOP_FIELDS} + result['shop']['slots'] = [None if slot is None else {key: slot.get(key) for key in SLOT_FIELDS} + for slot in shop['slots']] + result['phase'] = state['public']['phase'] + result['round'] = state['public']['round'] + return result + + +def read_case(path): + if path.stat().st_size > 64 << 20: + raise ValueError('Record exceeds 64 MiB') + header = footer = outcome = core = None + actions = [] + setup_revision = 0 + with path.open() as stream: + for line in stream: + row = json.loads(line) + if header is None: + header = row + elif row['kind'] == 'footer': + footer = row + elif row['kind'] == 'outcome-message' and row['message']['t'] == 'm.result': + outcome = row['message'] + elif row['kind'] == 'action': + action = {key: value for key, value in row['action'].items() if key != 'rid'} + if action['t'] == 'room.rerollSetup' and row['accepted'] and not actions: + if action.get('setupRevision') != setup_revision: + return None, 'nonsequential setup reroll' + setup_revision += 1 + elif not action['t'].startswith('g.') and not row['accepted']: + continue + elif action['t'] == 'g.band': + if row['accepted']: + core = action['bandId'] + elif action['t'] not in ('g.infoReady', 'g.unitStats'): + before = decision_state(row['before']) if action['t'].startswith('g.') else {} + actions.append((action, row['accepted'], before)) + if not header or header.get('schema') != 'stronghold-human-seat-trajectory/v1': + return None, 'record schema' + if header.get('roomMode') != 'solo' or header.get('difficulty') != 'ABYSS': + return None, 'mode outside solo Desperation' + if not footer or footer.get('complete') is not True or outcome is None: + return None, 'incomplete recording' + if core not in CORES: + return None, f'unsupported core {core}' + if type(header.get('seed')) is not int: + return None, 'missing original seed' + if any(not action['t'].startswith('g.') for action, _, _ in actions): + return None, 'room setup changes' + return dict(core=core, seed=header['seed'], actions=actions, outcome=outcome, + diy=header.get('diy', {}), setup_revision=setup_revision), None + + +def replay(native, catalog, case): + session = None + differences = Counter() + first = None + checked = 0 + try: + session = native.NativeSolo(catalog, case['core'], diy_json=json.dumps(case['diy']), setup_revision=case['setup_revision']) + session.reset(case['seed']) + for index, (action, accepted, expected) in enumerate(case['actions']): + actual = decision_state(json.loads(session.observation())) + for key in expected: + if actual[key] != expected[key]: + differences[key] += 1 + if first is None: + first = dict(action=index, round=expected['round'], + **first_difference(expected[key], actual[key], key)) + receipt = json.loads(session.step(json.dumps(action), 108000)) + checked += 1 + if receipt['accepted'] != accepted: + raise RuntimeError(f'Action {index} {action["t"]} acceptance differs') + for _ in range(16): + if not receipt['budgetExhausted']: + break + receipt = json.loads(session.advance(108000)) + if receipt['budgetExhausted']: + raise RuntimeError('Battle exceeded replay tick budget') + state = json.loads(session.observation()) + if not state['personalEnded']: + raise RuntimeError('Recording ended before native termination') + outcome = state['outcome'] + actual_outcome = {key: outcome.get(key) for key in OUTCOME_FIELDS} + actual_outcome['roundsPassed'] = outcome['players'][0]['roundsPassed'] + expected_outcome = {key: case['outcome'].get(key) for key in OUTCOME_FIELDS} + if actual_outcome != expected_outcome: + differences['outcome'] += 1 + if first is None: + first = dict(field='outcome', expected=expected_outcome, actual=actual_outcome) + return dict(status='drift' if differences else 'passed', decisions=checked, + differences=dict(differences), first_difference=first, + expected_outcome=expected_outcome, actual_outcome=actual_outcome) + except (RuntimeError, ValueError) as error: + return dict(status='error', decisions=checked, error=str(error), + differences=dict(differences), first_difference=first) + finally: + if session is not None: + session.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--records', type=Path, required=True) + parser.add_argument('--data-root', required=True) + parser.add_argument('--native-library', required=True) + parser.add_argument('--out', type=Path, required=True) + args = parser.parse_args() + native = load_native(args.native_library) + catalog = native.NativeCatalog(args.data_root, 64 << 20) + results = [] + paths = sorted(args.records.glob('*.jsonl')) + if not paths: + parser.error('No JSONL records found') + for index, path in enumerate(paths): + try: + case, reason = read_case(path) + except (ValueError, KeyError) as error: + results.append(dict(file=path.name, status='error', error=f'Record input: {error}')) + continue + if case is None: + result = dict(file=path.name, status='skipped', reason=reason) + else: + result = dict(file=path.name, core=case['core'], seed=case['seed'], **replay(native, catalog, case)) + if case['diy']: + result['diy'] = case['diy'] + results.append(result) + if (index + 1) % 20 == 0: + print(json.dumps(dict(records=index+1, counts=dict(Counter(r['status'] for r in results)))), flush=True) + summary = dict(records=len(results), counts=dict(Counter(r['status'] for r in results)), + decisions=sum(r.get('decisions', 0) for r in results), results=results) + args.out.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + '\n') + print(json.dumps({key: value for key, value in summary.items() if key != 'results'}), flush=True) + if any(r['status'] in ('drift', 'error') for r in results): + raise SystemExit(1) + + +if __name__ == '__main__': + main() diff --git a/benchmarks/ledger_compare.py b/benchmarks/ledger_compare.py new file mode 100644 index 0000000..bd87aaa --- /dev/null +++ b/benchmarks/ledger_compare.py @@ -0,0 +1,118 @@ +"""Compare Python/Rust ledgers on the same complete Desperation episodes.""" +import argparse +import json +from pathlib import Path +import statistics +import struct + +import numpy as np + +from arkguardrl_core.native_gym import ArkGuardNativeEnv +from benchmarks.native_session import measure, pilot + + +def public_stream(value): + # Each reset deliberately creates a fresh UUID. All other fields must match. + if isinstance(value, dict): + return {key: '' if key == 'stream_id' else public_stream(item) + for key, item in value.items()} + if isinstance(value, list): + return [public_stream(item) for item in value] + return value + + +def compare(left, right, arrays_left, arrays_right, histories): + a, b = left._result, right._result + assert a.observation == b.observation, 'Public observation differs' + assert (a.terminated, a.truncated, a.reason, a.accepted, a.action_id) == ( + b.terminated, b.truncated, b.reason, b.accepted, b.action_id), 'Transition differs' + assert public_stream(a.execution) == public_stream(b.execution), 'Execution differs' + assert public_stream(a.progress) == public_stream(b.progress), 'Progress differs' + ah, bh = histories + assert public_stream(ah.snapshot(a.observation)) == public_stream(bh.snapshot(b.observation)), 'History differs' + assert ah.blocked(a.observation) == bh.blocked(b.observation), 'Blocked actions differ' + if left._decision is not None: + assert left._decision.actions == right._decision.actions, 'Candidate order differs' + assert public_stream(json.loads(left._decision.history_json)) == public_stream( + json.loads(right._decision.history_json)), 'Decision history differs' + else: + assert right._decision is None, 'Terminal candidates differ' + for key in arrays_left: + assert arrays_left[key].dtype == arrays_right[key].dtype, key + assert arrays_left[key].shape == arrays_right[key].shape, key + assert arrays_left[key].tobytes() == arrays_right[key].tobytes(), key + + +def compare_reward(a, b, info_a, info_b): + assert struct.pack('d', a) == struct.pack('d', b), 'Reward bits differ' + for key, value in info_a['reward_components'].items(): + assert struct.pack('d', value) == struct.pack('d', info_b['reward_components'][key]), key + + +def parity(left, right, seed, actions): + a, _ = left.reset(seed=seed) + b, _ = right.reset(seed=seed) + histories = left._session.history, right._session.history + compare(left, right, a, b, histories) + for action in actions: + index_a = left._decision.actions.index(action) + index_b = right._decision.actions.index(action) + a, reward_a, done_a, trunc_a, info_a = left.step(index_a) + b, reward_b, done_b, trunc_b, info_b = right.step(index_b) + assert (done_a, trunc_a) == (done_b, trunc_b) + compare_reward(reward_a, reward_b, info_a, info_b) + compare(left, right, a, b, histories) + return len(actions) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--data-root', required=True) + parser.add_argument('--native-library', required=True) + parser.add_argument('--cycles', type=int, default=20) + parser.add_argument('--repeats', type=int, default=5) + parser.add_argument('--out', type=Path, required=True) + args = parser.parse_args() + if min(args.cycles, args.repeats) < 1: + parser.error('Positive cycles and repeats required') + options = dict(core='band_chen', native_library=args.native_library, profile=True) + results, parity_steps = [], 0 + with ArkGuardNativeEnv(args.data_root, native_ledger=False, **options) as left, \ + ArkGuardNativeEnv(args.data_root, native_ledger=True, **options) as right: + for roster in (False, True): + cases = [(seed, *pilot(left, seed, roster)) for seed in (42, 99)] + for seed, _, actions, _ in cases: + parity_steps += parity(left, right, seed, actions) + # The arrays returned by one decision must survive later decisions. + observation, _ = right.reset(seed=42) + saved = {key: value.copy() for key, value in observation.items()} + funds = right._result.observation['own']['funds'] + right._decision.state['own']['funds'] += 1 + assert right._result.observation['own']['funds'] == funds, 'Decision snapshot aliases live state' + right.step(0) + assert all(np.array_equal(value, saved[key]) for key, value in observation.items()) + for env in (left, right): + measure(env, None, cases, 2, 'gym') + runs = {'python': [], 'rust': []} + for repeat in range(args.repeats): + order = (('python', left), ('rust', right)) + if repeat % 2: + order = order[::-1] + for name, env in order: + runs[name].append(measure(env, None, cases, args.cycles, 'gym')) + medians = {name: statistics.median(run['decisions_per_second'] for run in values) + for name, values in runs.items()} + result = dict(workload='buy_deploy' if roster else 'empty', + decisions_per_second=medians, speedup=medians['rust'] / medians['python'], + runs=runs) + results.append(result) + print(json.dumps({key: value for key, value in result.items() if key != 'runs'}), flush=True) + output = dict(core='band_chen', seeds=[42, 99], cycles=args.cycles, repeats=args.repeats, + scope='Complete Gym decisions, same release library, alternating Python/Rust ledger runs.', + parity_decisions=parity_steps, results=results) + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(output, indent=2) + '\n') + + +if __name__ == '__main__': + main() diff --git a/benchmarks/movement_batch.py b/benchmarks/movement_batch.py new file mode 100644 index 0000000..e6d8ea3 --- /dev/null +++ b/benchmarks/movement_batch.py @@ -0,0 +1,131 @@ +"""A/B complete Desperation episodes and measure movement-window coverage.""" +import argparse +import json +from pathlib import Path +import statistics + +from arkguardrl_core.native_env import load_native +from arkguardrl_core.native_gym import ArkGuardNativeEnv +from benchmarks.native_session import choose, ending, measure, pilot +from benchmarks.ledger_compare import parity + + +def choose_rear(env, roster, bought): + index = choose(env, roster, bought) + chosen = env._decision.actions[index] + if chosen['t'] != 'g.move': + return index + occupied = {(p['row'], p['col']) for p in env._result.observation['own']['board']} + moves = [(i, action) for i, action in enumerate(env._decision.actions) + if action['t'] == 'g.move' and action['uid'] == chosen['uid'] + and action['to']['area'] == 'board' and action.get('dir') == 'RIGHT' + and (action['to']['row'], action['to']['col']) not in occupied] + return min(moves, key=lambda item: (item[1]['to']['col'], item[1]['to']['row']))[0] + + +def coverage(native, catalog, core, cases): + session = native.NativeSolo(catalog, core) + ticks = batched = tail = battles = 0 + fast_updates = enemy_updates = 0 + event_ticks = event_windows = 0 + deployed_battles = 0 + try: + for _, engine_seed, actions, expected in cases: + session.reset(engine_seed) + for action in actions: + receipt = json.loads(session.step(json.dumps(action), 0)) + if receipt['accepted'] is not True: + raise RuntimeError('Rejected coverage action') + count = 0 + paths = (0, 0) + windows = (0, 0) + if receipt['budgetExhausted']: + battles += 1 + deployed_battles += bool(json.loads(session.observation())['own']['board']) + while receipt['budgetExhausted']: + receipt = json.loads(session.advance(64)) + ticks += receipt['ticks'] + observed = session.movement_batch_ticks() + movement_paths = session.movement_path_steps() + observed_windows = session.event_window_stats() + if observed_windows is not None: + windows = observed_windows + if movement_paths is not None: + paths = movement_paths + if observed is not None: + count = observed + else: + # Settlement releases the Field. Bound the unobserved last chunk. + tail += receipt['ticks'] + batched += count + fast_updates += paths[0] + enemy_updates += paths[1] + event_ticks += windows[0] + event_windows += windows[1] + if ending(json.loads(session.observation())) != expected: + raise RuntimeError('Coverage replay changed public terminal state') + finally: + session.close() + return dict(ticks=ticks, battles=battles, deployed_battles=deployed_battles, + observed_event_ticks=event_ticks, observed_event_windows=event_windows, + mean_event_window_ticks=event_ticks / event_windows if event_windows else 0., + batch_ticks_lower_bound=batched, + observed_fast_enemy_updates=fast_updates, observed_enemy_updates=enemy_updates, + observed_fast_enemy_fraction=fast_updates / enemy_updates if enemy_updates else 0., + excluded_settlement_ticks=tail, + batch_ticks_upper_bound=min(ticks, batched + tail), + lower_fraction=batched / ticks if ticks else 0., + upper_fraction=min(ticks, batched + tail) / ticks if ticks else 0.) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--data-root', required=True) + parser.add_argument('--native-library', required=True) + parser.add_argument('--reference-library', required=True) + parser.add_argument('--core', default='band_chen', choices=('band_chen', 'band_amiya', 'band_sarkazb')) + parser.add_argument('--workload', default='both', choices=('empty', 'buy_deploy', 'both')) + parser.add_argument('--deployment', default='front', choices=('front', 'rear')) + parser.add_argument('--cycles', type=int, default=20) + parser.add_argument('--repeats', type=int, default=6) + parser.add_argument('--out', type=Path, required=True) + args = parser.parse_args() + if min(args.cycles, args.repeats) < 1: + parser.error('Positive cycles and repeats required') + native = load_native(args.native_library) + catalog = native.NativeCatalog(args.data_root, 64 << 20) + results, compared = [], 0 + with ArkGuardNativeEnv(args.data_root, core=args.core, native_library=args.reference_library, profile=True) as before, \ + ArkGuardNativeEnv(args.data_root, core=args.core, native_library=args.native_library, profile=True) as after: + rosters = (False, True) if args.workload == 'both' else (args.workload == 'buy_deploy',) + for roster in rosters: + chooser = choose_rear if args.deployment == 'rear' else None + cases = [(seed, *pilot(before, seed, roster, chooser=chooser)) for seed in (42, 99)] + for seed, _, actions, _ in cases: + compared += parity(before, after, seed, actions) + windows = coverage(native, catalog, args.core, cases) + for env in (before, after): + measure(env, None, cases, 2, 'gym') + runs = {'before': [], 'after': []} + for repeat in range(args.repeats): + order = (('before', before), ('after', after)) + if repeat % 2: + order = order[::-1] + for name, env in order: + runs[name].append(measure(env, None, cases, args.cycles, 'gym')) + medians = {name: statistics.median(run['decisions_per_second'] for run in values) + for name, values in runs.items()} + result = dict(workload='buy_deploy' if roster else 'empty', coverage=windows, + decisions_per_second=medians, speedup=medians['after'] / medians['before'], runs=runs) + results.append(result) + print(json.dumps({key: value for key, value in result.items() if key != 'runs'}), flush=True) + output = dict(core=args.core, deployment=args.deployment, seeds=[42, 99], cycles=args.cycles, repeats=args.repeats, + order='alternating', parity_decisions=compared, + scope='Complete Gym episodes, same Python path and action sequence, before/after native libraries.', + results=results) + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(output, indent=2) + '\n') + + +if __name__ == '__main__': + main() diff --git a/benchmarks/native_batch_slots.py b/benchmarks/native_batch_slots.py new file mode 100644 index 0000000..d6dc104 --- /dev/null +++ b/benchmarks/native_batch_slots.py @@ -0,0 +1,250 @@ +"""Vectorized Desperation facade for Rust-owned decision slots. + +Build the _native_slots extension from benchmarks/native_slots/Cargo.toml. +""" +import importlib.machinery +import importlib.util +import json +from copy import deepcopy +from dataclasses import replace +from pathlib import Path +import time +from uuid import uuid4 + +import numpy as np +from arkguardrl.catalog import PublicCatalog +from arkguardrl.candidates import Decision +from arkguardrl.contracts import canonical +from arkguardrl_core.native_ledger import NativeLedgerHistory +from arkguardrl_core.native_policy import metadata + + +def load_slots(path): + path = str(Path(path).resolve(strict=True)) + loader = importlib.machinery.ExtensionFileLoader('_native_slots', path) + spec = importlib.util.spec_from_file_location('_native_slots', path, loader=loader) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class _Slot: + def __init__(self): + self.rng = np.random.default_rng() + self.state = self.decision = None + self.done = True + self.info = {} + + def reset(self, engine_seed): + self.history = NativeLedgerHistory(self) + self.decisions = self.advances = 0 + self.reason = None + self.engine_seed = engine_seed + self.done = False + self.started = time.monotonic() + self.info = {} + + +class NativeSlotBatch: + """One batch call runs all native battles; one more encodes all model inputs. + + Explicit masked reset, no autoreset. Output arrays own their memory. Runtime + errors invalidate the entire Python facade, because native slots may already + have advanced when a different worker fails. A full reset recovers the batch. + """ + def __init__(self, data_root, *, core, num_envs=1, threads=1, native_library, + banned=(), max_candidates=16384, max_decisions=1024, + max_advances=4096, tick_budget=4096, wall_seconds=None, + max_output_bytes=256 << 20): + if type(num_envs) is not int or not 1 <= num_envs <= 64: + raise ValueError('num_envs must be 1..64') + if type(threads) is not int or not 1 <= threads <= num_envs: + raise ValueError('threads must be 1..num_envs') + if type(max_candidates) is not int or not 1 <= max_candidates <= 16384: + raise ValueError('Invalid candidate capacity') + if any(type(n) is not int or n <= 0 for n in (max_decisions, max_advances)): + raise ValueError('Invalid decision/advance budgets') + if type(tick_budget) is not int or not 1 <= tick_budget <= 108000: + raise ValueError('Invalid tick budget') + if wall_seconds is not None and (not np.isfinite(wall_seconds) or wall_seconds <= 0): + raise ValueError('Invalid wall budget') + output_bytes = num_envs * (4784 * 4 + max_candidates * (41 * 4 + 17) + 10) + if output_bytes > max_output_bytes: + raise ValueError('Batch output exceeds memory limit') + native = load_slots(native_library) + catalog = native.NativeCatalog(str(Path(data_root).resolve()), 64 << 20) + self.catalog = PublicCatalog.from_native(catalog) + self.catalog.definitions() + cores = [core] * num_envs if isinstance(core, str) else list(core) + if len(cores) != num_envs: + raise ValueError('One core per slot required') + self.native = native.NativeBatch(catalog, cores, [list(banned) for _ in cores], threads) + self.native.configure_policy(metadata(self.catalog)) + self.max_candidates, self.num_envs = max_candidates, num_envs + self.max_decisions, self.max_advances = max_decisions, max_advances + self.tick_budget, self.wall_seconds = tick_budget, wall_seconds + self.slots = [_Slot() for _ in cores] + self._closed = self._faulted = False + + def _mask(self, value): + mask = np.ones(self.num_envs, bool) if value is None else np.asarray(value) + if mask.shape != (self.num_envs,) or mask.dtype != np.bool_: + raise ValueError('Mask must be a boolean vector with num_envs entries') + return mask + + def _adopt(self, slot, raw): + slot.raw = raw + slot._ledger = json.loads(raw) + slot.state = slot._ledger['observation'] + + def _refresh(self, slot): + if slot.state['decisionRequired'] and not slot.state['personalEnded']: + snapshot = slot.history.snapshot(slot.state) + slot.decision = Decision(json.loads(slot.raw)['observation'], (), (), (), (), (), False, + history_json=canonical(snapshot)) + else: + slot.decision = None + slot.info = dict(candidate_count=0, + phase=slot.state['phase'], round=slot.state['round'], + engine_seed=slot.engine_seed, reason=slot.reason or '') + + def _output(self): + n, k = self.num_envs, self.max_candidates + for slot in self.slots: + slot.history._check(slot.state) + tokens, actions, buffers = self.native.build_current_policy_all([s.state['revision'] for s in self.slots]) + for slot, token, raw in zip(self.slots, tokens, actions): + slot.token = token + candidates = tuple(json.loads(raw)) + if len(candidates) > self.max_candidates: + raise ValueError('Candidate capacity exceeded; no domain truncation') + if slot.decision is not None: + slot.decision = replace(slot.decision, actions=candidates) + slot.info['candidate_count'] = len(candidates) + obs = dict(observation=np.empty((n, 4784), np.float32), + candidates=np.zeros((n, k, 41), np.float32), + schedules=np.zeros((n, k), np.int64), experts=np.zeros((n, k), np.int64), + action_mask=np.zeros((n, k), np.int8)) + for i, slot in enumerate(self.slots): + obs['observation'][i] = np.frombuffer(buffers[0][i], dtype='= self.max_decisions: + slot.reason = 'decision-budget' + elif slot.advances >= self.max_advances: + slot.reason = 'advance-budget' + reward = ledger['reward'] + if not terminated and self.wall_seconds is not None and time.monotonic() - slot.started >= self.wall_seconds: + slot.reason = 'wall-budget' + slot.done = terminated or bool(slot.reason) + self._refresh(slot) + slot.info['accepted'] = ledger['execution']['accepted'] + slot.info['reward_components'] = reward['components'] + rewards[i] = reward['reward'] + obs, info = self._output() + return (obs, rewards, np.array([s.state['personalEnded'] for s in self.slots], bool), + np.array([bool(s.reason and not s.state['personalEnded']) for s in self.slots], bool), info) + except BaseException: + self._faulted = True + self.native.close() + raise + + def public_spatial(self): + if self._closed or self._faulted or any(s.state is None for s in self.slots): + raise RuntimeError('Reset a live batch before reading public spatial information') + spatial = [json.loads(raw) if raw is not None else None + for raw in self.native.public_spatial_all()] + if any(packet is not None and packet['revision'] != slot.state['revision'] + for packet, slot in zip(spatial, self.slots)): + raise ValueError('Public spatial revision mismatch') + return spatial + + def public_spatial_update(self, geometry_keys=None): + if self._closed or self._faulted or any(s.state is None for s in self.slots): + raise RuntimeError('Reset a live batch before reading public spatial information') + keys = [None] * self.num_envs if geometry_keys is None else list(geometry_keys) + return self.native.public_spatial_updates([s.state['revision'] for s in self.slots], keys) + + def close(self): + self.native.close() + self._closed = True + + def __enter__(self): + return self + + def __exit__(self, *_): + self.close() diff --git a/benchmarks/native_replay.html b/benchmarks/native_replay.html new file mode 100644 index 0000000..3f62152 --- /dev/null +++ b/benchmarks/native_replay.html @@ -0,0 +1,118 @@ + + + +Native battle replay + +

原生战斗回放

+ + +

选择 native_replay.py 导出的 JSONL

+ +

蓝色为友方,红色为敌方,金色描边表示技能开启,黄色点为弹道。按采样帧显示位置和血条,回合间直接切换。

+ + diff --git a/benchmarks/native_replay.py b/benchmarks/native_replay.py new file mode 100644 index 0000000..3b01d37 --- /dev/null +++ b/benchmarks/native_replay.py @@ -0,0 +1,170 @@ +"""Export bounded native battle frames and a standalone canvas replay. + +An action file contains {"engine_seed": ..., "actions": [...]} and optionally +"core". Without it, the existing buy/deploy benchmark supplies a diagnostic +policy. Outcome is recorded explicitly, including defeats. +""" +import argparse +import json +from pathlib import Path + +from arkguardrl_core.native_env import load_native +from arkguardrl_core.native_gym import ArkGuardNativeEnv +from benchmarks.native_session import ending, pilot + + +def load_actions(path, core, max_bytes, *, include_config=False): + if path.stat().st_size > max_bytes: + raise ValueError('Action input exceeds replay byte limit') + if path.suffix != '.jsonl': + payload = json.loads(path.read_text()) + if payload.get('core', core) != core: + raise ValueError('Action file core differs from --core') + result = payload['engine_seed'], payload['actions'] + return (*result, payload.get('diy', {}), payload.get('setup_revision', 0)) if include_config else result + header = None + footer = None + actions = [] + setup_revision = 0 + with path.open() as stream: + for line in stream: + row = json.loads(line) + record = row.get('record', row) + if header is None: + header = record + if header.get('kind') != 'header' or header.get('schema') not in ( + 'arkguardrl/native-battle-replay-v1', 'arkguardrl/native-trajectory-v1', + 'stronghold-human-seat-trajectory/v1'): + raise ValueError('Unsupported trajectory header') + if header.get('core', core) != core: + raise ValueError('Trajectory core differs from --core') + if header.get('config', {}).get('difficulty', 'ABYSS') != 'ABYSS': + raise ValueError('Trajectory must use Desperation') + if header['schema'] == 'stronghold-human-seat-trajectory/v1': + if header.get('roomMode') != 'solo' or header.get('difficulty') != 'ABYSS': + raise ValueError('Human trajectory must use solo Desperation') + elif record.get('kind') == 'footer': + footer = record + elif record.get('kind') == 'action' and 'action' in record: + action = record['action'] + if header['schema'] == 'stronghold-human-seat-trajectory/v1': + if action['t'] == 'room.rerollSetup' and record.get('accepted') and not actions: + if action.get('setupRevision') != setup_revision: + raise ValueError('Nonsequential setup reroll') + setup_revision += 1 + continue + if record.get('accepted') is False: + continue + # Request correlation belongs to the live transport. + action = {key: value for key, value in action.items() if key != 'rid'} + if action['t'] in ('g.infoReady', 'g.unitStats'): + continue + if action['t'] == 'g.band': + if action['bandId'] != core: + raise ValueError('Recorded band differs from --core') + continue + actions.append(action) + if header is None or not actions: + raise ValueError('Trajectory omitted its header or actions') + if header['schema'] == 'stronghold-human-seat-trajectory/v1': + if not footer or footer.get('complete') is not True: + raise ValueError('Human trajectory did not complete its recording') + engine_seed = header.get('seed') + if type(engine_seed) is not int: + raise ValueError('Human trajectory omitted its original seed') + else: + engine_seed = (header['engine_seed'] if 'engine_seed' in header + else header['config']['seed']) + return (engine_seed, actions, header.get('diy', {}), header.get('setup_revision', setup_revision)) if include_config else (engine_seed, actions) + + +def record(session, engine_seed, actions, core, path, interval, max_bytes, diy=None, setup_revision=0): + total_bytes = frames = 0 + session.reset(engine_seed) + with path.open('xb') as stream: + def append(row): + nonlocal total_bytes + payload = (json.dumps(row, ensure_ascii=False, separators=(',', ':'), + allow_nan=False) + '\n').encode('utf-8') + if total_bytes + len(payload) > max_bytes: + raise RuntimeError('Replay byte limit reached before completion') + stream.write(payload) + total_bytes += len(payload) + + append(dict(kind='header', schema='arkguardrl/native-battle-replay-v1', + core=core, engine_seed=engine_seed, diy=diy or {}, setup_revision=setup_revision, tick_rate=30, + sample_ticks=interval, source='explicit-actions')) + append(dict(kind='state', state=json.loads(session.observation()))) + for index, action in enumerate(actions): + receipt = json.loads(session.step(json.dumps(action), 0)) + if not receipt['accepted']: + raise RuntimeError(f'Rejected replay action {index}: {receipt}') + append(dict(kind='action', index=index, action=action, receipt=receipt)) + while receipt['budgetExhausted']: + frame = json.loads(session.replay_frame()) + if frame is None: + raise RuntimeError('Suspended combat omitted its replay frame') + append(dict(kind='frame', **frame)) + frames += 1 + receipt = json.loads(session.advance(interval)) + append(dict(kind='state', state=json.loads(session.observation()))) + state = json.loads(session.observation()) + complete = state['personalEnded'] + summary = dict(kind='footer', status='complete' if complete else 'incomplete', + frames=frames, round=state['round'], outcome=state['outcome'], + diagnostics=json.loads(session.diagnostics())) + append(summary) + if not complete: + raise RuntimeError('Action sequence ended before the episode completed') + return summary + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--data-root', required=True) + parser.add_argument('--native-library', required=True) + parser.add_argument('--core', default='band_chen', choices=('band_chen', 'band_amiya', 'band_sarkazb', 'band_sciurus')) + parser.add_argument('--seed', type=int, default=42) + parser.add_argument('--actions', type=Path) + parser.add_argument('--require-victory', action='store_true') + parser.add_argument('--sample-ticks', type=int, default=3) + parser.add_argument('--max-bytes', type=int, default=128 << 20) + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--html', type=Path) + args = parser.parse_args() + if not 1 <= args.sample_ticks <= 30 or args.max_bytes <= 0: + parser.error('sample-ticks must be 1..30 and max-bytes must be positive') + if args.out.exists() or (args.html and args.html.exists()): + parser.error('Replay outputs must use new paths') + expected = None + diy = {} + setup_revision = 0 + if args.actions: + engine_seed, actions, diy, setup_revision = load_actions(args.actions, args.core, args.max_bytes, include_config=True) + else: + with ArkGuardNativeEnv(args.data_root, core=args.core, + native_library=args.native_library) as env: + engine_seed, actions, expected = pilot(env, args.seed, True) + native = load_native(args.native_library) + catalog = native.NativeCatalog(args.data_root, 64 << 20) + session = native.NativeSolo(catalog, args.core, diy_json=json.dumps(diy), setup_revision=setup_revision) + try: + summary = record(session, engine_seed, actions, args.core, args.out, + args.sample_ticks, args.max_bytes, diy, setup_revision) + if expected is not None and ending(json.loads(session.observation())) != expected: + raise RuntimeError('Frame capture changed the public terminal result') + finally: + session.close() + if args.html: + records = [json.loads(line) for line in args.out.read_text().splitlines()] + template = Path(__file__).with_suffix('.html').read_text() + data = json.dumps(records, ensure_ascii=False).replace('<', '\\u003c') + with args.html.open('x') as output: + output.write(template.replace('/*REPLAY_DATA*/ null', data)) + print(json.dumps(summary, ensure_ascii=False)) + if args.require_victory and (summary['outcome'] or {}).get('victory') is not True: + raise RuntimeError('Replay completed with a defeat; victory acceptance failed') + + +if __name__ == '__main__': + main() diff --git a/benchmarks/native_session.py b/benchmarks/native_session.py new file mode 100644 index 0000000..06d9f0b --- /dev/null +++ b/benchmarks/native_session.py @@ -0,0 +1,170 @@ +"""Single-env native/Gym throughput on identical, complete Desperation episodes.""" +import argparse +import json +from pathlib import Path +import platform +import statistics +import time + +try: + import resource +except ImportError: # Windows + resource = None + +from arkguardrl_core.native_env import load_native +from arkguardrl_core.native_gym import ArkGuardNativeEnv + +CORES = ('band_amiya', 'band_sarkazb', 'band_chen') + + +def peak_rss_bytes(): + """Peak resident set where the platform reports it, else current RSS.""" + if resource is not None: + scale = 1 if platform.system() == 'Darwin' else 1024 + return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * scale + import psutil + info = psutil.Process().memory_info() + return int(getattr(info, 'peak_wset', info.rss)) + + +def choose(env, roster, bought): + state = env._result.observation + own, actions = state['own'], env._decision.actions + for i, action in enumerate(actions): + if action['t'] == 'g.choice': + return i + if roster: + hand = {p['uid'] for p in own['hand'] if p and p['kind'] == 'chess'} + occupied = {(p['row'], p['col']) for p in own['board']} + moves = [(i, a) for i, a in enumerate(actions) if a['t'] == 'g.move' + and a['uid'] in hand and a['to']['area'] == 'board' and a.get('dir') == 'RIGHT' + and (a['to']['row'], a['to']['col']) not in occupied] + if moves and own['deployCount'] < own['deployCap']: + return max(moves, key=lambda x: (x[1]['to']['col'], x[1]['to']['row']))[0] + if state['round'] not in bought and None in own['hand']: + bought.add(state['round']) + for i, action in enumerate(actions): + if action['t'] == 'g.buy': + slot = own['shop']['slots'][action['slot']] + if slot and slot['kind'] == 'chess' and not slot['sold'] and slot['price'] <= own['funds']: + return i + return next(i for i, a in enumerate(actions) if a['t'] == 'g.ready') + + +def ending(state): + return {key: state[key] for key in ('round', 'own', 'outcome')} + + +def pilot(env, seed, roster, chooser=None): + _, info = env.reset(seed=seed) + engine_seed, actions, bought = info['engine_seed'], [], set() + for _ in range(150): + index = (chooser or choose)(env, roster, bought) + actions.append(env._decision.actions[index]) + _, _, terminated, truncated, info = env.step(index) + if truncated or not info.get('accepted'): + raise RuntimeError(f'Pilot did not execute a complete valid episode: {info}') + if terminated: + return engine_seed, actions, ending(env._result.observation) + raise RuntimeError('Pilot exceeded decision limit') + + +def measure(env, session, cases, cycles, backend): + durations, steps, ticks, candidate_max = [], 0, 0, 0 + phases = dict(engine_seconds=0., encoding_seconds=0., reward_seconds=0.) + reset_seconds = combat_seconds = step_seconds = 0. + for _ in range(cycles): + for seed, engine_seed, actions, expected in cases: + begin = time.perf_counter() + if backend == 'gym': + observation, info = env.reset(seed=seed) + candidate_max = max(candidate_max, info['candidate_count']) + else: + session.reset(engine_seed) + json.loads(session.observation()) + reset_seconds += time.perf_counter() - begin + for action in actions: + if backend == 'gym': + index = env._decision.actions.index(action) + start = time.perf_counter() + observation, _, terminated, truncated, info = env.step(index) + step_seconds += time.perf_counter() - start + if truncated or not info.get('accepted'): + raise RuntimeError('Rejected or truncated benchmark') + candidate_max = max(candidate_max, info['candidate_count']) + for key in phases: + phases[key] += info['timing'].get(key, 0.) + else: + start = time.perf_counter() + receipt = json.loads(session.step(json.dumps(action), 108000)) + elapsed = time.perf_counter() - start + step_seconds += elapsed + if not receipt['accepted'] or receipt['budgetExhausted']: + raise RuntimeError('Rejected or incomplete benchmark') + ticks += receipt['ticks'] + if receipt['ticks']: + combat_seconds += elapsed + state = json.loads(session.observation()) + steps += 1 + durations.append(time.perf_counter() - begin) + state = env._result.observation if backend == 'gym' else state + if not state['gameEnded'] or ending(state) != expected: + raise RuntimeError('Replay changed outcome or public terminal state') + seconds = sum(durations) + result = dict(episodes=len(durations), decisions=steps, seconds=seconds, + episodes_per_second=len(durations)/seconds, decisions_per_second=steps/seconds, + median_episode_ms=statistics.median(durations)*1000, + reset_seconds=reset_seconds, step_seconds=step_seconds) + if backend == 'gym': + result.update(phase_seconds=phases, candidate_max=candidate_max, + observation_bytes=sum(a.nbytes for a in observation.values())) + else: + result.update(combat_ticks=ticks, combat_step_seconds=combat_seconds, + combat_ticks_per_second=ticks/combat_seconds if combat_seconds else 0.) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--data-root', required=True) + parser.add_argument('--native-library', required=True) + parser.add_argument('--cycles', type=int, default=5) + parser.add_argument('--repeats', type=int, default=3) + parser.add_argument('--out', type=Path, required=True) + args = parser.parse_args() + if min(args.cycles, args.repeats) < 1: + parser.error('Positive cycles and repeats required') + native = load_native(args.native_library) + catalog = native.NativeCatalog(args.data_root, 64 << 20) + results = [] + startup = time.perf_counter() + for core in CORES: + session = native.NativeSolo(catalog, core) + with ArkGuardNativeEnv(args.data_root, core=core, native_library=args.native_library, + profile=True) as env: + for roster in (False, True): + cases = [(seed, *pilot(env, seed, roster)) for seed in (42, 99)] + # Warm both paths; data loading/compilation are outside steady-state metrics. + measure(env, session, cases, 1, 'native') + for backend in ('native', 'gym'): + runs = [measure(env, session, cases, args.cycles, backend) for _ in range(args.repeats)] + result = dict(core=core, workload='buy_deploy' if roster else 'empty', backend=backend, + terminal_rounds=[case[3]['round'] for case in cases], runs=runs, + median_decisions_per_second=statistics.median(r['decisions_per_second'] for r in runs), + median_episodes_per_second=statistics.median(r['episodes_per_second'] for r in runs)) + results.append(result) + print(json.dumps({k:v for k,v in result.items() if k != 'runs'}), flush=True) + session.close() + output = dict(platform=platform.platform(), python=platform.python_version(), + scope='Single env; no model, training or scheduling. Same actions and terminal states across backends.', + timing='Includes episode reset and action lookup; excludes initialization/pilot/terminal equality check.', + seeds=[42, 99], cycles=args.cycles, repeats=args.repeats, + wall_seconds=time.perf_counter()-startup, + peak_rss_bytes=peak_rss_bytes(), + results=results) + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(output, indent=2)+'\n') + + +if __name__ == '__main__': + main() diff --git a/benchmarks/native_slots/Cargo.lock b/benchmarks/native_slots/Cargo.lock new file mode 100644 index 0000000..6a0236e --- /dev/null +++ b/benchmarks/native_slots/Cargo.lock @@ -0,0 +1,267 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arkguard-engine" +version = "0.1.0" +dependencies = [ + "serde_json", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "indoc" +version = "2.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37b2691796cffeb8a8cd305ac66e65841559f147f4e63231d0eafa4db5384d1" +dependencies = [ + "rustversion", +] + +[[package]] +name = "itoa" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memchr" +version = "2.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "native_slots" +version = "0.0.0" +dependencies = [ + "arkguard-engine", + "pyo3", + "pyo3-build-config", + "serde", + "serde_json", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pyo3" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab53c047fcd1a1d2a8820fe84f05d6be69e9526be40cb03b73f86b6b03e6d87d" +dependencies = [ + "indoc", + "libc", + "memoffset", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", + "unindent", +] + +[[package]] +name = "pyo3-build-config" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b455933107de8642b4487ed26d912c2d899dec6114884214a0b3bb3be9261ea6" +dependencies = [ + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c85c9cbfaddf651b1221594209aed57e9e5cff63c4d11d1feead529b872a089" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a5b10c9bf9888125d917fb4d2ca2d25c8df94c7ab5a52e13313a07e050a3b02" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03b51720d314836e53327f5871d4c0cfb4fb37cc2c4a11cc71907a86342c40f9" +dependencies = [ + "heck", + "proc-macro2", + "pyo3-build-config", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unindent" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3" + +[[package]] +name = "zmij" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd8f3f50b848df28f887acb68e41201b5aea6bc8a8dacc00fb40635ff9a72fea" diff --git a/benchmarks/native_slots/Cargo.toml b/benchmarks/native_slots/Cargo.toml new file mode 100644 index 0000000..f23bfbc --- /dev/null +++ b/benchmarks/native_slots/Cargo.toml @@ -0,0 +1,27 @@ +[workspace] + +# Isolated experiment crate: it must not join the repository workspace, so it +# keeps its own lock and can be built by CI on the same branch. +[package] +name = "native_slots" +version = "0.0.0" +edition = "2021" +license = "GPL-3.0-or-later" +publish = false + +[lib] +name = "_native_slots" +crate-type = ["cdylib"] + +[dependencies] +arkguard-engine = { path = "../../crates/engine" } +pyo3 = { version = "=0.27.2", features = ["extension-module"] } +serde_json = "=1.0.149" +serde = { version = "=1.0.228", features = ["derive"] } + +[build-dependencies] +pyo3-build-config = "=0.27.2" + +[profile.release] +lto = "thin" +codegen-units = 1 diff --git a/benchmarks/native_slots/build.rs b/benchmarks/native_slots/build.rs new file mode 100644 index 0000000..dace4a9 --- /dev/null +++ b/benchmarks/native_slots/build.rs @@ -0,0 +1,3 @@ +fn main() { + pyo3_build_config::add_extension_module_link_args(); +} diff --git a/benchmarks/native_slots/src/batch.rs b/benchmarks/native_slots/src/batch.rs new file mode 100644 index 0000000..06c5369 --- /dev/null +++ b/benchmarks/native_slots/src/batch.rs @@ -0,0 +1,424 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Ordered native slots. All engine work and numeric encoding run without the GIL. +use crate::{policy::PolicyEncoder, NativeCatalog}; +use arkguard_engine::{ + data::Catalog, + solo::session::{Session, MAX_TICK_BUDGET}, +}; +use pyo3::{ + exceptions::{PyRuntimeError, PyValueError}, + prelude::*, + types::PyBytes, +}; +use std::sync::Arc; + +type Result = std::result::Result; +type Wire = (Vec, Vec, Vec, Vec); +type PolicyBytes<'py> = ( + Vec>, + Vec>, + Vec>, + Vec>, +); + +struct Episode { + session: Session, + ledger: Option, + domain: Option, +} + +/// Join every worker, including after errors; flatten chunks in slot order. +/// Workers never share mutable slots and may not stop other slots on failure. +fn parallel(items: &mut [T], threads: usize, f: F) -> Vec> +where + F: Fn(&mut T, usize) -> Result + Sync, +{ + let total = items.len(); + let chunk_size = total.div_ceil(threads); + std::thread::scope(|scope| { + let mut workers = Vec::new(); + for (chunk_index, chunk) in items.chunks_mut(chunk_size).enumerate() { + let f = &f; + let start = chunk_index * chunk_size; + let len = chunk.len(); + workers.push(( + len, + scope.spawn(move || { + chunk + .iter_mut() + .enumerate() + .map(|(i, item)| f(item, start + i)) + .collect::>() + }), + )); + } + let mut results = Vec::with_capacity(total); + for (len, worker) in workers { + match worker.join() { + Ok(chunk) => results.extend(chunk), + Err(_) => { + results.extend((0..len).map(|_| Err("Native batch worker panicked".into()))) + } + } + } + results + }) +} + +fn live(episode: &mut Option) -> Result<&mut Episode> { + episode.as_mut().ok_or_else(|| "Reset required".into()) +} +fn runtime(results: Vec>) -> PyResult> { + results + .into_iter() + .enumerate() + .map(|(slot, result)| { + result.map_err(|error| PyRuntimeError::new_err(format!("Slot {slot}: {error}"))) + }) + .collect() +} +fn f32_bytes(values: &[f32]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} +fn i64_bytes(values: &[i64]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() +} + +#[pyclass] +pub struct NativeBatch { + data: Arc, + cores: Vec, + banned: Vec>, + threads: usize, + episodes: Vec>, + policy: Option>, + policy_token: u64, +} +impl NativeBatch { + fn length(&self, len: usize, name: &str) -> PyResult<()> { + if len != self.episodes.len() { + return Err(PyValueError::new_err(format!( + "{name} length must equal slot count" + ))); + } + Ok(()) + } +} + +#[pymethods] +impl NativeBatch { + #[new] + fn new( + catalog: &NativeCatalog, + cores: Vec, + banned: Vec>, + threads: usize, + ) -> PyResult { + if !(1..=64).contains(&cores.len()) { + return Err(PyValueError::new_err("Slot count must be in 1..=64")); + } + if cores.len() != banned.len() { + return Err(PyValueError::new_err( + "Cores and bans must have equal lengths", + )); + } + if !(1..=cores.len()).contains(&threads) { + return Err(PyValueError::new_err("Threads must be in 1..=slot count")); + } + if cores.iter().any(|core| { + !matches!( + core.as_str(), + "band_amiya" | "band_sarkazb" | "band_chen" | "band_sciurus" + ) + }) { + return Err(PyValueError::new_err("Unsupported core")); + } + if banned + .iter() + .any(|bans| bans.len() > 4096 || bans.iter().any(|id| id.len() > 256)) + { + return Err(PyValueError::new_err("Manual bans exceed capacity")); + } + let episodes = (0..cores.len()).map(|_| None).collect(); + Ok(Self { + data: Arc::clone(&catalog.inner), + cores, + banned, + threads, + episodes, + policy: None, + policy_token: 0, + }) + } + + /// Commit selected episodes only after every selected initialization succeeds. + fn reset_decision_all( + &mut self, + py: Python<'_>, + seeds: Vec>, + streams: Vec>, + ) -> PyResult>> { + self.length(seeds.len(), "Seeds")?; + self.length(streams.len(), "Streams")?; + if seeds.iter().zip(&streams).any(|(seed, stream)| { + seed.is_some() != stream.is_some() || stream.as_ref().is_some_and(|s| s.len() != 32) + }) { + return Err(PyValueError::new_err( + "One progress stream per reset slot required", + )); + } + if seeds + .iter() + .zip(&self.episodes) + .any(|(seed, episode)| seed.is_none() && episode.is_none()) + { + return Err(PyValueError::new_err( + "Initial reset requires a seed for every slot", + )); + } + for (episode, seed) in self.episodes.iter_mut().zip(&seeds) { + if seed.is_some() { + *episode = None; + } + } + let data = &self.data; + let cores = &self.cores; + let banned = &self.banned; + let initialized = runtime(py.detach(|| { + parallel(&mut self.episodes, self.threads, |episode, slot| { + let Some(seed) = seeds[slot] else { + live(episode)?; + return Ok(None); + }; + let session = Session::new(Arc::clone(data), seed, &cores[slot], &banned[slot])?; + let state = Arc::new(session.observation()?); + let mut ledger = crate::ledger::DecisionLedger::new( + state, + streams[slot].as_ref().unwrap().clone(), + )?; + let snapshot = ledger.snapshot(None, None, 0)?; + Ok(Some(( + Episode { + session, + ledger: Some(ledger), + domain: None, + }, + snapshot, + ))) + }) + }))?; + let mut snapshots = Vec::with_capacity(initialized.len()); + for (target, initialized) in self.episodes.iter_mut().zip(initialized) { + snapshots.push(match initialized { + Some((episode, snapshot)) => { + *target = Some(episode); + Some(snapshot) + } + None => None, + }); + } + Ok(snapshots) + } + + fn step_index_all( + &mut self, + py: Python<'_>, + revisions: Vec, + tokens: Vec, + indices: Vec>, + tick_budget: usize, + max_advances: Vec, + ) -> PyResult>> { + self.length(revisions.len(), "Revisions")?; + self.length(tokens.len(), "Candidate tokens")?; + self.length(indices.len(), "Indices")?; + self.length(max_advances.len(), "Max advances")?; + if !(1..=MAX_TICK_BUDGET).contains(&tick_budget) { + return Err(PyValueError::new_err("Invalid decision tick budget")); + } + // Validate the whole selection vector before any slot advances. + let actions = self + .episodes + .iter() + .enumerate() + .map(|(slot, episode)| { + let Some(index) = indices[slot] else { + return Ok(None); + }; + let domain = episode + .as_ref() + .and_then(|e| e.domain.as_ref()) + .ok_or_else(|| { + PyValueError::new_err("Build a native candidate domain before stepping") + })?; + domain + .selected(revisions[slot], tokens[slot], index) + .map(Some) + .map_err(PyValueError::new_err) + }) + .collect::>>()?; + runtime(py.detach(|| { + parallel(&mut self.episodes, self.threads, |episode, slot| { + let Some(action) = &actions[slot] else { + return Ok(None); + }; + let episode = live(episode)?; + episode.domain = None; + let mut ledger = episode + .ledger + .take() + .ok_or("Reset a decision session before stepping")?; + let result = ledger.step( + &mut episode.session, + action, + tick_budget, + max_advances[slot], + )?; + episode.ledger = Some(ledger); + Ok(Some(result)) + }) + })) + } + + fn build_current_policy_all<'py>( + &mut self, + py: Python<'py>, + revisions: Vec, + ) -> PyResult<(Vec, Vec, PolicyBytes<'py>)> { + self.length(revisions.len(), "Revisions")?; + let policy = self + .policy + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("Configure policy before numeric encoding"))?; + let token = self.policy_token; + self.policy_token = token + .checked_add(self.episodes.len() as u64) + .ok_or_else(|| PyRuntimeError::new_err("Candidate token overflow"))?; + let results = py.detach(|| { + parallel(&mut self.episodes, self.threads, |episode, slot| { + let episode = live(episode)?; + let ledger = episode + .ledger + .as_ref() + .ok_or("Reset a decision session before encoding")?; + if ledger.state["revision"].as_u64() != Some(revisions[slot]) { + return Err("Numeric observation revision mismatch".into()); + } + episode.domain = None; + let actions = policy.current_candidates( + &ledger.state, + &ledger.policy_history, + &ledger.blocked, + )?; + let encoded = policy.encode(&ledger.state, &ledger.policy_history, &actions)?; + let json = serde_json::to_string(&actions).map_err(|e| e.to_string())?; + let token = token + slot as u64 + 1; + episode.domain = Some(crate::ledger::PolicyDomain { + revision: revisions[slot], + token, + actions, + }); + Ok(( + token, + json, + ( + f32_bytes(&encoded.observation), + f32_bytes(&encoded.candidates), + i64_bytes(&encoded.schedules), + i64_bytes(&encoded.experts), + ), + )) + }) + }); + let mut tokens = Vec::with_capacity(results.len()); + let mut actions = Vec::with_capacity(results.len()); + let mut buffers = Vec::with_capacity(results.len()); + for (slot, result) in results.into_iter().enumerate() { + let (token, json, wire) = + result.map_err(|e| PyValueError::new_err(format!("Slot {slot}: {e}")))?; + tokens.push(token); + actions.push(json); + buffers.push(wire); + } + Ok((tokens, actions, policy_bytes(py, buffers))) + } + + fn public_spatial_all(&mut self, py: Python<'_>) -> PyResult>> { + runtime(py.detach(|| { + parallel(&mut self.episodes, self.threads, |episode, _| { + let session = &live(episode)?.session; + if session.status()?["decisionRequired"] != true { + return Ok(None); + } + session.public_spatial_json().map(Some) + }) + })) + } + + fn public_spatial_updates( + &mut self, + py: Python<'_>, + revisions: Vec, + keys: Vec>, + ) -> PyResult, String)>>> { + self.length(revisions.len(), "Revisions")?; + self.length(keys.len(), "Geometry keys")?; + if keys.iter().flatten().any(|key| key.len() > 8 << 20) { + return Err(PyValueError::new_err( + "Public spatial key exceeds byte limit", + )); + } + runtime(py.detach(|| { + parallel(&mut self.episodes, self.threads, |episode, slot| { + let session = &live(episode)?.session; + let status = session.status()?; + if status["revision"].as_u64() != Some(revisions[slot]) { + return Err("Public spatial revision mismatch".into()); + } + if status["decisionRequired"] != true { + return Ok(None); + } + session + .public_spatial_update(keys[slot].as_deref()) + .map(Some) + }) + })) + } + + fn configure_policy(&mut self, py: Python<'_>, metadata_json: &[u8]) -> PyResult<()> { + if metadata_json.len() > 8 << 20 { + return Err(PyValueError::new_err("Policy metadata exceeds byte limit")); + } + let encoder = py + .detach(|| { + let metadata = serde_json::from_slice(metadata_json).map_err(|e| e.to_string())?; + PolicyEncoder::new(&metadata) + }) + .map_err(PyValueError::new_err)?; + self.policy = Some(Arc::new(encoder)); + for episode in self.episodes.iter_mut().flatten() { + episode.domain = None; + } + Ok(()) + } + + fn close(&mut self) { + for episode in &mut self.episodes { + *episode = None; + } + } +} + +fn policy_bytes<'py>(py: Python<'py>, results: Vec) -> PolicyBytes<'py> { + let mut observations = Vec::with_capacity(results.len()); + let mut candidates = Vec::with_capacity(results.len()); + let mut schedules = Vec::with_capacity(results.len()); + let mut experts = Vec::with_capacity(results.len()); + for (observation, candidate, schedule, expert) in results { + observations.push(PyBytes::new(py, &observation)); + candidates.push(PyBytes::new(py, &candidate)); + schedules.push(PyBytes::new(py, &schedule)); + experts.push(PyBytes::new(py, &expert)); + } + (observations, candidates, schedules, experts) +} diff --git a/benchmarks/native_slots/src/lib.rs b/benchmarks/native_slots/src/lib.rs new file mode 100644 index 0000000..8110b5f --- /dev/null +++ b/benchmarks/native_slots/src/lib.rs @@ -0,0 +1,53 @@ +//! Parallel decision slots sharing the single-session ledger and policy encoder. +use arkguard_engine::data::Catalog; +use pyo3::{exceptions::PyValueError, prelude::*}; +use std::sync::Arc; +mod batch; +#[path = "../../../crates/python/src/candidates.rs"] +mod candidates; +#[path = "../../../crates/python/src/ledger.rs"] +mod ledger; +#[path = "../../../crates/python/src/policy.rs"] +mod policy; + +#[pyclass(frozen)] +pub(crate) struct NativeCatalog { + inner: Arc, +} +#[pymethods] +impl NativeCatalog { + #[new] + fn new(py: Python<'_>, data_root: String, max_bytes: usize) -> PyResult { + py.detach(|| Catalog::load(std::path::Path::new(&data_root), max_bytes)) + .map(|inner| Self { + inner: Arc::new(inner), + }) + .map_err(PyValueError::new_err) + } + fn public_tables(&self, py: Python<'_>) -> String { + py.detach(|| { + let mut out = serde_json::Map::new(); + for name in [ + "bands", + "chess", + "items", + "tokens", + "config", + "bonds", + "garrisons", + "enemies", + "choices", + "effects", + ] { + out.insert(name.into(), self.inner.table(name).unwrap().clone()); + } + serde_json::Value::Object(out).to_string() + }) + } +} +#[pymodule] +fn _native_slots(m: &Bound<'_, PyModule>) -> PyResult<()> { + m.add_class::()?; + m.add_class::()?; + Ok(()) +} diff --git a/benchmarks/node_bridge.py b/benchmarks/node_bridge.py new file mode 100644 index 0000000..9732762 --- /dev/null +++ b/benchmarks/node_bridge.py @@ -0,0 +1,61 @@ +"""Bounded JSON client for the original Node performance baseline.""" +import json +from pathlib import Path +import selectors +import subprocess + +class Oracle: + def __init__(self, root, data_dir=None): + self.root = root + self.data_dir = data_dir + + def __enter__(self): + bridge = Path(__file__).with_name('node_session.mjs') + args = ['node', str(bridge), self.root] + if self.data_dir: + args.append(str(self.data_dir)) + self.process = subprocess.Popen(args, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1) + self.selector = selectors.DefaultSelector() + self.selector.register(self.process.stdout, selectors.EVENT_READ) + return self + + def call(self, **command): + self.process.stdin.write(json.dumps(command) + '\n') + self.process.stdin.flush() + if not self.selector.select(30): + raise TimeoutError('Original runtime did not reply within 30 seconds') + line = self.process.stdout.readline() + if not line: + raise RuntimeError('Original runtime exited: ' + self.process.stderr.read(2000)) + reply = json.loads(line) + if not reply.get('ok'): + raise RuntimeError(reply) + if reply.get('truncated'): + raise RuntimeError('Original runtime exhausted its callback budget') + return reply + + def __exit__(self, *_): + self.selector.close() + self.process.stdin.close() + try: + self.process.wait(timeout=3) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait() + self.process.stdout.close() + self.process.stderr.close() + +def compare_public(actual, expected, path="terminal"): + if isinstance(actual, dict): + for key, value in actual.items(): + if key not in expected: + raise RuntimeError(f"Missing {path}.{key}") + compare_public(value, expected[key], path+"."+key) + elif isinstance(actual, list): + if len(actual) != len(expected): + raise RuntimeError(f"Length mismatch: {path}") + for i, (a, b) in enumerate(zip(actual, expected)): + compare_public(a, b, f"{path}[{i}]") + elif actual != expected: + raise RuntimeError(f"Replay mismatch: {path}: {actual!r} != {expected!r}") diff --git a/benchmarks/node_compare.py b/benchmarks/node_compare.py new file mode 100644 index 0000000..03e6b37 --- /dev/null +++ b/benchmarks/node_compare.py @@ -0,0 +1,67 @@ +"""Paired single-env benchmark using the original-runtime JSON bridge.""" +import argparse +import sys, json, time, statistics +from pathlib import Path +repo=Path(__file__).resolve().parents[1] +parser=argparse.ArgumentParser(description=__doc__) +parser.add_argument('--reference-root', required=True) +parser.add_argument('--native-library', required=True) +parser.add_argument('--out', type=Path, required=True) +args=parser.parse_args() +sys.path.insert(0,str(repo/'benchmarks')) +import native_session as b +import node_bridge as ref +reference_root=str(Path(args.reference_root).resolve()) +native=b.load_native(args.native_library) +catalog=native.NativeCatalog(reference_root+'/data',64<<20) +def normalize(x): + if isinstance(x,dict):return {k:normalize(v) for k,v in x.items()} + if isinstance(x,list):return [normalize(v) for v in x] + return 'solo' if x=='agent' else x + +def node_run(oracle,cases,cycles,core): + durations=[];steps=0 + for _ in range(cycles): + for _,seed,actions,expected in cases: + start=time.perf_counter() + oracle.call(cmd='reset',seed=seed,difficulty='ABYSS') + oracle.call(cmd='step',action={'t':'g.infoReady'}) + oracle.call(cmd='step',action={'t':'g.band','bandId':core}) + for action in actions: + reply=oracle.call(cmd='step',action=action) + if not reply.get('accepted'):raise RuntimeError(reply) + state=reply['state'];steps+=1 + for _ in range(100): + if state['gameEnded']:break + state=oracle.call(cmd='advance',maxSteps=4096)['state'] + durations.append(time.perf_counter()-start) + if not state['gameEnded']:raise RuntimeError('Not terminal') + ref.compare_public(expected,normalize(b.ending(state))) + seconds=sum(durations) + return dict(seconds=seconds,episodes=len(durations),decisions=steps,episodes_per_second=len(durations)/seconds,decisions_per_second=steps/seconds) + +rows=[] +for core in b.CORES: + session=native.NativeSolo(catalog,core) + with b.ArkGuardNativeEnv(reference_root+'/data',core=core,native_library=args.native_library,profile=True) as env, ref.Oracle(reference_root) as oracle: + oracle.call(cmd='identity') + for roster in (False,True): + cases=[(seed,*b.pilot(env,seed,roster)) for seed in (42,99)] + b.measure(env,session,cases,2,'native') + node_run(oracle,cases,2,core) + runs={'native':[],'node':[]} + for repeat in range(3): + # Alternate order to reduce systematic warmup/thermal bias. + for backend in (('native','node') if repeat%2==0 else ('node','native')): + r=b.measure(env,session,cases,5,'native') if backend=='native' else node_run(oracle,cases,5,core) + runs[backend].append(r) + row=dict(core=core,workload='buy_deploy' if roster else 'empty',runs=runs) + for backend in runs: + row[backend+'_episodes_per_second']=statistics.median(r['episodes_per_second'] for r in runs[backend]) + row['speedup']=row['native_episodes_per_second']/row['node_episodes_per_second'] + rows.append(row) + print(json.dumps({k:v for k,v in row.items() if k!='runs'}),flush=True) + session.close() +out=dict(note='Same engine seeds and actions, terminal public subset checked. Warm persistent Node Match JSON bridge vs native PyO3 JSON session; excludes startup and pilot, includes reset and public observations. No Gym encoding in either timed path.',results=rows) +args.out.parent.mkdir(parents=True,exist_ok=True) +args.out.write_text(json.dumps(out,indent=2)+'\n') diff --git a/tools/reference/session.mjs b/benchmarks/node_session.mjs similarity index 88% rename from tools/reference/session.mjs rename to benchmarks/node_session.mjs index afa0c43..32d0912 100644 --- a/tools/reference/session.mjs +++ b/benchmarks/node_session.mjs @@ -2,34 +2,21 @@ import fs from 'node:fs'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; -import { execFileSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; import readline from 'node:readline'; if (Number(process.versions.node.split('.')[0]) < 22) throw new Error('Node 22+ required'); -const REVISION = '41bbca5712ac08394bbc4d5b4e3411c6be1634b6'; const SCHEMA = 'arkguardrl/native-session-v2'; const PLAYER = 'agent'; const root = fs.realpathSync(process.argv[2]); -const git = (...args) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim(); -if (git('rev-parse', 'HEAD') !== REVISION) throw new Error('Expected frozen 0.3.3 engine revision'); -if (git('status', '--porcelain', '--untracked-files=all')) throw new Error('Engine checkout must be clean'); const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); -if (pkg.version !== '0.3.3') throw new Error('Expected engine app version 0.3.3'); -const digest = createHash('sha256'); -for (const name of fs.readdirSync(path.join(root, 'data')).filter(n => n.endsWith('.json')).sort()) { - digest.update(name + '\0'); - digest.update(fs.readFileSync(path.join(root, 'data', name))); - digest.update('\0'); -} -const identity = { schema: SCHEMA, engineRevision: REVISION, appVersion: pkg.version, dataSha256: digest.digest('hex') }; +const identity = { schema: SCHEMA, appVersion: pkg.version }; const imp = rel => import(pathToFileURL(path.join(root, rel)).href); -const [{ Match }, { VirtualScheduler }, { getData, DATA_FILES }, protocol, constants] = await Promise.all([ +const [{ Match }, { VirtualScheduler }, { getData, loadData, DATA_FILES }, protocol, constants] = await Promise.all([ imp('server/match/Match.js'), imp('server/match/scheduler.js'), imp('server/data.js'), imp('shared/protocol.js'), imp('shared/constants.js'), ]); const quiet = { info() {}, debug() {}, warn() {}, error() {} }; -const data = getData({ log: quiet }); +const data = process.argv[3] ? loadData(fs.realpathSync(process.argv[3]), { log: quiet }) : getData({ log: quiet }); for (const key of DATA_FILES) { if (!data[key] || !Object.keys(data[key]).length) throw new Error(`Missing or empty engine data: ${key}`); } @@ -103,9 +90,15 @@ function dispatch(req) { try { match = new Match({ roomCode: 'ARKGUARD', seed, mode: 'solo', difficulty, data, scheduler, clientCombat: false, botRehearsal: 0, botRehearsalDelegate: false, - seats: [{ seat: 0, playerId: PLAYER, name: 'Agent', isBot: false, connected: true }], + seats: [{ seat: 0, playerId: PLAYER, name: 'Agent', isBot: false, connected: true, diy: req.diy ?? {} }], send() { return true; }, broadcast() {}, onEnd(result) { summary = result; }, log: quiet }); match.start(); + const setupRevision = req.setup_revision ?? 0; + if (!Number.isInteger(setupRevision) || setupRevision < 0 || setupRevision > 256) throw new Error('Invalid setup revision'); + for (let i = 0; i < setupRevision; i++) { + const reroll = match.requestSetupReroll(PLAYER, i); + if (!reroll?.ok) throw new Error('Setup reroll rejected'); + } return stateReply(); } catch (err) { close(); throw err; } } diff --git a/benchmarks/oracle_identity.py b/benchmarks/oracle_identity.py new file mode 100644 index 0000000..9721930 --- /dev/null +++ b/benchmarks/oracle_identity.py @@ -0,0 +1,530 @@ +#!/usr/bin/env python3 +"""Temporary byte-equivalence oracle for crates/engine/src/identity.rs. + +Builds a throwaway crate outside the repository (identity.rs is included with +#[path], so lib.rs does not need to register it yet), replays values collected +from real ArkGuardNativeEnv episodes plus handwritten and fuzzed boundaries, +and compares every result against arkguardrl.contracts. + +Run with an environment that has the project's [gym] extras installed, e.g.: + + python benchmarks/oracle_identity.py --data-root ../ArkGuardRL/game/data + +--no-real skips episode collection and checks only handwritten/fuzzed samples. +The script writes nothing inside the repository. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import shutil +import struct +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +RUNNER_SOURCE = r'''#[path = __IDENTITY_PATH__] +mod identity; + +use std::io::{self, BufRead, Write}; + +fn hex(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for &byte in bytes { + out.push(DIGITS[(byte >> 4) as usize] as char); + out.push(DIGITS[(byte & 0x0f) as usize] as char); + } + out +} + +fn main() { + let stdin = io::stdin(); + let mut out = io::BufWriter::new(io::stdout().lock()); + for line in stdin.lock().lines() { + let line = match line { + Ok(line) => line, + Err(_) => break, + }; + if line.trim().is_empty() { + continue; + } + let request: serde_json::Value = serde_json::from_str(&line).expect("request JSON"); + let op = request[0].as_str().expect("op"); + let value = &request[1]; + let body = match op { + "canonical" => identity::canonical(value) + .map(|bytes| format!("{{\"hex\":\"{}\"}}", hex(&bytes))), + "fingerprint" => identity::fingerprint(value) + .map(|text| format!("{{\"fp\":\"{}\"}}", text)), + "action" => identity::action_id(value) + .map(|text| format!("{{\"fp\":\"{}\"}}", text)), + "decision" => identity::decision_id(value) + .map(|text| format!("{{\"fp\":\"{}\"}}", text)), + other => Err(format!("unknown op: {}", other)), + }; + match body { + Ok(text) => writeln!(out, "{}", text).expect("stdout"), + Err(error) => writeln!( + out, + "{{\"error\":{}}}", + serde_json::to_string(&error).expect("error JSON") + ) + .expect("stdout"), + } + } + out.flush().expect("flush"); +}''' + + +def build_runner(root, keep=False): + """Compile identity.rs with serde_json into a standalone JSONL filter.""" + build = Path(tempfile.mkdtemp(prefix="arkguard-identity-")) + source = RUNNER_SOURCE.replace("__IDENTITY_PATH__", json.dumps(str(root / "crates/engine/src/identity.rs"))) + (build / "src").mkdir() + (build / "Cargo.toml").write_text( + "[package]\nname = \"identity-oracle\"\nversion = \"0.0.0\"\nedition = \"2021\"\n" + "[dependencies]\n" + "serde_json = { version = \"=1.0.149\", features = [\"preserve_order\", \"float_roundtrip\"] }\n", + encoding="utf-8", + ) + (build / "src/main.rs").write_text(source, encoding="utf-8") + environment = os.environ.copy() + environment["CARGO_TARGET_DIR"] = str(build / "target") + command = ["cargo", "build", "--release", "--quiet"] + for extra in (["--offline"], []): + result = subprocess.run(command + extra, cwd=build, env=environment, + capture_output=True, text=True) + if result.returncode == 0: + break + else: + raise SystemExit(f"cargo build failed:\n{result.stdout}\n{result.stderr}") + binary = build / "target/release/identity-oracle" + if not binary.exists(): + raise SystemExit(f"missing built runner at {binary}") + return binary, (None if keep else build) + + +def run_rust(binary, requests): + """One subprocess for all requests; returns one parsed response per request.""" + payload = "\n".join( + json.dumps([request["op"], request["value"]], ensure_ascii=False, + separators=(",", ":"), allow_nan=False) + for request in requests + ) + "\n" + result = subprocess.run([str(binary)], input=payload, capture_output=True, + text=True, timeout=600) + if result.returncode != 0: + raise SystemExit(f"runner failed ({result.returncode}):\n{result.stderr[-4000:]}") + lines = result.stdout.splitlines() + if len(lines) != len(requests): + raise SystemExit(f"runner returned {len(lines)} lines for {len(requests)} requests") + return [json.loads(line) for line in lines] + + +def python_result(request): + from arkguardrl import contracts + try: + if request["op"] == "canonical": + return {"hex": contracts.canonical(request["value"]).hex()} + if request["op"] == "fingerprint": + return {"fp": contracts.fingerprint(request["value"])} + if request["op"] == "action": + return {"fp": contracts.action_id(request["value"])} + if request["op"] == "decision": + return {"fp": contracts.decision_id(request["value"])} + raise ValueError(request["op"]) + except Exception as exc: # ValueError/KeyError/TypeError are expected refusals + return {"error": True, "detail": f"{type(exc).__name__}: {exc}"} + + +def add(requests, seen, label, op, value, group, known=False): + key = (op, json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))) + if key in seen: + return False + seen.add(key) + requests.append({"label": label, "op": op, "value": value, "group": group, + "known": known}) + return True + + +def int_bounds(value, low=None, high=None, floats=None): + """Track the integer range and float presence of collected JSON.""" + if isinstance(value, bool): + return low, high, floats + if isinstance(value, int): + low = value if low is None else min(low, value) + high = value if high is None else max(high, value) + elif isinstance(value, float): + floats = floats + 1 + elif isinstance(value, list): + for item in value: + low, high, floats = int_bounds(item, low, high, floats) + elif isinstance(value, dict): + for item in value.values(): + low, high, floats = int_bounds(item, low, high, floats) + return low, high, floats + + +def choose(environment, step, rng): + """Deterministic pilot: rounds, legal placements, buys, then filler moves.""" + actions = environment._decision.actions + own = environment._result.observation["own"] + if step < 150: + if step % 4 == 0: + for index, action in enumerate(actions): + if action["t"] == "g.choice": + return index + hand = {piece["uid"] for piece in own["hand"] if piece and piece["kind"] == "chess"} + occupied = {(piece["row"], piece["col"]) for piece in own["board"]} + moves = [(index, action) for index, action in enumerate(actions) + if action["t"] == "g.move" and action["uid"] in hand + and action["to"]["area"] == "board" and action.get("dir") == "RIGHT" + and (action["to"]["row"], action["to"]["col"]) not in occupied] + if moves and own["deployCount"] < own["deployCap"]: + return rng.choice(moves)[0] + if step % 3 == 0: + for index, action in enumerate(actions): + if action["t"] == "g.buy": + slot = own["shop"]["slots"][action["slot"]] + if slot and slot["kind"] == "chess" and not slot["sold"] \ + and slot["price"] <= own["funds"]: + return index + pool = [index for index, action in enumerate(actions) if action["t"] != "g.ready"] + if pool: + return rng.choice(pool) + return next(index for index, action in enumerate(actions) if action["t"] == "g.ready") + + +def collect_real(requests, seen, data_root, library, seeds, max_steps): + from arkguardrl_core.native_gym import ArkGuardNativeEnv + + states = actions = unique_actions = 0 + low = high = None + floats = 0 + per_seed = [] + for seed in seeds: + rng = random.Random(seed) + environment = ArkGuardNativeEnv(data_root, core="band_chen", + native_library=library) + episodes_states = episodes_actions = 0 + try: + environment.reset(seed=seed) + for step in range(max_steps): + state = environment._result.observation + if state["decisionRequired"] and not state["personalEnded"]: + episodes_states += 1 + low, high, floats = int_bounds(state, low, high, floats) + add(requests, seen, f"state seed={seed} step={step}", "canonical", + state, "real state") + add(requests, seen, f"state seed={seed} step={step}", "fingerprint", + state, "real state") + add(requests, seen, f"state seed={seed} step={step}", "decision", + state, "real state") + for index, action in enumerate(environment._decision.actions): + episodes_actions += 1 + low, high, floats = int_bounds(action, low, high, floats) + label = f"action seed={seed} step={step} #{index}" + if add(requests, seen, label, "action", action, "real action"): + unique_actions += 1 + add(requests, seen, label, "canonical", action, "real action bytes") + add(requests, seen, label, "fingerprint", action, "real action fingerprint") + else: + # Check every candidate occurrence, even repeated intents. + for op, group in (("action", "real action"), + ("canonical", "real action bytes"), + ("fingerprint", "real action fingerprint")): + requests.append({"label": label, "op": op, "value": action, + "group": group, "known": False}) + if not environment._decision or not environment._decision.actions: + break + _, _, terminated, truncated, _ = environment.step(choose(environment, step, rng)) + if terminated or truncated: + break + finally: + environment.close() + states += episodes_states + actions += episodes_actions + per_seed.append((seed, episodes_states, episodes_actions)) + return states, actions, unique_actions, per_seed, (low, high, floats) + + +def manual_samples(requests, seen): + values = [ + ({"t": "g.move", "uid": 7, "to": {"area": "board", "row": 9, "col": 2}, + "dir": "RIGHT"}, "fast board move"), + ({"t": "g.move", "uid": 7, "to": {"area": "hand", "idx": 3}}, "fast hand move"), + ({"t": "g.move", "uid": 7, "to": {"area": "board", "row": 9, "col": 2}, + "dir": "RIGHT", "x": 1}, "board move with extra field"), + ({"t": "g.move", "uid": True, "to": {"area": "board", "row": 9, "col": 2}, + "dir": "RIGHT"}, "board move bool uid"), + ({"t": "g.move", "uid": 7, "to": {"area": "board", "row": 9.0, "col": 2}, + "dir": "RIGHT"}, "board move float row"), + ({"t": "g.move", "uid": 7, "to": {"area": "board", "row": 9, "col": 2}, + "dir": "R" * 257}, "board move long dir"), + ({"t": "g.move", "uid": 7, "to": {"area": "hand", "idx": 3, "x": 0}}, + "hand move extra field"), + ({"t": "g.move", "uid": 7, "to": {"area": "temp", "idx": 3}}, "unknown move area"), + ({"t": "g.buy", "slot": 1}, "buy"), + ({"t": "g.buy", "slot": 1.0}, "buy float slot"), + ({"t": "g.buy", "slot": [1]}, "buy list slot"), + ({"t": "g.buy", "slot": 1, "名": "值"}, "buy unicode field"), + ({"t": "x.unknown", "a": 1}, "unknown t"), + ({"t": "g.buy", "slot": 1, **{f"k{i}": i for i in range(15)}}, "17-key action"), + ({"t": "g.buy", "slot": 1, **{f"k{i}": i for i in range(14)}}, "16-key action"), + ({"t": "g.buy", "slot": 1, "k" * 300: 1}, "long action key"), + ({"t": "g.buy", "slot": 1, "deep": {"a": {"b": {"c": 1}}}}, "depth-3 action"), + ({"t": "g.buy", "slot": 1, "deep": {"a": {"b": 1}}}, "depth-2 action"), + ({"t": "g.buy", "slot": 1, "neg": -0.0, "big": 1e16}, "action floats"), + ({"t": "g.buy", "slot": 1, "none": None, "bool": True, "int": 1}, + "action scalar tags"), + ({"t": "g.move", "uid": 1, "to": {"area": "hand", "idx": 2}, "dir": "LEFT"}, + "hand move with dir"), + ("g.ready", "action not an object"), + ({"slot": 1}, "action without t"), + ({"t": 1, "slot": 1}, "action non-string t"), + ({"t": "g.ready", "ready": True, "extra": [1, None, True]}, "ready with list"), + ] + for value, label in values: + add(requests, seen, label, "action", value, "manual action") + + states = [ + ({"schema": "arkguardrl/native-solo-decisions-feedback-intent-v3", + "revision": 3, + "public": {"round": 2, "phase": "PREP", "serverNow": "2026-01-01T00:00:00Z", + "deadline": 123, "overtimeAt": None, "中文键": "值", "nested": {"b": 1, "a": 1.0}}, + "own": {"funds": 10, "hand": [None, {"uid": 1, "kind": "chess"}]}, + "personalEnded": False, "gameEnded": False}, "representative state"), + ({"schema": "s", "public": {"serverNow": 1, "deadline": 2, "overtimeAt": 3}, + "own": {}, "personalEnded": True, "gameEnded": False}, "only ignored public keys"), + ({"schema": "s", "public": {"z": -0.0, "a": 1e-7, "m": [None, True, 1, 1.0]}, + "own": {"x": 18446744073709551615}, "personalEnded": False, "gameEnded": True}, + "state scalars"), + ({"schema": "s", "public": {}, "own": None, "personalEnded": False, + "gameEnded": False, "extra": "ignored"}, "state extra ignored"), + ({"schema": "s", "public": {"😀": 1, "É": 2, "中": 3, "a": 4}, "own": [], + "personalEnded": False, "gameEnded": False}, "state unicode keys"), + ] + for value, label in states: + add(requests, seen, label, "decision", value, "manual decision") + add(requests, seen, label, "canonical", value, "manual decision") + missing = [ + ({"schema": "s", "own": {}, "personalEnded": False, "gameEnded": False}, + "state missing public"), + ({"schema": "s", "public": {}, "personalEnded": False, "gameEnded": False}, + "state missing own"), + ({"schema": "s", "public": {}, "own": {}, + "personalEnded": False}, "state missing gameEnded"), + ] + for value, label in missing: + add(requests, seen, label, "decision", value, "manual decision error") + + canonical = [ + ({"z": None, "b": True, "i": 0, "neg": -1, "big": 18446744073709551615, + "s": "text", "f": 1.0, "negzero": -0.0, "tiny": 1e-7, "huge": 1e16, + "fixed": 1e15, "mid": 0.30000000000000004}, "all scalar kinds"), + ({"中文": "值", "é": "e", "😀": [1, 2], "Z": "upper", "a": "lower", + "\u2028": "separator", "\u007f": "del", "\ue000": "private use"}, + "unicode keys and values"), + ({"k" * 300: 1, "短": 2}, "300-char key"), + ({"esc": "\"\\\b\f\n\r\t\u0000\u0001\u001f\u007f\u2028\u2029"}, + "string escapes"), + ({"deep": [{"b": [{"c": None}]}, [[[]]]], "empty": {}, "list": []}, + "nesting"), + ({}, "empty object"), + ([], "empty array"), + ([True, 1, False, 0, None, "1"], "bool and int"), + ({"u000b": "\u000b", "u001f": "\u001f"}, "low controls"), + ({"astral": "𝄞😀", "bmp": "中文é"}, "astral text"), + ({"long": "x" * 1000}, "long string"), + ({"big neg": -9223372036854775808, "big pos": 18446744073709551615}, + "64-bit integer bounds"), + ] + for value, label in canonical: + add(requests, seen, label, "canonical", value, "manual canonical") + add(requests, seen, label, "fingerprint", value, "manual canonical") + add(requests, seen, "beyond u64 integer", "canonical", + {"n": 123456789012345678901234567890}, "known limitation", known=True) + + +def float_samples(requests, seen, count, rng): + values = [1.0, -0.0, 0.0, 0.1, 1e-7, 1e-5, 1e-4, 1e15, 1e16, 1e21, 1e22, + 5e-324, 2.2250738585072014e-308, 1.7976931348623157e308, + 9007199254740993.0, 1234567890123456.0, 1.0000000000000002, + 0.30000000000000004, 123456789.0, 2.0 ** 53, 1.5, -1.5, + 134862484565824.12] # exact halfway decimal: Python chooses even + for value in values: + add(requests, seen, f"float {value!r}", "canonical", value, "float boundary") + while count > 0: + bits = rng.getrandbits(64) + value = struct.unpack("= 3: + choices = choices[:5] + kind = rng.choice(choices) + if kind == "null": + return None + if kind == "bool": + return rng.random() < 0.5 + if kind == "int": + return rng.choice([0, 1, -1, 2 ** 31, 2 ** 63 - 1, 18446744073709551615, + rng.randrange(-1000, 1000)]) + if kind == "float": + return rng.choice([0.0, -0.0, 1.0, 1e-7, 1e16, rng.uniform(-1e6, 1e6)]) + if kind == "str": + alphabet = ["a", "Z", "é", "中", "😀", "\u0000", "\n", "\"", "\\", "\u2028", + "\u007f", "𝄞"] + return "".join(rng.choice(alphabet) for _ in range(rng.randrange(0, 8))) + if kind == "list": + return [random_json(rng, depth + 1) for _ in range(rng.randrange(0, 4))] + keys = ["a", "b", "Z", "é", "中", "😀", "k" * rng.randrange(1, 40), "\u0000"] + rng.shuffle(keys) + return {key: random_json(rng, depth + 1) + for key in keys[:rng.randrange(0, 4)]} + + +def json_samples(requests, seen, count, rng): + for _ in range(count): + value = random_json(rng) + add(requests, seen, f"json fuzz {json.dumps(value)[:80]}", "canonical", + value, "json fuzz") + add(requests, seen, f"json fuzz {json.dumps(value)[:80]}", "fingerprint", + value, "json fuzz") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--data-root", default=str(ROOT.parent / "ArkGuardRL/game/data")) + default_library = ROOT / ("target/release/lib_native.dylib" + if platform.system() == "Darwin" + else "target/release/lib_native.so") + parser.add_argument("--library", default=str(default_library)) + parser.add_argument("--seeds", default="7,11") + parser.add_argument("--max-steps", type=int, default=400) + parser.add_argument("--float-samples", type=int, default=5000) + parser.add_argument("--json-samples", type=int, default=300) + parser.add_argument("--no-real", action="store_true", + help="skip episode collection (handwritten/fuzzed samples only)") + parser.add_argument("--keep-build", action="store_true", + help="keep the throwaway crate for debugging") + parser.add_argument("--runner-bin", help="reuse an already built runner") + parser.add_argument("--show", type=int, default=20, + help="maximum differences to print per group") + args = parser.parse_args() + + requests, seen = [], set() + try: + from arkguardrl import contracts # noqa: F401 (fail early, clear message) + except ImportError as exc: + raise SystemExit(f"run from the repository with its dependencies installed: {exc}") + + real = None + if not args.no_real: + if not Path(args.data_root).is_dir(): + raise SystemExit(f"missing data root {args.data_root}; pass --data-root or --no-real") + if not Path(args.library).exists(): + raise SystemExit(f"missing native library {args.library}; pass --library or --no-real") + seeds = [int(seed) for seed in args.seeds.split(",") if seed] + real = collect_real(requests, seen, args.data_root, args.library, seeds, + args.max_steps) + + manual_samples(requests, seen) + rng = random.Random(20261109) + float_samples(requests, seen, args.float_samples, rng) + json_samples(requests, seen, args.json_samples, random.Random(7)) + + if args.runner_bin: + binary, cleanup = Path(args.runner_bin), None + else: + binary, cleanup = build_runner(ROOT, keep=args.keep_build) + + try: + responses = run_rust(binary, requests) + finally: + if cleanup is not None: + shutil.rmtree(cleanup, ignore_errors=True) + + expected = [python_result(request) for request in requests] + def normalize(result): + return {"error": True} if "error" in result else result + groups = {} + differences = [] + known_differences = [] + for request, want, got in zip(requests, expected, responses): + bucket = groups.setdefault(request["group"], [0, 0]) + bucket[1] += 1 + if normalize(want) == normalize(got): + bucket[0] += 1 + continue + entry = (request, want, got) + if request["known"]: + known_differences.append(entry) + else: + differences.append(entry) + + print("== coverage ==") + if real: + states, actions, unique_actions, per_seed, bounds = real + print(f"real episodes: {len(per_seed)} seeds " + + ", ".join(f"seed {seed}: {s} states/{a} candidates" + for seed, s, a in per_seed)) + print(f"real states: {states} unique; candidate actions: {actions} occurrences, " + f"{unique_actions} unique; decision ids: {states}") + low, high, floats = bounds + print(f"real integer range: {low}..{high}; real float occurrences: {floats}") + if low is not None and (low < -(2 ** 63) or high > 2 ** 64 - 1): + print("WARNING: real data exceeds serde_json's 64-bit integer domain") + else: + print("real episodes: skipped (--no-real)") + print(f"requests: {len(requests)}") + + print("\n== results ==") + for group, (passed, total) in sorted(groups.items()): + print(f"{group:20s} {passed:6d}/{total:<6d} matched") + print(f"TOTAL {sum(v[0] for v in groups.values()):6d}/" + f"{len(requests):<6d} matched") + + def show(entries, title): + if not entries: + return + print(f"\n== {title} ({len(entries)}) ==") + by_group = {} + for entry in entries: + by_group.setdefault(entry[0]["group"], []).append(entry) + for group, items in sorted(by_group.items()): + print(f"-- {group} --") + for request, want, got in items[:args.show]: + print(f"label: {request['label']}") + print(f"input: {json.dumps(request['value'], ensure_ascii=False)}") + print(f"python: {json.dumps(want, ensure_ascii=False)}") + print(f"rust: {json.dumps(got, ensure_ascii=False)}") + if len(items) > args.show: + print(f"... {len(items) - args.show} more in {group}") + + show(differences, "differences") + show(known_differences, "known limitations") + + if differences: + print(f"\nFAIL: {len(differences)} unexpected difference(s)") + return 1 + print("\nPASS: every non-known sample matched byte-for-byte" + + (f" ({len(known_differences)} known limitation sample(s))" + if known_differences else "")) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) \ No newline at end of file diff --git a/crates/engine/examples/field.rs b/crates/engine/examples/field.rs index 2de13d0..2d8c2fa 100644 --- a/crates/engine/examples/field.rs +++ b/crates/engine/examples/field.rs @@ -3,8 +3,9 @@ use arkguard_engine::{ battle::{ direction::Direction, + health::Pool, operators::Placement, - runtime::{Field, Limits}, + runtime::{BossConfig, BossKind, BossOvertime, BossRoundConfig, Field, Limits}, waves::Template, }, data::Catalog, @@ -31,6 +32,13 @@ fn main() -> Result<(), String> { let object = input.as_object().ok_or("Expected field input object")?; for key in object.keys() { if ![ + "kind", + "map", + "bossPool", + "bossRound", + "branches", + "devices", + "extraRoutes", "stage", "stageId", "routes", @@ -87,26 +95,112 @@ fn main() -> Result<(), String> { .transpose() .map_err(|_| "Seed outside u32")? .unwrap_or(1); - let mut field = Field::new( - Arc::clone(&data), - stage, - template, - seed, - input["timeLimit"].as_f64().unwrap_or(60.), - limits, - )?; + let kind = input + .get("kind") + .map(|v| v.as_str().ok_or("Expected field kind string")) + .transpose()? + .unwrap_or("normal"); + let time_limit = + input["timeLimit"] + .as_f64() + .unwrap_or(if kind == "normal" { 60. } else { f64::INFINITY }); + let mut field = match kind { + "normal" => { + if input.get("bossPool").is_some() { + return Err("bossPool requires boss or hidden kind".into()); + } + Field::new(Arc::clone(&data), stage, template, seed, time_limit, limits)? + } + "boss" | "hidden" => { + let pool = input["bossPool"] + .as_object() + .ok_or("Specify bossPool for boss or hidden kind")?; + if pool + .keys() + .any(|key| !matches!(key.as_str(), "hp" | "maxHp")) + { + return Err("Unsupported bossPool input".into()); + } + let max_hp = input["bossPool"]["maxHp"] + .as_f64() + .ok_or("Expected bossPool.maxHp number")?; + let hp = pool + .get("hp") + .map(|v| v.as_f64().ok_or("Expected bossPool.hp number")) + .transpose()? + .unwrap_or(max_hp); + Field::new_boss( + Arc::clone(&data), + stage, + template, + seed, + time_limit, + limits, + BossConfig { + kind: if kind == "boss" { + BossKind::FinalAssault + } else { + BossKind::HiddenCore + }, + pool: Pool { hp, max_hp }, + }, + )? + } + _ => return Err(format!("Unsupported field kind: {kind}")), + }; + field.configure_map(arkguard_engine::battle::runtime::MapConfig::parse( + &input["map"], + )?)?; + if let Some(value) = input.get("bossRound") { + let object = value.as_object().ok_or("Expected bossRound object")?; + if object + .keys() + .any(|k| !matches!(k.as_str(), "lp" | "overtime")) + { + return Err("Unsupported bossRound input".into()); + } + let life_points = value["lp"].as_f64().ok_or("Expected bossRound.lp number")?; + let overtime = if let Some(o) = value.get("overtime") { + let object = o.as_object().ok_or("Expected overtime object")?; + if object + .keys() + .any(|k| !matches!(k.as_str(), "afterReal" | "combatTimeScale" | "lpPerSecond")) + { + return Err("Unsupported overtime input".into()); + } + Some(BossOvertime { + after_real_seconds: o["afterReal"] + .as_f64() + .ok_or("Expected overtime.afterReal number")?, + combat_time_scale: o["combatTimeScale"] + .as_f64() + .ok_or("Expected overtime.combatTimeScale number")?, + lp_per_real_second: o["lpPerSecond"] + .as_f64() + .ok_or("Expected overtime.lpPerSecond number")?, + }) + } else { + None + }; + field.configure_boss_round(BossRoundConfig { + life_points, + overtime, + })?; + } for u in input["players"][0]["units"] .as_array() .into_iter() .flatten() { let object = u.as_object().ok_or("Expected operator object")?; - if object - .keys() - .any(|k| !matches!(k.as_str(), "chessId" | "uid" | "row" | "col" | "dir")) - { + if object.keys().any(|k| { + !matches!( + k.as_str(), + "chessId" | "uid" | "row" | "col" | "dir" | "skillIndex" + ) + }) { return Err( - "Only default operators without items or loadout overrides are implemented".into(), + "Only supported skills with default modules and no items are implemented".into(), ); } let direction = u @@ -128,7 +222,7 @@ fn main() -> Result<(), String> { ) .map_err(|_| "Operator coordinate outside i32".into()) }; - field.add_operator( + field.add_operator_with_skill( u["chessId"].as_str().ok_or("Expected chessId")?, Placement { uid: u["uid"] @@ -137,6 +231,13 @@ fn main() -> Result<(), String> { home: [coordinate("row")?, coordinate("col")?], direction: dir, }, + u.get("skillIndex") + .map(|v| { + v.as_u64() + .and_then(|n| u32::try_from(n).ok()) + .ok_or("Expected nonnegative u32 skillIndex") + }) + .transpose()?, )?; } let advance = field.run(budget)?; diff --git a/crates/engine/examples/solo.rs b/crates/engine/examples/solo.rs new file mode 100644 index 0000000..a49d6c9 --- /dev/null +++ b/crates/engine/examples/solo.rs @@ -0,0 +1,526 @@ +//! Development runner for seeded modes or prepared single-player round plans. +use arkguard_engine::{ + battle::{ + direction::Direction, + operators::Placement, + runtime::{BossOvertime, Limits}, + waves::Template, + }, + data::Catalog, + solo::{ + preparation::{Action, Config as PrepConfig, EffectsConfig, Grant, Kind}, + Boss, Config, HiddenRule, Operator, Phase, PreparedRound, RoundKind, RoundPlan, Runner, + }, +}; +use serde_json::{json, Value}; +use std::{io::Read, path::Path, sync::Arc}; + +enum PreparationInput { + Supplied { + lineup: PreparedRound, + spend: u64, + }, + Owned { + actions: Vec, + layers: f64, + spend: u64, + }, +} +fn owned_preparation(v: &Value) -> Result { + keys(v, &["modeId", "banned", "initial", "capacity", "effects"])?; + let banned = v + .get("banned") + .map(|v| { + v.as_array() + .ok_or("Expected banned array")? + .iter() + .map(|v| v.as_str().map(str::to_owned).ok_or("Expected banned id")) + .collect::, _>>() + }) + .transpose()? + .unwrap_or_default(); + let initial = v + .get("initial") + .map(|v| { + v.as_array() + .ok_or("Expected initial grant array")? + .iter() + .map(|v| { + keys(v, &["kind", "id"])?; + Ok(Grant { + kind: match v["kind"].as_str() { + Some("chess") => Kind::Chess, + Some("item") => Kind::Item, + _ => return Err("Invalid initial grant kind".into()), + }, + key: v["id"].as_str().ok_or("Expected grant id")?.into(), + }) + }) + .collect::, String>>() + }) + .transpose()? + .unwrap_or_default(); + let effects = v + .get("effects") + .map(|v| { + keys(v, &["disabledBonds", "layers", "countBonus"])?; + Ok::<_, String>(EffectsConfig { + disabled_bonds: serde_json::from_value( + v.get("disabledBonds").cloned().unwrap_or_else(|| json!([])), + ) + .map_err(|e| e.to_string())?, + layers: serde_json::from_value( + v.get("layers").cloned().unwrap_or_else(|| json!({})), + ) + .map_err(|e| e.to_string())?, + count_bonus: serde_json::from_value( + v.get("countBonus").cloned().unwrap_or_else(|| json!({})), + ) + .map_err(|e| e.to_string())?, + }) + }) + .transpose()?; + Ok(PrepConfig { + effects, + mode_id: v["modeId"] + .as_str() + .ok_or("Expected preparation.modeId")? + .into(), + banned, + initial, + capacity: v + .get("capacity") + .map(|v| { + v.as_u64() + .and_then(|v| usize::try_from(v).ok()) + .ok_or("Expected preparation capacity") + }) + .transpose()? + .unwrap_or(256), + }) +} + +fn keys(value: &Value, allowed: &[&str]) -> Result<(), String> { + let object = value.as_object().ok_or("Expected an input object")?; + if let Some(key) = object.keys().find(|key| !allowed.contains(&key.as_str())) { + return Err(format!("Unsupported single-player input: {key}")); + } + Ok(()) +} +fn overtime(value: &Value) -> Result, String> { + if value.is_null() { + return Ok(None); + } + keys(value, &["afterReal", "combatTimeScale", "lpPerSecond"])?; + Ok(Some(BossOvertime { + after_real_seconds: value["afterReal"] + .as_f64() + .ok_or("Expected overtime.afterReal")?, + combat_time_scale: value["combatTimeScale"] + .as_f64() + .ok_or("Expected overtime.combatTimeScale")?, + lp_per_real_second: value["lpPerSecond"] + .as_f64() + .ok_or("Expected overtime.lpPerSecond")?, + })) +} +fn prepared(value: &Value) -> Result { + keys(value, &["units", "activeLayers"])?; + let units = value["units"].as_array().ok_or("Expected prepared.units")?; + if units.len() > 36 { + return Err("Prepared lineup exceeds board capacity".into()); + } + let operators = units + .iter() + .map(|u| { + keys( + u, + &["chessId", "uid", "row", "col", "dir", "skillIndex", "items"], + )?; + let direction = match u + .get("dir") + .filter(|v| !v.is_null()) + .map(|v| v.as_str().ok_or("Expected prepared facing string")) + .transpose()? + .unwrap_or("RIGHT") + { + "RIGHT" => Direction::Right, + "UP" => Direction::Up, + "DOWN" => Direction::Down, + "LEFT" => Direction::Left, + _ => return Err("Invalid prepared facing".into()), + }; + let coordinate = |key| { + u[key] + .as_i64() + .and_then(|v| i32::try_from(v).ok()) + .ok_or("Expected board coordinate") + }; + Ok(Operator { + items: serde_json::from_value(u.get("items").cloned().unwrap_or_else(|| json!([]))) + .map_err(|e| e.to_string())?, + key: u["chessId"].as_str().ok_or("Expected chessId")?.into(), + placement: Placement { + uid: u["uid"].as_u64().ok_or("Expected operator uid")?, + home: [coordinate("row")?, coordinate("col")?], + direction, + }, + skill_index: u + .get("skillIndex") + .filter(|v| !v.is_null()) + .map(|v| { + v.as_u64() + .and_then(|v| u32::try_from(v).ok()) + .ok_or("Expected skillIndex") + }) + .transpose()?, + }) + }) + .collect::>()?; + Ok(PreparedRound { + operators, + active_layers: value["activeLayers"] + .as_f64() + .ok_or("Expected prepared.activeLayers")?, + }) +} +fn main() -> Result<(), String> { + let args: Vec<_> = std::env::args().skip(1).collect(); + if args.len() != 3 { + return Err("usage: solo DATA_ROOT INPUT.json TICK_BUDGET".into()); + } + let data = Arc::new(Catalog::load(Path::new(&args[0]), 64 << 20)?); + let mut bytes = Vec::new(); + std::fs::File::open(&args[1]) + .map_err(|e| e.to_string())? + .take((4 << 20) + 1) + .read_to_end(&mut bytes) + .map_err(|e| e.to_string())?; + if bytes.len() > 4 << 20 { + return Err("Single-player input exceeds byte limit".into()); + } + let mut input: Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + let setup = if input.get("modeId").is_some() { + keys( + &input, + &[ + "seed", + "modeId", + "preparation", + "roundActions", + "map", + "drafts", + "core", + ], + )?; + let mode = input["modeId"].as_str().ok_or("Expected modeId")?; + let seed = input["seed"] + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .ok_or("Expected seed in u32 domain")?; + let mut prep = input + .get("preparation") + .cloned() + .unwrap_or_else(|| json!({})); + if !prep.is_object() { + return Err("Expected preparation object".into()); + } + if prep.get("modeId").is_some_and(|v| v != mode) { + return Err("Conflicting preparation modeId".into()); + } + prep["modeId"] = json!(mode); + let options = owned_preparation(&prep)?; + let mut generated = + arkguard_engine::solo::mode::generate(&data, seed, mode, &options.banned)?; + let mut effects = prep.get("effects").cloned().unwrap_or_else(|| json!({})); + let mut disabled: Vec = serde_json::from_value( + generated.input["preparation"]["effects"]["disabledBonds"].clone(), + ) + .map_err(|e| e.to_string())?; + if let Some(e) = options.effects { + disabled.extend(e.disabled_bonds); + } + disabled.sort(); + disabled.dedup(); + effects["disabledBonds"] = json!(disabled); + prep["effects"] = effects; + prep["banned"] = generated.input["preparation"]["banned"].clone(); + generated.input["preparation"] = prep; + if let Some(actions) = input.get("roundActions") { + let actions = actions.as_array().ok_or("Expected roundActions array")?; + let plans = generated.input["plans"].as_array_mut().unwrap(); + if actions.len() > plans.len() { + return Err("Too many roundActions".into()); + } + for (plan, actions) in plans.iter_mut().zip(actions) { + if !actions.is_array() { + return Err("Expected round action array".into()); + } + plan["actions"] = actions.clone(); + } + } + if let Some(map) = input.get("map") { + generated.input["map"] = map.clone(); + } + if let Some(drafts) = input.get("drafts") { + if drafts.as_bool().ok_or("Expected drafts boolean")? { + generated.input["drafts"] = generated.setup["stageId"].clone(); + } + } + if let Some(core) = input.get("core") { + generated.input["core"] = core.clone(); + } + input = generated.input; + Some(generated.setup) + } else { + None + }; + keys( + &input, + &[ + "seed", + "stage", + "config", + "plans", + "preparation", + "map", + "drafts", + "core", + ], + )?; + let owned = input + .get("preparation") + .map(owned_preparation) + .transpose()?; + let seed = input["seed"] + .as_u64() + .and_then(|v| u32::try_from(v).ok()) + .ok_or("Expected seed in u32 domain")?; + let budget: usize = args[2].parse().map_err(|_| "Invalid tick budget")?; + let cfg = &input["config"]; + keys(cfg, &["lp", "lpCap", "keepFunds", "hidden"])?; + let hidden = if cfg["hidden"].is_null() { + None + } else { + let h = &cfg["hidden"]; + keys(h, &["layerThreshold", "minLp"])?; + Some(HiddenRule { + layer_threshold: h["layerThreshold"] + .as_f64() + .ok_or("Expected hidden.layerThreshold")?, + min_lp_exclusive: h["minLp"].as_f64().ok_or("Expected hidden.minLp")?, + }) + }; + let config = Config { + initial_lp: cfg["lp"].as_f64().ok_or("Expected config.lp")?, + lp_cap_per_round: cfg["lpCap"].as_u64().ok_or("Expected config.lpCap")?, + keep_funds: cfg["keepFunds"] + .as_bool() + .ok_or("Expected config.keepFunds")?, + hidden, + }; + let raw = input["plans"].as_array().ok_or("Expected plans array")?; + if raw.is_empty() || raw.len() > 64 { + return Err("Single-player round capacity exceeded".into()); + } + let limits = Limits::default(); + let mut preps = Vec::new(); + let plans = raw + .iter() + .map(|p| { + keys( + p, + &[ + "kind", + "timeLimit", + "income", + "deployCap", + "routes", + "spawns", + "extraRoutes", + "templateId", + "spawnActions", + "branches", + "devices", + "overrides", + "maxHp", + "overtime", + "prepared", + "spend", + "actions", + ], + )?; + let boss = || { + Ok::<_, String>(Boss { + max_hp: p["maxHp"].as_f64().ok_or("Expected maxHp")?, + overtime: overtime(&p["overtime"])?, + }) + }; + let kind = match p["kind"].as_str().ok_or("Expected round kind")? { + "normal" => { + if !p["overtime"].is_null() { + return Err("Normal rounds use their combat time limit".into()); + } + RoundKind::Normal + } + "boss" => RoundKind::FinalAssault(boss()?), + "hidden" => RoundKind::HiddenCore(boss()?), + _ => return Err("Invalid single-player round kind".into()), + }; + let mut wave = Template::parse( + p, + &Value::Null, + &Value::Null, + limits.units, + limits.route_legs, + )?; + if let Some(id) = p.get("templateId").filter(|v| !v.is_null()) { + let id = id.as_str().ok_or("Expected templateId")?; + let original = &data.table("waves").unwrap()[id]; + if !original.is_object() { + return Err("Unknown wave template".into()); + } + let actions = p["spawnActions"] + .as_array() + .ok_or("Expected resolved spawnActions")?; + wave.configure_bounty_actions( + original, + actions, + &data.table("factions").unwrap()["templateSlots"], + limits.units, + )?; + } else if p.get("spawnActions").is_some() { + return Err("spawnActions require templateId".into()); + } + wave.spawns = p["spawns"] + .as_array() + .ok_or("Expected round spawns")? + .clone(); + let spend = p + .get("spend") + .map(|v| v.as_u64().ok_or("Expected preparation spend")) + .transpose()? + .unwrap_or(0); + let preparation = if owned.is_some() { + if p.get("prepared").is_some() { + keys(&p["prepared"], &["activeLayers"])?; + } + PreparationInput::Owned { + actions: p + .get("actions") + .map(|v| { + v.as_array() + .ok_or("Expected action array")? + .iter() + .map(Action::parse) + .collect::, _>>() + }) + .transpose()? + .unwrap_or_default(), + layers: p["prepared"] + .get("activeLayers") + .map(|v| v.as_f64().ok_or("Expected activeLayers")) + .transpose()? + .unwrap_or(0.), + spend, + } + } else { + if p.get("actions").is_some() { + return Err("Preparation actions require preparation configuration".into()); + } + PreparationInput::Supplied { + lineup: prepared(&p["prepared"])?, + spend, + } + }; + preps.push(preparation); + Ok(RoundPlan { + kind, + wave, + time_limit: p["timeLimit"] + .as_f64() + .or_else(|| { + (p["timeLimit"].is_null() && p["kind"] != "normal").then_some(f64::INFINITY) + }) + .ok_or("Expected timeLimit")?, + income: p["income"].as_u64().ok_or("Expected round income")?, + deploy_cap: p["deployCap"] + .as_u64() + .and_then(|v| usize::try_from(v).ok()) + .ok_or("Expected deployCap")?, + }) + }) + .collect::>()?; + let effects = owned.as_ref().is_some_and(|p| p.effects.is_some()); + let mut run = if let Some(owned) = owned { + Runner::new_with_preparation( + data, + input["stage"].clone(), + seed, + config, + plans, + limits, + owned, + )? + } else { + Runner::new(data, input["stage"].clone(), seed, config, plans, limits)? + }; + run.configure_map(arkguard_engine::battle::runtime::MapConfig::parse( + &input["map"], + )?)?; + if let Some(stage) = input.get("drafts") { + run.enable_drafts(stage.as_str().ok_or("Expected draft stage ID")?)?; + } + if let Some(core) = input.get("core") { + run.configure_core(core.as_str().ok_or("Expected core ID")?)?; + } + let mut preps = preps.into_iter().peekable(); + let mut ticks = 0; + while ticks < budget && run.phase() != Phase::Result { + if run.phase() == Phase::Draft { + let Some(PreparationInput::Owned { actions, .. }) = preps.peek_mut() else { + break; + }; + if !matches!(actions.first(), Some(Action::Draft(_))) { + break; + } + run.prep_action(actions.remove(0))?; + continue; + } + if run.phase() == Phase::Prep { + match preps.next().ok_or("Missing prepared round")? { + PreparationInput::Supplied { lineup, spend } => { + run.spend(spend)?; + run.ready(lineup)?; + } + PreparationInput::Owned { + actions, + layers, + spend, + } => { + run.spend(spend)?; + for action in actions { + run.prep_action(action)?; + } + if effects { + if layers != 0. { + return Err( + "Effects derive active layers from owned preparation".into() + ); + } + run.ready_current()?; + } else { + run.ready_owned(layers)?; + } + } + } + } + ticks += run.advance(budget - ticks)?.ticks; + } + let mut report = json!({"ticks":ticks,"budgetExhausted":ticks==budget&&run.phase()!=Phase::Result,"state":run.report()?}); + if let Some(setup) = setup { + report["setup"] = setup; + } + println!("{report}"); + Ok(()) +} diff --git a/crates/engine/src/battle/ally.rs b/crates/engine/src/battle/ally.rs index b31345f..9420a95 100644 --- a/crates/engine/src/battle/ally.rs +++ b/crates/engine/src/battle/ally.rs @@ -6,6 +6,7 @@ use super::{ health::{Id, World}, search::{self, AttackProfile, Commitments, Selection}, skills::{self, Runtime}, + stats::Stat, }; pub trait Host: search::Host + skills::Hooks + blocking::Hooks { fn effective_profile( @@ -33,7 +34,7 @@ fn interval(w: &mut World, id: Id) -> Result { w.unit_mut(id)? .stats .stats() - .map(|s| s.n("interval")) + .map(|s| s.get(Stat::Interval)) .map_err(str::to_string) } fn store(w: &mut World, h: &mut H, id: Id, p: AttackProfile) -> Result<(), String> { diff --git a/crates/engine/src/battle/attacks.rs b/crates/engine/src/battle/attacks.rs index 9f11d7a..e35a7ae 100644 --- a/crates/engine/src/battle/attacks.rs +++ b/crates/engine/src/battle/attacks.rs @@ -17,6 +17,8 @@ pub enum Mode { } #[derive(Clone, Copy, Debug)] pub struct Direct { + pub attachment: Option, + pub element_heal_ratio: f64, pub mode: Mode, pub hits: u32, pub atk_scale: f64, @@ -27,6 +29,15 @@ pub struct Direct { pub is_skill: bool, } #[derive(Clone, Copy, Debug)] +pub struct Attachment { + pub count: u32, + pub initial: f64, + pub delta: f64, + pub cap: f64, + pub per_target: bool, + pub scale: f64, +} +#[derive(Clone, Copy, Debug)] pub struct Splash { pub radius: f64, pub scale: f64, @@ -79,10 +90,48 @@ pub struct Prepared { pub payload: Direct, } pub trait Hooks: super::skills::Hooks + health::Hooks + Queries { + fn heal(&mut self, w: &mut World, source: Id, target: Id, amount: f64) -> Result + where + Self: Sized, + { + health::heal( + w, + self, + Some(source), + target, + amount, + HealOptions::default(), + ) + } + + fn prepare_attachment( + &mut self, + _world: &mut World, + _source: Id, + _target: Option, + _payload: &mut Direct, + ) -> Result<(), String> { + Ok(()) + } + fn attachment_damage( + &mut self, + _world: &mut World, + _source: Id, + _target: Id, + _attack_id: u64, + _payload: Direct, + ) -> Result { + Ok(0.) + } fn has_before_attack(&self) -> bool; fn before_attack(&mut self, c: &mut Context, w: &mut World) -> Result<(), String>; fn engage(&mut self, id: Id, w: &mut World) -> Result<(), String>; - fn damage(&mut self, w: &mut World, request: &mut Request) -> Result; + fn damage( + &mut self, + w: &mut World, + request: &mut Request, + skill: Option<&mut Runtime>, + ) -> Result; /// Raw body-radius or selectable centre-radius query, in battle enemy order. fn radius_targets( &mut self, @@ -239,12 +288,15 @@ impl Executor { id: Id, target: Option, attack_id: u64, - p: Direct, + mut p: Direct, area: Area, mut position: [f64; 2], mut skill: Option<&mut Runtime>, ) -> Result<(), String> { self.validate(p)?; + if p.attachment.is_some() { + h.prepare_attachment(w, id, target, &mut p)?; + } if let Some(chain) = area.chain { // k < count: a fractional count may produce ceil(count) victims. let count = if chain.count == 0.0 { @@ -273,8 +325,11 @@ impl Executor { let (amount, heal) = match p.mode { Mode::Heal => { let target = target.ok_or("A direct heal requires a target")?; + if p.element_heal_ratio > 0. { + super::element::heal(w, target, atk * p.element_heal_ratio, None)?; + } let amount = atk * (p.atk_scale * p.heal_scale * atk_mul); - health::heal(w, h, Some(id), target, amount, HealOptions::default())?; + h.heal(w, id, target, amount)?; (amount, true) } Mode::Damage(kind) => { @@ -314,7 +369,10 @@ impl Executor { request.attack_id = Some(attack_id); request.is_attack = true; request.is_skill = p.is_skill; - total += h.damage(w, &mut request)?; + total += h.damage(w, &mut request, skill.as_deref_mut())?; + } + if p.attachment.is_some() { + total += h.attachment_damage(w, id, target, attack_id, p)?; } h.each_hit( Impact { @@ -365,7 +423,7 @@ impl Executor { let mut r = single_hit(id, victim, attack_id, kind, amount, p.is_skill); r.is_splash = true; r.attack_type = super::hit::AttackType::Splash; - let dealt = h.damage(w, &mut r)?; + let dealt = h.damage(w, &mut r, skill.as_deref_mut())?; total += dealt; h.each_hit( Impact { @@ -436,7 +494,7 @@ impl Executor { atk * scale * p.skill_damage_mul * powi(1.0 - chain.falloff, k)?; let mut r = single_hit(id, victim, attack_id, kind, amount, p.is_skill); r.tags.push("chain".into()); - let dealt = h.damage(w, &mut r)?; + let dealt = h.damage(w, &mut r, skill.as_deref_mut())?; total += dealt; if chain.sluggish != 0.0 && w.unit(victim)?.stats.alive { h.sluggish(id, victim, chain.sluggish, w)?; diff --git a/crates/engine/src/battle/blocking.rs b/crates/engine/src/battle/blocking.rs index c546b99..e713d26 100644 --- a/crates/engine/src/battle/blocking.rs +++ b/crates/engine/src/battle/blocking.rs @@ -4,6 +4,7 @@ use super::{ deploy::{Deployment, Kind}, grid::{Grid, COLS, ROWS}, health::{Id, World}, + stats::Stat, }; pub trait Hooks { fn unblock_with_buffs( @@ -112,7 +113,7 @@ pub fn release(w: &mut World, h: &mut H, blocker: Id) -> Result<(), St pub fn enforce_capacity(w: &mut World, h: &mut H, blocker: Id) -> Result<(), String> { let u = w.unit_mut(blocker)?; let cap = if u.stats.alive && u.deployed { - u.stats.stats().map_err(str::to_string)?.n("blockCnt") + u.stats.stats().map_err(str::to_string)?.get(Stat::BlockCnt) } else { 0.0 }; @@ -160,7 +161,7 @@ pub fn blocker_for( { return Ok(false); } - let cap = s.n("blockCnt"); + let cap = s.get(Stat::BlockCnt); if cap <= 0.0 { return Ok(false); } @@ -226,7 +227,7 @@ pub fn check( .stats .stats() .map_err(str::to_string)? - .n("blockRadiusScale") + .get(Stat::BlockRadiusScale) } else { 1.0 }; @@ -252,108 +253,3 @@ pub fn check( h.blocked(id, enemy, w)?; Ok(true) } - -#[cfg(test)] -mod tests { - use super::*; - use crate::battle::{ - deploy::{self, Event, Options}, - health::{Side, Unit}, - stats::{Base, UnitStats}, - }; - #[derive(Default)] - struct Host { - ended: Vec, - } - impl Hooks for Host { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, id: Id, _: &mut World) -> Result<(), String> { - self.ended.push(id); - Ok(()) - } - } - impl deploy::Hooks for Host { - fn initialize( - &mut self, - _: Id, - _: Options, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn event( - &mut self, - _: Event, - _: Id, - _: Option, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn remove_temporary_effects(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - } - #[test] - fn movement_and_retreat_release_both_ends_before_final_removal() { - let g = Grid::new( - &serde_json::json!({"rows":vec!["r".repeat(COLS);ROWS]}), - super::super::grid::Rect::FULL, - ) - .unwrap(); - let mut w = World::new(3, 1, 1).unwrap(); - let mut d = Deployment::new(g.rect(), 3, 1, 99.0).unwrap(); - let mut h = Host::default(); - let mut base = Base::default(); - base.0.insert("blockCnt".into(), 2.0); - let mut a = Unit::new(UnitStats::new(base), Side::Ally); - a.deployment.kind = Kind::Operator; - a.deployment.home = [10, 4]; - a.ground = true; - w.insert_unit(1, a).unwrap(); - d.register(1, &w).unwrap(); - d.deploy(&mut w, &mut h, 1, Options::default()).unwrap(); - let mut e = Unit::new(UnitStats::new(Base::default()), Side::Enemy); - e.position = [10.0, 4.0]; - w.insert_unit(2, e).unwrap(); - assert!(check(&mut w, &d, &g, &mut h, 2).unwrap()); - assert!(d.relocate(&mut w, &mut h, 1, [10, 5]).unwrap()); - assert_eq!(w.unit(2).unwrap().blocked_by(), None); - assert!(w.unit(1).unwrap().blocking().is_empty()); - assert_eq!(h.ended, vec![2]); - w.unit_mut(2).unwrap().position = [10.0, 5.0]; - assert!(check(&mut w, &d, &g, &mut h, 2).unwrap()); - d.retreat(&mut w, &mut h, 1, "retreat", false).unwrap(); - assert_eq!(h.ended, vec![2, 2]); - assert_eq!(w.unit(2).unwrap().blocked_by(), None); - } - #[test] - fn falling_capacity_releases_latest_first_and_dead_blocker_releases_all() { - let mut w = World::new(3, 1, 1).unwrap(); - let mut a = Unit::new(UnitStats::new(Base::default()), Side::Ally); - a.deployed = true; - a.stats.edit_base(|b| { - b.0.insert("blockCnt".into(), 1.0); - }); - a.blocking = vec![2, 3]; - w.insert_unit(1, a).unwrap(); - for id in [2, 3] { - let mut e = Unit::new(UnitStats::new(Base::default()), Side::Enemy); - e.blocked_by = Some(1); - w.insert_unit(id, e).unwrap(); - } - let mut h = Host::default(); - enforce_capacity(&mut w, &mut h, 1).unwrap(); - assert_eq!(h.ended, vec![3]); - assert_eq!(w.unit(1).unwrap().blocking(), &[2]); - assert_eq!(w.unit(3).unwrap().blocked_by(), None); - w.unit_mut(1).unwrap().stats.alive = false; - enforce_capacity(&mut w, &mut h, 1).unwrap(); - assert_eq!(h.ended, vec![3, 2]); - assert!(w.unit(1).unwrap().blocking().is_empty()); - } -} diff --git a/crates/engine/src/battle/body.rs b/crates/engine/src/battle/body.rs index 1ccfd76..8aab13a 100644 --- a/crates/engine/src/battle/body.rs +++ b/crates/engine/src/battle/body.rs @@ -60,23 +60,29 @@ pub fn position_key(u: &Unit) -> Option { } } pub fn keys(u: &Unit) -> Vec { + let mut out = Vec::new(); + keys_into(u, &mut out); + out +} +/// Reuse query storage while preserving the exact tile enumeration order. +pub(crate) fn keys_into(u: &Unit, out: &mut Vec) { + out.clear(); let Some(rect) = rectangle(u) else { - return position_key(u).into_iter().collect(); + out.extend(position_key(u)); + return; }; if !u.position.iter().all(|x| x.is_finite()) { - return vec![]; + return; } let r0 = (rect.y0 + 0.5 + 1e-9).floor().max(0.0) as i32; let r1 = (rect.y1 - 0.5 - 1e-9).ceil().min(ROWS as f64 - 1.0) as i32; let c0 = (rect.x0 + 0.5 + 1e-9).floor().max(0.0) as i32; let c1 = (rect.x1 - 0.5 - 1e-9).ceil().min(COLS as f64 - 1.0) as i32; - let mut out = Vec::new(); for r in r0..=r1 { for c in c0..=c1 { out.push(r as usize * COLS + c as usize); } } - out } pub fn on_tile(u: &Unit, r: i32, c: i32) -> bool { if let Some(rect) = rectangle(u) { @@ -89,19 +95,28 @@ pub fn on_tile(u: &Unit, r: i32, c: i32) -> bool { } } pub fn collider_keys(u: &Unit) -> Vec { + let mut out = Vec::new(); + collider_keys_into(u, &mut out); + out +} +pub(crate) fn collider_keys_into(u: &Unit, out: &mut Vec) { + out.clear(); if u.hit_area.is_some() || u.side == Side::Ally { - return keys(u); + keys_into(u, out); + return; } - let [y, x] = u.position; + enemy_collider_keys(u.position, |key| out.push(key)); +} +/// Ordinary enemy colliders touch at most four tiles; callers may avoid a Vec. +pub(crate) fn enemy_collider_keys([y, x]: [f64; 2], mut visit: impl FnMut(usize)) { if !y.is_finite() || !x.is_finite() { - return vec![]; + return; } let rho = 0.1; let r0 = (y - rho + 0.5 + 1e-9).floor().max(0.0) as i32; let r1 = (y + rho - 0.5 - 1e-9).ceil().min(ROWS as f64 - 1.0) as i32; let c0 = (x - rho + 0.5 + 1e-9).floor().max(0.0) as i32; let c1 = (x + rho - 0.5 - 1e-9).ceil().min(COLS as f64 - 1.0) as i32; - let mut out = Vec::new(); for r in r0..=r1 { let dy = if y < r as f64 - 0.5 { r as f64 - 0.5 - y @@ -121,10 +136,9 @@ pub fn collider_keys(u: &Unit) -> Vec { if dx > 0.0 && dy > 0.0 && dx * dx + dy * dy >= rho * rho { continue; } - out.push(r as usize * COLS + c as usize); + visit(r as usize * COLS + c as usize); } } - out } pub fn in_keys(u: &Unit, tiles: &[usize]) -> bool { keys(u).iter().any(|k| tiles.contains(k)) diff --git a/crates/engine/src/battle/buffs.rs b/crates/engine/src/battle/buffs.rs index cb078df..4097a1c 100644 --- a/crates/engine/src/battle/buffs.rs +++ b/crates/engine/src/battle/buffs.rs @@ -19,6 +19,9 @@ pub enum Refresh { #[derive(Clone, Debug)] pub struct State { pub(crate) id: BuffId, + pub tick_count: u64, + pub tick_payload: f64, + pub(crate) enemy_effect: Option, pub duration: f64, pub time_left: f64, pub max_stacks: u32, @@ -26,6 +29,7 @@ pub struct State { pub visible: bool, pub status: Option, pub source: Option, + retained_unit: Option, pub persist: bool, pub interval: f64, pub accumulator: f64, @@ -45,10 +49,18 @@ pub struct State { pub flags_present: bool, pub stealth_restore: Option, } +impl State { + pub(crate) fn retained_unit(&self) -> Option { + self.retained_unit + } +} impl Default for State { fn default() -> Self { Self { id: 0, + tick_count: 0, + tick_payload: 0., + enemy_effect: None, duration: f64::INFINITY, time_left: f64::INFINITY, max_stacks: 1, @@ -56,6 +68,7 @@ impl Default for State { visible: false, status: None, source: None, + retained_unit: None, persist: false, interval: 0.0, accumulator: 0.0, @@ -99,6 +112,13 @@ pub struct Spec { pub flags_present: bool, pub allow_dead: bool, } +impl Spec { + /// Keep a referenced unit available for this effect's complete attached lifetime. + pub(crate) fn retaining_unit(mut self, id: Id) -> Self { + self.buff.runtime.retained_unit = Some(id); + self + } +} #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Event { Tick, @@ -112,6 +132,81 @@ pub struct Context { pub dt: f64, } pub trait Hooks: health::Hooks { + fn field_deploy( + &mut self, + _w: &mut World, + _r: &mut Runtime, + _id: Id, + _fresh: bool, + ) -> Result<(), String> { + Ok(()) + } + + fn operator_removed( + &mut self, + _w: &mut World, + _r: &mut Runtime, + _id: Id, + ) -> Result<(), String> { + Ok(()) + } + fn heal_with_buffs( + &mut self, + w: &mut World, + _r: &mut Runtime, + source: Option, + target: Id, + amount: f64, + options: HealOptions, + ) -> Result + where + Self: Sized, + { + health::heal(w, self, source, target, amount, options) + } + + fn operator_skill_effect( + &mut self, + _w: &mut World, + _r: &mut Runtime, + _dir: super::direction::Direction, + _definition: &super::operators::Definition, + _event: super::skills::Event, + _ctx: &mut super::skills::Context, + _skill: &mut super::skills::Runtime, + ) -> Result<(), String> { + Ok(()) + } + + fn operator_target_status( + &mut self, + _w: &mut World, + _r: &mut Runtime, + _source: Id, + _target: Id, + _key: &str, + _duration: f64, + ) -> Result<(), String> { + Err("Target status handler not installed".into()) + } + fn operator_release( + &mut self, + _w: &mut World, + _r: &mut Runtime, + _id: Id, + ) -> Result<(), String> { + Err("Operator release handler not installed".into()) + } + fn operator_status( + &mut self, + _w: &mut World, + _r: &mut Runtime, + _id: Id, + _key: &str, + _duration: f64, + ) -> Result<(), String> { + Err("Operator control status handler not installed".into()) + } fn burst_damage( &mut self, _request: &mut super::hit::Request, @@ -338,6 +433,14 @@ impl Runtime { .iter() .position(|old| old.key == b.key); if let Some(index) = index.filter(|_| b.runtime.refresh != Refresh::Independent) { + if b.runtime.refresh == Refresh::Replace { + if self.retained.len() >= self.max_retained { + return Err("Retained buff capacity exceeded".into()); + } + if let Some(id) = b.runtime.retained_unit { + w.pin_unit(id)?; + } + } let s = &mut w.unit_mut(unit)?.stats; let old = &mut s.buffs_mut()[index]; let id = old.runtime.id; @@ -377,13 +480,15 @@ impl Runtime { } } _ => { - if self.retained.len() >= self.max_retained { - return Err("Retained buff capacity exceeded".into()); - } let removed = std::mem::replace(old, b); + let retained_unit = removed.runtime.retained_unit; self.retained.insert(id, (unit, removed)); s.mark_dirty(); - return Ok(Some(s.buffs()[index].runtime.id)); + let installed = s.buffs()[index].runtime.id; + if let Some(id) = retained_unit { + w.unpin_unit(id)?; + } + return Ok(Some(installed)); } } old.permanent = old.runtime.persist && old.runtime.duration == f64::INFINITY; @@ -406,10 +511,13 @@ impl Runtime { } } // onRemove may add another instance; enforce capacity again after that callback. - let s = &mut w.unit_mut(unit)?.stats; - if s.buffs().len() >= self.max_buffs { + if w.unit(unit)?.stats.buffs().len() >= self.max_buffs { return Err("Unit buff capacity exceeded; no effects dropped".into()); } + if let Some(id) = b.runtime.retained_unit { + w.pin_unit(id)?; + } + let s = &mut w.unit_mut(unit)?.stats; let id = b.runtime.id; let key = status_key(&b); let visible = b.runtime.visible || b.runtime.status.is_some(); @@ -481,7 +589,11 @@ impl Runtime { let off = (b.runtime.visible || b.runtime.status.is_some()) && !s.buffs().iter().any(|b| status_key(b) == key); let token = b.runtime.on_remove; + let retained_unit = b.runtime.retained_unit; self.retained.insert(id, (unit, b)); + if let Some(id) = retained_unit { + w.unpin_unit(id)?; + } if off { h.status(unit, &key, false)?; } @@ -624,9 +736,9 @@ impl Runtime { u.regen_acc += regen * dt; if u.regen_acc >= 1.0 || u.stats.hp + u.regen_acc >= max { let amount = u.regen_acc; - health::heal( + h.heal_with_buffs( w, - h, + r, Some(unit), unit, amount, @@ -669,6 +781,13 @@ impl Runtime { .runtime .on_tick .ok_or("Buff tick callback removed during interval loop")?; + let count = self + .get(w, unit, id)? + .runtime + .tick_count + .checked_add(1) + .ok_or("Buff tick count exhausted")?; + self.edit_timer(w, unit, id, |b| b.runtime.tick_count = count)?; h.callback(token, Event::Tick, Context { unit, buff: id, dt }, self, w) } } @@ -687,115 +806,3 @@ fn js_max(a: f64, b: f64) -> f64 { a.max(b) } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::battle::{ - health::{Side, Unit}, - stats::{Base, UnitStats}, - }; - struct Host; - impl health::Hooks for Host { - fn kill(&mut self, _: Id, _: Option, _: &mut World) -> Result<(), String> { - unreachable!() - } - } - impl Hooks for Host { - fn status(&mut self, _: Id, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - token: u64, - _: Event, - c: Context, - r: &mut Runtime, - w: &mut World, - ) -> Result<(), String> { - if token == 1 { - r.remove(w, self, c.unit, "b")?; - } else { - r.tick(w, self, &[c.unit], 0.0)?; - } - Ok(()) - } - } - fn world() -> World { - let mut w = World::new(1, 1, 1).unwrap(); - w.insert_unit(1, Unit::new(UnitStats::new(Base::default()), Side::Ally)) - .unwrap(); - w - } - fn named(key: &str) -> Spec { - let mut spec = Spec::default(); - spec.buff.key = Some(key.into()); - spec - } - #[test] - fn deployment_discard_keeps_persistent_effects_and_defers_record_release() { - let mut w = world(); - let mut r = Runtime::new(4, 4, 8).unwrap(); - let mut h = Host; - let mut temporary = named("temporary"); - // This handler would remove b if normal onRemove dispatch ran. - temporary.buff.runtime.on_remove = Some(1); - let id = r.add(&mut w, &mut h, 1, temporary).unwrap().unwrap(); - let mut persistent = named("b"); - persistent.buff.runtime.persist = true; - r.add(&mut w, &mut h, 1, persistent).unwrap(); - r.call(|r| { - r.discard_temporary(&mut w, &mut h, 1)?; - assert_eq!(r.get(&w, 1, id)?.key.as_deref(), Some("temporary")); - assert_eq!(w.unit(1)?.stats.buffs().len(), 1); - assert_eq!(w.unit(1)?.stats.buffs()[0].key.as_deref(), Some("b")); - Ok(()) - }) - .unwrap(); - assert!(r.get(&w, 1, id).is_err()); - assert!(r.retained.is_empty()); - } - #[test] - fn capacity_failure_preserves_existing_effect_and_faults_runtime() { - let mut w = world(); - let mut r = Runtime::new(1, 2, 8).unwrap(); - let mut h = Host; - let id = r.add(&mut w, &mut h, 1, named("a")).unwrap().unwrap(); - assert!(r.add(&mut w, &mut h, 1, named("b")).is_err()); - assert!(r.faulted()); - assert_eq!(w.unit(1).unwrap().stats.buffs().len(), 1); - assert_eq!(r.get(&w, 1, id).unwrap().key.as_deref(), Some("a")); - assert!(r.tick(&mut w, &mut h, &[1], 0.1).is_err()); - } - #[test] - fn nested_removal_failure_clears_retained_records_and_rejects_continuation() { - let mut w = world(); - let mut r = Runtime::new(4, 1, 8).unwrap(); - let mut h = Host; - let mut a = named("a"); - a.buff.runtime.on_remove = Some(1); - r.add(&mut w, &mut h, 1, a).unwrap(); - r.add(&mut w, &mut h, 1, named("b")).unwrap(); - assert!(r.remove(&mut w, &mut h, 1, "a").is_err()); - assert!(r.faulted()); - assert!(r.retained.is_empty()); - assert_eq!(r.depth, 0); - assert_eq!( - w.unit(1).unwrap().stats.buffs()[0].key.as_deref(), - Some("b") - ); - } - #[test] - fn nested_tick_exhaustion_is_a_technical_failure() { - let mut w = world(); - let mut r = Runtime::new(4, 4, 2).unwrap(); - let mut h = Host; - let mut a = named("a"); - a.buff.runtime.on_tick = Some(2); - r.add(&mut w, &mut h, 1, a).unwrap(); - assert!(r.tick(&mut w, &mut h, &[1], 0.0).is_err()); - assert!(r.faulted()); - assert_eq!(r.depth, 0); - assert!(r.retained.is_empty()); - } -} diff --git a/crates/engine/src/battle/cadence.rs b/crates/engine/src/battle/cadence.rs index a4ac525..de73848 100644 --- a/crates/engine/src/battle/cadence.rs +++ b/crates/engine/src/battle/cadence.rs @@ -81,52 +81,3 @@ pub fn tick_unit( u.cadence.tick(dt, can_act); Ok(()) } -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn integer_second_attacks_finish_on_frame_30_and_control_pauses_timer() { - let mut s = State { - cooldown: 1.0, - ..State::default() - }; - s.tick(1.0 / 30.0, false); - assert_eq!(s.cooldown, 1.0); - for _ in 0..29 { - s.tick(1.0 / 30.0, true); - } - assert!(s.cooldown > 0.0); - s.tick(1.0 / 30.0, true); - assert_eq!(s.cooldown, 0.0); - s.cooldown = 0.04; - s.tick(1.0 / 30.0, true); - assert!(s.cooldown > 0.0); - s.tick(1.0 / 30.0, true); - assert_eq!(s.cooldown, 0.0); - } - #[test] - fn reselecting_aoe_heals_and_idle_units_do_not_commit() { - let s = State { - cooldown: 0.0, - had_target: Some(false), - }; - assert!(!s.may_commit(1.0 / 30.0, true, false, true, Profile::default())); - let s = State::default(); - for p in [ - Profile { - range_aoe: true, - ..Profile::default() - }, - Profile { - heal_attack: true, - ..Profile::default() - }, - Profile { - all_in_range: true, - ..Profile::default() - }, - ] { - assert!(!s.may_commit(1.0 / 30.0, true, false, true, p)); - } - } -} diff --git a/crates/engine/src/battle/clock.rs b/crates/engine/src/battle/clock.rs index 85bb003..a903139 100644 --- a/crates/engine/src/battle/clock.rs +++ b/crates/engine/src/battle/clock.rs @@ -38,6 +38,10 @@ pub struct EndState { pub max_battle_time: f64, } pub trait Host: Sized { + /// Advance a proven event-free movement window, or return zero to use full ticks. + fn movement_batch(&mut self, _clock: &mut Clock, _budget: usize) -> Result { + Ok(0) + } fn phase(&mut self, phase: Phase, clock: &mut Clock) -> Result<(), String>; fn compact_enemies(&mut self, clock: &mut Clock) -> Result<(), String>; fn has_removed(&self) -> bool; @@ -55,6 +59,7 @@ pub struct Clock { stepping: bool, faulted: bool, ticks: u64, + movement_ticks: u64, time: f64, request: Option, reason: Option, @@ -69,6 +74,21 @@ impl Clock { pub fn ticks(&self) -> u64 { self.ticks } + pub fn movement_ticks(&self) -> u64 { + self.movement_ticks + } + pub(crate) fn movement_tick(&mut self) -> Result<(), String> { + self.ticks = self + .ticks + .checked_add(1) + .ok_or("Battle tick count exhausted")?; + self.movement_ticks = self + .movement_ticks + .checked_add(1) + .ok_or("Movement tick count exhausted")?; + self.time = self.ticks as f64 * DT; + Ok(()) + } pub fn started(&self) -> bool { self.started } @@ -230,6 +250,29 @@ impl Clock { } let mut n = 0; while n < budget && !self.finished { + if self.started && budget - n >= 2 && self.request.is_none() && !self.stepping { + let before = self.ticks; + self.stepping = true; + let batch = host.movement_batch(self, budget - n); + self.stepping = false; + let count = match batch { + Ok(count) if count <= budget - n && self.ticks - before == count as u64 => { + count + } + Ok(_) => { + self.faulted = true; + return Err("Invalid movement batch accounting".into()); + } + Err(error) => { + self.faulted = true; + return Err(error); + } + }; + if count > 0 { + n += count; + continue; + } + } self.step(host)?; n += 1; } @@ -240,25 +283,24 @@ impl Clock { #[cfg(test)] mod tests { use super::*; - #[derive(Default)] - struct Driver { - fail: bool, - request_on_scheduled: bool, - calls: usize, - finishes: usize, + + struct MovingHost { + invalid: bool, } - impl Host for Driver { - fn phase(&mut self, p: Phase, c: &mut Clock) -> Result<(), String> { - self.calls += 1; - if p == Phase::Start { - c.mark_started(); + impl Host for MovingHost { + fn movement_batch(&mut self, clock: &mut Clock, budget: usize) -> Result { + if self.invalid { + return Ok(budget); } - if self.fail && p == Phase::Scheduled { - return Err("scheduled callback failed".into()); + let count = budget.min(4); + for _ in 0..count { + clock.movement_tick()?; } - if self.request_on_scheduled && p == Phase::Scheduled { - c.force_end(self, "timeout".into())?; - c.force_end(self, "later request".into())?; + Ok(count) + } + fn phase(&mut self, phase: Phase, clock: &mut Clock) -> Result<(), String> { + if phase == Phase::Start { + clock.mark_started(); } Ok(()) } @@ -269,63 +311,41 @@ mod tests { false } fn release_removed(&mut self, _: &mut Clock) -> Result<(), String> { - unreachable!() + Ok(()) } fn has_tick_hook(&self) -> bool { false } fn finish(&mut self, _: &End, _: &Clock) -> Result<(), String> { - self.finishes += 1; Ok(()) } } + #[test] - fn time_is_tick_multiple_and_budget_does_not_terminate() { - let mut c = Clock::new(); - let mut h = Driver::default(); - assert_eq!(c.run_steps(&mut h, 9000).unwrap(), 9000); - assert_eq!(c.time().to_bits(), (9000.0 * DT).to_bits()); - assert!(!c.finished()); - assert_eq!(h.finishes, 0); - assert_eq!(c.run_steps(&mut h, 0).unwrap(), 0); - assert_eq!(c.ticks(), 9000); - c.force_end(&mut h, "external".into()).unwrap(); - assert_eq!(c.run_steps(&mut h, 10).unwrap(), 0); - assert_eq!(h.finishes, 1); - } - #[test] - fn first_end_request_wins_and_external_end_starts_battle() { - let mut c = Clock::new(); - let mut h = Driver { - request_on_scheduled: true, - ..Driver::default() - }; - c.step(&mut h).unwrap(); - assert_eq!(c.reason(), Some(&End::Timeout)); - assert_eq!(c.ticks(), 0); - assert_eq!(h.finishes, 1); - let mut fresh = Clock::new(); - let mut host = Driver::default(); - fresh.force_end(&mut host, "anything".into()).unwrap(); - assert!(fresh.started()); - assert_eq!(fresh.reason(), Some(&End::Forced)); - assert_eq!(host.calls, 1); + fn movement_batches_respect_tick_budgets() { + let mut host = MovingHost { invalid: false }; + let mut clock = Clock::new(); + let mut total = 0; + for budget in [0, 1, 2, 3, 4, 17, 64, 65] { + assert_eq!(clock.run_steps(&mut host, budget).unwrap(), budget); + total += budget as u64; + assert_eq!(clock.ticks(), total); + assert_eq!(clock.time().to_bits(), (total as f64 * DT).to_bits()); + } + assert!(clock.movement_ticks() > 100); + assert!(clock.movement_ticks() < total); } + #[test] - fn phase_failure_never_becomes_a_valid_continuation() { - let mut c = Clock::new(); - let mut h = Driver { - fail: true, - ..Driver::default() - }; - assert!(c.step(&mut h).is_err()); - assert!(c.faulted()); - assert!(!c.finished()); - assert_eq!(c.ticks(), 0); - let calls = h.calls; - h.fail = false; - assert!(c.step(&mut h).is_err()); - assert_eq!(h.calls, calls); - assert_eq!(h.finishes, 0); + fn invalid_movement_accounting_faults_the_clock() { + let mut host = MovingHost { invalid: true }; + let mut clock = Clock::new(); + clock.run_steps(&mut host, 1).unwrap(); + assert_eq!( + clock.run_steps(&mut host, 2).unwrap_err(), + "Invalid movement batch accounting" + ); + assert!(clock.faulted()); + assert!(clock.run_steps(&mut host, 1).is_err()); } } diff --git a/crates/engine/src/battle/content/enemies.rs b/crates/engine/src/battle/content/enemies.rs index 474a6db..a381752 100644 --- a/crates/engine/src/battle/content/enemies.rs +++ b/crates/engine/src/battle/content/enemies.rs @@ -8,32 +8,119 @@ use crate::battle::{ stats::Buff, }; use serde_json::Value; -use std::collections::BTreeMap; +use std::{collections::BTreeMap, sync::Arc}; + +mod abilities; +pub(crate) mod bosses; +pub use bosses::Boss; +pub(crate) mod specials; +pub use specials::Special; +pub(crate) mod terrain; +pub use terrain::TerrainKit; +pub(crate) mod casters; +pub use casters::Caster; +pub(crate) mod leaders; +pub(crate) mod supporters; +pub use leaders::Leader; +pub use supporters::Supporter; +pub(crate) mod lifecycle; +pub(crate) mod movement; +pub use lifecycle::Lifecycle; +pub use movement::Movement; +mod families; +pub(crate) mod forms; +pub(crate) mod reactions; +pub(crate) mod zones; +pub use forms::Form; +pub use reactions::Reaction; +pub use zones::ZoneKit; +mod splits; +pub use abilities::Ability; +pub use families::{Family, Prisoner}; +pub use splits::Split; #[derive(Clone, Copy, Debug)] pub enum Kit { Plain, + Boss(Boss), + Special(Special), + Terrain(TerrainKit), + Caster(Caster), + Leader(Leader), + Supporter(Supporter), + Movement(Movement), + Lifecycle(Lifecycle), + Reaction(Reaction), + Form(Form), + Zone(ZoneKit), + Ability(Ability), + Family(Family), + Split(Split), Stealth { restore: f64 }, Times { arts_only: bool }, Refraction { res: f64, hp_pct: f64 }, Element { kind: Element, ratio: f64 }, } -fn talent(raw: &Value, overrides: &Value, keys: &[&str]) -> f64 { +fn talent_value(raw: &Value, overrides: &Value, key: &str) -> Option { let base = raw["talents"] .get("bb") .filter(|v| !v.is_null()) .unwrap_or(&raw["talent"]); + overrides["talents"]["bb"] + .get(key) + .or_else(|| base.get(key)) + .and_then(Value::as_f64) + .filter(|n| n.is_finite()) +} +fn talent(raw: &Value, overrides: &Value, keys: &[&str]) -> f64 { keys.iter() - .find_map(|key| { - overrides["talents"]["bb"] - .get(*key) - .or_else(|| base.get(*key)) - .and_then(Value::as_f64) - .filter(|n| n.is_finite()) - }) + .find_map(|key| talent_value(raw, overrides, key)) .unwrap_or(0.) } + impl Kit { + pub(crate) fn validate_tag(self, tag: Option<&str>) -> Result<(), String> { + let supported = match tag { + Some("boss") => matches!( + self, + Self::Boss( + Boss::Helm(_) + | Boss::Gun(_) + | Boss::Lion(_) + | Boss::Deer(_) + | Boss::Pipe(_) + | Boss::Quintus(_) + ) | Self::Caster(Caster { + passive: casters::Passive::Lucien { .. }, + .. + }) + ), + Some("part") => matches!( + self, + Self::Boss( + Boss::Blade(_) + | Boss::Shell { .. } + | Boss::Spring(_) + | Boss::Pipe(_) + | Boss::Echo(_) + | Boss::Equipment + ) + ), + _ => true, + }; + if supported { + Ok(()) + } else { + Err("Boss or part tag requires an implemented kit".into()) + } + } + pub(crate) fn rebirth(self) -> Option<(f64, f64, f64)> { + match self { + Self::Lifecycle(k) => k.rebirth(), + Self::Caster(c) => c.rebirth(), + _ => None, + } + } /// Explicit content dispatch, not an inference from an enemy's name or tags. pub fn compile( key: &str, @@ -43,7 +130,61 @@ impl Kit { ) -> Result { let original_key = key; let key = raw["effectRef"].as_str().unwrap_or(key); + if let Some(kit) = Boss::compile(key, raw, overrides)? { + return Ok(Self::Boss(kit)); + } + if let Some(kit) = Special::compile(key, raw, overrides)? { + return Ok(Self::Special(kit)); + } + if let Some(kit) = TerrainKit::compile(key, raw, overrides)? { + return Ok(Self::Terrain(kit)); + } + if let Some(kit) = Caster::compile(key, raw, overrides)? { + return Ok(Self::Caster(kit)); + } + if let Some(kit) = Leader::compile(key, raw, overrides)? { + return Ok(Self::Leader(kit)); + } + if let Some(kit) = Supporter::compile(key, raw, overrides)? { + return Ok(Self::Supporter(kit)); + } + if let Some(kit) = Movement::compile(key, raw, overrides, tag) { + return Ok(Self::Movement(kit)); + } + if let Some(kit) = Lifecycle::compile(key, raw, overrides)? { + return Ok(Self::Lifecycle(kit)); + } + if let Some(reaction) = Reaction::compile(key, raw, overrides)? { + return Ok(Self::Reaction(reaction)); + } + if let Some(form) = Form::compile(key, raw, overrides)? { + return Ok(Self::Form(form)); + } + if let Some(zone) = ZoneKit::compile(key, raw, overrides)? { + return Ok(Self::Zone(zone)); + } + if let Some(split) = Split::compile(key, raw, overrides)? { + return Ok(Self::Split(split)); + } + if let Some(family) = Family::compile(key, raw, overrides, original_key, tag)? { + return Ok(Self::Family(family)); + } + if let Some(ability) = Ability::compile(key, raw, overrides)? { + return Ok(Self::Ability(ability)); + } Ok(match key { + "enemy_2009_csaudc" => Self::Element { + kind: Element::Neural, + ratio: talent(raw, overrides, &["combat.attack@ep_damage_ratio"]), + }, + "enemy_10094_crstf" => Self::Element { + kind: Element::Neural, + ratio: talent(raw, overrides, &["ep.ep_damage_ratio"]), + }, + "enemy_10099_crvln" => Self::Element { + kind: Element::Neural, + ratio: talent(raw, overrides, &["inside.attack@ep_damage_ratio"]), + }, "enemy_1148_dssbr" | "enemy_1148_dssbr_2" => Self::Element { kind: Element::Neural, ratio: talent(raw, overrides, &["epdamage.attack@ep_damage_ratio"]), @@ -157,16 +298,102 @@ impl Kit { }) } } -#[derive(Clone, Copy)] -struct State { +#[derive(Clone)] +pub(crate) struct Definition { kit: Kit, + child: Option>, + branch: Option>, + quintus: Option>, +} +impl Definition { + pub(crate) fn compile( + key: &str, + raw: &Value, + overrides: &Value, + tag: Option<&str>, + ) -> Result { + let kit = Kit::compile(key, raw, overrides, tag)?; + let child = if matches!(kit, Kit::Boss(Boss::Helm(_))) { + Some(Arc::from( + abilities::skill(raw, overrides, "2")["bbStr"]["enemy_key"] + .as_str() + .unwrap_or("enemy_1005_yokai"), + )) + } else if matches!(kit, Kit::Boss(Boss::Pipe(_))) { + Some(Arc::from( + overrides["talents"]["bbStr"] + .get("1.enemy_key") + .or_else(|| raw["talents"]["bbStr"].get("1.enemy_key")) + .and_then(Value::as_str) + .unwrap_or("enemy_9023_acdums"), + )) + } else if let Kit::Split(split) = kit { + let field = if matches!(split, Split::Boat { .. }) { + "DeathRattle.enemy_key" + } else { + "DeadSpawn.enemy_key" + }; + overrides["talents"]["bbStr"] + .get(field) + .or_else(|| raw["talents"]["bbStr"].get(field)) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .map(Arc::from) + } else if matches!(kit, Kit::Supporter(Supporter::Torturer { .. })) { + overrides["talents"]["bbStr"] + .get("Summon.enemy_key") + .or_else(|| raw["talents"]["bbStr"].get("Summon.enemy_key")) + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .map(Arc::from) + } else { + None + }; + let branch = matches!(kit, Kit::Boss(Boss::Helm(_))).then(|| { + Arc::from( + abilities::skill(raw, overrides, "2")["bbStr"]["branch_id"] + .as_str() + .unwrap_or("boss_summon_enemy"), + ) + }); + let quintus = matches!(kit, Kit::Boss(Boss::Quintus(_))) + .then(|| Arc::new(bosses::quintus::Stages::compile(raw, overrides))); + Ok(Self { + kit, + child, + branch, + quintus, + }) + } +} +#[derive(Clone)] +struct State { + definition: Definition, on: Option, hp_lost: bool, + count: u32, + accumulator: f64, + memory: families::Memory, + form: Option, + tank: Option, + reaction: reactions::Memory, + movement: movement::Memory, + lifecycle: lifecycle::Memory, + leader: leaders::Memory, + caster: casters::State, + boss: bosses::Memory, + terrain: terrain::State, + special: specials::Memory, + supporter: supporters::Memory, + drone: Option, } pub struct Runtime { units: BTreeMap, capacity: usize, faulted: bool, + freed_all: bool, + chalices: usize, + lp_loss: f64, } fn flag_buff(key: &str, flag: &str) -> Buff { let mut b = Buff::default(); @@ -184,16 +411,36 @@ impl Runtime { units: BTreeMap::new(), capacity, faulted: false, + freed_all: false, + chalices: 0, + lp_loss: 0., }) } + pub(crate) fn has_chalices(&self) -> bool { + self.chalices > 0 + } pub fn faulted(&self) -> bool { self.faulted } pub fn retained(&self) -> usize { self.units.len() } + pub(crate) fn branch(&self, id: Id) -> Option> { + self.units + .get(&id) + .and_then(|s| s.definition.branch.clone()) + } + pub(crate) fn child(&self, id: Id) -> Option> { + self.units.get(&id).and_then(|s| s.definition.child.clone()) + } pub fn remove(&mut self, id: Id) { - self.units.remove(&id); + if self + .units + .remove(&id) + .is_some_and(|s| matches!(s.definition.kit, Kit::Terrain(TerrainKit::Chalice { .. }))) + { + self.chalices -= 1; + } } /// The actual `damaged` callback: one proc per resolved normal-attack damage /// instance, before fatal removal. Caller immediately applies the returned @@ -218,8 +465,19 @@ impl Runtime { let Some(state) = self.units.get(&source) else { return Ok(None); }; - let Kit::Element { kind, ratio } = state.kit else { - return Ok(None); + let (kind, ratio) = match state.definition.kit { + Kit::Element { kind, ratio } => (kind, ratio), + Kit::Caster(Caster { + passive: casters::Passive::DeathEye { element }, + .. + }) => (Element::Apoptosis, element), + Kit::Movement(Movement::Syufo { erosion }) => (Element::Erosion, erosion), + Kit::Lifecycle(Lifecycle::Reborn { neural, .. }) => (Element::Neural, neural), + Kit::Ability(Ability::Song { neural, .. }) => (Element::Neural, neural), + Kit::Split(Split::Boat { erosion }) => (Element::Erosion, erosion), + Kit::Ability(Ability::Power { erosion, .. }) + | Kit::Ability(Ability::Tide { erosion }) => (Element::Erosion, erosion), + _ => return Ok(None), }; if !(ratio > 0.) || !w.unit(request.hit.target)?.stats.alive { return Ok(None); @@ -260,6 +518,30 @@ impl Runtime { kit: Kit, mods: &Value, ) -> Result<(), String> { + self.install( + w, + r, + h, + id, + Definition { + kit, + child: None, + branch: None, + quintus: None, + }, + mods, + ) + } + pub(crate) fn install( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + definition: Definition, + mods: &Value, + ) -> Result<(), String> { + let kit = definition.kit; self.call(r, |this, r| { if w.unit(id)?.side != Side::Enemy { return Err("Enemy kit installed on a non-enemy".into()); @@ -270,15 +552,86 @@ impl Runtime { if this.units.len() >= this.capacity { return Err("Enemy content capacity exceeded".into()); } + if matches!(kit, Kit::Terrain(TerrainKit::Chalice { .. })) { + this.chalices += 1; + } this.units.insert( id, State { - kit, + drone: None, + boss: match kit { + Kit::Boss(k) => k.memory(w.unit(id)?.position, w.time), + _ => bosses::Memory::None, + }, + special: match kit { + Kit::Special(k) => k.memory(), + _ => specials::Memory::None, + }, + terrain: terrain::State::default(), + caster: match kit { + Kit::Caster(k) => k.state(), + Kit::Boss(k) => definition + .quintus + .as_ref() + .map(|q| q.casters[0]) + .unwrap_or_else(|| k.caster()) + .state(), + _ => casters::State::default(), + }, + leader: match kit { + Kit::Leader(k) => k.memory(), + _ => leaders::Memory::None, + }, + supporter: match kit { + Kit::Supporter(k) => k.memory(), + _ => supporters::Memory::None, + }, + movement: match kit { + Kit::Movement(k) => k.memory(), + _ => movement::Memory::None, + }, + lifecycle: match kit { + Kit::Lifecycle(k) => k.memory(w.time), + _ => lifecycle::Memory::None, + }, + reaction: match kit { + Kit::Reaction(k) => k.memory(w.unit(id)?.position), + _ => reactions::Memory::None, + }, + form: match kit { + Kit::Form(f) => Some(f.state()), + _ => None, + }, + tank: match kit { + Kit::Zone(ZoneKit::Tank(t)) => Some(zones::TankState { + sp: t.initial, + skill: false, + }), + _ => None, + }, + definition, on: None, hp_lost: false, + count: 0, + accumulator: 0., + memory: match kit { + Kit::Family(f) => f.memory(), + Kit::Split(s) => s.memory(), + _ => families::Memory::None, + }, }, ); match kit { + Kit::Boss(k) => k.spawn(w, r, h, id)?, + Kit::Special(k) => k.spawn(w, r, h, id)?, + Kit::Caster(k) => k.spawn(w, r, h, id)?, + Kit::Lifecycle(k) => k.spawn(w, r, h, id)?, + Kit::Supporter(k) => k.spawn(w, r, h, id)?, + Kit::Movement(k) => k.spawn(w, r, h, id)?, + Kit::Reaction(reaction) => reaction.spawn(w, r, h, id)?, + Kit::Split(split) => split.spawn(w, r, h, id)?, + Kit::Family(family) => family.spawn(w, r, h, id)?, + Kit::Ability(ability) => Self::spawn_ability(w, r, h, id, ability)?, Kit::Stealth { restore } => { let mut b = flag_buff("ab:stealth", "stealth"); b.runtime.stealth_restore = Some(restore); @@ -356,14 +709,17 @@ impl Runtime { return Err("Invalid enemy content tick limits".into()); } for &id in ids { - let Some(state) = this.units.get(&id).copied() else { + // Read the kit without copying the whole runtime state; most + // enemies have no refraction at all. + let Some(state) = this.units.get(&id) else { continue; }; + let refraction = state.definition.kit.refraction(); let u = w.unit(id)?; if !u.stats.alive || u.enemy.carrier.is_some() { continue; } - if let Kit::Refraction { res, hp_pct } = state.kit { + if let Some((res, hp_pct)) = refraction { let on = !w .unit_mut(id)? .stats diff --git a/crates/engine/src/battle/content/enemies/abilities.rs b/crates/engine/src/battle/content/enemies/abilities.rs new file mode 100644 index 0000000..6d8a399 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/abilities.rs @@ -0,0 +1,323 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Stronghold Protocol content/enemies/{archetypes,special,fly}.js. +use super::*; + +#[derive(Clone, Copy, Debug)] +pub enum Ability { + Unblockable, + Bleed { + amount: f64, + duration: f64, + }, + Nest { + ratio: f64, + radius: f64, + resist: f64, + }, + Boil { + interval: f64, + radius: f64, + scale: f64, + burn: f64, + }, + Expose { + duration: f64, + scale: f64, + }, + Tide { + erosion: f64, + }, + Nucleus { + speed: f64, + interval: f64, + radius: f64, + neural: f64, + }, + Taunt(f64), + HitShield(u32), + MaxTargets(f64), + LowHp(f64), + Run(f64), + DefDecay { + max: u32, + def: f64, + res: f64, + }, + FrozenPower(f64), + Stun { + every: u32, + duration: f64, + }, + Power { + every: u32, + scale: f64, + erosion: f64, + }, + Song { + every: u32, + duration: f64, + aspd: f64, + neural: f64, + }, + Frost { + radius: f64, + aspd: f64, + }, + Enhance { + interval: f64, + speed: f64, + atk: f64, + }, + SelfDamage(f64), + DeathBoom { + radius: f64, + scale: f64, + cold: Option, + }, +} +pub(super) fn count(n: f64) -> Result { + if !n.is_finite() || n < 0. || n.ceil() > i32::MAX as f64 { + return Err("Enemy ability count outside nonnegative i32 domain".into()); + } + Ok(n.ceil() as u32) +} +pub(super) fn skill<'a>(raw: &'a Value, overrides: &'a Value, key: &str) -> &'a Value { + overrides + .get("skills") + .and_then(Value::as_array) + .or_else(|| raw["skills"].as_array()) + .and_then(|a| a.iter().find(|s| s["prefabKey"] == key)) + .unwrap_or(&Value::Null) +} +fn number(v: &Value, default: f64) -> f64 { + v.as_f64().filter(|v| v.is_finite()).unwrap_or(default) +} +fn every(s: &Value) -> Result { + let sp = number(&s["spCost"], 0.); + count(if sp > 0. { sp + 1. } else { 3. }) +} +impl Ability { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key| talent(raw, ov, &[key]); + let value = |key, default| talent_value(raw, ov, key).unwrap_or(default); + Ok(Some(match key { + "enemy_1270_nhstlk" | "enemy_1270_nhstlk_2" => Self::Bleed { + amount: t("Bleeding.attack@bleeding_damage"), + duration: t("Bleeding.attack@duration"), + }, + "enemy_1234_dsubrl" | "enemy_1234_dsubrl_2" => { + let resist = -value("Buff.one_minus_status_resistance", -0.5); + Self::Nest { + ratio: t("EpDamage.ep_damage_ratio"), + radius: raw["stats"]["rangeRadius"] + .as_f64() + .filter(|n| n.is_finite() && *n != 0.) + .unwrap_or(1.6), + resist: if resist > 0. { resist.min(1.) } else { 0.5 }, + } + } + "enemy_10054_cjhot" => Self::Boil { + interval: raw["stats"]["bat"] + .as_f64() + .filter(|n| n.is_finite() && *n != 0.) + .unwrap_or(1.), + radius: raw["stats"]["rawRangeRadius"] + .as_f64() + .filter(|n| n.is_finite() && *n != 0.) + .unwrap_or(1.6), + scale: value("aoe.atk_scale", 1.), + burn: t("aoe.ep_damage_ratio"), + }, + "enemy_1402_tgshd_2" => Self::Expose { + duration: t("Expose.weak[limit]"), + scale: value("Expose.damage_scale", 1.), + }, + "enemy_1161_tidmag" | "enemy_1161_tidmag_2" => Self::Tide { + erosion: t("EpDamage.attack@ep_damage_ratio"), + }, + "enemy_1439_dslntf" | "enemy_1439_dslntf_2" => Self::Nucleus { + speed: value("0.move_speed", 1.), + interval: value("1.interval", 1.), + radius: t("1.range_radius"), + neural: t("1.ep_damage_ratio"), + }, + "enemy_1026_aghost" => Self::Unblockable, + "enemy_1081_sotisd" => Self::Taunt(t("taunt.taunt_level")), + "enemy_1249_lysdb_2" => Self::HitShield(count(t("Shield.max_block_damage_cnt"))?), + "enemy_1501_demonk" | "enemy_10018_sgrobh" => Self::MaxTargets(2.), + "enemy_1025_reveng" => Self::LowHp(t("atkup.atk")), + "enemy_2001_duckmi" | "enemy_2001_duckmi_2" => Self::Run(t("run.attack@move_speed")), + "enemy_1329_cbshld" | "enemy_1329_cbshld_2" => Self::DefDecay { + max: count(t("def_reduce.max_stack_cnt"))?, + def: t("def_reduce.def"), + res: t("def_reduce.magic_resistance"), + }, + "enemy_1069_icebrk_2" => Self::FrozenPower(value("atkup.atk_scale", 1.)), + "enemy_1045_hammer" | "enemy_1045_hammer_2" => { + let s = skill(raw, ov, "stuncombat"); + Self::Stun { + every: every(s)?, + duration: number(&s["bb"]["stun"], 0.), + } + } + "enemy_1183_mlasrt" => { + let s = skill(raw, ov, "PowerAttack"); + Self::Power { + every: every(s)?, + scale: number(&s["bb"]["atk_scale"], 1.), + erosion: t("EpDamage.attack@ep_damage_ratio"), + } + } + "enemy_2010_csdcr" => Self::Song { + every: talent_value(raw, ov, "AttackSpeedUp.stack_cnt") + .map(|n| count(n.max(1.))) + .transpose()? + .unwrap_or(0), + duration: t("AttackSpeedUp.duration"), + aspd: t("AttackSpeedUp.attack_speed"), + neural: t("attack.attack@ep_damage_ratio"), + }, + "enemy_1042_frostd" => Self::Frost { + radius: value("defup.range_radius", 2.5), + aspd: t("atkSpeedDown.attack_speed") * 100., + }, + "enemy_10087_hlchgr" => { + let s = skill(raw, ov, "ForeverEnhance"); + Self::Enhance { + interval: value("SkillTrigger.interval", 6.), + speed: number(&s["bb"]["move_speed_add"], 0.), + atk: number(&s["bb"]["atk_add"], 0.), + } + } + "enemy_1062_rager_2" => Self::SelfDamage(t("periodic_damage.damage")), + "enemy_1021_bslime" => Self::DeathBoom { + radius: 1.25, + scale: t("boom.atk_scale"), + cold: None, + }, + "enemy_1067_snslime" => Self::DeathBoom { + radius: number(&raw["stats"]["rawRangeRadius"], 0.).max(0.), + scale: t("boom.atk_scale"), + cold: Some(t("boom.freeze")), + }, + _ => return Ok(None), + })) + } +} +impl Runtime { + const PLAIN: Kit = Kit::Plain; + pub(crate) fn kit(&self, id: Id) -> Kit { + self.units + .get(&id) + .map(|s| s.definition.kit) + .unwrap_or(Kit::Plain) + } + /// Read-only kit access for hot dispatch paths that only inspect a variant. + pub(crate) fn kit_ref(&self, id: Id) -> &Kit { + self.units + .get(&id) + .map(|s| &s.definition.kit) + .unwrap_or(&Self::PLAIN) + } + pub(crate) fn trigger_once(&mut self, id: Id) -> bool { + let Some(s) = self.units.get_mut(&id) else { + return false; + }; + if s.on == Some(true) { + return false; + } + s.on = Some(true); + true + } + /// Counters wrap at their ability's period, independently of the world's attack IDs. + pub(crate) fn counted(&mut self, id: Id, every: u32) -> bool { + if every == 0 { + return false; + } + let Some(s) = self.units.get_mut(&id) else { + return false; + }; + s.count = s.count.saturating_add(1); + if s.count < every { + return false; + } + s.count = 0; + true + } + pub(crate) fn before_attack(&mut self, id: Id) { + if let Some(s) = self.units.get_mut(&id) { + if let Kit::Ability(Ability::Power { every, .. }) = s.definition.kit { + s.on = Some(s.count + 1 == every); + } + } + } + pub(crate) fn triggered(&self, id: Id) -> bool { + self.units.get(&id).is_some_and(|s| s.on == Some(true)) + } + /// Pausing a silenced interval keeps its phase. Catch-up matches the source's four-pulse cap. + pub(crate) fn pulses(&mut self, id: Id, dt: f64, interval: f64) -> usize { + let s = self.units.get_mut(&id).unwrap(); + if interval <= 0. { + return 1; + } + s.accumulator += dt; + let mut n = 0; + while s.accumulator >= interval - 1e-9 && n < 4 { + s.accumulator -= interval; + n += 1; + } + n + } + pub(crate) fn enhance(&mut self, id: Id) -> bool { + let s = self.units.get_mut(&id).unwrap(); + if s.count == 5 { + return false; + } + s.count += 1; + true + } + pub(super) fn spawn_ability( + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ability: Ability, + ) -> Result<(), String> { + if matches!(ability, Ability::Nest { .. } | Ability::Boil { .. }) { + w.unit_mut(id)?.immune.insert("sluggish".into()); + } + let b = match ability { + Ability::Unblockable | Ability::Run(_) => flag_buff("ab:unblockable", "unblockable"), + Ability::Taunt(n) if n != 0. => { + let mut b = Buff::default(); + b.key = Some("ab:taunt".into()); + b.runtime.persist = true; + b.mods.insert("taunt".into(), n); + b + } + Ability::HitShield(n) if n > 0 => { + let mut b = Buff::default(); + b.key = Some("ab:hitShield".into()); + b.runtime.shield_hits = n; + b.runtime.injury.shield_types = Some(vec![ + crate::battle::damage::DamageType::Physical, + crate::battle::damage::DamageType::Arts, + ]); + b + } + _ => return Ok(()), + }; + r.add( + w, + h, + id, + Spec { + mods_present: !b.mods.is_empty(), + flags_present: !b.flags.is_empty(), + buff: b, + ..Spec::default() + }, + )?; + Ok(()) + } +} diff --git a/crates/engine/src/battle/content/enemies/bosses.rs b/crates/engine/src/battle/content/enemies/bosses.rs new file mode 100644 index 0000000..02ae597 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/bosses.rs @@ -0,0 +1,533 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::{ + casters::{Caster, Passive, Spell}, + *, +}; +pub(crate) mod ensemble; +pub(crate) mod gun; +pub(crate) mod quintus; +pub use ensemble::{Echo, EchoForm, Pipe}; +pub use quintus::Quintus; +pub(crate) mod helm; +pub use gun::{Gun, Spring, SpringKind}; +pub use helm::{Blade, Helm}; +#[derive(Clone, Copy, Debug)] +pub struct Store { + pub count: usize, + pub scale: f64, + pub shield: f64, + pub cut: f64, +} +#[derive(Clone, Copy, Debug)] +pub struct Lion { + pub caster: Caster, + pub advance: f64, + pub defense: f64, + pub resistance: f64, + pub cost: f64, + pub stores: [Store; 2], +} +#[derive(Clone, Copy, Debug)] +pub struct Deer { + pub caster: Caster, + pub resistance: f64, + pub columns: usize, + pub surge: usize, +} +#[derive(Clone, Copy, Debug)] +pub enum Boss { + Pipe(Pipe), + Echo(Echo), + Quintus(Quintus), + Gun(Gun), + Spring(Spring), + Helm(Helm), + Blade(Blade), + Shell { stun: f64, dot: f64 }, + Lion(Lion), + Deer(Deer), + Equipment, +} +#[derive(Clone, Debug)] +pub(crate) enum Memory { + Pipe { + acc: f64, + attack: f64, + held_until: f64, + }, + Echo(ensemble::EchoState), + Quintus(quintus::QuintusState), + Gun(gun::GunState), + Spring(gun::SpringState), + Helm { + low: bool, + }, + Blade { + phase: helm::BladePhase, + home: [f64; 2], + }, + Shell { + target: Option, + }, + None, + Lion { + sp: f64, + advanced: bool, + next_anim: Option, + wand: bool, + }, + Deer { + low: bool, + acc: f64, + held_until: f64, + }, +} +impl Boss { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + if let Some(boss) = Self::ensemble(key, raw, ov)? { + return Ok(Some(boss)); + } + if let Some(boss) = Self::quintus(key, raw, ov) { + return Ok(Some(boss)); + } + if let Some(boss) = Self::gun(key, raw, ov)? { + return Ok(Some(boss)); + } + if let Some(boss) = Self::helm(key, raw, ov)? { + return Ok(Some(boss)); + } + let t = |key, default| talent_value(raw, ov, key).unwrap_or(default); + let sk = |key| abilities::skill(raw, ov, key); + let n = |v: &Value, default| v.as_f64().filter(|v| v.is_finite()).unwrap_or(default); + let bb = |key, field, default| n(&sk(key)["bb"][field], default); + let make = |key, spell, clip| { + casters::ability(raw, ov, key, spell, clip, true, false).map(|mut s| { + s.own = false; + s + }) + }; + let caster = |skills| Caster { + passive: Passive::Plain, + skills, + }; + Ok(Some(match key { + "enemy_9032_aclionk" => { + let cost = n(&sk("equip")["spCost"], 0.); + let store = |key, count| -> Result { + Ok(Store { + count: if key == "store" { + 1 + } else { + abilities::count(bb(key, "max_target", count).max(0.).floor())? as usize + }, + scale: bb(key, "atk_scale", 0.), + shield: bb(key, "dynamic", 0.), + cut: bb(key, "damage_resistance", 0.), + }) + }; + Self::Lion(Lion { + caster: caster([ + make( + "equip", + Spell::Decree { + scales: [ + bb("equip", "atk_scale", 0.), + bb("equipA", "atk_scale", bb("equip", "atk_scale", 0.)), + ], + }, + 3.667, + ), + make( + "Suicide", + Spell::Repel { + scale: bb("Suicide", "atk_scale", 0.), + loss: bb("Suicide", "value", 0.).abs(), + }, + 5.667, + ), + None, + None, + ]), + advance: t("advance.hp_ratio", 0.), + defense: t("advance.def", 0.), + resistance: t("advance.magic_resistance", 0.), + cost: if sk("equip").is_null() { + f64::INFINITY + } else if cost > 0. { + cost + } else { + 25. + }, + stores: [ + store("store", 1.)?, + if sk("storeA").is_null() { + store("store", 1.)? + } else { + store("storeA", 2.)? + }, + ], + }) + } + "enemy_9033_acdeer" => Self::Deer(Deer { + caster: caster([ + make( + "Lasso", + Spell::Surge { + max: abilities::count(bb("Lasso", "max_target", 1.).max(0.).floor())? + as usize, + duration: bb("Lasso", "projectile_life_time", 0.), + scale: bb("Lasso", "atk_scale", 0.), + }, + 0., + ), + make( + "Doom", + Spell::Repel { + scale: bb("Doom", "atk_scale", 0.), + loss: bb("Doom", "value", 0.).abs(), + }, + 2.667, + ), + None, + None, + ]), + resistance: t("Madness.damage_resistance", 0.), + columns: abilities::count( + t("Madness.enemy_smdeer_mad[attack].max_cnt", 1.) + .max(0.) + .ceil(), + )? as usize, + surge: abilities::count( + t("Madness.enemy_smdeer_mad[skill].max_target", 1.) + .max(0.) + .floor(), + )? as usize, + }), + "enemy_10028_vtswd" | "enemy_10029_vtshld" | "enemy_10030_vtwand" => Self::Equipment, + _ => return Ok(None), + })) + } + pub(crate) fn caster(self) -> Caster { + self.caster_ref().copied().unwrap_or(casters::EMPTY) + } + /// Embedded caster configuration; dynamic Quintus and synthetic parts have none. + pub(crate) fn caster_ref(&self) -> Option<&Caster> { + match self { + Self::Pipe(c) => Some(&c.caster), + Self::Echo(c) => Some(&c.caster), + Self::Gun(c) => Some(&c.caster), + Self::Helm(c) => Some(&c.caster), + Self::Blade(c) => Some(&c.caster), + Self::Lion(c) => Some(&c.caster), + Self::Deer(c) => Some(&c.caster), + Self::Quintus(_) | Self::Spring(_) | Self::Shell { .. } | Self::Equipment => None, + } + } + pub(super) fn memory(self, position: [f64; 2], now: f64) -> Memory { + match self { + Self::Pipe(_) => Memory::Pipe { + acc: 0., + attack: f64::INFINITY, + held_until: 0., + }, + Self::Echo(_) => Memory::Echo(ensemble::EchoState { + form: EchoForm::Dark, + strikes: 0, + pulses: Default::default(), + pulsing: false, + }), + Self::Quintus(_) => Memory::Quintus(quintus::QuintusState { + stage: 0, + born_at: now, + stage_at: now, + tentacles: 0, + }), + Self::Gun(_) => Memory::Gun(gun::GunState { + last: None, + stacks: 0, + charge: None, + link_acc: 0., + }), + Self::Spring(_) => Memory::Spring(gun::SpringState { + up: true, + down_at: None, + attacks: 0, + dash: None, + }), + Self::Helm(_) => Memory::Helm { low: false }, + Self::Blade(_) => Memory::Blade { + phase: helm::BladePhase::Hover, + home: position, + }, + Self::Shell { .. } => Memory::Shell { target: None }, + Self::Lion(_) => Memory::Lion { + sp: 0., + advanced: false, + next_anim: None, + wand: false, + }, + Self::Deer(_) => Memory::Deer { + low: false, + acc: f64::INFINITY, + held_until: 0., + }, + Self::Equipment => Memory::None, + } + } + pub(super) fn spawn( + self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + let mut b = Buff::default(); + b.runtime.persist = true; + match self { + Self::Pipe(config) => { + if !config.gold { + let mut bound = flag_buff("boss:selfBound", "selfBound"); + bound + .flags + .extend(["noMove", "unblockable"].map(str::to_string)); + r.add( + w, + h, + id, + Spec { + buff: bound, + flags_present: true, + ..Default::default() + }, + )?; + } + if config.raw_aspd { + let mut speed = Buff::default(); + speed.key = Some("boss:aspd".into()); + speed.runtime.persist = true; + speed + .mods + .insert("aspd".into(), 20. - w.unit(id)?.stats.base_number("aspd")); + r.add( + w, + h, + id, + Spec { + buff: speed, + mods_present: true, + ..Default::default() + }, + )?; + } + if config.gold { + let mut eternal = flag_buff("boss:eternal", "invulnerable"); + eternal.flags.insert("untargetable".into()); + r.add( + w, + h, + id, + Spec { + buff: eternal, + flags_present: true, + ..Default::default() + }, + )?; + } + return Ok(()); + } + Self::Echo(config) => { + let hits = (w.unit(id)?.stats.base_number("maxHp") + 0.5) + .floor() + .max(1.); + w.unit_mut(id)?.stats.edit_base(|base| { + base.0.insert("maxHp".into(), hits); + }); + w.unit_mut(id)?.stats.stats().map_err(str::to_string)?; + w.unit_mut(id)?.stats.hp = hits; + w.unit_mut(id)?.block_weight = 2.; + r.add( + w, + h, + id, + Spec { + buff: flag_buff("ab:hitCount", "hitCount"), + flags_present: true, + ..Default::default() + }, + )?; + r.add( + w, + h, + id, + Spec { + buff: ensemble::form_buff(config, EchoForm::Dark), + mods_present: true, + ..Default::default() + }, + )?; + return Ok(()); + } + Self::Gun(config) => { + b.key = Some("boss:unblockable".into()); + b.flags.insert("unblockable".into()); + r.add( + w, + h, + id, + Spec { + buff: b, + flags_present: true, + ..Default::default() + }, + )?; + if config.raw_aspd { + let mut speed = Buff::default(); + speed.key = Some("boss:aspd".into()); + speed.runtime.persist = true; + speed + .mods + .insert("aspd".into(), 20. - w.unit(id)?.stats.base_number("aspd")); + r.add( + w, + h, + id, + Spec { + buff: speed, + mods_present: true, + ..Default::default() + }, + )?; + } + return Ok(()); + } + Self::Spring(config) => { + b.key = Some("boss:springUnblockable".into()); + b.flags.insert("unblockable".into()); + r.add( + w, + h, + id, + Spec { + buff: b, + flags_present: true, + ..Default::default() + }, + )?; + let shield = gun::spring_shield(w, id, config)?; + r.add( + w, + h, + id, + Spec { + buff: shield, + ..Default::default() + }, + )?; + if config.kind != SpringKind::Arts { + let mut share = Buff::default(); + share.key = Some("boss:springShare".into()); + share.runtime.persist = true; + share.runtime.injury.observe = Some(gun::SPRING_SHARE); + r.add( + w, + h, + id, + Spec { + buff: share, + ..Default::default() + }, + )?; + } + return Ok(()); + } + Self::Shell { .. } => { + let hits = w.unit(id)?.stats.base_number("maxHp"); + let hits = (hits + 0.5).floor().max(1.); + w.unit_mut(id)?.stats.edit_base(|base| { + base.0.insert("maxHp".into(), hits); + }); + w.unit_mut(id)?.stats.stats().map_err(str::to_string)?; + w.unit_mut(id)?.stats.hp = hits; + let count = flag_buff("ab:hitCount", "hitCount"); + r.add( + w, + h, + id, + Spec { + buff: count, + flags_present: true, + ..Default::default() + }, + )?; + b.key = Some("boss:shellGuard".into()); + b.flags.insert("noDisplace".into()); + } + Self::Blade(_) => { + let mut hover = Buff::default(); + hover.key = Some("boss:hover".into()); + hover.runtime.persist = true; + hover.runtime.visible = true; + hover + .flags + .extend(["invulnerable", "untargetable"].map(str::to_string)); + r.add( + w, + h, + id, + Spec { + buff: hover, + flags_present: true, + ..Default::default() + }, + )?; + b.key = Some("boss:anchor".into()); + b.flags.extend( + ["noMove", "selfBound", "unblockable", "noDisplace"].map(str::to_string), + ); + } + Self::Equipment => { + b.key = Some("boss:equip".into()); + b.flags + .extend(["invulnerable", "untargetable", "noMove"].map(str::to_string)); + } + _ => { + b.key = Some("boss:selfBound".into()); + b.flags + .extend(["noMove", "selfBound", "unblockable"].map(str::to_string)); + } + } + r.add( + w, + h, + id, + Spec { + buff: b, + flags_present: true, + ..Default::default() + }, + )?; + Ok(()) + } +} +impl Runtime { + pub(crate) fn boss(&self, id: Id) -> Memory { + self.units + .get(&id) + .map(|s| s.boss.clone()) + .unwrap_or(Memory::None) + } + pub(crate) fn set_boss(&mut self, id: Id, memory: Memory) { + self.units.get_mut(&id).unwrap().boss = memory; + } + pub(crate) fn lose_lp(&mut self, amount: f64) -> Result<(), String> { + let total = self.lp_loss + amount; + if !amount.is_finite() || amount < 0. || !total.is_finite() { + return Err("Invalid field LP loss".into()); + } + self.lp_loss = total; + Ok(()) + } + pub(crate) fn lp_loss(&self) -> f64 { + self.lp_loss + } +} diff --git a/crates/engine/src/battle/content/enemies/bosses/ensemble.rs b/crates/engine/src/battle/content/enemies/bosses/ensemble.rs new file mode 100644 index 0000000..d2c3cfb --- /dev/null +++ b/crates/engine/src/battle/content/enemies/bosses/ensemble.rs @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use std::collections::VecDeque; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EchoForm { + Dark, + Gold, +} +#[derive(Clone, Copy, Debug)] +pub struct Pipe { + pub caster: Caster, + pub gold: bool, + pub raw_aspd: bool, + pub intervals: [f64; 2], + pub threshold: f64, +} +#[derive(Clone, Copy, Debug)] +pub struct Echo { + pub caster: Caster, + pub gold_aspd: f64, + pub dark_atk: f64, + pub dark_slow: f64, + pub strikes: [f64; 2], + pub pulse: f64, + pub element: f64, + pub ensemble: [f64; 2], +} +#[derive(Clone, Debug)] +pub(crate) struct EchoState { + pub form: EchoForm, + pub strikes: u64, + pub pulses: VecDeque, + pub pulsing: bool, +} +impl Boss { + pub(super) fn ensemble(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key: &str, default| talent_value(raw, ov, key).unwrap_or(default); + let skill = abilities::skill(raw, ov, "1"); + let bb = |field: &str| { + skill["bb"][field] + .as_f64() + .filter(|n| n.is_finite()) + .unwrap_or(0.) + }; + let caster = |skill| Caster { + passive: Passive::Plain, + skills: [skill, None, None, None], + }; + Ok(Some(match key { + "enemy_9021_acduml" | "enemy_9021_acduml_2" | "enemy_9022_acdumm" => { + let gold = key == "enemy_9022_acdumm"; + let prefix = if gold { "acdumm" } else { "acduml" }; + let hi = t(&format!("1.{prefix}_t_1[high_hp].interval"), 40.); + Self::Pipe(Pipe { + caster: caster( + casters::ability( + raw, + ov, + "1", + Spell::PipeStrike { + gold, + radius: bb("range_radius"), + element: bb("ep_damage_ratio"), + }, + if gold { 3.333 } else { 4.167 }, + true, + false, + ) + .map(|mut s| { + s.own = false; + s + }), + ), + gold, + raw_aspd: raw["stats"]["aspd"].as_f64() == Some(0.), + intervals: [hi, t(&format!("1.{prefix}_t_1[low_hp].interval"), hi)], + threshold: t("1.hp_ratio", 0.), + }) + } + "enemy_9023_acdums" => Self::Echo(Echo { + caster: caster(casters::ability( + raw, + ov, + "Skill", + Spell::Ensemble, + 0., + false, + false, + )), + gold_aspd: t("1.attack_speed", 0.), + dark_atk: t("2.atk", 0.), + dark_slow: t("2.move_speed", 0.), + strikes: [ + t("2.hit_times_to_switch", 0.), + t("1.hit_times_to_switch", 0.), + ], + pulse: t("3.atk_scale", 0.), + element: t("3.ep_damage_ratio", 0.), + ensemble: [ + t("4.ep_damage_ratio_depassion", 0.), + t("4.ep_damage_ratio_passion", 0.), + ], + }), + _ => return Ok(None), + })) + } +} +pub(crate) fn form_buff(config: Echo, form: EchoForm) -> Buff { + let mut b = Buff::default(); + b.key = Some("boss:echoForm".into()); + b.runtime.persist = true; + b.runtime.visible = true; + b.mods = match form { + EchoForm::Gold => [("aspd".into(), config.gold_aspd)].into(), + EchoForm::Dark => [ + ("atkPct".into(), config.dark_atk), + ("moveMul".into(), 1. - config.dark_slow), + ] + .into(), + }; + b +} diff --git a/crates/engine/src/battle/content/enemies/bosses/gun.rs b/crates/engine/src/battle/content/enemies/bosses/gun.rs new file mode 100644 index 0000000..e902712 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/bosses/gun.rs @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(crate) const SPRING_SHIELD: u64 = 1715; +pub(crate) const SPRING_SHARE: u64 = 1716; +#[derive(Clone, Copy, Debug)] +pub struct Gun { + pub caster: Caster, + pub hidden: bool, + pub raw_aspd: bool, + pub step: f64, + pub max: u32, + pub erosion: f64, + pub speed: f64, + pub scale: f64, + pub duration: f64, + pub confession: f64, + pub link: Option<[f64; 2]>, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SpringKind { + Arts, + Element, + Hits, +} +#[derive(Clone, Copy, Debug)] +pub struct Spring { + pub kind: SpringKind, + pub scale: f64, + pub regen: f64, + pub pool: f64, + pub counter: f64, + pub erosion: f64, + pub every: Option, + pub times: u32, + pub shot: f64, +} +#[derive(Clone, Debug)] +pub(crate) struct Charge { + pub target: [f64; 2], + pub until: f64, + pub hit: Vec, +} +#[derive(Clone, Debug)] +pub(crate) struct Dash { + pub gun: Id, + pub until: f64, + pub mul: f64, + pub hit: Vec, +} +#[derive(Clone, Debug)] +pub(crate) struct GunState { + pub last: Option, + pub stacks: u32, + pub charge: Option, + pub link_acc: f64, +} +#[derive(Clone, Debug)] +pub(crate) struct SpringState { + pub up: bool, + pub down_at: Option, + pub attacks: u32, + pub dash: Option, +} +impl Boss { + pub(super) fn gun(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key, default| talent_value(raw, ov, key).unwrap_or(default); + let sk = |key| abilities::skill(raw, ov, key); + let bb = |key, field: &str, default| { + sk(key)["bb"][field] + .as_f64() + .filter(|x| x.is_finite()) + .unwrap_or(default) + }; + Ok(Some(match key { + "enemy_9017_achunt" | "enemy_9017_achunt_2" => { + let hidden = key.ends_with("_2"); + Self::Gun(Gun { + caster: Caster { + passive: Passive::Plain, + skills: [ + casters::ability(raw, ov, "1", Spell::GunCharge, 0., false, false), + if hidden { + casters::ability( + raw, + ov, + "2", + Spell::SpringDash { + duration: bb("2", "dog_duration", 0.), + mul: 1. + bb("2", "move_speed", 0.), + }, + 0., + false, + false, + ) + } else { + None + }, + None, + None, + ], + }, + hidden, + raw_aspd: raw["stats"]["aspd"].as_f64() == Some(0.), + step: t("2.attack_speed", 0.), + max: abilities::count(t("2.max_stack_cnt", 0.).max(0.).floor())?, + erosion: t("1.ep_damage_ratio", 0.), + speed: t("3.move_speed", 0.), + scale: t("3.atk_scale", 1.), + duration: t("3.duration", 0.), + confession: t("4.damage_scale", 1.), + link: if hidden && !sk("3").is_null() { + Some([bb("3", "interval", 1.), bb("3", "value", 0.)]) + } else { + None + }, + }) + } + "enemy_9018_actrpa" | "enemy_9019_actrpb" | "enemy_9020_actrpc" => { + let kind = match key { + "enemy_9018_actrpa" => SpringKind::Arts, + "enemy_9019_actrpb" => SpringKind::Element, + _ => SpringKind::Hits, + }; + let skill = sk("1"); + Self::Spring(Spring { + kind, + scale: t("1.damage_scale", 1.), + regen: t("1.regenerate_duration", 0.), + pool: if kind == SpringKind::Arts { + t("1.shield_ratio", 0.) + } else { + t("1.block_damage_max_times", 0.) + }, + counter: t("1.atk_scale", 0.), + erosion: t("1.ep_damage_ratio", 0.), + every: if kind != SpringKind::Arts && !skill.is_null() { + let cost = skill["spCost"].as_f64().unwrap_or(0.); + Some(abilities::count(if cost > 0. { cost + 1. } else { 3. })?) + } else { + None + }, + times: abilities::count(bb("1", "times", 1.).max(1.).ceil())?, + shot: if kind == SpringKind::Element { + bb("1", "ep_damage_ratio", 0.) + } else { + bb("1", "atk_scale", 0.) + }, + }) + } + _ => return Ok(None), + })) + } +} +pub(crate) fn spring_shield(w: &mut World, id: Id, config: Spring) -> Result { + let mut b = Buff::default(); + b.key = Some("boss:springShield".into()); + b.runtime.persist = true; + b.runtime.visible = true; + b.runtime.injury.keep_empty_shield = true; + b.runtime.injury.on_injury = Some(SPRING_SHIELD); + b.runtime.injury.observe = Some(SPRING_SHIELD); + match config.kind { + SpringKind::Arts => { + b.shield = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp") + * config.pool; + b.runtime.injury.shield_types = Some(vec![crate::battle::damage::DamageType::Arts]); + } + SpringKind::Hits => b.runtime.shield_hits = abilities::count(config.pool.max(0.).floor())?, + SpringKind::Element => {} + } + Ok(b) +} diff --git a/crates/engine/src/battle/content/enemies/bosses/helm.rs b/crates/engine/src/battle/content/enemies/bosses/helm.rs new file mode 100644 index 0000000..4a0e592 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/bosses/helm.rs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +#[derive(Clone, Copy, Debug)] +pub struct Helm { + pub caster: Caster, + pub low: f64, + pub scale: f64, +} +#[derive(Clone, Copy, Debug)] +pub struct Blade { + pub caster: Caster, + pub hammer: bool, + pub hits: f64, + pub stun: f64, + pub down: f64, + pub scale: f64, + pub dot: f64, + pub duration: f64, +} +#[derive(Clone, Copy, Debug)] +pub(crate) enum BladePhase { + Hover, + Dive { tile: [i32; 2], hits: u32 }, + Down, + Gone, +} +#[derive(Clone, Copy, Debug)] +pub(crate) struct ShellTarget { + pub tile: [i32; 2], + pub source: Id, +} +#[derive(Clone, Copy, Debug)] +pub(crate) struct DroneLink { + pub owner: Id, + pub ratio: f64, +} +impl Boss { + pub(super) fn helm(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let sk = |key| abilities::skill(raw, ov, key); + let n = |v: &Value, default| v.as_f64().filter(|v| v.is_finite()).unwrap_or(default); + let t = |key, default| talent_value(raw, ov, key).unwrap_or(default); + let caster = |skills| Caster { + passive: Passive::Plain, + skills, + }; + let make = |key, spell, turn, clip| { + casters::ability(raw, ov, key, spell, clip, turn, false).map(|mut s| { + s.own = false; + s + }) + }; + Ok(Some(match key { + "enemy_9013_acstmk" | "enemy_9013_acstmk_2" => Self::Helm(Helm { + caster: caster([ + make("1", Spell::HelmShell, true, 2.333), + make( + "2", + Spell::HelmDrones { + ratio: n(&sk("2")["bb"]["hp_ratio"], 0.), + hp: n(&sk("2")["bb"]["summon.hp_ratio"], 0.), + }, + false, + 0., + ), + None, + None, + ]), + low: t("1.hp_ratio", 0.), + scale: t("1.damage_scale", 1.), + }), + "enemy_9014_acstma" | "enemy_9015_acstmb" => Self::Blade(Blade { + caster: caster([make("1", Spell::BladeDive, false, 0.), None, None, None]), + hammer: key == "enemy_9015_acstmb", + hits: n(&sk("1")["bb"]["max_hit_cnt"], f64::INFINITY), + stun: n(&sk("1")["bb"]["stun"], 0.), + down: n( + &sk("1")["bb"]["special_stun_duration"], + n(&sk("1")["bb"]["stun"], 0.), + ), + scale: n(&sk("1")["bb"]["damage_scale"], 1.), + dot: n(&sk("1")["bb"]["dot_damage"], 0.), + duration: n(&sk("1")["bb"]["dot_duration"], 0.), + }), + "enemy_9016_acstmr" => Self::Shell { + stun: t("killed.duration", 0.), + dot: t("killed.value", 0.), + }, + _ => return Ok(None), + })) + } +} +impl Runtime { + pub(crate) fn drone(&self, id: Id) -> Option { + self.units.get(&id).and_then(|s| s.drone) + } + pub(crate) fn set_drone(&mut self, id: Id, link: Option) { + self.units.get_mut(&id).unwrap().drone = link; + } +} diff --git a/crates/engine/src/battle/content/enemies/bosses/quintus.rs b/crates/engine/src/battle/content/enemies/bosses/quintus.rs new file mode 100644 index 0000000..83a98b4 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/bosses/quintus.rs @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +#[derive(Clone, Copy, Debug)] +pub struct Quintus { + pub growth: [f64; 2], + pub deadlines: [f64; 2], + pub attack: [f64; 2], + pub neural: f64, +} +#[derive(Clone, Copy, Debug)] +pub(crate) struct QuintusState { + pub stage: u8, + pub born_at: f64, + pub stage_at: f64, + pub tentacles: usize, +} +#[derive(Clone, Debug)] +pub(crate) struct Stages { + pub casters: [Caster; 3], + pub branches: [Arc; 3], +} +impl Stages { + pub(in crate::battle::content::enemies) fn compile(raw: &Value, ov: &Value) -> Self { + let names = [ + ["Tidewater", "Rockfall", "SummonTentac", ""], + ["TidewaterG1", "RockfallG1", "SummonTentacG1", ""], + ["TidewaterG2", "RockfallG2", "SummonTentacG2", "Doom"], + ]; + let casters = std::array::from_fn(|stage| Caster { + passive: Passive::Plain, + skills: std::array::from_fn(|slot| { + let name = names[stage][slot]; + let sk = abilities::skill(raw, ov, name); + let n = |key: &str| { + sk["bb"][key] + .as_f64() + .filter(|n| n.is_finite()) + .unwrap_or(0.) + }; + let (spell, clip) = match slot { + 0 => ( + Spell::Tide { + stage: stage as u8, + scale: n("atk_scale"), + element: n("ep_damage_ratio"), + }, + 1.667, + ), + 1 => ( + Spell::Rockfall { + stage: stage as u8, + scale: n("atk_scale"), + }, + 3., + ), + 2 => (Spell::Tentacles { stage: stage as u8 }, 2.), + _ => ( + Spell::Species { + loss: n("value").abs(), + }, + 4.467, + ), + }; + casters::ability(raw, ov, name, spell, clip, true, false).map(|mut s| { + s.own = slot >= 2; + s + }) + }), + }); + Self { + casters, + branches: std::array::from_fn(|stage| { + Arc::from( + abilities::skill(raw, ov, names[stage][2])["bbStr"]["branch_id"] + .as_str() + .unwrap_or("dslily_dstnta"), + ) + }), + } + } +} +impl Boss { + pub(super) fn quintus(key: &str, raw: &Value, ov: &Value) -> Option { + if key != "enemy_1521_dslily" { + return None; + } + let t = |key, default| talent_value(raw, ov, key).unwrap_or(default); + Some(Self::Quintus(Quintus { + growth: [t("growup1.hp_ratio", 1.), 2. * t("growup2.hp_ratio", 1.)], + deadlines: [ + t("growup1.interval", f64::INFINITY), + t("growup2.interval", f64::INFINITY), + ], + attack: [t("atkup1.atk", 0.), t("atkup2.atk", 0.)], + neural: t("epdamage.attack@ep_damage_ratio", 0.), + })) + } +} +impl Runtime { + pub(crate) fn quintus_caster(&self, id: Id) -> Option { + self.quintus_caster_ref(id).copied() + } + pub(crate) fn quintus_caster_ref(&self, id: Id) -> Option<&Caster> { + let unit = self.units.get(&id)?; + let Memory::Quintus(state) = unit.boss else { + return None; + }; + unit.definition + .quintus + .as_ref() + .map(|s| &s.casters[state.stage as usize]) + } + pub(crate) fn tentacle_branch(&self, id: Id) -> Option> { + let unit = self.units.get(&id)?; + let Memory::Quintus(state) = unit.boss else { + return None; + }; + unit.definition + .quintus + .as_ref() + .map(|s| s.branches[state.stage as usize].clone()) + } +} diff --git a/crates/engine/src/battle/content/enemies/casters.rs b/crates/engine/src/battle/content/enemies/casters.rs new file mode 100644 index 0000000..cc40616 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/casters.rs @@ -0,0 +1,670 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::movement::Cooldown; +use super::*; +mod champions; +pub(crate) use champions::BuffEffect; +#[derive(Clone, Copy, Debug)] +pub enum Spell { + PipeStrike { + gold: bool, + radius: f64, + element: f64, + }, + Ensemble, + Tide { + stage: u8, + scale: f64, + element: f64, + }, + Rockfall { + stage: u8, + scale: f64, + }, + Tentacles { + stage: u8, + }, + Species { + loss: f64, + }, + GunCharge, + SpringDash { + duration: f64, + mul: f64, + }, + HelmShell, + HelmDrones { + ratio: f64, + hp: f64, + }, + BladeDive, + Decree { + scales: [f64; 2], + }, + Repel { + scale: f64, + loss: f64, + }, + Surge { + max: usize, + duration: f64, + scale: f64, + }, + XiShield { + form2: bool, + duration: f64, + amount: f64, + radius: f64, + scale: f64, + }, + XiCross { + scale: f64, + }, + MaceBlink { + form2: bool, + distance: f64, + scale: f64, + }, + MaceCircle { + form2: bool, + radius: f64, + scale: f64, + }, + Fear { + max: usize, + aspd: f64, + peak: f64, + ramp: f64, + cut: f64, + refund: f64, + wait: f64, + }, + LucienAoe { + scale: f64, + element: f64, + }, + Phantom { + distance: f64, + }, + Charge { + duration: f64, + scale: f64, + }, + Triple { + radius: f64, + delay: f64, + scale: f64, + }, + Cross { + scale: f64, + stun: f64, + }, + DeathEye { + duration: f64, + scale: f64, + element: f64, + }, + Cannon { + scale: f64, + }, + Jazz { + radius: f64, + duration: f64, + interval: f64, + scale: f64, + element: f64, + }, + C4 { + radius: f64, + scale: f64, + }, + Drift { + damage: f64, + }, + Sand { + duration: f64, + damage: f64, + attack: f64, + }, + Rock { + radius: f64, + scale: f64, + stun: f64, + }, + Chain { + radius: f64, + jump: f64, + max: u32, + duration: f64, + speed: f64, + aspd: f64, + }, + Shield { + amount: f64, + hp: f64, + aspd: f64, + }, + TombShield { + ratio: f64, + }, + Blink { + distance: f64, + }, +} +#[derive(Clone, Copy, Debug)] +pub struct Skill { + pub spell: Spell, + pub clock: Cooldown, + pub priority: f64, + pub clip: f64, + pub turn: bool, + pub own: bool, + pub silence: bool, +} +#[derive(Clone, Copy, Debug)] +pub enum Passive { + Xi { + duration: f64, + invincible: f64, + atk: f64, + }, + Mace { + resist: f64, + duration: f64, + invincible: f64, + pen: [f64; 2], + cut: f64, + disarm: f64, + radius: f64, + }, + Wolf { + duration: f64, + invincible: f64, + resistance: f64, + atk: f64, + bat: f64, + }, + Lucien { + penetration: f64, + dodge: f64, + element: f64, + }, + Knight { + ranged: bool, + atk: f64, + aspd: f64, + speed: f64, + }, + Pompeii { + ratio: f64, + aspd: f64, + dot: f64, + interval: f64, + duration: f64, + blast: f64, + blast_interval: f64, + }, + Plain, + Stealth { + jazz: bool, + }, + DeathEye { + element: f64, + }, + Mouse { + shield: f64, + defense: f64, + ratio: f64, + scale: f64, + }, + Mudrock { + shield: f64, + hp: f64, + aspd: f64, + atk: f64, + }, + Tomb { + scale: f64, + }, + Snow { + cold: f64, + max: u32, + fall: f64, + jump: f64, + }, +} +#[derive(Clone, Copy, Debug)] +pub struct Caster { + pub passive: Passive, + pub skills: [Option; 4], +} +pub(crate) const EMPTY: Caster = Caster { + passive: Passive::Plain, + skills: [None; 4], +}; +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct State { + pub left: [f64; 4], + pub channel: bool, + pub cannon: bool, + pub enraged: bool, + pub splash: bool, + pub no_attack: bool, + pub held: f64, + pub phase: Option, + pub next: f64, + pub caught: usize, + pub wait_until: f64, + pub reborn_at: f64, + pub evade: Option, +} +fn n(v: &Value, default: f64) -> f64 { + v.as_f64().filter(|v| v.is_finite()).unwrap_or(default) +} +pub(super) fn ability( + raw: &Value, + ov: &Value, + key: &str, + spell: Spell, + clip: f64, + turn: bool, + silence: bool, +) -> Option { + let clock = Cooldown::compile(raw, ov, key)?; + let s = abilities::skill(raw, ov, key); + Some(Skill { + spell, + clock, + clip, + turn, + own: turn, + silence, + priority: n(&s["priority"], 0.), + }) +} +impl Caster { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + if let Some(config) = Self::champion(key, raw, ov)? { + return Ok(Some(config)); + } + let t = |key| talent(raw, ov, &[key]); + let v = |key, fallback| talent_value(raw, ov, key).unwrap_or(fallback); + let skill = |key| abilities::skill(raw, ov, key); + let radius = n(&raw["stats"]["rangeRadius"], 0.); + let raw_radius = n(&raw["stats"]["rawRangeRadius"], 0.); + let (passive, primary, secondary) = match key { + "enemy_1050_lslime" => ( + Passive::Pompeii { + ratio: v("selfbuff.hp_ratio", 0.5), + aspd: t("selfbuff.attack_speed"), + dot: t("dot.damage"), + interval: v("dot.interval", 1.), + duration: t("dot.duration"), + blast: t("rangedamage.attack@damage"), + blast_interval: v("rangedamage.interval", 10.), + }, + None, + None, + ), + "enemy_1513_dekght" | "enemy_1513_dekght_2" => { + let ranged = key.ends_with("_2"); + let spell = if ranged { + Spell::Triple { + radius: if radius != 0. { radius } else { 2.5 }, + delay: n(&skill("TripleAttack")["bb"]["dekght_2[aoe].interval"], 0.), + scale: n(&skill("TripleAttack")["bb"]["dekght_2[aoe].atk_scale"], 1.), + } + } else { + Spell::Charge { + duration: n(&skill("ChargeAttack")["bb"]["duration"], 0.), + scale: n( + &skill("ChargeAttack")["bb"]["dekght[aoe].atk_scale"], + n(&skill("ChargeAttack")["bb"]["atk_scale"], 1.), + ), + } + }; + let mut cast = ability( + raw, + ov, + if ranged { + "TripleAttack" + } else { + "ChargeAttack" + }, + spell, + if ranged { 1.667 } else { 0. }, + true, + false, + ); + if let Some(c) = &mut cast { + c.own = ranged; + } + ( + Passive::Knight { + ranged, + atk: t("triggerrage.atk"), + aspd: t("triggerrage.attack_speed"), + speed: t("triggerrage.move_speed"), + }, + cast, + None, + ) + } + + "enemy_1404_msnip" => ( + Passive::Stealth { jazz: false }, + ability( + raw, + ov, + "CrossAttack", + Spell::Cross { + scale: n(&skill("CrossAttack")["bb"]["atk_scale"], 1.), + stun: n(&skill("CrossAttack")["bb"]["stun"], 0.), + }, + 0., + true, + true, + ), + None, + ), + "enemy_1275_dwlock_2" => ( + Passive::DeathEye { + element: t("empty.attack@ep_damage_ratio"), + }, + ability( + raw, + ov, + "DeathEye", + Spell::DeathEye { + duration: n(&skill("DeathEye")["bb"]["hit_duration"], 0.), + scale: n(&skill("DeathEye")["bb"]["atk_scale"], 0.), + element: n(&skill("DeathEye")["bb"]["ep_damage_ratio"], 0.), + }, + 0., + true, + true, + ), + None, + ), + "enemy_1273_stmgun_2" => ( + Passive::Plain, + ability( + raw, + ov, + "Cannon", + Spell::Cannon { + scale: n(&skill("Cannon")["bb"]["atk_scale"], 0.), + }, + 10., + true, + false, + ), + None, + ), + "enemy_10034_cnvsax" => ( + Passive::Stealth { jazz: true }, + ability( + raw, + ov, + "fire", + Spell::Jazz { + radius: if raw_radius != 0. { raw_radius } else { 2.5 }, + duration: n(&skill("fire")["bb"]["enemy_cnvsax[cd].duration"], 0.), + interval: n(&skill("fire")["bb"]["hit_interval"], 0.5), + scale: n(&skill("fire")["bb"]["atk_scale"], 0.), + element: n(&skill("fire")["bb"]["ep_damage_ratio"], 0.), + }, + 0., + true, + true, + ), + None, + ), + "enemy_1504_cqbw" => ( + Passive::Plain, + ability( + raw, + ov, + "C4", + Spell::C4 { + radius: n(&skill("C4")["bb"]["range_radius"], radius), + scale: n(&skill("C4")["bb"]["atk_scale"], 1.), + }, + 4.8, + true, + false, + ), + None, + ), + "enemy_1509_mousek" => ( + Passive::Mouse { + shield: t("shield.dynamic"), + defense: t("defup.def"), + ratio: v("enrage.hp_ratio", 0.5), + scale: v("enrage.damage_scale", 1.), + }, + ability( + raw, + ov, + "DriftSand", + Spell::Drift { + damage: n(&skill("DriftSand")["bb"]["damage"], 0.), + }, + 2.333, + true, + false, + ), + ability( + raw, + ov, + "SandStorm", + Spell::Sand { + duration: n(&skill("SandStorm")["bb"]["duration"], 0.), + damage: n(&skill("SandStorm")["bb"]["damage"], 0.), + attack: n(&skill("SandStorm")["bb"]["atk"], 0.), + }, + 1.333, + true, + false, + ), + ), + "enemy_2003_rockman" => ( + Passive::Plain, + ability( + raw, + ov, + "StunAttack", + Spell::Rock { + radius: if raw_radius != 0. { raw_radius } else { 2.5 }, + scale: n(&skill("StunAttack")["bb"]["atk_scale"], 1.), + stun: n(&skill("StunAttack")["bb"]["stun"], 0.), + }, + 2.333, + true, + false, + ), + None, + ), + "enemy_2050_smsha" => { + let jump = v("Attack.attack@projectile_range", 1.6); + ( + Passive::Snow { + cold: t("Attack.attack@freeze"), + max: abilities::count(v("Attack.attack@chain.max_target", 1.))?, + fall: v("Attack.attack@chain.atk_scale", 1.), + jump, + }, + ability( + raw, + ov, + "ChainBuff", + Spell::Chain { + radius: if radius != 0. { radius } else { 3.5 }, + jump: n(&skill("ChainBuff")["bb"]["projectile_range"], jump), + max: abilities::count(n( + &skill("ChainBuff")["bb"]["chain.max_target"], + 3., + ))?, + duration: n(&skill("ChainBuff")["bb"]["duration"], 0.), + speed: n(&skill("ChainBuff")["bb"]["move_speed"], 0.), + aspd: n(&skill("ChainBuff")["bb"]["attack_speed"], 0.), + }, + 1.667, + true, + true, + ), + None, + ) + } + "enemy_1511_mdrock" => { + let s = skill("RefreshShield"); + let amount = n(&s["bb"]["dynamic"], t("shield.dynamic")); + let hp = n(&s["bb"]["max_hp"], t("shield.max_hp")); + let aspd = n(&s["bb"]["attack_speed"], t("shield.attack_speed")); + ( + Passive::Mudrock { + shield: amount, + hp, + aspd, + atk: t("charge.attack@enemy_mdrock_s_1[charge].atk") / 6., + }, + ability( + raw, + ov, + "RefreshShield", + Spell::Shield { amount, hp, aspd }, + 0., + false, + false, + ), + None, + ) + } + "enemy_2008_flking" => ( + Passive::Tomb { + scale: v("atkdown.atk_scale", 1.), + }, + ability( + raw, + ov, + "refreshshield", + Spell::TombShield { + ratio: n(&skill("refreshshield")["bb"]["hp_ratio"], 0.), + }, + 0., + false, + false, + ), + None, + ), + "enemy_1502_crowns" => ( + Passive::Plain, + ability( + raw, + ov, + "blink", + Spell::Blink { + distance: n(&skill("blink")["bb"]["dist"], 1.5), + }, + 0., + false, + true, + ), + None, + ), + _ => return Ok(None), + }; + Ok(Some(Self { + passive, + skills: [primary, secondary, None, None], + })) + } + pub(super) fn state(self) -> State { + State { + phase: self.rebirth().map(|_| lifecycle::RebornPhase::Fresh), + next: 1., + wait_until: f64::NEG_INFINITY, + no_attack: matches!(self.passive, Passive::Stealth { jazz: true }), + left: self + .skills + .map(|s| s.map(|s| s.clock.initial).unwrap_or(0.)), + ..Default::default() + } + } + pub(super) fn spawn( + self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + let mut list = vec![]; + match self.passive { + Passive::Wolf { resistance, .. } => { + w.unit_mut(id)?.immune.insert("stun".into()); + let mut b = Buff::default(); + b.key = Some("ab:wolfGuard".into()); + b.runtime.persist = true; + b.runtime.visible = true; + b.mods.insert("dmgTakenMul".into(), 1. - resistance); + list.push(b); + } + Passive::Lucien { penetration, .. } if penetration > 0. => { + let mut b = Buff::default(); + b.key = Some("boss:pierce".into()); + b.runtime.persist = true; + b.mods.insert("defIgnorePct".into(), penetration); + list.push(b); + } + Passive::Stealth { jazz } => { + let mut b = flag_buff("ab:stealth", "stealth"); + b.runtime.stealth_restore = Some(if jazz { 0. } else { 3. }); + list.push(b); + } + Passive::Mouse { + shield, defense, .. + } if shield > 0. => { + list.push(Self::barrier("ab:sandDef", shield, &[("defFlat", defense)])) + } + Passive::Mudrock { + shield, hp, aspd, .. + } if shield > 0. => list.push(Self::barrier( + "ab:rockPower", + shield, + &[("hpPct", hp), ("aspd", aspd)], + )), + _ => {} + } + for b in list { + r.add( + w, + h, + id, + Spec { + mods_present: !b.mods.is_empty(), + flags_present: !b.flags.is_empty(), + buff: b, + ..Default::default() + }, + )?; + } + Ok(()) + } + pub(crate) fn barrier(key: &str, amount: f64, mods: &[(&str, f64)]) -> Buff { + let mut b = Buff::default(); + b.key = Some(key.into()); + b.runtime.persist = true; + b.runtime.visible = true; + b.runtime.tick_payload = amount; + b.runtime.injury.on_injury = Some(1703); + b.mods = mods.iter().map(|&(k, v)| (k.into(), v)).collect(); + b + } +} +impl Runtime { + pub(crate) fn caster(&self, id: Id) -> State { + self.units.get(&id).map(|s| s.caster).unwrap_or_default() + } + pub(crate) fn set_caster(&mut self, id: Id, state: State) { + self.units.get_mut(&id).unwrap().caster = state; + } +} diff --git a/crates/engine/src/battle/content/enemies/casters/champions.rs b/crates/engine/src/battle/content/enemies/casters/champions.rs new file mode 100644 index 0000000..9d8b699 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/casters/champions.rs @@ -0,0 +1,215 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +#[derive(Clone, Copy, Debug)] +pub(crate) enum BuffEffect { + Vest { + side: f64, + cut: f64, + }, + XiShield { + radius: f64, + scale: f64, + }, + Fear { + started: f64, + hp: f64, + ramp: f64, + peak: f64, + }, +} +impl Caster { + pub(super) fn champion(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key, default| talent_value(raw, ov, key).unwrap_or(default); + let bb = |key: &str, field: &str, default| { + n(&abilities::skill(raw, ov, key)["bb"][field], default) + }; + let make = |key, spell, clip, turn| ability(raw, ov, key, spell, clip, turn, false); + let (passive, skills) = match key { + "enemy_1517_xi" => { + let shield = |key, form2| { + make( + key, + Spell::XiShield { + form2, + duration: bb(key, "duration", 0.), + amount: bb(key, "dynamic", 0.), + radius: bb(key, "range_radius", 0.), + scale: bb(key, "atk_scale", 0.), + }, + 0., + true, + ) + .map(|mut s| { + s.own = false; + s + }) + }; + ( + Passive::Xi { + duration: t("reborn.duration", 0.), + invincible: t("reborn.invincible", 0.), + atk: t("reborn.atk", 0.), + }, + [ + shield("ShieldBurst", false), + shield("ShieldBurstReborn", true), + make( + "CrossAttack", + Spell::XiCross { + scale: bb("CrossAttack", "atk_scale", 1.), + }, + 1.333, + true, + ), + None, + ], + ) + } + "enemy_1525_blkswb" => { + let blink = |key, form2| { + make( + key, + Spell::MaceBlink { + form2, + distance: bb(key, "dist", 1.5), + scale: bb(key, "atk_scale", 1.), + }, + 0., + false, + ) + }; + let circle = |key, form2| { + make( + key, + Spell::MaceCircle { + form2, + radius: bb(key, "range_radius", 0.), + scale: bb(key, "atk_scale", 1.), + }, + 2.067, + true, + ) + }; + ( + Passive::Mace { + resist: { + let v = -t("Buff.one_minus_status_resistance", -0.5); + if v > 0. { + v.min(1.) + } else { + 0.5 + } + }, + duration: t("Reborn.duration", 0.), + invincible: t("Reborn.invincible", 0.), + pen: [ + t("DefPenetrate.enemy_blkswb_t_2.def_penetrate", 0.), + t( + "DefPenetrate.enemy_blkswb_t_2[reborn].def_penetrate", + t("DefPenetrate.enemy_blkswb_t_2.def_penetrate", 0.), + ), + ], + cut: t("ClearSp.hp_ratio", 0.), + disarm: t("ClearSp.duration", 0.), + radius: t("ClearSp.range_radius", 0.), + }, + [ + blink("Blink", false), + blink("Blink2", true), + circle("CircleAttack", false), + circle("CircleAttack2", true), + ], + ) + } + "enemy_1535_wlfmster" => { + let mut fear = make( + "FearCage", + Spell::Fear { + max: abilities::count(bb("FearCage", "max_target", 3.))? as usize, + aspd: bb("FearCage", "attack_speed", 0.), + peak: bb("FearCage", "hp_ratio", 0.), + ramp: bb("FearCage", "duration_bleed", 40.).max(1.), + cut: bb("FearCage", "hp_ratio_offset", 0.2).abs(), + refund: bb("FearCage", "sp", 0.), + wait: bb("FearCage", "duration_wait", 0.), + }, + 0., + true, + ); + if let Some(s) = &mut fear { + let sp = n(&abilities::skill(raw, ov, "FearCage")["spCost"], 0.); + if sp != 0. { + s.clock = Cooldown { + initial: sp, + period: sp, + }; + } + } + ( + Passive::Wolf { + duration: t("Reborn.duration", 0.), + invincible: t("Passive2.invincible_time", 0.), + resistance: t("Passive.damage_resistance", 0.), + atk: t("Passive2.atk", 0.), + bat: t("Passive2.base_attack_time", 0.), + }, + [fear, None, None, None], + ) + } + "enemy_2016_csphtm" | "enemy_2017_csphts" => ( + Passive::Lucien { + penetration: t("penetrate.def_penetrate", 0.), + dodge: t("evade.prob", 0.), + element: t("combat.attack@ep_damage_ratio", 0.), + }, + [ + make( + "aoe", + Spell::LucienAoe { + scale: bb("aoe", "atk_scale", 0.), + element: bb("aoe", "ep_damage_ratio", 0.), + }, + 1.8, + true, + ), + if key == "enemy_2016_csphtm" { + make( + "blink", + Spell::Phantom { + distance: bb("blink", "dist", 1.5), + }, + 0., + false, + ) + } else { + None + }, + None, + None, + ], + ), + _ => return Ok(None), + }; + Ok(Some(Self { passive, skills })) + } + pub(crate) fn rebirth(&self) -> Option<(f64, f64, f64)> { + match self.passive { + Passive::Xi { + duration, + invincible, + .. + } + | Passive::Mace { + duration, + invincible, + .. + } + | Passive::Wolf { + duration, + invincible, + .. + } => Some((duration, invincible, 1.)), + _ => None, + } + } +} diff --git a/crates/engine/src/battle/content/enemies/families.rs b/crates/engine/src/battle/content/enemies/families.rs new file mode 100644 index 0000000..92e73a9 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/families.rs @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Stronghold Protocol enemies/{archetypes,reflection,invisible}.js. +use super::*; + +#[derive(Clone, Copy, Debug)] +pub struct Prisoner { + pub attacks: u32, + pub free_all: bool, + pub aspd: f64, + pub def: f64, + pub atk: f64, + pub penetration: f64, + pub res: f64, + pub regen: f64, +} +#[derive(Clone, Copy, Debug)] +pub enum Family { + Prisoner(Prisoner), + Phalanx { res: f64, radius: f64, def: f64 }, + HolyGuard { res: f64, radius: f64, aspd: f64 }, + ShadowBlade { bat: f64 }, + ShadowKiller { scale: f64 }, + Tear { restore: f64, stun: f64 }, +} +#[derive(Clone, Copy, Default)] +pub(super) enum Memory { + #[default] + None, + Blades { + used: u32, + clear_cd: bool, + }, + Veil { + left: f64, + }, + Prisoner { + freed: bool, + }, + Shadow { + concealed: bool, + power: bool, + }, +} +impl Family { + pub(super) fn compile( + key: &str, + raw: &Value, + ov: &Value, + original: &str, + tag: Option<&str>, + ) -> Result, String> { + let t = |key| talent(raw, ov, &[key]); + let value = |key, fallback| talent_value(raw, ov, key).unwrap_or(fallback); + Ok(Some(match key { + "enemy_1116_liprr" + | "enemy_1116_liprr_2" + | "enemy_1118_lidbox_2" + | "enemy_1119_vofsd" + | "enemy_1121_lifbos" + | "enemy_1121_lifbos_2" => { + let attacks = (value("confinement.times", 4.) + 0.5).floor().max(1.); + if attacks > i32::MAX as f64 { + return Err("Prisoner attack count outside positive i32 domain".into()); + } + Self::Prisoner(Prisoner { + attacks: attacks as u32, + free_all: matches!(key, "enemy_1121_lifbos" | "enemy_1121_lifbos_2"), + aspd: t("confinement.attack_speed"), + def: t("confinement.def"), + atk: t("liberty.atk"), + penetration: t("liberty.def_penetrate"), + res: t("liberty.magic_resistance"), + regen: t("liberty.hp_recovery_per_sec"), + }) + } + "enemy_1169_duphlx" | "enemy_1169_duphlx_2" => Self::Phalanx { + res: talent( + raw, + ov, + &["refracting.magic_resistance", "Refracting.magic_resistance"], + ), + radius: raw["stats"]["rawRangeRadius"] + .as_f64() + .filter(|n| n.is_finite() && *n != 0.) + .unwrap_or(1.5), + def: t("auraDefup.def"), + }, + "enemy_1174_duholy" | "enemy_1174_duholy_2" => Self::HolyGuard { + res: talent( + raw, + ov, + &["refracting.magic_resistance", "Refracting.magic_resistance"], + ), + radius: value("traitAbility.range_radius", 1.1), + aspd: t("traitAbility.attack_speed"), + }, + "enemy_1175_dushdo_2" => Self::ShadowBlade { + bat: t("traitAbility.base_attack_time"), + }, + "enemy_1299_ymkilr" | "enemy_1299_ymkilr_2" => Self::ShadowKiller { + scale: abilities::skill(raw, ov, "InvisibleCombat")["bb"]["atk_scale"] + .as_f64() + .filter(|n| n.is_finite() && *n != 0.) + .unwrap_or(1.), + }, + "enemy_2034_sythef" | "enemy_2034_sythef_2" => Self::Tear { + restore: if matches!(original, "enemy_2034_sythef" | "enemy_2034_sythef_2") { + if tag == Some("duck") { + 1. + } else { + 0. + } + } else { + 3. + }, + stun: t("Combat.attack@stun"), + }, + _ => return Ok(None), + })) + } + pub(super) fn memory(self) -> Memory { + match self { + Self::Prisoner(_) => Memory::Prisoner { freed: false }, + Self::ShadowKiller { .. } => Memory::Shadow { + concealed: true, + power: true, + }, + _ => Memory::None, + } + } + pub(super) fn spawn( + self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + let b = match self { + Self::Prisoner(p) => { + let mut b = Buff::default(); + b.key = Some("ab:confined".into()); + b.runtime.persist = true; + b.runtime.visible = true; + b.mods.insert("aspd".into(), p.aspd); + b.mods.insert("defFlat".into(), p.def); + b + } + Self::ShadowKiller { .. } | Self::ShadowBlade { .. } | Self::Tear { .. } => { + let mut b = flag_buff("ab:stealth", "stealth"); + b.runtime.stealth_restore = Some(match self { + Self::Tear { restore, .. } => restore, + _ => 3., + }); + b + } + _ => return Ok(()), + }; + r.add( + w, + h, + id, + Spec { + mods_present: !b.mods.is_empty(), + flags_present: !b.flags.is_empty(), + buff: b, + ..Default::default() + }, + )?; + Ok(()) + } +} +impl Kit { + pub(super) fn refraction(&self) -> Option<(f64, f64)> { + match *self { + Self::Refraction { res, hp_pct } => Some((res, hp_pct)), + Self::Form(Form::Stone(s)) => Some((s.res, 0.)), + Self::Family(Family::Phalanx { res, .. } | Family::HolyGuard { res, .. }) => { + Some((res, 0.)) + } + _ => None, + } + } +} +impl Runtime { + pub(crate) fn prisoner_attack(&mut self, id: Id) -> bool { + let s = self.units.get_mut(&id).unwrap(); + if let (Kit::Family(Family::Prisoner(p)), Memory::Prisoner { freed: false }) = + (s.definition.kit, s.memory) + { + s.count += 1; + return s.count >= p.attacks; + } + false + } + pub(crate) fn free_prisoner(&mut self, id: Id) -> Option { + let s = self.units.get_mut(&id)?; + if let (Kit::Family(Family::Prisoner(p)), Memory::Prisoner { freed: false }) = + (s.definition.kit, s.memory) + { + s.memory = Memory::Prisoner { freed: true }; + return Some(p); + } + None + } + pub(crate) fn free_all_once(&mut self) -> bool { + let first = !self.freed_all; + self.freed_all = true; + first + } + pub(crate) fn shadow_tick(&mut self, id: Id, on: bool) { + if let Memory::Shadow { concealed, power } = &mut self.units.get_mut(&id).unwrap().memory { + if on && !*concealed { + *power = true; + } + *concealed = on; + } + } + pub(crate) fn shadow_power(&self, id: Id) -> bool { + self.units + .get(&id) + .is_some_and(|s| matches!(s.memory, Memory::Shadow { power: true, .. })) + } + pub(crate) fn shadow_spent(&mut self, id: Id) { + if let Memory::Shadow { power, .. } = &mut self.units.get_mut(&id).unwrap().memory { + *power = false; + } + } +} diff --git a/crates/engine/src/battle/content/enemies/forms.rs b/crates/engine/src/battle/content/enemies/forms.rs new file mode 100644 index 0000000..44f201d --- /dev/null +++ b/crates/engine/src/battle/content/enemies/forms.rs @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +#[derive(Clone, Copy, Debug)] +pub struct Husk { + pub hits: f64, + pub delay: f64, + pub shield: u32, + pub regen: bool, +} +impl Husk { + pub(crate) fn key(self) -> &'static str { + if self.regen { + "ab:regen" + } else { + "ab:ember" + } + } +} +#[derive(Clone, Copy, Debug)] +pub struct Stone { + pub res: f64, + pub duration: f64, + pub def: f64, + pub stone_res: f64, +} +#[derive(Clone, Copy, Debug)] +pub enum Form { + Husk(Husk), + Stone(Stone), +} +#[derive(Clone, Copy, Debug)] +pub(crate) enum HuskPhase { + Living { original: Option }, + Rebirth { original: f64, until: f64 }, + Husk { original: f64 }, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum StonePhase { + Ground, + Stone, + Flight, +} +#[derive(Clone, Copy, Debug)] +pub(crate) enum State { + Husk { config: Husk, phase: HuskPhase }, + Stone { config: Stone, phase: StonePhase }, +} +impl Form { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key| talent(raw, ov, &[key]); + Ok(Some(match key { + "enemy_1288_duskls" + | "enemy_1288_duskls_2" + | "enemy_1292_duskld" + | "enemy_9010_acpupp" => { + let shield = t("Aura.max_damage_block_cnt"); + if shield < 0. || shield.ceil() > i32::MAX as f64 { + return Err("Husk shield count outside i32 domain".into()); + } + Self::Husk(Husk { + hits: t("Revive[Trigger].prop_max_hp"), + delay: t("Revive[Trigger].interval"), + shield: shield.ceil() as u32, + regen: key == "enemy_9010_acpupp", + }) + } + "enemy_1172_dugago" | "enemy_1172_dugago_2" => Self::Stone(Stone { + res: talent( + raw, + ov, + &["refracting.magic_resistance", "Refracting.magic_resistance"], + ), + duration: t("stone.duration"), + def: t("stone.def"), + stone_res: t("stone.magic_resistance"), + }), + _ => return Ok(None), + })) + } + pub(super) fn state(self) -> State { + match self { + Self::Husk(config) => State::Husk { + config, + phase: HuskPhase::Living { original: None }, + }, + Self::Stone(config) => State::Stone { + config, + phase: StonePhase::Ground, + }, + } + } +} +impl Runtime { + pub(crate) fn form(&self, id: Id) -> Option { + self.units.get(&id).and_then(|s| s.form) + } + pub(crate) fn set_form(&mut self, id: Id, state: State) { + self.units.get_mut(&id).unwrap().form = Some(state); + } +} diff --git a/crates/engine/src/battle/content/enemies/leaders.rs b/crates/engine/src/battle/content/enemies/leaders.rs new file mode 100644 index 0000000..7ce5629 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/leaders.rs @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::movement::Cooldown; +use super::*; +#[derive(Clone, Copy, Debug)] +pub enum Leader { + Skull { + ratio: f64, + atk: f64, + defense: f64, + }, + Axe { + atk: f64, + aspd: f64, + max: u32, + delay: f64, + }, + Demon { + aspd: f64, + scale: f64, + }, + Vines { + every: u32, + stun: f64, + duration: f64, + scale: f64, + }, + Balloon { + skill: Option, + duration: f64, + speed: f64, + }, + Spin { + skill: Option, + duration: f64, + interval: f64, + radius: f64, + scale: f64, + }, +} +#[derive(Clone, Copy, Debug)] +pub(crate) enum Memory { + None, + Skull { + splash: bool, + enraged: bool, + }, + Axe { + last: Option, + }, + Vines { + count: u32, + }, + Balloon { + left: f64, + }, + Spin { + left: f64, + until: f64, + no_attack: bool, + previous: Option<[f64; 2]>, + hidden: bool, + }, +} +impl Leader { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key| talent(raw, ov, &[key]); + let v = |key, fallback| talent_value(raw, ov, key).unwrap_or(fallback); + let n = |v: &Value, fallback| v.as_f64().filter(|n| n.is_finite()).unwrap_or(fallback); + Ok(Some(match key { + "enemy_1500_skulsr" => Self::Skull { + ratio: v("atkup.hp_ratio", 0.5), + atk: t("atkup.atk"), + defense: -t("defdown.def"), + }, + "enemy_2005_axetro" => Self::Axe { + atk: t("atkup.atk"), + aspd: t("atkup.attack_speed"), + max: abilities::count(v("atkup.max_stack_cnt", 1.))?, + delay: v("checker.delay", 4.), + }, + "enemy_2048_smgrd" => Self::Demon { + aspd: t("BlackFog.attack_speed"), + scale: v("DamageUp.atk_scale", 1.), + }, + "enemy_2052_smgia" => { + let s = abilities::skill(raw, ov, "StunAttack"); + let sp = n(&s["spCost"], 0.); + Self::Vines { + every: abilities::count(if sp > 0. { sp + 1. } else { 3. })?, + stun: n(&s["bb"]["stun"], 0.), + duration: t("Weak.weak[limit]"), + scale: v("Weak.damage_scale", 1.), + } + } + "enemy_2004_balloon" => { + let s = abilities::skill(raw, ov, "TakeOff"); + Self::Balloon { + skill: Cooldown::compile(raw, ov, "TakeOff"), + duration: n(&s["bb"]["duration"], 0.), + speed: n(&s["bb"]["balloon_s[fly].move_speed"], 0.), + } + } + "enemy_10116_ymgtop" => Self::Spin { + skill: Cooldown::compile(raw, ov, "SwitchModeTrigger").or(Some(Cooldown { + initial: 10., + period: 60., + })), + duration: t("EndRotate.rotate_duration"), + interval: v("RotateDamage.interval", 1.), + radius: v("RotateDamage.attack@range_radius", 1.), + scale: v("RotateDamage.attack@atk_scale", 1.), + }, + _ => return Ok(None), + })) + } + pub(super) fn memory(self) -> Memory { + match self { + Self::Skull { .. } => Memory::Skull { + splash: false, + enraged: false, + }, + Self::Axe { .. } => Memory::Axe { last: None }, + Self::Vines { .. } => Memory::Vines { count: 0 }, + Self::Balloon { skill, .. } => Memory::Balloon { + left: skill.map(|s| s.initial).unwrap_or(0.), + }, + Self::Spin { skill, .. } => Memory::Spin { + left: skill.map(|s| s.initial).unwrap_or(0.), + until: f64::NEG_INFINITY, + no_attack: false, + previous: None, + hidden: false, + }, + _ => Memory::None, + } + } +} +impl Runtime { + pub(crate) fn leader(&self, id: Id) -> Memory { + self.units + .get(&id) + .map(|s| s.leader) + .unwrap_or(Memory::None) + } + pub(crate) fn set_leader(&mut self, id: Id, state: Memory) { + self.units.get_mut(&id).unwrap().leader = state; + } +} diff --git a/crates/engine/src/battle/content/enemies/lifecycle.rs b/crates/engine/src/battle/content/enemies/lifecycle.rs new file mode 100644 index 0000000..8d7bcaf --- /dev/null +++ b/crates/engine/src/battle/content/enemies/lifecycle.rs @@ -0,0 +1,294 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::movement::Cooldown; +use super::*; +#[derive(Clone, Copy, Debug)] +pub enum Lifecycle { + Warden { + duration: f64, + res: f64, + atk: f64, + defense: f64, + bat: f64, + speed: f64, + every: [u32; 2], + stun: f64, + targets: usize, + times: u32, + penetration: f64, + }, + Ugly { + duration: f64, + melee: f64, + bomb: f64, + stun: f64, + speed: f64, + defense: Option, + res: Option, + burn: f64, + }, + Reid { + duration: f64, + invincible: f64, + hp: f64, + ratio: f64, + atk: f64, + skill: Option, + speed: f64, + rush: f64, + }, + Vine { + attack: f64, + time: f64, + first: f64, + normal: f64, + }, + Ignitable { + scale: f64, + }, + Brood { + skill: Option, + }, + Seed, + Reborn { + duration: f64, + invincible: f64, + neural: f64, + }, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum RebornPhase { + Fresh, + Rebirth, + Revived, +} +#[derive(Clone, Copy, Debug)] +pub(crate) enum Memory { + None, + Vine { + start: f64, + first: bool, + }, + Ignitable { + on: bool, + }, + Brood { + left: f64, + }, + Seed { + projectile: Option, + }, + Reborn(RebornPhase), + Warden { + phase: RebornPhase, + count: u32, + power: bool, + }, + Ugly { + phase: RebornPhase, + splash: bool, + }, + Reid { + phase: RebornPhase, + left: f64, + enraged: bool, + }, +} +impl Lifecycle { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key| talent(raw, ov, &[key]); + let v = |key, fallback| talent_value(raw, ov, key).unwrap_or(fallback); + let skill = |key| abilities::skill(raw, ov, key); + let every = |key| { + let sp = skill(key)["spCost"].as_f64().unwrap_or(0.); + abilities::count(if sp > 0. { sp + 1. } else { 3. }) + }; + Ok(Some(match key { + "enemy_1516_jakill" => Self::Warden { + duration: t("reborn.duration"), + res: t("enhance.magic_resistance"), + atk: t("enhance.atk"), + defense: t("enhance.def"), + bat: t("enhance.base_attack_time"), + speed: t("enhance.move_speed"), + every: [every("ironsandstorm")?, every("armorpiercing")?], + stun: skill("ironsandstorm")["bb"]["stun"].as_f64().unwrap_or(0.), + targets: abilities::count( + skill("ironsandstorm")["bb"]["max_target"] + .as_f64() + .unwrap_or(1.), + )? as usize, + times: abilities::count( + skill("armorpiercing")["bb"]["times"] + .as_f64() + .unwrap_or(1.) + .min(64.), + )?, + penetration: skill("armorpiercing")["bb"]["def_penetrate"] + .as_f64() + .unwrap_or(0.), + }, + "enemy_1512_mcmstr" => Self::Ugly { + duration: t("reborn.duration"), + melee: v("combat.attack@mcmstr_rage_attack.atk_scale", 1.), + bomb: skill("bomb[reborning]")["bb"]["atk_scale"] + .as_f64() + .unwrap_or(0.), + stun: skill("bomb[reborning]")["bb"]["stun"] + .as_f64() + .unwrap_or(0.), + speed: t("bird_run.move_speed"), + defense: talent_value(raw, ov, "bird_run.def"), + res: talent_value(raw, ov, "bird_run.magic_resistance"), + burn: t("bird_run.damage"), + }, + "enemy_1539_reid" => Self::Reid { + duration: t("Reborn.duration"), + invincible: t("Reborn.invincible"), + hp: v("Reborn.hp_ratio", 0.5), + ratio: v("atkup.hp_ratio", 0.5), + atk: talent_value(raw, ov, "AtkUp.atk").unwrap_or_else(|| t("atkup.atk")), + skill: Cooldown::compile(raw, ov, "Rush"), + speed: skill("Rush")["bb"]["move_speed"].as_f64().unwrap_or(0.), + rush: skill("Rush")["bb"]["duration"].as_f64().unwrap_or(0.), + }, + "enemy_10065_ftzlc" => Self::Ignitable { + scale: t("boom.atk_scale"), + }, + "enemy_10067_ftsjc" => Self::Vine { + attack: t("pow.add_max_atk"), + time: t("pow.time"), + first: t("pow.attack@ep_damage_ratio"), + normal: t("pow.attack@ep_damage_ratio_normal"), + }, + "enemy_1321_wdarft" => Self::Brood { + skill: Cooldown::compile(raw, ov, "BornBugs"), + }, + "enemy_1269_nhfly" => Self::Seed, + "enemy_10098_crhro" => Self::Reborn { + duration: t("reborn.duration"), + invincible: t("reborn.invincible"), + neural: t("inside.attack@ep_damage_ratio"), + }, + _ => return Ok(None), + })) + } + pub(crate) fn rebirth(self) -> Option<(f64, f64, f64)> { + match self { + Self::Reborn { + duration, + invincible, + .. + } => Some((duration, invincible, 1.)), + Self::Warden { duration, .. } | Self::Ugly { duration, .. } => Some((duration, 0., 1.)), + Self::Reid { + duration, + invincible, + hp, + .. + } => Some((duration, invincible, hp.clamp(0., 1.))), + _ => None, + } + } + pub(super) fn spawn( + self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + match self { + Self::Warden { res, .. } => { + let mut b = Buff::default(); + b.key = Some("ab:warden".into()); + b.mods.insert("resFlat".into(), res); + b.runtime.persist = true; + b.runtime.visible = true; + r.add( + w, + h, + id, + Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } + Self::Ugly { .. } => { + w.unit_mut(id)?.stats.edit_base(|b| { + let r = b.0.get("rangeRadius").copied().unwrap_or(0.); + b.0.insert("rangeRadius".into(), r.max(2.5)); + }); + } + _ => {} + } + Ok(()) + } + pub(super) fn memory(self, time: f64) -> Memory { + match self { + Self::Warden { .. } => Memory::Warden { + phase: RebornPhase::Fresh, + count: 0, + power: false, + }, + Self::Ugly { .. } => Memory::Ugly { + phase: RebornPhase::Fresh, + splash: false, + }, + Self::Reid { skill, .. } => Memory::Reid { + phase: RebornPhase::Fresh, + left: skill.map(|s| s.initial).unwrap_or(0.), + enraged: false, + }, + Self::Vine { .. } => Memory::Vine { + start: time, + first: true, + }, + Self::Ignitable { .. } => Memory::Ignitable { on: false }, + Self::Brood { skill } => Memory::Brood { + left: skill.map(|s| s.initial).unwrap_or(0.), + }, + Self::Seed => Memory::Seed { projectile: None }, + Self::Reborn { .. } => Memory::Reborn(RebornPhase::Fresh), + } + } +} +impl Runtime { + pub(crate) fn reborn_phase(&self, id: Id) -> Option { + if let Kit::Caster(c) = self.kit_ref(id) { + if c.rebirth().is_some() { + return self.caster(id).phase; + } + } + match self.lifecycle(id) { + Memory::Reborn(p) + | Memory::Warden { phase: p, .. } + | Memory::Ugly { phase: p, .. } + | Memory::Reid { phase: p, .. } => Some(p), + _ => None, + } + } + pub(crate) fn set_reborn_phase(&mut self, id: Id, p: RebornPhase) { + let caster = matches!(self.kit_ref(id), Kit::Caster(c) if c.rebirth().is_some()); + if caster { + self.units.get_mut(&id).unwrap().caster.phase = Some(p); + return; + } + match &mut self.units.get_mut(&id).unwrap().lifecycle { + Memory::Reborn(phase) + | Memory::Warden { phase, .. } + | Memory::Ugly { phase, .. } + | Memory::Reid { phase, .. } => *phase = p, + _ => unreachable!(), + } + } + pub(crate) fn lifecycle(&self, id: Id) -> Memory { + self.units + .get(&id) + .map(|s| s.lifecycle) + .unwrap_or(Memory::None) + } + pub(crate) fn set_lifecycle(&mut self, id: Id, state: Memory) { + self.units.get_mut(&id).unwrap().lifecycle = state; + } +} diff --git a/crates/engine/src/battle/content/enemies/movement.rs b/crates/engine/src/battle/content/enemies/movement.rs new file mode 100644 index 0000000..a82beab --- /dev/null +++ b/crates/engine/src/battle/content/enemies/movement.rs @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; + +#[derive(Clone, Copy, Debug)] +pub struct Cooldown { + pub initial: f64, + pub period: f64, +} +impl Cooldown { + pub(super) fn compile(raw: &Value, ov: &Value, key: &str) -> Option { + let s = abilities::skill(raw, ov, key); + (!s.is_null()).then(|| Self { + initial: s["initCooldown"] + .as_f64() + .filter(|n| n.is_finite()) + .unwrap_or(0.), + period: s["cooldown"] + .as_f64() + .filter(|n| n.is_finite()) + .unwrap_or(0.), + }) + } + pub(crate) fn advance(self, left: &mut f64, dt: f64, castable: bool) -> bool { + *left -= dt; + if *left > 1e-9 || !castable { + return false; + } + *left = self.period.max(1. / 30.); + true + } +} +#[derive(Clone, Copy, Debug)] +pub enum Unbalance { + Bleed { amount: f64, interval: f64 }, + Stun(f64), + Wall(f64), + LoseEgg(f64), +} +#[derive(Clone, Copy, Debug)] +pub enum Movement { + Syufo { + erosion: f64, + }, + Parrot { + down: f64, + speed: f64, + duration: f64, + }, + Unbalanced(Unbalance), + BoneSpike { + restore: f64, + }, + Run { + skill: Option, + speed: f64, + duration: f64, + }, +} +#[derive(Clone, Copy, Debug)] +pub(crate) enum Memory { + None, + Syufo { + crawl: bool, + }, + Parrot { + down: bool, + chill: bool, + ran: bool, + }, + Bleed { + elapsed: f64, + }, + Travel { + previous: Option<[f64; 2]>, + hidden: bool, + done: bool, + }, + Cast { + left: f64, + }, +} +impl Movement { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value, tag: Option<&str>) -> Option { + let t = |key| talent(raw, ov, &[key]); + Some(match key { + "enemy_2025_syufo" => Self::Syufo { + erosion: t("EpDamage.attack@ep_damage_ratio"), + }, + "enemy_10045_parrot" => Self::Parrot { + down: t("Stun.duration"), + speed: talent_value(raw, ov, "M0SpeedUp.move_speed").unwrap_or(1.), + duration: t("M0SpeedUp.duration"), + }, + "enemy_1328_cbjedi" => Self::Unbalanced(Unbalance::Bleed { + amount: t("unbalanced_bleed.damage"), + interval: t("unbalanced_bleed.interval"), + }), + "enemy_10112_ymgds" => Self::Unbalanced(Unbalance::Stun(t("StunAfterUnbalance.stun"))), + "enemy_10138_xdsnow" => Self::Unbalanced(Unbalance::Wall(t("hitWall.value"))), + "enemy_10141_xdpeng_2" => Self::Unbalanced(Unbalance::LoseEgg(t("speed.move_speed"))), + "enemy_9008_acbunn" => Self::BoneSpike { + restore: if tag == Some("duck") { 1. } else { 0. }, + }, + "enemy_10001_trslim" => { + let s = abilities::skill(raw, ov, "StartRun"); + Self::Run { + skill: Cooldown::compile(raw, ov, "StartRun"), + speed: s["bb"]["move_speed"] + .as_f64() + .filter(|n| n.is_finite()) + .unwrap_or(0.), + duration: s["bb"]["block_free_time"] + .as_f64() + .filter(|n| n.is_finite()) + .unwrap_or(0.), + } + } + _ => return None, + }) + } + pub(super) fn memory(self) -> Memory { + match self { + Self::Syufo { .. } => Memory::Syufo { crawl: false }, + Self::Parrot { .. } => Memory::Parrot { + down: false, + chill: false, + ran: false, + }, + Self::Unbalanced(Unbalance::Bleed { .. }) => Memory::Bleed { elapsed: 0. }, + Self::Unbalanced(_) => Memory::Travel { + previous: None, + hidden: false, + done: false, + }, + Self::Run { skill, .. } => Memory::Cast { + left: skill.map(|s| s.initial).unwrap_or(0.), + }, + _ => Memory::None, + } + } + pub(super) fn spawn( + self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + let b = match self { + Self::Syufo { .. } | Self::Parrot { .. } => { + let mut b = flag_buff("ab:float", "float"); + b.flags + .extend(["unblockable", "noDisplace"].map(str::to_string)); + b + } + Self::BoneSpike { restore } => { + let mut b = flag_buff("ab:stealth", "stealth"); + b.runtime.stealth_restore = Some(restore); + b + } + _ => return Ok(()), + }; + r.add( + w, + h, + id, + Spec { + buff: b, + flags_present: true, + ..Default::default() + }, + )?; + Ok(()) + } +} +impl Runtime { + pub(crate) fn movement(&self, id: Id) -> Memory { + self.units + .get(&id) + .map(|s| s.movement) + .unwrap_or(Memory::None) + } + pub(crate) fn set_movement(&mut self, id: Id, state: Memory) { + self.units.get_mut(&id).unwrap().movement = state; + } +} diff --git a/crates/engine/src/battle/content/enemies/reactions.rs b/crates/engine/src/battle/content/enemies/reactions.rs new file mode 100644 index 0000000..3e6699e --- /dev/null +++ b/crates/engine/src/battle/content/enemies/reactions.rs @@ -0,0 +1,258 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; + +#[derive(Clone, Copy, Debug)] +pub struct Fear { + pub duration: f64, + pub speed: f64, + pub speed_duration: f64, + pub steal: Option, +} +#[derive(Clone, Copy, Debug)] +pub enum Reaction { + Aura { + radius: f64, + defense: bool, + amount: f64, + }, + ExposeDeath { + radius: f64, + duration: f64, + scale: f64, + }, + HealDeath { + radius: f64, + scale: f64, + }, + Barrier { + resistance: f64, + aspd: f64, + shield: f64, + }, + Double { + every: u32, + scale: f64, + }, + Rush { + speed: f64, + interval: f64, + max: u32, + scale: f64, + }, + FirstSplash { + scale: f64, + }, + Fear(Fear), + Front { + reduction: f64, + neural: f64, + }, + Crowd { + reduction: f64, + }, + Shell, + Blood { + ratio: f64, + }, +} +#[derive(Clone, Copy, Debug)] +pub(crate) enum Memory { + None, + Once { + done: bool, + }, + Power { + count: u32, + powered: bool, + }, + Rush { + active: bool, + layers: u32, + elapsed: f64, + }, + Facing { + x: f64, + sign: f64, + }, +} +impl Reaction { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key| talent(raw, ov, &[key]); + let v = |key, default| talent_value(raw, ov, key).unwrap_or(default); + let n = |v: &Value, default| v.as_f64().filter(|n| n.is_finite()).unwrap_or(default); + Ok(Some(match key { + "enemy_2085_skzjxd" | "enemy_2085_skzjxd_2" => Self::Crowd { + reduction: t("Weakness.damage_resistance"), + }, + "enemy_1017_defdrn" => Self::Aura { + radius: v("defup.range_radius", 2.5), + defense: true, + amount: t("defup.def"), + }, + "enemy_1355_mrfly" | "enemy_1355_mrfly_2" => Self::Aura { + radius: n(&raw["stats"]["rangeRadius"], 0.).max(0.), + defense: false, + amount: t("magdef_add.magic_resistance"), + }, + "enemy_1407_hummbd" => Self::ExposeDeath { + radius: v("Expose.range_radius", 1.), + duration: t("Expose.weak[limit]"), + scale: v("Expose.damage_scale", 1.), + }, + "enemy_10156_mncrer" => Self::HealDeath { + radius: v("Boom.projectile_range", 1.), + scale: t("Boom.heal_scale"), + }, + "enemy_10127_rkmbst_2" => Self::Barrier { + resistance: t("M0Shield.damage_resistance"), + aspd: t("M0Shield.attack_speed"), + shield: t("M0Shield.init_shield_hp_ratio"), + }, + "enemy_10118_ymgprc" => { + let s = abilities::skill(raw, ov, "PowerAttack"); + let sp = n(&s["spCost"], 0.); + Self::Double { + every: abilities::count(if sp > 0. { sp + 1. } else { 3. })?, + scale: s["bb"]["atk_scale"] + .as_f64() + .filter(|n| n.is_finite() && *n != 0.) + .unwrap_or(1.), + } + } + "enemy_1072_dlancer" => Self::Rush { + speed: t("rush.dlancer_t[trigger].move_speed"), + interval: { + let value = v("rush.dlancer_t[trigger].interval", 0.5); + // The official 0.5-second step permits a tenfold speedup. + if value > 0. { + value.max(0.05) + } else { + value + } + }, + max: abilities::count(t("rush.dlancer_t[trigger].trig_cnt"))?, + scale: t("firstattack.atk_scale"), + }, + "enemy_1320_wdrrl_2" => Self::FirstSplash { + scale: t("AOEAttack.atk_scale"), + }, + "enemy_10083_hlbird" | "enemy_10084_hlegle" => Self::Fear(Fear { + duration: t("SelfFear.fear"), + speed: t("SelfFear.move_speed"), + speed_duration: t("SelfFear.speed_duration"), + steal: (key == "enemy_10084_hlegle") + .then(|| v("DamageOrBullet.attack@minus_bullet", 1.)), + }), + "enemy_10097_crshd" => Self::Front { + reduction: t("weakness.damage_resistance"), + neural: t("block.ep_damage_ratio"), + }, + "enemy_1112_emppnt" | "enemy_1112_emppnt_2" => Self::Shell, + "enemy_1367_dseed" => Self::Blood { + ratio: t("Passive.hp_ratio"), + }, + _ => return Ok(None), + })) + } + pub(super) fn memory(self, position: [f64; 2]) -> Memory { + match self { + Self::Fear(_) | Self::FirstSplash { .. } => Memory::Once { done: false }, + Self::Double { .. } => Memory::Power { + count: 0, + powered: false, + }, + Self::Rush { .. } => Memory::Rush { + active: true, + layers: 0, + elapsed: 0., + }, + Self::Front { .. } | Self::Crowd { .. } => Memory::Facing { + x: position[1], + sign: -1., + }, + _ => Memory::None, + } + } + pub(super) fn spawn( + self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + let mut list = vec![]; + match self { + Self::Crowd { .. } => { + list.push(flag_buff("ab:unblockable", "unblockable")); + } + Self::FirstSplash { .. } => w.unit_mut(id)?.block_weight = 3., + Self::Barrier { + resistance, + aspd, + shield, + } => { + let mut taunt = Buff::default(); + taunt.key = Some("ab:taunt".into()); + taunt.mods.insert("taunt".into(), 1.); + taunt.runtime.persist = true; + list.push(taunt); + let mut m = Buff::default(); + m.key = Some("ab:m0".into()); + m.mods = [ + ("dmgTakenMul".into(), 1. - resistance), + ("aspd".into(), aspd), + ] + .into(); + m.runtime.persist = true; + m.runtime.visible = true; + list.push(m); + let amount = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp") + * shield; + if amount > 0. { + let mut b = Buff::default(); + b.key = Some("ab:m0barrier".into()); + b.shield = amount; + b.runtime.persist = true; + list.push(b); + } + } + Self::Blood { .. } => { + let mut b = flag_buff("ab:dseed", "selfBound"); + b.flags + .extend(["noMove", "unblockable", "noDisplace"].map(str::to_string)); + list.push(b); + } + _ => {} + } + for b in list { + r.add( + w, + h, + id, + Spec { + mods_present: !b.mods.is_empty(), + flags_present: !b.flags.is_empty(), + buff: b, + ..Default::default() + }, + )?; + } + Ok(()) + } +} +impl Runtime { + pub(crate) fn reaction(&self, id: Id) -> Memory { + self.units + .get(&id) + .map(|s| s.reaction) + .unwrap_or(Memory::None) + } + pub(crate) fn set_reaction(&mut self, id: Id, state: Memory) { + self.units.get_mut(&id).unwrap().reaction = state; + } +} diff --git a/crates/engine/src/battle/content/enemies/specials.rs b/crates/engine/src/battle/content/enemies/specials.rs new file mode 100644 index 0000000..f717685 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/specials.rs @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::movement::Cooldown; +use super::*; +#[derive(Clone, Copy, Debug)] +pub enum Special { + Catapult { + times: u32, + interval: f64, + radius: f64, + bound: f64, + }, + Bomb { + skill: Option, + speed: f64, + }, + Cloud { + grab: Option, + fire: Option, + radius: f64, + duration: f64, + gain: f64, + max: f64, + cost: f64, + scale: f64, + }, + Parasite { + scale: f64, + element: f64, + }, + Armor { + skill: Option, + appear: u32, + times: u32, + ranged: f64, + }, + Translator { + counts: [u32; 2], + mods: [[f64; 7]; 3], + anger: f64, + }, + Elk { + skill: Option, + duration: f64, + scale: f64, + stun: f64, + }, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Form { + Fuchou, + Youling, + Shushi, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Translation { + Origin, + Pending(Form), + Changing(Form), + Done(Form), +} +#[derive(Clone, Copy, Debug)] +pub(crate) enum BombPhase { + Ready, + Charging { release: f64 }, + Dropped { waited: bool, landed: bool }, + Done, +} +#[derive(Clone, Copy, Debug)] +pub(crate) struct Charge { + pub target: Id, + pub until: f64, +} +#[derive(Clone, Copy, Debug)] +pub(crate) enum Memory { + Catapult { + target: Option, + position: Option<[f64; 2]>, + }, + None, + Bomb { + phase: BombPhase, + left: f64, + }, + Cloud { + left: [f64; 2], + ammo: f64, + }, + Parasite { + host: Option, + }, + Armor { + left: f64, + combo: u32, + appeared: bool, + }, + Translator { + phase: Translation, + counts: [u32; 2], + anger: bool, + }, + Elk { + left: f64, + charge: Option, + previous: Option<[f64; 2]>, + hidden: bool, + }, +} +impl Special { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key: &str| talent(raw, ov, &[key]); + let v = |key, fallback| talent_value(raw, ov, key).unwrap_or(fallback); + let sk = |key| abilities::skill(raw, ov, key); + let n = |v: &Value, f| v.as_f64().filter(|v| v.is_finite()).unwrap_or(f); + Ok(Some(match key { + "enemy_10162_mnctpt" => Self::Catapult { + times: v("Attack.attack@times", 1.).clamp(1., 100.).floor() as u32, + interval: v("Attack.attack@hit_interval", 0.3), + radius: v("Attack.attack@projectile_range", 0.5), + bound: v("Attack.attack@offset_bound", 3.), + }, + "enemy_1040_bombd" => Self::Bomb { + skill: Cooldown::compile(raw, ov, "boomb"), + speed: n(&sk("boomb")["bb"]["move_speed"], 0.), + }, + "enemy_9009_acfort" => Self::Cloud { + grab: Cooldown::compile(raw, ov, "KillOthers"), + fire: Cooldown::compile(raw, ov, "FireWeapon"), + radius: n(&sk("KillOthers")["bb"]["range_radius"], 1.5) * 2.5, + duration: n(&sk("KillOthers")["bb"]["duration"], 4.), + gain: n(&sk("KillOthers")["bb"]["sp"], 1.).min(64.), + max: n(&raw["sp"]["maxSp"], 3.).max(1.).min(64.), + cost: n(&sk("FireWeapon")["spCost"], 1.).max(1.), + scale: n(&sk("FireWeapon")["bb"]["atk_scale"], 1.), + }, + "enemy_9007_acelem" => Self::Parasite { + scale: t("1.atk_scale"), + element: v("1.ep_damage_scale", 1.), + }, + "enemy_10027_vtsk" => Self::Armor { + skill: Cooldown::compile(raw, ov, "MultiCombat"), + appear: abilities::count(n(&sk("Appear")["bb"]["times"], 0.).clamp(0., 100.))?, + times: abilities::count(n(&sk("MultiCombat")["bb"]["times"], 1.).clamp(0., 100.))?, + ranged: v("range.attack@atk_scale_range", 1.), + }, + "enemy_10081_mpplai" => { + let bat = n(&raw["stats"]["bat"], 1.); + let speed = n(&raw["stats"]["moveSpeed"], 1.); + let mods = [ + "Mode_Fuchou_Passive", + "Mode_Youling_Passive", + "Mode_Shushi_Passive", + ] + .map(|prefix| { + [ + t(&format!("{prefix}.max_hp")), + t(&format!("{prefix}.atk")), + t(&format!("{prefix}.def")), + t(&format!("{prefix}.magic_resistance")), + (1. + t(&format!("{prefix}.move_speed")) + / if speed == 0. { 1. } else { speed }) + .max(0.), + t(&format!("{prefix}.base_attack_time")) / if bat == 0. { 1. } else { bat }, + t(&format!("{prefix}.mass_level")), + ] + }); + Self::Translator { + counts: [ + abilities::count(v("Passive.phy_max_count", 4.))?, + abilities::count(v("Passive.magic_max_count", 4.))?, + ], + mods, + anger: t("Mode_Fuchou_Anger.atk"), + } + } + "enemy_10144_xdelk_2" => Self::Elk { + skill: Cooldown::compile(raw, ov, "skill"), + duration: n(&sk("skill")["bb"]["duration"], 0.), + scale: n(&sk("skill")["bb"]["atk_scale_s"], 1.) * 2., + stun: t("data.attack@fail_duration"), + }, + _ => return Ok(None), + })) + } + pub(super) fn memory(self) -> Memory { + match self { + Self::Catapult { .. } => Memory::Catapult { + target: None, + position: None, + }, + Self::Bomb { skill, .. } => Memory::Bomb { + phase: BombPhase::Ready, + left: skill.map(|s| s.initial).unwrap_or(f64::INFINITY), + }, + Self::Cloud { grab, fire, .. } => Memory::Cloud { + left: [grab, fire].map(|s| s.map(|s| s.initial).unwrap_or(f64::INFINITY)), + ammo: 0., + }, + Self::Parasite { .. } => Memory::Parasite { host: None }, + Self::Armor { skill, .. } => Memory::Armor { + left: skill.map(|s| s.initial).unwrap_or(f64::INFINITY), + combo: 0, + appeared: false, + }, + Self::Translator { .. } => Memory::Translator { + phase: Translation::Origin, + counts: [0; 2], + anger: false, + }, + Self::Elk { skill, .. } => Memory::Elk { + left: skill.map(|s| s.initial).unwrap_or(f64::INFINITY), + charge: None, + previous: None, + hidden: false, + }, + } + } + pub(super) fn spawn( + self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + let mut b = Buff::default(); + match self { + Self::Translator { .. } => { + b.key = Some("ab:origin".into()); + b.runtime.persist = true; + b.flags.insert("noDisplace".into()); + } + Self::Parasite { .. } => { + b.key = Some("ab:taunt".into()); + b.runtime.persist = true; + b.mods.insert("taunt".into(), -1.); + } + _ => return Ok(()), + } + r.add( + w, + h, + id, + Spec { + mods_present: !b.mods.is_empty(), + flags_present: !b.flags.is_empty(), + buff: b, + ..Default::default() + }, + )?; + Ok(()) + } +} +impl Runtime { + pub(crate) fn special(&self, id: Id) -> Memory { + self.units + .get(&id) + .map(|s| s.special) + .unwrap_or(Memory::None) + } + pub(crate) fn set_special(&mut self, id: Id, state: Memory) { + self.units.get_mut(&id).unwrap().special = state; + } +} diff --git a/crates/engine/src/battle/content/enemies/splits.rs b/crates/engine/src/battle/content/enemies/splits.rs new file mode 100644 index 0000000..e1ecfa0 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/splits.rs @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::families::Memory; +use super::*; + +#[derive(Clone, Copy, Debug)] +pub enum Split { + Plain { + count: f64, + }, + Blades { + count: f64, + per_used: f64, + atk: f64, + }, + Veil { + count: f64, + radius: f64, + duration: f64, + cooldown: Option, + initial: f64, + }, + Teapot { + count: f64, + duration: f64, + aspd: f64, + }, + Boat { + erosion: f64, + }, +} +impl Split { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key| talent(raw, ov, &[key]); + let count = t("DeadSpawn.cnt"); + Ok(Some(match key { + "enemy_1195_sfyin" | "enemy_1195_sfyin_2" | "enemy_1197_sfshu" + | "enemy_1197_sfshu_2" | "enemy_1199_sfjin" => Self::Plain { count }, + "enemy_1207_sfji" | "enemy_1207_sfji_2" => { + if count.ceil() > i32::MAX as f64 { + return Err("Blade count outside i32 domain".into()); + } + Self::Blades { + count, + per_used: t("DeadSpawn.cnt_add"), + atk: talent(raw, ov, &["Atkup.atk", "AtkUp.atk"]), + } + } + "enemy_1209_sfden" | "enemy_1209_sfden_2" => { + let s = abilities::skill(raw, ov, "InvisibleShield"); + Self::Veil { + count, + radius: raw["stats"]["rawRangeRadius"] + .as_f64() + .filter(|n| n.is_finite() && *n != 0.) + .unwrap_or(2.), + duration: talent_value(raw, ov, "InvisibleShield.duration") + .unwrap_or_else(|| s["bb"]["duration"].as_f64().unwrap_or(0.)), + cooldown: s + .get("cooldown") + .map(|v| v.as_f64().filter(|n| n.is_finite()).unwrap_or(0.)), + initial: s["initCooldown"] + .as_f64() + .filter(|n| n.is_finite()) + .unwrap_or(0.), + } + } + "enemy_1203_sfhu" | "enemy_1203_sfhu_2" => Self::Teapot { + count, + duration: t("DeadBoom.duration"), + aspd: t("DeadBoom.attack_speed"), + }, + "enemy_1162_magmot" => Self::Boat { + erosion: t("EpDamage.attack@ep_damage_ratio"), + }, + _ => return Ok(None), + })) + } + pub(super) fn memory(self) -> Memory { + match self { + Self::Blades { .. } => Memory::Blades { + used: 0, + clear_cd: false, + }, + Self::Veil { initial, .. } => Memory::Veil { left: initial }, + _ => Memory::None, + } + } + pub(super) fn spawn( + self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + if let Self::Blades { count, atk, .. } = self { + if count > 0. && atk != 0. { + let mut b = Buff::default(); + b.key = Some("ab:blade".into()); + b.runtime.persist = true; + b.runtime.visible = true; + b.mods.insert("atkPct".into(), atk); + r.add( + w, + h, + id, + Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } + } + Ok(()) + } +} +impl Runtime { + pub(crate) fn split_count(&self, id: Id, split: Split) -> usize { + let n = match split { + Split::Plain { count } | Split::Veil { count, .. } | Split::Teapot { count, .. } => { + count + } + Split::Boat { .. } => 1., + Split::Blades { + count, per_used, .. + } => { + let used = match self.units.get(&id).unwrap().memory { + Memory::Blades { used, .. } => used, + _ => 0, + }; + (count + per_used * used as f64).max(1.) + } + }; + n.floor().clamp(0., 20.) as usize + } + pub(crate) fn spend_blade(&mut self, id: Id) -> bool { + let s = self.units.get_mut(&id).unwrap(); + if let (Kit::Split(Split::Blades { count, .. }), Memory::Blades { used, clear_cd }) = + (s.definition.kit, &mut s.memory) + { + if *used as f64 >= count { + return false; + } + *used += 1; + if (*used as f64) >= count { + *clear_cd = true; + return true; + } + } + false + } + pub(crate) fn clear_blade_cooldown(&mut self, id: Id) -> bool { + if let Memory::Blades { clear_cd, .. } = &mut self.units.get_mut(&id).unwrap().memory { + return std::mem::take(clear_cd); + } + false + } + pub(crate) fn veil_ready(&mut self, id: Id, dt: f64, castable: bool) -> bool { + let s = self.units.get_mut(&id).unwrap(); + if let ( + Kit::Split(Split::Veil { + cooldown: Some(cd), .. + }), + Memory::Veil { left }, + ) = (s.definition.kit, &mut s.memory) + { + *left -= dt; + if *left <= 1e-9 && castable { + *left = cd; + return true; + } + } + false + } +} diff --git a/crates/engine/src/battle/content/enemies/supporters.rs b/crates/engine/src/battle/content/enemies/supporters.rs new file mode 100644 index 0000000..b4e1ff6 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/supporters.rs @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use super::{movement::Cooldown, reactions::Fear}; +#[derive(Clone, Copy, Debug)] +pub enum Supporter { + Roar { + fear: Fear, + skill: Option, + duration: f64, + aspd: f64, + }, + Torturer { + count: usize, + radius: f64, + heal: f64, + atk: f64, + max: u32, + ranged: f64, + }, + Barrel { + speed: f64, + scale: f64, + life: f64, + aspd: f64, + dodge: f64, + }, + Carrier { + max: usize, + camel: bool, + speed: f64, + }, +} +#[derive(Clone, Debug)] +pub(crate) enum Memory { + None, + Roar { left: f64, feared: bool }, + Barrel { done: bool }, + Carrier { passengers: Vec, seats: usize }, +} +impl Supporter { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key| talent(raw, ov, &[key]); + let v = |key, fallback| talent_value(raw, ov, key).unwrap_or(fallback); + let n = |v: &Value, fallback| v.as_f64().filter(|n| n.is_finite()).unwrap_or(fallback); + Ok(Some(match key { + "enemy_10085_hllevi_2" => { + let s = abilities::skill(raw, ov, "Roar"); + Self::Roar { + fear: Fear { + duration: t("SelfFear.fear"), + speed: t("SelfFear.move_speed"), + speed_duration: t("SelfFear.speed_duration"), + steal: None, + }, + skill: Cooldown::compile(raw, ov, "Roar"), + duration: n(&s["bb"]["duration"], 0.), + aspd: n(&s["bb"]["attack_speed"], 0.), + } + } + "enemy_1364_spnaxe_2" => Self::Torturer { + count: t("Summon.cnt").floor().max(0.).min(20.) as usize, + radius: v("Attack.range_radius", 1.), + heal: t("Attack.hp_ratio"), + atk: t("Attack.atk"), + max: abilities::count(v("Attack.max_stack_cnt", 1.))?, + ranged: v("Attack.attack@ranged_atk_scale", 1.), + }, + "enemy_10044_wintun" => { + let s = abilities::skill(raw, ov, "BlockedBoom"); + Self::Barrel { + speed: v("1.move_speed", 1.), + scale: n(&s["bb"]["blockee_atk_scale"], 1.), + life: n(&s["bb"]["fixed_duration"], 0.), + aspd: n(&s["bb"]["attack_speed"], 0.), + dodge: n(&s["bb"]["prob"], 0.), + } + } + "enemy_1302_ymtro_2" | "enemy_10159_mntrjn" => { + let camel = key == "enemy_10159_mntrjn"; + Self::Carrier { + max: abilities::count( + talent_value(raw, ov, if camel { "bus.max_cnt" } else { "Bus.max_cnt" }) + .or_else(|| talent_value(raw, ov, "bus.max_cnt")) + .or_else(|| talent_value(raw, ov, "Bus.max_cnt")) + .unwrap_or(if camel { 5. } else { 4. }), + )? as usize, + camel, + speed: v("bus.move_speed", -0.2), + } + } + _ => return Ok(None), + })) + } + pub(super) fn memory(self) -> Memory { + match self { + Self::Roar { skill, .. } => Memory::Roar { + left: skill.map(|s| s.initial).unwrap_or(0.), + feared: false, + }, + Self::Barrel { .. } => Memory::Barrel { done: false }, + Self::Carrier { .. } => Memory::Carrier { + passengers: vec![], + seats: 0, + }, + _ => Memory::None, + } + } + pub(super) fn spawn( + self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + let b = match self { + Self::Barrel { speed, .. } => { + let mut b = Buff::default(); + b.key = Some("ab:barrel".into()); + b.runtime.persist = true; + b.mods.insert("moveMul".into(), speed); + Some(b) + } + Self::Carrier { camel: true, .. } => { + w.unit_mut(id)?.stats.set_move_floor(0.1); + Some(flag_buff("ab:unblockable", "unblockable")) + } + Self::Carrier { camel: false, .. } => { + w.unit_mut(id)?.block_weight = 4.; + None + } + _ => None, + }; + if let Some(b) = b { + r.add( + w, + h, + id, + Spec { + mods_present: !b.mods.is_empty(), + flags_present: !b.flags.is_empty(), + buff: b, + ..Default::default() + }, + )?; + } + Ok(()) + } +} +impl Runtime { + pub(crate) fn supporter(&self, id: Id) -> Memory { + self.units + .get(&id) + .map(|s| s.supporter.clone()) + .unwrap_or(Memory::None) + } + pub(crate) fn set_supporter(&mut self, id: Id, state: Memory) { + self.units.get_mut(&id).unwrap().supporter = state; + } +} diff --git a/crates/engine/src/battle/content/enemies/terrain.rs b/crates/engine/src/battle/content/enemies/terrain.rs new file mode 100644 index 0000000..dad8a15 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/terrain.rs @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +#[derive(Clone, Copy, Debug)] +pub enum TerrainKit { + Infection, + Chimera { + damage: f64, + recovery: f64, + }, + Nazg { + radius: f64, + }, + Chalice { + radius: f64, + share: f64, + }, + Deepsea { + swim: bool, + atk: f64, + drown: f64, + every: u32, + stun: f64, + }, +} +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct State { + pub active: bool, + pub wet: bool, + pub elapsed: f64, +} +impl TerrainKit { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key| talent(raw, ov, &[key]); + Ok(Some(match key { + "enemy_1422_lrsldr" | "enemy_1422_lrsldr_2" => Self::Infection, + "enemy_1425_lrcmra" | "enemy_1425_lrcmra_2" => Self::Chimera { + damage: t("OrigAura.damage"), + recovery: t("OrigAura.sp_recover_ratio"), + }, + "enemy_1427_lrnazg" => Self::Nazg { + radius: raw["stats"]["rawRangeRadius"] + .as_f64() + .filter(|v| *v != 0.) + .or_else(|| raw["stats"]["rangeRadius"].as_f64().filter(|v| *v != 0.)) + .unwrap_or(1.3), + }, + "enemy_1430_lrrook" => Self::Chalice { + radius: talent_value(raw, ov, "takeDmg.range_radius").unwrap_or(1.7), + share: t("takeDmg.damage_scale"), + }, + "enemy_1158_divman" => Self::Deepsea { + swim: true, + atk: t("Swim.atk"), + drown: 0., + every: 0, + stun: 0., + }, + "enemy_1160_hvyslr" | "enemy_1160_hvyslr_2" => { + let s = abilities::skill(raw, ov, "stuncombat"); + let sp = s["spCost"].as_f64().unwrap_or(0.); + Self::Deepsea { + swim: false, + atk: 0., + drown: t("Drown.damage"), + every: abilities::count(if sp > 0. { sp + 1. } else { 3. })?, + stun: s["bb"]["stun"].as_f64().unwrap_or(0.), + } + } + _ => return Ok(None), + })) + } +} +impl Runtime { + pub(crate) fn terrain_state(&self, id: Id) -> State { + self.units.get(&id).map(|s| s.terrain).unwrap_or_default() + } + pub(crate) fn set_terrain_state(&mut self, id: Id, state: State) { + self.units.get_mut(&id).unwrap().terrain = state; + } +} diff --git a/crates/engine/src/battle/content/enemies/zones.rs b/crates/engine/src/battle/content/enemies/zones.rs new file mode 100644 index 0000000..82caa05 --- /dev/null +++ b/crates/engine/src/battle/content/enemies/zones.rs @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +#[derive(Clone, Copy, Debug)] +pub struct Pollution { + pub radius: f64, + pub life: f64, + pub low: f64, + pub high: f64, +} +#[derive(Clone, Copy, Debug)] +pub struct Cloud { + pub radius: f64, + pub life: f64, + pub interval: f64, + pub scale: f64, +} +#[derive(Clone, Copy, Debug)] +pub struct Tank { + pub max: f64, + pub initial: f64, + pub melee: f64, + pub pollution: Pollution, +} +#[derive(Clone, Copy, Debug)] +pub enum ZoneKit { + Pollution(Pollution), + Poison(Cloud), + Tank(Tank), + Cannon { radius: f64, life: f64, amount: f64 }, +} +#[derive(Clone, Copy, Debug)] +pub(crate) struct TankState { + pub sp: f64, + pub skill: bool, +} +impl ZoneKit { + pub(super) fn compile(key: &str, raw: &Value, ov: &Value) -> Result, String> { + let t = |key| talent(raw, ov, &[key]); + let val = |key, default| talent_value(raw, ov, key).unwrap_or(default); + let n = |v: &Value, default| v.as_f64().filter(|n| n.is_finite()).unwrap_or(default); + Ok(Some(match key { + "enemy_1267_nhpbr" | "enemy_1267_nhpbr_2" => Self::Pollution(Pollution { + radius: val("PollutedDie.projectile_range", 1.), + life: t("PollutedDie.projectile_life_time"), + low: t("PollutedDie.polluted_damage_low"), + high: t("PollutedDie.polluted_damage_high"), + }), + "enemy_9006_actoxi" => Self::Poison(Cloud { + radius: val("1.projectile_range", 0.8), + life: t("1.projectile_life_time"), + interval: val("1.interval", 1.), + scale: t("1.damage_atk_scale"), + }), + "enemy_1272_nhtank" | "enemy_1272_nhtank_2" => { + let s = abilities::skill(raw, ov, "PollutedRangedAtk"); + let max = [ + n(&raw["sp"]["maxSp"], 0.), + n(&s["spCost"], 0.), + val("Empty.sp", 2.), + ] + .into_iter() + .find(|n| *n != 0.) + .unwrap_or(0.) + .max(1.); + Self::Tank(Tank { + max, + initial: n(&raw["sp"]["initSp"], 0.).max(0.).min(max), + melee: val("Empty.attack@chuang_atk_scale", 1.), + pollution: Pollution { + radius: 1.7, + life: n(&s["bb"]["projectile_life_time"], 0.), + low: n(&s["bb"]["polluted_damage_low"], 0.), + high: n(&s["bb"]["polluted_damage_high"], 0.), + }, + }) + } + "enemy_10122_uacann_2" => Self::Cannon { + radius: val("ProjectileBoomRange.attack@projectile_range", 1.) * 1.5, + life: t("ProjectileBoomRange.attack@projectile_life_time"), + amount: t("ProjectileBoomRange.attack@value"), + }, + _ => return Ok(None), + })) + } +} +impl Runtime { + pub(crate) fn tank_before(&mut self, id: Id) { + let s = self.units.get_mut(&id).unwrap(); + if let (Kit::Zone(ZoneKit::Tank(config)), Some(state)) = (s.definition.kit, &mut s.tank) { + state.skill = state.sp >= config.max; + } + } + pub(crate) fn tank_skill(&self, id: Id) -> bool { + self.units + .get(&id) + .and_then(|s| s.tank) + .is_some_and(|s| s.skill) + } + pub(crate) fn tank_attack(&mut self, id: Id) -> bool { + let s = self.units.get_mut(&id).unwrap(); + if let (Kit::Zone(ZoneKit::Tank(config)), Some(state)) = (s.definition.kit, &mut s.tank) { + if state.skill { + state.skill = false; + state.sp = 0.; + return true; + } + state.sp = (state.sp + 1.).min(config.max); + } + false + } +} diff --git a/crates/engine/src/battle/content/operators.rs b/crates/engine/src/battle/content/operators.rs index ba33620..4ea584e 100644 --- a/crates/engine/src/battle/content/operators.rs +++ b/crates/engine/src/battle/content/operators.rs @@ -1,5 +1,5 @@ // SPDX-License-Identifier: GPL-3.0-or-later -//! Native counterparts of the original tier-1 kits. Blackboard parameters stay +//! Native counterparts of the original operator kits. Blackboard parameters stay //! in external data; these builders compose the same SkillSpec/trait behaviour. use crate::battle::{ attacks::{Chain, Splash}, @@ -15,27 +15,50 @@ use crate::battle::{ use crate::deterministic::rng::Rng; use serde_json::Value; -#[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum Kit { - Yak, - Leizi, - Skgoat, - Greyy, - Prove, +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) struct Skill { + pub id: &'static str, + pub kind: Kind, + pub sp_type: SpType, + pub rule: &'static str, + pub attack_override: bool, } +impl Skill { + pub const fn duration(id: &'static str) -> Self { + Self { + id, + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + } + } +} +pub(crate) struct Kit { + pub position: &'static str, + pub profession: &'static str, + pub branch: &'static str, + pub ranged: bool, + pub can_hit_fly: bool, + pub physical: bool, + pub projectile: &'static str, + pub projectile_speed: f64, + pub required_range: Option<&'static [[i32; 2]]>, + pub skills: &'static [Skill], // default first + pub build: fn(&Value, bool, &mut Spec) -> Result<(), String>, +} +pub(crate) type AttackFilter = fn(&mut World, Id) -> Result; #[derive(Clone, Copy, Default)] pub(crate) enum HitHandler { #[default] None, - Leizi { - unblocked_scale: f64, - }, - Prove { - drop: f64, - up: f64, - prob: f64, - front_prob: f64, - crit_scale: f64, + Leizi(leizi::Hit), + Prove(prove::Hit), + Vigna(vigna::Hit), + Blocked { + scale: f64, + own: bool, + inverse: bool, }, } impl HitHandler { @@ -48,191 +71,320 @@ impl HitHandler { rng: &mut Rng, ) -> Result<(), String> { match self { - Self::None => {} - Self::Leizi { unblocked_scale } => { - if w.unit(q.hit.target)?.blocked_by().is_none() { - q.damage.amount *= unblocked_scale; - } - } - Self::Prove { - drop, - up, - prob, - front_prob, - crit_scale, + Self::Blocked { + scale, + own, + inverse, } => { - if drop > 0. && up > 0. { - let u = w.unit_mut(q.hit.target)?; - let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); - let ratio = if max > 0. { u.stats.hp / max } else { 0. }; - let lost = (1. - ratio).min(1.).max(0.); - if lost > 0. { - q.damage.amount *= 1. + (lost / drop) * up; - } - } - if q.is_splash || q.tags.iter().any(|t| t == "chain") { - return Ok(()); - } - let home = w.unit(source)?.deployment.tile; - let v = dir.vector(); - let front = [home[0] + v[0], home[1] + v[1]]; - let in_front = Grid::in_bounds(front) - && body::in_range( - w.unit(q.hit.target)?, - &[front[0] as usize * COLS + front[1] as usize], - ); - let p = if in_front { front_prob } else { prob }; - if p > 0. && rng.chance(p) { - q.damage.amount *= crit_scale; + let blocker = w.unit(q.hit.target)?.blocked_by(); + let blocked = if own { + blocker == Some(source) + } else { + blocker.is_some() + }; + if blocked != inverse { + q.damage.amount *= scale; } + Ok(()) } + Self::None => Ok(()), + Self::Leizi(h) => h.apply(w, q), + Self::Vigna(h) => h.apply(w, q), + Self::Prove(h) => h.apply(w, source, dir, q, rng), } - Ok(()) } } +#[derive(Default)] pub(crate) struct Spec { + pub extra: Extra, + pub while_blocked: Option, + pub ground_bonus: Option, + pub aura: Option, + pub element_attach: Option, + pub undying: bool, + pub end_stun: f64, + pub skill_flags: std::collections::BTreeSet, + pub death_heal: Option, + pub incoming_hit: Option, + pub attack_proc: Option, + pub dp_on_kill: f64, + pub initial_dp: f64, + pub trigger_range: Option>, + pub rule_override: Option, + pub skill_start: Option, + pub grid_scale: Option, pub modifiers: Numbers, pub permanent: Option, pub combat: Combat, pub hit: HitHandler, + pub attack_filter: Option, } +fn talent(raw: &Value) -> &Value { + raw["talents"] + .as_array() + .into_iter() + .flatten() + .find(|t| t["index"] != -1) + .map(|t| &t["bb"]) + .unwrap_or(&Value::Null) +} +use crate::battle::runtime::kits::{ + archet, blemsh, demkni, lumen, mlynar, papyrs, pasngr, pepe, philae, qiubai, rmixer, snhunt, + sntlla, texas2, tinman, +}; +mod tactics; +pub(crate) use tactics::*; +mod advanced; +pub(crate) use advanced::*; +mod aglina; +mod akkord; +mod angel; +mod aroma; +mod ayer; +mod billro; +mod bldsk; +mod bpipe; +mod branch; +mod bubble; +mod cathy; +mod f12yin; +mod fartth; +mod flamtl; +mod flower; +mod forcer; +mod glady; +mod gnosis; +mod grabds; +mod gvial2; +mod haini; +mod harold; +mod hsguma; +mod humus; +mod inside; +mod kroos2; +mod lionhd; +mod lisa; +pub(crate) mod mechanics; +mod mint; +mod mizuki; +mod mostma; +mod mudrok; +mod plosis; +mod podego; +mod reckpr; +mod slbell; +mod sunbr; +mod support; +mod surtr; +mod svrash; +mod vendla; +pub(crate) use support::*; +mod pinecn; +mod shotst; +mod skadi; +mod slchan; +mod wildmn; +pub(crate) use mechanics::*; +mod ashlok; +mod effects; +mod estell; +mod excu; +mod extras; +mod ghost; +mod gravel; +mod greyy; +mod leizi; +mod liskam; +mod pithst; +mod prove; +mod skgoat; +mod snakek; +mod swire; +mod texas; +mod udflow; +mod utage; +mod vigna; +mod whitew; +mod yak; +use crate::battle::runtime::kits::angel2; +use crate::battle::runtime::kits::dusk; +use crate::battle::runtime::kits::etlchi; +use crate::battle::runtime::kits::kazema; +use crate::battle::runtime::kits::lemuen; +use crate::battle::runtime::kits::mlyss; +use crate::battle::runtime::kits::nearl2; +use crate::battle::runtime::kits::sbell2; +use crate::battle::runtime::kits::siege2; +use crate::battle::runtime::kits::skadi2; +use crate::battle::runtime::kits::svash2; +use crate::battle::runtime::kits::swire2; +use crate::battle::runtime::kits::thorn2; +use crate::battle::runtime::kits::ulpia; +use crate::battle::runtime::kits::vigil; +use crate::battle::runtime::kits::whitw2; +use crate::battle::runtime::kits::yu; +use crate::battle::runtime::kits::{ + agoat2, blaze2, blkkgt, caper, cello, cetsyr, excu2, ghost2, halo2, horn, indigo, ines, kjera, + malist, nymph, rockr, silent, tippi, titi, vulpis, +}; +use crate::battle::runtime::kits::{reed2, rosmon}; +pub(crate) use effects::{ + passive_garrisons, AreaCast, AttackProc, Aura, DeathHeal, ElementAttach, GridScale, + GroundBonus, PhysicalResistance, SkillStart, WhileBlocked, +}; +pub(crate) use extras::*; impl Kit { - pub fn resolve(key: &str) -> Result { + pub fn healing(&self) -> bool { + self.profession == "MEDIC" && self.branch != "incantationmedic" + } + + pub fn resolve(key: &str) -> Result<&'static Self, String> { Ok(match key { - "chess_char_1_02_a" | "chess_char_1_02_b" => Self::Yak, - "chess_char_1_03_a" | "chess_char_1_03_b" => Self::Leizi, - "chess_char_1_11_a" | "chess_char_1_11_b" => Self::Skgoat, - "chess_char_1_14_a" | "chess_char_1_14_b" => Self::Greyy, - "chess_char_1_07_a" | "chess_char_1_07_b" => Self::Prove, + "chess_char_1_02_a" | "chess_char_1_02_b" => &yak::KIT, + "chess_char_1_03_a" | "chess_char_1_03_b" => &leizi::KIT, + "chess_char_1_11_a" | "chess_char_1_11_b" => &skgoat::KIT, + "chess_char_1_14_a" | "chess_char_1_14_b" => &greyy::KIT, + "chess_char_1_07_a" | "chess_char_1_07_b" => &prove::KIT, + "chess_char_1_12_a" | "chess_char_1_12_b" => &estell::KIT, + "chess_char_1_05_a" | "chess_char_1_05_b" => &vigna::KIT, + "chess_char_1_08_a" | "chess_char_1_08_b" => &texas::KIT, + "chess_char_2_01_a" | "chess_char_2_01_b" => &excu::KIT, + "chess_char_3_16_a" | "chess_char_3_16_b" => &snakek::KIT, + "chess_char_2_07_a" | "chess_char_2_07_b" => &ghost::KIT, + "chess_char_2_18_a" | "chess_char_2_18_b" => &ashlok::KIT, + "chess_char_3_03_a" | "chess_char_3_03_b" => &swire::KIT, + "chess_char_1_15_a" | "chess_char_1_15_b" => &pithst::KIT, + "chess_char_1_18_a" | "chess_char_1_18_b" => &utage::KIT, + "chess_char_2_12_a" | "chess_char_2_12_b" => &gravel::KIT, + "chess_char_2_16_a" | "chess_char_2_16_b" => &whitew::KIT, + "chess_char_1_20_a" | "chess_char_1_20_b" => &liskam::KIT, + "chess_char_1_04_a" | "chess_char_1_04_b" => &udflow::KIT, + "chess_char_1_01_a" | "chess_char_1_01_b" => &inside::KIT, + "chess_char_1_19_a" | "chess_char_1_19_b" => &wildmn::KIT, + "chess_char_2_03_a" | "chess_char_2_03_b" => &slchan::KIT, + "chess_char_2_08_a" | "chess_char_2_08_b" => &bubble::KIT, + "chess_char_2_15_a" | "chess_char_2_15_b" => &akkord::KIT, + "chess_char_2_17_a" | "chess_char_2_17_b" => &branch::KIT, + "chess_char_3_01_a" | "chess_char_3_01_b" => &angel::KIT, + "chess_char_3_02_a" | "chess_char_3_02_b" => &ayer::KIT, + "chess_char_3_05_a" | "chess_char_3_05_b" => &skadi::KIT, + "chess_char_3_10_a" | "chess_char_3_10_b" => &pinecn::KIT, + "chess_char_3_17_a" | "chess_char_3_17_b" => &shotst::KIT, + "chess_char_4_06_a" | "chess_char_4_06_b" => &kroos2::KIT, + "chess_char_4_07_a" | "chess_char_4_07_b" => &bpipe::KIT, + "chess_char_4_14_a" | "chess_char_4_14_b" => &lionhd::KIT, + "chess_char_4_17_a" | "chess_char_4_17_b" => &hsguma::KIT, + "chess_char_1_06_a" | "chess_char_1_06_b" => &vendla::KIT, + "chess_char_1_10_a" | "chess_char_1_10_b" => &sunbr::KIT, + "chess_char_1_13_a" | "chess_char_1_13_b" => &podego::KIT, + "chess_char_2_04_a" | "chess_char_2_04_b" => &grabds::KIT, + "chess_char_2_09_a" | "chess_char_2_09_b" => &humus::KIT, + "chess_char_2_14_a" | "chess_char_2_14_b" => &flower::KIT, + "chess_char_3_07_a" | "chess_char_3_07_b" => &forcer::KIT, + "chess_char_3_08_a" | "chess_char_3_08_b" => &mint::KIT, + "chess_char_3_09_a" | "chess_char_3_09_b" => &haini::KIT, + "chess_char_3_14_a" | "chess_char_3_14_b" => &slbell::KIT, + "chess_char_4_11_a" | "chess_char_4_11_b" => &cathy::KIT, + "chess_char_4_21_a" | "chess_char_4_21_b" => &plosis::KIT, + "chess_char_4_22_a" | "chess_char_4_22_b" => &svrash::KIT, + "chess_char_4_23_a" | "chess_char_4_23_b" => &gvial2::KIT, + "chess_char_4_26_a" | "chess_char_4_26_b" => &bldsk::KIT, + "chess_char_2_05_a" | "chess_char_2_05_b" => &harold::KIT, + "chess_char_4_02_a" | "chess_char_4_02_b" => &mostma::KIT, + "chess_char_4_09_a" | "chess_char_4_09_b" => &mizuki::KIT, + "chess_char_4_10_a" | "chess_char_4_10_b" => &aroma::KIT, + "chess_char_4_24_a" | "chess_char_4_24_b" => &billro::KIT, + "chess_char_4_18_a" | "chess_char_4_18_b" => &mudrok::KIT, + "chess_char_4_19_a" | "chess_char_4_19_b" => &flamtl::KIT, + "chess_char_4_20_a" | "chess_char_4_20_b" => &fartth::KIT, + "chess_char_5_10_a" | "chess_char_5_10_b" => &lisa::KIT, + "chess_char_5_17_a" | "chess_char_5_17_b" => &f12yin::KIT, + "chess_char_5_07_a" | "chess_char_5_07_b" => &surtr::KIT, + "chess_char_5_20_a" | "chess_char_5_20_b" => &aglina::KIT, + "chess_char_5_23_a" | "chess_char_5_23_b" => &reckpr::KIT, + "chess_char_4_12_a" | "chess_char_4_12_b" => &glady::KIT, + "chess_char_4_13_a" | "chess_char_4_13_b" => &gnosis::KIT, + "chess_char_2_06_a" | "chess_char_2_06_b" => &papyrs::KIT, + "chess_char_2_19_a" | "chess_char_2_19_b" => &tinman::KIT, + "chess_char_3_06_a" | "chess_char_3_06_b" => &philae::KIT, + "chess_char_3_11_a" | "chess_char_3_11_b" => &snhunt::KIT, + "chess_char_3_12_a" | "chess_char_3_12_b" => &blemsh::KIT, + "chess_char_3_21_a" | "chess_char_3_21_b" => &archet::KIT, + "chess_char_4_01_a" | "chess_char_4_01_b" => &rmixer::KIT, + "chess_char_4_16_a" | "chess_char_4_16_b" => &texas2::KIT, + "chess_char_5_11_a" | "chess_char_5_11_b" => &demkni::KIT, + "chess_char_5_19_a" | "chess_char_5_19_b" => &mlynar::KIT, + "chess_char_5_21_a" | "chess_char_5_21_b" => &sntlla::KIT, + "chess_char_6_05_a" | "chess_char_6_05_b" => &pasngr::KIT, + "chess_char_6_15_a" | "chess_char_6_15_b" => &qiubai::KIT, + "chess_char_6_06_a" | "chess_char_6_06_b" => &pepe::KIT, + "chess_char_6_14_a" | "chess_char_6_14_b" => &lumen::KIT, + "chess_char_1_09_a" | "chess_char_1_09_b" => &caper::KIT, + "chess_char_1_17_a" | "chess_char_1_17_b" => &indigo::KIT, + "chess_char_2_02_a" | "chess_char_2_02_b" => &silent::KIT, + "chess_char_2_10_a" | "chess_char_2_10_b" => &rockr::KIT, + "chess_char_2_13_a" | "chess_char_2_13_b" => &tippi::KIT, + "chess_char_3_13_a" | "chess_char_3_13_b" => &malist::KIT, + "chess_char_3_18_a" | "chess_char_3_18_b" => &vulpis::KIT, + "chess_char_3_20_a" | "chess_char_3_20_b" => &kjera::KIT, + "chess_char_4_04_a" | "chess_char_4_04_b" => &ines::KIT, + "chess_char_4_25_a" | "chess_char_4_25_b" => &cetsyr::KIT, + "chess_char_5_01_a" | "chess_char_5_01_b" => &excu2::KIT, + "chess_char_5_02_a" | "chess_char_5_02_b" => &titi::KIT, + "chess_char_5_03_a" | "chess_char_5_03_b" => &blaze2::KIT, + "chess_char_5_08_a" | "chess_char_5_08_b" => &horn::KIT, + "chess_char_5_13_a" | "chess_char_5_13_b" => &ghost2::KIT, + "chess_char_5_22_a" | "chess_char_5_22_b" => &nymph::KIT, + "chess_char_6_09_a" | "chess_char_6_09_b" => &cello::KIT, + "chess_char_6_16_a" | "chess_char_6_16_b" => &halo2::KIT, + "chess_char_6_19_a" | "chess_char_6_19_b" => &blkkgt::KIT, + "chess_char_6_20_a" | "chess_char_6_20_b" => &agoat2::KIT, + "chess_char_6_08_a" | "chess_char_6_08_b" => &reed2::KIT, + "chess_char_6_12_a" | "chess_char_6_12_b" => &rosmon::KIT, + "chess_char_6_02_a" | "chess_char_6_02_b" => &sbell2::KIT, + "chess_char_6_04_a" | "chess_char_6_04_b" => &skadi2::KIT, + "chess_char_5_14_a" | "chess_char_5_14_b" => &svash2::KIT, + "chess_char_6_13_a" | "chess_char_6_13_b" => &angel2::KIT, + "chess_char_5_15_a" | "chess_char_5_15_b" => þ2::KIT, + "chess_char_6_03_a" | "chess_char_6_03_b" => &yu::KIT, + "chess_char_5_12_a" | "chess_char_5_12_b" => &dusk::KIT, + "chess_char_2_11_a" | "chess_char_2_11_b" => &kazema::KIT, + "chess_char_6_01_a" | "chess_char_6_01_b" => &lemuen::KIT, + "chess_char_6_17_a" | "chess_char_6_17_b" => &nearl2::KIT, + "chess_char_6_07_a" | "chess_char_6_07_b" => &siege2::KIT, + "chess_char_5_05_a" | "chess_char_5_05_b" => &ulpia::KIT, + "chess_char_3_04_a" | "chess_char_3_04_b" => &swire2::KIT, + "chess_char_6_18_a" | "chess_char_6_18_b" => &whitw2::KIT, + "chess_char_5_06_a" | "chess_char_5_06_b" => &etlchi::KIT, + "chess_char_3_19_a" | "chess_char_3_19_b" => &vigil::KIT, + "chess_char_6_11_a" | "chess_char_6_11_b" => &mlyss::KIT, _ => return Err(format!("Operator kit not implemented: {key}")), }) } - pub fn identity(self) -> (&'static str, &'static str, &'static str) { - match self { - Self::Yak => ("skchr_yak_2", "TANK", "protector"), - Self::Leizi => ("skchr_leizi_2", "CASTER", "chain"), - Self::Skgoat => ("skcom_atk_up[2]", "SUPPORT", "slower"), - Self::Greyy => ("skchr_greyy_2", "CASTER", "splashcaster"), - Self::Prove => ("skchr_prove_1", "SNIPER", "closerange"), - } - } - pub fn attack_override(self) -> bool { - matches!(self, Self::Leizi | Self::Greyy) - } - pub fn ranged(self) -> bool { - self != Self::Yak - } - pub fn passive(self) -> bool { - self == Self::Prove - } - pub fn physical(self) -> bool { - matches!(self, Self::Yak | Self::Prove) - } - pub fn projectile(self) -> &'static str { - if self == Self::Prove { - "arrow" - } else if self.ranged() { - "bolt" + pub fn build(&self, raw: &Value) -> Result { + let mut s = Spec::default(); + // Damage type is independent of ranged/projectile delivery. + s.combat.damage = if self.physical { + crate::battle::damage::DamageType::Physical } else { - "none" - } - } - pub fn build(self, raw: &Value) -> Spec { - let bb = &raw["skill"]["bb"]; - let t = raw["talents"] - .as_array() - .into_iter() - .flatten() - .find(|t| t["index"] != -1) - .map(|t| &t["bb"]) - .unwrap_or(&Value::Null); - let tb = &raw["trait"]["bb"]; - let mut combat = Combat::default(); - if self.ranged() { - combat.profile.selection.can_hit_fly = true; - combat.damage = if self.physical() { - crate::battle::damage::DamageType::Physical - } else { - crate::battle::damage::DamageType::Arts - }; - combat.projectile = Some(self.projectile()); - combat.projectile_speed = if self == Self::Prove { 14. } else { 11. }; - combat.area.selection = combat.profile.selection; - } - let mut permanent = None; - let mut hit = HitHandler::None; - let modifiers = match self { - Self::Yak => { - let mut buff = Buff { - key: Some("talent:yak".into()), - mods: [("resFlat".into(), number(&t["magic_resistance"], 0.))].into(), - ..Default::default() - }; - buff.runtime.persist = true; - permanent = Some(buff); - [ - ("hpPct".into(), number(&bb["max_hp"], 0.)), - ("defPct".into(), number(&bb["def"], 0.)), - ("resMul".into(), 1. + number(&bb["magic_resistance"], 0.)), - ] - .into() - } - Self::Leizi => { - combat.area.chain = Some(Chain { - count: number(&tb["attack@max_target"], 3.), - radius: 1.7, - falloff: if tb["attack@chain.atk_scale"].is_null() { - 0.15 - } else { - 1. - number(&tb["attack@chain.atk_scale"], 0.85) - }, - sluggish: number(&tb["attack@sluggish"], 0.5), - }); - hit = HitHandler::Leizi { - unblocked_scale: number(&t["atk_scale"], 1.), - }; - [("atkPct".into(), number(&bb["atk"], 0.))].into() - } - Self::Skgoat => { - combat.sluggish = number(&tb["sluggish"], 0.8) + number(&t["sluggish"], 0.); - [("atkPct".into(), number(&bb["atk"], 0.))].into() - } - Self::Greyy => { - // Original Greyy's radius is 1.0 rather than the branch's 1.1. - combat.area.splash = Some(Splash { - radius: 1., - scale: 1., - hits_fly: false, - fortress_melee: false, - }); - combat.sluggish = number(&t["sluggish"], 0.); - [("aspd".into(), number(&bb["attack_speed"], 0.))].into() - } - Self::Prove => { - hit = HitHandler::Prove { - drop: number(&bb["hp_ratio_drop"], 0.), - up: number(&bb["atk_scale_up"], 0.), - prob: number(&t["prob"], 0.), - front_prob: number(&t["prob2"], 0.), - crit_scale: number(&t["atk_scale"], 1.), - }; - Numbers::new() - } + crate::battle::damage::DamageType::Arts }; - combat.skill_area = combat.area; - if self == Self::Leizi { - combat.skill_area.chain.as_mut().unwrap().falloff = 0.; + if self.ranged { + s.combat.profile.selection.can_hit_fly = self.can_hit_fly; + s.combat.projectile = Some(self.projectile); + s.combat.projectile_speed = self.projectile_speed; + s.combat.area.selection = s.combat.profile.selection; + s.combat.skill_area = s.combat.area; } - combat.skill_sluggish = if self == Self::Greyy { - combat.sluggish * number(&bb["talent_scale"], 1.) - } else { - combat.sluggish - }; - Spec { - modifiers, - permanent, - combat, - hit, + if self.healing() { + support::healing(&mut s, if self.branch == "ringhealer" { 3. } else { 1. }); + } + (self.build)(raw, raw["skill"]["skillId"] == self.skills[0].id, &mut s)?; + if let Some(observer) = &s.extra.effects.observer { + let mut b = persistent(observer.key, Numbers::new()); + b.runtime.injury.observe = Some(INJURY_OBSERVER); + s.extra.effects.permanent.push(b); } + Ok(s) } } diff --git a/crates/engine/src/battle/content/operators/advanced.rs b/crates/engine/src/battle/content/operators/advanced.rs new file mode 100644 index 0000000..7ddd9d7 --- /dev/null +++ b/crates/engine/src/battle/content/operators/advanced.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Parameters for the next set of independent operator Kits. +use super::*; +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Mode { + First, + Second, + Third, +} +#[derive(Default)] +pub(crate) enum Advanced { + #[default] + None, + Harold(Harold), + Mostma(Mostma), + Mizuki(Mizuki), + Aroma(Aroma), + Billro(Billro), + Mudrok(Mudrok), + Flamtl(Flamtl), + Fartth(Fartth), + Lisa(Lisa), + Mountain(Mountain), + Surtr(Surtr), + Aglina(Aglina), + Reckpr(Reckpr), + Glady(Glady), + Gnosis(Gnosis), +} +pub(crate) struct Harold { + pub severe: bool, + pub element_ratio: f64, + pub extra_scale: f64, + pub resistance: f64, +} +pub(crate) struct Mostma { + pub lock: bool, + pub ripple: bool, + pub slow: f64, + pub slow_scale: f64, + pub force: f64, + pub lock_scale: f64, +} +pub(crate) struct Mizuki { + pub mode: Mode, + pub scale: f64, + pub count: usize, + pub extra: usize, + pub skill_scale: f64, + pub status: f64, + pub loss: f64, + pub threshold: f64, + pub attack: f64, + pub slow: f64, +} +pub(crate) struct Aroma { + pub landing: bool, + pub first_scale: f64, + pub levitate: f64, + pub land_scale: f64, + pub fly_scale: f64, +} +pub(crate) struct Billro { + pub mode: Mode, + pub heal: f64, + pub charged_heal: f64, + pub recovery: f64, + pub charged_atk: f64, + pub ramp_atk: f64, + pub mark: f64, + pub guard: Numbers, + pub keep: Numbers, + pub sluggish: f64, + pub bind: f64, + pub per_enemy: f64, + pub enemy_cap: f64, +} +pub(crate) struct Mudrok { + pub mode: Mode, + pub grid: Vec<[i32; 2]>, + pub sleep: f64, + pub slow: f64, + pub stun: f64, + pub awake: Numbers, + pub layer_period: f64, + pub layer_add: u32, + pub layer_cap: u32, + pub layer_heal: f64, + pub layer_sp: f64, + pub sarkaz_resistance: f64, + pub module: Numbers, +} +pub(crate) struct Flamtl { + pub mode: Mode, + pub total: u32, + pub cost: f64, + pub ally_dodge: f64, + pub ally_duration: f64, + pub faction_dodge: f64, + pub grid: Vec<[i32; 2]>, + pub module: Numbers, +} +pub(crate) struct Fartth { + pub mode: Mode, + pub focus: f64, + pub delay: f64, + pub far_scale: f64, + pub module_sp: f64, + pub base_grid: Vec<[i32; 2]>, +} +pub(crate) struct Lisa { + pub fox: bool, + pub fragile: f64, + pub boost: f64, + pub regen: f64, + pub module_sp: f64, +} +pub(crate) struct Mountain { + pub mode: Mode, + pub probability: f64, + pub active_probability: f64, + pub scale: f64, + pub weaken: f64, + pub duration: f64, + pub module_aspd: f64, +} +pub(crate) struct Surtr { + pub mode: Mode, + pub withdraw: f64, + pub drain_interval: f64, + pub drain_peak: f64, + pub drain_ramp: f64, + pub solo: f64, + pub module_aspd: f64, + pub module_fragile: f64, +} +pub(crate) struct Aglina { + pub weightless: bool, + pub aspd: f64, + pub regen: f64, + pub module_sp: f64, +} +pub(crate) struct Reckpr { + pub guard: bool, + pub duration: f64, + pub heal: f64, + pub probability: f64, + pub sp: f64, + pub aspd: f64, + pub learn_duration: f64, +} +pub(crate) struct Glady { + pub mode: Mode, + pub force: f64, + pub interval: f64, + pub scale: f64, + pub slow: f64, + pub regen: f64, + pub resistance: f64, + pub max_weight: f64, + pub light_scale: f64, + pub drag: f64, + pub drag_distance: f64, + pub far_radius: f64, + pub far_force: f64, +} +pub(crate) struct Gnosis { + pub mode: Mode, + pub cold: f64, + pub burst_cold: f64, + pub burst_scale: f64, + pub fragile_cold: f64, + pub fragile_frozen: f64, + pub module_sp: f64, + pub resist_delay: f64, + pub resist: f64, +} +#[derive(Default)] +pub(crate) struct AdvancedState { + pub elapsed: f64, + pub skill_left: f64, + pub accumulator: f64, + pub aura_accumulator: f64, + pub next_fast: f64, + pub next_aura: f64, + pub charged: bool, + pub floating: std::collections::BTreeSet, + pub locked: std::collections::BTreeSet, + pub tornado: Option<[f64; 2]>, + pub layers: u32, + pub next_layer: f64, + pub riposte: bool, + pub riposte_now: bool, + pub critical: bool, + pub solo: bool, + pub last_hurt: f64, + pub ember: bool, + pub dp_given: u32, + pub extra_range: Vec, + pub harold_half: std::collections::BTreeSet, +} diff --git a/crates/engine/src/battle/content/operators/aglina.rs b/crates/engine/src/battle/content/operators/aglina.rs new file mode 100644 index 0000000..5e6c670 --- /dev/null +++ b/crates/engine/src/battle/content/operators/aglina.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "slower", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_aglina_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_aglina_1", + kind: Kind::Duration, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_aglina_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SEARCH", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_aglina_1" => Mode::First, + "skchr_aglina_2" => Mode::Second, + "skchr_aglina_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.extra.normal_status = Some(OnHitStatus { + key: "sluggish", + duration: number(&tb["sluggish"], 0.8), + chance: None, + }); + skill_range(raw, s)?; + s.combat.profile.only_while_skill = mode != Mode::First; + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + if mode == Mode::Second { + let bat = number(&bb["base_attack_time"], 1.); + s.modifiers.insert( + "batPct".into(), + if bat > 0. && bat < 1. { + bat - 1. + } else { + flat_bat(raw, bat) + }, + ); + s.combat.skill_scale = number(&bb["damage_scale"], 1.); + } + if default { + let mut p = s.combat.profile; + p.max_targets = number(&bb["attack@max_target"], 1.); + s.combat.skill_profile = Some(p); + } + s.extra.advanced = Advanced::Aglina(Aglina { + weightless: default, + aspd: number(&t["attack_speed"], 0.), + regen: number(&t1["hp_recovery_per_sec"], 0.), + module_sp: number(&tm["sp_recovery_per_sec"], 0.), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/akkord.rs b/crates/engine/src/battle/content/operators/akkord.rs new file mode 100644 index 0000000..30a61a5 --- /dev/null +++ b/crates/engine/src/battle/content/operators/akkord.rs @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "blastcaster", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_akkord_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_akkord_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + let tb = &raw["trait"]["bb"]; + s.combat.profile.range_aoe = true; + s.combat.profile.all_in_range = true; + s.combat.projectile = None; + s.extra.effects.condition = Some(Conditional { + key: "akkord:sync", + when: Predicate::AllyInRange, + mods: [("atkPct".into(), number(&t["atk"], 0.))].into(), + }); + s.extra.effects.distance = Some(DistanceScale { + minimum: number(&tb["min_dist"], 0.), + maximum: number(&tb["max_dist"], 4.), + attack_scale: number(&tb["damage_scale"], 0.), + damage_scale: 0., + }); + if default { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + s.extra.effects.secondary = Some(Secondary::Sonic { + radius: number(&bb["attack@range_radius"], 0.9), + scale: number(&bb["attack@aoe_atk_scale"], 0.), + }); + } else { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/angel.rs b/crates/engine/src/battle/content/operators/angel.rs new file mode 100644 index 0000000..7d2db22 --- /dev/null +++ b/crates/engine/src/battle/content/operators/angel.rs @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "fastshot", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_angel_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_angel_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_angel_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + fastshot(raw, s); + let t0 = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + s.extra.effects.permanent.push(persistent( + "talent:angel_mag", + [("aspd".into(), number(&t0["attack_speed"], 0.))].into(), + )); + let bless: Numbers = [ + ("atkPct".into(), number(&t1["atk"], 0.)), + ("hpPct".into(), number(&t1["max_hp"], 0.)), + ] + .into(); + s.extra + .effects + .permanent + .push(persistent("talent:angel_bless", bless.clone())); + s.extra.effects.random_bless = Some(bless); + let id = raw["skill"]["skillId"].as_str().unwrap_or(""); + s.combat.skill_scale = number( + &bb[if id == "skchr_angel_1" { + "atk_scale" + } else { + "attack@atk_scale" + }], + 1., + ); + s.combat.skill_hits = number( + &bb[if id == "skchr_angel_1" { + "times" + } else { + "attack@times" + }], + 1., + ) + .floor() + .max(1.) as u32; + if default { + s.modifiers = [("batPct".into(), number(&bb["base_attack_time"], 0.))].into(); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/aroma.rs b/crates/engine/src/battle/content/operators/aroma.rs new file mode 100644 index 0000000..665fec0 --- /dev/null +++ b/crates/engine/src/battle/content/operators/aroma.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "blastcaster", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_aroma_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_aroma_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let _t1 = talent_at(raw, 1); + let _tm = talent_at(raw, -1); + let _mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_aroma_1" => Mode::First, + "skchr_aroma_2" => Mode::Second, + _ => return Err("Unknown selected skill".into()), + }; + s.combat.profile.range_aoe = true; + s.combat.profile.all_in_range = true; + s.combat.projectile = None; + if default { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + } else { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + } + if number(&tb["damage_scale"], 0.) > 0. { + s.extra.effects.distance = Some(DistanceScale { + minimum: number(&tb["min_dist"], 0.), + maximum: number(&tb["max_dist"], 4.), + attack_scale: 0., + damage_scale: number(&tb["damage_scale"], 0.), + }); + } + s.extra.advanced = Advanced::Aroma(Aroma { + landing: default, + first_scale: number(&t["damage_scale"], 1.1), + levitate: number(&t["levitate_duration"], 2.5), + land_scale: number(&bb["attack@atk_scale_when_fly_finish"], 0.65), + fly_scale: number(&bb["atk_scale_to_fly"], 0.55), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/ashlok.rs b/crates/engine/src/battle/content/operators/ashlok.rs new file mode 100644 index 0000000..dbd751b --- /dev/null +++ b/crates/engine/src/battle/content/operators/ashlok.rs @@ -0,0 +1,64 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Ashlock: fortress melee/bomb profiles and deployment terrain talent. +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "fortress", + can_hit_fly: false, + ranged: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[ + Skill::duration("skcom_atk_up[3]"), + Skill { + attack_override: true, + ..Skill::duration("skchr_ashlok_2") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.combat.profile.fortress = true; + s.combat.profile.selection.can_hit_fly = false; + s.combat.profile.selection.ground_only = true; + s.combat.area.selection = s.combat.profile.selection; + s.combat.area.splash = Some(Splash { + radius: 1., + scale: 1., + hits_fly: false, + fortress_melee: true, + }); + s.combat.area.fortress_melee = true; + s.combat.skill_area = s.combat.area; + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + if !default { + let bat = number(&raw["stats"]["bat"], 1.); + s.modifiers.insert( + "batPct".into(), + (number(&bb["base_attack_time"], 0.) / if bat == 0. { 1. } else { bat }).max(-0.9), + ); + s.skill_flags.insert("noBlock".into()); + let mut p = s.combat.profile; + p.fortress = false; + s.combat.skill_profile = Some(p); + s.combat.skill_area.fortress_melee = false; + s.combat.skill_area.splash.as_mut().unwrap().fortress_melee = false; + } + s.ground_bonus = Some(GroundBonus { + key: "talent:ashlok", + count: number(&t["cnt"], 4.), + normal: number(&t["atk"], 0.), + surrounded: number(&t["ashlok_t_1.atk"], number(&t["atk"], 0.)), + }); + s.hit = HitHandler::Blocked { + scale: number(&raw["trait"]["bb"]["atk_scale"], 1.), + own: false, + inverse: false, + }; + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/ayer.rs b/crates/engine/src/battle/content/operators/ayer.rs new file mode 100644 index 0000000..6b88f23 --- /dev/null +++ b/crates/engine/src/battle/content/operators/ayer.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "lord", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_ayer_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_ayer_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + s.extra.lord = Some(Lord { + scale: number(&tb["atk_scale"], 0.8), + arts: number(&tb["atk_scale_m"], 0.), + skill_full: false, + }); + s.extra.effects.lord_skill_scale = number(&bb["atk_scale"], 1.); + let grid = raw["talents"] + .as_array() + .into_iter() + .flatten() + .find(|t| t["index"] == 0) + .map(|t| &t["rangeGrid"]) + .unwrap_or(&Value::Null); + s.extra.effects.aura = Some(StatAura { + key: "talent:ayer_aspd", + grid: Some(if grid.is_null() { + (-1..=1) + .flat_map(|r| (-1..=1).map(move |c| [r, c])) + .collect() + } else { + crate::battle::operators::parse_range(grid)? + }), + profession: None, + mods: [("aspd".into(), number(&talent(raw)["attack_speed"], 0.))].into(), + }); + s.combat.skill_damage = Some(crate::battle::damage::DamageType::Arts); + if default { + skill_range(raw, s)?; + s.combat.skill_scale = number(&bb["attack@atk_scale"], 1.); + s.extra.effects.secondary = Some(Secondary::NearbyBlocked { + scale: number(&bb["atk_scale"], 1.), + }); + } else { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + let mut p = s.combat.profile; + p.max_targets = number(&bb["max_target"], 1.).floor().max(1.); + s.combat.skill_profile = Some(p); + s.extra.skill_status = Some(OnHitStatus { + key: "sluggish", + duration: number(&bb["sluggish"], 0.), + chance: None, + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/billro.rs b/crates/engine/src/battle/content/operators/billro.rs new file mode 100644 index 0000000..02cda07 --- /dev/null +++ b/crates/engine/src/battle/content/operators/billro.rs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "phalanx", + ranged: true, + can_hit_fly: false, + physical: false, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_billro_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SEARCH", + attack_override: false, + }, + Skill { + id: "skchr_billro_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SEARCH", + attack_override: false, + }, + Skill { + id: "skchr_billro_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_billro_1" => Mode::First, + "skchr_billro_2" => Mode::Second, + "skchr_billro_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.combat.profile.only_while_skill = true; + s.combat.profile.all_in_range = true; + s.combat.profile.range_aoe = true; + s.combat.profile.selection.can_hit_fly = true; + s.combat.projectile = None; + skill_range(raw, s)?; + if mode == Mode::First { + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("defPct".into(), number(&bb["def"], 0.)), + ] + .into(); + } + if mode == Mode::Second { + s.modifiers = [( + "batPct".into(), + flat_bat(raw, number(&bb["base_attack_time"], 0.)).max(-0.9), + )] + .into(); + } + let mut guard = Buff { + key: Some("trait:phalanxGuard".into()), + mods: [ + ("defPct".into(), number(&tb["def"], 2.)), + ("resFlat".into(), number(&tb["magic_resistance"], 20.)), + ] + .into(), + ..Default::default() + }; + guard.runtime.source = None; + s.extra.effects.deploy_buff = Some(guard); + s.extra.advanced = Advanced::Billro(Billro { + mode, + heal: number(&t["heal_scale"], 0.4), + charged_heal: number(&t["billro_t_1[enhance].heal_scale"], 0.8), + recovery: number(&t1["sp_recovery_per_sec"], 0.6), + charged_atk: number(&bb["atk"], 0.1), + ramp_atk: number(&bb["atk"], 0.), + mark: number(&bb["attack@damage_scale"], 0.2), + guard: [ + ("defPct".into(), number(&tb["def"], 2.)), + ("resFlat".into(), number(&tb["magic_resistance"], 20.)), + ] + .into(), + keep: [ + ("defPct".into(), number(&tb["billro_e_002[buff].def"], 0.)), + ( + "resFlat".into(), + number(&tb["billro_e_002[buff].magic_resistance"], 0.), + ), + ] + .into(), + sluggish: number(&bb["attack@sluggish"], 0.3), + bind: number(&bb["attack@root"], 0.3), + per_enemy: number(&tm["damage_scale"], 0.), + enemy_cap: number(&tm["max_valid_stack_cnt"], 5.), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/bldsk.rs b/crates/engine/src/battle/content/operators/bldsk.rs new file mode 100644 index 0000000..e401961 --- /dev/null +++ b/crates/engine/src/battle/content/operators/bldsk.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "physician", + ranged: true, + can_hit_fly: false, + physical: false, + projectile: "orb", + projectile_speed: 10., + required_range: None, + skills: &[ + Skill { + id: "skchr_bldsk_1", + kind: Kind::Charges, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_bldsk_2", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let tb = &raw["trait"]["bb"]; + healing(s, 1.); + s.extra.support.heal_bonus = Some(HealBonus { + below: number(&tb["hp_ratio"], 0.), + scale: number(&tb["heal_scale"], 1.), + inclusive: true, + }); + s.extra.support.death_sp = Some([ + number(&t["bldsk_t_1[self].sp"], 2.), + number(&t["bldsk_t_1[rand].sp"], 2.), + ]); + if default { + s.rule_override = Some(crate::battle::skills::Rule::Never); + s.extra.support.bandage = Some(number(&bb["hp_ratio"], 0.15)); + } else { + s.extra.support.plasma = Some(Plasma { + duration: number(&bb["duration"], 15.), + interval: number(&bb["interval"], 1.).max(0.1), + ratio: number(&bb["hp_ratio"], 0.03), + attack: number(&bb["atk"], 0.), + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/bpipe.rs b/crates/engine/src/battle/content/operators/bpipe.rs new file mode 100644 index 0000000..24a6e2a --- /dev/null +++ b/crates/engine/src/battle/content/operators/bpipe.rs @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "PIONEER", + branch: "charger", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_bpipe_2", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skcom_quickattack[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_bpipe_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t0 = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tb = &raw["trait"]["bb"]; + s.dp_on_kill = number(&tb["cost"], 1.); + s.extra.effects.attack_boost = Some(AttackBoost { + chance: number(&t0["prob"], 0.25), + scale: number(&t0["atk_scale"], 1.3), + }); + s.extra.effects.deploy_sp = number(&t1["sp"], 6.); + if !tb["hp_ratio"].is_null() { + s.hit = HitHandler::Vigna(super::vigna::Hit { + below: number(&tb["hp_ratio"], 0.), + scale: number(&tb["atk_scale"], 1.), + }); + } + if default { + s.combat.skill_scale = number(&bb["atk_scale"], 1.45); + s.combat.skill_hits = 2; + } else { + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("defPct".into(), number(&bb["def"], 0.)), + ("aspd".into(), number(&bb["attack_speed"], 0.)), + ("blockCnt".into(), number(&bb["block_cnt"], 0.)), + ( + "batPct".into(), + flat_bat(raw, number(&bb["base_attack_time"], 0.)), + ), + ] + .into(); + if raw["skill"]["skillId"] == "skchr_bpipe_3" { + s.combat.skill_hits = 3; + } + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/branch.rs b/crates/engine/src/battle/content/operators/branch.rs new file mode 100644 index 0000000..8678b42 --- /dev/null +++ b/crates/engine/src/battle/content/operators/branch.rs @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "unyield", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_branch_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: true, + }, + Skill { + id: "skchr_branch_1", + kind: Kind::Duration, + sp_type: SpType::Hurt, + rule: "TAKE_DAMAGE", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + s.extra.no_heal = true; + s.extra.effects.end_heal = number(&talent(raw)["hp_ratio"], 0.); + s.extra.effects.blocked_taken = number(&raw["trait"]["bb"]["damage_scale"], 1.); + s.modifiers = [("defPct".into(), number(&bb["def"], 0.))].into(); + if default { + s.modifiers.insert("atkPct".into(), number(&bb["atk"], 0.)); + let mut p = s.combat.profile; + p.hit_all_blocked = true; + s.combat.skill_profile = Some(p); + s.extra.effects.start_status = Some(( + crate::battle::operators::parse_range(&raw["skill"]["rangeGrid"])?, + OnHitStatus { + key: "tremble", + duration: number(&bb["not_combat"], 0.), + chance: None, + }, + )); + } else { + s.extra.effects.resist = (-number(&bb["one_minus_status_resistance"], 0.)).clamp(0., 0.95); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/bubble.rs b/crates/engine/src/battle/content/operators/bubble.rs new file mode 100644 index 0000000..af6c68a --- /dev/null +++ b/crates/engine/src/battle/content/operators/bubble.rs @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "protector", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_bubble_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: true, + }, + Skill { + id: "skcom_def_up[2]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.modifiers = [("defPct".into(), number(&bb["def"], 0.))].into(); + s.extra.effects.observer = Some(InjuryObserver { + key: "bubble:spikeObserver", + counter: None, + debuff: Some(Debuff { + key: "bubble:spike", + stat: "atkPct", + value: number(&t["atk"], 0.), + duration: number(&t["duration"], 5.), + strongest: false, + }), + }); + blocked_def(raw, s, "bubble:guard"); + if default { + s.modifiers + .insert("taunt".into(), number(&bb["taunt_level"], 0.)); + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + s.extra.effects.skill_counter = Some(Counter { + key: "bubble:counter", + stat: "def", + scale: number(&bb["atk_scale"], 0.), + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/cathy.rs b/crates/engine/src/battle/content/operators/cathy.rs new file mode 100644 index 0000000..cc5a18b --- /dev/null +++ b/crates/engine/src/battle/content/operators/cathy.rs @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "SUPPORT", + branch: "craftsman", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + id: "skchr_cathy_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_cathy_1", + kind: Kind::Passive, + sp_type: SpType::None, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + if default { + s.modifiers = [ + ("hpPct".into(), number(&bb["max_hp"], 0.)), + ("defPct".into(), number(&bb["def"], 0.)), + ] + .into(); + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + } else { + let mods: Numbers = [ + ("atkPct".into(), number(&bb["s1_atk"], 0.)), + ("defPct".into(), number(&bb["s1_def"], 0.)), + ] + .into(); + s.modifiers = mods.clone(); + s.extra.support.forge = Some(mods); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/effects.rs b/crates/engine/src/battle/content/operators/effects.rs new file mode 100644 index 0000000..d8b58f7 --- /dev/null +++ b/crates/engine/src/battle/content/operators/effects.rs @@ -0,0 +1,269 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Shared content components; all geometry and settlement use engine primitives. +use super::*; +pub(crate) struct DeathHeal { + pub ratio: f64, + pub grid: Option>, +} +impl DeathHeal { + pub fn amount( + &self, + w: &mut World, + source: Id, + victim: Id, + dir: Direction, + ) -> Result, String> { + let u = w.unit(source)?; + if !u.stats.alive || !u.deployed || u.removed { + return Ok(None); + } + let near = if let Some(grid) = &self.grid { + let keys = crate::battle::targeting::absolute_range(grid, u.deployment.tile, dir, 0); + body::in_range(w.unit(victim)?, &keys) + } else { + let e = w.unit(victim)?; + (u.position[0] - e.position[0]) + .abs() + .max((u.position[1] - e.position[1]).abs()) + <= 1. + }; + Ok(if near { + Some( + w.unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp") + * self.ratio, + ) + } else { + None + }) + } +} +#[derive(Clone, Copy)] +pub(crate) struct PhysicalResistance { + pub above_hp: f64, + pub fraction: f64, +} +impl PhysicalResistance { + pub fn apply(self, w: &mut World, q: &mut hit::Request) -> Result<(), String> { + if q.hit.damage_type != crate::battle::damage::DamageType::Physical { + return Ok(()); + } + let u = w.unit_mut(q.hit.target)?; + let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + let ratio = if max > 0. { u.stats.hp / max } else { 0. }; + if ratio > self.above_hp { + q.damage.mul *= 1. - self.fraction; + } + Ok(()) + } +} + +#[derive(Clone, Copy)] +pub(crate) struct AttackProc { + pub key: &'static str, + pub normal: f64, + pub active: f64, + pub atk: f64, +} +impl AttackProc { + pub fn roll(self, active: bool, rng: &mut Rng) -> Option { + let p = if active { self.active } else { self.normal }; + if p <= 0. || !rng.chance(p) { + return None; + } + let mut b = Buff { + key: Some(self.key.into()), + mods: [("atkPct".into(), self.atk)].into(), + ..Default::default() + }; + b.runtime.duration = 0.1; + Some(b) + } +} + +pub(crate) struct AreaCast { + pub grid: Vec<[i32; 2]>, + pub scale: f64, + pub hits: u32, + pub stun: f64, +} +pub(crate) struct SkillStart { + pub dp: f64, + pub area: Option, +} +pub(crate) struct GridScale { + pub grid: Vec<[i32; 2]>, + pub scale: f64, + pub skill_all: bool, +} +impl GridScale { + pub fn multiplier( + &self, + w: &World, + source: Id, + target: Id, + dir: Direction, + skill: bool, + ) -> Result { + let keys = crate::battle::targeting::absolute_range( + &self.grid, + w.unit(source)?.deployment.tile, + dir, + 0, + ); + Ok( + if skill && self.skill_all || body::in_range(w.unit(target)?, &keys) { + self.scale + } else { + 1. + }, + ) + } +} + +pub(crate) struct WhileBlocked { + pub key: &'static str, + pub mods: Numbers, +} +pub(crate) struct GroundBonus { + pub key: &'static str, + pub count: f64, + pub normal: f64, + pub surrounded: f64, +} +pub(crate) struct Aura { + pub key: &'static str, + pub grid: Vec<[i32; 2]>, + pub skill_grid: Option>, + pub atk: f64, + pub skill_scale: f64, +} +impl Aura { + pub fn refresh( + &self, + w: &mut World, + r: &mut crate::battle::buffs::Runtime, + h: &mut H, + source: Id, + dir: Direction, + active: bool, + ) -> Result<(), String> { + use crate::battle::{buffs, health::Side, targeting}; + let u = w.unit(source)?; + let on = u.stats.alive && u.deployed && !u.removed; + let grid = if active { + self.skill_grid.as_ref().unwrap_or(&self.grid) + } else { + &self.grid + }; + let keys = targeting::absolute_range(grid, u.deployment.tile, dir, 0); + let ids: Vec<_> = w.unit_ids().collect(); + for id in ids { + let u = w.unit(id)?; + if u.side != Side::Ally { + continue; + } + let eligible = on + && u.targeting.melee_operator + && targeting::aura_selectable(w, id)? + && body::in_range(w.unit(id)?, &keys); + if eligible { + let mut b = Buff { + key: Some(self.key.into()), + mods: [( + "atkPct".into(), + self.atk * if active { self.skill_scale } else { 1. }, + )] + .into(), + ..Default::default() + }; + b.runtime.duration = 0.45; + b.runtime.source = Some(source); + b.runtime.refresh = buffs::Refresh::Extend; + r.add( + w, + h, + id, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } else if w + .unit(id)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(self.key) && b.runtime.source == Some(source)) + { + r.remove(w, h, id, self.key)?; + } + } + Ok(()) + } +} +#[derive(Clone, Copy)] +pub(crate) struct ElementAttach { + pub normal: f64, + pub leader: f64, +} + +pub(crate) fn passive_garrisons( + data: &crate::data::Catalog, + raw: &Value, +) -> Result, String> { + let mut out = Vec::new(); + let ids = raw["garrisonIds"] + .as_array() + .map(Vec::as_slice) + .unwrap_or(&[]); + if ids.len() > crate::battle::grid::N { + return Err("Garrison list exceeds field bound".into()); + } + for gid in ids { + let Some(key) = gid.as_str() else { + return Err("Expected garrison id".into()); + }; + let g = &data.table("garrisons").ok_or("Missing garrison data")?[key]; + if g["eventType"] != "IN_BATTLE" { + continue; + } + let mut mods = Numbers::new(); + match g["effectKey"].as_str() { + Some("GAIN_BUFF") => { + for (from, to) in [("atk", "atkMul"), ("max_hp", "hpMul"), ("def", "defMul")] { + let n = number(&g["bb"][from], 0.); + if n > 0. { + mods.insert(to.into(), n); + } + } + } + Some("attr_common_global_buff") => { + for (from, to) in [ + ("sp_recovery_per_sec", "spRecoveryFlat"), + ("atk", "atkPct"), + ("max_hp", "hpPct"), + ("attack_speed", "aspd"), + ] { + let n = number(&g["bb"][from], 0.); + if n != 0. { + mods.insert(to.into(), n); + } + } + } + _ => continue, + } + let mut b = Buff { + key: Some(format!("gar:{key}")), + mods, + ..Default::default() + }; + b.runtime.persist = true; + out.push(b); + } + Ok(out) +} diff --git a/crates/engine/src/battle/content/operators/estell.rs b/crates/engine/src/battle/content/operators/estell.rs new file mode 100644 index 0000000..aff3ead --- /dev/null +++ b/crates/engine/src/battle/content/operators/estell.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Estelle: centurion attacks, self-heal on nearby death, and CEN-Y resistance. +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "centurion", + can_hit_fly: false, + ranged: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + sp_type: SpType::Hurt, + ..Skill::duration("skchr_estell_2") + }, + Skill::duration("skcom_atk_up[2]"), + ], + build, +}; +pub(super) fn build(raw: &Value, default_skill: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = raw["talents"] + .as_array() + .into_iter() + .flatten() + .find(|t| t["index"] == 0); + let tb = &raw["trait"]["bb"]; + s.combat.profile.hit_all_blocked = true; + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + if default_skill { + s.skill_flags.insert("noHeal".into()); + } + s.death_heal = Some(DeathHeal { + ratio: number(&t.map(|t| &t["bb"]["hp_ratio"]).unwrap_or(&Value::Null), 0.), + grid: t + .map(|t| &t["rangeGrid"]) + .filter(|g| !g.is_null()) + .map(crate::battle::operators::parse_range) + .transpose()?, + }); + if !tb["damage_resistance"].is_null() { + s.incoming_hit = Some(PhysicalResistance { + above_hp: number(&tb["hp_ratio"], 0.), + fraction: number(&tb["damage_resistance"], 0.), + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/excu.rs b/crates/engine/src/battle/content/operators/excu.rs new file mode 100644 index 0000000..8510411 --- /dev/null +++ b/crates/engine/src/battle/content/operators/excu.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Executor: all-in-range volleys, front-row multiplier, and fixed DEF ignore. +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "reaperrange", + can_hit_fly: true, + ranged: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[ + Skill { + attack_override: true, + ..Skill::duration("skchr_excu_2") + }, + Skill { + attack_override: true, + ..Skill::duration("skchr_excu_1") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default_skill: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let mut buff = Buff { + key: Some("talent:excu".into()), + mods: [( + "defIgnoreFlat".into(), + number(&talent(raw)["def_penetrate_fixed"], 0.), + )] + .into(), + ..Default::default() + }; + buff.runtime.persist = true; + s.permanent = Some(buff); + s.combat.profile.all_in_range = true; + s.grid_scale = Some(GridScale { + grid: crate::battle::operators::parse_range(&raw["trait"]["rangeGrid"])?, + scale: number(&raw["trait"]["bb"]["atk_scale"], 1.5), + skill_all: !default_skill, + }); + if default_skill { + s.combat.skill_hits = 2; + let bat = number(&raw["stats"]["bat"], 1.); + s.modifiers = [( + "batPct".into(), + (number(&bb["base_attack_time"], 0.) / if bat == 0. { 1. } else { bat }).max(-0.9), + )] + .into(); + } else { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/extras.rs b/crates/engine/src/battle/content/operators/extras.rs new file mode 100644 index 0000000..9afdfde --- /dev/null +++ b/crates/engine/src/battle/content/operators/extras.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Bounded lifecycle components shared by deployment and attack kits. +use super::*; +use crate::battle::{buffs, health, skills, valued}; +pub(crate) const DECAY: u64 = 1001; +pub(crate) const DOT: u64 = 1002; +#[derive(Default)] +pub(crate) struct Extra { + pub effects: Mechanics, + pub advanced: Advanced, + pub tactics: Tactics, + pub advanced_start_heal: f64, + pub advanced_burst_hits: u32, + pub advanced_range_extend: u32, + pub support: Support, + pub weakness: bool, + pub tag_scale: Vec<(String, f64)>, + pub deploy: bool, + pub release_on_start: bool, + pub duration: Option, + pub hp_loss: f64, + pub start_buff: Option, + pub skill_range: Option>, + pub no_heal: bool, + pub cost_delta: f64, + pub cost_aura: Option, + pub hp_speed: Option, + pub reveal: bool, + pub dot: Option, + pub normal_status: Option, + pub skill_status: Option, + pub sp_hurt: Option, + pub lord: Option, + pub skill_arts: bool, + pub self_heal: f64, +} +pub(crate) struct StartBuff { + pub key: &'static str, + pub shield: f64, + pub def: f64, + pub block: bool, + pub decay: bool, +} +pub(crate) struct CostAura { + pub value: f64, + pub limit: f64, +} +pub(crate) struct HpSpeed { + pub maximum: f64, + pub minimum: f64, + pub protect: f64, + pub below: f64, +} +#[derive(Clone, Copy)] +pub(crate) struct Dot { + pub duration: f64, + pub interval: f64, + pub amount: f64, + pub sea: f64, +} +#[derive(Clone, Copy)] +pub(crate) struct OnHitStatus { + pub key: &'static str, + pub duration: f64, + pub chance: Option, +} +pub(crate) struct SpHurt { + pub amount: f64, + pub grid: Vec<[i32; 2]>, +} +#[derive(Clone, Copy)] +pub(crate) struct Lord { + pub scale: f64, + pub arts: f64, + pub skill_full: bool, +} +impl Extra { + pub fn event( + &self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + e: skills::Event, + s: &skills::Runtime, + ) -> Result<(), String> { + let id = s.unit(); + if e == skills::Event::Start { + if self.release_on_start { + h.operator_release(w, r, id)?; + } + let hp = w.unit(id)?.stats.hp; + let loss = hp * self.hp_loss; + if loss > 0. && hp - loss >= 1. { + health::lose_hp( + w, + h, + health::Hit { + source: Some(id), + credit: Some(id), + target: id, + damage_type: crate::battle::damage::DamageType::True, + no_sp: true, + silent: false, + hp_loss: true, + on_applied: false, + }, + loss, + Default::default(), + false, + )?; + } + if let Some(start) = &self.start_buff { + let max = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp"); + let mut b = Buff { + key: Some(start.key.into()), + shield: max * start.shield, + ..Default::default() + }; + if start.def != 0. { + b.mods.insert("defPct".into(), start.def); + } + b.runtime.duration = s.spec.duration + if start.block { 0.05 } else { 0. }; + b.runtime.shield_hits = if start.block { 1 } else { 0 }; + if start.decay { + b.runtime.interval = 1.; + b.runtime.on_tick = Some(DECAY); + } + r.add( + w, + h, + id, + buffs::Spec { + buff: b, + mods_present: start.def != 0., + ..Default::default() + }, + )?; + } + } + if e == skills::Event::End { + if let Some(start) = &self.start_buff { + r.remove(w, h, id, start.key)?; + } + } + Ok(()) + } + pub fn tick( + &self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + let u = w.unit(id)?; + if !u.stats.alive || !u.deployed { + return Ok(()); + } + if let Some(p) = self + .hp_speed + .as_ref() + .filter(|p| p.maximum > 0. && p.minimum < 1.) + { + let u = w.unit_mut(id)?; + let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + let ratio = if max > 0. { u.stats.hp / max } else { 0. }; + let v = p.maximum * ((1. - ratio) / (1. - p.minimum)).clamp(0., 1.); + let current = u + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("utage:serious")) + .and_then(|b| b.mods.get("aspd")) + .copied(); + if current.map_or(true, |old| (old - v).abs() >= 0.5) { + if v < 0.5 { + if current.is_some() { + r.remove(w, h, id, "utage:serious")?; + } + } else { + r.add( + w, + h, + id, + buffs::Spec { + buff: Buff { + key: Some("utage:serious".into()), + mods: [("aspd".into(), v)].into(), + ..Default::default() + }, + mods_present: true, + ..Default::default() + }, + )?; + } + } + } + self.protect(w, r, h, id)?; + Ok(()) + } + pub fn protect( + &self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + if let Some(p) = &self.hp_speed { + let u = w.unit_mut(id)?; + let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + if u.stats.alive + && u.deployed + && p.protect > 0. + && max > 0. + && u.stats.hp / max < p.below + { + valued::apply( + w, + h, + r, + id, + valued::Request { + key: "protect", + kind: valued::Kind::Custom(|v| { + [ + ("physTakenMul".into(), 1. - v), + ("artsTakenMul".into(), 1. - v), + ] + .into() + }), + plain: false, + duration: 0.05, + value: p.protect, + source: Some(id), + stack_as: None, + }, + )?; + } + } + Ok(()) + } +} +impl CostAura { + pub fn refresh( + &self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + source: Id, + allies: &[(Id, f64)], + ) -> Result<(), String> { + let u = w.unit(source)?; + if !u.stats.alive || !u.deployed { + return Ok(()); + } + for &(id, cost) in allies { + if cost > self.limit || !crate::battle::targeting::aura_selectable(w, id)? { + continue; + } + if w.unit(id)?.stats.buffs().iter().any(|b| { + b.key.as_deref() == Some("talent:gravel") + && b.runtime.source != Some(source) + && b.mods.get("defPct").copied().unwrap_or(0.) > self.value + && b.runtime.time_left > 0.05 + }) { + continue; + } + let mut b = Buff { + key: Some("talent:gravel".into()), + mods: [("defPct".into(), self.value)].into(), + ..Default::default() + }; + b.runtime.duration = 0.6; + b.runtime.source = Some(source); + r.add( + w, + h, + id, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/content/operators/f12yin.rs b/crates/engine/src/battle/content/operators/f12yin.rs new file mode 100644 index 0000000..526f33c --- /dev/null +++ b/crates/engine/src/battle/content/operators/f12yin.rs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "fighter", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_f12yin_2", + kind: Kind::Toggle, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_f12yin_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_f12yin_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SKILL_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let _tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_f12yin_1" => Mode::First, + "skchr_f12yin_2" => Mode::Second, + "skchr_f12yin_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + skill_range(raw, s)?; + s.extra.effects.permanent.push(persistent( + "f12yin:body", + [ + ("defPct".into(), number(&t1["def"], 0.)), + ("dodgePhys".into(), number(&t1["prob"], 0.)), + ] + .into(), + )); + if number(&tb["prob"], 0.) > 0. { + s.extra.effects.permanent.push(persistent( + "f12yin:moduleX", + [("dodgePhys".into(), number(&tb["prob"], 0.))].into(), + )); + } + let mut p = s.combat.profile; + if mode == Mode::First { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + p.max_targets = number(&bb["max_target"], 2.); + } else { + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("defPct".into(), number(&bb["def"], 0.)), + ("blockCnt".into(), number(&bb["block_cnt"], 0.)), + ( + "hpRegenRatio".into(), + number(&bb["hp_recovery_per_sec_by_max_hp_ratio"], 0.), + ), + ( + "batPct".into(), + if mode == Mode::Third { + flat_bat(raw, number(&bb["base_attack_time"], 0.)) + } else { + 0. + }, + ), + ] + .into(); + } + if default { + p.hit_all_blocked = true; + } + if mode == Mode::Third { + s.combat.skill_hits = 2; + p.max_targets = number(&bb["attack@max_target"], 3.); + s.extra.support.radial_push = Some(number(&bb["attack@force"], 1.)); + } + s.combat.skill_profile = Some(p); + s.extra.advanced = Advanced::Mountain(Mountain { + mode, + probability: number(&t["prob"], 0.), + active_probability: number(&bb["talent@prob"], number(&t["prob"], 0.)), + scale: number(&t["atk_scale"], 1.), + weaken: number(&t["atk"], 0.), + duration: number(&t["duration"], 3.), + module_aspd: number(&tb["attack_speed"], 0.), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/fartth.rs b/crates/engine/src/battle/content/operators/fartth.rs new file mode 100644 index 0000000..c63e64e --- /dev/null +++ b/crates/engine/src/battle/content/operators/fartth.rs @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "longrange", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_fartth_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "CUSTOM_RANGE", + attack_override: true, + }, + Skill { + id: "skcom_quickattack[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_fartth_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let _tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skcom_quickattack[3]" => Mode::First, + "skchr_fartth_2" => Mode::Second, + "skchr_fartth_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + skill_range(raw, s)?; + s.combat.profile.priority = crate::battle::targeting::Priority::LowDef; + if raw["skill"]["trigger"]["customRangeGrid"].is_array() { + s.trigger_range = Some(crate::battle::operators::parse_range( + &raw["skill"]["trigger"]["customRangeGrid"], + )?); + } + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("aspd".into(), number(&bb["attack_speed"], 0.)), + ("taunt".into(), number(&t1["taunt_level"], -1.)), + ] + .into(); + if default { + s.extra.skill_range = Some( + (0..crate::battle::grid::COLS as i32) + .map(|c| [0, c]) + .collect(), + ); + } + if number(&tb["damage_scale"], 0.) > 0. { + s.extra.effects.distance = Some(DistanceScale { + minimum: number(&tb["min_dist"], 1.), + maximum: number(&tb["max_dist"], 4.5), + attack_scale: 0., + damage_scale: number(&tb["damage_scale"], 0.), + }); + } + s.extra.advanced = Advanced::Fartth(Fartth { + mode, + focus: number(&t["atk"], 0.15), + delay: number(&t["delay"], 10.), + far_scale: number(&bb["damage_scale"], 1.25), + module_sp: number(&tb["sp"], 0.), + base_grid: crate::battle::operators::parse_range(&raw["rangeGrid"])?, + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/flamtl.rs b/crates/engine/src/battle/content/operators/flamtl.rs new file mode 100644 index 0000000..4794ca1 --- /dev/null +++ b/crates/engine/src/battle/content/operators/flamtl.rs @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "PIONEER", + branch: "pioneer", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_flamtl_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_flamtl_1", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_flamtl_2", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "SKILL_RANGE", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let _t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let _tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_flamtl_1" => Mode::First, + "skchr_flamtl_2" => Mode::Second, + "skchr_flamtl_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + let grid = crate::battle::operators::parse_range(&raw["skill"]["rangeGrid"]) + .unwrap_or_else(|_| vec![[0, 0], [0, 1]]); + if mode == Mode::First { + s.rule_override = Some(crate::battle::skills::Rule::SpFull); + } + if mode == Mode::Second { + skill_range(raw, s)?; + s.skill_start = Some(SkillStart { + dp: number(&bb["cost"], 11.), + area: None, + }); + s.extra.effects.burst = Some(Burst { + grid: grid.clone(), + count: number(&bb["max_target"], 6.).floor().max(1.) as usize, + scale: number(&bb["atk_scale"], 1.8), + damage: crate::battle::damage::DamageType::Physical, + status: Some(OnHitStatus { + key: "stun", + duration: number(&bb["stun"], 0.5), + chance: None, + }), + debuff: None, + pull: None, + fly_scale: 1., + ground: false, + }); + s.extra.advanced_burst_hits = 2; + } + if default { + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ( + "batPct".into(), + (number(&bb["base_attack_time"], 1.) - 1.).max(-0.9), + ), + ("blockCnt".into(), number(&bb["block_cnt"], 1.)), + ("dodgePhys".into(), number(&bb["prob"], 0.6)), + ("dodgeArts".into(), number(&bb["prob"], 0.6)), + ] + .into(); + } + s.extra.advanced = Advanced::Flamtl(Flamtl { + mode, + total: number(&bb["value"], 8.).floor().max(0.) as u32, + cost: number(&bb["cost"], if mode == Mode::First { 6. } else { 1. }), + ally_dodge: number(&bb["flamtl_s_2.prob"], 0.4), + ally_duration: number(&bb["flamtl_s_2.duration"], 10.), + faction_dodge: number(&t1["prob"], 0.22), + grid, + module: [ + ("atkPct".into(), number(&tb["atk"], 0.)), + ("defPct".into(), number(&tb["def"], 0.)), + ] + .into(), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/flower.rs b/crates/engine/src/battle/content/operators/flower.rs new file mode 100644 index 0000000..66b959e --- /dev/null +++ b/crates/engine/src/battle/content/operators/flower.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "ringhealer", + ranged: true, + can_hit_fly: false, + physical: false, + projectile: "orb", + projectile_speed: 10., + required_range: None, + skills: &[ + Skill { + id: "skchr_flower_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skcom_heal_up[2]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let count = raw["talents"] + .as_array() + .into_iter() + .flatten() + .find(|t| t["hidden"] == true) + .map(|t| number(&t["bb"]["attack@max_target"], 3.)) + .unwrap_or(3.); + healing(s, count); + s.extra.support.lavender = number(&t["atk_to_hp_recovery_ratio"], 0.); + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("aspd".into(), number(&bb["attack_speed"], 0.)), + ] + .into(); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/forcer.rs b/crates/engine/src/battle/content/operators/forcer.rs new file mode 100644 index 0000000..5696d3a --- /dev/null +++ b/crates/engine/src/battle/content/operators/forcer.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "SPECIAL", + branch: "pusher", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + id: "skchr_forcer_2", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "SKILL_RANGE", + attack_override: false, + }, + Skill { + id: "skchr_forcer_1", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let tb = &raw["trait"]["bb"]; + s.combat.profile.hit_all_blocked = true; + s.extra.support.heavy_penetration = Some([ + number(&t["value"], 3.), + number(&t["def_penetrate_fixed"], 0.), + ]); + s.extra.support.refund = number(&tb["value"], 0.); + if default { + let grid = crate::battle::operators::parse_range(&raw["skill"]["rangeGrid"])?; + s.trigger_range = Some(grid.clone()); + let direct = number( + &bb["forcer_s_2[hit_directly].stun"], + number(&bb["stun"], 1.), + ); + s.extra.support.push = Some(PushCast { + grid, + force: number(&bb["force"], 1.), + direct, + wall: number(&bb["stun"], direct), + collision: number(&bb["forcer_s_2[brush].stun"], direct), + }); + } else { + s.extra.support.effect_push = true; + s.extra.effects.skill_push = Some(number(&bb["force"], 1.)); + s.extra.skill_status = Some(OnHitStatus { + key: "stun", + duration: number(&bb["stun"], 0.), + chance: None, + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/ghost.rs b/crates/engine/src/battle/content/operators/ghost.rs new file mode 100644 index 0000000..c2c0323 --- /dev/null +++ b/crates/engine/src/battle/content/operators/ghost.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Specter: centurion attacks, undying skill, and post-skill stun. +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "centurion", + can_hit_fly: false, + ranged: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill::duration("skchr_ghost_2"), + Skill::duration("skcom_atk_up[3]"), + ], + build, +}; +pub(super) fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.combat.profile.hit_all_blocked = true; + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + let mut b = Buff { + key: Some("talent:ghost".into()), + mods: [ + ("hpPct".into(), number(&t["max_hp"], 0.)), + ( + "hpRegenRatio".into(), + number(&t["hp_recovery_per_sec_by_max_hp_ratio"], 0.), + ), + ] + .into(), + ..Default::default() + }; + b.runtime.persist = true; + s.permanent = Some(b); + if default { + s.undying = true; + s.end_stun = number(&bb["stun"], 0.); + } + s.hit = HitHandler::Blocked { + scale: number(&raw["trait"]["bb"]["atk_scale"], 1.), + own: false, + inverse: false, + }; + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/glady.rs b/crates/engine/src/battle/content/operators/glady.rs new file mode 100644 index 0000000..75b2806 --- /dev/null +++ b/crates/engine/src/battle/content/operators/glady.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "SPECIAL", + branch: "hookmaster", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_glady_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_glady_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_glady_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_glady_1" => Mode::First, + "skchr_glady_2" => Mode::Second, + "skchr_glady_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + skill_range(raw, s)?; + if !default { + s.combat.skill_scale = number(&bb["attack@atk_scale"], number(&bb["atk_scale"], 1.)); + let mut p = s.combat.profile; + p.max_targets = number(&bb["attack@max_target"], 1.); + s.combat.skill_profile = Some(p); + if mode == Mode::Second { + s.modifiers = [( + "batPct".into(), + flat_bat(raw, number(&bb["base_attack_time"], 0.)).max(-0.9), + )] + .into(); + } + } + s.extra.advanced = Advanced::Glady(Glady { + mode, + force: number(&bb["force"], number(&bb["attack@force"], 0.)), + interval: number(&bb["interval"], 1.5).max(0.1), + scale: number(&bb["atk_scale"], 0.85), + slow: number(&bb["move_speed"], -0.5), + regen: number(&t["hp_recovery_per_sec_by_max_hp_ratio"], 0.025), + resistance: number(&t["damage_resistance"], 0.25), + max_weight: number(&t1["value"], 3.), + light_scale: number(&t1["atk_scale"], 1.3), + drag: number(&tb["value"], 0.), + drag_distance: number(&tb["dist"], 1.).max(1e-6), + far_radius: number( + &tm["skill@range_radius"], + number(&tm["attack@range_radius"], 0.), + ), + far_force: number( + &tm["skill@delta_force"], + number(&tm["attack@delta_force"], 0.), + ), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/gnosis.rs b/crates/engine/src/battle/content/operators/gnosis.rs new file mode 100644 index 0000000..595e9d7 --- /dev/null +++ b/crates/engine/src/battle/content/operators/gnosis.rs @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "underminer", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_gnosis_2", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_gnosis_1", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_gnosis_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let _tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_gnosis_1" => Mode::First, + "skchr_gnosis_2" => Mode::Second, + "skchr_gnosis_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + debuffer(raw, s); + if mode == Mode::First { + s.combat.skill_hits = 2; + s.combat.skill_scale = number(&bb["atk_scale"], 1.35); + } + if mode == Mode::Third { + s.modifiers = [("aspd".into(), number(&bb["attack_speed"], 0.))].into(); + let mut p = s.combat.profile; + p.max_targets = number(&bb["max_target"], 2.); + s.combat.skill_profile = Some(p); + } + s.extra.advanced = Advanced::Gnosis(Gnosis { + mode, + cold: number(&t["cold"], 1.), + burst_cold: number(&bb["cold"], 2.5), + burst_scale: number(&bb["atk_scale"], 1.3), + fragile_cold: number(&t["damage_scale_cold"], 1.25), + fragile_frozen: number(&t["damage_scale_freeze"], 1.5), + module_sp: number(&tb["sp_recovery_per_sec"], 0.), + resist_delay: number(&t1["interval"], 10.), + resist: (-number(&t1["one_minus_status_resistance"], -0.5)).clamp(0., 1.), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/grabds.rs b/crates/engine/src/battle/content/operators/grabds.rs new file mode 100644 index 0000000..faae229 --- /dev/null +++ b/crates/engine/src/battle/content/operators/grabds.rs @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "slower", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[ + Skill { + id: "skchr_grabds_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SKILL_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_grabds_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let tb = &raw["trait"]["bb"]; + slow_sp(raw, s); + s.permanent = Some(persistent( + "talent:grabds", + [("aspd".into(), number(&t["attack_speed"], 0.))].into(), + )); + s.extra.support.sluggish = Some([ + number(&tb["sluggish"], 0.8), + number(&t["sluggish_addition"], 0.), + ]); + if default { + s.modifiers = [("aspd".into(), number(&bb["attack_speed"], 0.))].into(); + skill_range(raw, s)?; + let mut p = s.combat.profile; + p.max_targets = number(&bb["max_target"], 1.).floor().max(1.); + s.combat.skill_profile = Some(p); + s.extra.support.quiet = Some(Quiet { + duration: number(&bb["sleep"], 0.), + count: p.max_targets as usize, + }); + } else { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + s.modifiers = [("maxTargets".into(), 1.)].into(); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/gravel.rs b/crates/engine/src/battle/content/operators/gravel.rs new file mode 100644 index 0000000..d1c894d --- /dev/null +++ b/crates/engine/src/battle/content/operators/gravel.rs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "SPECIAL", + branch: "executor", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + sp_type: SpType::None, + ..Skill::duration("skchr_gravel_2") + }, + Skill { + sp_type: SpType::None, + ..Skill::duration("skchr_gravel_1") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.extra.deploy = true; + s.extra.duration = Some(number(&bb["duration"], 10.)); + s.rule_override = Some(crate::battle::skills::Rule::Never); + s.combat.normal_hits = 2; + s.combat.split_mul = Some(0.5); + s.extra.cost_delta = number(&t["cost"], 0.); + s.extra.start_buff = Some(StartBuff { + key: if default { + "gravel:rats" + } else { + "gravel:shadow" + }, + shield: if default { + number(&bb["hp_ratio"], 0.) + } else { + 0. + }, + def: if default { 0. } else { number(&bb["def"], 0.) }, + block: false, + decay: true, + }); + if !t["cond.cost"].is_null() && number(&t["def"], 0.) != 0. { + s.extra.cost_aura = Some(CostAura { + value: number(&t["def"], 0.), + limit: number(&t["cond.cost"], 0.), + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/greyy.rs b/crates/engine/src/battle/content/operators/greyy.rs new file mode 100644 index 0000000..9e41fc4 --- /dev/null +++ b/crates/engine/src/battle/content/operators/greyy.rs @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "splashcaster", + can_hit_fly: true, + ranged: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[ + Skill { + attack_override: true, + ..Skill::duration("skchr_greyy_2") + }, + Skill::duration("skcom_magic_rage[2]"), + ], + build, +}; +pub(super) fn build(raw: &Value, default_skill: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.modifiers = { + // Original Greyy's radius is 1.0 rather than the branch's 1.1. + s.combat.area.splash = Some(Splash { + radius: 1., + scale: 1., + hits_fly: false, + fortress_melee: false, + }); + s.combat.sluggish = number(&t["sluggish"], 0.); + [("aspd".into(), number(&bb["attack_speed"], 0.))].into() + }; + s.combat.skill_area = s.combat.area; + s.combat.skill_sluggish = if default_skill { + s.combat.sluggish * number(&bb["talent_scale"], 1.) + } else { + s.combat.sluggish + }; + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/gvial2.rs b/crates/engine/src/battle/content/operators/gvial2.rs new file mode 100644 index 0000000..c40158a --- /dev/null +++ b/crates/engine/src/battle/content/operators/gvial2.rs @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "centurion", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + id: "skchr_gvial2_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_gvial2_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_gvial2_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let tb = &raw["trait"]["bb"]; + let t1 = talent_at(raw, 1); + s.combat.profile.hit_all_blocked = true; + s.extra.support.block_stats = Some([ + number(&t["atk"], 0.1), + number(&t["def"], 0.1), + number(&t["atk_add"], 0.04), + number(&t["def_add"], 0.04), + ]); + s.extra.support.received_heal = Some(ReceivedHeal { + below: number(&t1["hp_ratio"], 0.5), + normal: number(&t1["heal_scale_1"], 1.2), + low: number(&t1["heal_scale_2"], 1.4), + }); + if !tb["atk_scale"].is_null() { + s.hit = HitHandler::Blocked { + scale: number(&tb["atk_scale"], 1.), + own: true, + inverse: false, + }; + } + if number(&tb["damage_resistance"], 0.) > 0. { + s.incoming_hit = Some(PhysicalResistance { + above_hp: number(&tb["hp_ratio"], 0.), + fraction: number(&tb["damage_resistance"], 0.), + }); + } + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("defPct".into(), number(&bb["def"], 0.)), + ("aspd".into(), number(&bb["attack_speed"], 0.)), + ("blockCnt".into(), number(&bb["block_cnt"], 0.)), + ] + .into(); + if default { + s.extra.support.deferred = Some(Deferred { + resistance: number(&bb["damage_resistance"], 0.5).clamp(0., 0.99), + duration: number(&bb["final_duration"], 20.), + interval: number(&bb["interval"], 0.1).max(1. / 30.), + }); + } else if raw["skill"]["skillId"] == "skchr_gvial2_1" { + s.extra.support.skill_drain_heal = number(&bb["heal_scale"], 0.3); + } else { + skill_range(raw, s)?; + s.extra.support.pull_unblocked = true; + s.extra.effects.skill_pull = Some(PullHit { + force: number(&bb["attack@force"], 1.), + travel_damage: 0., + distance: 1., + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/haini.rs b/crates/engine/src/battle/content/operators/haini.rs new file mode 100644 index 0000000..9ea752c --- /dev/null +++ b/crates/engine/src/battle/content/operators/haini.rs @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "underminer", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[ + Skill { + id: "skchr_haini_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_haini_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + debuffer(raw, s); + s.extra.support.enemy_auras.push(EnemyAura { + key: "talent:haini_fragile", + mods: [("dmgTakenMul".into(), number(&t["damage_scale"], 1.))].into(), + filter: AuraFilter::Normal, + period: 0.2, + active_only: false, + growth: Some([ + number(&bb["attack@talent_up"], 0.), + number(&bb["attack@max_talent_up"], 1.), + ]), + }); + let mut p = s.combat.profile; + if default { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + p.max_targets = number(&bb["attack@max_target"], 1.).floor().max(1.); + s.extra.support.enemy_auras.push(EnemyAura { + key: "skill:haini_slow", + mods: [( + "moveMul".into(), + (1. + number(&bb["attack@move_speed"], 0.)).max(0.), + )] + .into(), + filter: AuraFilter::Normal, + period: 0., + active_only: true, + growth: None, + }); + } else { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + p.max_targets = number(&bb["max_target"], 1.).floor().max(1.); + } + s.combat.skill_profile = Some(p); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/harold.rs b/crates/engine/src/battle/content/operators/harold.rs new file mode 100644 index 0000000..c96c614 --- /dev/null +++ b/crates/engine/src/battle/content/operators/harold.rs @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "wandermedic", + ranged: true, + can_hit_fly: false, + physical: false, + projectile: "orb", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_harold_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skcom_heal_up[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let _t1 = talent_at(raw, 1); + let _tm = talent_at(raw, -1); + let _mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skcom_heal_up[3]" => Mode::First, + "skchr_harold_2" => Mode::Second, + _ => return Err("Unknown selected skill".into()), + }; + healing(s, 1.); + if let Some(h) = &mut s.combat.profile.heal { + h.element_heal = true; + } + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("aspd".into(), number(&bb["attack_speed"], 0.)), + ] + .into(); + s.extra.advanced = Advanced::Harold(Harold { + severe: default, + element_ratio: number(&tb["ep_heal_ratio"], 0.5), + extra_scale: number(&bb["trait_scale"], 1.), + resistance: number(&t["ep_damage_resistance"], 0.).clamp(0., 1.), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/hsguma.rs b/crates/engine/src/battle/content/operators/hsguma.rs new file mode 100644 index 0000000..f6fac8b --- /dev/null +++ b/crates/engine/src/battle/content/operators/hsguma.rs @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "protector", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_hsguma_2", + kind: Kind::Passive, + sp_type: SpType::None, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_hsguma_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: false, + }, + Skill { + id: "skchr_hsguma_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t0 = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + blocked_def(raw, s, "hsguma:module"); + let mut armor = persistent("hsguma:armor", Numbers::new()); + armor.runtime.injury.on_injury = Some(ARMOR_BLOCK); + armor.runtime.tick_payload = number(&t0["prob"], 0.25); + s.extra.effects.permanent.push(armor); + s.extra.effects.aura = Some(StatAura { + key: "hsguma:def", + grid: None, + profession: Some("TANK"), + mods: [("defPct".into(), number(&t1["def"], 0.06))].into(), + }); + s.modifiers = [ + ("defPct".into(), number(&bb["def"], 0.)), + ("atkPct".into(), number(&bb["atk"], 0.)), + ] + .into(); + if default { + s.extra.effects.observer = Some(InjuryObserver { + key: "hsguma:thorns", + counter: Some(Counter { + key: "hsguma:thorns", + stat: "atk", + scale: number(&bb["atk_scale"], 0.65), + }), + debuff: None, + }); + } else if raw["skill"]["skillId"] == "skchr_hsguma_3" { + let mut p = s.combat.profile; + p.all_in_range = true; + s.combat.skill_profile = Some(p); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/humus.rs b/crates/engine/src/battle/content/operators/humus.rs new file mode 100644 index 0000000..de6d733 --- /dev/null +++ b/crates/engine/src/battle/content/operators/humus.rs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "reaper", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + id: "skchr_humus_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_humus_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let tb = &raw["trait"]["bb"]; + s.extra.no_heal = true; + s.combat.profile.all_in_range = true; + s.extra.support.reaper = number(&tb["value"], 50.); + s.extra.support.overflow = number(&t["max_hp_ratio"], 0.); + if default { + s.modifiers = [("blockCnt".into(), number(&bb["block_cnt"], 0.))].into(); + let mut peaks = Vec::new(); + for (key, value) in bb.as_object().into_iter().flatten() { + if key.ends_with(".peak_performance.hp_ratio") { + let atk = key.replace(".hp_ratio", ".atk"); + peaks.push([number(value, 1.), number(&bb[&atk], 0.)]); + } + } + peaks.sort_by(|a, b| b[0].total_cmp(&a[0])); + s.extra.support.peaks = peaks; + } else { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + s.extra.support.skill_heal = number(&bb["value"], 0.); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/inside.rs b/crates/engine/src/battle/content/operators/inside.rs new file mode 100644 index 0000000..187f49f --- /dev/null +++ b/crates/engine/src/battle/content/operators/inside.rs @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "fastshot", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_inside_2", + kind: Kind::Ammo, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_inside_1", + kind: Kind::Ammo, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + fastshot(raw, s); + s.extra.effects.ammo = Some(AmmoSupport { + delay: number(&t["duration"], 0.), + own: number(&t["self_ammo"], 0.), + ally: number(&t["ally_ammo"], 0.), + }); + s.extra.effects.ammo_count = number(&bb["attack@trigger_time"], 1.).max(1.); + if default { + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ( + "batPct".into(), + flat_bat(raw, number(&bb["base_attack_time"], 0.)), + ), + ("taunt".into(), -1.), + ] + .into(); + let mut p = s.combat.profile; + p.priority = crate::battle::targeting::Priority::Ranged; + s.combat.skill_profile = Some(p); + } else { + s.combat.skill_scale = number(&bb["attack@atk_scale"], 1.); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/kroos2.rs b/crates/engine/src/battle/content/operators/kroos2.rs new file mode 100644 index 0000000..3628559 --- /dev/null +++ b/crates/engine/src/battle/content/operators/kroos2.rs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "fastshot", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_kroos2_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_kroos2_1", + kind: Kind::Duration, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + fastshot(raw, s); + let t = talent(raw); + s.extra.effects.crit = Some(Critical { + chance: number(&t["prob"], 0.2), + attack_scale: 1., + damage_scale: number(&t["atk_scale"], 1.5), + stun: number(&t["stun"], 0.2), + }); + s.combat.skill_hits = 2; + if default { + s.modifiers = [( + "batPct".into(), + flat_bat(raw, number(&bb["base_attack_time"], 0.)), + )] + .into(); + s.extra.effects.hit_upgrade = + Some(number(&bb["attack@max_stack_count"], 40.).max(0.) as u64); + } else { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + s.skill_flags.insert("camou".into()); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/leizi.rs b/crates/engine/src/battle/content/operators/leizi.rs new file mode 100644 index 0000000..eed1f7e --- /dev/null +++ b/crates/engine/src/battle/content/operators/leizi.rs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "chain", + can_hit_fly: true, + ranged: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[ + Skill { + attack_override: true, + ..Skill::duration("skchr_leizi_2") + }, + Skill::duration("skcom_atk_up[3]"), + ], + build, +}; +pub(super) fn build(raw: &Value, default_skill: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + let tb = &raw["trait"]["bb"]; + s.modifiers = { + s.combat.area.chain = Some(Chain { + count: number(&tb["attack@max_target"], 3.), + radius: 1.7, + falloff: if tb["attack@chain.atk_scale"].is_null() { + 0.15 + } else { + 1. - number(&tb["attack@chain.atk_scale"], 0.85) + }, + sluggish: number(&tb["attack@sluggish"], 0.5), + }); + s.hit = HitHandler::Leizi(Hit { + unblocked_scale: number(&t["atk_scale"], 1.), + }); + [("atkPct".into(), number(&bb["atk"], 0.))].into() + }; + s.combat.skill_area = s.combat.area; + if default_skill { + s.combat.skill_area.chain.as_mut().unwrap().falloff = 0.; + } + Ok(()) +} + +#[derive(Clone, Copy)] +pub(crate) struct Hit { + pub unblocked_scale: f64, +} +impl Hit { + pub fn apply(&self, w: &mut World, q: &mut hit::Request) -> Result<(), String> { + let unblocked_scale = self.unblocked_scale; + if w.unit(q.hit.target)?.blocked_by().is_none() { + q.damage.amount *= unblocked_scale; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/content/operators/lionhd.rs b/crates/engine/src/battle/content/operators/lionhd.rs new file mode 100644 index 0000000..2d5eb4e --- /dev/null +++ b/crates/engine/src/battle/content/operators/lionhd.rs @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "splashcaster", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_lionhd_2", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: false, + }, + Skill { + id: "skcom_atk_up[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.combat.area.splash = Some(Splash { + radius: 1.1, + scale: 1., + hits_fly: true, + fortress_melee: false, + }); + s.combat.skill_area = s.combat.area; + module_range(raw, s)?; + s.extra.effects.enemy_atk = Some(EnemyAttack { + value: number(&t["atk"], 0.04), + cap: number(&t["max_valid_stack_cnt"], 5.), + }); + if default { + skill_range(raw, s)?; + s.extra.effects.burst = Some(Burst { + grid: crate::battle::operators::parse_range(&raw["skill"]["rangeGrid"])?, + count: usize::MAX, + scale: number(&bb["atk_scale"], 1.7), + damage: crate::battle::damage::DamageType::Arts, + status: None, + debuff: Some(Debuff { + key: "lionhd:res", + stat: "resMul", + value: number(&bb["magic_resistance"], 0.), + duration: number(&bb["duration"], 6.), + strongest: true, + }), + pull: None, + fly_scale: 1., + ground: false, + }); + } else { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/lisa.rs b/crates/engine/src/battle/content/operators/lisa.rs new file mode 100644 index 0000000..9b7b8e9 --- /dev/null +++ b/crates/engine/src/battle/content/operators/lisa.rs @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "slower", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_lisa_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_lisa_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_lisa_2", + kind: Kind::Toggle, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_lisa_1" => Mode::First, + "skchr_lisa_2" => Mode::Second, + "skchr_lisa_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.extra.normal_status = Some(OnHitStatus { + key: "sluggish", + duration: number(&tb["sluggish"], 0.8), + chance: None, + }); + s.extra.support.sp_aura = number(&t["sp_recovery_per_sec"], 0.); + s.extra.support.sp_period = Some(0.25); + s.extra.support.sp_duration = Some(0.5); + s.extra.support.sp_profession = Some("SUPPORT"); + skill_range(raw, s)?; + if default { + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + } else { + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("aspd".into(), number(&bb["attack_speed"], 0.)), + ] + .into(); + if mode == Mode::Second { + let mut p = s.combat.profile; + p.max_targets = number(&bb["attack@max_target"], 2.); + s.combat.skill_profile = Some(p); + } + } + s.extra.advanced = Advanced::Lisa(Lisa { + fox: default, + fragile: number(&t1["damage_scale"], 1.) - 1., + boost: number(&bb["scale_delta_to_one"], 1.), + regen: number(&bb["attack@atk_to_hp_recovery_ratio"], 0.), + module_sp: number(&tm["sp_recovery_per_sec"], 0.), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/liskam.rs b/crates/engine/src/battle/content/operators/liskam.rs new file mode 100644 index 0000000..fdd88e6 --- /dev/null +++ b/crates/engine/src/battle/content/operators/liskam.rs @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "shotprotector", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[ + Skill { + sp_type: SpType::Hurt, + attack_override: true, + ..Skill::duration("skchr_liskam_2") + }, + Skill { + sp_type: SpType::Hurt, + ..Skill::duration("skchr_liskam_1") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = raw["talents"] + .as_array() + .into_iter() + .flatten() + .find(|t| t["index"] == 0) + .ok_or("Missing Liskarm talent")?; + let t1 = raw["talents"] + .as_array() + .into_iter() + .flatten() + .find(|t| t["index"] == 1) + .map(|t| &t["bb"]) + .unwrap_or(&Value::Null); + let resistance = number(&t1["magic_resistance"], 0.); + if resistance != 0. { + let mut b = Buff { + key: Some("talent:liskam".into()), + mods: [("resFlat".into(), resistance)].into(), + ..Default::default() + }; + b.runtime.persist = true; + s.permanent = Some(b); + } + s.extra.sp_hurt = Some(SpHurt { + amount: number(&t["bb"]["sp"], 0.), + grid: if t["rangeGrid"].is_null() { + vec![[1, 0], [0, -1], [0, 1], [-1, 0]] + } else { + crate::battle::operators::parse_range(&t["rangeGrid"])? + }, + }); + s.extra.reveal = raw["isGolden"] == true && !raw["module"].is_null(); + if default { + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("batPct".into(), number(&bb["base_attack_time"], 0.).max(0.)), + ] + .into(); + let mut p = s.combat.profile; + p.max_targets = number(&bb["attack@max_target"], 1.).floor().max(1.); + s.combat.skill_profile = Some(p); + s.combat.skill_damage = Some(crate::battle::damage::DamageType::Arts); + s.extra.skill_status = Some(OnHitStatus { + key: "stun", + duration: number(&bb["attack@stun"], 0.), + chance: Some(number(&bb["attack@buff_prob"], 0.)), + }); + s.end_stun = number(&bb["stun"], 0.); + } else { + s.extra.duration = Some(number(&bb["duration"], 8.)); + s.modifiers = [("defPct".into(), number(&bb["def"], 0.))].into(); + s.rule_override = Some(crate::battle::skills::Rule::SpFull); + s.extra.start_buff = Some(StartBuff { + key: "liskam:block", + shield: 0., + def: 0., + block: true, + decay: false, + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/mechanics.rs b/crates/engine/src/battle/content/operators/mechanics.rs new file mode 100644 index 0000000..a94c00f --- /dev/null +++ b/crates/engine/src/battle/content/operators/mechanics.rs @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Typed components assembled by individual Kits. Mutable counters stay per unit. +use super::*; +use crate::battle::damage::DamageType; +pub(crate) const ARMOR_BLOCK: u64 = 1101; +pub(crate) const INJURY_OBSERVER: u64 = 1102; +pub(crate) const SKILL_COUNTER: u64 = 1103; +#[derive(Default)] +pub(crate) struct Memory { + pub support: super::support::State, + pub advanced: AdvancedState, + pub tactical: TacticalState, + pub hits: u64, + pub active_skill: bool, + pub skill_death_pending: bool, + pub deployments: u64, + pub uses: usize, + pub revived: bool, + pub boosted: bool, + pub cost_cut: f64, + pub ammo_granted: bool, + pub ammo_grants: std::collections::BTreeMap, + pub next_pulse: f64, + pub blessing_pending: bool, +} +pub(crate) struct Mechanics { + pub ammo: Option, + pub ammo_count: f64, + pub permanent: Vec, + pub deploy_buff: Option, + pub condition: Option, + pub observer: Option, + pub skill_counter: Option, + pub aura: Option, + pub team: Option, + pub random_bless: Option, + pub deploy_sp: f64, + pub respawn_delta: f64, + pub cost_cut: Option, + pub burst: Option, + pub skill_debuff: Option, + pub skill_pull: Option, + pub skill_push: Option, + pub start_status: Option<(Vec<[i32; 2]>, OnHitStatus)>, + pub secondary: Option, + pub end_heal: f64, + pub blocked_taken: f64, + pub resist: f64, + pub crit: Option, + pub hit_upgrade: Option, + pub attack_boost: Option, + pub growing_atk: Option>, + pub enemy_atk: Option, + pub distance: Option, + pub fly_scale: f64, + pub lord_skill_scale: f64, + pub skill_def_ignore: f64, + pub force_attack: bool, + pub revive: Option, + pub base_range: Option>, +} +impl Default for Mechanics { + fn default() -> Self { + Self { + ammo: None, + ammo_count: 0., + permanent: vec![], + deploy_buff: None, + condition: None, + observer: None, + skill_counter: None, + aura: None, + team: None, + random_bless: None, + deploy_sp: 0., + respawn_delta: 0., + cost_cut: None, + burst: None, + skill_debuff: None, + skill_pull: None, + skill_push: None, + start_status: None, + secondary: None, + end_heal: 0., + blocked_taken: 1., + resist: 0., + crit: None, + hit_upgrade: None, + attack_boost: None, + growing_atk: None, + enemy_atk: None, + distance: None, + fly_scale: 1., + lord_skill_scale: 1., + skill_def_ignore: 0., + force_attack: false, + revive: None, + base_range: None, + } + } +} +pub(crate) struct AmmoSupport { + pub delay: f64, + pub own: f64, + pub ally: f64, +} +pub(crate) enum Predicate { + Unblocked, + AllyInRange, +} +pub(crate) struct Conditional { + pub key: &'static str, + pub when: Predicate, + pub mods: Numbers, +} +#[derive(Clone, Copy)] +pub(crate) struct Counter { + pub key: &'static str, + pub stat: &'static str, + pub scale: f64, +} +pub(crate) struct InjuryObserver { + pub key: &'static str, + pub counter: Option, + pub debuff: Option, +} +pub(crate) struct StatAura { + pub key: &'static str, + pub grid: Option>, + pub profession: Option<&'static str>, + pub mods: Numbers, +} +pub(crate) struct TeamBuff { + pub key: &'static str, + pub characters: &'static [&'static str], + pub mods: Numbers, +} +impl TeamBuff { + pub fn apply( + &self, + w: &mut World, + r: &mut crate::battle::buffs::Runtime, + h: &mut H, + source: Id, + target: Id, + ) -> Result<(), String> { + let mut buff = persistent(self.key, self.mods.clone()); + buff.runtime.source = Some(source); + r.add( + w, + h, + target, + crate::battle::buffs::Spec { + buff, + allow_dead: true, + mods_present: true, + ..Default::default() + }, + )?; + Ok(()) + } +} +pub(crate) struct CostCut { + pub amount: f64, + pub cap: f64, + pub every: bool, +} +pub(crate) struct Burst { + pub grid: Vec<[i32; 2]>, + pub count: usize, + pub scale: f64, + pub damage: DamageType, + pub status: Option, + pub debuff: Option, + pub pull: Option, + pub fly_scale: f64, + pub ground: bool, +} +#[derive(Clone, Copy)] +pub(crate) struct Debuff { + pub key: &'static str, + pub stat: &'static str, + pub value: f64, + pub duration: f64, + pub strongest: bool, +} +#[derive(Clone, Copy)] +pub(crate) struct PullHit { + pub force: f64, + pub travel_damage: f64, + pub distance: f64, +} +pub(crate) enum Secondary { + Sonic { radius: f64, scale: f64 }, + NearbyBlocked { scale: f64 }, +} +pub(crate) struct Critical { + pub chance: f64, + pub attack_scale: f64, + pub damage_scale: f64, + pub stun: f64, +} +pub(crate) struct AttackBoost { + pub chance: f64, + pub scale: f64, +} +pub(crate) struct EnemyAttack { + pub value: f64, + pub cap: f64, +} +pub(crate) struct DistanceScale { + pub minimum: f64, + pub maximum: f64, + pub attack_scale: f64, + pub damage_scale: f64, +} +pub(crate) struct Revive { + pub hp_mul: f64, + pub aspd: f64, + pub hp_ratio: f64, +} +pub(crate) fn talent_at(raw: &Value, index: i64) -> &Value { + raw["talents"] + .as_array() + .into_iter() + .flatten() + .find(|t| t["index"] == index) + .map(|t| &t["bb"]) + .unwrap_or(&Value::Null) +} +pub(crate) fn persistent(key: &str, mods: Numbers) -> Buff { + let mut b = Buff { + key: Some(key.into()), + mods, + ..Default::default() + }; + b.runtime.persist = true; + b +} +pub(crate) fn flat_bat(raw: &Value, value: f64) -> f64 { + let bat = number(&raw["stats"]["bat"], 1.); + (value / if bat == 0. { 1. } else { bat }).max(-0.95) +} +pub(crate) fn fastshot(raw: &Value, s: &mut Spec) { + s.combat.profile.priority = crate::battle::targeting::Priority::Fly; + s.extra.effects.fly_scale = number(&raw["trait"]["bb"]["atk_scale"], 1.); +} +pub(super) fn blocked_def(raw: &Value, s: &mut Spec, key: &'static str) { + let def = number(&raw["trait"]["bb"]["def"], 0.); + if def != 0. { + s.while_blocked = Some(WhileBlocked { + key, + mods: [("defPct".into(), def)].into(), + }); + } +} +pub(crate) fn skill_range(raw: &Value, s: &mut Spec) -> Result<(), String> { + if !raw["skill"]["rangeGrid"].is_null() { + let grid = crate::battle::operators::parse_range(&raw["skill"]["rangeGrid"])?; + s.trigger_range = Some(grid.clone()); + s.extra.skill_range = Some(grid); + } + Ok(()) +} +pub(crate) fn module_range(raw: &Value, s: &mut Spec) -> Result<(), String> { + if raw["module"]["active"] != true || raw["trait"]["rangeExpand"] != true { + return Ok(()); + } + let module = raw["module"]["id"].as_str().unwrap_or(""); + if let Some(record) = raw["modules"] + .as_array() + .into_iter() + .flatten() + .find(|m| m["uniEquipId"] == module) + { + if let Some(change) = record["talentChanges"] + .as_array() + .into_iter() + .flatten() + .find(|t| t["rangeGrid"].is_array()) + { + s.extra.effects.base_range = + Some(crate::battle::operators::parse_range(&change["rangeGrid"])?); + } + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/mint.rs b/crates/engine/src/battle/content/operators/mint.rs new file mode 100644 index 0000000..d676f23 --- /dev/null +++ b/crates/engine/src/battle/content/operators/mint.rs @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "phalanx", + ranged: true, + can_hit_fly: false, + physical: false, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + id: "skchr_mint_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SEARCH", + attack_override: true, + }, + Skill { + id: "skchr_mint_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let tb = &raw["trait"]["bb"]; + // The no-attack data row retains the caster profession's air targeting. + s.combat.profile.selection.can_hit_fly = true; + s.combat.profile.only_while_skill = true; + s.combat.profile.all_in_range = true; + s.combat.profile.range_aoe = true; + s.combat.projectile = None; + let mut p = s.combat.profile; + p.selection.can_hit_fly = true; + s.combat.skill_profile = Some(p); + s.combat.skill_scale = number(&bb["attack@atk_scale"], number(&bb["atk_scale"], 1.)); + s.combat.skill_area.selection.can_hit_fly = true; + skill_range(raw, s)?; + let grid = raw["talents"] + .as_array() + .into_iter() + .flatten() + .find(|t| t["index"] == 0) + .map(|t| &t["rangeGrid"]) + .unwrap_or(&Value::Null); + s.extra.support.phalanx = Some(Phalanx { + guard: [ + ("defPct".into(), number(&tb["def"], 2.)), + ("resFlat".into(), number(&tb["magic_resistance"], 20.)), + ] + .into(), + keep: [ + ("defPct".into(), number(&tb["soil_e_002[buff].def"], 0.)), + ( + "resFlat".into(), + number(&tb["soil_e_002[buff].magic_resistance"], 0.), + ), + ] + .into(), + taunt: number(&t["taunt_level"], -1.), + aura: StatAura { + key: "talent:mint_geo", + grid: Some(if grid.is_null() { + vec![[1, 0], [0, -1], [0, 0], [0, 1], [-1, 0]] + } else { + crate::battle::operators::parse_range(grid)? + }), + profession: None, + mods: [("defPct".into(), number(&t["def"], 0.))].into(), + }, + burst: if default { + number(&bb["atk_scale"], 0.) + } else { + 0. + }, + }); + if default { + s.extra.support.inward = Some(number(&bb["attack@force"], number(&bb["force"], 0.))); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/mizuki.rs b/crates/engine/src/battle/content/operators/mizuki.rs new file mode 100644 index 0000000..2f5e066 --- /dev/null +++ b/crates/engine/src/battle/content/operators/mizuki.rs @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "SPECIAL", + branch: "stalker", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_mizuki_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_mizuki_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_mizuki_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_mizuki_1" => Mode::First, + "skchr_mizuki_2" => Mode::Second, + "skchr_mizuki_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.combat.profile.all_in_range = true; + s.extra.effects.permanent.push(persistent( + "trait:stalker", + [ + ("dodgePhys".into(), number(&tb["prob"], 0.5)), + ("dodgeArts".into(), number(&tb["prob"], 0.5)), + ("taunt".into(), -1.), + ] + .into(), + )); + skill_range(raw, s)?; + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ( + "batPct".into(), + if mode == Mode::Second { + flat_bat(raw, number(&bb["base_attack_time"], 0.)).max(-0.9) + } else { + 0. + }, + ), + ] + .into(); + if mode == Mode::First { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + } + s.extra.advanced = Advanced::Mizuki(Mizuki { + mode, + scale: number(&t["attack@mizuki_t_1.atk_scale"], 0.5), + count: number(&t["attack@max_target"], 1.).floor().max(1.) as usize, + extra: number(&bb["attack@max_target"], 0.).floor().max(0.) as usize, + skill_scale: number(&bb["talent_scale"], 2.), + status: number( + &bb[if mode == Mode::Second { + "attack@unmovable" + } else { + "attack@stun" + }], + 0.8, + ), + loss: number(&bb["attack@hp_ratio"], 0.15), + threshold: number(&t1["hp_ratio"], 0.5), + attack: number(&t1["atk"], 0.), + slow: number(&tm["move_speed"], 0.), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/mostma.rs b/crates/engine/src/battle/content/operators/mostma.rs new file mode 100644 index 0000000..4d84fee --- /dev/null +++ b/crates/engine/src/battle/content/operators/mostma.rs @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "splashcaster", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_mostma_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skcom_atk_up[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_mostma_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let _tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let _tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skcom_atk_up[3]" => Mode::First, + "skchr_mostma_2" => Mode::Second, + "skchr_mostma_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + module_range(raw, s)?; + skill_range(raw, s)?; + s.combat.area.splash = Some(Splash { + radius: 1.1, + scale: 1., + hits_fly: false, + fortress_melee: false, + }); + s.combat.skill_area = s.combat.area; + s.extra.support.sp_aura = number(&t["sp_recovery_per_sec"], 0.4); + s.extra.support.sp_profession = Some("CASTER"); + if default { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + let mut p = s.combat.profile; + p.all_in_range = true; + s.combat.skill_profile = Some(p); + s.combat.skill_area.splash = None; + s.combat.skill_direct = true; + } else if mode == Mode::First { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + } + s.extra.advanced = Advanced::Mostma(Mostma { + lock: mode == Mode::Second, + ripple: default, + slow: number(&t1["move_speed"], -0.15), + slow_scale: number(&bb["talent_scale"], 3.), + force: number(&bb["attack@force"], 0.), + lock_scale: number(&bb["atk_scale"], 1.), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/mudrok.rs b/crates/engine/src/battle/content/operators/mudrok.rs new file mode 100644 index 0000000..5aa5c37 --- /dev/null +++ b/crates/engine/src/battle/content/operators/mudrok.rs @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "unyield", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_mudrok_2", + kind: Kind::Instant, + sp_type: SpType::Hurt, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skcom_def_up[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: false, + }, + Skill { + id: "skchr_mudrok_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let _tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skcom_def_up[3]" => Mode::First, + "skchr_mudrok_2" => Mode::Second, + "skchr_mudrok_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.extra.no_heal = true; + skill_range(raw, s)?; + let grid = + crate::battle::operators::parse_range(&raw["skill"]["rangeGrid"]).unwrap_or_else(|_| { + vec![ + [-1, -1], + [-1, 0], + [-1, 1], + [0, -1], + [0, 0], + [0, 1], + [1, -1], + [1, 0], + [1, 1], + ] + }); + if default { + s.extra.skill_range = Some(grid.clone()); + let mut p = s.combat.profile; + p.all_in_range = true; + p.selection.ground_only = true; + p.selection.can_hit_fly = false; + s.combat.skill_profile = Some(p); + s.combat.skill_scale = number(&bb["atk_scale"], 1.9); + s.extra.skill_status = Some(OnHitStatus { + key: "stun", + duration: number(&bb["stun"], 0.5), + chance: Some(number(&bb["buff_prob"], 0.3)), + }); + } + if mode == Mode::First { + s.modifiers = [("defPct".into(), number(&bb["def"], 0.))].into(); + } + if mode == Mode::Third { + let mut p = s.combat.profile; + p.hit_all_blocked = true; + s.combat.skill_profile = Some(p); + s.extra.effects.blocked_taken = number(&tb["damage_scale"], 1.); + } + s.extra.effects.blocked_taken = number(&tb["damage_scale"], 1.); + let mut layer = Buff { + key: Some("mudrok:layers".into()), + ..Default::default() + }; + layer.runtime.shield_hits = + (number(&t["times"], 1.).max(0.) as u32).min(number(&t["max_times"], 3.).max(0.) as u32); + if layer.runtime.shield_hits > 0 { + s.extra.effects.deploy_buff = Some(layer); + } + s.extra.advanced = Advanced::Mudrok(Mudrok { + mode, + grid, + sleep: number(&bb["sleep"], 10.), + slow: number(&bb["move_speed"], -0.6), + stun: number(&bb["stun"], 3.), + awake: [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("defPct".into(), number(&bb["def"], 0.)), + ( + "batPct".into(), + flat_bat(raw, number(&bb["base_attack_time"], 0.)).max(-0.9), + ), + ] + .into(), + layer_period: number(&t["interval"], 9.).max(1. / 30.), + layer_add: number(&t["times"], 1.).max(0.) as u32, + layer_cap: number(&t["max_times"], 3.).max(0.) as u32, + layer_heal: number(&t["hp_ratio"], 0.2), + layer_sp: number(&t["sp"], 0.), + sarkaz_resistance: number(&t1["damage_resistance"], 0.3), + module: [ + ("atkPct".into(), number(&tb["atk"], 0.)), + ("defPct".into(), number(&tb["def"], 0.)), + ] + .into(), + }); + if default { + s.extra.advanced_start_heal = number(&bb["hp_ratio"], 0.04); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/pinecn.rs b/crates/engine/src/battle/content/operators/pinecn.rs new file mode 100644 index 0000000..3644613 --- /dev/null +++ b/crates/engine/src/battle/content/operators/pinecn.rs @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "reaperrange", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_pinecn_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_pinecn_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.combat.profile.all_in_range = true; + s.grid_scale = Some(GridScale { + grid: crate::battle::operators::parse_range(&raw["trait"]["rangeGrid"])?, + scale: number(&raw["trait"]["bb"]["atk_scale"], 1.5), + skill_all: false, + }); + let mut power = Buff { + key: Some("talent:pinecn_power".into()), + mods: [( + "spRecoveryFlat".into(), + number(&t["sp_recovery_per_sec"], 0.), + )] + .into(), + ..Default::default() + }; + power.runtime.duration = number(&t["duration"], 60.); + s.extra.effects.deploy_buff = Some(power); + if default { + skill_range(raw, s)?; + s.rule_override = Some(crate::battle::skills::Rule::CustomRange); + let mut entries: Vec<_> = bb + .as_object() + .into_iter() + .flatten() + .filter(|(k, _)| k.ends_with("].atk")) + .collect(); + entries.sort_by_key(|(k, _)| *k); + s.extra.effects.growing_atk = + Some(entries.into_iter().map(|(_, v)| number(v, 0.)).collect()); + } else { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + s.extra.effects.skill_def_ignore = number(&bb["def_penetrate_fixed"], 0.); + s.extra.effects.force_attack = true; + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/pithst.rs b/crates/engine/src/battle/content/operators/pithst.rs new file mode 100644 index 0000000..14861e4 --- /dev/null +++ b/crates/engine/src/battle/content/operators/pithst.rs @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Pithst: ordered neural/burn/apoptosis attachment after real HP damage. +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "ritualist", + can_hit_fly: true, + ranged: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[Skill { + sp_type: SpType::Attack, + attack_override: true, + ..Skill::duration("skchr_pithst_1") + }], + build, +}; +pub(super) fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.modifiers = [("aspd".into(), number(&bb["attack_speed"], 0.))].into(); + s.combat.profile.priority = crate::battle::targeting::Priority::NotBurst; + let mut p = s.combat.profile; + p.max_targets = number(&bb["attack@max_target"], 1.).floor().max(1.); + s.combat.skill_profile = Some(p); + let normal = number(&t["ep_damage_ratio"], 0.); + s.element_attach = Some(ElementAttach { + normal, + leader: number(&t["ep_damage_ratio_boss"], normal), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/plosis.rs b/crates/engine/src/battle/content/operators/plosis.rs new file mode 100644 index 0000000..c28a1c2 --- /dev/null +++ b/crates/engine/src/battle/content/operators/plosis.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "ringhealer", + ranged: true, + can_hit_fly: false, + physical: false, + projectile: "orb", + projectile_speed: 10., + required_range: None, + skills: &[ + Skill { + id: "skchr_plosis_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: false, + }, + Skill { + id: "skcom_heal_up[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + healing(s, 3.); + module_range(raw, s)?; + s.extra.support.sp_aura = number(&t["sp_recovery_per_sec"], 0.3); + if default { + skill_range(raw, s)?; + s.modifiers = [( + "batPct".into(), + flat_bat(raw, number(&bb["base_attack_time"], 0.)), + )] + .into(); + } else { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/podego.rs b/crates/engine/src/battle/content/operators/podego.rs new file mode 100644 index 0000000..610feb0 --- /dev/null +++ b/crates/engine/src/battle/content/operators/podego.rs @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "slower", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[ + Skill { + id: "skchr_podego_2", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_podego_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let tb = &raw["trait"]["bb"]; + slow_sp(raw, s); + s.extra.normal_status = Some(OnHitStatus { + key: "sluggish", + duration: number(&tb["sluggish"], 0.8), + chance: None, + }); + s.extra.support.support_atk = number(&t["atk"], 0.); + if default { + s.extra.support.zone = Some(Zone { + duration: number(&bb["projectile_delay_time"], 5.), + scale: number(&bb["atk_scale"], 0.), + }); + } else { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + skill_healing(s, 1., 1.); + s.extra.support.auto_heal = true; + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/prove.rs b/crates/engine/src/battle/content/operators/prove.rs new file mode 100644 index 0000000..953d0c9 --- /dev/null +++ b/crates/engine/src/battle/content/operators/prove.rs @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "closerange", + can_hit_fly: true, + ranged: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[ + Skill { + kind: Kind::Passive, + sp_type: SpType::None, + ..Skill::duration("skchr_prove_1") + }, + Skill::duration("skchr_prove_2"), + ], + build, +}; +pub(super) fn build(raw: &Value, default_skill: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.modifiers = { + s.hit = HitHandler::Prove(Hit { + drop: number(&bb["hp_ratio_drop"], 0.), + up: number(&bb["atk_scale_up"], 0.), + prob: number(&t["prob"], 0.), + front_prob: number(&t["prob2"], 0.), + crit_scale: number(&t["atk_scale"], 1.), + }); + if default_skill { + Numbers::new() + } else { + [("atkPct".into(), number(&bb["atk"], 0.))].into() + } + }; + if !default_skill { + s.attack_filter = Some(huntable); + } + Ok(()) +} + +#[derive(Clone, Copy)] +pub(crate) struct Hit { + pub drop: f64, + pub up: f64, + pub prob: f64, + pub front_prob: f64, + pub crit_scale: f64, +} +impl Hit { + pub fn apply( + self, + w: &mut World, + source: Id, + dir: Direction, + q: &mut hit::Request, + rng: &mut Rng, + ) -> Result<(), String> { + let Self { + drop, + up, + prob, + front_prob, + crit_scale, + } = self; + + if drop > 0. && up > 0. { + let u = w.unit_mut(q.hit.target)?; + let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + let ratio = if max > 0. { u.stats.hp / max } else { 0. }; + let lost = (1. - ratio).min(1.).max(0.); + if lost > 0. { + q.damage.amount *= 1. + (lost / drop) * up; + } + } + if q.is_splash || q.tags.iter().any(|t| t == "chain") { + return Ok(()); + } + let home = w.unit(source)?.deployment.tile; + let v = dir.vector(); + let front = [home[0] + v[0], home[1] + v[1]]; + let in_front = Grid::in_bounds(front) + && body::in_range( + w.unit(q.hit.target)?, + &[front[0] as usize * COLS + front[1] as usize], + ); + let p = if in_front { front_prob } else { prob }; + if p > 0. && rng.chance(p) { + q.damage.amount *= crit_scale; + } + Ok(()) + } +} +fn huntable(w: &mut World, id: Id) -> Result { + let u = w.unit_mut(id)?; + let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + Ok((if max > 0. { u.stats.hp / max } else { 0. }) <= 0.8 + 1e-9) +} diff --git a/crates/engine/src/battle/content/operators/reckpr.rs b/crates/engine/src/battle/content/operators/reckpr.rs new file mode 100644 index 0000000..9f77b42 --- /dev/null +++ b/crates/engine/src/battle/content/operators/reckpr.rs @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "physician", + ranged: true, + can_hit_fly: false, + physical: false, + projectile: "orb", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_reckpr_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_reckpr_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let _t1 = talent_at(raw, 1); + let _tm = talent_at(raw, -1); + let _mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_reckpr_1" => Mode::First, + "skchr_reckpr_2" => Mode::Second, + _ => return Err("Unknown selected skill".into()), + }; + healing(s, 1.); + s.extra.support.heal_bonus = Some(HealBonus { + below: number(&tb["hp_ratio"], 0.), + scale: number(&tb["heal_scale"], 1.), + inclusive: false, + }); + if default { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + } else { + skill_healing( + s, + number(&bb["max_target"], 2.), + number(&bb["heal_scale"], 1.), + ); + } + s.extra.advanced = Advanced::Reckpr(Reckpr { + guard: default, + duration: number(&bb["attack@buff_duration"], 10.), + heal: number(&bb["attack@fixed_heal_value"], 0.), + probability: number(&t["prob"], 1.), + sp: number(&t["sp"], 0.), + aspd: number(&t["attack_speed"], 0.), + learn_duration: number(&t["duration"], 8.), + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/shotst.rs b/crates/engine/src/battle/content/operators/shotst.rs new file mode 100644 index 0000000..96012ac --- /dev/null +++ b/crates/engine/src/battle/content/operators/shotst.rs @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "fastshot", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_shotst_2", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_shotst_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + fastshot(raw, s); + s.extra.effects.fly_scale *= number(&talent(raw)["atk_scale"], 1.); + let debuff = Debuff { + key: "skill:shotst_shred", + stat: "defPct", + value: number(&bb["def"], 0.), + duration: number(&bb["duration"], 5.), + strongest: false, + }; + if default { + s.extra.effects.burst = Some(Burst { + grid: crate::battle::operators::parse_range(&raw["rangeGrid"])?, + count: 5, + scale: number(&bb["atk_scale"], 1.), + damage: crate::battle::damage::DamageType::Physical, + status: None, + debuff: Some(debuff), + pull: None, + fly_scale: s.extra.effects.fly_scale, + ground: false, + }); + } else { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + s.extra.effects.skill_debuff = Some(debuff); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/skadi.rs b/crates/engine/src/battle/content/operators/skadi.rs new file mode 100644 index 0000000..f81115c --- /dev/null +++ b/crates/engine/src/battle/content/operators/skadi.rs @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "fearless", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_skadi_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skcom_quickattack[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_skadi_2", + kind: Kind::Duration, + sp_type: SpType::None, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t0 = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tb = &raw["trait"]["bb"]; + s.extra.effects.team = Some(TeamBuff { + key: "talent:skadi_predator", + characters: &[ + "char_263_skadi", + "char_143_ghost", + "char_218_cuttle", + "char_474_glady", + "char_1023_ghost2", + "char_4145_ulpia", + ], + mods: [("atkPct".into(), number(&t0["atk"], 0.))].into(), + }); + s.extra.effects.respawn_delta = number(&t1["respawn_time"], 0.); + if !tb["value"].is_null() || !tb["hp_ratio"].is_null() { + s.extra.effects.revive = Some(Revive { + hp_mul: if !tb["value"].is_null() { + 1. - number(&tb["value"], 0.) + } else { + number(&tb["max_hp"], 0.4) + } + .max(0.05), + aspd: number(&tb["attack_speed"], 0.), + hp_ratio: number(&tb["hp_ratio"], 1.), + }); + } + if !tb["atk_scale"].is_null() { + s.hit = HitHandler::Blocked { + scale: number(&tb["atk_scale"], 1.), + own: false, + inverse: false, + }; + } + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("defPct".into(), number(&bb["def"], 0.)), + ("hpPct".into(), number(&bb["max_hp"], 0.)), + ("aspd".into(), number(&bb["attack_speed"], 0.)), + ] + .into(); + if raw["skill"]["skillId"] == "skchr_skadi_2" { + s.extra.deploy = true; + s.extra.duration = Some(number(&bb["duration"], 20.)); + s.rule_override = Some(crate::battle::skills::Rule::Never); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/skgoat.rs b/crates/engine/src/battle/content/operators/skgoat.rs new file mode 100644 index 0000000..1528de6 --- /dev/null +++ b/crates/engine/src/battle/content/operators/skgoat.rs @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "slower", + can_hit_fly: true, + ranged: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[Skill::duration("skcom_atk_up[2]")], + build, +}; +pub(super) fn build(raw: &Value, _default_skill: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + let tb = &raw["trait"]["bb"]; + s.modifiers = { + s.combat.sluggish = number(&tb["sluggish"], 0.8) + number(&t["sluggish"], 0.); + [("atkPct".into(), number(&bb["atk"], 0.))].into() + }; + s.combat.skill_sluggish = s.combat.sluggish; + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/slbell.rs b/crates/engine/src/battle/content/operators/slbell.rs new file mode 100644 index 0000000..ffc5889 --- /dev/null +++ b/crates/engine/src/battle/content/operators/slbell.rs @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "underminer", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[ + Skill { + id: "skchr_slbell_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_slbell_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + debuffer(raw, s); + let t1 = talent_at(raw, 1); + s.combat.profile.max_targets = number(&t1["attack@max_target"], 1.).floor().max(1.); + s.extra.support.enemy_auras.push(EnemyAura { + key: "talent:weak_fragile", + mods: [("dmgTakenMul".into(), number(&t["damage_scale"], 1.))].into(), + filter: AuraFilter::LowHp(number(&t["hp_ratio"], 0.4)), + period: 0.1, + active_only: false, + growth: None, + }); + let mods = if default { + let mr = number(&bb["magic_resistance"], 0.); + [ + ("defPct".into(), number(&bb["def"], 0.)), + ( + if mr.abs() < 1. { + "resMul".into() + } else { + "resFlat".into() + }, + if mr.abs() < 1. { (1. + mr).max(0.) } else { mr }, + ), + ] + .into() + } else { + let mut p = s.combat.profile; + p.max_targets = number(&bb["attack@max_target"], number(&bb["max_target"], 1.)) + .floor() + .max(1.); + s.combat.skill_profile = Some(p); + [("aspd".into(), number(&bb["attack_speed"], 0.))].into() + }; + s.extra.support.enemy_auras.push(EnemyAura { + key: if default { + "skill:slbell_shred" + } else { + "skill:slbell_aspd" + }, + mods, + filter: AuraFilter::All, + period: 0., + active_only: true, + growth: None, + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/slchan.rs b/crates/engine/src/battle/content/operators/slchan.rs new file mode 100644 index 0000000..96c1922 --- /dev/null +++ b/crates/engine/src/battle/content/operators/slchan.rs @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "SPECIAL", + branch: "hookmaster", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_slchan_2", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "SKILL_RANGE", + attack_override: false, + }, + Skill { + id: "skchr_slchan_1", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + let tb = &raw["trait"]["bb"]; + s.extra.effects.condition = Some(Conditional { + key: "slchan:hunter", + when: Predicate::Unblocked, + mods: [ + ("atkPct".into(), number(&t["atk"], 0.)), + ("defPct".into(), number(&t["def"], 0.)), + ] + .into(), + }); + let pull = PullHit { + force: number(&bb["force"], 1.), + travel_damage: number(&tb["value"], 0.), + distance: number(&tb["dist"], 1.).max(0.01), + }; + if default { + let grid = crate::battle::operators::parse_range(&raw["skill"]["rangeGrid"])?; + s.trigger_range = Some(grid.clone()); + s.extra.effects.burst = Some(Burst { + grid, + count: number(&bb["max_target"], 1.).max(1.) as usize, + scale: number(&bb["atk_scale"], 1.), + damage: crate::battle::damage::DamageType::True, + status: Some(OnHitStatus { + key: "stun", + duration: number(&bb["stun"], 0.), + chance: None, + }), + debuff: None, + pull: Some(pull), + fly_scale: 1., + ground: false, + }); + } else { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + s.combat.skill_damage = Some(crate::battle::damage::DamageType::Physical); + s.extra.effects.skill_pull = Some(PullHit { + travel_damage: 0., + ..pull + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/snakek.rs b/crates/engine/src/battle/content/operators/snakek.rs new file mode 100644 index 0000000..42af890 --- /dev/null +++ b/crates/engine/src/battle/content/operators/snakek.rs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Cuora: shell defence, self regeneration, and blocking module. +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "protector", + can_hit_fly: false, + ranged: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: Some(&[[0, 0]]), + skills: &[ + Skill { + rule: "TAKE_DAMAGE", + attack_override: true, + ..Skill::duration("skchr_snakek_2") + }, + Skill { + rule: "TAKE_DAMAGE", + ..Skill::duration("skcom_def_up[2]") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let mut b = Buff { + key: Some("talent:snakek_def".into()), + mods: [("defPct".into(), number(&talent(raw)["def"], 0.))].into(), + ..Default::default() + }; + b.runtime.persist = true; + s.permanent = Some(b); + s.modifiers = [("defPct".into(), number(&bb["def"], 0.))].into(); + if default { + s.modifiers + .insert("blockCnt".into(), number(&bb["block_cnt"], 0.)); + s.modifiers.insert( + "hpRegenRatio".into(), + number(&bb["hp_recovery_per_sec_by_max_hp_ratio"], 0.), + ); + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + } + let d = number(&raw["trait"]["bb"]["def"], 0.); + if d > 0. { + s.while_blocked = Some(WhileBlocked { + key: "trait:snakek_block", + mods: [("defPct".into(), d)].into(), + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/sunbr.rs b/crates/engine/src/battle/content/operators/sunbr.rs new file mode 100644 index 0000000..c312bc4 --- /dev/null +++ b/crates/engine/src/battle/content/operators/sunbr.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "guardian", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + id: "skchr_sunbr_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_sunbr_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let tb = &raw["trait"]["bb"]; + if number(&t["prob"], 0.) > 0. { + s.extra.effects.crit = Some(Critical { + chance: number(&t["prob"], 0.), + attack_scale: number(&t["atk_scale"], 1.), + damage_scale: 1., + stun: number(&t["stun"], 0.), + }); + } + s.extra.support.heal_bonus = Some(HealBonus { + below: number(&tb["hp_ratio"], 0.), + scale: number(&tb["heal_scale"], 1.), + inclusive: false, + }); + skill_healing( + s, + 1., + if default { + number(&bb["heal_scale"], 1.) + } else { + 1. + }, + ); + skill_range(raw, s)?; + if default { + s.rule_override = Some(crate::battle::skills::Rule::SkillRange); + } else { + let cook = number(&bb["disarm"], 10.).max(0.); + s.extra.duration = Some(cook + number(&raw["skill"]["duration"], 30.).max(0.)); + s.modifiers = [("batPct".into(), number(&bb["base_attack_time"], 0.).max(0.))].into(); + s.extra.support.cook = Some(Cook { + duration: cook, + defence: number(&bb["def"], 0.), + attack: number(&bb["atk"], 0.), + }); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/support.rs b/crates/engine/src/battle/content/operators/support.rs new file mode 100644 index 0000000..84067d0 --- /dev/null +++ b/crates/engine/src/battle/content/operators/support.rs @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Healing, area statuses and damage deferral assembled by individual Kits. +use super::*; +pub(crate) const HP_DRAIN: u64 = 1201; +pub(crate) const PROTEGE_COUNTER: u64 = 1202; +pub(crate) const PLASMA_DRAIN: u64 = 1203; +pub(crate) enum SpChange { + Gain(f64), + Bond(f64), + Clear, + Damaged, +} +#[derive(Default)] +pub(crate) struct State { + pub protege: Option, + pub debt: f64, + pub fragile_scale: f64, + pub next_aura: Vec, + pub next_lavender: f64, + pub next_sp_aura: f64, + pub next_support_aura: f64, + pub next_phalanx: f64, + pub next_forge: f64, + pub next_block_stats: f64, + pub next_reaper: f64, + pub reaper_window: f64, + pub reaper_limit: usize, + pub reaper_accepted: usize, + pub reaper_queue: std::collections::VecDeque, + pub quiet_until: f64, + pub bandage: Option, + pub sp_changes: Vec, +} +#[derive(Default)] +pub(crate) struct Support { + pub auto_heal: bool, + pub sp_period: Option, + pub sp_duration: Option, + pub sp_profession: Option<&'static str>, + pub radial_push: Option, + pub reveal: bool, + pub effect_push: bool, + pub pull_unblocked: bool, + pub heal_bonus: Option, + pub received_heal: Option, + pub top_heal: f64, + pub incantation: f64, + pub protege: Option, + pub reaper: f64, + pub overflow: f64, + pub skill_heal: f64, + pub skill_drain_heal: f64, + pub peaks: Vec<[f64; 2]>, + pub cook: Option, + pub lavender: f64, + pub sp_aura: f64, + pub support_atk: f64, + pub sp_near: f64, + pub zone: Option, + pub quiet: Option, + pub sluggish: Option<[f64; 2]>, + pub weaken: Option<[f64; 2]>, + pub enemy_auras: Vec, + pub phalanx: Option, + pub push: Option, + pub inward: Option, + pub heavy_penetration: Option<[f64; 2]>, + pub refund: f64, + pub death_sp: Option<[f64; 2]>, + pub bandage: Option, + pub plasma: Option, + pub deferred: Option, + pub block_stats: Option<[f64; 4]>, + pub forge: Option, + pub elite_scale: Option, +} +#[derive(Clone, Copy)] +pub(crate) struct HealBonus { + pub below: f64, + pub scale: f64, + pub inclusive: bool, +} +pub(crate) struct ReceivedHeal { + pub below: f64, + pub normal: f64, + pub low: f64, +} +pub(crate) struct Protege { + pub taunt: f64, + pub scale: f64, +} +pub(crate) struct Cook { + pub duration: f64, + pub defence: f64, + pub attack: f64, +} +pub(crate) struct Zone { + pub duration: f64, + pub scale: f64, +} +pub(crate) struct Quiet { + pub duration: f64, + pub count: usize, +} +pub(crate) struct Plasma { + pub duration: f64, + pub interval: f64, + pub ratio: f64, + pub attack: f64, +} +pub(crate) struct Deferred { + pub resistance: f64, + pub duration: f64, + pub interval: f64, +} +pub(crate) struct Phalanx { + pub guard: Numbers, + pub keep: Numbers, + pub taunt: f64, + pub aura: StatAura, + pub burst: f64, +} +pub(crate) struct PushCast { + pub grid: Vec<[i32; 2]>, + pub force: f64, + pub direct: f64, + pub wall: f64, + pub collision: f64, +} +pub(crate) enum AuraFilter { + All, + Normal, + LowHp(f64), +} +pub(crate) struct EnemyAura { + pub key: &'static str, + pub mods: Numbers, + pub filter: AuraFilter, + pub period: f64, + pub active_only: bool, + pub growth: Option<[f64; 2]>, +} +pub(crate) fn healing(s: &mut Spec, count: f64) { + s.combat.heal = true; + s.combat.projectile = None; + s.combat.profile.heal = Some(crate::battle::search::Heal { + multi: count > 1., + count, + hp_at_most: 1., + element_heal: false, + }); + s.combat.profile.heal_attack = true; +} +pub(crate) fn skill_healing(s: &mut Spec, count: f64, scale: f64) { + s.combat.skill_heal = true; + s.combat.skill_heal_scale = scale; + let mut p = s.combat.profile; + p.heal = Some(crate::battle::search::Heal { + multi: count > 1., + count, + hp_at_most: 1., + element_heal: false, + }); + p.heal_attack = true; + s.combat.skill_profile = Some(p); +} +pub(super) fn slow_sp(raw: &Value, s: &mut Spec) { + s.extra.support.sp_near = raw["talents"] + .as_array() + .into_iter() + .flatten() + .filter(|t| t["hidden"] == true) + .map(|t| number(&t["bb"]["sp_recovery_per_sec"], 0.)) + .sum(); +} +pub(super) fn debuffer(raw: &Value, s: &mut Spec) { + let tb = &raw["trait"]["bb"]; + if !tb["atk"].is_null() && !tb["duration"].is_null() { + s.extra.support.weaken = Some([number(&tb["atk"], 0.).abs(), number(&tb["duration"], 2.)]); + } +} diff --git a/crates/engine/src/battle/content/operators/surtr.rs b/crates/engine/src/battle/content/operators/surtr.rs new file mode 100644 index 0000000..4cd63e6 --- /dev/null +++ b/crates/engine/src/battle/content/operators/surtr.rs @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "artsfghter", + ranged: false, + can_hit_fly: false, + physical: false, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_surtr_3", + kind: Kind::Toggle, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_surtr_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_surtr_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let _tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_surtr_1" => Mode::First, + "skchr_surtr_2" => Mode::Second, + "skchr_surtr_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.combat.damage = crate::battle::damage::DamageType::Arts; + skill_range(raw, s)?; + if raw["skill"]["trigger"]["customRangeGrid"].is_array() { + s.trigger_range = Some(crate::battle::operators::parse_range( + &raw["skill"]["trigger"]["customRangeGrid"], + )?); + } + s.extra.effects.permanent.push(persistent( + "surtr:magma", + [( + "resIgnoreFlat".into(), + number(&t["magic_resist_penetrate_fixed"], 0.), + )] + .into(), + )); + if mode == Mode::First { + s.combat.skill_scale = number(&bb["atk_scale"], 1.); + } else { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + let max = number(&bb["max_hp"], 0.); + if max != 0. { + s.modifiers + .insert(if max.abs() > 5. { "hpFlat" } else { "hpPct" }.into(), max); + } + let mut p = s.combat.profile; + p.max_targets = number(&bb["attack@max_target"], 1.); + s.combat.skill_profile = Some(p); + } + if mode != Mode::First { + s.extra.advanced_range_extend = number(&bb["ability_range_forward_extend"], 0.) + .round() + .max(0.) as u32; + } + s.extra.advanced = Advanced::Surtr(Surtr { + mode, + withdraw: number(&t1["surtr_t_2[withdraw].interval"], 8.), + drain_interval: number(&bb["interval"], 0.2).max(0.05), + drain_peak: number(&bb["hp_ratio"], 0.), + drain_ramp: number(&bb["duration"], 60.).max(0.1), + solo: number(&bb["attack@surtr_s_2[critical].atk_scale"], 1.), + module_aspd: number(&tb["attack_speed"], 0.), + module_fragile: number(&tb["damage_scale"], 1.) - 1., + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/svrash.rs b/crates/engine/src/battle/content/operators/svrash.rs new file mode 100644 index 0000000..8012592 --- /dev/null +++ b/crates/engine/src/battle/content/operators/svrash.rs @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "lord", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[ + Skill { + id: "skchr_svrash_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_svrash_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_svrash_2", + kind: Kind::Toggle, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let tb = &raw["trait"]["bb"]; + s.permanent = Some(persistent( + "svrash:t1", + [("atkPct".into(), number(&t["atk"], 0.1))].into(), + )); + s.extra.effects.team = Some(TeamBuff { + key: "svrash:leader", + characters: &[], + mods: [( + "redeployMul".into(), + (1. + number(&t["respawn_time"], -0.1)).max(0.), + )] + .into(), + }); + s.extra.support.reveal = true; + s.extra.lord = Some(Lord { + scale: number(&tb["atk_scale"], 0.8), + arts: number(&tb["atk_scale_m"], 0.), + skill_full: default, + }); + s.extra.effects.lord_skill_scale = number(&bb["atk_scale"], 1.); + if number(&tb["atk_scale_m"], 0.) > 0. { + s.extra.support.elite_scale = Some(number(&t["atk_scale"], 1.)); + } + skill_range(raw, s)?; + if default { + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ("defPct".into(), number(&bb["def"], 0.)), + ] + .into(); + let mut p = s.combat.profile; + p.max_targets = number(&bb["attack@max_target"], 4.).floor().max(1.); + s.combat.skill_profile = Some(p); + s.combat.skill_direct = true; + } else if raw["skill"]["skillId"] == "skchr_svrash_1" { + s.combat.skill_scale = number(&bb["atk_scale"], 2.05); + } else { + s.modifiers = [ + ("defPct".into(), number(&bb["def"], 0.)), + ( + "hpRegenRatio".into(), + number(&bb["hp_recovery_per_sec_by_max_hp_ratio"], 0.), + ), + ] + .into(); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/swire.rs b/crates/engine/src/battle/content/operators/swire.rs new file mode 100644 index 0000000..7bcaf26 --- /dev/null +++ b/crates/engine/src/battle/content/operators/swire.rs @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Swire: melee-operator ATK aura, skill amplification and expanded talent range. +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "instructor", + can_hit_fly: false, + ranged: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + sp_type: SpType::Attack, + ..Skill::duration("skchr_swire_2") + }, + Skill { + rule: "SKILL_RANGE", + ..Skill::duration("skchr_swire_1") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = raw["talents"] + .as_array() + .into_iter() + .flatten() + .find(|t| t["index"] == 0) + .ok_or("Missing Swire talent")?; + let grid = if t["rangeGrid"].is_null() { + vec![ + [1, -1], + [1, 0], + [1, 1], + [0, -1], + [0, 0], + [0, 1], + [-1, -1], + [-1, 0], + [-1, 1], + ] + } else { + crate::battle::operators::parse_range(&t["rangeGrid"])? + }; + let skill_grid = if number(&bb["talent_range_flag"], 0.) > 0. { + Some(crate::battle::operators::parse_range( + &raw["skill"]["rangeGrid"], + )?) + } else { + None + }; + if !default { + s.trigger_range = Some(crate::battle::operators::parse_range( + &raw["skill"]["rangeGrid"], + )?); + } + s.aura = Some(Aura { + key: "talent:swire_guide", + grid, + skill_grid, + atk: number(&t["bb"]["atk"], 0.), + skill_scale: number(&bb["talent_scale"], 1.), + }); + if default { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + } + s.hit = HitHandler::Blocked { + scale: number(&raw["trait"]["bb"]["atk_scale"], 1.2), + own: true, + inverse: true, + }; + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/tactics.rs b/crates/engine/src/battle/content/operators/tactics.rs new file mode 100644 index 0000000..d741a12 --- /dev/null +++ b/crates/engine/src/battle/content/operators/tactics.rs @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Typed parameters for operator-specific healing and tactical callbacks. +use super::*; +use crate::battle::runtime::kits; + +#[derive(Default)] +pub(crate) struct TacticalState { + pub next: [f64; 5], + state: OperatorState, +} +// Each declaration binds the parameters, behavior and optional mutable state. +// State reset/redeployment policies remain explicit in TacticalState::reset. +// Brackets contain the optional immutable state accessor. +macro_rules! operator_tactics { + ($( $variant:ident($module:ident::$parameters:ident $(, $state:ident, [$($get:ident)?], $get_mut:ident, $error:literal)?); )*) => { + #[derive(Default)] + pub(crate) enum Tactics { + #[default] + None, + $( $variant(kits::$module::$parameters), )* + } + + impl Tactics { + pub(crate) fn behavior(&self) -> Option<&dyn kits::dispatch::Behavior> { + match self { + Self::None => None, + $( Self::$variant(kit) => Some(kit), )* + } + } + } + + #[derive(Default)] + enum OperatorState { + #[default] + None, + $( $( $variant(kits::$module::$state), )? )* + } + + impl TacticalState { + $( $( + $( + pub fn $get(&self) -> Result<&kits::$module::$state, String> { + match &self.state { + OperatorState::$variant(state) => Ok(state), + _ => Err($error.into()), + } + } + )? + pub fn $get_mut(&mut self) -> Result<&mut kits::$module::$state, String> { + match &mut self.state { + OperatorState::$variant(state) => Ok(state), + _ => Err($error.into()), + } + } + )? )* + } + }; +} +operator_tactics! { + Clemnt(clemnt::Clemnt, State, [clemnt], clemnt_mut, "Invalid Clement state"); + PreparedSummon(prepared_summon::PreparedSummon, State, [prepared_summon], prepared_summon_mut, "Missing prepared summon state"); + Yanyou(yanyou::Yanyou, State, [yanyou], yanyou_mut, "Missing yanyou state"); + Mlyss(mlyss::Mlyss, State, [mlyss], mlyss_mut, "Invalid mlyss kit state"); + Manifold(manifold::Manifold, State, [manifold], manifold_mut, "Missing manifold state"); + Vigil(vigil::Vigil, State, [vigil], vigil_mut, "Invalid vigil kit state"); + Wolf(wolf::Wolf, State, [wolf], wolf_mut, "Missing wolf state"); + Etlchi(etlchi::Etlchi, State, [etlchi], etlchi_mut, "Invalid etlchi kit state"); + Whitw2(whitw2::Whitw2, State, [whitw2], whitw2_mut, "Invalid whitw2 kit state"); + Swire2(swire2::Swire2, State, [swire2], swire2_mut, "Invalid swire2 kit state"); + Ulpia(ulpia::Ulpia, State, [], ulpia_mut, "Invalid ulpia kit state"); + Siege2(siege2::Siege2, State, [siege2], siege2_mut, "Invalid siege2 kit state"); + Nearl2(nearl2::Nearl2, State, [nearl2], nearl2_mut, "Invalid nearl2 kit state"); + Lemuen(lemuen::Lemuen, State, [lemuen], lemuen_mut, "Invalid lemuen kit state"); + Kazema(kazema::Kazema, State, [kazema], kazema_mut, "Invalid kazema kit state"); + Dusk(dusk::Dusk, State, [dusk], dusk_mut, "Invalid dusk kit state"); + Yu(yu::Yu, State, [yu], yu_mut, "Invalid yu kit state"); + Thorn2(thorn2::Thorn2, State, [thorn2], thorn2_mut, "Invalid thorn2 kit state"); + Angel2(angel2::Angel2, State, [angel2], angel2_mut, "Invalid angel2 kit state"); + Svash2(svash2::Svash2, State, [svash2], svash2_mut, "Invalid svash2 kit state"); + Skadi2(skadi2::Skadi2, State, [skadi2], skadi2_mut, "Invalid skadi2 kit state"); + Sbell2(sbell2::Sbell2, State, [sbell2], sbell2_mut, "Invalid sbell2 kit state"); + Reed2(reed2::Reed2, State, [], reed2_mut, "Invalid reed2 kit state"); + Rosmon(rosmon::Rosmon); + Caper(caper::Caper, State, [caper], caper_mut, "Invalid caper kit state"); + Indigo(indigo::Indigo, State, [indigo], indigo_mut, "Invalid indigo kit state"); + Silent(silent::Silent); + Rockr(rockr::Rockr, State, [rockr], rockr_mut, "Invalid rockr kit state"); + Tippi(tippi::Tippi, State, [tippi], tippi_mut, "Invalid tippi kit state"); + Malist(malist::Malist, State, [malist], malist_mut, "Invalid malist kit state"); + Vulpis(vulpis::Vulpis, State, [vulpis], vulpis_mut, "Invalid vulpis kit state"); + Kjera(kjera::Kjera, State, [kjera], kjera_mut, "Invalid kjera kit state"); + Ines(ines::Ines, State, [ines], ines_mut, "Invalid ines kit state"); + Cetsyr(cetsyr::Cetsyr, State, [cetsyr], cetsyr_mut, "Invalid cetsyr kit state"); + Excu2(excu2::Excu2, State, [excu2], excu2_mut, "Invalid excu2 kit state"); + Titi(titi::Titi, State, [titi], titi_mut, "Invalid titi kit state"); + Blaze2(blaze2::Blaze2, State, [blaze2], blaze2_mut, "Invalid blaze2 kit state"); + Horn(horn::Horn, State, [horn], horn_mut, "Invalid horn kit state"); + Ghost2(ghost2::Ghost2, State, [ghost2], ghost2_mut, "Invalid ghost2 kit state"); + Nymph(nymph::Nymph); + Cello(cello::Cello, State, [cello], cello_mut, "Invalid cello kit state"); + Halo2(halo2::Halo2, State, [halo2], halo2_mut, "Invalid halo2 kit state"); + Blkkgt(blkkgt::Blkkgt, State, [blkkgt], blkkgt_mut, "Invalid blkkgt kit state"); + Agoat2(agoat2::Agoat2, State, [agoat2], agoat2_mut, "Invalid agoat2 kit state"); + Papyrs(papyrs::Papyrs, State, [papyrs], papyrs_mut, "Invalid papyrs kit state"); + Tinman(tinman::Tinman, State, [tinman], tinman_mut, "Invalid tinman kit state"); + Philae(philae::Philae, State, [philae], philae_mut, "Invalid philae kit state"); + Snhunt(snhunt::Snhunt, State, [snhunt], snhunt_mut, "Invalid snhunt kit state"); + Blemsh(blemsh::Blemsh, State, [blemsh], blemsh_mut, "Invalid blemsh kit state"); + Archet(archet::Archet, State, [archet], archet_mut, "Invalid archet kit state"); + Rmixer(rmixer::Rmixer, State, [rmixer], rmixer_mut, "Invalid rmixer kit state"); + Texas2(texas2::Texas2, State, [texas2], texas2_mut, "Invalid texas2 kit state"); + Demkni(demkni::Demkni, State, [demkni], demkni_mut, "Invalid demkni kit state"); + Mlynar(mlynar::Mlynar, State, [mlynar], mlynar_mut, "Invalid mlynar kit state"); + Sntlla(sntlla::Sntlla, State, [sntlla], sntlla_mut, "Invalid sntlla kit state"); + Pasngr(pasngr::Pasngr); + Qiubai(qiubai::Qiubai, State, [qiubai], qiubai_mut, "Invalid qiubai kit state"); + Pepe(pepe::Pepe, State, [pepe], pepe_mut, "Invalid pepe kit state"); + Lumen(lumen::Lumen, State, [lumen], lumen_mut, "Invalid lumen kit state"); +} +pub(crate) fn n(v: &Value, key: &str, default: f64) -> f64 { + number(&v[key], default) +} +pub(crate) fn suffix_number(v: &Value, key: &str, default: f64) -> f64 { + v.as_object() + .and_then(|o| { + o.get(key).or_else(|| { + o.iter() + .find(|(k, _)| k.ends_with(&format!(".{key}"))) + .map(|(_, v)| v) + }) + }) + .map(|v| number(v, default)) + .unwrap_or(default) +} +pub(crate) fn tactical_mode(raw: &Value) -> Result { + match raw["skill"]["skillId"] + .as_str() + .unwrap_or("") + .rsplit('_') + .next() + .unwrap_or("") + { + "1" => Ok(Mode::First), + "2" => Ok(Mode::Second), + "3" => Ok(Mode::Third), + // Shared quick-attack skill is the first skill of 寒檀. + "quickattack[3]" => Ok(Mode::First), + _ => Err("Unknown tactical operator skill".into()), + } +} +pub(crate) fn tactical_grid(v: &Value, box_fallback: bool) -> Result, String> { + if v.as_array().is_some_and(|a| !a.is_empty()) { + return crate::battle::operators::parse_range(v); + } + Ok(if box_fallback { + (-1..=1) + .flat_map(|r| (-1..=1).map(move |c| [r, c])) + .collect() + } else { + vec![[0, 0]] + }) +} + +impl TacticalState { + pub(crate) fn dollkeeper( + &self, + ) -> Result<&crate::battle::runtime::kits::dollkeeper::State, String> { + match &self.state { + OperatorState::Ghost2(s) => Ok(&s.dollkeeper), + OperatorState::Kazema(s) => Ok(&s.dollkeeper), + _ => Err("Missing dollkeeper state".into()), + } + } + pub(crate) fn dollkeeper_mut( + &mut self, + ) -> Result<&mut crate::battle::runtime::kits::dollkeeper::State, String> { + match &mut self.state { + OperatorState::Ghost2(s) => Ok(&mut s.dollkeeper), + OperatorState::Kazema(s) => Ok(&mut s.dollkeeper), + _ => Err("Missing dollkeeper state".into()), + } + } + + pub fn reset(&mut self, tactics: &Tactics) { + use crate::battle::runtime::kits; + let state = match tactics { + Tactics::PreparedSummon(_) => { + let previous = match &self.state { + OperatorState::PreparedSummon(previous) => Some(previous), + _ => None, + }; + OperatorState::PreparedSummon(kits::prepared_summon::State::redeployed(previous)) + } + Tactics::Mlyss(_) => OperatorState::Mlyss( + crate::battle::runtime::kits::mlyss::State::redeployed(match &self.state { + OperatorState::Mlyss(previous) => Some(previous), + _ => None, + }), + ), + Tactics::Yanyou(_) => OperatorState::Yanyou(Default::default()), + Tactics::Manifold(_) => OperatorState::Manifold(Default::default()), + Tactics::Vigil(_) => OperatorState::Vigil(Default::default()), + Tactics::Wolf(_) => OperatorState::Wolf(match &self.state { + OperatorState::Wolf(previous) => { + crate::battle::runtime::kits::wolf::State::redeployed(previous) + } + _ => Default::default(), + }), + Tactics::Etlchi(_) => OperatorState::Etlchi(Default::default()), + Tactics::Whitw2(_) => OperatorState::Whitw2(Default::default()), + Tactics::Swire2(_) => OperatorState::Swire2( + crate::battle::runtime::kits::swire2::State::redeployed(match &self.state { + OperatorState::Swire2(previous) => Some(previous), + _ => None, + }), + ), + Tactics::Ulpia(_) => OperatorState::Ulpia(Default::default()), + Tactics::Siege2(_) => OperatorState::Siege2( + crate::battle::runtime::kits::siege2::State::redeployed(match &self.state { + OperatorState::Siege2(previous) => Some(previous), + _ => None, + }), + ), + Tactics::Nearl2(_) => OperatorState::Nearl2(Default::default()), + Tactics::Lemuen(_) => OperatorState::Lemuen(Default::default()), + Tactics::Kazema(_) => { + OperatorState::Kazema(kits::kazema::State::redeployed(self.kazema().ok())) + } + Tactics::Dusk(_) => OperatorState::Dusk(Default::default()), + Tactics::Yu(_) => OperatorState::Yu(kits::yu::State::redeployed(self.yu().ok())), + Tactics::Thorn2(_) => { + OperatorState::Thorn2(kits::thorn2::State::redeployed(self.thorn2().ok())) + } + Tactics::Angel2(_) => OperatorState::Angel2(Default::default()), + Tactics::Svash2(_) => { + OperatorState::Svash2(kits::svash2::State::redeployed(self.svash2().ok())) + } + Tactics::Skadi2(_) => { + OperatorState::Skadi2(kits::skadi2::State::redeployed(self.skadi2().ok())) + } + Tactics::Sbell2(_) => OperatorState::Sbell2(Default::default()), + Tactics::Reed2(_) => OperatorState::Reed2(Default::default()), + Tactics::Caper(_) => OperatorState::Caper(Default::default()), + Tactics::Indigo(_) => OperatorState::Indigo(Default::default()), + Tactics::Rockr(_) => OperatorState::Rockr(Default::default()), + Tactics::Tippi(_) => OperatorState::Tippi(Default::default()), + Tactics::Malist(_) => OperatorState::Malist(Default::default()), + Tactics::Vulpis(_) => { + OperatorState::Vulpis(kits::vulpis::State::redeployed(self.vulpis().ok())) + } + Tactics::Kjera(_) => OperatorState::Kjera(Default::default()), + Tactics::Ines(_) => { + OperatorState::Ines(kits::ines::State::redeployed(self.ines().ok())) + } + Tactics::Cetsyr(_) => { + OperatorState::Cetsyr(kits::cetsyr::State::redeployed(self.cetsyr().ok())) + } + Tactics::Excu2(_) => OperatorState::Excu2(Default::default()), + Tactics::Titi(_) => { + OperatorState::Titi(kits::titi::State::redeployed(self.titi().ok())) + } + Tactics::Blaze2(_) => OperatorState::Blaze2(Default::default()), + Tactics::Horn(_) => { + OperatorState::Horn(kits::horn::State::redeployed(self.horn().ok())) + } + Tactics::Ghost2(_) => OperatorState::Ghost2(Default::default()), + Tactics::Cello(_) => { + OperatorState::Cello(kits::cello::State::redeployed(self.cello().ok())) + } + Tactics::Halo2(_) => { + OperatorState::Halo2(kits::halo2::State::redeployed(self.halo2().ok())) + } + Tactics::Blkkgt(_) => { + OperatorState::Blkkgt(kits::blkkgt::State::redeployed(self.blkkgt().ok())) + } + Tactics::Agoat2(_) => { + OperatorState::Agoat2(kits::agoat2::State::redeployed(self.agoat2().ok())) + } + + Tactics::Blemsh(_) => OperatorState::Blemsh(Default::default()), + Tactics::Demkni(_) => OperatorState::Demkni(Default::default()), + Tactics::Papyrs(_) => OperatorState::Papyrs(Default::default()), + Tactics::Tinman(_) => { + OperatorState::Tinman(kits::tinman::State::redeployed(self.tinman().ok())) + } + Tactics::Philae(_) => OperatorState::Philae(Default::default()), + Tactics::Snhunt(p) => OperatorState::Snhunt(kits::snhunt::State::deployed(p)), + Tactics::Archet(_) => { + OperatorState::Archet(kits::archet::State::redeployed(self.archet().ok())) + } + Tactics::Rmixer(_) => OperatorState::Rmixer(Default::default()), + Tactics::Clemnt(_) => OperatorState::Clemnt(Default::default()), + Tactics::Texas2(_) => { + OperatorState::Texas2(kits::texas2::State::redeployed(self.texas2().ok())) + } + Tactics::Mlynar(p) => OperatorState::Mlynar(kits::mlynar::State::deployed(p)), + Tactics::Sntlla(_) => OperatorState::Sntlla(Default::default()), + Tactics::Qiubai(_) => OperatorState::Qiubai(Default::default()), + Tactics::Pepe(_) => { + OperatorState::Pepe(kits::pepe::State::redeployed(self.pepe().ok())) + } + Tactics::Lumen(_) => OperatorState::Lumen(Default::default()), + _ => OperatorState::None, + }; + *self = Self { + next: self.next, + state, + }; + } +} diff --git a/crates/engine/src/battle/content/operators/texas.rs b/crates/engine/src/battle/content/operators/texas.rs new file mode 100644 index 0000000..ceccbaa --- /dev/null +++ b/crates/engine/src/battle/content/operators/texas.rs @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Texas: battle-start DP, instant charge, and two-hit sword rain. +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "PIONEER", + branch: "pioneer", + can_hit_fly: false, + ranged: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + kind: Kind::Instant, + rule: "SKILL_RANGE", + ..Skill::duration("skchr_texas_2") + }, + Skill { + kind: Kind::Instant, + ..Skill::duration("skcom_charge_cost[3]") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default_skill: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + s.initial_dp = number(&talent(raw)["cost"], 0.).max(0.); + let area = if default_skill { + let grid = crate::battle::operators::parse_range(&raw["skill"]["rangeGrid"])?; + s.trigger_range = Some(grid.clone()); + Some(AreaCast { + grid, + scale: number(&bb["atk_scale"], 0.), + hits: 2, + stun: number(&bb["stun"], 0.), + }) + } else { + s.rule_override = Some(crate::battle::skills::Rule::SpFull); + None + }; + s.skill_start = Some(SkillStart { + dp: number(&bb["cost"], 0.), + area, + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/udflow.rs b/crates/engine/src/battle/content/operators/udflow.rs new file mode 100644 index 0000000..17fb13f --- /dev/null +++ b/crates/engine/src/battle/content/operators/udflow.rs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "shotprotector", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[ + Skill { + rule: "ACTIVE_RANGE", + attack_override: true, + ..Skill::duration("skchr_udflow_2") + }, + Skill { + rule: "TAKE_DAMAGE", + ..Skill::duration("skchr_udflow_1") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.extra.dot = Some(Dot { + duration: number(&t["duration"], 0.), + interval: number(&t["interval"], 1.), + amount: number(&t["damage"], 0.), + sea: number(&t["damage_seamonster"], number(&t["damage"], 0.) * 2.), + }); + s.extra.reveal = raw["isGolden"] == true && !raw["module"].is_null(); + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + if default { + s.modifiers + .insert("aspd".into(), number(&bb["attack_speed"], 0.)); + let grid = crate::battle::operators::parse_range(&raw["skill"]["rangeGrid"])?; + s.trigger_range = Some(grid.clone()); + s.extra.skill_range = Some(grid); + let mut p = s.combat.profile; + p.max_targets = number(&bb["attack@max_target"], 1.).max(1.); + s.combat.skill_profile = Some(p); + s.extra.skill_status = Some(OnHitStatus { + key: "sluggish", + duration: number(&bb["attack@sluggish"], 1.), + chance: None, + }); + } else { + s.modifiers.insert("defPct".into(), number(&bb["def"], 0.)); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/utage.rs b/crates/engine/src/battle/content/operators/utage.rs new file mode 100644 index 0000000..4299149 --- /dev/null +++ b/crates/engine/src/battle/content/operators/utage.rs @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "musha", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill { + sp_type: SpType::None, + ..Skill::duration("skchr_utage_2") + }, + Skill { + attack_override: true, + ..Skill::duration("skchr_utage_1") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.extra.no_heal = true; + s.extra.self_heal = number(&raw["trait"]["bb"]["value"], 50.); + s.extra.hp_speed = Some(HpSpeed { + maximum: number(&t["min_attack_speed"], 0.), + minimum: number(&t["min_hp_ratio"], 0.), + protect: number(&t["damage_resistance"], 0.), + below: number(&t["hp_ratio"], 0.), + }); + if default { + s.extra.deploy = true; + s.extra.duration = Some(number(&bb["duration"], 0.)); + s.extra.hp_loss = number(&bb["hp_ratio"], 0.); + s.extra.skill_arts = true; + s.rule_override = Some(crate::battle::skills::Rule::Never); + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + } else { + s.modifiers = [ + ("defPct".into(), number(&bb["def"], 0.)), + ( + "hpRegenRatio".into(), + number(&bb["hp_recovery_per_sec_by_max_hp_ratio"], 0.), + ), + ("blockCnt".into(), -99.), + ] + .into(); + s.extra.release_on_start = true; + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/vendla.rs b/crates/engine/src/battle/content/operators/vendla.rs new file mode 100644 index 0000000..ac53935 --- /dev/null +++ b/crates/engine/src/battle/content/operators/vendla.rs @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "incantationmedic", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[ + Skill { + id: "skchr_vendla_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skcom_magic_rage[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let tb = &raw["trait"]["bb"]; + s.extra.support.incantation = number(&tb["scale"], 0.5); + s.extra.support.top_heal = number(&t["heal_scale"], 1.); + if default { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + s.extra.support.protege = Some(Protege { + taunt: number(&bb["taunt_level"], 1.), + scale: number(&bb["atk_scale"], 0.), + }); + } else { + s.modifiers = [("aspd".into(), number(&bb["attack_speed"], 0.))].into(); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/vigna.rs b/crates/engine/src/battle/content/operators/vigna.rs new file mode 100644 index 0000000..a04d50a --- /dev/null +++ b/crates/engine/src/battle/content/operators/vigna.rs @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Vigna's one-attack ATK proc and low-HP module multiplier. +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "PIONEER", + branch: "charger", + can_hit_fly: false, + ranged: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[ + Skill::duration("skchr_vigna_2"), + Skill::duration("skchr_vigna_1"), + ], + build, +}; +pub(super) fn build(raw: &Value, _default_skill: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + let tb = &raw["trait"]["bb"]; + let bat = number(&raw["stats"]["bat"], 1.); + let bat = if bat == 0. { 1. } else { bat }; + s.modifiers = [ + ("atkPct".into(), number(&bb["atk"], 0.)), + ( + "batPct".into(), + (number(&bb["base_attack_time"], 0.) / bat).max(-0.9), + ), + ] + .into(); + s.attack_proc = Some(AttackProc { + key: "vigna:proc", + normal: number(&t["prob1"], 0.), + active: number(&t["prob2"], 0.), + atk: number(&t["atk"], 0.), + }); + s.dp_on_kill = number(&tb["cost"], 1.); + if !tb["hp_ratio"].is_null() { + s.hit = HitHandler::Vigna(Hit { + below: number(&tb["hp_ratio"], 0.), + scale: number(&tb["atk_scale"], 1.), + }); + } + Ok(()) +} +#[derive(Clone, Copy)] +pub(crate) struct Hit { + pub below: f64, + pub scale: f64, +} +impl Hit { + pub fn apply(self, w: &mut World, q: &mut hit::Request) -> Result<(), String> { + let u = w.unit_mut(q.hit.target)?; + let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + if (if max > 0. { u.stats.hp / max } else { 0. }) < self.below { + q.damage.amount *= self.scale; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/content/operators/whitew.rs b/crates/engine/src/battle/content/operators/whitew.rs new file mode 100644 index 0000000..b9584d1 --- /dev/null +++ b/crates/engine/src/battle/content/operators/whitew.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "lord", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[ + Skill { + sp_type: SpType::Attack, + attack_override: true, + ..Skill::duration("skchr_whitew_2") + }, + Skill { + kind: Kind::Toggle, + sp_type: SpType::Attack, + ..Skill::duration("skchr_whitew_1") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + if default { + let mut p = s.combat.profile; + p.max_targets = 2.; + s.combat.skill_profile = Some(p); + s.combat.skill_damage = Some(crate::battle::damage::DamageType::Arts); + } else { + s.modifiers + .insert("dodgePhys".into(), number(&bb["prob"], 0.)); + } + s.extra.lord = Some(Lord { + scale: number(&tb["atk_scale"], 0.8), + arts: number(&tb["atk_scale_m"], 0.), + skill_full: default, + }); + s.extra.normal_status = Some(OnHitStatus { + key: "silence", + duration: number(&talent(raw)["duration"], 0.), + chance: None, + }); + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/wildmn.rs b/crates/engine/src/battle/content/operators/wildmn.rs new file mode 100644 index 0000000..c039acd --- /dev/null +++ b/crates/engine/src/battle/content/operators/wildmn.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "PIONEER", + branch: "charger", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_wildmn_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_wildmn_1", + kind: Kind::Duration, + sp_type: SpType::None, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.dp_on_kill = number(&raw["trait"]["bb"]["cost"], 1.); + s.extra.effects.cost_cut = Some(CostCut { + amount: number(&t["value"], -1.).abs(), + cap: number(&t["max_stack_cnt"], 1.), + every: number(&t["flag"], 0.) == 1., + }); + if default { + s.modifiers = [("atkPct".into(), number(&bb["atk"], 0.))].into(); + skill_range(raw, s)?; + s.extra.effects.skill_push = Some(number(&bb["attack@force"], 1.)); + } else { + s.extra.deploy = true; + s.extra.duration = Some(number(&raw["skill"]["duration"], 0.)); + s.rule_override = Some(crate::battle::skills::Rule::Never); + s.modifiers = [("aspd".into(), number(&bb["attack_speed"], 0.))].into(); + } + Ok(()) +} diff --git a/crates/engine/src/battle/content/operators/yak.rs b/crates/engine/src/battle/content/operators/yak.rs new file mode 100644 index 0000000..2c710f7 --- /dev/null +++ b/crates/engine/src/battle/content/operators/yak.rs @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(super) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "protector", + can_hit_fly: false, + ranged: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: Some(&[[0, 0]]), + skills: &[ + Skill { + rule: "TAKE_DAMAGE", + ..Skill::duration("skchr_yak_2") + }, + Skill { + rule: "TAKE_DAMAGE", + ..Skill::duration("skchr_yak_1") + }, + ], + build, +}; +pub(super) fn build(raw: &Value, default_skill: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent(raw); + s.modifiers = { + let mut buff = Buff { + key: Some("talent:yak".into()), + mods: [("resFlat".into(), number(&t["magic_resistance"], 0.))].into(), + ..Default::default() + }; + buff.runtime.persist = true; + s.permanent = Some(buff); + if !default_skill { + [ + ("hpPct".into(), number(&bb["max_hp"], 0.)), + ("hpRegen".into(), number(&bb["hp_recovery_per_sec"], 0.)), + ] + .into() + } else { + [ + ("hpPct".into(), number(&bb["max_hp"], 0.)), + ("defPct".into(), number(&bb["def"], 0.)), + ("resMul".into(), 1. + number(&bb["magic_resistance"], 0.)), + ] + .into() + } + }; + Ok(()) +} diff --git a/crates/engine/src/battle/damage.rs b/crates/engine/src/battle/damage.rs index 552ecf0..da94f48 100644 --- a/crates/engine/src/battle/damage.rs +++ b/crates/engine/src/battle/damage.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later // Stronghold Protocol attack/calculation.js. Pure arithmetic only: no injury hooks or HP mutation. -use super::stats::Stats; +use super::stats::{Stat, Stats}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DamageType { Physical, @@ -47,11 +47,11 @@ pub fn mitigate( ) -> f64 { match kind { DamageType::Physical => { - let eff = max(0.0, target.n("def") - ign.def_flat) * (1.0 - clamp01(ign.def_pct)); + let eff = max(0.0, target.get(Stat::Def) - ign.def_flat) * (1.0 - clamp01(ign.def_pct)); max(amount - eff, 0.05 * amount) } DamageType::Arts => { - let eff = max(0.0, target.n("res") - ign.res_flat) * (1.0 - clamp01(ign.res_pct)); + let eff = max(0.0, target.get(Stat::Res) - ign.res_flat) * (1.0 - clamp01(ign.res_pct)); let eff = if eff.is_nan() { eff } else { eff.min(100.0) }; max(amount * (1.0 - eff / 100.0), 0.05 * amount) } @@ -68,8 +68,8 @@ pub fn mitigate( } pub fn attack_input(amount: f64, kind: DamageType, target: &Stats) -> f64 { amount - + if matches!(kind, DamageType::Arts) && target.n("artsAttackAddition").is_finite() { - target.n("artsAttackAddition") + + if matches!(kind, DamageType::Arts) && target.get(Stat::ArtsAttackAddition).is_finite() { + target.get(Stat::ArtsAttackAddition) } else { 0.0 } @@ -100,10 +100,10 @@ pub fn calculate( ) -> f64 { let mut ign = dmg.penetration; if let Some(s) = source { - ign.def_flat += s.n("defIgnoreFlat"); - ign.def_pct += s.n("defIgnorePct"); - ign.res_flat += s.n("resIgnoreFlat"); - ign.res_pct += s.n("resIgnorePct"); + ign.def_flat += s.get(Stat::DefIgnoreFlat); + ign.def_pct += s.get(Stat::DefIgnorePct); + ign.res_flat += s.get(Stat::ResIgnoreFlat); + ign.res_pct += s.get(Stat::ResIgnorePct); } let mut final_ = if dmg.resolved { dmg.amount @@ -113,10 +113,10 @@ pub fn calculate( let mut mul = dmg.mul; if let Some(s) = source { if !dmg.resolved { - mul *= s.n("dmgDealtMul") + mul *= s.get(Stat::DmgDealtMul) * match kind { - DamageType::Physical => s.n("physDealtMul"), - DamageType::Arts => s.n("artsDealtMul"), + DamageType::Physical => s.get(Stat::PhysDealtMul), + DamageType::Arts => s.get(Stat::ArtsDealtMul), _ => 1.0, }; } @@ -128,12 +128,12 @@ pub fn estimate(base: f64, kind: DamageType, target: &Stats) -> f64 { let mul = (if matches!(kind, DamageType::Elemental) { 1.0 } else { - target.n("dmgTakenMul") - }) * target.n(match kind { - DamageType::Physical => "physTakenMul", - DamageType::Arts => "artsTakenMul", - DamageType::Elemental => "elementalTakenMul", - DamageType::True => "trueTakenMul", + target.get(Stat::DmgTakenMul) + }) * target.get(match kind { + DamageType::Physical => Stat::PhysTakenMul, + DamageType::Arts => Stat::ArtsTakenMul, + DamageType::Elemental => Stat::ElementalTakenMul, + DamageType::True => Stat::TrueTakenMul, }); positive(base * mul) } diff --git a/crates/engine/src/battle/definitions.rs b/crates/engine/src/battle/definitions.rs index 8be37f8..070f4ff 100644 --- a/crates/engine/src/battle/definitions.rs +++ b/crates/engine/src/battle/definitions.rs @@ -18,6 +18,8 @@ pub struct Enemy { pub profile: Profile, pub fly: bool, pub leader: bool, + pub elite: bool, + pub machine: bool, pub lpr: f64, pub block_weight: f64, pub immune: BTreeSet, @@ -187,10 +189,17 @@ impl Enemy { .or_else(|| raw["motion"].as_str()) .unwrap_or("WALK") .eq_ignore_ascii_case("FLY"), + machine: raw["tags"] + .as_array() + .is_some_and(|tags| tags.iter().any(|v| v == "machine")), leader: raw["rank"] .as_str() .unwrap_or("NORMAL") .eq_ignore_ascii_case("BOSS"), + elite: !raw["rank"] + .as_str() + .unwrap_or("NORMAL") + .eq_ignore_ascii_case("NORMAL"), lpr: number( first(st, &["lpr"]), number(first(raw, &["lpr", "lifePointReduce"]), 1.), @@ -273,6 +282,7 @@ impl Enemy { u.ep_resistance = self.ep_resistance; u.elemental_resistance = self.elemental_resistance; u.element_leader = self.leader; + u.targeting.elite = self.elite; Ok(u) } } diff --git a/crates/engine/src/battle/deploy.rs b/crates/engine/src/battle/deploy.rs index e125385..0cc8fd6 100644 --- a/crates/engine/src/battle/deploy.rs +++ b/crates/engine/src/battle/deploy.rs @@ -60,6 +60,7 @@ impl Default for State { #[derive(Clone, Copy, Debug, Default)] pub struct Options { pub initial: bool, + pub keep_sp: bool, pub tile: Option<[i32; 2]>, pub aggro_seq: Option, } @@ -80,7 +81,7 @@ pub enum Event { /// the host. Required methods avoid silently dropping those steps during migration. pub trait Hooks: super::blocking::Hooks { /// Reset attack/element/skill state and apply initial-deployment cooldown. - /// Carry and retained SP require the future skill runtime and are not inferred here. + /// The operator skill runtime handles retained SP before deployment callbacks. fn initialize( &mut self, id: Id, @@ -203,6 +204,13 @@ impl Deployment { self.dp.insert(id, dp); Ok(()) } + pub(crate) fn add_dp(&mut self, owner: Id, amount: f64) -> Result<(), String> { + if !amount.is_finite() { + return Err("Non-finite DP change".into()); + } + let dp = self.dp(owner).ok_or("Missing deployment points")?; + self.set_dp(owner, (dp + amount).clamp(0., self.dp_max)) + } pub fn occupant(&self, tile: [i32; 2]) -> Option { if Grid::in_bounds(tile) { self.occupants[key(tile)] @@ -468,6 +476,17 @@ impl Deployment { id: Id, free: bool, tile: Option<[i32; 2]>, + ) -> Result { + self.redeploy_retaining(w, h, id, free, tile, false) + } + pub(crate) fn redeploy_retaining( + &mut self, + w: &mut World, + h: &mut H, + id: Id, + free: bool, + tile: Option<[i32; 2]>, + keep_sp: bool, ) -> Result { let u = w.unit(id)?; if u.side != Side::Ally || u.stats.alive || u.removed { @@ -520,6 +539,7 @@ impl Deployment { id, Options { tile: at, + keep_sp, ..Options::default() }, )? { @@ -574,146 +594,3 @@ impl Deployment { Ok(()) } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::battle::{ - health::Unit, - stats::{Base, UnitStats}, - }; - #[derive(Default)] - struct Host { - blocked_reentrant: bool, - reenter: bool, - releases: usize, - } - impl super::super::blocking::Hooks for Host { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - } - impl Hooks for Host { - fn initialize( - &mut self, - _: Id, - _: Options, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn event( - &mut self, - e: Event, - id: Id, - _: Option, - w: &mut World, - d: &mut Deployment, - ) -> Result<(), String> { - if e == Event::EndSkill && self.reenter { - self.blocked_reentrant = !d.deploy(w, self, id, Options::default())?; - } - if e == Event::Release { - self.releases += 1; - } - Ok(()) - } - fn remove_temporary_effects(&mut self, id: Id, w: &mut World) -> Result<(), String> { - w.unit_mut(id)?.stats.set_buffs(vec![]); - Ok(()) - } - } - fn make(home: [i32; 2], kind: Kind) -> Unit { - let mut base = Base::default(); - base.0.insert("maxHp".into(), 100.0); - base.0.insert("cost".into(), 7.0); - base.0.insert("respawnTime".into(), 3.0); - let mut u = Unit::new(UnitStats::new(base), Side::Ally); - u.stats.alive = false; - u.owner = Some(1); - u.deployment.kind = kind; - u.deployment.home = home; - u.deployment.tile = home; - u.deployment.uid = Some(1); - u - } - fn setup() -> (World, Deployment, Host) { - let mut w = World::new(4, 1, 1).unwrap(); - let mut d = Deployment::new( - Rect { - r0: 9, - r1: 12, - c0: 2, - c1: 10, - }, - 4, - 1, - 99.0, - ) - .unwrap(); - let mut h = Host::default(); - w.insert_unit(1, make([9, 2], Kind::Operator)).unwrap(); - w.insert_unit(2, make([10, 4], Kind::Token)).unwrap(); - for id in [1, 2] { - d.register(id, &w).unwrap(); - assert!(d.deploy(&mut w, &mut h, id, Options::default()).unwrap()); - } - d.set_dp(1, 20.0).unwrap(); - (w, d, h) - } - #[test] - fn death_cannot_redeploy_from_skill_end_and_removed_home_is_retained() { - let (mut w, mut d, mut h) = setup(); - h.reenter = true; - d.retreat(&mut w, &mut h, 2, "expired", true).unwrap(); - assert!(h.blocked_reentrant); - d.release_removed(&mut w, &mut h).unwrap(); - assert!(w.unit(2).is_err()); - assert_eq!(h.releases, 1); - d.release_removed(&mut w, &mut h).unwrap(); - assert_eq!(h.releases, 1); - assert!(d.relocate(&mut w, &mut h, 1, [10, 4]).unwrap()); - d.kill(&mut w, &mut h, 1, None).unwrap(); - assert_eq!(w.unit(1).unwrap().deployment.body, Some([9, 2])); - } - #[test] - fn body_prevents_deployment_and_failed_payment_is_refunded() { - let (mut w, mut d, mut h) = setup(); - d.kill(&mut w, &mut h, 1, None).unwrap(); - assert!(d.reserved(&w, [9, 2]).unwrap()); - assert!(!d.relocate(&mut w, &mut h, 2, [9, 2]).unwrap()); - w.insert_unit(3, make([9, 2], Kind::Token)).unwrap(); - d.register(3, &w).unwrap(); - assert!(!d.redeploy(&mut w, &mut h, 3, false, None).unwrap()); - assert_eq!(d.dp(1), Some(20.0)); - d.set_dp(1, 6.0).unwrap(); - w.time = 10.0; - d.check_redeploys(&mut w, &mut h).unwrap(); - assert!(!w.unit(1).unwrap().stats.alive); - d.set_dp(1, 7.0).unwrap(); - w.unit_mut(1).unwrap().cadence.cooldown = 9.0; - d.check_redeploys(&mut w, &mut h).unwrap(); - assert!(w.unit(1).unwrap().stats.alive); - assert_eq!(d.dp(1), Some(0.0)); - assert_eq!(w.unit(1).unwrap().cadence.cooldown, 0.0); - } - #[test] - fn retained_corpse_cleans_hooks_once_then_releases_after_flight() { - let (mut w, mut d, mut h) = setup(); - w.pin_unit(2).unwrap(); - d.retreat(&mut w, &mut h, 2, "expired", true).unwrap(); - d.release_removed(&mut w, &mut h).unwrap(); - assert_eq!(h.releases, 1); - assert!(w.unit(2).is_ok()); - d.release_removed(&mut w, &mut h).unwrap(); - assert_eq!(h.releases, 1); - w.unpin_unit(2).unwrap(); - d.release_removed(&mut w, &mut h).unwrap(); - assert_eq!(h.releases, 1); - assert!(w.unit(2).is_err()); - } -} diff --git a/crates/engine/src/battle/element.rs b/crates/engine/src/battle/element.rs index d3862da..e485465 100644 --- a/crates/engine/src/battle/element.rs +++ b/crates/engine/src/battle/element.rs @@ -308,17 +308,16 @@ fn resolve_burst( } _ => {} } - r.add( - w, - h, - target, - Spec { - mods_present: !b.mods.is_empty(), - flags_present: true, - buff: b, - ..Default::default() - }, - )?; + let mut spec = Spec { + mods_present: !b.mods.is_empty(), + flags_present: true, + buff: b, + ..Default::default() + }; + if let Some(credit) = credit.filter(|_| state.periodic()) { + spec = spec.retaining_unit(credit); + } + r.add(w, h, target, spec)?; match element { Element::Burn => { h.burst_damage( @@ -629,137 +628,3 @@ fn round(v: f64) -> f64 { f + 1.0 } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::battle::{ - blocking, - health::{Side, Unit}, - stats::{Base, UnitStats}, - }; - struct Host; - impl super::super::health::Hooks for Host { - fn kill(&mut self, _: Id, _: Option, _: &mut World) -> Result<(), String> { - unreachable!() - } - } - impl blocking::Hooks for Host { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - } - impl buffs::Hooks for Host { - fn status(&mut self, _: Id, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - } - impl status::Hooks for Host { - fn has_before_status(&self) -> bool { - false - } - fn before_status( - &mut self, - _: &mut status::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - fn has_status_applied(&self) -> bool { - false - } - fn status_applied( - &mut self, - _: &status::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - } - impl Hooks for Host { - fn battle_rect(&self) -> Rect { - Rect::FULL - } - fn element_enabled(&self, p: Phase) -> bool { - p == Phase::Burst - } - fn element_event( - &mut self, - _: Phase, - _: &mut Request, - _: f64, - _: f64, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("burst callback failed".into()) - } - fn element_number(&mut self, _: Id, _: f64, _: Element) -> Result<(), String> { - Ok(()) - } - fn burst_visual(&mut self, _: Id, _: Element, _: &World) -> Result<(), String> { - Ok(()) - } - } - fn world() -> World { - let mut w = World::new(1, 1, 1).unwrap(); - let mut u = Unit::new(UnitStats::new(Base::default()), Side::Enemy); - u.deployed = true; - w.insert_unit(1, u).unwrap(); - w - } - #[test] - fn burst_callback_failure_clears_pending_and_faults_runtime() { - let mut w = world(); - let mut r = Runtime::new(8, 16, 8).unwrap(); - let mut h = Host; - let error = burst(&mut w, &mut h, &mut r, None, None, 1, Element::Burn).unwrap_err(); - assert_eq!(error, "burst callback failed"); - assert!(r.faulted()); - assert_eq!(w.unit(1).unwrap().burst_pending, [false; 5]); - assert!(w.unit(1).unwrap().stats.buffs().is_empty()); - } - #[test] - fn recovery_lowers_each_gauge_and_pending_burst_locks_every_element() { - let mut w = world(); - w.unit_mut(1).unwrap().element_buildup = [150.0, 250.0, 0.0, 80.0, 10.0]; - assert_eq!(heal(&mut w, 1, 100.0, None).unwrap(), 290.0); - assert_eq!( - w.unit(1).unwrap().element_buildup, - [50.0, 150.0, 0.0, 0.0, 0.0] - ); - w.unit_mut(1).unwrap().burst_pending[2] = true; - assert_eq!(heal(&mut w, 1, 1000.0, Some(Element::Neural)).unwrap(), 0.0); - assert_eq!(w.unit(1).unwrap().element_buildup[1], 150.0); - } - #[test] - fn visible_gauge_ties_use_official_order_and_entity_class_is_independent_of_side() { - let mut w = world(); - let u = w.unit_mut(1).unwrap(); - u.side = Side::Ally; - u.enemy_entity = true; - u.element_leader = true; - u.element_buildup = [100.0; 5]; - assert_eq!(gauge_max(&w, 1).unwrap(), 2000.0); - let v = view(&mut w, 1, 0.0).unwrap().unwrap(); - assert_eq!(v.element, Element::Neural); - assert_eq!(v.fill, 0.05); - w.unit_mut(1).unwrap().element_buildup = [0.0001, 0.0, 0.0, 0.0, 0.0]; - assert_eq!(view(&mut w, 1, 0.0).unwrap().unwrap().fill, 0.01); - } -} diff --git a/crates/engine/src/battle/enemy.rs b/crates/engine/src/battle/enemy.rs index f2975db..4d61253 100644 --- a/crates/engine/src/battle/enemy.rs +++ b/crates/engine/src/battle/enemy.rs @@ -8,6 +8,7 @@ use super::{ health::{self, Hit, Id, World}, hit::Request, motion, settlement, + stats::Stat, targeting::{self, Profile as Selection}, }; use crate::deterministic::{math::hypot, rng::Rng}; @@ -44,14 +45,15 @@ pub struct Animation { pub duration: f64, pub hit: Option, } -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] pub struct Profile { pub mode: Mode, pub no_attack: bool, pub melee: bool, pub attack_moves: bool, pub deferred: bool, - pub shot: String, + /// Static delivery style; no per-tick string allocation. + pub shot: &'static str, pub selection: Selection, pub max_targets: f64, pub atk_scale: f64, @@ -65,7 +67,7 @@ impl Default for Profile { melee: true, attack_moves: false, deferred: false, - shot: "none".into(), + shot: "none", selection: Selection::default(), max_targets: 1.0, atk_scale: 1.0, @@ -136,20 +138,21 @@ pub trait Hooks: motion::Hooks + blocking::Hooks + settlement::Hooks { rng: &mut Rng, ) -> Result<(), String>; } -fn flags(w: &mut World, id: Id) -> Result, String> { +/// Single-flag reads stay borrowed; the aggregated flag set is never copied. +fn flag(w: &mut World, id: Id, key: &str) -> Result { Ok(w.unit_mut(id)? .stats .stats() .map_err(str::to_string)? .flags - .clone()) + .contains(key)) } -fn number(w: &mut World, id: Id, key: &str) -> Result { +fn number(w: &mut World, id: Id, stat: Stat) -> Result { Ok(w.unit_mut(id)? .stats .stats() .map_err(str::to_string)? - .n(key)) + .get(stat)) } pub fn windup(interval: f64, animation: Option) -> f64 { let Some(a) = animation.filter(|a| a.duration > 0.0) else { @@ -294,15 +297,13 @@ pub fn attack( limit: usize, ) -> Result { let p = h.profile(id, w)?; - if p.no_attack || matches!(p.mode, Mode::None) || number(w, id, "atk")? <= 0.0 { + if p.no_attack || matches!(p.mode, Mode::None) || number(w, id, Stat::Atk)? <= 0.0 { w.unit_mut(id)?.enemy.swing = false; return Ok(false); } - let f = flags(w, id)?; - if f.contains("fear") - || f.contains("disarm") - || f.contains("tremble") && w.unit(id)?.blocked_by().is_some() - { + let fear = flag(w, id, "fear")?; + let disarm = flag(w, id, "disarm")?; + if fear || disarm || flag(w, id, "tremble")? && w.unit(id)?.blocked_by().is_some() { clear(w, id)?; return Ok(false); } @@ -317,7 +318,7 @@ pub fn attack( } else { w.unit(id)?.stats.base_number("rangeRadius") }; - let wind = windup(number(w, id, "interval")?, p.animation); + let wind = windup(number(w, id, Stat::Interval)?, p.animation); if w.unit(id)?.cadence.cooldown > wind + 1e-9 { clear(w, id)?; return Ok(false); @@ -356,7 +357,7 @@ pub fn attack( if h.enemy_event_enabled(Event::AttackStart) { let mut c = context(id, selected.clone()); h.enemy_event(Event::AttackStart, &mut c, r, w, g, rng)?; - if !w.unit(id)?.stats.alive || flags(w, id)?.contains("stun") { + if !w.unit(id)?.stats.alive || flag(w, id, "stun")? { return Ok(false); } } @@ -385,7 +386,7 @@ pub fn attack( r.edit(w, id, palsy.runtime.id(), |b| b.stacks -= 1)?; } } - w.unit_mut(id)?.cadence.cooldown = number(w, id, "interval")?; + w.unit_mut(id)?.cadence.cooldown = number(w, id, Stat::Interval)?; let live = h.profile(id, w)?; if w.unit(id)?.blocked_by().is_none() && radius > 0.0 && !live.attack_moves { w.unit_mut(id)?.motion.attack_stand_until = w.time + 0.35; @@ -393,8 +394,8 @@ pub fn attack( h.palsy_visual(id, w)?; return Ok(false); } - let n = - (h.profile(id, w)?.max_targets.floor() + number(w, id, "maxTargets")?.floor()).max(1.0); + let n = (h.profile(id, w)?.max_targets.floor() + number(w, id, Stat::MaxTargets)?.floor()) + .max(1.0); if selected.len() as f64 > n { selected.truncate(n as usize); } @@ -455,7 +456,7 @@ pub fn attack( id, target, if delivery_profile.deferred { - &delivery_profile.shot + delivery_profile.shot } else if ranged { "enemy" } else { @@ -489,7 +490,7 @@ pub fn attack( c.attack_id = Some(attack_id); h.enemy_event(Event::Attack, &mut c, r, w, g, rng)?; } - let interval = number(w, id, "interval")?; + let interval = number(w, id, Stat::Interval)?; w.unit_mut(id)?.cadence.cooldown = interval; let current = h.profile(id, w)?; w.unit_mut(id)?.motion.attack_stand_until = w.time + stand(interval, ¤t).1; @@ -522,7 +523,7 @@ fn heal( if target == id { continue; } - let max = number(w, target, "maxHp")?; + let max = number(w, target, Stat::MaxHp)?; let u = w.unit(target)?; if u.stats.hp >= max || u.pool.is_some() { continue; @@ -546,9 +547,9 @@ fn heal( u.last_attack_at = time; u.attacks = count; h.attack_visual(id, target, "orb")?; - let amount = number(w, id, "atk")?; + let amount = number(w, id, Stat::Atk)?; health::heal(w, h, Some(id), target, amount, Default::default())?; - w.unit_mut(id)?.cadence.cooldown = number(w, id, "interval")?; + w.unit_mut(id)?.cadence.cooldown = number(w, id, Stat::Interval)?; Ok(()) } /// Read current ATK/profile at arrival; the damage type and attack identity belong @@ -568,7 +569,7 @@ pub fn impact( return Ok(0.0); } let scale = h.profile(d.source, w)?.atk_scale; - let amount = number(w, d.source, "atk")? * scale; + let amount = number(w, d.source, Stat::Atk)? * scale; let mut request = Request::new( Hit { source: Some(d.source), @@ -615,13 +616,19 @@ pub fn update( w.unit_mut(id)?.moving = false; return Ok(()); } - let f = flags(w, id)?; - let stunned = f.contains("stun"); + let (stunned, fear, levitate) = { + let flags = &w.unit_mut(id)?.stats.stats().map_err(str::to_string)?.flags; + ( + flags.contains("stun"), + flags.contains("fear"), + flags.contains("levitate"), + ) + }; let hidden = w.unit(id)?.hidden; - if stunned || hidden || f.contains("fear") { + if stunned || hidden || fear { h.cut_attack_stand(id, w)?; } - if f.contains("levitate") && w.unit(id)?.motion.unbalance_until > w.time { + if levitate && w.unit(id)?.motion.unbalance_until > w.time { w.unit_mut(id)?.motion.unbalance_until = f64::NEG_INFINITY; } let unbalanced = w.time < w.unit(id)?.motion.unbalance_until - 1e-9; @@ -637,24 +644,39 @@ pub fn update( } if stunned && !w.unit(id)?.hidden { w.unit_mut(id)?.motion.attack_stand_until = f64::NEG_INFINITY; - if w.unit(id)?.blocked_by().is_some() && flags(w, id)?.contains("sleep") { + if w.unit(id)?.blocked_by().is_some() && flag(w, id, "sleep")? { h.unblock_with_buffs(w, r, id)?; } h.check_block(id, w, g)?; return Ok(()); } if let Some(blocker) = w.unit(id)?.blocked_by() { - let bf = flags(w, blocker)?; - let ef = flags(w, id)?; + let (no_block, blocker_sleep) = { + let flags = &w + .unit_mut(blocker)? + .stats + .stats() + .map_err(str::to_string)? + .flags; + (flags.contains("noBlock"), flags.contains("sleep")) + }; + let (unblockable, enemy_levitate, enemy_fear) = { + let flags = &w.unit_mut(id)?.stats.stats().map_err(str::to_string)?.flags; + ( + flags.contains("unblockable"), + flags.contains("levitate"), + flags.contains("fear"), + ) + }; let bl = w.unit(blocker)?; if !bl.stats.alive || !bl.deployed || bl.hidden - || bf.contains("noBlock") - || bf.contains("sleep") - || ef.contains("unblockable") - || ef.contains("levitate") - || ef.contains("fear") + || no_block + || blocker_sleep + || unblockable + || enemy_levitate + || enemy_fear { h.unblock_with_buffs(w, r, id)?; } else { @@ -669,8 +691,7 @@ pub fn update( } let standing = winding || unbalanced - || w.time < w.unit(id)?.motion.attack_stand_until - && !flags(w, id)?.contains("fear"); + || w.time < w.unit(id)?.motion.attack_stand_until && !flag(w, id, "fear")?; motion::update(w, g, r, rng, h, id, dt, standing, unbalanced) })(); let release = w.unpin_unit(id); diff --git a/crates/engine/src/battle/equipment.rs b/crates/engine/src/battle/equipment.rs new file mode 100644 index 0000000..ebd3f3f --- /dev/null +++ b/crates/engine/src/battle/equipment.rs @@ -0,0 +1,591 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Equipment definitions shared by preparation and battle installation. +use super::stats::{Buff, Numbers}; +use crate::data::Catalog; +use std::sync::Arc; + +pub(crate) const DRAIN: u64 = 0xE901; +pub(crate) const PEGASUS_HEAL: u64 = 0xE902; +pub(crate) const FIXED_REDUCTION: u64 = 0xE903; + +#[derive(Clone, Copy)] +pub(crate) enum Hammer { + Burn(f64), + Undying(f64), + Speed(f64), + Tremble { probability: f64, duration: f64 }, +} +impl Hammer { + pub fn index(self) -> usize { + match self { + Self::Burn(_) => 0, + Self::Undying(_) => 1, + Self::Speed(_) => 2, + Self::Tremble { .. } => 3, + } + } +} +#[derive(Clone, Copy)] +pub(crate) struct Steam { + pub burn: f64, + pub undying: f64, + pub speed: f64, + pub probability: f64, + pub tremble: f64, +} +impl Steam { + pub fn hammer(self, index: usize) -> Hammer { + match index { + 0 => Hammer::Burn(self.burn), + 1 => Hammer::Undying(self.undying), + 2 => Hammer::Speed(self.speed), + 3 => Hammer::Tremble { + probability: self.probability, + duration: self.tremble, + }, + _ => unreachable!(), + } + } +} +pub(crate) struct Hammers { + pub own: [u32; 4], + pub params: [Option; 4], + pub steam: Option, + pub speed: f64, + pub next: f64, + pub order: usize, + pub lock_at: Option, + pub window_at: Option, + pub until: f64, +} +#[derive(Clone, Copy)] +pub(crate) enum Timer { + Effect(usize), + Hammers, +} +pub(crate) struct FieldHammers { + pub at: f64, + pub present: [bool; 4], +} + +#[derive(Clone, Copy)] +pub(crate) enum Effect { + Silence(f64), + Cocoon { + cap: u32, + used: u32, + }, + Cauldron { + speed: f64, + cap: u32, + }, + Chivalry { + duration: f64, + attack: f64, + speed: f64, + movement: f64, + next: f64, + until: f64, + combo: bool, + doomed: bool, + }, + Crest { + per: f64, + cap: f64, + scale: f64, + next: f64, + bonus: f64, + deployment: u64, + }, + PegasusHeal, + PegasusDamage(f64), + Trench { + cooldown: f64, + scale: f64, + ready: f64, + }, + Compass { + initial: f64, + end: f64, + team: f64, + spent: bool, + }, + GunKnight { + probability: f64, + scale: f64, + combo: f64, + }, + Tears { + interval: f64, + next: f64, + scale: f64, + combo: f64, + }, + Hammer(Hammer), + Steam(Steam), + DeploySp(f64), + FrontHealth(f64), + SideAura { + speed: f64, + next: f64, + }, + AmmoClip { + probability: f64, + ratio: f64, + cap: u32, + used: u32, + deployment: u64, + }, + Weakness, + Sniper { + radius: f64, + scale: f64, + }, + SkillAttack { + attack: f64, + cap: u32, + probability: f64, + stacks: u32, + }, + Grenade { + window: f64, + duration: f64, + }, + Accelerator { + speed: f64, + cap: u32, + }, + Camouflage { + duration: f64, + used: bool, + }, + RiotShield(f64), + AttackHeal(f64), + Flag { + scale: f64, + window: f64, + interval: f64, + decay: f64, + }, + StatusImmunity(f64), + DamageStatus { + key: &'static str, + probability: f64, + duration: f64, + }, + HealShield { + probability: f64, + cap: u32, + }, +} + +#[derive(Clone)] +pub(crate) struct Grant { + pub buffs: Vec, + pub effects: Vec, + pub tag: Arc, + pub partner: Option>, +} + +#[derive(Clone)] +pub(crate) struct Instance { + pub tag: Arc, + pub partner: Option>, + pub effect: Effect, +} +pub(crate) struct Loadout { + pub effects: Vec, + pub bonds: Vec, + pub items: Vec>, + pub hammers: Option, +} +#[derive(Default)] +pub(crate) struct Runtime { + pub units: std::collections::BTreeMap, + pub pegasus_damage: bool, + pub gained_chess: u64, + pub fields: std::collections::BTreeMap, +} +impl Runtime { + pub(crate) fn clock_quiet(&self) -> bool { + self.fields.is_empty() + && self + .units + .values() + .all(|u| u.effects.is_empty() && u.hammers.is_none()) + } + pub fn register(&mut self, unit: super::health::Id, grants: &[Grant], bonds: Vec) { + let effects: Vec<_> = grants + .iter() + .flat_map(|g| { + g.effects.iter().map(|&effect| Instance { + tag: Arc::clone(&g.tag), + partner: g.partner.clone(), + effect, + }) + }) + .collect(); + self.pegasus_damage |= effects + .iter() + .any(|instance| matches!(instance.effect, Effect::PegasusDamage(_))); + let hammers = effects + .iter() + .position(|instance| matches!(instance.effect, Effect::Hammer(_) | Effect::Steam(_))) + .map(|order| Hammers { + own: [0; 4], + params: [None; 4], + steam: None, + speed: 0., + next: 0., + order, + lock_at: None, + window_at: None, + until: f64::NEG_INFINITY, + }); + self.units.insert( + unit, + Loadout { + effects, + bonds, + items: grants.iter().map(|g| Arc::clone(&g.tag)).collect(), + hammers, + }, + ); + } + pub fn effects(&self, unit: super::health::Id) -> Vec<(usize, Instance)> { + self.units + .get(&unit) + .into_iter() + .flat_map(|loadout| &loadout.effects) + .cloned() + .enumerate() + .collect() + } +} + +pub(crate) fn compile(data: &Catalog, id: &str) -> Result { + let raw = &data.table("items").unwrap()[id]; + if !raw.is_object() + || raw["itemType"] != "EQUIP" + || !matches!( + raw["kind"].as_str(), + Some( + "passive" + | "passive_counter" + | "passive_player" + | "post_battle_transform" + | "consume_on_equip_or_delayed" + ) + ) + { + return Err(format!("Unsupported equipment: {id}")); + } + let buffs = raw["buffs"] + .as_array() + .ok_or_else(|| format!("Missing equipment buffs: {id}"))?; + if buffs.len() > 64 { + return Err("Equipment buff capacity exceeded".into()); + } + let mut out = Vec::new(); + let mut effects = Vec::new(); + let mut partner = None; + for b in buffs { + if let Some(id) = b["bbStr"]["equip_chess_id"].as_str() { + partner = Some(Arc::from(id)); + } + let key = b["bbStr"]["key"] + .as_str() + .or(b["key"].as_str()) + .unwrap_or(""); + let n = + |name: &str| super::waves::number(b["bbStr"].get(name).unwrap_or(&b["bb"][name]), 0.); + let cap = |name| -> Result { + let value = n(name).floor().max(1.); + if value > i32::MAX as f64 { + return Err("Equipment stack capacity exceeded".into()); + } + Ok(value as u32) + }; + let effect = match key { + "attr_common_global_buff" + | "act1autochess_equip_acarm056_global_buff" + | "act1autochess_equip_acarm050_global_buff" + | "magic_penetrate_global_buff" + | "act1autochess_equip_acarm054_global_buff" => None, + "periodic_damage" => { + let mut buff = Buff { + key: Some(format!("item:{id}:drain")), + permanent: true, + ..Default::default() + }; + buff.runtime.persist = true; + buff.runtime.interval = 1.; + buff.runtime.tick_payload = n("damage"); + buff.runtime.on_tick = Some(DRAIN); + out.push(buff); + continue; + } + "act1autochess_equip_acarm076_global_buff" => Some(Effect::GunKnight { + probability: n("prob"), + scale: n("atk_scale_1"), + combo: n("atk_scale_2"), + }), + "act2autochess_equip_acarm102_ability" => Some(Effect::Tears { + interval: n("interval").max(0.1), + next: n("interval").max(0.1), + scale: n("atk_scale"), + combo: n("atk_scale_ex"), + }), + "act2autochess_equip_acarm118_global_buff" => { + let mut buff = Buff { + key: Some(format!("item:{id}:set")), + permanent: true, + ..Default::default() + }; + buff.runtime.persist = true; + buff.runtime.interval = 1.; + buff.runtime.tick_payload = n("hp_recovery_per_sec_by_max_hp_ratio"); + buff.runtime.on_tick = Some(PEGASUS_HEAL); + out.push(buff); + Some(Effect::PegasusHeal) + } + "act2autochess_equip_acarm117_global_buff" => { + Some(Effect::PegasusDamage(n("atk_scale"))) + } + "act2autochess_equip_acarm078_global_buff" => Some(Effect::Trench { + cooldown: n("lock_duration"), + scale: n("atk_scale"), + ready: f64::NEG_INFINITY, + }), + "halfidle_block_fixed_damage" => { + let mut buff = Buff { + key: Some(format!("item:{id}:fixedReduction")), + permanent: true, + ..Default::default() + }; + buff.runtime.persist = true; + buff.runtime.tick_payload = n("value"); + buff.runtime.injury.on_injury = Some(FIXED_REDUCTION); + out.push(buff); + continue; + } + "act1autochess_equip_acarm103_global_buff" => Some(Effect::Compass { + initial: n("init_sp"), + end: n("sp"), + team: n("addition_sp"), + spent: false, + }), + "act1autochess_equip_acarm068_global_buff" => Some(Effect::Cocoon { + cap: cap("max_respawn_cnt")?, + used: 0, + }), + "act1autochess_equip_acarm077_global_buff" => Some(Effect::Cauldron { + speed: n("attack_speed"), + cap: cap("max_cnt")?, + }), + "equip_with_another_gain_coin_when_gain_char" + | "act2autochess_equip_acarm119_ability" => continue, + "act2autochess_equip_acarm119_global_buff" => { + let ability = buffs + .iter() + .find(|v| v["bbStr"]["key"] == "act2autochess_equip_acarm119_ability"); + let a = |key: &str| { + ability.map_or(1., |v| { + super::waves::number(v["bbStr"].get(key).unwrap_or(&v["bb"][key]), 1.) + }) + }; + Some(Effect::Chivalry { + duration: n("duration"), + attack: n("atk"), + speed: a("attack_speed"), + movement: a("move_speed"), + next: 0., + until: f64::NEG_INFINITY, + combo: false, + doomed: false, + }) + } + "act2autochess_equip_acarm122_global_buff" => Some(Effect::Crest { + per: n("atk_per_sec"), + cap: n("max_atk"), + scale: n("atk_scale"), + next: 0.25, + bonus: 0., + deployment: 0, + }), + "silence_attachment" => Some(Effect::Silence(n("silence"))), + "act1autochess_equip_acarm042_global_buff" => { + Some(Effect::Hammer(Hammer::Burn(n("damage_scale")))) + } + "act1autochess_equip_acarm043_global_buff" => { + Some(Effect::Hammer(Hammer::Undying(n("undeadable_duration")))) + } + "act1autochess_equip_acarm044_global_buff" => { + Some(Effect::Hammer(Hammer::Speed(n("attack_speed")))) + } + "act1autochess_equip_acarm045_global_buff" => Some(Effect::Hammer(Hammer::Tremble { + probability: n("prob"), + duration: n("disarmed_duration"), + })), + "act1autochess_equip_acarm079_global_buff" => Some(Effect::Steam(Steam { + burn: n("damage_scale"), + undying: n("undeadable_duration"), + speed: n("attack_speed"), + probability: n("prob"), + tremble: n("disarmed_duration"), + })), + "act1autochess_equip_acarm051_global_buff" => { + Some(Effect::DeploySp(n("sp_each_person"))) + } + "act1autochess_equip_acarm049_global_buff" => { + let mut buff = Buff { + key: Some(format!("item:{id}:hp")), + mods: [("hpPct".into(), n("init_max_hp"))].into(), + permanent: true, + ..Default::default() + }; + buff.runtime.persist = true; + out.push(buff); + Some(Effect::FrontHealth(n("ex_max_hp"))) + } + "act2autochess_equip_acarm121_ability" => Some(Effect::SideAura { + speed: n("attack_speed"), + next: 0., + }), + "act1autochess_equip_acarm057_global_buff" => Some(Effect::AmmoClip { + probability: n("prob"), + ratio: n("ammo_percent"), + cap: cap("max_trigger_cnt")?, + used: 0, + deployment: 0, + }), + "act1autochess_equip_acarm067_global_buff" => Some(Effect::Weakness), + "act1autochess_equip_acarm063_global_buff" => Some(Effect::Sniper { + radius: n("radius"), + scale: n("damage_scale"), + }), + "act1vautochess_equip_acarm024_global_buff" => Some(Effect::SkillAttack { + attack: n("atk"), + cap: cap("atk_buff_cnt")?, + probability: n("prob"), + stacks: 0, + }), + "act1autochess_equip_acarm064_global_buff" => Some(Effect::Grenade { + window: n("duration"), + duration: n("stun"), + }), + "act1vautochess_equip_acarm037_global_buff" => Some(Effect::Accelerator { + speed: n("attack_speed"), + cap: cap("max_buff_cnt")?, + }), + "act2autochess_equip_acarm055_global_buff" => Some(Effect::Camouflage { + duration: n("duration"), + used: false, + }), + "act1autochess_equip_acarm060_global_buff" => { + Some(Effect::RiotShield(n("damage_scale"))) + } + "act1vautochess_equip_acarm025_global_buff" => Some(Effect::AttackHeal(n("hp_ratio"))), + "act2autochess_equip_acarm120_global_buff" => Some(Effect::Flag { + scale: n("damage_scale"), + window: n("interval"), + interval: n("ex_interval").max(0.1), + decay: n("damage_scale_minus"), + }), + "act1autochess_equip_acarm059_global_buff" => { + Some(Effect::StatusImmunity(n("hp_ratio"))) + } + "act1autochess_equip_acarm058_global_buff" => Some(Effect::DamageStatus { + key: "palsy", + probability: n("prob"), + duration: f64::INFINITY, + }), + "act1vautochess_equip_acarm003_global_buff" => Some(Effect::DamageStatus { + key: "cold", + probability: n("prob"), + duration: n("cold"), + }), + "act1autochess_equip_acarm061_global_buff" => Some(Effect::HealShield { + probability: n("prob"), + cap: cap("max_stack_cnt")?, + }), + "equip_round_start_upgrade_char" + | "sell_char_count_gain_equip_owner_bond" + | "char_chess_transformation_equip" => None, + _ => return Err(format!("Unsupported equipment effect {key}: {id}")), + }; + if let Some(effect) = effect { + effects.push(effect); + continue; + } + let mut mods = Numbers::new(); + for (from, to) in [ + ("atk", "atkPct"), + ("def", "defPct"), + ("max_hp", "hpPct"), + ("attack_speed", "aspd"), + ("magic_resistance", "resFlat"), + ("sp_recovery_per_sec", "spRecoveryFlat"), + ("magic_resist_penetrate", "resIgnorePct"), + ("taunt_level", "taunt"), + ] { + let value = n(from); + if value != 0. { + mods.insert( + to.into(), + if from == "max_hp" { + value.max(-0.99) + } else { + value + }, + ); + } + } + if n("respawn_time") != 0. { + mods.insert("redeployMul".into(), (1. + n("respawn_time")).max(0.)); + } + if !mods.is_empty() { + let mut buff = Buff { + key: Some(format!("item:{id}:stat:{key}")), + mods, + permanent: true, + ..Default::default() + }; + buff.runtime.persist = true; + out.push(buff); + } + } + Ok(Grant { + buffs: out, + effects, + tag: format!("item:{id}").into(), + partner, + }) +} + +pub(crate) fn bonds(data: &Catalog, key: &str, items: &[String]) -> Vec { + let mut out: Vec<_> = data.table("chess").unwrap()[key]["bonds"] + .as_array() + .into_iter() + .flatten() + .filter_map(|v| v.as_str()) + .map(str::to_owned) + .collect(); + let table = data.table("items").unwrap(); + if items.len() >= 2 && items.iter().any(|id| table[id]["canGiveBond"] == true) { + for id in items { + if table[id]["canGiveBond"] == true { + continue; + } + if let Some(bond) = table[id]["giveBondId"] + .as_str() + .filter(|id| data.table("bonds").unwrap()[*id].is_object()) + { + if !out.iter().any(|b| b == bond) { + out.push(bond.into()); + } + } + } + } + out +} diff --git a/crates/engine/src/battle/events.rs b/crates/engine/src/battle/events.rs index b6bd3c7..8fba7ae 100644 --- a/crates/engine/src/battle/events.rs +++ b/crates/engine/src/battle/events.rs @@ -427,105 +427,3 @@ impl Runtime { self.leave(result) } } - -#[cfg(test)] -mod tests { - use super::*; - struct Host { - calls: usize, - reenter: bool, - fail: bool, - } - impl super::Host for Host { - fn hook( - &mut self, - _: Handle, - _: u64, - c: &mut Context<()>, - r: &mut Runtime, - ) -> Result<(), String> { - self.calls += 1; - if self.reenter && self.calls < 2 { - r.emit(&0, c, self)?; - } - if self.fail { - return Err("content callback failed".into()); - } - Ok(()) - } - } - #[test] - fn once_removes_after_callback_so_nested_emit_can_enter_it_again() { - let mut r = Runtime::new(4, 4, 4, 16).unwrap(); - r.on(0, 1, 0.0, None, true).unwrap(); - let mut h = Host { - calls: 0, - reenter: true, - fail: false, - }; - r.emit(&0, &mut Context::new(()), &mut h).unwrap(); - assert_eq!(h.calls, 2); - assert!(!r.has_hook(&0)); - assert_eq!(r.depth, 0); - assert!(r.hooks.is_empty()); - } - #[test] - fn callback_error_cleans_frames_and_once_registration_then_faults() { - let mut r = Runtime::new(4, 4, 4, 16).unwrap(); - r.on(0, 1, 0.0, None, true).unwrap(); - let mut h = Host { - calls: 0, - reenter: false, - fail: true, - }; - assert_eq!( - r.emit(&0, &mut Context::new(()), &mut h).unwrap_err(), - "content callback failed" - ); - assert!(!r.has_hook(&0)); - assert!(r.faulted()); - assert_eq!(r.depth, 0); - assert!(r.hooks.is_empty()); - assert!(r.run_scheduled(&mut h).is_err()); - } - #[test] - fn delivery_and_shared_callback_depth_fail_without_a_valid_continuation() { - let mut r = Runtime::new(4, 4, 4, 1).unwrap(); - for _ in 0..2 { - r.on(0, 1, 0.0, None, false).unwrap(); - } - let mut h = Host { - calls: 0, - reenter: false, - fail: false, - }; - assert!(r.emit(&0, &mut Context::new(()), &mut h).is_err()); - assert_eq!(h.calls, 1); - assert!(r.faulted()); - assert_eq!(r.depth, 0); - let mut r = Runtime::::new(4, 4, 1, 16).unwrap(); - assert!(r.callback(|r| r.callback(|_| Ok(()))).is_err()); - assert!(r.faulted()); - assert_eq!(r.depth, 0); - } - #[test] - fn capacity_and_owner_removal_preserve_hold_semantics() { - let mut r = Runtime::::new(1, 1, 4, 8).unwrap(); - r.after(1.0, 1, Some(9), true).unwrap(); - assert!(r.pending_holds()); - r.off_owner(Some(9)); - assert_eq!(r.pending(), 0); - assert!(!r.pending_holds()); - let mut h = Host { - calls: 0, - reenter: false, - fail: false, - }; - r.run_scheduled(&mut h).unwrap(); - assert!(r.timers.is_empty()); - assert!(r.after(1.0, 2, None, true).is_ok()); - assert!(r.after(1.0, 3, None, false).is_err()); - assert!(r.faulted()); - assert_eq!(r.pending(), 1); - } -} diff --git a/crates/engine/src/battle/grid.rs b/crates/engine/src/battle/grid.rs index e5d7245..d7241cc 100644 --- a/crates/engine/src/battle/grid.rs +++ b/crates/engine/src/battle/grid.rs @@ -196,7 +196,7 @@ pub struct Flow { } #[derive(Clone)] pub struct Grid { - tiles: Vec, + tiles: Arc<[Tile]>, rect: Rect, obstacle: [u8; N], unblockable: [i32; N], @@ -214,6 +214,9 @@ impl Grid { pub fn tiles(&self) -> &[Tile] { &self.tiles } + pub(crate) fn tile_layout(&self) -> Arc<[Tile]> { + Arc::clone(&self.tiles) + } pub fn rect(&self) -> Rect { self.rect } @@ -242,11 +245,14 @@ impl Grid { } else { String::new() }; - let glyphs: Vec = line.chars().collect(); + // Slice the original line: no per-glyph String allocation. + let glyphs: Vec<&str> = line + .char_indices() + .map(|(i, ch)| &line[i..i + ch.len_utf8()]) + .collect(); for c in 0..COLS { tiles.push(if let Some(g) = glyphs.get(c) { - let g = g.to_string(); - Tile::normalize(&g, &stage["legend"][&g]) + Tile::normalize(g, &stage["legend"][g]) } else { Tile::empty() }); @@ -258,7 +264,7 @@ impl Grid { i32::from(tiles[k].pass == "ALL" && tiles[k].terrain.as_deref() == Some("deepsea")) }); Ok(Self { - tiles, + tiles: tiles.into(), rect, obstacle: [0; N], unblockable, @@ -270,7 +276,7 @@ impl Grid { pub fn in_bounds([r, c]: [i32; 2]) -> bool { r >= 0 && r < ROWS as i32 && c >= 0 && c < COLS as i32 } - fn in_rect(&self, [r, c]: [i32; 2]) -> bool { + pub(crate) fn in_rect(&self, [r, c]: [i32; 2]) -> bool { r >= self.rect.r0 && r <= self.rect.r1 && c >= self.rect.c0 && c <= self.rect.c1 } pub fn walkable(&self, p: [i32; 2], ignore: bool) -> bool { @@ -703,46 +709,3 @@ pub fn segment_tiles([mut r, mut c]: [i32; 2], [r1, c1]: [i32; 2]) -> Vec<[i32; } out } - -#[cfg(test)] -mod tests { - use super::*; - fn open() -> Grid { - Grid::new( - &serde_json::json!({"rows": vec!["r".repeat(COLS); ROWS]}), - Rect::FULL, - ) - .unwrap() - } - #[test] - fn cache_is_bounded_and_invalidated_only_on_changes() { - let mut g = open(); - let before = g.flow_field([9, 2], true, false); - assert!(Arc::ptr_eq(&before, &g.flow_field([9, 2], true, false))); - g.set_obstacle([9, 8], false, CRATE).unwrap(); - assert!(Arc::ptr_eq(&before, &g.flow_field([9, 2], true, false))); - g.set_obstacle([9, 8], true, CRATE).unwrap(); - let after = g.flow_field([9, 2], true, false); - assert!(!Arc::ptr_eq(&before, &after)); - assert_eq!(before.dist[key([9, 8])], 6); // old output still owns its snapshot - assert_eq!(after.dist[key([9, 8])], 1005); - for k in 0..N { - g.flow_field(coord(k), true, false); - } - assert_eq!(g.cache.len(), 64); - } - #[test] - fn corner_clearance_and_obstacle_bits_are_independent() { - let mut g = open(); - g.set_obstacle([9, 8], true, CRATE).unwrap(); - g.set_obstacle([9, 8], true, BLOCK).unwrap(); - g.set_obstacle([9, 8], false, BLOCK).unwrap(); - assert!(g.walkable([9, 8], false)); - assert!(!g.ground_passable([9, 8], false)); - assert!(!g.straight_clear(7.0, 9.0, [10, 8])); - g.set_obstacle([9, 8], false, CRATE).unwrap(); - assert!(g.straight_clear(7.0, 9.0, [10, 8])); - assert!(g.find_path([-1, 0], [9, 2], false).is_none()); - assert_eq!(g.waypoints([9, 2], [9, 2], true, false), Some(vec![[9, 2]])); - } -} diff --git a/crates/engine/src/battle/health.rs b/crates/engine/src/battle/health.rs index 90937c8..302d44a 100644 --- a/crates/engine/src/battle/health.rs +++ b/crates/engine/src/battle/health.rs @@ -3,7 +3,7 @@ // Unit removal/redeployment and content callbacks are delegated to the battle host. use super::{ damage::{self, DamageType, Penetration}, - stats::UnitStats, + stats::{Stat, UnitStats}, }; use std::collections::BTreeMap; pub type Id = u64; @@ -13,6 +13,7 @@ pub enum Side { Enemy, } pub struct Unit { + pub(crate) operator: super::content::operators::Memory, pub deployment: super::deploy::State, pub targeting: super::targeting::State, pub hit_area: Option, @@ -30,6 +31,7 @@ pub struct Unit { pub stats: UnitStats, pub side: Side, pub owner: Option, + pub summoner: Option, pub deployed: bool, pub removed: bool, pub hidden: bool, @@ -54,12 +56,19 @@ pub struct Unit { pub healing_done: f64, pub regen_acc: f64, pub last_hit_at: f64, + pub(crate) polluted_at: f64, + pub(crate) chimera_at: f64, + pub(crate) terrain: super::terrain::State, pub last_attack_at: f64, pub attacks: u64, pub engaged: bool, pins: usize, } impl Unit { + /// Operators and their tokens have kits; map devices do not. + pub(crate) fn has_operator_kit(&self) -> bool { + self.side == Side::Ally && self.deployment.kind != super::deploy::Kind::Device + } pub fn blocking(&self) -> &[Id] { &self.blocking } @@ -68,6 +77,7 @@ impl Unit { } pub fn new(stats: UnitStats, side: Side) -> Self { Self { + operator: Default::default(), deployment: super::deploy::State::default(), targeting: super::targeting::State::default(), hit_area: None, @@ -85,6 +95,7 @@ impl Unit { stats, side, owner: None, + summoner: None, deployed: false, removed: false, hidden: false, @@ -106,6 +117,9 @@ impl Unit { damage_taken: 0.0, healing_done: 0.0, regen_acc: 0.0, + polluted_at: f64::NEG_INFINITY, + chimera_at: f64::NEG_INFINITY, + terrain: Default::default(), last_hit_at: f64::NEG_INFINITY, last_attack_at: f64::NEG_INFINITY, attacks: 0, @@ -118,18 +132,42 @@ impl Unit { pub struct PlayerTotals { pub damage: f64, pub boss_damage: f64, + /// Match-level SharedBossPool.onHit credits, accumulated in hit order. + pub match_boss_damage: f64, pub healing: f64, } pub struct Pool { pub hp: f64, pub max_hp: f64, } +#[derive(Clone, Copy)] +enum PoolPolicy { + Exact, + SharedBoss, +} +struct StoredPool { + value: Pool, + policy: PoolPolicy, +} +impl Pool { + pub(crate) fn validate_shared(&self) -> Result<(), String> { + if !self.max_hp.is_finite() + || self.max_hp < 1. + || !self.hp.is_finite() + || self.hp < 0. + || self.hp > self.max_hp + { + return Err("Boss pool requires finite 0 <= hp <= maxHp and maxHp >= 1".into()); + } + Ok(()) + } +} pub struct World { unit_sequence: u64, deployment_sequence: u64, attack_sequence: u64, units: BTreeMap, - pools: BTreeMap, + pools: BTreeMap, players: BTreeMap, capacities: [usize; 3], pub time: f64, @@ -212,10 +250,22 @@ impl World { Ok(()) } pub fn insert_pool(&mut self, id: Id, value: Pool) -> Result<(), String> { + self.insert_pool_with_policy(id, value, PoolPolicy::Exact) + } + pub(crate) fn insert_shared_boss_pool(&mut self, id: Id, value: Pool) -> Result<(), String> { + value.validate_shared()?; + self.insert_pool_with_policy(id, value, PoolPolicy::SharedBoss) + } + fn insert_pool_with_policy( + &mut self, + id: Id, + value: Pool, + policy: PoolPolicy, + ) -> Result<(), String> { if self.pools.contains_key(&id) || self.pools.len() >= self.capacities[1] { return Err("Duplicate pool or pool capacity exceeded".into()); } - self.pools.insert(id, value); + self.pools.insert(id, StoredPool { value, policy }); Ok(()) } pub fn insert_player(&mut self, id: Id, value: PlayerTotals) -> Result<(), String> { @@ -225,6 +275,9 @@ impl World { self.players.insert(id, value); Ok(()) } + pub fn unit_ids(&self) -> impl Iterator + '_ { + self.units.keys().copied() + } pub fn unit(&self, id: Id) -> Result<&Unit, String> { unit(self, id) } @@ -242,14 +295,17 @@ impl World { Ok(()) } pub fn pool(&self, id: Id) -> Option<&Pool> { - self.pools.get(&id) + self.pools.get(&id).map(|p| &p.value) } pub fn pool_mut(&mut self, id: Id) -> Option<&mut Pool> { - self.pools.get_mut(&id) + self.pools.get_mut(&id).map(|p| &mut p.value) } pub fn player(&self, id: Id) -> Option<&PlayerTotals> { self.players.get(&id) } + pub(crate) fn player_mut(&mut self, id: Id) -> Option<&mut PlayerTotals> { + self.players.get_mut(&id) + } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { @@ -296,6 +352,17 @@ pub struct Hit { /// All handlers run synchronously and may change world state, including the target's HP. /// Errors are technical failures propagated to the future environment owner. pub trait Hooks { + fn adjust_heal( + &mut self, + _source: Option, + _target: Id, + amount: f64, + _options: HealOptions, + _world: &mut World, + ) -> Result { + Ok(amount) + } + fn emit(&mut self, _event: &mut Event, _world: &mut World) -> Result<(), String> { Ok(()) } @@ -330,11 +397,11 @@ fn unit_mut(w: &mut World, id: Id) -> Result<&mut Unit, String> { .get_mut(&id) .ok_or_else(|| format!("Unknown health unit {id}")) } -fn stats(w: &mut World, id: Id, key: &str) -> Result { +fn stats(w: &mut World, id: Id, stat: Stat) -> Result { unit_mut(w, id)? .stats .stats() - .map(|s| s.n(key)) + .map(|s| s.get(stat)) .map_err(str::to_string) } fn flag(w: &mut World, id: Id, key: &str) -> Result { @@ -436,17 +503,34 @@ pub fn apply_hp_decrease( .and_then(|c| world.units.get(&c)) .filter(|c| c.side == Side::Ally) .and_then(|c| c.owner); - let p = world.pools.get_mut(&id).ok_or("Unknown boss pool")?; + let stored = world.pools.get_mut(&id).ok_or("Unknown boss pool")?; + let p = &mut stored.value; let before = p.hp; - if hp_amount > 0.0 { - p.hp = (p.hp - hp_amount).max(0.0); - } + let credited = match stored.policy { + PoolPolicy::SharedBoss if hp_amount.is_finite() && hp_amount > 0. && before > 0. => { + let taken = if before - hp_amount < 1. { + before + } else { + hp_amount + }; + p.hp -= taken; + taken + } + PoolPolicy::SharedBoss => 0., + PoolPolicy::Exact => { + if hp_amount > 0. { + p.hp = (p.hp - hp_amount).max(0.); + } + 0. + } + }; let d = (before - p.hp).max(0.0); dealt = if d.is_finite() { d } else { 0.0 }; let (pool_hp, max_hp) = (p.hp, p.max_hp); if let Some(owner) = credit_owner { if let Some(pp) = world.players.get_mut(&owner) { pp.boss_damage += dealt; + pp.match_boss_damage += credited; } } let u = unit_mut(world, hit.target)?; @@ -464,7 +548,7 @@ pub fn apply_hp_decrease( } else { 0.0 }; - u.stats.hp = u.stats.stats().map_err(str::to_string)?.n("maxHp") * ratio.min(1.0); + u.stats.hp = u.stats.stats().map_err(str::to_string)?.get(Stat::MaxHp) * ratio.min(1.0); } else { let before = unit(world, hit.target)?.stats.hp; let u = unit_mut(world, hit.target)?; @@ -477,7 +561,7 @@ pub fn apply_hp_decrease( && unit(world, hit.target)?.stats.alive && unit(world, hit.target)?.stats.hp < 1.0 { - let max = stats(world, hit.target, "maxHp")?; + let max = stats(world, hit.target, Stat::MaxHp)?; unit_mut(world, hit.target)?.stats.hp = 1.0f64.min(max); } } @@ -529,7 +613,7 @@ pub fn apply_hp_decrease( } let u = unit(world, hit.target)?; let dead = if let Some(id) = u.pool { - world.pools.get(&id).ok_or("Unknown boss pool")?.hp <= 0.0 + world.pools.get(&id).ok_or("Unknown boss pool")?.value.hp <= 0.0 } else { u.stats.hp <= 0.0 }; @@ -585,12 +669,13 @@ pub fn heal( } else { amount * if let Some(s) = source { - stats(world, s, "healingDealtMul")? + stats(world, s, Stat::HealingDealtMul)? } else { 1.0 } - * stats(world, target, "healingTakenMul")? + * stats(world, target, Stat::HealingTakenMul)? }; + amt = hooks.adjust_heal(source, target, amt, opts, world)?; if !(amt > 0.0) || !amt.is_finite() { return Ok(0.0); } @@ -626,7 +711,7 @@ pub fn heal( return Ok(0.0); } } - let max = stats(world, target, "maxHp")?; + let max = stats(world, target, Stat::MaxHp)?; let actual = amt.min(max - unit(world, target)?.stats.hp).max(0.0); let u = unit_mut(world, target)?; u.stats.hp = max.min(u.stats.hp + actual); @@ -660,100 +745,3 @@ pub fn heal( } Ok(actual) } - -#[cfg(test)] -mod tests { - use super::*; - use crate::battle::stats::{Base, Buff}; - fn world() -> World { - let mut w = World::new(1, 1, 1).unwrap(); - let mut base = Base::default(); - base.0.insert("maxHp".into(), 100.0); - let mut u = Unit::new(UnitStats::new(base), Side::Ally); - u.deployed = true; - u.stats.hp = 20.0; - w.insert_unit(1, u).unwrap(); - w - } - struct Host { - death: bool, - heal_calls: usize, - } - impl Hooks for Host { - fn emit(&mut self, e: &mut Event, w: &mut World) -> Result<(), String> { - if e.stage == Stage::Heal { - self.heal_calls += 1; - e.amount = 0.0; - if self.death { - w.unit_mut(e.target)?.stats.alive = false; - } - } - Ok(()) - } - fn kill(&mut self, _: Id, _: Option, _: &mut World) -> Result<(), String> { - Err("Unexpected kill".into()) - } - } - #[test] - fn registry_overflow_preserves_existing_units_and_allows_final_release() { - let mut w = world(); - assert!(w - .insert_unit(1, Unit::new(UnitStats::new(Base::default()), Side::Enemy)) - .is_err()); - assert!(w - .insert_unit(2, Unit::new(UnitStats::new(Base::default()), Side::Enemy)) - .is_err()); - assert_eq!(w.unit(1).unwrap().stats.hp, 20.0); - assert!(w.release_removed(1).is_err()); - w.unit_mut(1).unwrap().removed = true; - w.release_removed(1).unwrap(); - w.insert_unit(2, Unit::new(UnitStats::new(Base::default()), Side::Enemy)) - .unwrap(); - } - #[test] - fn regen_ignores_heal_modifier_but_rechecks_target_liveness() { - let mut w = world(); - let mut h = Host { - death: false, - heal_calls: 0, - }; - let opts = HealOptions { - regen: true, - ..HealOptions::default() - }; - assert_eq!(heal(&mut w, &mut h, Some(1), 1, 10.0, opts).unwrap(), 10.0); - assert_eq!(h.heal_calls, 1); - h.death = true; - assert_eq!(heal(&mut w, &mut h, Some(1), 1, 10.0, opts).unwrap(), 0.0); - assert_eq!(w.unit(1).unwrap().stats.hp, 30.0); - } - #[test] - fn restore_bypasses_heal_free_and_heal_callbacks() { - let mut w = world(); - w.unit_mut(1).unwrap().stats.set_buffs(vec![Buff { - flags: ["healFree".into(), "noHeal".into()].into_iter().collect(), - ..Buff::default() - }]); - let mut h = Host { - death: true, - heal_calls: 0, - }; - assert_eq!( - heal( - &mut w, - &mut h, - None, - 1, - 10.0, - HealOptions { - restore: true, - ..HealOptions::default() - } - ) - .unwrap(), - 10.0 - ); - assert_eq!(h.heal_calls, 0); - assert!(w.unit(1).unwrap().stats.alive); - } -} diff --git a/crates/engine/src/battle/hit.rs b/crates/engine/src/battle/hit.rs index 93e1b26..0cbc250 100644 --- a/crates/engine/src/battle/hit.rs +++ b/crates/engine/src/battle/hit.rs @@ -36,6 +36,7 @@ pub struct Request { pub attack_type: AttackType, pub element: Option, pub attack_id: Option, + pub trait_ally: Option, pub is_attack: bool, pub is_skill: bool, pub is_splash: bool, @@ -61,6 +62,7 @@ impl Request { attack_type: AttackType::Normal, element: None, attack_id: None, + trait_ally: None, is_attack: false, is_skill: false, is_splash: false, @@ -165,7 +167,7 @@ pub trait Hooks: health::Hooks + Sized { ) -> HookResult { Ok(()) } - fn cleanup(&mut self, _token: u64, _world: &mut World) -> HookResult { + fn cleanup(&mut self, _token: u64, _target: health::Id, _world: &mut World) -> HookResult { Ok(()) } /// Runs after HP guards, before HP application. The concrete content host owns @@ -270,7 +272,8 @@ impl injury::Hooks for Adapter<'_, H> { .notice(n, self.expected, self.request, self.world, effects, rng) } fn cleanup(&mut self, token: u64) -> HookResult { - self.host.cleanup(token, self.world) + self.host + .cleanup(token, self.request.hit.target, self.world) } } pub fn resolve( diff --git a/crates/engine/src/battle/injury.rs b/crates/engine/src/battle/injury.rs index 931c046..cc8ddbd 100644 --- a/crates/engine/src/battle/injury.rs +++ b/crates/engine/src/battle/injury.rs @@ -652,179 +652,3 @@ pub fn run>( deferred: event.deferred, }) } -#[cfg(test)] -mod tests { - use super::*; - #[derive(Default)] - struct Nested { - seen: Vec, - nesting: bool, - } - impl Hooks for Nested { - fn injury( - &mut self, - id: EffectId, - _: &mut InjuryEvent, - set: &mut Effects, - rng: &mut Rng, - ) -> HookResult { - if !self.nesting { - self.nesting = true; - set.remove(id); - execute( - set, - rng, - self, - 2.0, - DamageType::True, - DodgeMode::Ignore, - false, - )?; - } - Ok(()) - } - fn observe( - &mut self, - id: EffectId, - _: Observation, - _: &mut Effects, - _: &mut Rng, - ) -> HookResult { - self.seen.push(id); - Ok(()) - } - } - #[test] - fn nested_damage_keeps_removed_snapshot_alive_until_outer_return() { - let mut set = Effects::new(4).unwrap(); - let a = set - .insert(Effect { - injury: true, - observer: true, - ..Effect::default() - }) - .unwrap(); - let b = set - .insert(Effect { - observer: true, - ..Effect::default() - }) - .unwrap(); - let mut hooks = Nested::default(); - execute( - &mut set, - &mut Rng::new(42), - &mut hooks, - 1.0, - DamageType::True, - DodgeMode::Ignore, - false, - ) - .unwrap(); - assert_eq!(hooks.seen, vec![b, a, b]); // removed current observer still runs - assert!(set.get(a).is_none()); - assert_eq!(set.entries.len(), 1); - assert_eq!(set.depth, 0); - } - struct Deferred { - cleaned: Vec, - } - impl Hooks for Deferred { - fn injury( - &mut self, - _: EffectId, - e: &mut InjuryEvent, - _: &mut Effects, - _: &mut Rng, - ) -> HookResult { - e.defer(1)?; - e.defer(2)?; - Ok(()) - } - fn cleanup(&mut self, t: u64) -> HookResult { - self.cleaned.push(t); - if t == 1 { - Err("cleanup".into()) - } else { - Ok(()) - } - } - } - #[test] - fn cleanup_continues_after_errors_and_preserves_apply_failure() { - let mut set = Effects::new(4).unwrap(); - set.insert(Effect { - injury: true, - ..Effect::default() - }) - .unwrap(); - let mut hooks = Deferred { cleaned: vec![] }; - let result = execute( - &mut set, - &mut Rng::new(42), - &mut hooks, - 1.0, - DamageType::True, - DodgeMode::Ignore, - false, - ) - .unwrap(); - let settled: Result = result.settle(&mut hooks, |_| Err("apply".into()), 0.0); - assert_eq!(settled.unwrap_err(), "apply"); - assert_eq!(hooks.cleaned, vec![1, 2]); - } - #[test] - fn callback_budget_failure_releases_processing_depth() { - let mut set = Effects::with_limits(4, 1, 1).unwrap(); - set.insert(Effect { - injury: true, - ..Effect::default() - }) - .unwrap(); - let mut hooks = Deferred { cleaned: vec![] }; - assert!(execute( - &mut set, - &mut Rng::new(42), - &mut hooks, - 1.0, - DamageType::True, - DodgeMode::Ignore, - false - ) - .is_err()); - assert_eq!(set.depth, 0); - } - #[test] - fn equal_priorities_preserve_acquisition_order_even_for_negative_zero() { - let mut set = Effects::new(4).unwrap(); - let a = set - .insert(Effect { - priority: -0.0, - observer: true, - ..Effect::default() - }) - .unwrap(); - let b = set - .insert(Effect { - priority: 0.0, - observer: true, - ..Effect::default() - }) - .unwrap(); - let mut hooks = Nested { - seen: vec![], - nesting: true, - }; - execute( - &mut set, - &mut Rng::new(42), - &mut hooks, - 1.0, - DamageType::True, - DodgeMode::Ignore, - false, - ) - .unwrap(); - assert_eq!(hooks.seen, vec![a, b]); - } -} diff --git a/crates/engine/src/battle/ledger.rs b/crates/engine/src/battle/ledger.rs index 71ae436..1f611df 100644 --- a/crates/engine/src/battle/ledger.rs +++ b/crates/engine/src/battle/ledger.rs @@ -203,11 +203,14 @@ impl Ledger { self.timed_out = true; Ok(()) } + pub fn counted_leaks(&self) -> u64 { + self.leaks.iter().filter(|e| e["counted"] == true).count() as u64 + } /// Accounting projection of BattleResult. The battle assembles unit end state, /// damage/healing and layer gains separately before publishing its full result. pub fn report(&self, time: f64, reason: Option<&str>) -> Value { let pp = json!({"killed":self.killed,"total":self.total,"leaked":self.leaks, - "perfect":!self.leaks.iter().any(|e|e["counted"] == true),"killedInTotal":self.killed_in_total, + "perfect":self.counted_leaks() == 0,"killedInTotal":self.killed_in_total, "leakedInTotal":self.leaked_in_total,"resolved":self.resolved(),"creditedKills":self.credited_kills,"coins":self.coins}); let mut result = json!({"time":(time*1000.+0.5).floor()/1000.,"reason":reason, "perPlayer":{self.player.as_str().unwrap():pp},"killed":self.killed,"total":self.total,"resolved":self.resolved(),"errors":0}); @@ -217,36 +220,3 @@ impl Ledger { result } } - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn timeout_capacity_failure_preserves_successor_state() { - let mut q = Queue::new(3).unwrap(); - q.push(&json!({"enemyKey":"enemy_a","count":3}), true, false) - .unwrap(); - let mut l = Ledger::new(json!("p"), &q, 3, 1).unwrap(); - for id in 1..=2 { - let p = q.pop_due(0.).unwrap(); - l.spawn( - id, - Enemy::from_pending(&p, 1., l.player()).unwrap(), - p.precounted, - ) - .unwrap(); - } - assert!(l.timeout(&mut q).is_err()); - assert_eq!(l.alive().len(), 2); - assert_eq!(l.total, 3); - assert_eq!(q.pending().len(), 1); - assert_eq!(l.report(0., None)["perPlayer"]["p"]["leaked"], json!([])); - l.kill(1, false).unwrap(); - l.timeout(&mut q).unwrap(); - assert_eq!(l.total, 2); - assert_eq!(l.resolved(), 2); - assert_eq!(l.alive().len(), 1); - l.timeout(&mut q).unwrap(); - assert_eq!(l.leaked_count, 1); - } -} diff --git a/crates/engine/src/battle/mod.rs b/crates/engine/src/battle/mod.rs index a8cbc39..8051780 100644 --- a/crates/engine/src/battle/mod.rs +++ b/crates/engine/src/battle/mod.rs @@ -15,6 +15,7 @@ pub mod direction; pub mod displacement; pub mod element; pub mod enemy; +pub(crate) mod equipment; pub mod events; pub mod grid; pub mod health; @@ -34,5 +35,6 @@ pub mod spawns; pub mod stats; pub mod status; pub mod targeting; +pub(crate) mod terrain; pub mod valued; pub mod waves; diff --git a/crates/engine/src/battle/motion.rs b/crates/engine/src/battle/motion.rs index ca977d0..1cf8428 100644 --- a/crates/engine/src/battle/motion.rs +++ b/crates/engine/src/battle/motion.rs @@ -5,6 +5,7 @@ use super::{ buffs::Runtime, grid::{Flow, Grid, Rect, COLS, N}, health::{Id, World}, + stats::Stat, status::FearStamp, }; use crate::deterministic::{math::hypot, rng::Rng}; @@ -19,6 +20,7 @@ pub enum Leg { } #[derive(Clone, Debug)] pub struct Route { + pub(crate) patrol: bool, capacity: usize, legs: Vec, pub leg: usize, @@ -102,6 +104,7 @@ impl Route { }); } Ok(Self { + patrol: false, capacity, legs, leg: 0, @@ -115,6 +118,75 @@ impl Route { spawn, }) } + pub(crate) fn after_wait(&self, spawn: [f64; 2], rect: Rect) -> Result { + let mut next = self.remaining(spawn, rect)?; + if matches!(next.legs.first(), Some(Leg::Wait(_))) { + next.legs.remove(0); + } + Ok(next) + } + pub(crate) fn stationary(&self, spawn: [f64; 2], rect: Rect) -> Result { + let mut next = self.remaining(spawn, rect)?; + if next.capacity < 2 { + return Err("Stationary child route exceeds leg capacity".into()); + } + next.legs = vec![ + Leg::Wait(99999.), + Leg::Move { + tile: [ + (spawn[0] + 0.5) + .floor() + .clamp(rect.r0 as f64, rect.r1 as f64) as i32, + (spawn[1] + 0.5) + .floor() + .clamp(rect.c0 as f64, rect.c1 as f64) as i32, + ], + final_leg: true, + }, + ]; + Ok(next) + } + /// A child starts a fresh movement cursor at the parent's remaining legs. + pub(crate) fn remaining(&self, spawn: [f64; 2], rect: Rect) -> Result { + let mut legs: Vec<_> = self.legs.iter().skip(self.leg).cloned().collect(); + if let Some(Leg::Wait(time)) = legs.first_mut() { + *time = self.wait_left.unwrap_or(*time).max(0.); + } + if !legs.iter().any(|l| { + matches!( + l, + Leg::Move { + final_leg: true, + .. + } + ) + }) { + legs.push(Leg::Move { + tile: [ + (spawn[0].round() as i32).clamp(rect.r0, rect.r1), + (spawn[1].round() as i32).clamp(rect.c0, rect.c1), + ], + final_leg: true, + }); + } + if legs.len() > self.capacity { + return Err("Route leg capacity exceeded; no checkpoints dropped".into()); + } + Ok(Self { + patrol: self.patrol, + capacity: self.capacity, + legs, + leg: 0, + wait_left: None, + points: None, + point: 0, + version: 0, + suffix: vec![], + tail: None, + tail_version: 0, + spawn, + }) + } } #[derive(Clone, Debug)] pub struct Attract { @@ -158,7 +230,7 @@ pub trait Hooks { fn portal_pickup(&mut self, id: Id, w: &mut World, g: &mut Grid) -> Result { portal_pickup(w, g, id) } - fn leak(&mut self, id: Id, w: &mut World) -> Result<(), String>; + fn leak(&mut self, id: Id, w: &mut World, rng: &mut Rng) -> Result<(), String>; } fn round(x: f64) -> f64 { let f = x.floor(); @@ -381,6 +453,7 @@ pub fn advance( id: Id, dt: f64, mut standing: bool, + rng: &mut Rng, ) -> Result<(), String> { if !dt.is_finite() || dt < 0.0 { return Err("Invalid movement tick".into()); @@ -393,7 +466,7 @@ pub fn advance( let leg = route(w, id)?.legs.get(route(w, id)?.leg).cloned(); let Some(leg) = leg else { if !h.portal_pickup(id, w, g)? { - h.leak(id, w)?; + h.leak(id, w, rng)?; return Ok(()); } continue; @@ -442,7 +515,7 @@ pub fn advance( .stats .stats() .map_err(str::to_string)? - .n("moveSpeed") + .get(Stat::MoveSpeed) * 0.5; if speed <= 0.0 { w.unit_mut(id)?.moving = false; @@ -478,7 +551,7 @@ pub fn advance( .unwrap_or(false) { if final_leg && !h.portal_pickup(id, w, g)? { - h.leak(id, w)?; + h.leak(id, w, rng)?; return Ok(()); } let r = route_mut(w, id)?; @@ -490,20 +563,28 @@ pub fn advance( } Ok(()) } -fn step(w: &mut World, id: Id, p: [f64; 2], distance: f64) -> Result<(f64, bool, f64), String> { - let u = w.unit_mut(id)?; - let dy = p[0] - u.position[0]; - let dx = p[1] - u.position[1]; +pub(crate) fn step_position( + mut position: [f64; 2], + p: [f64; 2], + distance: f64, +) -> ([f64; 2], f64, bool, f64) { + let dy = p[0] - position[0]; + let dx = p[1] - position[1]; let d = hypot(dx, dy); if d <= distance { - u.position = p; - Ok((distance - d, true, d)) + (p, distance - d, true, d) } else { - u.position[1] += (dx / d) * distance; - u.position[0] += (dy / d) * distance; - Ok((0.0, false, d)) + position[1] += (dx / d) * distance; + position[0] += (dy / d) * distance; + (position, 0.0, false, d) } } +fn step(w: &mut World, id: Id, p: [f64; 2], distance: f64) -> Result<(f64, bool, f64), String> { + let u = w.unit_mut(id)?; + let (position, left, reached, used) = step_position(u.position, p, distance); + u.position = position; + Ok((left, reached, used)) +} fn open(g: &Grid, fly: bool, k: usize) -> bool { let tile = coord(k); (if fly { @@ -768,7 +849,7 @@ pub fn move_feared( .stats .stats() .map_err(str::to_string)? - .n("moveSpeed") + .get(Stat::MoveSpeed) * 0.5; let mut moved = false; if speed > 0.0 { @@ -829,30 +910,38 @@ pub fn update( if !dt.is_finite() || dt < 0.0 { return Err("Invalid movement tick".into()); } - let u = w.unit_mut(id)?; - let flags = u.stats.stats().map_err(str::to_string)?.flags.clone(); - if flags.contains("noMove") { - u.moving = false; + let (no_move, fear, attracted) = { + let u = w.unit_mut(id)?; + let hidden = u.hidden; + let f = &u.stats.stats().map_err(str::to_string)?.flags; + ( + f.contains("noMove"), + f.contains("fear") && !hidden, + f.contains("attract"), + ) + }; + if no_move { + w.unit_mut(id)?.moving = false; return Ok(()); } - if flags.contains("fear") && !u.hidden { + if fear { if unbalanced { - u.moving = false; + w.unit_mut(id)?.moving = false; return Ok(()); } return move_feared(w, g, rng, id, dt); } - if u.motion.fear.is_some() { + if w.unit(id)?.motion.fear.is_some() { end_fear(w, id)?; } - if flags.contains("attract") { + if attracted { if standing { w.unit_mut(id)?.moving = false; return Ok(()); } return move_attracted(w, g, r, id, dt); } - advance(w, g, h, id, dt, standing) + advance(w, g, h, id, dt, standing, rng) } pub fn move_attracted( w: &mut World, @@ -920,7 +1009,7 @@ pub fn move_attracted( .stats .stats() .map_err(str::to_string)? - .n("moveSpeed") + .get(Stat::MoveSpeed) * 0.5 * dt; let mut moved = false; @@ -951,87 +1040,3 @@ pub fn move_attracted( Ok(()) }) } - -#[cfg(test)] -mod tests { - use super::super::{ - health::{Side, Unit}, - stats::{Base, UnitStats}, - }; - use super::*; - use serde_json::json; - struct Host; - impl Hooks for Host { - fn check_block(&mut self, _: Id, _: &mut World, _: &mut Grid) -> Result { - Ok(false) - } - fn hidden(&mut self, id: Id, on: bool, w: &mut World) -> Result<(), String> { - w.unit_mut(id)?.hidden = on; - Ok(()) - } - fn cut_attack_stand(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn leak(&mut self, id: Id, w: &mut World) -> Result<(), String> { - w.unit_mut(id)?.stats.alive = false; - Ok(()) - } - } - fn world() -> World { - let mut w = World::new(1, 1, 1).unwrap(); - let mut u = Unit::new(UnitStats::new(Base::default()), Side::Enemy); - u.deployed = true; - w.insert_unit(1, u).unwrap(); - w - } - #[test] - fn route_and_portal_capacity_fail_without_clipping_legs() { - let data = json!({"checkpoints":[{"type":"WAIT","time":1.0}],"end":[10,6]}); - assert!(Route::compile(&data, Rect::FULL, 1, [10.0, 6.0]).is_err()); - assert!(Route::compile(&json!({"end":[1.5,6]}), Rect::FULL, 8, [10.0, 6.0]).is_err()); - let mut rows = vec!["r".repeat(21); 19]; - rows[10].replace_range(6..7, "I"); - rows[10].replace_range(8..9, "O"); - rows[10].replace_range(10..11, "E"); - let g = Grid::new(&json!({"rows":rows,"legend":{}}), Rect::FULL).unwrap(); - let mut w = world(); - let u = w.unit_mut(1).unwrap(); - u.position = [10.0, 6.0]; - u.motion.route = - Some(Route::compile(&json!({"end":[10,6]}), Rect::FULL, 1, u.position).unwrap()); - assert!(portal_pickup(&mut w, &g, 1).is_err()); - assert_eq!(route(&w, 1).unwrap().legs.len(), 1); - assert_eq!(route(&w, 1).unwrap().leg, 0); - // A farther exit outside this battle's rectangle cannot receive the unit. - rows[2].replace_range(20..21, "O"); - let rect = Rect { - r0: 9, - r1: 12, - c0: 2, - c1: 10, - }; - let g = Grid::new(&json!({"rows":rows,"legend":{}}), rect).unwrap(); - w.unit_mut(1).unwrap().motion.route = - Some(Route::compile(&json!({"end":[10,6]}), rect, 8, [10.0, 6.0]).unwrap()); - assert!(portal_pickup(&mut w, &g, 1).unwrap()); - assert!(matches!( - route(&w, 1).unwrap().legs[3], - Leg::Appear([10, 8]) - )); - } - #[test] - fn attack_stand_advances_wait_and_teleport_before_holding_walk() { - let mut w = world(); - let mut g = Grid::new( - &json!({"rows":vec!["r".repeat(21);19],"legend":{}}), - Rect::FULL, - ) - .unwrap(); - w.unit_mut(1).unwrap().motion.route=Some(Route::compile(&json!({"checkpoints":[{"type":"WAIT","time":0.1},{"type":"DISAPPEAR"},{"type":"APPEAR","pos":[10,6]},{"type":"WAIT","time":0.1}],"end":[10,8]}),Rect::FULL,8,[0.0;2]).unwrap()); - advance(&mut w, &mut g, &mut Host, 1, 0.15, true).unwrap(); - assert_eq!(w.unit(1).unwrap().position, [10.0, 6.0]); - assert!(!w.unit(1).unwrap().hidden); - assert_eq!(route(&w, 1).unwrap().leg, 3); - assert!((route(&w, 1).unwrap().wait_left.unwrap() - 0.05).abs() < 1e-15); - } -} diff --git a/crates/engine/src/battle/operators.rs b/crates/engine/src/battle/operators.rs index 4ae11be..ecf61fb 100644 --- a/crates/engine/src/battle/operators.rs +++ b/crates/engine/src/battle/operators.rs @@ -17,53 +17,130 @@ use super::{ }; use crate::data::Catalog; use serde_json::Value; +use std::borrow::Cow; use std::collections::BTreeMap; use std::sync::Arc; +pub(crate) fn parse_range(raw: &Value) -> Result, String> { + let grid = raw.as_array().ok_or("Missing range grid")?; + if grid.is_empty() || grid.len() > super::grid::N { + return Err("Invalid range size".into()); + } + grid.iter() + .map(|p| { + if p.as_array().map(Vec::len) != Some(2) { + return Err("Expected range offset pair".to_string()); + } + let get = |i: usize| { + p[i].as_i64() + .and_then(|n| i32::try_from(n).ok()) + .filter(|n| n.unsigned_abs() <= super::grid::COLS as u32) + .ok_or("Range offset outside field bound".to_string()) + }; + Ok([get(0)?, get(1)?]) + }) + .collect::, String>>() +} pub struct Definition { pub key: String, base: Base, + original_cost: f64, + pub(crate) char_id: String, + pub(crate) profession: &'static str, + pub(crate) laterano: bool, + max_charges: u32, + pub(crate) extra: super::content::operators::Extra, modifiers: Numbers, - permanent: Option, - range_grid: Vec<[i32; 2]>, + permanent: Vec, + pub(crate) equipment: Vec, + pub(crate) range_grid: Vec<[i32; 2]>, pub(crate) combat: Combat, pub(crate) hit: super::content::operators::HitHandler, + pub(crate) attack_filter: Option, + skill_flags: std::collections::BTreeSet, + pub(crate) death_heal: Option, + pub(crate) incoming_hit: Option, + pub(crate) attack_proc: Option, + pub(crate) dp_on_kill: f64, + pub(crate) initial_dp: f64, + pub(crate) trigger_range: Option>, + pub(crate) skill_start: Option, + pub(crate) grid_scale: Option, + pub(crate) while_blocked: Option, + pub(crate) ground_bonus: Option, + pub(crate) aura: Option, + pub(crate) element_attach: Option, + pub(crate) undying: bool, + end_stun: f64, + pub(crate) melee_operator: bool, kind: Kind, spec: skills::Spec, cost: f64, + no_skill: bool, } #[derive(Clone, Copy)] pub(crate) struct Combat { pub profile: AttackProfile, pub damage: super::damage::DamageType, + pub skill_damage: Option, + pub normal_hits: u32, + pub skill_scale: f64, + pub heal: bool, + pub skill_heal: bool, + pub skill_heal_scale: f64, + pub skill_direct: bool, + pub split_mul: Option, pub projectile: Option<&'static str>, pub projectile_speed: f64, pub area: super::attacks::Area, pub skill_area: super::attacks::Area, pub sluggish: f64, pub skill_sluggish: f64, + pub skill_hits: u32, + pub skill_profile: Option, +} +impl Combat { + pub(crate) const MAX_HITS: u32 = 5; } impl Default for Combat { fn default() -> Self { Self { profile: AttackProfile::default(), damage: super::damage::DamageType::Physical, + skill_damage: None, + normal_hits: 1, + skill_scale: 1., + heal: false, + skill_heal: false, + skill_heal_scale: 1., + skill_direct: false, + split_mul: None, projectile: None, projectile_speed: 0., area: Default::default(), skill_area: Default::default(), sluggish: 0., skill_sluggish: 0., + skill_hits: 1, + skill_profile: None, } } } impl Definition { + pub(crate) fn skill_kind(&self) -> Kind { + self.kind + } + pub(crate) fn sp_type(&self) -> skills::SpType { + self.spec.sp_type + } + pub(crate) fn skill_event( &self, w: &mut World, r: &mut buffs::Runtime, h: &mut H, e: skills::Event, + direction: Direction, c: &mut skills::Context, s: &mut skills::Runtime, ) -> Result<(), String> { @@ -71,7 +148,12 @@ impl Definition { &mut Skill { r, h, + definition: self, + aura: self.aura.as_ref(), + direction, + end_stun: self.end_stun, mods: &self.modifiers, + flags: &self.skill_flags, }, e, c, @@ -80,17 +162,262 @@ impl Definition { ) } pub fn load(data: &Catalog, key: &str) -> Result { + Self::load_with_skill(data, key, None) + } + /// Select a supported skill by its external record index; module and potential + /// stay at their defaults. Unknown indices never fall back to a default skill. + pub fn load_with_skill(data: &Catalog, key: &str, index: Option) -> Result { let raw = &data.table("chess").ok_or("Missing chess data")?[key]; - Self::compile(key, raw) + let mut definition = if let Some(index) = index { + let skill = raw["skills"] + .as_array() + .into_iter() + .flatten() + .find(|s| s["index"].as_u64() == Some(u64::from(index))) + .ok_or_else(|| format!("Unknown operator skill index {index}: {key}"))?; + let mut selected = raw.clone(); + + selected["skill"] = skill.clone(); + Self::compile(key, &selected) + } else { + Self::compile(key, raw) + }?; + definition + .permanent + .extend(super::content::operators::passive_garrisons(data, raw)?); + for gid in raw["garrisonIds"].as_array().into_iter().flatten() { + let g = &data.table("garrisons").ok_or("Missing garrison data")? + [gid.as_str().ok_or("Expected garrison id")?]; + match g["effectKey"].as_str().unwrap_or("") { + "act1autochess_gar_eff_chaos" => definition.extra.weakness = true, + "act1autochess_gar_eff_attack_enemy" => { + if let Some(tag) = g["bbStr"]["check_tag"].as_str() { + definition + .extra + .tag_scale + .push((tag.into(), number(&g["bb"]["atk"], 1.))); + } + } + _ => {} + } + } + Ok(definition) + } + + /// Resolve a summon from the selected owner form. + pub(crate) fn token(data: &Catalog, key: &str, owner: &str) -> Result { + use super::content::operators::Skill; + let raw = data + .table("tokens") + .and_then(|t| t.get(key)) + .ok_or("Unknown summon definition")?; + let mut selected = raw.clone(); + if key == "enemy_9012_acloon" { + selected["rangeGrid"] = serde_json::json!([[0, 0]]); + selected["stats"]["spRecovery"] = Value::from(1.); + } + + if let Some(variant) = raw["variants"].get(owner) { + for (key, value) in variant.as_object().ok_or("Invalid summon variant")? { + selected[key] = value.clone(); + } + } + let ranged = selected["attackKind"] == "ranged" || selected["attackKind"] == "heal"; + let projectile = match selected["projectile"].as_str().unwrap_or("none") { + "none" | "orb" => "none", + "arrow" => "arrow", + "bolt" => "bolt", + "lob" => "lob", + "bomb" => "bomb", + _ => return Err("Unsupported summon projectile".into()), + }; + let position = if selected["position"] == "RANGED" { + "RANGED" + } else { + "MELEE" + }; + let kit = Kit { + position, + profession: "TOKEN", + branch: "native_token", + ranged, + can_hit_fly: selected["canHitFly"] == true, + physical: selected["dmgType"] != "arts", + projectile, + projectile_speed: match projectile { + "arrow" => 14., + "bolt" => 11., + "bomb" | "lob" => 8., + _ => 0., + }, + required_range: None, + skills: &[Skill { + id: "native_token", + kind: Kind::Instant, + sp_type: skills::SpType::Time, + rule: "NEVER", + attack_override: false, + }], + build: |raw, _, spec| { + spec.combat.profile.no_attack = raw["nativeNoAttack"] == true; + if raw["tokenId"] == "enemy_9012_acloon" { + super::runtime::kits::yanyou::build(raw, spec); + } + if raw["tokenId"] == "token_10028_vigil_wolf" { + super::runtime::kits::wolf::build(raw, spec); + } + if raw["tokenId"] == "token_10030_mlyss_wtrman" { + super::runtime::kits::manifold::build(raw, spec); + } + if raw["tokenId"] == "token_10000_silent_healrb" + || raw["tokenId"] == "token_10041_cathy_catsld" + { + super::runtime::kits::prepared_summon::build(raw, spec); + } + if raw["nativeTrueDamage"] == true { + spec.combat.damage = super::damage::DamageType::True; + } + if raw["tokenId"] == "token_10039_ulpia_block" + || raw["tokenId"] == "token_10031_swire2_gdtrap" + { + spec.combat.profile.no_attack = true; + let mut buff = Buff { + key: Some("trait:untargetable".into()), + permanent: true, + ..Default::default() + }; + buff.runtime.persist = true; + buff.flags.insert("untargetable".into()); + if raw["tokenId"] == "token_10039_ulpia_block" { + spec.extra.effects.permanent.push(buff); + } else { + let mut hold = Buff { + key: Some("token:champagneHold".into()), + permanent: true, + ..Default::default() + }; + hold.runtime.persist = true; + hold.flags = ["noHeal", "healFree", "isolated"] + .map(str::to_string) + .into(); + spec.extra.effects.permanent.extend([hold, buff]); + } + } + let mut buff = Buff { + key: Some("trait:abnormal".into()), + permanent: true, + ..Default::default() + }; + buff.runtime.persist = true; + for flag in raw["abnormal"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if flag == "healFree" || flag == "isolated" { + buff.flags.insert("noHeal".into()); + } + if flag == "isolated" { + buff.flags.insert("isolated".into()); + } + } + if !buff.flags.is_empty() { + spec.extra.effects.permanent.push(buff); + } + Ok(()) + }, + }; + if selected["dmgType"] == "heal" { + selected["dmgType"] = Value::from("phys"); + } + selected["nativeTrueDamage"] = Value::Bool(selected["dmgType"] == "true"); + if selected["nativeTrueDamage"] == true { + selected["dmgType"] = Value::from("phys"); + } + selected["nativeNoAttack"] = Value::Bool(selected["attackKind"] == "none"); + selected["attackKind"] = Value::from(if ranged { "ranged" } else { "melee" }); + selected["projectile"] = Value::from(projectile); + selected["position"] = Value::from(position); + selected["profession"] = Value::from("TOKEN"); + selected["subProfessionId"] = Value::from("native_token"); + selected["immunities"] = Value::Null; + selected["nativeSkill"] = selected["skill"].clone(); + selected["skill"] = serde_json::json!({ "skillId":"native_token", "spType":"INCREASE_WITH_TIME", "trigger":{"rule":"NEVER"} }); + let mut definition = Self::compile_kit(key, &selected, &kit)?; + definition.no_skill = true; + if key == "enemy_9012_acloon" { + let sk = selected["skills"] + .as_array() + .and_then(|a| a.iter().find(|s| s["prefabKey"] == "Skill_2")) + .ok_or("Missing yanyou skill")?; + definition.no_skill = false; + definition.kind = Kind::Duration; + definition.cost = number(&sk["cooldown"], 15.); + definition.spec.duration = number(&sk["bb"]["hit_duration"], 20.); + definition.spec.init_sp = + (definition.cost - number(&sk["initCooldown"], definition.cost)).max(0.); + definition.spec.rule = skills::Rule::Default; + } + + if key == "token_10030_mlyss_wtrman" { + definition.kind = Kind::Toggle; + definition.no_skill = false; + definition.spec.duration = number(&selected["nativeSkill"]["duration"], 0.).max(0.); + definition.spec.init_sp = number(&selected["nativeSkill"]["initSp"], 0.).max(0.); + definition.spec.sp_type = skills::SpType::Time; + definition.cost = number(&selected["nativeSkill"]["spCost"], 0.).max(0.); + } + + Ok(definition) } - /// Defaults only: no selected skill/module, potential, items or custom data - /// composition is inferred. Raw records already contain default module stats. + pub fn load_with_loadout( + data: &Catalog, + key: &str, + index: Option, + items: &[String], + ) -> Result { + if items.len() > 16 { + return Err("Equipment slot capacity exceeded".into()); + } + let mut definition = Self::load_with_skill(data, key, index)?; + for id in items { + definition + .equipment + .push(super::equipment::compile(data, id)?); + } + definition.laterano = super::equipment::bonds(data, key, items) + .iter() + .any(|b| b == "lateranoShip"); + Ok(definition) + } + /// Compile an explicitly supported operator skill with its recorded loadout. pub fn compile(key: &str, raw: &Value) -> Result { - let kit = Kit::resolve(key)?; - let (skill_id, profession, branch) = kit.identity(); - if !raw.is_object() || raw["skill"]["skillId"] != skill_id { - return Err(format!("Unsupported default operator definition: {key}")); + let kit = if raw["isDiy"] == true { + match raw["charId"].as_str() { + Some("char_4231_clemnt") => &super::runtime::kits::clemnt::KIT, + _ => { + return Err(format!( + "Unsupported DIY combat operator: {}", + raw["charId"] + )) + } + } + } else { + Kit::resolve(key)? + }; + Self::compile_kit(key, raw, kit) + } + fn compile_kit(key: &str, raw: &Value, kit: &Kit) -> Result { + let skill_id = raw["skill"]["skillId"].as_str().unwrap_or(""); + if !raw.is_object() { + return Err(format!("Invalid operator definition: {key}")); } + let selected = kit + .skills + .iter() + .find(|s| s.id == skill_id) + .ok_or_else(|| format!("Unsupported operator skill definition: {key}"))?; let st = &raw["stats"]; let mut base = Base::default(); for (key, aliases, default, min) in [ @@ -139,114 +466,264 @@ impl Definition { } base.0.insert("moveSpeed".into(), 0.); let skill = &raw["skill"]; - let ranged = kit.ranged(); - let rule = if ranged { "DEFAULT" } else { "TAKE_DAMAGE" }; - if raw["position"] != if ranged { "RANGED" } else { "MELEE" } - || raw["profession"] != profession - || raw["subProfessionId"] != branch + let ranged = kit.ranged; + let rule = selected.rule; + let sp_type = selected.sp_type; + if raw["position"] != kit.position + || raw["profession"] != kit.profession + || raw["subProfessionId"] != kit.branch || raw["immunities"] .as_object() .is_some_and(|o| o.values().any(|v| *v == true)) || skill["spType"] - != if kit.passive() { - "ON_DEPLOY" - } else { - "INCREASE_WITH_TIME" + != match sp_type { + skills::SpType::None => "ON_DEPLOY", + skills::SpType::Hurt => "INCREASE_WHEN_TAKEN_DAMAGE", + skills::SpType::Time => "INCREASE_WITH_TIME", + skills::SpType::Attack => "INCREASE_WHEN_ATTACK", } || skill["trigger"]["rule"] != rule - || number(&skill["maxChargeTime"], 1.).max(1.).floor() != 1. + || number(&skill["maxChargeTime"], 1.).max(1.).floor() > 64. { return Err(format!("Unsupported operator mechanics: {key}")); } for (field, expected) in [ ( "attackKind", - Value::from(if ranged { "ranged" } else { "melee" }), + Value::from(if kit.healing() { + "heal" + } else if matches!(kit.branch, "phalanx" | "librator" | "bard") { + "none" + } else if ranged { + "ranged" + } else { + "melee" + }), ), ( "dmgType", - Value::from(if kit.physical() { "phys" } else { "arts" }), + Value::from(if kit.healing() || kit.branch == "bard" { + "heal" + } else if kit.physical { + "phys" + } else { + "arts" + }), ), - ("projectile", Value::from(kit.projectile())), - ("canHitFly", Value::from(ranged)), + ("projectile", Value::from(kit.projectile)), + ("canHitFly", Value::from(kit.can_hit_fly)), ] { if !raw[field].is_null() && raw[field] != expected { return Err(format!("Unsupported operator profile {field}: {key}")); } } - if !raw["targetPriority"].is_null() || !raw["splashRadius"].is_null() { + if (!raw["targetPriority"].is_null() + && !(raw["targetPriority"] == "fly" && kit.branch == "fastshot") + && !(raw["targetPriority"] == "lowestDef" && kit.branch == "longrange")) + || !raw["splashRadius"].is_null() + { return Err(format!("Unsupported operator targeting: {key}")); } let grid = raw["rangeGrid"] .as_array() .ok_or("Missing operator attack range")?; - if grid.is_empty() - || grid.len() > super::grid::N - || (kit == Kit::Yak && raw["rangeGrid"] != serde_json::json!([[0, 0]])) - { + if grid.is_empty() || grid.len() > super::grid::N { return Err("Invalid or unsupported operator range".into()); } - let range_grid = grid - .iter() - .map(|p| { - if p.as_array().map(Vec::len) != Some(2) { - return Err("Expected range offset pair".to_string()); - } - let get = |i: usize| { - p[i].as_i64() - .and_then(|n| i32::try_from(n).ok()) - .filter(|n| n.unsigned_abs() <= super::grid::COLS as u32) - .ok_or("Range offset outside field bound".to_string()) - }; - Ok([get(0)?, get(1)?]) - }) - .collect::, String>>()?; - let content = kit.build(raw); - let has_modifiers = !content.modifiers.is_empty(); + let mut range_grid = parse_range(&raw["rangeGrid"])?; + if kit + .required_range + .is_some_and(|required| range_grid != required) + { + return Err("Unsupported operator range".into()); + } + let content = kit.build(raw)?; + if content.combat.normal_hits == 0 + || content.combat.normal_hits > Combat::MAX_HITS + || content.combat.skill_hits == 0 + || content.combat.skill_hits > Combat::MAX_HITS + { + return Err(format!("Unsupported operator hit count: {key}")); + } + if let Some(grid) = &content.extra.effects.base_range { + range_grid = grid.clone(); + } + base.0.insert( + "respawnTime".into(), + (base.0["respawnTime"] + content.extra.effects.respawn_delta).max(0.), + ); + let original_cost = base.0["cost"]; + base.0.insert( + "cost".into(), + (original_cost + content.extra.cost_delta).max(0.), + ); + let has_modifiers = !content.modifiers.is_empty() || !content.skill_flags.is_empty(); Ok(Self { + no_skill: false, key: key.into(), + original_cost, + char_id: raw["charId"].as_str().unwrap_or("").into(), + profession: kit.profession, + laterano: raw["bonds"] + .as_array() + .is_some_and(|a| a.iter().any(|x| x == "lateranoShip")), + equipment: Vec::new(), + max_charges: number(&skill["maxChargeTime"], 1.).floor().max(1.) as u32, base, modifiers: content.modifiers, - permanent: content.permanent, + permanent: content + .permanent + .into_iter() + .chain(content.extra.effects.permanent.iter().cloned()) + .collect(), range_grid, combat: content.combat, hit: content.hit, - kind: if kit.passive() { - Kind::Passive - } else { - Kind::Duration - }, + attack_filter: content.attack_filter, + skill_flags: content.skill_flags, + death_heal: content.death_heal, + incoming_hit: content.incoming_hit, + attack_proc: content.attack_proc, + dp_on_kill: content.dp_on_kill, + initial_dp: content.initial_dp, + trigger_range: content.trigger_range, + skill_start: content.skill_start, + grid_scale: content.grid_scale, + while_blocked: content.while_blocked, + ground_bonus: content.ground_bonus, + aura: content.aura, + element_attach: content.element_attach, + undying: content.undying, + end_stun: content.end_stun, + melee_operator: kit.position == "MELEE", + kind: selected.kind, spec: skills::Spec { - duration: number(&skill["duration"], 0.), + duration: content + .extra + .duration + .unwrap_or_else(|| number(&skill["duration"], 0.)), + activate_on_deploy: content.extra.deploy, + ammo: content.extra.effects.ammo_count, init_sp: number(&skill["initSp"], 0.).max(0.), - rule: skills::Rule::parse(rule), - attack: kit.attack_override(), + rule: content + .rule_override + .unwrap_or_else(|| skills::Rule::parse(rule)), + attack: selected.attack_override, + heal_skill: content.combat.heal + || content.combat.skill_heal + || content.extra.support.plasma.is_some() + || content.extra.support.bandage.is_some(), + trigger_allies: content.combat.heal || content.combat.skill_heal, + extra_ranges: matches!( + content.extra.tactics, + super::content::operators::Tactics::Mlyss(_) + ), + on_tick: !matches!( + content.extra.advanced, + super::content::operators::Advanced::None + ) || !matches!( + content.extra.tactics, + super::content::operators::Tactics::None + ) || content.extra.support.cook.is_some() + || !content.extra.support.peaks.is_empty() + || content.extra.support.phalanx.is_some() + || content + .extra + .support + .enemy_auras + .iter() + .any(|a| a.active_only), modifiers: has_modifiers, - sp_type: if kit.passive() { - skills::SpType::None - } else { - skills::SpType::Time - }, + sp_type, manual: skill["skillType"] .as_str() .unwrap_or("MANUAL") .eq_ignore_ascii_case("MANUAL"), ..Default::default() }, - cost: number(&skill["spCost"], 0.).max(0.), + cost: if content.extra.deploy { + 0. + } else { + number(&skill["spCost"], 0.).max(0.) + }, + extra: content.extra, }) } } +#[derive(PartialEq)] +pub(crate) enum RangeGeometry<'a> { + Absolute(Cow<'a, [usize]>), + Relative { + grid: Cow<'a, [[i32; 2]]>, + origin: [i32; 2], + direction: Direction, + extend: u32, + extra: Cow<'a, [usize]>, + }, +} +impl RangeGeometry<'_> { + pub(crate) fn keys(&self) -> Vec { + match self { + Self::Absolute(keys) => keys.to_vec(), + Self::Relative { + grid, + origin, + direction, + extend, + extra, + } => { + let mut keys = super::targeting::absolute_range(grid, *origin, *direction, *extend); + for &key in extra.iter() { + if !keys.contains(&key) { + keys.push(key); + } + } + keys + } + } + } + pub(crate) fn owned(self) -> RangeGeometry<'static> { + match self { + Self::Absolute(keys) => RangeGeometry::Absolute(Cow::Owned(keys.into_owned())), + Self::Relative { + grid, + origin, + direction, + extend, + extra, + } => RangeGeometry::Relative { + grid: Cow::Owned(grid.into_owned()), + origin, + direction, + extend, + extra: Cow::Owned(extra.into_owned()), + }, + } + } +} + pub struct Entry { + next_aura: f64, + next_cost: f64, + next_reveal: f64, pub definition: Arc, pub direction: Direction, skill: Option, } impl Entry { + pub(crate) fn talent_sp_eligible(&self, active: bool) -> bool { + if let Some(s) = &self.skill { + !s.bank.no_skill + && s.bank.kind != Kind::Passive + && !(s.bank.active && s.bank.kind.timed()) + } else { + self.definition.kind != Kind::Passive && !(active && self.definition.kind.timed()) + } + } pub fn skill(&self) -> Result<&skills::Runtime, String> { self.skill .as_ref() - .ok_or("Operator skill is already executing".into()) + .ok_or_else(|| "Operator skill is already executing".into()) } } /// Default 0.3.3 normal-field deployment comparator. This follows the source @@ -285,6 +762,8 @@ pub struct Placement { pub struct Roster { entries: BTreeMap, order: Vec, + kit_observers: Vec<(Id, Arc)>, + tick_observers: Vec<(Id, Arc)>, deployment: Deployment, capacity: usize, depth: usize, @@ -317,6 +796,8 @@ impl Roster { Ok(Self { entries: BTreeMap::new(), order: vec![], + kit_observers: vec![], + tick_observers: vec![], deployment, capacity, depth, @@ -345,10 +826,109 @@ impl Roster { pub fn ids(&self) -> &[Id] { &self.order } + fn register_observer(&mut self, id: Id) { + use super::runtime::kits::dispatch::Event; + let def = &self.entries[&id].definition; + if let Some(kit) = def.extra.tactics.behavior() { + if kit.observes(&Event::Tick) { + self.tick_observers.push((id, Arc::clone(def))); + } + self.kit_observers.push((id, Arc::clone(def))); + } + } + pub(crate) fn kit_observers(&self, tick: bool) -> &[(Id, Arc)] { + if tick { + &self.tick_observers + } else { + &self.kit_observers + } + } pub fn entry(&self, id: Id) -> Result<&Entry, String> { self.entries .get(&id) - .ok_or("Unknown operator identity".into()) + .ok_or_else(|| "Unknown operator identity".into()) + } + /// Earliest scheduled callback. None denotes a per-frame mechanism without a quiet planner. + pub(crate) fn quiet_deadline(&self, w: &World) -> Result, String> { + use super::content::operators::{Advanced, Tactics}; + let mut at = f64::INFINITY; + for &id in &self.order { + let entry = self.entry(id)?; + let def = &entry.definition; + let extra = &def.extra; + let u = w.unit(id)?; + let cfg = &extra.support; + let fx = &extra.effects; + if !matches!(extra.advanced, Advanced::None) + || !matches!(extra.tactics, Tactics::None | Tactics::Indigo(_)) + || extra.hp_speed.is_some() + || fx.condition.is_some() + || def.while_blocked.as_ref().is_some_and(|effect| { + u.blocking().is_empty() + && u.stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(effect.key)) + }) + || u.operator.blessing_pending + || !u.operator.advanced.locked.is_empty() + || !u.operator.support.sp_changes.is_empty() + || cfg.sp_near != 0. + || cfg.reaper != 0. + { + return Ok(None); + } + if def.aura.is_some() { + at = at.min(entry.next_aura); + } + if extra.cost_aura.is_some() { + at = at.min(entry.next_cost); + } + if extra.reveal { + at = at.min(entry.next_reveal); + } + if fx.aura.is_some() || fx.enemy_atk.is_some() { + at = at.min(u.operator.next_pulse); + } + if let Some(ammo) = fx + .ammo + .as_ref() + .filter(|a| a.ally > 0. && !u.operator.ammo_granted) + { + at = at.min(u.deployment.deployed_at + ammo.delay); + } + let support = &u.operator.support; + if cfg.lavender > 0. { + at = at.min(support.next_lavender); + } + if cfg.sp_aura > 0. || cfg.reveal { + at = at.min(support.next_sp_aura); + } + if cfg.support_atk != 0. { + at = at.min(support.next_support_aura); + } + if support.next_aura.len() != cfg.enemy_auras.len() { + return Ok(None); + } + for (&next, aura) in support.next_aura.iter().zip(&cfg.enemy_auras) { + if !aura.active_only { + at = at.min(next); + } + } + if cfg.phalanx.is_some() { + at = at.min(support.next_phalanx); + } + if cfg.block_stats.is_some() { + at = at.min(support.next_block_stats.max(0.1)); + } + if cfg.forge.is_some() { + at = at.min(support.next_forge.max(0.2)); + } + } + Ok(Some(at)) + } + pub(crate) fn deployment_mut(&mut self) -> &mut Deployment { + &mut self.deployment } pub fn deployment(&self) -> &Deployment { &self.deployment @@ -356,6 +936,28 @@ impl Roster { pub fn dp(&self, owner: Id) -> Option { self.deployment.dp(owner) } + pub(crate) fn clear_inactive_sp(&mut self, w: &mut World, id: Id) -> Result<(), String> { + let entry = self + .entries + .get_mut(&id) + .ok_or("Unknown operator identity")?; + if let Some(skill) = &mut entry.skill { + return skill.bank.clear_inactive(w); + } + if entry.definition.kind != Kind::Passive && !w.unit(id)?.operator.active_skill { + // The attack callback owns this skill. Preserve clear/gain order until it flushes. + let limit = w + .unit_capacity() + .checked_mul(self.ids().len()) + .ok_or("SP change capacity overflow")?; + let pending = &mut w.unit_mut(id)?.operator.support.sp_changes; + if pending.len() >= limit { + return Err("Pending SP change capacity exceeded".into()); + } + pending.push(crate::battle::content::operators::SpChange::Clear); + } + Ok(()) + } pub(crate) fn take_skill(&mut self, id: Id) -> Result { self.healthy()?; self.entries @@ -363,7 +965,7 @@ impl Roster { .ok_or("Unknown operator identity")? .skill .take() - .ok_or("Operator skill is already executing".into()) + .ok_or_else(|| "Operator skill is already executing".into()) } pub(crate) fn restore_skill(&mut self, id: Id, skill: skills::Runtime) -> Result<(), String> { let entry = self @@ -377,6 +979,126 @@ impl Roster { entry.skill = Some(skill); Ok(()) } + pub(crate) fn scheduled( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + ) -> Result<(), String> { + self.healthy()?; + let needs_cost_aura = self.order.iter().any(|id| { + let entry = &self.entries[id]; + entry.definition.extra.cost_aura.is_some() && entry.next_cost <= w.time + 1e-9 + }); + let allies: Vec<_> = if needs_cost_aura { + self.order + .iter() + .map(|&id| (id, self.entries[&id].definition.original_cost)) + .collect() + } else { + Vec::new() + }; + for &id in &self.order { + let entry = self.entries.get_mut(&id).unwrap(); + if let Some(aura) = &entry.definition.aura { + if entry.next_aura <= w.time + 1e-9 { + aura.refresh(w, r, h, id, entry.direction, entry.skill()?.bank.active)?; + entry.next_aura += 0.2; + } + } + if let Some(aura) = &entry.definition.extra.cost_aura { + if entry.next_cost <= w.time + 1e-9 { + aura.refresh(w, r, h, id, &allies)?; + entry.next_cost += 0.5; + } + } + if entry.definition.extra.reveal && entry.next_reveal <= w.time + 1e-9 { + entry.next_reveal += 0.2; + if !w.unit(id)?.stats.alive || !w.unit(id)?.deployed { + continue; + } + let active = entry.skill()?.bank.active; + let range = if active { + entry + .definition + .extra + .skill_range + .as_ref() + .unwrap_or(&entry.definition.range_grid) + } else { + &entry.definition.range_grid + }; + let keys = super::targeting::absolute_range( + range, + w.unit(id)?.deployment.tile, + entry.direction, + 0, + ); + let ids: Vec<_> = w.unit_ids().collect(); + for enemy in ids { + let u = w.unit_mut(enemy)?; + if u.side == Side::Enemy + && u.stats.alive + && !u.hidden + && u.stats + .stats() + .map_err(str::to_string)? + .flags + .contains("stealth") + && super::body::in_range(u, &keys) + { + h.operator_target_status(w, r, id, enemy, "reveal", 0.2 + 0.1)?; + } + } + } + } + Ok(()) + } + pub(crate) fn tick_effects( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + ) -> Result<(), String> { + self.healthy()?; + for &id in &self.order { + if let Some(effect) = &self.entries[&id].definition.while_blocked { + let u = w.unit(id)?; + let on = u.stats.alive && u.deployed && !u.blocking().is_empty(); + let has = u + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(effect.key)); + if on && !has { + r.add( + w, + h, + id, + buffs::Spec { + buff: Buff { + key: Some(effect.key.into()), + mods: effect.mods.clone(), + ..Default::default() + }, + mods_present: true, + ..Default::default() + }, + )?; + } else if !on && has { + r.remove(w, h, id, effect.key)?; + } + } + } + for &id in &self.order { + self.entries[&id].definition.extra.tick(w, r, h, id)?; + } + Ok(()) + } + pub(crate) fn add_dp(&mut self, amount: f64) -> Result<(), String> { + self.healthy()?; + self.deployment.add_dp(self.owner, amount) + } pub(crate) fn recover_dp(&mut self, dt: f64) -> Result<(), String> { self.healthy()?; let dp = (self @@ -417,6 +1139,15 @@ impl Roster { let owner = self.owner; let rect = grid.rect(); if self.order.len() >= self.capacity + || self + .order + .iter() + .filter(|&&id| { + w.unit(id) + .is_ok_and(|u| u.deployment.kind == deploy::Kind::Operator) + }) + .count() + >= 36 || home[0] < rect.r0 || home[0] > rect.r1 || home[1] < rect.c0 @@ -432,12 +1163,21 @@ impl Roster { } let result = (|| { let id = w.next_unit_id()?; - let bank = Bank::new(id, def.kind, def.cost, 1, 1)?; + let mut bank = Bank::new(id, def.kind, def.cost, def.max_charges, 64)?; + bank.no_skill = def.no_skill; let skill = skills::Runtime::new(bank, def.spec.clone(), self.depth)?; let mut u = Unit::new(UnitStats::new(def.base.clone()), Side::Ally); + u.operator.tactical.reset(&def.extra.tactics); u.stats.alive = false; u.owner = Some(owner); u.skill = true; + u.profile_no_heal = def.extra.no_heal; + u.targeting.melee_operator = def.melee_operator; + u.targeting.enemy_filter = def + .extra + .tactics + .behavior() + .and_then(|kit| kit.enemy_filter()); u.deployment.kind = deploy::Kind::Operator; u.deployment.uid = Some(uid); u.deployment.home = home; @@ -445,7 +1185,17 @@ impl Roster { u.position = [home[0] as f64, home[1] as f64]; w.insert_unit(id, u)?; self.deployment.register(id, w)?; - if let Some(buff) = def.permanent.clone() { + // Earlier Kits already granted their team effects before this + // operator's own talents were installed in the reference runtime. + for &source in &self.order { + if let Some(team) = &self.entries[&source].definition.extra.effects.team { + if team.characters.is_empty() || team.characters.contains(&def.char_id.as_str()) + { + team.apply(w, r, h, source, id)?; + } + } + } + for buff in def.permanent.iter().cloned() { r.add( w, h, @@ -458,47 +1208,221 @@ impl Roster { }, )?; } + if let Some(team) = &def.extra.effects.team { + for &target in &self.order { + if team.characters.is_empty() + || team + .characters + .contains(&self.entries[&target].definition.char_id.as_str()) + { + team.apply(w, r, h, id, target)?; + } + } + if team.characters.is_empty() || team.characters.contains(&def.char_id.as_str()) { + team.apply(w, r, h, id, id)?; + } + } self.entries.insert( id, Entry { + next_aura: 0., + next_cost: 0., + next_reveal: 0.2, definition: Arc::new(def), direction, skill: Some(skill), }, ); self.order.push(id); + self.register_observer(id); Ok(id) })(); self.finish(result) } - pub fn deploy_initial( + pub(crate) fn spawn_token( &mut self, w: &mut World, r: &mut buffs::Runtime, h: &mut H, grid: &Grid, - ) -> Result<(), String> { + def: Definition, + summoner: Id, + tile: [i32; 2], + direction: Direction, + ) -> Result, String> { + self.healthy()?; + if !grid.in_rect(tile) || self.deployment.reserved(w, tile)? { + return Ok(None); + } + if self.order.len() >= self.capacity { + return Err("Summon roster capacity exceeded".into()); + } + let result = (|| { + let id = w.next_unit_id()?; + let mut bank = Bank::new(id, def.kind, def.cost, def.max_charges, 64)?; + bank.no_skill = def.no_skill; + let skill = skills::Runtime::new(bank, def.spec.clone(), self.depth)?; + let mut unit = Unit::new(UnitStats::new(def.base.clone()), Side::Ally); + unit.stats.alive = false; + unit.owner = w.unit(summoner)?.owner; + unit.summoner = (def.key != "enemy_9012_acloon").then_some(summoner); + unit.skill = true; + unit.profile_no_heal = def.extra.no_heal; + unit.targeting.melee_operator = def.melee_operator; + unit.deployment.kind = deploy::Kind::Token; + unit.deployment.home = tile; + unit.deployment.tile = tile; + unit.position = [tile[0] as f64, tile[1] as f64]; + unit.operator.tactical.reset(&def.extra.tactics); + w.insert_unit(id, unit)?; + self.deployment.register(id, w)?; + for buff in def.permanent.iter().cloned() { + r.add( + w, + h, + id, + buffs::Spec { + buff, + allow_dead: true, + mods_present: true, + ..Default::default() + }, + )?; + } + self.entries.insert( + id, + Entry { + next_aura: 0., + next_cost: 0., + next_reveal: 0.2, + definition: Arc::new(def), + direction, + skill: Some(skill), + }, + ); + self.order.push(id); + self.register_observer(id); + let deployed = self.deployment.deploy( + w, + &mut Deploy { + entries: &mut self.entries, + r, + h, + grid: Some(grid.tiles()), + initial_cooldown: self.initial_cooldown, + }, + id, + deploy::Options::default(), + )?; + if !deployed { + return Err("Validated summon deployment rejected".into()); + } + Ok(Some(id)) + })(); + self.finish(result) + } + pub(crate) fn relocate( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + grid: &Grid, + id: Id, + tile: [i32; 2], + ) -> Result { + let moved = self.deployment.relocate( + w, + &mut Deploy { + entries: &mut self.entries, + r, + h, + grid: Some(grid.tiles()), + initial_cooldown: self.initial_cooldown, + }, + id, + tile, + )?; + if moved { + h.field_deploy(w, r, id, false)?; + } + Ok(moved) + } + pub(crate) fn initial_order(&self, w: &World) -> Result, String> { self.healthy()?; let mut order = self.order.clone(); // Input/unit update order is preserved separately from deployment order. let mut homes = BTreeMap::new(); for &id in &order { - homes.insert(id, w.unit(id)?.deployment.home); + homes.insert( + id, + ( + w.unit(id)?.deployment.kind == deploy::Kind::Token, + w.unit(id)?.deployment.home, + ), + ); } order.sort_by(|a, b| { - let [ar, ac] = homes[a]; - let [br, bc] = homes[b]; - match self.deploy_order { - DeployOrder::Column => ac.cmp(&bc).then(br.cmp(&ar)), - DeployOrder::RowBottomUp => ar.cmp(&br).then(ac.cmp(&bc)), - } - .then(a.cmp(b)) + let (a_token, [ar, ac]) = homes[a]; + let (b_token, [br, bc]) = homes[b]; + a_token + .cmp(&b_token) + .then_with(|| match self.deploy_order { + DeployOrder::Column => ac.cmp(&bc).then(br.cmp(&ar)), + DeployOrder::RowBottomUp => ar.cmp(&br).then(ac.cmp(&bc)), + }) + .then(a.cmp(b)) }); + Ok(order) + } + pub(crate) fn deploy_initial_unit( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + grid: &Grid, + id: Id, + ) -> Result<(), String> { + self.healthy()?; + if w.unit(id)?.deployed { + return Ok(()); + } + + let result = self.deployment.deploy( + w, + &mut Deploy { + entries: &mut self.entries, + r, + h, + grid: Some(grid.tiles()), + initial_cooldown: self.initial_cooldown, + }, + id, + deploy::Options { + initial: true, + ..Default::default() + }, + ); + self.finish(result).and_then(|deployed| { + if deployed { + Ok(()) + } else { + Err("Initial operator deployment rejected".into()) + } + }) + } + pub fn deploy_initial( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + grid: &Grid, + ) -> Result<(), String> { + let order = self.initial_order(w)?; let mut dispatch = Deploy { entries: &mut self.entries, r, h, - grid: Some(grid), + grid: Some(grid.tiles()), initial_cooldown: self.initial_cooldown, }; let result = (|| { @@ -531,6 +1455,22 @@ impl Roster { .entries .get_mut(&id) .ok_or("Unknown operator identity")?; + if entry.skill.is_none() { + if entry.definition.spec.sp_type == skills::SpType::Hurt + || entry.definition.spec.rule == skills::Rule::TakeDamage + { + let limit = w + .unit_capacity() + .checked_mul(self.order.len()) + .ok_or("SP change capacity overflow")?; + let pending = &mut w.unit_mut(id)?.operator.support.sp_changes; + if pending.len() >= limit { + return Err("Pending SP change capacity exceeded".into()); + } + pending.push(crate::battle::content::operators::SpChange::Damaged); + } + return Ok(()); + } let result = entry .skill .as_mut() @@ -540,7 +1480,12 @@ impl Roster { &mut Skill { r, h, + definition: &entry.definition, + aura: entry.definition.aura.as_ref(), + direction: entry.direction, + end_stun: entry.definition.end_stun, mods: &entry.definition.modifiers, + flags: &entry.definition.skill_flags, }, ); self.finish(result) @@ -567,7 +1512,12 @@ impl Roster { &mut Skill { r, h, + definition: &entry.definition, + aura: entry.definition.aura.as_ref(), + direction: entry.direction, + end_stun: entry.definition.end_stun, mods: &entry.definition.modifiers, + flags: &entry.definition.skill_flags, }, amount, "talent", @@ -602,7 +1552,12 @@ impl Roster { &mut Skill { r, h, + definition: &entry.definition, + aura: entry.definition.aura.as_ref(), + direction: entry.direction, + end_stun: entry.definition.end_stun, mods: &entry.definition.modifiers, + flags: &entry.definition.skill_flags, }, dt, )?; @@ -659,6 +1614,154 @@ impl Roster { ); self.finish(result) } + pub(crate) fn copy_token( + &mut self, + data: &Catalog, + w: &mut World, + id: Id, + source: Id, + scale: f64, + ranged: bool, + ) -> Result<(), String> { + let source_definition = Arc::clone(&self.entry(source)?.definition); + let key = self.entry(id)?.definition.key.clone(); + let owner = w.unit(id)?.summoner.ok_or("Copy has no owner")?; + let owner_key = &self.entry(owner)?.definition.key; + let mut definition = Definition::token(data, &key, owner_key)?; + for field in ["maxHp", "atk", "def", "res", "blockCnt", "bat", "aspd"] { + let mut value = w.unit(source)?.stats.base_number(field); + if matches!(field, "maxHp" | "atk" | "def" | "res") { + value *= scale; + } + if field == "maxHp" { + value = value.max(1.); + } + definition.base.0.insert(field.into(), value); + } + let copied = definition.base.0.clone(); + w.unit_mut(id)?.stats.edit_base(|base| { + for (field, value) in copied { + base.0.insert(field, value); + } + }); + definition.range_grid = source_definition.range_grid.clone(); + definition.melee_operator = !ranged; + definition.combat.profile.selection.can_hit_fly = + ranged || source_definition.combat.profile.selection.can_hit_fly; + definition.combat.profile.no_attack = false; + definition.combat.projectile = if ranged { + Some(match source_definition.combat.projectile { + Some("arrow") => "arrow", + Some("bomb") => "bomb", + Some("lob") => "lob", + _ => "bolt", + }) + } else { + None + }; + definition.combat.projectile_speed = match definition.combat.projectile { + Some("arrow") => 14., + Some("bomb" | "lob") => 8., + Some(_) => 11., + None => 0., + }; + if !source_definition.combat.heal + && !source_definition.combat.profile.no_attack + && !source_definition.combat.profile.only_while_skill + { + definition.combat.damage = source_definition.combat.damage; + } + self.entries.get_mut(&id).unwrap().definition = Arc::new(definition); + // Definition replacement is rare. Rebuild in roster order so equal-priority + // listeners retain their original ordering, including copied summons. + self.kit_observers.clear(); + self.tick_observers.clear(); + for cursor in 0..self.order.len() { + self.register_observer(self.order[cursor]); + } + w.unit_mut(id)?.targeting.melee_operator = !ranged; + let maximum = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp"); + w.unit_mut(id)?.stats.hp = maximum; + Ok(()) + } + pub(crate) fn disable_token_skill(&mut self, id: Id) -> Result<(), String> { + let skill = self + .entries + .get_mut(&id) + .ok_or("Unknown clone")? + .skill + .as_mut() + .ok_or("Clone skill is executing")?; + skill.bank.no_skill = true; + skill.bank.sp = 0.; + skill.bank.charges = 0.; + skill.bank.active = false; + Ok(()) + } + pub(crate) fn redeploy_free( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + tiles: &[super::grid::Tile], + id: Id, + ) -> Result { + self.redeploy_at(w, r, h, tiles, id, None, false) + } + pub(crate) fn redeploy_at( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + tiles: &[super::grid::Tile], + id: Id, + tile: Option<[i32; 2]>, + keep_sp: bool, + ) -> Result { + let result = self.deployment.redeploy_retaining( + w, + &mut Deploy { + entries: &mut self.entries, + r, + h, + grid: Some(tiles), + initial_cooldown: self.initial_cooldown, + }, + id, + true, + tile, + keep_sp, + ); + self.finish(result) + } + pub(crate) fn expire_token( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + self.healthy()?; + let result = self.deployment.retreat( + w, + &mut Deploy { + entries: &mut self.entries, + r, + h, + grid: None, + initial_cooldown: self.initial_cooldown, + }, + id, + "expired", + true, + ); + self.finish(result) + } pub fn check_redeploys( &mut self, w: &mut World, @@ -673,13 +1776,69 @@ impl Roster { entries: &mut self.entries, r, h, - grid: Some(grid), + grid: Some(grid.tiles()), initial_cooldown: self.initial_cooldown, }, ); self.finish(result) } pub fn range(&self, w: &World, id: Id) -> Result, String> { + Ok(self.range_geometry(w, id)?.keys()) + } + pub(crate) fn range_geometry<'a>( + &'a self, + w: &'a World, + id: Id, + ) -> Result, String> { + let entry = self.entry(id)?; + if matches!( + entry.definition.extra.tactics, + super::content::operators::Tactics::Yanyou(_) + ) { + return Ok(RangeGeometry::Absolute(Cow::Borrowed( + &w.unit(id)?.operator.tactical.yanyou()?.keys, + ))); + } + let active = entry + .skill + .as_ref() + .map(|s| s.bank.active) + .unwrap_or_else(|| w.unit(id).is_ok_and(|u| u.operator.active_skill)); + let doll_grid = match &entry.definition.extra.tactics { + super::content::operators::Tactics::Kazema(parameters) + if w.unit(id)?.operator.tactical.kazema()?.dollkeeper.doll => + { + Some(¶meters.grid) + } + _ => None, + }; + let grid = if let Some(grid) = doll_grid { + grid + } else if active { + entry + .definition + .extra + .skill_range + .as_ref() + .unwrap_or(&entry.definition.range_grid) + } else { + &entry.definition.range_grid + }; + let extend = if active { + entry.definition.extra.advanced_range_extend + } else { + 0 + }; + let unit = w.unit(id)?; + Ok(RangeGeometry::Relative { + grid: Cow::Borrowed(grid), + origin: unit.deployment.tile, + direction: entry.direction, + extend, + extra: Cow::Borrowed(&unit.operator.advanced.extra_range), + }) + } + pub(crate) fn base_range(&self, w: &World, id: Id) -> Result, String> { let entry = self.entry(id)?; Ok(super::targeting::absolute_range( &entry.definition.range_grid, @@ -692,13 +1851,18 @@ impl Roster { struct Skill<'a, H> { r: &'a mut buffs::Runtime, h: &'a mut H, + definition: &'a Definition, + aura: Option<&'a super::content::operators::Aura>, + direction: Direction, + end_stun: f64, mods: &'a Numbers, + flags: &'a std::collections::BTreeSet, } impl skills::Hooks for Skill<'_, H> { fn event( &mut self, e: skills::Event, - _: &mut skills::Context, + c: &mut skills::Context, s: &mut skills::Runtime, w: &mut World, ) -> Result<(), String> { @@ -712,26 +1876,47 @@ impl skills::Hooks for Skill<'_, H> { buff: Buff { key: Some(format!("skill:{}", s.unit())), mods: self.mods.clone(), + flags: self.flags.clone(), ..Default::default() }, mods_present: true, ..Default::default() }, )?; + if self.flags.contains("noBlock") { + self.h.operator_release(w, self.r, s.unit())?; + } } skills::Event::RemoveModifiers => { self.r .remove(w, self.h, s.unit(), &format!("skill:{}", s.unit()))?; } - skills::Event::Start + skills::Event::Deploy + | skills::Event::Start | skills::Event::End | skills::Event::SkillStart | skills::Event::SkillEnd | skills::Event::DisplayOn | skills::Event::DisplayOff => {} - skills::Event::PassiveWindow => {} + skills::Event::PassiveWindow | skills::Event::AmmoUsed | skills::Event::Tick => {} _ => return Err("Unexpected callback in default operator kit".into()), } + self.definition.extra.event(w, self.r, self.h, e, s)?; + self.h + .operator_skill_effect(w, self.r, self.direction, self.definition, e, c, s)?; + if e == skills::Event::End + && c.reason != "death" + && w.unit(s.unit())?.stats.alive + && self.end_stun > 0. + { + self.h + .operator_status(w, self.r, s.unit(), "stun", self.end_stun)?; + } + if matches!(e, skills::Event::Start | skills::Event::End) { + if let Some(aura) = self.aura { + aura.refresh(w, self.r, self.h, s.unit(), self.direction, s.bank.active)?; + } + } Ok(()) } fn condition( @@ -753,7 +1938,7 @@ struct Deploy<'a, H> { entries: &'a mut BTreeMap, r: &'a mut buffs::Runtime, h: &'a mut H, - grid: Option<&'a Grid>, + grid: Option<&'a [super::grid::Tile]>, initial_cooldown: f64, } impl blocking::Hooks for Deploy<'_, H> { @@ -775,7 +1960,7 @@ impl deploy::Hooks for Deploy<'_, H> { let u = w.unit_mut(id)?; u.element_buildup = [0.; 5]; let [row, col] = u.deployment.tile; - u.ground = self.grid.ok_or("Deployment requires grid context")?.tiles() + u.ground = self.grid.ok_or("Deployment requires tile context")? [row as usize * COLS + col as usize] .height == "LOW"; @@ -783,22 +1968,165 @@ impl deploy::Hooks for Deploy<'_, H> { .entries .get_mut(&id) .ok_or("Unknown operator identity")?; + w.unit_mut(id)?.terrain.direction = Some(entry.direction); let skill = entry .skill .as_mut() .ok_or("Operator skill is already executing")?; + w.unit_mut(id)?.operator.active_skill = false; + w.unit_mut(id)?.operator.skill_death_pending = false; + w.unit_mut(id)?.operator.hits = 0; + { + let m = &mut w.unit_mut(id)?.operator.support; + m.protege = None; + m.debt = 0.; + m.fragile_scale = 1.; + m.reaper_queue.clear(); + m.next_reaper = f64::NEG_INFINITY; + m.reaper_window = f64::NEG_INFINITY; + m.reaper_accepted = 0; + m.quiet_until = f64::NEG_INFINITY; + m.bandage = None; + m.sp_changes.clear(); + } + let next_fast = w.unit(id)?.operator.advanced.next_fast; + let next_aura = w.unit(id)?.operator.advanced.next_aura; + let floating = std::mem::take(&mut w.unit_mut(id)?.operator.advanced.floating); + w.unit_mut(id)?.operator.advanced = Default::default(); + w.unit_mut(id)?.operator.advanced.next_fast = next_fast; + w.unit_mut(id)?.operator.advanced.next_aura = next_aura; + w.unit_mut(id)?.operator.advanced.floating = floating; + w.unit_mut(id)?.operator.advanced.last_hurt = f64::NEG_INFINITY; + match &entry.definition.extra.advanced { + super::content::operators::Advanced::Mudrok(p) => { + w.unit_mut(id)?.operator.advanced.layers = p.layer_add.min(p.layer_cap); + w.unit_mut(id)?.operator.advanced.next_layer = w.time + p.layer_period; + } + _ => {} + } + w.unit_mut(id)? + .operator + .tactical + .reset(&entry.definition.extra.tactics); + w.unit_mut(id)?.hits_sleep = entry.definition.combat.profile.selection.hit_sleep; + w.unit_mut(id)?.operator.uses = 0; + w.unit_mut(id)?.operator.revived = false; + w.unit_mut(id)?.operator.ammo_granted = false; + w.unit_mut(id)?.operator.blessing_pending = + entry.definition.extra.effects.random_bless.is_some(); + if w.unit(id)?.operator.deployments == 0 { + w.unit_mut(id)?.operator.next_pulse = + if entry.definition.extra.effects.enemy_atk.is_some() { + 0.1 + } else if entry + .definition + .extra + .effects + .aura + .as_ref() + .is_some_and(|a| a.grid.is_none()) + { + 0.2 + } else { + 0. + }; + } + if let Some(b) = entry.definition.extra.effects.deploy_buff.clone() { + self.r.add( + w, + self.h, + id, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + let carry = if opts.keep_sp { + Some((skill.bank.sp, skill.bank.charges)) + } else { + None + }; skill.reset( w, &mut Skill { r: self.r, h: self.h, + definition: &entry.definition, + aura: entry.definition.aura.as_ref(), + direction: entry.direction, + end_stun: entry.definition.end_stun, mods: &entry.definition.modifiers, + flags: &entry.definition.skill_flags, }, None, )?; + if let Some((sp, charges)) = carry { + let cost = skill.bank.cost(w)?; + if !skill.bank.no_skill + && skill.bank.kind != super::sp::Kind::Passive + && !skill.bank.active + && cost > 0. + { + skill.bank.charges = charges.floor().clamp(0., skill.bank.max_charges() as f64); + skill.bank.sp = if skill.bank.charges >= skill.bank.max_charges() as f64 { + cost + } else { + sp.clamp(0., cost) + }; + } + } + if let Some(p) = &entry.definition.extra.support.phalanx { + self.r.add( + w, + self.h, + id, + buffs::Spec { + buff: Buff { + key: Some("trait:phalanxGuard".into()), + mods: p.guard.clone(), + ..Default::default() + }, + mods_present: true, + ..Default::default() + }, + )?; + } if opts.initial { skill.op_ready_at = w.time + self.initial_cooldown; } + if let Some(bonus) = &entry.definition.ground_bonus { + let grid = self.grid.ok_or("Deployment requires grid context")?; + let home = w.unit(id)?.deployment.tile; + let low = [[1, 0], [-1, 0], [0, 1], [0, -1]] + .into_iter() + .filter(|d| { + let p = [home[0] + d[0], home[1] + d[1]]; + Grid::in_bounds(p) && grid[p[0] as usize * COLS + p[1] as usize].height == "LOW" + }) + .count(); + let v = if low as f64 >= bonus.count { + bonus.surrounded + } else { + bonus.normal + }; + if v != 0. { + self.r.add( + w, + self.h, + id, + buffs::Spec { + buff: Buff { + key: Some(bonus.key.into()), + mods: [("atkPct".into(), v)].into(), + ..Default::default() + }, + mods_present: true, + ..Default::default() + }, + )?; + } + } Ok(()) } fn event( @@ -807,26 +2135,69 @@ impl deploy::Hooks for Deploy<'_, H> { id: Id, _: Option, w: &mut World, - _: &mut Deployment, + deployment: &mut Deployment, ) -> Result<(), String> { + if e == deploy::Event::Death { + self.h.operator_removed(w, self.r, id)?; + } + if e == deploy::Event::Deploy { + self.h.field_deploy(w, self.r, id, true)?; + self.team_deploy(id, w)?; + let entry = self.entries.get_mut(&id).unwrap(); + self.h.operator_skill_effect( + w, + self.r, + entry.direction, + &entry.definition, + skills::Event::Deploy, + &mut skills::Context { + reason: "deploy".into(), + dt: 0., + amount: 0., + no_ammo: false, + targets: vec![], + }, + entry.skill.as_mut().ok_or("Deployment lost its skill")?, + )?; + + let refund = self.entries[&id].definition.extra.support.refund; + let u = w.unit(id)?; + if refund > 0. && u.operator.deployments > 1 && !u.ground { + deployment.add_dp( + u.owner.ok_or("Missing operator owner")?, + u.stats.base_number("cost") * refund, + )?; + } + } if e == deploy::Event::EndSkill { + let m = &mut w.unit_mut(id)?.operator.support; + m.reaper_queue.clear(); + m.next_reaper = f64::NEG_INFINITY; + m.reaper_window = f64::NEG_INFINITY; + m.reaper_accepted = 0; + m.sp_changes.clear(); let entry = self .entries .get_mut(&id) .ok_or("Unknown operator identity")?; - entry - .skill - .as_mut() - .ok_or("Operator skill is already executing")? - .end( + if let Some(skill) = entry.skill.as_mut() { + skill.end( w, &mut Skill { r: self.r, h: self.h, + definition: &entry.definition, + aura: entry.definition.aura.as_ref(), + direction: entry.direction, + end_stun: entry.definition.end_stun, mods: &entry.definition.modifiers, + flags: &entry.definition.skill_flags, }, "death", )?; + } else { + w.unit_mut(id)?.operator.skill_death_pending = true; + } } Ok(()) } @@ -834,3 +2205,72 @@ impl deploy::Hooks for Deploy<'_, H> { self.r.discard_temporary(w, self.h, id) } } + +impl Deploy<'_, H> { + fn team_deploy(&mut self, id: Id, w: &mut World) -> Result<(), String> { + let u = w.unit_mut(id)?; + u.operator.deployments = u + .operator + .deployments + .checked_add(1) + .ok_or("Operator deployment count exhausted")?; + if u.operator.cost_cut > 0. { + let cost = u.stats.base_number("cost") + u.operator.cost_cut; + u.stats.edit_base(|b| { + b.0.insert("cost".into(), cost); + }); + u.operator.cost_cut = 0.; + } + if let Some(cut) = &self.entries[&id].definition.extra.effects.cost_cut { + if cut.every || w.unit(id)?.operator.deployments == 1 { + for (&other, entry) in self.entries.iter() { + let u = w.unit_mut(other)?; + if other == id + || u.stats.alive + || u.removed + || entry.definition.profession != "WARRIOR" + { + continue; + } + let cost = u.stats.base_number("cost"); + let value = cut.amount.min(cut.cap - u.operator.cost_cut).min(cost); + if value > 0. { + u.stats.edit_base(|b| { + b.0.insert("cost".into(), cost - value); + }); + u.operator.cost_cut += value; + } + } + } + } + if self.entries[&id].definition.profession == "PIONEER" { + let amount: f64 = self + .entries + .values() + .map(|e| e.definition.extra.effects.deploy_sp) + .sum(); + let e = self.entries.get_mut(&id).unwrap(); + let s = e.skill.as_mut().ok_or("Missing deployment skill")?; + if !(s.bank.active && s.bank.kind.timed()) && amount > 0. { + s.gain( + w, + &mut Skill { + r: self.r, + h: self.h, + definition: &e.definition, + aura: e.definition.aura.as_ref(), + direction: e.direction, + end_stun: e.definition.end_stun, + mods: &e.definition.modifiers, + flags: &e.definition.skill_flags, + }, + amount, + "init", + false, + false, + )?; + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime.rs b/crates/engine/src/battle/runtime.rs index 3d01fa8..06da896 100644 --- a/crates/engine/src/battle/runtime.rs +++ b/crates/engine/src/battle/runtime.rs @@ -17,7 +17,34 @@ use super::{ use crate::{data::Catalog, deterministic::rng::Rng}; use serde_json::{json, Value}; use std::sync::Arc; +mod advanced; +mod boss; +mod boss_round; +pub use boss::{BossConfig, BossKind, BossState}; +pub(crate) use boss_round::validate_boss_round; +pub use boss_round::{BossOvertime, BossRoundConfig, BossRoundOutcome, BossRoundState}; mod allies; +mod bands; +mod bonds; +mod growth; +pub use bonds::BattleBond; +mod choices; +mod devices; +pub use choices::BattleChoice; +mod turrets; +pub use devices::{ColdWind, MapConfig}; +mod enemies; +mod equipment; +mod equipment_special; +mod event_window; +mod hammers; +pub(crate) mod kits; +mod movement_batch; +mod movement_paths; +mod settlement_hooks; +mod support; +mod tactics; +mod terrain; #[derive(Clone, Copy)] pub struct Limits { @@ -46,6 +73,19 @@ pub struct Advance { pub terminated: bool, pub budget_exhausted: bool, } +/// Owned terminal accounting for match settlement. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FieldResult { + pub killed: u64, + pub credited_kills: u64, + pub counted_leaks: u64, + pub coins: f64, + pub damage: f64, + pub healing: f64, + pub match_boss_damage: f64, + pub boss: Option, + pub boss_round: Option, +} /// Internal state for battle parity/debugging, not a policy observation. pub struct EnemyState { pub element: [f64; 5], @@ -70,16 +110,26 @@ pub struct Field { faulted: bool, } struct Core { + movement_batching: bool, + event_windows: u64, + movement_paths: movement_paths::MovementPaths, world: World, host: Host, commitments: super::search::Commitments, time_limit: f64, unit_limit: usize, + boss: Option, } -struct Host { +pub(crate) struct Host { + boss_round: Option, + rect: Rect, data: Arc, - grid: Option, - roster: Option, + terrain: Arc, + grid: Option>, + route_query_grid: Box, + tiles: Arc<[super::grid::Tile]>, + // Callbacks temporarily take ownership; keep the embedded occupancy grid in place. + roster: Option>, index: Option, executor: Option, flights: Option>, @@ -87,6 +137,23 @@ struct Host { content: Option, buffs: Option, rng: Rng, + zones: Vec, + tactical_timers: Vec, + tactical_limit: usize, + tactical_slots: usize, + pending_skill_starts: Vec<(Id, Vec)>, + deferred_kit_events: std::collections::VecDeque, + kit_event_limit: usize, + flushing_kit_events: bool, + last_operator: Option, + equipment: super::equipment::Runtime, + devices: devices::Devices, + choices: choices::Choices, + bonds: bonds::Runtime, + bands: bands::Bands, + growth: growth::Growth, + /// Reused per-tick identity list; empty between phases. + scratch: Vec, } struct Spawn<'a> { host: &'a mut Host, @@ -100,16 +167,66 @@ impl super::spawns::Hooks for Spawn<'_> { w: &mut World, r: &mut super::spawns::Runtime, ) -> Result<(), String> { + if r.definition(id)?.key == "enemy_5601_entlec" { + return Ok(()); + } + self.host.attach_boss_pool(w, id)?; + self.host.field_terrain(w, self.buffs, id, true)?; let data = Arc::clone(&self.host.data); - r.install_content(&data, w, self.buffs, self.content, self.host, id) + r.install_content(&data, w, self.buffs, self.content, self.host, id)?; + if let content::Kit::Special(config @ content::Special::Armor { .. }) = self.content.kit(id) + { + self.host.enemy_special_spawn(w, id, config)?; + if let content::specials::Memory::Armor { left, combo, .. } = self.content.special(id) { + self.content.set_special( + id, + content::specials::Memory::Armor { + left, + combo, + appeared: true, + }, + ); + } + } + + let resist = match self.content.kit(id) { + content::Kit::Ability(content::Ability::Nest { resist, .. }) => Some(resist), + content::Kit::Caster(content::Caster { + passive: content::casters::Passive::Mace { resist, .. }, + .. + }) => Some(resist), + _ => None, + }; + if let Some(resist) = resist { + self.host.apply_status( + w, + self.buffs, + id, + "resist", + super::status::Options { + source: Some(id), + value: Some(resist), + ..Default::default() + }, + )?; + } + Ok(()) } - fn release(&mut self, id: Id, _: &mut World) -> Result<(), String> { + fn release(&mut self, _: Id, _: &mut World) -> Result<(), String> { + Ok(()) + } + fn retired(&mut self, id: Id, _: &mut World) -> Result<(), String> { + self.host + .index + .as_mut() + .ok_or("Missing retirement index")? + .retire(id); self.content.remove(id); Ok(()) } } impl Field { - /// `stage` and `template` come from external data. Active combat devices and + /// `stage` and `template` come from external data. Unsupported devices and /// unsupported terrain/content fail before the clock starts. There is no /// 'disable content' option in this execution entry. pub fn new( @@ -120,6 +237,25 @@ impl Field { time_limit: f64, limits: Limits, ) -> Result { + Self::build(data, stage, template, seed, time_limit, limits, None) + } + fn build( + data: Arc, + stage: &Value, + template: Template, + seed: u32, + time_limit: f64, + limits: Limits, + boss: Option, + ) -> Result { + if let Some(config) = &boss { + config.validate()?; + } + let rect = if boss.is_some() { + Rect::BOSS + } else { + Rect::NORMAL + }; if [ limits.units, limits.reports, @@ -150,44 +286,31 @@ impl Field { if normalized["rows"].is_null() { normalized["rows"] = normalized["grid"].clone(); } - let mut grid = Grid::new(&normalized, Rect::NORMAL).map_err(str::to_string)?; - for r in Rect::NORMAL.r0..=Rect::NORMAL.r1 { - for c in Rect::NORMAL.c0..=Rect::NORMAL.c1 { - if grid.tiles()[(r as usize) * COLS + c as usize] - .terrain - .is_some() - { - return Err("Field terrain effects are not implemented".into()); - } - } - } - for d in normalized["devices"].as_array().into_iter().flatten() { - let active = d["active"].as_bool().unwrap_or(d["hidden"] != true); - let at = [ - d["row"] - .as_i64() - .or_else(|| d["pos"][0].as_i64()) - .unwrap_or(-1) as i32, - d["col"] - .as_i64() - .or_else(|| d["pos"][1].as_i64()) - .unwrap_or(-1) as i32, - ]; - if active && inside(grid.rect(), at) { - if matches!(d["role"].as_str(), Some("platform" | "mound")) { - grid.set_obstacle(at, true, super::grid::BLOCK) - .map_err(str::to_string)?; - } else { - return Err(format!("Stage device not implemented: {}", d["key"])); - } - } - } - if !template.extra_routes.is_empty() { - return Err("Additional content routes are not implemented in this field entry".into()); - } - for s in &template.spawns { - if s["tag"] == "boss" || s["tag"] == "part" { - return Err("Boss and part fields are not implemented".into()); + let mut grid = Grid::new(&normalized, rect).map_err(str::to_string)?; + let terrain = super::terrain::Config::compile(&normalized, &grid)?; + let devices = devices::Devices::compile(&normalized, &mut grid)?; + for s in + template + .spawns + .iter() + .chain(template.branches.values().flatten().flatten().filter(|s| { + s["action"] + .as_str() + .is_none_or(|a| a.eq_ignore_ascii_case("SPAWN")) + && s["key"] + .as_str() + .or_else(|| s["enemyKey"].as_str()) + .is_some_and(|k| k.starts_with("enemy_")) + })) + { + if let Some(key) = s["enemyKey"].as_str().or_else(|| s["key"].as_str()) { + let kit = content::Kit::compile( + key, + &data.table("enemies").ok_or("Missing enemies")?[key], + &template.overrides[key], + s["tag"].as_str(), + )?; + kit.validate_tag(s["tag"].as_str())?; } } let spawns = super::spawns::Runtime::new( @@ -209,7 +332,7 @@ impl Field { limits.callback_depth, )?; let content = content::Runtime::new(limits.units)?; - let ally_limit = limits.units.min(36); + let ally_limit = limits.units; let roster = super::operators::Roster::new( &grid, 1, @@ -227,19 +350,56 @@ impl Field { ..Default::default() }, )?; - Ok(Self { + let mut world = World::new(limits.units, 1, 1)?; + world.insert_player(1, health::PlayerTotals::default())?; + let boss = boss + .map(|config| { + world.boss_battle = true; + world.insert_shared_boss_pool(1, config.pool)?; + Ok::<_, String>(config.kind) + }) + .transpose()?; + let field = Self { clock: Clock::new(), core: Core { - world: World::new(limits.units, 1, 1)?, + movement_batching: true, + event_windows: 0, + movement_paths: movement_paths::MovementPaths::default(), + world, + boss, host: Host { + boss_round: None, + rect, data, - grid: Some(grid), - roster: Some(roster), + terrain: Arc::new(terrain), + devices, + choices: Default::default(), + bonds: bonds::Runtime::for_stage(&normalized), + bands: Default::default(), + growth: Default::default(), + scratch: Vec::new(), + zones: Vec::new(), + tactical_timers: Vec::new(), + tactical_limit: limits.projectiles, + tactical_slots: 0, + pending_skill_starts: Vec::new(), + deferred_kit_events: Default::default(), + kit_event_limit: limits.units * limits.callback_depth, + flushing_kit_events: false, + last_operator: None, + equipment: Default::default(), + tiles: grid.tile_layout(), + route_query_grid: Box::new(grid.clone()), + grid: Some(Box::new(grid)), + roster: Some(Box::new(roster)), index: Some(spatial::Index::new( limits.units, limits.units * super::grid::N, )?), - executor: Some(super::attacks::Executor::new(limits.units, 1)?), + executor: Some(super::attacks::Executor::new( + limits.units, + super::operators::Combat::MAX_HITS, + )?), flights: Some(super::projectiles::System::new(limits.projectiles)?), spawns: Some(spawns), content: Some(content), @@ -255,7 +415,8 @@ impl Field { unit_limit: limits.units, }, faulted: false, - }) + }; + Ok(field) } fn healthy(&self) -> Result<(), String> { if self.faulted || self.clock.faulted() { @@ -290,16 +451,48 @@ impl Field { &mut self, key: &str, placement: super::operators::Placement, + ) -> Result { + self.add_operator_with_skill(key, placement, None) + } + /// Install a supported skill index with the default module and potential. + pub fn add_operator_with_skill( + &mut self, + key: &str, + placement: super::operators::Placement, + skill_index: Option, + ) -> Result { + self.add_operator_with_loadout(key, placement, skill_index, &[]) + } + pub fn configure_round_gained_chess(&mut self, count: u64) -> Result<(), String> { + self.healthy()?; + if self.clock.started() || self.ticks() != 0 { + return Err("Round context must be installed before field start".into()); + } + self.core.host.equipment.gained_chess = count; + Ok(()) + } + pub fn add_operator_with_loadout( + &mut self, + key: &str, + placement: super::operators::Placement, + skill_index: Option, + items: &[String], ) -> Result { self.healthy()?; if self.ticks() != 0 || self.clock.started() || self.finished() { return Err("Operators must be installed before field start".into()); } - let def = super::operators::Definition::load(&self.core.host.data, key)?; - let grid = self.core.host.grid.take().unwrap(); - if grid.obstacle(placement.home) != 0 { + let def = super::operators::Definition::load_with_loadout( + &self.core.host.data, + key, + skill_index, + items, + )?; + let equipment = def.equipment.clone(); + let grid = self.core.host.take_grid(); + if grid.obstacle(placement.home) & super::grid::CRATE != 0 { self.core.host.grid = Some(grid); - return Err("Operator deployment on a combat device is not implemented".into()); + return Err("Operator deployment tile is occupied by a crate".into()); } let mut roster = self.core.host.roster.take().unwrap(); let mut r = self.core.host.buffs.take().unwrap(); @@ -311,15 +504,163 @@ impl Field { def, placement, ); + if let Ok(id) = &result { + let bonds = super::equipment::bonds(&self.core.host.data, key, items); + self.core.host.equipment.register(*id, &equipment, bonds); + } self.faulted |= roster.faulted(); self.core.host.roster = Some(roster); self.core.host.buffs = Some(r); self.core.host.grid = Some(grid); result } + pub(crate) fn add_prepared_token( + &mut self, + key: &str, + placement: super::operators::Placement, + owner_key: &str, + ) -> Result { + self.healthy()?; + if self.clock.started() || self.ticks() != 0 { + return Err("Summons must be installed before field start".into()); + } + let definition = super::operators::Definition::token(&self.core.host.data, key, owner_key)?; + let grid = self.core.host.take_grid(); + let mut roster = self.core.host.roster.take().unwrap(); + let mut buffs = self.core.host.buffs.take().unwrap(); + let result = roster.add( + &mut self.core.world, + &mut buffs, + &mut self.core.host, + &grid, + definition, + placement, + ); + self.faulted |= roster.faulted(); + self.core.host.roster = Some(roster); + self.core.host.buffs = Some(buffs); + self.core.host.grid = Some(grid); + let id = result?; + let unit = self.core.world.unit_mut(id)?; + unit.deployment.kind = super::deploy::Kind::Token; + Ok(id) + } + pub(crate) fn bind_prepared_token(&mut self, token: Id, owner_uid: u64) -> Result<(), String> { + let owner = self + .allies() + .iter() + .copied() + .find(|&id| { + self.unit(id).is_ok_and(|u| { + u.deployment.kind == super::deploy::Kind::Operator + && u.deployment.uid == Some(owner_uid) + }) + }) + .ok_or("Prepared summon owner is missing")?; + self.core.world.unit_mut(token)?.summoner = Some(owner); + Ok(()) + } + /// The owner's cultivation is an independent multiplier, not an additive + /// bond/equipment percentage. Raw Field callers opt in; owned solo defaults + /// to the original player's E2 level-60 tier. + pub fn configure_operator_cultivation(&mut self, id: Id, tier: u8) -> Result<(), String> { + self.healthy()?; + if self.clock.started() || self.ticks() != 0 || tier > 3 { + return Err("Cultivation requires an unstarted field and tier 0..3".into()); + } + if self.core.world.unit(id)?.deployment.kind != super::deploy::Kind::Operator { + return Err("Cultivation requires an operator".into()); + } + let effect = format!("aceffect_char_{}", tier + 1); + let buff = self + .core + .host + .data + .table("effects") + .and_then(|v| v.get(&effect)) + .and_then(|v| v["buffs"].as_array()) + .and_then(|a| a.iter().find(|b| b["key"] == "char_attribute_mul")); + let Some(buff) = buff else { + return Ok(()); + }; + let mul = |key: &str| { + buff["bb"][key] + .as_f64() + .filter(|v| v.is_finite() && *v > 0.) + .unwrap_or(1.) + }; + let cultivation = super::stats::Cultivation { + hp: mul("max_hp"), + atk: mul("atk"), + def: mul("def"), + }; + self.core + .world + .unit_mut(id)? + .stats + .set_cultivation(cultivation); + Ok(()) + } pub fn unit(&self, id: Id) -> Result<&Unit, String> { self.core.world.unit(id) } + /// On-demand rendering data. Reading it never materializes lazy combat stats. + pub fn replay_frame(&self) -> Result { + self.healthy()?; + let mut units = Vec::new(); + for &id in self.allies().iter().chain(self.enemies()) { + let u = self.unit(id)?; + if !u.stats.alive || !u.deployed || u.hidden { + continue; + } + let key = match u.side { + health::Side::Ally => { + &self + .core + .host + .roster + .as_ref() + .unwrap() + .entry(id)? + .definition + .key + } + health::Side::Enemy => &self.core.host.spawns.as_ref().unwrap().definition(id)?.key, + }; + units.push(json!({"id":id,"key":key, + "side":if u.side == health::Side::Ally {"ally"} else {"enemy"}, + "position":u.position,"hp":u.stats.hp,"maxHp":u.stats.observed_max_hp(), + "moving":u.moving,"skillActive":u.operator.active_skill, + "attacks":u.attacks,"lastAttackAt":u.last_attack_at})); + } + let projectiles: Vec<_> = self + .core + .host + .flights + .as_ref() + .unwrap() + .list() + .iter() + .map(|p| { + json!({"id":p.id,"position":p.position,"to":p.destination, + "source":p.source,"target":p.target,"visual":p.visual}) + }) + .collect(); + let rect = self.core.host.grid.as_ref().unwrap().rect(); + let tiles: Vec<_> = self + .core + .host + .grid + .as_ref() + .unwrap() + .tiles() + .iter() + .map(|tile| &tile.glyph) + .collect(); + Ok(json!({"tick":self.ticks(),"time":self.time(), + "bounds":[rect.r0,rect.c0,rect.r1,rect.c1],"tiles":tiles, + "units":units,"projectiles":projectiles})) + } pub fn rng_state(&self) -> u32 { self.core.host.rng.state() } @@ -377,7 +718,11 @@ impl Field { } pub fn run(&mut self, budget: usize) -> Result { self.healthy()?; - let result = self.clock.run_steps(&mut self.core, budget); + let result = if self.core.host.boss_round.is_some() { + self.run_boss_round(budget) + } else { + self.clock.run_steps(&mut self.core, budget) + }; match result { Ok(ticks) => Ok(Advance { ticks, @@ -398,6 +743,8 @@ impl Field { ); if result.is_err() { self.faulted = true; + } else { + self.finish_boss_round(); } result } @@ -417,16 +764,11 @@ impl Field { } self.core.world.time = self.clock.time(); let mut buffs = self.core.host.buffs.take().unwrap(); - let mut rng = self.core.host.rng.clone(); - let result = settlement::resolve( - &mut self.core.world, - &mut buffs, - &mut rng, - &mut self.core.host, - request, - ); + let result = self + .core + .host + .resolve_hit(&mut self.core.world, &mut buffs, request); self.core.host.buffs = Some(buffs); - self.core.host.rng = rng; if result.is_err() { self.faulted = true; } @@ -437,9 +779,6 @@ impl Field { if self.finished() { return Err("Cannot spawn into a finished field".into()); } - if matches!(options["tag"].as_str(), Some("boss" | "part")) { - return Err("Boss and part fields are not implemented".into()); - } let raw = &self .core .host @@ -456,26 +795,17 @@ impl Field { .unwrap() .content_overrides(key), options["tag"].as_str(), - )?; + )? + .validate_tag(options["tag"].as_str())?; self.core.world.time = self.clock.time(); - let mut spawns = self.core.host.spawns.take().unwrap(); let mut buffs = self.core.host.buffs.take().unwrap(); - let mut content = self.core.host.content.take().unwrap(); - let grid = self.core.host.grid.take().unwrap(); - let result = spawns.spawn( + let grid = self.core.host.take_grid(); + let result = self.core.host.with_spawns( &mut self.core.world, - &grid, - &mut Spawn { - host: &mut self.core.host, - buffs: &mut buffs, - content: &mut content, - }, - key, - options, + &mut buffs, + |spawns, context, world| spawns.spawn(world, &grid, context, key, options), ); - self.core.host.spawns = Some(spawns); self.core.host.buffs = Some(buffs); - self.core.host.content = Some(content); self.core.host.grid = Some(grid); if result.is_err() { self.faulted = true; @@ -484,6 +814,25 @@ impl Field { } /// Owned accounting snapshot. This internal field result is not a policy /// observation and exposes no provisional success for a faulted execution. + pub fn result(&self) -> Result { + self.healthy()?; + if !self.finished() { + return Err("Field result requires a finished battle".into()); + } + let ledger = &self.core.host.spawns.as_ref().unwrap().ledger; + let player = self.core.world.player(1).unwrap(); + Ok(FieldResult { + killed: ledger.killed, + credited_kills: ledger.credited_kills, + counted_leaks: ledger.counted_leaks(), + coins: ledger.coins, + damage: player.damage, + healing: player.healing, + match_boss_damage: player.match_boss_damage, + boss: self.boss_state()?, + boss_round: self.boss_round_state()?, + }) + } pub fn report(&self) -> Result { self.healthy()?; let reason = self.reason().map(|e| match e { @@ -491,80 +840,241 @@ impl Field { End::Timeout => "timeout", End::Forced => "forced", }); - Ok(self + let mut report = self .core .host .spawns .as_ref() .unwrap() .ledger - .report(self.time(), reason)) + .report(self.time(), reason); + let loss = self.core.host.content.as_ref().unwrap().lp_loss(); + if self.finished() && loss > 0. { + report["lpLoss"] = Value::from(loss); + } + if let Some(state) = self.boss_state()? { + report["bossHpLeft"] = Value::from(state.hp); + report["perPlayer"]["p"]["bossDamage"] = Value::from(state.damage); + } + if let Some(state) = self.boss_round_state()? { + let (outcome, reason) = match state.outcome { + None => (None, None), + Some(BossRoundOutcome::Victory) => (Some("victory"), Some("cleared")), + Some(BossRoundOutcome::LifeDepleted) => (Some("defeat"), Some("lp_depleted")), + Some(BossRoundOutcome::Timeout) => (Some("defeat"), Some("timeout")), + Some(BossRoundOutcome::Forced) => (Some("defeat"), Some("forced")), + }; + report["bossRound"] = json!({"initialLp":state.initial_lp,"lp":state.lp,"leakLoss":state.leak_loss,"skillLoss":state.skill_loss,"overtimeLoss":state.overtime_loss,"outcome":outcome,"reason":reason}); + } + Ok(report) } } fn inside(r: Rect, p: [i32; 2]) -> bool { p[0] >= r.r0 && p[0] <= r.r1 && p[1] >= r.c0 && p[1] <= r.c1 } impl clock::Host for Core { + fn movement_batch(&mut self, clock: &mut Clock, budget: usize) -> Result { + self.run_movement_batch(clock, budget) + } fn phase(&mut self, phase: Phase, c: &mut Clock) -> Result<(), String> { self.world.time = c.time(); match phase { Phase::Start => { - let grid = self.host.grid.take().unwrap(); + self.install_devices()?; + self.host.growth_install(&self.world)?; + let mut buffs = self.host.buffs.take().unwrap(); + let result = self + .host + .bonds_install(&mut self.world, &mut buffs) + .and_then(|_| self.host.growth_begin_readers(&mut self.world, &mut buffs)) + .and_then(|_| self.host.equipment_install(&mut self.world, &mut buffs)) + .and_then(|_| self.host.bands_install(&mut self.world, &mut buffs, false)); + self.host.buffs = Some(buffs); + result?; + self.host.rebuild_index(&self.world)?; + let order = self + .host + .roster + .as_ref() + .unwrap() + .initial_order(&self.world)?; + for id in order { + let grid = self.host.take_grid(); + let mut roster = self.host.roster.take().unwrap(); + let mut buffs = self.host.buffs.take().unwrap(); + let result = roster.deploy_initial_unit( + &mut self.world, + &mut buffs, + &mut self.host, + &grid, + id, + ); + self.host.roster = Some(roster); + self.host.grid = Some(grid); + let result = result + .and_then(|_| self.host.flush_kit_events(&mut self.world, &mut buffs)); + self.host.buffs = Some(buffs); + result?; + } + let mut summons = self + .host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .filter(|&id| { + self.world.unit(id).is_ok_and(|u| { + u.deployment.kind == super::deploy::Kind::Token + && u.stats.alive + && u.deployed + }) + }) + .collect::>(); + summons.sort_by_key(|&id| self.world.unit(id).unwrap().deployment.deploy_seq); + for id in summons { + let sequence = self.world.next_deployment_sequence()?; + self.world.unit_mut(id)?.deployment.aggro_seq = sequence; + } + self.start_map_devices()?; + let mut buffs = self.host.buffs.take().unwrap(); + let result = self + .host + .choices_start(&mut self.world, &mut buffs) + .and_then(|_| { + self.host.kit_event( + &mut self.world, + &mut buffs, + &mut kits::dispatch::Event::BattleStart, + ) + }) + .and_then(|_| self.host.yan_start(&mut self.world, &mut buffs)) + .and_then(|_| self.host.egir_start(&mut self.world, &mut buffs)) + .and_then(|_| self.host.bands_install(&mut self.world, &mut buffs, true)); + self.host.buffs = Some(buffs); + result?; + let ids = self.host.roster.as_ref().unwrap().ids().to_vec(); + for id in ids { + let roster = self.host.roster.as_mut().unwrap(); + let dp = roster.entry(id)?.definition.initial_dp; + if dp != 0. { + roster.add_dp(dp)?; + } + } + let mut buffs = self.host.buffs.take().unwrap(); + let result = self.host.advanced_flush_starts(&mut self.world, &mut buffs); + self.host.buffs = Some(buffs); + result?; + self.host.refresh_kit_effects(&mut self.world, 0.)?; + c.mark_started(); + } + Phase::Scheduled => { + let mut r = self.host.buffs.take().unwrap(); + let result = self.host.growth_refresh(&mut self.world, &mut r); + self.host.buffs = Some(r); + result?; + self.device_scheduled()?; + self.cold_wind_scheduled()?; let mut roster = self.host.roster.take().unwrap(); let mut r = self.host.buffs.take().unwrap(); - let result = roster.deploy_initial(&mut self.world, &mut r, &mut self.host, &grid); + let result = roster.scheduled(&mut self.world, &mut r, &mut self.host); self.host.roster = Some(roster); self.host.buffs = Some(r); - self.host.grid = Some(grid); result?; - c.mark_started(); + self.host.component_scheduled(&mut self.world)?; + self.host.support_scheduled(&mut self.world)?; + self.host.advanced_scheduled(&mut self.world)?; + self.host.tactical_scheduled(&mut self.world)?; } Phase::Spawns => { - let mut spawns = self.host.spawns.take().unwrap(); let mut buffs = self.host.buffs.take().unwrap(); - let mut content = self.host.content.take().unwrap(); - let grid = self.host.grid.take().unwrap(); - let result = spawns.process( - &mut self.world, - &grid, - &mut Spawn { - host: &mut self.host, - buffs: &mut buffs, - content: &mut content, - }, - ); - self.host.spawns = Some(spawns); + let grid = self.host.take_grid(); + let result = + self.host + .with_spawns(&mut self.world, &mut buffs, |spawns, context, world| { + spawns.process(world, &grid, context) + }); self.host.buffs = Some(buffs); - self.host.content = Some(content); self.host.grid = Some(grid); result?; } Phase::Dp => self.host.roster.as_mut().unwrap().recover_dp(DT)?, Phase::Buffs => { - let mut ids = self.host.roster.as_ref().unwrap().ids().to_vec(); + // Reusable tick list: this phase never re-enters another phase. + let mut ids = std::mem::take(&mut self.host.scratch); + ids.clear(); + ids.extend_from_slice(self.host.roster.as_ref().unwrap().ids()); ids.extend_from_slice(self.host.spawns.as_ref().unwrap().live()); let mut r = self.host.buffs.take().unwrap(); let result = r.tick(&mut self.world, &mut self.host, &ids, DT); self.host.buffs = Some(r); + self.host.scratch = ids; result?; } Phase::Enemies => { - let ids = self.host.spawns.as_ref().unwrap().live().to_vec(); + let mut ids = std::mem::take(&mut self.host.scratch); + ids.clear(); + ids.extend_from_slice(self.host.spawns.as_ref().unwrap().live()); let mut r = self.host.buffs.take().unwrap(); let mut rng = self.host.rng.clone(); - let mut grid = self.host.grid.take().unwrap(); + let mut grid = self.host.take_grid(); let result = (|| { - for id in ids { - enemy::update( - &mut self.world, - &mut grid, - &mut r, - &mut rng, - &mut self.host, - id, - DT, - self.unit_limit, - )?; + let mut movement_map_dirty = true; + for &id in &ids { + let moved = self.movement_batching + && self.movement_paths.step( + &mut self.world, + &mut self.host, + &grid, + id, + &mut movement_map_dirty, + )?; + if !moved { + enemy::update( + &mut self.world, + &mut grid, + &mut r, + &mut rng, + &mut self.host, + id, + DT, + self.unit_limit, + )?; + movement_map_dirty = true; + } + self.host.devices.flush(&mut grid)?; + if self.host.route_query_grid.version() != grid.version() { + self.host.route_query_grid.clone_from(&grid); + } + self.host.enemy_special_flush(&mut self.world, &mut r, id)?; + if self.world.unit(id)?.deployment.remove_reason.as_deref() == Some("leak") + { + // Leaving the field releases Ines' stolen attack too. + let operators = self.host.roster.as_ref().unwrap().ids().to_vec(); + for source in operators { + if matches!( + self.host.tac_def(source)?.extra.tactics, + super::content::operators::Tactics::Ines(_) + ) { + self.host.kit_event_for( + &mut self.world, + &mut r, + source, + &mut kits::dispatch::Event::Death { + unit: id, + credit: None, + }, + )?; + } + } + } + if !matches!( + self.host.content.as_ref().unwrap().kit_ref(id), + content::Kit::Plain + ) { + movement_map_dirty = true; + } let u = self.world.unit_mut(id)?; let rect = grid.rect(); let m = 0.5 - 1. / 1048576.; @@ -575,29 +1085,39 @@ impl clock::Host for Core { .max(rect.c0 as f64 - m) .min(rect.c1 as f64 + m); } + self.movement_paths.retain_live(&self.world); Ok::<_, String>(()) })(); self.host.buffs = Some(r); self.host.rng = rng; self.host.grid = Some(grid); + self.host.scratch = ids; result?; } Phase::AttackCommit => { self.host.rebuild_index(&self.world)?; - let ids = self.host.roster.as_ref().unwrap().ids().to_vec(); - self.commitments - .capture(&mut self.world, &mut self.host, &ids, DT)?; + let mut ids = std::mem::take(&mut self.host.scratch); + ids.clear(); + ids.extend_from_slice(self.host.roster.as_ref().unwrap().ids()); + let result = self + .commitments + .capture(&mut self.world, &mut self.host, &ids, DT); + self.host.scratch = ids; + result?; } Phase::EnemyIndex => self.host.rebuild_index(&self.world)?, Phase::Allies => { - let ids = self.host.roster.as_ref().unwrap().ids().to_vec(); - for id in ids { + let mut cursor = 0; + while cursor < self.host.roster.as_ref().unwrap().ids().len() { + let id = self.host.roster.as_ref().unwrap().ids()[cursor]; + cursor += 1; if !self.world.unit(id)?.stats.alive || !self.world.unit(id)?.deployed { continue; } let mut skill = self.host.roster.as_mut().unwrap().take_skill(id)?; let result = (|| { skill.tick(&mut self.world, &mut self.host, DT)?; + self.host.resume_kit_skill(&mut self.world, &mut skill)?; super::ally::update( &mut self.world, &mut self.host, @@ -606,7 +1126,10 @@ impl clock::Host for Core { Some(&mut skill), DT, self.unit_limit, - ) + )?; + self.host + .advanced_finish_skill(&mut self.world, &mut skill)?; + self.host.support_flush_sp(&mut self.world, &mut skill) })(); let restore = self.host.roster.as_mut().unwrap().restore_skill(id, skill); result?; @@ -620,25 +1143,50 @@ impl clock::Host for Core { result?; } Phase::Redeploy => { - let grid = self.host.grid.take().unwrap(); + let grid = self.host.take_grid(); let mut roster = self.host.roster.take().unwrap(); let mut r = self.host.buffs.take().unwrap(); let result = roster.check_redeploys(&mut self.world, &mut r, &mut self.host, &grid); self.host.roster = Some(roster); - self.host.buffs = Some(r); self.host.grid = Some(grid); + let result = + result.and_then(|_| self.host.advanced_flush_starts(&mut self.world, &mut r)); + self.host.buffs = Some(r); result?; } Phase::TickHook => { - let ids = self.host.spawns.as_ref().unwrap().live().to_vec(); + self.host.growth_dolls(&self.world)?; + let mut ids = std::mem::take(&mut self.host.scratch); + ids.clear(); + ids.extend_from_slice(self.host.spawns.as_ref().unwrap().live()); let mut r = self.host.buffs.take().unwrap(); - let mut content = self.host.content.take().unwrap(); - let result = content.tick(&mut self.world, &mut r, &mut self.host, &ids, DT); + let result = self + .host + .enemy_content_tick(&mut self.world, &mut r, &ids, DT); + self.host.buffs = Some(r); + self.host.scratch = ids; + result?; + let mut r = self.host.buffs.take().unwrap(); + let result = self.host.refresh_terrain(&mut self.world, &mut r); + self.host.buffs = Some(r); + result?; + self.tick_turrets(DT)?; + let mut roster = self.host.roster.take().unwrap(); + let mut r = self.host.buffs.take().unwrap(); + let result = roster.tick_effects(&mut self.world, &mut r, &mut self.host); + self.host.roster = Some(roster); + self.host.buffs = Some(r); + result?; + self.host.refresh_kit_effects(&mut self.world, DT)?; + self.host + .kit_event_with_buffs(&mut self.world, &mut kits::dispatch::Event::Tick)?; + let mut r = self.host.buffs.take().unwrap(); + let result = self.host.choices_tick(&mut self.world, &mut r); self.host.buffs = Some(r); - self.host.content = Some(content); result?; } - // Timers, boss pools and custom content hooks are not admitted here. + Phase::Boss if self.boss.is_some() => self.host.sync_bosses(&mut self.world)?, + // Remaining phases require no separate work here. _ => {} } Ok(()) @@ -651,30 +1199,24 @@ impl clock::Host for Core { > self.host.spawns.as_ref().unwrap().live().len() } fn release_removed(&mut self, _: &mut Clock) -> Result<(), String> { - let mut spawns = self.host.spawns.take().unwrap(); let mut buffs = self.host.buffs.take().unwrap(); - let mut content = self.host.content.take().unwrap(); - let result = spawns.release_removed( - &mut self.world, - &mut Spawn { - host: &mut self.host, - buffs: &mut buffs, - content: &mut content, - }, - ); - self.host.spawns = Some(spawns); + let result = + self.host + .with_spawns(&mut self.world, &mut buffs, |spawns, context, world| { + spawns.release_removed(world, context) + }); self.host.buffs = Some(buffs); - self.host.content = Some(content); result } + fn has_tick_hook(&self) -> bool { true } fn end_state(&self) -> Option { let r = self.host.spawns.as_ref().unwrap(); Some(EndState { - shared_hp: None, - boss_like: false, + shared_hp: self.boss.and_then(|_| self.world.pool(1).map(|p| p.hp)), + boss_like: self.boss.is_some(), auto_finish: true, pending_spawns: !r.queue.pending().is_empty(), enemy_alive: !r.live().is_empty(), @@ -693,6 +1235,17 @@ impl clock::Host for Core { } } impl health::Hooks for Host { + fn adjust_heal( + &mut self, + source: Option, + target: Id, + amount: f64, + options: health::HealOptions, + w: &mut World, + ) -> Result { + self.support_heal_amount(w, source, target, amount, options) + } + fn kill(&mut self, id: Id, credit: Option, w: &mut World) -> Result<(), String> { let mut r = self .buffs @@ -704,6 +1257,55 @@ impl health::Hooks for Host { } } impl Host { + fn take_grid(&mut self) -> Box { + // Reentrant targeting queries share the same geometry while movement or + // deployment temporarily owns the authoritative grid. Flow caches are local. + let grid = self.grid.take().unwrap(); + if self.route_query_grid.version() != grid.version() { + self.route_query_grid.clone_from(&grid); + } + grid + } + fn apply_status( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + key: &str, + options: super::status::Options, + ) -> Result { + let rect = self.rect; + super::status::apply(w, self, r, rect, id, key, options) + } + + fn with_spawns( + &mut self, + w: &mut World, + buffs: &mut buffs::Runtime, + operation: impl FnOnce( + &mut super::spawns::Runtime, + &mut Spawn<'_>, + &mut World, + ) -> Result, + ) -> Result { + if self.spawns.is_none() || self.content.is_none() { + return Err("Spawn context is already borrowed".into()); + } + let mut spawns = self.spawns.take().unwrap(); + let mut content = self.content.take().unwrap(); + let result = operation( + &mut spawns, + &mut Spawn { + host: self, + buffs, + content: &mut content, + }, + w, + ); + self.spawns = Some(spawns); + self.content = Some(content); + result + } fn kill_enemy( &mut self, id: Id, @@ -714,6 +1316,27 @@ impl Host { if !w.unit(id)?.stats.alive { return Ok(()); } + if self.enemy_knockout(w, r, id)? { + return Ok(()); + } + self.kit_kill(w, r, id, credit)?; + // A synchronous kill reaction can finish removing the same victim. + if !w.unit(id)?.stats.alive { + return Ok(()); + } + self.enemy_cancel_form_timers(w, id)?; + if let Some(source) = credit { + if w.unit(source)?.has_operator_kit() { + let roster = self.roster.as_mut().ok_or("Missing kill content context")?; + let dp = roster.entry(source)?.definition.dp_on_kill; + if dp != 0. { + roster.add_dp(dp)?; + } + } + } + let children = self + .enemy_torturer_children(w, id)? + .or(self.enemy_children(w, id)?); self.spawns.as_mut().unwrap().ledger.kill( id, credit @@ -741,171 +1364,308 @@ impl Host { if let Some(credit) = credit { w.unit_mut(credit)?.deployment.kills += 1; } - Ok(()) - } -} -impl buffs::Hooks for Host { - fn status(&mut self, _: Id, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Enemy buff callback is not implemented".into()) - } - fn burst_damage( - &mut self, - q: &mut hit::Request, - r: &mut buffs::Runtime, - w: &mut World, - ) -> Result { + if let Some(children) = children { + self.enemy_spawn_children(w, r, children)?; + } let mut rng = self.rng.clone(); - let result = settlement::resolve(w, r, &mut rng, self, q); + self.enemy_unload(w, id, &mut rng)?; self.rng = rng; - result - } - fn burst_sp_loss(&mut self, id: Id, amount: f64, w: &mut World) -> Result<(), String> { - if w.unit(id)?.side == health::Side::Ally { - self.roster - .as_mut() - .ok_or("Missing elemental SP context")? - .drain_sp(w, id, amount) - } else { - super::element::drain_sp(w, None, amount) - } + self.enemy_content_death(w, r, id, credit)?; + self.enemy_other_death(w, r, id)?; + self.support_enemy_death(w, r, id)?; + self.growth_death(w, id, credit)?; + self.kit_event(w, r, &mut kits::dispatch::Event::Death { unit: id, credit })?; + self.operator_enemy_death(w, id) } } -impl settlement::Hooks for Host { - fn phase_enabled(&self, p: hit::Phase) -> bool { - p == hit::Phase::Hit - } - fn damage_phase( +impl buffs::Hooks for Host { + fn field_deploy( &mut self, - p: hit::Phase, - q: &mut hit::Request, - _: &mut f64, - _: &mut buffs::Runtime, w: &mut World, - rng: &mut Rng, + r: &mut buffs::Runtime, + id: Id, + fresh: bool, ) -> Result<(), String> { - if p == hit::Phase::Hit && q.is_attack && w.unit(q.hit.target)?.side == health::Side::Enemy + let u = w.unit(id)?; + if fresh + && u.deployment.remove_reason.as_deref() == Some("killed") + && u.deployment.respawn_at > w.time + 1e-9 + && self.equipment_member(id, "raidShip") { - if let Some(id) = q.hit.source { - if w.unit(id)?.side == health::Side::Ally { - let entry = self - .roster - .as_ref() - .ok_or("Missing operator hit context")? - .entry(id)?; - entry.definition.hit.apply(w, id, entry.direction, q, rng)?; - } - } + self.bonds.raid_revived.insert(id, u.deployment.deploy_seq); } - Ok(()) + self.field_terrain(w, r, id, fresh) } - fn health_kill( + + fn operator_removed( &mut self, - id: Id, - credit: Option, - r: &mut buffs::Runtime, w: &mut World, + r: &mut buffs::Runtime, + id: Id, ) -> Result<(), String> { - if w.unit(id)?.side == health::Side::Enemy { - return self.kill_enemy(id, credit, r, w); + if w.unit(id)?.deployment.kind == super::deploy::Kind::Operator { + self.equipment.fields.clear(); } - let mut roster = self.roster.take().ok_or("Missing operator death context")?; - let result = roster.kill(w, r, self, id, credit); - self.roster = Some(roster); - result + self.advanced_removed(w, r, id) } - fn health_event( + + fn heal_with_buffs( &mut self, - e: &mut health::Event, + w: &mut World, r: &mut buffs::Runtime, + source: Option, + target: Id, + amount: f64, + options: health::HealOptions, + ) -> Result { + self.support_heal(w, r, source, target, amount, options) + } + + fn operator_skill_effect( + &mut self, w: &mut World, + r: &mut buffs::Runtime, + dir: super::direction::Direction, + def: &super::operators::Definition, + event: super::skills::Event, + ctx: &mut super::skills::Context, + skill: &mut super::skills::Runtime, ) -> Result<(), String> { - if e.stage == health::Stage::SkillDamaged { - let mut roster = self - .roster - .take() - .ok_or("Missing operator damage context")?; - let result = roster.damaged(w, r, self, e.target); - self.roster = Some(roster); - result?; - } - Ok(()) + self.component_skill(w, r, dir, def, event, ctx, skill)?; + self.support_skill(w, r, dir, def, event, ctx, skill)?; + self.advanced_event(w, r, dir, def, event, ctx, skill)?; + self.kit_skill_event(w, r, def, event, ctx, skill) } - fn damage_health_event( + + fn operator_target_status( &mut self, - e: &mut health::Event, - q: &mut hit::Request, - r: &mut buffs::Runtime, w: &mut World, - rng: &mut Rng, + r: &mut buffs::Runtime, + source: Id, + target: Id, + key: &str, + duration: f64, ) -> Result<(), String> { - if e.stage == health::Stage::Damaged { - if let Some(mut effect) = self.content.as_ref().unwrap().damaged(w, q)? { - self.rng = rng.clone(); - let result = super::element::apply(w, self, r, &mut effect); - *rng = self.rng.clone(); - result?; - } - } - self.health_event(e, r, w) - } -} -impl super::status::Hooks for Host { - fn has_before_status(&self) -> bool { - false + self.apply_status( + w, + r, + target, + key, + super::status::Options { + duration, + source: Some(source), + ..Default::default() + }, + )?; + Ok(()) } - fn before_status( + fn operator_release( &mut self, - _: &mut super::status::Context, - _: &mut buffs::Runtime, - _: &mut World, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, ) -> Result<(), String> { - Err("Enemy before-status hook not implemented".into()) - } - fn has_status_applied(&self) -> bool { - false + blocking::release( + w, + &mut allies::Blocking { + host: self, + buffs: r, + }, + id, + ) } - fn status_applied( + fn operator_status( &mut self, - _: &super::status::Context, - _: &mut buffs::Runtime, - _: &mut World, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + key: &str, + duration: f64, ) -> Result<(), String> { - Err("Enemy status-applied hook not implemented".into()) - } -} -impl super::element::Hooks for Host { - fn battle_rect(&self) -> Rect { - Rect::NORMAL + self.apply_status( + w, + r, + id, + key, + super::status::Options { + duration, + source: Some(id), + ..Default::default() + }, + )?; + Ok(()) } - fn element_enabled(&self, _: super::element::Phase) -> bool { - false + fn status(&mut self, _: Id, _: &str, _: bool) -> Result<(), String> { + Ok(()) } - fn element_event( + fn callback( &mut self, - _: super::element::Phase, - _: &mut super::element::Request, - _: f64, - _: f64, - _: &mut buffs::Runtime, - _: &mut World, + token: u64, + event: buffs::Event, + c: buffs::Context, + r: &mut buffs::Runtime, + w: &mut World, ) -> Result<(), String> { - Err("Enemy element hook not implemented".into()) + if token == bonds::SIRACUSA_END { + self.bond_siracusa_end(c.unit, w.time); + return Ok(()); + } + if token == bonds::SARGON_EXPIRE { + return self.bond_sargon_sync(w, r, c.unit); + } + use super::content::operators::{DECAY, DOT}; + if token == super::equipment::PEGASUS_HEAL && event == buffs::Event::Tick { + return self.equipment_pegasus_heal(w, r, c); + } + if token == super::equipment::DRAIN && event == buffs::Event::Tick { + return self.equipment_drain(w, r, c); + } + if matches!(token, super::terrain::INFECTION | super::terrain::DEEPSEA) + && event == buffs::Event::Tick + { + return self.terrain_damage(w, r, c, token == super::terrain::DEEPSEA); + } + if token == enemies::LANDING && event == buffs::Event::Expire { + return self.enemy_landing(w, r, c.unit); + } + if token == enemies::WOLF_REBORN && event == buffs::Event::Tick { + return self.wolf_reborn(w, r, c.unit); + } + if token == enemies::REBORN_FINISH && event == buffs::Event::Expire { + return self.enemy_reborn_finish(w, r, c.unit); + } + if token == enemies::TRANSLATOR_FINISH && event == buffs::Event::Expire { + return self.enemy_translator_finish(w, r, c.unit); + } + if token == enemies::XI_SHIELD && event == buffs::Event::Expire + || token == enemies::FEAR_CAGE && event == buffs::Event::Tick + { + return self.champion_buff(w, r, c); + } + if token == enemies::SURGE_TICK && event == buffs::Event::Tick { + return self.enemy_surge_tick(w, r, c); + } + if token == enemies::PART_DOT && event == buffs::Event::Tick { + return self.helm_dot(w, r, c); + } + if token == enemies::BLADE_RETURN && event == buffs::Event::Expire { + return self.blade_return(w, r, c.unit); + } + if token == enemies::PARASITE_TICK && event == buffs::Event::Tick { + return self.enemy_parasite_tick(w, r, c); + } + if token == enemies::PILOT_BURN && event == buffs::Event::Tick { + return self.enemy_pilot_tick(w, r, c); + } + if token == enemies::BURN_TICK && event == buffs::Event::Tick { + return self.enemy_burn_tick(w, r, c); + } + if token == enemies::SAND_TICK && event == buffs::Event::Tick { + return self.enemy_sand_tick(w, r, c); + } + if token == enemies::BLEED { + return self.enemy_bleed_event(event, c, r, w); + } + if (1500..1600).contains(&token) { + return self.kit_event( + w, + r, + &mut kits::dispatch::Event::Buff { + context: c, + event, + token, + }, + ); + } + if matches!( + token, + tactics::RAIN | tactics::DRIZZLE | tactics::SHIELD_LOST | tactics::GAP_FINISH + ) { + return self.kit_buff_event(w, r, c, event, token); + } + if matches!( + token, + super::content::operators::HP_DRAIN | super::content::operators::PLASMA_DRAIN + ) { + return self.support_drain(w, r, c, token); + } + if event != buffs::Event::Tick { + return Err("Unexpected operator buff callback".into()); + } + match token { + DECAY => { + let b = r.get(w, c.unit, c.buff)?; + let duration = b.runtime.duration; + let step = b.runtime.tick_count as f64; + let prev = (duration - step + 1.).max(0.); + let next = (duration - step).max(0.); + let start = self + .roster + .as_ref() + .unwrap() + .entry(c.unit)? + .definition + .extra + .start_buff + .as_ref() + .ok_or("Missing decay descriptor")?; + let def = start.def; + r.edit(w, c.unit, c.buff, |b| { + if prev > 0. && b.shield > 0. { + b.shield *= next / prev; + } + if def > 0. { + b.mods = [("defPct".into(), def * next / duration)].into(); + } + }) + } + DOT => { + let b = r.get(w, c.unit, c.buff)?; + let source = b.runtime.source.ok_or("Missing DoT source")?; + let amount = b.runtime.tick_payload; + let mut q = hit::Request::new( + health::Hit { + source: Some(source), + credit: Some(source), + target: c.unit, + damage_type: super::damage::DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + super::damage::Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.dodge_mode = super::injury::DodgeMode::Ignore; + q.tags.push("dot".into()); + let result = self.resolve_hit(w, r, &mut q); + result.map(|_| ()) + } + _ => Err("Buff callback is not implemented".into()), + } } - fn element_number(&mut self, _: Id, _: f64, _: super::element::Element) -> Result<(), String> { - Ok(()) + fn burst_damage( + &mut self, + q: &mut hit::Request, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result { + self.resolve_hit(w, r, q) } - fn burst_visual(&mut self, _: Id, _: super::element::Element, _: &World) -> Result<(), String> { - Ok(()) + fn burst_sp_loss(&mut self, id: Id, amount: f64, w: &mut World) -> Result<(), String> { + if w.unit(id)?.has_operator_kit() { + self.roster + .as_mut() + .ok_or("Missing elemental SP context")? + .drain_sp(w, id, amount) + } else { + super::element::drain_sp(w, None, amount) + } } } impl blocking::Hooks for Host { @@ -939,8 +1699,10 @@ impl blocking::Hooks for Host { id, ) } - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) // Current default operator kits have no block-event handlers. + fn blocked(&mut self, blocker: Id, id: Id, w: &mut World) -> Result<(), String> { + self.device_blocked(w, blocker, id)?; + self.enemy_special_blocked(id); + Ok(()) } fn ended(&mut self, id: Id, w: &mut World) -> Result<(), String> { let mut r = self @@ -966,8 +1728,27 @@ impl motion::Hooks for Host { fn cut_attack_stand(&mut self, _: Id, _: &mut World) -> Result<(), String> { Ok(()) } - fn leak(&mut self, id: Id, w: &mut World) -> Result<(), String> { + fn leak(&mut self, id: Id, w: &mut World, rng: &mut Rng) -> Result<(), String> { + let cost = if self.boss_round.is_some() { + let enemy = self + .spawns + .as_ref() + .unwrap() + .ledger + .alive() + .get(&id) + .ok_or("Missing leaking enemy")?; + Some(if enemy.lpr >= 0. { enemy.lpr } else { 1. }) + } else { + None + }; self.spawns.as_mut().unwrap().ledger.leak(id)?; + if let Some(cost) = cost { + self.boss_round + .as_mut() + .unwrap() + .charge(boss_round::Cost::Leak, cost)?; + } enemy::clear(w, id)?; let time = w.time; let u = w.unit_mut(id)?; @@ -976,29 +1757,66 @@ impl motion::Hooks for Host { u.removed = true; u.deployment.death_at = time; u.deployment.remove_reason = Some("leak".into()); + self.enemy_cancel_form_timers(w, id)?; + self.helm_detach(w, id)?; + self.enemy_unload(w, id, rng)?; Ok(()) } } impl Queries for Host { - fn skip_enemy(&mut self, _: Option, _: Id, _: &mut World) -> Result { + fn skip_enemy( + &mut self, + source: Option, + target: Id, + world: &mut World, + ) -> Result { + if let Some(source) = + source.filter(|&id| world.unit(id).is_ok_and(|u| u.side == health::Side::Ally)) + { + if let Some(filter) = world.unit(source)?.targeting.enemy_filter { + return filter(world, source, target); + } + } Ok(false) } fn remaining_distance(&mut self, id: Id, w: &mut World) -> Result { - motion::remaining_distance(w, self.grid.as_mut().ok_or("Missing route query grid")?, id) + let grid = self.grid.as_mut().unwrap_or(&mut self.route_query_grid); + motion::remaining_distance(w, grid, id) } fn body_distance(&mut self, id: Id, p: [f64; 2], w: &mut World) -> Result { Ok(super::body::distance(w.unit(id)?, p)) } } impl enemy::Hooks for Host { - fn profile(&mut self, id: Id, _: &mut World) -> Result { - Ok(self + fn profile(&mut self, id: Id, _w: &mut World) -> Result { + let mut profile = self .spawns .as_ref() .unwrap() .definition(id)? .profile - .clone()) + .clone(); + let kit = self.content.as_ref().unwrap().kit_ref(id); + match kit { + content::Kit::Ability(content::Ability::MaxTargets(n)) => { + profile.max_targets = *n; + } + content::Kit::Ability(content::Ability::Nest { .. }) => profile.no_attack = true, + content::Kit::Reaction(content::Reaction::Shell) => { + profile.deferred = true; + profile.shot = "mortar"; + } + content::Kit::Reaction(content::Reaction::Blood { .. }) => profile.no_attack = true, + _ => {} + } + self.enemy_movement_profile(id, kit, &mut profile); + self.enemy_lifecycle_profile(id, kit, &mut profile); + self.enemy_leader_profile(id, &mut profile); + self.enemy_boss_profile(kit, &mut profile); + self.enemy_caster_profile(id, kit, &mut profile); + self.enemy_special_profile(id, kit, &mut profile); + self.enemy_form_profile(id, &mut profile); + Ok(profile) } fn allies_in_radius( &mut self, @@ -1036,22 +1854,48 @@ impl enemy::Hooks for Host { limit, ) } - fn can_target(&mut self, _: Id, _: Id, _: &mut World) -> Result { - Ok(true) + fn can_target(&mut self, enemy: Id, ally: Id, w: &mut World) -> Result { + let unit = w.unit(ally)?; + Ok(match self.content.as_ref().unwrap().kit(enemy) { + content::Kit::Boss(content::Boss::Blade(_)) => !super::targeting::flying(w, ally)?, + content::Kit::Lifecycle(content::Lifecycle::Ugly { .. }) => !unit.motion_fly, + content::Kit::Zone(content::ZoneKit::Tank(_)) => unit.ground && !unit.motion_fly, + content::Kit::Caster(content::Caster { + passive: content::casters::Passive::Tomb { .. }, + .. + }) + | content::Kit::Zone(content::ZoneKit::Cannon { .. }) + | content::Kit::Leader(content::Leader::Skull { .. }) => !unit.motion_fly, + content::Kit::Movement( + content::Movement::Syufo { .. } + | content::Movement::BoneSpike { .. } + | content::Movement::Unbalanced(content::movement::Unbalance::LoseEgg(_)), + ) => !unit.motion_fly, + content::Kit::Reaction(content::Reaction::Fear(config)) if config.steal.is_some() => { + !unit.motion_fly + } + content::Kit::Form(content::Form::Stone(_)) if w.unit(enemy)?.motion_fly => { + !unit.motion_fly + } + _ => true, + }) } - fn enemy_event_enabled(&self, _: enemy::Event) -> bool { - false + fn enemy_event_enabled(&self, event: enemy::Event) -> bool { + matches!(event, enemy::Event::BeforeAttack | enemy::Event::Attack) } fn enemy_event( &mut self, - _: enemy::Event, - _: &mut enemy::Context, - _: &mut buffs::Runtime, - _: &mut World, - _: &mut Grid, - _: &mut Rng, + event: enemy::Event, + c: &mut enemy::Context, + r: &mut buffs::Runtime, + w: &mut World, + grid: &mut Grid, + rng: &mut Rng, ) -> Result<(), String> { - Err("Enemy event callback not implemented".into()) + self.rng = rng.clone(); + let result = self.enemy_content_attack(event, c, r, w, Some(grid)); + *rng = self.rng.clone(); + result } fn attack_visual(&mut self, _: Id, _: Id, _: &str) -> Result<(), String> { Ok(()) diff --git a/crates/engine/src/battle/runtime/advanced.rs b/crates/engine/src/battle/runtime/advanced.rs new file mode 100644 index 0000000..02c8d66 --- /dev/null +++ b/crates/engine/src/battle/runtime/advanced.rs @@ -0,0 +1,1561 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Lifecycle callbacks for the second-half operator batch. +use super::super::{ + attacks, body, + content::operators::*, + damage::{Damage, DamageType}, + direction::Direction, + displacement, + health::HealOptions, + hit, injury, + operators::Definition, + search, skills, + stats::{Buff, Numbers}, + targeting, +}; +use super::*; +use crate::deterministic::math::hypot; +mod combat; + +pub(super) const FLAME_EVADE: u64 = 1301; +#[derive(Clone, Copy)] +pub(super) enum Periodic { + Frame, + Fast, + Aura(f64), + Layer(f64), +} +impl Host { + pub(super) fn advanced_stat(w: &mut World, id: Id, stat: &str) -> Result { + Ok(w.unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n(stat)) + } + fn advanced_flag(w: &mut World, id: Id, flag: &str) -> Result { + Ok(w.unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains(flag)) + } + pub(super) fn advanced_has(w: &World, id: Id, key: &str) -> bool { + w.unit(id).is_ok_and(|u| { + u.stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(key)) + }) + } + pub(super) fn advanced_enemies(&self, w: &World, id: Id) -> Result, String> { + let keys = self + .roster + .as_ref() + .ok_or("Missing range context")? + .range(w, id)?; + Ok(self + .spawns + .as_ref() + .ok_or("Missing enemy context")? + .live() + .iter() + .copied() + .filter(|&e| { + w.unit(e) + .is_ok_and(|u| u.stats.alive && !u.hidden && body::in_range(u, &keys)) + }) + .collect()) + } + fn advanced_allies(&self, w: &mut World, id: Id) -> Result, String> { + let keys = self + .roster + .as_ref() + .ok_or("Missing allied range context")? + .range(w, id)?; + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + let mut out = vec![]; + for target in ids { + if targeting::friendly_selectable(w, id, target)? + && body::in_range(w.unit(target)?, &keys) + { + out.push(target); + } + } + Ok(out) + } + pub(super) fn advanced_status( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + key: &str, + duration: f64, + value: Option, + ) -> Result<(), String> { + self.apply_status( + w, + r, + target, + key, + super::super::status::Options { + duration, + source: Some(source), + value, + ..Default::default() + }, + )?; + Ok(()) + } + pub(super) fn advanced_toggle( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + key: &str, + on: bool, + mods: Numbers, + ) -> Result<(), String> { + if on { + if !w + .unit(id)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(key) && b.mods == mods) + { + self.component_buff(w, r, id, key, mods, f64::INFINITY, id)?; + } + } else { + r.remove(w, self, id, key)?; + } + Ok(()) + } + fn advanced_hit_damage( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + amount: f64, + kind: DamageType, + skill: bool, + attack: bool, + tag: &str, + ) -> Result { + let mut q = hit::Request::new( + health::Hit { + source: Some(source), + credit: Some(source), + target, + damage_type: kind, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.is_skill = skill; + q.is_attack = attack; + q.tags.push(tag.into()); + self.resolve_hit(w, r, &mut q) + } + pub(super) fn advanced_grant_sp( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + amount: f64, + ) -> Result<(), String> { + if amount <= 0. { + return Ok(()); + } + if self + .roster + .as_ref() + .ok_or("Missing SP recipient")? + .entry(id)? + .skill() + .is_err() + { + let limit = w + .unit_capacity() + .checked_mul(self.roster.as_ref().unwrap().ids().len()) + .ok_or("SP capacity overflow")?; + let pending = &mut w.unit_mut(id)?.operator.support.sp_changes; + if pending.len() >= limit { + return Err("Pending SP capacity exceeded".into()); + } + pending.push(crate::battle::content::operators::SpChange::Gain(amount)); + return Ok(()); + } + let mut roster = self.roster.take().unwrap(); + let result = roster.grant_sp(w, r, self, id, amount); + self.roster = Some(roster); + result.map(|_| ()) + } + fn advanced_abyssal(&self, id: Id) -> Result { + Ok(matches!( + self.roster + .as_ref() + .unwrap() + .entry(id)? + .definition + .char_id + .as_str(), + "char_263_skadi" + | "char_143_ghost" + | "char_1023_ghost2" + | "char_474_glady" + | "char_4145_ulpia" + )) + } + fn advanced_pull( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + target: Id, + p: &Glady, + point: Option<[f64; 2]>, + ) -> Result<(), String> { + if !w.unit(target)?.stats.alive { + return Ok(()); + } + let dir = self.roster.as_ref().unwrap().entry(id)?.direction; + let origin = w.unit(id)?.position; + let at = w.unit(target)?.position; + let force = p.force + + if point.is_none() + && p.far_radius > 0. + && hypot(at[0] - origin[0], at[1] - origin[1]) > p.far_radius + 1e-9 + { + p.far_force + } else { + 0. + }; + let grid = self.grid.take().ok_or("Missing pull grid")?; + let mut host = allies::Blocking { + host: self, + buffs: r, + }; + let result = if let Some(to) = point { + displacement::pull( + w, + &grid, + &mut host, + target, + force, + displacement::Pull { + to, + center: None, + stop: 0.05, + }, + ) + } else { + displacement::pull_to_front(w, &grid, &mut host, target, id, dir, force) + }; + self.grid = Some(grid); + let moved = result?; + if moved > 0. && p.drag > 0. && w.unit(target)?.stats.alive { + self.advanced_hit_damage( + w, + r, + id, + target, + p.drag * moved / p.drag_distance, + DamageType::Arts, + true, + false, + "drag", + )?; + } + Ok(()) + } + fn advanced_layers( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + n: u32, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.advanced.layers = n; + if n == 0 { + r.remove(w, self, id, "mudrok:layers")?; + return Ok(()); + } + let mut b = Buff { + key: Some("mudrok:layers".into()), + ..Default::default() + }; + b.runtime.shield_hits = n; + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + Ok(()) + } + fn advanced_weightless( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + left: f64, + ) -> Result<(), String> { + let ids = self.spawns.as_ref().unwrap().live().to_vec(); + for target in ids { + if w.unit(target)?.stats.alive && !Self::advanced_has(w, target, "aglina:weightless") { + let mut b = Buff { + key: Some("aglina:weightless".into()), + mods: [("massFlat".into(), -1.)].into(), + ..Default::default() + }; + b.runtime.duration = left.max(0.1); + b.runtime.source = Some(id); + b.runtime.status = Some("weightless".into()); + r.add( + w, + self, + target, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } + } + Ok(()) + } + pub(super) fn advanced_event( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + dir: Direction, + def: &Definition, + event: skills::Event, + c: &skills::Context, + s: &mut skills::Runtime, + ) -> Result<(), String> { + let id = s.unit(); + w.unit_mut(id)?.operator.advanced.skill_left = s.time_left; + if event == skills::Event::Start { + let m = &mut w.unit_mut(id)?.operator.advanced; + m.elapsed = 0.; + m.accumulator = 0.; + m.aura_accumulator = 0.; + m.dp_given = 0; + m.locked.clear(); + m.charged = + s.bank.max_charges() > 1 && s.bank.charges + 1. >= f64::from(s.bank.max_charges()); + if def.extra.advanced_start_heal > 0. { + let amount = Self::advanced_stat(w, id, "maxHp")? * def.extra.advanced_start_heal; + self.support_heal( + w, + r, + Some(id), + id, + amount, + HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + match &def.extra.advanced { + Advanced::Mostma(_) => {} + Advanced::Billro(p) => match p.mode { + Mode::First => { + if w.unit(id)?.operator.advanced.charged { + self.component_buff( + w, + r, + id, + "billro:s1guard", + p.guard.clone(), + f64::INFINITY, + id, + )?; + } + } + Mode::Second => { + if w.unit(id)?.operator.advanced.charged { + self.component_buff( + w, + r, + id, + "billro:charged", + [("atkPct".into(), p.charged_atk)].into(), + f64::INFINITY, + id, + )?; + } + } + Mode::Third => { + self.component_buff( + w, + r, + id, + "billro:s3atk", + [("atkPct".into(), 0.)].into(), + f64::INFINITY, + id, + )?; + } + }, + Advanced::Mudrok(p) if p.mode == Mode::Third => { + let mut b = Buff { + key: Some("mudrok:dormant".into()), + flags: ["invulnerable".into(), "disarm".into(), "noBlock".into()].into(), + ..Default::default() + }; + b.runtime.duration = p.sleep + 1.; + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + flags_present: true, + ..Default::default() + }, + )?; + blocking::release( + w, + &mut allies::Blocking { + host: self, + buffs: r, + }, + id, + )?; + } + Advanced::Flamtl(p) => { + if p.mode == Mode::First { + self.roster.as_mut().unwrap().add_dp(p.cost)?; + let mut b = Buff { + key: Some("flamtl:evade".into()), + ..Default::default() + }; + b.runtime.injury.on_injury = Some(FLAME_EVADE); + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + if p.mode == Mode::Second { + let keys = + targeting::absolute_range(&p.grid, w.unit(id)?.deployment.tile, dir, 0); + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + for a in ids { + if targeting::friendly_selectable(w, id, a)? + && body::in_range(w.unit(a)?, &keys) + { + self.component_buff( + w, + r, + a, + "flamtl:redPine", + [("dodgePhys".into(), p.ally_dodge)].into(), + p.ally_duration, + id, + )?; + } + } + } + } + Advanced::Lisa(p) if p.fox => { + w.unit_mut(id)?.operator.advanced.aura_accumulator = 0.25; + } + Advanced::Surtr(p) if p.mode == Mode::Third => { + let amount = Self::advanced_stat(w, id, "maxHp")?; + self.support_heal( + w, + r, + Some(id), + id, + amount, + HealOptions { + self_heal: true, + ignore_heal_free: true, + ..Default::default() + }, + )?; + } + Advanced::Aglina(p) if p.weightless => { + self.advanced_weightless(w, r, id, s.time_left)? + } + Advanced::Glady(p) if p.mode == Mode::Third => { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let mut foes = search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + let origin = w.unit(id)?.position; + foes.sort_by(|a, b| { + body::distance(w.unit(*b).unwrap(), origin) + .total_cmp(&body::distance(w.unit(*a).unwrap(), origin)) + .then(a.cmp(b)) + }); + w.unit_mut(id)?.operator.advanced.tornado = + foes.first().map(|&t| w.unit(t).unwrap().position); + if let Some(&t) = foes.first() { + self.advanced_status(w, r, id, t, "bind", s.spec.duration, None)?; + } + } + Advanced::Gnosis(p) if p.mode == Mode::Second => { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let mut foes = search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + targeting::sort_enemies(w, self, id, &mut foes, def.combat.profile.priority)?; + for target in foes { + let amount = Self::advanced_stat(w, id, "atk")? * p.burst_scale; + self.advanced_hit_damage( + w, + r, + id, + target, + amount, + DamageType::Arts, + true, + false, + "burst", + )?; + if w.unit(target)?.stats.alive { + self.advanced_status(w, r, id, target, "cold", p.burst_cold, None)?; + if w.unit(id)?.operator.advanced.charged { + self.advanced_status(w, r, id, target, "cold", p.burst_cold, None)?; + } + } + } + } + _ => {} + } + } + if event == skills::Event::SkillStart { + if let Advanced::Billro(p) = &def.extra.advanced { + r.remove(w, self, id, "trait:phalanxGuard")?; + let ratio = if w.unit(id)?.operator.advanced.charged { + p.charged_heal + } else { + p.heal + }; + let amount = Self::advanced_stat(w, id, "maxHp")? * ratio; + self.support_heal( + w, + r, + Some(id), + id, + amount, + HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + if !(p.mode == Mode::First && w.unit(id)?.operator.advanced.charged) + && p.keep.values().any(|v| *v != 0.) + { + self.component_buff( + w, + r, + id, + "billro:keep", + p.keep.clone(), + f64::INFINITY, + id, + )?; + } + } + if self.roster.is_some() { + self.advanced_learn(w, r, id, None)?; + } else { + if self.pending_skill_starts.len() >= w.unit_capacity() { + return Err("Skill notification capacity exceeded".into()); + } + self.pending_skill_starts.push(( + id, + w.unit_ids() + .filter(|&a| { + w.unit(a).is_ok_and(|u| { + u.side == health::Side::Ally && u.stats.alive && u.deployed + }) + }) + .collect(), + )); + } + } + if event == skills::Event::Tick { + self.advanced_skill_tick(w, r, id, dir, def, s, c.dt)?; + } + if event == skills::Event::End { + match &def.extra.advanced { + Advanced::Billro(_) => { + for key in ["billro:s1guard", "billro:charged", "billro:s3atk"] { + r.remove(w, self, id, key)?; + } + self.advanced_clear_marks(w, r, id, "billro:mark")?; + w.unit_mut(id)?.operator.advanced.charged = false; + } + Advanced::Mudrok(_) => { + r.remove(w, self, id, "mudrok:dormant")?; + r.remove(w, self, id, "mudrok:awake")?; + } + Advanced::Flamtl(p) if p.mode == Mode::Third && c.reason == "duration" => { + let left = p + .total + .saturating_sub(w.unit(id)?.operator.advanced.dp_given); + self.roster + .as_mut() + .unwrap() + .add_dp(f64::from(left) * p.cost)?; + } + Advanced::Fartth(_) => w.unit_mut(id)?.operator.advanced.extra_range.clear(), + Advanced::Lisa(_) => { + let ids: Vec<_> = w.unit_ids().collect(); + for a in ids { + r.remove(w, self, a, &format!("lisa:fox:{id}"))?; + } + } + Advanced::Aglina(p) if p.weightless => { + self.advanced_clear_marks(w, r, id, "aglina:weightless")? + } + Advanced::Glady(p) if p.mode == Mode::Third => { + let pos = w.unit_mut(id)?.operator.advanced.tornado.take(); + if c.reason != "death" && w.unit(id)?.stats.alive { + if let Some(pos) = pos { + let foes = self.advanced_radius(w, pos, 1.)?; + for target in foes { + self.advanced_pull(w, r, id, target, p, None)?; + } + } + } + } + Advanced::Gnosis(p) if p.mode == Mode::Third => { + if c.reason != "death" && w.unit(id)?.stats.alive { + let mut list = self.advanced_enemies(w, id)?; + let held = w.unit(id)?.operator.advanced.locked.clone(); + for a in held { + if w.unit(a).is_ok_and(|u| u.stats.alive) && !list.contains(&a) { + list.push(a); + } + } + for target in list { + if Self::advanced_has(w, target, "freeze") { + let amount = Self::advanced_stat(w, id, "atk")? * p.burst_scale; + self.advanced_hit_damage( + w, + r, + id, + target, + amount, + DamageType::Arts, + true, + false, + "shatter", + )?; + r.remove(w, self, target, "freeze")?; + } + } + } + w.unit_mut(id)?.operator.advanced.locked.clear(); + } + _ => {} + } + } + if event == skills::Event::SkillEnd { + if let Advanced::Billro(p) = &def.extra.advanced { + if w.unit(id)?.stats.alive { + self.component_buff( + w, + r, + id, + "trait:phalanxGuard", + p.guard.clone(), + f64::INFINITY, + id, + )?; + } + r.remove(w, self, id, "billro:keep")?; + } + } + Ok(()) + } + fn advanced_radius( + &mut self, + w: &mut World, + pos: [f64; 2], + radius: f64, + ) -> Result, String> { + let ids = self.spawns.as_ref().unwrap().live().to_vec(); + spatial::enemies_in_radius( + w, + self, + &ids, + pos, + radius, + spatial::RadiusRule::Body, + true, + w.unit_capacity(), + ) + } + fn advanced_clear_marks( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + key: &str, + ) -> Result<(), String> { + let ids: Vec<_> = w.unit_ids().collect(); + for a in ids { + if w.unit(a)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(key) && b.runtime.source == Some(id)) + { + r.remove(w, self, a, key)?; + } + } + Ok(()) + } + pub(super) fn advanced_flush_starts( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + self.flush_kit_events(w, r)?; + let pending = std::mem::take(&mut self.pending_skill_starts); + for (id, eligible) in pending { + self.advanced_learn(w, r, id, Some(&eligible))?; + } + Ok(()) + } + fn advanced_learn( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + eligible: Option<&[Id]>, + ) -> Result<(), String> { + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + for id in ids { + if id == source + || eligible.is_some_and(|a| !a.contains(&id)) + || !w.unit(id)?.stats.alive + || !w.unit(id)?.deployed + { + continue; + } + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + let Advanced::Reckpr(p) = &def.extra.advanced else { + continue; + }; + let keys = self.roster.as_ref().unwrap().range(w, id)?; + if !body::in_range(w.unit(source)?, &keys) + || p.probability < 1. && !self.rng.chance(p.probability) + { + continue; + } + self.advanced_grant_sp(w, r, id, p.sp)?; + if p.aspd != 0. { + self.component_buff( + w, + r, + id, + "reckpr:learn", + [("aspd".into(), p.aspd)].into(), + p.learn_duration, + id, + )?; + } + } + Ok(()) + } + fn advanced_skill_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + dir: Direction, + def: &Definition, + s: &mut skills::Runtime, + dt: f64, + ) -> Result<(), String> { + { + let m = &mut w.unit_mut(id)?.operator.advanced; + m.elapsed += dt; + m.accumulator += dt; + m.aura_accumulator += dt; + } + match &def.extra.advanced { + Advanced::Mostma(p) if p.lock => { + let targets = self.advanced_enemies(w, id)?; + for &target in &targets { + if w.unit_mut(id)?.operator.advanced.locked.insert(target) { + self.advanced_status( + w, + r, + id, + target, + "stun", + s.time_left.max(0.01), + None, + )?; + } + } + if w.unit(id)?.operator.advanced.accumulator + 1e-9 >= 1. { + w.unit_mut(id)?.operator.advanced.accumulator -= 1.; + for target in targets { + let damage = Self::advanced_stat(w, id, "atk")? * p.lock_scale; + self.advanced_hit_damage( + w, + r, + id, + target, + damage, + DamageType::Arts, + true, + false, + "timeLock", + )?; + } + } + } + Advanced::Billro(p) if p.mode == Mode::Third => { + let value = p.ramp_atk + * (w.unit(id)?.operator.advanced.elapsed + 1e-9) + .floor() + .min(20.) + / 20.; + self.advanced_edit_mod(w, r, id, "billro:s3atk", "atkPct", value)?; + } + Advanced::Mudrok(p) + if p.mode == Mode::Third && !Self::advanced_has(w, id, "mudrok:awake") => + { + let keys = targeting::absolute_range(&p.grid, w.unit(id)?.deployment.tile, dir, 0); + let targets = self.spawns.as_ref().unwrap().live().to_vec(); + let mut nearby = vec![]; + for a in targets { + if w.unit(a)?.stats.alive + && !w.unit(a)?.hidden + && body::in_range(w.unit(a)?, &keys) + && targeting::can_target_enemy( + w, + self, + Some(id), + a, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? + { + nearby.push(a); + } + } + for &a in &nearby { + self.component_buff( + w, + r, + a, + &format!("mudrok:slow:{id}"), + [("moveMul".into(), (1. + p.slow).max(0.))].into(), + 0.25, + id, + )?; + } + if w.unit(id)?.operator.advanced.elapsed + 1e-9 >= p.sleep { + r.remove(w, self, id, "mudrok:dormant")?; + for a in nearby { + if !targeting::flying(w, a)? { + self.advanced_status(w, r, id, a, "stun", p.stun, None)?; + } + } + self.component_buff( + w, + r, + id, + "mudrok:awake", + p.awake.clone(), + f64::INFINITY, + id, + )?; + } + } + Advanced::Flamtl(p) if p.mode == Mode::Third => { + let step = (s.spec.duration / f64::from(p.total.max(1))).max(DT); + while w.unit(id)?.operator.advanced.accumulator + 1e-9 >= step + && w.unit(id)?.operator.advanced.dp_given < p.total + { + let m = &mut w.unit_mut(id)?.operator.advanced; + m.accumulator -= step; + m.dp_given += 1; + self.roster.as_mut().unwrap().add_dp(p.cost)?; + } + } + Advanced::Fartth(p) if p.mode == Mode::Second => { + let ids = self.spawns.as_ref().unwrap().live(); + let mut keys: Vec<_> = ids + .iter() + .filter_map(|&a| { + let u = w.unit(a).ok()?; + if !u.stats.alive + || u.hidden + || !u.blocked_by().is_some_and(|b| { + w.unit(b) + .is_ok_and(|b| b.stats.alive && b.side == health::Side::Ally) + }) + { + return None; + } + Some( + (u.position[0].round() as usize) * super::super::grid::COLS + + u.position[1].round() as usize, + ) + }) + .collect(); + keys.sort_unstable(); + w.unit_mut(id)?.operator.advanced.extra_range = keys; + } + Advanced::Lisa(p) if p.fox => { + if w.unit(id)?.operator.advanced.aura_accumulator >= 0.25 { + w.unit_mut(id)?.operator.advanced.aura_accumulator = 0.; + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let targets = search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + for a in targets { + self.advanced_status(w, r, id, a, "sluggish", 0.5, None)?; + } + } + if w.unit(id)?.operator.advanced.accumulator >= 1. { + w.unit_mut(id)?.operator.advanced.accumulator -= 1.; + let value = Self::advanced_stat(w, id, "atk")? * p.regen; + for a in self.advanced_allies(w, id)? { + self.component_buff( + w, + r, + a, + &format!("lisa:fox:{id}"), + [("hpRegen".into(), value)].into(), + 1.25, + id, + )?; + } + } + } + Advanced::Surtr(p) if p.mode == Mode::Third && p.drain_peak > 0. => { + while w.unit(id)?.operator.advanced.accumulator >= p.drain_interval + && w.unit(id)?.stats.alive + { + w.unit_mut(id)?.operator.advanced.accumulator -= p.drain_interval; + let rate = p.drain_peak + * (w.unit(id)?.operator.advanced.elapsed / p.drain_ramp).min(1.); + let amount = Self::advanced_stat(w, id, "maxHp")? * rate * p.drain_interval; + self.support_lose_hp(w, r, id, amount, Some(id), true)?; + } + } + Advanced::Aglina(p) + if p.weightless && w.unit(id)?.operator.advanced.aura_accumulator >= 0.25 => + { + w.unit_mut(id)?.operator.advanced.aura_accumulator = 0.; + self.advanced_weightless(w, r, id, s.time_left)?; + } + Advanced::Glady(p) if p.mode == Mode::Third => { + if let Some(pos) = w.unit(id)?.operator.advanced.tornado { + let targets = self.advanced_radius(w, pos, 1.5)?; + for &a in &targets { + self.component_buff( + w, + r, + a, + &format!("glady:slow:{id}"), + [("moveMul".into(), (1. + p.slow).max(0.))].into(), + 0.25, + id, + )?; + } + if w.unit(id)?.operator.advanced.accumulator + 1e-9 >= p.interval { + w.unit_mut(id)?.operator.advanced.accumulator -= p.interval; + for a in targets { + if w.unit(a)?.stats.alive && !Self::advanced_flag(w, a, "untargetable")? + { + let amount = Self::advanced_stat(w, id, "atk")? * p.scale; + self.advanced_hit_damage( + w, + r, + id, + a, + amount, + DamageType::Arts, + true, + false, + "tornado", + )?; + self.advanced_pull(w, r, id, a, p, Some(pos))?; + } + } + } + } + } + Advanced::Gnosis(p) if p.mode == Mode::Third => { + for a in self.advanced_enemies(w, id)? { + if let Some(b) = w + .unit(a)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("freeze")) + { + let bid = b.runtime.id(); + if b.runtime.time_left < s.time_left { + r.edit(w, a, bid, |b| { + b.runtime.time_left = s.time_left; + b.runtime.duration = b.runtime.duration.max(s.time_left); + })?; + } + w.unit_mut(id)?.operator.advanced.locked.insert(a); + } + } + } + _ => {} + } + Ok(()) + } + fn advanced_edit_mod( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + key: &str, + stat: &str, + value: f64, + ) -> Result<(), String> { + if let Some(b) = w + .unit(id)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some(key)) + { + let bid = b.runtime.id(); + if b.mods.get(stat).copied() != Some(value) { + r.edit(w, id, bid, |b| { + b.mods.insert(stat.into(), value); + })?; + } + } + Ok(()) + } +} +impl Host { + pub(super) fn advanced_scheduled(&mut self, w: &mut World) -> Result<(), String> { + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + let mut r = self.buffs.take().ok_or("Missing periodic buffs")?; + let result = (|| { + self.advanced_flush_starts(w, &mut r)?; + for &id in &ids { + if matches!( + self.roster + .as_ref() + .unwrap() + .entry(id)? + .definition + .extra + .advanced, + Advanced::None + ) && w.unit(id)?.operator.advanced.locked.is_empty() + { + continue; + } + let mut locked = std::mem::take(&mut w.unit_mut(id)?.operator.advanced.locked); + locked.retain(|a| w.unit(*a).is_ok_and(|u| u.stats.alive)); + w.unit_mut(id)?.operator.advanced.locked = locked; + self.advanced_periodic(w, &mut r, &ids, id, Periodic::Frame)?; + } + Ok(()) + })(); + self.buffs = Some(r); + result + } + pub(super) fn advanced_deadlines(&self, w: &World) -> Result, String> { + let mut due = vec![]; + for &id in self.roster.as_ref().unwrap().ids() { + let def = &self.roster.as_ref().unwrap().entry(id)?.definition; + if matches!(def.extra.advanced, Advanced::None) { + continue; + } + let state = &w.unit(id)?.operator.advanced; + let period = if matches!(def.extra.advanced, Advanced::Lisa(_) | Advanced::Aglina(_)) { + 0.25 + } else { + 0.2 + }; + for (at, kind) in [ + (state.next_fast.max(0.1), Periodic::Fast), + (state.next_aura.max(period), Periodic::Aura(period)), + ] { + if at <= w.time + 1e-9 { + due.push((at, id, kind)); + } + } + if let Advanced::Mudrok(p) = &def.extra.advanced { + if state.next_layer <= w.time + 1e-9 && Self::tac_up(w, id) { + due.push((state.next_layer, id, Periodic::Layer(p.layer_period))); + } + } + } + Ok(due) + } + pub(super) fn advanced_periodic( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ids: &[Id], + id: Id, + event: Periodic, + ) -> Result<(), String> { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + let state = &mut w.unit_mut(id)?.operator.advanced; + match event { + Periodic::Fast => state.next_fast = state.next_fast.max(0.1) + 0.1, + Periodic::Aura(period) => state.next_aura = state.next_aura.max(period) + period, + Periodic::Layer(period) => state.next_layer += period, + Periodic::Frame => {} + } + if !Self::tac_up(w, id) { + return Ok(()); + } + let now = w.time; + let active = w.unit(id)?.operator.active_skill; + let fast = matches!(event, Periodic::Fast); + let aura = matches!(event, Periodic::Aura(_)); + let layer = matches!(event, Periodic::Layer(_)); + let frame = matches!(event, Periodic::Frame); + match &def.extra.advanced { + Advanced::Mostma(p) if aura => { + let slow = p.slow * if p.ripple && active { p.slow_scale } else { 1. }; + for a in self.advanced_enemies(w, id)? { + self.component_buff( + w, + r, + a, + &format!("mostma:slow:{id}"), + [("moveMul".into(), (1. + slow).max(0.))].into(), + 0.25, + id, + )?; + } + } + Advanced::Mizuki(p) => { + if fast { + let targets = self.advanced_enemies(w, id)?; + let mut on = false; + for a in targets { + if w.unit(a)?.stats.hp / Self::advanced_stat(w, a, "maxHp")? < p.threshold { + on = true; + break; + } + } + self.advanced_toggle( + w, + r, + id, + "mizuki:t2", + on, + [("atkPct".into(), p.attack)].into(), + )?; + } + if aura && p.slow != 0. { + for a in self.advanced_enemies(w, id)? { + self.component_buff( + w, + r, + a, + &format!("mizuki:slow:{id}"), + [("moveMul".into(), (1. + p.slow).max(0.))].into(), + 0.25, + id, + )?; + } + } + } + Advanced::Aroma(p) if frame => { + let pending = w.unit(id)?.operator.advanced.floating.clone(); + for a in pending { + if !w.unit(a).is_ok_and(|u| u.stats.alive) { + w.unit_mut(id)?.operator.advanced.floating.remove(&a); + continue; + } + if !Self::advanced_has(w, a, "levitate") { + w.unit_mut(id)?.operator.advanced.floating.remove(&a); + if active && p.landing { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + if body::in_range(w.unit(a)?, &keys) { + let amount = Self::advanced_stat(w, id, "atk")? * p.land_scale; + self.advanced_hit_damage( + w, + r, + id, + a, + amount, + DamageType::Arts, + true, + false, + "landing", + )?; + } + } + } + } + } + Advanced::Billro(p) if fast => { + let ready = self + .roster + .as_ref() + .unwrap() + .entry(id)? + .skill()? + .bank + .charges + >= 1.; + self.advanced_toggle( + w, + r, + id, + "billro:t2", + ready && !active, + [("spRecoveryFlat".into(), p.recovery)].into(), + )?; + } + Advanced::Mudrok(p) => { + if layer { + let layers = w.unit(id)?.operator.advanced.layers; + if layers < p.layer_cap { + self.advanced_layers( + w, + r, + id, + layers.saturating_add(p.layer_add).min(p.layer_cap), + )?; + } + } + if aura && p.module.values().any(|v| *v != 0.) { + let home = w.unit(id)?.deployment.tile; + let mut lonely = true; + for &a in ids { + let u = w.unit(a)?; + if a != id + && u.stats.alive + && u.deployed + && (u.deployment.tile[0] - home[0]).abs() <= 1 + && (u.deployment.tile[1] - home[1]).abs() <= 1 + { + lonely = false; + break; + } + } + self.advanced_toggle(w, r, id, "mudrok:module", lonely, p.module.clone())?; + } + } + Advanced::Flamtl(p) => { + if fast && p.module.values().any(|v| *v != 0.) { + self.advanced_toggle( + w, + r, + id, + "flamtl:module", + !w.unit(id)?.blocking().is_empty(), + p.module.clone(), + )?; + } + if aura { + for &a in ids { + let d = &self.roster.as_ref().unwrap().entry(a)?.definition; + let key = &d.key; + if self.data.table("chess").unwrap()[key]["nationId"] == "kazimierz" + && w.unit(a)?.stats.alive + && w.unit(a)?.deployed + { + self.component_buff( + w, + r, + a, + "flamtl:dodge", + [("dodgePhys".into(), p.faction_dodge)].into(), + 0.25, + id, + )?; + } + } + } + } + Advanced::Fartth(p) if fast => { + self.advanced_toggle( + w, + r, + id, + "fartth:focus", + now - w.unit(id)?.operator.advanced.last_hurt >= p.delay - 1e-9, + [("atkPct".into(), p.focus)].into(), + )?; + } + Advanced::Lisa(p) if aura => { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let targets = search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + if p.module_sp > 0. && !targets.is_empty() { + self.component_buff( + w, + r, + id, + "lisa:module", + [("spRecoveryFlat".into(), p.module_sp)].into(), + 0.5, + id, + )?; + } + for a in targets { + if Self::advanced_has(w, a, "sluggish") { + self.advanced_status( + w, + r, + id, + a, + "fragile", + 0.5, + Some(p.fragile * if active { p.boost } else { 1. }), + )?; + } + } + } + Advanced::Mountain(p) if aura && p.module_aspd != 0. => { + if w.unit(id)?.stats.hp / Self::advanced_stat(w, id, "maxHp")? > 0.5 { + self.component_buff( + w, + r, + id, + "f12yin:module", + [("aspd".into(), p.module_aspd)].into(), + 0.3, + id, + )?; + } + } + Advanced::Surtr(p) if aura => { + if p.module_aspd != 0. { + if w.unit(id)?.blocking().is_empty() { + self.component_buff( + w, + r, + id, + "surtr:module", + [("aspd".into(), p.module_aspd)].into(), + 0.3, + id, + )?; + } else { + r.remove(w, self, id, "surtr:module")?; + } + } + if p.module_fragile > 0. { + let held = w.unit(id)?.blocking().to_vec(); + for a in held { + if w.unit(a)?.stats.alive { + self.advanced_status( + w, + r, + id, + a, + "artsFragile", + 0.3, + Some(p.module_fragile), + )?; + } + } + } + } + Advanced::Aglina(p) if aura => { + for &a in ids { + if targeting::friendly_selectable(w, id, a)? { + if p.aspd != 0. { + self.component_buff( + w, + r, + a, + "aglina:field", + [("aspd".into(), p.aspd)].into(), + 0.5, + id, + )?; + } + if !active && p.regen > 0. { + self.component_buff( + w, + r, + a, + "aglina:parttime", + [("hpRegen".into(), p.regen)].into(), + 0.5, + id, + )?; + } + } + } + if p.module_sp > 0. { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + if !search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )? + .is_empty() + { + self.component_buff( + w, + r, + id, + "aglina:module", + [("spRecoveryFlat".into(), p.module_sp)].into(), + 0.5, + id, + )?; + } + } + } + Advanced::Glady(p) if aura => { + for &a in ids { + if self.advanced_abyssal(a)? && w.unit(a)?.stats.alive && w.unit(a)?.deployed { + self.component_buff( + w, + r, + a, + "glady:tide", + [("hpRegenRatio".into(), p.regen)].into(), + 0.25, + id, + )?; + } + } + } + Advanced::Gnosis(p) => { + if fast { + let targets = self.advanced_enemies(w, id)?; + let elite = targets + .iter() + .any(|&a| w.unit(a).is_ok_and(|u| u.boss || u.targeting.elite)); + if p.module_sp > 0. { + self.advanced_toggle( + w, + r, + id, + "gnosis:module", + elite, + [("spRecoveryFlat".into(), p.module_sp)].into(), + )?; + } + for a in targets { + let scale = if Self::advanced_flag(w, a, "freeze")? { + p.fragile_frozen + } else if Self::advanced_flag(w, a, "cold")? { + p.fragile_cold + } else { + 0. + }; + if scale > 0. { + super::super::valued::apply( + w, + self, + r, + a, + super::super::valued::Request { + key: "gnosis:fragile", + kind: super::super::valued::Kind::Custom(|v| { + [("dmgTakenMul".into(), v)].into() + }), + plain: true, + duration: 0.15, + value: scale, + source: Some(id), + stack_as: None, + }, + )?; + } + } + } + if aura + && now - w.unit(id)?.deployment.deployed_at >= p.resist_delay - 1e-9 + && p.resist > 0. + { + for &a in ids { + let key = &self.roster.as_ref().unwrap().entry(a)?.definition.key; + if self.data.table("chess").unwrap()[key]["nationId"] == "kjerag" + && w.unit(a)?.stats.alive + && w.unit(a)?.deployed + { + self.advanced_status(w, r, id, a, "resist", 0.25, Some(p.resist))?; + } + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/advanced/combat.rs b/crates/engine/src/battle/runtime/advanced/combat.rs new file mode 100644 index 0000000..3d23cec --- /dev/null +++ b/crates/engine/src/battle/runtime/advanced/combat.rs @@ -0,0 +1,861 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Continuous-combat callbacks for legacy operator components. +use super::*; + +impl Host { + pub(in crate::battle::runtime) fn advanced_before( + &mut self, + c: &mut attacks::Context, + w: &mut World, + ) -> Result<(), String> { + let id = c.attacker; + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + let active = w.unit(id)?.operator.active_skill; + match &def.extra.advanced { + Advanced::Harold(p) if p.severe && active => { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let mut candidates = + search::Host::injured_allies(self, id, &keys, true, w, w.unit_capacity())?; + let mut order = vec![]; + for a in candidates.drain(..) { + let load = w + .unit(a)? + .element_buildup + .iter() + .copied() + .fold(0., f64::max); + let ratio = w.unit(a)?.stats.hp / Self::advanced_stat(w, a, "maxHp")?; + order.push((a, load, ratio, w.unit(a)?.deployment.deploy_seq)); + } + order.sort_by(|a, b| { + b.1.total_cmp(&a.1) + .then(a.2.total_cmp(&b.2)) + .then(a.3.cmp(&b.3)) + }); + c.targets = order + .into_iter() + .take(c.targets.len().max(1)) + .map(|x| x.0) + .collect(); + w.unit_mut(id)?.operator.advanced.harold_half = c + .targets + .iter() + .copied() + .filter(|&a| w.unit(a).unwrap().element_buildup.iter().any(|&v| v > 500.)) + .collect(); + } + Advanced::Mountain(p) => { + let probability = if p.mode == Mode::Third && active { + p.active_probability + } else { + p.probability + }; + w.unit_mut(id)?.operator.advanced.critical = + probability > 0. && self.rng.chance(probability); + } + Advanced::Surtr(p) if p.mode == Mode::Second => { + w.unit_mut(id)?.operator.advanced.solo = active && c.targets.len() == 1; + } + Advanced::Flamtl(_) => { + if w.unit(id)?.operator.advanced.riposte { + let m = &mut w.unit_mut(id)?.operator.advanced; + m.riposte = false; + m.riposte_now = true; + let held = w.unit(id)?.blocking().to_vec(); + for a in held { + if !c.targets.contains(&a) + && targeting::can_target_enemy( + w, + self, + Some(id), + a, + def.combat.profile.selection, + )? + { + c.targets.push(a); + } + } + } + } + Advanced::Fartth(p) if p.mode == Mode::Second && active => { + let own = targeting::absolute_range( + &p.base_grid, + w.unit(id)?.deployment.tile, + self.roster.as_ref().unwrap().entry(id)?.direction, + 0, + ); + let eligible = |w: &World, a: Id| { + w.unit(a).is_ok_and(|u| { + body::in_range(u, &own) + || u.blocked_by().is_some_and(|b| { + w.unit(b) + .is_ok_and(|u| u.stats.alive && u.side == health::Side::Ally) + }) + }) + }; + if c.targets.iter().any(|&a| !eligible(w, a)) { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let mut targets = search::Host::enemies( + self, + id, + &keys, + def.combat.profile.selection, + w, + w.unit_capacity(), + )?; + for &a in w.unit(id)?.blocking() { + if !targets.contains(&a) { + targets.push(a); + } + } + targets.retain(|&a| eligible(w, a)); + targeting::sort_enemies( + w, + self, + id, + &mut targets, + def.combat.profile.priority, + )?; + targets.truncate(c.targets.len().max(1)); + c.targets = targets; + } + } + Advanced::Gnosis(p) if p.mode == Mode::Third && active => { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let mut targets = search::Host::enemies( + self, + id, + &keys, + def.combat.profile.selection, + w, + w.unit_capacity(), + )?; + for &a in w.unit(id)?.blocking() { + if !targets.contains(&a) { + targets.push(a); + } + } + if targets.len() > 1 { + targeting::sort_enemies( + w, + self, + id, + &mut targets, + def.combat.profile.priority, + )?; + targets.sort_by_key(|&a| Self::advanced_has(w, a, "freeze")); + targets.truncate(c.targets.len().max(1)); + c.targets = targets; + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn advanced_attack( + &mut self, + c: &attacks::Context, + w: &mut World, + ) -> Result<(), String> { + let id = c.attacker; + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + let active = w.unit(id)?.operator.active_skill; + let mut r = self.buffs.take().ok_or("Missing attack callback buffs")?; + let result = (|| { + match &def.extra.advanced { + Advanced::Mizuki(p) if w.unit(id)?.stats.alive => { + if active + && p.mode == Mode::Third + && c.targets + .iter() + .filter(|&&a| w.unit(a).is_ok_and(|u| u.side == health::Side::Enemy)) + .count() + < 3 + { + let amount = Self::advanced_stat(w, id, "maxHp")? * p.loss; + self.support_lose_hp(w, &mut r, id, amount, None, false)?; + } + if !w.unit(id)?.stats.alive { + return Ok(()); + } + let mut targets: Vec<_> = c + .targets + .iter() + .copied() + .filter(|&a| { + w.unit(a) + .is_ok_and(|u| u.stats.alive && u.side == health::Side::Enemy) + }) + .collect(); + targets.sort_by(|a, b| { + w.unit(*a) + .unwrap() + .stats + .hp + .total_cmp(&w.unit(*b).unwrap().stats.hp) + .then(a.cmp(b)) + }); + targets.truncate( + p.count + + if active && p.mode != Mode::First { + p.extra + } else { + 0 + }, + ); + for a in targets { + let amount = Self::advanced_stat(w, id, "atk")? + * p.scale + * if p.mode == Mode::First && c.is_skill { + p.skill_scale + } else { + 1. + }; + self.advanced_hit_damage( + w, + &mut r, + id, + a, + amount, + DamageType::Arts, + false, + false, + "talent", + )?; + if active && p.mode != Mode::First && w.unit(a)?.stats.alive { + self.advanced_status( + w, + &mut r, + id, + a, + if p.mode == Mode::Second { + "bind" + } else { + "stun" + }, + p.status, + None, + )?; + } + } + } + Advanced::Flamtl(_) => { + if std::mem::take(&mut w.unit_mut(id)?.operator.advanced.riposte_now) { + for &a in &c.targets { + if w.unit(a)?.stats.alive { + let amount = Self::advanced_stat(w, id, "atk")? + * Self::advanced_stat(w, id, "atkScaleMul")?; + self.advanced_hit_damage( + w, + &mut r, + id, + a, + amount, + DamageType::Physical, + false, + true, + "riposte", + )?; + } + } + } + } + _ => {} + } + Ok(()) + })(); + self.buffs = Some(r); + result + } + pub(in crate::battle::runtime) fn advanced_impact( + &mut self, + impact: attacks::Impact, + skill: Option<&mut skills::Runtime>, + w: &mut World, + ) -> Result<(), String> { + let id = impact.attacker; + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + let active = w.unit(id)?.operator.active_skill; + let mut r = self.buffs.take().ok_or("Missing impact buffs")?; + let result = (|| { + if impact.heal { + if let Some(target) = impact.target { + match &def.extra.advanced { + Advanced::Harold(p) => { + let mut amount = Self::advanced_stat(w, id, "atk")? * p.element_ratio; + if p.severe + && active + && w.unit(id)?.operator.advanced.harold_half.contains(&target) + { + amount *= p.extra_scale; + } + if !crate::battle::element::locked(w, target)? { + for v in &mut w.unit_mut(target)?.element_buildup { + *v -= v.min(amount); + } + } + } + Advanced::Reckpr(p) + if p.guard && active && p.heal > 0. && w.unit(target)?.stats.alive => + { + let mut b = Buff { + key: Some("reckpr:guard".into()), + ..Default::default() + }; + b.runtime.duration = p.duration; + b.runtime.source = Some(id); + b.runtime.tick_payload = p.heal; + r.add( + w, + self, + target, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + _ => {} + } + } + return Ok(()); + } + let Some(target) = impact.target else { + return Ok(()); + }; + if let Advanced::Surtr(p) = &def.extra.advanced { + if p.mode == Mode::First && impact.is_skill && !w.unit(target)?.stats.alive { + if let Some(skill) = skill { + let cost = skill.bank.cost(w)?; + skill.gain(w, self, cost, "skill", false, false)?; + } + } + } + if !w.unit(target)?.stats.alive { + return Ok(()); + } + match &def.extra.advanced { + Advanced::Mountain(p) + if w.unit(id)?.operator.advanced.critical && p.weaken != 0. => + { + self.component_buff( + w, + &mut r, + target, + "f12yin:punch", + [("atkPct".into(), p.weaken)].into(), + p.duration, + id, + )?; + } + Advanced::Aroma(p) + if !p.landing && impact.is_skill && targeting::flying(w, target)? => + { + let amount = Self::advanced_stat(w, id, "atk")? * p.fly_scale; + self.advanced_hit_damage( + w, + &mut r, + id, + target, + amount, + DamageType::Arts, + true, + false, + "antiAir", + )?; + } + Advanced::Glady(p) if p.mode != Mode::Third && impact.is_skill => { + self.advanced_pull(w, &mut r, id, target, p, None)?; + } + Advanced::Mostma(p) if p.ripple && active && impact.is_skill => { + let dir = self.roster.as_ref().unwrap().entry(id)?.direction; + let grid = self.grid.take().ok_or("Missing ripple grid")?; + let result = displacement::push( + w, + &grid, + &mut allies::Blocking { + host: self, + buffs: &mut r, + }, + target, + p.force, + displacement::Push { + from: Some(displacement::Origin::unit(w, id, dir)?), + ..Default::default() + }, + ); + self.grid = Some(grid); + result?; + } + _ => {} + } + Ok(()) + })(); + self.buffs = Some(r); + result + } +} +impl Host { + fn advanced_enemy_tag(&self, id: Id, tag: &str) -> bool { + self.spawns + .as_ref() + .and_then(|s| s.definition(id).ok()) + .is_some_and(|d| { + self.data.table("enemies").unwrap()[&d.key]["tags"] + .as_array() + .is_some_and(|tags| tags.iter().any(|t| t == tag)) + }) + } + pub(in crate::battle::runtime) fn advanced_phase( + &mut self, + p: hit::Phase, + q: &mut hit::Request, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + if p != hit::Phase::Hit { + return Ok(()); + } + if w.unit(q.hit.target)?.side == health::Side::Ally + && w.unit(q.hit.target)?.deployment.kind != crate::battle::deploy::Kind::Device + { + let def = Arc::clone( + &self + .roster + .as_ref() + .unwrap() + .entry(q.hit.target)? + .definition, + ); + if let Advanced::Mudrok(m) = &def.extra.advanced { + if q.hit + .source + .is_some_and(|a| self.advanced_enemy_tag(a, "sarkaz")) + { + q.damage.mul *= 1. - m.sarkaz_resistance; + } + } + if matches!(q.hit.damage_type, DamageType::Physical | DamageType::Arts) + && Self::advanced_has(w, q.hit.target, "glady:tide") + && q.hit + .source + .is_some_and(|a| self.advanced_enemy_tag(a, "seamonster")) + { + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + for id in ids { + if let Advanced::Glady(g) = &self + .roster + .as_ref() + .unwrap() + .entry(id)? + .definition + .extra + .advanced + { + q.damage.mul *= 1. - g.resistance; + } + } + } + } + let Some(source) = q + .hit + .source + .filter(|&a| w.unit(a).is_ok_and(|u| u.has_operator_kit())) + else { + return Ok(()); + }; + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(source)?.definition); + let active = w.unit(source)?.operator.active_skill; + match &def.extra.advanced { + Advanced::Mountain(m) if q.is_attack && w.unit(source)?.operator.advanced.critical => { + q.damage.mul *= m.scale + } + Advanced::Surtr(m) + if q.is_attack + && !q.is_splash + && active + && w.unit(source)?.operator.advanced.solo => + { + q.damage.amount *= m.solo + } + Advanced::Aroma(a) + if q.is_attack + && w.unit(q.hit.target)?.side == health::Side::Enemy + && !Self::advanced_has(w, q.hit.target, "aroma:bubbled") => + { + self.component_buff( + w, + r, + q.hit.target, + "aroma:bubbled", + Numbers::new(), + f64::INFINITY, + source, + )?; + q.damage.mul *= a.first_scale; + self.advanced_status(w, r, source, q.hit.target, "levitate", a.levitate, None)?; + } + Advanced::Billro(b) if w.unit(q.hit.target)?.side == health::Side::Enemy => { + if b.per_enemy > 0. { + let n = self.advanced_enemies(w, source)?.len() as f64; + q.damage.mul *= 1. + b.per_enemy * n.min(b.enemy_cap); + } + if b.mode == Mode::Third { + if q.is_attack && active && w.unit(source)?.operator.advanced.charged { + let old = w + .unit(q.hit.target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("billro:mark")) + .map(|b| (b.runtime.time_left, b.runtime.source)); + let mut mark = Buff { + key: Some("billro:mark".into()), + ..Default::default() + }; + mark.runtime.duration = old.map(|x| x.0).unwrap_or_else(|| { + (self + .roster + .as_ref() + .unwrap() + .entry(source) + .unwrap() + .skill() + .map(|s| s.time_left) + .unwrap_or(w.unit(source).unwrap().operator.advanced.skill_left) + + 0.1) + .max(0.1) + }); + mark.runtime.source = old.and_then(|x| x.1).or(Some(source)); + mark.runtime.refresh = buffs::Refresh::Stack; + mark.runtime.max_stacks = 5; + r.add( + w, + self, + q.hit.target, + buffs::Spec { + buff: mark, + ..Default::default() + }, + )?; + } + if let Some(mark) = w.unit(q.hit.target)?.stats.buffs().iter().find(|b| { + b.key.as_deref() == Some("billro:mark") && b.runtime.source == Some(source) + }) { + q.damage.mul *= 1. + b.mark * f64::from(mark.stacks); + } + } + } + Advanced::Fartth(f) => { + if active && q.hit.damage_type == DamageType::Physical { + q.dodge_mode = injury::DodgeMode::Ignore; + } + if f.mode == Mode::Third && active && q.is_attack { + let keys = targeting::absolute_range( + &f.base_grid, + w.unit(source)?.deployment.tile, + self.roster.as_ref().unwrap().entry(source)?.direction, + 0, + ); + if !body::in_range(w.unit(q.hit.target)?, &keys) { + q.damage.mul *= f.far_scale; + } + } + } + Advanced::Glady(g) + if q.is_attack && w.unit(q.hit.target)?.side == health::Side::Enemy => + { + if Self::advanced_stat(w, q.hit.target, "massLevel")? <= g.max_weight { + q.damage.mul *= g.light_scale; + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn advanced_landed( + &mut self, + e: &health::Event, + q: &hit::Request, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + if w.unit(e.target)?.side == health::Side::Ally + && w.unit(e.target)?.deployment.kind != crate::battle::deploy::Kind::Device + { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(e.target)?.definition); + if let Advanced::Fartth(_) = &def.extra.advanced { + if e.amount > 0. && !q.hit.hp_loss { + w.unit_mut(e.target)?.operator.advanced.last_hurt = w.time; + } + } + if let Advanced::Mudrok(p) = &def.extra.advanced { + let left = w + .unit(e.target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("mudrok:layers")) + .map(|b| b.runtime.shield_hits) + .unwrap_or(0); + let broken = w + .unit(e.target)? + .operator + .advanced + .layers + .saturating_sub(left); + if broken > 0 && w.unit(e.target)?.stats.alive { + w.unit_mut(e.target)?.operator.advanced.layers = left; + let amount = Self::advanced_stat(w, e.target, "maxHp")? + * p.layer_heal + * f64::from(broken); + self.support_heal( + w, + r, + Some(e.target), + e.target, + amount, + HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + self.advanced_grant_sp(w, r, e.target, p.layer_sp * f64::from(broken))?; + } + } + if e.amount > 0. + && !q.hit.hp_loss + && q.hit.damage_type != DamageType::Elemental + && w.unit(e.target)?.stats.hp > 0. + { + let guard = w + .unit(e.target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("reckpr:guard")) + .map(|b| (b.runtime.source, b.runtime.tick_payload)); + if let Some((Some(source), amount)) = guard { + self.support_heal( + w, + r, + Some(source), + e.target, + amount, + HealOptions::default(), + )?; + } + } + } + let Some(source) = q + .hit + .source + .filter(|&a| w.unit(a).is_ok_and(|u| u.has_operator_kit())) + else { + return Ok(()); + }; + if w.unit(e.target)?.side != health::Side::Enemy { + return Ok(()); + } + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(source)?.definition); + match &def.extra.advanced { + Advanced::Billro(b) + if b.mode == Mode::Second + && q.is_attack + && w.unit(source)?.operator.active_skill + && w.unit(e.target)?.stats.alive => + { + let charged = w.unit(source)?.operator.advanced.charged; + self.advanced_status( + w, + r, + source, + e.target, + if charged { "bind" } else { "sluggish" }, + if charged { b.bind } else { b.sluggish }, + None, + )?; + } + Advanced::Gnosis(g) if q.is_attack && !q.is_splash && w.unit(e.target)?.stats.alive => { + self.advanced_status(w, r, source, e.target, "cold", g.cold, None)?; + } + Advanced::Fartth(f) + if q.is_attack + && !q.is_splash + && f.module_sp > 0. + && w.unit(e.target)?.stats.alive + && w.unit(e.target)?.stats.hp > 0. => + { + self.advanced_grant_sp(w, r, source, f.module_sp)?; + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn advanced_fatal( + &mut self, + e: &mut health::Event, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + if e.stage != health::Stage::Fatal + || e.prevented + || w.unit(e.target)?.side != health::Side::Ally + { + return Ok(()); + } + let id = e.target; + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + if let Advanced::Surtr(p) = &def.extra.advanced { + e.prevented = true; + if !w.unit(id)?.operator.advanced.ember { + let now = w.time; + let m = &mut w.unit_mut(id)?.operator.advanced; + m.ember = true; + self.tac_timer( + w, + id, + now + p.withdraw, + 0., + 1, + crate::battle::runtime::tactics::Task::Callback(|k| k.retreat()), + )?; + let mut b = Buff { + key: Some("surtr:ember".into()), + flags: ["noHeal".into(), "healFree".into()].into(), + ..Default::default() + }; + b.runtime.status = Some("healFree".into()); + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + flags_present: true, + ..Default::default() + }, + )?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn advanced_removed( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + self.advanced_clear_marks(w, r, id, "aroma:bubbled")?; + w.unit_mut(id)?.operator.advanced.riposte = false; + w.unit_mut(id)?.operator.advanced.riposte_now = false; + w.unit_mut(id)?.operator.advanced.extra_range.clear(); + Ok(()) + } + pub(in crate::battle::runtime) fn advanced_notice( + &mut self, + notice: injury::Notice, + q: &hit::Request, + w: &mut World, + ) -> Result<(), String> { + if matches!(notice, injury::Notice::Dodge { .. }) + && w.unit(q.hit.target)?.side == health::Side::Ally + && w.unit(q.hit.target)?.deployment.kind != crate::battle::deploy::Kind::Device + { + if matches!( + self.roster + .as_ref() + .unwrap() + .entry(q.hit.target)? + .definition + .extra + .advanced, + Advanced::Flamtl(_) + ) { + w.unit_mut(q.hit.target)?.operator.advanced.riposte = true; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn advanced_evade( + e: &mut injury::InjuryEvent, + c: &mut settlement::Context<'_, Self>, + ) -> Result<(), String> { + if c.request.hit.damage_type == DamageType::Physical + && c.request.is_attack + && c.request + .hit + .source + .is_some_and(|a| c.world.unit(a).is_ok_and(|u| u.side == health::Side::Enemy)) + && c.dodge(e, None)? + { + c.runtime + .remove_id(c.world, c.host, c.request.hit.target, c.buff)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn advanced_status_applied( + &mut self, + status: &crate::battle::status::Context, + w: &mut World, + ) -> Result<(), String> { + if status.key != "levitate" || w.unit(status.target)?.side != health::Side::Enemy { + return Ok(()); + } + if let Some(roster) = &self.roster { + for &id in roster.ids() { + if matches!( + roster.entry(id)?.definition.extra.advanced, + Advanced::Aroma(_) + ) { + w.unit_mut(id)? + .operator + .advanced + .floating + .insert(status.target); + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn advanced_element( + &mut self, + q: &mut crate::battle::element::Request, + w: &mut World, + ) -> Result<(), String> { + let target = q.damage.hit.target; + if w.unit(target)?.side != health::Side::Ally + || !w.unit(target)?.element_buildup.iter().any(|&v| v > 500.) + { + return Ok(()); + } + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + let mut cut: f64 = 0.; + for id in ids { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + if let Advanced::Harold(h) = &def.extra.advanced { + if w.unit(id)?.stats.alive && w.unit(id)?.deployed { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + if body::in_range(w.unit(target)?, &keys) { + cut = cut.max(h.resistance); + } + } + } + } + q.damage.damage.mul *= 1. - cut; + Ok(()) + } +} + +impl Host { + pub(in crate::battle::runtime) fn advanced_finish_skill( + &mut self, + w: &mut World, + skill: &mut skills::Runtime, + ) -> Result<(), String> { + if std::mem::take(&mut w.unit_mut(skill.unit())?.operator.skill_death_pending) { + skill.end(w, self, "death")?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/allies.rs b/crates/engine/src/battle/runtime/allies.rs index c077f91..33ae0db 100644 --- a/crates/engine/src/battle/runtime/allies.rs +++ b/crates/engine/src/battle/runtime/allies.rs @@ -5,9 +5,23 @@ use super::super::{ally, attacks, projectiles, search, skills, targeting}; use super::*; #[derive(Clone, Copy)] pub(super) enum Shot { + Turret(super::turrets::Shot), + Tactical(super::tactics::Arrow), Enemy(enemy::Delivery), + Skill(super::enemies::SkillShot), + Bomb(super::enemies::BombShot), + Cloud(super::enemies::CloudShot), + Seed { + source: Id, + amount: f64, + }, + BoomerangReturn { + source: Id, + deployment: u64, + }, Ally { source: Id, + deployment: u64, attack_id: u64, payload: attacks::Direct, area: attacks::Area, @@ -27,6 +41,159 @@ impl blocking::Hooks for Blocking<'_> { } } impl Host { + fn active_attack_filter( + &self, + w: &World, + id: Id, + ) -> Result, String> { + let entry = self + .roster + .as_ref() + .ok_or("Missing operator context")? + .entry(id)?; + let unit = w.unit(id)?; + let Some(filter) = entry.definition.attack_filter else { + return Ok(None); + }; + let key = format!("skill:{id}"); + // Modifiers follow skill activation even while its runtime is borrowed. + let active = unit + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(key.as_str())); + Ok(active.then_some(filter)) + } + fn filtered_targets( + &mut self, + w: &mut World, + id: Id, + p: search::AttackProfile, + filter: super::super::content::operators::AttackFilter, + ) -> Result, String> { + let keys = search::Host::range(self, id, w)?; + let candidates = search::Host::enemies(self, id, &keys, p.selection, w, w.unit_capacity())?; + let mut targets = Vec::with_capacity(candidates.len()); + for target in candidates { + if filter(w, target)? { + targets.push(target); + } + } + Ok(targets) + } + pub(super) fn operator_enemy_death(&mut self, w: &mut World, victim: Id) -> Result<(), String> { + let ids = self + .roster + .as_ref() + .ok_or("Missing death content context")? + .ids() + .to_vec(); + for id in ids { + let entry = self.roster.as_ref().unwrap().entry(id)?; + let def = Arc::clone(&entry.definition); + if let Some(effect) = &def.death_heal { + if let Some(amount) = effect.amount(w, id, victim, entry.direction)? { + health::heal( + w, + self, + Some(id), + id, + amount, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + } + } + Ok(()) + } + fn cast_start( + &mut self, + w: &mut World, + source: Id, + def: &super::super::operators::Definition, + ) -> Result<(), String> { + let Some(start) = &def.skill_start else { + return Ok(()); + }; + self.roster.as_mut().unwrap().add_dp(start.dp)?; + let Some(area) = &start.area else { + return Ok(()); + }; + let entry = self.roster.as_ref().unwrap().entry(source)?; + let keys = targeting::absolute_range( + &area.grid, + w.unit(source)?.deployment.tile, + entry.direction, + 0, + ); + let mut targets = search::Host::enemies( + self, + source, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + targeting::sort_enemies(w, self, source, &mut targets, def.combat.profile.priority)?; + for target in targets { + for _ in 0..area.hits { + if !w.unit(target)?.stats.alive { + break; + } + let amount = w + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * area.scale; + let mut q = hit::Request::new( + health::Hit { + source: Some(source), + credit: Some(source), + target, + damage_type: super::super::damage::DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + super::super::damage::Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.is_skill = true; + q.tags.push("skill".into()); + attacks::Hooks::damage(self, w, &mut q, None)?; + } + if w.unit(target)?.stats.alive { + let mut r = self.buffs.take().ok_or("Missing cast status context")?; + let result = self.apply_status( + w, + &mut r, + target, + "stun", + super::super::status::Options { + duration: area.stun, + source: Some(source), + ..Default::default() + }, + ); + self.buffs = Some(r); + result?; + } + } + Ok(()) + } pub(super) fn rebuild_index(&mut self, w: &World) -> Result<(), String> { self.index .as_mut() @@ -41,11 +208,27 @@ impl Field { return Err("Cannot retreat from a finished field".into()); } self.core.host.roster.as_ref().unwrap().entry(id)?; + if !Host::tac_up(&self.core.world, id) { + return Ok(()); + } self.core.world.time = self.clock.time(); let mut roster = self.core.host.roster.take().unwrap(); let mut r = self.core.host.buffs.take().unwrap(); let result = roster.retreat(&mut self.core.world, &mut r, &mut self.core.host, id); self.core.host.roster = Some(roster); + let result = result.and_then(|_| { + self.core.host.kit_event( + &mut self.core.world, + &mut r, + &mut kits::dispatch::Event::Death { + unit: id, + credit: None, + }, + )?; + self.core + .host + .flush_kit_events(&mut self.core.world, &mut r) + }); self.core.host.buffs = Some(r); if result.is_err() { self.faulted = true; @@ -71,7 +254,7 @@ impl Field { "buffs":u.stats.buffs().iter().map(|b|json!({"key":b.key,"left":b.runtime.time_left,"stacks":b.stacks,"persist":b.runtime.persist})).collect::>(), "sp":skill.bank.sp,"charges":skill.bank.charges, "left":skill.time_left,"active":skill.bank.active,"activations":skill.activations, - "attacks":u.attacks,"dealt":u.damage_dealt,"taken":u.damage_taken})); + "attacks":u.attacks,"dealt":u.damage_dealt,"taken":u.damage_taken,"healed":u.healing_done})); } Ok(out) } @@ -90,6 +273,9 @@ impl Field { } } impl skills::Hooks for Host { + fn can_activate(&mut self, skill: &skills::Runtime, w: &mut World) -> Result { + self.kit_can_activate(w, skill.unit()) + } fn event( &mut self, e: skills::Event, @@ -97,6 +283,10 @@ impl skills::Hooks for Host { s: &mut skills::Runtime, w: &mut World, ) -> Result<(), String> { + if e == skills::Event::SpGain { + self.kit_sp_gain(s.unit(), c)?; + return self.support_sp_gain(w, s.unit(), c); + } let def = Arc::clone( &self .roster @@ -106,9 +296,26 @@ impl skills::Hooks for Host { .definition, ); let mut r = self.buffs.take().ok_or("Missing skill buff context")?; - let result = def.skill_event(w, &mut r, self, e, c, s); + let direction = self.roster.as_ref().unwrap().entry(s.unit())?.direction; + let result = def.skill_event(w, &mut r, self, e, direction, c, s); self.buffs = Some(r); - result + result?; + if e == skills::Event::SkillStart { + self.resume_kit_skill(w, s)?; + } + if e == skills::Event::Start { + self.cast_start(w, s.unit(), &def)?; + if def.extra.effects.force_attack { + let profile = def.combat.profile; + let keys = search::Host::range(self, s.unit(), w)?; + let selection = + search::acquire(w, self, s.unit(), &keys, profile, w.unit_capacity())?; + if !selection.targets.is_empty() { + ally::Host::perform(self, s.unit(), profile, selection, Some(s), w)?; + } + } + } + Ok(()) } fn condition( &mut self, @@ -116,10 +323,129 @@ impl skills::Hooks for Host { skill: &skills::Runtime, w: &mut World, ) -> Result { + let id = skill.unit(); + let definition = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + if let Some(yes) = self.kit_condition(w, id, which)? { + return Ok(yes); + } + if matches!(which, skills::Condition::Allies) + || skill.spec.heal_skill && which == skills::Condition::Default + || skill.spec.heal_skill && which == skills::Condition::TickRule + { + let keys = if which == skills::Condition::TickRule + && skill.spec.rule == skills::Rule::Global + { + (0..super::super::grid::N).collect() + } else if which == skills::Condition::TickRule { + self.support_trigger_range(w, id, &definition)? + } else { + search::Host::range(self, id, w)? + }; + return Ok(!search::Host::injured_allies( + self, + id, + &keys, + definition + .combat + .profile + .heal + .is_some_and(|h| h.element_heal), + w, + w.unit_capacity(), + )? + .is_empty()); + } + if which == skills::Condition::TickRule && skill.spec.rule == skills::Rule::Search { + let keys = search::Host::range(self, id, w)?; + return Ok(!search::Host::enemies( + self, + id, + &keys, + definition.combat.profile.selection, + w, + w.unit_capacity(), + )? + .is_empty()); + } + if which == skills::Condition::TickRule { + if skill.spec.rule == skills::Rule::Global { + let keys: Vec<_> = (0..super::super::grid::N).collect(); + return Ok(!search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )? + .is_empty()); + } + if skill.spec.rule == skills::Rule::SpFull { + return Ok(true); + } + if skill.spec.rule == skills::Rule::ActiveRange { + // ACTIVE_RANGE follows DEFAULT's blocked-target condition, even + // when the blocker faces away from the enemy it is holding. + let held = w.unit(id)?.blocking().to_vec(); + for target in held { + if targeting::can_target_enemy( + w, + self, + Some(id), + target, + definition.combat.profile.selection, + )? { + return Ok(true); + } + } + } + if matches!( + skill.spec.rule, + skills::Rule::SkillRange | skills::Rule::ActiveRange | skills::Rule::CustomRange + ) { + let entry = self.roster.as_ref().unwrap().entry(id)?; + let grid = entry + .definition + .trigger_range + .as_ref() + .ok_or("Missing skill trigger grid")?; + let keys = targeting::absolute_range( + grid, + w.unit(id)?.deployment.tile, + entry.direction, + 0, + ); + if skill.spec.rule == skills::Rule::SkillRange { + return self + .index + .as_ref() + .ok_or("Missing enemy index")? + .any_enemy(w, &keys, false); + } + return Ok(!search::Host::enemies( + self, + id, + &keys, + if skill.spec.rule == skills::Rule::ActiveRange { + definition.combat.profile.selection + } else { + targeting::Profile { + can_hit_fly: true, + ..Default::default() + } + }, + w, + w.unit_capacity(), + )? + .is_empty()); + } + } if which != skills::Condition::Default { return Err("Unsupported operator trigger condition".into()); } - let id = skill.unit(); let keys = search::Host::range(self, id, w)?; let p = self .roster @@ -153,7 +479,7 @@ impl skills::Hooks for Host { )) } fn has_sp_hook(&self) -> bool { - false + true } } impl search::Host for Host { @@ -172,13 +498,19 @@ impl search::Host for Host { } fn injured_allies( &mut self, - _: Id, - _: &[usize], - _: bool, - _: &mut World, - _: usize, + id: Id, + keys: &[usize], + element: bool, + w: &mut World, + limit: usize, ) -> Result, String> { - Err("No healer kit is implemented in this field entry".into()) + let ids = self + .roster + .as_ref() + .ok_or("Missing healer roster")? + .ids() + .to_vec(); + spatial::injured_allies(w, self, &ids, keys, Some(id), element, limit) } fn has_ally_targets(&self) -> bool { false @@ -192,8 +524,14 @@ impl search::Host for Host { ) -> Result, String> { Err("No allied-target content is implemented in this field entry".into()) } - fn profile(&mut self, id: Id, w: &mut World) -> Result, String> { - skills::Hooks::profile(self, id, w) + fn profile(&mut self, id: Id, _: &mut World) -> Result, String> { + let entry = self.roster.as_ref().unwrap().entry(id)?; + let c = entry.definition.combat; + Ok(Some(if entry.skill()?.bank.active { + c.skill_profile.unwrap_or(c.profile) + } else { + c.profile + })) } fn range(&mut self, id: Id, w: &World) -> Result, String> { self.roster.as_ref().unwrap().range(w, id) @@ -210,21 +548,57 @@ impl search::Host for Host { } fn can_attack( &mut self, - _: Id, - _: search::AttackProfile, - _: &mut World, + id: Id, + p: search::AttackProfile, + w: &mut World, ) -> Result { - Ok(true) + let def = self.tac_def(id)?; + if let Some(kit) = def.extra.tactics.behavior() { + if !kit.can_attack(self, w, id)? { + return Ok(false); + } + } + if let Some(filter) = self.active_attack_filter(w, id)? { + Ok(!self.filtered_targets(w, id, p, filter)?.is_empty()) + } else { + Ok(true) + } } } impl ally::Host for Host { fn effective_profile( &mut self, id: Id, - _: Option<&skills::Runtime>, + skill: Option<&skills::Runtime>, w: &mut World, ) -> Result, String> { - search::Host::profile(self, id, w) + let c = self.roster.as_ref().unwrap().entry(id)?.definition.combat; + let mut profile = if skill.is_some_and(|s| s.bank.active) { + c.skill_profile.unwrap_or(c.profile) + } else { + c.profile + }; + if let super::super::content::operators::Advanced::Billro(p) = &self + .roster + .as_ref() + .unwrap() + .entry(id)? + .definition + .extra + .advanced + { + if p.mode == super::super::content::operators::Mode::First + && w.unit(id)?.operator.advanced.charged + && skill.is_some_and(|s| s.bank.active) + { + profile.no_attack = true; + } + } + if w.time < w.unit(id)?.operator.support.quiet_until { + profile.no_attack = true; + } + self.kit_profile(w, id, skill, &mut profile)?; + Ok(Some(profile)) } fn range_changed(&mut self, _: Id, _: &mut World) -> Result { Ok(false) @@ -232,45 +606,106 @@ impl ally::Host for Host { fn refresh_range(&mut self, _: Id, _: &mut World) -> Result<(), String> { Ok(()) } - fn has_store_energy(&self, _: Id, _: search::AttackProfile) -> bool { - false + fn has_store_energy(&self, id: Id, _: search::AttackProfile) -> bool { + self.tac_def(id).is_ok_and(|d| { + matches!( + d.extra.tactics, + super::super::content::operators::Tactics::Indigo(_) + ) + }) } fn store_energy( &mut self, - _: Id, + id: Id, _: search::AttackProfile, - _: &mut World, + world: &mut World, ) -> Result { - Err("No stored attack energy implemented for this operator".into()) + let def = self.tac_def(id)?; + let super::super::content::operators::Tactics::Indigo(kit) = &def.extra.tactics else { + return Ok(false); + }; + let state = world.unit_mut(id)?.operator.tactical.indigo_mut()?; + if state.stored >= kit.capacity { + return Ok(false); + } + state.stored += 1; + Ok(true) } fn perform( &mut self, id: Id, _: search::AttackProfile, selected: search::Selection, - skill: Option<&mut skills::Runtime>, + mut skill: Option<&mut skills::Runtime>, w: &mut World, ) -> Result<(), String> { + self.support_before_attack(w, id, &selected.targets, skill.as_deref_mut())?; let combat = self.roster.as_ref().unwrap().entry(id)?.definition.combat; let is_skill = skill.as_deref().is_some_and(|s| s.attack_override()); - let area = if is_skill { + let melee = selected.fortress_melee == Some(true); + let mut area = if is_skill { combat.skill_area } else { combat.area }; - let payload = attacks::Direct { - mode: attacks::Mode::Damage(combat.damage), - hits: 1, - atk_scale: 1., + area.fortress_melee = melee; + if melee { + area.splash = None; + } + let mut payload = attacks::Direct { + attachment: None, + element_heal_ratio: 0., + mode: if combat.heal || is_skill && combat.skill_heal { + attacks::Mode::Heal + } else { + attacks::Mode::Damage(if is_skill { + combat.skill_damage.unwrap_or(combat.damage) + } else { + combat.damage + }) + }, + hits: if is_skill + && self + .roster + .as_ref() + .unwrap() + .entry(id)? + .definition + .extra + .effects + .hit_upgrade + .is_some_and(|n| w.unit(id).is_ok_and(|u| u.operator.hits >= n)) + { + 4 + } else if is_skill { + combat.skill_hits + } else { + combat.normal_hits + }, + atk_scale: if is_skill { combat.skill_scale } else { 1. }, skill_damage_mul: 1., target_damage_mul: 1., - split_mul: None, - heal_scale: 1., + split_mul: combat.split_mul, + heal_scale: if is_skill { + combat.skill_heal_scale + } else { + 1. + }, is_skill, }; + self.kit_payload(w, id, &mut payload, &mut area)?; + let suppress_sp = w.unit(id)?.operator.support.bandage.is_some(); + let sp_type = skill.as_deref().map(|s| s.spec.sp_type); + if suppress_sp { + if let Some(s) = skill.as_deref_mut() { + s.spec.sp_type = skills::SpType::None; + } + } let mut executor = self.executor.take().ok_or("Reentrant attack executor")?; let result = (|| { - if let Some(projectile) = combat.projectile { + if let Some(projectile) = combat.projectile.filter(|_| { + !melee && !combat.heal && !(is_skill && (combat.skill_heal || combat.skill_direct)) + }) { let Some(prepared) = executor.prepare(w, self, id, &selected.targets, payload)? else { return Ok(()); @@ -287,7 +722,8 @@ impl ally::Host for Host { target: Some(target), to: None, speed: combat.projectile_speed, - hit_dead: area.splash.is_some(), + hit_dead: area.splash.is_some() + || combat.projectile == Some("boomerang"), max_age: 10., on_hit: true, visual: projectile.into(), @@ -295,6 +731,7 @@ impl ally::Host for Host { removable: None, payload: Shot::Ally { source: id, + deployment: w.unit(id)?.deployment.deploy_seq, attack_id: prepared.attack_id, payload, area, @@ -302,31 +739,149 @@ impl ally::Host for Host { }, )?; } - executor.finish(w, self, prepared, skill) + executor.finish(w, self, prepared, skill.as_deref_mut()) } else { - executor.perform_area(w, self, id, &selected.targets, payload, area, skill) + executor.perform_area( + w, + self, + id, + &selected.targets, + payload, + area, + skill.as_deref_mut(), + ) } })(); self.executor = Some(executor); + if let (Some(s), Some(sp)) = (skill, sp_type) { + s.spec.sp_type = sp; + } result } } impl attacks::Hooks for Host { + fn heal(&mut self, w: &mut World, source: Id, target: Id, amount: f64) -> Result { + let amount = self.kit_attack_heal(w, source, target, amount)?; + let mut r = self.buffs.take().ok_or("Missing healing buff context")?; + let result = self.support_heal( + w, + &mut r, + Some(source), + target, + amount, + health::HealOptions::default(), + ); + self.buffs = Some(r); + result + } + + fn prepare_attachment( + &mut self, + w: &mut World, + source: Id, + target: Option, + payload: &mut attacks::Direct, + ) -> Result<(), String> { + self.funnel_prepare(w, source, target, payload) + } + fn attachment_damage( + &mut self, + w: &mut World, + source: Id, + target: Id, + attack_id: u64, + payload: attacks::Direct, + ) -> Result { + self.funnel_damage(w, source, target, attack_id, payload) + } fn has_before_attack(&self) -> bool { - false + true } - fn before_attack(&mut self, _: &mut attacks::Context, _: &mut World) -> Result<(), String> { - Err("No before-attack handler installed".into()) + fn before_attack(&mut self, c: &mut attacks::Context, w: &mut World) -> Result<(), String> { + self.component_before(c, w)?; + self.advanced_before(c, w)?; + self.kit_before(w, c)?; + let proc = self + .roster + .as_ref() + .unwrap() + .entry(c.attacker)? + .definition + .attack_proc; + if let Some(proc) = proc { + let key = format!("skill:{}", c.attacker); + let active = w + .unit(c.attacker)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(key.as_str())); + if let Some(buff) = proc.roll(active, &mut self.rng) { + let mut r = self + .buffs + .take() + .ok_or("Missing before-attack buff context")?; + let result = r.add( + w, + self, + c.attacker, + buffs::Spec { + buff, + mods_present: true, + ..Default::default() + }, + ); + self.buffs = Some(r); + result?; + } + } + let Some(filter) = self.active_attack_filter(w, c.attacker)? else { + return Ok(()); + }; + let mut all_eligible = true; + for &target in &c.targets { + all_eligible &= filter(w, target)?; + } + if all_eligible { + return Ok(()); + } + let p = self + .roster + .as_ref() + .unwrap() + .entry(c.attacker)? + .definition + .combat + .profile; + let mut targets = self.filtered_targets(w, c.attacker, p, filter)?; + targeting::sort_enemies(w, self, c.attacker, &mut targets, p.priority)?; + targets.truncate(c.targets.len().max(1)); + c.targets = targets; + Ok(()) } fn engage(&mut self, _: Id, _: &mut World) -> Result<(), String> { Ok(()) } - fn damage(&mut self, w: &mut World, q: &mut hit::Request) -> Result { + fn damage( + &mut self, + w: &mut World, + q: &mut hit::Request, + skill: Option<&mut skills::Runtime>, + ) -> Result { + // Damage can synchronously restart the attacker's skill (Texas's first + // kill). Publish its actual state while resolving, then recover it even + // on failure; do not clone state or defer the kill until after removal. + if let Some(skill) = skill { + let id = skill.unit(); + let owned = skill.take_for_callback()?; + self.roster.as_mut().unwrap().restore_skill(id, owned)?; + let result = attacks::Hooks::damage(self, w, q, None); + *skill = self.roster.as_mut().unwrap().take_skill(id)?; + return result; + } let mut r = self.buffs.take().ok_or("Missing attack buff context")?; - let mut rng = self.rng.clone(); - let result = settlement::resolve(w, &mut r, &mut rng, self, q); + let result = self.resolve_hit(w, &mut r, q); self.buffs = Some(r); - self.rng = rng; result } fn radius_targets( @@ -364,11 +919,9 @@ impl attacks::Hooks for Host { w: &mut World, ) -> Result<(), String> { let mut r = self.buffs.take().ok_or("Missing attack status context")?; - let result = super::super::status::apply( + let result = self.apply_status( w, - self, &mut r, - Rect::NORMAL, target, "sluggish", super::super::status::Options { @@ -383,14 +936,50 @@ impl attacks::Hooks for Host { fn each_hit( &mut self, impact: attacks::Impact, - _: Option<&mut skills::Runtime>, + mut skill: Option<&mut skills::Runtime>, w: &mut World, ) -> Result<(), String> { - if impact.kind == attacks::VictimKind::Main { + self.advanced_impact(impact, skill.as_deref_mut(), w)?; + self.kit_impact(w, impact)?; + self.support_hit(impact, w)?; + self.component_hit(impact, w)?; + if impact.kind == attacks::VictimKind::Main && !impact.heal { if let Some(target) = impact .target .filter(|id| w.unit(*id).is_ok_and(|u| u.stats.alive)) { + let def = Arc::clone( + &self + .roster + .as_ref() + .unwrap() + .entry(impact.attacker)? + .definition, + ); + let effect = if impact.is_skill { + def.extra.skill_status.or(def.extra.normal_status) + } else { + def.extra.normal_status + }; + if let Some(effect) = effect.filter(|e| e.duration > 0.) { + let apply = effect.chance.map_or(true, |p| self.rng.chance(p)); + if apply { + let mut r = self.buffs.take().ok_or("Missing on-hit status context")?; + let result = self.apply_status( + w, + &mut r, + target, + effect.key, + super::super::status::Options { + duration: effect.duration, + source: Some(impact.attacker), + ..Default::default() + }, + ); + self.buffs = Some(r); + result?; + } + } let combat = self .roster .as_ref() @@ -412,18 +1001,52 @@ impl attacks::Hooks for Host { } fn after_hit( &mut self, - _: attacks::Impact, - _: Option<&mut skills::Runtime>, - _: &mut World, + impact: attacks::Impact, + skill: Option<&mut skills::Runtime>, + w: &mut World, ) -> Result<(), String> { + if impact.heal { + self.advanced_impact(impact, skill, w)?; + self.kit_impact(w, impact)?; + } Ok(()) } fn attack( &mut self, - _: &mut attacks::Context, - _: Option<&mut skills::Runtime>, - _: &mut World, + c: &mut attacks::Context, + mut skill: Option<&mut skills::Runtime>, + w: &mut World, ) -> Result<(), String> { + if let Some(skill) = skill.as_deref_mut() { + self.advanced_finish_skill(w, skill)?; + self.resume_kit_skill(w, skill)?; + self.support_flush_sp(w, skill)?; + } + self.support_attack(c, w)?; + self.advanced_attack(c, w)?; + self.kit_attack(w, c, skill.as_deref_mut())?; + if let Some(skill) = skill.as_deref_mut() { + self.advanced_finish_skill(w, skill)?; + self.resume_kit_skill(w, skill)?; + } + self.component_attack(c, w)?; + let mut buffs = self.buffs.take().ok_or("Missing equipment attack buffs")?; + let result = self.equipment_attack(w, &mut buffs, c); + self.buffs = Some(buffs); + result?; + let proc = self + .roster + .as_ref() + .unwrap() + .entry(c.attacker)? + .definition + .attack_proc; + if let Some(proc) = proc { + let mut r = self.buffs.take().ok_or("Missing attack cleanup context")?; + let result = r.remove(w, self, c.attacker, proc.key); + self.buffs = Some(r); + result?; + } Ok(()) } fn after_attack( @@ -437,30 +1060,106 @@ impl attacks::Hooks for Host { } impl projectiles::Hooks for Host { fn has_step(&self) -> bool { - false + self.roster.as_ref().is_some_and(|r| { + r.ids().iter().any(|&id| { + r.entry(id).is_ok_and(|e| { + matches!( + e.definition.extra.tactics, + super::super::content::operators::Tactics::Yu(_) + ) + }) + }) + }) } fn step( &mut self, - _: &mut projectiles::Projectile, - _: &mut projectiles::System, - _: &mut World, + p: &mut projectiles::Projectile, + flights: &mut projectiles::System, + w: &mut World, ) -> Result { - Err("No projectile step content installed".into()) + let mut cancelled = false; + self.flights = Some(std::mem::replace(flights, projectiles::System::new(1)?)); + let result = self.kit_event_with_buffs( + w, + &mut kits::dispatch::Event::ProjectileStep { + id: p.id, + source: p.source, + position: p.position, + speed: p.speed, + removable: p.removable, + cancelled: &mut cancelled, + }, + ); + *flights = self + .flights + .take() + .ok_or("Missing step projectile system")?; + result.map(|_| cancelled) } fn impact( &mut self, p: &mut projectiles::Projectile, target: Option, - _: &mut projectiles::System, + flights: &mut projectiles::System, w: &mut World, ) -> Result<(), String> { - match p.payload { + // Callbacks can launch through death, skill and chained-hit hooks. Keep + // the active system's capacity reservations and pins available to them. + self.flights = Some(std::mem::replace(flights, projectiles::System::new(1)?)); + let result = (|| match p.payload { + Shot::Turret(shot) => self.turret_impact(w, shot, target), + Shot::Seed { source, amount } => { + self.enemy_seed_impact(w, source, target, p.position, amount) + } + Shot::Bomb(shot) => self.enemy_bomb_impact(w, shot, target, p.position), + Shot::Skill(shot) => self.enemy_skill_impact(w, shot, target), + Shot::Cloud(shot) => self.enemy_cloud(w, shot, p.position), + Shot::Tactical(arrow) => { + let mut r = self + .buffs + .take() + .ok_or("Missing tactical projectile buffs")?; + let result = self.tactical_arrow(w, &mut r, arrow, target, p.position); + self.buffs = Some(r); + result + } + Shot::BoomerangReturn { source, deployment } => { + if Host::tac_up(w, source) && w.unit(source)?.deployment.deploy_seq == deployment { + let state = w.unit_mut(source)?.operator.tactical.caper_mut()?; + state.out = state.out.saturating_sub(1); + } + Ok(()) + } Shot::Ally { source, + deployment, attack_id, - payload, + mut payload, area, } => { + if let Some(target) = target { + let entry = self.roster.as_ref().unwrap().entry(source)?; + if let Some(lord) = entry.definition.extra.lord { + let home = w.unit(source)?.deployment.tile; + let melee_range = + targeting::absolute_range(&[[0, 0], [0, 1]], home, entry.direction, 0); + if !(payload.is_skill && lord.skill_full) + && w.unit(target)?.blocked_by() != Some(source) + && !super::super::body::in_range(w.unit(target)?, &melee_range) + { + payload.target_damage_mul *= lord.scale; + } + } + if let Some(scale) = &entry.definition.grid_scale { + payload.target_damage_mul *= scale.multiplier( + w, + source, + target, + entry.direction, + payload.is_skill, + )?; + } + } let mut executor = self .executor .take() @@ -469,6 +1168,12 @@ impl projectiles::Hooks for Host { w, self, source, target, attack_id, payload, area, p.position, None, ); self.executor = Some(executor); + if matches!( + self.tac_def(source)?.extra.tactics, + super::super::content::operators::Tactics::Caper(_) + ) { + self.caper_return(w, source, deployment, p.position)?; + } result } Shot::Enemy(delivery) => { @@ -479,6 +1184,11 @@ impl projectiles::Hooks for Host { self.rng = rng; result.map(|_| ()) } - } + })(); + *flights = self + .flights + .take() + .ok_or("Missing impact projectile system")?; + result } } diff --git a/crates/engine/src/battle/runtime/bands.rs b/crates/engine/src/battle/runtime/bands.rs new file mode 100644 index 0000000..7707b54 --- /dev/null +++ b/crates/engine/src/battle/runtime/bands.rs @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Selected core effects. Unsupported cores fail before battle state is changed. +use super::*; +use crate::battle::{deploy::Kind, stats::Numbers}; +#[derive(Default)] +pub(super) struct Bands { + plan: Option, +} +struct Plan { + id: String, + kind: Effect, + bb: Numbers, +} +enum Effect { + Bonds, + Weakness, + Life, + Preparation, +} +impl Plan { + fn compile(data: &Catalog, id: &str) -> Result { + let record = data + .table("bands") + .and_then(|v| v.get(id)) + .ok_or("Unknown core")?; + if !record["modeTypeList"] + .as_array() + .is_some_and(|a| a.iter().any(|v| v == "SINGLE")) + { + return Err("Core is unavailable in Desperation".into()); + } + if !matches!( + id, + "band_amiya" | "band_sarkazb" | "band_chen" | "band_sciurus" + ) { + return Err("Core is outside the supported scope".into()); + } + if id == "band_sciurus" { + if record["buffs"][0]["key"] != "first_buy_in_round_char_price_change" { + return Err("Unsupported Sciurus effects".into()); + } + return Ok(Self { + id: id.into(), + kind: Effect::Preparation, + bb: Numbers::new(), + }); + } + if id == "band_sarkazb" { + if record["buffs"].as_array().is_none_or(|a| !a.is_empty()) { + return Err("Unsupported Goliath effects".into()); + } + return Ok(Self { + id: id.into(), + kind: Effect::Life, + bb: Numbers::new(), + }); + } + let buffs = record["buffs"] + .as_array() + .filter(|a| a.len() == 1) + .ok_or("Unsupported core effects")?; + let b = &buffs[0]; + let kind = match b["bbStr"]["key"].as_str() { + Some("act1autochess_band2_buff") => Effect::Bonds, + Some("act1autochess_band19_buff") => Effect::Weakness, + _ => return Err("Unsupported core effects".into()), + }; + let bb = b["bb"] + .as_object() + .ok_or("Missing core parameters")? + .iter() + .map(|(k, v)| { + v.as_f64() + .filter(|n| n.is_finite()) + .map(|n| (k.clone(), n)) + .ok_or("Invalid core parameter".to_string()) + }) + .collect::>()?; + Ok(Self { + id: id.into(), + kind, + bb, + }) + } + fn n(&self, key: &str) -> f64 { + self.bb.get(key).copied().unwrap_or(0.) + } +} +impl Field { + pub(crate) fn validate_core(data: &Catalog, id: &str) -> Result<(), String> { + Plan::compile(data, id).map(|_| ()) + } + pub fn configure_core(&mut self, id: &str) -> Result<(), String> { + self.healthy()?; + if self.clock.started() || self.ticks() != 0 || self.core.host.bands.plan.is_some() { + return Err("Core requires an unstarted field and can be configured once".into()); + } + let plan = Plan::compile(&self.core.host.data, id)?; + self.core.host.bands.plan = Some(plan); + Ok(()) + } +} +impl Host { + pub(super) fn bands_install( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + start: bool, + ) -> Result<(), String> { + let Some(p) = &self.bands.plan else { + return Ok(()); + }; + let ops: Vec<_> = self + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .filter(|&id| { + w.unit(id) + .is_ok_and(|u| u.deployment.kind == Kind::Operator) + }) + .collect(); + let (ids, atk, hp) = match p.kind { + Effect::Bonds if !start => { + let count = self.growth.live.values().filter(|b| b.tier > 0).count() as f64; + let (mut atk, mut hp) = (0., 0.); + for i in 1..=9 { + let Some(threshold) = p.bb.get(&format!("value_{i}")) else { + break; + }; + if count >= *threshold { + atk = p.n(&format!("atk_{i}")); + hp = p.n(&format!("max_hp_{i}")); + } + } + (ops, atk, hp) + } + _ => return Ok(()), + }; + if atk <= 0. && hp <= 0. { + return Ok(()); + } + let key = format!("band:{}", p.id); + let mods: Numbers = [("atkPct".into(), atk), ("hpPct".into(), hp)].into(); + for id in ids { + self.equipment_stat(w, r, id, key.clone(), mods.clone())?; + } + Ok(()) + } + pub(super) fn core_weakness(&self, w: &World, source: Id, target: Id) -> bool { + self.bands + .plan + .as_ref() + .is_some_and(|p| matches!(p.kind, Effect::Weakness)) + && w.unit(source) + .is_ok_and(|u| u.deployment.kind == Kind::Operator) + && w.unit(target).is_ok_and(|u| u.side == health::Side::Enemy) + } +} diff --git a/crates/engine/src/battle/runtime/bonds.rs b/crates/engine/src/battle/runtime/bonds.rs new file mode 100644 index 0000000..836b183 --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds.rs @@ -0,0 +1,294 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Layered covenant effects; values come from the canonical content blackboards. +use super::*; +use crate::battle::{ + deploy::Kind, + skills, + stats::{Buff, Numbers}, +}; + +#[derive(Clone, Debug)] +pub struct BattleBond { + pub id: String, + pub tier: usize, + pub layers: f64, +} +#[derive(Clone)] +struct Bond { + id: String, + tier: usize, + bb: Numbers, +} +impl Bond { + fn n(&self, key: &str) -> f64 { + self.bb.get(key).copied().unwrap_or(0.) + } + fn value(&self, key: &str, default: f64) -> f64 { + self.bb.get(key).copied().unwrap_or(default) + } +} +mod aura; +mod damage; +mod defence; +mod deployment; +mod egir; +mod lifecycle; +mod passives; +mod raid; +mod revival; +mod yan; +#[derive(Default)] +pub(super) struct Runtime { + plans: Vec>, + ammo_used: u64, + reserved_map_chars: std::collections::BTreeSet, + egir: egir::Egir, + raid_next: f64, + pub(super) raid_revived: std::collections::BTreeMap, + indom: revival::Indom, + thorns_at: std::collections::BTreeMap, + skill_costs: std::collections::BTreeSet, + aura: Aura, + siracusa: deployment::Siracusa, + kazimierz: deployment::Kazimierz, +} +struct Aura { + pending: bool, + next: f64, +} +impl Default for Aura { + fn default() -> Self { + Self { + pending: false, + next: 0.25, + } + } +} +const ORDER: &[&str] = &[ + "yanShip", + "egirShip", + "sargonShip", + "victoriaShip", + "kjeragShip", + "lateranoShip", + "siracusaShip", + "kazimierzShip", + "preciShip", + "steadShip", + "indomShip", + "raidShip", + "deputShip", + "swiftShip", + "arcaneShip", + "skillfulShip", + "emptyShip", + "soloShip", + "suntShip", +]; +pub(super) const SIRACUSA_END: u64 = 0x424f4e440002; +pub(super) const SARGON_EXPIRE: u64 = 0x424f4e440001; +pub(super) fn core_bond(id: &str) -> bool { + matches!( + id, + "yanShip" + | "sargonShip" + | "victoriaShip" + | "kjeragShip" + | "lateranoShip" + | "egirShip" + | "siracusaShip" + | "kazimierzShip" + ) +} +impl Field { + pub fn configure_bonds(&mut self, bonds: &[BattleBond]) -> Result<(), String> { + self.healthy()?; + if self.clock.started() || self.ticks() != 0 { + return Err("Bonds require an unstarted field".into()); + } + if bonds.len() > 256 { + return Err("Bond passive capacity exceeded".into()); + } + let mut seen = std::collections::BTreeSet::new(); + let mut plans = Vec::new(); + for bond in bonds { + if bond.tier > 64 + || !bond.layers.is_finite() + || bond.layers < 0. + || !seen.insert(&bond.id) + { + return Err("Invalid or unsupported battle bond".into()); + } + let record = self + .core + .host + .data + .table("bonds") + .and_then(|t| t.get(&bond.id)) + .ok_or("Missing battle bond")?; + if bond.tier == 0 || !ORDER.contains(&bond.id.as_str()) { + continue; + } + let key = format!( + "{}autochess_bond_eff_{}", + if matches!(bond.id.as_str(), "siracusaShip" | "kazimierzShip") { + "act2" + } else { + "act1" + }, + bond.id.trim_end_matches("Ship") + ); + let bb = record["buffs"] + .as_array() + .and_then(|a| { + a.iter().find(|b| { + if core_bond(&bond.id) { + b["bbStr"]["key"] == key || b["key"] == key + } else { + b["key"] == "env_gbuff_new" + } + }) + }) + .map(|b| &b["bb"]) + .and_then(|b| b.as_object()) + .ok_or("Missing bond parameters")?; + let mut numbers = Numbers::new(); + for (k, v) in bb { + numbers.insert( + k.clone(), + v.as_f64() + .filter(|n| n.is_finite()) + .ok_or("Invalid bond parameter")?, + ); + } + plans.push(Arc::new(Bond { + id: bond.id.clone(), + tier: bond.tier, + bb: numbers, + })); + } + plans.sort_by_key(|p| ORDER.iter().position(|id| *id == p.id).unwrap()); + let mut runtime = Runtime { + reserved_map_chars: self.core.host.bonds.reserved_map_chars.clone(), + plans, + ..Default::default() + }; + if let Some(p) = runtime + .plans + .iter() + .find(|p| p.id == "siracusaShip" && p.tier >= 2) + { + runtime.siracusa.constant = deployment::prd_constant(p.n("prob"))?; + } + if let Some(p) = runtime.plans.iter().find(|p| { + p.id == "kazimierzShip" + && p.tier >= 2 + && p.n("damage_interval") > 0. + && p.n("damage_atk_scale") > 0. + }) { + runtime.kazimierz.next = Some(p.n("damage_interval")); + } + let mut growth = super::growth::Growth::default(); + growth.live = bonds.iter().map(|b| (b.id.clone(), b.clone())).collect(); + growth.enabled = self.core.boss.is_none(); + self.core.host.growth = growth; + self.core.host.bonds = runtime; + Ok(()) + } +} +impl Host { + pub(super) fn movement_bonds_quiet(&self) -> bool { + !self.bonds.aura.pending + } + pub(super) fn movement_bond_deadline(&self) -> f64 { + let mut at = self.bonds.kazimierz.next.unwrap_or(f64::INFINITY); + if self.bonds.plans.iter().any(|p| p.id == "skillfulShip") { + at = at.min(self.bonds.aura.next); + } + if self.bonds.plans.iter().any(|p| p.id == "raidShip") { + at = at.min(self.bonds.raid_next.max(0.25)); + } + at + } + fn bond_layers(&self, id: &str) -> f64 { + self.growth.live.get(id).map_or(0., |b| b.layers) + } + pub(super) fn bond_elite(&self, id: Id) -> bool { + self.roster + .as_ref() + .and_then(|r| r.entry(id).ok()) + .is_some_and(|e| e.definition.key.ends_with("_b")) + } +} + +#[derive(Clone, Copy)] +pub(in crate::battle::runtime) enum Periodic { + Kazimierz, + Aura, + Raid, +} +impl Host { + pub(in crate::battle::runtime) fn bond_deadlines(&self, w: &World) -> Vec<(f64, Periodic)> { + let mut out = Vec::with_capacity(2); + if let Some(at) = self.bonds.kazimierz.next.filter(|at| w.time >= *at) { + out.push((at, Periodic::Kazimierz)); + } + if self.bonds.plans.iter().any(|p| p.id == "skillfulShip") && w.time >= self.bonds.aura.next + { + out.push((self.bonds.aura.next, Periodic::Aura)); + } + if self.bonds.plans.iter().any(|p| p.id == "raidShip") + && w.time >= self.bonds.raid_next.max(0.25) + { + out.push((self.bonds.raid_next.max(0.25), Periodic::Raid)); + } + out + } + pub(in crate::battle::runtime) fn bond_periodic( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + event: Periodic, + ) -> Result<(), String> { + match event { + Periodic::Raid => { + self.bonds.raid_next = self.bonds.raid_next.max(0.25) + 0.25; + self.raid_poll(w, r) + } + Periodic::Kazimierz => self.bond_kazimierz_pulse(w, r), + Periodic::Aura => { + self.bonds.aura.next = w.time + 0.25; + self.bonds_aura(w, r) + } + } + } + fn bond_ops(&self, w: &World) -> Vec { + self.roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .filter(|&id| { + w.unit(id) + .is_ok_and(|u| u.deployment.kind == Kind::Operator) + }) + .collect() + } +} + +impl Runtime { + pub(super) fn for_stage(stage: &Value) -> Self { + let mut state = Self::default(); + for record in stage["mapChars"].as_array().into_iter().flatten() { + if let (Some(r), Some(c)) = (record["pos"][0].as_u64(), record["pos"][1].as_u64()) { + if r < crate::battle::grid::ROWS as u64 && c < COLS as u64 { + state + .reserved_map_chars + .insert(r as usize * COLS + c as usize); + } + } + } + state + } +} diff --git a/crates/engine/src/battle/runtime/bonds/aura.rs b/crates/engine/src/battle/runtime/bonds/aura.rs new file mode 100644 index 0000000..6b10aa5 --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds/aura.rs @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +impl Host { + pub(in crate::battle::runtime) fn bonds_aura( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let Some(p) = self.bonds.plans.iter().find(|p| p.id == "skillfulShip") else { + return Ok(()); + }; + let l = self.bond_layers(&p.id); + let wide = l >= p.value("power_bond_stack_cnt", f64::INFINITY); + let aspd = p.n("base_attack_speed") + p.n("attack_speed_per_stack") * l; + let ids = self.bond_ops(w); + let mut next = std::collections::BTreeSet::new(); + for &id in &ids { + if !self.equipment_member(id, "skillfulShip") { + continue; + } + let live = Self::tac_up(w, id); + let unit = w.unit(id)?; + if !live + && !(unit.deployment.remove_reason.as_deref() == Some("killed") + && crate::battle::deploy::Deployment::is_down(w, id)?) + { + continue; + } + let at = if live { + unit.deployment.tile + } else { + crate::battle::deploy::Deployment::rest_tile(w, id)? + }; + if live { + next.insert(id); + } + for &target in &ids { + if !Self::tac_up(w, target) || w.unit(target)?.deployment.kind != Kind::Operator { + continue; + } + let tile = w.unit(target)?.deployment.tile; + let dr = (tile[0] - at[0]).abs(); + let dc = (tile[1] - at[1]).abs(); + if dr.max(dc) == 1 && (wide || dr + dc == 1) { + next.insert(target); + } + } + } + for id in ids { + if !next.contains(&id) { + r.remove(w, self, id, "bond:skillfulShip")?; + continue; + } + let stats = &mut w.unit_mut(id)?.stats; + if let Some(b) = stats + .buffs_mut() + .iter_mut() + .find(|b| b.key.as_deref() == Some("bond:skillfulShip")) + { + b.mods.insert("aspd".into(), aspd); + stats.mark_dirty(); + } else { + let buff = Buff { + key: Some("bond:skillfulShip".into()), + mods: [("aspd".into(), aspd)].into(), + ..Default::default() + }; + r.add( + w, + self, + id, + buffs::Spec { + buff, + mods_present: true, + ..Default::default() + }, + )?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn bonds_flush( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + if self.bonds.aura.pending { + self.bonds.aura.pending = false; + self.bonds_aura(w, r)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/bonds/damage.rs b/crates/engine/src/battle/runtime/bonds/damage.rs new file mode 100644 index 0000000..db530de --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds/damage.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +impl Host { + pub(in crate::battle::runtime) fn bonds_landed( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + ) -> Result<(), String> { + self.bonds_core_landed(w, r, q)?; + self.bond_thorns(w, r, q)?; + let Some(source) = q.hit.source else { + return Ok(()); + }; + let Some(p) = self.bonds.plans.iter().find(|p| p.id == "arcaneShip") else { + return Ok(()); + }; + if q.hit.damage_type != crate::battle::damage::DamageType::Arts + || w.unit(q.hit.target)?.side != health::Side::Enemy + || !w.unit(q.hit.target)?.stats.alive + || w.unit(source)?.deployment.kind != Kind::Operator + || !self.equipment_member(source, &p.id) + { + return Ok(()); + } + let l = self.bond_layers(&p.id); + let mut value = + (p.value("base_damage_scale", 1.) + p.n("damage_scale_per_stack") * l).max(0.); + let target = w.unit_mut(q.hit.target)?; + let ratio = target.stats.hp / target.stats.stats().map_err(str::to_string)?.n("maxHp"); + if p.tier >= 2 && ratio < p.n("hp_ratio") { + value = (value * p.value("power_weak_scale", 1.)).max(0.); + } + crate::battle::valued::apply( + w, + self, + r, + q.hit.target, + crate::battle::valued::Request { + key: "bond:arcaneShip", + kind: crate::battle::valued::Kind::Custom(|v| [("artsTakenMul".into(), v)].into()), + plain: true, + duration: p.value("weak_duration", 3.), + value, + source: Some(source), + stack_as: None, + }, + )?; + Ok(()) + } + pub(in crate::battle::runtime) fn bonds_hit( + &self, + w: &mut World, + q: &mut hit::Request, + ) -> Result<(), String> { + let Some(source) = q.hit.source else { + return Ok(()); + }; + let Some(p) = self.bonds.plans.iter().find(|p| p.id == "kjeragShip") else { + return Ok(()); + }; + if !self.equipment_member(source, &p.id) + || w.unit(q.hit.target)?.side != health::Side::Enemy + { + return Ok(()); + } + let stats = w + .unit_mut(q.hit.target)? + .stats + .stats() + .map_err(str::to_string)?; + if stats.flags.contains("cold") || stats.flags.contains("freeze") { + let base = p.value("base_damage_scale", 1.); + let target = p.value("base_ex_damage_scale", base) + + p.n("ex_damage_scale_per_stack") * self.bond_layers(&p.id); + if base > 0. && target > 0. { + q.damage.mul *= target / base; + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/bonds/defence.rs b/crates/engine/src/battle/runtime/bonds/defence.rs new file mode 100644 index 0000000..f4d9b22 --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds/defence.rs @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Steadfast: post-mitigation sharing and per-member retaliation cooldowns. +use super::*; +use crate::battle::{damage::DamageType, status}; + +const SHARE: &str = "bond:stead:share"; +const THORN: &str = "bond:stead:thorn"; + +impl Host { + pub(in crate::battle::runtime) fn bonds_has_share(&self) -> bool { + self.bonds + .plans + .iter() + .any(|p| p.id == "steadShip" && p.tier >= 2) + } + + pub(in crate::battle::runtime) fn bond_share( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + amount: &mut f64, + ) -> Result<(), String> { + let target = w.unit(q.hit.target)?; + if target.side != health::Side::Ally + || target.deployment.kind != Kind::Operator + || q.hit.hp_loss + || q.tags.iter().any(|t| t == SHARE) + || self.equipment_member(q.hit.target, "steadShip") + { + return Ok(()); + } + let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "steadShip" && p.tier >= 2) + else { + return Ok(()); + }; + let ratio = p.n("damage_resistance").clamp(0., 1.); + let members: Vec<_> = self + .bond_ops(w) + .into_iter() + .filter(|&id| Self::tac_up(w, id) && self.equipment_member(id, "steadShip")) + .collect(); + if members.is_empty() || ratio <= 0. { + return Ok(()); + } + let shared = *amount * ratio; + *amount -= shared; + for id in &members { + let mut extra = deployment::damage(*id, *id, shared / members.len() as f64, SHARE); + extra.tags.extend(q.tags.iter().cloned()); + extra.hit.source = None; + extra.hit.credit = None; + extra.calculation = hit::Calculation::Resolved; + self.enemy_damage(w, r, &mut extra)?; + } + Ok(()) + } + + pub(super) fn bond_thorns( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + ) -> Result<(), String> { + let id = q.hit.target; + let target = w.unit(id)?; + if target.side != health::Side::Ally + || target.deployment.kind != Kind::Operator + || q.hit.hp_loss + || q.tags.iter().any(|t| t == SHARE || t == THORN) + || !self.equipment_member(id, "steadShip") + { + return Ok(()); + } + let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "steadShip" && p.tier >= 2) + .cloned() + else { + return Ok(()); + }; + if !p.bb.contains_key("base_damage_value") && !p.bb.contains_key("damage_value_per_stack") { + return Ok(()); + } + let last = self + .bonds + .thorns_at + .get(&id) + .copied() + .unwrap_or(f64::NEG_INFINITY); + if w.time - last < p.n("cd_duration") - 1e-9 { + return Ok(()); + } + // Sourceless damage spends the opportunity, even though there is nobody to hit. + self.bonds.thorns_at.insert(id, w.time); + let Some(source) = q.hit.source.filter(|&source| { + w.unit(source) + .is_ok_and(|u| u.side == health::Side::Enemy && u.stats.alive) + }) else { + return Ok(()); + }; + let amount = + p.n("base_damage_value") + p.n("damage_value_per_stack") * self.bond_layers(&p.id); + let mut extra = deployment::damage(id, source, amount, THORN); + extra.hit.source = None; + extra.hit.damage_type = DamageType::Arts; + self.enemy_damage(w, r, &mut extra)?; + if w.unit(source)?.stats.alive && p.bb.contains_key("damage_scale") { + self.apply_status( + w, + r, + source, + "fragile", + status::Options { + duration: p.value("weak[limit]", 5.), + value: Some(p.value("damage_scale", 1.) - 1.), + source: Some(id), + ..Default::default() + }, + )?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/bonds/deployment.rs b/crates/engine/src/battle/runtime/bonds/deployment.rs new file mode 100644 index 0000000..eac46d7 --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds/deployment.rs @@ -0,0 +1,343 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Deployment-driven core covenants: Siracusa and Kazimierz. +use super::*; +use crate::battle::{ + damage::{Damage, DamageType}, + injury::DodgeMode, +}; +use std::collections::BTreeMap; +#[derive(Default)] +pub(super) struct Siracusa { + pub constant: f64, + attempts: u64, + ended: BTreeMap, +} +#[derive(Default)] +pub(super) struct Kazimierz { + deploys: u64, + pub next: Option, +} + +// Keep the reference's summation order; a probability outside the supported +// convergence bound is rejected before changing the field configuration. +pub(super) fn prd_constant(p: f64) -> Result { + if p <= 0. { + return Ok(0.); + } + if p >= 1. { + return Ok(1.); + } + let rate = |c: f64| -> Result { + let mut expected = 0.; + let mut pending = 1.; + let limit = (1. / c).ceil() + 1.; + for n in 1..=65536 { + if n as f64 > limit || pending <= 0. { + return Ok(if expected > 0. { 1. / expected } else { 1. }); + } + let chance = (n as f64 * c).min(1.); + expected += n as f64 * pending * chance; + pending *= 1. - chance; + } + Err("Covenant probability exceeds PRD convergence bound".into()) + }; + let (mut lo, mut hi) = (0., p); + for _ in 0..50 { + let mid = (lo + hi) / 2.; + if rate(mid)? < p { + lo = mid; + } else { + hi = mid; + } + } + Ok((lo + hi) / 2.) +} +pub(super) fn damage(source: Id, target: Id, amount: f64, key: &str) -> hit::Request { + let mut q = hit::Request::new( + health::Hit { + source: Some(source), + credit: Some(source), + target, + damage_type: DamageType::True, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + penetration: Default::default(), + resolved: false, + }, + ); + q.tags.push(key.into()); + q.dodge_mode = DodgeMode::Ignore; + q +} +impl Host { + pub(in crate::battle::runtime) fn bond_siracusa_end(&mut self, id: Id, time: f64) { + self.bonds.siracusa.ended.insert(id, time); + } + pub(super) fn bonds_deploy( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if w.unit(id)?.deployment.kind != Kind::Operator { + return Ok(()); + } + if let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "siracusaShip") + .cloned() + .filter(|p| self.equipment_member(id, &p.id)) + { + let l = self.bond_layers(&p.id); + let duration = p.n("base_duration") + p.n("duration_per_stack") * l; + if duration > 0. { + let mut buff = Buff { + key: Some("bond:siracusa".into()), + mods: [( + "aspd".into(), + p.n("base_attack_speed") + p.n("attack_speed_per_stack") * l, + )] + .into(), + ..Default::default() + }; + buff.runtime.duration = duration; + r.add( + w, + self, + id, + buffs::Spec { + buff, + mods_present: true, + ..Default::default() + }, + )?; + if p.tier >= 2 { + self.bonds.siracusa.ended.remove(&id); + let mut buff = Buff { + key: Some("bond:siracusa:stealth".into()), + flags: ["stealth".into()].into(), + ..Default::default() + }; + buff.runtime.duration = duration; + buff.runtime.status = Some("stealth".into()); + buff.runtime.on_expire = Some(SIRACUSA_END); + buff.runtime.on_remove = Some(SIRACUSA_END); + r.add( + w, + self, + id, + buffs::Spec { + buff, + flags_present: true, + ..Default::default() + }, + )?; + } + } + } + if self.bonds.plans.iter().any(|p| p.id == "kazimierzShip") { + self.bonds.kazimierz.deploys = self + .bonds + .kazimierz + .deploys + .checked_add(1) + .ok_or("Covenant deployment counter exhausted")?; + self.bond_kazimierz_refresh(w, r)?; + } + Ok(()) + } + pub(super) fn bond_kazimierz_refresh( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "kazimierzShip") + .cloned() + else { + return Ok(()); + }; + let cap = p.n("base_max_atk_when_born") + + p.n("max_atk_when_born_per_stack") * self.bond_layers(&p.id); + let bonus = cap + .min(self.bonds.kazimierz.deploys as f64 * p.n("atk_when_born")) + .max(0.); + if bonus <= 0. { + return Ok(()); + } + for id in self.bond_ops(w) { + if self.equipment_member(id, &p.id) { + self.equipment_stat( + w, + r, + id, + "bond:kazimierz".into(), + [("atkPct".into(), bonus)].into(), + )?; + } + } + Ok(()) + } + pub(super) fn bond_kazimierz_pulse( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "kazimierzShip") + .cloned() + else { + return Ok(()); + }; + self.bonds.kazimierz.next = Some(w.time + p.n("damage_interval")); + for id in self.bond_ops(w) { + if !Self::tac_up(w, id) + || !self.equipment_member(id, &p.id) + || w.unit(id)?.blocking().is_empty() + { + continue; + } + let targets = self.tac_radius(w, w.unit(id)?.position, p.n("range_radius"))?; + let amount = p.n("damage_atk_scale") * Self::tac_stat(w, id, "atk")?; + for target in targets { + if !w.unit(target)?.stats.alive { + continue; + } + let mut q = damage(id, target, amount, "bond:kazimierz"); + q.is_splash = true; + self.enemy_damage(w, r, &mut q)?; + if w.unit(target)?.stats.alive && p.n("stun") > 0. { + self.apply_status( + w, + r, + target, + "stun", + crate::battle::status::Options { + duration: p.n("stun"), + source: Some(id), + ..Default::default() + }, + )?; + } + } + } + Ok(()) + } + pub(super) fn bonds_core_landed( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + ) -> Result<(), String> { + let Some(source) = q.hit.source else { + return Ok(()); + }; + let target = q.hit.target; + if w.unit(target)?.side != health::Side::Enemy || !w.unit(target)?.stats.alive { + return Ok(()); + } + if let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "siracusaShip" && p.tier >= 2) + .cloned() + .filter(|p| self.equipment_member(source, &p.id)) + { + let ordinary = !q.is_splash + && !q.hit.hp_loss + && q.hit.damage_type != DamageType::Elemental + && !q.tags.iter().any(|s| { + matches!( + s.as_str(), + "dot" | "periodic" | "addition" | "item" | "hpLoss" + ) || s.starts_with("bond:") + }); + let hidden = w + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("stealth") + || w.time + <= self + .bonds + .siracusa + .ended + .get(&source) + .copied() + .unwrap_or(f64::NEG_INFINITY) + + p.n("end_duration") + + 1e-9; + if ordinary && hidden && self.bonds.siracusa.constant > 0. { + let state = &mut self.bonds.siracusa; + state.attempts = state.attempts.saturating_add(1); + if self.rng.next_f64() < (state.constant * state.attempts as f64).min(1.) { + state.attempts = 0; + let amount = + p.n("base_damage") + p.n("damage_per_stack") * self.bond_layers(&p.id); + self.enemy_damage(w, r, &mut damage(source, target, amount, "bond:siracusa"))?; + if w.unit(target)?.stats.alive && p.n("fear") > 0. { + self.apply_status( + w, + r, + target, + "fear", + crate::battle::status::Options { + duration: p.n("fear"), + source: Some(source), + ..Default::default() + }, + )?; + } + } + } + } + if !w.unit(target)?.stats.alive { + return Ok(()); + } + if let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "kazimierzShip" && p.tier >= 2) + .cloned() + .filter(|p| self.equipment_member(source, &p.id)) + { + if !q.hit.hp_loss + && q.attack_type == hit::AttackType::Normal + && q.hit.damage_type != DamageType::Elemental + && !q.tags.iter().any(|s| s == "bond:kazimierz") + && w.unit(source)?.blocking().is_empty() + && p.n("pure_atk_scale") > 0. + { + let mut extra = damage( + source, + target, + p.n("pure_atk_scale") * Self::tac_stat(w, source, "atk")?, + "bond:kazimierz", + ); + extra.hit.source = None; + extra.calculation = hit::Calculation::Precomputed; + extra.attack_type = hit::AttackType::Addition; + self.enemy_damage(w, r, &mut extra)?; + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/bonds/egir.rs b/crates/engine/src/battle/runtime/bonds/egir.rs new file mode 100644 index 0000000..93f16f2 --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds/egir.rs @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +#[derive(Default)] +pub(super) struct Egir { + opening: bool, + seen: BTreeSet, + batch: Vec, + used: usize, +} +impl Host { + pub(in crate::battle::runtime) fn egir_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "egirShip" && p.tier >= 2) + .cloned() + else { + return Ok(()); + }; + let u = w.unit(id)?; + if u.stats.alive + || u.deployment.remove_reason.as_deref() != Some("killed") + || !self.equipment_member(id, "egirShip") + || !self.bonds.egir.seen.insert(id) + { + return Ok(()); + } + if self.bonds.egir.opening { + self.bonds.egir.batch.push(id); + return Ok(()); + } + self.egir_revive(w, r, id, &p) + } + fn egir_revive( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + p: &Bond, + ) -> Result<(), String> { + if self.bonds.egir.used >= p.n("max_free_respawn_cnt").max(0.) as usize + || w.unit(id)?.stats.alive + || w.unit(id)?.removed + { + return Ok(()); + } + if (kits::dispatch::Context { + host: self, + world: w, + buffs: r, + unit: id, + }) + .redeploy_free(id)? + { + self.bonds.egir.used += 1; + } + Ok(()) + } + pub(in crate::battle::runtime) fn egir_start( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "egirShip") + .cloned() + else { + return Ok(()); + }; + let ops: Vec<_> = self + .bond_ops(w) + .into_iter() + .filter(|&id| Self::tac_up(w, id)) + .collect(); + let mut members: Vec<_> = ops + .iter() + .copied() + .filter(|&id| self.equipment_member(id, "egirShip")) + .collect(); + members.sort_by_key(|&id| { + let t = w.unit(id).unwrap().deployment.tile; + (t[1], -t[0], id) + }); + let mut marked: BTreeMap> = BTreeMap::new(); + let mut marks = Vec::new(); + for m in members { + let mut seen = BTreeSet::from([m]); + let mut queue = VecDeque::from([m]); + let mut mine = Vec::new(); + while let Some(x) = queue.pop_front() { + let tile = w.unit(x)?.deployment.tile; + let d = self.roster.as_ref().unwrap().entry(x)?.direction.vector(); + let front = [tile[0] + d[0], tile[1] + d[1]]; + for &t in &ops { + if w.unit(t)?.deployment.tile != front + || seen.contains(&t) + || marked.get(&t).is_some_and(|v| v.contains(&m)) + { + continue; + } + seen.insert(t); + mine.push(t); + if self.equipment_member(t, "egirShip") { + queue.push_back(t); + } + } + } + let mut atk = 0.; + let mut block = 0.; + for &t in &mine { + atk += w.unit(t)?.stats.base_number("atk"); + block += w.unit(t)?.stats.base_number("blockCnt"); + marks.push((m, t, w.unit(t)?.deployment.deploy_seq)); + } + marked.insert(m, mine); + let mut mods = Numbers::new(); + if atk > 0. { + mods.insert("atkFinal".into(), atk); + } + if block > 0. { + mods.insert("blockCnt".into(), block); + } + if !mods.is_empty() { + self.equipment_stat(w, r, m, "bond:egir:devour".into(), mods)?; + } + } + self.bonds.egir.opening = true; + let result = (|| { + let mut layered = BTreeSet::new(); + for (m, t, seq) in marks { + if !w.unit(t)?.stats.alive || w.unit(t)?.deployment.deploy_seq != seq { + continue; + } + if p.n("damage_value") > 0. { + let mut q = deployment::damage(t, t, p.n("damage_value"), "bond:egir:devour"); + q.hit.credit = Some(m); + q.hit.hp_loss = true; + q.hit.damage_type = crate::battle::damage::DamageType::Physical; + self.enemy_damage(w, r, &mut q)?; + } + if layered.insert(t) { + let key = &self.roster.as_ref().unwrap().entry(t)?.definition.key; + let tier = self + .data + .table("chess") + .and_then(|v| v.get(key)) + .and_then(|v| v["tier"].as_f64()) + .unwrap_or(0.); + self.growth_bond_gain(w, m, "egirShip", tier)?; + } + } + Ok::<_, String>(()) + })(); + self.bonds.egir.opening = false; + result?; + let mut batch = std::mem::take(&mut self.bonds.egir.batch); + batch.sort_by_key(|&id| { + let t = w.unit(id).unwrap().deployment.tile; + (t[1], t[0], id) + }); + for id in batch { + self.egir_revive(w, r, id, &p)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/bonds/lifecycle.rs b/crates/engine/src/battle/runtime/bonds/lifecycle.rs new file mode 100644 index 0000000..f811548 --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds/lifecycle.rs @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +impl Host { + pub(in crate::battle::runtime) fn bond_sargon_sync( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "sargonShip" && p.tier >= 2) + else { + return Ok(()); + }; + let atk = p.n("base_atk"); + let n = w + .unit(id)? + .stats + .buffs() + .iter() + .filter(|b| b.key.as_deref() == Some("bond:sargon")) + .count(); + if n > 0 && w.unit(id)?.stats.alive { + let buff = Buff { + key: Some("bond:sargon:atk".into()), + mods: [("atkPct".into(), atk * n as f64)].into(), + ..Default::default() + }; + r.add( + w, + self, + id, + buffs::Spec { + buff, + mods_present: true, + ..Default::default() + }, + )?; + } else { + r.remove(w, self, id, "bond:sargon:atk")?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn bonds_skill( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + event: skills::Event, + c: &skills::Context, + s: &mut skills::Runtime, + ) -> Result<(), String> { + if !matches!( + event, + skills::Event::Deploy + | skills::Event::End + | skills::Event::SkillStart + | skills::Event::SkillEnd + | skills::Event::AmmoUsed + ) { + return Ok(()); + } + let id = s.unit(); + if event == skills::Event::Deploy { + self.bonds.indom.free.remove(&id); + self.bonds_deploy(w, r, id)?; + self.bonds_aura(w, r)?; + } + if event == skills::Event::End { + self.bonds.aura.pending = true; + } + for p in self.bonds.plans.clone() { + let l = self.bond_layers(&p.id); + let member = self.equipment_member(id, &p.id); + match p.id.as_str() { + "soloShip" if member && event == skills::Event::Deploy => { + if p.n("sp") > 0. { + self.with_kit_buffs(w, r, |h, w| { + s.gain(w, h, p.n("sp"), "init", false, false) + })?; + } + } + "suntShip" if p.tier >= 2 && event == skills::Event::Deploy => { + let owner = w.unit(id)?.summoner.unwrap_or(id); + // Each skill runtime receives the multiplier once, including elite summons. + if self.bond_elite(owner) + && !s.bank.no_skill + && !self.bonds.skill_costs.contains(&id) + { + s.bank.set_multiplier( + w, + s.bank.cost_multiplier() * p.value("sp_ratio", 1.), + )?; + self.bonds.skill_costs.insert(id); + } + } + "swiftShip" + if event == skills::Event::SkillEnd + && c.reason != "death" + && w.unit(id)?.stats.alive + && w.unit(id)?.deployment.kind == Kind::Operator => + { + let prob = (p.n("base_prob") + p.n("prob_per_stack") * l).clamp(0., 1.); + for (roll, amount) in [ + (member, p.n("normal_sp")), + ( + l >= p.value("power_bond_stack_cnt", f64::INFINITY), + p.n("power_sp"), + ), + ] { + if roll && self.rng.next_f64() < prob { + self.with_kit_buffs(w, r, |h, w| { + s.gain(w, h, amount, "bond", false, false) + })?; + } + } + } + "sargonShip" if member && event == skills::Event::SkillStart => { + let dur = p.n("base_time") + p.n("time_per_stack") * l; + if dur <= 0. { + continue; + } + for target in self.roster.as_ref().unwrap().ids().to_vec() { + if !Self::tac_up(w, target) || !self.equipment_member(target, &p.id) { + continue; + } + let mut buff = Buff { + key: Some("bond:sargon".into()), + mods: [("aspd".into(), p.n("base_attack_speed"))].into(), + ..Default::default() + }; + buff.runtime.duration = dur; + buff.runtime.refresh = buffs::Refresh::Independent; + buff.runtime.max_stacks = + p.value("max_buff_stack_cnt", 25.).clamp(1., 4096.) as u32; + buff.runtime.on_remove = Some(SARGON_EXPIRE); + buff.runtime.on_expire = Some(SARGON_EXPIRE); + r.add( + w, + self, + target, + buffs::Spec { + buff, + mods_present: true, + ..Default::default() + }, + )?; + self.bond_sargon_sync(w, r, target)?; + } + } + "lateranoShip" + if member + && event == skills::Event::SkillStart + && s.bank.kind == crate::battle::sp::Kind::Ammo + && s.ammo_left > 0. => + { + let ammo = (s.ammo_left + * (1. + p.n("base_ammo_percent") + p.n("ammo_percent_per_stack") * l) + + 1e-9) + .floor(); + if ammo.is_finite() && ammo > s.ammo_left { + s.ammo_left = ammo; + } + } + "lateranoShip" + if member + && event == skills::Event::AmmoUsed + && p.tier >= 2 + && p.n("atk_per_consume") > 0. => + { + let cap = p.value("max_atk_for_consume", f64::INFINITY); + if self.bonds.ammo_used as f64 * p.n("atk_per_consume") >= cap { + continue; + } + self.bonds.ammo_used = self.bonds.ammo_used.saturating_add(1); + let bonus = (self.bonds.ammo_used as f64 * p.n("atk_per_consume")).min(cap); + for target in self.roster.as_ref().unwrap().ids().to_vec() { + if self.equipment_member(target, &p.id) { + self.equipment_stat( + w, + r, + target, + "bond:laterano:ammo".into(), + [("atkPct".into(), bonus)].into(), + )?; + } + } + } + _ => (), + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/bonds/passives.rs b/crates/engine/src/battle/runtime/bonds/passives.rs new file mode 100644 index 0000000..42c312d --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds/passives.rs @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +impl Host { + pub(in crate::battle::runtime) fn bonds_install( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + if self.bonds.plans.is_empty() { + return Ok(()); + } + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + for p in self.bonds.plans.clone() { + let l = self.bond_layers(&p.id); + if p.id == "kjeragShip" && p.tier >= 2 && self.devices.config.cold_wind.is_none() { + let interval = p.n("bond_eff_kjerag[storm].interval"); + let duration = p.n("bond_eff_kjerag[storm].base_time") + + p.n("bond_eff_kjerag[storm].time_per_stack") * l; + if interval > 0. && duration.is_finite() && duration >= 0. { + self.devices.config.cold_wind = Some(ColdWind { + interval, + duration, + first: None, + }); + self.devices.cold_due = Some(interval); + self.growth.follow_wind = true; + } + } + for &id in &ids { + if w.unit(id)?.deployment.kind != Kind::Operator { + continue; + } + let member = self.equipment_member(id, &p.id); + let elite = self.bond_elite(id); + let mut mods = Numbers::new(); + let mut key = format!("bond:{}", p.id); + match p.id.as_str() { + "preciShip" => { + let def = &self.roster.as_ref().unwrap().entry(id)?.definition; + let ranged = self + .data + .table("chess") + .and_then(|t| t.get(&def.key)) + .is_some_and(|c| c["position"] == "RANGED"); + if !member && !(p.tier >= 2 && ranged) { + continue; + } + mods.insert("atkPct".into(), p.n("base_atk") + p.n("atk_per_stack") * l); + if p.tier >= 2 { + mods.insert("defIgnorePct".into(), p.n("power_def_penetrate")); + mods.insert("resIgnorePct".into(), p.n("power_magic_resist_penetrate")); + } + } + "raidShip" => { + if member + && w.unit(id)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some("bond:raidShip")) + { + self.raid_buff(w, r, id, &p)?; + } + if l < p.value("power_bond_stack_cnt", f64::INFINITY) { + continue; + } + key.push_str(":aspd"); + mods.insert("aspd".into(), p.n("power_attack_speed")); + for (param, stat) in [ + ("power_cost_scale", "costMul"), + ("power_respawn_time", "redeployMul"), + ] { + if let Some(value) = p.bb.get(param) { + mods.insert(stat.into(), *value); + } + } + } + "yanShip" => { + if !member { + continue; + } + key = "bond:yan".into(); + mods.insert("atkPct".into(), p.n("base_atk") + p.n("atk_per_stack") * l); + } + "egirShip" => { + if !member { + continue; + } + key = "bond:egir".into(); + mods.insert( + "hpPct".into(), + p.n("base_max_hp") + p.n("max_hp_per_stack") * l, + ); + } + "steadShip" => { + mods.insert( + "hpPct".into(), + p.n("base_max_hp") + p.n("max_hp_per_stack") * l, + ); + } + "deputShip" => { + mods.insert("defPct".into(), p.n("base_def") + p.n("def_per_stack") * l); + mods.insert("redeployMul".into(), (1. + p.n("respawn_time")).max(0.)); + } + "victoriaShip" => { + if !member { + continue; + } + let items = &self.equipment.units[&id].items; + if items.is_empty() { + continue; + } + let atk = items + .iter() + .map(|item| { + p.n("atk_normal_equip") + + if item.ends_with("_b") { + p.n("atk_golden_equip") + } else { + 0. + } + }) + .sum::(); + mods.insert( + "dmgDealtMul".into(), + p.value("base_damage_scale", 1.) + p.n("damage_scale_per_stack") * l, + ); + key = "bond:victoria".into(); + self.equipment_stat(w, r, id, key.clone(), mods.clone())?; + if p.tier < 2 { + continue; + } + key = "bond:victoria:atk".into(); + mods.clear(); + mods.insert("atkPct".into(), p.value("power_atk", atk)); + } + "kjeragShip" => { + if !member { + continue; + } + key = "bond:kjerag".into(); + mods.insert("dmgDealtMul".into(), p.value("base_damage_scale", 1.)); + } + "emptyShip" => { + let taken = (1. - p.n("damage_resistance")).max(0.); + mods.insert("physTakenMul".into(), taken); + mods.insert("artsTakenMul".into(), taken); + self.equipment_stat(w, r, id, key.clone(), mods.clone())?; + if !member { + continue; + } + key.push_str(":dmg"); + mods.clear(); + mods.insert( + "dmgDealtMul".into(), + p.value( + if elite { + "damage_scale_extra" + } else { + "damage_scale_normal" + }, + 1., + ), + ); + } + "soloShip" => { + if !member { + continue; + } + mods.insert("atkPct".into(), p.n("atk")); + mods.insert("hpPct".into(), p.n("max_hp")); + } + "suntShip" => { + if !elite { + continue; + } + mods.insert("atkPct".into(), p.n("power_atk")); + if p.tier >= 2 && !self.bonds.skill_costs.contains(&id) { + let mut s = self.roster.as_mut().unwrap().take_skill(id)?; + let result = s.bank.set_multiplier( + w, + s.bank.cost_multiplier() * p.value("sp_ratio", 1.), + ); + self.roster.as_mut().unwrap().restore_skill(id, s)?; + result?; + self.bonds.skill_costs.insert(id); + } + } + _ => continue, + } + if mods.values().any(|v| !v.is_finite()) { + return Err("Bond passive overflow".into()); + } + self.equipment_stat(w, r, id, key, mods)?; + } + } + self.bond_kazimierz_refresh(w, r)?; + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/bonds/raid.rs b/crates/engine/src/battle/runtime/bonds/raid.rs new file mode 100644 index 0000000..7a9ce60 --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds/raid.rs @@ -0,0 +1,280 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{body, direction::Placement, targeting}; +impl Host { + fn raid_tile(&mut self, w: &mut World, id: Id, enemy: Id) -> Result, String> { + let roster = self.roster.as_ref().unwrap(); + let entry = roster.entry(id)?; + let direction = entry.direction; + let ranged = !w.unit(id)?.targeting.melee_operator; + let range = entry.definition.range_grid.clone(); + let extend = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("rangeExtend") + .max(0.) as u32; + let block = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("blockCnt") + > 0.; + let body = body::keys(w.unit(enemy)?); + let at = w + .unit(enemy)? + .position + .map(|x| crate::deterministic::math::round_half_even(x) as i32); + let paths = self + .spawns + .as_mut() + .unwrap() + .path_tiles(self.grid.as_mut().unwrap()); + let placement = Placement { + boss_like: self.rect.r0 == 0, + right_side: false, + field_coords: false, + row_offset: None, + col_offset: 0, + }; + let mut best = None; + let mut score = (2u8, f64::INFINITY, [i32::MAX; 2]); + for row in 0..crate::battle::grid::ROWS as i32 { + for col in 0..COLS as i32 { + let tile = [row, col]; + let grid = self.grid.as_ref().unwrap(); + if !placement.on_own_board(tile) + || !grid.in_rect(tile) + || !grid.can_stand(tile, ranged) + || self + .roster + .as_ref() + .unwrap() + .deployment() + .reserved(w, tile)? + { + continue; + } + if !body.iter().any(|k| { + (row - (*k / COLS) as i32) + .abs() + .max((col - (*k % COLS) as i32).abs()) + <= 2 + }) { + continue; + } + let reach = targeting::absolute_range(&range, tile, direction, extend); + if !body.iter().any(|k| reach.contains(k)) { + continue; + } + let key = row as usize * COLS + col as usize; + let priority = if !ranged + && block + && grid.ground_passable(tile, false) + && (paths.contains(&key) || body.contains(&key)) + { + 0 + } else { + 1 + }; + let delta = [row - at[0], col - at[1]]; + let distance = delta[0].abs().max(delta[1].abs()) as f64 + + 0.01 * (delta[0].abs() + delta[1].abs()) as f64; + let local = direction.local(delta); + if priority < score.0 + || priority == score.0 + && (distance < score.1 - 1e-9 + || (distance - score.1).abs() <= 1e-9 && local < score.2) + { + best = Some(tile); + score = (priority, distance, local); + } + } + } + Ok(best) + } + pub(super) fn raid_buff( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + p: &Bond, + ) -> Result<(), String> { + let l = self.bond_layers(&p.id); + let mut mods = Numbers::new(); + mods.insert("atkPct".into(), p.n("base_atk") + p.n("atk_per_stack") * l); + mods.insert( + "hpPct".into(), + p.n("base_max_hp") + p.n("max_hp_per_stack") * l, + ); + let aspd = p.n("base_attack_speed") + p.n("attack_speed_per_stack") * l; + if aspd != 0. { + mods.insert("aspd".into(), aspd); + } + r.add( + w, + self, + id, + buffs::Spec { + buff: Buff { + key: Some("bond:raidShip".into()), + mods, + ..Default::default() + }, + mods_present: true, + ..Default::default() + }, + )?; + Ok(()) + } + pub(super) fn raid_poll( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "raidShip") + .cloned() + else { + return Ok(()); + }; + for id in self.bond_ops(w) { + if !self.equipment_member(id, &p.id) || !Self::tac_up(w, id) || !skills::can_act(w, id)? + { + continue; + } + let revived = + self.bonds.raid_revived.remove(&id) == Some(w.unit(id)?.deployment.deploy_seq); + if revived { + let tile = w.unit(id)?.deployment.tile; + for enemy in self.spawns.as_ref().unwrap().live().to_vec() { + let at = w + .unit(enemy)? + .position + .map(|x| crate::deterministic::math::round_half_even(x) as i32); + if (at[0] - tile[0]).abs() > 1 || (at[1] - tile[1]).abs() > 1 { + continue; + } + if w.unit(enemy)?.stats.alive + && !w.unit(enemy)?.hidden + && w.unit(enemy)?.blocked_by().is_none() + { + let mut grid = self.grid.take().unwrap(); + let result = self.with_kit_buffs(w, r, |h, w| { + crate::battle::motion::Hooks::check_block(h, enemy, w, &mut grid) + }); + self.grid = Some(grid); + result?; + } + } + if !w.unit(id)?.blocking().is_empty() { + continue; + } + } + let skill = self.roster.as_ref().unwrap().entry(id)?.skill()?; + let ready = !skill.bank.no_skill + && ((skill.bank.ready() && !(skill.bank.active && skill.bank.kind.timed())) + || skill.bank.active + && (skill.bank.kind == crate::battle::sp::Kind::Passive + || skill.spec.sp_type == skills::SpType::None)); + let u = w.unit(id)?; + if !revived + && !ready + && w.time - u.last_attack_at.max(u.deployment.deployed_at) + < p.value("no_attack_duration", 10.) - 1e-9 + { + continue; + } + let range = self.roster.as_ref().unwrap().range(w, id)?; + let mut targets = Vec::new(); + let mut occupied = false; + for enemy in self.spawns.as_ref().unwrap().live().to_vec() { + let profile = self + .roster + .as_ref() + .unwrap() + .entry(id)? + .definition + .combat + .profile + .selection; + let visible = targeting::can_target_enemy(w, self, Some(id), enemy, profile)?; + let ground = !targeting::flying(w, enemy)? + && targeting::can_target_enemy( + w, + self, + Some(id), + enemy, + targeting::Profile { + ignore_stealth: true, + ground_only: true, + ..Default::default() + }, + )?; + if !revived && (visible || ground) && body::in_range(w.unit(enemy)?, &range) { + occupied = true; + break; + } + if ground { + let distance = targeting::Queries::remaining_distance(self, enemy, w)?; + let taunt = if revived { + w.unit_mut(enemy)? + .stats + .stats() + .map_err(str::to_string)? + .n("taunt") + } else { + 0. + }; + targets.push((distance, enemy, taunt)); + } + } + if occupied { + continue; + } + targets.sort_by(|a, b| { + b.2.total_cmp(&a.2) + .then(a.0.total_cmp(&b.0)) + .then(a.1.cmp(&b.1)) + }); + for (_, enemy, _) in targets.into_iter().take(8) { + let Some(tile) = self.raid_tile(w, id, enemy)? else { + continue; + }; + kits::dispatch::Context { + host: self, + world: w, + buffs: r, + unit: id, + } + .retreat_with_reason("raid")?; + if w.unit(id)?.stats.alive { + break; + } + let tiles = Arc::clone(&self.tiles); + let mut roster = self.roster.take().unwrap(); + let result = roster.redeploy_at(w, r, self, &tiles, id, Some(tile), true); + self.roster = Some(roster); + let landed = result?; + if !landed { + let mut roster = self.roster.take().unwrap(); + let result = roster.redeploy_at(w, r, self, &tiles, id, None, true); + self.roster = Some(roster); + result?; + } + self.rebuild_index(w)?; + self.flush_kit_events(w, r)?; + if landed { + self.raid_buff(w, r, id, &p)?; + } + break; + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/bonds/revival.rs b/crates/engine/src/battle/runtime/bonds/revival.rs new file mode 100644 index 0000000..54c01a4 --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds/revival.rs @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Default)] +pub(super) struct Indom { + pub free: BTreeSet, + last: BTreeMap, +} + +impl Host { + fn indom_plan(&self, w: &World, id: Id) -> Option> { + let unit = w.unit(id).ok()?; + if unit.deployment.kind != Kind::Operator || !unit.targeting.melee_operator { + return None; + } + self.bonds + .plans + .iter() + .find(|p| p.id == "indomShip") + .cloned() + } + fn indom_roll(&mut self, p: &Bond) -> bool { + let probability = + (p.n("base_prob") + p.n("prob_per_stack") * self.bond_layers(&p.id)).clamp(0., 1.); + self.rng.next_f64() < probability + } + pub(in crate::battle::runtime) fn bond_doll_swap( + &mut self, + w: &World, + id: Id, + ) -> Result<(), String> { + if !w.unit(id)?.stats.alive || self.bonds.indom.free.contains(&id) { + return Ok(()); + } + if let Some(p) = self.indom_plan(w, id) { + if self.indom_roll(&p) { + self.bonds.indom.free.insert(id); + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn bond_indom_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + reason: Option<&str>, + ) -> Result<(), String> { + if !matches!(reason, Some("killed" | "retreat" | "merchant")) { + return Ok(()); + } + let p = self.indom_plan(w, id); + let banked = self.bonds.indom.free.contains(&id); + if p.is_none() && !banked { + return Ok(()); + } + if let Some(p) = p + .as_ref() + .filter(|p| p.tier >= 2 && reason == Some("killed")) + { + let amount = p.n("sp"); + if amount > 0. { + for target in self.bond_ops(w) { + if !Self::tac_up(w, target) { + continue; + } + if self.roster.as_ref().unwrap().entry(target)?.skill().is_ok() { + let mut s = self.roster.as_mut().unwrap().take_skill(target)?; + let result = self.with_kit_buffs(w, r, |h, w| { + s.gain(w, h, amount, "bond", false, false) + }); + let restored = self.roster.as_mut().unwrap().restore_skill(target, s); + result.and(restored)?; + } else { + let limit = w + .unit_capacity() + .checked_mul(self.roster.as_ref().unwrap().ids().len()) + .ok_or("Bond SP capacity overflow")?; + let pending = &mut w.unit_mut(target)?.operator.support.sp_changes; + if pending.len() >= limit { + return Err("Pending bond SP capacity exceeded".into()); + } + pending.push(crate::battle::content::operators::SpChange::Bond(amount)); + } + } + } + } + let unit = w.unit(id)?; + if unit.stats.alive || unit.removed || self.bonds.indom.last.get(&id) == Some(&w.time) { + return Ok(()); + } + if banked || p.as_ref().is_some_and(|p| self.indom_roll(p)) { + self.bonds.indom.last.insert(id, w.time); + let mut context = kits::dispatch::Context { + host: self, + world: w, + buffs: r, + unit: id, + }; + context.redeploy_free(id)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/bonds/yan.rs b/crates/engine/src/battle/runtime/bonds/yan.rs new file mode 100644 index 0000000..327628c --- /dev/null +++ b/crates/engine/src/battle/runtime/bonds/yan.rs @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::deterministic::math::hypot; +impl Host { + pub(in crate::battle::runtime) fn yan_start( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let Some(p) = self + .bonds + .plans + .iter() + .find(|p| p.id == "yanShip" && p.tier >= 2) + .cloned() + else { + return Ok(()); + }; + let ops = self.bond_ops(w); + let mut atk = 0.; + let mut hp = 0.; + let mut owner = None; + for id in ops { + if !Self::tac_up(w, id) + || !self + .equipment + .units + .get(&id) + .is_some_and(|l| l.bonds.iter().any(|b| b == "yanShip")) + { + continue; + } + owner.get_or_insert(id); + let stats = w.unit_mut(id)?.stats.stats().map_err(str::to_string)?; + atk += stats.n("atk"); + hp += stats.n("maxHp"); + } + let Some(owner) = owner else { return Ok(()) }; + if hp <= 0. { + return Ok(()); + } + let share = 0.3; + for index in 0..if p.tier >= 3 { 2 } else { 1 } { + let mut best = None; + let mut score = (3u8, f64::INFINITY, usize::MAX); + let rect = self.rect; + for row in rect.r0..=rect.r1 { + for col in rect.c0..=rect.c1 { + let tile = [row, col]; + if self + .bonds + .reserved_map_chars + .contains(&(row as usize * COLS + col as usize)) + { + continue; + } + if self + .roster + .as_ref() + .unwrap() + .deployment() + .reserved(w, tile)? + { + continue; + } + let grid = self.grid.as_ref().unwrap(); + let cell = &grid.tiles()[row as usize * COLS + col as usize]; + let class = if cell.build == "NONE" { + if cell.pass != "ALL" { + 0 + } else { + 1 + } + } else { + 2 + }; + let distance = hypot( + row as f64 - (rect.r0 + rect.r1) as f64 / 2., + col as f64 - (rect.c0 + rect.c1) as f64 / 2., + ); + let key = row as usize * COLS + col as usize; + if class < score.0 + || class == score.0 + && (distance < score.1 - 1e-9 + || (distance - score.1).abs() <= 1e-9 && key < score.2) + { + best = Some(tile); + score = (class, distance, key); + } + } + } + let Some(tile) = best else { break }; + let id = (kits::dispatch::Context { + host: self, + world: w, + buffs: r, + unit: owner, + }) + .summon("enemy_9012_acloon", tile, 0.)?; + let Some(id) = id else { continue }; + let u = w.unit_mut(id)?; + u.summoner = None; + u.stats.edit_base(|base| { + *base.0.entry("atk".into()).or_default() += atk * share; + *base.0.entry("maxHp".into()).or_default() += hp * share; + }); + u.operator.tactical.yanyou_mut()?.hover = if index == 0 { 0. } else { 0.8 }; + if p.tier >= 3 { + self.equipment_stat( + w, + r, + id, + "bond:yanyou".into(), + [ + ("atkMul".into(), p.value("atk", 1.)), + ( + "dmgTakenMul".into(), + (1. - p.n("damage_resistance")).max(0.), + ), + ] + .into(), + )?; + } + let u = w.unit_mut(id)?; + u.stats.hp = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/boss.rs b/crates/engine/src/battle/runtime/boss.rs new file mode 100644 index 0000000..dacc69b --- /dev/null +++ b/crates/engine/src/battle/runtime/boss.rs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +const POOL: Id = 1; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BossKind { + FinalAssault, + HiddenCore, +} +pub struct BossConfig { + pub kind: BossKind, + pub pool: health::Pool, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BossState { + pub kind: BossKind, + pub hp: f64, + pub max_hp: f64, + pub damage: f64, +} +impl BossConfig { + pub(super) fn validate(&self) -> Result<(), String> { + self.pool.validate_shared() + } +} +impl Field { + pub(crate) fn inherit_boss_damage(&mut self, damage: f64) -> Result<(), String> { + self.healthy()?; + if self.core.boss.is_none() + || self.clock.started() + || self.finished() + || !damage.is_finite() + || damage < 0. + { + return Err("Boss damage carry requires an unstarted boss field".into()); + } + self.core.world.player_mut(1).unwrap().match_boss_damage = damage; + Ok(()) + } + pub(crate) fn match_boss_damage(&self) -> Result { + self.healthy()?; + Ok(self.core.world.player(1).unwrap().match_boss_damage) + } + pub fn new_boss( + data: Arc, + stage: &Value, + template: Template, + seed: u32, + time_limit: f64, + limits: Limits, + boss: BossConfig, + ) -> Result { + Self::build(data, stage, template, seed, time_limit, limits, Some(boss)) + } + pub fn boss_state(&self) -> Result, String> { + self.healthy()?; + Ok(self.core.boss.map(|kind| { + let pool = self.core.world.pool(POOL).unwrap(); + BossState { + kind, + hp: pool.hp, + max_hp: pool.max_hp, + damage: self.core.world.player(1).unwrap().boss_damage, + } + })) + } +} +impl Host { + pub(super) fn attach_boss_pool(&mut self, w: &mut World, id: Id) -> Result<(), String> { + if w.unit(id)?.boss && w.pool(POOL).is_some() { + w.unit_mut(id)?.pool = Some(POOL); + Self::sync_boss_hp(w, id)?; + } + Ok(()) + } + fn sync_boss_hp(w: &mut World, id: Id) -> Result<(), String> { + let pool = w + .pool(w.unit(id)?.pool.ok_or("Boss unit has no pool")?) + .ok_or("Missing boss pool")?; + let hp = pool.hp; + let max = pool.max_hp; + let unit = w.unit_mut(id)?; + if unit.stats.base_number("maxHp") != max { + unit.stats.edit_base(|b| { + b.0.insert("maxHp".into(), max); + }); + } + unit.stats.hp = unit.stats.stats().map_err(str::to_string)?.n("maxHp") * (hp / max).min(1.); + Ok(()) + } + pub(super) fn sync_bosses(&mut self, w: &mut World) -> Result<(), String> { + let ids = self.spawns.as_ref().unwrap().live().to_vec(); + let mut effects = self.buffs.take().unwrap(); + let result = (|| { + for id in ids { + if !w.unit(id)?.stats.alive || w.unit(id)?.pool.is_none() { + continue; + } + Self::sync_boss_hp(w, id)?; + if w.unit(id)?.stats.hp <= 0. { + self.kill_enemy(id, None, &mut effects, w)?; + } + } + Ok(()) + })(); + self.buffs = Some(effects); + result + } +} diff --git a/crates/engine/src/battle/runtime/boss_round.rs b/crates/engine/src/battle/runtime/boss_round.rs new file mode 100644 index 0000000..0127076 --- /dev/null +++ b/crates/engine/src/battle/runtime/boss_round.rs @@ -0,0 +1,167 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +#[derive(Clone, Copy, Debug)] +pub struct BossOvertime { + pub after_real_seconds: f64, + pub combat_time_scale: f64, + pub lp_per_real_second: f64, +} +#[derive(Clone, Copy, Debug)] +pub struct BossRoundConfig { + pub life_points: f64, + pub overtime: Option, +} +pub(crate) fn validate_boss_round(config: BossRoundConfig) -> Result<(), String> { + Round::new(config).map(|_| ()) +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BossRoundOutcome { + Victory, + LifeDepleted, + Timeout, + Forced, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BossRoundState { + pub initial_lp: f64, + pub lp: f64, + pub leak_loss: f64, + pub skill_loss: f64, + pub overtime_loss: f64, + pub outcome: Option, +} +pub(super) enum Cost { + Leak, + Skill, + Overtime, +} +pub(super) struct Round { + state: BossRoundState, + overtime: Option, +} +impl Round { + fn new(config: BossRoundConfig) -> Result { + if !config.life_points.is_finite() || config.life_points <= 0. { + return Err("Boss round requires positive finite life points".into()); + } + if let Some(o) = config.overtime { + if !o.after_real_seconds.is_finite() + || o.after_real_seconds < 0. + || !o.combat_time_scale.is_finite() + || o.combat_time_scale <= 0. + || !o.lp_per_real_second.is_finite() + || o.lp_per_real_second < 0. + { + return Err("Invalid boss overtime settings".into()); + } + } + Ok(Self { + state: BossRoundState { + initial_lp: config.life_points, + lp: config.life_points, + leak_loss: 0., + skill_loss: 0., + overtime_loss: 0., + outcome: None, + }, + overtime: config.overtime, + }) + } + pub(super) fn charge(&mut self, cost: Cost, amount: f64) -> Result<(), String> { + let total = match cost { + Cost::Leak => &mut self.state.leak_loss, + Cost::Skill => &mut self.state.skill_loss, + Cost::Overtime => &mut self.state.overtime_loss, + }; + let next = *total + amount; + if !amount.is_finite() || amount < 0. || !next.is_finite() { + return Err("Invalid or overflowing boss LP cost".into()); + } + *total = next; + self.state.lp = (self.state.lp - amount).max(0.); + Ok(()) + } + pub(super) fn advance(&mut self, time: f64) -> Result<(), String> { + if let Some(o) = self.overtime { + let elapsed = time / o.combat_time_scale - o.after_real_seconds; + let due = if elapsed >= 1. { + elapsed.floor() * o.lp_per_real_second + } else { + 0. + }; + if !due.is_finite() { + return Err("Boss overtime cost overflow".into()); + } + if due > self.state.overtime_loss { + self.charge(Cost::Overtime, due - self.state.overtime_loss)?; + self.state.overtime_loss = due; + } + } + Ok(()) + } + pub(super) fn depleted(&self) -> bool { + self.state.lp <= 0. + } + pub(super) fn finish(&mut self, reason: &End, hp: f64) { + self.state.outcome = Some(if hp <= 0. { + BossRoundOutcome::Victory + } else if self.depleted() { + BossRoundOutcome::LifeDepleted + } else if *reason == End::Timeout { + BossRoundOutcome::Timeout + } else { + BossRoundOutcome::Forced + }); + } +} +impl Field { + /// Configure the single-player Boss round before its first tick. + pub fn configure_boss_round(&mut self, config: BossRoundConfig) -> Result<(), String> { + self.healthy()?; + if self.core.boss.is_none() + || self.finished() + || self.clock.started() + || self.ticks() != 0 + || self.core.host.boss_round.is_some() + { + return Err("Boss round must be configured once before a boss field starts".into()); + } + self.core.host.boss_round = Some(Round::new(config)?); + Ok(()) + } + // MatchBoss applies overtime after Battle.step, including its final frame. + // Keep the round clock outside the combat phases so a natural timeout wins + // over a force-end request issued at that same deadline. + pub(super) fn run_boss_round(&mut self, budget: usize) -> Result { + let mut ticks = 0; + while ticks < budget && !self.finished() { + self.clock.step(&mut self.core)?; + ticks += 1; + let round = self.core.host.boss_round.as_mut().unwrap(); + round.advance(self.clock.time())?; + if round.depleted() && self.core.world.pool(1).unwrap().hp > 0. { + self.clock.force_end(&mut self.core, "forced".into())?; + } + self.finish_boss_round(); + } + Ok(ticks) + } + pub(super) fn finish_boss_round(&mut self) { + if let (Some(round), Some(reason)) = (&mut self.core.host.boss_round, self.clock.reason()) { + round.finish(reason, self.core.world.pool(1).unwrap().hp); + } + } + pub fn boss_round_state(&self) -> Result, String> { + self.healthy()?; + Ok(self.core.host.boss_round.as_ref().map(|r| r.state)) + } +} +impl Host { + pub(super) fn lose_lp(&mut self, amount: f64) -> Result<(), String> { + self.content.as_mut().unwrap().lose_lp(amount)?; + if let Some(round) = &mut self.boss_round { + round.charge(Cost::Skill, amount)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/choices.rs b/crates/engine/src/battle/runtime/choices.rs new file mode 100644 index 0000000..c41e36e --- /dev/null +++ b/crates/engine/src/battle/runtime/choices.rs @@ -0,0 +1,336 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Friendly tactical decisions: preparation gates and battle event effects. +use super::*; +use crate::battle::{ + deploy::Kind, + stats::{Buff, Numbers}, +}; +#[derive(Clone, Debug)] +pub struct BattleChoice { + pub effect_id: String, + pub sequence: u64, + pub bench_units: usize, +} +#[derive(Clone)] +enum Gate { + Always, + AtLeast(usize), + AtMost(usize), + Row(usize), +} +#[derive(Clone)] +enum Effect { + Heal(f64), + Flawless(Numbers), + Stats(Numbers), +} +#[derive(Clone)] +struct Plan { + key: String, + gate: Gate, + effect: Effect, + active: bool, +} +#[derive(Default)] +pub(super) struct Choices { + plans: Vec, + heal: f64, +} +impl BattleChoice { + fn compile(&self, data: &Catalog) -> Result { + let buffs = data + .table("effects") + .and_then(|t| t.get(&self.effect_id)) + .and_then(|r| r["buffs"].as_array()) + .ok_or("Unknown battle choice")?; + if buffs.len() > 32 || self.sequence == 0 || self.bench_units > 4096 { + return Err("Invalid battle choice limits".into()); + } + let mut gate = Gate::Always; + let mut effect = None; + for b in buffs { + let number = |key: &str| { + b["bb"][key] + .as_f64() + .filter(|v| v.is_finite()) + .ok_or_else(|| format!("Invalid choice parameter: {key}")) + }; + match b["key"].as_str() { + Some("global_special_choice_all_activated") => (), + Some( + "global_special_choice_prep_finish_bench_at_least" + | "global_special_choice_prep_finish_bench_at_most" + | "global_special_choice_prep_finish_same_row_at_least", + ) => { + let count = number("count")?.max(0.).trunc().min(4096.) as usize; + gate = match b["key"].as_str().unwrap() { + "global_special_choice_prep_finish_bench_at_least" => Gate::AtLeast(count), + "global_special_choice_prep_finish_bench_at_most" => Gate::AtMost(count), + _ => Gate::Row(count.max(1)), + }; + } + Some("char_respawntime_mul") => { + effect = Some(Effect::Stats(Numbers::from([( + "redeployMul".into(), + number("scale")?.max(0.), + )]))) + } + Some("env_gbuff_new_with_verify") => { + effect = Some(match b["bbStr"]["key"].as_str() { + Some("act1autochess_debuff_3") => Effect::Heal(number("value")?.max(0.)), + Some("act1autochess_debuff_9") => Effect::Flawless(Numbers::from([ + ("atkPct".into(), number("atk")?), + ("defPct".into(), number("def")?), + ])), + _ => return Err("Unsupported verified choice modifier".into()), + }); + } + Some("env_gbuff_new") => { + let mut mods = Numbers::new(); + for (key, value) in b["bb"].as_object().ok_or("Missing choice modifiers")? { + let key = match key.as_str() { + "magic_resist_penetrate_fixed" => "resIgnoreFlat", + "def_penetrate" => "defIgnorePct", + _ => return Err(format!("Unsupported choice modifier: {key}")), + }; + mods.insert( + key.into(), + value + .as_f64() + .filter(|v| v.is_finite()) + .ok_or("Invalid choice modifier")?, + ); + } + effect = Some(Effect::Stats(mods)); + } + _ => return Err(format!("Battle choice not implemented: {}", b["key"])), + } + } + let active = match gate { + Gate::Always => true, + Gate::AtLeast(n) => self.bench_units >= n, + Gate::AtMost(n) => self.bench_units <= n, + Gate::Row(_) => false, + }; + Ok(Plan { + key: format!("choice:{}#{}", self.effect_id, self.sequence), + gate, + effect: effect.ok_or("Choice has no battle effect")?, + active, + }) + } + pub(crate) fn validate(&self, data: &Catalog) -> Result<(), String> { + self.compile(data).map(|_| ()) + } +} +impl Field { + pub fn configure_choices(&mut self, choices: &[BattleChoice]) -> Result<(), String> { + self.healthy()?; + if self.clock.started() || self.ticks() != 0 { + return Err("Choices require an unstarted field".into()); + } + if choices.len() > super::super::grid::N { + return Err("Battle choice capacity exceeded".into()); + } + let mut keys = std::collections::BTreeSet::new(); + let mut plans = Vec::new(); + for choice in choices { + let plan = choice.compile(&self.core.host.data)?; + if !keys.insert(plan.key.clone()) { + return Err("Duplicate battle choice identity".into()); + } + plans.push(plan); + } + self.core.host.choices = Choices { plans, heal: 0. }; + Ok(()) + } +} +impl Host { + pub(super) fn choices_start( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + if self.choices.plans.is_empty() { + return Ok(()); + } + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + let mut rows = std::collections::BTreeMap::::new(); + for &id in &ids { + let u = w.unit(id)?; + if u.deployment.kind == Kind::Operator && u.stats.alive && u.deployed { + *rows.entry(u.deployment.tile[0]).or_default() += 1; + } + } + let max = rows.values().copied().max().unwrap_or(0); + for plan in &mut self.choices.plans { + if let Gate::Row(n) = plan.gate { + plan.active = max >= n; + } + } + for plan in self.choices.plans.clone().into_iter().filter(|p| p.active) { + match plan.effect { + Effect::Heal(amount) => self.choices.heal += amount, + Effect::Stats(mods) => { + for &id in &ids { + if w.unit(id)?.deployment.kind == Kind::Operator { + self.equipment_stat(w, r, id, plan.key.clone(), mods.clone())?; + } + } + } + Effect::Flawless(_) => (), + } + } + self.choices_tick(w, r) + } + fn choice_full_health( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if !self + .choices + .plans + .iter() + .any(|p| p.active && matches!(p.effect, Effect::Flawless(_))) + { + return Ok(()); + } + if w.unit(id)?.deployment.kind != Kind::Operator { + return Ok(()); + } + let full = Self::choice_is_full(w, id)?; + for plan in self.choices.plans.clone().into_iter().filter(|p| p.active) { + let Effect::Flawless(mods) = plan.effect else { + continue; + }; + let has = w + .unit(id)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(&plan.key)); + if full && !has { + r.add( + w, + self, + id, + buffs::Spec { + buff: Buff { + key: Some(plan.key), + mods, + permanent: true, + ..Default::default() + }, + mods_present: true, + ..Default::default() + }, + )?; + } else if !full && has { + r.remove(w, self, id, &plan.key)?; + } + } + Ok(()) + } + fn choice_is_full(w: &mut World, id: Id) -> Result { + let u = w.unit_mut(id)?; + let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + Ok(u.stats.alive && u.deployed && u.stats.hp >= max - 1e-6) + } + pub(super) fn choices_clock_quiet(&self, w: &mut World) -> Result { + let plans: Vec<_> = self + .choices + .plans + .iter() + .filter(|p| p.active && matches!(p.effect, Effect::Flawless(_))) + .collect(); + if plans.is_empty() { + return Ok(true); + } + for &id in self.roster.as_ref().unwrap().ids() { + if w.unit(id)?.deployment.kind != Kind::Operator { + continue; + } + let full = Self::choice_is_full(w, id)?; + if plans.iter().any(|plan| { + w.unit(id) + .unwrap() + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(&plan.key)) + != full + }) { + return Ok(false); + } + } + Ok(true) + } + pub(super) fn choices_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + if !self + .choices + .plans + .iter() + .any(|p| p.active && matches!(p.effect, Effect::Flawless(_))) + { + return Ok(()); + } + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + for id in ids { + self.choice_full_health(w, r, id)?; + } + Ok(()) + } + pub(super) fn choices_damaged( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + e: &health::Event, + q: &hit::Request, + ) -> Result<(), String> { + if self.choices.plans.is_empty() { + return Ok(()); + } + let u = w.unit(e.target)?; + if u.side != health::Side::Ally + || !matches!(u.deployment.kind, Kind::Operator | Kind::Token) + { + return Ok(()); + } + if self.choices.heal > 0. + && e.amount > 0. + && !q.hit.hp_loss + && q.hit.damage_type != super::super::damage::DamageType::Elemental + && u.stats.alive + && u.deployed + && u.stats.hp > 0. + { + if w.unit_mut(e.target)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("noHeal") + { + return self.choice_full_health(w, r, e.target); + } + self.support_heal( + w, + r, + None, + e.target, + self.choices.heal, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + self.choice_full_health(w, r, e.target) + } +} diff --git a/crates/engine/src/battle/runtime/devices.rs b/crates/engine/src/battle/runtime/devices.rs new file mode 100644 index 0000000..4234daa --- /dev/null +++ b/crates/engine/src/battle/runtime/devices.rs @@ -0,0 +1,553 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Stage fixtures use the shared unit, occupancy, blocking and damage lifecycles. +use super::*; +use crate::battle::deploy; +#[derive(Clone, Debug, Default)] +pub struct MapConfig { + pub effects: Vec, + pub device_overrides: std::collections::BTreeMap, + pub top_layers: f64, + pub cold_wind: Option, +} +#[derive(Clone, Debug)] +pub struct ColdWind { + pub interval: f64, + pub duration: f64, + pub first: Option, +} +impl MapConfig { + pub fn parse(v: &Value) -> Result { + if v.is_null() { + return Ok(Self::default()); + } + let object = v.as_object().ok_or("Expected map configuration object")?; + if object + .keys() + .any(|k| !["deviceOverrides", "topLayers", "coldWind", "effects"].contains(&k.as_str())) + { + return Err("Unknown map configuration field".into()); + } + let mut out = Self::default(); + if let Some(effects) = v.get("effects") { + let effects = effects.as_array().ok_or("Expected map effect list")?; + if effects.len() > super::super::grid::N { + return Err("Map effect capacity exceeded".into()); + } + out.effects = effects + .iter() + .map(|e| { + e.as_str() + .map(str::to_owned) + .ok_or_else(|| "Expected map effect ID".to_string()) + }) + .collect::>()?; + } + if let Some(overrides) = v.get("deviceOverrides") { + for (key, value) in overrides + .as_object() + .ok_or("Expected device override object")? + { + out.device_overrides.insert( + key.clone(), + value.as_bool().ok_or("Device switch must be boolean")?, + ); + } + } + if let Some(layers) = v.get("topLayers") { + out.top_layers = layers.as_f64().ok_or("Expected device layer count")?; + } + if let Some(c) = v.get("coldWind").filter(|c| !c.is_null()) { + if c.as_object() + .ok_or("Expected cold wind configuration")? + .keys() + .any(|k| !["interval", "duration", "first"].contains(&k.as_str())) + { + return Err("Unknown cold wind field".into()); + } + out.cold_wind = Some(ColdWind { + interval: c["interval"].as_f64().ok_or("Expected wind interval")?, + duration: c["duration"].as_f64().ok_or("Expected wind duration")?, + first: c + .get("first") + .map(|x| x.as_f64().ok_or("Expected first wind time")) + .transpose()?, + }); + } + out.validate()?; + Ok(out) + } + + pub(crate) fn resolved(mut self, data: &Catalog) -> Result { + self.validate()?; + let mut overrides = std::collections::BTreeMap::new(); + for id in &self.effects { + let record = data + .table("effects") + .and_then(|t| t.get(id)) + .ok_or_else(|| format!("Unknown map effect: {id}"))?; + let buffs = record["buffs"] + .as_array() + .ok_or("Map effect has no buffs")?; + if buffs.is_empty() { + return Err("Map effect has no buffs".into()); + } + for buff in buffs { + if buff["key"] != "auto_chess_change_map" { + return Err(format!("Not a map-switch effect: {id}")); + } + for (alias, value) in buff["bb"] + .as_object() + .ok_or("Map effect has no parameters")? + { + if !alias.starts_with("trap_") || !alias.contains('#') { + return Err(format!("Unsupported map effect parameter: {alias}")); + } + let on = match value { + Value::Bool(v) => *v, + Value::Number(v) => v.as_f64().unwrap_or(0.) != 0., + Value::String(v) => !v.is_empty() && v != "0" && v != "false", + _ => return Err("Invalid map effect switch".into()), + }; + overrides.insert(alias.clone(), on); + } + } + } + overrides.extend(self.device_overrides); + self.device_overrides = overrides; + self.validate()?; + Ok(self) + } + pub(crate) fn validate(&self) -> Result<(), String> { + if self.effects.len() > super::super::grid::N + || self.device_overrides.len() > super::super::grid::N + || !self.top_layers.is_finite() + || self.top_layers < 0. + || self.cold_wind.as_ref().is_some_and(|c| { + !c.interval.is_finite() + || c.interval <= 0. + || !c.duration.is_finite() + || c.duration < 0. + || c.first.is_some_and(|f| !f.is_finite() || f < 0.) + }) + { + return Err("Invalid map device configuration".into()); + } + Ok(()) + } +} +#[derive(Default)] +pub(super) struct Devices { + pub(super) stage: Value, + pub(super) config: MapConfig, + pub(super) cold_due: Option, + crates: Vec<([i32; 2], f64)>, + removed: std::collections::BTreeSet<[i32; 2]>, + pub(super) added: Vec<([i32; 2], f64)>, + pub(super) turrets: Vec, + pub(super) ids: Vec, + breaks: Vec<(f64, Id, Id)>, + cleared: Vec<[i32; 2]>, + elevated: std::collections::BTreeSet<[i32; 2]>, +} +impl Devices { + pub(super) fn movement_quiet(&self) -> bool { + self.crates.is_empty() + && self.added.is_empty() + && self.breaks.is_empty() + && self.cleared.is_empty() + && self.turrets.is_empty() + && self.ids.is_empty() + && self.cold_due.is_none() + && self.config.cold_wind.is_none() + } + pub(super) fn compile(stage: &Value, grid: &mut Grid) -> Result { + if stage["devices"] + .as_array() + .is_some_and(|d| d.len() > super::super::grid::N) + { + return Err("Stage device capacity exceeded".into()); + } + let mut out = Self { + stage: stage.clone(), + ..Default::default() + }; + for d in stage["devices"].as_array().into_iter().flatten() { + if !d["active"].as_bool().unwrap_or(d["hidden"] != true) { + continue; + } + let at = [ + d["row"] + .as_i64() + .or_else(|| d["pos"][0].as_i64()) + .unwrap_or(-1) as i32, + d["col"] + .as_i64() + .or_else(|| d["pos"][1].as_i64()) + .unwrap_or(-1) as i32, + ]; + match d["role"].as_str() { + Some("platform" | "mound") if inside(grid.rect(), at) => { + grid.set_obstacle(at, true, super::super::grid::BLOCK)?; + out.elevated.insert(at); + } + Some("crate") if inside(grid.rect(), at) => { + if out.crates.iter().any(|(tile, _)| *tile == at) { + continue; + } + let hp = if d["key"] == "trap_1105_accrate" { + 100. + } else { + d["stats"]["maxHp"] + .as_f64() + .filter(|v| v.is_finite() && *v > 0.) + .unwrap_or(100.) + }; + out.crates.push((at, hp)); + grid.set_obstacle(at, true, super::super::grid::CRATE)?; + } + // Controllers supply terrain parameters; cold wind is triggered by effects, + // not by the presence of its controller in the stage data. + Some("blower" | "mireController" | "tideController" | "coldWind" | "turret") => {} + _ if inside(grid.rect(), at) => { + return Err(format!("Stage device not implemented: {}", d["key"])) + } + _ => {} + } + } + Ok(out) + } + pub(super) fn flush(&mut self, grid: &mut Grid) -> Result<(), String> { + for tile in self.cleared.drain(..) { + grid.set_obstacle(tile, false, super::super::grid::CRATE)?; + } + Ok(()) + } + pub(super) fn elevated(&self, at: [i32; 2]) -> bool { + self.elevated.contains(&at) + } +} +pub(super) struct Hooks<'a> { + pub(super) host: &'a mut Host, + pub(super) buffs: &'a mut buffs::Runtime, +} +impl blocking::Hooks for Hooks<'_> { + fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { + Ok(()) + } + fn ended(&mut self, id: Id, w: &mut World) -> Result<(), String> { + blocking::restore_stealth(w, self.buffs, self.host, id) + } +} +impl deploy::Hooks for Hooks<'_> { + fn initialize( + &mut self, + _: Id, + _: deploy::Options, + _: &mut World, + _: &mut deploy::Deployment, + ) -> Result<(), String> { + Ok(()) + } + fn event( + &mut self, + _: deploy::Event, + _: Id, + _: Option, + _: &mut World, + _: &mut deploy::Deployment, + ) -> Result<(), String> { + Ok(()) + } + fn remove_temporary_effects(&mut self, id: Id, w: &mut World) -> Result<(), String> { + self.buffs.discard_temporary(w, self.host, id) + } +} +impl Core { + pub(super) fn install_devices(&mut self) -> Result<(), String> { + for (tile, hp) in self.host.devices.crates.clone() { + self.spawn_map_unit(tile, &Value::Null, Some(hp))?; + } + let mut buffs = self.host.buffs.take().unwrap(); + let result = (|| { + for id in self.host.devices.ids.clone() { + if self + .host + .devices + .removed + .contains(&self.world.unit(id)?.deployment.tile) + { + self.host.remove_device(&mut self.world, &mut buffs, id)?; + } + } + Ok(()) + })(); + self.host.buffs = Some(buffs); + result + } + pub(super) fn device_scheduled(&mut self) -> Result<(), String> { + let now = self.world.time; + let due: Vec<_> = self + .host + .devices + .breaks + .iter() + .copied() + .filter(|(at, _, _)| *at <= now) + .collect(); + self.host.devices.breaks.retain(|(at, _, _)| *at > now); + let mut buffs = self.host.buffs.take().unwrap(); + let result = (|| { + for (_, device, enemy) in due { + if self.world.unit(device)?.stats.alive + && self + .world + .unit(enemy) + .is_ok_and(|e| e.stats.alive && e.blocked_by() == Some(device)) + { + self.host + .kill_device(&mut self.world, &mut buffs, device, Some(enemy))?; + } + } + Ok(()) + })(); + self.host.buffs = Some(buffs); + result + } +} +impl Host { + pub(super) fn device_blocked( + &mut self, + w: &mut World, + blocker: Id, + enemy: Id, + ) -> Result<(), String> { + if !self.devices.ids.contains(&blocker) { + return Ok(()); + } + if self.devices.breaks.len() >= self.tactical_limit { + return Err("Device timer capacity exceeded".into()); + } + let delay = w + .unit_mut(enemy)? + .stats + .stats() + .map_err(str::to_string)? + .n("interval") + .clamp(0.1, 10.); + self.devices.breaks.push((w.time + delay, blocker, enemy)); + Ok(()) + } + pub(super) fn kill_device( + &mut self, + w: &mut World, + buffs: &mut buffs::Runtime, + id: Id, + credit: Option, + ) -> Result<(), String> { + if !w.unit(id)?.stats.alive { + return Ok(()); + } + let tile = w.unit(id)?.deployment.tile; + let mut roster = self + .roster + .take() + .ok_or("Missing device deployment context")?; + let result = roster + .deployment_mut() + .kill(w, &mut Hooks { host: self, buffs }, id, credit); + self.roster = Some(roster); + result?; + if let Some(grid) = self.grid.as_mut() { + grid.set_obstacle(tile, false, super::super::grid::CRATE)?; + } else { + self.devices.cleared.push(tile); + } + self.devices.breaks.retain(|(_, device, _)| *device != id); + Ok(()) + } +} + +impl Field { + /// Install map-card switches and device effects before adding the lineup. + pub fn configure_map(&mut self, config: MapConfig) -> Result<(), String> { + self.healthy()?; + config.validate()?; + if self.clock.started() || self.ticks() != 0 || !self.allies().is_empty() { + return Err("Map configuration requires an unstarted field without a lineup".into()); + } + let config = config.resolved(&self.core.host.data)?; + let previous = &self.core.host.devices.config; + if config.effects.is_empty() + && config.device_overrides.is_empty() + && config.cold_wind.is_none() + && previous.effects.is_empty() + && previous.device_overrides.is_empty() + && previous.cold_wind.is_none() + && self.core.world.unit_ids().next().is_none() + { + // No switch to apply: the field was built from this same stage, so + // rebuilding the grid, devices and terrain would only repeat work. + self.core.host.devices.config = config; + return Ok(()); + } + let stage = self.core.host.devices.stage.clone(); + let mut grid = Grid::new(&stage, self.core.host.rect)?; + let mut devices = Devices::compile(&stage, &mut grid)?; + let mut terrain_stage = stage.clone(); + for (i, d) in stage["devices"] + .as_array() + .into_iter() + .flatten() + .enumerate() + { + let alias = d["alias"].as_str().or(d["raw"]["alias"].as_str()); + let Some(on) = alias.and_then(|a| config.device_overrides.get(a)).copied() else { + continue; + }; + let at = device_position(d); + let active = d["active"].as_bool().unwrap_or(d["hidden"] != true); + terrain_stage["devices"][i]["active"] = json!(on); + if !grid.in_rect(at) { + continue; + } + match d["role"].as_str() { + Some("crate") if active && !on => { + devices.removed.insert(at); + grid.set_obstacle(at, false, super::super::grid::CRATE)?; + } + Some("crate") if !active && on => { + devices.added.push((at, num(&d["stats"]["maxHp"], 100.))) + } + Some("platform" | "mound") => { + grid.set_obstacle(at, on, super::super::grid::BLOCK)?; + if on { + devices.elevated.insert(at); + } else { + devices.elevated.remove(&at); + } + } + _ => {} + } + } + let terrain = super::super::terrain::Config::compile(&terrain_stage, &grid)?; + devices.cold_due = config + .cold_wind + .as_ref() + .map(|c| c.first.unwrap_or(c.interval)); + devices.config = config; + self.core.host.devices = devices; + self.core.host.terrain = Arc::new(terrain); + self.core.host.grid = Some(Box::new(grid)); + Ok(()) + } + /// Update a live covenant's wind duration without restarting its pulse timer. + pub fn update_cold_wind_duration(&mut self, duration: f64) -> Result<(), String> { + self.healthy()?; + if !duration.is_finite() || duration < 0. { + return Err("Invalid cold wind duration".into()); + } + self.core + .host + .devices + .config + .cold_wind + .as_mut() + .ok_or("Cold wind is not configured")? + .duration = duration; + Ok(()) + } + /// Live highest bond layers, used when a turret starts its next attack. + pub fn update_map_layers(&mut self, layers: f64) -> Result<(), String> { + self.healthy()?; + if !layers.is_finite() || layers < 0. { + return Err("Invalid device bond layers".into()); + } + self.core.host.devices.config.top_layers = layers; + Ok(()) + } +} +pub(super) fn num(v: &Value, fallback: f64) -> f64 { + v.as_f64() + .or_else(|| v.as_str().and_then(|s| s.parse().ok())) + .filter(|v| v.is_finite()) + .unwrap_or(fallback) +} +pub(super) fn device_position(d: &Value) -> [i32; 2] { + [ + d["row"] + .as_i64() + .or(d["pos"][0].as_i64()) + .or(d["pos"]["row"].as_i64()) + .unwrap_or(-1) as i32, + d["col"] + .as_i64() + .or(d["pos"][1].as_i64()) + .or(d["pos"]["col"].as_i64()) + .unwrap_or(-1) as i32, + ] +} +impl Core { + pub(super) fn cold_wind_scheduled(&mut self) -> Result<(), String> { + let Some(due) = self.host.devices.cold_due else { + return Ok(()); + }; + if self.world.time < due { + return Ok(()); + } + let cold = self.host.devices.config.cold_wind.as_ref().unwrap().clone(); + // Original repeating timers schedule the next pulse from the current tick. + self.host.devices.cold_due = Some(self.world.time + cold.interval); + let ids = self.host.spawns.as_ref().unwrap().live().to_vec(); + let mut buffs = self.host.buffs.take().unwrap(); + let result = (|| { + if cold.duration <= 0. { + return Ok(()); + } + for id in ids { + if !self.world.unit(id)?.hidden && self.world.unit(id)?.stats.alive { + self.host.apply_status( + &mut self.world, + &mut buffs, + id, + "cold", + super::super::status::Options { + duration: cold.duration, + ..Default::default() + }, + )?; + } + } + Ok(()) + })(); + self.host.buffs = Some(buffs); + result + } +} +impl Host { + fn remove_device( + &mut self, + w: &mut World, + buffs: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let mut roster = self + .roster + .take() + .ok_or("Missing device deployment context")?; + let tile = w.unit(id)?.deployment.tile; + let result = roster.deployment_mut().retreat( + w, + &mut Hooks { host: self, buffs }, + id, + "removed", + true, + ); + self.roster = Some(roster); + result?; + self.grid + .as_mut() + .ok_or("Missing device grid")? + .set_obstacle(tile, false, super::super::grid::CRATE)?; + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies.rs b/crates/engine/src/battle/runtime/enemies.rs new file mode 100644 index 0000000..2046ec2 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies.rs @@ -0,0 +1,574 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Enemy content uses the same settlement, status, selection and buff runtimes as operators. +use super::*; +mod bosses; +mod casters; +pub(super) use bosses::{BossTask, BLADE_RETURN, PART_DOT, SURGE_TICK}; +mod catapult; +mod dots; +mod specials; +mod terrain; +pub(super) use casters::{ + SkillShot, SpellTask, ARTS_BARRIER, BURN_TICK, FEAR_CAGE, SAND_TICK, WOLF_REBORN, XI_SHIELD, +}; +pub(super) use specials::{BombShot, Task as SpecialTask, PARASITE_TICK, TRANSLATOR_FINISH}; +mod leaders; +mod supporters; +pub(super) use leaders::LANDING; +mod lifecycle; +mod rebirth; +pub(super) use rebirth::PILOT_BURN; +mod movement; +pub(super) use lifecycle::REBORN_FINISH; +mod forms; +mod reactions; +mod zones; +pub(super) use zones::{CloudShot, EnemyTask}; +mod families; +pub(super) use dots::BLEED; +mod splits; +use crate::battle::{ + content::enemies::{Ability, Kit}, + damage::{Damage, DamageType, Penetration}, + stats::Buff, + status, +}; + +fn silenced(w: &mut World, id: Id) -> Result { + Ok(w.unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("silence")) +} +fn buff(key: &str, mods: &[(&str, f64)]) -> Buff { + let mut b = Buff::default(); + b.key = Some(key.into()); + b.mods = mods.iter().map(|&(k, v)| (k.into(), v)).collect(); + b +} +fn ability_damage(source: Option, target: Id, amount: f64, kind: DamageType) -> hit::Request { + let mut request = hit::Request::new( + health::Hit { + source, + credit: source, + target, + damage_type: kind, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Penetration::default(), + }, + ); + request.is_skill = true; + request.dodge_mode = crate::battle::injury::DodgeMode::Ignore; + request.tags = vec!["enemyAbility".into()]; + request +} +impl Host { + fn enemy_buff( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + b: Buff, + ) -> Result<(), String> { + r.add( + w, + self, + id, + buffs::Spec { + mods_present: !b.mods.is_empty(), + buff: b, + ..Default::default() + }, + )?; + Ok(()) + } + pub(super) fn enemy_content_hit( + &mut self, + w: &mut World, + q: &mut hit::Request, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + if q.cancelled || !q.is_attack { + return Ok(()); + } + let Some(id) = q.hit.source else { + return Ok(()); + }; + self.enemy_boss_hit(id, q); + self.enemy_special_hit(w, q, id)?; + self.enemy_terrain_hit(w, q, id)?; + self.enemy_rebirth_hit(w, r, q, id)?; + self.enemy_caster_hit(w, r, q, id)?; + self.enemy_leader_hit(w, r, q, id)?; + self.enemy_supporter_hit(w, q, id)?; + self.enemy_reaction_hit(w, r, q, id)?; + if matches!( + self.content.as_ref().unwrap().kit_ref(id), + Kit::Split(content::Split::Teapot { .. }) | Kit::Zone(content::ZoneKit::Cannon { .. }) + ) { + let centre = w.unit(q.hit.target)?.position; + let targets = spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + centre, + 1., + None, + false, + w.unit_capacity(), + )?; + for target in targets { + if target == q.hit.target + || w.unit(target)?.motion_fly + || !crate::battle::targeting::area_selectable(w, Some(id), target)? + { + continue; + } + let amount = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk"); + let mut splash = ability_damage(Some(id), target, amount, q.hit.damage_type); + splash.tags.push("splash".into()); + splash.dodge_mode = crate::battle::injury::DodgeMode::Normal; + self.enemy_damage(w, r, &mut splash)?; + } + } + if let Kit::Zone(content::ZoneKit::Tank(tank)) = self.content.as_ref().unwrap().kit_ref(id) + { + if !self.content.as_ref().unwrap().tank_skill(id) + && w.unit(id)?.blocked_by() == Some(q.hit.target) + { + q.damage.amount *= tank.melee; + } + } + match self.content.as_ref().unwrap().kit_ref(id) { + Kit::Family(content::Family::ShadowKiller { scale }) + if self.content.as_ref().unwrap().shadow_power(id) => + { + q.damage.amount *= scale; + } + Kit::Ability(Ability::FrozenPower(scale)) => { + if w.unit_mut(q.hit.target)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("freeze") + { + q.damage.amount *= scale; + } + } + Kit::Ability(Ability::Power { scale, .. }) + if self.content.as_ref().unwrap().triggered(id) => + { + q.damage.amount *= scale + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_content_taken( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + amount: f64, + ) -> Result<(), String> { + let id = q.hit.target; + if q.hit.damage_type != DamageType::Elemental { + self.helm_taken(w, r, id, q.hit.source, q.hit.credit, amount)?; + } + if q.hit.damage_type != DamageType::Elemental { + self.echo_taken(w, r, id, q.hit.source, q.hit.credit)?; + } + self.enemy_rebirth_taken(w, r, id)?; + self.enemy_caster_taken(w, r, id)?; + self.enemy_leader_taken(w, r, q, amount)?; + self.enemy_supporter_taken(w, r, id)?; + self.enemy_movement_taken(w, r, id)?; + self.enemy_reaction_taken(w, r, id)?; + let Kit::Ability(ability) = self.content.as_ref().unwrap().kit_ref(id) else { + return Ok(()); + }; + let ability = *ability; + let b = match ability { + Ability::Nucleus { speed, .. } => { + if !self.content.as_mut().unwrap().trigger_once(id) { + return Ok(()); + } + let mut b = buff("ab:combat", &[("moveMul", speed)]); + b.runtime.persist = true; + b.runtime.visible = true; + b + } + Ability::Expose { duration, scale } => { + if duration <= 0. || silenced(w, id)? { + return Ok(()); + } + let Some(source) = q.hit.source else { + return Ok(()); + }; + let u = w.unit(source)?; + if !u.stats.alive + || u.side != health::Side::Ally + || u.deployment.kind == crate::battle::deploy::Kind::Device + { + return Ok(()); + } + let mut b = buff("ab:exposed", &[("dmgTakenMul", scale)]); + b.runtime.duration = duration; + b.runtime.refresh = buffs::Refresh::Extend; + b.runtime.visible = true; + return self.enemy_buff(w, r, source, b); + } + Ability::LowHp(atk) => { + let s = &mut w.unit_mut(id)?.stats; + let hp = s.hp; + if hp / s.stats().map_err(str::to_string)?.n("maxHp") >= 0.5 + || !self.content.as_mut().unwrap().trigger_once(id) + { + return Ok(()); + } + let mut b = buff("ab:lowhp", &[("atkPct", atk)]); + b.runtime.persist = true; + b.runtime.visible = true; + b + } + Ability::Run(speed) if speed > 0. => { + if !self.content.as_mut().unwrap().trigger_once(id) { + return Ok(()); + } + let mut b = buff("ab:duckRun", &[("moveMul", 1. + speed)]); + b.runtime.persist = true; + b + } + Ability::DefDecay { max, def, res } if max > 0 => { + let mut b = buff( + "ab:defDecay", + &[("defFlat", def / max as f64), ("resFlat", res / max as f64)], + ); + b.runtime.persist = true; + b.runtime.refresh = buffs::Refresh::Stack; + b.runtime.max_stacks = max; + b + } + Ability::Song { + every, + duration, + aspd, + .. + } => { + if !self.content.as_mut().unwrap().counted(id, every) { + return Ok(()); + } + let ids = self.spawns.as_ref().unwrap().live().to_vec(); + for target in ids { + if !w.unit(target)?.stats.alive { + continue; + } + let mut b = buff("ab:songOfWar", &[("aspd", aspd)]); + b.runtime.duration = duration; + b.runtime.refresh = buffs::Refresh::Extend; + b.runtime.visible = true; + self.enemy_buff(w, r, target, b)?; + } + return Ok(()); + } + _ => return Ok(()), + }; + self.enemy_buff(w, r, id, b) + } + pub(super) fn enemy_content_attack( + &mut self, + event: enemy::Event, + c: &mut enemy::Context, + r: &mut buffs::Runtime, + w: &mut World, + grid: Option<&Grid>, + ) -> Result<(), String> { + let id = c.enemy; + self.enemy_catapult_attack(w, r, c, event)?; + if self.enemy_special_attack(w, r, c, event)? { + return Ok(()); + } + if self.enemy_caster_attack(w, r, c, event, grid)? { + return Ok(()); + } + self.helm_attack(w, c, event)?; + self.quintus_attack(w, c, event)?; + self.gun_attack(w, r, c, event)?; + self.enemy_terrain_attack(w, r, c, event)?; + self.enemy_leader_attack(w, r, c, event)?; + self.enemy_supporter_attack(w, r, c.enemy, event)?; + self.enemy_movement_attack(w, c, event)?; + self.enemy_lifecycle_attack(w, r, c, event)?; + self.enemy_reaction_attack(w, c, event)?; + self.enemy_zone_attack(w, c, event)?; + self.enemy_family_attack(event, c, r, w)?; + if event == enemy::Event::Attack { + self.enemy_split_attack(c, r, w)?; + } + if event == enemy::Event::BeforeAttack { + self.content.as_mut().unwrap().before_attack(id); + return Ok(()); + } + let ability = match self.content.as_ref().unwrap().kit_ref(id) { + Kit::Ability(ability) => Some(*ability), + _ => None, + }; + match ability { + Some(Ability::Stun { every, duration }) => { + if silenced(w, id)? + || !self.content.as_mut().unwrap().counted(id, every) + || duration <= 0. + { + return Ok(()); + } + for &target in &c.targets { + let u = w.unit(target)?; + if !u.stats.alive || !c.deployments.contains(&(target, u.deployment.deploy_seq)) + { + continue; + } + self.apply_status( + w, + r, + target, + "stun", + status::Options { + source: Some(id), + duration, + ..Default::default() + }, + )?; + } + } + Some(Ability::Power { every, .. }) => { + self.content.as_mut().unwrap().counted(id, every); + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_damage( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + request: &mut hit::Request, + ) -> Result<(), String> { + if request.damage.amount <= 0. { + return Ok(()); + } + let result = self.resolve_hit(w, r, request); + result.map(|_| ()) + } + pub(super) fn enemy_content_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + credit: Option, + ) -> Result<(), String> { + self.helm_death(w, r, id, credit)?; + self.pipe_death(w, r, id)?; + self.parasite_detach(w, r, id)?; + self.enemy_lifecycle_death(w, r, id)?; + self.enemy_reaction_death(w, r, id)?; + self.enemy_zone_death(w, id, credit)?; + self.enemy_teapot_death(w, r, id)?; + let Some((radius, scale, cold)) = (match self.content.as_ref().unwrap().kit_ref(id) { + Kit::Ability(Ability::DeathBoom { + radius, + scale, + cold, + }) => Some((*radius, *scale, *cold)), + _ => None, + }) else { + return Ok(()); + }; + if silenced(w, id)? { + return Ok(()); + } + let atk = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk"); + let radius = if radius > 0. { radius } else { 1.25 }; + let targets = enemy::Hooks::allies_in_radius(self, id, radius, w, w.unit_capacity())?; + for target in targets { + if w.unit(target)?.motion_fly + || !super::super::targeting::area_selectable(w, Some(id), target)? + { + continue; + } + let mut damage = ability_damage(Some(id), target, atk * scale, DamageType::Physical); + self.enemy_damage(w, r, &mut damage)?; + if let Some(duration) = cold { + if w.unit(target)?.stats.alive { + self.apply_status( + w, + r, + target, + "cold", + status::Options { + duration, + source: Some(id), + ..Default::default() + }, + )?; + } + } + } + Ok(()) + } + pub(super) fn enemy_content_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ids: &[Id], + dt: f64, + ) -> Result<(), String> { + self.enemy_sync_seeds(w, r, ids)?; + for &id in ids { + let mut content = self.content.take().ok_or("Missing enemy content context")?; + let result = content.tick(w, r, self, &[id], dt); + self.content = Some(content); + result?; + let u = w.unit(id)?; + if !u.stats.alive || u.enemy.carrier.is_some() { + continue; + } + let ability = match self.content.as_ref().unwrap().kit(id) { + Kit::Ability(ability) => ability, + Kit::Special(kit) => { + self.enemy_special_tick(w, r, id, kit, dt)?; + continue; + } + Kit::Terrain(kit) => { + self.enemy_terrain_tick(w, r, id, kit, dt)?; + continue; + } + Kit::Boss(boss) => { + if let Some(route) = w.unit_mut(id)?.motion.route.as_mut() { + if route.patrol + && route.legs().len() >= 2 + && route.leg >= route.legs().len() - 1 + { + route.leg = 0; + route.points = None; + route.wait_left = None; + } + } + self.enemy_boss_tick(w, r, id, boss, dt)?; + continue; + } + Kit::Caster(config) => { + self.enemy_caster_tick(w, r, id, config, dt)?; + continue; + } + Kit::Leader(kit) => { + self.enemy_leader_tick(w, r, id, kit, dt)?; + continue; + } + Kit::Supporter(kit) => { + self.enemy_supporter_tick(w, r, id, kit, dt)?; + continue; + } + Kit::Movement(kit) => { + self.enemy_movement_tick(w, r, id, kit, dt)?; + continue; + } + Kit::Lifecycle(kit) => { + self.enemy_lifecycle_tick(w, r, id, kit, dt)?; + continue; + } + Kit::Reaction(kit) => { + self.enemy_reaction_tick(w, r, id, kit, dt)?; + continue; + } + Kit::Split(split) => { + self.enemy_split_tick(w, r, id, split, dt)?; + continue; + } + Kit::Family(family) => { + self.enemy_family_tick(w, r, id, family, dt)?; + continue; + } + _ => continue, + }; + let interval = match ability { + Ability::Frost { .. } => { + if silenced(w, id)? { + continue; + } + 0.5 + } + Ability::Enhance { interval, .. } => interval, + Ability::SelfDamage(_) | Ability::Nest { .. } => 1., + Ability::Boil { interval, .. } => interval, + Ability::Nucleus { interval, .. } => interval, + _ => continue, + }; + let pulses = self.content.as_mut().unwrap().pulses(id, dt, interval); + for _ in 0..pulses { + if !w.unit(id)?.stats.alive { + break; + } + match ability { + Ability::Frost { radius, aspd } => { + let targets = + enemy::Hooks::allies_in_radius(self, id, radius, w, w.unit_capacity())?; + for target in targets { + let mut b = buff("ab:frost", &[("aspd", aspd)]); + b.runtime.duration = 0.6; + b.runtime.visible = true; + self.enemy_buff(w, r, target, b)?; + } + } + Ability::Enhance { speed, atk, .. } => { + if !self.content.as_mut().unwrap().enhance(id) { + continue; + } + let speed = speed * w.unit(id)?.stats.base_number("moveSpeed"); + let mut b = buff("ab:enhance", &[("moveFlat", speed), ("atkPct", atk)]); + b.runtime.persist = true; + b.runtime.refresh = buffs::Refresh::Stack; + b.runtime.max_stacks = 5; + self.enemy_buff(w, r, id, b)?; + } + Ability::Nucleus { radius, neural, .. } => { + if self.content.as_ref().unwrap().triggered(id) { + self.enemy_element_pulse(w, r, id, radius, neural)?; + } + } + Ability::Nest { .. } | Ability::Boil { .. } => { + self.enemy_dot_tick(w, r, id, ability)? + } + Ability::SelfDamage(amount) => { + let mut damage = ability_damage(None, id, amount, DamageType::True); + damage.is_skill = false; + damage.attack_type = hit::AttackType::Buff; + damage.tags = vec!["dot".into(), "periodic".into()]; + self.enemy_damage(w, r, &mut damage)?; + } + _ => unreachable!(), + } + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/bosses.rs b/crates/engine/src/battle/runtime/enemies/bosses.rs new file mode 100644 index 0000000..e68860a --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/bosses.rs @@ -0,0 +1,618 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::{ + bosses::{Lion, Memory}, + casters::{BuffEffect, Spell}, + Boss, + }, + targeting, +}; +mod ensemble; +mod gun; +mod quintus; +mod spawning; +mod tasks; +pub(in crate::battle::runtime) use tasks::BossTask; +mod helm; +pub(in crate::battle::runtime) use helm::{BLADE_RETURN, PART_DOT}; +pub(in crate::battle::runtime) const SURGE_TICK: u64 = 1712; +const EQUIPMENT: [&str; 3] = [ + "enemy_10028_vtswd", + "enemy_10029_vtshld", + "enemy_10030_vtwand", +]; +impl Host { + fn boss_config(&self, id: Id) -> Option { + match self.content.as_ref().unwrap().kit(id) { + Kit::Boss(b) => Some(b), + _ => None, + } + } + fn boss_targets(&mut self, w: &mut World, id: Id, radius: f64) -> Result, String> { + let mut targets = if radius.is_infinite() { + self.roster.as_ref().unwrap().ids().to_vec() + } else { + enemy::Hooks::allies_in_radius(self, id, radius, w, w.unit_capacity())? + }; + let mut out = vec![]; + for t in targets.drain(..) { + if targeting::can_target_ally(w, id, t, true, Default::default())? { + out.push(t); + } + } + Ok(out) + } + fn boss_area(&mut self, w: &mut World, id: Id) -> Result, String> { + let mut out = vec![]; + for t in self.roster.as_ref().unwrap().ids().to_vec() { + if targeting::area_selectable(w, Some(id), t)? { + out.push(t); + } + } + Ok(out) + } + fn lion_range(w: &World, id: Id) -> Result { + let radius = w.unit(id)?.stats.base_number("rangeRadius"); + Ok(if radius != 0. { radius } else { 3.4 }) + } + pub(super) fn boss_condition( + &mut self, + w: &mut World, + id: Id, + spell: Spell, + ) -> Result, String> { + if let Some(ready) = self.ensemble_condition(w, spell) { + return Ok(Some(ready)); + } + if let Some(ready) = self.quintus_condition(id, spell) { + return Ok(Some(ready)); + } + if let Some(ready) = self.gun_condition(w, id, spell)? { + return Ok(Some(ready)); + } + if let Some(ready) = self.helm_condition(w, id, spell)? { + return Ok(Some(ready)); + } + Ok(Some(match spell { + Spell::Decree { .. } => { + let Some(Boss::Lion(lion)) = self.boss_config(id) else { + return Err("Decree requires a lion kit".into()); + }; + let Memory::Lion { sp, .. } = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + sp >= lion.cost + && !self + .boss_targets(w, id, Self::lion_range(w, id)?)? + .is_empty() + } + Spell::Surge { .. } => !self.boss_targets(w, id, f64::INFINITY)?.is_empty(), + Spell::Repel { .. } => true, + _ => return Ok(None), + })) + } + pub(super) fn boss_fire( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + spell: Spell, + grid: Option<&Grid>, + ) -> Result<(), String> { + match spell { + spell @ (Spell::PipeStrike { .. } | Spell::Ensemble) => { + self.ensemble_fire(w, r, id, spell)? + } + spell @ (Spell::Tide { .. } + | Spell::Rockfall { .. } + | Spell::Tentacles { .. } + | Spell::Species { .. }) => self.quintus_fire(w, r, id, spell)?, + spell @ (Spell::GunCharge | Spell::SpringDash { .. }) => { + self.gun_fire(w, r, id, spell)? + } + spell @ (Spell::HelmShell | Spell::HelmDrones { .. } | Spell::BladeDive) => { + self.helm_fire(w, r, id, spell)? + } + Spell::Decree { scales } => self.lion_decree(w, r, id, scales, grid)?, + Spell::Repel { scale, loss } => { + for t in self.boss_area(w, id)? { + let amount = Self::tac_stat(w, id, "atk")? * scale; + let mut q = ability_damage(Some(id), t, amount, DamageType::Arts); + self.enemy_damage(w, r, &mut q)?; + } + self.lose_lp(loss)?; + } + Spell::Surge { + max, + duration, + scale, + } => { + let Some(Boss::Deer(deer)) = self.boss_config(id) else { + return Err("Surge requires a deer kit".into()); + }; + let Memory::Deer { low, .. } = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + let mut targets = self.boss_targets(w, id, f64::INFINITY)?; + targeting::sort_allies(w, id, &mut targets, Default::default())?; + for t in targets.into_iter().take(if low { deer.surge } else { max }) { + self.apply_status( + w, + r, + t, + "stun", + status::Options { + duration, + source: Some(id), + ..Default::default() + }, + )?; + let mut b = buff("boss:surge", &[]); + b.runtime.duration = duration; + b.runtime.interval = 1.; + b.runtime.visible = true; + b.runtime.source = Some(id); + b.runtime.tick_payload = scale; + b.runtime.on_tick = Some(SURGE_TICK); + r.add( + w, + self, + t, + buffs::Spec { + buff: b, + ..Default::default() + } + .retaining_unit(id), + )?; + } + } + _ => unreachable!(), + } + Ok(()) + } + fn lion_equipment(&self, w: &World) -> Result, String> { + let spawns = self.spawns.as_ref().unwrap(); + let mut out = vec![]; + for &t in spawns.live() { + if w.unit(t)?.stats.alive && EQUIPMENT.contains(&spawns.definition(t)?.key.as_str()) { + out.push(t); + } + } + out.sort_by_key(|&t| w.unit(t).unwrap().targeting.spawn_seq); + Ok(out) + } + fn lion_decree( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + scales: [f64; 2], + grid: Option<&Grid>, + ) -> Result<(), String> { + let targets = self.boss_targets(w, id, Self::lion_range(w, id)?)?; + let Some(target) = self.rng.pick(&targets).copied() else { + return Ok(()); + }; + let Memory::Lion { + advanced, + next_anim, + wand, + .. + } = self.content.as_ref().unwrap().boss(id) + else { + unreachable!() + }; + self.content.as_mut().unwrap().set_boss( + id, + Memory::Lion { + sp: 0., + advanced, + next_anim, + wand, + }, + ); + let tile = w.unit(target)?.deployment.tile; + for t in self.caster_cross_area(w, id, tile)? { + let amount = Self::tac_stat(w, id, "atk")? * scales[usize::from(advanced)]; + let mut q = ability_damage(Some(id), t, amount, DamageType::Physical); + self.enemy_damage(w, r, &mut q)?; + } + let equipment = self.lion_equipment(w)?; + let tiles = [ + tile, + [tile[0] + 1, tile[1]], + [tile[0] - 1, tile[1]], + [tile[0], tile[1] + 1], + [tile[0], tile[1] - 1], + ]; + let grid = grid + .or(self.grid.as_deref()) + .ok_or("Missing equipment grid")?; + let mut free = vec![]; + for p in tiles { + if !inside(grid.rect(), p) + || grid.tiles()[p[0] as usize * crate::battle::grid::COLS + p[1] as usize].height + != "LOW" + || !grid.ground_passable(p, false) + || self + .roster + .as_ref() + .unwrap() + .deployment() + .occupant(p) + .is_some() + { + continue; + } + if equipment.iter().any(|&t| { + w.unit(t) + .is_ok_and(|u| u.position.map(|v| (v + 0.5).floor() as i32) == p) + }) { + continue; + } + free.push(p); + } + if let Some(position) = self.rng.pick(&free).copied() { + let key = *self.rng.pick(&EQUIPMENT).unwrap(); + self.with_spawns(w, r, |spawns, context, world| { + spawns.spawn_part(world, context, key, position.map(|v| v as f64)) + })?; + self.rebuild_index(w)?; + } + Ok(()) + } + fn lion_animate( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + lion: Lion, + ) -> Result<(), String> { + let Memory::Lion { advanced, .. } = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + let store = lion.stores[usize::from(advanced)]; + let equipment = self.lion_equipment(w)?; + let count = if store.count == 0 { + equipment.len() + } else { + store.count + }; + for &item in equipment.iter().skip(equipment.len().saturating_sub(count)) { + match self.spawns.as_ref().unwrap().definition(item)?.key.as_str() { + "enemy_10028_vtswd" => { + let targets = self.boss_targets(w, id, Self::lion_range(w, id)?)?; + if let Some(t) = self.rng.pick(&targets).copied() { + let amount = Self::tac_stat(w, id, "atk")? * store.scale; + let mut q = ability_damage(Some(id), t, amount, DamageType::Physical); + self.enemy_damage(w, r, &mut q)?; + } + } + "enemy_10029_vtshld" => { + let dx = w.unit(item)?.position[1] - w.unit(id)?.position[1]; + let side = if dx == 0. { -1. } else { dx.signum() }; + let mut b = buff("boss:vest", &[]); + b.shield = store.shield; + b.runtime.persist = true; + b.runtime.visible = true; + b.runtime.enemy_effect = Some(BuffEffect::Vest { + side, + cut: store.cut, + }); + self.enemy_buff(w, r, id, b)?; + } + "enemy_10030_vtwand" => { + let Memory::Lion { + sp, + advanced, + next_anim, + .. + } = self.content.as_ref().unwrap().boss(id) + else { + unreachable!() + }; + self.content.as_mut().unwrap().set_boss( + id, + Memory::Lion { + sp, + advanced, + next_anim, + wand: true, + }, + ); + } + _ => unreachable!(), + } + self.kill_enemy(item, None, r, w)?; + } + Ok(()) + } + pub(super) fn enemy_boss_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + boss: Boss, + dt: f64, + ) -> Result<(), String> { + match boss { + Boss::Pipe(config) => self.pipe_tick(w, r, id, config, dt)?, + Boss::Echo(config) => self.enemy_caster_tick(w, r, id, config.caster, dt)?, + Boss::Quintus(config) => self.quintus_tick(w, r, id, config, dt)?, + Boss::Gun(config) => self.gun_tick(w, r, id, config, dt)?, + Boss::Spring(config) => self.spring_tick(w, r, id, config, dt)?, + Boss::Helm(_) | Boss::Blade(_) | Boss::Shell { .. } => { + self.helm_tick(w, r, id, boss, dt)? + } + Boss::Equipment => {} + Boss::Lion(lion) => { + let Memory::Lion { + mut sp, + mut advanced, + mut next_anim, + wand, + } = self.content.as_ref().unwrap().boss(id) + else { + unreachable!() + }; + if !advanced + && w.unit(id)?.stats.hp / Self::tac_stat(w, id, "maxHp")? <= lion.advance + { + advanced = true; + let mut b = buff( + "boss:advance", + &[("defPct", lion.defense), ("resFlat", lion.resistance)], + ); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + if self.enemy_can_cast(w, id, false)? { + sp += dt; + if self.lion_equipment(w)?.is_empty() { + next_anim = None; + } else { + let deadline = *next_anim.get_or_insert(w.time + 2.); + if w.time >= deadline { + self.content.as_mut().unwrap().set_boss( + id, + Memory::Lion { + sp, + advanced, + next_anim, + wand, + }, + ); + self.lion_animate(w, r, id, lion)?; + let Memory::Lion { wand: armed, .. } = + self.content.as_ref().unwrap().boss(id) + else { + unreachable!() + }; + next_anim = + Some(w.time + if lion.cost.is_finite() { lion.cost } else { 2. }); + self.content.as_mut().unwrap().set_boss( + id, + Memory::Lion { + sp, + advanced, + next_anim, + wand: armed, + }, + ); + return self.enemy_caster_tick(w, r, id, lion.caster, dt); + } + } + } + self.content.as_mut().unwrap().set_boss( + id, + Memory::Lion { + sp, + advanced, + next_anim, + wand, + }, + ); + self.enemy_caster_tick(w, r, id, lion.caster, dt)?; + } + Boss::Deer(deer) => { + let Memory::Deer { + mut low, + mut acc, + held_until, + } = self.content.as_ref().unwrap().boss(id) + else { + unreachable!() + }; + if !low && w.unit(id)?.stats.hp / Self::tac_stat(w, id, "maxHp")? < 0.5 { + low = true; + let mut b = buff( + "boss:madness", + &[ + ("physTakenMul", 1. - deer.resistance), + ("artsTakenMul", 1. - deer.resistance), + ], + ); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + if self.enemy_can_cast(w, id, false)? { + acc += dt; + if acc >= Self::tac_stat(w, id, "interval")? && w.time >= held_until { + let mut targets = self.boss_targets(w, id, f64::INFINITY)?; + targeting::sort_allies(w, id, &mut targets, Default::default())?; + if !targets.is_empty() { + acc = 0.; + self.content.as_mut().unwrap().set_boss( + id, + Memory::Deer { + low, + acc, + held_until, + }, + ); + if let Some(clip) = self.caster_turn(w, r, id, false, None)? { + self.content.as_mut().unwrap().set_boss( + id, + Memory::Deer { + low, + acc, + held_until: w.time + clip, + }, + ); + return self.enemy_caster_tick(w, r, id, deer.caster, dt); + } + let mut columns = vec![]; + for t in targets { + let col = w.unit(t)?.deployment.tile[1]; + if !columns.contains(&col) { + columns.push(col); + } + if columns.len() >= if low { deer.columns } else { 1 } { + break; + } + } + for col in columns { + for t in self.boss_area(w, id)? { + if w.unit(t)?.deployment.tile[1] != col { + continue; + } + let amount = Self::tac_stat(w, id, "atk")?; + let mut q = + ability_damage(Some(id), t, amount, DamageType::Physical); + q.is_attack = true; + q.is_skill = false; + q.dodge_mode = crate::battle::injury::DodgeMode::Normal; + q.tags.clear(); + self.enemy_damage(w, r, &mut q)?; + } + } + let now = w.time; + let u = w.unit_mut(id)?; + u.last_attack_at = now; + u.attacks += 1; + } + } + } + self.content.as_mut().unwrap().set_boss( + id, + Memory::Deer { + low, + acc, + held_until, + }, + ); + self.enemy_caster_tick(w, r, id, deer.caster, dt)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_boss_profile(&self, kit: &Kit, p: &mut enemy::Profile) { + self.helm_profile(kit, p); + match kit { + Kit::Boss(Boss::Quintus(_)) => p.max_targets = 2., + Kit::Boss(Boss::Deer(_) | Boss::Pipe(_)) => p.no_attack = true, + _ => {} + } + } + pub(super) fn enemy_boss_hit(&self, id: Id, q: &mut hit::Request) { + if matches!(self.boss_config(id), Some(Boss::Helm(_))) + && q.hit.damage_type != DamageType::Elemental + { + q.hit.damage_type = DamageType::Arts; + } + if matches!( + self.content.as_ref().unwrap().boss(id), + Memory::Lion { wand: true, .. } + ) { + q.hit.damage_type = DamageType::Arts; + } + } + pub(in crate::battle::runtime) fn enemy_boss_in( + &self, + w: &World, + q: &mut hit::Request, + ) -> Result<(), String> { + if let Some(source) = q.hit.source { + if let Some(b) = w + .unit(q.hit.target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("boss:vest") && b.shield > 0.) + { + if let Some(BuffEffect::Vest { side, cut }) = b.runtime.enemy_effect { + let dx = w.unit(source)?.position[1] - w.unit(q.hit.target)?.position[1]; + if dx != 0. && dx.signum() == side { + q.damage.mul *= 1. - cut; + } + } + } + } + Ok(()) + } + pub(super) fn enemy_boss_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + target: Id, + ) -> Result<(), String> { + self.gun_dealt(w, r, id, target)?; + self.quintus_dealt(w, r, id, target)?; + let Memory::Lion { + sp, + advanced, + next_anim, + wand: true, + } = self.content.as_ref().unwrap().boss(id) + else { + return Ok(()); + }; + self.content.as_mut().unwrap().set_boss( + id, + Memory::Lion { + sp, + advanced, + next_anim, + wand: false, + }, + ); + let raw = &self.data.table("enemies").unwrap()["enemy_10030_vtwand"]; + let duration = raw["talents"]["bb"]["1.disarmed_duration"] + .as_f64() + .or_else(|| raw["talent"]["1.disarmed_duration"].as_f64()) + .unwrap_or(0.); + if duration > 0. { + self.apply_status( + w, + r, + target, + "disarm", + status::Options { + duration, + source: Some(id), + ..Default::default() + }, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_surge_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + let b = r.get(w, c.unit, c.buff)?; + let source = b.runtime.source.ok_or("Missing surge source")?; + let scale = b.runtime.tick_payload; + let amount = Self::tac_stat(w, source, "atk")? * scale; + let mut q = ability_damage(Some(source), c.unit, amount, DamageType::Arts); + q.is_skill = false; + q.ignore_select = true; + self.enemy_damage(w, r, &mut q) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/bosses/ensemble.rs b/crates/engine/src/battle/runtime/enemies/bosses/ensemble.rs new file mode 100644 index 0000000..b99cda4 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/bosses/ensemble.rs @@ -0,0 +1,359 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::bosses::{ensemble, EchoForm, Pipe}, + element::Element, +}; +use crate::deterministic::math::hypot; +#[derive(Clone, Copy)] +pub(super) struct AreaStrike { + pub position: [f64; 2], + pub radius: f64, + pub scale: f64, + pub element: Element, + pub ratio: f64, + pub attack: Option, +} +impl Host { + pub(super) fn boss_arts_area( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + strike: AreaStrike, + ) -> Result<(), String> { + for target in self.boss_area(w, id)? { + let p = w.unit(target)?.position; + if hypot(p[1] - strike.position[1], p[0] - strike.position[0]) > strike.radius { + continue; + } + let atk = match strike.attack { + Some(atk) => atk, + None => Self::tac_stat(w, id, "atk")?, + }; + let mut q = ability_damage(Some(id), target, atk * strike.scale, DamageType::Arts); + self.enemy_damage(w, r, &mut q)?; + let atk = match strike.attack { + Some(atk) => atk, + None => Self::tac_stat(w, id, "atk")?, + }; + self.enemy_element(w, r, id, target, strike.element, atk * strike.ratio)?; + } + Ok(()) + } + fn echoes(&self, w: &World, form: EchoForm) -> Vec { + self.spawns.as_ref().unwrap().live().iter().copied().filter(|&target| { + w.unit(target).is_ok_and(|unit|unit.stats.alive) + && matches!(self.content.as_ref().unwrap().boss(target),Memory::Echo(state) if state.form==form) + }).collect() + } + pub(in crate::battle::runtime) fn echo_form( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + form: EchoForm, + ) -> Result<(), String> { + let Some(Boss::Echo(config)) = self.boss_config(id) else { + return Ok(()); + }; + let Memory::Echo(mut state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + state.form = form; + state.strikes = 0; + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Echo(state)); + self.enemy_buff(w, r, id, ensemble::form_buff(config, form)) + } + pub(in crate::battle::runtime) fn echo_hit( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Some(Boss::Echo(config)) = self.boss_config(id) else { + return Ok(()); + }; + if !w.unit(id)?.stats.alive { + return Ok(()); + } + let Memory::Echo(mut state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + if state.pulses.len() >= w.unit_capacity() { + return Err("Echo pulse capacity exceeded".into()); + } + state.pulses.push_back(Self::tac_stat(w, id, "atk")?); + let active = state.pulsing; + state.pulsing = true; + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Echo(state)); + if active { + return Ok(()); + } + let result = (|| { + loop { + let Memory::Echo(mut state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + let Some(atk) = state.pulses.pop_front() else { + break; + }; + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Echo(state)); + self.boss_arts_area( + w, + r, + id, + AreaStrike { + position: w.unit(id)?.position, + radius: 1.6, + scale: config.pulse, + element: Element::Apoptosis, + ratio: config.element, + attack: Some(atk), + }, + )?; + let Memory::Echo(mut state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + state.strikes = state + .strikes + .checked_add(1) + .ok_or("Echo strike count exhausted")?; + let need = config.strikes[usize::from(state.form == EchoForm::Gold)]; + let switch = w.unit(id)?.stats.alive && need > 0. && state.strikes as f64 >= need; + let next = if state.form == EchoForm::Gold { + EchoForm::Dark + } else { + EchoForm::Gold + }; + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Echo(state)); + if switch { + self.echo_form(w, r, id, next)?; + } + } + Ok(()) + })(); + let Memory::Echo(mut state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + state.pulsing = false; + state.pulses.clear(); + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Echo(state)); + result + } + pub(in crate::battle::runtime) fn echo_taken( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + source: Option, + credit: Option, + ) -> Result<(), String> { + if source + .or(credit) + .is_some_and(|t| w.unit(t).is_ok_and(|u| u.side == health::Side::Ally)) + { + self.echo_hit(w, r, id)?; + } + Ok(()) + } + pub(super) fn ensemble_condition(&self, w: &World, spell: Spell) -> Option { + match spell { + Spell::PipeStrike { gold, .. } => Some( + !self + .echoes(w, if gold { EchoForm::Gold } else { EchoForm::Dark }) + .is_empty(), + ), + Spell::Ensemble => Some(true), + _ => None, + } + } + pub(super) fn ensemble_fire( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + spell: Spell, + ) -> Result<(), String> { + match spell { + Spell::Ensemble => { + let Some(Boss::Echo(config)) = self.boss_config(id) else { + unreachable!() + }; + let Memory::Echo(state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + self.boss_arts_area( + w, + r, + id, + AreaStrike { + position: w.unit(id)?.position, + radius: if state.form == EchoForm::Gold { + 0.8 + } else { + 1.6 + }, + scale: 1., + element: Element::Apoptosis, + ratio: config.ensemble[usize::from(state.form == EchoForm::Gold)], + attack: None, + }, + )?; + } + Spell::PipeStrike { + gold, + radius, + element, + } => { + for echo in self.echoes(w, if gold { EchoForm::Gold } else { EchoForm::Dark }) { + if gold { + self.boss_arts_area( + w, + r, + id, + AreaStrike { + position: w.unit(echo)?.position, + radius, + scale: 1., + element: Element::Apoptosis, + ratio: element, + attack: None, + }, + )?; + self.echo_form(w, r, echo, EchoForm::Dark)?; + } else { + for k in 0..3 { + self.enemy_schedule( + w, + Some(id), + k as f64 * 0.4, + 0., + 1, + EnemyTask::Boss(BossTask::Pipe { + echo, + radius, + element, + }), + )?; + } + } + } + } + _ => unreachable!(), + } + Ok(()) + } + pub(super) fn pipe_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Pipe, + dt: f64, + ) -> Result<(), String> { + let Memory::Pipe { + mut acc, + mut attack, + mut held_until, + } = self.content.as_ref().unwrap().boss(id) + else { + unreachable!() + }; + acc += dt; + let low = w.unit(id)?.stats.hp / Self::tac_stat(w, id, "maxHp")? < config.threshold; + if acc >= config.intervals[usize::from(low)] { + acc = 0.; + let key = self + .content + .as_ref() + .unwrap() + .child(id) + .unwrap_or_else(|| Arc::from("enemy_9023_acdums")); + for t in self.boss_spawn_branch(w, r, id, "summon_enemy", &key, Value::Null, "WALK")? { + if config.gold { + self.echo_form(w, r, t, EchoForm::Gold)?; + } + } + } + if self.enemy_can_cast(w, id, false)? { + attack += dt; + if attack >= Self::tac_stat(w, id, "interval")? && w.time >= held_until { + let form = if config.gold { + EchoForm::Gold + } else { + EchoForm::Dark + }; + let targets = self.echoes(w, form); + if let Some(&target) = self.rng.pick(&targets) { + attack = 0.; + self.content.as_mut().unwrap().set_boss( + id, + Memory::Pipe { + acc, + attack, + held_until, + }, + ); + if let Some(clip) = self.caster_turn(w, r, id, false, None)? { + held_until = w.time + clip; + } else { + let now = w.time; + let u = w.unit_mut(id)?; + u.last_attack_at = now; + u.attacks += 1; + self.echo_hit(w, r, target)?; + } + } + } + } + self.content.as_mut().unwrap().set_boss( + id, + Memory::Pipe { + acc, + attack, + held_until, + }, + ); + self.enemy_caster_tick(w, r, id, config.caster, dt) + } + pub(in crate::battle::runtime::enemies) fn pipe_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if matches!( + self.boss_config(id), + Some(Boss::Pipe(Pipe { gold: false, .. })) + ) { + let ids = self.spawns.as_ref().unwrap().live().to_vec(); + for t in ids { + if w.unit(t)?.stats.alive + && matches!( + self.boss_config(t), + Some(Boss::Pipe(Pipe { gold: true, .. })) + ) + { + self.kill_enemy(t, None, r, w)?; + } + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/bosses/gun.rs b/crates/engine/src/battle/runtime/enemies/bosses/gun.rs new file mode 100644 index 0000000..f764076 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/bosses/gun.rs @@ -0,0 +1,362 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::bosses::{ + gun::{Charge, Dash}, + Gun, SpringKind, + }, + element::Element, +}; +use crate::deterministic::math::hypot; +mod springs; +impl Host { + fn gun_companions(&self, w: &World, id: Id, springs_only: bool) -> Vec { + self.spawns + .as_ref() + .unwrap() + .live() + .iter() + .copied() + .filter(|&t| { + t != id + && w.unit(t).is_ok_and(|u| u.stats.alive) + && match self.boss_config(t) { + Some(Boss::Spring(_)) => true, + Some(Boss::Gun(_)) => !springs_only, + _ => false, + } + }) + .collect() + } + fn gun_defense_targets( + &mut self, + w: &mut World, + id: Id, + ground: bool, + ) -> Result, String> { + let radius = w.unit(id)?.stats.base_number("rangeRadius"); + let mut targets = self.boss_targets( + w, + id, + if ground { + f64::INFINITY + } else if radius != 0. { + radius + } else { + 2. + }, + )?; + if ground { + targets.retain(|&t| w.unit(t).unwrap().ground); + } + targeting::sort_allies(w, id, &mut targets, Default::default())?; + let mut keyed = vec![]; + for t in targets { + keyed.push((t, Self::tac_stat(w, t, "def")?)); + } + keyed.sort_by(|a, b| b.1.total_cmp(&a.1)); + Ok(keyed.into_iter().map(|x| x.0).collect()) + } + pub(super) fn gun_condition( + &mut self, + w: &mut World, + id: Id, + spell: Spell, + ) -> Result, String> { + Ok(Some(match spell { + Spell::GunCharge => { + matches!(self.content.as_ref().unwrap().boss(id), Memory::Gun(s) if s.charge.is_none()) + && !self.gun_defense_targets(w, id, true)?.is_empty() + } + Spell::SpringDash { .. } => !self.gun_companions(w, id, true).is_empty(), + _ => return Ok(None), + })) + } + pub(super) fn gun_fire( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + spell: Spell, + ) -> Result<(), String> { + match spell { + Spell::GunCharge => { + let Some(Boss::Gun(config)) = self.boss_config(id) else { + unreachable!() + }; + if let Some(&target) = self.gun_defense_targets(w, id, true)?.first() { + let Memory::Gun(mut state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + state.charge = Some(Charge { + target: w.unit(target)?.position, + until: w.time + config.duration, + hit: vec![], + }); + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Gun(state)); + let mut b = buff("boss:charge", &[]); + b.runtime.duration = config.duration; + b.runtime.visible = true; + b.flags.extend(["noMove", "disarm"].map(str::to_string)); + self.enemy_buff(w, r, id, b)?; + } + } + Spell::SpringDash { duration, mul } => { + for t in self.gun_companions(w, id, true) { + let Memory::Spring(mut state) = self.content.as_ref().unwrap().boss(t) else { + unreachable!() + }; + state.dash = Some(Dash { + gun: id, + until: w.time + duration, + mul, + hit: vec![], + }); + self.content + .as_mut() + .unwrap() + .set_boss(t, Memory::Spring(state)); + let mut b = buff("boss:dash", &[]); + b.runtime.duration = duration; + b.runtime.visible = true; + b.flags.extend( + ["invulnerable", "noMove", "unblockable", "disarm"].map(str::to_string), + ); + self.enemy_buff(w, r, t, b)?; + } + } + _ => unreachable!(), + } + Ok(()) + } + fn gun_aspd( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Gun, + stacks: u32, + ) -> Result<(), String> { + if config.raw_aspd { + let mut b = buff( + "boss:aspd", + &[( + "aspd", + (config.step * stacks as f64).max(20.) - w.unit(id)?.stats.base_number("aspd"), + )], + ); + b.runtime.persist = true; + self.enemy_buff(w, r, id, b)?; + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn gun_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: &mut enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + let id = c.enemy; + if let Some(Boss::Spring(config)) = self.boss_config(id) { + return self.spring_attack(w, r, c, event, config); + } + let Some(Boss::Gun(config)) = self.boss_config(id) else { + return Ok(()); + }; + if event == enemy::Event::BeforeAttack { + if let Some(&t) = self.gun_defense_targets(w, id, false)?.first() { + c.targets = vec![t]; + } + } else { + let Memory::Gun(mut state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + let target = c.targets.first().copied(); + state.stacks = if target == state.last { + state.stacks.saturating_add(1).min(config.max) + } else { + 0 + }; + state.last = target; + self.gun_aspd(w, r, id, config, state.stacks)?; + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Gun(state)); + } + Ok(()) + } + pub(in crate::battle::runtime) fn gun_confession( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Some(Boss::Gun(config)) = self + .boss_config(id) + .filter(|b| matches!(b, Boss::Gun(Gun { hidden: true, .. }))) + else { + return Ok(()); + }; + if self.gun_companions(w, id, false).is_empty() { + r.remove(w, self, id, "boss:confession")?; + } else { + let mut b = buff( + "boss:confession", + &[ + ("physTakenMul", config.confession), + ("artsTakenMul", config.confession), + ], + ); + b.runtime.duration = 0.35; + self.enemy_buff(w, r, id, b)?; + } + Ok(()) + } + fn gun_step(w: &mut World, id: Id, target: [f64; 2], speed: f64) -> Result { + let origin = w.unit(id)?.position; + let d = [target[0] - origin[0], target[1] - origin[1]]; + let len = hypot(d[1], d[0]); + if len <= speed + 1e-9 { + w.unit_mut(id)?.position = target; + return Ok(true); + } + w.unit_mut(id)?.position = [ + origin[0] + d[0] / len * speed, + origin[1] + d[1] / len * speed, + ]; + Ok(false) + } + fn gun_trample( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + hit: &mut Vec, + scale: f64, + ) -> Result<(), String> { + let origin = w.unit(id)?.position; + for t in self.boss_area(w, id)? { + let pos = w.unit(t)?.position; + if hypot(pos[1] - origin[1], pos[0] - origin[0]) <= 0.35 && !hit.contains(&t) { + if hit.len() >= w.unit_capacity() { + return Err("Trample target capacity exceeded".into()); + } + hit.push(t); + let mut q = ability_damage( + Some(id), + t, + Self::tac_stat(w, id, "atk")? * scale, + DamageType::Physical, + ); + self.enemy_damage(w, r, &mut q)?; + } + } + Ok(()) + } + pub(super) fn gun_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Gun, + dt: f64, + ) -> Result<(), String> { + let Memory::Gun(mut state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + if w.time >= w.unit(id)?.motion.unbalance_until - 1e-9 { + if let Some(mut charge) = state.charge.take() { + let old = w.unit(id)?.position; + let speed = (Self::tac_stat(w, id, "moveSpeed")? + config.speed) * 0.5 * dt; + let arrived = Self::gun_step(w, id, charge.target, speed)?; + let pos = w.unit(id)?.position.map(|v| (v + 0.5).floor() as i32); + if !self + .grid + .as_ref() + .ok_or("Missing charge grid")? + .ground_passable(pos, false) + { + w.unit_mut(id)?.position = old; + } + self.gun_trample(w, r, id, &mut charge.hit, config.scale)?; + if arrived || w.time >= charge.until || w.unit(id)?.position == old { + r.remove(w, self, id, "boss:charge")?; + if let Some(route) = w.unit_mut(id)?.motion.route.as_mut() { + route.points = None; + } + } else { + state.charge = Some(charge); + } + } + } + if config.hidden && self.content.as_mut().unwrap().pulses(id, dt, 0.25) > 0 { + self.gun_confession(w, r, id)?; + } + if let Some([interval, damage]) = config.link { + let mut pulses = 1; + if interval > 0. { + state.link_acc += dt; + pulses = 0; + while state.link_acc >= interval - 1e-9 && pulses < 4 { + state.link_acc -= interval; + pulses += 1; + } + } + for _ in 0..pulses { + let start = w.unit(id)?.position; + for t in self.gun_companions(w, id, true) { + let end = w.unit(t)?.position; + for a in self.roster.as_ref().unwrap().ids().to_vec() { + let u = w.unit(a)?; + if !u.stats.alive || !u.deployed { + continue; + } + let p = u.position; + let d = [end[0] - start[0], end[1] - start[1]]; + let len = d[0] * d[0] + d[1] * d[1]; + let along = if len == 0. { + 0. + } else { + ((p[0] - start[0]) * d[0] + (p[1] - start[1]) * d[1]) / len + } + .clamp(0., 1.); + if hypot( + p[1] - start[1] - along * d[1], + p[0] - start[0] - along * d[0], + ) <= 0.5 + { + let mut q = ability_damage(Some(id), a, damage, DamageType::Physical); + q.ignore_select = true; + q.tags.push("faithLink".into()); + self.enemy_damage(w, r, &mut q)?; + } + } + } + } + } + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Gun(state)); + self.rebuild_index(w)?; + self.enemy_caster_tick(w, r, id, config.caster, dt) + } + pub(super) fn gun_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + target: Id, + ) -> Result<(), String> { + if let Some(Boss::Gun(config)) = self.boss_config(id) { + let amount = Self::tac_stat(w, id, "atk")? * config.erosion; + self.enemy_element(w, r, id, target, Element::Erosion, amount)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/bosses/gun/springs.rs b/crates/engine/src/battle/runtime/enemies/bosses/gun/springs.rs new file mode 100644 index 0000000..90b4d8c --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/bosses/gun/springs.rs @@ -0,0 +1,372 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::bosses::{ + gun::{self, SPRING_SHIELD}, + Spring, + }, + injury, +}; +impl Host { + fn spring_drop(&mut self, w: &mut World, r: &mut buffs::Runtime, id: Id) -> Result<(), String> { + let Memory::Spring(mut s) = self.content.as_ref().unwrap().boss(id) else { + return Ok(()); + }; + s.up = false; + s.down_at = Some(w.time); + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Spring(s)); + r.remove(w, self, id, "boss:springShield")?; + Ok(()) + } + pub(in crate::battle::runtime) fn spring_injury( + event: &mut injury::InjuryEvent, + c: &mut settlement::Context<'_, Self>, + ) -> Result<(), String> { + let id = c.request.hit.target; + let Some(Boss::Spring(config)) = c.host.boss_config(id) else { + return Ok(()); + }; + if !matches!(c.host.content.as_ref().unwrap().boss(id),Memory::Spring(s) if s.up) { + return Ok(()); + } + let kind = c.request.hit.damage_type; + if (config.kind == SpringKind::Arts + && kind == DamageType::Physical + && c.request.attack_type == hit::AttackType::Normal) + || (config.kind == SpringKind::Element + && matches!(kind, DamageType::Physical | DamageType::Arts)) + { + event.amount *= config.scale; + } + Ok(()) + } + pub(in crate::battle::runtime) fn spring_observe( + token: u64, + event: injury::Observation, + c: &mut settlement::Context<'_, Self>, + ) -> Result<(), String> { + let id = c.request.hit.target; + if token != SPRING_SHIELD { + return c.host.spring_transfer( + c.world, + c.runtime, + id, + c.request.hit.source, + c.request.hit.credit, + event.amount, + event.cancelled, + ); + } + let Some(Boss::Spring(config)) = c.host.boss_config(id) else { + return Ok(()); + }; + if !matches!(c.host.content.as_ref().unwrap().boss(id),Memory::Spring(s) if s.up) { + return Ok(()); + } + let b = c.runtime.get(c.world, id, c.buff)?; + if (config.kind == SpringKind::Arts && b.shield <= 1e-6) + || (config.kind == SpringKind::Hits && b.runtime.shield_hits == 0) + { + return c.host.spring_drop(c.world, c.runtime, id); + } + if config.kind != SpringKind::Arts + || c.request.hit.damage_type != DamageType::Physical + || c.request.attack_type != hit::AttackType::Normal + { + return Ok(()); + } + let Some(source) = c + .request + .hit + .source + .filter(|&s| c.world.unit(s).is_ok_and(|u| u.stats.alive)) + else { + return Ok(()); + }; + let mut q = ability_damage( + None, + source, + Self::tac_stat(c.world, id, "atk")? * config.counter, + DamageType::Physical, + ); + q.hit.credit = Some(id); + q.hit.on_applied = true; + q.attack_type = hit::AttackType::Addition; + q.ignore_select = true; + q.tags = vec!["springCounter".into()]; + c.resolve(&mut q)?; + Ok(()) + } + pub(in crate::battle::runtime) fn spring_transfer( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + source: Option, + credit: Option, + amount: f64, + cancelled: bool, + ) -> Result<(), String> { + if !(amount > 0.) || cancelled { + return Ok(()); + } + let credit = source + .or(credit) + .filter(|&t| w.unit(t).is_ok_and(|u| u.side == health::Side::Ally)); + let mut guns = self + .gun_companions(w, id, false) + .into_iter() + .filter(|&t| matches!(self.boss_config(t), Some(Boss::Gun(_)))) + .collect::>(); + targeting::sort_allies( + w, + id, + &mut guns, + targeting::Profile { + block_free: true, + ..Default::default() + }, + )?; + let mut targets = vec![]; + if let Some(&g) = guns.first() { + targets.push((g, amount)); + } + let others = self.gun_companions(w, id, true); + for &t in &others { + targets.push((t, amount / others.len() as f64)); + } + for (target, amount) in targets { + self.lose_hp_with_credit( + w, + r, + health::Hit { + source: None, + credit, + target, + damage_type: DamageType::True, + no_sp: true, + silent: false, + hp_loss: true, + on_applied: false, + }, + amount, + false, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn spring_modifier( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + source: Option, + credit: Option, + amount: f64, + ) -> Result<(), String> { + if matches!( + self.boss_config(id), + Some(Boss::Spring(Spring { + kind: SpringKind::Arts, + .. + })) + ) { + self.spring_transfer(w, r, id, source, credit, amount, false)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn spring_element_burst( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if matches!( + self.boss_config(id), + Some(Boss::Spring(Spring { + kind: SpringKind::Element, + .. + })) + ) && matches!(self.content.as_ref().unwrap().boss(id),Memory::Spring(s) if s.up) + { + self.spring_drop(w, r, id)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn spring_counter_applied( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + ) -> Result<(), String> { + if q.tags.iter().any(|s| s == "springCounter") { + if let Some(id) = q.hit.credit { + if let Some(Boss::Spring(config)) = self.boss_config(id) { + let mut effect = crate::battle::element::Request::new( + Some(id), + Some(id), + q.hit.target, + Element::Erosion, + Self::tac_stat(w, id, "atk")? * config.erosion, + ); + effect.damage.ignore_select = true; + effect.damage.tags = vec!["springCounter".into()]; + crate::battle::element::apply(w, self, r, &mut effect)?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime::enemies::bosses) fn spring_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Spring, + dt: f64, + ) -> Result<(), String> { + let Memory::Spring(mut s) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + if !s.up && s.down_at.is_some_and(|at| w.time - at >= config.regen) { + s.up = true; + let b = gun::spring_shield(w, id, config)?; + self.enemy_buff(w, r, id, b)?; + } + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Spring(s.clone())); + if w.time >= w.unit(id)?.motion.unbalance_until - 1e-9 { + if let Some(mut dash) = s.dash.take() { + let gun = if w.unit(dash.gun).is_ok_and(|u| u.stats.alive) { + Some(dash.gun) + } else { + let p = w.unit(id)?.position; + let mut guns = self + .gun_companions(w, id, false) + .into_iter() + .filter(|&t| matches!(self.boss_config(t), Some(Boss::Gun(_)))) + .collect::>(); + guns.sort_by(|&a, &b| { + let a = w.unit(a).unwrap().position; + let b = w.unit(b).unwrap().position; + hypot(a[1] - p[1], a[0] - p[0]).total_cmp(&hypot(b[1] - p[1], b[0] - p[0])) + }); + guns.first().copied() + }; + if let Some(g) = gun { + let speed = Self::tac_stat(w, id, "moveSpeed")? * dash.mul * 0.5 * dt; + Self::gun_step(w, id, w.unit(g)?.position, speed)?; + } + self.gun_trample(w, r, id, &mut dash.hit, 1.)?; + if w.time >= dash.until { + r.remove(w, self, id, "boss:dash")?; + if let Some(route) = w.unit_mut(id)?.motion.route.as_mut() { + route.points = None; + } + } else { + s.dash = Some(dash) + } + } + } + let Memory::Spring(mut current) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + current.dash = s.dash; + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Spring(current)); + self.rebuild_index(w) + } + pub(super) fn spring_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: &mut enemy::Context, + event: enemy::Event, + config: Spring, + ) -> Result<(), String> { + if event != enemy::Event::Attack { + return Ok(()); + } + let Some(every) = config.every else { + return Ok(()); + }; + let Memory::Spring(mut s) = self.content.as_ref().unwrap().boss(c.enemy) else { + unreachable!() + }; + if !s.up { + return Ok(()); + } + s.attacks = (s.attacks + 1) % every; + let fire = s.attacks == 0; + self.content + .as_mut() + .unwrap() + .set_boss(c.enemy, Memory::Spring(s)); + if !fire { + return Ok(()); + } + let Some(&first) = c + .targets + .iter() + .find(|&&t| w.unit(t).is_ok_and(|u| u.stats.alive)) + else { + return Ok(()); + }; + let atk = Self::tac_stat(w, c.enemy, "atk")?; + if config.kind == SpringKind::Hits { + for _ in 0..10 { + if !w.unit(first)?.stats.alive { + break; + } + let mut q = ability_damage( + Some(c.enemy), + first, + atk * config.shot, + DamageType::Physical, + ); + self.enemy_damage(w, r, &mut q)?; + } + } else { + let mut target = Some(first); + let mut hit = vec![]; + for k in 0..config.times.min(w.unit_capacity() as u32) { + let Some(t) = target else { break }; + hit.push(t); + self.enemy_element( + w, + r, + c.enemy, + t, + Element::Erosion, + atk * config.shot + * crate::deterministic::math::powi(0.85, k as i32) + .map_err(str::to_string)?, + )?; + let origin = w.unit(t)?.position; + let mut next = self.boss_area(w, c.enemy)?; + next.retain(|&a| { + !hit.contains(&a) && { + let p = w.unit(a).unwrap().position; + hypot(p[1] - origin[1], p[0] - origin[0]) <= 2. + } + }); + targeting::sort_allies(w, c.enemy, &mut next, Default::default())?; + next.sort_by(|&a, &b| { + let a = w.unit(a).unwrap().position; + let b = w.unit(b).unwrap().position; + hypot(a[1] - origin[1], a[0] - origin[0]) + .total_cmp(&hypot(b[1] - origin[1], b[0] - origin[0])) + }); + target = next.first().copied(); + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/bosses/helm.rs b/crates/engine/src/battle/runtime/enemies/bosses/helm.rs new file mode 100644 index 0000000..886d855 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/bosses/helm.rs @@ -0,0 +1,379 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::content::enemies::bosses::helm::{BladePhase, DroneLink, ShellTarget}; +use crate::deterministic::math::hypot; +mod parts; +pub(in crate::battle::runtime) const PART_DOT: u64 = 1713; +pub(in crate::battle::runtime) const BLADE_RETURN: u64 = 1714; +impl Host { + fn helm_range(w: &World, id: Id) -> Result { + let r = w.unit(id)?.stats.base_number("rangeRadius"); + Ok(if r != 0. { r } else { 8. }) + } + fn helm_ops(&mut self, w: &mut World, id: Id, radius: f64) -> Result, String> { + Ok(self + .boss_targets(w, id, radius)? + .into_iter() + .filter(|&t| { + w.unit(t) + .is_ok_and(|u| u.deployment.kind == crate::battle::deploy::Kind::Operator) + }) + .collect()) + } + pub(super) fn helm_condition( + &mut self, + w: &mut World, + id: Id, + spell: Spell, + ) -> Result, String> { + Ok(Some(match spell { + Spell::HelmShell => !self.helm_ops(w, id, Self::helm_range(w, id)?)?.is_empty(), + Spell::HelmDrones { .. } => true, + Spell::BladeDive => { + matches!( + self.content.as_ref().unwrap().boss(id), + Memory::Blade { + phase: BladePhase::Hover, + .. + } + ) && !self.helm_ops(w, id, f64::INFINITY)?.is_empty() + } + _ => return Ok(None), + })) + } + pub(super) fn helm_fire( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + spell: Spell, + ) -> Result<(), String> { + match spell { + Spell::HelmShell => { + let mut targets = self.helm_ops(w, id, Self::helm_range(w, id)?)?; + targeting::sort_allies(w, id, &mut targets, Default::default())?; + let mut keyed = vec![]; + for t in targets { + keyed.push((t, Self::tac_stat(w, t, "atk")?)); + } + keyed.sort_by(|a, b| b.1.total_cmp(&a.1)); + if let Some(&(target, _)) = keyed.first() { + let tile = w.unit(target)?.deployment.tile; + let position = w.unit(id)?.position; + let options = serde_json::json!({"pos":position,"route":{"motion":"FLY","start":position,"end":tile,"steps":[{"t":"WAIT","s":99999}]},"tag":"part","countInTotal":false}); + let shell = self.with_spawns(w, r, |spawns, context, world| { + spawns.spawn_runtime(world, context, "enemy_9016_acstmr", &options) + })?; + w.pin_unit(id)?; + self.content.as_mut().unwrap().set_boss( + shell, + Memory::Shell { + target: Some(ShellTarget { tile, source: id }), + }, + ); + self.rebuild_index(w)?; + } + } + Spell::HelmDrones { ratio, hp } => { + let content = self.content.as_ref().unwrap(); + let key = content + .child(id) + .unwrap_or_else(|| Arc::from("enemy_1005_yokai")); + let branch = content + .branch(id) + .unwrap_or_else(|| Arc::from("boss_summon_enemy")); + let mods = if hp > 0. { + serde_json::json!({"hpMul":hp}) + } else { + Value::Null + }; + for drone in self.boss_spawn_branch(w, r, id, &branch, &key, mods, "FLY")? { + w.pin_unit(id)?; + self.content + .as_mut() + .unwrap() + .set_drone(drone, Some(DroneLink { owner: id, ratio })); + } + } + Spell::BladeDive => self.blade_dive(w, r, id)?, + _ => unreachable!(), + } + Ok(()) + } + pub(in crate::battle::runtime) fn helm_attack( + &mut self, + w: &mut World, + c: &mut enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + if event != enemy::Event::BeforeAttack { + return Ok(()); + } + match self.boss_config(c.enemy) { + Some(Boss::Helm(_)) => { + let targets = self.boss_targets(w, c.enemy, Self::helm_range(w, c.enemy)?)?; + if let Some(t) = self.rng.pick(&targets).copied() { + c.targets = vec![t]; + } + } + Some(Boss::Blade(_)) => { + let radius = w.unit(c.enemy)?.stats.base_number("rangeRadius"); + let targets = + self.boss_targets(w, c.enemy, if radius != 0. { radius } else { 1.6 })?; + let mut ground = vec![]; + for t in targets { + if !targeting::flying(w, t)? { + ground.push(t); + } + } + if !ground.is_empty() { + c.targets = ground; + } + } + _ => {} + } + Ok(()) + } + pub(super) fn helm_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + boss: Boss, + dt: f64, + ) -> Result<(), String> { + match boss { + Boss::Helm(config) => { + for _ in 0..self.content.as_mut().unwrap().pulses(id, dt, 0.25) { + if matches!( + self.content.as_ref().unwrap().boss(id), + Memory::Helm { low: false } + ) && w.unit(id)?.stats.hp / Self::tac_stat(w, id, "maxHp")? < config.low + { + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Helm { low: true }); + let mut b = buff( + "boss:helmGuard", + &[ + ("physTakenMul", config.scale), + ("artsTakenMul", config.scale), + ], + ); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + } + self.enemy_caster_tick(w, r, id, config.caster, dt)?; + } + Boss::Shell { stun, dot } => { + let Memory::Shell { + target: Some(target), + } = self.content.as_ref().unwrap().boss(id) + else { + return Ok(()); + }; + if self.helm_step(w, id, target.tile, dt)? { + let source = if w.unit(target.source)?.stats.alive { + target.source + } else { + id + }; + self.helm_blast(w, r, source, id, target.tile, stun, dot, stun, false)?; + self.kill_enemy(id, None, r, w)?; + } + } + Boss::Blade(config) => { + self.blade_tick(w, r, id, config, dt)?; + if w.unit(id)?.stats.alive { + self.enemy_caster_tick(w, r, id, config.caster, dt)?; + } + } + _ => unreachable!(), + } + Ok(()) + } + fn helm_step( + &mut self, + w: &mut World, + id: Id, + tile: [i32; 2], + dt: f64, + ) -> Result { + let p = w.unit(id)?.position; + let target = tile.map(|v| v as f64); + let d = hypot(target[1] - p[1], target[0] - p[0]); + let step = Self::tac_stat(w, id, "moveSpeed")? * 0.5 * dt; + if d <= step + 1e-9 { + w.unit_mut(id)?.position = target; + return Ok(true); + } + let u = w.unit_mut(id)?; + u.position[0] += (target[0] - p[0]) / d * step; + u.position[1] += (target[1] - p[1]) / d * step; + Ok(false) + } + pub(super) fn helm_profile(&self, kit: &Kit, p: &mut enemy::Profile) { + if let Kit::Boss(Boss::Blade(config)) = kit { + if config.hammer { + p.atk_scale = 1.5; + } + } + } + fn helm_leader(&self, w: &World, id: Id) -> Result, String> { + let p = w.unit(id)?.position; + let mut best = None; + let mut distance = f64::INFINITY; + for &t in self.spawns.as_ref().unwrap().live() { + if !w.unit(t)?.boss + || !w.unit(t)?.stats.alive + || !matches!(self.boss_config(t), Some(Boss::Helm(_))) + { + continue; + } + let at = w.unit(t)?.position; + let d = hypot(at[1] - p[1], at[0] - p[0]); + if d < distance { + best = Some(t); + distance = d; + } + } + Ok(best) + } + pub(in crate::battle::runtime) fn helm_taken( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + source: Option, + credit: Option, + amount: f64, + ) -> Result<(), String> { + let Some(Boss::Blade(config)) = self.boss_config(id) else { + return Ok(()); + }; + if amount > 0. { + if let Some(leader) = self.helm_leader(w, id)? { + let by = source + .or(credit) + .filter(|&t| w.unit(t).is_ok_and(|u| u.side == health::Side::Ally)); + self.lose_hp_with_credit( + w, + r, + health::Hit { + source: None, + credit: by, + target: leader, + damage_type: DamageType::True, + no_sp: true, + silent: false, + hp_loss: true, + on_applied: false, + }, + amount, + false, + )?; + } + } + if let Memory::Blade { + phase: BladePhase::Dive { tile, hits }, + home, + } = self.content.as_ref().unwrap().boss(id) + { + if w.unit(id)?.stats.alive { + let hits = hits.checked_add(1).ok_or("Blade hit count overflow")?; + self.content.as_mut().unwrap().set_boss( + id, + Memory::Blade { + phase: BladePhase::Dive { tile, hits }, + home, + }, + ); + if hits as f64 >= config.hits { + self.blade_down(w, r, id, config, home)?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn helm_detach( + &mut self, + w: &mut World, + id: Id, + ) -> Result<(), String> { + if let Some(link) = self.content.as_ref().unwrap().drone(id) { + self.content.as_mut().unwrap().set_drone(id, None); + w.unpin_unit(link.owner)?; + } + if let Memory::Shell { + target: Some(target), + } = self.content.as_ref().unwrap().boss(id) + { + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Shell { target: None }); + w.unpin_unit(target.source)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn helm_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + credit: Option, + ) -> Result<(), String> { + if let Some(link) = self.content.as_ref().unwrap().drone(id) { + let key = self + .spawns + .as_ref() + .unwrap() + .definition(link.owner)? + .key + .clone(); + let owner = if w.unit(link.owner)?.stats.alive { + Some(link.owner) + } else { + self.spawns + .as_ref() + .unwrap() + .live() + .iter() + .copied() + .find(|&t| { + w.unit(t).is_ok_and(|u| u.stats.alive && u.boss) + && self + .spawns + .as_ref() + .unwrap() + .definition(t) + .is_ok_and(|d| d.key == key) + }) + }; + if let Some(owner) = owner.filter(|_| link.ratio > 0.) { + let amount = Self::tac_stat(w, owner, "maxHp")? * link.ratio; + let by = credit.filter(|&t| w.unit(t).is_ok_and(|u| u.side == health::Side::Ally)); + self.lose_hp_with_credit( + w, + r, + health::Hit { + source: by, + credit: by, + target: owner, + damage_type: DamageType::True, + no_sp: true, + silent: false, + hp_loss: true, + on_applied: false, + }, + amount, + true, + )?; + } + } + self.helm_detach(w, id) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/bosses/helm/parts.rs b/crates/engine/src/battle/runtime/enemies/bosses/helm/parts.rs new file mode 100644 index 0000000..ce6801d --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/bosses/helm/parts.rs @@ -0,0 +1,263 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::content::enemies::bosses::Blade; +impl Host { + pub(super) fn blade_dive( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Memory::Blade { home, .. } = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + let mut targets = vec![]; + for t in self.roster.as_ref().unwrap().ids().to_vec() { + let u = w.unit(t)?; + if u.stats.alive + && u.deployed + && u.deployment.kind == crate::battle::deploy::Kind::Operator + { + targets.push(t); + } + } + targeting::sort_allies(w, id, &mut targets, Default::default())?; + let mut keyed = vec![]; + for t in targets { + keyed.push((t, Self::tac_stat(w, t, "atk")?)); + } + keyed.sort_by(|a, b| a.1.total_cmp(&b.1)); + let Some(&(target, _)) = keyed.first() else { + return Ok(()); + }; + let tile = w.unit(target)?.deployment.tile; + self.content.as_mut().unwrap().set_boss( + id, + Memory::Blade { + phase: BladePhase::Dive { tile, hits: 0 }, + home, + }, + ); + r.remove(w, self, id, "boss:hover")?; + let mut b = buff("boss:sortie", &[]); + b.runtime.persist = true; + b.flags.insert("disarm".into()); + self.enemy_buff(w, r, id, b)?; + let hand = match self.boss_config(id) { + Some(Boss::Blade(Blade { hammer: true, .. })) => "right_hand_blink", + _ => "left_hand_blink", + }; + if let Some(route) = self.spawns.as_ref().unwrap().branch_route(hand) { + if let Some(p) = route["start"].as_array().filter(|p| p.len() == 2) { + w.unit_mut(id)?.position = [ + p[0].as_f64().ok_or("Invalid blink row")?, + p[1].as_f64().ok_or("Invalid blink column")?, + ]; + } + } + Ok(()) + } + pub(super) fn blade_down( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Blade, + home: [f64; 2], + ) -> Result<(), String> { + self.content.as_mut().unwrap().set_boss( + id, + Memory::Blade { + phase: BladePhase::Down, + home, + }, + ); + w.unit_mut(id)?.motion_fly = false; + w.unit_mut(id)?.ground = true; + self.apply_status( + w, + r, + id, + "stun", + status::Options { + duration: config.stun, + force: true, + ..Default::default() + }, + )?; + let mut b = buff("boss:downed", &[("dmgTakenMul", config.scale)]); + b.runtime.duration = config.down.min(config.stun); + b.runtime.visible = true; + b.runtime.on_expire = Some(BLADE_RETURN); + self.enemy_buff(w, r, id, b) + } + pub(super) fn blade_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Blade, + dt: f64, + ) -> Result<(), String> { + let Memory::Blade { + phase: BladePhase::Dive { tile, .. }, + .. + } = self.content.as_ref().unwrap().boss(id) + else { + return Ok(()); + }; + if self.enemy_can_cast(w, id, false)? && self.helm_step(w, id, tile, dt)? { + let leader = self.helm_leader(w, id)?.unwrap_or(id); + self.helm_blast( + w, + r, + leader, + id, + tile, + config.stun, + config.dot, + config.duration, + true, + )?; + self.blade_replace(w, r, id)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn blade_return( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if w.unit(id)?.stats.alive + && matches!( + self.content.as_ref().unwrap().boss(id), + Memory::Blade { + phase: BladePhase::Down, + .. + } + ) + { + self.blade_replace(w, r, id)?; + } + Ok(()) + } + fn blade_replace( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Memory::Blade { home, .. } = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + self.content.as_mut().unwrap().set_boss( + id, + Memory::Blade { + phase: BladePhase::Gone, + home, + }, + ); + w.unit_mut(id)?.motion_fly = true; + w.unit_mut(id)?.ground = false; + let hand = match self.boss_config(id) { + Some(Boss::Blade(Blade { hammer: true, .. })) => "right_hand_origin", + _ => "left_hand_origin", + }; + let route = self.spawns.as_ref().unwrap().branch_route(hand); + let ledger = &self.spawns.as_ref().unwrap().ledger.alive()[&id]; + let mut options = serde_json::json!({"route":route.clone().unwrap_or_else(||serde_json::json!({"motion":"FLY","start":home,"end":home,"steps":[{"t":"WAIT","s":99999}]})),"tag":ledger.tag,"countInTotal":false,"mods":ledger.mods}); + if route.is_none() { + options["pos"] = serde_json::json!(home); + } + let key = self.spawns.as_ref().unwrap().definition(id)?.key.clone(); + let hp = w.unit(id)?.stats.hp; + let replacement = self.with_spawns(w, r, |spawns, context, world| { + spawns.spawn_runtime(world, context, &key, &options) + })?; + w.unit_mut(replacement)?.stats.hp = hp.min(Self::tac_stat(w, replacement, "maxHp")?); + self.kill_enemy(id, None, r, w)?; + self.rebuild_index(w) + } + pub(super) fn helm_blast( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + by: Id, + tile: [i32; 2], + stun: f64, + dot: f64, + duration: f64, + blade: bool, + ) -> Result<(), String> { + for t in self.enemy_tile_allies(w, tile, 1)? { + if !targeting::area_selectable(w, Some(by), t)? { + continue; + } + if stun > 0. { + self.apply_status( + w, + r, + t, + "stun", + status::Options { + duration: stun, + source: Some(source), + ignore_select: true, + ..Default::default() + }, + )?; + } + if dot > 0. && duration > 0. { + let mut b = buff( + if blade { + "boss:bladeDiveDot" + } else { + "boss:helmShellDot" + }, + &[], + ); + b.runtime.duration = duration; + b.runtime.interval = 1.; + b.runtime.visible = true; + b.runtime.source = Some(source); + b.runtime.tick_payload = dot; + b.runtime.on_tick = Some(PART_DOT); + r.add( + w, + self, + t, + buffs::Spec { + buff: b, + ..Default::default() + } + .retaining_unit(source), + )?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn helm_dot( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + let b = r.get(w, c.unit, c.buff)?; + let source = b.runtime.source.ok_or("Missing part damage source")?; + let amount = b.runtime.tick_payload; + let mut q = ability_damage(Some(source), c.unit, amount, DamageType::Physical); + q.is_skill = false; + q.ignore_select = true; + q.tags.push( + if b.key.as_deref() == Some("boss:bladeDiveDot") { + "bladeDive" + } else { + "helmShell" + } + .into(), + ); + self.enemy_damage(w, r, &mut q) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/bosses/quintus.rs b/crates/engine/src/battle/runtime/enemies/bosses/quintus.rs new file mode 100644 index 0000000..e51a8f7 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/bosses/quintus.rs @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::ensemble::AreaStrike; +use super::*; +use crate::battle::{content::enemies::bosses::Quintus, element::Element}; +impl Host { + fn quintus_targets(&mut self, w: &mut World, id: Id, radius: f64) -> Result, String> { + let mut targets = self.boss_targets(w, id, radius)?; + targeting::sort_allies( + w, + id, + &mut targets, + targeting::Profile { + block_free: true, + ..Default::default() + }, + )?; + let mut keyed = vec![]; + for t in targets { + keyed.push((t, Self::tac_stat(w, t, "def")?)); + } + keyed.sort_by(|a, b| b.1.total_cmp(&a.1)); + Ok(keyed.into_iter().map(|x| x.0).collect()) + } + pub(super) fn quintus_condition(&self, id: Id, spell: Spell) -> Option { + match spell { + Spell::Tide { stage, .. } | Spell::Rockfall { stage, .. } => Some( + matches!(self.content.as_ref().unwrap().boss(id),Memory::Quintus(s) if s.stage==stage), + ), + Spell::Tentacles { stage } => { + let Memory::Quintus(s) = self.content.as_ref().unwrap().boss(id) else { + return Some(false); + }; + let branch = self + .content + .as_ref() + .unwrap() + .tentacle_branch(id) + .unwrap_or_else(|| Arc::from("dslily_dstnta")); + let phases = self.spawns.as_ref().unwrap().branch_phases(&branch); + Some(s.stage == stage && (phases == 0 || s.tentacles < phases)) + } + Spell::Species { .. } => Some( + matches!(self.content.as_ref().unwrap().boss(id),Memory::Quintus(s) if s.stage==2), + ), + _ => None, + } + } + pub(super) fn quintus_fire( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + spell: Spell, + ) -> Result<(), String> { + match spell { + Spell::Tide { scale, element, .. } => self.boss_arts_area( + w, + r, + id, + AreaStrike { + position: w.unit(id)?.position, + radius: f64::INFINITY, + scale, + element: Element::Neural, + ratio: element, + attack: None, + }, + )?, + Spell::Rockfall { stage, scale } => { + for target in self + .quintus_targets(w, id, f64::INFINITY)? + .into_iter() + .take([2, 4, 8][stage as usize]) + { + self.enemy_schedule( + w, + Some(id), + 1., + 0., + 1, + EnemyTask::Boss(BossTask::Rockfall { target, scale }), + )?; + } + } + Spell::Tentacles { .. } => { + let Memory::Quintus(mut state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + let branch = self + .content + .as_ref() + .unwrap() + .tentacle_branch(id) + .unwrap_or_else(|| Arc::from("dslily_dstnta")); + let mut spots = self + .spawns + .as_ref() + .unwrap() + .tentacle_spots(&branch, state.tentacles); + if spots.is_empty() { + let targets = self.boss_targets(w, id, f64::INFINITY)?; + if let Some(&t) = self.rng.pick(&targets) { + spots.push(w.unit(t)?.deployment.tile.map(|v| v as f64)); + } + } + state.tentacles = state + .tentacles + .checked_add(1) + .ok_or("Tentacle phase count exhausted")?; + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Quintus(state)); + for spot in spots { + for t in self.boss_area(w, id)? { + let p = w.unit(t)?.position; + if crate::deterministic::math::hypot(p[1] - spot[1], p[0] - spot[0]) <= 1. { + self.apply_status( + w, + r, + t, + "stun", + status::Options { + duration: 5., + source: Some(id), + ..Default::default() + }, + )?; + } + } + } + } + Spell::Species { loss } => self.enemy_schedule( + w, + Some(id), + 4., + 0., + 1, + EnemyTask::Boss(BossTask::Species { loss }), + )?, + _ => unreachable!(), + } + Ok(()) + } + pub(super) fn quintus_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Quintus, + dt: f64, + ) -> Result<(), String> { + for _ in 0..self.content.as_mut().unwrap().pulses(id, dt, 0.25) { + let Memory::Quintus(mut state) = self.content.as_ref().unwrap().boss(id) else { + unreachable!() + }; + if state.stage >= 2 { + break; + } + let stage = state.stage as usize; + let lost = 1. - w.unit(id)?.stats.hp / Self::tac_stat(w, id, "maxHp")?; + let since = if stage == 0 { + state.born_at + } else { + state.stage_at + }; + if lost >= config.growth[stage] || w.time - since >= config.deadlines[stage] { + state.stage += 1; + state.stage_at = w.time; + self.content + .as_mut() + .unwrap() + .set_boss(id, Memory::Quintus(state)); + let mut b = buff("boss:grow", &[("atkPct", config.attack[stage])]); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + let caster = self + .content + .as_ref() + .unwrap() + .quintus_caster(id) + .ok_or("Missing Quintus stage skills")?; + let mut clock = self.content.as_ref().unwrap().caster(id); + clock.left = caster + .skills + .map(|s| s.map(|s| s.clock.initial).unwrap_or(0.)); + self.content.as_mut().unwrap().set_caster(id, clock); + } + } + let caster = self + .content + .as_ref() + .unwrap() + .quintus_caster(id) + .ok_or("Missing Quintus stage skills")?; + self.enemy_caster_tick(w, r, id, caster, dt) + } + pub(in crate::battle::runtime::enemies) fn quintus_attack( + &mut self, + w: &mut World, + c: &mut enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + if event == enemy::Event::BeforeAttack + && matches!(self.boss_config(c.enemy), Some(Boss::Quintus(_))) + { + let radius = w.unit(c.enemy)?.stats.base_number("rangeRadius"); + let targets = + self.quintus_targets(w, c.enemy, if radius != 0. { radius } else { 99. })?; + if !targets.is_empty() { + c.targets = targets.into_iter().take(2).collect(); + } + } + Ok(()) + } + pub(super) fn quintus_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + target: Id, + ) -> Result<(), String> { + if let Some(Boss::Quintus(config)) = self.boss_config(id) { + let amount = Self::tac_stat(w, id, "atk")? * config.neural; + self.enemy_element(w, r, id, target, Element::Neural, amount)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/bosses/spawning.rs b/crates/engine/src/battle/runtime/enemies/bosses/spawning.rs new file mode 100644 index 0000000..3e453a2 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/bosses/spawning.rs @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::deterministic::math::hypot; +impl Host { + pub(in crate::battle::runtime::enemies::bosses) fn boss_spawn_branch( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + branch: &str, + fallback_key: &str, + mods: Value, + fallback_motion: &str, + ) -> Result, String> { + let phase = self.spawns.as_ref().unwrap().branch_phase(branch); + let mut specs = vec![]; + if let Some(phase) = phase { + for s in phase { + if s["action"] + .as_str() + .is_some_and(|a| !a.eq_ignore_ascii_case("SPAWN")) + { + continue; + } + let Some(key) = s["key"] + .as_str() + .or_else(|| s["enemyKey"].as_str()) + .filter(|k| k.starts_with("enemy_")) + else { + continue; + }; + let count = s["count"] + .as_f64() + .filter(|v| v.is_finite()) + .unwrap_or(1.) + .max(1.) + .ceil(); + if count > w.unit_capacity() as f64 || count > usize::MAX as f64 { + return Err("Branch spawn count exceeds unit capacity".into()); + } + let route = s["routeIndex"] + .as_u64() + .and_then(|index| { + self.spawns + .as_ref() + .unwrap() + .extra_routes() + .get(index as usize) + }) + .cloned(); + let route = route + .unwrap_or_else(|| self.boss_goal_route(w.unit(id).unwrap().position, "WALK")); + let mut options = serde_json::json!({"route":route,"tag":s["tag"],"mods":mods}); + if options["route"]["start"].is_null() { + options["pos"] = serde_json::json!(w.unit(id)?.position); + } + if s["unharmful"] == true { + options["countInTotal"] = Value::Bool(false); + } + specs.push((key.to_owned(), count as usize, options)); + } + } else { + let position = w.unit(id)?.position; + let options = serde_json::json!({"pos":position,"route":self.boss_goal_route(position,fallback_motion),"mods":mods}); + specs.push((fallback_key.to_owned(), 1, options)); + } + let mut spawned = vec![]; + for (key, count, options) in specs { + if spawned + .len() + .checked_add(count) + .is_none_or(|n| n > w.unit_capacity()) + { + return Err("Branch spawn count exceeds unit capacity".into()); + } + for _ in 0..count { + spawned.push(self.with_spawns(w, r, |spawns, context, world| { + spawns.spawn_runtime(world, context, &key, &options) + })?); + } + } + self.rebuild_index(w)?; + Ok(spawned) + } + fn boss_goal_route(&self, position: [f64; 2], motion: &str) -> Value { + let grid = self.grid.as_ref().unwrap(); + let mut best = position.map(|v| (v + 0.5).floor() as i32); + let mut distance = f64::INFINITY; + for (key, tile) in grid.tiles().iter().enumerate() { + if tile.special.as_deref() != Some("end") { + continue; + } + let p = [ + key / crate::battle::grid::COLS, + key % crate::battle::grid::COLS, + ] + .map(|v| v as i32); + let d = hypot(p[1] as f64 - position[1], p[0] as f64 - position[0]); + if d < distance { + distance = d; + best = p; + } + } + serde_json::json!({"motion":motion,"start":position,"end":best,"checkpoints":[]}) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/bosses/tasks.rs b/crates/engine/src/battle/runtime/enemies/bosses/tasks.rs new file mode 100644 index 0000000..d4f0449 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/bosses/tasks.rs @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::ensemble::AreaStrike; +use super::*; +use crate::battle::element::Element; +#[derive(Clone, Copy)] +pub(in crate::battle::runtime) enum BossTask { + Pipe { echo: Id, radius: f64, element: f64 }, + Rockfall { target: Id, scale: f64 }, + Species { loss: f64 }, +} +impl BossTask { + pub(in crate::battle::runtime::enemies) fn target(self) -> Option { + match self { + Self::Pipe { echo, .. } => Some(echo), + Self::Rockfall { target, .. } => Some(target), + Self::Species { .. } => None, + } + } +} +impl Host { + pub(in crate::battle::runtime::enemies) fn boss_task( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + task: BossTask, + ) -> Result { + if !w.unit(id)?.stats.alive { + return Ok(false); + } + match task { + BossTask::Pipe { + echo, + radius, + element, + } => { + if !w.unit(echo)?.stats.alive { + return Ok(false); + } + self.boss_arts_area( + w, + r, + id, + AreaStrike { + position: w.unit(echo)?.position, + radius, + scale: 1., + element: Element::Apoptosis, + ratio: element, + attack: None, + }, + )?; + self.echo_hit(w, r, echo)?; + } + BossTask::Rockfall { target, scale } => { + if w.unit(target)?.stats.alive { + let mut q = ability_damage( + Some(id), + target, + Self::tac_stat(w, id, "atk")? * scale, + DamageType::Physical, + ); + self.enemy_damage(w, r, &mut q)?; + } + } + BossTask::Species { loss } => self.lose_lp(loss)?, + } + Ok(true) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/casters.rs b/crates/engine/src/battle/runtime/enemies/casters.rs new file mode 100644 index 0000000..a605a72 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/casters.rs @@ -0,0 +1,772 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::casters::{Caster, Passive, Skill, Spell}, + motion::Leg, + targeting, +}; +use crate::deterministic::math::hypot; +mod champions; +mod tasks; +pub(in crate::battle::runtime) use champions::{FEAR_CAGE, WOLF_REBORN, XI_SHIELD}; +pub(in crate::battle::runtime) use tasks::{ + SkillShot, SpellTask, ARTS_BARRIER, BURN_TICK, SAND_TICK, +}; +impl Host { + fn caster_config(&self, id: Id) -> Option<&Caster> { + let kit = self.content.as_ref().unwrap().kit_ref(id); + self.caster_config_from(id, kit) + } + fn caster_config_from<'a>(&'a self, id: Id, kit: &'a Kit) -> Option<&'a Caster> { + match kit { + Kit::Caster(c) => Some(c), + Kit::Boss(content::Boss::Quintus(_)) => { + self.content.as_ref().unwrap().quintus_caster_ref(id) + } + Kit::Boss(c) => Some(c.caster_ref().unwrap_or(&content::casters::EMPTY)), + _ => None, + } + } + pub(super) fn caster_targets( + &mut self, + w: &mut World, + id: Id, + radius: f64, + ) -> Result, String> { + let mut targets = if radius.is_infinite() { + self.roster.as_ref().unwrap().ids().to_vec() + } else { + enemy::Hooks::allies_in_radius(self, id, radius, w, w.unit_capacity())? + }; + let mut out = vec![]; + for target in targets.drain(..) { + if targeting::can_target_ally(w, id, target, true, Default::default())? { + out.push(target); + } + } + Ok(out) + } + fn cross_targets( + &mut self, + w: &mut World, + id: Id, + direction: Option<[i32; 2]>, + ) -> Result, String> { + let origin = w.unit(id)?.position; + let mut targets = self.caster_targets(w, id, 6.)?; + targets.retain(|&t| { + let p = w.unit(t).unwrap().position; + let delta = [p[0] - origin[0], p[1] - origin[1]]; + let sign = delta.map(|x| ((x + 0.5).floor() as i32).signum()); + (delta[0].abs() < 0.5 || delta[1].abs() < 0.5) && direction.is_none_or(|d| d == sign) + }); + targets.sort_by(|&a, &b| { + let a = w.unit(a).unwrap().position; + let b = w.unit(b).unwrap().position; + hypot(a[1] - origin[1], a[0] - origin[0]) + .total_cmp(&hypot(b[1] - origin[1], b[0] - origin[0])) + }); + Ok(targets) + } + fn cast_targets(&mut self, w: &mut World, id: Id, spell: Spell) -> Result, String> { + let mut targets = match spell { + Spell::Charge { .. } => { + return Ok(w + .unit(id)? + .blocked_by() + .into_iter() + .filter(|&t| w.unit(t).is_ok_and(|u| u.stats.alive)) + .collect()) + } + Spell::Cross { .. } => return self.cross_targets(w, id, None), + Spell::DeathEye { .. } => { + let radius = w.unit(id)?.stats.base_number("rangeRadius"); + self.caster_targets(w, id, if radius == 0. { 2.5 } else { radius })? + } + Spell::Triple { radius, .. } + | Spell::Jazz { radius, .. } + | Spell::C4 { radius, .. } + | Spell::Rock { radius, .. } => self.caster_targets(w, id, radius)?, + Spell::Cannon { .. } => { + self.caster_targets(w, id, w.unit(id)?.stats.base_number("rangeRadius") + 0.25)? + } + Spell::Drift { .. } | Spell::Sand { .. } => { + self.caster_targets(w, id, f64::INFINITY)? + } + Spell::Chain { radius, .. } => { + let mut targets = self.enemy_nearby(w, id, radius)?; + targets.retain(|&t| t != id); + return Ok(targets); + } + _ => return Ok(vec![]), + }; + if matches!(spell, Spell::Rock { .. }) { + let mut selected = vec![]; + for target in targets { + if !w + .unit_mut(target)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("stun") + { + selected.push(target); + } + } + targets = selected; + } + if matches!(spell, Spell::Cannon { .. }) { + let mut keyed = vec![]; + for target in targets { + keyed.push((target, Self::tac_stat(w, target, "maxHp")?)); + } + keyed.sort_by(|a, b| b.1.total_cmp(&a.1)); + return Ok(keyed.into_iter().map(|x| x.0).collect()); + } + targeting::sort_allies( + w, + id, + &mut targets, + targeting::Profile { + block_free: matches!(spell, Spell::Drift { .. } | Spell::Sand { .. }), + ..Default::default() + }, + )?; + if matches!(spell, Spell::Drift { .. } | Spell::Sand { .. }) { + let mut keyed = vec![]; + for target in targets { + keyed.push((target, Self::tac_stat(w, target, "maxHp")?)); + } + keyed.sort_by(|a, b| { + if matches!(spell, Spell::Drift { .. }) { + b.1.total_cmp(&a.1) + } else { + a.1.total_cmp(&b.1) + } + }); + targets = keyed.into_iter().map(|x| x.0).collect(); + } + Ok(targets) + } + fn caster_condition(&mut self, w: &mut World, id: Id, spell: Spell) -> Result { + if let Some(ready) = self.boss_condition(w, id, spell)? { + return Ok(ready); + } + if let Some(ready) = self.champion_condition(w, id, spell)? { + return Ok(ready); + } + Ok(match spell { + Spell::Shield { .. } | Spell::TombShield { .. } => true, + Spell::Blink { .. } => w.unit(id)?.blocked_by().is_some(), + Spell::Jazz { .. } => { + !self.content.as_ref().unwrap().caster(id).channel + && !Queries::enemy_stealthed(self, id, w)? + && !self.cast_targets(w, id, spell)?.is_empty() + } + _ => !self.cast_targets(w, id, spell)?.is_empty(), + }) + } + fn caster_fire( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + slot: usize, + skill: Skill, + grid: Option<&Grid>, + ) -> Result<(), String> { + let mut state = self.content.as_ref().unwrap().caster(id); + state.left[slot] = (skill.clock.period + skill.clip.max(0.)).max(DT); + self.content.as_mut().unwrap().set_caster(id, state); + let targets = self.cast_targets(w, id, skill.spell)?; + match skill.spell { + spell @ (Spell::PipeStrike { .. } + | Spell::Ensemble + | Spell::Tide { .. } + | Spell::Rockfall { .. } + | Spell::Tentacles { .. } + | Spell::Species { .. } + | Spell::GunCharge + | Spell::SpringDash { .. } + | Spell::HelmShell + | Spell::HelmDrones { .. } + | Spell::BladeDive + | Spell::Decree { .. } + | Spell::Repel { .. } + | Spell::Surge { .. }) => self.boss_fire(w, r, id, spell, grid)?, + spell @ (Spell::XiShield { .. } + | Spell::XiCross { .. } + | Spell::MaceBlink { .. } + | Spell::MaceCircle { .. } + | Spell::Fear { .. } + | Spell::LucienAoe { .. } + | Spell::Phantom { .. }) => self.champion_fire(w, r, id, spell)?, + Spell::Charge { duration, scale } => { + if let Some(&target) = targets.first() { + let mut b = buff("ab:charging", &[]); + b.runtime.duration = duration; + b.runtime.visible = true; + b.flags.insert("disarm".into()); + self.enemy_buff(w, r, id, b)?; + self.enemy_schedule( + w, + Some(id), + duration, + 0., + 1, + EnemyTask::Spell(SpellTask::Knight { + target: None, + tile: w.unit(target)?.deployment.tile, + scale, + charge: true, + }), + )?; + } + } + Spell::Triple { delay, scale, .. } => { + for &target in targets.iter().take(3) { + self.enemy_schedule( + w, + Some(id), + delay, + 0., + 1, + EnemyTask::Spell(SpellTask::Knight { + target: Some(target), + tile: w.unit(target)?.deployment.tile, + scale, + charge: false, + }), + )?; + } + } + Spell::Cross { scale, stun } => { + let Some(&target) = targets.first() else { + return Ok(()); + }; + let a = w.unit(id)?.position; + let b = w.unit(target)?.position; + let direction = + [b[0] - a[0], b[1] - a[1]].map(|x| ((x + 0.5).floor() as i32).signum()); + for (key, flags) in [ + ("ab:revealed", vec!["reveal"]), + ("ab:aim", vec!["noMove", "disarm"]), + ] { + let mut b = buff(key, &[]); + b.runtime.duration = 2.5; + b.flags.extend(flags.into_iter().map(str::to_string)); + self.enemy_buff(w, r, id, b)?; + } + self.enemy_schedule( + w, + Some(id), + 1.4, + 0., + 1, + EnemyTask::Spell(SpellTask::Cross { + direction, + scale, + stun, + }), + )?; + } + Spell::DeathEye { + duration, + scale, + element, + } => { + if let Some(&target) = targets.first() { + let mut b = buff("ab:channel", &[]); + b.runtime.duration = duration; + b.flags.insert("disarm".into()); + self.enemy_buff(w, r, id, b)?; + self.enemy_schedule( + w, + Some(id), + 1., + 1., + Self::spell_count(duration.ceil().max(1.))?, + EnemyTask::Spell(SpellTask::Channel { + target, + jazz: false, + scale, + element, + }), + )?; + } + } + Spell::Jazz { + duration, + interval, + scale, + element, + .. + } => { + let Some(&target) = targets.first() else { + return Ok(()); + }; + if duration <= 0. || interval <= 0. { + return Ok(()); + } + let mut b = buff("ab:channel", &[]); + b.runtime.duration = duration; + b.flags.insert("disarm".into()); + self.enemy_buff(w, r, id, b)?; + let mut state = self.content.as_ref().unwrap().caster(id); + state.channel = true; + self.content.as_mut().unwrap().set_caster(id, state); + self.enemy_schedule( + w, + Some(id), + interval.max(DT), + interval.max(DT), + Self::spell_count((duration / interval + 1e-9).floor().max(1.))?, + EnemyTask::Spell(SpellTask::Channel { + target, + jazz: true, + scale, + element, + }), + )?; + } + Spell::Cannon { scale } => { + if let Some(&target) = targets.first() { + let tile = w.unit(target)?.position.map(|x| (x + 0.5).floor() as i32); + let mut b = buff("ab:cannon", &[]); + b.runtime.duration = 5.; + b.flags.insert("noDisplace".into()); + self.enemy_buff(w, r, id, b)?; + let mut state = self.content.as_ref().unwrap().caster(id); + state.cannon = true; + self.content.as_mut().unwrap().set_caster(id, state); + self.enemy_schedule( + w, + Some(id), + 0.5, + 0.5, + 10, + EnemyTask::Spell(SpellTask::Cannon { tile, scale }), + )?; + } + } + Spell::C4 { scale, .. } => { + let hp = w.unit(id)?.stats.hp; + let count = if hp / Self::tac_stat(w, id, "maxHp")? < 0.5 { + 2 + } else { + 1 + }; + for &target in targets.iter().take(count) { + self.enemy_schedule( + w, + Some(id), + 1., + 0., + 1, + EnemyTask::Spell(SpellTask::C4 { + target, + position: w.unit(target)?.position, + scale, + }), + )?; + } + } + Spell::Drift { damage } => { + if let Some(&target) = targets.first() { + let tile = w.unit(target)?.deployment.tile; + for t in self.caster_cross_area(w, id, tile)? { + let mut hit = ability_damage(Some(id), t, damage, DamageType::Physical); + self.enemy_damage(w, r, &mut hit)?; + } + } + } + Spell::Sand { + duration, + damage, + attack, + } => { + if let Some(&target) = targets.first() { + let ids = spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + w.unit(target)?.position, + 1., + None, + false, + w.unit_capacity(), + )?; + for t in ids { + if !targeting::area_selectable(w, Some(id), t)? { + continue; + } + let mut b = buff("ab:sandStorm", &[("atkPct", attack)]); + b.runtime.duration = duration; + b.runtime.interval = 1.; + b.runtime.visible = true; + b.runtime.source = Some(id); + b.runtime.tick_payload = damage; + b.runtime.on_tick = Some(SAND_TICK); + r.add( + w, + self, + t, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + } + .retaining_unit(id), + )?; + } + } + } + Spell::Rock { scale, stun, .. } => { + if let Some(&target) = targets.first() { + self.caster_projectile(w, id, target, 8., DamageType::Physical, scale, stun)?; + } + } + Spell::Chain { + radius, + jump, + max, + duration, + speed, + aspd, + } => { + let mut seen = vec![id]; + let mut position = w.unit(id)?.position; + let mut reach = radius; + while seen.len() - 1 < max as usize { + let ids = self.spawns.as_ref().unwrap().live().to_vec(); + let mut near = spatial::enemies_in_radius( + w, + self, + &ids, + position, + reach, + RadiusRule::Body, + false, + w.unit_capacity(), + )?; + near.retain(|t| !seen.contains(t)); + near.sort_by(|&a, &b| { + let a = w.unit(a).unwrap().position; + let b = w.unit(b).unwrap().position; + hypot(a[1] - position[1], a[0] - position[0]) + .total_cmp(&hypot(b[1] - position[1], b[0] - position[0])) + }); + let Some(&target) = near.first() else { + break; + }; + seen.push(target); + let mut b = buff("ab:chainBuff", &[("moveMul", 1. + speed), ("aspd", aspd)]); + b.runtime.duration = duration; + b.runtime.visible = true; + self.enemy_buff(w, r, target, b)?; + position = w.unit(target)?.position; + reach = jump; + } + } + Spell::Shield { amount, hp, aspd } => self.enemy_buff( + w, + r, + id, + Caster::barrier("ab:rockPower", amount, &[("hpPct", hp), ("aspd", aspd)]), + )?, + Spell::TombShield { ratio } => { + let amount = Self::tac_stat(w, id, "maxHp")? * ratio; + let mut b = buff("ab:tombShield", &[]); + b.shield = amount; + b.runtime.persist = true; + self.enemy_buff(w, r, id, b)?; + } + Spell::Blink { distance } => { + self.caster_blink(w, r, id, distance)?; + } + } + Ok(()) + } + pub(super) fn caster_turn( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + own: bool, + grid: Option<&Grid>, + ) -> Result, String> { + let Some(skills) = self.caster_config(id).map(|c| c.skills) else { + return Ok(None); + }; + let state = self.content.as_ref().unwrap().caster(id); + let mut ready = vec![]; + let mut top = f64::NEG_INFINITY; + for (slot, skill) in skills.into_iter().enumerate() { + let Some(skill) = skill else { + continue; + }; + if !skill.turn + || own && !skill.own + || state.left[slot] > 1e-9 + || !self.enemy_can_cast(w, id, skill.silence)? + || !self.caster_condition(w, id, skill.spell)? + { + continue; + } + if skill.priority > top { + ready.clear(); + top = skill.priority; + } + if skill.priority == top { + ready.push((slot, skill)); + } + } + if ready.is_empty() { + return Ok(None); + } + let pick = if ready.len() > 1 { + self.rng.int(ready.len() as u32) as usize + } else { + 0 + }; + let (slot, skill) = ready[pick]; + self.caster_fire(w, r, id, slot, skill, grid)?; + Ok(Some(skill.clip)) + } + pub(super) fn enemy_caster_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: &mut enemy::Context, + event: enemy::Event, + grid: Option<&Grid>, + ) -> Result { + if event == enemy::Event::BeforeAttack { + if let Some(clip) = self.caster_turn(w, r, c.enemy, false, grid)? { + Self::caster_restart_attack(w, c.enemy, clip)?; + c.targets.clear(); + return Ok(true); + } + } + let Some(config) = self.caster_config(c.enemy) else { + return Ok(false); + }; + let passive = config.passive; + match passive { + Passive::Knight { ranged: false, .. } if event == enemy::Event::BeforeAttack => { + if let Some(&target) = c.targets.first() { + for t in self.caster_cross_area(w, c.enemy, w.unit(target)?.deployment.tile)? { + if !c.targets.contains(&t) { + c.targets.push(t); + } + } + } + } + Passive::Mudrock { atk, .. } if event == enemy::Event::Attack => { + let mut b = buff("ab:rockCharge", &[("atkPct", atk)]); + b.runtime.persist = true; + b.runtime.refresh = buffs::Refresh::Stack; + b.runtime.max_stacks = 6; + self.enemy_buff(w, r, c.enemy, b)?; + } + Passive::Tomb { .. } if event == enemy::Event::BeforeAttack => { + let mut state = self.content.as_ref().unwrap().caster(c.enemy); + state.splash = w.unit(c.enemy)?.blocked_by().is_none(); + self.content.as_mut().unwrap().set_caster(c.enemy, state); + } + _ => {} + } + Ok(false) + } + pub(super) fn enemy_caster_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Caster, + dt: f64, + ) -> Result<(), String> { + self.champion_tick(w, r, id, config, dt)?; + if let Passive::Pompeii { + blast, + blast_interval, + .. + } = config.passive + { + let blocked = w.unit(id)?.blocked_by().is_some(); + let mut state = self.content.as_ref().unwrap().caster(id); + if !blocked { + state.held = 0.; + } else if !w.unit(id)?.hidden + && !w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("stun") + { + state.held += dt; + if state.held + 1e-9 >= blast_interval { + state.held = 0.; + for target in + enemy::Hooks::allies_in_radius(self, id, 1.4, w, w.unit_capacity())? + { + if !w.unit(target)?.motion_fly + && targeting::area_selectable(w, Some(id), target)? + { + let mut q = ability_damage(Some(id), target, blast, DamageType::Arts); + q.tags.push("splash".into()); + self.enemy_damage(w, r, &mut q)?; + } + } + } + } + self.content.as_mut().unwrap().set_caster(id, state); + } + if matches!(config.passive, Passive::Stealth { jazz: true }) { + let hidden = Queries::enemy_stealthed(self, id, w)?; + let mut state = self.content.as_ref().unwrap().caster(id); + state.no_attack = hidden; + self.content.as_mut().unwrap().set_caster(id, state); + } + if matches!(config.passive, Passive::Tomb { .. }) { + let pulses = self.content.as_mut().unwrap().pulses(id, dt, 0.5); + for _ in 0..pulses { + for t in self.roster.as_ref().unwrap().ids().to_vec() { + let u = w.unit(t)?; + if !u.stats.alive || !u.deployed || u.hidden { + continue; + } + let mut b = buff("ab:tombstone", &[("atkMul", 0.5), ("defMul", 0.5)]); + b.runtime.duration = 0.6; + b.runtime.visible = true; + self.enemy_buff(w, r, t, b)?; + let mut b = buff("ab:tombRedeploy", &[("redeployMul", 2.)]); + b.runtime.duration = 0.6; + b.runtime.persist = true; + self.enemy_buff(w, r, t, b)?; + } + } + self.roster.as_mut().unwrap().add_dp(-0.5 * dt)?; + } + for (slot, skill) in config.skills.into_iter().enumerate() { + let Some(skill) = skill else { + continue; + }; + let mut state = self.content.as_ref().unwrap().caster(id); + state.left[slot] -= dt; + self.content.as_mut().unwrap().set_caster(id, state); + if !skill.turn + && state.left[slot] <= 1e-9 + && self.enemy_can_cast(w, id, skill.silence)? + && self.caster_condition(w, id, skill.spell)? + { + self.caster_fire(w, r, id, slot, skill, None)?; + } + } + let u = w.unit_mut(id)?; + let blocked = u.blocked_by().is_some(); + let flags = &u.stats.stats().map_err(str::to_string)?.flags; + let disabled = flags.contains("fear") + || flags.contains("disarm") + || flags.contains("tremble") && blocked; + if !u.enemy.swing && u.cadence.cooldown <= 0. && !disabled { + if let Some(clip) = self.caster_turn(w, r, id, true, None)? { + Self::caster_restart_attack(w, id, clip)?; + } + } + Ok(()) + } + fn caster_restart_attack(w: &mut World, id: Id, clip: f64) -> Result<(), String> { + w.unit_mut(id)?.cadence.cooldown = Self::tac_stat(w, id, "interval")?.max(clip); + w.unit_mut(id)?.motion.attack_stand_until = f64::NEG_INFINITY; + Ok(()) + } + fn spell_count(count: f64) -> Result { + if !count.is_finite() || count < 1. || count > i32::MAX as f64 { + return Err("Enemy skill pulse count outside positive i32 domain".into()); + } + Ok(count as u32) + } + pub(super) fn caster_cross_area( + &mut self, + w: &mut World, + id: Id, + tile: [i32; 2], + ) -> Result, String> { + let mut ids = vec![]; + for t in self.enemy_tile_allies(w, tile, 1)? { + let p = w.unit(t)?.deployment.tile; + if (p[0] - tile[0]).abs() + (p[1] - tile[1]).abs() <= 1 + && targeting::area_selectable(w, Some(id), t)? + { + ids.push(t); + } + } + Ok(ids) + } + pub(super) fn caster_blink( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + distance: f64, + ) -> Result, String> { + let origin = w.unit(id)?.position; + let mut at = origin; + let route = w + .unit(id)? + .motion + .route + .as_ref() + .ok_or("Missing blink route")?; + if let Some(points) = route.points.as_ref().filter(|p| route.point < p.len()) { + let mut left = distance; + for p in points.iter().skip(route.point) { + if left <= 1e-9 { + break; + } + let d = hypot(p[1] - at[1], p[0] - at[0]); + if d <= left { + at = *p; + left -= d; + } else { + at[0] += (p[0] - at[0]) / d * left; + at[1] += (p[1] - at[1]) / d * left; + break; + } + } + } else if let Some(Leg::Move { tile, .. } | Leg::Appear(tile)) = route.legs().get(route.leg) + { + let p = tile.map(|x| x as f64); + let d = hypot(p[1] - at[1], p[0] - at[0]); + if d <= distance + 1e-9 { + at = p; + } else if d > 0. { + at[0] += (p[0] - at[0]) / d * distance; + at[1] += (p[1] - at[1]) / d * distance; + } + } + let tile = at.map(|x| (x + 0.5).floor() as i32); + if !w.unit(id)?.motion_fly + && !self + .grid + .as_ref() + .ok_or("Missing blink grid")? + .ground_passable(tile, false) + { + return Ok(None); + } + w.unit_mut(id)?.position = at; + let mut b = buff("ab:blink", &[]); + b.runtime.duration = 1.; + b.flags + .extend(["invulnerable", "unblockable"].map(str::to_string)); + self.enemy_buff(w, r, id, b)?; + if let Some(route) = w.unit_mut(id)?.motion.route.as_mut() { + route.points = None; + } + Ok(Some(origin)) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/casters/champions.rs b/crates/engine/src/battle/runtime/enemies/casters/champions.rs new file mode 100644 index 0000000..3e92847 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/casters/champions.rs @@ -0,0 +1,586 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::{casters::BuffEffect, lifecycle::RebornPhase}, + element::Element, +}; +pub(in crate::battle::runtime) const XI_SHIELD: u64 = 1709; +pub(in crate::battle::runtime) const FEAR_CAGE: u64 = 1710; +pub(in crate::battle::runtime) const WOLF_REBORN: u64 = 1711; +impl Host { + fn champion_form2(&self, id: Id) -> bool { + self.content.as_ref().unwrap().caster(id).phase == Some(RebornPhase::Revived) + } + pub(super) fn champion_condition( + &mut self, + w: &mut World, + id: Id, + spell: Spell, + ) -> Result, String> { + let second = self.champion_form2(id); + Ok(Some(match spell { + Spell::XiShield { form2, .. } => second == form2, + Spell::MaceBlink { form2, .. } => second == form2 && w.unit(id)?.blocked_by().is_some(), + Spell::MaceCircle { form2, radius, .. } => { + second == form2 && !self.caster_targets(w, id, radius)?.is_empty() + } + Spell::XiCross { .. } => !self.caster_targets(w, id, f64::INFINITY)?.is_empty(), + Spell::Phantom { .. } => w.unit(id)?.blocked_by().is_some(), + Spell::LucienAoe { .. } => !self.caster_targets(w, id, 2.)?.is_empty(), + Spell::Fear { .. } => { + !second + && w.time >= self.content.as_ref().unwrap().caster(id).wait_until + && !self.roster.as_ref().unwrap().ids().iter().any(|&t| { + w.unit(t).is_ok_and(|u| { + u.stats.alive + && u.deployed + && u.stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some("ab:fearCage")) + }) + }) + && self.caster_targets(w, id, f64::INFINITY)?.iter().any(|&t| { + w.unit(t).is_ok_and(|u| { + u.deployment.kind == crate::battle::deploy::Kind::Operator + }) + }) + } + _ => return Ok(None), + })) + } + pub(super) fn champion_fire( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + spell: Spell, + ) -> Result<(), String> { + match spell { + Spell::XiShield { + duration, + amount, + radius, + scale, + .. + } => { + let mut b = buff("ab:xiShield", &[]); + b.shield = amount; + b.runtime.duration = duration; + b.runtime.visible = true; + b.runtime.on_expire = Some(XI_SHIELD); + b.runtime.source = Some(id); + b.runtime.enemy_effect = Some(BuffEffect::XiShield { radius, scale }); + self.enemy_buff(w, r, id, b)?; + } + Spell::XiCross { scale } => { + let mut targets = self.caster_targets(w, id, f64::INFINITY)?; + targeting::sort_allies( + w, + id, + &mut targets, + targeting::Profile { + block_free: true, + ..Default::default() + }, + )?; + let origin = w.unit(id)?.position; + targets.sort_by(|&a, &b| { + let a = w.unit(a).unwrap().position; + let b = w.unit(b).unwrap().position; + hypot(a[1] - origin[1], a[0] - origin[0]) + .total_cmp(&hypot(b[1] - origin[1], b[0] - origin[0])) + }); + let mut centers = targets.first().copied().into_iter().collect::>(); + if self.champion_form2(id) && targets.len() > 1 { + centers.push(*targets.last().unwrap()); + } + for center in centers { + let tile = w.unit(center)?.deployment.tile; + for t in self.roster.as_ref().unwrap().ids().to_vec() { + let p = w.unit(t)?.deployment.tile; + let delta = [(p[0] - tile[0]).abs(), (p[1] - tile[1]).abs()]; + if (delta[0] == 0 || delta[1] == 0) + && delta[0] + delta[1] <= 2 + && targeting::area_selectable(w, Some(id), t)? + { + self.champion_hurt(w, r, id, t, scale, DamageType::Arts)?; + } + } + } + } + Spell::MaceCircle { radius, scale, .. } => { + self.champion_aoe(w, r, id, radius, scale, 0.)? + } + Spell::LucienAoe { scale, element } => { + self.champion_aoe(w, r, id, 2., scale, element)? + } + Spell::MaceBlink { + distance, scale, .. + } => { + let blocker = w.unit(id)?.blocked_by(); + let from = w.unit(id)?.position; + if self.caster_blink(w, r, id, distance)?.is_some() { + let to = w.unit(id)?.position; + let delta = [to[0] - from[0], to[1] - from[1]]; + let length = delta[0] * delta[0] + delta[1] * delta[1]; + for t in self.roster.as_ref().unwrap().ids().to_vec() { + if Some(t) != blocker { + let p = w.unit(t)?.position; + let k = if length > 0. { + ((p[0] - from[0]) * delta[0] + (p[1] - from[1]) * delta[1]) / length + } else { + 0. + }; + let k = k.clamp(0., 1.); + if hypot(p[1] - from[1] - k * delta[1], p[0] - from[0] - k * delta[0]) + > 0.5 + || !targeting::area_selectable(w, Some(id), t)? + { + continue; + } + } + self.champion_hurt(w, r, id, t, scale, DamageType::Physical)?; + } + } + } + Spell::Phantom { distance } => { + let mut child = + self.enemy_children_spec(w, id, Arc::from("enemy_2017_csphts"), 1)?; + // Boss summons use the battle's summon scaling. Solo Field has no global enemy scaling. + child.clear_scaling(); + if self.caster_blink(w, r, id, distance)?.is_some() { + self.enemy_spawn_children(w, r, child)?; + } + } + Spell::Fear { + max, + aspd, + peak, + ramp, + .. + } => { + let mut targets = self.caster_targets(w, id, f64::INFINITY)?; + targets.retain(|&t| { + w.unit(t).is_ok_and(|u| { + u.deployment.kind == crate::battle::deploy::Kind::Operator + && !u + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some("ab:fearCage")) + }) + }); + self.rng.shuffle(&mut targets); + let hp = w.unit(id)?.stats.hp / Self::tac_stat(w, id, "maxHp")?; + for t in targets.into_iter().take(max) { + let mut b = buff("ab:fearCage", &[("aspd", aspd)]); + b.runtime.visible = true; + b.runtime.interval = 1.; + b.runtime.source = Some(id); + b.runtime.on_tick = Some(FEAR_CAGE); + b.runtime.enemy_effect = Some(BuffEffect::Fear { + started: w.time, + hp, + ramp, + peak, + }); + r.add( + w, + self, + t, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + } + .retaining_unit(id), + )?; + } + } + _ => unreachable!(), + } + Ok(()) + } + fn champion_aoe( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + radius: f64, + scale: f64, + element: f64, + ) -> Result<(), String> { + for t in self.champion_area(w, id, w.unit(id)?.position, radius)? { + self.champion_hurt(w, r, id, t, scale, DamageType::Physical)?; + let amount = Self::tac_stat(w, id, "atk")? * element; + self.enemy_element(w, r, id, t, Element::Neural, amount)?; + } + Ok(()) + } + fn champion_hurt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + target: Id, + scale: f64, + kind: DamageType, + ) -> Result<(), String> { + let amount = Self::tac_stat(w, id, "atk")? * scale; + let mut q = ability_damage(Some(id), target, amount, kind); + self.enemy_damage(w, r, &mut q) + } + fn champion_area( + &mut self, + w: &mut World, + id: Id, + position: [f64; 2], + radius: f64, + ) -> Result, String> { + let mut out = vec![]; + for t in spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + position, + radius, + None, + false, + w.unit_capacity(), + )? { + if targeting::area_selectable(w, Some(id), t)? { + out.push(t); + } + } + Ok(out) + } + pub(in crate::battle::runtime) fn champion_buff( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + let b = r.get(w, c.unit, c.buff)?; + let source = b.runtime.source.ok_or("Missing champion buff source")?; + let effect = b + .runtime + .enemy_effect + .ok_or("Missing champion buff effect")?; + match effect { + BuffEffect::Vest { .. } => unreachable!("Vest has no timed callback"), + BuffEffect::XiShield { radius, scale } => { + if w.unit(source)?.stats.alive { + for t in self.champion_area(w, source, w.unit(source)?.position, radius)? { + self.champion_hurt(w, r, source, t, scale, DamageType::Arts)?; + } + } + } + BuffEffect::Fear { + started, + ramp, + peak, + .. + } => { + if !w.unit(source)?.stats.alive || w.unit(source)?.removed { + r.remove_id(w, self, c.unit, c.buff)?; + return Ok(()); + } + let amount = Self::tac_stat(w, c.unit, "maxHp")? + * peak + * ((w.time - started) / ramp).min(1.); + self.support_lose_hp(w, r, c.unit, amount, Some(source), false)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn champion_rebirth_start( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Caster, + ) -> Result<(), String> { + let mut state = self.content.as_ref().unwrap().caster(id); + state.reborn_at = w.time; + self.content.as_mut().unwrap().set_caster(id, state); + match config.passive { + Passive::Xi { .. } => { + r.remove(w, self, id, "ab:xiShield")?; + } + Passive::Wolf { .. } => { + for t in self.roster.as_ref().unwrap().ids().to_vec() { + r.remove(w, self, t, "ab:fearCage")?; + } + r.remove(w, self, id, "ab:wolfGuard")?; + w.unit_mut(id)?.immune.remove("stun"); + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn champion_rebirth_finish( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Caster, + ) -> Result<(), String> { + let mut state = self.content.as_ref().unwrap().caster(id); + state.left = config + .skills + .map(|s| s.map(|s| s.clock.initial).unwrap_or(0.)); + state.next = 1.; + self.content.as_mut().unwrap().set_caster(id, state); + let mut b = match config.passive { + Passive::Xi { atk, .. } => buff("ab:xiReborn", &[("atkPct", atk)]), + Passive::Mace { .. } => { + let mut b = buff("ab:stealth", &[]); + b.flags.insert("stealth".into()); + b + } + Passive::Wolf { atk, bat, .. } => { + w.unit_mut(id)?.stats.edit_base(|b| { + let r = b.0.get("rangeRadius").copied().unwrap_or(0.); + b.0.insert("rangeRadius".into(), r.max(1.25)); + }); + let bat0 = w.unit(id)?.stats.base_number("bat"); + buff( + "ab:wolfRage", + &[ + ("atkPct", atk), + ("batPct", bat / if bat0 != 0. { bat0 } else { 1. }), + ], + ) + } + _ => return Ok(()), + }; + b.runtime.persist = true; + b.runtime.visible = !matches!(config.passive, Passive::Mace { .. }); + self.enemy_buff(w, r, id, b) + } + pub(super) fn champion_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Caster, + dt: f64, + ) -> Result<(), String> { + match config.passive { + Passive::Lucien { dodge, .. } => { + let on = w.unit(id)?.blocked_by().is_none() && dodge > 0.; + let mut state = self.content.as_ref().unwrap().caster(id); + if state.evade != Some(on) { + state.evade = Some(on); + self.content.as_mut().unwrap().set_caster(id, state); + if on { + let mut b = + buff("boss:evade", &[("dodgePhys", dodge), ("dodgeArts", dodge)]); + b.runtime.persist = true; + self.enemy_buff(w, r, id, b)?; + } else { + r.remove(w, self, id, "boss:evade")?; + } + } + } + Passive::Wolf { .. } => { + let pulses = self.content.as_mut().unwrap().pulses(id, dt, 0.1); + for _ in 0..pulses { + if self.champion_form2(id) { + self.wolf_awe(w, r, id)?; + continue; + } + let Some((slot, skill)) = + config.skills.iter().enumerate().find_map(|(i, s)| { + s.map(|s| (i, s)) + .filter(|(_, s)| matches!(s.spell, Spell::Fear { .. })) + }) + else { + continue; + }; + let Spell::Fear { + cut, refund, wait, .. + } = skill.spell + else { + unreachable!() + }; + let hp = w.unit(id)?.stats.hp / Self::tac_stat(w, id, "maxHp")?; + let mut n = 0; + for t in self.roster.as_ref().unwrap().ids().to_vec() { + if !w.unit(t)?.stats.alive || !w.unit(t)?.deployed { + continue; + } + let b = w.unit(t)?.stats.buffs().iter().find(|b| { + b.key.as_deref() == Some("ab:fearCage") && b.runtime.source == Some(id) + }); + if let Some(b) = b { + let Some(BuffEffect::Fear { hp: at, .. }) = b.runtime.enemy_effect + else { + unreachable!() + }; + if hp <= at - cut + 1e-9 { + r.remove(w, self, t, "ab:fearCage")?; + } else { + n += 1; + } + } + } + let mut state = self.content.as_ref().unwrap().caster(id); + if n < state.caught { + state.left[slot] -= refund * (state.caught - n) as f64; + if n == 0 { + state.wait_until = w.time + wait; + } + } + if n > 0 || w.time < state.wait_until { + state.left[slot] += 0.1; + } + state.caught = n; + self.content.as_mut().unwrap().set_caster(id, state); + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn wolf_reborn( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Some(duration) = self.caster_config(id).and_then(|c| match c.passive { + Passive::Wolf { duration, .. } => Some(duration), + _ => None, + }) else { + return Ok(()); + }; + let state = self.content.as_ref().unwrap().caster(id); + w.unit_mut(id)?.stats.hp = (Self::tac_stat(w, id, "maxHp")? + * ((w.time - state.reborn_at) / duration.max(DT)).min(1.)) + .max(1.); + self.wolf_awe(w, r, id) + } + fn wolf_awe(&mut self, w: &mut World, r: &mut buffs::Runtime, id: Id) -> Result<(), String> { + for t in spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + w.unit(id)?.position, + 1.5, + None, + false, + w.unit_capacity(), + )? { + if !targeting::aura_selectable(w, t)? { + continue; + } + let mut b = buff("ab:ancientAwe", &[("aspd", -50.)]); + b.runtime.duration = 0.2 + 0.1; + b.runtime.visible = true; + self.enemy_buff(w, r, t, b)?; + } + Ok(()) + } + pub(super) fn champion_hit( + &self, + w: &World, + id: Id, + q: &mut hit::Request, + ) -> Result<(), String> { + if let Some(config) = self.caster_config(id) { + if let Passive::Mace { pen, .. } = &config.passive { + if w.unit(id)?.blocked_by() == Some(q.hit.target) { + q.damage.penetration.def_pct = (q.damage.penetration.def_pct + + pen[usize::from(self.champion_form2(id))]) + .min(1.); + } + } + } + Ok(()) + } + pub(super) fn champion_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + q: &hit::Request, + ) -> Result<(), String> { + let (element, rebirth) = match self.caster_config(id) { + Some(config) => ( + match &config.passive { + Passive::Lucien { element, .. } => Some(*element), + _ => None, + }, + config.rebirth().is_some(), + ), + None => return Ok(()), + }; + if let Some(element) = element { + let amount = Self::tac_stat(w, id, "atk")? * element; + self.enemy_element(w, r, id, q.hit.target, Element::Neural, amount)?; + } + if rebirth && self.champion_form2(id) && w.unit(q.hit.target)?.stats.alive { + let amount = Self::tac_stat(w, id, "atk")?; + let mut hit = ability_damage(Some(id), q.hit.target, amount, q.hit.damage_type); + hit.is_skill = false; + hit.dodge_mode = crate::battle::injury::DodgeMode::Normal; + hit.tags.push("secondHit".into()); + self.champion_hit(w, id, &mut hit)?; + self.enemy_damage(w, r, &mut hit)?; + } + Ok(()) + } + pub(super) fn champion_taken( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Some((cut, disarm, radius)) = self.caster_config(id).and_then(|c| match c.passive { + Passive::Mace { + cut, + disarm, + radius, + .. + } => Some((cut, disarm, radius)), + _ => None, + }) else { + return Ok(()); + }; + if !self.champion_form2(id) || cut <= 0. { + return Ok(()); + } + let hp = w.unit(id)?.stats.hp / Self::tac_stat(w, id, "maxHp")?; + for _ in 0..64 { + // bounded crossings of one HP bar + let mut state = self.content.as_ref().unwrap().caster(id); + if !w.unit(id)?.stats.alive || hp > state.next - cut + 1e-9 || state.next - cut <= 1e-9 + { + break; + } + let previous = state.next; + state.next -= cut; + if state.next == previous { + break; + } + self.content.as_mut().unwrap().set_caster(id, state); + for t in self.champion_area(w, id, w.unit(id)?.position, radius)? { + self.roster.as_mut().unwrap().clear_inactive_sp(w, t)?; + if disarm > 0. { + self.apply_status( + w, + r, + t, + "disarm", + status::Options { + duration: disarm, + source: Some(id), + ..Default::default() + }, + )?; + } + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/casters/tasks.rs b/crates/engine/src/battle/runtime/enemies/casters/tasks.rs new file mode 100644 index 0000000..2a5398d --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/casters/tasks.rs @@ -0,0 +1,569 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{element::Element, injury, projectiles}; +use crate::deterministic::math::powi; +pub(in crate::battle::runtime) const ARTS_BARRIER: u64 = 1703; +pub(in crate::battle::runtime) const SAND_TICK: u64 = 1704; +pub(in crate::battle::runtime) const BURN_TICK: u64 = 1705; +#[derive(Clone, Copy)] +pub(in crate::battle::runtime) struct SkillShot { + pub source: Id, + pub kind: DamageType, + pub scale: f64, + pub stun: f64, +} +#[derive(Clone, Copy)] +pub(in crate::battle::runtime) enum SpellTask { + Knight { + target: Option, + tile: [i32; 2], + scale: f64, + charge: bool, + }, + Cross { + direction: [i32; 2], + scale: f64, + stun: f64, + }, + Channel { + target: Id, + jazz: bool, + scale: f64, + element: f64, + }, + Cannon { + tile: [i32; 2], + scale: f64, + }, + C4 { + target: Id, + position: [f64; 2], + scale: f64, + }, +} +impl SpellTask { + pub(in crate::battle::runtime) fn target(self) -> Option { + match self { + Self::Knight { target, .. } => target, + Self::Channel { target, .. } | Self::C4 { target, .. } => Some(target), + _ => None, + } + } +} +impl Host { + pub(super) fn caster_projectile( + &mut self, + w: &mut World, + source: Id, + target: Id, + speed: f64, + kind: DamageType, + scale: f64, + stun: f64, + ) -> Result<(), String> { + let from = w.unit(source)?.position; + self.flights + .as_mut() + .ok_or("Missing enemy skill projectiles")? + .add( + w, + projectiles::Launch { + from, + source: Some(source), + target: Some(target), + to: None, + speed, + hit_dead: false, + max_age: 10., + on_hit: true, + visual: if speed == 8. { "lob" } else { "enemy" }.into(), + speed_changeable: None, + removable: None, + payload: allies::Shot::Skill(SkillShot { + source, + kind, + scale, + stun, + }), + }, + )?; + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_skill_impact( + &mut self, + w: &mut World, + shot: SkillShot, + target: Option, + ) -> Result<(), String> { + let mut r = self + .buffs + .take() + .ok_or("Missing enemy skill impact buffs")?; + let result = (|| { + if let Some(target) = target { + let amount = Self::tac_stat(w, shot.source, "atk")? * shot.scale; + let mut hit = ability_damage(Some(shot.source), target, amount, shot.kind); + self.enemy_damage(w, &mut r, &mut hit)?; + if shot.stun > 0. && w.unit(target)?.stats.alive { + self.apply_status( + w, + &mut r, + target, + "stun", + status::Options { + source: Some(shot.source), + duration: shot.stun, + ..Default::default() + }, + )?; + } + } + Ok(()) + })(); + self.buffs = Some(r); + result + } + pub(in crate::battle::runtime::enemies) fn enemy_spell_task( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Option, + task: SpellTask, + last: bool, + ) -> Result { + let id = source.ok_or("Missing enemy spell source")?; + if !matches!(task, SpellTask::C4 { .. }) && !w.unit(id)?.stats.alive { + return Ok(false); + } + match task { + SpellTask::Knight { + target, + tile, + scale, + charge, + } => { + if charge + && w.unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("stun") + { + return Ok(false); + } + let mut targets = vec![]; + if let Some(target) = target { + if w.unit(target)?.stats.alive && w.unit(target)?.deployed { + targets.push(target); + } + } + for t in self.caster_cross_area(w, id, tile)? { + if !targets.contains(&t) { + targets.push(t); + } + } + for t in targets { + let amount = Self::tac_stat(w, id, "atk")? * scale; + let mut q = ability_damage( + Some(id), + t, + amount, + if charge { + DamageType::Physical + } else { + DamageType::Arts + }, + ); + self.enemy_damage(w, r, &mut q)?; + } + } + SpellTask::Cross { + direction, + scale, + stun, + } => { + let u = w.unit_mut(id)?; + let flags = &u.stats.stats().map_err(str::to_string)?.flags; + if u.hidden || flags.contains("stun") || flags.contains("silence") { + return Ok(false); + } + if let Some(&target) = self.cross_targets(w, id, Some(direction))?.first() { + self.caster_projectile(w, id, target, 12., DamageType::Arts, scale, stun)?; + } + } + SpellTask::Channel { + target, + jazz, + scale, + element, + } => { + let flags = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .clone(); + if flags.contains("silence") + || (!jazz && flags.contains("stun")) + || !w.unit(target)?.stats.alive + || (jazz && !w.unit(target)?.deployed) + { + self.caster_end_channel(w, r, id, jazz)?; + return Ok(false); + } + let amount = Self::tac_stat(w, id, "atk")? * scale; + let mut hit = ability_damage(Some(id), target, amount, DamageType::Arts); + self.enemy_damage(w, r, &mut hit)?; + if jazz { + let amount = Self::tac_stat(w, id, "atk")? * element; + self.enemy_element(w, r, id, target, Element::Burn, amount)?; + } else if last { + let mut targets = vec![]; + if w.unit(target)?.stats.alive && w.unit(target)?.deployed { + targets.push(target); + } + for t in spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + w.unit(target)?.position, + 1., + None, + false, + w.unit_capacity(), + )? { + if t != target && targeting::area_selectable(w, Some(id), t)? { + targets.push(t); + } + } + for t in targets { + let amount = Self::tac_stat(w, id, "atk")? * element; + self.enemy_element(w, r, id, t, Element::Apoptosis, amount)?; + } + } + if last && jazz { + self.caster_end_channel(w, r, id, true)?; + } + } + SpellTask::Cannon { tile, scale } => { + if last { + let mut state = self.content.as_ref().unwrap().caster(id); + state.cannon = false; + self.content.as_mut().unwrap().set_caster(id, state); + } + let mut keyed = vec![]; + for target in self.enemy_tile_allies(w, tile, 1)? { + if !targeting::area_selectable(w, Some(id), target)? { + continue; + } + let hp = w.unit(target)?.stats.hp; + keyed.push((target, hp / Self::tac_stat(w, target, "maxHp")?)); + } + keyed.sort_by(|a, b| b.1.total_cmp(&a.1)); + if let Some(&(target, _)) = keyed.first() { + let amount = Self::tac_stat(w, id, "atk")? * scale; + let mut hit = ability_damage(Some(id), target, amount, DamageType::Arts); + self.enemy_damage(w, r, &mut hit)?; + } + } + SpellTask::C4 { + target, + position, + scale, + } => { + let mut targets = vec![]; + if w.unit(target)?.stats.alive && w.unit(target)?.deployed { + targets.push(target); + } + for t in spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + position, + 1., + None, + false, + w.unit_capacity(), + )? { + if t != target && targeting::area_selectable(w, Some(id), t)? { + targets.push(t); + } + } + for t in targets { + let amount = Self::tac_stat(w, id, "atk")? * scale; + let mut hit = ability_damage(Some(id), t, amount, DamageType::Physical); + self.enemy_damage(w, r, &mut hit)?; + } + } + } + Ok(true) + } + fn caster_end_channel( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + jazz: bool, + ) -> Result<(), String> { + if jazz { + let mut state = self.content.as_ref().unwrap().caster(id); + state.channel = false; + self.content.as_mut().unwrap().set_caster(id, state); + } + r.remove(w, self, id, "ab:channel")?; + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_sand_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + let b = r.get(w, c.unit, c.buff)?; + let amount = b.runtime.tick_payload; + let source = b.runtime.source; + let mut hit = ability_damage(source, c.unit, amount, DamageType::Arts); + hit.is_skill = false; + hit.ignore_select = true; + hit.tags.push("sandStorm".into()); + self.enemy_damage(w, r, &mut hit) + } + pub(in crate::battle::runtime) fn enemy_burn_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + let b = r.get(w, c.unit, c.buff)?; + let mut q = ability_damage( + b.runtime.source, + c.unit, + b.runtime.tick_payload, + DamageType::Arts, + ); + q.is_skill = false; + q.ignore_select = true; + self.enemy_damage(w, r, &mut q) + } + pub(in crate::battle::runtime) fn enemy_barrier_injury( + event: &mut injury::InjuryEvent, + c: &mut settlement::Context<'_, Self>, + ) -> Result<(), String> { + if c.request.hit.damage_type != DamageType::Arts { + return Ok(()); + } + let target = c.request.hit.target; + let b = c.runtime.get(c.world, target, c.buff)?; + let left = b.runtime.tick_payload; + if left <= 0. { + return Ok(()); + } + let take = left.min(event.amount); + let rest = (left - take).max(0.); + event.amount -= take; + c.runtime + .edit(c.world, target, c.buff, |b| b.runtime.tick_payload = rest)?; + if rest <= 1e-6 { + event.defer(c.buff)?; + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn enemy_caster_hit( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &mut hit::Request, + id: Id, + ) -> Result<(), String> { + self.champion_hit(w, id, q)?; + let tomb = self.caster_config(id).and_then(|c| match c.passive { + Passive::Tomb { scale } => Some(scale), + _ => None, + }); + if let Some(scale) = tomb { + if self.content.as_ref().unwrap().caster(id).splash { + let amount = Self::tac_stat(w, id, "atk")? * scale; + for t in self.enemy_tile_allies(w, w.unit(q.hit.target)?.deployment.tile, 1)? { + if t == q.hit.target || !targeting::area_selectable(w, Some(id), t)? { + continue; + } + let mut hit = ability_damage(Some(id), t, amount, DamageType::Physical); + hit.tags.push("splash".into()); + self.enemy_damage(w, r, &mut hit)?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn enemy_caster_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + id: Id, + ) -> Result<(), String> { + self.champion_dealt(w, r, id, q)?; + let pompeii = self.caster_config(id).and_then(|c| match &c.passive { + Passive::Pompeii { + dot, + interval, + duration, + .. + } => Some((*dot, *interval, *duration)), + _ => None, + }); + if let Some((dot, interval, duration)) = pompeii { + if duration > 0. { + let mut b = buff("ab:burnDot", &[]); + b.runtime.duration = duration; + b.runtime.interval = interval; + b.runtime.source = Some(id); + b.runtime.tick_payload = dot; + b.runtime.visible = true; + b.runtime.on_tick = Some(BURN_TICK); + r.add( + w, + self, + q.hit.target, + buffs::Spec { + buff: b, + ..Default::default() + } + .retaining_unit(id), + )?; + } + } + let Some((cold, max, fall, jump)) = self.caster_config(id).and_then(|c| match &c.passive { + Passive::Snow { + cold, + max, + fall, + jump, + } => Some((*cold, *max, *fall, *jump)), + _ => None, + }) else { + return Ok(()); + }; + self.caster_cold(w, r, id, q.hit.target, cold)?; + let mut previous = q.hit.target; + let mut seen = vec![previous]; + for k in 1..max { + let mut next = None; + for t in spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + w.unit(previous)?.position, + jump, + None, + false, + w.unit_capacity(), + )? { + if !seen.contains(&t) && targeting::area_selectable(w, Some(id), t)? { + next = Some(t); + break; + } + } + let Some(target) = next else { + break; + }; + seen.push(target); + let amount = + Self::tac_stat(w, id, "atk")? * powi(fall, k as i32).map_err(str::to_string)?; + let mut hit = ability_damage(Some(id), target, amount, DamageType::Arts); + self.enemy_damage(w, r, &mut hit)?; + self.caster_cold(w, r, id, target, cold)?; + previous = target; + } + Ok(()) + } + fn caster_cold( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + target: Id, + duration: f64, + ) -> Result<(), String> { + if duration > 0. && w.unit(target)?.stats.alive { + self.apply_status( + w, + r, + target, + "cold", + status::Options { + duration, + source: Some(id), + ..Default::default() + }, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn enemy_caster_taken( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + self.champion_taken(w, r, id)?; + let (ratio, mods) = match self.caster_config(id).map(|c| &c.passive) { + Some(Passive::Mouse { ratio, scale, .. }) => (*ratio, vec![("dmgDealtMul", *scale)]), + Some(Passive::Pompeii { ratio, aspd, .. }) => (*ratio, vec![("aspd", *aspd)]), + _ => return Ok(()), + }; + let mut state = self.content.as_ref().unwrap().caster(id); + let hp = w.unit(id)?.stats.hp; + if !state.enraged && hp / Self::tac_stat(w, id, "maxHp")? < ratio { + state.enraged = true; + self.content.as_mut().unwrap().set_caster(id, state); + let mut b = buff("ab:lowhp", &mods); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_caster_profile( + &self, + id: Id, + kit: &Kit, + profile: &mut enemy::Profile, + ) { + let state = self.content.as_ref().unwrap().caster(id); + profile.no_attack |= + state.phase == Some(crate::battle::content::enemies::lifecycle::RebornPhase::Rebirth); + match self.caster_config_from(id, kit).map(|c| &c.passive) { + Some(Passive::Wolf { .. }) + if state.phase + == Some(crate::battle::content::enemies::lifecycle::RebornPhase::Revived) => + { + profile.melee = false + } + Some(Passive::Pompeii { .. }) => profile.max_targets = 4., + Some(Passive::Knight { ranged: true, .. }) => profile.max_targets = 2., + Some(Passive::Stealth { jazz: true }) => { + profile.melee = true; + profile.no_attack = state.no_attack; + } + Some(Passive::Tomb { scale }) => { + profile.atk_scale = if state.splash { *scale } else { 1. } + } + _ => {} + } + } + pub(in crate::battle::runtime) fn enemy_caster_before_status(&self, c: &mut status::Context) { + if !matches!( + c.key.as_str(), + "stun" | "freeze" | "cold" | "levitate" | "sleep" + ) { + return; + } + if self + .content + .as_ref() + .is_some_and(|r| r.caster(c.target).cannon) + { + c.cancelled = true; + } + } +} diff --git a/crates/engine/src/battle/runtime/enemies/catapult.rs b/crates/engine/src/battle/runtime/enemies/catapult.rs new file mode 100644 index 0000000..e19f972 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/catapult.rs @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use std::sync::{Arc, Mutex}; +pub(in crate::battle::runtime) type SharedVolley = Arc; +use crate::battle::{ + content::enemies::{specials::Memory, Special}, + targeting, +}; +#[derive(Debug)] +pub(in crate::battle::runtime) struct Volley { + pub target: Option, + position: Mutex<[f64; 2]>, + radius: f64, + bound: f64, + in_play: bool, +} +impl Host { + pub(super) fn enemy_catapult_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: &enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + let id = c.enemy; + let Kit::Special(Special::Catapult { + times, + interval, + radius, + bound, + }) = self.content.as_ref().unwrap().kit(id) + else { + return Ok(()); + }; + if event == enemy::Event::BeforeAttack { + if let Some(&target) = c.targets.first() { + self.content.as_mut().unwrap().set_special( + id, + Memory::Catapult { + target: Some(target), + position: Some(w.unit(target)?.position), + }, + ); + } + } + if event != enemy::Event::Attack { + return Ok(()); + } + let Memory::Catapult { target, position } = self.content.as_ref().unwrap().special(id) + else { + unreachable!() + }; + let in_play = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("inPlay") + || w.unit(id)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some("inPlay")); + let volley = Arc::new(Volley { + target, + position: Mutex::new(position.unwrap_or(w.unit(id)?.position)), + radius: if in_play { radius } else { 1.5 }, + bound, + in_play, + }); + self.enemy_catapult_stone(w, r, id, &volley)?; + if interval > 0. && times > 1 { + for stone in 1..times { + self.enemy_schedule( + w, + Some(id), + interval * f64::from(stone), + 0., + 1, + EnemyTask::Catapult(Arc::clone(&volley)), + )?; + } + } else { + for _ in 1..times { + self.enemy_catapult_stone(w, r, id, &volley)?; + } + } + Ok(()) + } + pub(super) fn enemy_catapult_stone( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + volley: &Volley, + ) -> Result<(), String> { + let mut position = { + let mut aim = volley.position.lock().unwrap(); + if let Some(t) = volley.target { + if w.unit(t)?.stats.alive { + *aim = w.unit(t)?.position; + } + } + *aim + }; + if volley.in_play { + // The source rolls x before y. World coordinates are row, column. + position[1] += (self.rng.next_f64() * 2. - 1.) * volley.bound.max(0.); + position[0] += (self.rng.next_f64() * 2. - 1.) * volley.bound.max(0.); + } + let mut primary = None; + if !volley.in_play { + if let Some(t) = volley.target { + if w.unit(t)?.stats.alive + && targeting::can_target_ally( + w, + id, + t, + true, + targeting::Profile { + block_free: true, + ..Default::default() + }, + )? + { + primary = Some(t); + self.catapult_damage(w, r, id, t, false)?; + } + } + } + if volley.radius > 0. { + for t in spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + position, + volley.radius, + None, + false, + w.unit_capacity(), + )? { + if Some(t) != primary && targeting::area_selectable(w, Some(id), t)? { + self.catapult_damage(w, r, id, t, true)?; + } + } + } + Ok(()) + } + fn catapult_damage( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + target: Id, + splash: bool, + ) -> Result<(), String> { + let amount = Self::tac_stat(w, id, "atk")?; + let mut q = ability_damage(Some(id), target, amount, DamageType::Physical); + q.is_attack = true; + q.is_skill = false; + q.is_splash = splash; + q.dodge_mode = crate::battle::injury::DodgeMode::Normal; + q.tags = vec!["catapult:stone".into()]; + self.enemy_damage(w, r, &mut q) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/dots.rs b/crates/engine/src/battle/runtime/enemies/dots.rs new file mode 100644 index 0000000..8bd9c8d --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/dots.rs @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{element, targeting}; + +pub(in crate::battle::runtime) const BLEED: u64 = 1700; +impl Host { + pub(super) fn enemy_bleed( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + amount: f64, + duration: f64, + ) -> Result<(), String> { + if amount <= 0. || duration <= 0. || !w.unit(target)?.stats.alive { + return Ok(()); + } + let mut b = buff("ab:bleed", &[]); + b.runtime.source = Some(source); + b.runtime.duration = duration; + b.runtime.interval = 1.; + b.runtime.tick_payload = amount; + b.runtime.visible = true; + b.runtime.on_tick = Some(BLEED); + r.add( + w, + self, + target, + buffs::Spec { + buff: b, + ..Default::default() + } + .retaining_unit(source), + )?; + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_bleed_event( + &mut self, + event: buffs::Event, + c: buffs::Context, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + let b = r.get(w, c.unit, c.buff)?; + let source = b.runtime.source.ok_or("Missing bleed source")?; + let amount = b.runtime.tick_payload; + if event != buffs::Event::Tick { + return Err("Unexpected bleed callback".into()); + } + let mut damage = ability_damage(Some(source), c.unit, amount, DamageType::Arts); + damage.is_skill = false; + damage.ignore_select = true; + damage.tags.push("bleed".into()); + self.enemy_damage(w, r, &mut damage) + } + pub(super) fn enemy_dot_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ability: Ability, + ) -> Result<(), String> { + let (radius, scale, burn, dodge, no_air, tag) = match ability { + Ability::Nest { radius, .. } => { + if w.unit(id)?.hidden { + return Ok(()); + } + (radius, 1., 0., true, false, "nestPulse") + } + Ability::Boil { + radius, + scale, + burn, + .. + } => (radius, scale, burn, false, true, "boil"), + _ => return Ok(()), + }; + for target in enemy::Hooks::allies_in_radius(self, id, radius, w, w.unit_capacity())? { + if no_air && w.unit(target)?.motion_fly + || !targeting::area_selectable(w, Some(id), target)? + { + continue; + } + let atk = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk"); + let mut damage = ability_damage(Some(id), target, atk * scale, DamageType::Arts); + damage.tags.push(tag.into()); + if dodge { + damage.dodge_mode = crate::battle::injury::DodgeMode::Normal; + } + self.enemy_damage(w, r, &mut damage)?; + if burn > 0. { + let amount = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * burn; + self.enemy_element(w, r, id, target, element::Element::Burn, amount)?; + } + } + Ok(()) + } + pub(super) fn enemy_element( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + kind: element::Element, + amount: f64, + ) -> Result<(), String> { + if amount <= 0. { + return Ok(()); + } + let mut effect = element::Request::new(Some(source), Some(source), target, kind, amount); + effect.damage.tags = vec!["enemyAbility".into()]; + effect.damage.attack_type = hit::AttackType::None; + element::apply(w, self, r, &mut effect).map(|_| ()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/families.rs b/crates/engine/src/battle/runtime/enemies/families.rs new file mode 100644 index 0000000..ec12b25 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/families.rs @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{content::enemies::Family, element, targeting}; +use crate::deterministic::math::hypot; + +impl Host { + pub(super) fn liberate_prisoner( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result { + if !w.unit(id)?.stats.alive { + return Ok(false); + } + let Some(p) = self.content.as_mut().unwrap().free_prisoner(id) else { + return Ok(false); + }; + r.remove(w, self, id, "ab:confined")?; + let mut b = buff( + "ab:liberty", + &[ + ("atkPct", p.atk), + ("defIgnorePct", p.penetration), + ("resFlat", p.res), + ("hpRegen", p.regen), + ], + ); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + Ok(p.free_all && self.content.as_mut().unwrap().free_all_once()) + } + pub(super) fn enemy_family_attack( + &mut self, + event: enemy::Event, + c: &mut enemy::Context, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + match self.content.as_ref().unwrap().kit(c.enemy) { + Kit::Family(Family::Prisoner(_)) if event == enemy::Event::BeforeAttack => { + if self.content.as_mut().unwrap().prisoner_attack(c.enemy) + && self.liberate_prisoner(w, r, c.enemy)? + { + let ids = self.spawns.as_ref().unwrap().live().to_vec(); + for id in ids { + self.liberate_prisoner(w, r, id)?; + } + } + } + Kit::Family(Family::ShadowKiller { .. }) if event == enemy::Event::Attack => { + self.content.as_mut().unwrap().shadow_spent(c.enemy) + } + Kit::Ability(Ability::Tide { .. }) | Kit::Split(content::Split::Boat { .. }) + if event == enemy::Event::BeforeAttack => + { + let Some(&first) = c.targets.first() else { + return Ok(()); + }; + let tile = w.unit(first)?.deployment.tile; + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + for id in ids { + let at = w.unit(id)?.deployment.tile; + if (at[0] - tile[0]).abs() + (at[1] - tile[1]).abs() <= 1 + && !c.targets.contains(&id) + && targeting::area_selectable(w, Some(c.enemy), id)? + { + c.targets.push(id); + } + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_content_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + ) -> Result<(), String> { + if let Some(source) = q.hit.source { + if let Kit::Ability(Ability::Nest { ratio, .. }) = + self.content.as_ref().unwrap().kit(source) + { + if w.unit(source)?.stats.alive + && q.tags.iter().any(|t| t == "nestPulse") + && q.hit.damage_type != DamageType::Elemental + && ratio > 0. + { + let amount = w + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * ratio; + self.enemy_element( + w, + r, + source, + q.hit.target, + element::Element::Neural, + amount, + )?; + } + } + } + if !q.is_attack + || q.hit.damage_type == DamageType::Elemental + || w.unit(q.hit.target)?.side != health::Side::Ally + { + return Ok(()); + } + let Some(id) = q.hit.source else { + return Ok(()); + }; + self.enemy_boss_dealt(w, r, id, q.hit.target)?; + self.enemy_special_dealt(w, r, q, id)?; + self.enemy_caster_dealt(w, r, q, id)?; + self.enemy_leader_dealt(w, r, q, id)?; + self.enemy_lifecycle_dealt(w, r, q, id)?; + self.enemy_reaction_dealt(w, r, q, id)?; + self.enemy_zone_dealt(w, q, id)?; + if let Kit::Ability(Ability::Bleed { amount, duration }) = + self.content.as_ref().unwrap().kit(id) + { + self.enemy_bleed(w, r, id, q.hit.target, amount, duration)?; + } + if let Kit::Family(Family::Tear { stun, .. }) = self.content.as_ref().unwrap().kit(id) { + if stun > 0. { + self.apply_status( + w, + r, + q.hit.target, + "stun", + status::Options { + source: Some(id), + duration: stun, + ..Default::default() + }, + )?; + } + } + Ok(()) + } + pub(super) fn enemy_nearby( + &mut self, + w: &mut World, + id: Id, + radius: f64, + ) -> Result, String> { + let ids = self.spawns.as_ref().unwrap().live().to_vec(); + spatial::enemies_in_radius( + w, + self, + &ids, + w.unit(id)?.position, + radius, + RadiusRule::Body, + false, + w.unit_capacity(), + ) + } + pub(super) fn enemy_family_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + family: Family, + dt: f64, + ) -> Result<(), String> { + if let Family::ShadowKiller { .. } = family { + let on = targeting::enemy_stealthed(w, id)?; + self.content.as_mut().unwrap().shadow_tick(id, on); + return Ok(()); + } + if matches!(family, Family::Prisoner(_) | Family::Tear { .. }) { + return Ok(()); + } + let pulses = self.content.as_mut().unwrap().pulses(id, dt, 0.5); + for _ in 0..pulses { + match family { + Family::Phalanx { radius, def, .. } => { + let key = self.spawns.as_ref().unwrap().definition(id)?.key.clone(); + let mut n = 0; + for other in self.enemy_nearby(w, id, radius)? { + if other != id + && self.spawns.as_ref().unwrap().definition(other)?.key == key + { + n += 1; + } + } + if n > 0 { + let mut b = buff("ab:phalanx", &[("defFlat", def * n as f64)]); + b.runtime.duration = 0.6; + self.enemy_buff(w, r, id, b)?; + } + } + Family::HolyGuard { radius, aspd, .. } => { + let mut on = false; + for other in self.enemy_nearby(w, id, radius)? { + if self + .spawns + .as_ref() + .unwrap() + .definition(other)? + .key + .contains("enemy_1175_dushdo") + { + on = true; + break; + } + } + if !on { + continue; + } + let targets = + enemy::Hooks::allies_in_radius(self, id, radius, w, w.unit_capacity())?; + for target in targets { + if !targeting::aura_selectable(w, target)? { + continue; + } + let mut b = buff("ab:forceField", &[("aspd", aspd)]); + b.runtime.duration = 0.6; + b.runtime.visible = true; + self.enemy_buff(w, r, target, b)?; + } + } + Family::ShadowBlade { bat } => { + let mut partner = None; + for other in self.enemy_nearby(w, id, 3.)? { + if self + .spawns + .as_ref() + .unwrap() + .definition(other)? + .key + .contains("enemy_1174_duholy") + { + partner = Some(other); + break; + } + } + let Some(partner) = partner else { + continue; + }; + let radius = match self.content.as_ref().unwrap().kit(partner) { + Kit::Family(Family::HolyGuard { radius, .. }) => radius, + _ => 1.1, + }; + let a = w.unit(id)?.position; + let b = w.unit(partner)?.position; + let base = w.unit(id)?.stats.base_number("bat"); + if base > 0. && hypot(a[0] - b[0], a[1] - b[1]) <= radius + 1e-9 { + let mut b = buff("ab:shadowSync", &[("batPct", bat / base)]); + b.runtime.duration = 0.6; + self.enemy_buff(w, r, id, b)?; + } + } + _ => unreachable!(), + } + } + Ok(()) + } + pub(super) fn enemy_element_pulse( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + radius: f64, + ratio: f64, + ) -> Result<(), String> { + let targets = enemy::Hooks::allies_in_radius(self, id, radius, w, w.unit_capacity())?; + for target in targets { + if !targeting::area_selectable(w, Some(id), target)? { + continue; + } + let amount = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * ratio; + if amount <= 0. { + continue; + } + let mut effect = + element::Request::new(Some(id), Some(id), target, element::Element::Neural, amount); + effect.damage.attack_type = hit::AttackType::None; + effect.damage.tags = vec!["enemyAbility".into()]; + element::apply(w, self, r, &mut effect)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/forms.rs b/crates/engine/src/battle/runtime/enemies/forms.rs new file mode 100644 index 0000000..6af4b52 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/forms.rs @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::content::enemies::forms::{HuskPhase, State, StonePhase}; + +#[derive(Clone, Copy)] +pub(in crate::battle::runtime) enum FormEvent { + HuskEnter, + HuskRevive, + StoneFlight, +} +impl Host { + pub(super) fn enemy_cleanse_rebirth( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let mut remove = vec![]; + for b in w.unit(id)?.stats.buffs() { + if b.runtime.persist + || b.runtime + .source + .is_some_and(|s| w.unit(s).is_ok_and(|u| u.side == health::Side::Enemy)) + { + continue; + } + if b.runtime.source.is_some() + || b.runtime.status.is_some() + || b.key.as_deref() == Some("terrain:infection") + { + remove.push(b.runtime.id()); + } + } + for buff in remove { + r.remove_id(w, self, id, buff)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_knockout( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result { + if self.enemy_special_knockout(w, id)? { + return Ok(true); + } + if self.enemy_reborn_knockout(w, r, id)? { + return Ok(true); + } + let Some(form) = self.content.as_ref().unwrap().form(id) else { + return Ok(false); + }; + match form { + State::Husk { + phase: HuskPhase::Rebirth { until, .. }, + .. + } if w.time < until => { + let max = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp"); + w.unit_mut(id)?.stats.hp = max; + Ok(true) + } + State::Husk { + config, + phase: HuskPhase::Living { original }, + } if config.hits > 0. && config.delay > 0. => { + let original = original.unwrap_or(w.unit(id)?.stats.base_number("maxHp")); + self.content.as_mut().unwrap().set_form( + id, + State::Husk { + config, + phase: HuskPhase::Rebirth { + original, + until: w.time + 1., + }, + }, + ); + w.unit_mut(id)?.motion.unbalance_until = f64::NEG_INFINITY; + self.enemy_cleanse_rebirth(w, r, id)?; + let hits = (config.hits + 0.5).floor().max(1.); + let u = w.unit_mut(id)?; + u.stats.edit_base(|b| { + b.0.insert("maxHp".into(), hits); + }); + u.stats.stats().map_err(str::to_string)?; + u.stats.hp = hits; + u.last_attack_at = f64::NEG_INFINITY; + let mut count = buff("ab:hitCount", &[]); + count.flags.insert("hitCount".into()); + count.runtime.persist = true; + self.enemy_buff(w, r, id, count)?; + let mut husk = buff(config.key(), &[]); + husk.runtime.persist = true; + husk.runtime.visible = true; + husk.flags.insert("disarm".into()); + husk.flags.insert( + if config.regen { + "unblockable" + } else { + "stealth" + } + .into(), + ); + self.enemy_buff(w, r, id, husk)?; + let mut reborn = buff(&format!("{}:reborn", config.key()), &[]); + reborn.runtime.duration = 1.; + reborn.flags = [ + "invulnerable", + "untargetable", + "unblockable", + "noMove", + "noDisplace", + ] + .map(str::to_string) + .into(); + self.enemy_buff(w, r, id, reborn)?; + blocking::unblock( + w, + &mut allies::Blocking { + host: self, + buffs: r, + }, + id, + )?; + if let Some(route) = w.unit_mut(id)?.motion.route.as_mut() { + route.points = None; + } + self.enemy_schedule( + w, + Some(id), + 1., + 0., + 1, + EnemyTask::Form(FormEvent::HuskEnter), + )?; + self.enemy_schedule( + w, + Some(id), + 1. + config.delay, + 0., + 1, + EnemyTask::Form(FormEvent::HuskRevive), + )?; + Ok(true) + } + State::Stone { + config, + phase: StonePhase::Ground, + } if config.duration > 0. => { + self.content.as_mut().unwrap().set_form( + id, + State::Stone { + config, + phase: StonePhase::Stone, + }, + ); + self.enemy_cleanse_rebirth(w, r, id)?; + let u = w.unit_mut(id)?; + u.stats.hp = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + u.immune.insert("levitate".into()); + let mut stone = buff( + "ab:stone", + &[("defFlat", config.def), ("resFlat", config.stone_res)], + ); + stone.runtime.duration = config.duration; + stone.runtime.visible = true; + stone.flags = ["noMove", "selfBound", "unblockable", "noDisplace"] + .map(str::to_string) + .into(); + self.enemy_buff(w, r, id, stone)?; + self.enemy_schedule( + w, + Some(id), + config.duration, + 0., + 1, + EnemyTask::Form(FormEvent::StoneFlight), + )?; + Ok(true) + } + _ => Ok(false), + } + } + pub(super) fn enemy_form_event( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + event: FormEvent, + ) -> Result<(), String> { + let Some(state) = self.content.as_ref().unwrap().form(id) else { + return Ok(()); + }; + match (state, event) { + ( + State::Husk { + config, + phase: HuskPhase::Rebirth { original, .. }, + }, + FormEvent::HuskEnter, + ) => { + self.content.as_mut().unwrap().set_form( + id, + State::Husk { + config, + phase: HuskPhase::Husk { original }, + }, + ); + if config.shield > 0 { + for other in self.enemy_nearby(w, id, 1.8)? { + if other == id { + continue; + } + let mut shield = buff("ab:hitShield", &[]); + shield.runtime.shield_hits = config.shield; + shield.runtime.refresh = buffs::Refresh::Extend; + shield.runtime.injury.shield_types = + Some(vec![DamageType::Physical, DamageType::Arts]); + self.enemy_buff(w, r, other, shield)?; + } + } + } + ( + State::Husk { + config, + phase: HuskPhase::Husk { original }, + }, + FormEvent::HuskRevive, + ) => { + self.content.as_mut().unwrap().set_form( + id, + State::Husk { + config, + phase: HuskPhase::Living { + original: Some(original), + }, + }, + ); + r.remove(w, self, id, "ab:hitCount")?; + let u = w.unit_mut(id)?; + u.stats.edit_base(|b| { + b.0.insert("maxHp".into(), original); + }); + u.stats.hp = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + r.remove(w, self, id, config.key())?; + r.remove(w, self, id, &format!("{}:reborn", config.key()))?; + if let Some(route) = w.unit_mut(id)?.motion.route.as_mut() { + route.points = None; + } + w.unit_mut(id)?.cadence.cooldown = 0.; + } + ( + State::Stone { + config, + phase: StonePhase::Stone, + }, + FormEvent::StoneFlight, + ) => { + self.content.as_mut().unwrap().set_form( + id, + State::Stone { + config, + phase: StonePhase::Flight, + }, + ); + w.unit_mut(id)?.motion_fly = true; + let mut flight = buff("ab:flight", &[]); + flight.runtime.persist = true; + flight.flags.insert("noDisplace".into()); + self.enemy_buff(w, r, id, flight)?; + if let Some(route) = w.unit_mut(id)?.motion.route.as_mut() { + route.points = None; + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_form_profile( + &self, + id: Id, + profile: &mut enemy::Profile, + ) { + match self.content.as_ref().unwrap().form(id) { + Some(State::Husk { + phase: HuskPhase::Rebirth { .. } | HuskPhase::Husk { .. }, + .. + }) => profile.no_attack = true, + Some(State::Stone { phase, .. }) => { + profile.melee = phase != StonePhase::Flight; + profile.no_attack |= phase == StonePhase::Stone; + if phase == StonePhase::Flight { + profile.mode = enemy::Mode::Damage(DamageType::Arts); + } + } + _ => {} + } + } + pub(in crate::battle::runtime) fn enemy_cancel_form_timers( + &mut self, + w: &mut World, + id: Id, + ) -> Result<(), String> { + let mut removed = 0; + self.tactical_timers.retain(|t| { + let remove = t.source == Some(id) + && matches!( + t.kind, + super::super::tactics::Task::Enemy(EnemyTask::Form(_)) + ); + if remove { + removed += 1; + } + !remove + }); + self.tactical_slots -= removed; + for _ in 0..removed { + w.unpin_unit(id)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/leaders.rs b/crates/engine/src/battle/runtime/enemies/leaders.rs new file mode 100644 index 0000000..083274f --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/leaders.rs @@ -0,0 +1,391 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::{leaders::Memory, Leader}, + targeting, +}; +use crate::deterministic::math::hypot; +pub(in crate::battle::runtime) const LANDING: u64 = 1702; +impl Host { + pub(super) fn enemy_tile_allies( + &self, + w: &World, + tile: [i32; 2], + reach: i32, + ) -> Result, String> { + let mut out = vec![]; + for &id in self.roster.as_ref().unwrap().ids() { + let u = w.unit(id)?; + let at = u.deployment.tile; + if u.stats.alive + && u.deployed + && !u.hidden + && (at[0] - tile[0]).abs() <= reach + && (at[1] - tile[1]).abs() <= reach + { + out.push(id); + } + } + Ok(out) + } + pub(super) fn enemy_skull_debuff( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + defense: f64, + ) -> Result<(), String> { + if defense != 0. { + self.apply_status( + w, + r, + target, + "defDown", + status::Options { + source: Some(source), + duration: 5., + value: Some(defense), + ..Default::default() + }, + )?; + } + Ok(()) + } + pub(super) fn enemy_leader_hit( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &mut hit::Request, + id: Id, + ) -> Result<(), String> { + match self.content.as_ref().unwrap().kit(id) { + Kit::Leader(Leader::Skull { defense, .. }) + if matches!( + self.content.as_ref().unwrap().leader(id), + Memory::Skull { splash: true, .. } + ) => + { + let amount = Self::tac_stat(w, id, "atk")? * 0.26; + for target in self.enemy_tile_allies(w, w.unit(q.hit.target)?.deployment.tile, 1)? { + if target == q.hit.target || !targeting::area_selectable(w, Some(id), target)? { + continue; + } + let mut hit = ability_damage(Some(id), target, amount, DamageType::Physical); + hit.tags.push("splash".into()); + self.enemy_damage(w, r, &mut hit)?; + self.enemy_skull_debuff(w, r, id, target, defense)?; + } + } + Kit::Leader(Leader::Demon { scale, .. }) => { + let pos = w.unit(id)?.position.map(|x| (x + 0.5).floor() as i32); + let tile = w.unit(q.hit.target)?.deployment.tile; + if (tile[0] - pos[0]).abs() <= 1 && (tile[1] - pos[1]).abs() <= 1 { + q.damage.amount *= scale; + } + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_leader_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + id: Id, + ) -> Result<(), String> { + if let Kit::Leader(Leader::Skull { defense, .. }) = self.content.as_ref().unwrap().kit(id) { + if matches!( + self.content.as_ref().unwrap().leader(id), + Memory::Skull { splash: true, .. } + ) { + self.enemy_skull_debuff(w, r, id, q.hit.target, defense)?; + } + } + Ok(()) + } + pub(super) fn enemy_leader_taken( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + amount: f64, + ) -> Result<(), String> { + let id = q.hit.target; + match self.content.as_ref().unwrap().kit(id) { + Kit::Leader(Leader::Skull { ratio, atk, .. }) => { + let Memory::Skull { splash, enraged } = self.content.as_ref().unwrap().leader(id) + else { + unreachable!() + }; + let hp = w.unit(id)?.stats.hp; + if enraged || hp / Self::tac_stat(w, id, "maxHp")? >= ratio { + return Ok(()); + } + self.content.as_mut().unwrap().set_leader( + id, + Memory::Skull { + splash, + enraged: true, + }, + ); + let mut b = buff("ab:lowhp", &[("atkPct", atk)]); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + Kit::Leader(Leader::Vines { + duration, scale, .. + }) if duration > 0. && amount > 0. && q.tags.iter().any(|t| t == "terrain") => { + let mut b = buff("ab:natureWeak", &[("dmgTakenMul", scale)]); + b.runtime.duration = duration; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_leader_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: &enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + let id = c.enemy; + match self.content.as_ref().unwrap().kit(id) { + Kit::Leader(Leader::Skull { .. }) if event == enemy::Event::BeforeAttack => { + let Memory::Skull { enraged, .. } = self.content.as_ref().unwrap().leader(id) + else { + unreachable!() + }; + self.content.as_mut().unwrap().set_leader( + id, + Memory::Skull { + enraged, + splash: w.unit(id)?.blocked_by().is_none(), + }, + ); + } + Kit::Leader(Leader::Axe { atk, aspd, max, .. }) if event == enemy::Event::Attack => { + self.content + .as_mut() + .unwrap() + .set_leader(id, Memory::Axe { last: Some(w.time) }); + let mut b = buff("ab:axeStack", &[("atkPct", atk), ("aspd", aspd)]); + b.runtime.persist = true; + b.runtime.refresh = buffs::Refresh::Stack; + b.runtime.max_stacks = max; + self.enemy_buff(w, r, id, b)?; + } + Kit::Leader(Leader::Vines { every, stun, .. }) if event == enemy::Event::Attack => { + let Memory::Vines { count } = self.content.as_ref().unwrap().leader(id) else { + unreachable!() + }; + let next = count.saturating_add(1); + let fire = every > 0 && next >= every; + self.content.as_mut().unwrap().set_leader( + id, + Memory::Vines { + count: if fire { 0 } else { next }, + }, + ); + if !fire || stun <= 0. { + return Ok(()); + } + for &target in &c.targets { + let u = w.unit(target)?; + if u.stats.alive && c.deployments.contains(&(target, u.deployment.deploy_seq)) { + self.apply_status( + w, + r, + target, + "stun", + status::Options { + duration: stun, + source: Some(id), + ..Default::default() + }, + )?; + } + } + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_leader_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + kit: Leader, + dt: f64, + ) -> Result<(), String> { + match kit { + Leader::Axe { delay, .. } => { + let pulses = self.content.as_mut().unwrap().pulses(id, dt, 0.5); + for _ in 0..pulses { + if let Memory::Axe { last: Some(last) } = + self.content.as_ref().unwrap().leader(id) + { + if w.time - last >= delay { + self.content + .as_mut() + .unwrap() + .set_leader(id, Memory::Axe { last: None }); + r.remove(w, self, id, "ab:axeStack")?; + } + } + } + } + Leader::Demon { aspd, .. } => { + let pulses = self.content.as_mut().unwrap().pulses(id, dt, 0.5); + for _ in 0..pulses { + let tile = w.unit(id)?.position.map(|x| (x + 0.5).floor() as i32); + for target in self.enemy_tile_allies(w, tile, 1)? { + let mut b = buff("ab:blackFog", &[("aspd", aspd)]); + b.runtime.duration = 0.6; + b.runtime.visible = true; + self.enemy_buff(w, r, target, b)?; + } + } + } + Leader::Balloon { + skill: Some(skill), + duration, + speed, + } => { + let Memory::Balloon { mut left } = self.content.as_ref().unwrap().leader(id) else { + unreachable!() + }; + let castable = + self.enemy_can_cast(w, id, false)? && w.unit(id)?.blocked_by().is_some(); + let cast = skill.advance(&mut left, dt, castable); + self.content + .as_mut() + .unwrap() + .set_leader(id, Memory::Balloon { left }); + if cast { + let mut b = buff("ab:takeoff", &[("moveMul", 1. + speed)]); + b.runtime.duration = duration; + b.runtime.visible = true; + b.runtime.on_expire = Some(LANDING); + b.flags + .extend(["unblockable", "float", "noDisplace"].map(str::to_string)); + self.enemy_buff(w, r, id, b)?; + let mut b = buff("ab:takeoffBrake", &[("moveMul", 0.1)]); + b.runtime.duration = 1.5; + self.enemy_buff(w, r, id, b)?; + } + } + Leader::Spin { + skill, + duration, + interval, + radius, + scale, + } => { + let Memory::Spin { + mut left, + mut until, + previous, + hidden, + .. + } = self.content.as_ref().unwrap().leader(id) + else { + unreachable!() + }; + let flags = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .clone(); + if !flags.contains("silence") { + let pulses = self.content.as_mut().unwrap().pulses(id, dt, interval); + for _ in 0..pulses { + if until <= w.time + || flags.contains("stun") + || flags.contains("sleep") + || flags.contains("disarm") + { + continue; + } + let amount = Self::tac_stat(w, id, "atk")? * scale; + for target in + enemy::Hooks::allies_in_radius(self, id, radius, w, w.unit_capacity())? + { + if w.unit(target)?.motion_fly + || !targeting::area_selectable(w, Some(id), target)? + { + continue; + } + let mut hit = + ability_damage(Some(id), target, amount, DamageType::Physical); + self.enemy_damage(w, r, &mut hit)?; + } + } + } + let castable = self.enemy_can_cast(w, id, true)?; + if skill.is_some_and(|s| s.advance(&mut left, dt, castable)) { + until = w.time + duration; + } + let no_attack = until > w.time; + let u = w.unit(id)?; + let position = u.position; + let now_hidden = u.hidden; + if let Some(p) = previous.filter(|_| !hidden && !now_hidden) { + let speed = Self::tac_stat(w, id, "moveSpeed")?; + if hypot(position[1] - p[1], position[0] - p[0]) + - (speed * 0.5 * dt * 1.5 + 1e-3) + > 0.05 + && until > w.time + { + until = 0.; + } + } + self.content.as_mut().unwrap().set_leader( + id, + Memory::Spin { + left, + until, + no_attack, + previous: Some(position), + hidden: now_hidden, + }, + ); + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_landing( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if w.unit(id)?.stats.alive { + let mut b = buff("ab:landing", &[("moveMul", 0.1)]); + b.runtime.duration = 1.333; + b.flags.insert("unblockable".into()); + self.enemy_buff(w, r, id, b)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_leader_profile( + &self, + id: Id, + profile: &mut enemy::Profile, + ) { + match self.content.as_ref().unwrap().leader(id) { + Memory::Skull { splash, .. } => profile.atk_scale = if splash { 0.26 } else { 1. }, + Memory::Spin { no_attack, .. } => profile.no_attack = no_attack, + _ => {} + } + } +} diff --git a/crates/engine/src/battle/runtime/enemies/lifecycle.rs b/crates/engine/src/battle/runtime/enemies/lifecycle.rs new file mode 100644 index 0000000..58bfd4f --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/lifecycle.rs @@ -0,0 +1,430 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::{ + lifecycle::{Memory, RebornPhase}, + Lifecycle, + }, + element, projectiles, targeting, +}; +use crate::deterministic::math::hypot; +pub(in crate::battle::runtime) const REBORN_FINISH: u64 = 1701; +impl Host { + pub(in crate::battle::runtime) fn enemy_lifecycle_profile( + &self, + id: Id, + kit: &Kit, + profile: &mut enemy::Profile, + ) { + match kit { + Kit::Lifecycle(Lifecycle::Seed) => profile.no_attack = true, + Kit::Lifecycle(kit) if kit.rebirth().is_some() => { + profile.no_attack |= + self.content.as_ref().unwrap().reborn_phase(id) == Some(RebornPhase::Rebirth); + match kit { + Lifecycle::Warden { .. } => { + profile.melee = self.content.as_ref().unwrap().reborn_phase(id) + == Some(RebornPhase::Revived) + } + Lifecycle::Ugly { .. } => { + profile.melee = false; + profile.no_attack |= self.content.as_ref().unwrap().reborn_phase(id) + == Some(RebornPhase::Revived); + profile.atk_scale = match self.content.as_ref().unwrap().lifecycle(id) { + Memory::Ugly { splash: true, .. } => 1., + _ => { + if let Lifecycle::Ugly { melee, .. } = kit { + *melee + } else { + 1. + } + } + }; + } + _ => {} + } + } + _ => {} + } + } + pub(super) fn enemy_lifecycle_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + id: Id, + ) -> Result<(), String> { + self.enemy_rebirth_dealt(w, r, q, id)?; + let Kit::Lifecycle(Lifecycle::Vine { first, normal, .. }) = + self.content.as_ref().unwrap().kit(id) + else { + return Ok(()); + }; + let Memory::Vine { + start, + first: initial, + } = self.content.as_ref().unwrap().lifecycle(id) + else { + unreachable!() + }; + if !initial { + let amount = Self::tac_stat(w, id, "atk")? * normal; + return self.enemy_element(w, r, id, q.hit.target, element::Element::Burn, amount); + } + self.content.as_mut().unwrap().set_lifecycle( + id, + Memory::Vine { + start, + first: false, + }, + ); + let tile = w.unit(q.hit.target)?.deployment.tile; + let mut targets = vec![q.hit.target]; + for target in self.roster.as_ref().unwrap().ids().to_vec() { + if target == q.hit.target { + continue; + } + let at = w.unit(target)?.deployment.tile; + if (at[0] - tile[0]).abs() <= 1 + && (at[1] - tile[1]).abs() <= 1 + && targeting::area_selectable(w, Some(id), target)? + { + targets.push(target); + } + } + for target in targets { + let amount = Self::tac_stat(w, id, "atk")?; + if target != q.hit.target { + let mut hit = ability_damage(Some(id), target, amount, DamageType::Arts); + self.enemy_damage(w, r, &mut hit)?; + } + let amount = Self::tac_stat(w, id, "atk")? * first; + self.enemy_element(w, r, id, target, element::Element::Burn, amount)?; + } + r.remove(w, self, id, "ab:pow")?; + Ok(()) + } + pub(super) fn enemy_lifecycle_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: &enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + let id = c.enemy; + self.enemy_rebirth_attack(w, r, c, event)?; + if event == enemy::Event::Attack + && matches!( + self.content.as_ref().unwrap().kit(id), + Kit::Lifecycle(Lifecycle::Vine { .. }) + ) + { + for other in self.enemy_nearby(w, id, 1.5)? { + if self.spawns.as_ref().unwrap().definition(other)?.key == "enemy_10065_ftzlc" + && matches!( + self.content.as_ref().unwrap().lifecycle(other), + Memory::Ignitable { on: false } + ) + { + self.content + .as_mut() + .unwrap() + .set_lifecycle(other, Memory::Ignitable { on: true }); + } + } + } + Ok(()) + } + pub(super) fn enemy_lifecycle_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Kit::Lifecycle(Lifecycle::Ignitable { scale }) = self.content.as_ref().unwrap().kit(id) + else { + return Ok(()); + }; + if !matches!( + self.content.as_ref().unwrap().lifecycle(id), + Memory::Ignitable { on: true } + ) || silenced(w, id)? + { + return Ok(()); + } + let amount = Self::tac_stat(w, id, "atk")? * scale; + for target in enemy::Hooks::allies_in_radius(self, id, 1.25, w, w.unit_capacity())? { + if w.unit(target)?.motion_fly || !targeting::area_selectable(w, Some(id), target)? { + continue; + } + let mut hit = ability_damage(Some(id), target, amount, DamageType::Arts); + self.enemy_damage(w, r, &mut hit)?; + } + Ok(()) + } + pub(super) fn enemy_lifecycle_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + kit: Lifecycle, + dt: f64, + ) -> Result<(), String> { + self.enemy_reid_tick(w, r, id, kit, dt)?; + match kit { + Lifecycle::Vine { attack, time, .. } => { + let Memory::Vine { start, first } = self.content.as_ref().unwrap().lifecycle(id) + else { + unreachable!() + }; + self.content + .as_mut() + .unwrap() + .set_lifecycle(id, Memory::Vine { start, first }); + let pulses = self.content.as_mut().unwrap().pulses(id, dt, 0.5); + for _ in 0..pulses { + if !first || time <= 0. { + continue; + } + let mut b = buff( + "ab:pow", + &[("atkPct", attack * ((w.time - start) / time).min(1.))], + ); + b.runtime.persist = true; + self.enemy_buff(w, r, id, b)?; + } + } + Lifecycle::Brood { skill: Some(skill) } => { + let Memory::Brood { mut left } = self.content.as_ref().unwrap().lifecycle(id) + else { + unreachable!() + }; + let castable = self.enemy_can_cast(w, id, false)?; + let cast = skill.advance(&mut left, dt, castable); + self.content + .as_mut() + .unwrap() + .set_lifecycle(id, Memory::Brood { left }); + if cast { + let children = + self.enemy_children_spec(w, id, Arc::from("enemy_1269_nhfly"), 3)?; + self.enemy_spawn_children(w, r, children)?; + } + } + Lifecycle::Seed + if matches!( + self.content.as_ref().unwrap().lifecycle(id), + Memory::Seed { projectile: None } + ) => + { + if w.time < w.unit(id)?.motion.unbalance_until - 1e-9 { + return Ok(()); + } + let radius = w.unit(id)?.stats.base_number("rangeRadius"); + let mut targets = + self.enemy_targets_near(w, id, if radius == 0. { 1. } else { radius })?; + let position = w.unit(id)?.position; + targets.sort_by(|&a, &b| { + let a = w.unit(a).unwrap().position; + let b = w.unit(b).unwrap().position; + hypot(a[1] - position[1], a[0] - position[0]) + .total_cmp(&hypot(b[1] - position[1], b[0] - position[0])) + }); + let Some(&target) = targets.first() else { + return Ok(()); + }; + let amount = Self::tac_stat(w, id, "atk")?; + let mut b = buff("ab:dive", &[]); + b.flags.extend( + ["noMove", "untargetable", "invulnerable", "unblockable"].map(str::to_string), + ); + self.enemy_buff(w, r, id, b)?; + let shot = self + .flights + .as_mut() + .ok_or("Missing seed projectile system")? + .add( + w, + projectiles::Launch { + from: position, + source: Some(id), + target: Some(target), + to: None, + speed: 10., + hit_dead: true, + max_age: 10., + on_hit: true, + visual: "".into(), + speed_changeable: None, + removable: None, + payload: allies::Shot::Seed { source: id, amount }, + }, + )?; + self.content.as_mut().unwrap().set_lifecycle( + id, + Memory::Seed { + projectile: Some(shot), + }, + ); + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_sync_seeds( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ids: &[Id], + ) -> Result<(), String> { + for &id in ids { + let Memory::Seed { + projectile: Some(shot), + } = self.content.as_ref().unwrap().lifecycle(id) + else { + continue; + }; + if !w.unit(id)?.stats.alive { + continue; + } + let position = self + .flights + .as_ref() + .ok_or("Missing seed projectile system")? + .list() + .iter() + .find(|p| p.id == shot) + .map(|p| p.position); + if let Some(position) = position { + w.unit_mut(id)?.position = position; + } else { + self.kill_enemy(id, None, r, w)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_seed_impact( + &mut self, + w: &mut World, + source: Id, + target: Option, + position: [f64; 2], + amount: f64, + ) -> Result<(), String> { + let mut r = self.buffs.take().ok_or("Missing seed impact buffs")?; + let result = (|| { + w.unit_mut(source)?.position = position; + if let Some(target) = target { + let mut hit = ability_damage(Some(source), target, amount, DamageType::Physical); + self.enemy_damage(w, &mut r, &mut hit)?; + } + self.kill_enemy(source, None, &mut r, w) + })(); + self.buffs = Some(r); + result + } + pub(super) fn enemy_reborn_knockout( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result { + let kit = self.content.as_ref().unwrap().kit(id); + let Some((duration, _, _)) = kit.rebirth() else { + return Ok(false); + }; + if self.content.as_ref().unwrap().reborn_phase(id) != Some(RebornPhase::Fresh) { + return Ok(false); + } + self.content + .as_mut() + .unwrap() + .set_reborn_phase(id, RebornPhase::Rebirth); + w.unit_mut(id)?.motion.unbalance_until = f64::NEG_INFINITY; + self.enemy_cleanse_rebirth(w, r, id)?; + w.unit_mut(id)?.stats.hp = Self::tac_stat(w, id, "maxHp")?.min(1.); + match kit { + Kit::Lifecycle(k) => self.enemy_rebirth_start(w, r, id, k)?, + Kit::Caster(c) => self.champion_rebirth_start(w, r, id, c)?, + _ => unreachable!(), + } + if duration <= 0. { + self.enemy_reborn_finish(w, r, id)?; + return Ok(true); + } + let mut b = buff("ab:reborn", &[]); + b.runtime.duration = duration; + b.runtime.visible = true; + b.runtime.persist = true; + b.runtime.on_expire = Some(REBORN_FINISH); + if matches!( + kit, + Kit::Caster(crate::battle::content::enemies::Caster { + passive: crate::battle::content::enemies::casters::Passive::Wolf { .. }, + .. + }) + ) { + b.runtime.on_tick = Some(super::WOLF_REBORN); + } + b.flags.extend( + [ + "invulnerable", + "untargetable", + "unblockable", + "noMove", + "stun", + ] + .map(str::to_string), + ); + self.enemy_buff(w, r, id, b)?; + Ok(true) + } + pub(in crate::battle::runtime) fn enemy_reborn_finish( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let kit = self.content.as_ref().unwrap().kit(id); + let Some((_, invincible, hp)) = kit.rebirth() else { + return Ok(()); + }; + if !w.unit(id)?.stats.alive + || self.content.as_ref().unwrap().reborn_phase(id) != Some(RebornPhase::Rebirth) + { + return Ok(()); + } + self.content + .as_mut() + .unwrap() + .set_reborn_phase(id, RebornPhase::Revived); + r.remove(w, self, id, "ab:reborn")?; + match kit { + Kit::Lifecycle(k) => self.enemy_rebirth_finish(w, r, id, k)?, + Kit::Caster(c) => self.champion_rebirth_finish(w, r, id, c)?, + _ => unreachable!(), + } + w.unit_mut(id)?.stats.hp = (Self::tac_stat(w, id, "maxHp")? * hp).max(1.); + if invincible > 0. { + let mut b = buff("ab:reborn:inv", &[]); + b.runtime.duration = invincible; + b.runtime.visible = true; + b.flags.insert("invulnerable".into()); + if matches!( + kit, + Kit::Caster(crate::battle::content::enemies::Caster { + passive: crate::battle::content::enemies::casters::Passive::Xi { .. }, + .. + }) + ) { + b.flags.insert("untargetable".into()); + } + self.enemy_buff(w, r, id, b)?; + } + if let Some(route) = w.unit_mut(id)?.motion.route.as_mut() { + route.points = None; + } + w.unit_mut(id)?.cadence.cooldown = 0.; + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/movement.rs b/crates/engine/src/battle/runtime/enemies/movement.rs new file mode 100644 index 0000000..c252a68 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/movement.rs @@ -0,0 +1,445 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::{ + movement::{Memory, Unbalance}, + Movement, + }, + grid::{Grid, COLS}, + targeting, +}; +use crate::deterministic::math::hypot; +impl Host { + pub(super) fn enemy_can_cast( + &mut self, + w: &mut World, + id: Id, + silence: bool, + ) -> Result { + let time = w.time; + let u = w.unit_mut(id)?; + let alive = u.stats.alive; + let flags = &u.stats.stats().map_err(str::to_string)?.flags; + Ok(alive + && !u.hidden + && !flags.contains("stun") + && !(silence && flags.contains("silence")) + && time >= u.motion.unbalance_until - 1e-9) + } + fn enemy_float( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + on: bool, + ) -> Result<(), String> { + if !on { + r.remove(w, self, id, "ab:float")?; + return Ok(()); + } + let mut b = buff("ab:float", &[]); + b.runtime.persist = true; + b.flags + .extend(["unblockable", "float", "noDisplace"].map(str::to_string)); + self.enemy_buff(w, r, id, b)?; + blocking::unblock( + w, + &mut allies::Blocking { + host: self, + buffs: r, + }, + id, + ) + } + pub(in crate::battle::runtime) fn enemy_movement_status( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: &status::Context, + ) -> Result<(), String> { + if !matches!(c.key.as_str(), "stun" | "freeze" | "sleep" | "groundbind") + || w.unit(c.target)?.side != health::Side::Enemy + { + return Ok(()); + } + let id = c.target; + match self.content.as_ref().unwrap().kit(id) { + Kit::Movement(Movement::Syufo { .. }) + if matches!(c.key.as_str(), "stun" | "freeze" | "sleep" | "groundbind") => + { + if !matches!( + self.content.as_ref().unwrap().movement(id), + Memory::Syufo { crawl: false } + ) { + return Ok(()); + } + self.content + .as_mut() + .unwrap() + .set_movement(id, Memory::Syufo { crawl: true }); + self.enemy_float(w, r, id, false)?; + self.apply_status( + w, + r, + id, + "stun", + status::Options { + duration: 0.5, + ..Default::default() + }, + )?; + } + Kit::Movement(Movement::Parrot { down: duration, .. }) => { + let Memory::Parrot { + down, + mut chill, + ran, + } = self.content.as_ref().unwrap().movement(id) + else { + unreachable!() + }; + if c.key == "freeze" { + chill = true; + self.content + .as_mut() + .unwrap() + .set_movement(id, Memory::Parrot { down, chill, ran }); + return Ok(()); + } + if down || !matches!(c.key.as_str(), "stun" | "sleep" | "groundbind") { + return Ok(()); + } + self.content.as_mut().unwrap().set_movement( + id, + Memory::Parrot { + down: true, + chill, + ran, + }, + ); + self.enemy_float(w, r, id, false)?; + r.remove(w, self, id, "ab:parrotRun")?; + let mut b = buff("ab:parrotDown", &[]); + b.flags.insert("unblockable".into()); + b.runtime.persist = true; + self.enemy_buff(w, r, id, b)?; + if duration > 0. { + self.apply_status( + w, + r, + id, + "stun", + status::Options { + duration, + ..Default::default() + }, + )?; + } + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_movement_taken( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if let Kit::Movement(Movement::Parrot { + speed, duration, .. + }) = self.content.as_ref().unwrap().kit(id) + { + if let Memory::Parrot { + down: false, + chill, + ran: false, + } = self.content.as_ref().unwrap().movement(id) + { + self.content.as_mut().unwrap().set_movement( + id, + Memory::Parrot { + down: false, + chill, + ran: true, + }, + ); + let mut b = buff("ab:parrotRun", &[("moveMul", speed)]); + b.runtime.duration = duration; + self.enemy_buff(w, r, id, b)?; + } + } + Ok(()) + } + pub(super) fn enemy_targets_near( + &mut self, + w: &mut World, + id: Id, + radius: f64, + ) -> Result, String> { + let candidates = enemy::Hooks::allies_in_radius(self, id, radius, w, w.unit_capacity())?; + let mut out = vec![]; + for target in candidates { + if targeting::can_target_ally(w, id, target, true, Default::default())? { + out.push(target); + } + } + Ok(out) + } + pub(super) fn enemy_movement_attack( + &mut self, + w: &mut World, + c: &mut enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + if event != enemy::Event::BeforeAttack + || !matches!( + self.content.as_ref().unwrap().kit(c.enemy), + Kit::Movement(Movement::BoneSpike { .. }) + ) + { + return Ok(()); + } + if !targeting::Queries::enemy_stealthed(self, c.enemy, w)? { + return Ok(()); + } + let radius = w.unit(c.enemy)?.stats.base_number("rangeRadius") + 0.25; + let mut targets = self.enemy_targets_near(w, c.enemy, radius)?; + targets.retain(|&id| w.unit(id).is_ok_and(|u| !u.motion_fly)); + targeting::sort_allies( + w, + c.enemy, + &mut targets, + targeting::Profile { + block_free: true, + ..Default::default() + }, + )?; + targets.truncate(3); + if !targets.is_empty() { + c.targets = targets; + } + Ok(()) + } + pub(super) fn enemy_movement_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + kit: Movement, + dt: f64, + ) -> Result<(), String> { + match kit { + Movement::Parrot { .. } => { + let Memory::Parrot { down, chill, ran } = + self.content.as_ref().unwrap().movement(id) + else { + unreachable!() + }; + let flags = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .clone(); + if chill && !flags.contains("freeze") { + self.content.as_mut().unwrap().set_movement( + id, + Memory::Parrot { + down, + chill: false, + ran, + }, + ); + self.apply_status( + w, + r, + id, + "stun", + status::Options { + duration: 0.05, + ..Default::default() + }, + )?; + } + let Memory::Parrot { down, chill, ran } = + self.content.as_ref().unwrap().movement(id) + else { + unreachable!() + }; + let flags = &w.unit_mut(id)?.stats.stats().map_err(str::to_string)?.flags; + if down && !flags.contains("stun") && !flags.contains("groundbind") { + self.content.as_mut().unwrap().set_movement( + id, + Memory::Parrot { + down: false, + chill, + ran, + }, + ); + r.remove(w, self, id, "ab:parrotDown")?; + r.remove(w, self, id, "ab:parrotRun")?; + self.enemy_float(w, r, id, true)?; + } + } + Movement::Unbalanced(Unbalance::Bleed { amount, interval }) => { + let Memory::Bleed { mut elapsed } = self.content.as_ref().unwrap().movement(id) + else { + unreachable!() + }; + if amount <= 0. + || interval <= 0. + || w.time >= w.unit(id)?.motion.unbalance_until - 1e-9 + { + elapsed = 0.; + } else { + elapsed += dt; + let mut count = 0; + while elapsed >= interval - 1e-9 && w.unit(id)?.stats.alive && count < 8 { + elapsed -= interval; + count += 1; + let mut hit = ability_damage(None, id, amount, DamageType::True); + hit.is_skill = false; + hit.attack_type = hit::AttackType::Buff; + hit.tags = vec!["dot".into(), "periodic".into(), "unbalanced".into()]; + self.enemy_damage(w, r, &mut hit)?; + } + } + if w.unit(id)?.stats.alive { + self.content + .as_mut() + .unwrap() + .set_movement(id, Memory::Bleed { elapsed }); + } + } + Movement::Unbalanced(react) => { + let Memory::Travel { + previous, + hidden, + done, + } = self.content.as_ref().unwrap().movement(id) + else { + unreachable!() + }; + let position = w.unit(id)?.position; + let now_hidden = w.unit(id)?.hidden; + self.content.as_mut().unwrap().set_movement( + id, + Memory::Travel { + previous: Some(position), + hidden: now_hidden, + done, + }, + ); + let Some(old) = previous.filter(|_| !hidden && !now_hidden) else { + return Ok(()); + }; + let dy = position[0] - old[0]; + let dx = position[1] - old[1]; + let moved = hypot(dx, dy); + let own = Self::tac_stat(w, id, "moveSpeed")? * 0.5 * dt * 1.5 + 1e-3; + if moved - own <= 0.05 { + return Ok(()); + } + match react { + Unbalance::Stun(duration) if duration > 0. => { + self.apply_status( + w, + r, + id, + "stun", + status::Options { + duration, + ..Default::default() + }, + )?; + } + Unbalance::LoseEgg(speed) if !done => { + self.content.as_mut().unwrap().set_movement( + id, + Memory::Travel { + previous: Some(position), + hidden: now_hidden, + done: true, + }, + ); + let mut b = buff("ab:noEgg", &[("moveMul", 1. + speed)]); + b.runtime.persist = true; + b.runtime.visible = true; + b.flags.insert("unblockable".into()); + self.enemy_buff(w, r, id, b)?; + } + Unbalance::Wall(amount) => { + let point = [ + (position[0] + dy / moved * 0.6 + 0.5).floor() as i32, + (position[1] + dx / moved * 0.6 + 0.5).floor() as i32, + ]; + let grid = self.grid.as_ref().ok_or("Missing collision query grid")?; + if Grid::in_bounds(point) + && grid.tiles()[(point[0] * COLS as i32 + point[1]) as usize].height + == "LOW" + && grid.ground_passable(point, false) + { + return Ok(()); + } + let mut hit = ability_damage(None, id, amount, DamageType::True); + hit.tags.push("wallHit".into()); + self.enemy_damage(w, r, &mut hit)?; + } + _ => {} + } + } + Movement::Run { + skill: Some(skill), + speed, + duration, + } => { + let Memory::Cast { mut left } = self.content.as_ref().unwrap().movement(id) else { + unreachable!() + }; + let hp = w.unit(id)?.stats.hp; + let ready = + self.enemy_can_cast(w, id, true)? && hp / Self::tac_stat(w, id, "maxHp")? < 0.5; + let cast = skill.advance(&mut left, dt, ready); + self.content + .as_mut() + .unwrap() + .set_movement(id, Memory::Cast { left }); + if cast { + let mut b = buff("ab:run", &[("moveMul", 1. + speed)]); + b.runtime.duration = duration; + b.runtime.visible = true; + b.flags.insert("unblockable".into()); + self.enemy_buff(w, r, id, b)?; + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_movement_profile( + &self, + id: Id, + kit: &Kit, + profile: &mut enemy::Profile, + ) { + match kit { + Kit::Movement(Movement::Syufo { .. }) => { + profile.melee = matches!( + self.content.as_ref().unwrap().movement(id), + Memory::Syufo { crawl: true } + ); + } + Kit::Movement(Movement::Parrot { .. }) => profile.no_attack = true, + Kit::Movement(Movement::Unbalanced(Unbalance::LoseEgg(_))) => { + profile.no_attack |= matches!( + self.content.as_ref().unwrap().movement(id), + Memory::Travel { done: true, .. } + ); + } + Kit::Movement(Movement::BoneSpike { .. }) => profile.selection.block_free = true, + _ => {} + } + } +} diff --git a/crates/engine/src/battle/runtime/enemies/reactions.rs b/crates/engine/src/battle/runtime/enemies/reactions.rs new file mode 100644 index 0000000..f823d45 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/reactions.rs @@ -0,0 +1,520 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::{reactions::Memory, Reaction}, + element, targeting, +}; + +impl Host { + pub(super) fn enemy_reaction_hit( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &mut hit::Request, + id: Id, + ) -> Result<(), String> { + match self.content.as_ref().unwrap().kit(id) { + Kit::Reaction(Reaction::Double { scale, .. }) => { + if matches!( + self.content.as_ref().unwrap().reaction(id), + Memory::Power { powered: true, .. } + ) { + q.damage.amount *= scale; + } + } + Kit::Reaction(Reaction::Fear(config)) => { + if let Some(amount) = config.steal { + let target = q.hit.target; + let active = self + .roster + .as_ref() + .unwrap() + .entry(target)? + .skill() + .is_ok_and(|s| { + s.bank.active + && s.bank.kind == crate::battle::sp::Kind::Ammo + && s.ammo_left > 0. + }); + if active { + let mut skill = self.roster.as_mut().unwrap().take_skill(target)?; + skill.ammo_left = (skill.ammo_left - amount).max(0.); + let result = if skill.ammo_left <= 0. { + self.with_kit_buffs(w, r, |h, w| skill.end(w, h, "ammo")) + } else { + Ok(()) + }; + self.roster.as_mut().unwrap().restore_skill(target, skill)?; + result?; + q.cancelled = true; + } else if let Ok(state) = w.unit_mut(target)?.operator.tactical.snhunt_mut() { + if state.ammo > 0. { + state.ammo = (state.ammo - amount).max(0.); + q.cancelled = true; + } + } + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_reaction_in( + &self, + w: &World, + q: &mut hit::Request, + ) -> Result<(), String> { + if q.cancelled || !matches!(q.hit.damage_type, DamageType::Physical | DamageType::Arts) { + return Ok(()); + } + let Some(source) = q.hit.source else { + return Ok(()); + }; + if w.unit(source)?.side != health::Side::Ally { + return Ok(()); + } + if let Kit::Reaction(Reaction::Front { reduction, .. } | Reaction::Crowd { reduction }) = + self.content.as_ref().unwrap().kit(q.hit.target) + { + if let Memory::Facing { sign, .. } = + self.content.as_ref().unwrap().reaction(q.hit.target) + { + if reduction > 0. + && (w.unit(source)?.position[1] - w.unit(q.hit.target)?.position[1]) * sign + > 1e-6 + { + q.damage.mul *= (1. - reduction).max(0.); + } + } + } + Ok(()) + } + pub(super) fn enemy_reaction_taken( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Kit::Reaction(Reaction::Fear(config)) = self.content.as_ref().unwrap().kit(id) else { + return Ok(()); + }; + let hp = w.unit(id)?.stats.hp; + if hp / Self::tac_stat(w, id, "maxHp")? >= 0.5 + || !matches!( + self.content.as_ref().unwrap().reaction(id), + Memory::Once { done: false } + ) + { + return Ok(()); + } + self.content + .as_mut() + .unwrap() + .set_reaction(id, Memory::Once { done: true }); + if config.duration > 0. { + self.apply_status( + w, + r, + id, + "fear", + status::Options { + source: Some(id), + duration: config.duration, + ..Default::default() + }, + )?; + } + if config.speed > 0. && config.speed_duration > 0. { + let mut b = buff("ab:fearRun", &[("moveMul", config.speed)]); + b.runtime.duration = config.speed_duration; + b.flags.insert("unblockable".into()); + self.enemy_buff(w, r, id, b)?; + } + Ok(()) + } + pub(super) fn enemy_reaction_attack( + &mut self, + w: &mut World, + c: &enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + let id = c.enemy; + match self.content.as_ref().unwrap().kit(id) { + Kit::Reaction(Reaction::Double { every, .. }) => { + if let Memory::Power { count, powered } = + self.content.as_ref().unwrap().reaction(id) + { + let state = match event { + enemy::Event::BeforeAttack => Memory::Power { + count, + powered: every > 0 && count + 1 == every, + }, + enemy::Event::Attack => Memory::Power { + count: if every == 0 || count + 1 >= every { + 0 + } else { + count + 1 + }, + powered, + }, + _ => return Ok(()), + }; + self.content.as_mut().unwrap().set_reaction(id, state); + } + } + Kit::Reaction(Reaction::Shell) if event == enemy::Event::Attack => { + let amount = Self::tac_stat(w, id, "atk")?; + for &target in &c.targets { + self.enemy_schedule( + w, + Some(id), + 3., + 0., + 1, + EnemyTask::Shell { + position: w.unit(target)?.position, + amount, + }, + )?; + } + } + _ => {} + } + Ok(()) + } + fn enemy_stop_rush( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + self.content.as_mut().unwrap().set_reaction( + id, + Memory::Rush { + active: false, + layers: 0, + elapsed: 0., + }, + ); + r.remove(w, self, id, "ab:rush")?; + Ok(()) + } + pub(super) fn enemy_reaction_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + id: Id, + ) -> Result<(), String> { + match self.content.as_ref().unwrap().kit(id) { + Kit::Reaction(Reaction::Double { scale, .. }) => { + let powered = matches!( + self.content.as_ref().unwrap().reaction(id), + Memory::Power { powered: true, .. } + ); + let amount = Self::tac_stat(w, id, "atk")? * if powered { scale } else { 1. }; + let mut hit = ability_damage(Some(id), q.hit.target, amount, DamageType::Physical); + hit.is_skill = false; + self.enemy_damage(w, r, &mut hit)?; + } + Kit::Reaction(Reaction::Rush { scale, .. }) + if matches!( + self.content.as_ref().unwrap().reaction(id), + Memory::Rush { active: true, .. } + ) => + { + let amount = Self::tac_stat(w, id, "moveSpeed")? * scale; + self.enemy_stop_rush(w, r, id)?; + if w.unit(q.hit.target)?.stats.alive { + let mut hit = + ability_damage(Some(id), q.hit.target, amount, DamageType::Physical); + hit.hit.no_sp = true; + hit.tags.push("rush".into()); + self.enemy_damage(w, r, &mut hit)?; + } + } + Kit::Reaction(Reaction::FirstSplash { scale }) + if matches!( + self.content.as_ref().unwrap().reaction(id), + Memory::Once { done: false } + ) => + { + self.content + .as_mut() + .unwrap() + .set_reaction(id, Memory::Once { done: true }); + let amount = Self::tac_stat(w, id, "atk")? * scale; + let targets = spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + w.unit(q.hit.target)?.position, + 1., + None, + false, + w.unit_capacity(), + )?; + for target in targets { + if target == q.hit.target { + continue; + } + let mut hit = ability_damage(Some(id), target, amount, DamageType::Physical); + hit.ignore_select = true; + hit.tags.push("aoeAttack".into()); + self.enemy_damage(w, r, &mut hit)?; + } + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_reaction_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let kit = self.content.as_ref().unwrap().kit(id); + match kit { + Kit::Reaction(Reaction::ExposeDeath { + radius, + duration, + scale, + }) if !silenced(w, id)? => { + if duration <= 0. { + return Ok(()); + } + for target in + enemy::Hooks::allies_in_radius(self, id, radius, w, w.unit_capacity())? + { + let mut b = buff("ab:exposed", &[("dmgTakenMul", scale)]); + b.runtime.duration = duration; + b.runtime.refresh = buffs::Refresh::Extend; + b.runtime.visible = true; + self.enemy_buff(w, r, target, b)?; + } + } + Kit::Reaction(Reaction::HealDeath { radius, scale }) if !silenced(w, id)? => { + let amount = Self::tac_stat(w, id, "atk")? * scale; + for target in self.enemy_nearby(w, id, radius)? { + if target != id { + self.support_heal( + w, + r, + Some(id), + target, + amount, + health::HealOptions::default(), + )?; + } + } + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_reaction_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + kit: Reaction, + dt: f64, + ) -> Result<(), String> { + if let Reaction::Crowd { .. } = kit { + let Memory::Facing { x, mut sign } = self.content.as_ref().unwrap().reaction(id) else { + unreachable!() + }; + let mut left = 0; + let mut right = 0; + let at = w.unit(id)?.position[1]; + for &other in self.roster.as_ref().unwrap().ids() { + let u = w.unit(other)?; + if !u.stats.alive + || !u.deployed + || u.hidden + || u.deployment.kind != crate::battle::deploy::Kind::Operator + { + continue; + } + if u.position[1] > at + 1e-6 { + right += 1; + } else if u.position[1] < at - 1e-6 { + left += 1; + } + } + if left != right { + sign = if right > left { 1. } else { -1. }; + } + self.content + .as_mut() + .unwrap() + .set_reaction(id, Memory::Facing { x, sign }); + return Ok(()); + } + let interval = match kit { + Reaction::Aura { .. } => { + if silenced(w, id)? { + return Ok(()); + } + 0.5 + } + Reaction::Blood { .. } | Reaction::Front { .. } => 1., + Reaction::Rush { .. } => 0.1, + _ => return Ok(()), + }; + if let Reaction::Front { .. } = kit { + if let Memory::Facing { x, mut sign } = self.content.as_ref().unwrap().reaction(id) { + let u = w.unit(id)?; + let dx = match u + .blocked_by() + .filter(|&b| w.unit(b).is_ok_and(|u| u.stats.alive)) + { + Some(blocker) => w.unit(blocker)?.position[1] - u.position[1], + None => u.position[1] - x, + }; + if dx.abs() > 1e-6 { + sign = if dx > 0. { 1. } else { -1. }; + } + self.content.as_mut().unwrap().set_reaction( + id, + Memory::Facing { + x: u.position[1], + sign, + }, + ); + } + } + let pulses = self.content.as_mut().unwrap().pulses(id, dt, interval); + for _ in 0..pulses { + if !w.unit(id)?.stats.alive { + break; + } + match kit { + Reaction::Aura { + radius, + defense, + amount, + } => { + let radius = if !defense && radius == 0. { + 2.5 + } else { + radius + }; + for target in self.enemy_nearby(w, id, radius)? { + if target == id { + continue; + } + let mut b = buff( + if defense { "ab:defdrn" } else { "ab:mrfly" }, + &[(if defense { "defFlat" } else { "resFlat" }, amount)], + ); + b.runtime.duration = 0.6; + self.enemy_buff(w, r, target, b)?; + } + } + Reaction::Blood { ratio } if ratio > 0. => { + let amount = Self::tac_stat(w, id, "maxHp")? * ratio; + self.support_lose_hp(w, r, id, amount, None, false)?; + } + Reaction::Front { neural, .. } => { + if let Some(target) = w.unit(id)?.blocked_by() { + let amount = Self::tac_stat(w, id, "atk")? * neural; + self.enemy_element(w, r, id, target, element::Element::Neural, amount)?; + } + } + Reaction::Rush { + speed, + interval, + max, + .. + } => { + let held = w + .unit(id)? + .stats + .buffs() + .iter() + .any(|b| matches!(b.runtime.status.as_deref(), Some("stun" | "bind"))); + let Memory::Rush { + active, + mut layers, + mut elapsed, + } = self.content.as_ref().unwrap().reaction(id) + else { + unreachable!() + }; + if held { + if active { + self.enemy_stop_rush(w, r, id)?; + } + continue; + } + if !active { + if w.unit(id)?.blocked_by().is_none() { + self.content.as_mut().unwrap().set_reaction( + id, + Memory::Rush { + active: true, + layers: 0, + elapsed: 0., + }, + ); + } + continue; + } + if layers >= max || interval <= 0. { + continue; + } + elapsed += 0.1; + let old = layers; + while elapsed >= interval - 1e-9 && layers < max && layers - old < 8 { + elapsed -= interval; + layers += 1; + } + self.content.as_mut().unwrap().set_reaction( + id, + Memory::Rush { + active, + layers, + elapsed, + }, + ); + if layers != old { + let mut b = buff("ab:rush", &[("moveMul", 1. + speed * layers as f64)]); + b.runtime.persist = true; + self.enemy_buff(w, r, id, b)?; + } + } + _ => {} + } + } + Ok(()) + } + pub(super) fn enemy_shell( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Option, + position: [f64; 2], + amount: f64, + ) -> Result<(), String> { + let targets = spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + position, + 1.45, + None, + false, + w.unit_capacity(), + )?; + for target in targets { + if !targeting::area_selectable(w, source, target)? { + continue; + } + let mut damage = ability_damage(None, target, amount, DamageType::Physical); + damage.is_skill = false; + damage.tags.push("shell".into()); + self.enemy_damage(w, r, &mut damage)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/rebirth.rs b/crates/engine/src/battle/runtime/enemies/rebirth.rs new file mode 100644 index 0000000..2497265 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/rebirth.rs @@ -0,0 +1,412 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::{ + lifecycle::{Memory, RebornPhase}, + Lifecycle, + }, + targeting, +}; +use crate::deterministic::math::hypot; +pub(in crate::battle::runtime) const PILOT_BURN: u64 = 1706; +impl Host { + pub(in crate::battle::runtime::enemies) fn enemy_rebirth_start( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + kit: Lifecycle, + ) -> Result<(), String> { + match kit { + Lifecycle::Warden { .. } => { + for other in self.spawns.as_ref().unwrap().live().to_vec() { + self.liberate_prisoner(w, r, other)?; + } + } + Lifecycle::Ugly { bomb, stun, .. } => { + self.enemy_schedule( + w, + Some(id), + 2.17, + 0., + 1, + EnemyTask::Blast { + position: w.unit(id)?.position, + scale: bomb, + stun, + }, + )?; + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn enemy_rebirth_finish( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + kit: Lifecycle, + ) -> Result<(), String> { + match kit { + Lifecycle::Warden { + atk, + defense, + bat, + speed, + .. + } => { + self.content.as_mut().unwrap().set_lifecycle( + id, + Memory::Warden { + phase: RebornPhase::Revived, + count: 0, + power: false, + }, + ); + r.remove(w, self, id, "ab:warden")?; + let mut b = buff( + "ab:killer", + &[ + ("atkFlat", atk), + ("defFlat", defense), + ( + "batPct", + bat / w.unit(id)?.stats.base_number("bat").max(1e-9), + ), + ("moveFlat", speed), + ], + ); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + Lifecycle::Ugly { + speed, + defense, + res, + burn, + .. + } => { + let mut b = buff( + "ab:pilot", + &[ + ("moveMul", 1. + speed), + ( + "defFlat", + defense + .map(|v| v - w.unit(id).unwrap().stats.base_number("def")) + .unwrap_or(0.), + ), + ( + "resFlat", + res.map(|v| v - w.unit(id).unwrap().stats.base_number("res")) + .unwrap_or(0.), + ), + ], + ); + b.flags.insert("unblockable".into()); + b.runtime.persist = true; + b.runtime.visible = true; + b.runtime.interval = 1.; + b.runtime.tick_payload = burn; + b.runtime.on_tick = Some(PILOT_BURN); + self.enemy_buff(w, r, id, b)?; + } + Lifecycle::Reid { skill, .. } => { + if let Memory::Reid { phase, enraged, .. } = + self.content.as_ref().unwrap().lifecycle(id) + { + self.content.as_mut().unwrap().set_lifecycle( + id, + Memory::Reid { + phase, + enraged, + left: skill.map(|s| s.initial).unwrap_or(0.), + }, + ); + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_pilot_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + let amount = r.get(w, c.unit, c.buff)?.runtime.tick_payload; + let mut q = ability_damage(None, c.unit, amount, DamageType::True); + q.is_skill = false; + q.tags.push("pilotBurn".into()); + self.enemy_damage(w, r, &mut q) + } + pub(super) fn enemy_rebirth_hit( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &mut hit::Request, + id: Id, + ) -> Result<(), String> { + match ( + self.content.as_ref().unwrap().kit(id), + self.content.as_ref().unwrap().lifecycle(id), + ) { + ( + Kit::Lifecycle(Lifecycle::Warden { penetration, .. }), + Memory::Warden { phase, power, .. }, + ) => { + q.hit.damage_type = if phase == RebornPhase::Revived { + DamageType::Physical + } else { + DamageType::Arts + }; + if phase == RebornPhase::Revived && power { + q.damage.penetration.def_pct = + (q.damage.penetration.def_pct + penetration).min(1.); + } + } + (Kit::Lifecycle(Lifecycle::Ugly { .. }), Memory::Ugly { splash: true, .. }) => { + let amount = Self::tac_stat(w, id, "atk")?; + for t in self.enemy_tile_allies(w, w.unit(q.hit.target)?.deployment.tile, 1)? { + if t != q.hit.target && targeting::area_selectable(w, Some(id), t)? { + let mut h = ability_damage(Some(id), t, amount, DamageType::Physical); + h.tags.push("splash".into()); + self.enemy_damage(w, r, &mut h)?; + } + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn enemy_rebirth_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: &enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + let id = c.enemy; + match ( + self.content.as_ref().unwrap().kit(id), + self.content.as_ref().unwrap().lifecycle(id), + ) { + ( + Kit::Lifecycle(Lifecycle::Warden { + every, + stun, + targets, + .. + }), + Memory::Warden { + phase, + count, + power, + }, + ) => { + if event == enemy::Event::BeforeAttack { + let n = every[usize::from(phase == RebornPhase::Revived)]; + self.content.as_mut().unwrap().set_lifecycle( + id, + Memory::Warden { + phase, + count, + power: n > 0 && (count + 1) % n == 0, + }, + ); + } + if event == enemy::Event::Attack { + self.content.as_mut().unwrap().set_lifecycle( + id, + Memory::Warden { + phase, + count: count.saturating_add(1), + power, + }, + ); + if phase != RebornPhase::Revived && power { + let radius = w.unit(id)?.stats.base_number("rangeRadius"); + let mut list = + self.enemy_targets_near(w, id, if radius == 0. { 2. } else { radius })?; + targeting::sort_allies(w, id, &mut list, Default::default())?; + for &t in &c.targets { + if !list.contains(&t) { + list.insert(0, t); + } + } + for t in list.into_iter().take(targets) { + if stun > 0. && w.unit(t)?.stats.alive { + self.apply_status( + w, + r, + t, + "stun", + status::Options { + source: Some(id), + duration: stun, + ..Default::default() + }, + )?; + } + } + } + } + } + (Kit::Lifecycle(Lifecycle::Ugly { .. }), Memory::Ugly { phase, .. }) + if event == enemy::Event::BeforeAttack => + { + self.content.as_mut().unwrap().set_lifecycle( + id, + Memory::Ugly { + phase, + splash: w.unit(id)?.blocked_by().is_none(), + }, + ); + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn enemy_rebirth_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + id: Id, + ) -> Result<(), String> { + if let ( + Kit::Lifecycle(Lifecycle::Warden { + times, penetration, .. + }), + Memory::Warden { + phase: RebornPhase::Revived, + power: true, + .. + }, + ) = ( + self.content.as_ref().unwrap().kit(id), + self.content.as_ref().unwrap().lifecycle(id), + ) { + for _ in 1..times { + if !w.unit(q.hit.target)?.stats.alive { + break; + } + let amount = Self::tac_stat(w, id, "atk")?; + let mut h = ability_damage(Some(id), q.hit.target, amount, DamageType::Physical); + h.damage.penetration.def_pct = penetration; + h.dodge_mode = crate::battle::injury::DodgeMode::Normal; + h.tags.push("armorPiercing".into()); + self.enemy_damage(w, r, &mut h)?; + } + } + Ok(()) + } + pub(super) fn enemy_rebirth_taken( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if let ( + Kit::Lifecycle(Lifecycle::Reid { ratio, atk, .. }), + Memory::Reid { + phase, + left, + enraged: false, + }, + ) = ( + self.content.as_ref().unwrap().kit(id), + self.content.as_ref().unwrap().lifecycle(id), + ) { + if w.unit(id)?.stats.hp / Self::tac_stat(w, id, "maxHp")? < ratio { + self.content.as_mut().unwrap().set_lifecycle( + id, + Memory::Reid { + phase, + left, + enraged: true, + }, + ); + let mut b = buff("ab:lowhp", &[("atkPct", atk)]); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn enemy_reid_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + kit: Lifecycle, + dt: f64, + ) -> Result<(), String> { + let Lifecycle::Reid { + skill: Some(skill), + speed, + rush, + .. + } = kit + else { + return Ok(()); + }; + let Memory::Reid { + phase, + mut left, + enraged, + } = self.content.as_ref().unwrap().lifecycle(id) + else { + return Ok(()); + }; + let mut path = std::collections::BTreeSet::new(); + let origin = w.unit(id)?.position; + path.insert(origin.map(|v| (v + 0.5).floor() as i32)); + if let Some(route) = w.unit(id)?.motion.route.as_ref() { + if let Some(points) = &route.points { + let mut from = origin; + for &p in points.iter().skip(route.point) { + let n = (hypot(p[0] - from[0], p[1] - from[1]) * 4.).ceil().max(1.) as usize; + for k in 1..=n { + path.insert( + [ + from[0] + (p[0] - from[0]) * k as f64 / n as f64, + from[1] + (p[1] - from[1]) * k as f64 / n as f64, + ] + .map(|v| (v + 0.5).floor() as i32), + ); + } + from = p; + } + } + } + let mut has = false; + for t in self.enemy_targets_near(w, id, 3.)? { + has |= w.unit(t)?.ground && path.contains(&w.unit(t)?.deployment.tile); + } + let fire = skill.advance( + &mut left, + dt, + w.unit(id)?.blocked_by().is_none() && has && self.enemy_can_cast(w, id, false)?, + ); + self.content.as_mut().unwrap().set_lifecycle( + id, + Memory::Reid { + phase, + left, + enraged, + }, + ); + if fire { + let mut b = buff("ab:rush", &[("moveMul", 1. + speed)]); + b.runtime.duration = rush; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/specials.rs b/crates/engine/src/battle/runtime/enemies/specials.rs new file mode 100644 index 0000000..1266383 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/specials.rs @@ -0,0 +1,705 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{ + content::enemies::specials::{BombPhase, Charge, Form, Memory, Special, Translation}, + element, projectiles, targeting, +}; +use crate::deterministic::math::hypot; +mod tasks; +pub(in crate::battle::runtime) use tasks::{Task, PARASITE_TICK, TRANSLATOR_FINISH}; +#[derive(Clone, Copy)] +pub(in crate::battle::runtime) struct BombShot { + pub source: Id, + pub attack: f64, +} +impl Host { + fn special_config(&self, id: Id) -> Option { + match self.content.as_ref()?.kit(id) { + Kit::Special(c) => Some(c), + _ => None, + } + } + pub(in crate::battle::runtime) fn enemy_special_spawn( + &mut self, + w: &mut World, + id: Id, + config: Special, + ) -> Result<(), String> { + if let Special::Armor { appear, .. } = config { + self.enemy_schedule( + w, + Some(id), + 0.5, + 0., + 1, + EnemyTask::Special(Task::Entrance { hits: appear }), + )?; + } + Ok(()) + } + fn special_targets(&mut self, w: &mut World, id: Id, radius: f64) -> Result, String> { + let mut out = if radius.is_infinite() { + let mut v = vec![]; + for t in self.roster.as_ref().unwrap().ids() { + if targeting::can_target_ally(w, id, *t, true, Default::default())? { + v.push(*t); + } + } + v + } else { + self.enemy_targets_near(w, id, radius)? + }; + if !radius.is_infinite() { + targeting::sort_allies(w, id, &mut out, Default::default())?; + } + Ok(out) + } + fn cloud_prey(&mut self, w: &mut World, id: Id, radius: f64) -> Result, String> { + let mut out = vec![]; + for t in self.enemy_nearby(w, id, radius)? { + if t == id + || w.unit(t)?.boss + || self.data.table("enemies").unwrap() + [&self.spawns.as_ref().unwrap().definition(t)?.key]["rank"] + .as_str() + .unwrap_or("NORMAL") + != "NORMAL" + || !targeting::flying(w, t)? + || w.unit(t)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some("ab:devoured")) + { + continue; + } + out.push(t); + } + let p = w.unit(id)?.position; + out.sort_by(|&a, &b| { + let a = w.unit(a).unwrap().position; + let b = w.unit(b).unwrap().position; + hypot(a[0] - p[0], a[1] - p[1]).total_cmp(&hypot(b[0] - p[0], b[1] - p[1])) + }); + Ok(out) + } + pub(in crate::battle::runtime) fn enemy_special_profile( + &self, + id: Id, + kit: &Kit, + p: &mut enemy::Profile, + ) { + let Kit::Special(config) = kit else { + return; + }; + match config { + Special::Catapult { .. } => { + p.deferred = true; + p.selection.block_free = true; + } + Special::Bomb { .. } => p.no_attack = true, + Special::Translator { .. } => match self.content.as_ref().unwrap().special(id) { + Memory::Translator { + phase: Translation::Done(form), + .. + } => { + p.no_attack = form == Form::Youling; + p.melee = form == Form::Fuchou; + p.mode = enemy::Mode::Damage(if form == Form::Shushi { + DamageType::Arts + } else { + DamageType::Physical + }); + p.max_targets = if form == Form::Shushi { 2. } else { 1. }; + } + _ => p.no_attack = true, + }, + _ => {} + } + } + pub(in crate::battle::runtime) fn enemy_special_before_status(&self, c: &mut status::Context) { + if !matches!( + c.key.as_str(), + "stun" | "sleep" | "cold" | "freeze" | "levitate" | "fear" + ) { + return; + } + if let Some(content) = &self.content { + if matches!( + content.special(c.target), + Memory::Translator { + phase: Translation::Origin | Translation::Pending(_) | Translation::Changing(_), + .. + } + ) { + c.cancelled = true; + } + } + } + pub(in crate::battle::runtime) fn enemy_special_blocked(&mut self, id: Id) { + if let Some(content) = &mut self.content { + if let Memory::Translator { + phase: Translation::Origin, + counts, + anger, + } = content.special(id) + { + content.set_special( + id, + Memory::Translator { + phase: Translation::Pending(Form::Youling), + counts, + anger, + }, + ); + } + } + } + pub(in crate::battle::runtime) fn enemy_special_flush( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if let Memory::Translator { + phase: Translation::Pending(form), + counts, + anger, + } = self.content.as_ref().unwrap().special(id) + { + self.content.as_mut().unwrap().set_special( + id, + Memory::Translator { + phase: Translation::Changing(form), + counts, + anger, + }, + ); + let mut b = buff("ab:change", &[]); + b.runtime.duration = 2.; + b.runtime.persist = true; + b.flags.insert("noMove".into()); + b.runtime.on_expire = Some(TRANSLATOR_FINISH); + self.enemy_buff(w, r, id, b)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_special_in( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &mut hit::Request, + ) -> Result<(), String> { + let id = q.hit.target; + let Some(Special::Translator { counts: limits, .. }) = self.special_config(id) else { + return Ok(()); + }; + let Memory::Translator { + mut phase, + mut counts, + anger, + } = self.content.as_ref().unwrap().special(id) + else { + unreachable!() + }; + if matches!(phase, Translation::Done(_)) { + return Ok(()); + } + if phase == Translation::Origin + && q.hit + .source + .or(q.hit.credit) + .is_some_and(|s| w.unit(s).is_ok_and(|u| u.side == health::Side::Ally)) + { + let kind = match q.hit.damage_type { + DamageType::Physical => Some((0, Form::Fuchou)), + DamageType::Arts => Some((1, Form::Shushi)), + _ => None, + }; + if let Some((i, form)) = kind { + counts[i] = counts[i].saturating_add(1); + if counts[i] >= limits[i] { + phase = Translation::Pending(form); + } + } + } + self.content.as_mut().unwrap().set_special( + id, + Memory::Translator { + phase, + counts, + anger, + }, + ); + self.enemy_special_flush(w, r, id)?; + q.cancelled = true; + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_special_knockout( + &self, + w: &mut World, + id: Id, + ) -> Result { + if matches!( + self.content.as_ref().unwrap().special(id), + Memory::Translator { + phase: Translation::Origin | Translation::Pending(_) | Translation::Changing(_), + .. + } + ) { + w.unit_mut(id)?.stats.hp = w.unit(id)?.stats.hp.max(1.); + return Ok(true); + } + Ok(false) + } + pub(super) fn enemy_special_hit( + &self, + w: &World, + q: &mut hit::Request, + id: Id, + ) -> Result<(), String> { + if let Some(Special::Armor { ranged, .. }) = self.special_config(id) { + if w.unit(id)?.blocked_by() != Some(q.hit.target) { + q.damage.amount *= ranged; + } + } + Ok(()) + } + pub(super) fn enemy_special_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: &mut enemy::Context, + event: enemy::Event, + ) -> Result { + let id = c.enemy; + let Some(Special::Cloud { + fire: Some(fire), + cost, + scale, + .. + }) = self.special_config(id) + else { + return Ok(false); + }; + let Memory::Cloud { mut left, ammo } = self.content.as_ref().unwrap().special(id) else { + unreachable!() + }; + if event != enemy::Event::BeforeAttack + || left[1] > 1e-9 + || ammo < cost + || !self.enemy_can_cast(w, id, true)? + || self.special_targets(w, id, f64::INFINITY)?.is_empty() + { + return Ok(false); + } + left[1] = (fire.period + 2.).max(DT); + self.content + .as_mut() + .unwrap() + .set_special(id, Memory::Cloud { left, ammo: 0. }); + for _ in 0..ammo.floor() as usize { + let targets = self.special_targets(w, id, f64::INFINITY)?; + if let Some(&t) = self.rng.pick(&targets) { + let amount = Self::tac_stat(w, id, "atk")? * scale; + let mut q = ability_damage(Some(id), t, amount, DamageType::Physical); + self.enemy_damage(w, r, &mut q)?; + } else { + break; + } + } + w.unit_mut(id)?.cadence.cooldown = Self::tac_stat(w, id, "interval")?.max(2.); + w.unit_mut(id)?.motion.attack_stand_until = f64::NEG_INFINITY; + c.targets.clear(); + Ok(true) + } + pub(super) fn enemy_special_dealt( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &hit::Request, + id: Id, + ) -> Result<(), String> { + if let Memory::Armor { + left, + combo, + appeared, + } = self.content.as_ref().unwrap().special(id) + { + if combo > 1 { + self.content.as_mut().unwrap().set_special( + id, + Memory::Armor { + left, + combo: 0, + appeared, + }, + ); + for _ in 1..combo { + let amount = Self::tac_stat(w, id, "atk")?; + let mut hit = + ability_damage(Some(id), q.hit.target, amount, DamageType::Physical); + self.enemy_damage(w, r, &mut hit)?; + } + } + } + Ok(()) + } + pub(super) fn enemy_special_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + config: Special, + dt: f64, + ) -> Result<(), String> { + self.enemy_special_flush(w, r, id)?; + match (config, self.content.as_ref().unwrap().special(id)) { + ( + Special::Bomb { + skill: Some(skill), .. + }, + Memory::Bomb { phase, mut left }, + ) => { + if let BombPhase::Charging { .. } = phase { + if w.unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("stun") + { + left = skill.period.max(DT) - dt; + self.content.as_mut().unwrap().set_special( + id, + Memory::Bomb { + phase: BombPhase::Ready, + left, + }, + ); + w.unit_mut(id)?.enemy.pause_until = w.time; + } + return Ok(()); + } + if !matches!(phase, BombPhase::Ready) { + return Ok(()); + } + left -= dt; + if left <= 1e-9 && self.enemy_can_cast(w, id, false)? { + let radius = w.unit(id)?.stats.base_number("rangeRadius"); + if let Some(&target) = self + .special_targets(w, id, if radius == 0. { 2. } else { radius })? + .first() + { + let release = w.time + 8. / 30.; + self.content.as_mut().unwrap().set_special( + id, + Memory::Bomb { + phase: BombPhase::Charging { release }, + left: f64::INFINITY, + }, + ); + w.unit_mut(id)?.enemy.pause_until = w.time + 8. / 30. + 10. + 0.667; + self.enemy_schedule( + w, + Some(id), + 8. / 30., + 0., + 1, + EnemyTask::Special(Task::BombRelease { target, release }), + )?; + return Ok(()); + } + } + self.content + .as_mut() + .unwrap() + .set_special(id, Memory::Bomb { phase, left }); + } + ( + Special::Cloud { + grab, + fire, + radius, + duration, + .. + }, + Memory::Cloud { mut left, ammo }, + ) => { + left[0] -= dt; + left[1] -= dt; + self.content + .as_mut() + .unwrap() + .set_special(id, Memory::Cloud { left, ammo }); + if let Some(grab) = grab { + if left[0] <= 1e-9 && self.enemy_can_cast(w, id, true)? { + let targets = self.cloud_prey(w, id, radius)?; + if !targets.is_empty() { + left[0] = grab.period.max(DT); + self.content + .as_mut() + .unwrap() + .set_special(id, Memory::Cloud { left, ammo }); + let mut b = buff("ab:grabbing", &[]); + b.runtime.duration = duration; + b.flags.extend(["bind", "noMove"].map(str::to_string)); + self.enemy_buff(w, r, id, b)?; + for &target in targets.iter().take(3) { + self.enemy_schedule( + w, + Some(id), + 0.5, + 0., + 1, + EnemyTask::Special(Task::Devour { + target, + finish: false, + }), + )?; + } + } + } + } + if fire.is_some() && !w.unit(id)?.enemy.swing && w.unit(id)?.cadence.cooldown <= 0. + { + let flags = &w.unit_mut(id)?.stats.stats().map_err(str::to_string)?.flags; + if !flags.contains("fear") + && !flags.contains("disarm") + && !(flags.contains("tremble") && w.unit(id)?.blocked_by().is_some()) + { + let mut c = enemy::Context { + enemy: id, + targets: vec![], + deployments: vec![], + palsy: None, + keep: false, + attack_id: None, + }; + self.enemy_special_attack(w, r, &mut c, enemy::Event::BeforeAttack)?; + } + } + } + ( + Special::Armor { + skill, + appear: _, + times, + .. + }, + Memory::Armor { + mut left, + mut combo, + appeared, + }, + ) => { + if !appeared { + self.enemy_special_spawn(w, id, config)?; + } + if let Some(skill) = skill { + if skill.advance(&mut left, dt, self.enemy_can_cast(w, id, false)?) { + combo = times; + } + } + self.content.as_mut().unwrap().set_special( + id, + Memory::Armor { + left, + combo, + appeared: true, + }, + ); + } + ( + Special::Translator { anger: atk, .. }, + Memory::Translator { + phase: Translation::Done(Form::Fuchou), + counts, + anger, + }, + ) => { + let on = w.unit(id)?.stats.hp / Self::tac_stat(w, id, "maxHp")? < 0.5; + if on != anger { + self.content.as_mut().unwrap().set_special( + id, + Memory::Translator { + phase: Translation::Done(Form::Fuchou), + counts, + anger: on, + }, + ); + if on { + let mut b = buff("ab:anger", &[("atkPct", atk)]); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } else { + r.remove(w, self, id, "ab:anger")?; + } + } + } + ( + Special::Elk { + skill, + duration, + scale, + stun, + }, + Memory::Elk { + mut left, + mut charge, + previous, + hidden, + }, + ) => { + let u = w.unit(id)?; + let p = u.position; + let was_hidden = hidden; + let hidden = u.hidden; + let own_speed = Self::tac_stat(w, id, "moveSpeed")?; + let forced = previous.is_some_and(|old| { + !was_hidden + && !hidden + && hypot(p[0] - old[0], p[1] - old[1]) - own_speed * 0.5 * dt * 1.5 - 0.001 + > 0.05 + }); + if let Some(ch) = charge { + let flags = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .clone(); + if flags.contains("stun") + || !w.unit(ch.target)?.stats.alive + || w.unit(id)?.blocked_by() != Some(ch.target) + { + charge = None; + r.remove(w, self, id, "ab:elkCharge")?; + } else if w.time + 1e-9 >= ch.until + && w.time >= w.unit(id)?.motion.unbalance_until + { + charge = None; + r.remove(w, self, id, "ab:elkCharge")?; + let amount = Self::tac_stat(w, id, "atk")? * scale; + let mut q = + ability_damage(Some(id), ch.target, amount, DamageType::Physical); + self.enemy_damage(w, r, &mut q)?; + if stun > 0. && w.unit(ch.target)?.stats.alive { + self.apply_status( + w, + r, + ch.target, + "stun", + status::Options { + source: Some(id), + duration: stun, + ..Default::default() + }, + )?; + } + } + } + if forced && charge.is_some() { + charge = None; + r.remove(w, self, id, "ab:elkCharge")?; + } + if let Some(skill) = skill { + if skill.advance( + &mut left, + dt, + charge.is_none() + && w.unit(id)?.blocked_by().is_some() + && self.enemy_can_cast(w, id, false)?, + ) { + let target = w.unit(id)?.blocked_by().unwrap(); + charge = Some(Charge { + target, + until: w.time + duration, + }); + let mut b = buff("ab:elkCharge", &[]); + b.runtime.duration = duration + 0.1; + b.runtime.visible = true; + b.flags.insert("disarm".into()); + self.enemy_buff(w, r, id, b)?; + } + } + self.content.as_mut().unwrap().set_special( + id, + Memory::Elk { + left, + charge, + previous: Some(p), + hidden, + }, + ); + } + (Special::Parasite { .. }, Memory::Parasite { .. }) => { + let pulses = self.content.as_mut().unwrap().pulses(id, dt, 0.2); + for _ in 0..pulses { + let Memory::Parasite { host } = self.content.as_ref().unwrap().special(id) + else { + unreachable!() + }; + let next = w + .unit(id)? + .blocked_by() + .filter(|&t| w.unit(t).is_ok_and(|u| u.stats.alive)); + if host != next { + self.parasite_detach(w, r, id)?; + if let Some(target) = next { + w.pin_unit(target)?; + self.content + .as_mut() + .unwrap() + .set_special(id, Memory::Parasite { host: Some(target) }); + w.unit_mut(id)?.position = + w.unit(target)?.deployment.tile.map(f64::from); + if let Some(route) = w.unit_mut(id)?.motion.route.as_mut() { + route.points = None; + } + let mut b = buff("ab:parasiteAttached", &[]); + b.flags.extend(["noMove", "selfBound"].map(str::to_string)); + self.enemy_buff(w, r, id, b)?; + let mut b = buff("ab:parasite", &[]); + b.runtime.visible = true; + b.runtime.interval = 1.; + b.runtime.on_tick = Some(PARASITE_TICK); + r.add( + w, + self, + target, + buffs::Spec { + buff: b, + ..Default::default() + } + .retaining_unit(id), + )?; + } + } + } + } + _ => {} + } + Ok(()) + } + pub(super) fn parasite_detach( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if let Memory::Parasite { host: Some(target) } = self.content.as_ref().unwrap().special(id) + { + self.content + .as_mut() + .unwrap() + .set_special(id, Memory::Parasite { host: None }); + r.remove(w, self, target, "ab:parasite")?; + r.remove(w, self, id, "ab:parasiteAttached")?; + w.unpin_unit(target)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/specials/tasks.rs b/crates/engine/src/battle/runtime/enemies/specials/tasks.rs new file mode 100644 index 0000000..e021255 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/specials/tasks.rs @@ -0,0 +1,408 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +pub(in crate::battle::runtime) const PARASITE_TICK: u64 = 1707; +pub(in crate::battle::runtime) const TRANSLATOR_FINISH: u64 = 1708; +#[derive(Clone, Copy)] +pub(in crate::battle::runtime) enum Task { + BombRelease { target: Id, release: f64 }, + BombWait, + Devour { target: Id, finish: bool }, + Entrance { hits: u32 }, +} +impl Task { + pub(in crate::battle::runtime) fn target(self) -> Option { + match self { + Self::BombRelease { target, .. } | Self::Devour { target, .. } => Some(target), + _ => None, + } + } +} +impl Host { + fn bomb_finish(&mut self, w: &mut World, r: &mut buffs::Runtime, id: Id) -> Result<(), String> { + if !w.unit(id)?.stats.alive { + return Ok(()); + } + if let Some(Special::Bomb { speed, .. }) = self.special_config(id) { + self.content.as_mut().unwrap().set_special( + id, + Memory::Bomb { + phase: BombPhase::Done, + left: f64::INFINITY, + }, + ); + w.unit_mut(id)?.enemy.pause_until = w.time; + if speed > 0. { + let mut b = buff("ab:bombRun", &[("moveMul", speed)]); + b.runtime.persist = true; + self.enemy_buff(w, r, id, b)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime::enemies) fn enemy_special_task( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + task: Task, + ) -> Result { + if !w.unit(id)?.stats.alive { + return Ok(false); + } + match task { + Task::BombRelease { target, release } => { + if !matches!(self.content.as_ref().unwrap().special(id),Memory::Bomb{phase:BombPhase::Charging{release:held},..} if held==release) + { + return Ok(false); + } + if w.unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("stun") + { + let left = match self.special_config(id) { + Some(Special::Bomb { skill: Some(s), .. }) => s.period.max(DT), + _ => 1., + }; + self.content.as_mut().unwrap().set_special( + id, + Memory::Bomb { + phase: BombPhase::Ready, + left, + }, + ); + w.unit_mut(id)?.enemy.pause_until = w.time; + return Ok(false); + } + self.content.as_mut().unwrap().set_special( + id, + Memory::Bomb { + phase: BombPhase::Dropped { + waited: false, + landed: false, + }, + left: f64::INFINITY, + }, + ); + let attack = Self::tac_stat(w, id, "atk")?; + self.flights + .as_mut() + .ok_or("Missing bomb projectiles")? + .add( + w, + projectiles::Launch { + from: w.unit(id)?.position, + source: Some(id), + target: Some(target), + to: None, + speed: 5., + hit_dead: true, + max_age: 10., + on_hit: true, + visual: "droneBomb".into(), + speed_changeable: None, + removable: None, + payload: allies::Shot::Bomb(BombShot { source: id, attack }), + }, + )?; + self.enemy_schedule( + w, + Some(id), + 0.667, + 0., + 1, + EnemyTask::Special(Task::BombWait), + )?; + } + Task::BombWait => { + if let Memory::Bomb { + phase: BombPhase::Dropped { landed, .. }, + .. + } = self.content.as_ref().unwrap().special(id) + { + if landed { + self.bomb_finish(w, r, id)?; + } else { + self.content.as_mut().unwrap().set_special( + id, + Memory::Bomb { + phase: BombPhase::Dropped { + waited: true, + landed, + }, + left: f64::INFINITY, + }, + ); + } + } + } + Task::Devour { target, finish } => { + if !w.unit(target)?.stats.alive { + return Ok(false); + } + if let Some(Special::Cloud { + duration, + gain, + max, + .. + }) = self.special_config(id) + { + if finish { + if let Memory::Cloud { left, ammo } = + self.content.as_ref().unwrap().special(id) + { + self.content.as_mut().unwrap().set_special( + id, + Memory::Cloud { + left, + ammo: (ammo + gain).min(max), + }, + ); + } + self.kill_enemy(target, None, r, w)?; + } else { + let mut b = buff("ab:devoured", &[]); + b.runtime.duration = duration; + b.runtime.visible = true; + b.flags + .extend(["bind", "noMove", "disarm"].map(str::to_string)); + self.enemy_buff(w, r, target, b)?; + self.enemy_schedule( + w, + Some(id), + duration.max(0.), + 0., + 1, + EnemyTask::Special(Task::Devour { + target, + finish: true, + }), + )?; + } + } + } + Task::Entrance { hits } => { + let mut all = self.special_targets(w, id, f64::INFINITY)?; + all.sort_by(|&a, &b| { + w.unit(b) + .unwrap() + .stats + .hp + .total_cmp(&w.unit(a).unwrap().stats.hp) + }); + if let Some(&target) = all.first() { + let tile = w.unit(target)?.deployment.tile; + for _ in 0..hits { + let mut list = vec![]; + for t in self.enemy_tile_allies(w, tile, 1)? { + if targeting::area_selectable(w, Some(id), t)? { + list.push(t); + } + } + list.sort_by(|&a, &b| { + w.unit(b) + .unwrap() + .stats + .hp + .total_cmp(&w.unit(a).unwrap().stats.hp) + }); + if let Some(&t) = list.first() { + let amount = Self::tac_stat(w, id, "atk")?; + let mut q = ability_damage(Some(id), t, amount, DamageType::Physical); + self.enemy_damage(w, r, &mut q)?; + } + } + } + } + } + Ok(true) + } + pub(in crate::battle::runtime) fn enemy_bomb_impact( + &mut self, + w: &mut World, + shot: BombShot, + target: Option, + position: [f64; 2], + ) -> Result<(), String> { + let mut r = self.buffs.take().ok_or("Missing bomb impact buffs")?; + let result = (|| { + let tile = if let Some(t) = target { + w.unit(t)?.deployment.tile + } else { + position.map(|v| (v + 0.5).floor() as i32) + }; + if let Some(t) = target { + let mut q = ability_damage(Some(shot.source), t, shot.attack, DamageType::Physical); + self.enemy_damage(w, &mut r, &mut q)?; + } + for t in self.enemy_tile_allies(w, tile, 1)? { + if Some(t) != target && targeting::area_selectable(w, Some(shot.source), t)? { + let mut q = + ability_damage(Some(shot.source), t, shot.attack, DamageType::Physical); + q.tags.push("splash".into()); + self.enemy_damage(w, &mut r, &mut q)?; + } + } + if let Memory::Bomb { + phase: BombPhase::Dropped { waited, .. }, + .. + } = self.content.as_ref().unwrap().special(shot.source) + { + if waited { + self.bomb_finish(w, &mut r, shot.source)?; + } else { + self.content.as_mut().unwrap().set_special( + shot.source, + Memory::Bomb { + phase: BombPhase::Dropped { + waited, + landed: true, + }, + left: f64::INFINITY, + }, + ); + } + } + Ok(()) + })(); + self.buffs = Some(r); + result + } + pub(in crate::battle::runtime) fn enemy_translator_finish( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Some(Special::Translator { mods, .. }) = self.special_config(id) else { + return Ok(()); + }; + let Memory::Translator { + phase: Translation::Changing(form), + counts, + anger, + } = self.content.as_ref().unwrap().special(id) + else { + return Ok(()); + }; + if !w.unit(id)?.stats.alive { + return Ok(()); + } + self.content.as_mut().unwrap().set_special( + id, + Memory::Translator { + phase: Translation::Done(form), + counts, + anger, + }, + ); + r.remove(w, self, id, "ab:origin")?; + let i = match form { + Form::Fuchou => 0, + Form::Youling => 1, + Form::Shushi => 2, + }; + let values = mods[i]; + let mut b = buff( + "ab:form", + &[ + ("hpFlat", values[0]), + ("atkFlat", values[1]), + ("defFlat", values[2]), + ("resFlat", values[3]), + ("moveMul", values[4]), + ("batPct", values[5]), + ("massFlat", values[6]), + ], + ); + b.runtime.persist = true; + b.runtime.visible = true; + if form == Form::Youling { + b.flags.insert("unblockable".into()); + } + self.enemy_buff(w, r, id, b)?; + if form != Form::Youling { + w.unit_mut(id)?.cadence.cooldown = 0.; + } + if let Some(route) = w.unit_mut(id)?.motion.route.as_mut() { + route.points = None; + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_parasite_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + let Some(source) = r.get(w, c.unit, c.buff)?.runtime.retained_unit() else { + return Ok(()); + }; + if let Some(Special::Parasite { scale, .. }) = self.special_config(source) { + if w.unit(source)?.stats.alive { + let amount = Self::tac_stat(w, source, "atk")? * scale; + let mut q = ability_damage(Some(source), c.unit, amount, DamageType::Arts); + q.ignore_select = true; + q.is_skill = false; + q.tags.push("parasite".into()); + self.enemy_damage(w, r, &mut q)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_parasite_element( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + phase: element::Phase, + q: &mut element::Request, + ) -> Result<(), String> { + let target = q.damage.hit.target; + let source = w + .unit(target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("ab:parasite")) + .and_then(|b| b.runtime.retained_unit()); + let Some(source) = source else { + return Ok(()); + }; + match phase { + element::Phase::Hit => { + if let Some(Special::Parasite { element, .. }) = self.special_config(source) { + if element > 0. && element != 1. { + q.damage.damage.mul *= element; + } + } + } + element::Phase::Burst => { + if let Some(el) = q.damage.element { + let tile = w.unit(target)?.deployment.tile; + for t in self.roster.as_ref().unwrap().ids().to_vec() { + let u = w.unit(t)?; + if t != target + && u.stats.alive + && u.deployed + && !u.hidden + && (u.deployment.tile[0] - tile[0]).abs() + + (u.deployment.tile[1] - tile[1]).abs() + <= 1 + { + let mut hit = + element::Request::new(Some(source), Some(source), t, el, 1000.); + hit.damage.ignore_select = true; + hit.damage.attack_type = hit::AttackType::None; + hit.damage.tags = vec!["enemyAbility".into()]; + element::apply(w, self, r, &mut hit)?; + } + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/splits.rs b/crates/engine/src/battle/runtime/enemies/splits.rs new file mode 100644 index 0000000..6f90c7b --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/splits.rs @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{content::enemies::Split, motion::Route}; + +pub(in crate::battle::runtime) struct Children { + key: Arc, + count: usize, + position: [f64; 2], + route: Route, + mods: Value, + source_player: Value, + counted: Option, +} +impl Children { + pub(super) fn clear_scaling(&mut self) { + self.mods = Value::Null; + } + pub(super) fn make_stationary(&mut self, w: &World, id: Id, rect: Rect) -> Result<(), String> { + self.route = self.route.stationary(w.unit(id)?.position, rect)?; + self.counted = Some(false); + Ok(()) + } +} +impl Host { + pub(in crate::battle::runtime) fn enemy_children( + &self, + w: &World, + id: Id, + ) -> Result, String> { + let content = self + .content + .as_ref() + .ok_or("Missing enemy content context")?; + let Kit::Split(split) = content.kit(id) else { + return Ok(None); + }; + let count = content.split_count(id, split); + if count == 0 { + return Ok(None); + } + let Some(child) = content.child(id) else { + return Ok(None); + }; + self.enemy_children_spec(w, id, child, count).map(Some) + } + pub(super) fn enemy_children_spec( + &self, + w: &World, + id: Id, + child: Arc, + count: usize, + ) -> Result { + let spawns = self.spawns.as_ref().ok_or("Missing child spawn context")?; + let entry = spawns + .ledger + .alive() + .get(&id) + .ok_or("Missing parent spawn record")?; + let mut mods = entry.mods.clone(); + if let Some(m) = mods.as_object_mut() { + m.remove("bountyId"); + m.remove("bountyCoins"); + } + let u = w.unit(id)?; + let route = spawns.remaining_route(w, id)?; + Ok(Children { + key: child, + count, + position: u.position, + route, + mods, + source_player: entry.source_player.clone(), + counted: None, + }) + } + + pub(in crate::battle::runtime) fn enemy_spawn_children( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + children: Children, + ) -> Result<(), String> { + // The enemy index is a phase snapshot. Children born after EnemyIndex + // join range queries when the next EnemyIndex phase rebuilds it. + self.with_spawns(w, r, |spawns, context, world| { + for i in 0..children.count { + let offset = if children.count > 1 { + (i as f64 - (children.count as f64 - 1.) / 2.) * 0.2 + } else { + 0. + }; + let position = [children.position[0], children.position[1] + offset]; + spawns.spawn_child( + world, + context, + &children.key, + children.route.clone(), + position, + &children.mods, + &children.source_player, + children.counted, + None, + )?; + } + Ok(()) + }) + } + pub(super) fn enemy_split_attack( + &mut self, + c: &enemy::Context, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + if self.content.as_mut().unwrap().spend_blade(c.enemy) { + r.remove(w, self, c.enemy, "ab:blade")?; + } + Ok(()) + } + pub(super) fn enemy_split_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + split: Split, + dt: f64, + ) -> Result<(), String> { + match split { + Split::Blades { .. } => { + if self.content.as_mut().unwrap().clear_blade_cooldown(id) { + w.unit_mut(id)?.cadence.cooldown = 0.; + } + } + Split::Veil { + radius, duration, .. + } => { + let time = w.time; + let u = w.unit_mut(id)?; + let castable = !u.hidden + && !u + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("stun") + && time >= u.motion.unbalance_until - 1e-9; + if self.content.as_mut().unwrap().veil_ready(id, dt, castable) { + for other in self.enemy_nearby(w, id, radius)? { + if other == id || duration <= 0. { + continue; + } + let mut b = buff("ab:veiled", &[]); + b.runtime.duration = duration; + b.runtime.visible = true; + b.runtime.stealth_restore = Some(0.); + b.flags.insert("stealth".into()); + self.enemy_buff(w, r, other, b)?; + } + } + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_teapot_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Kit::Split(Split::Teapot { duration, aspd, .. }) = + self.content.as_ref().unwrap().kit(id) + else { + return Ok(()); + }; + if silenced(w, id)? { + return Ok(()); + } + let amount = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk"); + for target in enemy::Hooks::allies_in_radius(self, id, 1.25, w, w.unit_capacity())? { + if w.unit(target)?.motion_fly + || !crate::battle::targeting::area_selectable(w, Some(id), target)? + { + continue; + } + let mut damage = ability_damage(None, target, amount, DamageType::Arts); + damage.tags.push("teaBoom".into()); + self.enemy_damage(w, r, &mut damage)?; + if w.unit(target)?.stats.alive && duration > 0. && aspd != 0. { + let mut b = buff(&format!("ab:teaBoom:{id}"), &[("aspd", aspd)]); + b.runtime.duration = duration; + b.runtime.visible = true; + self.enemy_buff(w, r, target, b)?; + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/supporters.rs b/crates/engine/src/battle/runtime/enemies/supporters.rs new file mode 100644 index 0000000..8c38f17 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/supporters.rs @@ -0,0 +1,437 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::content::enemies::{supporters::Memory, Supporter}; +use crate::deterministic::math::hypot; +impl Host { + pub(super) fn enemy_supporter_taken( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let Kit::Supporter(Supporter::Roar { fear, .. }) = self.content.as_ref().unwrap().kit(id) + else { + return Ok(()); + }; + let Memory::Roar { left, feared } = self.content.as_ref().unwrap().supporter(id) else { + unreachable!() + }; + let hp = w.unit(id)?.stats.hp; + if feared || hp / Self::tac_stat(w, id, "maxHp")? >= 0.5 { + return Ok(()); + } + self.content + .as_mut() + .unwrap() + .set_supporter(id, Memory::Roar { left, feared: true }); + if fear.duration > 0. { + self.apply_status( + w, + r, + id, + "fear", + status::Options { + source: Some(id), + duration: fear.duration, + ..Default::default() + }, + )?; + } + if fear.speed > 0. && fear.speed_duration > 0. { + let mut b = buff("ab:fearRun", &[("moveMul", fear.speed)]); + b.runtime.duration = fear.speed_duration; + b.flags.insert("unblockable".into()); + self.enemy_buff(w, r, id, b)?; + } + Ok(()) + } + pub(super) fn enemy_supporter_hit( + &mut self, + w: &World, + q: &mut hit::Request, + id: Id, + ) -> Result<(), String> { + match self.content.as_ref().unwrap().kit(id) { + Kit::Supporter(Supporter::Torturer { ranged, .. }) + if w.unit(id)?.blocked_by() != Some(q.hit.target) => + { + q.damage.amount *= ranged + } + Kit::Supporter(Supporter::Barrel { scale, .. }) + if !w + .unit(id)? + .stats + .buffs() + .iter() + .any(|b| b.flags.contains("silence")) + && matches!( + self.content.as_ref().unwrap().supporter(id), + Memory::Barrel { done: false } + ) => + { + q.damage.amount *= scale + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_supporter_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + event: enemy::Event, + ) -> Result<(), String> { + let Kit::Supporter(Supporter::Barrel { + life, aspd, dodge, .. + }) = self.content.as_ref().unwrap().kit(id) + else { + return Ok(()); + }; + if event != enemy::Event::Attack + || silenced(w, id)? + || !matches!( + self.content.as_ref().unwrap().supporter(id), + Memory::Barrel { done: false } + ) + { + return Ok(()); + } + self.content + .as_mut() + .unwrap() + .set_supporter(id, Memory::Barrel { done: true }); + r.remove(w, self, id, "ab:barrel")?; + let count = ((life - 1e-6) / 0.5).ceil().max(1.); + if !count.is_finite() || count > i32::MAX as f64 { + return Err("Barrel pulse count outside positive i32 domain".into()); + } + self.enemy_schedule( + w, + None, + 0.5, + 0.5, + count as u32, + EnemyTask::Barrel { + position: w.unit(id)?.position, + aspd, + dodge, + }, + ) + } + pub(super) fn enemy_barrel_pulse( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + position: [f64; 2], + aspd: f64, + dodge: f64, + ) -> Result<(), String> { + let ids = self.spawns.as_ref().unwrap().live().to_vec(); + let targets = spatial::enemies_in_radius( + w, + self, + &ids, + position, + 1.5, + RadiusRule::Body, + false, + w.unit_capacity(), + )?; + for target in targets { + let mut b = buff("ab:barrelZone", &[("aspd", aspd), ("dodgePhys", dodge)]); + b.runtime.duration = 0.6; + self.enemy_buff(w, r, target, b)?; + } + Ok(()) + } + pub(super) fn enemy_supporter_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + kit: Supporter, + dt: f64, + ) -> Result<(), String> { + match kit { + Supporter::Roar { + skill: Some(skill), + duration, + aspd, + .. + } => { + let Memory::Roar { mut left, feared } = + self.content.as_ref().unwrap().supporter(id) + else { + unreachable!() + }; + let castable = self.enemy_can_cast(w, id, true)?; + let cast = skill.advance(&mut left, dt, castable); + self.content + .as_mut() + .unwrap() + .set_supporter(id, Memory::Roar { left, feared }); + if cast { + for target in self.roster.as_ref().unwrap().ids().to_vec() { + if w.unit(target)?.motion_fly + || !crate::battle::targeting::area_selectable(w, Some(id), target)? + { + continue; + } + let mut b = buff("ab:roar", &[("aspd", aspd)]); + b.runtime.duration = duration; + b.runtime.visible = true; + b.runtime.refresh = buffs::Refresh::Extend; + self.enemy_buff(w, r, target, b)?; + } + } + } + Supporter::Carrier { max, camel, speed } => { + let Memory::Carrier { + mut passengers, + seats, + } = self.content.as_ref().unwrap().supporter(id) + else { + unreachable!() + }; + let mut keep = vec![]; + for p in passengers { + let u = w.unit(p)?; + if u.stats.alive && u.enemy.carrier == Some(id) { + keep.push(p); + } else { + if u.enemy.carrier == Some(id) { + w.unit_mut(p)?.enemy.carrier = None; + } + w.unpin_unit(p)?; + } + } + passengers = keep; + let picking = self.enemy_can_cast(w, id, false)?; + if picking { + for other in self.spawns.as_ref().unwrap().live().to_vec() { + if passengers.len() >= max { + break; + } + let u = w.unit(other)?; + if other == id + || !u.stats.alive + || !u.deployed + || u.hidden + || u.enemy.carrier.is_some() + || u.boss + || u.motion_fly + { + continue; + } + let def = self.spawns.as_ref().unwrap().definition(other)?; + if def.leader || def.machine { + continue; + } + let at = w.unit(id)?.position; + if hypot(u.position[1] - at[1], u.position[0] - at[0]) > 0.5 + 1e-9 { + continue; + } + enemy::clear(w, other)?; + let u = w.unit_mut(other)?; + u.enemy.carrier = Some(id); + u.hidden = true; + u.motion.attack_stand_until = f64::NEG_INFINITY; + w.pin_unit(other)?; + blocking::unblock( + w, + &mut allies::Blocking { + host: self, + buffs: r, + }, + other, + )?; + passengers.push(other); + } + } + for &other in &passengers { + let position = w.unit(id)?.position; + let u = w.unit_mut(other)?; + u.position = position; + u.moving = false; + } + let now = passengers.len(); + self.content.as_mut().unwrap().set_supporter( + id, + Memory::Carrier { + passengers, + seats: if camel { now } else { seats }, + }, + ); + if camel && seats != now { + let mut b = buff( + "ab:busSpeed", + &[("moveMul", (1. + speed * now as f64).max(0.))], + ); + b.runtime.persist = true; + self.enemy_buff(w, r, id, b)?; + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_other_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + victim: Id, + ) -> Result<(), String> { + if w.unit(victim)?.stats.alive { + return Ok(()); + } + let position = w.unit(victim)?.position; + let knight = w.unit(victim)?.side == health::Side::Enemy + && self + .spawns + .as_ref() + .unwrap() + .definition(victim)? + .key + .contains("enemy_1513_dekght"); + for id in self.spawns.as_ref().unwrap().live().to_vec() { + if id == victim || !w.unit(id)?.stats.alive { + continue; + } + if knight { + if let Kit::Caster(content::Caster { + passive: + content::casters::Passive::Knight { + atk, aspd, speed, .. + }, + .. + }) = self.content.as_ref().unwrap().kit(id) + { + let mut state = self.content.as_ref().unwrap().caster(id); + if !state.enraged { + state.enraged = true; + self.content.as_mut().unwrap().set_caster(id, state); + let mut b = buff( + "ab:rage", + &[("atkPct", atk), ("aspd", aspd), ("moveMul", 1. + speed)], + ); + b.runtime.persist = true; + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + } + } + let Kit::Supporter(Supporter::Torturer { + radius, + heal, + atk, + max, + .. + }) = self.content.as_ref().unwrap().kit(id) + else { + continue; + }; + let at = w.unit(id)?.position; + if hypot(at[1] - position[1], at[0] - position[0]) > radius + 1e-9 { + continue; + } + let amount = Self::tac_stat(w, id, "maxHp")? * heal; + self.support_heal( + w, + r, + Some(id), + id, + amount, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + let mut b = buff("ab:torture", &[("atkPct", atk)]); + b.runtime.persist = true; + b.runtime.refresh = buffs::Refresh::Stack; + b.runtime.max_stacks = max; + self.enemy_buff(w, r, id, b)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_torturer_children( + &mut self, + w: &World, + id: Id, + ) -> Result, String> { + let Kit::Supporter(Supporter::Torturer { count, .. }) = + self.content.as_ref().unwrap().kit(id) + else { + return Ok(None); + }; + let Some(key) = self + .content + .as_ref() + .unwrap() + .child(id) + .filter(|_| count > 0) + else { + return Ok(None); + }; + let mut children = self.enemy_children_spec(w, id, key, count)?; + children.make_stationary(w, id, self.spawns.as_ref().unwrap().rect())?; + Ok(Some(children)) + } + pub(in crate::battle::runtime) fn enemy_unload( + &mut self, + w: &mut World, + id: Id, + rng: &mut Rng, + ) -> Result<(), String> { + let Kit::Supporter(Supporter::Carrier { camel, .. }) = + self.content.as_ref().unwrap().kit(id) + else { + return Ok(()); + }; + let Memory::Carrier { passengers, .. } = self.content.as_ref().unwrap().supporter(id) + else { + unreachable!() + }; + let origin = w.unit(id)?.position; + let rect = self.spawns.as_ref().unwrap().rect(); + for other in passengers { + if w.unit(other)?.enemy.carrier == Some(id) { + w.unit_mut(other)?.enemy.carrier = None; + } + if !w.unit(other)?.stats.alive { + w.unpin_unit(other)?; + continue; + } + let position = if camel { + let x = (origin[1] + rng.range(-0.2, 0.2)).clamp(rect.c0 as f64, rect.c1 as f64); + let y = (origin[0] + rng.range(-0.2, 0.2)).clamp(rect.r0 as f64, rect.r1 as f64); + [y, x] + } else { + origin.map(|x| (x + 0.5).floor()) + }; + let route = w + .unit(if camel { id } else { other })? + .motion + .route + .as_ref() + .ok_or("Missing passenger unload route")? + .after_wait(position, rect)?; + enemy::clear(w, other)?; + let u = w.unit_mut(other)?; + u.position = position; + u.motion.route = Some(route); + u.motion.attack_stand_until = f64::NEG_INFINITY; + u.hidden = false; + w.unpin_unit(other)?; + } + self.content.as_mut().unwrap().set_supporter( + id, + Memory::Carrier { + passengers: vec![], + seats: 0, + }, + ); + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/terrain.rs b/crates/engine/src/battle/runtime/enemies/terrain.rs new file mode 100644 index 0000000..d86e079 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/terrain.rs @@ -0,0 +1,225 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::battle::{content::enemies::terrain::TerrainKit, targeting, terrain::Kind}; +use crate::deterministic::math::hypot; +impl Host { + fn enemy_on_terrain(&self, w: &World, id: Id, kind: Kind) -> Result { + Ok(self.terrain.at(w.unit(id)?.position) == kind) + } + pub(super) fn enemy_terrain_hit( + &mut self, + w: &mut World, + q: &mut hit::Request, + id: Id, + ) -> Result<(), String> { + match self.content.as_ref().unwrap().kit(id) { + Kit::Terrain(TerrainKit::Infection) + if self.enemy_on_terrain(w, id, Kind::Infection)? => + { + q.hit.damage_type = DamageType::Arts + } + Kit::Terrain(TerrainKit::Chimera { .. }) => { + let mut state = self.content.as_ref().unwrap().terrain_state(id); + if !state.active && self.enemy_on_terrain(w, id, Kind::Infection)? { + state.active = true; + self.content.as_mut().unwrap().set_terrain_state(id, state); + } + if state.active { + q.hit.damage_type = DamageType::Arts; + } + } + _ => {} + } + Ok(()) + } + pub(in crate::battle::runtime) fn enemy_terrain_in(&self, q: &mut hit::Request) { + if let Some(content) = &self.content { + if matches!( + content.kit(q.hit.target), + Kit::Terrain(TerrainKit::Deepsea { swim: true, .. }) + ) && content.terrain_state(q.hit.target).wet + && q.tags.iter().any(|t| t == "deepsea" || t == "drown") + { + q.cancelled = true; + } + } + } + pub(in crate::battle::runtime) fn enemy_chalice_share( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + q: &mut hit::Request, + ) -> Result<(), String> { + if !self.content.as_ref().is_some_and(|c| c.has_chalices()) + || q.cancelled + || w.unit(q.hit.target)?.side != health::Side::Enemy + || q.tags.iter().any(|t| t == "chalice") + || targeting::flying(w, q.hit.target)? + { + return Ok(()); + } + let at = w.unit(q.hit.target)?.position; + for id in self.spawns.as_ref().unwrap().live().to_vec() { + if id == q.hit.target || !w.unit(id)?.stats.alive { + continue; + } + let Kit::Terrain(TerrainKit::Chalice { radius, share }) = + self.content.as_ref().unwrap().kit(id) + else { + continue; + }; + let p = w.unit(id)?.position; + if share <= 0. || hypot(p[0] - at[0], p[1] - at[1]) > radius { + continue; + } + let amount = q.damage.amount * share; + q.damage.amount -= amount; + let mut part = ability_damage(q.hit.source, id, amount, q.hit.damage_type); + part.hit.credit = q.hit.credit; + part.is_skill = false; + part.tags = q.tags.clone(); + part.tags.push("chalice".into()); + self.enemy_damage(w, r, &mut part)?; + break; + } + Ok(()) + } + pub(super) fn enemy_terrain_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: &mut enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + let id = c.enemy; + match self.content.as_ref().unwrap().kit(id) { + Kit::Terrain(TerrainKit::Nazg { radius }) if event == enemy::Event::BeforeAttack => { + let mut targets = vec![]; + let at = w.unit(id)?.position; + let infected = self.enemy_on_terrain(w, id, Kind::Infection)?; + for t in self.roster.as_ref().unwrap().ids() { + let p = w.unit(*t)?.position; + if (hypot(p[0] - at[0], p[1] - at[1]) <= radius + || infected && self.enemy_on_terrain(w, *t, Kind::Infection)?) + && targeting::can_target_ally(w, id, *t, true, Default::default())? + { + targets.push(*t); + } + } + if !targets.is_empty() { + targeting::sort_allies(w, id, &mut targets, Default::default())?; + c.targets = targets; + } + } + Kit::Terrain(TerrainKit::Deepsea { every, stun, .. }) + if event == enemy::Event::Attack => + { + if every == 0 + || silenced(w, id)? + || !self.content.as_mut().unwrap().counted(id, every) + { + return Ok(()); + } + for &t in &c.targets { + if stun > 0. + && w.unit(t)?.stats.alive + && c.deployments + .contains(&(t, w.unit(t)?.deployment.deploy_seq)) + { + self.apply_status( + w, + r, + t, + "stun", + status::Options { + source: Some(id), + duration: stun, + ..Default::default() + }, + )?; + } + } + } + _ => {} + } + Ok(()) + } + pub(super) fn enemy_terrain_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + kit: TerrainKit, + dt: f64, + ) -> Result<(), String> { + if !matches!(kit, TerrainKit::Deepsea { .. } | TerrainKit::Chimera { .. }) { + return Ok(()); + } + let pulses = self.content.as_mut().unwrap().pulses(id, dt, 0.25); + for _ in 0..pulses { + let mut state = self.content.as_ref().unwrap().terrain_state(id); + match kit { + TerrainKit::Chimera { damage, recovery } => { + state.active |= self.enemy_on_terrain(w, id, Kind::Infection)?; + if !state.active { + continue; + } + state.elapsed += 0.25; + let pulse = state.elapsed >= 0.5 - 1e-9; + if pulse { + state.elapsed -= 0.5; + } + for t in enemy::Hooks::allies_in_radius(self, id, 1.2, w, w.unit_capacity())? { + let mut b = buff( + "ab:originium", + &[("spRecoveryMul", (1. + recovery).max(0.))], + ); + b.runtime.duration = 0.35; + self.enemy_buff(w, r, t, b)?; + if !pulse || damage <= 0. || w.time - w.unit(t)?.chimera_at < 0.5 - 1e-6 { + continue; + } + let now = w.time; + w.unit_mut(t)?.chimera_at = now; + let mut q = ability_damage(None, t, damage, DamageType::True); + q.hit.credit = Some(id); + q.hit.no_sp = false; + q.is_skill = false; + q.tags = vec!["dot".into(), "pollution".into()]; + self.enemy_damage(w, r, &mut q)?; + } + } + TerrainKit::Deepsea { + swim, atk, drown, .. + } => { + let wet = self.enemy_on_terrain(w, id, Kind::Deepsea)?; + if swim { + if wet && !state.wet { + let mut b = buff("ab:swim", &[("atkPct", atk)]); + b.flags.insert("stealth".into()); + b.runtime.visible = true; + self.enemy_buff(w, r, id, b)?; + } + if !wet && state.wet { + r.remove(w, self, id, "ab:swim")?; + } + if wet { + r.remove(w, self, id, "terrain:deepsea")?; + } + } + if wet && drown > 0. { + let mut q = ability_damage(None, id, drown * 0.25, DamageType::True); + q.hit.no_sp = false; + q.is_skill = false; + q.tags = vec!["dot".into(), "periodic".into(), "drown".into()]; + self.enemy_damage(w, r, &mut q)?; + } + state.wet = wet; + } + _ => {} + } + self.content.as_mut().unwrap().set_terrain_state(id, state); + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/enemies/zones.rs b/crates/engine/src/battle/runtime/enemies/zones.rs new file mode 100644 index 0000000..8ab2c95 --- /dev/null +++ b/crates/engine/src/battle/runtime/enemies/zones.rs @@ -0,0 +1,409 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::forms::FormEvent; +use super::*; +use crate::battle::{ + content::enemies::zones::{Cloud, Pollution, ZoneKit}, + projectiles, targeting, +}; + +#[derive(Clone, Copy)] +pub(in crate::battle::runtime) enum ZoneDamage { + Pollution { + low: f64, + high: f64, + }, + Arts { + amount: f64, + no_air: bool, + poison: bool, + }, +} +#[derive(Clone, Copy)] +pub(in crate::battle::runtime) struct Zone { + pub position: [f64; 2], + pub radius: f64, + pub damage: ZoneDamage, +} +#[derive(Clone)] +pub(in crate::battle::runtime) enum EnemyTask { + Catapult(super::catapult::SharedVolley), + Boss(super::BossTask), + Special(super::SpecialTask), + Blast { + position: [f64; 2], + scale: f64, + stun: f64, + }, + Form(FormEvent), + Spell(super::SpellTask), + Barrel { + position: [f64; 2], + aspd: f64, + dodge: f64, + }, + Shell { + position: [f64; 2], + amount: f64, + }, + Zone(Zone), +} +#[derive(Clone, Copy)] +pub(in crate::battle::runtime) struct CloudShot { + pub cloud: Cloud, + pub amount: f64, +} +impl EnemyTask { + pub(in crate::battle::runtime) fn retained_target(&self) -> Option { + match self { + Self::Catapult(v) => v.target, + Self::Special(t) => t.target(), + Self::Spell(t) => t.target(), + Self::Boss(t) => t.target(), + _ => None, + } + } +} +impl Host { + pub(super) fn enemy_schedule( + &mut self, + w: &mut World, + source: Option, + delay: f64, + interval: f64, + count: u32, + task: EnemyTask, + ) -> Result<(), String> { + let seq = source + .map(|id| w.unit(id).map(|u| u.deployment.deploy_seq)) + .transpose()? + .unwrap_or(0); + let references = [source, task.retained_target()]; + for (index, reference) in references.iter().enumerate() { + if let Some(id) = reference { + if let Err(error) = w.pin_unit(*id) { + for previous in references[..index].iter().flatten() { + w.unpin_unit(*previous)?; + } + return Err(error); + } + } + } + let result = self.enqueue_timer(super::super::tactics::Timer { + source, + seq, + at: w.time + delay, + interval, + left: count, + kind: super::super::tactics::Task::Enemy(task), + }); + if result.is_err() { + for id in references.into_iter().flatten() { + w.unpin_unit(id)?; + } + } + result + } + fn enemy_zone( + &mut self, + w: &mut World, + source: Option, + zone: Zone, + life: f64, + interval: f64, + ) -> Result<(), String> { + let interval = if interval > 0. { + interval + } else { + super::super::DT + }; + let count = ((life - 1e-6) / interval).ceil().max(1.); + if !count.is_finite() || count > i32::MAX as f64 { + return Err("Enemy zone pulse count outside i32 domain".into()); + } + self.enemy_schedule( + w, + source, + interval, + interval, + count as u32, + EnemyTask::Zone(zone), + ) + } + pub(super) fn enemy_pollution( + &mut self, + w: &mut World, + id: Id, + position: [f64; 2], + p: Pollution, + ) -> Result<(), String> { + self.enemy_zone( + w, + Some(id), + Zone { + position, + radius: p.radius, + damage: ZoneDamage::Pollution { + low: p.low, + high: p.high, + }, + }, + p.life, + 1., + ) + } + pub(in crate::battle::runtime) fn enemy_cloud( + &mut self, + w: &mut World, + shot: CloudShot, + position: [f64; 2], + ) -> Result<(), String> { + self.enemy_zone( + w, + None, + Zone { + position, + radius: shot.cloud.radius, + damage: ZoneDamage::Arts { + amount: shot.amount, + no_air: false, + poison: true, + }, + }, + shot.cloud.life, + shot.cloud.interval, + ) + } + pub(in crate::battle::runtime) fn enemy_task( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Option, + task: &mut EnemyTask, + last: bool, + ) -> Result { + if let EnemyTask::Catapult(volley) = task { + self.enemy_catapult_stone(w, r, source.ok_or("Missing catapult source")?, volley)?; + return Ok(true); + } + match *task { + EnemyTask::Catapult(_) => unreachable!(), + EnemyTask::Boss(t) => { + return self.boss_task(w, r, source.ok_or("Missing boss task source")?, t) + } + EnemyTask::Special(t) => { + return self.enemy_special_task( + w, + r, + source.ok_or("Missing special timer source")?, + t, + ) + } + EnemyTask::Blast { + position, + scale, + stun, + } => { + let id = source.ok_or("Missing blast source")?; + if !w.unit(id)?.stats.alive { + return Ok(false); + } + for t in spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + position, + 3., + None, + false, + w.unit_capacity(), + )? { + if !targeting::area_selectable(w, Some(id), t)? { + continue; + } + let amount = Self::tac_stat(w, id, "atk")? * scale; + let mut q = ability_damage(Some(id), t, amount, DamageType::Physical); + self.enemy_damage(w, r, &mut q)?; + if stun > 0. && w.unit(t)?.stats.alive { + self.apply_status( + w, + r, + t, + "stun", + status::Options { + source: Some(id), + duration: stun, + ..Default::default() + }, + )?; + } + } + } + EnemyTask::Spell(t) => return self.enemy_spell_task(w, r, source, t, last), + EnemyTask::Barrel { + position, + aspd, + dodge, + } => self.enemy_barrel_pulse(w, r, position, aspd, dodge)?, + EnemyTask::Shell { position, amount } => { + self.enemy_shell(w, r, source, position, amount)? + } + EnemyTask::Form(event) => { + let id = source.ok_or("Missing form timer source")?; + if !w.unit(id)?.stats.alive { + return Ok(false); + } + self.enemy_form_event(w, r, id, event)?; + } + EnemyTask::Zone(zone) => { + let targets = spatial::allies_in_radius( + w, + self.roster.as_ref().unwrap().ids(), + zone.position, + zone.radius, + None, + false, + w.unit_capacity(), + )?; + for target in targets { + let (amount, kind, tag, ignore) = match zone.damage { + ZoneDamage::Pollution { low, high } => { + let time = w.time; + let u = w.unit_mut(target)?; + let amount = if u.ground { low } else { high }; + if amount <= 0. || time - u.polluted_at < 1. - 1e-6 { + continue; + } + u.polluted_at = time; + (amount, DamageType::True, "pollution", true) + } + ZoneDamage::Arts { + amount, + no_air, + poison, + } => { + if no_air && w.unit(target)?.motion_fly + || !targeting::area_selectable(w, source, target)? + { + continue; + } + ( + amount, + DamageType::Arts, + if poison { "poison" } else { "burning" }, + false, + ) + } + }; + let mut damage = ability_damage(source, target, amount, kind); + damage.ignore_select = ignore; + damage.tags.push(tag.into()); + self.enemy_damage(w, r, &mut damage)?; + } + } + } + Ok(true) + } + pub(super) fn enemy_zone_attack( + &mut self, + w: &mut World, + c: &enemy::Context, + event: enemy::Event, + ) -> Result<(), String> { + if event == enemy::Event::BeforeAttack { + self.content.as_mut().unwrap().tank_before(c.enemy); + } + if event == enemy::Event::Attack { + if let Kit::Zone(ZoneKit::Tank(tank)) = self.content.as_ref().unwrap().kit(c.enemy) { + if self.content.as_mut().unwrap().tank_attack(c.enemy) { + if let Some(&target) = c.targets.first() { + self.enemy_pollution(w, c.enemy, w.unit(target)?.position, tank.pollution)?; + } + } + } + } + Ok(()) + } + pub(super) fn enemy_zone_dealt( + &mut self, + w: &mut World, + q: &hit::Request, + id: Id, + ) -> Result<(), String> { + if let Kit::Zone(ZoneKit::Cannon { + radius, + life, + amount, + }) = self.content.as_ref().unwrap().kit(id) + { + self.enemy_zone( + w, + Some(id), + Zone { + position: w.unit(q.hit.target)?.position, + radius, + damage: ZoneDamage::Arts { + amount, + no_air: true, + poison: false, + }, + }, + life, + 1., + )?; + } + Ok(()) + } + pub(super) fn enemy_zone_death( + &mut self, + w: &mut World, + id: Id, + credit: Option, + ) -> Result<(), String> { + match self.content.as_ref().unwrap().kit(id) { + Kit::Zone(ZoneKit::Pollution(p)) if !silenced(w, id)? => { + self.enemy_pollution(w, id, w.unit(id)?.position, p)? + } + Kit::Zone(ZoneKit::Poison(cloud)) if !silenced(w, id)? => { + let shot = CloudShot { + cloud, + amount: w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * cloud.scale, + }; + let target = credit.filter(|&k| { + w.unit(k) + .is_ok_and(|u| u.side == health::Side::Ally && u.stats.alive) + }); + if let Some(target) = target { + self.flights + .as_mut() + .ok_or("Missing poison projectile system")? + .add( + w, + projectiles::Launch { + from: w.unit(id)?.position, + source: None, + target: Some(target), + to: None, + speed: 8., + hit_dead: true, + max_age: 10., + on_hit: true, + visual: "lob".into(), + speed_changeable: None, + removable: None, + payload: allies::Shot::Cloud(shot), + }, + )?; + } else { + self.enemy_cloud(w, shot, w.unit(id)?.position)?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/equipment.rs b/crates/engine/src/battle/runtime/equipment.rs new file mode 100644 index 0000000..5c93228 --- /dev/null +++ b/crates/engine/src/battle/runtime/equipment.rs @@ -0,0 +1,1105 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Equipped effects use canonical damage, healing, buffs and status lifetimes. +use super::super::{ + attacks, + damage::{Damage, DamageType}, + equipment::Effect, + search, skills, + stats::{Buff, Numbers}, + targeting, +}; +use super::*; +use crate::deterministic::math::hypot; + +impl Host { + pub(super) fn equipment_install( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let roster = self.roster.as_ref().unwrap(); + let loadouts: Vec<_> = roster + .ids() + .iter() + .map(|&id| Ok((id, Arc::clone(&roster.entry(id)?.definition)))) + .collect::>()?; + for (unit, definition) in loadouts { + for grant in &definition.equipment { + for buff in &grant.buffs { + r.add( + w, + self, + unit, + buffs::Spec { + buff: buff.clone(), + allow_dead: true, + mods_present: true, + ..Default::default() + }, + )?; + } + for effect in &grant.effects { + match effect { + Effect::Cauldron { speed, cap } + if self.equipment_member(unit, "yanShip") => + { + let count = self.equipment.gained_chess.min(*cap as u64); + if count > 0 { + self.equipment_stat( + w, + r, + unit, + format!("{}:yan", grant.tag), + [("aspd".into(), speed * count as f64)].into(), + )?; + } + } + Effect::Hammer(hammer) => { + let hammers = self + .equipment + .units + .get_mut(&unit) + .unwrap() + .hammers + .as_mut() + .unwrap(); + let index = hammer.index(); + hammers.own[index] += 1; + hammers.params[index].get_or_insert(*hammer); + self.hammer_refresh(w, r, unit)?; + } + Effect::Steam(params) => { + self.equipment + .units + .get_mut(&unit) + .unwrap() + .hammers + .as_mut() + .unwrap() + .steam + .get_or_insert(*params); + self.hammer_refresh(w, r, unit)?; + } + _ => (), + } + } + } + } + Ok(()) + } + + pub(super) fn equipment_member(&self, unit: Id, bond: &str) -> bool { + self.equipment.units.get(&unit).is_some_and(|loadout| { + loadout.bonds.iter().any(|b| b == bond) + || (super::bonds::core_bond(bond) + && loadout.bonds.iter().any(|b| b == "maniShip") + && self.growth.live.get("maniShip").is_some_and(|b| b.tier > 0)) + }) + } + pub(super) fn equipment_partner( + &self, + unit: Id, + instance: &super::super::equipment::Instance, + ) -> bool { + instance.partner.as_deref().is_some_and(|partner| { + self.equipment.units[&unit].items.iter().any(|tag| { + let id = tag.strip_prefix("item:").unwrap(); + let family = id + .strip_suffix("_a") + .or_else(|| id.strip_suffix("_b")) + .unwrap_or(id); + family + == partner + .strip_suffix("_a") + .or_else(|| partner.strip_suffix("_b")) + .unwrap_or(partner) + }) + }) + } + pub(super) fn equipment_targets( + &mut self, + w: &mut World, + unit: Id, + profile: targeting::Profile, + ) -> Result, String> { + let keys = self.roster.as_ref().unwrap().range(w, unit)?; + search::Host::enemies(self, unit, &keys, profile, w, w.unit_capacity()) + } + pub(super) fn equipment_damage( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + scale: f64, + kind: DamageType, + tag: &str, + dodge: bool, + ) -> Result<(), String> { + let amount = Self::tac_stat(w, source, "atk")? * scale; + let mut q = hit::Request::new( + health::Hit { + source: Some(source), + credit: Some(source), + target, + damage_type: kind, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + penetration: Default::default(), + resolved: false, + }, + ); + q.tags = vec!["item".into(), format!("item:{tag}")]; + if !dodge { + q.dodge_mode = super::super::injury::DodgeMode::Ignore; + } + self.enemy_damage(w, r, &mut q)?; + Ok(()) + } + pub(super) fn equipment_chance(&mut self, probability: f64) -> bool { + probability > 0. && (probability >= 1. || self.rng.next_f64() < probability) + } + pub(super) fn equipment_skill( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + event: skills::Event, + context: &skills::Context, + skill: &mut skills::Runtime, + ) -> Result<(), String> { + let unit = skill.unit(); + let initial = w.time == 0. && w.unit(unit)?.operator.deployments == 1; + let ammo_left = skill.ammo_left; + if event == skills::Event::Deploy { + self.equipment.fields.clear(); + } + if !matches!( + event, + skills::Event::Deploy + | skills::Event::SkillStart + | skills::Event::SkillEnd + | skills::Event::AmmoUsed + ) { + return Ok(()); + } + let direction = self.roster.as_ref().unwrap().entry(unit)?.direction; + // Dispatch in grant order so mixed loadouts observe the same SP and buff state. + for (index, instance) in self.equipment.effects(unit) { + match instance.effect { + Effect::Chivalry { .. } => { + self.chivalry_skill(w, r, unit, index, &instance, event, context, skill)? + } + Effect::Compass { + initial, + end, + team, + spent, + } => { + if event == skills::Event::Deploy { + self.with_kit_buffs(w, r, |host, world| { + skill.gain(world, host, initial, "init", false, false) + })?; + } + if !self.equipment_member(unit, "sargonShip") { + continue; + } + if event == skills::Event::SkillEnd && !spent && context.reason != "death" { + self.equipment.units.get_mut(&unit).unwrap().effects[index].effect = + Effect::Compass { + initial, + end, + team, + spent: true, + }; + if w.unit(unit)?.stats.alive { + self.with_kit_buffs(w, r, |host, world| { + skill.gain(world, host, end, "item", false, true) + })?; + } + } + if event == skills::Event::SkillStart + && team > 0. + && self.equipment_partner(unit, &instance) + { + let owner = w.unit(unit)?.owner; + for target in self.roster.as_ref().unwrap().ids().to_vec() { + if w.unit(target)?.owner != owner + || !Self::tac_up(w, target) + || !self.equipment_member(target, "sargonShip") + { + continue; + } + if target == unit { + self.with_kit_buffs(w, r, |host, world| { + skill.gain(world, host, team, "item", false, true) + })?; + } else { + let mut recipient = + self.roster.as_mut().unwrap().take_skill(target)?; + let result = self.with_kit_buffs(w, r, |host, world| { + recipient.gain(world, host, team, "item", false, true) + }); + self.roster + .as_mut() + .unwrap() + .restore_skill(target, recipient)?; + result?; + } + } + } + } + Effect::DeploySp(each) if event == skills::Event::Deploy => { + let mine = &self.equipment.units[&unit].bonds; + let mut count = 1; + for (&other, loadout) in &self.equipment.units { + let a = w.unit(other)?; + if other != unit + && a.owner == w.unit(unit)?.owner + && !a.removed + && (initial || Self::tac_up(w, other)) + && loadout.bonds.iter().any(|bond| mine.contains(bond)) + { + count += 1; + } + } + self.with_kit_buffs(w, r, |host, world| { + skill.gain(world, host, each * count as f64, "item", false, false) + })?; + } + Effect::FrontHealth(extra) if event == skills::Event::Deploy => { + let front = direction.vector(); + let tile = w.unit(unit)?.deployment.tile; + let front = [tile[0] + front[0], tile[1] + front[1]]; + let occupied = w.unit_ids().any(|other| { + let a = w.unit(other).unwrap(); + other != unit + && a.side == health::Side::Ally + && a.deployment.kind == super::super::deploy::Kind::Operator + && !a.removed + && if initial { + a.deployment.home == front + } else { + Self::tac_up(w, other) && a.deployment.tile == front + } + }); + let key = format!("{}:front", instance.tag); + if occupied { + r.remove(w, self, unit, &key)?; + } else { + r.add( + w, + self, + unit, + buffs::Spec { + buff: Buff { + key: Some(key), + mods: [("hpPct".into(), extra)].into(), + permanent: true, + ..Default::default() + }, + mods_present: true, + ..Default::default() + }, + )?; + } + } + Effect::AmmoClip { + probability, + ratio, + cap, + mut used, + mut deployment, + } if event == skills::Event::AmmoUsed && ammo_left == 1. => { + let current = w.unit(unit)?.deployment.deploy_seq; + if current != deployment { + used = 0; + deployment = current; + } + if used < cap && self.equipment_chance(probability) { + used += 1; + skill.add_ammo((ratio * skill.spec.ammo - 1e-9).ceil().max(1.)); + } + self.equipment.units.get_mut(&unit).unwrap().effects[index].effect = + Effect::AmmoClip { + probability, + ratio, + cap, + used, + deployment, + }; + } + Effect::SkillAttack { + attack, + cap, + probability, + stacks, + } if event == skills::Event::SkillStart => { + if stacks >= cap || !self.equipment_chance(probability) { + continue; + } + self.equipment.units.get_mut(&unit).unwrap().effects[index].effect = + Effect::SkillAttack { + attack, + cap, + probability, + stacks: stacks + 1, + }; + self.equipment_stat( + w, + r, + unit, + format!("{}:stacks", instance.tag), + [("atkPct".into(), attack * (stacks + 1) as f64)].into(), + )?; + } + _ => (), + } + } + Ok(()) + } + pub(super) fn equipment_stat( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + unit: Id, + key: String, + mods: Numbers, + ) -> Result<(), String> { + let mut buff = Buff { + key: Some(key), + mods, + permanent: true, + ..Default::default() + }; + buff.runtime.persist = true; + r.add( + w, + self, + unit, + buffs::Spec { + buff, + mods_present: true, + allow_dead: true, + ..Default::default() + }, + )?; + Ok(()) + } + pub(super) fn equipment_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + attack: &attacks::Context, + ) -> Result<(), String> { + let unit = attack.attacker; + for (index, instance) in self.equipment.effects(unit) { + if self.equipment.units[&unit] + .hammers + .as_ref() + .is_some_and(|hammers| hammers.order == index) + { + self.hammer_attack(w, r, attack)?; + } + match instance.effect { + Effect::GunKnight { + probability, + scale, + combo, + } => { + if !attack + .targets + .iter() + .any(|&id| w.unit(id).is_ok_and(|u| u.side == health::Side::Enemy)) + || !self.equipment_member(unit, "lateranoShip") + || !self.equipment_chance(probability) + { + continue; + } + let combat = self.tac_def(unit)?.combat; + let profile = if w.unit(unit)?.operator.active_skill { + combat.skill_profile.unwrap_or(combat.profile) + } else { + combat.profile + } + .selection; + let targets = self.equipment_targets(w, unit, profile)?; + if let Some(target) = self.rng.pick(&targets).copied() { + let scale = if self.equipment_partner(unit, &instance) { + combo + } else { + scale + }; + self.equipment_damage( + w, + r, + unit, + target, + scale, + DamageType::Physical, + "gunknight", + true, + )?; + } + } + Effect::Accelerator { speed, cap } => { + let mut buff = Buff { + key: Some(format!("{}:stacks", instance.tag)), + mods: [("aspd".into(), speed)].into(), + permanent: true, + ..Default::default() + }; + buff.runtime.persist = true; + buff.runtime.refresh = buffs::Refresh::Stack; + buff.runtime.max_stacks = cap; + r.add( + w, + self, + unit, + buffs::Spec { + buff, + mods_present: true, + allow_dead: true, + ..Default::default() + }, + )?; + } + Effect::Silence(duration) => { + for &target in &attack.targets { + if w.unit(target)?.side == health::Side::Enemy + && w.unit(target)?.stats.alive + { + self.apply_status( + w, + r, + target, + "silence", + super::super::status::Options { + duration, + source: Some(unit), + ..Default::default() + }, + )?; + } + } + } + Effect::Grenade { window, duration } => { + if w.time - w.unit(unit)?.deployment.deployed_at <= window + 1e-9 { + for &target in &attack.targets { + if w.unit(target)?.side == health::Side::Enemy + && w.unit(target)?.stats.alive + { + self.apply_status( + w, + r, + target, + "stun", + super::super::status::Options { + duration, + source: Some(unit), + ..Default::default() + }, + )?; + } + } + } + } + Effect::AttackHeal(ratio) => { + for &target in &attack.targets { + if w.unit(target)?.side == health::Side::Enemy + && w.unit(target)?.stats.alive + { + let max_hp = w + .unit_mut(unit)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp"); + self.support_heal( + w, + r, + Some(unit), + unit, + max_hp * ratio, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + } + } + _ => (), + } + } + Ok(()) + } + pub(super) fn equipment_retype( + &self, + w: &mut World, + q: &mut hit::Request, + ) -> Result<(), String> { + let Some(source) = q.hit.source else { + return Ok(()); + }; + if !matches!(q.hit.damage_type, DamageType::Physical | DamageType::Arts) + || !(self.core_weakness(w, source, q.hit.target) + || self + .equipment + .effects(source) + .iter() + .any(|(_, instance)| matches!(instance.effect, Effect::Weakness))) + { + return Ok(()); + } + let ss = w + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .clone(); + let ts = w + .unit_mut(q.hit.target)? + .stats + .stats() + .map_err(str::to_string)? + .clone(); + let penetration = super::super::damage::Penetration { + def_flat: q.damage.penetration.def_flat + ss.n("defIgnoreFlat"), + def_pct: q.damage.penetration.def_pct + ss.n("defIgnorePct"), + res_flat: q.damage.penetration.res_flat + ss.n("resIgnoreFlat"), + res_pct: q.damage.penetration.res_pct + ss.n("resIgnorePct"), + }; + let physical = super::super::damage::mitigate( + q.damage.amount, + DamageType::Physical, + &ts, + penetration, + 0., + ); + let arts = + super::super::damage::mitigate(q.damage.amount, DamageType::Arts, &ts, penetration, 0.); + if arts > physical + 1e-9 { + q.hit.damage_type = DamageType::Arts; + } else if physical > arts + 1e-9 { + q.hit.damage_type = DamageType::Physical; + } + Ok(()) + } + pub(super) fn equipment_deadlines( + &self, + w: &World, + ) -> Vec<(f64, Id, super::super::equipment::Timer)> { + use super::super::equipment::Timer; + let mut due = Vec::new(); + for (&unit, loadout) in &self.equipment.units { + for (index, instance) in loadout.effects.iter().enumerate() { + if let Effect::SideAura { next, .. } + | Effect::Tears { next, .. } + | Effect::Chivalry { next, .. } + | Effect::Crest { next, .. } = instance.effect + { + if next <= w.time + 1e-9 { + due.push((next, unit, Timer::Effect(index))); + } + } + if let Some(hammers) = &loadout.hammers { + if hammers.order == index && hammers.next <= w.time + 1e-9 { + due.push((hammers.next, unit, Timer::Hammers)); + } + } + } + } + due + } + pub(super) fn equipment_periodic( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + unit: Id, + timer: super::super::equipment::Timer, + ) -> Result<(), String> { + let index = match timer { + super::super::equipment::Timer::Effect(index) => index, + super::super::equipment::Timer::Hammers => { + self.equipment + .units + .get_mut(&unit) + .unwrap() + .hammers + .as_mut() + .unwrap() + .next += 0.5; + return self.hammer_refresh(w, r, unit); + } + }; + let instance = self.equipment.units[&unit].effects[index].clone(); + if matches!( + instance.effect, + Effect::Crest { .. } | Effect::Chivalry { .. } + ) { + return self.equipment_special_periodic(w, r, unit, index, &instance); + } + + if let Effect::Tears { + interval, + next, + scale, + combo, + } = instance.effect + { + self.equipment.units.get_mut(&unit).unwrap().effects[index].effect = Effect::Tears { + interval, + next: next + interval, + scale, + combo, + }; + if Self::tac_up(w, unit) && self.equipment_member(unit, "kjeragShip") { + let scale = if self.equipment_partner(unit, &instance) { + combo + } else { + scale + }; + let targets = self.equipment_targets( + w, + unit, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )?; + for target in targets { + let stats = w.unit_mut(target)?.stats.stats().map_err(str::to_string)?; + if stats.flags.contains("cold") || stats.flags.contains("freeze") { + self.equipment_damage( + w, + r, + unit, + target, + scale, + DamageType::Arts, + "tears", + false, + )?; + } + } + } + } + if let Effect::SideAura { speed, next } = instance.effect { + self.equipment.units.get_mut(&unit).unwrap().effects[index].effect = Effect::SideAura { + speed, + next: next + 0.5, + }; + if !Self::tac_up(w, unit) { + return Ok(()); + } + let direction = self.roster.as_ref().unwrap().entry(unit)?.direction; + let tile = w.unit(unit)?.deployment.tile; + let owner = w.unit(unit)?.owner; + for side in [[1, 0], [-1, 0]] { + let delta = direction.rotate(side); + let at = [tile[0] + delta[0], tile[1] + delta[1]]; + for other in self.roster.as_ref().unwrap().ids().to_vec() { + let a = w.unit(other)?; + if a.owner != owner || !Self::tac_up(w, other) || a.deployment.tile != at { + continue; + } + let mut buff = Buff { + key: Some(format!("{}:side", instance.tag)), + mods: [("aspd".into(), speed)].into(), + ..Default::default() + }; + buff.runtime.duration = 0.6; + r.add( + w, + self, + other, + buffs::Spec { + buff, + mods_present: true, + ..Default::default() + }, + )?; + } + } + } + Ok(()) + } + pub(super) fn equipment_hit( + &mut self, + w: &mut World, + q: &mut hit::Request, + ) -> Result<(), String> { + if q.hit.damage_type == DamageType::Elemental { + return Ok(()); + } + if let Some(unit) = q.hit.source { + for (_, instance) in self.equipment.effects(unit) { + match instance.effect { + Effect::Sniper { radius, scale } + if w.unit(q.hit.target)?.side == health::Side::Enemy => + { + let a = w.unit(unit)?.position; + let b = w.unit(q.hit.target)?.position; + if hypot(b[0] - a[0], b[1] - a[1]) >= radius - 1e-6 { + q.damage.mul *= scale; + } + } + Effect::Flag { + scale, + window, + interval, + decay, + } => { + let t = w.time - w.unit(unit)?.deployment.deployed_at; + let m = if t > window + 1e-9 { + if decay < 0. { + (scale + decay * ((t - window) / interval - 1e-9).ceil()).max(1.) + } else { + 1. + } + } else { + scale + }; + if m != 1. { + q.damage.mul *= m; + } + } + _ => (), + } + } + } + let target = w.unit(q.hit.target)?; + if !target.blocking.is_empty() + && q.hit + .source + .is_some_and(|source| source != q.hit.target && !target.blocking.contains(&source)) + { + for (_, instance) in self.equipment.effects(q.hit.target) { + if let Effect::RiotShield(scale) = instance.effect { + q.damage.mul *= scale; + } + } + } + Ok(()) + } + pub(super) fn equipment_landed( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + event: &health::Event, + q: &hit::Request, + ) -> Result<(), String> { + let target = event.target; + if !q.tags.iter().any(|tag| tag == "item") + && self.equipment_member(target, "egirShip") + && w.unit(target)?.stats.alive + { + if let Some(source) = event.source.filter(|&source| { + w.unit(source) + .is_ok_and(|unit| unit.side == health::Side::Enemy && unit.stats.alive) + }) { + for (index, instance) in self.equipment.effects(target) { + if let Effect::Trench { + cooldown, + scale, + ready, + } = instance.effect + { + if w.time < ready { + continue; + } + self.equipment.units.get_mut(&target).unwrap().effects[index].effect = + Effect::Trench { + cooldown, + scale, + ready: w.time + cooldown, + }; + let hits = if self.equipment_partner(target, &instance) { + 2 + } else { + 1 + }; + for _ in 0..hits { + if w.unit(source)?.stats.alive { + self.equipment_damage( + w, + r, + target, + source, + scale, + DamageType::Arts, + "trench", + true, + )?; + } + } + } + } + } + } + self.equipment_crest_landed(w, r, event, q)?; + if event.amount <= 0. || q.hit.hp_loss { + return Ok(()); + } + for (index, instance) in self.equipment.effects(target) { + if let Effect::Camouflage { + duration, + used: false, + } = instance.effect + { + if !w.unit(target)?.stats.alive { + continue; + } + self.equipment.units.get_mut(&target).unwrap().effects[index].effect = + Effect::Camouflage { + duration, + used: true, + }; + self.apply_status( + w, + r, + target, + "stealth", + super::super::status::Options { + duration, + source: Some(target), + ..Default::default() + }, + )?; + } + } + if q.hit.damage_type == DamageType::Elemental + || w.unit(target)?.side != health::Side::Enemy + || !w.unit(target)?.stats.alive + || w.unit(target)?.stats.hp <= 0. + { + return Ok(()); + } + if let Some(source) = event.source { + for (index, instance) in self.equipment.effects(source) { + if self.equipment.units[&source] + .hammers + .as_ref() + .is_some_and(|hammers| hammers.order == index) + { + self.hammer_landed(w, r, event, q)?; + } + if let Effect::DamageStatus { + key, + probability, + duration, + } = instance.effect + { + if self.equipment_chance(probability) { + self.apply_status( + w, + r, + target, + key, + super::super::status::Options { + duration, + value: (key == "palsy").then_some(1.), + source: Some(source), + ..Default::default() + }, + )?; + } + } + } + } + Ok(()) + } + pub(super) fn equipment_before_status( + &self, + w: &mut World, + c: &mut super::super::status::Context, + ) -> Result<(), String> { + if !matches!( + c.key.as_str(), + "stun" | "freeze" | "sleep" | "levitate" | "palsy" + ) { + return Ok(()); + } + for (_, instance) in self.equipment.effects(c.target) { + if let Effect::StatusImmunity(threshold) = instance.effect { + let stats = &mut w.unit_mut(c.target)?.stats; + let max = stats.stats().map_err(str::to_string)?.n("maxHp"); + if stats.hp / max > threshold { + c.cancelled = true; + } + } + } + Ok(()) + } + pub(super) fn equipment_heal( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + e: &health::Event, + options: health::HealOptions, + ) -> Result<(), String> { + if e.amount <= 0. || options.regen || options.self_heal || !w.unit(e.target)?.stats.alive { + return Ok(()); + } + let Some(source) = e.source else { + return Ok(()); + }; + for (_, instance) in self.equipment.effects(source) { + if let Effect::HealShield { probability, cap } = instance.effect { + let have = w + .unit(e.target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("item:shield_drone")) + .map_or(0, |b| b.runtime.shield_hits); + if have >= cap || !self.equipment_chance(probability) { + continue; + } + let mut buff = Buff { + key: Some("item:shield_drone".into()), + permanent: true, + ..Default::default() + }; + buff.runtime.shield_hits = have + 1; + buff.runtime.visible = true; + r.add( + w, + self, + e.target, + buffs::Spec { + buff, + ..Default::default() + }, + )?; + } + } + Ok(()) + } + pub(super) fn equipment_pegasus_heal( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + if !w.unit(c.unit)?.deployed { + return Ok(()); + } + let buff = r.get(w, c.unit, c.buff)?; + let ratio = buff.runtime.tick_payload; + let key = buff.key.as_deref().unwrap_or(""); + let instance = self + .equipment + .effects(c.unit) + .into_iter() + .find(|(_, instance)| { + matches!(instance.effect, Effect::PegasusHeal) + && key.strip_suffix(":set") == Some(instance.tag.as_ref()) + }); + if let Some((_, instance)) = instance { + if self.equipment_partner(c.unit, &instance) { + let amount = Self::tac_stat(w, c.unit, "maxHp")? * ratio; + self.support_heal( + w, + r, + Some(c.unit), + c.unit, + amount, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + } + Ok(()) + } + pub(super) fn equipment_before_apply( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + parent: &hit::Request, + ) -> Result<(), String> { + let Some(source) = parent.hit.source else { + return Ok(()); + }; + let target = parent.hit.target; + if parent.attack_type == hit::AttackType::Addition + || w.unit(target)?.side != health::Side::Enemy + || !w.unit(target)?.stats.alive + || w.unit(target)?.stats.hp <= 0. + { + return Ok(()); + } + for (_, instance) in self.equipment.effects(source) { + if let Effect::PegasusDamage(scale) = instance.effect { + if !self.equipment_partner(source, &instance) { + continue; + } + let mut q = hit::Request::new( + health::Hit { + source: None, + credit: Some(source), + target, + damage_type: DamageType::True, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount: parent.damage.amount * scale, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.attack_type = hit::AttackType::Addition; + q.calculation = hit::Calculation::Precomputed; + q.tags = vec!["item".into(), "item:pegasus".into()]; + self.enemy_damage(w, r, &mut q)?; + } + } + Ok(()) + } + pub(super) fn equipment_drain( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + if !w.unit(c.unit)?.deployed { + return Ok(()); + } + let amount = r.get(w, c.unit, c.buff)?.runtime.tick_payload; + let mut q = hit::Request::new( + health::Hit { + source: None, + credit: Some(c.unit), + target: c.unit, + damage_type: DamageType::True, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + penetration: Default::default(), + resolved: false, + }, + ); + q.dodge_mode = super::super::injury::DodgeMode::Ignore; + q.attack_type = hit::AttackType::Buff; + q.tags = vec!["dot".into(), "periodic".into()]; + self.enemy_damage(w, r, &mut q)?; + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/equipment_special.rs b/crates/engine/src/battle/runtime/equipment_special.rs new file mode 100644 index 0000000..201b00f --- /dev/null +++ b/crates/engine/src/battle/runtime/equipment_special.rs @@ -0,0 +1,321 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Equipment that owns death, skill-window or stealth-growth state. +use super::*; +use crate::battle::{ + damage::DamageType, + equipment::{Effect, Instance}, + skills, targeting, +}; + +impl Host { + pub(super) fn chivalry_skill( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + unit: Id, + index: usize, + instance: &Instance, + event: skills::Event, + context: &skills::Context, + skill: &skills::Runtime, + ) -> Result<(), String> { + let Effect::Chivalry { + duration, + attack, + speed, + movement, + next, + mut until, + mut combo, + mut doomed, + } = instance.effect + else { + return Ok(()); + }; + let key = format!("{}:combo", instance.tag); + if event == skills::Event::SkillStart && self.equipment_member(unit, "kazimierzShip") { + until = w.time + duration; + if self.equipment_partner(unit, instance) && skill.bank.kind.timed() { + combo = true; + doomed = false; + self.component_buff( + w, + r, + unit, + &key, + [("atkPct".into(), attack)].into(), + f64::INFINITY, + unit, + )?; + } + } + if event == skills::Event::SkillEnd && combo { + combo = false; + r.remove(w, self, unit, &key)?; + if doomed && context.reason != "death" { + doomed = false; + self.tac_timer( + w, + unit, + w.time, + 0., + 1, + tactics::Task::Callback(|c| c.retreat()), + )?; + } + } + self.equipment.units.get_mut(&unit).unwrap().effects[index].effect = Effect::Chivalry { + duration, + attack, + speed, + movement, + next, + until, + combo, + doomed, + }; + Ok(()) + } + pub(super) fn chivalry_fatal(&mut self, event: &mut health::Event) -> Result<(), String> { + if event.prevented { + return Ok(()); + } + let Some(loadout) = self.equipment.units.get_mut(&event.target) else { + return Ok(()); + }; + for instance in &mut loadout.effects { + if let Effect::Chivalry { + combo: true, + doomed, + .. + } = &mut instance.effect + { + *doomed = true; + event.prevented = true; + break; + } + } + Ok(()) + } + pub(super) fn equipment_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + unit: Id, + ) -> Result<(), String> { + for (index, instance) in self.equipment.effects(unit) { + if let Effect::Crest { + per, + cap, + scale, + next, + deployment, + .. + } = instance.effect + { + self.equipment.units.get_mut(&unit).unwrap().effects[index].effect = + Effect::Crest { + per, + cap, + scale, + next, + deployment, + bonus: 0., + }; + } + if let Effect::Cocoon { cap, used } = instance.effect { + let a = w.unit(unit)?; + if used >= cap + || a.stats.alive + || a.removed + || a.deployment.remove_reason.as_deref() != Some("killed") + { + continue; + } + let revived = kits::dispatch::Context { + host: self, + world: w, + buffs: r, + unit, + } + .redeploy_free(unit)?; + if revived { + self.equipment.units.get_mut(&unit).unwrap().effects[index].effect = + Effect::Cocoon { + cap, + used: used + 1, + }; + } + } + } + Ok(()) + } + pub(super) fn equipment_special_periodic( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + unit: Id, + index: usize, + instance: &Instance, + ) -> Result<(), String> { + match instance.effect { + Effect::Chivalry { + duration, + attack, + speed, + movement, + next, + until, + combo, + doomed, + } => { + self.equipment.units.get_mut(&unit).unwrap().effects[index].effect = + Effect::Chivalry { + duration, + attack, + speed, + movement, + next: next + 0.5, + until, + combo, + doomed, + }; + if w.time >= until || !Self::tac_up(w, unit) { + return Ok(()); + } + for enemy in self.equipment_targets( + w, + unit, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? { + let aspd = w.unit(enemy)?.stats.base_number("aspd"); + self.component_buff( + w, + r, + enemy, + &format!("{}:aura", instance.tag), + [ + ("aspd".into(), -(1. - speed) * aspd), + ("moveMul".into(), movement), + ] + .into(), + 0.6, + unit, + )?; + } + } + Effect::Crest { + per, + cap, + scale, + next, + mut bonus, + mut deployment, + } => { + let current = w.unit(unit)?.deployment.deploy_seq; + if current != deployment { + bonus = 0.; + deployment = current; + } + if Self::tac_up(w, unit) + && self.equipment_member(unit, "siracusaShip") + && Self::tac_stat_flag(w, unit, "stealth")? + && bonus < cap + { + bonus = (bonus + per * 0.25).min(cap); + self.component_buff( + w, + r, + unit, + &format!("{}:stealth", instance.tag), + [("atkPct".into(), bonus)].into(), + f64::INFINITY, + unit, + )?; + } + self.equipment.units.get_mut(&unit).unwrap().effects[index].effect = + Effect::Crest { + per, + cap, + scale, + next: next + 0.25, + bonus, + deployment, + }; + } + _ => (), + } + Ok(()) + } + fn tac_stat_flag(w: &mut World, unit: Id, flag: &str) -> Result { + Ok(w.unit_mut(unit)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains(flag)) + } + pub(super) fn equipment_crest_landed( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + event: &health::Event, + q: &hit::Request, + ) -> Result<(), String> { + let Some(source) = event.source else { + return Ok(()); + }; + if event.amount <= 0. + || q.tags.iter().any(|tag| tag == "item") + || !Self::tac_up(w, source) + || Self::tac_stat_flag(w, source, "stealth")? + { + return Ok(()); + } + for (index, instance) in self.equipment.effects(source) { + if let Effect::Crest { + per, + cap, + scale, + next, + bonus, + deployment, + } = instance.effect + { + if bonus <= 0. || deployment != w.unit(source)?.deployment.deploy_seq { + continue; + } + self.equipment.units.get_mut(&source).unwrap().effects[index].effect = + Effect::Crest { + per, + cap, + scale, + next, + bonus: 0., + deployment, + }; + let target = w.unit(event.target)?; + if self.equipment_partner(source, &instance) + && target.stats.alive + && target.side == health::Side::Enemy + { + self.equipment_damage( + w, + r, + source, + event.target, + scale, + DamageType::True, + "crest", + false, + )?; + } + r.remove(w, self, source, &format!("{}:stealth", instance.tag))?; + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/event_window.rs b/crates/engine/src/battle/runtime/event_window.rs new file mode 100644 index 0000000..d608087 --- /dev/null +++ b/crates/engine/src/battle/runtime/event_window.rs @@ -0,0 +1,351 @@ +//! Quiet-state projection. Event frames execute through the normal clock phases. +use super::*; +use crate::battle::{body, cadence, grid::N, search::AttackProfile, skills, stats::Stat}; + +pub(super) fn quiet_enemy(kit: &content::Kit) -> bool { + use content::Ability; + matches!( + kit, + content::Kit::Plain + | content::Kit::Zone(_) + | content::Kit::Reaction( + content::Reaction::ExposeDeath { .. } + | content::Reaction::HealDeath { .. } + | content::Reaction::Barrier { .. } + | content::Reaction::Double { .. } + | content::Reaction::FirstSplash { .. } + | content::Reaction::Fear(_) + | content::Reaction::Shell + ) + | content::Kit::Ability( + Ability::Unblockable + | Ability::Bleed { .. } + | Ability::Expose { .. } + | Ability::Tide { .. } + | Ability::Taunt(_) + | Ability::HitShield(_) + | Ability::MaxTargets(_) + | Ability::LowHp(_) + | Ability::Run(_) + | Ability::DefDecay { .. } + | Ability::FrozenPower(_) + | Ability::Stun { .. } + | Ability::Power { .. } + | Ability::Song { .. } + | Ability::DeathBoom { .. } + ) + ) +} + +struct QuietHooks { + profile: AttackProfile, + event: bool, +} +impl skills::Hooks for QuietHooks { + fn can_activate(&mut self, _: &skills::Runtime, _: &mut World) -> Result { + self.event = true; + Err("Quiet interval reached a skill event".into()) + } + fn event( + &mut self, + _: skills::Event, + _: &mut skills::Context, + _: &mut skills::Runtime, + _: &mut World, + ) -> Result<(), String> { + self.event = true; + Err("Quiet interval reached a skill event".into()) + } + fn condition( + &mut self, + _: skills::Condition, + _: &skills::Runtime, + _: &mut World, + ) -> Result { + Ok(false) + } + fn profile(&mut self, _: Id, _: &mut World) -> Result, String> { + Ok(Some(self.profile)) + } + fn has_sp_hook(&self) -> bool { + false + } +} + +struct Ally { + id: Id, + skill: skills::Runtime, + next_skill: skills::Runtime, + cadence: cadence::State, + next_cadence: cadence::State, + profile: AttackProfile, + base_profile: AttackProfile, + store: bool, +} +struct Timer { + unit: Id, + buff: buffs::BuffId, + left: f64, + accumulator: f64, + interval: f64, + periodic: bool, + next_left: f64, + next_accumulator: f64, +} +struct Regen { + unit: Id, + hp: f64, + max_hp: f64, + rate: f64, + accumulator: f64, + next_accumulator: f64, +} + +pub(super) struct Window { + allies: Vec, + timers: Vec, + regeneration: Vec, + deadline: f64, + trigger_range: [bool; N], +} +impl Window { + pub(super) fn prepare(h: &mut Host, w: &mut World) -> Result, String> { + use crate::battle::content::operators::Tactics; + let Some(deadline) = h.roster.as_ref().unwrap().quiet_deadline(w)? else { + return Ok(None); + }; + let time = w.time; + let mut out = Self { + allies: Vec::new(), + timers: Vec::new(), + regeneration: Vec::new(), + deadline: deadline.min(h.movement_bond_deadline()), + trigger_range: [false; N], + }; + let ids = h.roster.as_ref().unwrap().ids().to_vec(); + let mut injured_ally = false; + let mut healer = false; + for &id in &ids { + let roster = h.roster.as_ref().unwrap(); + let entry = roster.entry(id)?; + let def = Arc::clone(&entry.definition); + let skill = entry.skill()?.clone(); + if skill.pending + || skill.spec.trigger_allies + || matches!( + skill.spec.rule, + skills::Rule::Global | skills::Rule::AutoStop + ) + { + return Ok(None); + } + let u = w.unit_mut(id)?; + if !u.stats.alive + || !u.stats.cached_clean() + || !u.deployed + || u.hidden + || u.removed + || !u.blocking().is_empty() + || u.element_buildup.iter().any(|&n| n != 0.) + || !h.terrain.stationary_ground_clear(u) + { + return Ok(None); + } + let (flags_empty, max_hp) = { + let stats = u.stats.stats().map_err(str::to_string)?; + (stats.flags.is_empty(), stats.get(Stat::MaxHp)) + }; + injured_ally |= u.stats.hp < max_hp; + healer |= skill.spec.heal_skill + || def.combat.heal + || def.combat.skill_heal + || def.extra.support.auto_heal; + if !flags_empty { + return Ok(None); + } + if u.operator.support.quiet_until > time { + out.deadline = out.deadline.min(u.operator.support.quiet_until); + } + let store = match &def.extra.tactics { + Tactics::Indigo(kit) => u.operator.tactical.indigo()?.stored < kit.capacity, + _ => false, + }; + for grid in def.trigger_range.iter().chain(def.extra.skill_range.iter()) { + for key in crate::battle::targeting::absolute_range( + grid, + u.deployment.tile, + entry.direction, + 0, + ) { + out.trigger_range[key] = true; + } + } + let cadence = u.cadence.clone(); + let profile = crate::battle::ally::Host::effective_profile(h, id, Some(&skill), w)? + .unwrap_or(def.combat.profile); + out.allies.push(Ally { + id, + next_skill: skill.clone(), + skill, + next_cadence: cadence.clone(), + cadence, + profile, + base_profile: def.combat.profile, + store, + }); + } + if healer && injured_ally || !h.choices_clock_quiet(w)? { + return Ok(None); + } + for id in ids + .into_iter() + .chain(h.spawns.as_ref().unwrap().live().iter().copied()) + { + let u = w.unit_mut(id)?; + let (max_hp, rate) = { + let stats = u.stats.stats().map_err(str::to_string)?; + (stats.get(Stat::MaxHp), stats.n("hpRegen")) + }; + let hp = u.stats.hp; + if u.pool.is_none() && hp < max_hp && rate > 0. { + out.regeneration.push(Regen { + unit: id, + hp, + max_hp, + rate, + accumulator: u.regen_acc, + next_accumulator: u.regen_acc, + }); + } + for buff in u.stats.buffs() { + let b = &buff.runtime; + if b.id() == 0 { + return Ok(None); + } + let periodic = b.on_tick.is_some() + || b.resist_decay + || b.element_burst.is_some_and(|b| b.periodic()); + if periodic || b.time_left != f64::INFINITY { + out.timers.push(Timer { + unit: id, + buff: b.id(), + left: b.time_left, + accumulator: b.accumulator, + interval: b.interval, + periodic, + next_left: b.time_left, + next_accumulator: b.accumulator, + }); + } + } + } + Ok(Some(out)) + } + + pub(super) fn clear_at(&self, position: [f64; 2]) -> bool { + let mut clear = true; + body::enemy_collider_keys(position, |key| clear &= !self.trigger_range[key]); + clear + } + + pub(super) fn project(&mut self, w: &mut World, time: f64) -> Result { + if time + 1e-9 >= self.deadline { + return Ok(false); + } + for regen in &mut self.regeneration { + regen.next_accumulator = regen.accumulator + regen.rate * DT; + if regen.next_accumulator >= 1. || regen.hp + regen.next_accumulator >= regen.max_hp { + return Ok(false); + } + } + for timer in &mut self.timers { + timer.next_left = timer.left; + timer.next_accumulator = timer.accumulator; + if timer.periodic { + if timer.interval <= 0. { + return Ok(false); + } + timer.next_accumulator += DT; + if timer.next_accumulator >= timer.interval - 1e-9 { + return Ok(false); + } + } + if timer.left != f64::INFINITY { + timer.next_left -= DT; + if timer.next_left <= 1e-9 { + return Ok(false); + } + } + } + let saved_time = w.time; + w.time = time; + let result = (|| { + for ally in &mut self.allies { + ally.next_skill.clone_from(&ally.skill); + let mut hooks = QuietHooks { + profile: ally.base_profile, + event: false, + }; + if let Err(error) = ally.next_skill.tick(w, &mut hooks, DT) { + if hooks.event { + return Ok(false); + } + return Err(error); + } + if ally.next_skill.bank.charges != ally.skill.bank.charges { + return Ok(false); + } + ally.next_cadence.clone_from(&ally.cadence); + ally.next_cadence.tick(DT, true); + if ally.next_cadence.cooldown <= 0. + && !ally.profile.no_attack + && (!ally.profile.only_while_skill || ally.next_skill.bank.active) + { + if ally.store { + return Ok(false); + } + ally.next_cadence.had_target = Some(false); + } + } + Ok(true) + })(); + w.time = saved_time; + result + } + + pub(super) fn accept(&mut self) { + for regen in &mut self.regeneration { + regen.accumulator = regen.next_accumulator; + } + for ally in &mut self.allies { + std::mem::swap(&mut ally.skill, &mut ally.next_skill); + std::mem::swap(&mut ally.cadence, &mut ally.next_cadence); + } + for timer in &mut self.timers { + timer.left = timer.next_left; + timer.accumulator = timer.next_accumulator; + } + } + + pub(super) fn commit(self, h: &mut Host, w: &mut World) -> Result<(), String> { + for regen in self.regeneration { + w.unit_mut(regen.unit)?.regen_acc = regen.accumulator; + } + for timer in self.timers { + h.buffs + .as_mut() + .unwrap() + .edit_timer(w, timer.unit, timer.buff, |b| { + b.runtime.time_left = timer.left; + b.runtime.accumulator = timer.accumulator; + })?; + } + for ally in self.allies { + let roster = h.roster.as_mut().unwrap(); + roster.take_skill(ally.id)?; + roster.restore_skill(ally.id, ally.skill)?; + w.unit_mut(ally.id)?.cadence = ally.cadence; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/growth.rs b/crates/engine/src/battle/runtime/growth.rs new file mode 100644 index 0000000..75d8602 --- /dev/null +++ b/crates/engine/src/battle/runtime/growth.rs @@ -0,0 +1,771 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Battle-local covenant growth; preparation receives only the ordered delta. +use super::*; +use crate::battle::{body, deploy::Kind, skills}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Default)] +pub(super) struct Growth { + pub live: BTreeMap, + pub enabled: bool, + pub follow_wind: bool, + gains: Vec<(String, f64)>, + traits: Vec, + pending: bool, + onstart: Vec, +} +#[derive(Clone)] +struct Trait { + unit: Id, + id: String, + key: String, + record: Arc, + count: u64, + used: BTreeMap, + whole: f64, + doll: bool, + steps: i64, +} +impl Trait { + fn n(&self, key: &str, fallback: f64) -> f64 { + self.record["bb"][key] + .as_f64() + .filter(|n| n.is_finite()) + .unwrap_or(fallback) + } + fn s(&self, key: &str) -> &str { + self.record["bbStr"][key].as_str().unwrap_or("") + } +} +fn ids(value: &str) -> Vec { + value + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect() +} +impl Field { + pub(crate) fn follow_cold_wind_layers(&mut self) { + self.core.host.growth.follow_wind = true; + } + pub fn layer_gains(&self) -> Vec<(String, f64)> { + self.core.host.growth.gains.clone() + } + pub fn bond_layers(&self) -> BTreeMap { + self.core + .host + .growth + .live + .iter() + .map(|(id, b)| (id.clone(), b.layers)) + .collect() + } +} +impl Host { + pub(super) fn movement_growth_quiet(&self) -> bool { + !self.growth.pending && self.growth.onstart.is_empty() + } + fn growth_ops(&self, w: &World) -> Vec { + self.roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .filter(|&id| { + w.unit(id) + .is_ok_and(|u| u.deployment.kind == Kind::Operator) + }) + .collect() + } + fn growth_front(&self, w: &World, id: Id) -> Result<[i32; 2], String> { + let pos = w.unit(id)?.deployment.tile; + let vec = self.roster.as_ref().unwrap().entry(id)?.direction.vector(); + Ok([pos[0] + vec[0], pos[1] + vec[1]]) + } + pub(super) fn growth_install(&mut self, w: &World) -> Result<(), String> { + if self.growth.live.is_empty() { + return Ok(()); + } + let mut owned = BTreeSet::new(); + let mut records = BTreeMap::>::new(); + let mut list = Vec::new(); + let ops = self.growth_ops(w); + let mut add = |unit: Id, id: &str| -> Result<(), String> { + if !owned.insert((unit, id.to_owned())) { + return Ok(()); + } + let Some(record) = self.data.table("garrisons").and_then(|t| t.get(id)) else { + return Err("Unknown growth garrison".into()); + }; + if record["eventType"] != "IN_BATTLE" { + return Ok(()); + } + if list.len() >= w.unit_capacity() * 32 { + return Err("Growth trait capacity exceeded".into()); + } + list.push(Trait { + unit, + id: id.into(), + key: record["effectKey"].as_str().unwrap_or("").into(), + record: records + .entry(id.into()) + .or_insert_with(|| Arc::new(record.clone())) + .clone(), + count: 0, + used: BTreeMap::new(), + whole: 0., + doll: false, + steps: -1, + }); + Ok(()) + }; + for &unit in &ops { + let def = &self.roster.as_ref().unwrap().entry(unit)?.definition; + for id in self.data.table("chess").unwrap()[&def.key]["garrisonIds"] + .as_array() + .into_iter() + .flatten() + { + add(unit, id.as_str().ok_or("Invalid growth garrison")?)?; + } + } + drop(add); + // Grants are one pass over native traits; granted grants do not recurse. + for t in list.clone() { + if t.key != "ADD_BOND" && t.record["battleRuneKey"] != "give_garrion_to_front" { + continue; + } + let id = if t.s("give_garrison_id").is_empty() { + t.s("give_garrion_id") + } else { + t.s("give_garrison_id") + }; + let Some(record) = self.data.table("garrisons").and_then(|m| m.get(id)) else { + continue; + }; + if record["eventType"] != "IN_BATTLE" { + continue; + } + let desc = t.record["desc"].as_str().unwrap_or(""); + let home = w.unit(t.unit)?.deployment.tile; + let front = self.growth_front(w, t.unit)?; + let right = ops + .iter() + .copied() + .filter(|&u| w.unit(u).unwrap().deployment.tile[0] == home[0]) + .max_by_key(|&u| w.unit(u).unwrap().deployment.tile[1]); + for &unit in &ops { + let at = w.unit(unit)?.deployment.tile; + let selected = if desc.contains("所有") { + true + } else if desc.contains("同一行最右边") { + Some(unit) == right + } else { + at == front || desc.contains("自身和身前") && unit == t.unit + }; + if !selected + || !t.s("check_bond_id").is_empty() + && !self.equipment_member(unit, t.s("check_bond_id")) + || !owned.insert((unit, id.into())) + { + continue; + } + if list.len() >= w.unit_capacity() * 32 { + return Err("Growth trait capacity exceeded".into()); + } + list.push(Trait { + unit, + id: id.into(), + key: record["effectKey"].as_str().unwrap_or("").into(), + record: records + .entry(id.into()) + .or_insert_with(|| Arc::new(record.clone())) + .clone(), + count: 0, + used: BTreeMap::new(), + whole: 0., + doll: false, + steps: -1, + }); + } + } + self.growth.traits = list; + Ok(()) + } + pub(super) fn growth_bond_gain( + &mut self, + w: &World, + source: Id, + id: &str, + mut amount: f64, + ) -> Result<(), String> { + if !self.growth.enabled { + return Ok(()); + } + let u = w.unit(source)?; + if Self::tac_up(w, source) || !u.stats.alive && u.deployment.death_at == w.time { + for extra in &self.growth.traits { + if extra.key == "act1autochess_gar_event_addition_cnt" + && extra.unit != source + && Self::tac_up(w, extra.unit) + && matches!(extra.s("range_id"), "" | "1-1") + && self.growth_front(w, extra.unit)? == u.deployment.tile + { + amount += extra.n("extra_cnt", 0.); + } + } + } + let Some(b) = self.growth.live.get_mut(id).filter(|b| b.tier > 0) else { + return Ok(()); + }; + let amount = amount.floor().max(0.).min((999. - b.layers).max(0.)); + if amount <= 0. { + return Ok(()); + } + b.layers += amount; + if let Some((_, n)) = self.growth.gains.iter_mut().find(|(k, _)| k == id) { + *n += amount; + } else { + self.growth.gains.push((id.into(), amount)); + } + self.growth.pending = true; + self.growth_map(); + Ok(()) + } + fn growth_fire(&mut self, w: &World, index: usize) -> Result<(), String> { + if !self.growth.enabled { + return Ok(()); + } + let t = self.growth.traits[index].clone(); + let tile = w.unit(t.unit)?.deployment.tile; + let ops = self.growth_ops(w); + let row = ops + .iter() + .filter(|&&u| Self::tac_up(w, u) && w.unit(u).unwrap().deployment.tile[0] == tile[0]) + .count(); + let col = ops + .iter() + .filter(|&&u| Self::tac_up(w, u) && w.unit(u).unwrap().deployment.tile[1] == tile[1]) + .count(); + if t.s("conditionkey") == "character_same_row" && (row as f64) < t.n("check_count", 0.) + || t.s("conditionkey") == "character_same_col" && (col as f64) < t.n("check_count", 0.) + { + return Ok(()); + } + let active = |id: &String| self.growth.live.get(id).is_some_and(|b| b.tier > 0); + let bonds = match t.s("bond_type") { + "bond_self" => self + .equipment + .units + .get(&t.unit) + .map(|l| l.bonds.clone()) + .unwrap_or_default(), + "bond_actived_maxstack" => { + let mut best = None; + let mut top = -1.; + for (id, _) in self.data.table("bonds").unwrap().as_object().unwrap() { + if active(id) && self.growth.live[id].layers > top { + top = self.growth.live[id].layers; + best = Some(id.clone()); + } + } + best.into_iter().collect() + } + _ => ids(t.s("bond_id")), + }; + let n = match t.s("bond_add_type") { + "by_charcount_samerow" => { + row as f64 * t.n("bond_add_count_multi", t.n("bond_add_count", 1.)) + } + "by_charlevel" => { + let def = &self.roster.as_ref().unwrap().entry(t.unit)?.definition; + self.data.table("chess").unwrap()[&def.key]["tier"] + .as_f64() + .unwrap_or(1.) + .floor() + .max(1.) + * t.n("bond_add_count", 1.) + } + _ => t.n("bond_add_count", 0.), + } + .floor() + .max(0.); + let cap = t.n("max_add_count_per_battle", 0.); + let cap = if cap > 0. { cap.floor() } else { f64::INFINITY }; + let whole = t.s("bond_type") == "bond_actived_maxstack" && cap.is_finite(); + let mut whole_added = false; + for id in bonds { + let Some(b) = self.growth.live.get(&id) else { + continue; + }; + if b.tier == 0 || b.layers >= 999. { + continue; + } + let used = if whole { + t.whole + } else { + t.used.get(&id).copied().unwrap_or(0.) + }; + let base = n.min((cap - used).max(0.)); + if base <= 0. { + continue; + } + let mut amount = base; + for extra in &self.growth.traits { + if extra.key != "act1autochess_gar_event_addition_cnt" + || !Self::tac_up(w, extra.unit) + || extra.unit == t.unit + || !matches!(extra.s("range_id"), "" | "1-1") + { + continue; + } + if self.growth_front(w, extra.unit)? == tile { + amount += extra.n("extra_cnt", 0.); + } + } + let amount = amount.floor().min((999. - b.layers).max(0.)); + if amount <= 0. { + continue; + } + self.growth.live.get_mut(&id).unwrap().layers += amount; + if let Some((_, n)) = self.growth.gains.iter_mut().find(|(k, _)| k == &id) { + *n += amount; + } else { + self.growth.gains.push((id.clone(), amount)); + } + if whole { + whole_added = true; + } else { + *self.growth.traits[index].used.entry(id).or_default() += base; + } + self.growth.pending = true; + } + self.growth_map(); + if whole_added { + self.growth.traits[index].whole += n.min((cap - t.whole).max(0.)); + } + Ok(()) + } + pub(super) fn growth_skill( + &mut self, + w: &World, + unit: Id, + event: skills::Event, + ) -> Result<(), String> { + if event == skills::Event::Deploy + && self + .growth + .traits + .iter() + .any(|t| t.unit == unit && t.key == "act2autochess_gar_eff_attrByBond_add_onstart") + { + if self.growth.onstart.len() >= w.unit_capacity() * 32 { + return Err("Growth deployment capacity exceeded".into()); + } + self.growth.onstart.push(unit); + } + for i in 0..self.growth.traits.len() { + let t = &self.growth.traits[i]; + let fire = match event { + skills::Event::Deploy => { + t.unit == unit && t.key == "act2autochess_gar_event_onstart" + } + skills::Event::SkillStart => { + t.unit == unit && t.key == "act1autochess_gar_event_useskill" + } + skills::Event::AmmoUsed if t.key == "act1autochess_gar_event_consume_ammo" => { + let scope = match t.s("range_id") { + "1-1" => { + Self::tac_up(w, t.unit) + && Self::tac_up(w, unit) + && unit != t.unit + && self.growth_front(w, t.unit)? == w.unit(unit)?.deployment.tile + } + "x-5" => { + unit == t.unit + || Self::tac_up(w, t.unit) + && Self::tac_up(w, unit) + && w.unit(unit)?.deployment.kind == Kind::Operator + && { + let a = w.unit(unit)?.deployment.tile; + let b = w.unit(t.unit)?.deployment.tile; + (a[0] - b[0]).abs() + (a[1] - b[1]).abs() == 1 + } + } + _ => unit == t.unit, + }; + if scope { + let period = t.n("consume_count", 1.).max(1.); + self.growth.traits[i].count += 1; + (self.growth.traits[i].count as f64) % period == 0. + } else { + false + } + } + _ => false, + }; + if fire { + self.growth_fire(w, i)?; + } + } + Ok(()) + } + pub(super) fn growth_death( + &mut self, + w: &World, + unit: Id, + credit: Option, + ) -> Result<(), String> { + for deaths in [false, true] { + for i in 0..self.growth.traits.len() { + let t = &self.growth.traits[i]; + let fire = + if deaths && t.unit == unit && t.key == "act1autochess_gar_event_selfdead" { + true + } else if !deaths + && Some(t.unit) == credit + && t.key == "act1autochess_gar_event_selfkillenemy" + && (w.unit(unit)?.side == health::Side::Enemy + || t.record["desc"].as_str().unwrap_or("").contains("我方干员") + && w.unit(unit)?.deployment.kind == Kind::Operator) + { + let period = t.n("check_cnt", 1.).max(1.); + self.growth.traits[i].count += 1; + (self.growth.traits[i].count as f64) % period == 0. + } else { + false + }; + if fire { + self.growth_fire(w, i)?; + } + } + } + Ok(()) + } + pub(super) fn growth_status( + &mut self, + w: &mut World, + c: &super::super::status::Context, + ) -> Result<(), String> { + if !c.entered { + return Ok(()); + } + for i in 0..self.growth.traits.len() { + let t = &self.growth.traits[i]; + let freeze = t.key == "act1autochess_gar_event_enemy_abflag_inrange" + && c.key == "freeze" + && w.unit(c.target)?.side == health::Side::Enemy; + let control = t.key == "act2autochess_gar_event_allyenemy_sleepstun_inrange" + && matches!(c.key.as_str(), "sleep" | "stun") + && (w.unit(c.target)?.side == health::Side::Enemy + || w.unit(c.target)?.deployment.kind == Kind::Operator); + if !(freeze || control) || !Self::tac_up(w, t.unit) { + continue; + } + let keys = self + .roster + .as_ref() + .ok_or("Missing growth range context")? + .range(w, t.unit)?; + if !body::in_range(w.unit(c.target)?, &keys) { + continue; + } + if freeze && self.rng.next_f64() >= t.n("prob", 1.) { + continue; + } + self.growth_fire(w, i)?; + } + Ok(()) + } + pub(super) fn growth_refresh( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + if !self.growth.pending { + return Ok(()); + } + self.growth.pending = false; + self.bonds_install(w, r)?; + self.bonds_aura(w, r)?; + self.growth_readers(w, r)?; + Ok(()) + } + fn growth_map(&mut self) { + self.devices.config.top_layers = self + .growth + .live + .values() + .map(|b| b.layers) + .fold(0., f64::max); + if !self.growth.follow_wind { + return; + } + if let (Some(b), Some(wind)) = ( + self.growth.live.get("kjeragShip"), + self.devices.config.cold_wind.as_mut(), + ) { + if b.tier >= 2 { + if let Some(bb) = self + .data + .table("bonds") + .and_then(|t| t.get("kjeragShip")) + .and_then(|v| v["buffs"].as_array()) + .and_then(|a| a.iter().find(|b| b["key"] == "env_gbuff_new")) + .map(|v| &v["bb"]) + { + wind.duration = bb["bond_eff_kjerag[storm].base_time"] + .as_f64() + .unwrap_or(0.) + + bb["bond_eff_kjerag[storm].time_per_stack"] + .as_f64() + .unwrap_or(0.) + * b.layers; + } + } + } + } +} + +impl Host { + fn growth_steps(&self, t: &Trait) -> i64 { + let sum: f64 = ids(t.s("bond_id")) + .iter() + .filter_map(|id| self.growth.live.get(id)) + .filter(|b| b.tier > 0) + .map(|b| b.layers) + .sum(); + (sum / t.n("divide_num", 1.).max(1.)).floor() as i64 + } + pub(super) fn growth_begin_readers( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + if !self.growth.live.is_empty() { + // Definition construction installs static traits early; the original + // battle domain orders covenant passives before garrison passives. + for id in self.growth_ops(w) { + let stats = &mut w.unit_mut(id)?.stats; + stats + .buffs_mut() + .sort_by_key(|b| b.key.as_deref().is_some_and(|k| k.starts_with("gar:"))); + stats.mark_dirty(); + } + } + self.growth_readers(w, r) + } + pub(super) fn growth_readers( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let order: Vec<_> = [ + "act1autochess_gar_eff_attrByBond", + "act1autochess_gar_eff_respawnTimeByBond", + "act2autochess_gar_eff_attrByBond_add_onstart", + "act2autochess_gar_eff_ab_damageScaleByBond", + ] + .into_iter() + .flat_map(|key| { + self.growth + .traits + .iter() + .enumerate() + .filter_map(move |(i, t)| (t.key == key).then_some(i)) + }) + .collect(); + for i in order { + let t = self.growth.traits[i].clone(); + if !matches!( + t.key.as_str(), + "act1autochess_gar_eff_attrByBond" + | "act1autochess_gar_eff_respawnTimeByBond" + | "act2autochess_gar_eff_attrByBond_add_onstart" + | "act2autochess_gar_eff_ab_damageScaleByBond" + ) { + continue; + } + let k = self.growth_steps(&t); + if k == t.steps { + continue; + } + self.growth.traits[i].steps = k; + let key = format!("gar:{}", t.id); + let mut mods = crate::battle::stats::Numbers::new(); + match t.key.as_str() { + "act1autochess_gar_eff_attrByBond" => { + for (param, name) in [ + ("atk", "atkPct"), + ("max_hp", "hpPct"), + ("def", "defPct"), + ("attack_speed", "aspd"), + ("hp_recovery_per_sec", "hpRegen"), + ("sp_recovery_per_sec", "spRecoveryFlat"), + ] { + let value = t.n(param, 0.) * k as f64; + if value != 0. { + mods.insert(name.into(), value); + } + } + } + "act1autochess_gar_eff_respawnTimeByBond" => { + mods.insert( + "redeployMul".into(), + (1. + t.n("respawn_time", 0.) * k as f64).max(0.), + ); + } + "act2autochess_gar_eff_attrByBond_add_onstart" => { + if let Some(left) = w + .unit(t.unit)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some(&key)) + .map(|b| b.runtime.time_left) + { + self.growth_timed_reader(w, r, &t, left)?; + } + continue; + } + _ => continue, + } + if k > 0 { + self.equipment_stat(w, r, t.unit, key, mods)?; + } else { + r.remove(w, self, t.unit, &key)?; + } + } + Ok(()) + } + fn growth_timed_reader( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + t: &Trait, + duration: f64, + ) -> Result<(), String> { + let k = self.growth_steps(t); + let key = format!("gar:{}", t.id); + if k <= 0 || duration <= 0. { + r.remove(w, self, t.unit, &key)?; + return Ok(()); + } + let mut buff = crate::battle::stats::Buff { + key: Some(key), + mods: [ + ("atkFlat".into(), t.n("atk", 0.) * k as f64), + ("hpFlat".into(), t.n("max_hp", 0.) * k as f64), + ] + .into(), + ..Default::default() + }; + buff.runtime.duration = duration; + r.add( + w, + self, + t.unit, + buffs::Spec { + buff, + mods_present: true, + ..Default::default() + }, + )?; + Ok(()) + } + pub(super) fn growth_flush_onstart( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let pending = std::mem::take(&mut self.growth.onstart); + if !pending.is_empty() { + self.tactical_sync_injury(w, r)?; + } + for unit in pending { + self.growth_onstart(w, r, unit)?; + } + Ok(()) + } + fn growth_onstart( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + unit: Id, + ) -> Result<(), String> { + for t in self.growth.traits.clone() { + if t.unit == unit && t.key == "act2autochess_gar_eff_attrByBond_add_onstart" { + self.growth_timed_reader(w, r, &t, t.n("duration", 0.))?; + } + } + Ok(()) + } + pub(super) fn growth_doll_swap(&mut self, w: &World, unit: Id) -> Result<(), String> { + for i in 0..self.growth.traits.len() { + let t = &self.growth.traits[i]; + if t.unit == unit + && t.key == "act2autochess_gar_event_onstart" + && matches!(t.id.as_str(), "garrison_108_a" | "garrison_108_b") + { + self.growth_fire(w, i)?; + } + } + Ok(()) + } + pub(super) fn growth_dolls(&mut self, w: &World) -> Result<(), String> { + for i in 0..self.growth.traits.len() { + let t = &self.growth.traits[i]; + if t.key != "act1autochess_gar_event_selfdead" + || !t.record["desc"].as_str().unwrap_or("").contains("替身") + { + continue; + } + let doll = w + .unit(t.unit)? + .operator + .tactical + .dollkeeper() + .map(|s| s.doll) + .unwrap_or(false); + if doll != t.doll { + let up = Self::tac_up(w, t.unit); + self.growth.traits[i].doll = doll; + if up { + self.growth_fire(w, i)?; + } + } + } + Ok(()) + } + pub(super) fn growth_hit(&self, w: &World, q: &mut hit::Request) -> Result<(), String> { + if !w + .unit(q.hit.target) + .is_ok_and(|u| u.side == health::Side::Enemy) + || q.hit.damage_type == super::super::damage::DamageType::Elemental + { + return Ok(()); + } + for t in &self.growth.traits { + if Some(t.unit) != q.hit.source + || t.key != "act2autochess_gar_eff_ab_damageScaleByBond" + || t.steps <= 0 + { + continue; + } + let buffs = w.unit(q.hit.target)?.stats.buffs(); + let has = |key: &str| { + buffs + .iter() + .any(|b| b.key.as_deref() == Some(key) || b.flags.contains(key)) + }; + if t.n("check_ab_flag", 0.) != 0. && has("bind") + || t.n("check_sluggish", 0.) != 0. && has("sluggish") + { + q.damage.mul *= 1. + t.n("damage_scale_per_stack", 0.) * t.steps as f64; + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/hammers.rs b/crates/engine/src/battle/runtime/hammers.rs new file mode 100644 index 0000000..440c057 --- /dev/null +++ b/crates/engine/src/battle/runtime/hammers.rs @@ -0,0 +1,231 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Shared hammer grants, field borrowing and per-deployment undying windows. +use super::*; +use crate::battle::{ + equipment::{FieldHammers, Hammer}, + stats::Buff, +}; + +impl Host { + fn field_hammers(&mut self, w: &World, owner: Id) -> Result<[bool; 4], String> { + if let Some(cache) = self.equipment.fields.get(&owner) { + if w.time - cache.at < 0.5 - 1e-9 { + return Ok(cache.present); + } + } + let mut present = [false; 4]; + for (&unit, loadout) in &self.equipment.units { + let a = w.unit(unit)?; + if a.owner != Some(owner) || !Self::tac_up(w, unit) { + continue; + } + if let Some(hammers) = &loadout.hammers { + for (index, &count) in hammers.own.iter().enumerate() { + present[index] |= count > 0; + } + } + } + self.equipment.fields.insert( + owner, + FieldHammers { + at: w.time, + present, + }, + ); + Ok(present) + } + fn hammer_effect( + &mut self, + w: &World, + unit: Id, + index: usize, + ) -> Result, String> { + let Some(loadout) = self.equipment.units.get(&unit) else { + return Ok(None); + }; + let Some(hammers) = &loadout.hammers else { + return Ok(None); + }; + let count = hammers.own[index]; + let params = hammers.params[index].or(hammers.steam.map(|steam| steam.hammer(index))); + let steam = + hammers.steam.is_some() && loadout.bonds.iter().any(|bond| bond == "victoriaShip"); + let borrowed = if steam { + self.field_hammers(w, w.unit(unit)?.owner.ok_or("Hammer carrier has no owner")?)?[index] + } else { + false + }; + let count = count + u32::from(borrowed); + Ok(params.filter(|_| count > 0).map(|params| (params, count))) + } + pub(super) fn hammer_refresh( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + unit: Id, + ) -> Result<(), String> { + let speed = match self.hammer_effect(w, unit, 2)? { + Some((Hammer::Speed(speed), count)) => speed * count as f64, + _ => 0., + }; + let hammers = self + .equipment + .units + .get_mut(&unit) + .unwrap() + .hammers + .as_mut() + .unwrap(); + if speed == hammers.speed { + return Ok(()); + } + hammers.speed = speed; + let key = format!("item:hammer#{unit}:aspd"); + if speed == 0. { + r.remove(w, self, unit, &key)?; + } else { + let mut buff = Buff { + key: Some(key), + mods: [("aspd".into(), speed)].into(), + permanent: true, + ..Default::default() + }; + buff.runtime.persist = true; + r.add( + w, + self, + unit, + buffs::Spec { + buff, + mods_present: true, + allow_dead: true, + ..Default::default() + }, + )?; + } + Ok(()) + } + pub(super) fn holds_undying(&self, w: &mut World, unit: Id) -> Result { + let u = w.unit(unit)?; + let held = self + .equipment + .units + .get(&unit) + .and_then(|loadout| loadout.hammers.as_ref()) + .is_some_and(|hammers| { + hammers.window_at == Some(u.deployment.deploy_seq) && w.time < hammers.until + }); + Ok(held || Self::tac_has(w, unit, "undying")) + } + pub(super) fn hammer_fatal(&mut self, w: &World, e: &mut health::Event) -> Result<(), String> { + if e.prevented { + return Ok(()); + } + let unit = e.target; + let Some(hammers) = self + .equipment + .units + .get(&unit) + .and_then(|loadout| loadout.hammers.as_ref()) + else { + return Ok(()); + }; + let deployment = w.unit(unit)?.deployment.deploy_seq; + if hammers.lock_at == Some(deployment) { + return Ok(()); + } + if let Some((Hammer::Undying(duration), count)) = self.hammer_effect(w, unit, 1)? { + let hammers = self + .equipment + .units + .get_mut(&unit) + .unwrap() + .hammers + .as_mut() + .unwrap(); + hammers.lock_at = Some(deployment); + hammers.window_at = Some(deployment); + hammers.until = w.time + duration * count as f64; + e.prevented = true; + } + Ok(()) + } + pub(super) fn hammer_attack( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + attack: &super::super::attacks::Context, + ) -> Result<(), String> { + let unit = attack.attacker; + if !self + .roster + .as_ref() + .unwrap() + .entry(unit)? + .definition + .melee_operator + { + return Ok(()); + } + if let Some(( + Hammer::Tremble { + probability, + duration, + }, + count, + )) = self.hammer_effect(w, unit, 3)? + { + let probability = (probability * count as f64).min(1.); + for &target in &attack.targets { + if w.unit(target)?.side == health::Side::Enemy + && w.unit(target)?.stats.alive + && self.equipment_chance(probability) + { + self.apply_status( + w, + r, + target, + "tremble", + super::super::status::Options { + duration, + source: Some(unit), + ..Default::default() + }, + )?; + } + } + } + Ok(()) + } + pub(super) fn hammer_landed( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + e: &health::Event, + q: &hit::Request, + ) -> Result<(), String> { + if q.hit.damage_type != super::super::damage::DamageType::Arts + || q.tags.iter().any(|tag| tag == "item") + || e.amount <= 0. + || w.unit(e.target)?.side != health::Side::Enemy + || w.unit(e.target)?.stats.hp <= 0. + { + return Ok(()); + } + let Some(source) = e.source else { + return Ok(()); + }; + if let Some((Hammer::Burn(scale), count)) = self.hammer_effect(w, source, 0)? { + let mut request = super::super::element::Request::new( + Some(source), + Some(source), + e.target, + super::super::element::Element::Burn, + e.amount * scale * count as f64, + ); + request.damage.tags = vec!["item".into(), "item:hammer_burn".into()]; + super::super::element::apply(w, self, r, &mut request)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits.rs b/crates/engine/src/battle/runtime/kits.rs new file mode 100644 index 0000000..dd36e1b --- /dev/null +++ b/crates/engine/src/battle/runtime/kits.rs @@ -0,0 +1,1163 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Shared execution of typed operator components through canonical engine APIs. +use super::super::{ally, body, projectiles}; +use super::super::{ + attacks::{self, Chain, Splash}, + content::operators::*, + damage::{Damage, DamageType}, + direction::Direction, + displacement, hit, injury, + operators::Definition, + search, skills, + stats::{Buff, Numbers}, + targeting, +}; +use super::tactics::{ + Arrow, ArrowKind, Task, Timer, ABNORMAL, DRIZZLE, GAP_FINISH, OBSERVE, RAIN, SHIELD_LOST, + WITHER, +}; +use super::*; +use crate::deterministic::math::powi; +use std::collections::{BTreeMap, BTreeSet}; +pub(crate) mod agoat2; +pub(crate) mod archet; +pub(crate) mod blaze2; +pub(crate) mod blemsh; +pub(crate) mod blkkgt; +pub(crate) mod caper; +pub(crate) mod cello; +pub(crate) mod cetsyr; +pub(crate) mod clemnt; +pub(crate) mod demkni; +pub(crate) mod dispatch; +pub(crate) mod excu2; +pub(crate) mod funnel; +pub(crate) mod ghost2; +pub(crate) mod halo2; +pub(crate) mod horn; +pub(crate) mod indigo; +pub(crate) mod ines; +pub(crate) mod kjera; +pub(crate) mod lumen; +pub(crate) mod malist; +pub(crate) mod mlynar; +pub(crate) mod nymph; +pub(crate) mod papyrs; +pub(crate) mod pasngr; +pub(crate) mod pepe; +pub(crate) mod philae; +pub(crate) mod prepared_summon; +pub(crate) mod qiubai; +pub(crate) mod rmixer; +pub(crate) mod rockr; +pub(crate) mod silent; +pub(crate) mod snhunt; +pub(crate) mod sntlla; +pub(crate) mod texas2; +pub(crate) mod tinman; +pub(crate) mod tippi; +pub(crate) mod titi; +pub(crate) mod vulpis; + +pub(crate) mod reed2; +pub(crate) mod rosmon; + +pub(crate) mod sbell2; + +pub(crate) mod skadi2; + +pub(crate) mod svash2; + +pub(crate) mod angel2; + +pub(crate) mod thorn2; + +pub(crate) mod yu; + +pub(crate) mod dollkeeper; +pub(crate) mod dusk; + +pub(crate) mod kazema; + +pub(crate) mod lemuen; + +pub(crate) mod nearl2; + +pub(crate) mod siege2; + +pub(crate) mod ulpia; + +pub(crate) mod swire2; + +pub(crate) mod whitw2; + +pub(crate) mod etlchi; + +pub(crate) mod wolf; + +pub(crate) mod vigil; + +pub(crate) mod manifold; + +pub(crate) mod mlyss; + +impl Host { + pub(super) fn component_buff( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + key: &str, + mods: Numbers, + duration: f64, + source: Id, + ) -> Result<(), String> { + let mut b = Buff { + key: Some(key.into()), + mods, + ..Default::default() + }; + b.runtime.duration = duration; + b.runtime.source = Some(source); + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + Ok(()) + } + fn component_damage( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + amount: f64, + kind: DamageType, + tag: &str, + ignore_dodge: bool, + ) -> Result { + let mut q = hit::Request::new( + health::Hit { + source: Some(source), + credit: Some(source), + target, + damage_type: kind, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.is_skill = true; + q.is_splash = tag == "sonic"; + q.tags.push(tag.into()); + if ignore_dodge { + q.dodge_mode = injury::DodgeMode::Ignore; + q.ignore_select = true; + } + self.resolve_hit(w, r, &mut q) + } + pub(super) fn component_debuff( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + d: Debuff, + ) -> Result<(), String> { + if !w.unit(target)?.stats.alive || d.value == 0. { + return Ok(()); + } + if d.strongest { + let value = -d.value; + super::super::valued::apply( + w, + self, + r, + target, + super::super::valued::Request { + key: d.key, + kind: super::super::valued::Kind::Custom(|v| { + [("resMul".into(), (1. - v).max(0.))].into() + }), + plain: true, + duration: d.duration, + value, + source: Some(source), + stack_as: None, + }, + )?; + } else { + let mut b = Buff { + key: Some(d.key.into()), + mods: [(d.stat.into(), d.value)].into(), + ..Default::default() + }; + b.runtime.duration = d.duration; + b.runtime.refresh = buffs::Refresh::Extend; + b.runtime.source = Some(source); + r.add( + w, + self, + target, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } + Ok(()) + } + fn component_status( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + effect: OnHitStatus, + ) -> Result<(), String> { + if w.unit(target)?.stats.alive && effect.duration > 0. { + self.apply_status( + w, + r, + target, + effect.key, + super::super::status::Options { + duration: effect.duration, + source: Some(source), + ..Default::default() + }, + )?; + } + Ok(()) + } + fn component_pull( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + dir: Direction, + p: PullHit, + ) -> Result<(), String> { + let grid = self.grid.take().ok_or("Missing pull grid")?; + let result = displacement::pull_to_front( + w, + &grid, + &mut allies::Blocking { + host: self, + buffs: r, + }, + target, + source, + dir, + p.force, + ); + self.grid = Some(grid); + let moved = result?; + if moved > 0. && p.travel_damage > 0. { + self.component_damage( + w, + r, + source, + target, + p.travel_damage * moved / p.distance, + DamageType::Arts, + "drag", + true, + )?; + } + Ok(()) + } + pub(super) fn component_skill( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + dir: Direction, + def: &Definition, + event: skills::Event, + c: &skills::Context, + s: &mut skills::Runtime, + ) -> Result<(), String> { + let id = s.unit(); + let fx = &def.extra.effects; + if event == skills::Event::Start { + w.unit_mut(id)?.operator.active_skill = true; + w.unit_mut(id)?.operator.hits = 0; + if s.bank.kind == super::super::sp::Kind::Ammo { + let mut extra = 0.; + if let Some(a) = &fx.ammo { + if w.time - w.unit(id)?.deployment.deployed_at + 1e-9 >= a.delay { + extra += a.own; + } + } + let grants = w.unit(id)?.operator.ammo_grants.clone(); + for (source, (seq, n)) in grants { + let valid = w.unit(source).is_ok_and(|u| { + u.stats.alive && u.deployed && u.deployment.deploy_seq == seq + }); + if valid { + extra += n; + } else { + w.unit_mut(id)?.operator.ammo_grants.remove(&source); + } + } + s.add_ammo(extra); + } + if let Some(steps) = &fx.growing_atk { + let uses = w.unit(id)?.operator.uses; + let amount = steps + .get(uses.min(steps.len().saturating_sub(1))) + .copied() + .unwrap_or(0.); + w.unit_mut(id)?.operator.uses = uses.saturating_add(1).min(steps.len()); + self.component_buff( + w, + r, + id, + "skill:pinecn_atk", + [("atkPct".into(), amount)].into(), + f64::INFINITY, + id, + )?; + } + if let Some(counter) = &fx.skill_counter { + let mut b = Buff { + key: Some(counter.key.into()), + ..Default::default() + }; + b.runtime.injury.observe = Some(SKILL_COUNTER); + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + if fx.resist > 0. { + self.apply_status( + w, + r, + id, + "resist", + super::super::status::Options { + duration: s.time_left, + value: Some(fx.resist), + source: Some(id), + ..Default::default() + }, + )?; + } + if let Some((grid, effect)) = &fx.start_status { + let keys = targeting::absolute_range(grid, w.unit(id)?.deployment.tile, dir, 0); + let targets = search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: false, + ground_only: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + // Every eligible target receives the status. This can run during + // an enemy attack, while the movement phase owns the route grid. + for target in targets { + self.component_status(w, r, id, target, *effect)?; + } + } + if let Some(burst) = &fx.burst { + let keys = + targeting::absolute_range(&burst.grid, w.unit(id)?.deployment.tile, dir, 0); + let mut targets = search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: !burst.ground, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + targeting::sort_enemies(w, self, id, &mut targets, def.combat.profile.priority)?; + targets.truncate(burst.count); + for target in targets { + if let Some(pull) = burst.pull { + self.component_pull(w, r, id, target, dir, pull)?; + } + if !w.unit(target)?.stats.alive { + continue; + } + let scale = if targeting::flying(w, target)? { + burst.fly_scale + } else { + 1. + }; + let amount = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * burst.scale + * scale; + for _ in 0..def.extra.advanced_burst_hits.max(1) { + if !w.unit(target)?.stats.alive { + break; + } + self.component_damage( + w, + r, + id, + target, + amount, + burst.damage, + "burst", + false, + )?; + } + if let Some(effect) = burst.status { + self.component_status(w, r, id, target, effect)?; + } + if let Some(debuff) = burst.debuff { + self.component_debuff(w, r, id, target, debuff)?; + } + } + } + } + if event == skills::Event::End { + w.unit_mut(id)?.operator.active_skill = false; + if let Some(counter) = &fx.skill_counter { + r.remove(w, self, id, counter.key)?; + } + if fx.growing_atk.is_some() { + r.remove(w, self, id, "skill:pinecn_atk")?; + } + if c.reason != "death" && w.unit(id)?.stats.alive && fx.end_heal > 0. { + let amount = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp") + * fx.end_heal; + health::heal( + w, + self, + Some(id), + id, + amount, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + } + Ok(()) + } + pub(super) fn component_scheduled(&mut self, w: &mut World) -> Result<(), String> { + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + let mut r = self + .buffs + .take() + .ok_or("Missing component scheduler buffs")?; + let result = (|| { + for &id in &ids { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + let fx = &def.extra.effects; + let up = w.unit(id)?.stats.alive && w.unit(id)?.deployed; + if w.unit(id)?.operator.blessing_pending { + w.unit_mut(id)?.operator.blessing_pending = false; + if up { + let candidates: Vec<_> = ids + .iter() + .copied() + .filter(|&other| { + other != id + && targeting::aura_selectable(w, other).unwrap_or(false) + && !w.unit(other).unwrap().stats.buffs().iter().any(|b| { + b.key.as_deref() == Some("talent:angel_bless_ally") + }) + }) + .collect(); + if let Some(&other) = self.rng.pick(&candidates) { + let mut b = persistent( + "talent:angel_bless_ally", + fx.random_bless.as_ref().unwrap().clone(), + ); + b.runtime.source = Some(id); + r.add( + w, + self, + other, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } + } + } + if let Some(a) = fx.ammo.as_ref().filter(|a| a.ally > 0.) { + if up + && !w.unit(id)?.operator.ammo_granted + && w.time + 1e-9 >= w.unit(id)?.deployment.deployed_at + a.delay + { + w.unit_mut(id)?.operator.ammo_granted = true; + let mut candidates = vec![]; + for &other in &ids { + let entry = self.roster.as_ref().unwrap().entry(other)?; + if other != id + && w.unit(other)?.stats.alive + && entry.definition.laterano + && entry.skill()?.bank.kind == super::super::sp::Kind::Ammo + { + candidates.push(other); + } + } + if let Some(&other) = self.rng.pick(&candidates) { + let seq = w.unit(id)?.deployment.deploy_seq; + w.unit_mut(other)? + .operator + .ammo_grants + .insert(id, (seq, a.ally)); + } + } + } + if fx.aura.is_none() && fx.enemy_atk.is_none() { + continue; + } + if w.time + 1e-9 < w.unit(id)?.operator.next_pulse { + continue; + } + let interval = if fx.enemy_atk.is_some() { 0.1 } else { 0.2 }; + w.unit_mut(id)?.operator.next_pulse += interval; + if !up { + continue; + } + let keys = search::Host::range(self, id, w)?; + if let Some(aura) = &fx.aura { + let dir = self.roster.as_ref().unwrap().entry(id)?.direction; + let range = aura.grid.as_ref().map(|g| { + targeting::absolute_range(g, w.unit(id).unwrap().deployment.tile, dir, 0) + }); + for &other in &ids { + let entry = self.roster.as_ref().unwrap().entry(other)?; + // Friendly auras still reach stealthed and sleeping allies. + let selectable = if aura.grid.is_none() { + Self::tac_up(w, other) + } else { + targeting::friendly_selectable(w, id, other)? + }; + let eligible = selectable + && aura + .profession + .is_none_or(|p| entry.definition.profession == p) + && range.as_ref().is_none_or(|g| { + super::super::body::in_range(w.unit(other).unwrap(), g) + }); + if eligible { + self.component_buff( + w, + &mut r, + other, + aura.key, + aura.mods.clone(), + if aura.grid.is_some() { + 0.4 + 0.05 + } else { + 0.25 + }, + id, + )?; + } else if aura.grid.is_some() + && w.unit(other)?.stats.buffs().iter().any(|b| { + b.key.as_deref() == Some(aura.key) && b.runtime.source == Some(id) + }) + { + r.remove(w, self, other, aura.key)?; + } + } + } + if let Some(bonus) = &fx.enemy_atk { + let n = search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )? + .len() as f64; + let value = n.min(bonus.cap) * bonus.value; + if value > 0. + && !w.unit(id)?.stats.buffs().iter().any(|b| { + b.key.as_deref() == Some("lionhd:t1") + && b.mods.get("atkPct") == Some(&value) + }) + { + self.component_buff( + w, + &mut r, + id, + "lionhd:t1", + [("atkPct".into(), value)].into(), + f64::INFINITY, + id, + )?; + } + if value <= 0. { + r.remove(w, self, id, "lionhd:t1")?; + } + } + } + Ok(()) + })(); + self.buffs = Some(r); + result + } + pub(super) fn refresh_component_conditions(&mut self, w: &mut World) -> Result<(), String> { + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + let mut r = self.buffs.take().ok_or("Missing component tick buffs")?; + let result = (|| { + for id in ids { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + if let Some(condition) = &def.extra.effects.condition { + let u = w.unit(id)?; + let up = u.stats.alive && u.deployed; + let want = up + && match condition.when { + Predicate::Unblocked => u.blocking().is_empty(), + Predicate::AllyInRange => { + let keys = search::Host::range(self, id, w)?; + let allies = self.roster.as_ref().unwrap().ids(); + allies.iter().any(|&other| { + other != id + && targeting::aura_selectable(w, other).unwrap_or(false) + && super::super::body::in_range( + w.unit(other).unwrap(), + &keys, + ) + }) + } + }; + let has = w + .unit(id)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(condition.key)); + if want && !has { + self.component_buff( + w, + &mut r, + id, + condition.key, + condition.mods.clone(), + f64::INFINITY, + id, + )?; + } + if !want && has { + r.remove(w, self, id, condition.key)?; + } + } + } + Ok(()) + })(); + self.buffs = Some(r); + result + } + pub(super) fn component_observe( + c: &mut settlement::Context<'_, Self>, + token: u64, + ) -> Result<(), String> { + if !matches!(token, INJURY_OBSERVER | SKILL_COUNTER) { + return Err("Unknown operator observer callback".into()); + } + let target = c.request.hit.target; + let Some(source) = c.request.hit.source else { + return Ok(()); + }; + if !c.world.unit(target)?.stats.alive + || c.world.unit(source)?.side != health::Side::Enemy + || c.request.hit.hp_loss + || c.request.hit.damage_type == DamageType::Elemental + { + return Ok(()); + } + let def = Arc::clone(&c.host.roster.as_ref().unwrap().entry(target)?.definition); + let fx = &def.extra.effects; + let counter = if token == SKILL_COUNTER { + fx.skill_counter + } else { + fx.observer.as_ref().and_then(|o| o.counter) + }; + // Talent observers are installed before the skill counter, preserving injury snapshot order. + if let Some(d) = fx + .observer + .as_ref() + .and_then(|o| o.debuff) + .filter(|_| token != SKILL_COUNTER) + { + if targeting::can_target_enemy( + c.world, + c.host, + Some(target), + source, + def.combat.profile.selection, + )? { + c.host + .component_debuff(c.world, c.runtime, target, source, d)?; + } + } + if let Some(counter) = counter { + if c.world.unit(source)?.stats.alive { + let amount = c + .world + .unit_mut(target)? + .stats + .stats() + .map_err(str::to_string)? + .n(counter.stat) + * counter.scale; + let mut q = hit::Request::new( + health::Hit { + source: Some(target), + credit: Some(target), + target: source, + damage_type: DamageType::Physical, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.dodge_mode = injury::DodgeMode::Ignore; + q.ignore_select = true; + q.is_skill = true; + q.tags.push("counter".into()); + c.resolve(&mut q)?; + } + } + Ok(()) + } +} +impl Host { + pub(super) fn component_phase( + &mut self, + phase: hit::Phase, + q: &mut hit::Request, + _: &mut buffs::Runtime, + w: &mut World, + rng: &mut Rng, + ) -> Result<(), String> { + if phase != hit::Phase::Hit { + return Ok(()); + } + if w.unit(q.hit.target)?.side == health::Side::Ally + && w.unit(q.hit.target)?.deployment.kind != crate::battle::deploy::Kind::Device + { + let def = Arc::clone( + &self + .roster + .as_ref() + .unwrap() + .entry(q.hit.target)? + .definition, + ); + if q.hit.source.is_some_and(|s| { + w.unit(s) + .is_ok_and(|u| u.blocked_by() == Some(q.hit.target)) + }) { + q.damage.mul *= def.extra.effects.blocked_taken; + } + } + let Some(source) = q + .hit + .source + .filter(|&s| w.unit(s).is_ok_and(|u| u.has_operator_kit())) + else { + return Ok(()); + }; + if !q.is_attack || w.unit(q.hit.target)?.side != health::Side::Enemy { + return Ok(()); + } + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(source)?.definition); + let fx = &def.extra.effects; + if targeting::flying(w, q.hit.target)? { + q.damage.mul *= fx.fly_scale; + } + if let Some(d) = &fx.distance { + let a = w.unit(source)?.position; + let b = w.unit(q.hit.target)?.position; + let distance = crate::deterministic::math::hypot(a[0] - b[0], a[1] - b[1]); + let fraction = if d.maximum > d.minimum { + ((distance - d.minimum) / (d.maximum - d.minimum)).clamp(0., 1.) + } else { + 1. + }; + q.damage.amount *= 1. + d.attack_scale * fraction; + q.damage.mul *= 1. + d.damage_scale * fraction; + } + if let Some(boost) = &fx.attack_boost { + if w.unit(source)?.operator.boosted { + q.damage.mul *= boost.scale; + } + } + if let Some(crit) = &fx.crit { + if rng.chance(crit.chance) { + q.damage.amount *= crit.attack_scale; + q.damage.mul *= crit.damage_scale; + q.tags.push("kroos2Crit".into()); + } + } + if q.is_skill { + q.damage.penetration.def_flat += fx.skill_def_ignore; + } + Ok(()) + } + pub(super) fn component_landed( + &mut self, + e: &health::Event, + q: &hit::Request, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + let Some(source) = q + .hit + .source + .filter(|&s| w.unit(s).is_ok_and(|u| u.has_operator_kit())) + else { + return Ok(()); + }; + if !q.is_attack || w.unit(e.target)?.side != health::Side::Enemy { + return Ok(()); + } + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(source)?.definition); + let fx = &def.extra.effects; + if fx.hit_upgrade.is_some() && w.unit(source)?.operator.active_skill { + let u = w.unit_mut(source)?; + u.operator.hits = u.operator.hits.saturating_add(1); + } + if q.tags.iter().any(|t| t == "kroos2Crit") { + if let Some(crit) = &fx.crit { + self.component_status( + w, + r, + source, + e.target, + OnHitStatus { + key: "stun", + duration: crit.stun, + chance: None, + }, + )?; + } + } + Ok(()) + } + pub(super) fn component_fatal( + &mut self, + e: &mut health::Event, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + if e.stage != health::Stage::Fatal + || e.prevented + || w.unit(e.target)?.side != health::Side::Ally + || w.unit(e.target)?.operator.revived + { + return Ok(()); + } + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(e.target)?.definition); + if let Some(revive) = &def.extra.effects.revive { + w.unit_mut(e.target)?.operator.revived = true; + e.prevented = true; + self.component_buff( + w, + r, + e.target, + "trait:skadi_tide", + [ + ("hpMul".into(), revive.hp_mul), + ("aspd".into(), revive.aspd), + ] + .into(), + f64::INFINITY, + e.target, + )?; + let u = w.unit_mut(e.target)?; + u.stats.hp = + (u.stats.stats().map_err(str::to_string)?.n("maxHp") * revive.hp_ratio).max(1.); + } + Ok(()) + } + pub(super) fn component_before( + &mut self, + c: &mut attacks::Context, + w: &mut World, + ) -> Result<(), String> { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(c.attacker)?.definition); + if let Some(boost) = &def.extra.effects.attack_boost { + let boosted = self.rng.chance(boost.chance); + w.unit_mut(c.attacker)?.operator.boosted = boosted; + if boosted { + let keys = search::Host::range(self, c.attacker, w)?; + let mut candidates = search::Host::enemies( + self, + c.attacker, + &keys, + def.combat.profile.selection, + w, + w.unit_capacity(), + )?; + candidates.retain(|t| !c.targets.contains(t)); + targeting::sort_enemies( + w, + self, + c.attacker, + &mut candidates, + def.combat.profile.priority, + )?; + if let Some(&other) = candidates.first() { + c.targets.push(other); + } + } + } + Ok(()) + } + pub(super) fn component_hit( + &mut self, + impact: attacks::Impact, + w: &mut World, + ) -> Result<(), String> { + if impact.kind != attacks::VictimKind::Main || !impact.is_skill { + return Ok(()); + } + let Some(target) = impact + .target + .filter(|&t| w.unit(t).is_ok_and(|u| u.stats.alive)) + else { + return Ok(()); + }; + let source = impact.attacker; + let entry = self.roster.as_ref().unwrap().entry(source)?; + let dir = entry.direction; + let def = Arc::clone(&entry.definition); + let fx = &def.extra.effects; + let mut r = self + .buffs + .take() + .ok_or("Missing operator hit buff context")?; + let result = (|| { + if let Some(d) = fx.skill_debuff { + self.component_debuff(w, &mut r, source, target, d)?; + } + if let Some(p) = fx.skill_pull { + if !def.extra.support.pull_unblocked || w.unit(target)?.blocked_by().is_none() { + self.component_pull(w, &mut r, source, target, dir, p)?; + } + } + if let Some(force) = fx.skill_push { + let forward = dir.vector().map(|n| n as f64); + let a = w.unit(source)?.position; + let b = w.unit(target)?.position; + let behind = (b[0] - a[0]) * forward[0] + (b[1] - a[1]) * forward[1] < 0.; + let options = displacement::Push { + from: Some(displacement::Origin::unit(w, source, dir)?), + direction: Some(forward), + effect: behind || def.extra.support.effect_push, + ..Default::default() + }; + let grid = self.grid.take().ok_or("Missing push grid")?; + let result = displacement::push( + w, + &grid, + &mut allies::Blocking { + host: self, + buffs: &mut r, + }, + target, + force, + options, + ); + self.grid = Some(grid); + result?; + } + Ok(()) + })(); + self.buffs = Some(r); + result + } + pub(super) fn component_attack( + &mut self, + c: &attacks::Context, + w: &mut World, + ) -> Result<(), String> { + let source = c.attacker; + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(source)?.definition); + w.unit_mut(source)?.operator.boosted = false; + let active = w.unit(source)?.operator.active_skill; + let Some(secondary) = def.extra.effects.secondary.as_ref().filter(|_| active) else { + return Ok(()); + }; + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + let mut r = self + .buffs + .take() + .ok_or("Missing secondary attack buff context")?; + let result = (|| { + match secondary { + Secondary::Sonic { radius, scale } => { + let keys = search::Host::range(self, source, w)?; + for id in ids { + if id == source + || !targeting::aura_selectable(w, id)? + || !super::super::body::in_range(w.unit(id)?, &keys) + { + continue; + } + let targets = attacks::Hooks::radius_targets( + self, + w.unit(id)?.position, + *radius, + false, + w, + w.unit_capacity(), + )?; + for target in targets { + if w.unit_mut(target)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("untargetable") + { + continue; + } + let amount = w + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * scale; + self.component_damage( + w, + &mut r, + source, + target, + amount, + DamageType::Arts, + "sonic", + false, + )?; + } + } + } + Secondary::NearbyBlocked { scale } => { + let home = w.unit(source)?.deployment.tile; + let mut seen = std::collections::BTreeSet::new(); + for id in ids { + let u = w.unit(id)?; + let tile = u.deployment.tile; + if !u.stats.alive + || !u.deployed + || (tile[0] - home[0]).abs() > 1 + || (tile[1] - home[1]).abs() > 1 + { + continue; + } + for target in u.blocking().to_vec() { + if !w.unit(target)?.stats.alive || !seen.insert(target) { + continue; + } + let amount = w + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * scale; + self.component_damage( + w, + &mut r, + source, + target, + amount, + DamageType::Arts, + "ayerBlade", + false, + )?; + } + } + } + } + Ok(()) + })(); + self.buffs = Some(r); + result + } +} + +pub(crate) fn kit_text_count( + text: &Value, + prefix: &str, + suffix: &str, + fallback: u32, + limit: u32, +) -> Result { + let text = text.as_str().unwrap_or(""); + let after = if prefix.is_empty() { + text + } else { + text.split_once(prefix).map_or("", |(_, after)| after) + }; + let before = after.split_once(suffix).map_or("", |(before, _)| before); + let digits: String = before + .chars() + .rev() + .take_while(|c| c.is_ascii_digit()) + .collect::() + .chars() + .rev() + .collect(); + let count = digits.parse::().unwrap_or(fallback); + if count == 0 || count > limit { + return Err("Kit text count exceeds supported payload capacity".into()); + } + Ok(count) +} + +pub(crate) mod yanyou; diff --git a/crates/engine/src/battle/runtime/kits/agoat2.rs b/crates/engine/src/battle/runtime/kits/agoat2.rs new file mode 100644 index 0000000..bd8f86c --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/agoat2.rs @@ -0,0 +1,343 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::element; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "wandermedic", + ranged: false, + can_hit_fly: false, + physical: false, + projectile: "orb", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_agoat2_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "GDGLOW_SKILL_2", + attack_override: true, + }, + Skill { + id: "skchr_agoat2_1", + kind: Kind::Toggle, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_agoat2_2", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_agoat2_1" => Mode::First, + "skchr_agoat2_2" => Mode::Second, + "skchr_agoat2_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + healing(s, 1.); + if let Some(h) = &mut s.combat.profile.heal { + h.element_heal = true; + } + if mode == Mode::First { + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + s.rule_override = Some(skills::Rule::SpFull); + skill_healing(s, 2., 1.); + } + if mode == Mode::Third { + s.extra.skill_range = Some( + (-(crate::battle::grid::ROWS as i32 - 1)..crate::battle::grid::ROWS as i32) + .flat_map(|r| (-(COLS as i32 - 1)..COLS as i32).map(move |c| [r, c])) + .collect(), + ); + let shots = kit_text_count(&raw["skill"]["desc"], "", "连发", 1, 5)?; + skill_healing(s, shots as f64, n(bb, "attack@heal_scale", 1.)); + if let Some(p) = &mut s.combat.skill_profile { + p.heal.as_mut().unwrap().element_heal = true; + } + } + s.extra.tactics = Tactics::Agoat2(Agoat2 { + mode: mode, + element_ratio: n(tb, "ep_heal_ratio", 0.5), + shots: kit_text_count(&raw["skill"]["desc"], "", "连发", 1, 5)? as usize, + aura_element: suffix_number(bb, "ep_heal_ratio", 0.), + veil: suffix_number(bb, "atk_scale", 5.), + veil_duration: n(bb, "duration", 12.), + mist: n(t, "heal_scale", 0.), + mist_duration: n(t, "duration", 6.), + mist_cap: n(t, "max_stack_cnt", 3.).max(1.) as u32, + ash_hp: n(t1, "max_hp", 0.), + ash_cut: n(t1, "ep_damage_resistance", 0.), + talent_scale: n(bb, "talent_scale", 1.), + linger: n(tb, "attack_speed", 0.), + }); + Ok(()) +} +pub(crate) struct Agoat2 { + pub mode: Mode, + pub element_ratio: f64, + pub shots: usize, + pub aura_element: f64, + pub veil: f64, + pub veil_duration: f64, + pub mist: f64, + pub mist_duration: f64, + pub mist_cap: u32, + pub ash_hp: f64, + pub ash_cut: f64, + pub talent_scale: f64, + pub linger: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub accumulator: f64, + pub healing: bool, + pub veil_keys: Vec, + pub veil: f64, + pub veil_until: f64, +} + +const MIST: u64 = 1517; +impl Agoat2 { + fn guarded_heal(&self, k: &mut KitContext<'_>, target: Id, amount: f64) -> Result<(), String> { + k.world + .unit_mut(k.unit)? + .operator + .tactical + .agoat2_mut()? + .healing = true; + let result = k.heal(target, amount, health::HealOptions::default()); + k.world + .unit_mut(k.unit)? + .operator + .tactical + .agoat2_mut()? + .healing = false; + result.map(|_| ()) + } +} +impl Behavior for Agoat2 { + fn payload( + &self, + _: &World, + _: Id, + payload: &mut attacks::Direct, + _: &mut attacks::Area, + ) -> Result<(), String> { + payload.element_heal_ratio = self.element_ratio + * if self.mode == Mode::Third && payload.is_skill { + payload.heal_scale + } else { + 1. + }; + Ok(()) + } + + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Element { .. }) { + 20 + } else { + 0 + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .agoat2_mut()? + .accumulator = 0.; + if self.mode == Mode::Second { + let keys = k.keys()?; + let attack = k.stat(id, "atk")?; + for target in k.allies(&keys)? { + element::heal(k.world, target, attack * self.element_ratio, None)?; + if k.world.unit(target)?.stats.hp < k.stat(target, "maxHp")? { + self.guarded_heal(k, target, attack)?; + } + } + let until = k.world.time + self.veil_duration; + let state = k.world.unit_mut(id)?.operator.tactical.agoat2_mut()?; + state.veil_keys = keys; + state.veil = attack * self.veil; + state.veil_until = until; + } + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id && self.mode == Mode::First => { + let due = { + let s = k.world.unit_mut(id)?.operator.tactical.agoat2_mut()?; + s.accumulator += context.dt; + if s.accumulator + 1e-9 >= 1. { + s.accumulator -= 1.; + true + } else { + false + } + }; + if due { + let keys = k.keys()?; + let amount = k.stat(id, "atk")? * self.aura_element; + for target in k.allies(&keys)? { + element::heal(k.world, target, amount, None)?; + } + } + } + KitEvent::Before(context) + if context.attacker == id + && k.active()? + && !context.targets.is_empty() + && context.targets.len() < self.shots => + { + let base = context.targets.clone(); + context.targets = (0..self.shots) + .map(|index| base[index % base.len()]) + .collect(); + } + KitEvent::Heal { event, options } + if !options.regen + && event.source == Some(id) + && !k.world.unit(id)?.operator.tactical.agoat2()?.healing + && self.mist > 0. => + { + let mut buff = Buff { + key: Some(format!("agoat2:mist:{id}")), + ..Default::default() + }; + buff.runtime.duration = self.mist_duration; + buff.runtime.interval = 1.; + buff.runtime.refresh = buffs::Refresh::Stack; + buff.runtime.max_stacks = self.mist_cap; + buff.runtime.tick_payload = k.stat(id, "atk")?; + buff.runtime.on_tick = Some(MIST); + k.add(event.target, buff)?; + } + KitEvent::Buff { + context, + event: buffs::Event::Tick, + token, + } if *token == MIST => { + let buff = k.buffs.get(k.world, context.unit, context.buff)?.clone(); + if buff.runtime.source != Some(id) { + return Ok(()); + } + let amount = buff.runtime.tick_payload * self.mist * buff.stacks.max(1) as f64; + element::heal(k.world, context.unit, amount * self.element_ratio, None)?; + if k.world.unit(context.unit)?.stats.hp < k.stat(context.unit, "maxHp")? { + self.guarded_heal(k, context.unit, amount)?; + } + } + KitEvent::Scheduled(due) if k.up() => { + let keys = k.keys()?; + if due[3] { + let scale = if k.active()? { self.talent_scale } else { 1. }; + for target in k.allies(&keys)? { + let mut buff = Buff { + key: Some("agoat2:ash".into()), + mods: [("hpPct".into(), self.ash_hp * scale)].into(), + ..Default::default() + }; + buff.runtime.duration = 0.75; + buff.runtime.tick_payload = (self.ash_cut * scale).min(1.); + k.add(target, buff)?; + } + } + if due[2] + && self.linger != 0. + && k.allies(&keys)?.iter().any(|&target| { + k.world + .unit(target) + .is_ok_and(|u| u.element_buildup.iter().any(|&v| v > 0.)) + }) + { + k.buff( + id, + "agoat2:linger", + [("aspd".into(), self.linger)].into(), + 0.4, + )?; + } + } + KitEvent::Element { + phase: element::Phase::Hit, + request, + } => { + if let Some(buff) = k + .world + .unit(request.damage.hit.target)? + .stats + .buffs() + .iter() + .find(|b| { + b.key.as_deref() == Some("agoat2:ash") && b.runtime.source == Some(id) + }) + { + request.damage.damage.mul *= (1. - buff.runtime.tick_payload).max(0.); + } + } + KitEvent::ElementLate(request) + if !request.damage.cancelled + && k.world.unit(request.damage.hit.target)?.side == health::Side::Ally => + { + let now = k.world.time; + let target = request.damage.hit.target; + let covered = body::in_range( + k.world.unit(target)?, + &k.world.unit(id)?.operator.tactical.agoat2()?.veil_keys, + ); + let s = k.world.unit_mut(id)?.operator.tactical.agoat2_mut()?; + if covered && now < s.veil_until && s.veil > 1e-9 { + let amount = request.damage.damage.amount * request.damage.damage.mul; + if amount > 0. { + let take = s.veil.min(amount); + s.veil -= take; + if take >= amount - 1e-9 { + request.damage.cancelled = true; + } else { + request.damage.damage.mul *= (amount - take) / amount; + } + } + } + } + _ => {} + } + Ok(()) + } +} + +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + let mut state = Self::default(); + if let Some(previous) = previous { + state.veil_keys = previous.veil_keys.clone(); + state.veil = previous.veil.clone(); + state.veil_until = previous.veil_until.clone(); + } + state + } +} diff --git a/crates/engine/src/battle/runtime/kits/angel2.rs b/crates/engine/src/battle/runtime/kits/angel2.rs new file mode 100644 index 0000000..86e8460 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/angel2.rs @@ -0,0 +1,416 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::deploy; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SPECIAL", + branch: "geek", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[Skill { + id: "skchr_angel2_2", + kind: crate::battle::sp::Kind::Ammo, + sp_type: skills::SpType::Time, + rule: "DEFAULT", + attack_override: true, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + if raw["skill"]["skillId"] != "skchr_angel2_2" { + return Err("Unknown selected skill".into()); + } + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + s.modifiers = [( + "batPct".into(), + flat_bat(raw, n(bb, "base_attack_time", 0.)), + )] + .into(); + s.combat.skill_scale = n(bb, "attack@atk_scale", 1.); + s.extra.effects.ammo_count = n(bb, "attack@trigger_time", 10.).floor().max(1.); + s.extra.tactics = Tactics::Angel2(Angel2 { + drain: n(tb, "hp_ratio", 0.03), + steal: n(bb, "steal", 0.), + extra: n(bb, "addtional_ammo_each", 0.).floor(), + shield: n(bb, "shield_max_hp_ratio", 0.), + shield_duration: n(bb, "shield_max_duration", 0.), + heal: n(t, "hp_ratio", 0.), + probability: n(t, "prob", 0.), + blast: n(t, "aoe_atk_scale", n(t, "damage_scale", 0.)), + covenant: n(t1, "atk", 0.), + laterano: n(t1, "mult", 1.), + sp: suffix_number(tb, "sp_recovery_per_sec", 0.), + threshold: n(tb, "angel2_tr[e].hp_ratio", f64::INFINITY), + }); + Ok(()) +} +pub(crate) struct Angel2 { + drain: f64, + steal: f64, + extra: f64, + shield: f64, + shield_duration: f64, + heal: f64, + probability: f64, + blast: f64, + covenant: f64, + laterano: f64, + sp: f64, + threshold: f64, +} +struct Round { + time: f64, + target: Id, + position: [f64; 2], + amount: f64, + count: u32, + pending: u32, +} +#[derive(Default)] +pub(crate) struct State { + victim: Option, + rounds: BTreeMap, + current: BTreeMap, + next: u64, +} +const SHIELD: u64 = 1522; +impl Angel2 { + fn shield(&self, k: &mut KitContext<'_>, target: Id) -> Result<(), String> { + let total = k.stat(target, "maxHp")? * self.shield; + if total <= 0. { + return Ok(()); + } + let mut buff = Buff { + key: Some("angel2:barrier".into()), + shield: total, + ..Default::default() + }; + if self.shield_duration > 0. { + buff.runtime.duration = self.shield_duration; + buff.runtime.interval = 0.5; + buff.runtime.tick_payload = total * 0.5 / self.shield_duration; + buff.runtime.on_tick = Some(SHIELD); + } + k.add(target, buff)?; + Ok(()) + } + fn bomb(k: &mut KitContext<'_>, key: u64) -> Result<(), String> { + let target = match k + .world + .unit(k.unit)? + .operator + .tactical + .angel2()? + .rounds + .get(&key) + { + Some(round) => round.target, + None => return Ok(()), + }; + if let Ok(target) = k.world.unit(target) { + if target.stats.alive { + let position = target.position; + k.world + .unit_mut(k.unit)? + .operator + .tactical + .angel2_mut()? + .rounds + .get_mut(&key) + .unwrap() + .position = position; + } + } + let round = &k.world.unit(k.unit)?.operator.tactical.angel2()?.rounds[&key]; + let position = round.position; + let amount = round.amount; + let targets = attacks::Hooks::radius_targets( + k.host, + position, + 1.3, + true, + k.world, + k.world.unit_capacity(), + )?; + for target in targets { + let mut request = hit::Request::new( + health::Hit { + source: Some(k.unit), + credit: Some(k.unit), + target, + damage_type: DamageType::Physical, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.is_skill = true; + request.is_splash = true; + request.tags.extend(["talent".into(), "airstrike".into()]); + k.deal(&mut request)?; + } + if let Some(round) = k + .world + .unit_mut(k.unit)? + .operator + .tactical + .angel2_mut()? + .rounds + .get_mut(&key) + { + round.pending = round.pending.saturating_sub(1); + } + Ok(()) + } + fn ammo(&self, k: &mut KitContext<'_>, consumer: Id) -> Result<(), String> { + if self.heal > 0. { + let amount = k.stat(k.unit, "maxHp")? * self.heal; + k.heal( + k.unit, + amount, + health::HealOptions { + self_heal: true, + silent: true, + ..Default::default() + }, + )?; + } + if self.probability <= 0. || self.blast <= 0. || k.host.rng.next_f64() >= self.probability { + return Ok(()); + } + let now = k.world.time; + let current = k + .world + .unit(k.unit)? + .operator + .tactical + .angel2()? + .current + .get(&consumer) + .copied() + .filter(|key| { + k.world + .unit(k.unit) + .unwrap() + .operator + .tactical + .angel2() + .unwrap() + .rounds + .get(key) + .is_some_and(|r| r.time == now) + }); + let key = if let Some(key) = current { + key + } else { + let keys = k + .host + .roster + .as_ref() + .unwrap() + .base_range(k.world, consumer)?; + let targets = k.enemies(Some(&keys), true)?; + let Some(&target) = targets.first() else { + return Ok(()); + }; + let position = k.world.unit(target)?.position; + let amount = k.stat(k.unit, "atk")? * self.blast; + let limit = k.host.tactical_limit; + let state = k.world.unit_mut(k.unit)?.operator.tactical.angel2_mut()?; + if state.rounds.len() >= limit { + return Err("Angel2 bombing round capacity exceeded".into()); + } + state.next = state + .next + .checked_add(1) + .ok_or("Angel2 bombing identity overflow")?; + let key = state.next; + state.rounds.insert( + key, + Round { + time: now, + target, + position, + amount, + count: 0, + pending: 0, + }, + ); + state.current.insert(consumer, key); + key + }; + let round = k + .world + .unit_mut(k.unit)? + .operator + .tactical + .angel2_mut()? + .rounds + .get_mut(&key) + .unwrap(); + let index = round.count; + round.count += 1; + round.pending += 1; + if index == 0 { + Self::bomb(k, key)?; + } else { + k.later_key(index as f64 * 0.1, key, Self::bomb)?; + } + Ok(()) + } +} +impl Behavior for Angel2 { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + let keys = k.keys()?; + let mut candidates: Vec<_> = k + .allies(&keys)? + .into_iter() + .filter(|&a| { + a != id + && k.world + .unit(a) + .is_ok_and(|u| u.deployment.kind == deploy::Kind::Operator) + }) + .collect(); + targeting::sort_allies(k.world, id, &mut candidates, Default::default())?; + let victim = if self.steal > 0. { + candidates.first().copied() + } else { + None + }; + k.world.unit_mut(id)?.operator.tactical.angel2_mut()?.victim = victim; + self.shield(k, id)?; + if let Some(victim) = victim { + k.buff( + victim, + "angel2:stolen", + [("aspd".into(), -self.steal)].into(), + f64::INFINITY, + )?; + k.buff( + id, + "angel2:steal", + [("aspd".into(), self.steal)].into(), + f64::INFINITY, + )?; + self.shield(k, victim)?; + if self.extra > 0. { + skill.add_ammo(self.extra); + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + let victim = k + .world + .unit_mut(id)? + .operator + .tactical + .angel2_mut()? + .victim + .take(); + if let Some(victim) = victim.filter(|a| k.world.unit(*a).is_ok()) { + k.remove(victim, "angel2:stolen")?; + } + k.remove(id, "angel2:steal")?; + } + KitEvent::SkillObserved { + unit, + event: skills::Event::AmmoUsed, + .. + } if k.up() && k.world.unit(*unit)?.side == health::Side::Ally => { + self.ammo(k, *unit)?; + } + KitEvent::Buff { + context, + event: buffs::Event::Tick, + token, + } if *token == SHIELD => { + let buff = k.buffs.get(k.world, context.unit, context.buff)?; + if buff.runtime.source == Some(id) { + k.buffs.edit(k.world, context.unit, context.buff, |b| { + b.shield = (b.shield - b.runtime.tick_payload).max(0.); + })?; + } + } + KitEvent::Tick => { + let now = k.world.time; + let state = k.world.unit_mut(id)?.operator.tactical.angel2_mut()?; + state.rounds.retain(|_, r| r.time == now || r.pending > 0); + state + .current + .retain(|_, key| state.rounds.contains_key(key)); + } + KitEvent::Scheduled(due) if k.up() => { + if due[4] && self.drain > 0. { + let loss = k.stat(id, "maxHp")? * self.drain; + let hp = k.world.unit(id)?.stats.hp; + if hp - loss >= 1. { + k.lose_hp(loss)?; + } else { + k.world.unit_mut(id)?.stats.hp = hp.min(1.); + } + } + if due[3] && self.covenant != 0. { + for target in k.host.roster.as_ref().unwrap().ids().to_vec() { + if Host::tac_up(k.world, target) + && k.world.unit(target)?.deployment.kind == deploy::Kind::Operator + && k.host.tac_def(target)?.skill_kind() == crate::battle::sp::Kind::Ammo + { + let factor = if k.faction(target, "lateranoShip", &["laterano"])? { + self.laterano + } else { + 1. + }; + k.buff( + target, + "angel2:covenant", + [("atkPct".into(), self.covenant * factor)].into(), + 0.75, + )?; + } + } + } + if due[2] + && self.sp > 0. + && k.world.unit(id)?.stats.hp / k.stat(id, "maxHp")? > self.threshold + { + k.buff( + id, + "angel2:calm", + [("spRecoveryFlat".into(), self.sp)].into(), + 0.4, + )?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/archet.rs b/crates/engine/src/battle/runtime/kits/archet.rs new file mode 100644 index 0000000..0aa3033 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/archet.rs @@ -0,0 +1,319 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "fastshot", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_archet_3", + kind: Kind::Duration, + sp_type: SpType::Attack, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_archet_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_archet_2", + kind: Kind::Charges, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = tactical_mode(raw)?; + + if raw["skill"]["trigger"]["customRangeGrid"].is_array() { + s.trigger_range = Some(crate::battle::operators::parse_range( + &raw["skill"]["trigger"]["customRangeGrid"], + )?); + } + fastshot(raw, s); + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + s.combat.skill_scale = n(bb, "atk_scale", 1.); + s.combat.skill_hits = n(bb, "attack@times", 1.).floor().max(1.) as u32; + if mode == Mode::Third { + let mut p = s.combat.profile; + p.max_targets = n(bb, "attack@max_target", 1.); + s.combat.skill_profile = Some(p); + s.extra.advanced_range_extend = n(bb, "ability_range_forward_extend", 0.).max(0.) as u32; + } + let mut shield = Buff { + key: Some("talent:archet_shield".into()), + ..Default::default() + }; + shield.runtime.shield_hits = 1; + s.extra.effects.deploy_buff = Some(shield); + let times = n(bb, "times", 5.).floor().max(1.); + if times > f64::from(crate::battle::operators::Combat::MAX_HITS) { + return Err("Unsupported pursuit hit count".into()); + } + s.extra.tactics = Tactics::Archet(Archet { + mode, + scatter: n(bb, "atk_scale_2", 1.), + targets: n(bb, "max_target", 4.).max(1.) as usize, + times: times as u32, + scale: n(bb, "atk_scale", 1.), + interval: n(t, "interval", 2.5), + sp: n(t, "sp", 1.), + shield_sp: n(t1, "sp", 0.), + aspd: n(tm, "attack_speed", 0.), + }); + Ok(()) +} + +pub(crate) struct Archet { + pub mode: Mode, + pub scatter: f64, + pub targets: usize, + pub times: u32, + pub scale: f64, + pub interval: f64, + pub sp: f64, + pub shield_sp: f64, + pub aspd: f64, +} + +#[derive(Default)] +pub(crate) struct State { + pub sp_next: f64, + pub abnormal: bool, +} + +impl Host { + pub(in crate::battle::runtime) fn archet_start( + &mut self, + w: &mut World, + id: Id, + p: &Archet, + ) -> Result<(), String> { + if p.mode == Mode::Second { + if let Some(&a) = self.tac_enemies(w, id, None, true)?.first() { + self.tac_fire(w, id, a, ArrowKind::Pursuit, p.scale, p.times)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn archet_scheduled( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + due: [bool; 5], + archet_due: bool, + p: &Archet, + ) -> Result<(), String> { + if archet_due { + if self.tac_leader(w, id)? { + for a in self.roster.as_ref().unwrap().ids().to_vec() { + let d = self.tac_def(a)?; + if Self::tac_up(w, a) + && d.profession == "SNIPER" + && d.sp_type() == skills::SpType::Attack + { + self.advanced_grant_sp(w, r, a, p.sp)?; + } + } + } + } + if due[0] && p.aspd > 0. { + let mut ground = false; + for a in self.tac_enemies(w, id, None, true)? { + ground |= !targeting::flying(w, a)?; + } + self.advanced_toggle( + w, + r, + id, + "trait:archet_ground", + ground, + [("aspd".into(), p.aspd)].into(), + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn archet_impact( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + target: Id, + impact: attacks::Impact, + p: &Archet, + ) -> Result<(), String> { + if impact.is_skill && p.mode == Mode::First { + let position = impact.position; + let candidates = self.tac_radius(w, position, 1.5)?; + let mut ids = self.tac_selectable(w, id, candidates)?; + ids.retain(|&a| a != target); + ids.sort_by(|a, b| { + body::distance(w.unit(*a).unwrap(), position) + .total_cmp(&body::distance(w.unit(*b).unwrap(), position)) + .then( + w.unit(*a) + .unwrap() + .targeting + .spawn_seq + .cmp(&w.unit(*b).unwrap().targeting.spawn_seq), + ) + }); + for a in ids.into_iter().take(p.targets.saturating_sub(1)) { + let amount = Self::tac_stat(w, id, "atk")? * p.scatter; + self.tac_damage(w, r, id, a, amount, DamageType::Physical, false, "scatter")?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn archet_shield_lost( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + e: &health::Event, + p: &Archet, + ) -> Result<(), String> { + if !Self::tac_has(w, e.target, "talent:archet_shield") + && !w.unit(e.target)?.operator.tactical.archet()?.abnormal + { + w.unit_mut(e.target)? + .operator + .tactical + .archet_mut()? + .abnormal = true; + self.advanced_grant_sp(w, r, e.target, p.shield_sp)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn archet_continue_arrow( + &mut self, + w: &mut World, + arrow: Arrow, + position: [f64; 2], + ) -> Result<(), String> { + let candidates = self.tac_radius(w, position, 1.5)?; + let mut next = self.tac_selectable(w, arrow.source, candidates)?; + next.retain(|t| !arrow.seen[..arrow.count].contains(t)); + next.sort_by(|a, b| { + body::distance(w.unit(*a).unwrap(), position) + .total_cmp(&body::distance(w.unit(*b).unwrap(), position)) + .then( + w.unit(*a) + .unwrap() + .targeting + .spawn_seq + .cmp(&w.unit(*b).unwrap().targeting.spawn_seq), + ) + }); + if let Some(&t) = next.first() { + let mut next_arrow = arrow; + next_arrow.hits -= 1; + next_arrow.seen[next_arrow.count] = t; + next_arrow.count += 1; + Self::tac_arrow_launch( + w, + self.flights.as_mut().ok_or("Missing pursuit projectiles")?, + position, + t, + next_arrow, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn archet_sp_due( + &self, + w: &mut World, + id: Id, + p: &Archet, + ) -> Result { + let at = w + .unit(id)? + .operator + .tactical + .archet()? + .sp_next + .max(p.interval); + let due = w.time + 1e-9 >= at; + if due { + w.unit_mut(id)?.operator.tactical.archet_mut()?.sp_next = at + p.interval; + } + Ok(due) + } +} + +impl State { + pub fn redeployed(previous: Option<&Self>) -> Self { + Self { + sp_next: previous.map_or(0., |p| p.sp_next), + ..Default::default() + } + } +} + +impl Behavior for Archet { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::Scheduled(_)) + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + (Role::Source, KitEvent::Impact(impact)) => { + if let Some(target) = impact.target { + k.host + .archet_impact(k.world, id, k.buffs, target, *impact, self)?; + } + } + (Role::Target, KitEvent::Landed { event, .. }) => { + k.host.archet_shield_lost(k.world, k.buffs, event, self)?; + } + _ => {} + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Scheduled(due) => { + let sp_due = k.host.archet_sp_due(k.world, id, self)?; + if k.up() { + k.host + .archet_scheduled(k.world, id, k.buffs, *due, sp_due, self)?; + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.archet_start(k.world, id, self)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/blaze2.rs b/crates/engine/src/battle/runtime/kits/blaze2.rs new file mode 100644 index 0000000..ba595dc --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/blaze2.rs @@ -0,0 +1,305 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::element; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "primcaster", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[Skill { + id: "skchr_blaze2_3", + kind: Kind::Ammo, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + if raw["skill"]["skillId"] != "skchr_blaze2_3" { + return Err("Unknown selected skill".into()); + } + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ( + "batPct".into(), + flat_bat(raw, n(bb, "base_attack_time", 0.)), + ), + ] + .into(); + skill_range(raw, s)?; + s.extra.effects.ammo_count = n(bb, "attack@trigger_time", 18.); + s.combat.skill_area.splash = Some(Splash { + radius: 1.7, + scale: 1., + hits_fly: true, + fortress_melee: false, + }); + s.extra.tactics = Tactics::Blaze2(Blaze2 { + loss: n(bb, "lose_hp_scale", 0.), + burst_damage: n(t, "ep_damage_scale", 0.), + burst_heal: n(t, "hp_ratio", 0.), + shield: n(t1, "dynamic", 0.), + regen: n(t1, "hp_recovery_per_sec_by_max_hp_ratio", 0.), + stun: n(t1, "stun", 0.), + burst_attack: n(bb, "attack@atk_scale", 0.), + ammo_refill: n(bb, "ammo_recover", 0.), + ammo_cap: n(bb, "attack@trigger_time", 18.), + burst_mul: n(tb, "damage_scale", 1.), + sp: n(tm, "sp_recovery_per_sec", 0.), + }); + Ok(()) +} +pub(crate) struct Blaze2 { + pub loss: f64, + pub burst_damage: f64, + pub burst_heal: f64, + pub shield: f64, + pub regen: f64, + pub stun: f64, + pub burst_attack: f64, + pub ammo_refill: f64, + pub ammo_cap: f64, + pub burst_mul: f64, + pub sp: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub loss_acc: f64, + pub downed: bool, + pub pending_end: bool, + pub pending_ammo: f64, +} + +const DOWNED: u64 = 1519; +impl Blaze2 { + fn resume(k: &mut KitContext<'_>, skill: &mut skills::Runtime) -> Result<(), String> { + let state = k.world.unit_mut(k.unit)?.operator.tactical.blaze2_mut()?; + let end = std::mem::take(&mut state.pending_end); + let ammo = std::mem::take(&mut state.pending_ammo); + if end { + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + skill.end(world, host, "downed") + })?; + } else if skill.bank.active { + let def = k.host.tac_def(k.unit)?; + let Tactics::Blaze2(p) = &def.extra.tactics else { + unreachable!() + }; + skill.add_ammo(ammo.min((p.ammo_cap - skill.ammo_left).max(0.))); + } + Ok(()) + } +} +impl Behavior for Blaze2 { + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Fatal(_)) { + -50 + } else { + 0 + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .blaze2_mut()? + .loss_acc = 0.; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .blaze2_mut()? + .loss_acc += context.dt; + for _ in 0..30 { + if k.world.unit(id)?.operator.tactical.blaze2()?.loss_acc < 1. + || !k.world.unit(id)?.stats.alive + { + break; + } + k.world + .unit_mut(id)? + .operator + .tactical + .blaze2_mut()? + .loss_acc -= 1.; + let loss = k.stat(id, "maxHp")? * self.loss; + k.lose_hp(loss)?; + } + } + KitEvent::Attack { context, skill } if context.attacker == id => { + if let Some(skill) = skill { + Self::resume(k, skill)?; + } + } + KitEvent::Resume { unit, skill } if *unit == id => { + Self::resume(k, skill)?; + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.source == Some(id) => { + if k.flag(request.hit.target, "burstLock")? { + request.damage.mul *= self.burst_mul; + } + if request.is_attack && request.is_skill && k.has(request.hit.target, "burnBurst") { + let amount = k.stat(id, "atk")? * self.burst_attack; + k.element_damage( + request.hit.target, + amount, + element::Element::Burn, + "blazeBurn", + )?; + } + } + KitEvent::Element { + phase: element::Phase::Burst, + request, + } if request.damage.element == Some(element::Element::Burn) && k.up() => { + if k.world.unit(request.damage.hit.target)?.side == health::Side::Enemy { + let amount = k.stat(id, "atk")? * self.burst_damage; + k.element_damage( + request.damage.hit.target, + amount, + element::Element::Burn, + "blazeMelt", + )?; + if !k.world.unit(id)?.operator.tactical.blaze2()?.downed { + let amount = k.stat(id, "maxHp")? * self.burst_heal; + k.heal( + id, + amount, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + } + if k.active()? { + if k.host.roster.as_ref().unwrap().entry(id)?.skill().is_ok() { + k.skill(|skill, _, _| { + skill.add_ammo( + self.ammo_refill + .min((self.ammo_cap - skill.ammo_left).max(0.)), + ); + Ok(()) + })?; + } else { + k.world + .unit_mut(id)? + .operator + .tactical + .blaze2_mut()? + .pending_ammo += self.ammo_refill; + } + } + } + KitEvent::Fatal(event) + if event.target == id + && !event.prevented + && !k.world.unit(id)?.operator.tactical.blaze2()?.downed => + { + event.prevented = true; + k.world.unit_mut(id)?.operator.tactical.blaze2_mut()?.downed = true; + if !k.end_skill("downed")? { + k.world + .unit_mut(id)? + .operator + .tactical + .blaze2_mut()? + .pending_end = true; + } + k.release()?; + let mut buff = Buff { + key: Some("blaze2:downed".into()), + mods: [ + ("hpRegenRatio".into(), self.regen), + ("blockCnt".into(), -99.), + ] + .into(), + flags: ["disarm".into(), "noHeal".into()].into(), + ..Default::default() + }; + buff.shield = self.shield; + buff.runtime.interval = 0.2; + buff.runtime.on_tick = Some(DOWNED); + k.add(id, buff)?; + } + KitEvent::Buff { + context, + event: buffs::Event::Tick, + token, + } if *token == DOWNED => { + if k.buffs + .get(k.world, context.unit, context.buff)? + .runtime + .source + != Some(id) + { + return Ok(()); + } + if k.world.unit(id)?.stats.hp >= k.stat(id, "maxHp")? - 1e-6 { + k.buffs.remove_id(k.world, k.host, id, context.buff)?; + k.world.unit_mut(id)?.operator.tactical.blaze2_mut()?.downed = false; + let at = k.world.unit(id)?.position; + for target in k.radius(at, 1.7)? { + k.status(target, "stun", self.stun, None)?; + } + } + } + KitEvent::Scheduled(due) if due[2] && k.up() => { + let keys = k.keys()?; + if self.sp != 0. { + let mut found = false; + for target in k.host.spawns.as_ref().unwrap().live().to_vec() { + if k.world.unit(target)?.stats.alive + && body::in_range(k.world.unit(target)?, &keys) + && k.flag(target, "burstLock")? + { + found = true; + break; + } + } + if found { + k.buff( + id, + "blaze2:module", + [("spRecoveryFlat".into(), self.sp)].into(), + 0.5, + )?; + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/blemsh.rs b/crates/engine/src/battle/runtime/kits/blemsh.rs new file mode 100644 index 0000000..9bc9634 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/blemsh.rs @@ -0,0 +1,405 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "guardian", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_blemsh_3", + kind: Kind::Duration, + sp_type: SpType::Hurt, + rule: "TAKE_DAMAGE", + attack_override: true, + }, + Skill { + id: "skchr_blemsh_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_blemsh_2", + kind: Kind::Duration, + sp_type: SpType::Hurt, + rule: "TAKE_DAMAGE", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = tactical_mode(raw)?; + + s.combat.profile.selection.hit_sleep = true; + if mode == Mode::First { + s.combat.skill_scale = n(bb, "atk_scale", 1.); + } else { + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("defPct".into(), n(bb, "def", 0.)), + ] + .into(); + } + if mode == Mode::Third { + s.rule_override = Some(crate::battle::skills::Rule::Default); + } + if n(tb, "damage_resistance", 0.) > 0. { + s.extra.effects.permanent.push(persistent( + "trait:blemsh_guard", + [("dmgTakenMul".into(), 1. - n(tb, "damage_resistance", 0.))].into(), + )); + } + if n(tb, "heal_scale", 0.) > 0. { + s.extra.support.heal_bonus = Some(HealBonus { + below: n(tb, "hp_ratio", 0.5), + scale: n(tb, "heal_scale", 1.), + inclusive: false, + }); + } + s.extra.tactics = Tactics::Blemsh(Blemsh { + mode, + grid: tactical_grid(&raw["skill"]["rangeGrid"], true)?, + heal: n(bb, "heal_scale", 0.), + regen: n( + bb, + "attack@atk_to_hp_recovery_ratio", + n(bb, "atk_to_hp_recovery_ratio", 0.), + ), + bonus: n(bb, "attack@blemsh_s_3_extra_dmg[magic].atk_scale", 0.), + mercy: n(t1, "atk_scale", 1.), + sp: n(t, "sp", 1.), + }); + Ok(()) +} + +pub(crate) struct Blemsh { + pub mode: Mode, + pub grid: Vec<[i32; 2]>, + pub heal: f64, + pub regen: f64, + pub bonus: f64, + pub mercy: f64, + pub sp: f64, +} + +#[derive(Default)] +pub(crate) struct State { + pub aura: f64, +} + +impl Host { + pub(in crate::battle::runtime) fn tac_blemsh_aura( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + p: &Blemsh, + ) -> Result<(), String> { + let keys = self.tac_keys(w, id, &p.grid)?; + let value = Self::tac_stat(w, id, "atk")? * p.regen; + if value > 0. { + for a in self.roster.as_ref().unwrap().ids().to_vec() { + let u = w.unit(a)?; + if !u.stats.alive + || !u.deployed + || u.hidden + || u.deployment.kind == crate::battle::deploy::Kind::Device + || !body::in_range(u, &keys) + { + continue; + } + if a != id + && w.unit_mut(a)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("isolated") + { + continue; + } + self.component_buff( + w, + r, + a, + &format!("blemsh:regen:{id}"), + [("hpRegen".into(), value)].into(), + 0.5, + id, + )?; + } + } + let mut extra = vec![]; + for &a in self.spawns.as_ref().unwrap().live() { + if Self::tac_up(w, a) + && Self::tac_has(w, a, "sleep") + && body::in_range(w.unit(a)?, &keys) + { + extra.extend(body::keys(w.unit(a)?)); + } + } + extra.sort_unstable(); + extra.dedup(); + w.unit_mut(id)?.operator.advanced.extra_range = extra; + Ok(()) + } + pub(in crate::battle::runtime) fn blemsh_start( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + s: &mut skills::Runtime, + p: &Blemsh, + ) -> Result<(), String> { + if p.mode == Mode::Second { + let tile = w.unit(id)?.deployment.tile; + let blocked = w.unit(id)?.blocking().to_vec(); + let enemies = self.spawns.as_ref().unwrap().live().to_vec(); + for a in enemies { + if !w.unit(a)?.stats.alive || w.unit(a)?.hidden { + continue; + } + if blocked.contains(&a) + || !targeting::flying(w, a)? && body::on_tile(w.unit(a)?, tile[0], tile[1]) + { + self.advanced_status(w, r, id, a, "sleep", s.time_left, None)?; + } + } + w.unit_mut(id)?.operator.tactical.blemsh_mut()?.aura = 0.; + self.tac_blemsh_aura(w, r, id, p)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn blemsh_end( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Blemsh, + ) -> Result<(), String> { + if p.mode == Mode::Second { + w.unit_mut(id)?.operator.advanced.extra_range.clear(); + for a in self.roster.as_ref().unwrap().ids().to_vec() { + r.remove(w, self, a, &format!("blemsh:regen:{id}"))?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn blemsh_skill_tick( + &mut self, + dt: f64, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Blemsh, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.blemsh_mut()?.aura += dt; + if p.mode == Mode::Second { + if w.unit(id)?.operator.tactical.blemsh()?.aura >= 0.25 - 1e-9 { + w.unit_mut(id)?.operator.tactical.blemsh_mut()?.aura = 0.; + self.tac_blemsh_aura(w, r, id, p)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn blemsh_before( + &mut self, + w: &mut World, + id: Id, + c: &mut attacks::Context, + ) -> Result<(), String> { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + for a in self.spawns.as_ref().unwrap().live() { + if Self::tac_up(w, *a) + && Self::tac_has(w, *a, "sleep") + && body::in_range(w.unit(*a)?, &keys) + { + c.targets.retain(|t| t != a); + c.targets.insert(0, *a); + c.targets.truncate(1); + break; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn blemsh_attack( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + active: bool, + p: &Blemsh, + ) -> Result<(), String> { + if active && p.mode == Mode::Third && p.heal > 0. { + let keys = self.tac_keys(w, id, &p.grid)?; + if let Some(a) = self + .tac_heal_targets(w, id, &keys, true)? + .into_iter() + .find(|a| *a != id) + { + let amount = Self::tac_stat(w, id, "atk")? * p.heal; + self.tac_heal(w, r, id, a, amount)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn blemsh_impact( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + target: Id, + impact: attacks::Impact, + p: &Blemsh, + ) -> Result<(), String> { + if impact.is_skill { + if p.mode == Mode::First { + let keys = self.tac_keys(w, id, &p.grid)?; + if let Some(&a) = self.tac_heal_targets(w, id, &keys, true)?.first() { + let amount = Self::tac_stat(w, id, "atk")? * p.heal; + self.tac_heal(w, r, id, a, amount)?; + } + } else if p.mode == Mode::Third && Self::tac_up(w, target) { + let amount = Self::tac_stat(w, id, "atk")? * p.bonus; + self.tac_damage( + w, + r, + id, + target, + amount, + DamageType::Arts, + false, + "blemshBonus", + )?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn blemsh_phase( + &mut self, + w: &mut World, + q: &mut hit::Request, + c: &Blemsh, + ) -> Result<(), String> { + if w.unit(q.hit.target)?.side == health::Side::Enemy + && Self::tac_has(w, q.hit.target, "sleep") + { + q.damage.mul *= c.mercy; + } + Ok(()) + } +} + +impl Behavior for Blemsh { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::AttackFinished { .. }) + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + (Role::Source, KitEvent::Before(context)) => { + k.host.blemsh_before(k.world, id, context)?; + } + (Role::Source, KitEvent::Attack { .. }) => { + let active = k.active()?; + k.host.blemsh_attack(k.world, id, k.buffs, active, self)?; + } + (Role::Source, KitEvent::Impact(impact)) => { + if let Some(target) = impact.target { + k.host + .blemsh_impact(k.world, id, k.buffs, target, *impact, self)?; + } + } + ( + Role::Source, + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + }, + ) => { + k.host.blemsh_phase(k.world, request, self)?; + } + _ => {} + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::AttackFinished { context, skill } => { + let first = k + .host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .find(|&unit| { + Host::tac_up(k.world, unit) + && k.host + .tac_def(unit) + .is_ok_and(|def| matches!(def.extra.tactics, Tactics::Blemsh(_))) + }); + if first == Some(id) + && k.host.tac_def(context.attacker)?.sp_type() == skills::SpType::Hurt + { + if let Some(skill) = skill { + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + skill.gain(world, host, self.sp, "talent", false, false) + })?; + } else { + k.host + .advanced_grant_sp(k.world, k.buffs, context.attacker, self.sp)?; + } + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + k.host.blemsh_start(k.world, id, k.buffs, skill, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id => { + k.host + .blemsh_skill_tick(context.dt, k.world, id, k.buffs, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + k.host.blemsh_end(k.world, id, k.buffs, self)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/blkkgt.rs b/crates/engine/src/battle/runtime/kits/blkkgt.rs new file mode 100644 index 0000000..b5e1591 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/blkkgt.rs @@ -0,0 +1,337 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "sword", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_blkkgt_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SKILL_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_blkkgt_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_blkkgt_2", + kind: Kind::Charges, + sp_type: SpType::Attack, + rule: "SKILL_RANGE", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_blkkgt_1" => Mode::First, + "skchr_blkkgt_2" => Mode::Second, + "skchr_blkkgt_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.combat.normal_hits = 2; + let mods: Numbers = [ + ("defIgnoreFlat".into(), n(tb, "def_penetrate_fixed", 0.)), + ("atkPct".into(), n(t1, "atk", 0.)), + ] + .into(); + if mods.values().any(|v| *v != 0.) { + s.extra + .effects + .permanent + .push(persistent("blkkgt:contract", mods)); + } + if mode == Mode::First { + s.combat.skill_hits = 2; + s.combat.skill_scale = n(bb, "atk_scale_s1", 1.); + let mut p = s.combat.profile; + p.max_targets = n(bb, "max_target", 5.).max(1.); + s.combat.skill_profile = Some(p); + } + if mode == Mode::Third { + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + s.extra.duration = Some( + kit_text_count(&raw["skill"]["desc"], "总计", "次", 10, 64)? as f64 + * n(bb, "d_hit_interval", 0.3).max(0.05), + ); + } + skill_range(raw, s)?; + s.extra.tactics = Tactics::Blkkgt(Blkkgt { + mode: mode, + slashes: kit_text_count(&raw["skill"]["desc"], "总计", "次", 10, 64)?, + interval: n(bb, "d_hit_interval", 0.3).max(0.05), + pull_interval: n(bb, "p_hit_interval", 1.).max(0.1), + targets: n(bb, "max_target", 1.).floor().max(1.) as usize, + grid: tactical_grid(&raw["skill"]["rangeGrid"], false)?, + slash_scale: n(bb, "d_atk_scale", 1.), + dot_scale: n(bb, "dot_scale", 1.), + finisher: n(bb, "e_atk_scale_end", 1.), + pull_force: n(bb, "p_force", 0.), + final_force: n(bb, "e_force", 0.), + free_hits: n(bb, "blkkgt_s_2[not_blocked].trig_cnt", 2.) + .floor() + .max(0.) as u32, + blocked_hits: n(bb, "blkkgt_s_2[blocked].trig_cnt", 3.).floor().max(0.) as u32, + prob: n(t, "prob", 0.), + skill_prob: n(bb, "prob", n(t, "prob", 0.)), + crit: n(t, "atk_scale", 1.), + tremble: n(t, "not_combat", 0.), + pen: n(t1, "def_penetrate", 0.), + initial_tremble: n(t1, "not_combat", 0.), + skill_mul: n(tb, "damage_scale", 1.), + }); + Ok(()) +} +pub(crate) struct Blkkgt { + pub mode: Mode, + pub slashes: u32, + pub interval: f64, + pub pull_interval: f64, + pub targets: usize, + pub grid: Vec<[i32; 2]>, + pub slash_scale: f64, + pub dot_scale: f64, + pub finisher: f64, + pub pull_force: f64, + pub final_force: f64, + pub free_hits: u32, + pub blocked_hits: u32, + pub prob: f64, + pub skill_prob: f64, + pub crit: f64, + pub tremble: f64, + pub pen: f64, + pub initial_tremble: f64, + pub skill_mul: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub active: bool, + pub finale: bool, + pub slashes: u32, + pub accumulator: f64, + pub pull_acc: f64, + pub seen: BTreeSet, +} + +impl Blkkgt { + fn slash(&self, k: &mut KitContext<'_>, scale: f64) -> Result<(), String> { + let targets = k.enemies(None, true)?; + for target in targets.into_iter().take(self.targets) { + let amount = k.stat(k.unit, "atk")? * scale; + k.damage(target, amount, DamageType::Physical, true, "slash")?; + } + Ok(()) + } + fn pull(&self, k: &mut KitContext<'_>, force: f64, finale: bool) -> Result<(), String> { + for target in k.enemies(None, true)? { + if finale { + k.pull(target, force, Some(k.world.unit(k.unit)?.position))?; + } else { + k.pull(target, force, None)?; + } + } + Ok(()) + } +} +impl Behavior for Blkkgt { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + if self.mode == Mode::Second { + let keys = k.range(&self.grid)?; + for target in k + .enemies(Some(&keys), false)? + .into_iter() + .take(self.targets) + { + let count = if k.world.unit(target)?.blocked_by().is_some() { + self.blocked_hits + } else { + self.free_hits + }; + if count > 64 { + return Err("Slash count exceeds capacity".into()); + } + for _ in 0..count { + if !Host::tac_up(k.world, target) { + break; + } + let amount = k.stat(id, "atk")? * self.dot_scale; + k.damage(target, amount, DamageType::Physical, true, "slash")?; + } + } + } + if self.mode == Mode::Third { + let state = k.world.unit_mut(id)?.operator.tactical.blkkgt_mut()?; + state.active = true; + state.slashes = 1; + state.accumulator = 0.; + state.pull_acc = 0.; + let mut buff = Buff { + key: Some("blkkgt:slashes".into()), + flags: ["invulnerable".into()].into(), + ..Default::default() + }; + buff.runtime.duration = self.slashes as f64 * self.interval + 1.; + k.add(id, buff)?; + self.slash(k, self.slash_scale)?; + } + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id && self.mode == Mode::Third => { + { + let state = k.world.unit_mut(id)?.operator.tactical.blkkgt_mut()?; + state.accumulator += context.dt; + state.pull_acc += context.dt; + } + for _ in 0..self.slashes { + let due = { + let state = k.world.unit_mut(id)?.operator.tactical.blkkgt_mut()?; + if state.accumulator + 1e-9 >= self.interval && state.slashes < self.slashes + { + state.accumulator -= self.interval; + state.slashes += 1; + true + } else { + false + } + }; + if !due { + break; + } + self.slash(k, self.slash_scale)?; + } + let pull = { + let state = k.world.unit_mut(id)?.operator.tactical.blkkgt_mut()?; + if state.pull_acc + 1e-9 >= self.pull_interval { + state.pull_acc -= self.pull_interval; + true + } else { + false + } + }; + if pull { + self.pull(k, self.pull_force, false)?; + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + context, + .. + } if *unit == id && self.mode == Mode::Third => { + k.world.unit_mut(id)?.operator.tactical.blkkgt_mut()?.active = false; + k.remove(id, "blkkgt:slashes")?; + if context.reason != "death" && k.world.unit(id)?.stats.alive { + k.world.unit_mut(id)?.operator.tactical.blkkgt_mut()?.finale = true; + let result = self.slash(k, self.finisher); + k.world.unit_mut(id)?.operator.tactical.blkkgt_mut()?.finale = false; + result?; + self.pull(k, self.final_force, true)?; + } + } + KitEvent::BeforeStatus(context) + if context.target == id + && k.world.unit(id)?.operator.tactical.blkkgt()?.active + && matches!(context.key.as_str(), "stun" | "freeze") => + { + context.cancelled = true; + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.source == Some(id) + && k.world.unit(request.hit.target)?.side == health::Side::Enemy => + { + if self.pen > 0. && k.has(request.hit.target, "tremble") { + request.damage.penetration.def_pct += self.pen; + } + let probability = + if k.active()? || k.world.unit(id)?.operator.tactical.blkkgt()?.finale { + self.skill_prob + } else { + self.prob + }; + if probability > 0. && (probability >= 1. || k.host.rng.next_f64() < probability) { + request.damage.amount *= self.crit; + if self.tremble > 0. && Host::tac_up(k.world, request.hit.target) { + k.status(request.hit.target, "tremble", self.tremble, None)?; + } + } + if request.is_skill { + request.damage.mul *= self.skill_mul; + } + } + KitEvent::Scheduled(due) if due[2] => { + let valid: BTreeSet<_> = k.world.unit_ids().collect(); + k.world + .unit_mut(id)? + .operator + .tactical + .blkkgt_mut()? + .seen + .retain(|target| valid.contains(target)); + } + KitEvent::Tick if k.up() && self.initial_tremble > 0. => { + for target in k.enemies(None, true)? { + if targeting::flying(k.world, target)? { + continue; + } + if k.world + .unit_mut(id)? + .operator + .tactical + .blkkgt_mut()? + .seen + .insert(target) + { + k.status(target, "tremble", self.initial_tremble, None)?; + } + } + } + _ => {} + } + Ok(()) + } +} + +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + let mut state = Self::default(); + if let Some(previous) = previous { + state.seen = previous.seen.clone(); + } + state + } +} diff --git a/crates/engine/src/battle/runtime/kits/caper.rs b/crates/engine/src/battle/runtime/kits/caper.rs new file mode 100644 index 0000000..06df257 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/caper.rs @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "loopshooter", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_caper_2", + kind: Kind::Duration, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_caper_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_caper_1" => Mode::First, + "skchr_caper_2" => Mode::Second, + _ => return Err("Unknown selected skill".into()), + }; + s.combat.projectile = Some("boomerang"); + s.combat.projectile_speed = 15.; + if mode == Mode::First { + s.combat.skill_scale = n(bb, "atk_scale", 1.); + } else { + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + s.combat.skill_hits = n(bb, "cnt", 1.).max(1.) as u32; + } + s.extra.tactics = Tactics::Caper(Caper { + near: n(tb, "atk_scale", 1.), + prob: n(t, "prob", 0.), + crit: n(t, "atk_scale", 1.), + }); + Ok(()) +} +pub(crate) struct Caper { + pub near: f64, + pub prob: f64, + pub crit: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub out: u32, +} +impl Behavior for Caper { + fn can_attack(&self, _host: &Host, world: &World, unit: Id) -> Result { + Ok(world.unit(unit)?.operator.tactical.caper()?.out == 0) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Attack { context, .. } if context.attacker == id => { + k.world.unit_mut(id)?.operator.tactical.caper_mut()?.out += 1; + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.source == Some(id) && request.is_attack => { + let at = k.world.unit(id)?.position; + if body::tile_reach( + k.world.unit(request.hit.target)?, + at[0].round() as i32, + at[1].round() as i32, + ) <= 1. + { + request.damage.amount *= self.near; + } + if !request.is_splash && self.prob > 0. && k.host.rng.chance(self.prob) { + request.damage.amount *= self.crit; + } + } + _ => {} + } + Ok(()) + } +} +impl Host { + pub(in crate::battle::runtime) fn caper_return( + &mut self, + world: &mut World, + source: Id, + deployment: u64, + at: [f64; 2], + ) -> Result<(), String> { + if !Self::tac_up(world, source) || world.unit(source)?.deployment.deploy_seq != deployment { + return Ok(()); + } + self.flights + .as_mut() + .ok_or("Missing return projectiles")? + .add( + world, + projectiles::Launch { + from: at, + source: Some(source), + target: Some(source), + to: None, + speed: 3.75, + hit_dead: true, + max_age: 10., + on_hit: true, + visual: "boomerangReturn".into(), + speed_changeable: None, + removable: None, + payload: allies::Shot::BoomerangReturn { source, deployment }, + }, + ) + .map(|_| ()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/cello.rs b/crates/engine/src/battle/runtime/kits/cello.rs new file mode 100644 index 0000000..017dfd9 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/cello.rs @@ -0,0 +1,405 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::element; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "ritualist", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_cello_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_cello_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_cello_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_cello_1" => Mode::First, + "skchr_cello_2" => Mode::Second, + "skchr_cello_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.modifiers = match mode { + Mode::First => Default::default(), + Mode::Second => [("aspd".into(), n(bb, "attack_speed", 0.))].into(), + Mode::Third => [("atkPct".into(), n(bb, "atk", 0.))].into(), + }; + if mode == Mode::First { + s.combat.profile.only_while_skill = true; + s.combat.profile.priority = targeting::Priority::NotBurst; + s.combat.skill_scale = n(bb, "atk_scale", 1.); + } + if mode == Mode::Second { + let mut p = s.combat.profile; + p.max_targets = 2.; + s.combat.skill_profile = Some(p); + } + if mode == Mode::Third { + skill_range(raw, s)?; + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + } + s.extra.tactics = Tactics::Cello(Cello { + mode: mode, + ep: n(bb, "ep_damage_ratio", 0.), + aura_ep: n(t, "ep_damage_ratio", 0.), + sluggish: n(t, "sluggish", 0.), + amp: n(t1, "ep_damage_scale", 1.), + fragile: n(t1, "damage_scale", 1.) - 1., + elite_mul: n(tb, "ep_damage_scale", 1.), + wide: !t1["damage_value"].is_null(), + dot: n(t1, "damage_value", 0.), + dot_interval: n(t1, "interval", 1.).max(0.1), + module_fragile: n(tm, "damage_scale", 1.) - 1., + boost: n(bb, "scale_delta_to_one", 1.), + hp_up: n(bb, "cello_s_3[max_hp].max_hp", 0.), + atk_up: n(bb, "cello_s_3[atk].atk", 0.), + def_up: n(bb, "cello_s_3[def].def", 0.), + }); + Ok(()) +} +pub(crate) struct Cello { + pub mode: Mode, + pub ep: f64, + pub aura_ep: f64, + pub sluggish: f64, + pub amp: f64, + pub fragile: f64, + pub elite_mul: f64, + pub wide: bool, + pub dot: f64, + pub dot_interval: f64, + pub module_fragile: f64, + pub boost: f64, + pub hp_up: f64, + pub atk_up: f64, + pub def_up: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub boost: f64, + pub partner: Option, + pub pick: f64, + pub tango: f64, + pub dot: f64, +} + +impl Cello { + fn boost(&self, k: &KitContext<'_>) -> Result { + Ok(k.world + .unit(k.unit)? + .operator + .tactical + .cello()? + .boost + .max(1.)) + } + fn partner(&self, k: &mut KitContext<'_>) -> Result<(), String> { + let keys = k.keys()?; + let mut best = None; + let mut attack = f64::NEG_INFINITY; + for unit in k.allies(&keys)? { + if unit == k.unit { + continue; + } + let value = k.stat(unit, "atk")?; + if value > attack + 1e-9 { + best = Some(unit); + attack = value; + } + } + let s = k.world.unit_mut(k.unit)?.operator.tactical.cello_mut()?; + s.partner = best; + s.pick = 0.5; + Ok(()) + } +} +impl Behavior for Cello { + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Hit { .. }) { + -1000 + } else { + 0 + } + } + fn profile( + &self, + _: &World, + _: Id, + skill: Option<&skills::Runtime>, + profile: &mut search::AttackProfile, + ) -> Result<(), String> { + if self.mode == Mode::First { + profile.only_while_skill = !skill.is_some_and(|s| s.bank.ready() || s.bank.active); + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + if self.mode == Mode::Second { + self.partner(k)?; + } + if self.mode == Mode::Third { + let s = k.world.unit_mut(id)?.operator.tactical.cello_mut()?; + s.boost = self.boost; + s.tango = f64::INFINITY; + } + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id => { + if self.mode == Mode::Second { + let partner = k.world.unit(id)?.operator.tactical.cello()?.partner; + let partner_up = partner.is_some_and(|a| Host::tac_up(k.world, a)); + let pick = { + let s = k.world.unit_mut(id)?.operator.tactical.cello_mut()?; + s.pick -= context.dt; + s.pick <= 0. || !partner_up + }; + if pick { + self.partner(k)?; + } + } + if self.mode == Mode::Third { + let due = { + let s = k.world.unit_mut(id)?.operator.tactical.cello_mut()?; + s.tango += context.dt; + if s.tango >= 0.5 { + s.tango = 0.; + true + } else { + false + } + }; + if due { + let keys = k.keys()?; + let allies = k.allies(&keys)?; + for (stat, key, value) in [ + ("maxHp", "cello:tango:hp", self.hp_up), + ("atk", "cello:tango:atk", self.atk_up), + ("def", "cello:tango:def", self.def_up), + ] { + let mut best = None; + let mut maximum = f64::NEG_INFINITY; + for &a in &allies { + if a == id { + continue; + } + let v = k.world.unit(a)?.stats.base_number(stat); + if v > maximum + 1e-9 { + maximum = v; + best = Some(a); + } + } + if let Some(a) = best { + k.buff( + a, + key, + [( + if stat == "maxHp" { + "hpPct" + } else if stat == "atk" { + "atkPct" + } else { + "defPct" + } + .into(), + value, + )] + .into(), + 0.75, + )?; + } + } + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + let s = k.world.unit_mut(id)?.operator.tactical.cello_mut()?; + s.partner = None; + s.boost = 1.; + } + KitEvent::Impact(impact) + if impact.attacker == id + && impact.is_skill + && self.mode == Mode::First + && impact.kind == attacks::VictimKind::Main => + { + if let Some(target) = impact.target.filter(|&a| Host::tac_up(k.world, a)) { + let amount = k.stat(id, "atk")? * self.ep; + k.elemental(target, amount, element::Element::Apoptosis)?; + } + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if self.mode == Mode::Second + && k.up() + && k.active()? + && request.hit.damage_type != DamageType::Elemental + && request.damage.amount > 0. + && k.world.unit(request.hit.target)?.side == health::Side::Enemy => + { + if request.hit.source == Some(id) + || request.hit.source == k.world.unit(id)?.operator.tactical.cello()?.partner + { + let amount = k.stat(id, "atk")? * self.ep; + if amount > 0. { + k.elemental(request.hit.target, amount, element::Element::Apoptosis)?; + } + } + } + KitEvent::Scheduled(due) if k.up() => { + let foes = k.enemies(None, true)?; + if due[4] { + for &target in &foes { + let amount = k.stat(id, "atk")? * self.aura_ep; + if amount > 0. { + k.elemental(target, amount, element::Element::Apoptosis)?; + } + if self.sluggish > 0. && Host::tac_up(k.world, target) { + k.status(target, "sluggish", self.sluggish, None)?; + } + } + } + if due[2] { + let boost = self.boost(k)?; + for &target in &foes { + if self.fragile > 0. && k.has(target, "apoptosisBurst") { + k.status(target, "elemFragile", 0.4, Some(self.fragile * boost))?; + } + if self.module_fragile > 0. { + k.status(target, "elemFragile", 0.4, Some(self.module_fragile))?; + } + } + } + } + KitEvent::Tick if self.dot > 0. => { + let now = k.world.time; + let due = { + let state = k.world.unit_mut(id)?.operator.tactical.cello_mut()?; + let at = state.dot.max(self.dot_interval); + if now + 1e-9 >= at { + state.dot = at + self.dot_interval; + true + } else { + false + } + }; + if due && k.up() { + let amount = self.dot * self.boost(k)?; + for target in k.host.spawns.as_ref().unwrap().live().to_vec() { + if Host::tac_up(k.world, target) + && !k.world.unit(target)?.hidden + && k.has(target, "apoptosisBurst") + { + k.element_damage( + target, + amount, + element::Element::Apoptosis, + "elementDmg", + )?; + } + } + } + } + KitEvent::Element { + phase: element::Phase::Hit, + request, + } if request.damage.element == Some(element::Element::Apoptosis) + && k.world.unit(request.damage.hit.target)?.side == health::Side::Enemy => + { + if k.host.tac_leader(k.world, id)? { + let target = request.damage.hit.target; + let mut best = 1.; + for caster in k.host.roster.as_ref().unwrap().ids().to_vec() { + if !Host::tac_up(k.world, caster) { + continue; + } + let def = k.host.tac_def(caster)?; + if let Tactics::Cello(p) = &def.extra.tactics { + let keys = k.host.roster.as_ref().unwrap().range(k.world, caster)?; + if p.wide || body::in_range(k.world.unit(target)?, &keys) { + let boost = k + .world + .unit(caster)? + .operator + .tactical + .cello()? + .boost + .max(1.); + let scale = 1. + (p.amp - 1.) * boost; + if scale > best { + best = scale; + } + } + } + } + request.damage.damage.mul *= best; + } + if request.damage.hit.source == Some(id) + && (k.world.unit(request.damage.hit.target)?.boss + || k.world.unit(request.damage.hit.target)?.targeting.elite) + { + request.damage.damage.mul *= self.elite_mul; + } + } + _ => {} + } + Ok(()) + } +} + +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + Self { + dot: previous.map_or(0., |state| state.dot), + ..Self::default() + } + } +} diff --git a/crates/engine/src/battle/runtime/kits/cetsyr.rs b/crates/engine/src/battle/runtime/kits/cetsyr.rs new file mode 100644 index 0000000..7a0266a --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/cetsyr.rs @@ -0,0 +1,428 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "bard", + ranged: false, + can_hit_fly: false, + physical: false, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_cetsyr_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SP_FULL", + attack_override: false, + }, + Skill { + id: "skchr_cetsyr_1", + kind: Kind::Toggle, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_cetsyr_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SP_FULL", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_cetsyr_1" => Mode::First, + "skchr_cetsyr_2" => Mode::Second, + "skchr_cetsyr_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.combat.profile.no_attack = true; + s.combat.projectile = None; + if mode == Mode::First { + s.rule_override = Some(skills::Rule::SpFull); + } + skill_range(raw, s)?; + if n(t, "cnt", 3.) > 29. { + return Err("Mote capacity exceeded".into()); + } + s.extra.tactics = Tactics::Cetsyr(Cetsyr { + mode: mode, + base_motes: n(t, "cnt", 3.).floor().max(0.) as usize, + mote_radius: n(t, "range_radius", 1.15), + mote_duration: n(t, "talent_duration", 6.), + mote_cooldown: n(t, "cooldown", 6.), + mote_multiplier: n(t, "attack@trait_mul", 1.5), + skill_cooldown: n(bb, "talent_cool_down", 3.), + ratio: n(tb, "attack@atk_to_hp_recovery_ratio", 0.1), + skill_ratio: n( + bb, + "attack@atk_to_hp_recovery_ratio", + n(tb, "attack@atk_to_hp_recovery_ratio", 0.1), + ), + outside: n(bb, "outside_radius", 2.), + mote_damage: n(bb, "atk_scale", 2.2), + bind: n(bb, "unmoveable_duration", 3.), + inspire: n(bb, "attack@atk", 0.65), + hp_inspire: n(bb, "max_hp", 0.65), + redistribute: n(bb, "attack@cetsyr_s_3[cal_hp_ratio].interval", 2.).max(0.5), + cut: n(t1, "damage_resistance", 0.1), + module_atk: n(tm, "atk", 0.), + module_count: n(tm, "cnt", 2.), + base_grid: tactical_grid(&raw["rangeGrid"], false)?, + }); + Ok(()) +} +pub(crate) struct Cetsyr { + pub mode: Mode, + pub base_motes: usize, + pub mote_radius: f64, + pub mote_duration: f64, + pub mote_cooldown: f64, + pub mote_multiplier: f64, + pub skill_cooldown: f64, + pub ratio: f64, + pub skill_ratio: f64, + pub outside: f64, + pub mote_damage: f64, + pub bind: f64, + pub inspire: f64, + pub hp_inspire: f64, + pub redistribute: f64, + pub cut: f64, + pub module_atk: f64, + pub module_count: f64, + pub base_grid: Vec<[i32; 2]>, +} +#[derive(Default)] +pub(crate) struct State { + pub motes: Vec, + pub hit_at: BTreeMap, + pub redistribute: f64, +} + +impl Cetsyr { + fn take_mote(&self, k: &mut KitContext<'_>) -> Result { + let cooldown = if self.mode == Mode::First && k.active()? { + self.skill_cooldown + } else { + self.mote_cooldown + }; + let now = k.world.time; + let state = k.world.unit_mut(k.unit)?.operator.tactical.cetsyr_mut()?; + if let Some(at) = state.motes.iter_mut().find(|at| **at <= now + 1e-9) { + *at = now + cooldown; + Ok(true) + } else { + Ok(false) + } + } +} +impl Behavior for Cetsyr { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + let state = k.world.unit_mut(id)?.operator.tactical.cetsyr_mut()?; + state.redistribute = 0.; + if self.mode == Mode::Second { + state.motes = vec![f64::NEG_INFINITY; self.base_motes + 3]; + state.hit_at.clear(); + } + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id && self.mode != Mode::First => { + let keys = k.keys()?; + let allies = k.allies(&keys)?; + let value = if self.mode == Mode::Third { + k.stat(id, "maxHp")? * self.hp_inspire + } else { + k.stat(id, "atk")? * self.inspire + }; + for &target in &allies { + if target != id { + self.inspire(k, target, value, self.mode == Mode::Third)?; + } + } + if self.mode == Mode::Third { + let due = { + let state = k.world.unit_mut(id)?.operator.tactical.cetsyr_mut()?; + state.redistribute += context.dt; + if state.redistribute + 1e-9 >= self.redistribute { + state.redistribute -= self.redistribute; + true + } else { + false + } + }; + if due { + let mut pool = Vec::new(); + let mut hp = 0.; + let mut maximum = 0.; + for target in allies { + if target != id + && (k.flag(target, "noHeal")? + || k.host.tac_def(target)?.extra.no_heal) + { + continue; + } + let max = k.stat(target, "maxHp")?; + hp += k.world.unit(target)?.stats.hp; + maximum += max; + pool.push((target, max)); + } + if pool.len() > 1 && maximum > 0. { + let ratio = (hp / maximum).min(1.); + for (target, max) in pool { + k.world.unit_mut(target)?.stats.hp = (max * ratio).min(max).max(1.); + } + } + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id && self.mode == Mode::Second => { + let state = k.world.unit_mut(id)?.operator.tactical.cetsyr_mut()?; + state.motes.sort_by(f64::total_cmp); + state.motes.truncate(self.base_motes); + state.hit_at.clear(); + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if k.world.unit(request.hit.target)?.side == health::Side::Ally => { + if let Some(source) = request.hit.source { + if k.world.unit(source)?.side == health::Side::Enemy { + let key = &k.host.spawns.as_ref().unwrap().definition(source)?.key; + let tagged = k + .host + .data + .table("enemies") + .and_then(|v| v.get(key)) + .and_then(|v| v["tags"].as_array()) + .is_some_and(|tags| tags.iter().any(|v| v.as_str() == Some("sarkaz"))); + if tagged { + request.damage.mul *= 1. - self.cut; + } + } + } + } + KitEvent::Scheduled(due) if due[2] && k.up() => { + if k.world + .unit(id)? + .operator + .tactical + .cetsyr()? + .motes + .is_empty() + { + k.world.unit_mut(id)?.operator.tactical.cetsyr_mut()?.motes = + vec![f64::NEG_INFINITY; self.base_motes]; + } + let active = k.active()?; + let keys = k.keys()?; + let attack = k.stat(id, "atk")?; + let ratio = if active && self.mode != Mode::Second { + self.skill_ratio + } else { + self.ratio + }; + for target in k.allies(&keys)? { + let multiplier = if k.has(target, &format!("cetsyr:mote:{id}")) { + self.mote_multiplier + } else { + 1. + }; + k.buff( + target, + &format!("trait:bard:{id}"), + [("hpRegen".into(), attack * ratio * multiplier)].into(), + 0.5, + )?; + } + if active && self.mode == Mode::Second { + let at = k.world.unit(id)?.position; + let now = k.world.time; + let mut targets = k.radius(at, self.outside)?; + targets.sort_unstable(); + for target in targets { + if k.world + .unit(id)? + .operator + .tactical + .cetsyr()? + .hit_at + .get(&target) + .is_some_and(|t| *t > now + 1e-9) + { + continue; + } + if !self.take_mote(k)? { + break; + } + k.world + .unit_mut(id)? + .operator + .tactical + .cetsyr_mut()? + .hit_at + .insert(target, now + 0.5); + k.damage( + target, + attack * self.mote_damage, + DamageType::True, + true, + "mote", + )?; + if k.world.unit(target)?.stats.alive { + k.status(target, "bind", self.bind, None)?; + } + } + } else { + let at = k.world.unit(id)?.position; + for target in k.host.roster.as_ref().unwrap().ids().to_vec() { + if target == id + || !Host::tac_up(k.world, target) + || body::distance(k.world.unit(target)?, at) > self.mote_radius + 1e-9 + || k.has(target, &format!("cetsyr:mote:{id}")) + { + continue; + } + if !(active && self.mode == Mode::Third) && !self.take_mote(k)? { + break; + } + k.buff( + target, + &format!("cetsyr:mote:{id}"), + Numbers::new(), + self.mote_duration, + )?; + } + } + let valid: BTreeSet<_> = k.world.unit_ids().collect(); + k.world + .unit_mut(id)? + .operator + .tactical + .cetsyr_mut()? + .hit_at + .retain(|target, _| valid.contains(target)); + } + _ => {} + } + // The bard's regeneration timer is registered before the module poll. + if let KitEvent::Scheduled(due) = event { + if due[1] && k.up() { + if self.module_atk != 0. { + let base = k.range(&self.base_grid)?; + let count = k + .allies(&base)? + .into_iter() + .filter(|&target| target != id) + .count(); + if count as f64 >= self.module_count { + k.buff( + id, + "cetsyr:module", + [("atkPct".into(), self.module_atk)].into(), + f64::INFINITY, + )?; + } else { + k.remove(id, "cetsyr:module")?; + } + } + } + } + Ok(()) + } +} + +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + let mut state = Self::default(); + if let Some(previous) = previous { + state.motes = previous.motes.clone(); + } + state + } +} + +impl Cetsyr { + fn inspire( + &self, + k: &mut KitContext<'_>, + target: Id, + value: f64, + hp: bool, + ) -> Result<(), String> { + if !(value > 0.) + || !k.world.unit(target)?.stats.alive + || matches!( + k.host.tac_def(target)?.extra.tactics, + Tactics::Cetsyr(_) | Tactics::Skadi2(_) + ) + { + return Ok(()); + } + let key = if hp { "inspire:hp" } else { "inspire" }; + if let Some(old) = k + .world + .unit(target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some(key)) + { + if old.runtime.source != Some(k.unit) + && old.runtime.tick_payload > value + && old.runtime.time_left > 1e-6 + { + return Ok(()); + } + } + let modifiers = crate::battle::stats::Modifiers::aggregate_except( + k.world.unit(target)?.stats.buffs(), + key, + ) + .map_err(str::to_string)?; + let (pct, mul, flat) = if hp { + ("hpPct", "hpMul", "hpFlat") + } else { + ("atkPct", "atkMul", "atkFlat") + }; + let factor = (1. + modifiers.add.get(pct).copied().unwrap_or(0.)).max(0.) + * modifiers.mul.get(mul).copied().unwrap_or(1.); + let amount = if factor > 1e-6 { value / factor } else { value }; + let mut buff = Buff { + key: Some(key.into()), + mods: [(flat.into(), amount)].into(), + ..Default::default() + }; + buff.runtime.duration = 0.25; + buff.runtime.tick_payload = value; + k.add(target, buff).map(|_| ()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/clemnt.rs b/crates/engine/src/battle/runtime/kits/clemnt.rs new file mode 100644 index 0000000..a133128 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/clemnt.rs @@ -0,0 +1,306 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{element, skills::SpType, sp::Kind}; + +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "primguard", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_clemnt_3", + kind: Kind::Ammo, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + skill_range(raw, s)?; + let mut profile = s.combat.profile; + profile.max_targets = n(bb, "attack@max_target", 3.); + s.combat.skill_profile = Some(profile); + s.extra.effects.ammo_count = n(bb, "trigger_time", 10.); + s.combat.skill_scale = n(bb, "attack@atk_scale", 1.); + s.extra.tactics = Tactics::Clemnt(Clemnt { + crit: n(t, "prob_normal", 0.), + crit_debuffed: n(t, "prob_special", 0.), + crit_scale: n(t, "t1_atk_scale", 1.), + resistance: n(t1, "damage_resistance_normal", 0.), + sea_resistance: n(t1, "damage_resistance_seamonster", 0.), + rider: n(bb, "attack@ep_damage_ratio", 0.), + mark_life: n(bb, "ep_break_duration", 1.), + tile_life: n(bb, "projectile_life_time", 5.), + bomb_scale: n(bb, "s3_atk_scale", 1.), + element_scale: n(bb, "ep_damage_scale", 0.), + }); + Ok(()) +} +pub(crate) struct Clemnt { + crit: f64, + crit_debuffed: f64, + crit_scale: f64, + resistance: f64, + sea_resistance: f64, + rider: f64, + mark_life: f64, + tile_life: f64, + bomb_scale: f64, + element_scale: f64, +} +#[derive(Default)] +pub(crate) struct State { + marks: Vec<(Id, f64)>, + tiles: BTreeMap<[i32; 2], f64>, +} +impl Clemnt { + fn ground(k: &mut KitContext<'_>, target: Id) -> Result { + targeting::can_target_enemy( + k.world, + k.host, + Some(k.unit), + target, + targeting::Profile { + ground_only: true, + ..Default::default() + }, + ) + } + fn bombard(k: &mut KitContext<'_>, position: [f64; 2], attack: f64) -> Result<(), String> { + let def = k.host.tac_def(k.unit)?; + let Tactics::Clemnt(c) = &def.extra.tactics else { + return Err("Invalid Clement bombardment".into()); + }; + let tile = [position[0] as i32, position[1] as i32]; + let grid = [[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1]]; + let keys = targeting::absolute_range(&grid, tile, Direction::Right, 0); + for target in k.host.spawns.as_ref().unwrap().live().to_vec() { + if !Self::ground(k, target)? || !body::in_range(k.world.unit(target)?, &keys) { + continue; + } + for (kind, scale, element) in [ + (DamageType::Physical, c.bomb_scale, None), + ( + DamageType::Elemental, + c.element_scale, + Some(element::Element::Erosion), + ), + ] { + if !k.world.unit(target)?.stats.alive || k.world.unit(target)?.stats.hp <= 0. { + break; + } + let mut request = hit::Request::new( + health::Hit { + source: Some(k.unit), + credit: Some(k.unit), + target, + damage_type: kind, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount: attack * scale, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.is_skill = true; + request.element = element; + request.dodge_mode = injury::DodgeMode::Ignore; + request.tags = vec!["skill".into(), "clemnt:bomb".into()]; + k.deal(&mut request)?; + } + } + Ok(()) + } +} +impl Behavior for Clemnt { + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + match event { + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if role == Role::Source + && request.hit.damage_type == DamageType::Physical + && k.world.unit(request.hit.target)?.side == health::Side::Enemy => + { + let defence = k.stat(request.hit.target, "def")?; + let base = k.world.unit(request.hit.target)?.stats.base_number("def"); + if k.host.rng.next_f64() + < if defence < base { + self.crit_debuffed + } else { + self.crit + } + { + request.damage.amount *= self.crit_scale; + } + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if role == Role::Target + && matches!( + request.hit.damage_type, + DamageType::Physical | DamageType::Arts + ) => + { + if let Some(source) = request.hit.source { + let at = k.world.unit(source)?.position; + let home = k.world.unit(k.unit)?.deployment.home; + let dir = k.host.roster.as_ref().unwrap().entry(k.unit)?.direction; + let [dr, dc] = dir.vector(); + if k.world.unit(source)?.blocked_by() == Some(k.unit) + || (at[0].round() - home[0] as f64) * dr as f64 + + (at[1].round() - home[1] as f64) * dc as f64 + >= 0. + { + let sea = k + .host + .spawns + .as_ref() + .unwrap() + .definition(source) + .is_ok_and(|d| { + k.host.data.table("enemies").unwrap()[&d.key]["tags"] + .as_array() + .is_some_and(|a| a.iter().any(|s| s == "seamonster")) + }); + request.damage.mul *= 1. + - if sea { + self.sea_resistance + } else { + self.resistance + }; + } + } + } + KitEvent::Landed { event, request } + if role == Role::Source + && request.is_attack + && request.is_skill + && event.amount > 0. + && k.world.unit(request.hit.target)?.stats.hp > 0. => + { + k.elemental( + request.hit.target, + event.amount * self.rider, + element::Element::Erosion, + )?; + } + _ => {} + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Attack { context, .. } if context.attacker == id => context.no_ammo = true, + KitEvent::Skill { + event: skills::Event::Start | skills::Event::End, + .. + } => { + let state = k.world.unit_mut(id)?.operator.tactical.clemnt_mut()?; + state.marks.clear(); + state.tiles.clear(); + } + KitEvent::Element { + phase: element::Phase::Burst, + request, + } if request.damage.element == Some(element::Element::Erosion) + && k.up() + && k.active()? + && Self::ground(k, request.damage.hit.target)? => + { + let until = k.world.time + self.mark_life; + let state = k.world.unit_mut(id)?.operator.tactical.clemnt_mut()?; + if let Some(mark) = state + .marks + .iter_mut() + .find(|m| m.0 == request.damage.hit.target) + { + mark.1 = until; + } else { + state.marks.push((request.damage.hit.target, until)); + } + } + KitEvent::Skill { + event: skills::Event::Tick, + skill, + .. + } if k.up() && skills::can_act(k.world, id)? => { + let now = k.world.time; + let mut marks = k.world.unit(id)?.operator.tactical.clemnt()?.marks.clone(); + marks.retain(|(target, until)| { + *until >= now - 1e-9 + && k.world + .unit(*target) + .is_ok_and(|u| u.stats.alive && !u.hidden) + }); + k.world + .unit_mut(id)? + .operator + .tactical + .clemnt_mut()? + .marks + .clone_from(&marks); + let pos = k.world.unit(id)?.position; + marks.sort_by(|a, b| { + let dist = |target| { + let at = k.world.unit(target).unwrap().position; + (at[0] - pos[0]).powi(2) + (at[1] - pos[1]).powi(2) + }; + dist(a.0).total_cmp(&dist(b.0)).then_with(|| a.0.cmp(&b.0)) + }); + for (target, _) in marks { + if !Self::ground(k, target)? { + continue; + } + let at = k.world.unit(target)?.position; + let tile = [(at[0] + 0.5).floor() as i32, (at[1] + 0.5).floor() as i32]; + let state = k.world.unit_mut(id)?.operator.tactical.clemnt_mut()?; + if state.tiles.get(&tile).is_some_and(|end| *end > now) { + continue; + } + state.tiles.retain(|_, end| *end > now); + state.tiles.insert(tile, now + self.tile_life); + state.marks.retain(|m| m.0 != target); + let attack = k.stat(id, "atk")?; + for n in 0..3 { + k.later_at( + 0.5 + n as f64, + [tile[0] as f64, tile[1] as f64], + attack, + true, + Self::bombard, + )?; + } + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + skill.consume_ammo(world, host) + })?; + break; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/demkni.rs b/crates/engine/src/battle/runtime/kits/demkni.rs new file mode 100644 index 0000000..47c5d01 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/demkni.rs @@ -0,0 +1,321 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "guardian", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_demkni_2", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_demkni_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_demkni_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = tactical_mode(raw)?; + + if mode == Mode::First { + skill_healing(s, 1., n(bb, "heal_scale", 1.)); + let p = s.combat.skill_profile.as_mut().unwrap(); + p.heal.as_mut().unwrap().hp_at_most = 0.5; + s.extra.skill_range = Some(tactical_grid(&raw["skill"]["rangeGrid"], true)?); + } + if mode == Mode::Second { + s.rule_override = Some(crate::battle::skills::Rule::Never); + } + s.extra.support.heal_bonus = Some(HealBonus { + below: n(tb, "hp_ratio", 0.), + scale: n(tb, "heal_scale", 1.), + inclusive: false, + }); + if n(tb, "damage_resistance", 0.) > 0. { + s.extra.effects.permanent.push(persistent( + "saria:moduleY", + [("dmgTakenMul".into(), 1. - n(tb, "damage_resistance", 0.))].into(), + )); + } + s.extra.tactics = Tactics::Demkni(Demkni { + mode, + grid: tactical_grid(&raw["skill"]["rangeGrid"], false)?, + heal: n(bb, "heal_scale", n(bb, "attack@heal_scale", 0.)), + slow: n(bb, "demkni_s_3.move_speed", 0.), + arts: n(bb, "demkni_s_3.damage_scale", 1.), + interval: n(t, "interval", 20.), + stacks: n(t, "max_stack_cnt", 5.).max(1.) as u32, + attack: n(t, "atk", 0.), + defence: n(t, "def", 0.), + sp: n(t1, "sp", 0.), + }); + Ok(()) +} + +pub(crate) struct Demkni { + pub mode: Mode, + pub grid: Vec<[i32; 2]>, + pub heal: f64, + pub slow: f64, + pub arts: f64, + pub interval: f64, + pub stacks: u32, + pub attack: f64, + pub defence: f64, + pub sp: f64, +} + +#[derive(Default)] +pub(crate) struct State { + pub aura: f64, + pub accumulator: f64, +} + +impl Host { + pub(in crate::battle::runtime) fn demkni_start( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Demkni, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.demkni_mut()?.aura = 0.25; + w.unit_mut(id)?.operator.tactical.demkni_mut()?.accumulator = 0.; + if p.mode == Mode::Second { + let keys = self.tac_keys(w, id, &p.grid)?; + let amount = Self::tac_stat(w, id, "atk")? * p.heal; + for a in self.tac_heal_targets_in_order(w, id, &keys, true)? { + self.tac_heal(w, r, id, a, amount)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn demkni_skill_tick( + &mut self, + dt: f64, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Demkni, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.demkni_mut()?.aura += dt; + w.unit_mut(id)?.operator.tactical.demkni_mut()?.accumulator += dt; + if p.mode == Mode::Third { + let keys = self.tac_keys(w, id, &p.grid)?; + if w.unit(id)?.operator.tactical.demkni()?.aura >= 0.25 - 1e-9 { + w.unit_mut(id)?.operator.tactical.demkni_mut()?.aura = 0.; + let ids = self.spawns.as_ref().unwrap().live().to_vec(); + for a in ids { + if Self::tac_up(w, a) && body::in_range(w.unit(a)?, &keys) { + self.component_buff( + w, + r, + a, + "saria:calcify", + [ + ("artsTakenMul".into(), p.arts), + ("moveMul".into(), (1. + p.slow).max(0.)), + ] + .into(), + 0.5, + id, + )?; + } + } + } + if w.unit(id)?.operator.tactical.demkni()?.accumulator >= 1. - 1e-9 { + w.unit_mut(id)?.operator.tactical.demkni_mut()?.accumulator -= 1.; + let amount = Self::tac_stat(w, id, "atk")? * p.heal; + for a in self.tac_heal_targets_in_order(w, id, &keys, true)? { + self.tac_heal(w, r, id, a, amount)?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn demkni_scheduled( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + due: [bool; 5], + p: &Demkni, + ) -> Result<(), String> { + if due[4] { + let n = ((w.time - w.unit(id)?.deployment.deployed_at + 1e-6) / p.interval.max(1.)) + .floor() + .max(0.) as u32; + let n = n.min(p.stacks); + if n > 0 { + let old = w + .unit(id)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("saria:suit")) + .map(|b| b.stacks); + if old != Some(n) { + let mut b = Buff { + key: Some("saria:suit".into()), + stacks: n, + mods: [("atkPct".into(), p.attack), ("defPct".into(), p.defence)].into(), + ..Default::default() + }; + b.runtime.max_stacks = p.stacks; + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn demkni_heal_event( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + e: &health::Event, + p: &Demkni, + ) -> Result<(), String> { + if e.kind != health::Kind::Regen && e.amount > 0. { + self.advanced_grant_sp(w, r, e.target, p.sp)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn demkni_tick( + &mut self, + w: &mut World, + id: Id, + s: &mut skills::Runtime, + p: &Demkni, + ) -> Result<(), String> { + if s.bank.ready() + && skills::can_act(w, id)? + && !Self::tac_has(w, id, "silence") + && w.time - s.last_start >= Self::tac_stat(w, id, "interval")? - 1e-9 + { + let keys = self.tac_keys(w, id, &p.grid)?; + if !self.tac_heal_targets(w, id, &keys, true)?.is_empty() { + s.activate(w, self, "DEFAULT", false)?; + } + } + Ok(()) + } +} + +impl Behavior for Demkni { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::Scheduled(_)) + } + fn refreshes_skill(&self) -> bool { + self.mode == Mode::Second + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + match (role, event) { + (Role::Source, KitEvent::Heal { event, .. }) => { + k.host.demkni_heal_event(k.world, k.buffs, event, self)?; + } + _ => {} + } + Ok(()) + } + fn condition( + &self, + host: &Host, + world: &mut World, + unit: Id, + condition: skills::Condition, + ) -> Result, String> { + if self.mode == Mode::First + && matches!( + condition, + skills::Condition::Default + | skills::Condition::Allies + | skills::Condition::TickRule + ) + { + let keys = host.tac_keys(world, unit, &self.grid)?; + for target in host.tac_heal_targets(world, unit, &keys, true)? { + if world.unit(target)?.stats.hp / Host::tac_stat(world, target, "maxHp")? + <= 0.5 + 1e-9 + { + return Ok(Some(true)); + } + } + return Ok(Some(false)); + } + Ok(None) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Scheduled(due) => { + if k.up() { + k.host.demkni_scheduled(k.world, id, k.buffs, *due, self)?; + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.demkni_start(k.world, id, k.buffs, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id => { + k.host + .demkni_skill_tick(context.dt, k.world, id, k.buffs, self)?; + } + KitEvent::Refresh { skill, .. } => { + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + host.demkni_tick(world, id, skill, self) + })?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/dispatch.rs b/crates/engine/src/battle/runtime/kits/dispatch.rs new file mode 100644 index 0000000..8b05187 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/dispatch.rs @@ -0,0 +1,1016 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Typed Kit callbacks and bounded access to the canonical battle mechanisms. +use super::*; +use crate::battle::{element, status}; +mod context; +pub(crate) use context::Context; + +/// Identifies the actor that caused or received a combat event. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Role { + Source, + Target, +} + +pub(crate) enum Event<'a> { + BattleStart, + /// Initialization uses dt = 0, and frame refresh uses the simulation step. + Refresh { + skill: &'a mut skills::Runtime, + dt: f64, + }, + /// The deferred callback's skill has been restored to the roster. + Restored(skills::Event), + /// Reconcile effects after draining the deferred lifecycle queue. + Flush, + Resume { + unit: Id, + skill: &'a mut skills::Runtime, + }, + Skill { + unit: Id, + event: skills::Event, + context: &'a mut skills::Context, + skill: &'a mut skills::Runtime, + }, + SkillObserved { + unit: Id, + event: skills::Event, + skill: &'a mut skills::Runtime, + }, + Scheduled([bool; 5]), + /// Emitted once per simulation step by clock::Phase::TickHook. + Tick, + Before(&'a mut attacks::Context), + Attack { + context: &'a mut attacks::Context, + skill: Option<&'a mut skills::Runtime>, + }, + /// Attack observers have run, and the skill has yet to consume ammunition. + AttackFinished { + context: &'a attacks::Context, + skill: Option<&'a mut skills::Runtime>, + }, + Impact(attacks::Impact), + Hit { + phase: hit::Phase, + request: &'a mut hit::Request, + }, + Landed { + event: &'a health::Event, + request: &'a hit::Request, + }, + Heal { + event: &'a health::Event, + options: health::HealOptions, + }, + Fatal(&'a mut health::Event), + DamageApplied { + event: &'a health::Event, + request: &'a hit::Request, + }, + ProjectileStep { + id: u64, + source: Option, + position: [f64; 2], + speed: f64, + removable: bool, + cancelled: &'a mut bool, + }, + Element { + phase: element::Phase, + request: &'a mut element::Request, + }, + ElementLate(&'a mut element::Request), + BeforeStatus(&'a mut status::Context), + Status(&'a status::Context), + /// Status reactions have completed, before advanced support reactions. + StatusFinished(&'a status::Context), + /// Enemy kill, before removal; callbacks may reenter damage. + Kill { + victim: Id, + }, + Death { + unit: Id, + credit: Option, + }, + Buff { + context: buffs::Context, + event: buffs::Event, + token: u64, + }, +} + +impl Event<'_> { + pub(super) fn is_lifecycle(&self) -> bool { + matches!( + self, + Self::Skill { .. } + | Self::Resume { .. } + | Self::Refresh { .. } + | Self::Restored(_) + | Self::Flush + ) + } +} + +pub(crate) trait Behavior { + fn can_activate(&self, _host: &Host, _world: &mut World, _unit: Id) -> Result { + Ok(true) + } + fn condition( + &self, + _host: &Host, + _world: &mut World, + _unit: Id, + _condition: skills::Condition, + ) -> Result, String> { + Ok(None) + } + fn sp_gain(&self, _host: &Host, _unit: Id, _context: &mut skills::Context) {} + fn observe_injury( + &self, + _context: &mut settlement::Context<'_, Host>, + _key: &str, + _buff: &Buff, + ) -> Result<(), String> { + Ok(()) + } + fn heal_amount( + &self, + _world: &World, + _unit: Id, + _target: Id, + amount: f64, + _options: health::HealOptions, + ) -> Result { + Ok(amount) + } + /// Deliver a combat callback to its source or target Kit. + fn handle_unit( + &self, + _context: &mut Context<'_>, + _role: Role, + _event: &mut Event<'_>, + ) -> Result<(), String> { + Ok(()) + } + fn attack_heal( + &self, + _world: &World, + _unit: Id, + _target: Id, + amount: f64, + ) -> Result { + Ok(amount) + } + fn observes(&self, event: &Event<'_>) -> bool { + !matches!( + event, + Event::AttackFinished { .. } | Event::StatusFinished(_) + ) + } + fn refreshes_skill(&self) -> bool { + false + } + fn priority(&self, _event: &Event<'_>, _world: &World, _unit: Id) -> i32 { + 0 + } + fn handle(&self, context: &mut Context<'_>, event: &mut Event<'_>) -> Result<(), String>; + fn profile( + &self, + _world: &World, + _unit: Id, + _skill: Option<&skills::Runtime>, + _profile: &mut search::AttackProfile, + ) -> Result<(), String> { + Ok(()) + } + fn payload( + &self, + _world: &World, + _unit: Id, + _payload: &mut attacks::Direct, + _area: &mut attacks::Area, + ) -> Result<(), String> { + Ok(()) + } + fn reaper_eligible(&self, _request: &hit::Request) -> bool { + true + } + fn reaper_multiplier(&self, _world: &World, _unit: Id) -> Result { + Ok(1.) + } + fn heal_multiplier(&self, _world: &World, _target: Id) -> Result { + Ok(1.) + } + fn can_attack(&self, _host: &Host, _world: &World, _unit: Id) -> Result { + Ok(true) + } + fn enemy_filter(&self) -> Option { + None + } +} + +impl Host { + pub(in crate::battle::runtime) fn kit_event( + &mut self, + world: &mut World, + buffs: &mut buffs::Runtime, + event: &mut Event<'_>, + ) -> Result<(), String> { + let Some(roster) = self.roster.as_ref() else { + return Ok(()); + }; + enum Observer { + Kit(Id, Arc), + HeldUndying, + HammerLock, + Chivalry, + Cocoon, + Egir, + Indom(Option), + GrowthDeath, + DeathTarget(Id), + } + let mut handlers = Vec::new(); + if let Event::Death { unit, .. } = event { + let u = world.unit(*unit)?; + if u.has_operator_kit() { + // Capture the departing unit's effects before any revival. + handlers.push((20, Observer::DeathTarget(*unit))); + } + if u.side == health::Side::Ally + && u.deployment.remove_reason.as_deref() == Some("killed") + { + handlers.push((0, Observer::GrowthDeath)); + } + } + for (unit, def) in roster.kit_observers(matches!(event, Event::Tick)) { + let unit = *unit; + if let Some(kit) = def.extra.tactics.behavior() { + if !kit.observes(event) { + continue; + } + let priority = kit.priority(event, world, unit); + handlers.push((priority, Observer::Kit(unit, Arc::clone(def)))); + } + } + if matches!(event, Event::Fatal(_)) + && self + .equipment + .units + .values() + .any(|loadout| loadout.hammers.is_some()) + { + handlers.push((-99, Observer::HeldUndying)); + handlers.push((-100, Observer::HammerLock)); + } + if matches!(event, Event::Fatal(_)) { + handlers.push((20, Observer::Chivalry)); + } + if let Event::Death { unit, .. } = event { + handlers.push((13, Observer::Cocoon)); + handlers.push((11, Observer::Egir)); + handlers.push(( + 10, + Observer::Indom(world.unit(*unit)?.deployment.remove_reason.clone()), + )); + } + handlers.sort_by(|a, b| b.0.cmp(&a.0)); + for (_, observer) in handlers { + match observer { + Observer::Chivalry => { + if let Event::Fatal(e) = event { + self.chivalry_fatal(e)?; + } + } + Observer::Egir => { + if let Event::Death { unit, .. } = event { + self.egir_death(world, buffs, *unit)?; + } + } + Observer::Cocoon => { + if let Event::Death { unit, .. } = event { + self.equipment_death(world, buffs, *unit)?; + } + } + Observer::DeathTarget(unit) => { + self.kit_unit_event(world, buffs, unit, Role::Target, event)?; + } + Observer::GrowthDeath => { + if let Event::Death { unit, credit } = event { + self.growth_death(world, *unit, *credit)?; + } + } + Observer::Indom(reason) => { + if let Event::Death { unit, .. } = event { + self.bond_indom_death(world, buffs, *unit, reason.as_deref())?; + } + } + Observer::HeldUndying => { + if let Event::Fatal(e) = event { + if !e.prevented && self.holds_undying(world, e.target)? { + e.prevented = true; + } + } + } + Observer::HammerLock => { + if let Event::Fatal(e) = event { + self.hammer_fatal(world, e)?; + } + } + Observer::Kit(unit, def) => def.extra.tactics.behavior().unwrap().handle( + &mut Context { + host: self, + world, + buffs, + unit, + }, + event, + )?, + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn kit_event_for( + &mut self, + world: &mut World, + buffs: &mut buffs::Runtime, + unit: Id, + event: &mut Event<'_>, + ) -> Result<(), String> { + let def = self.tac_def(unit)?; + if let Some(behavior) = def + .extra + .tactics + .behavior() + .filter(|kit| kit.observes(event)) + { + behavior.handle( + &mut Context { + host: self, + world, + buffs, + unit, + }, + event, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn kit_event_with_buffs( + &mut self, + world: &mut World, + event: &mut Event<'_>, + ) -> Result<(), String> { + let mut buffs = self.buffs.take().ok_or("Missing Kit buff context")?; + let result = self.kit_event(world, &mut buffs, event); + self.buffs = Some(buffs); + result + } +} + +pub(in crate::battle::runtime) struct DeferredEvent { + pub unit: Id, + pub deployment: u64, + pub event: skills::Event, + pub context: skills::Context, +} +impl Host { + pub(in crate::battle::runtime) fn kit_skill_event( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + _def: &Definition, + event: skills::Event, + c: &mut skills::Context, + s: &mut skills::Runtime, + ) -> Result<(), String> { + let id = s.unit(); + if self.roster.is_none() { + if matches!( + event, + skills::Event::Deploy + | skills::Event::Start + | skills::Event::SkillStart + | skills::Event::End + | skills::Event::SkillEnd + | skills::Event::AmmoUsed + ) { + if self.deferred_kit_events.len() >= self.kit_event_limit { + return Err("Deferred kit event capacity exceeded".into()); + } + self.deferred_kit_events.push_back(DeferredEvent { + unit: id, + deployment: w.unit(id)?.deployment.deploy_seq, + event, + context: c.clone(), + }); + } + return Ok(()); + } + self.kit_event_for( + w, + r, + id, + &mut Event::Skill { + unit: id, + event, + context: c, + skill: s, + }, + )?; + if matches!( + event, + skills::Event::Deploy + | skills::Event::SkillStart + | skills::Event::AmmoUsed + | skills::Event::SkillEnd + ) { + self.kit_event( + w, + r, + &mut Event::SkillObserved { + unit: id, + event, + skill: s, + }, + )?; + } + self.bonds_skill(w, r, event, c, s)?; + self.growth_skill(w, id, event)?; + + self.equipment_skill(w, r, event, c, s)?; + if event == skills::Event::Deploy + && w.unit(id)?.deployment.kind == crate::battle::deploy::Kind::Operator + { + self.last_operator = Some(id); + } + + Ok(()) + } + pub(in crate::battle::runtime) fn flush_kit_events( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + if self.roster.is_none() || self.flushing_kit_events { + return Ok(()); + } + self.flushing_kit_events = true; + let result = (|| { + while let Some(pending) = self.deferred_kit_events.front() { + let id = pending.unit; + // A nested callback may still own this skill. Its enclosing entry point flushes again. + if self.roster.as_ref().unwrap().entry(id)?.skill().is_err() { + break; + } + let mut pending = self.deferred_kit_events.pop_front().unwrap(); + if w.unit(id)?.deployment.deploy_seq != pending.deployment + || (pending.event != skills::Event::End && !Self::tac_up(w, id)) + { + continue; + } + let def = self.tac_def(id)?; + let mut skill = self.roster.as_mut().unwrap().take_skill(id)?; + let result = self.kit_skill_event( + w, + r, + &def, + pending.event, + &mut pending.context, + &mut skill, + ); + let restore = self.roster.as_mut().unwrap().restore_skill(id, skill); + result.and(restore)?; + self.kit_event_for(w, r, id, &mut Event::Restored(pending.event))?; + } + for id in self.roster.as_ref().unwrap().ids().to_vec() { + self.kit_event_for(w, r, id, &mut Event::Flush)?; + } + self.growth_flush_onstart(w, r)?; + self.bonds_flush(w, r)?; + Ok(()) + })(); + self.flushing_kit_events = false; + result + } + pub(in crate::battle::runtime) fn with_kit_buffs( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + f: impl FnOnce(&mut Self, &mut World) -> Result, + ) -> Result { + if self.buffs.is_some() { + return Err("Kit callback already owns buffs".into()); + } + self.buffs = Some(std::mem::replace(r, buffs::Runtime::new(1, 1, 1)?)); + let result = f(self, w); + *r = self.buffs.take().ok_or("Kit callback lost buffs")?; + result + } + pub(in crate::battle::runtime) fn resume_kit_skill( + &mut self, + world: &mut World, + skill: &mut skills::Runtime, + ) -> Result<(), String> { + let id = skill.unit(); + let def = self.tac_def(id)?; + if def.extra.tactics.behavior().is_some() { + let mut buffs = self.buffs.take().ok_or("Missing resumed Kit buffs")?; + let result = self.kit_event_for( + world, + &mut buffs, + id, + &mut kits::dispatch::Event::Resume { unit: id, skill }, + ); + self.buffs = Some(buffs); + result?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn kit_profile( + &self, + w: &World, + id: Id, + skill: Option<&skills::Runtime>, + p: &mut search::AttackProfile, + ) -> Result<(), String> { + let def = self.tac_def(id)?; + if let Some(kit) = def.extra.tactics.behavior() { + kit.profile(w, id, skill, p)?; + } + + Ok(()) + } + pub(in crate::battle::runtime) fn kit_payload( + &self, + w: &World, + id: Id, + p: &mut attacks::Direct, + area: &mut attacks::Area, + ) -> Result<(), String> { + let def = self.tac_def(id)?; + if let Some(kit) = def.extra.tactics.behavior() { + kit.payload(w, id, p, area)?; + } + + Ok(()) + } + pub(in crate::battle::runtime) fn refresh_kit_effects( + &mut self, + w: &mut World, + dt: f64, + ) -> Result<(), String> { + self.refresh_component_conditions(w)?; + self.refresh_support_casts(w)?; + for timer in &mut self.tactical_timers { + if let Task::Explosion { + target, position, .. + } = &mut timer.kind + { + if let Ok(unit) = w.unit(*target) { + *position = unit.position; + } + } + } + for id in self.roster.as_ref().unwrap().ids().to_vec() { + if !Self::tac_up(w, id) { + continue; + } + let def = self.tac_def(id)?; + if !def + .extra + .tactics + .behavior() + .is_some_and(|kit| kit.refreshes_skill()) + { + continue; + } + let mut buffs = self.buffs.take().ok_or("Missing Kit refresh buffs")?; + let mut skill = match self.roster.as_mut().unwrap().take_skill(id) { + Ok(skill) => skill, + Err(error) => { + self.buffs = Some(buffs); + return Err(error); + } + }; + let result = self.kit_event_for( + w, + &mut buffs, + id, + &mut Event::Refresh { + skill: &mut skill, + dt, + }, + ); + self.buffs = Some(buffs); + let result = result.and_then(|_| self.support_flush_sp(w, &mut skill)); + let restored = self.roster.as_mut().unwrap().restore_skill(id, skill); + result.and(restored)?; + } + Ok(()) + } +} + +impl Host { + pub(in crate::battle::runtime) fn dispatch_scheduled_kits( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let ids: Vec<_> = self + .roster + .as_ref() + .unwrap() + .kit_observers(false) + .iter() + .map(|(id, _)| *id) + .collect(); + for id in ids { + let mut due = [false; 5]; + for (i, iv) in [0.1, 0.2, 0.25, 0.5, 1.].into_iter().enumerate() { + let at = w.unit(id)?.operator.tactical.next[i].max(iv); + if w.time + 1e-9 >= at { + due[i] = true; + w.unit_mut(id)?.operator.tactical.next[i] = at + iv; + } + } + self.kit_event_for(w, r, id, &mut Event::Scheduled(due))?; + } + Ok(()) + } +} + +impl Host { + pub(in crate::battle::runtime) fn kit_unit_event( + &mut self, + world: &mut World, + buffs: &mut buffs::Runtime, + unit: Id, + role: Role, + event: &mut Event<'_>, + ) -> Result<(), String> { + if self.roster.is_none() + || world.unit(unit)?.side != health::Side::Ally + || world.unit(unit)?.deployment.kind == crate::battle::deploy::Kind::Device + { + return Ok(()); + } + let definition = self.tac_def(unit)?; + if let Some(kit) = definition.extra.tactics.behavior() { + kit.handle_unit( + &mut Context { + host: self, + world, + buffs, + unit, + }, + role, + event, + )?; + } + Ok(()) + } +} + +impl Host { + pub(in crate::battle::runtime) fn kit_before( + &mut self, + w: &mut World, + c: &mut attacks::Context, + ) -> Result<(), String> { + let mut r = self + .buffs + .take() + .ok_or("Missing attack preparation buffs")?; + let result = (|| { + self.kit_event(w, &mut r, &mut Event::Before(c))?; + self.kit_unit_event(w, &mut r, c.attacker, Role::Source, &mut Event::Before(c)) + })(); + self.buffs = Some(r); + result + } + pub(in crate::battle::runtime) fn kit_attack( + &mut self, + w: &mut World, + c: &mut attacks::Context, + mut skill: Option<&mut skills::Runtime>, + ) -> Result<(), String> { + let mut r = self.buffs.take().ok_or("Missing attack callback buffs")?; + let result = (|| { + self.kit_unit_event( + w, + &mut r, + c.attacker, + Role::Source, + &mut Event::Attack { + context: c, + skill: skill.as_deref_mut(), + }, + )?; + self.kit_event( + w, + &mut r, + &mut Event::Attack { + context: c, + skill: skill.as_deref_mut(), + }, + )?; + self.kit_event(w, &mut r, &mut Event::AttackFinished { context: c, skill }) + })(); + self.buffs = Some(r); + result + } + pub(in crate::battle::runtime) fn kit_impact( + &mut self, + w: &mut World, + impact: attacks::Impact, + ) -> Result<(), String> { + if impact.target.is_none() { + return Ok(()); + } + let mut r = self.buffs.take().ok_or("Missing impact callback buffs")?; + let result = (|| { + self.kit_event(w, &mut r, &mut Event::Impact(impact))?; + self.kit_unit_event( + w, + &mut r, + impact.attacker, + Role::Source, + &mut Event::Impact(impact), + ) + })(); + self.buffs = Some(r); + result + } + pub(in crate::battle::runtime) fn kit_heal_event( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + e: &health::Event, + options: health::HealOptions, + ) -> Result<(), String> { + let mut event = Event::Heal { event: e, options }; + self.kit_event(w, r, &mut event)?; + let source = match e.source { + Some(source) if self.roster.is_some() && w.unit(source)?.side == health::Side::Ally => { + Some(source) + } + _ => None, + }; + let after_items = if let Some(source) = source { + self.tac_def(source)? + .extra + .tactics + .behavior() + .is_some_and(|behavior| behavior.priority(&event, w, source) < 0) + } else { + false + }; + if after_items { + self.equipment_heal(w, r, e, options)?; + } + if let Some(source) = source { + self.kit_unit_event(w, r, source, Role::Source, &mut event)?; + } + if !after_items { + self.equipment_heal(w, r, e, options)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn kit_hit_phase( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + phase: hit::Phase, + request: &mut hit::Request, + ) -> Result<(), String> { + // Broadcast reactions precede effect synchronization and target/source callbacks. + self.kit_event(w, r, &mut Event::Hit { phase, request })?; + if self.roster.is_none() { + return Ok(()); + } + if phase == hit::Phase::Hit { + self.tactical_sync_zones(w, r)?; + self.tactical_sync_injury(w, r)?; + self.kit_unit_event( + w, + r, + request.hit.target, + Role::Target, + &mut Event::Hit { phase, request }, + )?; + } + if let Some(source) = request.hit.source { + self.kit_unit_event( + w, + r, + source, + Role::Source, + &mut Event::Hit { phase, request }, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn kit_landed( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + event: &health::Event, + request: &hit::Request, + ) -> Result<(), String> { + self.kit_event(w, r, &mut Event::Landed { event, request })?; + if let Some(source) = request.hit.source { + self.kit_unit_event( + w, + r, + source, + Role::Source, + &mut Event::Landed { event, request }, + )?; + } + self.kit_unit_event( + w, + r, + event.target, + Role::Target, + &mut Event::Landed { event, request }, + ) + } + pub(in crate::battle::runtime) fn kit_kill( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + victim: Id, + credit: Option, + ) -> Result<(), String> { + if let Some(source) = credit { + self.kit_unit_event(w, r, source, Role::Source, &mut Event::Kill { victim })?; + } + self.kit_event(w, r, &mut Event::Kill { victim }) + } + pub(in crate::battle::runtime) fn kit_attack_heal( + &self, + world: &World, + unit: Id, + target: Id, + amount: f64, + ) -> Result { + let definition = self.tac_def(unit)?; + match definition.extra.tactics.behavior() { + Some(kit) => kit.attack_heal(world, unit, target, amount), + None => Ok(amount), + } + } +} + +impl Host { + pub(in crate::battle::runtime) fn kit_element( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + request: &mut element::Request, + ) -> Result<(), String> { + let phase = element::Phase::Hit; + self.kit_unit_event( + w, + r, + request.damage.hit.target, + Role::Target, + &mut Event::Element { phase, request }, + )?; + if let Some(source) = request.damage.hit.source { + self.kit_unit_event( + w, + r, + source, + Role::Source, + &mut Event::Element { phase, request }, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn kit_heal_amount( + &self, + w: &World, + source: Option, + target: Id, + amount: f64, + options: health::HealOptions, + ) -> Result { + let Some(source) = + source.filter(|&unit| w.unit(unit).is_ok_and(|u| u.side == health::Side::Ally)) + else { + return Ok(amount); + }; + let definition = self.tac_def(source)?; + match definition.extra.tactics.behavior() { + Some(kit) => kit.heal_amount(w, source, target, amount, options), + None => Ok(amount), + } + } + pub(in crate::battle::runtime) fn kit_observe( + c: &mut settlement::Context<'_, Self>, + ) -> Result<(), String> { + if c.request.hit.hp_loss { + return Ok(()); + } + let target = c.request.hit.target; + let buff = c.runtime.get(c.world, target, c.buff)?.clone(); + let owner = buff.runtime.source.unwrap_or(target); + let definition = c.host.tac_def(owner)?; + c.host.rng = c.rng.clone(); + let result = match definition.extra.tactics.behavior() { + Some(kit) => kit.observe_injury(c, buff.key.as_deref().unwrap_or(""), &buff), + None => Ok(()), + }; + *c.rng = c.host.rng.clone(); + result + } + pub(in crate::battle::runtime) fn kit_buff_event( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + context: buffs::Context, + event: buffs::Event, + token: u64, + ) -> Result<(), String> { + let owner = r + .get(w, context.unit, context.buff)? + .runtime + .source + .unwrap_or(context.unit); + self.kit_unit_event( + w, + r, + owner, + Role::Source, + &mut Event::Buff { + context, + event, + token, + }, + ) + } +} + +impl Host { + pub(in crate::battle::runtime) fn kit_can_activate( + &self, + world: &mut World, + unit: Id, + ) -> Result { + if self.roster.is_none() { + return Ok(true); + } + let definition = self.tac_def(unit)?; + match definition.extra.tactics.behavior() { + Some(kit) => kit.can_activate(self, world, unit), + None => Ok(true), + } + } + pub(in crate::battle::runtime) fn kit_condition( + &self, + world: &mut World, + unit: Id, + condition: skills::Condition, + ) -> Result, String> { + let definition = self.tac_def(unit)?; + match definition.extra.tactics.behavior() { + Some(kit) => kit.condition(self, world, unit, condition), + None => Ok(None), + } + } + pub(in crate::battle::runtime) fn kit_sp_gain( + &self, + unit: Id, + context: &mut skills::Context, + ) -> Result<(), String> { + let definition = self.tac_def(unit)?; + if let Some(kit) = definition.extra.tactics.behavior() { + kit.sp_gain(self, unit, context); + } + Ok(()) + } + pub(in crate::battle::runtime) fn kit_damage_applied( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + event: &health::Event, + request: &hit::Request, + ) -> Result<(), String> { + self.kit_event(w, r, &mut Event::DamageApplied { event, request })?; + if let Some(source) = event.source { + self.kit_unit_event( + w, + r, + source, + Role::Source, + &mut Event::DamageApplied { event, request }, + )?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/dispatch/context.rs b/crates/engine/src/battle/runtime/kits/dispatch/context.rs new file mode 100644 index 0000000..6cd5dc2 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/dispatch/context.rs @@ -0,0 +1,717 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Bounded access to battle operations from an operator callback. +use super::*; + +pub(crate) struct Context<'a> { + pub(in crate::battle::runtime) host: &'a mut Host, + pub(in crate::battle::runtime) world: &'a mut World, + pub(in crate::battle::runtime) buffs: &'a mut buffs::Runtime, + pub(in crate::battle::runtime) unit: Id, +} + +impl Context<'_> { + pub(in crate::battle::runtime) fn up(&self) -> bool { + Host::tac_up(self.world, self.unit) + } + pub(in crate::battle::runtime) fn active(&self) -> Result { + Ok(self.world.unit(self.unit)?.operator.active_skill) + } + pub(in crate::battle::runtime) fn stat(&mut self, unit: Id, key: &str) -> Result { + Host::tac_stat(self.world, unit, key) + } + pub(in crate::battle::runtime) fn flag(&mut self, unit: Id, key: &str) -> Result { + Ok(self + .world + .unit_mut(unit)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains(key)) + } + pub(in crate::battle::runtime) fn has(&self, unit: Id, key: &str) -> bool { + Host::tac_has(self.world, unit, key) + } + pub(in crate::battle::runtime) fn keys(&self) -> Result, String> { + self.host + .roster + .as_ref() + .unwrap() + .range(self.world, self.unit) + } + pub(in crate::battle::runtime) fn range( + &self, + grid: &[[i32; 2]], + ) -> Result, String> { + self.host.tac_keys(self.world, self.unit, grid) + } + pub(in crate::battle::runtime) fn enemies( + &mut self, + keys: Option<&[usize]>, + fly: bool, + ) -> Result, String> { + self.host.tac_enemies(self.world, self.unit, keys, fly) + } + pub(in crate::battle::runtime) fn radius( + &mut self, + at: [f64; 2], + radius: f64, + ) -> Result, String> { + self.host.tac_radius(self.world, at, radius) + } + pub(in crate::battle::runtime) fn allies(&mut self, keys: &[usize]) -> Result, String> { + let mut out = Vec::new(); + for id in self.host.roster.as_ref().unwrap().ids().to_vec() { + if crate::battle::targeting::friendly_selectable(self.world, self.unit, id)? + && body::in_range(self.world.unit(id)?, keys) + { + out.push(id); + } + } + Ok(out) + } + pub(in crate::battle::runtime) fn add( + &mut self, + unit: Id, + mut buff: Buff, + ) -> Result, String> { + buff.runtime.source = Some(self.unit); + self.buffs.add( + self.world, + self.host, + unit, + buffs::Spec { + buff, + ..Default::default() + }, + ) + } + pub(in crate::battle::runtime) fn buff( + &mut self, + unit: Id, + key: &str, + mods: Numbers, + duration: f64, + ) -> Result<(), String> { + self.host + .component_buff(self.world, self.buffs, unit, key, mods, duration, self.unit) + } + pub(in crate::battle::runtime) fn remove(&mut self, unit: Id, key: &str) -> Result<(), String> { + self.buffs + .remove(self.world, self.host, unit, key) + .map(|_| ()) + } + pub(in crate::battle::runtime) fn status( + &mut self, + target: Id, + key: &str, + duration: f64, + value: Option, + ) -> Result<(), String> { + self.host.advanced_status( + self.world, self.buffs, self.unit, target, key, duration, value, + ) + } + pub(in crate::battle::runtime) fn heal( + &mut self, + target: Id, + amount: f64, + options: health::HealOptions, + ) -> Result { + self.host.support_heal( + self.world, + self.buffs, + Some(self.unit), + target, + amount, + options, + ) + } + pub(in crate::battle::runtime) fn deal( + &mut self, + request: &mut hit::Request, + ) -> Result { + self.host.resolve_hit(self.world, self.buffs, request) + } + pub(in crate::battle::runtime) fn damage( + &mut self, + target: Id, + amount: f64, + kind: DamageType, + skill: bool, + tag: &str, + ) -> Result { + let mut request = hit::Request::new( + health::Hit { + source: Some(self.unit), + credit: Some(self.unit), + target, + damage_type: kind, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.is_skill = skill; + request.tags.push(tag.into()); + if matches!(tag, "addition" | "funnel" | "vulpisHunt") { + request.calculation = hit::Calculation::Precomputed; + request.attack_type = hit::AttackType::Addition; + request.tags.push("addition".into()); + } + self.deal(&mut request) + } + pub(in crate::battle::runtime) fn elemental( + &mut self, + target: Id, + amount: f64, + element: element::Element, + ) -> Result { + let mut request = + element::Request::new(Some(self.unit), Some(self.unit), target, element, amount); + element::apply(self.world, self.host, self.buffs, &mut request) + } + pub(in crate::battle::runtime) fn element_damage( + &mut self, + target: Id, + amount: f64, + element: element::Element, + tag: &str, + ) -> Result { + let mut request = hit::Request::new( + health::Hit { + source: Some(self.unit), + credit: Some(self.unit), + target, + damage_type: DamageType::Elemental, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.element = Some(element); + request.dodge_mode = injury::DodgeMode::Ignore; + request.tags.push(tag.into()); + self.deal(&mut request) + } + pub(in crate::battle::runtime) fn lose_hp(&mut self, amount: f64) -> Result<(), String> { + self.host.support_lose_hp( + self.world, + self.buffs, + self.unit, + amount, + Some(self.unit), + false, + ) + } + pub(in crate::battle::runtime) fn dp(&mut self, amount: f64) -> Result<(), String> { + self.host.roster.as_mut().unwrap().add_dp(amount) + } + pub(in crate::battle::runtime) fn skill( + &mut self, + operation: impl FnOnce(&mut skills::Runtime, &mut Host, &mut World) -> Result, + ) -> Result { + let id = self.unit; + self.host + .with_kit_buffs(self.world, self.buffs, |host, world| { + let mut skill = host.roster.as_mut().unwrap().take_skill(id)?; + let result = operation(&mut skill, host, world); + let restored = host.roster.as_mut().unwrap().restore_skill(id, skill); + match result { + Ok(value) => { + restored?; + Ok(value) + } + Err(error) => { + restored?; + Err(error) + } + } + }) + } + pub(in crate::battle::runtime) fn later( + &mut self, + delay: f64, + callback: fn(&mut Context<'_>) -> Result<(), String>, + ) -> Result<(), String> { + self.host.tac_timer( + self.world, + self.unit, + self.world.time + delay, + 0., + 1, + Task::Callback(callback), + ) + } + pub(in crate::battle::runtime) fn later_at( + &mut self, + delay: f64, + position: [f64; 2], + attack: f64, + survives_retreat: bool, + callback: fn(&mut Context<'_>, [f64; 2], f64) -> Result<(), String>, + ) -> Result<(), String> { + self.host.tac_timer( + self.world, + self.unit, + self.world.time + delay, + 0., + 1, + Task::AreaCallback { + position, + attack, + survives_retreat, + callback, + }, + ) + } + pub(in crate::battle::runtime) fn later_key( + &mut self, + delay: f64, + key: u64, + callback: fn(&mut Context<'_>, u64) -> Result<(), String>, + ) -> Result<(), String> { + self.host.tac_timer( + self.world, + self.unit, + self.world.time + delay, + 0., + 1, + Task::KeyedCallback { key, callback }, + ) + } +} + +impl Context<'_> { + pub(in crate::battle::runtime) fn faction( + &self, + unit: Id, + bond: &str, + nations: &[&str], + ) -> Result { + if self.world.unit(unit)?.side != health::Side::Ally { + return Ok(false); + } + let def = self.host.tac_def(unit)?; + let raw = &self + .host + .data + .table("chess") + .ok_or("Missing operator data")?[&def.key]; + Ok(raw["bonds"] + .as_array() + .is_some_and(|a| a.iter().any(|b| b.as_str() == Some(bond))) + || raw["nationId"] + .as_str() + .is_some_and(|n| nations.contains(&n))) + } + + pub(in crate::battle::runtime) fn retreat(&mut self) -> Result<(), String> { + self.retreat_with_reason("retreat") + } + pub(in crate::battle::runtime) fn retreat_with_reason( + &mut self, + reason: &str, + ) -> Result<(), String> { + if !self.up() { + return Ok(()); + } + let mut roster = self.host.roster.take().ok_or("Missing retreat roster")?; + let result = + if self.world.unit(self.unit)?.deployment.kind == crate::battle::deploy::Kind::Token { + roster.expire_token(self.world, self.buffs, self.host, self.unit) + } else { + roster.retreat(self.world, self.buffs, self.host, self.unit) + }; + self.host.roster = Some(roster); + result?; + if self.world.unit(self.unit)?.deployment.kind == crate::battle::deploy::Kind::Operator { + self.world.unit_mut(self.unit)?.deployment.remove_reason = Some(reason.into()); + } + self.host.kit_event( + self.world, + self.buffs, + &mut Event::Death { + unit: self.unit, + credit: None, + }, + )?; + self.host.flush_kit_events(self.world, self.buffs) + } +} + +impl Context<'_> { + pub(in crate::battle::runtime) fn pull( + &mut self, + target: Id, + force: f64, + to: Option<[f64; 2]>, + ) -> Result<(), String> { + let grid = self.host.grid.take().ok_or("Missing pull grid")?; + let result = if let Some(to) = to { + displacement::pull( + self.world, + &grid, + &mut allies::Blocking { + host: self.host, + buffs: self.buffs, + }, + target, + force, + displacement::Pull { + to, + center: None, + stop: 0.05, + }, + ) + } else { + let dir = self + .host + .roster + .as_ref() + .unwrap() + .entry(self.unit)? + .direction; + displacement::pull_to_front( + self.world, + &grid, + &mut allies::Blocking { + host: self.host, + buffs: self.buffs, + }, + target, + self.unit, + dir, + force, + ) + }; + self.host.grid = Some(grid); + result?; + Ok(()) + } + pub(in crate::battle::runtime) fn release(&mut self) -> Result<(), String> { + blocking::release( + self.world, + &mut allies::Blocking { + host: self.host, + buffs: self.buffs, + }, + self.unit, + ) + } + pub(in crate::battle::runtime) fn end_skill(&mut self, reason: &str) -> Result { + if self + .host + .roster + .as_ref() + .unwrap() + .entry(self.unit)? + .skill() + .is_err() + { + return Ok(false); + } + self.skill(|skill, host, world| skill.end(world, host, reason))?; + Ok(true) + } +} + +impl Context<'_> { + pub(in crate::battle::runtime) fn summon( + &mut self, + key: &str, + tile: [i32; 2], + duration: f64, + ) -> Result, String> { + let prepared = self + .host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .find(|&id| { + self.world.unit(id).is_ok_and(|u| { + u.deployment.kind == crate::battle::deploy::Kind::Token + && u.deployment.uid.is_some() + && !u.removed + && u.summoner == Some(self.unit) + }) && self.host.tac_def(id).is_ok_and(|def| def.key == key) + }); + if let Some(token) = prepared { + if !Host::tac_up(self.world, token) && !self.redeploy_free(token)? { + return Ok(None); + } + return Ok(Some(token)); + } + let definition = + Definition::token(&self.host.data, key, &self.host.tac_def(self.unit)?.key)?; + let direction = self + .host + .roster + .as_ref() + .unwrap() + .entry(self.unit)? + .direction; + let grid = self.host.grid.take().ok_or("Missing summon grid")?; + let mut roster = self.host.roster.take().ok_or("Missing summon roster")?; + let result = roster.spawn_token( + self.world, self.buffs, self.host, &grid, definition, self.unit, tile, direction, + ); + self.host.roster = Some(roster); + self.host.grid = Some(grid); + let token = result?; + self.host.rebuild_index(self.world)?; + self.host.flush_kit_events(self.world, self.buffs)?; + if let Some(token) = token.filter(|_| duration > 0.) { + let owner = self.unit; + self.unit = token; + let result = self.later(duration, |k| k.retreat()); + self.unit = owner; + result?; + } + Ok(token) + } + pub(in crate::battle::runtime) fn free_adjacent(&self) -> Result, String> { + let tile = self.world.unit(self.unit)?.deployment.tile; + let dir = self + .host + .roster + .as_ref() + .unwrap() + .entry(self.unit)? + .direction; + let grid = self.host.grid.as_ref().ok_or("Missing summon grid")?; + for offset in [ + [0, 1], + [1, 1], + [-1, 1], + [1, 0], + [-1, 0], + [0, -1], + [1, -1], + [-1, -1], + ] { + let offset = dir.rotate(offset); + let position = [tile[0] + offset[0], tile[1] + offset[1]]; + if grid.in_rect(position) + && grid.can_stand(position, false) + && !self + .host + .roster + .as_ref() + .unwrap() + .deployment() + .reserved(self.world, position)? + { + return Ok(Some(position)); + } + } + Ok(None) + } + pub(in crate::battle::runtime) fn relocate( + &mut self, + unit: Id, + tile: [i32; 2], + ) -> Result { + let grid = self.host.grid.take().ok_or("Missing relocation grid")?; + let mut roster = self.host.roster.take().ok_or("Missing relocation roster")?; + let result = roster.relocate(self.world, self.buffs, self.host, &grid, unit, tile); + self.host.roster = Some(roster); + self.host.grid = Some(grid); + result + } +} + +impl Context<'_> { + pub(in crate::battle::runtime) fn summon_tiles( + &self, + grid: &[[i32; 2]], + ground: bool, + ) -> Result, String> { + let map = self.host.grid.as_ref().ok_or("Missing summon grid")?; + let own = self.world.unit(self.unit)?.deployment.tile; + let mut tiles = Vec::new(); + for key in self.range(grid)? { + let tile = [(key / COLS) as i32, (key % COLS) as i32]; + if tile != own + && map.in_rect(tile) + && map.can_stand(tile, false) + && (!ground || map.ground_passable(tile, true)) + && !self + .host + .roster + .as_ref() + .unwrap() + .deployment() + .reserved(self.world, tile)? + { + tiles.push(tile); + } + } + Ok(tiles) + } + pub(in crate::battle::runtime) fn best_summon_tile( + &self, + tiles: &[[i32; 2]], + ) -> Option<[i32; 2]> { + let mut best = tiles.first().copied(); + let mut distance = f64::INFINITY; + for &tile in tiles { + let mut nearest = f64::INFINITY; + for id in self.world.unit_ids() { + let u = self.world.unit(id).ok()?; + if u.side == health::Side::Enemy && u.stats.alive && !u.hidden { + nearest = nearest.min(crate::deterministic::math::hypot( + u.position[0] - tile[0] as f64, + u.position[1] - tile[1] as f64, + )); + } + } + if nearest < distance - 1e-9 { + distance = nearest; + best = Some(tile); + } + } + best + } +} + +impl Context<'_> { + pub(in crate::battle::runtime) fn move_redeploy( + &mut self, + tile: [i32; 2], + skill: &mut skills::Runtime, + clear_sp: bool, + ) -> Result { + if !self.relocate(self.unit, tile)? { + return Ok(false); + } + let sequence = self.world.next_deployment_sequence()?; + let now = self.world.time; + let unit = self.world.unit_mut(self.unit)?; + unit.deployment.deploy_seq = sequence; + unit.deployment.aggro_seq = sequence; + unit.deployment.deployed_at = now; + if clear_sp + && !skill.bank.no_skill + && skill.bank.kind != crate::battle::sp::Kind::Passive + && !(skill.bank.active && skill.bank.kind.timed()) + { + skill.bank.sp = 0.; + skill.bank.charges = if skill.bank.cost(self.world)? <= 0. { + skill.bank.max_charges() as f64 + } else { + 0. + }; + } + let definition = self.host.tac_def(self.unit)?; + let direction = self + .host + .roster + .as_ref() + .unwrap() + .entry(self.unit)? + .direction; + definition.skill_event( + self.world, + self.buffs, + self.host, + skills::Event::Deploy, + direction, + &mut skills::Context { + reason: "move".into(), + dt: 0., + amount: 0., + no_ammo: false, + targets: Vec::new(), + }, + skill, + )?; + Ok(true) + } +} + +impl Context<'_> { + pub(in crate::battle::runtime) fn tactical_point( + &mut self, + ) -> Result, String> { + // A preplaced tactical summon already owns its tile, including on a full board. + for &id in self.host.roster.as_ref().unwrap().ids() { + let unit = self.world.unit(id)?; + if unit.deployment.kind == crate::battle::deploy::Kind::Token + && unit.deployment.uid.is_some() + && unit.summoner == Some(self.unit) + { + return Ok(Some(unit.deployment.home)); + } + } + let grid = self + .host + .grid + .as_mut() + .ok_or("Missing tactical point grid")?; + let paths = self + .host + .spawns + .as_mut() + .ok_or("Missing tactical point routes")? + .path_tiles(grid); + let roster = self.host.roster.as_ref().unwrap(); + let origin = self.world.unit(self.unit)?.deployment.tile; + let direction = roster.entry(self.unit)?.direction; + let mut best = None; + let mut score = (2u8, f64::INFINITY, [i32::MAX; 2]); + for key in roster.base_range(self.world, self.unit)? { + let tile = [(key / COLS) as i32, (key % COLS) as i32]; + let grid = self.host.grid.as_ref().unwrap(); + if !grid.ground_passable(tile, false) + || !grid.can_stand(tile, false) + || roster.deployment().reserved(self.world, tile)? + { + continue; + } + let delta = [tile[0] - origin[0], tile[1] - origin[1]]; + let local = direction.local(delta); + let distance = delta[0].abs().max(delta[1].abs()) as f64 + 0.01 * local[0].abs() as f64; + if distance <= 0. { + continue; + } + let path = if paths.contains(&key) { 0 } else { 1 }; + if path < score.0 + || path == score.0 + && (distance < score.1 - 1e-9 + || (distance - score.1).abs() <= 1e-9 && local < score.2) + { + score = (path, distance, local); + best = Some(tile); + } + } + Ok(best) + } + pub(in crate::battle::runtime) fn redeploy_free(&mut self, token: Id) -> Result { + let tiles = Arc::clone(&self.host.tiles); + let mut roster = self.host.roster.take().ok_or("Missing revival roster")?; + let result = roster.redeploy_free(self.world, self.buffs, self.host, &tiles, token); + self.host.roster = Some(roster); + let revived = result?; + self.host.rebuild_index(self.world)?; + self.host.flush_kit_events(self.world, self.buffs)?; + Ok(revived) + } +} diff --git a/crates/engine/src/battle/runtime/kits/dollkeeper.rs b/crates/engine/src/battle/runtime/kits/dollkeeper.rs new file mode 100644 index 0000000..738fcd6 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/dollkeeper.rs @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Context as KitContext, Event as KitEvent}; +use super::*; +#[derive(Default)] +pub(crate) struct State { + pub doll: bool, + pub pending_end: bool, + pub switching: bool, +} +const SWITCH: u64 = 1520; +const SUBSTITUTE: u64 = 1521; +pub(crate) fn switch(k: &mut KitContext<'_>) -> Result<(), String> { + k.host.growth_doll_swap(k.world, k.unit)?; + if !k.end_skill("substitute")? { + k.world + .unit_mut(k.unit)? + .operator + .tactical + .dollkeeper_mut()? + .pending_end = true; + } + let statuses: Vec<_> = k + .world + .unit(k.unit)? + .stats + .buffs() + .iter() + .filter(|b| b.runtime.status.is_some()) + .map(|b| b.runtime.id()) + .collect(); + for buff in statuses { + k.buffs.remove_id(k.world, k.host, k.unit, buff)?; + } + k.world + .unit_mut(k.unit)? + .operator + .tactical + .dollkeeper_mut()? + .switching = true; + let mut buff = Buff { + key: Some("trait:dollSwitching".into()), + flags: [ + "invulnerable", + "noSp", + "noHeal", + "healFree", + "isolated", + "disarm", + ] + .map(str::to_string) + .into(), + ..Default::default() + }; + buff.runtime.duration = 1.; + buff.runtime.on_expire = Some(SWITCH); + buff.runtime.on_remove = Some(SWITCH); + k.add(k.unit, buff)?; + let maximum = k.stat(k.unit, "maxHp")?; + k.world.unit_mut(k.unit)?.stats.hp = maximum; + Ok(()) +} +pub(crate) fn enter( + k: &mut KitContext<'_>, + duration: f64, + hp: f64, + no_attack: bool, +) -> Result { + if !k.up() || k.world.unit(k.unit)?.operator.tactical.dollkeeper()?.doll { + return Ok(false); + } + k.world + .unit_mut(k.unit)? + .operator + .tactical + .dollkeeper_mut()? + .doll = true; + switch(k)?; + let mut buff = Buff { + key: Some("trait:substitute".into()), + mods: [("blockCnt".into(), -99.), ("hpMul".into(), hp)].into(), + flags: if no_attack { + ["noSp", "disarm", "silence"].map(str::to_string).into() + } else { + ["noSp".to_string()].into() + }, + ..Default::default() + }; + buff.runtime.duration = 1. + duration; + buff.runtime.on_expire = Some(SUBSTITUTE); + buff.runtime.on_remove = Some(SUBSTITUTE); + k.add(k.unit, buff)?; + k.release()?; + let maximum = k.stat(k.unit, "maxHp")?; + k.world.unit_mut(k.unit)?.stats.hp = maximum; + k.host.bond_doll_swap(k.world, k.unit)?; + Ok(true) +} +pub(crate) fn resume(k: &mut KitContext<'_>, skill: &mut skills::Runtime) -> Result<(), String> { + if std::mem::take( + &mut k + .world + .unit_mut(k.unit)? + .operator + .tactical + .dollkeeper_mut()? + .pending_end, + ) { + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + skill.end(world, host, "substitute") + })?; + } + Ok(()) +} +pub(crate) fn handle(k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Buff { + context, + event, + token, + } if *token == SWITCH || *token == SUBSTITUTE => { + if k.buffs + .get(k.world, context.unit, context.buff)? + .runtime + .source + != Some(id) + { + return Ok(()); + } + if *token == SWITCH { + k.world + .unit_mut(id)? + .operator + .tactical + .dollkeeper_mut()? + .switching = false; + if *event == buffs::Event::Expire && k.up() { + let maximum = k.stat(id, "maxHp")?; + k.world.unit_mut(id)?.stats.hp = maximum; + } + } else if k.world.unit(id)?.operator.tactical.dollkeeper()?.doll { + k.world + .unit_mut(id)? + .operator + .tactical + .dollkeeper_mut()? + .doll = false; + if k.up() { + switch(k)?; + k.host.bond_doll_swap(k.world, id)?; + } + } + } + KitEvent::Death { unit, .. } if *unit == id => { + *k.world.unit_mut(id)?.operator.tactical.dollkeeper_mut()? = State::default(); + } + _ => {} + } + Ok(()) +} diff --git a/crates/engine/src/battle/runtime/kits/dusk.rs b/crates/engine/src/battle/runtime/kits/dusk.rs new file mode 100644 index 0000000..1e6b30b --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/dusk.rs @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "splashcaster", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[Skill { + id: "skchr_dusk_1", + kind: crate::battle::sp::Kind::Charges, + sp_type: skills::SpType::Time, + rule: "DEFAULT", + attack_override: true, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + s.combat.skill_scale = n(bb, "atk_scale", 1.); + s.combat.area.splash = Some(Splash { + radius: 1.1, + scale: 1., + hits_fly: true, + fortress_melee: false, + }); + s.combat.skill_area = s.combat.area; + s.combat.skill_area.splash.as_mut().unwrap().radius = 1.7; + crate::battle::content::operators::mechanics::module_range(raw, s)?; + s.extra.tactics = Tactics::Dusk(Dusk { + attack: n(talent_at(raw, 0), "atk", 0.), + cap: n(talent_at(raw, 0), "max_stack_cnt", 15.).max(1.) as u32, + duration: n(talent_at(raw, 1), "attack@tokenduration", 25.), + }); + Ok(()) +} +pub(crate) struct Dusk { + attack: f64, + cap: u32, + duration: f64, +} +#[derive(Default)] +pub(crate) struct State { + summoned: bool, +} +impl Behavior for Dusk { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Attack { context, .. } + if context.attacker == id + && !k.world.unit(id)?.operator.tactical.dusk()?.summoned => + { + if let Some(&target) = context.targets.first() { + k.world.unit_mut(id)?.operator.tactical.dusk_mut()?.summoned = true; + let p = k + .world + .unit(target)? + .position + .map(|v| (v + 0.5).floor() as i32); + let grid = k.host.grid.as_ref().ok_or("Missing dusk summon grid")?; + if grid.can_stand(p, false) && grid.obstacle(p) == 0 { + k.summon("token_10015_dusk_drgn", p, self.duration)?; + } + } + } + KitEvent::Death { + unit, + credit: Some(killer), + } if k.up() + && k.world.unit(*unit)?.side == health::Side::Enemy + && (*killer == id || k.world.unit(*killer)?.summoner == Some(id)) => + { + let mut buff = Buff { + key: Some("dusk:realm".into()), + mods: [("atkPct".into(), self.attack)].into(), + ..Default::default() + }; + buff.runtime.refresh = buffs::Refresh::Stack; + buff.runtime.max_stacks = self.cap; + k.add(id, buff)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/etlchi.rs b/crates/engine/src/battle/runtime/kits/etlchi.rs new file mode 100644 index 0000000..32ac24a --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/etlchi.rs @@ -0,0 +1,440 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "reaper", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_etlchi_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tb = &raw["trait"]["bb"]; + let count = n(bb, "attack@max_target", 3.).floor().max(1.); + if count > 64. { + return Err("Candle count exceeds capacity".into()); + } + s.extra.no_heal = true; + s.combat.profile.all_in_range = true; + s.extra.support.reaper = n(tb, "value", 50.); + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("aspd".into(), n(bb, "attack_speed", 0.)), + ] + .into(); + crate::battle::content::operators::mechanics::skill_range(raw, s)?; + s.extra.tactics = Tactics::Etlchi(Etlchi { + hp_scale: n(bb, "attack@max_hp_scale", 0.6), + defence: n(bb, "attack@def_scale", 1.), + resistance: n(bb, "attack@magic_resistance_scale", 1.), + count: count as usize, + steal: n(t, "attack@steal_hp", 0.), + cap: n(t, "attack@steal_hp_max", 0.), + dot: n(t, "magic_value", 0.), + duration: n(t, "dot_duration", 5.), + interval: n(t, "interval", 1.).max(0.1), + reborn: n(t1, "hp_ratio", 0.), + heal: n(t1, "etlchi_t_2[heal].hp_ratio", 0.), + protection: n(t1, "damage_resistance", 0.), + speed: n(tb, "attack_speed", 0.), + enemies: n(tb, "cnt", 2.), + }); + Ok(()) +} +pub(crate) struct Etlchi { + hp_scale: f64, + defence: f64, + resistance: f64, + count: usize, + steal: f64, + cap: f64, + dot: f64, + duration: f64, + interval: f64, + reborn: f64, + heal: f64, + protection: f64, + speed: f64, + enemies: f64, +} +#[derive(Default)] +pub(crate) struct State { + candles: BTreeMap, + stolen: f64, + losses: BTreeMap, + reborn: bool, +} +const DOT: u64 = 1523; +impl Etlchi { + fn extinguish(k: &mut KitContext<'_>, candle: Id) -> Result<(), String> { + if Host::tac_up(k.world, candle) { + settlement::Hooks::health_kill(k.host, candle, None, k.buffs, k.world)?; + } + Ok(()) + } +} +impl Behavior for Etlchi { + fn reaper_eligible(&self, request: &hit::Request) -> bool { + request.attack_type != hit::AttackType::Buff && !request.tags.iter().any(|tag| tag == "dot") + } + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Hit { .. }) { + -20 + } else { + 0 + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + let mut targets = k.enemies(None, false)?; + targets.retain(|&a| { + !k.world.unit(a).unwrap().boss + && !k + .host + .spawns + .as_ref() + .unwrap() + .definition(a) + .is_ok_and(|d| d.key == "enemy_5601_entlec") + }); + targets.sort_by(|&a, &b| { + k.world + .unit(b) + .unwrap() + .stats + .hp + .total_cmp(&k.world.unit(a).unwrap().stats.hp) + .then( + k.world + .unit(a) + .unwrap() + .targeting + .spawn_seq + .cmp(&k.world.unit(b).unwrap().targeting.spawn_seq), + ) + }); + for target in targets.into_iter().take(self.count) { + let position = k.world.unit(target)?.position; + let hp = (k.world.unit(target)?.stats.hp * self.hp_scale).max(1.); + let defence = k.stat(target, "def")? * self.defence; + let resistance = k.stat(target, "res")? * self.resistance; + let mass = k.world.unit(target)?.stats.base_number("massLevel"); + let grid = k.host.grid.take().ok_or("Missing candle grid")?; + let mut spawns = k.host.spawns.take().ok_or("Missing candle spawns")?; + let mut content = k.host.content.take().ok_or("Missing candle content")?; + let result = spawns.spawn_candle( + k.world, + &grid, + &mut super::super::Spawn { + host: k.host, + buffs: k.buffs, + content: &mut content, + }, + position, + hp, + defence, + resistance, + mass, + ); + k.host.spawns = Some(spawns); + k.host.content = Some(content); + k.host.grid = Some(grid); + let candle = result?; + k.world + .unit_mut(id)? + .operator + .tactical + .etlchi_mut()? + .candles + .insert(candle, target); + let mut buff = Buff { + key: Some("etlchi:candle".into()), + flags: ["unblockable", "noMove"].map(str::to_string).into(), + ..Default::default() + }; + buff.runtime.source = Some(id); + k.add(candle, buff)?; + // New enemies enter targeting at the next EnemyIndex phase. + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + let candles = std::mem::take( + &mut k + .world + .unit_mut(id)? + .operator + .tactical + .etlchi_mut()? + .candles, + ); + for candle in candles.keys() { + Self::extinguish(k, *candle)?; + } + } + KitEvent::Element { request, .. } + if request.damage.hit.source != Some(id) + && k.world + .unit(id)? + .operator + .tactical + .etlchi()? + .candles + .contains_key(&request.damage.hit.target) => + { + request.damage.cancelled = true + } + KitEvent::BeforeStatus(context) + if context.source != Some(id) + && k.world + .unit(id)? + .operator + .tactical + .etlchi()? + .candles + .contains_key(&context.target) => + { + context.cancelled = true + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if k + .world + .unit(id)? + .operator + .tactical + .etlchi()? + .candles + .contains_key(&request.hit.target) => + { + if request.hit.source != Some(id) { + request.cancelled = true; + } else if matches!( + request.hit.damage_type, + DamageType::Physical | DamageType::Arts + ) { + let source = k + .world + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .clone(); + let target = k + .world + .unit_mut(request.hit.target)? + .stats + .stats() + .map_err(str::to_string)? + .clone(); + let mut penetration = request.damage.penetration; + penetration.def_flat += source.n("defIgnoreFlat"); + penetration.def_pct += source.n("defIgnorePct"); + penetration.res_flat += source.n("resIgnoreFlat"); + penetration.res_pct += source.n("resIgnorePct"); + let amount = crate::battle::damage::mitigate( + request.damage.amount, + request.hit.damage_type, + &target, + penetration, + 0., + ); + let floor = source.n("atk") * 0.35; + if amount < floor { + request.hit.damage_type = DamageType::True; + request.damage.amount = floor; + request.dodge_mode = injury::DodgeMode::Ignore; + } + } + } + KitEvent::Before(context) + if context.attacker != id + && k.world.unit(context.attacker)?.side == health::Side::Ally => + { + let candles = &k.world.unit(id)?.operator.tactical.etlchi()?.candles; + let mut out = Vec::new(); + for target in &context.targets { + let target = candles.get(target).copied().unwrap_or(*target); + if Host::tac_up(k.world, target) && !out.contains(&target) { + out.push(target); + } + } + context.targets = out; + } + KitEvent::Landed { event, request } => { + if let Some(&original) = k + .world + .unit(id)? + .operator + .tactical + .etlchi()? + .candles + .get(&event.target) + { + if event.amount > 0. + && request.hit.damage_type != DamageType::Elemental + && Host::tac_up(k.world, original) + { + k.host.support_lose_hp( + k.world, + k.buffs, + original, + event.amount, + Some(id), + false, + )?; + } + } + if event.source == Some(id) + && request.is_attack + && request.hit.damage_type != DamageType::Elemental + && k.up() + && Host::tac_up(k.world, event.target) + && k.world.unit(event.target)?.side == health::Side::Enemy + && !k + .world + .unit(id)? + .operator + .tactical + .etlchi()? + .candles + .contains_key(&event.target) + { + let target = event.target; + if self.dot > 0. { + let mut buff = Buff { + key: Some(format!("etlchi:dot:{id}")), + ..Default::default() + }; + buff.runtime.duration = self.duration; + buff.runtime.interval = self.interval; + buff.runtime.on_tick = Some(DOT); + buff.runtime.tick_payload = self.dot; + buff.runtime.refresh = buffs::Refresh::Extend; + k.add(target, buff)?; + } + let stolen = k.world.unit(id)?.operator.tactical.etlchi()?.stolen; + let amount = self + .steal + .min(self.cap - stolen) + .min((k.stat(target, "maxHp")? - 1.).floor()); + if amount > 0. && k.world.unit(target)?.pool.is_none() { + let hp = k.world.unit(target)?.stats.hp; + let state = k.world.unit_mut(id)?.operator.tactical.etlchi_mut()?; + state.stolen += amount; + let total = state.losses.entry(target).or_default(); + *total += amount; + let total = *total; + let gain = state.stolen; + k.buff( + target, + &format!("etlchi:steal:{id}"), + [("hpFlat".into(), -total)].into(), + f64::INFINITY, + )?; + let maximum = k.stat(target, "maxHp")?; + k.world.unit_mut(target)?.stats.hp = hp.min(maximum); + k.buff( + id, + "etlchi:gain", + [("hpFlat".into(), gain)].into(), + f64::INFINITY, + )?; + } + } + if event.target == id + && k.up() + && !k.world.unit(id)?.operator.tactical.etlchi()?.reborn + && k.world.unit(id)?.stats.hp > 0. + && k.world.unit(id)?.stats.hp / k.stat(id, "maxHp")? < self.reborn + { + k.world.unit_mut(id)?.operator.tactical.etlchi_mut()?.reborn = true; + let amount = k.stat(id, "maxHp")? * self.heal; + k.heal( + id, + amount, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + if self.protection > 0. { + k.buff( + id, + "etlchi:reborn", + [("physTakenMul".into(), 1. - self.protection)].into(), + f64::INFINITY, + )?; + } + } + } + KitEvent::Buff { + context, + event: buffs::Event::Tick, + token, + } if *token == DOT => { + let b = k.buffs.get(k.world, context.unit, context.buff)?; + if b.runtime.source == Some(id) { + let amount = b.runtime.tick_payload; + k.damage(context.unit, amount, DamageType::Arts, false, "dot")?; + } + } + KitEvent::Death { unit, .. } => { + let candles = k + .world + .unit(id)? + .operator + .tactical + .etlchi()? + .candles + .iter() + .filter_map(|(&c, &original)| if original == *unit { Some(c) } else { None }) + .collect::>(); + for candle in candles { + Self::extinguish(k, candle)?; + } + } + KitEvent::Scheduled(due) if due[2] && k.up() => { + if self.speed != 0. && k.enemies(None, false)?.len() as f64 >= self.enemies { + k.buff( + id, + "trait:reaperAspd", + [("aspd".into(), self.speed)].into(), + 0.4, + )?; + } + let valid = k.world.unit_ids().collect::>(); + let state = k.world.unit_mut(id)?.operator.tactical.etlchi_mut()?; + state.losses.retain(|e, _| valid.contains(e)); + state.candles.retain(|c, _| valid.contains(c)); + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/excu2.rs b/crates/engine/src/battle/runtime/kits/excu2.rs new file mode 100644 index 0000000..786467b --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/excu2.rs @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "reaper", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_excu2_2", + kind: Kind::Ammo, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_excu2_1", + kind: Kind::Ammo, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_excu2_3", + kind: Kind::Ammo, + sp_type: SpType::Attack, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_excu2_1" => Mode::First, + "skchr_excu2_2" => Mode::Second, + "skchr_excu2_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.extra.no_heal = true; + let mut p = s.combat.profile; + p.all_in_range = true; + p.selection.ground_only = true; + s.combat.profile = p; + s.combat.area.selection = p.selection; + s.combat.skill_area = s.combat.area; + s.extra.support.reaper = n(tb, "value", 50.); + s.extra.effects.ammo_count = n(bb, "attack@trigger_time", 12.); + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("defPct".into(), n(bb, "def", 0.)), + ("blockCnt".into(), n(bb, "block_cnt", 0.)), + ("defIgnoreFlat".into(), n(bb, "def_penetrate_fixed", 0.)), + ( + "batPct".into(), + flat_bat(raw, n(bb, "base_attack_time", 0.)), + ), + ] + .into(); + skill_range(raw, s)?; + s.extra.tactics = Tactics::Excu2(Excu2 { + mode: mode, + prob: n(t, "prob", 0.), + prob_add: n(t, "prob_add", 0.), + bonus_ammo: n(t1, "add_count", 1.), + ammo_cap: n(t1, "add_count_max_stack", 4.), + dodge: n(bb, "prob", 0.), + refill: n(bb, "recover_cnt", 1.), + verdict: n(bb, "attack@final_atk_scale", 0.), + stack_atk: n(bb, "attack@atk", 0.), + stack_cap: n(bb, "attack@max_stack_cnt", 30.).max(1.) as u32, + heal_ratio: n(bb, "trait_ratio", 1.), + }); + Ok(()) +} +pub(crate) struct Excu2 { + pub mode: Mode, + pub prob: f64, + pub prob_add: f64, + pub bonus_ammo: f64, + pub ammo_cap: f64, + pub dodge: f64, + pub refill: f64, + pub verdict: f64, + pub stack_atk: f64, + pub stack_cap: u32, + pub heal_ratio: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub spent: u32, + pub pending_ammo: f64, + pub extra: bool, + pub verdict: BTreeSet, +} + +pub(in crate::battle::runtime) const DODGE: u64 = 1511; +impl Excu2 { + fn extra_attack(k: &mut KitContext<'_>) -> Result<(), String> { + let id = k.unit; + if !skills::can_act(k.world, id)? || k.flag(id, "disarm")? { + return Ok(()); + } + k.world.unit_mut(id)?.operator.tactical.excu2_mut()?.extra = true; + let result = k.skill(|skill, host, world| { + let Some(profile) = ally::Host::effective_profile(host, id, Some(skill), world)? else { + return Ok(()); + }; + let keys = host.roster.as_ref().unwrap().range(world, id)?; + let selected = search::acquire(world, host, id, &keys, profile, world.unit_capacity())?; + if selected.targets.is_empty() { + return Ok(()); + } + ally::Host::perform(host, id, profile, selected, Some(skill), world) + }); + k.world.unit_mut(id)?.operator.tactical.excu2_mut()?.extra = false; + result + } + fn refill(k: &mut KitContext<'_>, skill: &mut skills::Runtime) -> Result<(), String> { + let pending = std::mem::take( + &mut k + .world + .unit_mut(k.unit)? + .operator + .tactical + .excu2_mut()? + .pending_ammo, + ); + if skill.bank.active { + skill.add_ammo(pending); + } + Ok(()) + } +} +impl Behavior for Excu2 { + fn reaper_multiplier(&self, world: &World, id: Id) -> Result { + Ok( + if self.mode == Mode::Third && world.unit(id)?.operator.active_skill { + self.heal_ratio + } else { + 1. + }, + ) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + let s = k.world.unit_mut(id)?.operator.tactical.excu2_mut()?; + s.spent = 0; + s.verdict.clear(); + let mut count: f64 = 0.; + for target in k.host.roster.as_ref().unwrap().ids().to_vec() { + if Host::tac_up(k.world, target) + && k.faction(target, "lateranoShip", &["laterano"])? + { + count += 1.; + } + } + skill.add_ammo(count.min(self.ammo_cap) * self.bonus_ammo); + if self.mode == Mode::Second { + let mut buff = Buff { + key: Some("excu2:meleeDodge".into()), + ..Default::default() + }; + buff.runtime.injury.priority = 2000.; + buff.runtime.injury.on_injury = Some(DODGE); + k.add(id, buff)?; + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + let targets = std::mem::take( + &mut k.world.unit_mut(id)?.operator.tactical.excu2_mut()?.verdict, + ); + k.world.unit_mut(id)?.operator.tactical.excu2_mut()?.spent = 0; + if self.mode == Mode::Third && k.world.unit(id)?.stats.alive { + for target in targets { + if k.world.unit(target).is_ok_and(|u| u.stats.alive) { + let amount = k.stat(id, "atk")? * self.verdict; + k.damage(target, amount, DamageType::Physical, true, "verdict")?; + } + } + } + k.remove(id, "excu2:verdict")?; + k.remove(id, "excu2:meleeDodge")?; + } + KitEvent::Skill { + unit, + event: skills::Event::AmmoUsed, + .. + } if *unit == id => { + k.world.unit_mut(id)?.operator.tactical.excu2_mut()?.spent += 1; + if self.mode == Mode::Third && k.active()? { + let mut buff = Buff { + key: Some("excu2:verdict".into()), + mods: [("atkPct".into(), self.stack_atk)].into(), + ..Default::default() + }; + buff.runtime.refresh = buffs::Refresh::Stack; + buff.runtime.max_stacks = self.stack_cap; + k.add(id, buff)?; + } + } + KitEvent::Scheduled(due) if due[2] => { + let valid: BTreeSet<_> = k.world.unit_ids().collect(); + k.world + .unit_mut(id)? + .operator + .tactical + .excu2_mut()? + .verdict + .retain(|target| valid.contains(target)); + } + KitEvent::Resume { unit, skill } if *unit == id => { + Self::refill(k, skill)?; + } + KitEvent::Before(context) + if context.attacker == id && k.world.unit(id)?.operator.tactical.excu2()?.extra => + { + context.no_ammo = true; + } + KitEvent::Attack { context, skill } if context.attacker == id => { + if let Some(skill) = skill { + Self::refill(k, skill)?; + } + if !k.world.unit(id)?.operator.tactical.excu2()?.extra && k.up() { + let chance = self.prob + + if k.active()? { + self.prob_add + * k.world.unit(id)?.operator.tactical.excu2()?.spent as f64 + } else { + 0. + }; + if chance > 0. && k.host.rng.chance(chance.min(1.)) { + k.later(0., Self::extra_attack)?; + } + } + } + KitEvent::Impact(impact) + if impact.attacker == id && self.mode == Mode::Third && k.active()? => + { + k.world + .unit_mut(id)? + .operator + .tactical + .excu2_mut()? + .verdict + .extend(impact.target); + } + _ => {} + } + Ok(()) + } +} +impl Host { + pub(in crate::battle::runtime) fn excu2_injury( + c: &mut settlement::Context<'_, Self>, + event: &mut injury::InjuryEvent, + ) -> Result<(), String> { + if c.request.is_projectile + || !c.request.hit.source.is_some_and(|source| { + c.world + .unit(source) + .is_ok_and(|u| u.side == health::Side::Enemy) + }) + { + return Ok(()); + } + let id = c.request.hit.target; + let def = c.host.tac_def(id)?; + let Tactics::Excu2(p) = &def.extra.tactics else { + return Err("Invalid Excu2 injury owner".into()); + }; + if c.dodge(event, Some(p.dodge))? { + if c.host.roster.as_ref().unwrap().entry(id)?.skill().is_ok() { + let mut skill = c.host.roster.as_mut().unwrap().take_skill(id)?; + skill.add_ammo(p.refill); + c.host.roster.as_mut().unwrap().restore_skill(id, skill)?; + } else { + c.world + .unit_mut(id)? + .operator + .tactical + .excu2_mut()? + .pending_ammo += p.refill; + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/funnel.rs b/crates/engine/src/battle/runtime/kits/funnel.rs new file mode 100644 index 0000000..d5223b5 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/funnel.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! An attached drone keeps its launch-time profile and advances its ramp on impact. +use super::*; +#[derive(Clone, Copy)] +pub(crate) struct Parameters { + pub initial: f64, + pub delta: f64, + pub cap: f64, +} +impl Parameters { + pub fn read(raw: &Value) -> Self { + let tb = &raw["trait"]["bb"]; + Self { + initial: n(tb, "init_atk_scale", 0.2), + delta: n(tb, "delta_atk_scale", 0.15), + cap: n(tb, "max_atk_scale", 1.1), + } + } + pub fn attachment(self, count: u32, per_target: bool) -> attacks::Attachment { + attacks::Attachment { + count, + initial: self.initial, + delta: self.delta, + cap: self.cap, + per_target, + scale: 0., + } + } +} +#[derive(Clone, Default)] +pub(crate) struct State { + pub target: Option, + pub scale: f64, + pub map: BTreeMap, +} +impl State { + pub fn step(&mut self, target: Id, time: f64, parameters: Parameters, per_target: bool) -> f64 { + if per_target { + let scale = match self.map.get(&target) { + Some(&(scale, at)) if at == time => return scale, + Some(&(scale, _)) => (scale + parameters.delta).min(parameters.cap), + None => parameters.initial, + }; + self.map.insert(target, (scale, time)); + scale + } else { + self.scale = if self.target == Some(target) { + (self.scale + parameters.delta).min(parameters.cap) + } else { + parameters.initial + }; + self.target = Some(target); + self.scale + } + } +} +impl Host { + pub(in crate::battle::runtime) fn funnel_prepare( + &mut self, + world: &mut World, + source: Id, + target: Option, + payload: &mut attacks::Direct, + ) -> Result<(), String> { + let Some(mut attachment) = payload.attachment else { + return Ok(()); + }; + let Some(target) = target.filter(|&id| world.unit(id).is_ok_and(|u| u.stats.alive)) else { + return Ok(()); + }; + let def = self.tac_def(source)?; + if let Tactics::Malist(p) = &def.extra.tactics { + if self.rng.chance(p.prob) { + payload.atk_scale *= p.crit; + } + } + let time = world.time; + let count = match &def.extra.tactics { + Tactics::Malist(_) => world + .unit(source)? + .operator + .tactical + .malist()? + .funnel + .map + .len(), + Tactics::Kjera(_) => world + .unit(source)? + .operator + .tactical + .kjera()? + .funnel + .map + .len(), + _ => 0, + }; + let valid = if count >= world.unit_capacity() { + Some(world.unit_ids().collect::>()) + } else { + None + }; + let state = match &def.extra.tactics { + Tactics::Whitw2(_) => { + &mut world + .unit_mut(source)? + .operator + .tactical + .whitw2_mut()? + .funnel + } + Tactics::Rockr(_) => { + &mut world + .unit_mut(source)? + .operator + .tactical + .rockr_mut()? + .funnel + } + Tactics::Malist(_) => { + &mut world + .unit_mut(source)? + .operator + .tactical + .malist_mut()? + .funnel + } + Tactics::Kjera(_) => { + &mut world + .unit_mut(source)? + .operator + .tactical + .kjera_mut()? + .funnel + } + _ => return Err("Attached drone has no funnel owner".into()), + }; + if let Some(valid) = valid { + state.map.retain(|id, _| valid.contains(id)); + } + attachment.scale = state.step( + target, + time, + Parameters { + initial: attachment.initial, + delta: attachment.delta, + cap: attachment.cap, + }, + attachment.per_target, + ); + payload.attachment = Some(attachment); + Ok(()) + } + pub(in crate::battle::runtime) fn funnel_damage( + &mut self, + world: &mut World, + source: Id, + target: Id, + attack_id: u64, + payload: attacks::Direct, + ) -> Result { + let Some(attachment) = payload.attachment else { + return Ok(0.); + }; + if attachment.count > crate::battle::operators::Combat::MAX_HITS { + return Err("Attached drone hit capacity exceeded".into()); + } + let mut buffs = self.buffs.take().ok_or("Missing attached drone buffs")?; + let result = (|| { + let mut total = 0.; + for _ in 0..attachment.count { + if !world.unit(target)?.stats.alive { + break; + } + let amount = Self::tac_stat(world, source, "atk")? + * (payload.atk_scale * Self::tac_stat(world, source, "atkScaleMul")?) + * payload.skill_damage_mul + * payload.target_damage_mul + * attachment.scale; + let mut request = hit::Request::new( + health::Hit { + source: Some(source), + credit: Some(source), + target, + damage_type: DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.is_skill = payload.is_skill; + request.attack_id = Some(attack_id); + request.attack_type = hit::AttackType::Addition; + request.tags = vec!["addition".into(), "funnel".into()]; + let dealt = self.resolve_hit(world, &mut buffs, &mut request); + total += dealt?; + } + Ok(total) + })(); + self.buffs = Some(buffs); + result + } +} diff --git a/crates/engine/src/battle/runtime/kits/ghost2.rs b/crates/engine/src/battle/runtime/kits/ghost2.rs new file mode 100644 index 0000000..d4e5fa4 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/ghost2.rs @@ -0,0 +1,359 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "SPECIAL", + branch: "dollkeeper", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_ghost2_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_ghost2_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SKILL_RANGE", + attack_override: false, + }, + Skill { + id: "skchr_ghost2_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_ghost2_1" => Mode::First, + "skchr_ghost2_2" => Mode::Second, + "skchr_ghost2_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("aspd".into(), n(bb, "attack_speed", 0.)), + ("hpPct".into(), n(bb, "max_hp", 0.)), + ( + "batPct".into(), + flat_bat(raw, n(bb, "base_attack_time", 0.)), + ), + ] + .into(); + if mode == Mode::Third { + let mut p = s.combat.profile; + p.hit_all_blocked = true; + s.combat.skill_profile = Some(p); + } + let team = if n(t1, "max_hp", 0.) != 0. { + Some(TeamBuff { + key: "ghost2:abyss", + characters: &[ + "char_263_skadi", + "char_143_ghost", + "char_218_cuttle", + "char_474_glady", + "char_1023_ghost2", + "char_4145_ulpia", + ], + mods: [("hpPct".into(), n(t1, "max_hp", 0.))].into(), + }) + } else { + None + }; + s.extra.tactics = Tactics::Ghost2(Ghost2 { + team, + mode: mode, + slow: n(t, "move_speed", 0.), + scale: n(t, "atk_scale", 0.), + doll_atk: n(tb, "atk", 0.), + doll_hp: n(tb, "max_hp", 0.), + extra: n(bb, "attack@atk_scale_ex", 0.), + loss: n(bb, "attack@hp_ratio", 0.), + grid: if raw["skill"]["rangeGrid"] + .as_array() + .is_some_and(|a| !a.is_empty()) + { + tactical_grid(&raw["skill"]["rangeGrid"], true)? + } else { + vec![ + [-1, -1], + [-1, 0], + [-1, 1], + [0, -1], + [0, 0], + [0, 1], + [1, -1], + [1, 0], + [1, 1], + ] + }, + }); + Ok(()) +} +pub(crate) struct Ghost2 { + team: Option, + pub mode: Mode, + pub slow: f64, + pub scale: f64, + pub doll_atk: f64, + pub doll_hp: f64, + pub extra: f64, + pub loss: f64, + pub grid: Vec<[i32; 2]>, +} +#[derive(Default)] +pub(crate) struct State { + pub dollkeeper: super::dollkeeper::State, + pub heavy: BTreeMap, +} + +impl Ghost2 { + fn enter(&self, k: &mut KitContext<'_>) -> Result { + super::dollkeeper::enter(k, 20., 1., true) + } + fn resume(&self, k: &mut KitContext<'_>, skill: &mut skills::Runtime) -> Result<(), String> { + super::dollkeeper::resume(k, skill) + } +} +impl Behavior for Ghost2 { + fn priority(&self, event: &KitEvent<'_>, world: &World, id: Id) -> i32 { + if matches!(event, KitEvent::Fatal(_)) { + if self.mode == Mode::Second && world.unit(id).is_ok_and(|u| u.operator.active_skill) { + 10 + } else { + -100 + } + } else if matches!(event, KitEvent::Before(_)) { + -100 + } else { + 0 + } + } + fn can_attack(&self, _host: &Host, world: &World, id: Id) -> Result { + Ok(!world.unit(id)?.operator.tactical.ghost2()?.dollkeeper.doll) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + super::dollkeeper::handle(k, event)?; + let id = k.unit; + match event { + KitEvent::BattleStart => { + if let Some(team) = &self.team { + let units = k.host.roster.as_ref().unwrap().ids().to_vec(); + for target in units { + if team + .characters + .contains(&k.host.tac_def(target)?.char_id.as_str()) + { + team.apply(k.world, k.buffs, k.host, id, target)?; + } + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id && self.mode == Mode::First => { + let keys = k.range(&self.grid)?; + let mut pick = None; + let mut lowest = f64::INFINITY; + for target in k.allies(&keys)? { + if target == id { + continue; + } + let ratio = k.world.unit(target)?.stats.hp / k.stat(target, "maxHp")?; + if ratio < lowest { + lowest = ratio; + pick = Some(target); + } + } + if let Some(target) = pick { + let maximum = k.stat(id, "maxHp")?; + let other = k.stat(target, "maxHp")?; + let mine = k.world.unit(id)?.stats.hp / maximum; + k.world.unit_mut(id)?.stats.hp = (maximum * lowest).min(maximum).max(1.); + k.world.unit_mut(target)?.stats.hp = (other * mine).min(other).max(1.); + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + context, + .. + } if *unit == id + && self.mode == Mode::Second + && context.reason != "death" + && context.reason != "substitute" => + { + self.enter(k)?; + } + KitEvent::Resume { unit, skill } if *unit == id => { + self.resume(k, skill)?; + } + KitEvent::Attack { + context, + skill: Some(skill), + } if context.attacker == id => { + self.resume(k, skill)?; + } + KitEvent::Fatal(event) if event.target == id && !event.prevented => { + if k.world + .unit(id)? + .operator + .tactical + .ghost2()? + .dollkeeper + .switching + || self.mode == Mode::Second && k.active()? + { + event.prevented = true; + } else { + event.prevented = self.enter(k)?; + } + } + KitEvent::BeforeStatus(context) + if context.target == id + && k.world + .unit(id)? + .operator + .tactical + .ghost2()? + .dollkeeper + .switching + && ["stun", "freeze", "sleep"].contains(&context.key.as_str()) => + { + context.cancelled = true; + } + KitEvent::Before(context) + if context.attacker == id && self.mode == Mode::Third && k.active()? => + { + let ratio = k.world.unit(id)?.stats.hp / k.stat(id, "maxHp")?; + let mut heavy = BTreeMap::new(); + for &target in &context.targets { + heavy.insert( + target, + k.world.unit(target)?.stats.hp / k.stat(target, "maxHp")? >= ratio - 1e-9, + ); + } + k.world.unit_mut(id)?.operator.tactical.ghost2_mut()?.heavy = heavy; + } + KitEvent::Impact(impact) + if impact.attacker == id + && impact.is_skill + && self.mode == Mode::Third + && impact.kind == attacks::VictimKind::Main => + { + if let Some(target) = impact.target { + if k.world + .unit(id)? + .operator + .tactical + .ghost2()? + .heavy + .get(&target) + .copied() + .unwrap_or(false) + { + if k.world.unit(target)?.stats.alive { + let amount = k.stat(id, "atk")? * self.extra; + k.damage(target, amount, DamageType::Physical, true, "ghost2Weight")?; + } + } else if k.world.unit(id)?.stats.alive { + let amount = k.stat(id, "maxHp")? * self.loss; + k.lose_hp(amount)?; + } + } + } + KitEvent::Scheduled(due) => { + if !k.up() + || !k + .world + .unit(id)? + .operator + .tactical + .ghost2()? + .dollkeeper + .doll + { + return Ok(()); + } + if due[1] { + if self.doll_hp != 0. { + k.buff( + id, + "ghost2:moduleY", + [("hpPct".into(), self.doll_hp)].into(), + 0.3, + )?; + } + if self.doll_atk != 0. { + k.buff( + id, + "ghost2:module", + [("atkPct".into(), self.doll_atk)].into(), + 0.3, + )?; + } + } + if !k + .world + .unit(id)? + .operator + .tactical + .ghost2()? + .dollkeeper + .switching + && (due[2] || due[4]) + { + let keys = k.range(&[ + [-1, -1], + [-1, 0], + [-1, 1], + [0, -1], + [0, 0], + [0, 1], + [1, -1], + [1, 0], + [1, 1], + ])?; + for target in k.enemies(Some(&keys), false)? { + if due[2] && self.slow != 0. { + k.buff( + target, + "ghost2:embrace", + [("moveMul".into(), (1. + self.slow).max(0.))].into(), + 0.5, + )?; + } + if due[4] && self.scale > 0. { + let amount = k.stat(id, "atk")? * self.scale; + k.damage(target, amount, DamageType::Arts, false, "embrace")?; + } + } + } + } + + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/halo2.rs b/crates/engine/src/battle/runtime/kits/halo2.rs new file mode 100644 index 0000000..c057f55 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/halo2.rs @@ -0,0 +1,411 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "slower", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_halo2_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_halo2_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_halo2_2", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_halo2_1" => Mode::First, + "skchr_halo2_2" => Mode::Second, + "skchr_halo2_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.combat.sluggish = n(tb, "sluggish", 0.8); + s.combat.skill_sluggish = s.combat.sluggish; + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("batPct".into(), { + let v = n(bb, "base_attack_time", 0.); + if v > 0. { + v.max(-0.9) + } else { + flat_bat(raw, v).max(-0.9) + } + }), + ] + .into(); + if mode == Mode::Second { + s.combat.skill_scale = n(bb, "atk_scale", 1.); + s.combat.skill_sluggish = n(bb, "sluggish", 3.); + } + if mode == Mode::Third { + skill_range(raw, s)?; + let mut p = s.combat.profile; + p.max_targets = n(bb, "attack@max_target", 1.).max(1.); + s.combat.skill_profile = Some(p); + } + s.extra.tactics = Tactics::Halo2(Halo2 { + mode: mode, + sluggish: n(tb, "sluggish", 0.8), + jumps: n(bb, "attack@chain.max_target", 3.).floor().max(0.) as usize, + jump_radius: n(bb, "attack@projectile_range", 1.7), + link_radius: n(bb, "ability_range_radius", 2.), + link_targets: n(bb, "max_target", 2.).floor().max(0.) as usize, + link_scale: n(bb, "atk_scale_link", n(bb, "atk_scale", 1.)), + force: n(bb, "force", 0.), + locks: n(bb, "attack@max_target", 1.).max(1.) as usize, + share: n(bb, "attack@atk_share", 0.), + aspd: n(t, "attack_speed", 0.), + stack_cap: n(t, "max_stack_cnt", 18.).max(1.) as u32, + full_atk: n(tm, "atk", 0.), + fragile: suffix_number(t1, "damage_scale", 1.), + fragile_max: suffix_number( + t1, + "damage_scale_max", + suffix_number(t1, "damage_scale", 1.), + ), + fragile_time: suffix_number(t1, "interval", 7.), + }); + Ok(()) +} +pub(crate) struct Halo2 { + pub mode: Mode, + pub sluggish: f64, + pub jumps: usize, + pub jump_radius: f64, + pub link_radius: f64, + pub link_targets: usize, + pub link_scale: f64, + pub force: f64, + pub locks: usize, + pub share: f64, + pub aspd: f64, + pub stack_cap: u32, + pub full_atk: f64, + pub fragile: f64, + pub fragile_max: f64, + pub fragile_time: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub locks: Vec, + pub linking: bool, + pub stacks: u32, + pub stay: BTreeMap, +} + +impl Behavior for Halo2 { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start | skills::Event::End, + .. + } if *unit == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .halo2_mut()? + .locks + .clear(); + } + KitEvent::Before(context) if context.attacker == id && k.active()? => { + if self.mode == Mode::Second && context.is_skill { + let candidates = k.enemies(None, true)?; + let mut best = None; + let mut remaining = f64::NEG_INFINITY; + for target in candidates { + let value = + targeting::Queries::remaining_distance(k.host, target, k.world)?; + if value > remaining + 1e-9 { + remaining = value; + best = Some(target); + } + } + if let Some(target) = best { + context.targets = vec![target]; + } + } + if self.mode == Mode::Third { + let keys = k.keys()?; + let mut keep = Vec::new(); + for target in k.world.unit(id)?.operator.tactical.halo2()?.locks.clone() { + if Host::tac_up(k.world, target) + && body::in_range(k.world.unit(target)?, &keys) + && targeting::can_target_enemy( + k.world, + k.host, + Some(id), + target, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? + { + keep.push(target); + } + } + for &target in &context.targets { + if keep.len() < self.locks && !keep.contains(&target) { + keep.push(target); + } + } + keep.truncate(self.locks); + context.targets = keep.clone(); + k.world.unit_mut(id)?.operator.tactical.halo2_mut()?.locks = keep; + } + } + KitEvent::Impact(impact) + if impact.attacker == id + && impact.is_skill + && impact.kind == attacks::VictimKind::Main => + { + if let Some(target) = impact.target { + if self.mode == Mode::First { + if self.jumps > 64 { + return Err("Halo chain capacity exceeded".into()); + } + let mut previous = target; + let mut position = k.world.unit(target)?.position; + for _ in 0..self.jumps { + let mut best = None; + let mut distance = f64::INFINITY; + for next in k.radius(position, self.jump_radius)? { + if next == previous + || !targeting::can_target_enemy( + k.world, + k.host, + Some(id), + next, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? + { + continue; + } + let d = body::distance(k.world.unit(next)?, position); + if d < distance - 1e-9 { + distance = d; + best = Some(next); + } + } + let Some(next) = best else { + break; + }; + let amount = k.stat(id, "atk")?; + let mut request = hit::Request::new( + health::Hit { + source: Some(id), + credit: Some(id), + target: next, + damage_type: DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.is_attack = true; + request.is_skill = true; + request.tags.push("chain".into()); + k.deal(&mut request)?; + if Host::tac_up(k.world, next) { + k.status(next, "sluggish", self.sluggish, None)?; + } + previous = next; + position = k.world.unit(next)?.position; + } + } + if self.mode == Mode::Second { + let position = k.world.unit(target)?.position; + let mut near = k.radius(position, self.link_radius)?; + near.retain(|&next| next != target); + near.sort_by(|a, b| { + body::distance(k.world.unit(*a).unwrap(), position) + .total_cmp(&body::distance(k.world.unit(*b).unwrap(), position)) + .then( + k.world + .unit(*a) + .unwrap() + .targeting + .spawn_seq + .cmp(&k.world.unit(*b).unwrap().targeting.spawn_seq), + ) + }); + for next in near.into_iter().take(self.link_targets) { + if !targeting::can_target_enemy( + k.world, + k.host, + Some(id), + next, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? { + continue; + } + k.pull(next, self.force, Some(position))?; + if Host::tac_up(k.world, next) { + let amount = k.stat(id, "atk")? * self.link_scale; + k.damage(next, amount, DamageType::Arts, true, "link")?; + } + } + } + } + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if self.mode == Mode::Third + && k.active()? + && request.hit.damage_type == DamageType::Arts + && !request.tags.iter().any(|t| t == "link") => + { + let state = k.world.unit(id)?.operator.tactical.halo2()?; + if self.share > 0. + && !state.linking + && state.locks.len() > 1 + && state.locks.contains(&request.hit.target) + { + let locks = state.locks.clone(); + k.world.unit_mut(id)?.operator.tactical.halo2_mut()?.linking = true; + let result: Result<(), String> = (|| { + for target in locks { + if target == request.hit.target || !Host::tac_up(k.world, target) { + continue; + } + let source = request.hit.source.or(Some(id)); + let amount = request.damage.amount * self.share; + let mut linked = hit::Request::new( + health::Hit { + source, + credit: source, + target, + damage_type: DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + linked.is_skill = true; + linked.dodge_mode = injury::DodgeMode::Ignore; + linked.tags = vec!["skill".into(), "link".into()]; + k.deal(&mut linked)?; + } + Ok(()) + })(); + k.world.unit_mut(id)?.operator.tactical.halo2_mut()?.linking = false; + result?; + } + } + KitEvent::Status(context) + if context.source == Some(id) && context.key == "sluggish" && k.up() => + { + let count = { + let state = k.world.unit_mut(id)?.operator.tactical.halo2_mut()?; + if state.stacks >= self.stack_cap { + return Ok(()); + } + state.stacks += 1; + state.stacks + }; + k.buff( + id, + "halo2:model", + [ + ("aspd".into(), self.aspd * count as f64), + ( + "atkPct".into(), + if count >= self.stack_cap { + self.full_atk + } else { + 0. + }, + ), + ] + .into(), + f64::INFINITY, + )?; + } + KitEvent::Scheduled(due) if due[2] && k.up() => { + let foes = k.enemies(None, true)?; + let mut stay = + std::mem::take(&mut k.world.unit_mut(id)?.operator.tactical.halo2_mut()?.stay); + stay.retain(|target, _| foes.contains(target)); + for target in foes { + let time = stay.entry(target).or_insert(0.); + *time += 0.25; + let value = if *time > self.fragile_time { + self.fragile_max + } else { + self.fragile + }; + if value > 1. { + k.status(target, "fragile", 0.4, Some(value - 1.))?; + } + } + k.world.unit_mut(id)?.operator.tactical.halo2_mut()?.stay = stay; + } + _ => {} + } + Ok(()) + } +} + +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + let mut state = Self::default(); + if let Some(previous) = previous { + state.stay = previous.stay.clone(); + } + state + } +} diff --git a/crates/engine/src/battle/runtime/kits/horn.rs b/crates/engine/src/battle/runtime/kits/horn.rs new file mode 100644 index 0000000..2247fb6 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/horn.rs @@ -0,0 +1,414 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "fortress", + ranged: true, + can_hit_fly: false, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_horn_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_horn_1", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_horn_2", + kind: Kind::Ammo, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_horn_1" => Mode::First, + "skchr_horn_2" => Mode::Second, + "skchr_horn_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.combat.profile.fortress = true; + s.combat.area.splash = Some(Splash { + radius: 1., + scale: 1., + hits_fly: false, + fortress_melee: false, + }); + s.combat.area.selection = s.combat.profile.selection; + s.combat.skill_area = s.combat.area; + if mode == Mode::First { + s.combat.skill_scale = n(bb, "atk_scale", 1.); + } + if mode == Mode::Second { + s.extra.effects.ammo_count = n(bb, "attack@s2.trigger_time", 10.); + s.combat.skill_scale = n(bb, "attack@s2.atk_scale", 1.); + if let Some(a) = &mut s.combat.skill_area.splash { + a.fortress_melee = true; + } + } + if mode == Mode::Third { + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ( + "batPct".into(), + flat_bat(raw, n(bb, "base_attack_time", 0.)), + ), + ] + .into(); + } + s.extra.tactics = Tactics::Horn(Horn { + mode: mode, + duration: n(&raw["skill"], "duration", 0.), + flare_radius: n(bb, "projectile_range", 1.7), + flare_duration: n(bb, "projectile_delay_time", 6.), + ammo: n(bb, "attack@s2.trigger_time", 10.).max(1.), + magic: n(bb, "attack@s2.magic_atk_scale", 0.), + over_atk: n(bb, "horn_s_3[overload_start].atk", n(bb, "atk", 0.)) - n(bb, "atk", 0.), + over_interval: n(bb, "horn_s_3[overload_start].interval", 0.2).max(0.05), + over_peak: n(bb, "horn_s_3[overload_start].hp_ratio", 0.), + over_ramp: n( + bb, + "horn_s_3[overload_start].damage_duration", + n(&raw["skill"], "duration", 24.) / 2., + ) + .max(0.1), + tank_atk: n(t, "atk", 0.), + blood_hp: n(t1, "max_hp", 0.), + blood_heal: n(t1, "hp_ratio", 1.), + blood_aspd: n(t1, "attack_speed", 0.), + blood_def: n(t1, "def", 0.), + blocked_mul: n(tb, "atk_scale", 0.), + module_aspd: n(tm, "attack_speed", 0.), + }); + Ok(()) +} +pub(crate) struct Horn { + pub mode: Mode, + pub duration: f64, + pub flare_radius: f64, + pub flare_duration: f64, + pub ammo: f64, + pub magic: f64, + pub over_atk: f64, + pub over_interval: f64, + pub over_peak: f64, + pub over_ramp: f64, + pub tank_atk: f64, + pub blood_hp: f64, + pub blood_heal: f64, + pub blood_aspd: f64, + pub blood_def: f64, + pub blocked_mul: f64, + pub module_aspd: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub elapsed: f64, + pub ammo_remaining: f64, + pub accumulator: f64, + pub overloaded: bool, + pub flare: bool, + pub flares: Vec<([f64; 2], f64)>, + pub blood: bool, +} + +impl Behavior for Horn { + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Fatal(_)) { + -40 + } else { + 0 + } + } + fn payload( + &self, + _: &World, + _: Id, + payload: &mut attacks::Direct, + area: &mut attacks::Area, + ) -> Result<(), String> { + if self.mode == Mode::First && payload.is_skill && !area.fortress_melee { + if let Some(splash) = &mut area.splash { + splash.radius = splash.radius.max(self.flare_radius); + } + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + let s = k.world.unit_mut(id)?.operator.tactical.horn_mut()?; + s.ammo_remaining = skill.ammo_left; + s.elapsed = 0.; + s.accumulator = 0.; + s.overloaded = false; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id && self.mode == Mode::Third => { + let main = self.duration.max(0.1) - self.over_ramp.min(self.duration.max(0.1)); + let enter = { + let s = k.world.unit_mut(id)?.operator.tactical.horn_mut()?; + s.elapsed += context.dt; + !s.overloaded && s.elapsed >= main - 1e-9 + }; + if enter { + k.world + .unit_mut(id)? + .operator + .tactical + .horn_mut()? + .overloaded = true; + k.buff( + id, + "horn:overload", + [("atkPct".into(), self.over_atk)].into(), + f64::INFINITY, + )?; + } + if k.world.unit(id)?.operator.tactical.horn()?.overloaded && self.over_peak > 0. { + k.world + .unit_mut(id)? + .operator + .tactical + .horn_mut()? + .accumulator += context.dt; + for _ in 0..30 { + let rate = { + let s = k.world.unit_mut(id)?.operator.tactical.horn_mut()?; + if s.accumulator < self.over_interval { + break; + } + s.accumulator -= self.over_interval; + self.over_peak * ((s.elapsed - main) / self.over_ramp).min(1.) + }; + if rate > 0. { + let amount = k.stat(id, "maxHp")? * rate * self.over_interval; + k.lose_hp(amount)?; + } + if !k.up() { + break; + } + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .horn_mut()? + .overloaded = false; + k.remove(id, "horn:overload")?; + } + KitEvent::Before(context) if context.attacker == id && context.is_skill => { + if self.mode == Mode::Second { + let shot = + self.ammo - k.world.unit(id)?.operator.tactical.horn()?.ammo_remaining + 1.; + k.world + .unit_mut(id)? + .operator + .tactical + .horn_mut()? + .overloaded = shot > self.ammo * 0.5 + 1e-9; + } + if self.mode == Mode::First { + let melee = if let Some(&target) = context.targets.first() { + let keys = k.range(&[[0, 0], [0, 1]])?; + k.world.unit(target)?.blocked_by() == Some(id) + || body::in_range(k.world.unit(target)?, &keys) + } else { + true + }; + k.world.unit_mut(id)?.operator.tactical.horn_mut()?.flare = !melee; + } + } + KitEvent::Impact(impact) if impact.attacker == id && impact.is_skill => { + if self.mode == Mode::First + && impact.kind == attacks::VictimKind::Main + && k.world.unit(id)?.operator.tactical.horn()?.flare + { + k.world.unit_mut(id)?.operator.tactical.horn_mut()?.flare = false; + let until = k.world.time + self.flare_duration; + let limit = k.host.tactical_limit; + let state = k.world.unit_mut(id)?.operator.tactical.horn_mut()?; + if state.flares.len() >= limit { + return Err("Horn flare capacity exceeded".into()); + } + state.flares.push((impact.position, until)); + } + if self.mode == Mode::Second + && k.world.unit(id)?.operator.tactical.horn()?.overloaded + && self.magic > 0. + { + if let Some(target) = impact.target.filter(|&t| Host::tac_up(k.world, t)) { + let amount = k.stat(id, "atk")? * self.magic; + let mut request = hit::Request::new( + health::Hit { + source: Some(id), + credit: Some(id), + target, + damage_type: DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.is_skill = true; + request.is_splash = true; + request.tags.push("hornOverload".into()); + k.deal(&mut request)?; + } + } + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.source == Some(id) + && self.blocked_mul > 1. + && k.world.unit(request.hit.target)?.blocked_by().is_some() => + { + request.damage.amount *= self.blocked_mul; + } + KitEvent::Skill { + unit, + event: skills::Event::AmmoUsed, + .. + } if *unit == id && self.mode == Mode::Second => { + k.world + .unit_mut(id)? + .operator + .tactical + .horn_mut()? + .ammo_remaining -= 1.; + } + + KitEvent::Fatal(event) + if event.target == id + && !event.prevented + && !k.world.unit(id)?.operator.tactical.horn()?.blood => + { + event.prevented = true; + k.world.unit_mut(id)?.operator.tactical.horn_mut()?.blood = true; + k.buff( + id, + "horn:bloodBattle", + [ + ("hpMul".into(), 1. - self.blood_hp), + ("aspd".into(), self.blood_aspd), + ("defPct".into(), self.blood_def), + ] + .into(), + f64::INFINITY, + )?; + k.world.unit_mut(id)?.stats.hp = k.world.unit(id)?.stats.hp.max(1.); + let amount = k.stat(id, "maxHp")? * self.blood_heal; + k.heal( + id, + amount, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + KitEvent::Scheduled(due) => { + let now = k.world.time; + let mut flares = + std::mem::take(&mut k.world.unit_mut(id)?.operator.tactical.horn_mut()?.flares); + flares.retain(|(_, until)| *until > now + 1e-9); + if due[2] { + for &(at, _) in &flares { + for target in k.host.spawns.as_ref().unwrap().live().to_vec() { + if Host::tac_up(k.world, target) + && !k.world.unit(target)?.hidden + && body::in_radius(k.world.unit(target)?, at, self.flare_radius) + { + k.status(target, "reveal", 0.5, None)?; + } + } + } + } + k.world.unit_mut(id)?.operator.tactical.horn_mut()?.flares = flares; + if k.up() { + if due[2] && self.tank_atk != 0. { + for target in k.host.roster.as_ref().unwrap().ids().to_vec() { + if Host::tac_up(k.world, target) + && k.host.tac_def(target)?.profession == "TANK" + { + k.buff( + target, + "horn:fortress", + [("atkPct".into(), self.tank_atk)].into(), + 0.5, + )?; + } + } + } + if due[1] && self.module_aspd != 0. && k.world.unit(id)?.blocking().is_empty() { + k.buff( + id, + "horn:moduleY", + [("aspd".into(), self.module_aspd)].into(), + 0.3, + )?; + } + } + } + _ => {} + } + Ok(()) + } +} + +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + let mut state = Self::default(); + if let Some(previous) = previous { + state.flares = previous.flares.clone(); + } + state + } +} diff --git a/crates/engine/src/battle/runtime/kits/indigo.rs b/crates/engine/src/battle/runtime/kits/indigo.rs new file mode 100644 index 0000000..9a54502 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/indigo.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "mystic", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_indigo_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_indigo_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_indigo_1" => Mode::First, + "skchr_indigo_2" => Mode::Second, + _ => return Err("Unknown selected skill".into()), + }; + s.modifiers = [( + "batPct".into(), + if mode == Mode::First { + n(bb, "base_attack_time", 0.).clamp(-0.95, 0.) + } else { + n(bb, "base_attack_time", 1.) - 1. + }, + )] + .into(); + if mode == Mode::First { + s.combat.skill_scale = n(bb, "attack@atk_scale", 1.); + skill_range(raw, s)?; + } + if n(tb, "times", 3.) > 4. { + return Err("Stored attack capacity exceeded".into()); + } + s.extra.tactics = Tactics::Indigo(Indigo { + mode: mode, + prob: n(t, "prob", 0.), + bind: n(t, "duration", 0.), + talent_scale: n(bb, "talent_scale", 1.), + dot: n(bb, "indigo_s_2[damage].atk_scale", 0.), + interval: n(bb, "indigo_s_2[damage].interval", 0.5).max(DT), + capacity: n(tb, "times", 3.).floor().max(0.) as u32, + }); + Ok(()) +} +pub(crate) struct Indigo { + pub mode: Mode, + pub prob: f64, + pub bind: f64, + pub talent_scale: f64, + pub dot: f64, + pub interval: f64, + pub capacity: u32, +} +#[derive(Default)] +pub(crate) struct State { + pub stored: u32, + pub accumulator: f64, +} +impl Behavior for Indigo { + fn enemy_filter(&self) -> Option { + Some(bound_target) + } + fn payload( + &self, + world: &World, + id: Id, + payload: &mut attacks::Direct, + _: &mut attacks::Area, + ) -> Result<(), String> { + payload.hits = 1 + world.unit(id)?.operator.tactical.indigo()?.stored; + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .indigo_mut()? + .accumulator = 0.; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id && self.mode == Mode::Second => { + let ticks = { + let s = k.world.unit_mut(id)?.operator.tactical.indigo_mut()?; + s.accumulator += context.dt; + let n = ((s.accumulator + 1e-9) / self.interval).floor().max(0.) as usize; + s.accumulator -= n as f64 * self.interval; + n + }; + if ticks > 30 { + return Err("Indigo periodic payload capacity exceeded".into()); + } + for _ in 0..ticks { + let keys = k.keys()?; + let enemies = k.host.spawns.as_ref().unwrap().live().to_vec(); + for target in enemies { + if Host::tac_up(k.world, target) + && body::in_range(k.world.unit(target)?, &keys) + && k.flag(target, "bind")? + { + let amount = k.stat(id, "atk")? * self.dot; + let mut request = hit::Request::new( + health::Hit { + source: Some(id), + credit: Some(id), + target, + damage_type: DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.is_skill = true; + request.dodge_mode = injury::DodgeMode::Ignore; + request.tags.push("dot".into()); + k.deal(&mut request)?; + } + } + } + } + KitEvent::Attack { context, .. } if context.attacker == id => { + k.world.unit_mut(id)?.operator.tactical.indigo_mut()?.stored = 0; + } + KitEvent::Impact(impact) + if impact.attacker == id && impact.kind == attacks::VictimKind::Main => + { + if let Some(target) = impact.target.filter(|&t| Host::tac_up(k.world, t)) { + let probability = self.prob * if k.active()? { self.talent_scale } else { 1. }; + if probability > 0. && k.host.rng.chance(probability.min(1.)) { + k.status(target, "bind", self.bind, None)?; + } + } + } + _ => {} + } + Ok(()) + } +} + +fn bound_target(world: &mut World, _: Id, target: Id) -> Result { + Ok(world + .unit_mut(target)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("bind")) +} diff --git a/crates/engine/src/battle/runtime/kits/ines.rs b/crates/engine/src/battle/runtime/kits/ines.rs new file mode 100644 index 0000000..77636ac --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/ines.rs @@ -0,0 +1,478 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "PIONEER", + branch: "agent", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_ines_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_ines_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_ines_3", + kind: Kind::Duration, + sp_type: SpType::None, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_ines_1" => Mode::First, + "skchr_ines_2" => Mode::Second, + "skchr_ines_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + if mode == Mode::Second { + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + s.skill_flags.insert("stealth".into()); + skill_range(raw, s)?; + } + if mode == Mode::Third { + s.rule_override = Some(skills::Rule::Never); + s.extra.deploy = false; + } + s.extra.tactics = Tactics::Ines(Ines { + mode: mode, + dp: n(bb, "cost", 1.), + bleed: n(bb, "bleed_atk_scale", 0.4), + bleed_duration: n(bb, "bleed_duration", 3.), + steal_aspd: n(bb, "attack@steal_atk_speed", 5.), + aspd_cap: n(bb, "attack@steal_atk_speed_max", 50.), + steal_atk: n(t, "steal_atk", 90.), + atk_cap: n(t, "steal_atk_max", f64::INFINITY), + bind: n(t, "duration", 5.), + slow: n(t1, "move_speed", -0.3), + respawn: n(tb, "respawn_time", 0.), + recall_scale: n(bb, "atk_scale", 1.1), + recall_radius: n(bb, "projectile_range", 1.4), + recall_targets: n(bb, "max_target", 4.).max(1.) as usize, + attack: n(bb, "atk", 0.), + base_grid: tactical_grid(&raw["rangeGrid"], false)?, + }); + Ok(()) +} +pub(crate) struct Ines { + pub mode: Mode, + pub dp: f64, + pub bleed: f64, + pub bleed_duration: f64, + pub steal_aspd: f64, + pub aspd_cap: f64, + pub steal_atk: f64, + pub atk_cap: f64, + pub bind: f64, + pub slow: f64, + pub respawn: f64, + pub recall_scale: f64, + pub recall_radius: f64, + pub recall_targets: usize, + pub attack: f64, + pub base_grid: Vec<[i32; 2]>, +} +#[derive(Default)] +pub(crate) struct State { + pub woven: BTreeSet, + pub atk_victims: Vec, + pub aspd_victims: BTreeSet, + pub aspd: f64, + pub sentry: Vec, + pub sentry_at: Option<[f64; 2]>, + pub placed: bool, + pub first_retreat: bool, +} + +const BLEED: u64 = 1515; +impl Ines { + fn clear_aspd(&self, k: &mut KitContext<'_>) -> Result<(), String> { + let targets = std::mem::take( + &mut k + .world + .unit_mut(k.unit)? + .operator + .tactical + .ines_mut()? + .aspd_victims, + ); + for target in targets { + if k.world.unit(target).is_ok() { + k.remove(target, &format!("ines:aspd:{}", k.unit))?; + } + } + k.world.unit_mut(k.unit)?.operator.tactical.ines_mut()?.aspd = 0.; + k.remove(k.unit, "ines:aspdGain") + } + fn refresh(&self, k: &mut KitContext<'_>) -> Result<(), String> { + let mut targets = std::mem::take( + &mut k + .world + .unit_mut(k.unit)? + .operator + .tactical + .ines_mut()? + .atk_victims, + ); + targets.retain(|&target| k.world.unit(target).is_ok_and(|u| u.stats.alive)); + let gain = (self.steal_atk * targets.len() as f64).min(self.atk_cap); + k.world + .unit_mut(k.unit)? + .operator + .tactical + .ines_mut()? + .atk_victims = targets; + if k.world.unit(k.unit)?.stats.alive { + if gain > 0. { + k.buff( + k.unit, + "ines:atkGain", + [("atkFlat".into(), gain)].into(), + f64::INFINITY, + )?; + } else { + k.remove(k.unit, "ines:atkGain")?; + } + } + Ok(()) + } + fn initial_retreat(k: &mut KitContext<'_>) -> Result<(), String> { + k.retreat()?; + k.world.unit_mut(k.unit)?.deployment.respawn_at = k.world.time; + Ok(()) + } +} +impl Behavior for Ines { + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + if matches!((role, event), (Role::Target, KitEvent::Death { .. })) + && k.world.unit(k.unit)?.deployment.remove_reason.as_deref() != Some("expired") + { + let keys = k.range(&self.base_grid)?; + let at = k.world.unit(k.unit)?.position; + let state = k.world.unit_mut(k.unit)?.operator.tactical.ines_mut()?; + state.sentry = keys; + if self.mode == Mode::Third { + state.sentry_at = Some(at); + } + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + skill, + .. + } if *unit == id && self.mode == Mode::Third => { + if k.world.unit(id)?.operator.tactical.ines()?.placed { + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + skill.activate(world, host, "deploy", false) + })?; + } else { + k.world.unit_mut(id)?.operator.tactical.ines_mut()?.placed = true; + k.later(0., Self::initial_retreat)?; + } + } + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + if self.mode == Mode::Second { + self.clear_aspd(k)?; + } + if self.mode == Mode::Third { + k.buff( + id, + "ines:s3", + [("atkPct".into(), self.attack)].into(), + f64::INFINITY, + )?; + let from = k + .world + .unit_mut(id)? + .operator + .tactical + .ines_mut()? + .sentry_at + .take(); + if let Some(from) = from { + k.world + .unit_mut(id)? + .operator + .tactical + .ines_mut()? + .sentry + .clear(); + let to = k.world.unit(id)?.position; + let delta = [to[0] - from[0], to[1] - from[1]]; + let len = delta[0] * delta[0] + delta[1] * delta[1]; + let mut hits = Vec::new(); + for target in k.enemies(None, true)? { + let p = k.world.unit(target)?.position; + let t = if len > 1e-9 { + (((p[0] - from[0]) * delta[0] + (p[1] - from[1]) * delta[1]) / len) + .clamp(0., 1.) + } else { + 0. + }; + let distance = body::distance( + k.world.unit(target)?, + [from[0] + t * delta[0], from[1] + t * delta[1]], + ); + if distance <= self.recall_radius + 1e-9 { + hits.push((t, distance, target)); + } + } + hits.sort_by(|a, b| { + a.0.total_cmp(&b.0) + .then(a.1.total_cmp(&b.1)) + .then(a.2.cmp(&b.2)) + }); + let damage = k.stat(id, "atk")? * self.recall_scale; + for (_, _, target) in hits.into_iter().take(self.recall_targets) { + k.damage(target, damage, DamageType::Physical, true, "sentryRecall")?; + } + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + if self.mode == Mode::Second { + self.clear_aspd(k)?; + } + if self.mode == Mode::Third { + k.remove(id, "ines:s3")?; + } + } + KitEvent::Attack { context, .. } + if context.attacker == id && context.is_skill && self.mode == Mode::Second => + { + k.dp(self.dp)?; + } + KitEvent::Impact(impact) + if impact.attacker == id && impact.kind == attacks::VictimKind::Main => + { + let Some(target) = impact.target else { + return Ok(()); + }; + if self.mode == Mode::First && impact.is_skill { + k.dp(self.dp)?; + if k.world.unit(target)?.stats.alive { + let mut buff = Buff { + key: Some(format!("ines:bleed:{id}")), + ..Default::default() + }; + buff.runtime.duration = self.bleed_duration + 1e-6; + buff.runtime.interval = 1.; + buff.runtime.refresh = buffs::Refresh::Extend; + buff.runtime.on_tick = Some(BLEED); + k.add(target, buff)?; + } + } + // S2's live onHit hook follows the skill state at impact. S1's + // attack override above stays attached to the launched projectile. + if self.mode == Mode::Second && k.active()? && k.world.unit(target)?.stats.alive { + let gain = self + .steal_aspd + .min(self.aspd_cap - k.world.unit(id)?.operator.tactical.ines()?.aspd); + if gain > 0. { + let key = format!("ines:aspd:{id}"); + let old = k + .world + .unit(target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some(&key)) + .and_then(|b| b.mods.get("aspd")) + .copied() + .unwrap_or(0.); + k.buff( + target, + &key, + [("aspd".into(), old - gain)].into(), + f64::INFINITY, + )?; + let s = k.world.unit_mut(id)?.operator.tactical.ines_mut()?; + s.aspd += gain; + s.aspd_victims.insert(target); + let total = s.aspd; + k.buff( + id, + "ines:aspdGain", + [("aspd".into(), total)].into(), + f64::INFINITY, + )?; + } + } + } + KitEvent::Landed { event, request } + if event.source == Some(id) + && request.hit.damage_type != DamageType::Elemental + && k.world.unit(event.target)?.side == health::Side::Enemy => + { + if self.mode == Mode::Third && k.active()? && event.amount > 0. { + k.dp(self.dp)?; + } + if k.world.unit(id)?.stats.alive + && k.world + .unit_mut(id)? + .operator + .tactical + .ines_mut()? + .woven + .insert(event.target) + && k.world.unit(event.target)?.stats.alive + { + k.status(event.target, "bind", self.bind, None)?; + k.buff( + event.target, + &format!("ines:atkSteal:{id}"), + [("atkFlat".into(), -self.steal_atk)].into(), + f64::INFINITY, + )?; + k.world + .unit_mut(id)? + .operator + .tactical + .ines_mut()? + .atk_victims + .push(event.target); + self.refresh(k)?; + } + } + KitEvent::Death { unit, .. } => { + if *unit == id { + let targets = std::mem::take( + &mut k + .world + .unit_mut(id)? + .operator + .tactical + .ines_mut()? + .atk_victims, + ); + for target in targets { + if k.world.unit(target).is_ok() { + k.remove(target, &format!("ines:atkSteal:{id}"))?; + } + } + let now = k.world.time; + let unit = k.world.unit_mut(id)?; + let s = unit.operator.tactical.ines_mut()?; + s.woven.clear(); + if !s.first_retreat + && self.respawn != 0. + && unit.deployment.respawn_at.is_finite() + { + s.first_retreat = true; + unit.deployment.respawn_at = + now + (unit.deployment.respawn_at - now) * (1. + self.respawn).max(0.); + } + } else { + self.refresh(k)?; + } + } + KitEvent::Scheduled(due) if due[1] => { + let mut keys = k.world.unit(id)?.operator.tactical.ines()?.sentry.clone(); + if k.up() { + keys.extend(k.keys()?); + } + keys.sort_unstable(); + keys.dedup(); + if !keys.is_empty() { + // Reveals must also cover enemies that cannot yet be selected. + for target in k.host.spawns.as_ref().unwrap().live().to_vec() { + let enemy = k.world.unit(target)?; + if !enemy.stats.alive || enemy.hidden || !body::in_range(enemy, &keys) { + continue; + } + let mut buff = Buff { + key: Some(format!("ines:sentry:{id}")), + mods: [("moveMul".into(), (1. + self.slow).max(0.))].into(), + flags: ["reveal".into()].into(), + ..Default::default() + }; + buff.runtime.duration = 0.25; + k.add(target, buff)?; + } + } + let valid: BTreeSet<_> = k.world.unit_ids().collect(); + k.world + .unit_mut(id)? + .operator + .tactical + .ines_mut()? + .woven + .retain(|target| valid.contains(target)); + } + KitEvent::Buff { + context, + event: buffs::Event::Tick, + token, + } if *token == BLEED => { + if k.buffs + .get(k.world, context.unit, context.buff)? + .runtime + .source + != Some(id) + { + return Ok(()); + } + let amount = k.stat(id, "atk")? * self.bleed; + k.damage(context.unit, amount, DamageType::Arts, true, "dot")?; + } + _ => {} + } + Ok(()) + } +} + +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + let mut state = Self::default(); + if let Some(previous) = previous { + state.woven = previous.woven.clone(); + state.atk_victims = previous.atk_victims.clone(); + state.sentry = previous.sentry.clone(); + state.sentry_at = previous.sentry_at.clone(); + state.placed = previous.placed.clone(); + state.first_retreat = previous.first_retreat.clone(); + } + state + } +} diff --git a/crates/engine/src/battle/runtime/kits/kazema.rs b/crates/engine/src/battle/runtime/kits/kazema.rs new file mode 100644 index 0000000..c356a65 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/kazema.rs @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "SPECIAL", + branch: "dollkeeper", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_kazema_2", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "DEFAULT", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + s.modifiers = [("atkPct".into(), n(&raw["skill"]["bb"], "atk", 0.))].into(); + s.extra.tactics = Tactics::Kazema(Kazema { + loss: n(&raw["skill"]["bb"], "hp_ratio", 0.), + scale: n(talent_at(raw, 0), "damage_scale", 0.), + duration: n(&raw["trait"]["bb"], "duration", 20.), + bonus: n(&raw["trait"]["bb"], "atk", 0.), + grid: tactical_grid(&raw["trait"]["rangeGrid"], false)?, + }); + Ok(()) +} +pub(crate) struct Kazema { + loss: f64, + scale: f64, + duration: f64, + bonus: f64, + pub grid: Vec<[i32; 2]>, +} +#[derive(Default)] +pub(crate) struct State { + pub dollkeeper: super::dollkeeper::State, + token: Option, + substituted: bool, +} +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + Self { + // The tick observer, rather than deployment, detects a form change. + // An immediate revive and another substitution can happen between ticks. + substituted: previous.is_some_and(|s| s.substituted), + ..Default::default() + } + } +} +impl Kazema { + fn token_stats(k: &KitContext<'_>) -> Result { + let def = k.host.tac_def(k.unit)?; + let token = + &k.host.data.table("tokens").ok_or("Missing summon data")?["token_10022_kazema_shadow"]; + Ok(token["variants"][&def.key] + .get("stats") + .unwrap_or(&token["stats"]) + .clone()) + } + fn burst(&self, k: &mut KitContext<'_>, source: Id) -> Result<(), String> { + let tile = k + .world + .unit(source)? + .position + .map(|value| (value + 0.5).floor() as i32); + let amount = k.stat(source, "atk")? * self.scale; + let owner = k.unit; + k.unit = source; + let result = (|| { + for target in k.world.unit_ids().collect::>() { + let e = k.world.unit(target)?; + if e.side == health::Side::Enemy + && Host::tac_up(k.world, target) + && !e.hidden + && body::tile_reach(e, tile[0], tile[1]) <= 1. + && !k.flag(target, "untargetable")? + { + k.damage(target, amount, DamageType::Arts, true, "talent")?; + } + } + Ok(()) + })(); + k.unit = owner; + result + } +} +impl Behavior for Kazema { + fn profile( + &self, + w: &World, + id: Id, + _: Option<&skills::Runtime>, + profile: &mut search::AttackProfile, + ) -> Result<(), String> { + if w.unit(id)?.operator.tactical.kazema()?.dollkeeper.doll { + profile.selection.can_hit_fly = true; + } + Ok(()) + } + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Fatal(_)) { + -100 + } else { + 0 + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + super::dollkeeper::handle(k, event)?; + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + let amount = k.world.unit(id)?.stats.hp * self.loss; + if amount > 0. && k.world.unit(id)?.stats.hp - amount >= 1. { + k.lose_hp(amount)?; + } + if let Some(tile) = k.free_adjacent()? { + if let Some(token) = k.summon("token_10022_kazema_shadow", tile, 0.)? { + k.world.unit_mut(id)?.operator.tactical.kazema_mut()?.token = Some(token); + self.burst(k, token)?; + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + if let Some(token) = k + .world + .unit_mut(id)? + .operator + .tactical + .kazema_mut()? + .token + .take() + { + let owner = k.unit; + k.unit = token; + let result = k.retreat(); + k.unit = owner; + result?; + } + } + KitEvent::Fatal(context) if context.target == id && !context.prevented => { + let state = k.world.unit(id)?.operator.tactical.kazema()?; + if state.dollkeeper.switching { + context.prevented = true; + } else if !state.dollkeeper.doll { + let stats = Self::token_stats(k)?; + let hp = n( + &stats, + "maxHp", + k.world.unit(id)?.stats.base_number("maxHp"), + ) / k.world.unit(id)?.stats.base_number("maxHp").max(1.); + context.prevented = super::dollkeeper::enter(k, self.duration, hp, false)?; + } + } + KitEvent::Resume { unit, skill } if *unit == id => super::dollkeeper::resume(k, skill)?, + KitEvent::Attack { + context, + skill: Some(skill), + } if context.attacker == id => super::dollkeeper::resume(k, skill)?, + KitEvent::BeforeStatus(context) + if context.target == id + && k.world + .unit(id)? + .operator + .tactical + .kazema()? + .dollkeeper + .switching + && ["stun", "freeze", "sleep"].contains(&context.key.as_str()) => + { + context.cancelled = true + } + KitEvent::Tick => { + let active = k.up() && k.has(id, "trait:substitute"); + let previous = k.world.unit(id)?.operator.tactical.kazema()?.substituted; + if active && !previous { + k.world + .unit_mut(id)? + .operator + .tactical + .kazema_mut()? + .substituted = true; + let stats = Self::token_stats(k)?; + let mods = [ + ( + "atkFlat".into(), + n(&stats, "atk", 0.) - k.world.unit(id)?.stats.base_number("atk"), + ), + ( + "defFlat".into(), + n(&stats, "def", 0.) - k.world.unit(id)?.stats.base_number("def"), + ), + ("atkPct".into(), self.bonus), + ] + .into(); + k.buff(id, "kazema:doll", mods, f64::INFINITY)?; + self.burst(k, id)?; + } else if !active && previous { + k.world + .unit_mut(id)? + .operator + .tactical + .kazema_mut()? + .substituted = false; + k.remove(id, "kazema:doll")?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/kjera.rs b/crates/engine/src/battle/runtime/kits/kjera.rs new file mode 100644 index 0000000..328cdfd --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/kjera.rs @@ -0,0 +1,263 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "funnel", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_kjera_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skcom_atk_up[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skcom_atk_up[3]" => Mode::First, + "skchr_kjera_2" => Mode::Second, + _ => return Err("Unknown selected skill".into()), + }; + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + s.extra.tactics = Tactics::Kjera(Kjera { + mode: mode, + funnel: funnel::Parameters::read(raw), + drones: 1 + n(bb, "attack@cnt", 0.).max(0.) as usize, + prob: n(bb, "attack@prob", 0.), + cold: n(bb, "attack@cold", 0.), + low_count: n(t, "cnt", 2.), + atk: n(t, "atk", 0.), + low_atk: n(t, "kjera_t_1[high].atk", n(t, "atk", 0.)), + base_grid: tactical_grid(&raw["rangeGrid"], false)?, + }); + Ok(()) +} +pub(crate) struct Kjera { + pub mode: Mode, + pub funnel: funnel::Parameters, + pub drones: usize, + pub prob: f64, + pub cold: f64, + pub low_count: f64, + pub atk: f64, + pub low_atk: f64, + pub base_grid: Vec<[i32; 2]>, +} +#[derive(Default)] +pub(crate) struct State { + pub funnel: funnel::State, + pub released: funnel::State, + pub drones: Vec>, + pub cooldown: f64, +} +impl Behavior for Kjera { + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Before(_)) { + -100 + } else { + 0 + } + } + + fn payload( + &self, + world: &World, + id: Id, + payload: &mut attacks::Direct, + _: &mut attacks::Area, + ) -> Result<(), String> { + if !(self.mode == Mode::Second && world.unit(id)?.operator.active_skill) { + payload.attachment = Some(self.funnel.attachment(payload.hits, true)); + payload.hits = 1; + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Before(context) if context.attacker == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .kjera_mut()? + .funnel + .map + .retain(|target, _| context.targets.contains(target)); + } + + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == id => { + let keys = k.range(&self.base_grid)?; + let grid = k.host.grid.as_ref().ok_or("Kjera deployment needs grid")?; + let low = keys + .into_iter() + .filter(|&key| grid.tiles()[key].height == "LOW") + .count(); + let attack = if low as f64 >= self.low_count { + self.low_atk + } else { + self.atk + }; + k.buff( + id, + "talent:kjera_brow", + [("atkPct".into(), attack)].into(), + f64::INFINITY, + )?; + } + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id && self.mode == Mode::Second => { + if self.drones > crate::battle::operators::Combat::MAX_HITS as usize { + return Err("Released drone capacity exceeded".into()); + } + let s = k.world.unit_mut(id)?.operator.tactical.kjera_mut()?; + s.released = s.funnel.clone(); + s.drones = vec![None; self.drones]; + s.cooldown = 0.; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id && self.mode == Mode::Second => { + let valid: BTreeSet<_> = k + .world + .unit_ids() + .filter(|&target| k.world.unit(target).is_ok_and(|u| u.stats.alive)) + .collect(); + k.world + .unit_mut(id)? + .operator + .tactical + .kjera_mut()? + .released + .map + .retain(|target, _| valid.contains(target)); + let mut locks = k.world.unit(id)?.operator.tactical.kjera()?.drones.clone(); + let candidates = k.enemies(None, true)?; + for lock in &mut locks { + if let Some(target) = *lock { + if !Host::tac_up(k.world, target) + || !targeting::can_target_enemy( + k.world, + k.host, + Some(id), + target, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? + { + *lock = None; + } + } + } + for index in 0..locks.len() { + if locks[index].is_some() { + continue; + } + locks[index] = candidates + .iter() + .copied() + .find(|e| !locks.contains(&Some(*e))) + .or_else(|| candidates.first().copied()) + .or_else(|| locks.iter().flatten().copied().next()); + } + let due = { + let s = k.world.unit_mut(id)?.operator.tactical.kjera_mut()?; + s.drones = locks.clone(); + s.cooldown = (s.cooldown - context.dt).max(0.); + s.cooldown <= 1e-9 && locks.iter().any(Option::is_some) + }; + if due { + let interval = k.stat(id, "interval")?; + k.world + .unit_mut(id)? + .operator + .tactical + .kjera_mut()? + .cooldown = interval; + for target in locks.into_iter().flatten() { + if !Host::tac_up(k.world, target) { + continue; + } + let time = k.world.time; + let scale = k + .world + .unit_mut(id)? + .operator + .tactical + .kjera_mut()? + .released + .step(target, time, self.funnel, true); + let amount = k.stat(id, "atk")? * k.stat(id, "atkScaleMul")? * scale; + k.damage(target, amount, DamageType::Arts, true, "kjera:drone")?; + if Host::tac_up(k.world, target) + && self.cold > 0. + && k.host.rng.chance(self.prob) + { + k.status(target, "cold", self.cold, None)?; + } + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id && self.mode == Mode::Second => { + let s = k.world.unit_mut(id)?.operator.tactical.kjera_mut()?; + s.funnel = std::mem::take(&mut s.released); + s.drones.clear(); + } + KitEvent::Landed { + event: landed, + request, + } if landed.source == Some(id) + && self.mode == Mode::Second + && k.active()? + && request.is_attack + && !request.is_skill + && landed.target != id => + { + if self.cold > 0. + && Host::tac_up(k.world, landed.target) + && k.host.rng.chance(self.prob) + { + k.status(landed.target, "cold", self.cold, None)?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/lemuen.rs b/crates/engine/src/battle/runtime/kits/lemuen.rs new file mode 100644 index 0000000..d30198d --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/lemuen.rs @@ -0,0 +1,502 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{deploy, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "longrange", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[Skill { + id: "skchr_lemuen_3", + kind: Kind::Ammo, + sp_type: skills::SpType::Time, + rule: "DEFAULT", + attack_override: true, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + s.extra.effects.ammo_count = n(bb, "attack@trigger_time", 5.).floor().max(1.); + let mut profile = s.combat.profile; + profile.no_attack = true; + s.combat.skill_profile = Some(profile); + s.combat.profile.priority = targeting::Priority::LowDef; + s.extra.tactics = Tactics::Lemuen(Lemuen { + aim: n(bb, "attack@aim_interval", 0.5).max(0.05), + inner: n(bb, "attack@dist_1", 0.8), + outer: n(bb, "attack@dist_2", 1.5), + close: n(bb, "attack@proj_atk_scale_1", 1.), + far: n(bb, "attack@proj_atk_scale_2", 1.), + spread: n(bb, "attack@emit_offset", 0.2).max(0.), + wanted_interval: n(t, "interval", 8.), + wanted_scale: n(t, "damage_scale", 1.), + extradition: n(t1, "interval", 20.), + attack: n(t1, "atk", 0.), + ammo: n(t1, "add_count", 0.), + other_ammo: n(t1, "ex_add_count", 0.), + sp: n(&raw["trait"]["bb"], "sp", 0.), + }); + Ok(()) +} +pub(crate) struct Lemuen { + aim: f64, + inner: f64, + outer: f64, + close: f64, + far: f64, + spread: f64, + wanted_interval: f64, + wanted_scale: f64, + extradition: f64, + attack: f64, + ammo: f64, + other_ammo: f64, + sp: f64, +} +#[derive(Clone)] +struct Lock { + target: Id, + position: [f64; 2], + gone: bool, +} +struct Volley { + locks: Vec, + attack: f64, + next: usize, +} +#[derive(Default)] +pub(crate) struct State { + accumulator: f64, + locks: Vec, + times: BTreeMap, + marks: BTreeSet, + volleys: BTreeMap, + sequence: u64, +} +impl Lock { + fn update(&mut self, w: &World) { + if let Ok(e) = w.unit(self.target) { + if !self.gone && (!e.stats.alive || !e.hidden) { + self.position = e.position; + self.gone = !e.stats.alive; + } + } + } +} +impl Lemuen { + fn extradition(k: &mut KitContext<'_>) -> Result<(), String> { + let def = k.host.tac_def(k.unit)?; + let Tactics::Lemuen(p) = &def.extra.tactics else { + return Err("Missing Lemuen kit".into()); + }; + if k.up() && p.attack != 0. { + k.buff( + k.unit, + "lemuen:extradition", + [("atkPct".into(), p.attack)].into(), + f64::INFINITY, + )?; + } + Ok(()) + } + fn blast(k: &mut KitContext<'_>, position: [f64; 2], attack: f64) -> Result<(), String> { + let def = k.host.tac_def(k.unit)?; + let Tactics::Lemuen(p) = &def.extra.tactics else { + return Err("Missing Lemuen kit".into()); + }; + for target in attacks::Hooks::radius_targets( + k.host, + position, + p.outer, + true, + k.world, + k.world.unit_capacity(), + )? { + if k.flag(target, "untargetable")? { + continue; + } + let amount = attack + * if body::distance(k.world.unit(target)?, position) <= p.inner + 1e-9 { + p.close + } else { + p.far + }; + let mut request = hit::Request::new( + health::Hit { + source: Some(k.unit), + credit: Some(k.unit), + target, + damage_type: DamageType::Physical, + no_sp: false, + hp_loss: false, + silent: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.is_skill = true; + request.is_splash = true; + request.tags = ["skill".into(), "bombard".into()].into(); + k.deal(&mut request)?; + } + Ok(()) + } + fn fire(k: &mut KitContext<'_>, key: u64) -> Result<(), String> { + let def = k.host.tac_def(k.unit)?; + let Tactics::Lemuen(p) = &def.extra.tactics else { + return Err("Missing Lemuen kit".into()); + }; + let mut volley = match k + .world + .unit_mut(k.unit)? + .operator + .tactical + .lemuen_mut()? + .volleys + .remove(&key) + { + Some(v) => v, + None => return Ok(()), + }; + let lock = &mut volley.locks[volley.next]; + lock.update(k.world); + let local = [ + (k.host.rng.next_f64() * 2. - 1.) * p.spread, + (k.host.rng.next_f64() * 2. - 1.) * p.spread, + ]; + let dir = k.host.roster.as_ref().unwrap().entry(k.unit)?.direction; + let offset = match dir { + Direction::Right => local, + Direction::Left => [-local[0], -local[1]], + Direction::Up => [local[1], -local[0]], + Direction::Down => [-local[1], local[0]], + }; + k.later_at( + 0.3, + [lock.position[0] + offset[0], lock.position[1] + offset[1]], + volley.attack, + true, + Self::blast, + )?; + volley.next += 1; + if volley.next < volley.locks.len().min(33) { + k.world + .unit_mut(k.unit)? + .operator + .tactical + .lemuen_mut()? + .volleys + .insert(key, volley); + k.later_key(0.3, key, Self::fire)?; + } + Ok(()) + } + fn reconcile(k: &mut KitContext<'_>) -> Result<(), String> { + let mut marks = BTreeSet::new(); + for id in k.host.roster.as_ref().unwrap().ids() { + if Host::tac_up(k.world, *id) { + if let Ok(state) = k.world.unit(*id)?.operator.tactical.lemuen() { + marks.extend(state.marks.iter().copied()); + } + } + } + let enemies = k + .world + .unit_ids() + .filter(|&id| { + k.world + .unit(id) + .is_ok_and(|u| u.side == health::Side::Enemy) + }) + .collect::>(); + for enemy in enemies { + if marks.contains(&enemy) && Host::tac_up(k.world, enemy) { + if !k.has(enemy, "lemuen:wanted") { + k.buff(enemy, "lemuen:wanted", Numbers::new(), f64::INFINITY)?; + } + } else { + k.remove(enemy, "lemuen:wanted")?; + } + } + for id in k.host.roster.as_ref().unwrap().ids().to_vec() { + if k.world.unit(id)?.operator.tactical.lemuen().is_ok() { + let mut keys = Vec::new(); + if Host::tac_up(k.world, id) { + for &enemy in &marks { + // Marks are pruned on the quarter-second scan. A killed + // enemy may already have been reclaimed between scans. + let Ok(u) = k.world.unit(enemy) else { continue }; + if Host::tac_up(k.world, enemy) && !u.hidden { + for key in body::keys(u) { + if !keys.contains(&key) { + keys.push(key); + } + } + } + } + } + k.world.unit_mut(id)?.operator.advanced.extra_range = keys; + } + } + Ok(()) + } +} +impl Behavior for Lemuen { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == id => { + k.later(self.extradition, Self::extradition)?; + } + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + let state = k.world.unit_mut(id)?.operator.tactical.lemuen_mut()?; + state.locks.clear(); + state.accumulator = self.aim; + } + KitEvent::SkillObserved { + unit, + event: skills::Event::SkillStart, + skill, + } if k.up() + && skill.bank.kind == Kind::Ammo + && k.world.time - k.world.unit(id)?.deployment.deployed_at + >= self.extradition - 1e-6 => + { + if *unit == id { + skill.add_ammo(self.ammo); + } else if k.faction(*unit, "lateranoShip", &[])? { + skill.add_ammo(self.other_ammo); + } + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + skill, + } if *unit == id && skill.bank.active => { + let mut locks = std::mem::take( + &mut k.world.unit_mut(id)?.operator.tactical.lemuen_mut()?.locks, + ); + for lock in &mut locks { + lock.update(k.world); + } + k.world.unit_mut(id)?.operator.tactical.lemuen_mut()?.locks = locks; + if skills::can_act(k.world, id)? { + let accumulator = + k.world.unit(id)?.operator.tactical.lemuen()?.accumulator + context.dt; + k.world + .unit_mut(id)? + .operator + .tactical + .lemuen_mut()? + .accumulator = accumulator; + if accumulator + 1e-9 >= self.aim { + let mut candidates = k.enemies(None, true)?; + targeting::sort_enemies( + k.world, + k.host, + id, + &mut candidates, + targeting::Priority::LowDef, + )?; + let locks = &k.world.unit(id)?.operator.tactical.lemuen()?.locks; + let target = candidates.into_iter().min_by_key(|target| { + locks.iter().filter(|lock| lock.target == *target).count() + }); + if let Some(target) = target { + let position = k.world.unit(target)?.position; + let state = k.world.unit_mut(id)?.operator.tactical.lemuen_mut()?; + state.accumulator -= self.aim; + if state.locks.len() >= 64 { + return Err("Lemuen lock capacity exceeded".into()); + } + state.locks.push(Lock { + target, + position, + gone: false, + }); + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + skill.consume_ammo(world, host) + })?; + } else { + k.world + .unit_mut(id)? + .operator + .tactical + .lemuen_mut()? + .accumulator = self.aim; + } + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + context, + .. + } if *unit == id => { + let locks = std::mem::take( + &mut k.world.unit_mut(id)?.operator.tactical.lemuen_mut()?.locks, + ); + if context.reason != "death" && k.up() && !locks.is_empty() { + let attack = k.stat(id, "atk")?; + let state = k.world.unit_mut(id)?.operator.tactical.lemuen_mut()?; + if state.volleys.len() >= k.host.tactical_limit { + return Err("Lemuen volley capacity exceeded".into()); + } + state.sequence = state + .sequence + .checked_add(1) + .ok_or("Lemuen volley sequence exhausted")?; + let key = state.sequence; + state.volleys.insert( + key, + Volley { + locks, + attack, + next: 0, + }, + ); + Self::fire(k, key)?; + } + } + KitEvent::Scheduled(due) if due[2] && k.up() => { + let mut ranges = Vec::new(); + for ally in k.host.roster.as_ref().unwrap().ids().to_vec() { + if Host::tac_up(k.world, ally) + && k.world.unit(ally)?.deployment.kind == deploy::Kind::Operator + && k.faction(ally, "lateranoShip", &[])? + { + ranges.push(k.host.roster.as_ref().unwrap().range(k.world, ally)?); + } + } + let valid = k + .world + .unit_ids() + .filter(|&e| { + k.world + .unit(e) + .is_ok_and(|u| u.side == health::Side::Enemy && u.stats.alive) + }) + .collect::>(); + { + let state = k.world.unit_mut(id)?.operator.tactical.lemuen_mut()?; + state.times.retain(|e, _| valid.contains(e)); + state.marks.retain(|e| valid.contains(e)); + } + for enemy in valid { + let u = k.world.unit(enemy)?; + if !(u.boss || u.targeting.elite) + || k.world + .unit(id)? + .operator + .tactical + .lemuen()? + .marks + .contains(&enemy) + { + continue; + } + if u.hidden || !ranges.iter().any(|keys| body::in_range(u, keys)) { + k.world + .unit_mut(id)? + .operator + .tactical + .lemuen_mut()? + .times + .remove(&enemy); + continue; + } + if !k + .world + .unit(id)? + .operator + .tactical + .lemuen()? + .times + .contains_key(&enemy) + && k.host.tac_selectable(k.world, id, vec![enemy])?.is_empty() + { + continue; + } + let state = k.world.unit_mut(id)?.operator.tactical.lemuen_mut()?; + let time = state.times.entry(enemy).or_default(); + *time += 0.25; + if *time >= self.wanted_interval - 1e-9 { + state.marks.insert(enemy); + } + } + Self::reconcile(k)?; + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if k.up() + && k.has(request.hit.target, "lemuen:wanted") + && (request.is_attack || request.is_skill) => + { + if let Some(source) = request.hit.source { + if k.faction(source, "lateranoShip", &[])? { + let strongest = k + .host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .filter(|&a| Host::tac_up(k.world, a)) + .filter_map(|a| match &k.host.tac_def(a).ok()?.extra.tactics { + Tactics::Lemuen(p) => Some((a, p.wanted_scale)), + _ => None, + }) + .max_by(|a, b| a.1.total_cmp(&b.1).then(b.0.cmp(&a.0))); + if strongest.is_some_and(|(source, _)| source == id) { + request.damage.mul *= self.wanted_scale; + } + } + } + } + KitEvent::Impact(impact) + if impact.attacker == id + && self.sp > 0. + && impact.target.is_some_and(|a| Host::tac_up(k.world, a)) + && !k.active()? => + { + let amount = self.sp; + k.skill(|skill, host, w| skill.gain(w, host, amount, "trait", false, false))?; + } + KitEvent::Death { unit, .. } if *unit == id => { + let state = k.world.unit_mut(id)?.operator.tactical.lemuen_mut()?; + state.times.clear(); + state.marks.clear(); + Self::reconcile(k)?; + } + KitEvent::Tick => Self::reconcile(k)?, + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/lumen.rs b/crates/engine/src/battle/runtime/kits/lumen.rs new file mode 100644 index 0000000..a62df1b --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/lumen.rs @@ -0,0 +1,429 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "healer", + ranged: false, + can_hit_fly: false, + physical: false, + projectile: "orb", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_lumen_3", + kind: Kind::Ammo, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_lumen_1", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_lumen_2", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = tactical_mode(raw)?; + + healing(s, 1.); + if mode == Mode::Third { + s.extra.effects.ammo_count = n(bb, "attack@trigger_time", 4.); + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("aspd".into(), n(bb, "attack_speed", 0.)), + ] + .into(); + } + if n(tb, "taunt_level", 0.) != 0. { + s.extra.effects.permanent.push(persistent( + "lumen:scope", + [("taunt".into(), n(tb, "taunt_level", 0.))].into(), + )); + } + if n(tb, "one_minus_status_resistance", 0.) < 0. { + let mut b = persistent("lumen:scopeResist", Numbers::new()); + b.runtime.status = Some("resist".into()); + b.runtime.tick_payload = -n(tb, "one_minus_status_resistance", 0.); + s.extra.effects.permanent.push(b); + } + s.extra.tactics = Tactics::Lumen(Lumen { + mode, + heal: n(bb, "heal_scale", 1.), + targets: n(bb, "max_target", 2.).max(1.) as usize, + rain: suffix_number(bb, "heal_scale", 0.), + rain_life: suffix_number(bb, "projectile_life_time", 4.), + rain_interval: suffix_number(bb, "interval", 1.), + base: n(t, "status_resistance[limit]", 0.), + special: n( + t, + "lumen_t_1[special].status_resistance[limit]", + n(t, "status_resistance[limit]", 0.), + ), + resist: (-n(t, "one_minus_status_resistance", -0.5)).clamp(0., 1.), + threshold: n(t, "hp_ratio", 0.75), + emergency: n(t1, "heal_scale", 0.), + cooldown: n(t1, "duration", 12.), + far: n(tb, "heal_scale", 0.8), + }); + Ok(()) +} + +pub(crate) struct Lumen { + pub mode: Mode, + pub heal: f64, + pub targets: usize, + pub rain: f64, + pub rain_life: f64, + pub rain_interval: f64, + pub base: f64, + pub special: f64, + pub resist: f64, + pub threshold: f64, + pub emergency: f64, + pub cooldown: f64, + pub far: f64, +} + +pub(crate) struct State { + pub abnormal: bool, + pub ready: f64, +} +impl Default for State { + fn default() -> Self { + Self { + abnormal: Default::default(), + ready: f64::NEG_INFINITY, + } + } +} + +impl Host { + pub(in crate::battle::runtime) fn lumen_start( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + s: &mut skills::Runtime, + p: &Lumen, + ) -> Result<(), String> { + if p.mode == Mode::Second { + let full = + s.bank.max_charges() > 1 && s.bank.charges >= f64::from(s.bank.max_charges() - 1); + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let mut ids = self.tac_heal_targets(w, id, &keys, true)?; + if full { + for a in self.tac_heal_targets(w, id, &keys, false)? { + if !ids.contains(&a) && Self::tac_abnormal(w, a) { + ids.push(a); + } + } + } + for a in ids.into_iter().take(p.targets) { + let amount = Self::tac_stat(w, id, "atk")? * p.heal; + self.tac_heal(w, r, id, a, amount)?; + if full { + self.tac_cleanse(w, r, a)?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn lumen_before( + &mut self, + w: &mut World, + id: Id, + active: bool, + c: &mut attacks::Context, + p: &Lumen, + ) -> Result<(), String> { + if active && p.mode == Mode::Third { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let targets = self.tac_heal_targets(w, id, &keys, false)?; + let abnormal = targets.into_iter().find(|&a| Self::tac_abnormal(w, a)); + w.unit_mut(id)?.operator.tactical.lumen_mut()?.abnormal = abnormal.is_some(); + if let Some(a) = abnormal { + c.targets = vec![a]; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn lumen_attack( + &mut self, + w: &mut World, + id: Id, + active: bool, + c: &mut attacks::Context, + p: &Lumen, + ) -> Result<(), String> { + if active && p.mode == Mode::Third { + c.no_ammo = !w.unit(id)?.operator.tactical.lumen()?.abnormal; + w.unit_mut(id)?.operator.tactical.lumen_mut()?.abnormal = false; + } + Ok(()) + } + pub(in crate::battle::runtime) fn lumen_impact( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + target: Id, + impact: attacks::Impact, + p: &Lumen, + ) -> Result<(), String> { + if impact.heal && impact.is_skill { + if p.mode == Mode::Third && w.unit(id)?.operator.tactical.lumen()?.abnormal { + self.tac_cleanse(w, r, target)?; + } + if p.mode == Mode::First && p.rain > 0. { + let position = w.unit(target)?.position; + for a in self.roster.as_ref().unwrap().ids().to_vec() { + if Self::tac_up(w, a) + && body::in_radius(w.unit(a)?, position, 1.5) + && !Self::tac_has(w, a, "noHeal") + && !w.unit(a)?.profile_no_heal + { + let mut b = Buff { + key: Some(format!("lumen:rain:{id}")), + ..Default::default() + }; + b.runtime.source = Some(id); + b.runtime.duration = p.rain_life; + b.runtime.interval = p.rain_interval.max(0.2); + b.runtime.tick_payload = p.rain; + b.runtime.on_tick = Some(RAIN); + r.add( + w, + self, + a, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn lumen_heal_event( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + e: &health::Event, + p: &Lumen, + ) -> Result<(), String> { + if e.kind != health::Kind::Regen && p.resist > 0. && p.base > 0. { + let max = Self::tac_stat(w, e.target, "maxHp")?; + let after = (w.unit(e.target)?.stats.hp + e.amount).min(max); + self.advanced_status( + w, + r, + id, + e.target, + "resist", + if after / max > p.threshold { + p.special + } else { + p.base + }, + Some(p.resist), + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn lumen_tick( + &mut self, + w: &mut World, + id: Id, + def: &Definition, + s: &mut skills::Runtime, + ) -> Result<(), String> { + if s.bank.active + && w.unit(id)?.cadence.cooldown <= 0. + && skills::can_act(w, id)? + && !Self::tac_has(w, id, "disarm") + { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + if self.tac_heal_targets(w, id, &keys, true)?.is_empty() { + if let Some(target) = self + .tac_heal_targets(w, id, &keys, false)? + .into_iter() + .find(|&a| Self::tac_abnormal(w, a)) + { + ally::Host::perform( + self, + id, + def.combat.profile, + search::Selection { + targets: vec![target], + fortress_melee: None, + }, + Some(s), + w, + )?; + w.unit_mut(id)?.cadence.cooldown = Self::tac_stat(w, id, "interval")?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn lumen_rain_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + let b = r.get(w, c.unit, c.buff)?.clone(); + let id = b.runtime.source.ok_or("Missing lumen buff source")?; + + if w.unit(c.unit)?.stats.hp >= Self::tac_stat(w, c.unit, "maxHp")? { + return Ok(()); + } + let amount = Self::tac_stat(w, id, "atk")? * b.runtime.tick_payload; + self.tac_heal(w, r, id, c.unit, amount)?; + Ok(()) + } +} + +impl Behavior for Lumen { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::StatusFinished(_)) + } + fn refreshes_skill(&self) -> bool { + self.mode == Mode::Third + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + ( + Role::Source, + KitEvent::Buff { + context, + event: buffs::Event::Tick, + token: RAIN, + }, + ) => { + k.host.lumen_rain_tick(k.world, k.buffs, *context)?; + } + + (Role::Source, KitEvent::Before(context)) => { + let active = k.active()?; + k.host.lumen_before(k.world, id, active, context, self)?; + } + (Role::Source, KitEvent::Attack { context, .. }) => { + let active = k.active()?; + k.host.lumen_attack(k.world, id, active, context, self)?; + } + (Role::Source, KitEvent::Impact(impact)) => { + if let Some(target) = impact.target { + k.host + .lumen_impact(k.world, id, k.buffs, target, *impact, self)?; + } + } + (Role::Source, KitEvent::Heal { event, .. }) => { + k.host.lumen_heal_event(k.world, id, k.buffs, event, self)?; + } + _ => {} + } + Ok(()) + } + fn attack_heal(&self, world: &World, unit: Id, target: Id, amount: f64) -> Result { + Ok( + if self.mode == Mode::Third + && world.unit(unit)?.operator.active_skill + && Host::tac_abnormal(world, target) + { + amount * self.heal + } else { + amount + }, + ) + } + fn heal_amount( + &self, + world: &World, + unit: Id, + target: Id, + amount: f64, + options: health::HealOptions, + ) -> Result { + let a = world.unit(unit)?.deployment.tile; + let b = world.unit(target)?.deployment.tile; + Ok( + if !options.regen + && !options.restore + && (a[0] - b[0]).abs().max((a[1] - b[1]).abs()) > 2 + { + amount * self.far + } else { + amount + }, + ) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::StatusFinished(context) => { + if ABNORMAL.contains(&context.key.as_str()) + && k.world.unit(context.target)?.side == health::Side::Ally + && k.up() + && self.emergency > 0. + && k.world.time >= k.world.unit(id)?.operator.tactical.lumen()?.ready + { + let keys = k.keys()?; + let tile = k.world.unit(context.target)?.deployment.tile; + if keys.contains(&(tile[0] as usize * COLS + tile[1] as usize)) { + k.world.unit_mut(id)?.operator.tactical.lumen_mut()?.ready = + k.world.time + self.cooldown; + let amount = k.stat(id, "atk")? * self.emergency; + k.host + .tac_heal(k.world, k.buffs, id, context.target, amount)?; + } + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + k.host.lumen_start(k.world, id, k.buffs, skill, self)?; + } + KitEvent::Refresh { skill, .. } => { + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + let definition = host.tac_def(id)?; + host.lumen_tick(world, id, &definition, skill) + })?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/malist.rs b/crates/engine/src/battle/runtime/kits/malist.rs new file mode 100644 index 0000000..cbf1786 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/malist.rs @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "funnel", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_malist_2", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skcom_quickattack[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skcom_quickattack[3]" => Mode::First, + "skchr_malist_2" => Mode::Second, + _ => return Err("Unknown selected skill".into()), + }; + if mode == Mode::First { + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("aspd".into(), n(bb, "attack_speed", 0.)), + ] + .into(); + } else { + s.combat.skill_scale = n(bb, "atk_scale", 1.); + s.combat.skill_hits = 2; + } + s.extra.tactics = Tactics::Malist(Malist { + mode: mode, + funnel: funnel::Parameters::read(raw), + prob: n(t, "prob", 0.), + crit: n(t, "atk_scale", 1.), + }); + Ok(()) +} +pub(crate) struct Malist { + pub mode: Mode, + pub funnel: funnel::Parameters, + pub prob: f64, + pub crit: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub funnel: funnel::State, +} +impl Behavior for Malist { + fn payload( + &self, + _: &World, + _: Id, + payload: &mut attacks::Direct, + _: &mut attacks::Area, + ) -> Result<(), String> { + payload.attachment = Some(self.funnel.attachment(payload.hits, true)); + payload.hits = if payload.is_skill && self.mode == Mode::Second { + 2 + } else { + 1 + }; + Ok(()) + } + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Before(_)) { + -100 + } else { + 0 + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + if let KitEvent::Before(context) = event { + if context.attacker == k.unit { + k.world + .unit_mut(k.unit)? + .operator + .tactical + .malist_mut()? + .funnel + .map + .retain(|target, _| context.targets.contains(target)); + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/manifold.rs b/crates/engine/src/battle/runtime/kits/manifold.rs new file mode 100644 index 0000000..b9e362b --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/manifold.rs @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) struct Manifold { + pub scale: f64, + pub respawn: f64, + steal_attack: f64, + steal_defence: f64, + attack_cap: f64, + defence_cap: f64, + split: u64, + lifetime: f64, + guard: f64, + pub first_sp: f64, + pub force: f64, + pub taunt: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub from: Option, + pub ranged: bool, + pub clone: bool, + attack: f64, + defence: f64, + attacks: u64, +} +pub(crate) fn build(raw: &Value, s: &mut Spec) { + let talents = raw["talents"].as_array().cloned().unwrap_or_default(); + let find = |key: &str, fallback: f64| { + talents + .iter() + .find_map(|t| t["bb"][key].as_f64()) + .unwrap_or(fallback) + }; + let copy = talents + .iter() + .find(|t| t["bb"]["scale"].is_number()) + .map(|t| &t["bb"]) + .unwrap_or(&Value::Null); + let steal = talents + .iter() + .find(|t| t["bb"]["steal_atk"].is_number()) + .map(|t| &t["bb"]) + .unwrap_or(&Value::Null); + s.combat.profile.no_attack = true; + s.extra.tactics = Tactics::Manifold(Manifold { + scale: n(copy, "scale", 1.), + respawn: n(copy, "interval", 25.), + steal_attack: n(steal, "steal_atk", 0.), + steal_defence: n(steal, "steal_def", 0.), + attack_cap: n(steal, "steal_atk_max", 0.), + defence_cap: n(steal, "steal_def_max", 0.), + split: n(steal, "mlyss_wtrman_t_2[range].max_stack_cnt", 10.).max(1.) as u64, + lifetime: n(steal, "interval", 25.), + guard: find("damage_scale", 1.), + first_sp: find("sp", 0.), + force: n(&raw["nativeSkill"]["bb"], "force", 0.), + taunt: find("taunt_level", 0.), + }); +} +impl Manifold { + fn pick(k: &KitContext<'_>) -> Result, String> { + let owner = k + .world + .unit(k.unit)? + .summoner + .ok_or("Manifold has no summoner")?; + let position = k.world.unit(k.unit)?.deployment.tile; + let mut best = None; + let mut best_score = None; + for &id in k.host.roster.as_ref().unwrap().ids() { + let u = k.world.unit(id)?; + if id == owner + || !Host::tac_up(k.world, id) + || u.hidden + || u.deployment.kind != crate::battle::deploy::Kind::Operator + || u.owner != k.world.unit(owner)?.owner + { + continue; + } + let distance = (u.deployment.tile[0] - position[0]) + .abs() + .max((u.deployment.tile[1] - position[1]).abs()); + let score = (distance, -u.stats.base_number("atk"), id); + if best_score.is_none_or(|previous: (i32, f64, u64)| { + score.0 < previous.0 + || score.0 == previous.0 + && (score.1 < previous.1 || score.1 == previous.1 && score.2 < previous.2) + }) { + best = Some(id); + best_score = Some(score); + } + } + Ok(best) + } + pub(crate) fn copy( + k: &mut KitContext<'_>, + source: Id, + scale: f64, + ranged: bool, + clone: bool, + ) -> Result<(), String> { + let data = Arc::clone(&k.host.data); + k.host + .roster + .as_mut() + .unwrap() + .copy_token(&data, k.world, k.unit, source, scale, ranged)?; + k.remove(k.unit, "mlyss:stolen")?; + let state = k.world.unit_mut(k.unit)?.operator.tactical.manifold_mut()?; + *state = State { + from: Some(source), + ranged, + clone, + ..Default::default() + }; + Ok(()) + } +} +impl Behavior for Manifold { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + if let Some(source) = Self::pick(k)? { + let ranged = !k.world.unit(source)?.targeting.melee_operator; + Self::copy(k, source, self.scale, ranged, false)?; + let owner = k.world.unit(id)?.summoner.unwrap(); + let def = k.host.tac_def(owner)?; + if let Tactics::Mlyss(p) = &def.extra.tactics { + if p.copy_sp > 0. && super::mlyss::rhine(k, source)? { + let own = k.unit; + k.unit = owner; + let amount = p.copy_sp; + let result = k.skill(|skill, host, w| { + skill.gain(w, host, amount, "talent", false, false) + }); + k.unit = own; + result?; + } + } + } else { + k.host.with_kit_buffs(k.world, k.buffs, |host, w| { + skill.end(w, host, "noTarget")?; + let amount = skill.bank.cost(w)?; + skill.gain(w, host, amount, "refund", false, false) + })?; + } + } + KitEvent::Tick if k.up() && !k.world.unit(id)?.operator.tactical.manifold()?.clone => { + if Self::pick(k)?.is_some() + && skills::can_act(k.world, id)? + && !k.flag(id, "silence")? + { + let ready = { + let skill = k.host.roster.as_ref().unwrap().entry(id)?.skill()?; + skill.bank.ready() + && !skill.bank.active + && k.world.time + 1e-9 >= skill.op_ready_at + }; + if ready { + k.skill(|skill, host, w| { + skill.activate(w, host, "MLYSS_WTRMAN", false)?; + Ok(()) + })?; + } + } + } + KitEvent::Attack { context, .. } + if context.attacker == id + && k.up() + && k.world + .unit(id)? + .operator + .tactical + .manifold()? + .from + .is_some() => + { + if !k.world.unit(id)?.operator.tactical.manifold()?.ranged { + let mut changed = false; + for &enemy in &context.targets { + if !Host::tac_up(k.world, enemy) + || k.world.unit(enemy)?.side != health::Side::Enemy + { + continue; + } + let state = k.world.unit(id)?.operator.tactical.manifold()?; + let attack = self + .steal_attack + .min(self.attack_cap - state.attack) + .max(0.); + let defence = self + .steal_defence + .min(self.defence_cap - state.defence) + .max(0.); + if attack <= 0. && defence <= 0. { + break; + } + let state = k.world.unit_mut(id)?.operator.tactical.manifold_mut()?; + state.attack += attack; + state.defence += defence; + let mut old_attack = 0.; + let mut old_defence = 0.; + if let Some(buff) = k + .world + .unit(enemy)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("mlyss:robbed")) + { + old_attack = -buff.mods.get("atkFlat").copied().unwrap_or(0.); + old_defence = -buff.mods.get("defFlat").copied().unwrap_or(0.); + } + k.buff( + enemy, + "mlyss:robbed", + [ + ("atkFlat".into(), -old_attack - attack), + ("defFlat".into(), -old_defence - defence), + ] + .into(), + f64::INFINITY, + )?; + changed = true; + } + if changed { + let state = k.world.unit(id)?.operator.tactical.manifold()?; + let mods = [ + ("atkFlat".into(), state.attack), + ("defFlat".into(), state.defence), + ] + .into(); + k.buff(id, "mlyss:stolen", mods, f64::INFINITY)?; + } + } else if !k.world.unit(id)?.operator.tactical.manifold()?.clone { + let state = k.world.unit_mut(id)?.operator.tactical.manifold_mut()?; + state.attacks = state + .attacks + .checked_add(1) + .ok_or("Manifold attack counter exhausted")?; + if state.attacks % self.split == 0 { + let origin = k.world.unit(id)?.deployment.tile; + let mut tiles = Vec::new(); + for offset in [[1, 0], [-1, 0], [0, 1], [0, -1]] { + let tile = [origin[0] + offset[0], origin[1] + offset[1]]; + let grid = k.host.grid.as_ref().unwrap(); + if grid.in_rect(tile) + && grid.can_stand(tile, true) + && !k + .host + .roster + .as_ref() + .unwrap() + .deployment() + .reserved(k.world, tile)? + { + tiles.push(tile); + } + } + if let Some(tile) = k.best_summon_tile(&tiles) { + let owner = k.world.unit(id)?.summoner.unwrap(); + k.world + .unit_mut(owner)? + .operator + .tactical + .mlyss_mut()? + .clone_of = Some(id); + k.unit = owner; + let result = k.summon("token_10030_mlyss_wtrman", tile, self.lifetime); + k.unit = id; + k.world + .unit_mut(owner)? + .operator + .tactical + .mlyss_mut()? + .clone_of = None; + if let Some(clone) = result? { + k.host.roster.as_mut().unwrap().disable_token_skill(clone)?; + } + } + } + } + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.target == id + && request + .hit + .source + .is_some_and(|a| k.world.unit(a).is_ok_and(|u| u.blocked_by() == Some(id))) => + { + request.damage.mul *= self.guard + } + KitEvent::Landed { event, request } + if event.source == Some(id) + && request.is_attack + && k.world.unit(id)?.operator.tactical.manifold()?.ranged + && Host::tac_up(k.world, event.target) => + { + let owner = k.world.unit(id)?.summoner.unwrap(); + if k.world.unit(owner)?.operator.active_skill { + let def = k.host.tac_def(owner)?; + if let Tactics::Mlyss(p) = &def.extra.tactics { + if p.bind > 0. { + let own = k.unit; + k.unit = owner; + let result = k.status(event.target, "bind", p.bind, None); + k.unit = own; + result?; + } + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/mlynar.rs b/crates/engine/src/battle/runtime/kits/mlynar.rs new file mode 100644 index 0000000..756484a --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/mlynar.rs @@ -0,0 +1,536 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "librator", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_mlynar_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "CUSTOM_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_mlynar_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "SEARCH", + attack_override: true, + }, + Skill { + id: "skchr_mlynar_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = tactical_mode(raw)?; + + s.combat.profile.only_while_skill = true; + skill_range(raw, s)?; + s.combat.skill_scale = n(bb, "attack@atk_scale", 1.); + if mode == Mode::First { + s.modifiers = [("defPct".into(), n(bb, "def", 0.))].into(); + } + if mode == Mode::Second { + s.modifiers = [( + "batPct".into(), + flat_bat(raw, n(bb, "base_attack_time", 0.)), + )] + .into(); + s.combat.skill_hits = 2; + } + if mode == Mode::Third { + let mut p = s.combat.profile; + p.selection.can_hit_fly = true; + p.max_targets = n(bb, "attack@max_target", 1.); + s.combat.skill_profile = Some(p); + } + s.extra.effects.permanent.push(persistent( + "mlynar:unmoved", + [("taunt".into(), n(t1, "taunt_level", 0.))].into(), + )); + s.extra.tactics = Tactics::Mlynar(Mlynar { + mode, + ramp: n(tb, "atk", 2.), + ramp_time: n(tb, "max_stack_cnt", 40.), + initial: n(tb, "init_atk", 0.), + scale: n(t, "atk_scale_base", 1.), + crowd_scale: n(t, "atk_scale_up", 1.), + crowd: n(t, "cnt", 3.).max(1.) as usize, + cut: n(t, "damage_resistance", 0.), + reflect: n(t1, "atk_scale", 0.), + mark: n(bb, "atk_scale", 0.), + up: n(bb, "trait_up", 1.), + loss: n(bb, "per_kill_reduce", 0.), + }); + Ok(()) +} + +pub(crate) struct Mlynar { + pub mode: Mode, + pub ramp: f64, + pub ramp_time: f64, + pub initial: f64, + pub scale: f64, + pub crowd_scale: f64, + pub crowd: usize, + pub cut: f64, + pub reflect: f64, + pub mark: f64, + pub up: f64, + pub loss: f64, +} + +#[derive(Default)] +pub(crate) struct State { + pub ramp: f64, + pub kills: u32, + pub pending_kills: u32, + pub near: usize, +} + +impl Host { + pub(in crate::battle::runtime) fn tac_mlynar_up( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + p: &Mlynar, + ) -> Result<(), String> { + if p.mode != Mode::Third { + return Ok(()); + } + let m = w.unit(id)?.operator.tactical.mlynar()?; + let extra = (m.ramp * p.up + p.loss * f64::from(m.kills)).max(0.) - m.ramp; + if extra != 0. { + self.component_buff( + w, + r, + id, + "mlynar:traitUp", + [("atkPct".into(), extra)].into(), + f64::INFINITY, + id, + )?; + } else { + r.remove(w, self, id, "mlynar:traitUp")?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn tactical_sync_injury( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + for id in self.roster.as_ref().unwrap().ids().to_vec() { + let def = self.tac_def(id)?; + let Tactics::Mlynar(p) = &def.extra.tactics else { + continue; + }; + let up = Self::tac_up(w, id); + let leader = up + && self + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .find(|&a| { + Self::tac_up(w, a) + && self.tac_def(a).is_ok_and(|d| d.char_id == def.char_id) + }) + == Some(id); + for a in w.unit_ids().collect::>() { + let ally = w.unit(a)?.side == health::Side::Ally; + let key = format!("mlynar:{}:{id}", if ally { "reflection" } else { "mark" }); + let covered = if ally { + leader + && Self::tac_up(w, a) + && w.unit(a)?.has_operator_kit() + && self.tac_faction(a, "kazimierz")? + && p.reflect > 0. + } else { + up && w.unit(id)?.operator.active_skill + && p.mode == Mode::Third + && Self::tac_up(w, a) + && body::in_range(w.unit(a)?, &self.roster.as_ref().unwrap().range(w, id)?) + }; + if covered && !Self::tac_has(w, a, &key) { + let mut b = Buff { + key: Some(key), + ..Default::default() + }; + b.runtime.source = Some(id); + b.runtime.injury.observe = Some(OBSERVE); + r.add( + w, + self, + a, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } else if !covered { + r.remove(w, self, a, &key)?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn mlynar_start( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Mlynar, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.mlynar_mut()?.kills = 0; + w.unit_mut(id)? + .operator + .tactical + .mlynar_mut()? + .pending_kills = 0; + r.remove(w, self, id, "trait:libratorBlock")?; + self.tac_mlynar_up(w, r, id, p)?; + Ok(()) + } + pub(in crate::battle::runtime) fn mlynar_end( + &mut self, + c: &skills::Context, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Mlynar, + ) -> Result<(), String> { + r.remove(w, self, id, "mlynar:traitUp")?; + if p.mode != Mode::Second + || w.unit(id)?.operator.tactical.mlynar()?.kills == 0 + || c.reason == "death" + { + w.unit_mut(id)?.operator.tactical.mlynar_mut()?.ramp = 0.; + r.remove(w, self, id, "trait:libratorRamp")?; + } + if Self::tac_up(w, id) { + self.component_buff( + w, + r, + id, + "trait:libratorBlock", + [("blockCnt".into(), -99.)].into(), + f64::INFINITY, + id, + )?; + buffs::Hooks::operator_release(self, w, r, id)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn mlynar_scheduled( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + active: bool, + due: [bool; 5], + p: &Mlynar, + ) -> Result<(), String> { + if due[4] && !active { + let ramp = (w.unit(id)?.operator.tactical.mlynar()?.ramp + + p.ramp / p.ramp_time.max(1.)) + .min(p.ramp); + w.unit_mut(id)?.operator.tactical.mlynar_mut()?.ramp = ramp; + self.component_buff( + w, + r, + id, + "trait:libratorRamp", + [("atkPct".into(), ramp)].into(), + f64::INFINITY, + id, + )?; + } + if due[1] { + let near = self.tac_radius(w, w.unit(id)?.position, 1.5)?.len(); + w.unit_mut(id)?.operator.tactical.mlynar_mut()?.near = near; + if near >= p.crowd && p.cut > 0. { + self.component_buff( + w, + r, + id, + "mlynar:ranger", + [("dmgTakenMul".into(), 1. - p.cut)].into(), + 0.3, + id, + )?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn mlynar_attack( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + active: bool, + p: &Mlynar, + ) -> Result<(), String> { + let kills = w.unit(id)?.operator.tactical.mlynar()?.pending_kills; + w.unit_mut(id)?.operator.tactical.mlynar_mut()?.kills += kills; + w.unit_mut(id)? + .operator + .tactical + .mlynar_mut()? + .pending_kills = 0; + if kills > 0 && active { + self.tac_mlynar_up(w, r, id, p)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn mlynar_phase( + &mut self, + w: &mut World, + id: Id, + q: &mut hit::Request, + c: &Mlynar, + ) -> Result<(), String> { + if q.is_attack { + q.damage.amount *= if w.unit(id)?.operator.tactical.mlynar()?.near >= c.crowd { + c.crowd_scale + } else { + c.scale + }; + } + Ok(()) + } + pub(in crate::battle::runtime) fn mlynar_landed( + &mut self, + w: &mut World, + id: Id, + q: &hit::Request, + e: &health::Event, + ) -> Result<(), String> { + if w.unit(id)?.operator.active_skill + && (q.is_attack || q.tags.iter().any(|t| t == "markOwn")) + && w.unit(e.target)?.stats.hp <= 0. + { + w.unit_mut(id)? + .operator + .tactical + .mlynar_mut()? + .pending_kills = w + .unit(id)? + .operator + .tactical + .mlynar()? + .pending_kills + .saturating_add(1); + } + Ok(()) + } + pub(in crate::battle::runtime) fn mlynar_observe( + c: &mut settlement::Context<'_, Self>, + target: Id, + key: &str, + buff: &Buff, + ) -> Result<(), String> { + let id = buff.runtime.source.ok_or("Missing mlynar provider")?; + let def = c.host.tac_def(id)?; + let Tactics::Mlynar(p) = &def.extra.tactics else { + return Err("Invalid mlynar observer".into()); + }; + let Some(source) = c.request.hit.source else { + return Ok(()); + }; + if !Self::tac_up(c.world, id) { + return Ok(()); + } + if key.starts_with("mlynar:reflection:") + && c.world.unit(source)?.side == health::Side::Enemy + && Self::tac_up(c.world, source) + { + let amount = Self::tac_stat(c.world, id, "atk")? * p.reflect; + c.host.tac_damage( + c.world, + c.runtime, + id, + source, + amount, + DamageType::True, + false, + "reflect", + )?; + } + if key.starts_with("mlynar:mark:") + && c.world.unit(source)?.side == health::Side::Ally + && c.host.tac_faction(source, "kazimierz")? + && matches!( + c.request.attack_type, + hit::AttackType::Normal | hit::AttackType::Splash + ) + && c.world.unit(id)?.operator.active_skill + && c.world.unit(target)?.stats.hp > 0. + { + let amount = Self::tac_stat(c.world, id, "atk")? * p.mark; + c.host.tac_damage( + c.world, + c.runtime, + id, + target, + amount, + DamageType::True, + false, + if source == id && c.request.is_attack { + "markOwn" + } else { + "mark" + }, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn mlynar_idle( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + p: &Mlynar, + ) -> Result<(), String> { + if Self::tac_up(w, id) + && !Self::tac_has(w, id, "trait:libratorBlock") + && !w.unit(id)?.operator.active_skill + { + if p.initial > 0. && w.unit(id)?.operator.tactical.mlynar()?.ramp > 0. { + self.component_buff( + w, + r, + id, + "trait:libratorRamp", + [( + "atkPct".into(), + w.unit(id)?.operator.tactical.mlynar()?.ramp, + )] + .into(), + f64::INFINITY, + id, + )?; + } + self.component_buff( + w, + r, + id, + "trait:libratorBlock", + [("blockCnt".into(), -99.)].into(), + f64::INFINITY, + id, + )?; + } + Ok(()) + } +} + +impl State { + pub fn deployed(p: &Mlynar) -> Self { + Self { + ramp: p.initial.min(p.ramp), + ..Default::default() + } + } +} + +impl Behavior for Mlynar { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::Scheduled(_)) + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + (Role::Source, KitEvent::Attack { .. }) => { + let active = k.active()?; + k.host.mlynar_attack(k.world, id, k.buffs, active, self)?; + } + ( + Role::Source, + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + }, + ) => { + k.host.mlynar_phase(k.world, id, request, self)?; + } + (Role::Source, KitEvent::Landed { event, request }) => { + k.host.mlynar_landed(k.world, id, request, event)?; + } + _ => {} + } + Ok(()) + } + fn observe_injury( + &self, + c: &mut settlement::Context<'_, Host>, + key: &str, + buff: &Buff, + ) -> Result<(), String> { + if key.starts_with("mlynar:") { + Host::mlynar_observe(c, c.request.hit.target, key, buff)?; + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Scheduled(due) => { + if k.up() { + let active = k.active()?; + k.host + .mlynar_scheduled(k.world, id, k.buffs, active, *due, self)?; + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.mlynar_start(k.world, id, k.buffs, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::End, + context, + .. + } if *unit == id => { + k.host.mlynar_end(context, k.world, id, k.buffs, self)?; + } + KitEvent::Flush => { + k.host.mlynar_idle(k.world, k.buffs, id, self)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/mlyss.rs b/crates/engine/src/battle/runtime/kits/mlyss.rs new file mode 100644 index 0000000..25f4ad1 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/mlyss.rs @@ -0,0 +1,530 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "PIONEER", + branch: "tactician", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[Skill { + id: "skchr_mlyss_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "MLYSS_WTRMAN", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 1); + let module = talent_at(raw, -1); + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + s.extra.tactics = Tactics::Mlyss(Mlyss { + cost: n(bb, "cost", 0.), + attack: n(bb, "atk", 0.), + speed: n(bb, "attack_speed", 0.), + interval: suffix_number(bb, "interval", 2.).max(0.2), + bind: suffix_number(bb, "duration", 1.5), + copy_sp: n(module, "sp", 0.), + other_sp: n(module, "sp_other", 0.), + cost_cut: n(t, "cost", 0.), + first_cut: n(t, "runtime_cost", 0.), + trait_scale: n(&raw["trait"]["bb"], "atk_scale", 1.5), + }); + Ok(()) +} +pub(crate) struct Mlyss { + cost: f64, + attack: f64, + speed: f64, + interval: f64, + pub bind: f64, + pub copy_sp: f64, + other_sp: f64, + cost_cut: f64, + first_cut: f64, + trait_scale: f64, +} +#[derive(Default)] +pub(crate) struct State { + first: bool, + pub(super) clone_of: Option, + costs_applied: bool, + skill_left: f64, + pulse: Option, + pending: Option<([i32; 2], f64, u32)>, +} +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + Self { + first: previous.is_some_and(|s| s.first), + costs_applied: previous.is_some_and(|s| s.costs_applied), + ..Default::default() + } + } +} +pub(crate) fn rhine(k: &KitContext<'_>, id: Id) -> Result { + let character = &k.host.tac_def(id)?.char_id; + Ok([ + "char_108_silent", + "char_128_plosis", + "char_202_demkni", + "char_249_mlyss", + "char_1047_halo2", + "char_135_halo", + ] + .contains(&character.as_str())) +} +impl Mlyss { + fn mine(k: &KitContext<'_>) -> Result, String> { + Ok(k.host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .filter(|&a| { + k.world + .unit(a) + .is_ok_and(|u| u.summoner == Some(k.unit) && Host::tac_up(k.world, a)) + && k.world + .unit(a) + .unwrap() + .operator + .tactical + .manifold() + .is_ok() + }) + .collect()) + } + fn pulse(&self, k: &mut KitContext<'_>) -> Result<(), String> { + for token in Self::mine(k)? { + if !k + .world + .unit(token)? + .operator + .tactical + .manifold()? + .from + .is_some() + || k.world.unit(token)?.operator.tactical.manifold()?.ranged + { + continue; + } + let def = k.host.tac_def(token)?; + let force = if let Tactics::Manifold(p) = &def.extra.tactics { + p.force + } else { + 0. + }; + let owner = k.unit; + k.unit = token; + let result: Result<(), String> = (|| { + let keys = k.range(&[ + [-1, -1], + [-1, 0], + [-1, 1], + [0, -1], + [0, 1], + [1, -1], + [1, 0], + [1, 1], + ])?; + for enemy in k.enemies(Some(&keys), true)? { + k.pull(enemy, force, None)?; + } + for enemy in k.world.unit(token)?.blocking().to_vec() { + if Host::tac_up(k.world, enemy) { + k.unit = owner; + k.status(enemy, "stun", self.interval + 0.1, None)?; + k.unit = token; + } + } + Ok(()) + })(); + k.unit = owner; + result?; + } + Ok(()) + } +} +impl Behavior for Mlyss { + fn condition( + &self, + host: &Host, + w: &mut World, + id: Id, + condition: skills::Condition, + ) -> Result, String> { + if !matches!( + condition, + skills::Condition::Default | skills::Condition::ExtraWithoutAttack + ) { + return Ok(None); + } + for &a in host.roster.as_ref().unwrap().ids() { + if w.unit(a)?.summoner == Some(id) + && Host::tac_up(w, a) + && w.unit(a)? + .operator + .tactical + .manifold() + .is_ok_and(|s| s.from.is_some()) + { + let keys = host.roster.as_ref().unwrap().range(w, a)?; + for enemy in host.spawns.as_ref().unwrap().live() { + let e = w.unit(*enemy)?; + if e.stats.alive && !e.hidden && body::in_range(e, &keys) { + return Ok(Some(true)); + } + } + } + } + Ok((condition == skills::Condition::ExtraWithoutAttack).then_some(false)) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == id => { + if Self::mine(k)?.iter().all(|&a| { + k.world + .unit(a) + .unwrap() + .operator + .tactical + .manifold() + .unwrap() + .clone + }) { + let previous = k + .host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .filter(|&a| k.world.unit(a).is_ok_and(|u| u.summoner == Some(id))) + .filter(|&a| { + k.world + .unit(a) + .unwrap() + .operator + .tactical + .manifold() + .is_ok_and(|s| !s.clone) + }) + .max_by_key(|&a| k.world.unit(a).unwrap().deployment.deploy_seq); + let mut tile = previous + .map(|a| k.world.unit(a).unwrap().deployment.home) + .filter(|&tile| { + !k.host + .roster + .as_ref() + .unwrap() + .deployment() + .reserved(k.world, tile) + .unwrap_or(true) + }); + if tile.is_none() { + tile = k.tactical_point()?; + } + if let Some(tile) = tile { + k.summon("token_10030_mlyss_wtrman", tile, 0.)?; + } + } + } + KitEvent::BattleStart => { + if !k.world.unit(id)?.operator.tactical.mlyss()?.costs_applied { + let mut targets = k + .host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .filter(|&a| { + k.world.unit(a).unwrap().deployment.kind + == crate::battle::deploy::Kind::Operator + && k.world.unit(a).unwrap().owner == k.world.unit(id).unwrap().owner + }) + .collect::>(); + targets.retain(|&a| rhine(k, a).unwrap_or(false)); + targets.sort_by_key(|&a| k.world.unit(a).unwrap().deployment.deploy_seq); + for (index, target) in targets.into_iter().enumerate() { + let delta = self.cost_cut + if index == 0 { self.first_cut } else { 0. }; + let cost = k.world.unit(target)?.stats.base_number("cost"); + k.world.unit_mut(target)?.stats.edit_base(|b| { + b.0.insert("cost".into(), (cost + delta).max(0.)); + }); + } + k.world + .unit_mut(id)? + .operator + .tactical + .mlyss_mut()? + .costs_applied = true; + } + } + KitEvent::SkillObserved { + unit, + event: skills::Event::Deploy, + skill, + } if k.world.unit(*unit)?.summoner == Some(id) => { + if let Some(source) = k + .world + .unit_mut(id)? + .operator + .tactical + .mlyss_mut()? + .clone_of + .take() + { + let owner = k.unit; + k.unit = *unit; + let result = super::manifold::Manifold::copy(k, source, 1., true, true); + k.unit = owner; + result?; + skill.bank.no_skill = true; + return Ok(()); + } + let def = k.host.tac_def(*unit)?; + if let Tactics::Manifold(p) = &def.extra.tactics { + if !k.world.unit(id)?.operator.tactical.mlyss()?.first { + let amount = p.first_sp; + if amount > 0. { + k.host.with_kit_buffs(k.world, k.buffs, |host, w| { + skill.gain(w, host, amount, "talent", false, false) + })?; + } + k.world.unit_mut(id)?.operator.tactical.mlyss_mut()?.first = true; + } + } + k.world.unit_mut(id)?.operator.tactical.mlyss_mut()?.pending = None; + if k.active()? { + let duration = k.world.unit(id)?.operator.tactical.mlyss()?.skill_left; + k.buff( + *unit, + "mlyss:s3", + [("atkPct".into(), self.attack), ("aspd".into(), self.speed)].into(), + duration, + )?; + } + } + KitEvent::SkillObserved { + unit, + event: skills::Event::Deploy, + skill, + } if self.other_sp > 0. + && k.world.unit(*unit)?.deployment.kind + == crate::battle::deploy::Kind::Operator + && k.world.unit(*unit)?.operator.deployments > 1 + && rhine(k, *unit)? => + { + if Self::mine(k)?.iter().any(|&a| { + k.world + .unit(a) + .unwrap() + .operator + .tactical + .manifold() + .is_ok_and(|s| s.from == Some(*unit)) + }) { + let amount = self.other_sp; + k.host.with_kit_buffs(k.world, k.buffs, |host, w| { + skill.gain(w, host, amount, "talent", false, false) + })?; + } + } + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .mlyss_mut()? + .skill_left = skill.time_left; + k.dp(self.cost)?; + let tokens = Self::mine(k)?; + let ranged = tokens.iter().any(|&a| { + k.world + .unit(a) + .unwrap() + .operator + .tactical + .manifold() + .unwrap() + .ranged + }); + for token in tokens { + k.buff( + token, + "mlyss:s3", + [("atkPct".into(), self.attack), ("aspd".into(), self.speed)].into(), + skill.time_left, + )?; + if ranged { + let maximum = k.stat(token, "maxHp")?; + k.world.unit_mut(token)?.stats.hp = maximum; + } + } + if ranged { + if let Some((tile, _, _)) = k + .world + .unit_mut(id)? + .operator + .tactical + .mlyss_mut()? + .pending + .take() + { + k.summon("token_10030_mlyss_wtrman", tile, 0.)?; + } + } + self.pulse(k)?; + let next = k.world.time + self.interval; + k.world.unit_mut(id)?.operator.tactical.mlyss_mut()?.pulse = Some(next); + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + skill, + .. + } if *unit == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .mlyss_mut()? + .skill_left = skill.time_left + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + let state = k.world.unit_mut(id)?.operator.tactical.mlyss_mut()?; + state.pulse = None; + state.skill_left = 0.; + } + KitEvent::Tick if k.up() => { + if k.active()? + && k.world + .unit(id)? + .operator + .tactical + .mlyss()? + .pulse + .is_some_and(|at| k.world.time + 1e-9 >= at) + { + self.pulse(k)?; + k.world.unit_mut(id)?.operator.tactical.mlyss_mut()?.pulse = + Some(k.world.time + self.interval); + } + if let Some((tile, at, tries)) = + k.world.unit(id)?.operator.tactical.mlyss()?.pending + { + if k.world.time + 1e-9 >= at { + if tries <= 120 { + if k.summon("token_10030_mlyss_wtrman", tile, 0.)?.is_none() { + let at = k.world.time + 1.; + k.world.unit_mut(id)?.operator.tactical.mlyss_mut()?.pending = + Some((tile, at, tries + 1)); + } + } else { + k.world.unit_mut(id)?.operator.tactical.mlyss_mut()?.pending = None; + } + } + } + } + KitEvent::Death { unit, .. } if *unit == id => { + k.world.unit_mut(id)?.operator.tactical.mlyss_mut()?.pending = None; + } + + KitEvent::Death { unit, .. } + if k.world.unit(*unit)?.summoner == Some(id) + && k.world.unit(*unit)?.deployment.remove_reason.as_deref() + == Some("killed") + && k.world + .unit(*unit)? + .operator + .tactical + .manifold() + .is_ok_and(|s| !s.clone) => + { + if Self::mine(k)?.iter().all(|&a| { + k.world + .unit(a) + .unwrap() + .operator + .tactical + .manifold() + .unwrap() + .clone + }) { + let def = k.host.tac_def(*unit)?; + let delay = if let Tactics::Manifold(p) = &def.extra.tactics { + p.respawn + } else { + 25. + }; + let tile = k.world.unit(*unit)?.deployment.home; + let at = k.world.time + delay; + k.world.unit_mut(id)?.operator.tactical.mlyss_mut()?.pending = + Some((tile, at, 0)); + } + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.source == Some(id) && request.is_attack => { + if let Some(blocker) = k.world.unit(request.hit.target)?.blocked_by() { + if k.world.unit(blocker)?.summoner == Some(id) { + // Tactician dmgMul is applied to the attack amount before mitigation. + request.damage.amount *= self.trait_scale; + } + } + } + KitEvent::Scheduled(due) if due[2] => { + for token in Self::mine(k)? { + let def = k.host.tac_def(token)?; + if let Tactics::Manifold(p) = &def.extra.tactics { + if p.taunt > 0. { + let own = k.unit; + k.unit = token; + for enemy in k.world.unit(token)?.blocking().to_vec() { + if Host::tac_up(k.world, enemy) { + k.buff( + enemy, + "mlyss:exposed", + [("taunt".into(), p.taunt)].into(), + 0.4, + )?; + } + } + k.unit = own; + } + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/nearl2.rs b/crates/engine/src/battle/runtime/kits/nearl2.rs new file mode 100644 index 0000000..e7e2b1c --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/nearl2.rs @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +const PLUS: [[i32; 2]; 5] = [[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1]]; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "fearless", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_nearl2_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tb = &raw["trait"]["bb"]; + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("defPct".into(), n(bb, "def", 0.)), + ] + .into(); + crate::battle::content::operators::mechanics::skill_range(raw, s)?; + let penetration = n(t1, "def_penetrate", 0.); + if penetration != 0. { + s.extra.effects.permanent.push(persistent( + "nearl2:dawn", + [("defIgnorePct".into(), penetration)].into(), + )); + } + s.extra.tactics = Tactics::Nearl2(Nearl2 { + scale: n(bb, "value", 0.), + stun: n(bb, "value2", 0.), + dawn_scale: n(t, "atk_scale", 0.), + dawn_stun: n(t, "stun", 0.), + dawn_grid: raw["talents"] + .as_array() + .and_then(|a| a.iter().find(|t| t["index"] == 0)) + .and_then(|t| t["rangeGrid"].as_array()) + .map(|_| tactical_grid(&raw["talents"][0]["rangeGrid"], false)) + .transpose()? + .unwrap_or(PLUS.to_vec()), + blocked: n(tb, "atk_scale", 1.), + stand: n(tb, "value", 0.), + stand_speed: n(tb, "attack_speed", 0.), + stand_hp: n(tb, "hp_ratio", 1.), + }); + Ok(()) +} +pub(crate) struct Nearl2 { + scale: f64, + stun: f64, + dawn_scale: f64, + dawn_stun: f64, + dawn_grid: Vec<[i32; 2]>, + blocked: f64, + stand: f64, + stand_speed: f64, + stand_hp: f64, +} +#[derive(Default)] +pub(crate) struct State { + sun: Option, + stood: bool, + dawn_times: u32, +} +impl Nearl2 { + fn dawn(&self, k: &mut KitContext<'_>, times: u32) -> Result<(), String> { + let keys = k.range(&self.dawn_grid)?; + let amount = k.stat(k.unit, "atk")? * self.dawn_scale; + for enemy in k.world.unit_ids().collect::>() { + let u = k.world.unit(enemy)?; + if u.side != health::Side::Enemy + || !u.stats.alive + || u.hidden + || !body::in_range(u, &keys) + { + continue; + } + for _ in 0..times { + if !k.world.unit(enemy)?.stats.alive { + break; + } + k.damage(enemy, amount, DamageType::True, false, "talent")?; + } + if k.world.unit(enemy)?.stats.alive { + k.status(enemy, "stun", self.dawn_stun, None)?; + } + } + Ok(()) + } +} +impl Behavior for Nearl2 { + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Fatal(_)) { + -60 + } else { + 0 + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == id => { + let previous = k.host.last_operator; + let times = if let Some(previous) = previous.filter(|&a| a != id) { + if k.faction(previous, "kazimierzShip", &[])? { + 2 + } else { + 1 + } + } else { + 1 + }; + k.world + .unit_mut(id)? + .operator + .tactical + .nearl2_mut()? + .dawn_times = times; + self.dawn(k, times)?; + } + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + let previous_kazimierz = k + .host + .last_operator + .map(|previous| k.faction(previous, "kazimierzShip", &[])) + .transpose()? + .unwrap_or(false); + let tile = k.best_summon_tile(&k.summon_tiles(&PLUS, true)?); + let token = if let Some(tile) = tile { + k.summon("token_10019_nearl2_sword", tile, skill.time_left)? + } else { + None + }; + k.world.unit_mut(id)?.operator.tactical.nearl2_mut()?.sun = token; + let source = token.unwrap_or(id); + let own = k.unit; + k.unit = source; + let result: Result<(), String> = (|| { + let keys = k.range(&PLUS)?; + let amount = k.stat(own, "atk")? * self.scale; + for target in k.world.unit_ids().collect::>() { + let u = k.world.unit(target)?; + if u.side == health::Side::Enemy + && u.stats.alive + && !u.hidden + && body::in_range(u, &keys) + { + for _ in 0..if token.is_some() && previous_kazimierz { + 2 + } else { + 1 + } { + if k.world.unit(target)?.stats.alive { + k.damage(target, amount, DamageType::True, true, "skill")?; + } + } + if k.world.unit(target)?.stats.alive { + k.status(target, "stun", self.stun, None)?; + } + } + } + Ok(()) + })(); + k.unit = own; + result?; + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + if let Some(token) = k + .world + .unit_mut(id)? + .operator + .tactical + .nearl2_mut()? + .sun + .take() + { + let own = k.unit; + k.unit = token; + let result = k.retreat(); + k.unit = own; + result?; + } + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.source == Some(id) => { + if request.is_attack && k.world.unit(request.hit.target)?.blocked_by().is_some() { + request.damage.mul *= self.blocked; + } + let blocker = k.world.unit(request.hit.target)?.blocked_by(); + if request.is_attack + && k.active()? + && blocker.is_some() + && (blocker == Some(id) + || blocker == k.world.unit(id)?.operator.tactical.nearl2()?.sun) + { + request.hit.damage_type = DamageType::True; + } + } + KitEvent::Fatal(context) + if context.target == id + && !context.prevented + && self.stand > 0. + && !k.world.unit(id)?.operator.tactical.nearl2()?.stood => + { + context.prevented = true; + k.world.unit_mut(id)?.operator.tactical.nearl2_mut()?.stood = true; + k.buff( + id, + "nearl2:stand", + [ + ("hpMul".into(), (1. - self.stand).max(0.05)), + ("aspd".into(), self.stand_speed), + ] + .into(), + f64::INFINITY, + )?; + let hp = k.stat(id, "maxHp")? * self.stand_hp; + k.world.unit_mut(id)?.stats.hp = hp.max(1.); + self.dawn( + k, + k.world + .unit(id)? + .operator + .tactical + .nearl2()? + .dawn_times + .max(1), + )?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/nymph.rs b/crates/engine/src/battle/runtime/kits/nymph.rs new file mode 100644 index 0000000..ff170bb --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/nymph.rs @@ -0,0 +1,276 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::element; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "primcaster", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_nymph_2", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_nymph_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_nymph_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_nymph_1" => Mode::First, + "skchr_nymph_2" => Mode::Second, + "skchr_nymph_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + if mode == Mode::Second { + s.combat.skill_scale = n(bb, "atk_scale", 1.); + s.combat.skill_area.splash = Some(Splash { + radius: n(bb, "projectile_range", 1.5), + scale: 1., + hits_fly: true, + fortress_melee: false, + }); + } else { + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("aspd".into(), n(bb, "attack_speed", 0.)), + ] + .into(); + } + if mode == Mode::Third { + skill_range(raw, s)?; + let mut p = s.combat.profile; + p.max_targets = n(bb, "attack@max_target", 2.).max(1.); + s.combat.skill_profile = Some(p); + s.combat.skill_scale = n(bb, "attack@split_atk_scale", 1.); + } + s.extra.tactics = Tactics::Nymph(Nymph { + mode: mode, + ep: n(bb, "ep_damage_ratio", n(bb, "attack@ep_damage_ratio", 0.)), + soul: n(t, "element_atk_scale", 0.), + skill_soul: n(bb, "element_atk_scale", 0.), + key_atk: n(t1, "atk", 0.), + key_cap: n(t1, "max_stack_cnt", 10.).max(1.) as u32, + lash: n(bb, "attack@extra_ep_damage_scale", 0.), + fear: n(bb, "fear", 0.), + burst_mul: n(tb, "damage_scale", 1.), + sp: n(tm, "sp_recovery_per_sec", 0.), + }); + Ok(()) +} +pub(crate) struct Nymph { + pub mode: Mode, + pub ep: f64, + pub soul: f64, + pub skill_soul: f64, + pub key_atk: f64, + pub key_cap: u32, + pub lash: f64, + pub fear: f64, + pub burst_mul: f64, + pub sp: f64, +} + +pub(in crate::battle::runtime) const SOUL: u64 = 1510; +impl Behavior for Nymph { + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Hit { .. }) { + -10 + } else { + 0 + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.source == Some(id) => { + if k.flag(request.hit.target, "burstLock")? { + request.damage.mul *= self.burst_mul; + } + if self.mode == Mode::Third + && k.active()? + && request.is_attack + && k.has(request.hit.target, "apoptosisBurst") + && matches!( + request.hit.damage_type, + DamageType::Physical | DamageType::Arts + ) + { + request.hit.damage_type = DamageType::Elemental; + request.element = Some(element::Element::Apoptosis); + request.dodge_mode = injury::DodgeMode::Ignore; + request.tags.push("nymphBreak".into()); + } + } + KitEvent::Impact(impact) + if impact.attacker == id + && impact.is_skill + && self.mode == Mode::Second + && impact.kind == attacks::VictimKind::Main => + { + if let Some(target) = impact.target.filter(|&t| Host::tac_up(k.world, t)) { + k.status(target, "fear", self.fear, None)?; + } + } + KitEvent::Landed { + event: landed, + request, + } if landed.source == Some(id) + && request.is_attack + && k.world.unit(landed.target)?.side == health::Side::Enemy + && Host::tac_up(k.world, landed.target) => + { + let target = landed.target; + if (request.is_skill || self.mode == Mode::First && k.active()?) + && self.ep > 0. + && landed.amount > 0. + && !k.flag(target, "hitCount")? + { + k.elemental(target, landed.amount * self.ep, element::Element::Apoptosis)?; + } + let scale = if request.is_skill { + self.skill_soul.max(self.soul) + } else { + self.soul + }; + if let Some(duration) = k + .world + .unit(target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("apoptosisBurst")) + .map(|b| b.runtime.time_left) + { + let key = format!("nymph:soul:{id}"); + if let Some(buff) = k + .world + .unit(target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some(&key)) + .map(|b| b.runtime.id()) + { + k.buffs.edit_timer(k.world, target, buff, |b| { + b.runtime.tick_payload = b.runtime.tick_payload.max(scale) + })?; + } else if scale > 0. { + let mut buff = Buff { + key: Some(key), + ..Default::default() + }; + buff.runtime.duration = duration.max(0.1); + buff.runtime.interval = 1.; + buff.runtime.tick_payload = scale; + buff.runtime.on_tick = Some(SOUL); + k.add(target, buff)?; + } + if self.mode == Mode::First + && k.active()? + && self.lash > 0. + && request.hit.damage_type != DamageType::Elemental + { + let amount = k.stat(id, "atk")? * self.lash; + k.element_damage(target, amount, element::Element::Apoptosis, "nymphLash")?; + } + } + } + KitEvent::Element { + phase: element::Phase::Burst, + request, + } if request.damage.element == Some(element::Element::Apoptosis) && k.up() => { + let keys = k.keys()?; + if k.world.unit(request.damage.hit.target)?.side == health::Side::Enemy + && body::in_range(k.world.unit(request.damage.hit.target)?, &keys) + { + let mut buff = Buff { + key: Some("nymph:key".into()), + mods: [("atkPct".into(), self.key_atk)].into(), + ..Default::default() + }; + buff.runtime.refresh = buffs::Refresh::Stack; + buff.runtime.max_stacks = self.key_cap; + k.add(id, buff)?; + } + } + KitEvent::Scheduled(due) if due[2] && self.sp > 0. && k.up() => { + let keys = k.keys()?; + let foes = k.host.spawns.as_ref().unwrap().live().to_vec(); + let mut burst = false; + for target in foes { + if Host::tac_up(k.world, target) + && body::in_range(k.world.unit(target)?, &keys) + && k.flag(target, "burstLock")? + { + burst = true; + break; + } + } + if burst { + k.buff( + id, + "nymph:module", + [("spRecoveryFlat".into(), self.sp)].into(), + 0.5, + )?; + } + } + KitEvent::Buff { + context, + event: buffs::Event::Tick, + token, + } if *token == SOUL => { + let buff = k.buffs.get(k.world, context.unit, context.buff)?.clone(); + if buff.runtime.source != Some(id) { + return Ok(()); + } + if !k.has(context.unit, "apoptosisBurst") { + k.buffs + .remove_id(k.world, k.host, context.unit, context.buff)?; + } else { + let amount = k.stat(id, "atk")? * buff.runtime.tick_payload; + k.element_damage( + context.unit, + amount, + element::Element::Apoptosis, + "nymphSoul", + )?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/papyrs.rs b/crates/engine/src/battle/runtime/kits/papyrs.rs new file mode 100644 index 0000000..ba61183 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/papyrs.rs @@ -0,0 +1,334 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "chainhealer", + ranged: false, + can_hit_fly: false, + physical: false, + projectile: "orb", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_papyrs_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_papyrs_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let mode = tactical_mode(raw)?; + + healing(s, 1.); + if mode == Mode::First { + s.combat.skill_heal_scale = n(bb, "heal_scale", 1.); + } else { + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ( + "batPct".into(), + flat_bat(raw, n(bb, "base_attack_time", 0.)), + ), + ] + .into(); + } + s.extra.tactics = Tactics::Papyrs(Papyrs { + mode, + count: n(tb, "attack@chain.max_target", 3.), + falloff: 1. - n(tb, "attack@chain.atk_scale", 0.75), + extra: n(bb, "attack@chain.extra_value", 0.), + shield: n(t, "attack@scale", 0.), + duration: n(t, "attack@shield_duration", 8.), + boost: n(bb, "shield_scale_skill", 1.), + }); + Ok(()) +} + +pub(crate) struct Papyrs { + pub mode: Mode, + pub count: f64, + pub falloff: f64, + pub extra: f64, + pub shield: f64, + pub duration: f64, + pub boost: f64, +} + +#[derive(Default)] +pub(crate) struct State { + pub lock: Option, +} + +impl Host { + pub(in crate::battle::runtime) fn tac_lock( + &self, + w: &mut World, + id: Id, + ) -> Result, String> { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let mut ids = self.tac_heal_targets(w, id, &keys, false)?; + ids.retain(|&a| a != id); + let mut rank = vec![]; + for a in ids { + rank.push(( + a, + Self::tac_stat(w, a, "maxHp")?, + w.unit(a)?.deployment.deploy_seq, + )); + } + rank.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.2.cmp(&b.2))); + Ok(rank.first().map(|x| x.0)) + } + + pub(in crate::battle::runtime) fn papyrs_start( + &mut self, + w: &mut World, + id: Id, + p: &Papyrs, + ) -> Result<(), String> { + if p.mode == Mode::Second { + w.unit_mut(id)?.operator.tactical.papyrs_mut()?.lock = self.tac_lock(w, id)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn papyrs_end( + &mut self, + w: &mut World, + id: Id, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.papyrs_mut()?.lock = None; + Ok(()) + } + pub(in crate::battle::runtime) fn papyrs_skill_tick( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + s: &mut skills::Runtime, + p: &Papyrs, + ) -> Result<(), String> { + if p.mode == Mode::Second { + if !w + .unit(id)? + .operator + .tactical + .papyrs()? + .lock + .is_some_and(|a| Self::tac_up(w, a)) + { + self.with_kit_buffs(w, r, |h, w| s.end(w, h, "target"))?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn papyrs_before( + &mut self, + w: &mut World, + id: Id, + active: bool, + c: &mut attacks::Context, + p: &Papyrs, + ) -> Result<(), String> { + if p.mode == Mode::Second && active { + if let Some(a) = w.unit(id)?.operator.tactical.papyrs()?.lock { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + if Self::tac_up(w, a) && body::in_range(w.unit(a)?, &keys) { + c.targets = vec![a]; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn papyrs_impact( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + target: Id, + impact: attacks::Impact, + p: &Papyrs, + ) -> Result<(), String> { + if impact.heal { + let count = p.count + + if w.unit(id)?.operator.active_skill && p.mode == Mode::Second { + p.extra + } else { + 0. + }; + if count.ceil() > w.unit_capacity() as f64 { + return Err("Heal-chain capacity exceeded".into()); + } + let mut seen = vec![target]; + let mut prev = target; + for k in 1..count.ceil() as i32 { + let tile = w.unit(prev)?.deployment.tile; + let mut choices = vec![]; + for &a in self.roster.as_ref().unwrap().ids() { + if seen.contains(&a) || !Self::tac_up(w, a) { + continue; + } + let u = w.unit(a)?; + if u.hidden + || u.profile_no_heal + || Self::tac_has(w, a, "noHeal") + || (u.deployment.tile[0] - tile[0]).abs() > 1 + || (u.deployment.tile[1] - tile[1]).abs() > 1 + { + continue; + } + choices.push(( + a, + u.stats.hp / Self::tac_stat(w, a, "maxHp")?, + w.unit(a)?.deployment.aggro_seq, + )); + } + choices.sort_by(|a, b| a.1.total_cmp(&b.1).then(b.2.cmp(&a.2))); + let Some(a) = choices.first().map(|x| x.0) else { + break; + }; + self.tac_heal( + w, + r, + id, + a, + impact.amount * powi(1. - p.falloff, k).map_err(str::to_string)?, + )?; + seen.push(a); + prev = a; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn papyrs_heal_event( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + e: &health::Event, + p: &Papyrs, + ) -> Result<(), String> { + if e.amount > 0. && !(e.kind == health::Kind::Regen && id == e.target) { + let active = w.unit(id)?.operator.active_skill; + let pending = self + .roster + .as_ref() + .unwrap() + .entry(id)? + .skill() + .ok() + .map_or(active && p.mode == Mode::First, |s| { + s.pending && s.bank.active + }); + let amount = + Self::tac_stat(w, id, "atk")? * p.shield * if pending { p.boost } else { 1. }; + if amount > 0. { + let mut b = Buff { + key: Some("papyrs:shield".into()), + shield: amount, + ..Default::default() + }; + b.runtime.duration = p.duration; + b.runtime.source = Some(id); + r.add( + w, + self, + e.target, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + } + Ok(()) + } +} + +impl Behavior for Papyrs { + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Heal { .. }) { + -10 + } else { + 0 + } + } + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + (Role::Source, KitEvent::Before(context)) => { + let active = k.active()?; + k.host.papyrs_before(k.world, id, active, context, self)?; + } + (Role::Source, KitEvent::Impact(impact)) => { + if let Some(target) = impact.target { + k.host + .papyrs_impact(k.world, id, k.buffs, target, *impact, self)?; + } + } + (Role::Source, KitEvent::Heal { event, .. }) => { + k.host + .papyrs_heal_event(k.world, id, k.buffs, event, self)?; + } + _ => {} + } + Ok(()) + } + fn can_activate(&self, host: &Host, world: &mut World, unit: Id) -> Result { + Ok(self.mode != Mode::Second || host.tac_lock(world, unit)?.is_some()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.papyrs_start(k.world, id, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + skill, + .. + } if *unit == id => { + k.host + .papyrs_skill_tick(k.world, id, k.buffs, skill, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + k.host.papyrs_end(k.world, id)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/pasngr.rs b/crates/engine/src/battle/runtime/kits/pasngr.rs new file mode 100644 index 0000000..10820de --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/pasngr.rs @@ -0,0 +1,347 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "chain", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_pasngr_3", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "SKILL_RANGE", + attack_override: false, + }, + Skill { + id: "skchr_pasngr_1", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_pasngr_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = tactical_mode(raw)?; + + let chain = Chain { + count: n(tb, "attack@max_target", 4.), + radius: 1.7, + falloff: 1. - n(tb, "attack@chain.atk_scale", 0.85), + sluggish: n(tb, "attack@sluggish", 0.5), + }; + s.combat.area.chain = Some(chain); + s.combat.skill_area = s.combat.area; + skill_range(raw, s)?; + if raw["skill"]["trigger"]["customRangeGrid"].is_array() { + s.trigger_range = Some(crate::battle::operators::parse_range( + &raw["skill"]["trigger"]["customRangeGrid"], + )?); + } + if mode == Mode::First { + s.combat.skill_scale = suffix_number(bb, "atk_scale", 1.); + s.combat.skill_area.chain = Some(Chain { + count: suffix_number(bb, "max_target", 4.), + sluggish: suffix_number(bb, "sluggish", 0.5), + falloff: 1. - n(tb, "skill@pasngr_s_1.chain.atk_scale", 1. - chain.falloff), + ..chain + }); + } + if mode == Mode::Second { + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("batPct".into(), n(bb, "base_attack_time", 0.)), + ] + .into(); + s.extra.advanced_range_extend = n(bb, "ability_range_forward_extend", 0.).max(0.) as u32; + s.combat.skill_area.chain = Some(Chain { + count: n(bb, "attack@max_target", 5.), + ..chain + }); + } + s.extra.tactics = Tactics::Pasngr(Pasngr { + mode, + chain: Chain { + count: n(bb, "chain.max_target", 4.), + falloff: 1. - n(tb, "skill@chain.atk_scale", 1. - chain.falloff), + sluggish: n(tb, "skill@sluggish", n(bb, "sluggish", chain.sluggish)), + ..chain + }, + scale: n(bb, "atk_scale", 1.), + duration: n(bb, "duration", 4.), + interval: n(bb, "interval", 0.5).max(0.1), + threshold: n(t, "hp_ratio", 0.8), + enhance: suffix_number(t, "damage_scale", 1.), + enhance_duration: suffix_number(t, "duration", 3.), + attack: n(t1, "atk", 0.), + sp: n(t1, "sp_recovery_per_sec", 0.), + }); + Ok(()) +} + +pub(crate) struct Pasngr { + pub mode: Mode, + pub chain: Chain, + pub scale: f64, + pub duration: f64, + pub interval: f64, + pub threshold: f64, + pub enhance: f64, + pub enhance_duration: f64, + pub attack: f64, + pub sp: f64, +} + +impl Host { + pub(in crate::battle::runtime) fn pasngr_start( + &mut self, + w: &mut World, + id: Id, + def: &Definition, + p: &Pasngr, + ) -> Result<(), String> { + if p.mode == Mode::Third { + let keys = self.support_trigger_range(w, id, def)?; + let mut ids = search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + ids.sort_by(|a, b| { + w.unit(*b) + .unwrap() + .stats + .hp + .total_cmp(&w.unit(*a).unwrap().stats.hp) + }); + if let Some(&target) = ids.first() { + let pos = w.unit(target)?.position; + let position = [pos[0].round() as i32, pos[1].round() as i32]; + self.tac_timer( + w, + id, + w.time + p.interval, + p.interval, + (p.duration / p.interval).round().max(1.) as u32, + Task::Storm { + position, + scale: p.scale, + chain: p.chain, + }, + )?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn pasngr_scheduled( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + due: [bool; 5], + p: &Pasngr, + ) -> Result<(), String> { + if due[2] { + let keys = self.tac_keys(w, id, &[[-1, 0], [1, 0], [0, -1], [0, 1]])?; + if !self.spawns.as_ref().unwrap().live().iter().any(|&a| { + Self::tac_up(w, a) + && !w.unit(a).unwrap().hidden + && body::in_range(w.unit(a).unwrap(), &keys) + }) { + self.component_buff( + w, + r, + id, + "pasngr:lone", + [("atkPct".into(), p.attack), ("spRecoveryFlat".into(), p.sp)].into(), + 0.4, + id, + )?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn pasngr_phase( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + q: &mut hit::Request, + c: &Pasngr, + ) -> Result<(), String> { + if w.unit(q.hit.target)?.side == health::Side::Enemy + && q.hit.damage_type != DamageType::Elemental + { + let key = format!("pasngr:enhance:{id}"); + if q.is_attack + && w.unit(q.hit.target)?.stats.hp / Self::tac_stat(w, q.hit.target, "maxHp")? + >= c.threshold - 1e-9 + { + self.component_buff( + w, + r, + q.hit.target, + &key, + Numbers::new(), + c.enhance_duration, + id, + )?; + } + if Self::tac_has(w, q.hit.target, &key) { + q.damage.mul *= c.enhance; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn pasngr_storm_timer( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + t: &mut Timer, + ) -> Result { + let id = t.source.ok_or("Operator timer requires a source")?; + let Task::Storm { + position, + scale, + chain, + } = &mut t.kind + else { + return Err("Invalid storm timer".into()); + }; + + if !chain.count.is_finite() + || chain.count.ceil() > w.unit_capacity() as f64 + || !chain.radius.is_finite() + || !chain.falloff.is_finite() + { + return Err("Storm chain capacity exceeded".into()); + } + let grid: Vec<_> = (-2_i32..=2) + .rev() + .flat_map(|r| { + (-2_i32..=2).filter_map(move |c| { + if r.abs() + c.abs() <= 2 { + Some([r, c]) + } else { + None + } + }) + }) + .collect(); + let keys = targeting::absolute_range(&grid, *position, Direction::Right, 0); + // Random selection uses spatial query order, before attack-priority sorting. + let targets = search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + if let Some(&first) = self.rng.pick(&targets) { + let mut seen = vec![]; + let mut current = Some(first); + for k in 0..chain.count.ceil() as u32 { + let Some(a) = current else { + break; + }; + seen.push(a); + let pos = w.unit(a)?.position; + let amount = Self::tac_stat(w, id, "atk")? + * *scale + * powi(1. - chain.falloff, k as i32).map_err(str::to_string)?; + self.tac_damage(w, r, id, a, amount, DamageType::Arts, true, "storm")?; + if Self::tac_up(w, a) && chain.sluggish > 0. { + self.advanced_status(w, r, id, a, "sluggish", chain.sluggish, None)?; + } + let candidates = self.tac_radius(w, pos, chain.radius)?; + let mut next = self.tac_selectable(w, id, candidates)?; + next.retain(|a| !seen.contains(a)); + next.sort_by(|a, b| { + body::distance(w.unit(*a).unwrap(), pos) + .total_cmp(&body::distance(w.unit(*b).unwrap(), pos)) + }); + current = next.first().copied(); + } + } + + Ok(true) + } +} + +impl Behavior for Pasngr { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::Scheduled(_)) + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + ( + Role::Source, + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + }, + ) => { + k.host.pasngr_phase(k.world, id, k.buffs, request, self)?; + } + _ => {} + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Scheduled(due) => { + if k.up() { + k.host.pasngr_scheduled(k.world, id, k.buffs, *due, self)?; + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + let definition = k.host.tac_def(id)?; + k.host.pasngr_start(k.world, id, &definition, self)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/pepe.rs b/crates/engine/src/battle/runtime/kits/pepe.rs new file mode 100644 index 0000000..ec1b0e9 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/pepe.rs @@ -0,0 +1,433 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "hammer", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_pepe_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_pepe_1", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_pepe_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = tactical_mode(raw)?; + + let splash = Splash { + radius: n(tb, "attack@ability_range_radius", 1.), + scale: n(tb, "attack@atk_scale_2", 0.5), + hits_fly: false, + fortress_melee: false, + }; + s.combat.area.splash = Some(splash); + s.combat.skill_area = s.combat.area; + skill_range(raw, s)?; + if mode == Mode::First { + s.combat.skill_scale = n(bb, "atk_scale", 1.); + } else { + let base_attack_time = n(bb, "base_attack_time", 0.); + let bat_pct = if base_attack_time > 0. { + base_attack_time + } else { + flat_bat(raw, base_attack_time).max(-0.9) + }; + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("aspd".into(), n(bb, "attack_speed", 0.)), + ("batPct".into(), bat_pct), + ] + .into(); + } + s.extra.tactics = Tactics::Pepe(Pepe { + mode, + stack_attack: n(bb, "attack@atk", 0.), + stacks: n(bb, "attack@max_stack_cnt", 0.).max(0.) as u32, + extend: n(bb, "attack@ability_range_forward_extend", 0.), + stun: n(bb, "attack@stun", 0.), + main_stun: n(bb, "attack@stun_main", n(bb, "attack@stun", 0.)), + sp: n(t, "sp", 0.), + sp_cap: n(t, "max_sp", 0.), + aura: n(t1, "atk", 0.), + module_scale: n(tb, "atk_scale_e", 1.), + module_count: n(tb, "cnt", f64::INFINITY), + rage: n(bb, "attack_speed_extra", 0.), + rage_cap: n(bb, "max_stack_cnt", 2.).max(0.) as u32, + }); + Ok(()) +} + +pub(crate) struct Pepe { + pub mode: Mode, + pub stack_attack: f64, + pub stacks: u32, + pub extend: f64, + pub stun: f64, + pub main_stun: f64, + pub sp: f64, + pub sp_cap: f64, + pub aura: f64, + pub module_scale: f64, + pub module_count: f64, + pub rage: f64, + pub rage_cap: u32, +} + +#[derive(Default)] +pub(crate) struct State { + pub stacks: u32, + pub rage: u32, + pub kills: u32, + pub boost: bool, +} + +impl Host { + pub(in crate::battle::runtime) fn pepe_start( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Pepe, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.pepe_mut()?.kills = 0; + w.unit_mut(id)?.operator.tactical.pepe_mut()?.stacks = 0; + if p.mode == Mode::Second { + let n = w.unit(id)?.operator.tactical.pepe()?.rage; + if n > 0 { + self.component_buff( + w, + r, + id, + "pepe:rage", + [("aspd".into(), p.rage * f64::from(n))].into(), + f64::INFINITY, + id, + )?; + } + w.unit_mut(id)?.operator.tactical.pepe_mut()?.rage = + n.saturating_add(1).min(p.rage_cap); + } + Ok(()) + } + pub(in crate::battle::runtime) fn pepe_end( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + s: &mut skills::Runtime, + p: &Pepe, + ) -> Result<(), String> { + r.remove(w, self, id, "pepe:tremor")?; + r.remove(w, self, id, "pepe:rage")?; + if Self::tac_up(w, id) { + let amount = + (f64::from(w.unit(id)?.operator.tactical.pepe()?.kills) * p.sp).min(p.sp_cap); + self.with_kit_buffs(w, r, |h, w| s.gain(w, h, amount, "talent", false, false))?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn pepe_scheduled( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + due: [bool; 5], + p: &Pepe, + ) -> Result<(), String> { + if due[3] && p.aura != 0. { + for a in self.roster.as_ref().unwrap().ids().to_vec() { + if Self::tac_up(w, a) && self.tac_def(a)?.profession == "WARRIOR" { + self.component_buff( + w, + r, + a, + "pepe:lotus", + [("atkPct".into(), p.aura)].into(), + 0.75, + id, + )?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn pepe_before( + &mut self, + w: &mut World, + id: Id, + def: &Definition, + active: bool, + c: &mut attacks::Context, + p: &Pepe, + ) -> Result<(), String> { + if active && p.mode == Mode::Second { + let mut ids = self.tac_enemies(w, id, None, false)?; + for &a in w.unit(id)?.blocking() { + if !ids.contains(&a) { + ids.push(a); + } + } + if let Some(&a) = self.rng.pick(&ids) { + c.targets = vec![a]; + } + } + if p.module_scale > 1. { + if let Some(&a) = c.targets.first() { + let radius = def.combat.area.splash.map(|a| a.radius).unwrap_or(1.) + + if active && p.mode == Mode::Third { + p.extend * f64::from(w.unit(id)?.operator.tactical.pepe()?.stacks) + } else { + 0. + }; + w.unit_mut(id)?.operator.tactical.pepe_mut()?.boost = + self.tac_radius(w, w.unit(a)?.position, radius)?.len() as f64 >= p.module_count; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn pepe_attack( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + active: bool, + p: &Pepe, + ) -> Result<(), String> { + if active && p.mode == Mode::Third { + let stack = w + .unit(id)? + .operator + .tactical + .pepe()? + .stacks + .saturating_add(1) + .min(p.stacks); + w.unit_mut(id)?.operator.tactical.pepe_mut()?.stacks = stack; + self.component_buff( + w, + r, + id, + "pepe:tremor", + [("atkPct".into(), p.stack_attack * f64::from(stack))].into(), + f64::INFINITY, + id, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn pepe_impact( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + target: Id, + impact: attacks::Impact, + p: &Pepe, + ) -> Result<(), String> { + if impact.is_skill + && impact.kind == attacks::VictimKind::Main + && p.mode == Mode::Third + && Self::tac_up(w, target) + && p.main_stun > 0. + { + self.advanced_status(w, r, id, target, "stun", p.main_stun, None)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn pepe_phase( + &mut self, + w: &mut World, + id: Id, + q: &mut hit::Request, + c: &Pepe, + ) -> Result<(), String> { + if q.is_attack && w.unit(id)?.operator.tactical.pepe()?.boost { + q.damage.mul *= c.module_scale; + } + Ok(()) + } + pub(in crate::battle::runtime) fn pepe_kill( + &mut self, + w: &mut World, + source: Id, + ) -> Result<(), String> { + if w.unit(source)?.operator.active_skill { + w.unit_mut(source)?.operator.tactical.pepe_mut()?.kills = w + .unit(source)? + .operator + .tactical + .pepe()? + .kills + .saturating_add(1); + } + Ok(()) + } + pub(in crate::battle::runtime) fn pepe_tick( + &mut self, + w: &mut World, + id: Id, + s: &mut skills::Runtime, + ) -> Result<(), String> { + if s.bank.ready() && !s.bank.active && Self::tac_abnormal(w, id) { + let mut r = self.buffs.take().unwrap(); + let result = self.tac_cleanse(w, &mut r, id); + self.buffs = Some(r); + result?; + s.activate(w, self, "abnormal", false)?; + } + Ok(()) + } +} + +impl State { + pub fn redeployed(previous: Option<&Self>) -> Self { + Self { + rage: previous.map_or(0, |p| p.rage), + ..Default::default() + } + } +} + +impl Behavior for Pepe { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::Scheduled(_)) + } + fn refreshes_skill(&self) -> bool { + self.mode == Mode::First + } + fn payload( + &self, + world: &World, + unit: Id, + payload: &mut attacks::Direct, + area: &mut attacks::Area, + ) -> Result<(), String> { + if self.mode == Mode::Third && payload.is_skill { + if let Some(splash) = &mut area.splash { + splash.radius += + self.extend * f64::from(world.unit(unit)?.operator.tactical.pepe()?.stacks); + } + } + Ok(()) + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + (Role::Source, KitEvent::Before(context)) => { + let active = k.active()?; + let definition = k.host.tac_def(id)?; + k.host + .pepe_before(k.world, id, &definition, active, context, self)?; + } + (Role::Source, KitEvent::Attack { .. }) => { + let active = k.active()?; + k.host.pepe_attack(k.world, id, k.buffs, active, self)?; + } + (Role::Source, KitEvent::Impact(impact)) => { + if let Some(target) = impact.target { + k.host + .pepe_impact(k.world, id, k.buffs, target, *impact, self)?; + } + } + ( + Role::Source, + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + }, + ) => { + k.host.pepe_phase(k.world, id, request, self)?; + } + (Role::Source, KitEvent::Landed { event, request }) + if self.mode == Mode::Third + && request.is_splash + && self.stun > 0. + && k.active()? + && Host::tac_up(k.world, event.target) => + { + k.host.advanced_status( + k.world, + k.buffs, + id, + event.target, + "stun", + self.stun, + None, + )?; + } + (Role::Source, KitEvent::Kill { .. }) => { + k.host.pepe_kill(k.world, id)?; + } + _ => {} + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Scheduled(due) => { + if k.up() { + k.host.pepe_scheduled(k.world, id, k.buffs, *due, self)?; + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.pepe_start(k.world, id, k.buffs, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::End, + skill, + .. + } if *unit == id => { + k.host.pepe_end(k.world, id, k.buffs, skill, self)?; + } + KitEvent::Refresh { skill, .. } => { + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + host.pepe_tick(world, id, skill) + })?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/philae.rs b/crates/engine/src/battle/runtime/kits/philae.rs new file mode 100644 index 0000000..ae9684e --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/philae.rs @@ -0,0 +1,322 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "primprotector", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_philae_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: true, + }, + Skill { + id: "skchr_philae_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let mode = tactical_mode(raw)?; + + s.modifiers = [("hpPct".into(), n(bb, "max_hp", 0.))].into(); + if mode == Mode::Second { + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + } + s.extra.tactics = Tactics::Philae(Philae { + mode, + scale: n(bb, "atk_scale", 1.), + element: n(bb, "ep_damage_ratio", 0.), + cooldown: n(bb, "aoe_cd", 2.), + attack: n(bb, "atk", 0.), + cut: n(t, "damage_resistance", 0.), + sp: n(t, "sp", 0.), + barrier: n(bb, "shield_value", 0.), + element_scale: n(tb, "ep_damage_scale", 1.), + }); + Ok(()) +} + +pub(crate) struct Philae { + pub mode: Mode, + pub scale: f64, + pub element: f64, + pub cooldown: f64, + pub attack: f64, + pub cut: f64, + pub sp: f64, + pub barrier: f64, + pub element_scale: f64, +} + +pub(crate) struct State { + pub ready: f64, + pub barrier: f64, +} +impl Default for State { + fn default() -> Self { + Self { + ready: f64::NEG_INFINITY, + barrier: Default::default(), + } + } +} + +impl Host { + pub(in crate::battle::runtime) fn philae_start( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Philae, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.philae_mut()?.ready = f64::NEG_INFINITY; + w.unit_mut(id)?.operator.tactical.philae_mut()?.barrier = p.barrier; + if p.mode == Mode::First { + if !crate::battle::element::locked(w, id)? { + w.unit_mut(id)?.element_buildup = [0.; 5]; + } + } else { + let mut b = Buff { + key: Some("philae:counter".into()), + ..Default::default() + }; + b.runtime.injury.observe = Some(OBSERVE); + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn philae_end( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.philae_mut()?.barrier = 0.; + r.remove(w, self, id, "philae:counter")?; + r.remove(w, self, id, "skill:philae_rage")?; + Ok(()) + } + pub(in crate::battle::runtime) fn philae_observe( + c: &mut settlement::Context<'_, Self>, + target: Id, + ) -> Result<(), String> { + let def = c.host.tac_def(target)?; + let Tactics::Philae(p) = &def.extra.tactics else { + return Err("Invalid philae observer".into()); + }; + if !Self::tac_up(c.world, target) + || !c.world.unit(target)?.operator.active_skill + || c.world.time < c.world.unit(target)?.operator.tactical.philae()?.ready + { + return Ok(()); + } + c.world + .unit_mut(target)? + .operator + .tactical + .philae_mut()? + .ready = c.world.time + p.cooldown; + let keys = c.host.tac_keys( + c.world, + target, + &[ + [-1, -1], + [-1, 0], + [-1, 1], + [0, -1], + [0, 0], + [0, 1], + [1, -1], + [1, 0], + [1, 1], + ], + )?; + for a in c.host.tac_enemies(c.world, target, Some(&keys), false)? { + c.host.tac_timer( + c.world, + target, + c.world.time + 0.0334, + 0., + 1, + Task::Blast { + target: a, + scale: p.scale, + element: p.element, + }, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn philae_blast_timer( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + t: &mut Timer, + ) -> Result { + let id = t.source.ok_or("Operator timer requires a source")?; + let Task::Blast { + target, + scale, + element, + } = &mut t.kind + else { + return Err("Invalid blast timer".into()); + }; + + if Self::tac_up(w, *target) { + let attack = Self::tac_stat(w, id, "atk")?; + self.tac_damage( + w, + r, + id, + *target, + attack * *scale, + DamageType::Arts, + false, + "counter", + )?; + if Self::tac_up(w, *target) && *element > 0. { + let mut q = crate::battle::element::Request::new( + Some(id), + Some(id), + *target, + crate::battle::element::Element::Apoptosis, + attack * *element, + ); + crate::battle::element::apply(w, self, r, &mut q)?; + } + } + + Ok(true) + } +} + +impl Behavior for Philae { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + if let KitEvent::Element { + phase: crate::battle::element::Phase::Hit, + request, + } = event + { + let target = request.damage.hit.target; + match role { + Role::Target => { + if request.damage.element == Some(crate::battle::element::Element::Apoptosis) + && !k.active()? + { + k.host + .advanced_grant_sp(k.world, k.buffs, target, self.sp)?; + } + request.damage.damage.mul *= 1. - self.cut.clamp(0., 1.); + if k.active()? { + if self.mode == Mode::First { + let amount = request.damage.damage.amount * request.damage.damage.mul; + let barrier = k.world.unit(id)?.operator.tactical.philae()?.barrier; + if amount > 0. && barrier > 0. { + let take = amount.min(barrier); + k.world + .unit_mut(id)? + .operator + .tactical + .philae_mut()? + .barrier -= take; + if take >= amount - 1e-9 { + request.damage.cancelled = true; + } else { + request.damage.damage.amount *= (amount - take) / amount; + } + } + } else if !k.has(id, "skill:philae_rage") { + k.host.component_buff( + k.world, + k.buffs, + id, + "skill:philae_rage", + [("atkPct".into(), self.attack)].into(), + f64::INFINITY, + id, + )?; + } + } + } + Role::Source => { + if k.world.unit(target)?.side == health::Side::Enemy + && !k.world.unit(id)?.blocking().is_empty() + { + request.damage.damage.mul *= self.element_scale; + } + } + } + } + Ok(()) + } + fn observe_injury( + &self, + c: &mut settlement::Context<'_, Host>, + key: &str, + _: &Buff, + ) -> Result<(), String> { + if key == "philae:counter" { + Host::philae_observe(c, c.request.hit.target)?; + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.philae_start(k.world, id, k.buffs, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + k.host.philae_end(k.world, id, k.buffs)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/prepared_summon.rs b/crates/engine/src/battle/runtime/kits/prepared_summon.rs new file mode 100644 index 0000000..b6a01c2 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/prepared_summon.rs @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Effects and reusable board pieces for placeable medical drones and shields. +use super::dispatch::{Behavior, Context, Event}; +use super::*; +use crate::battle::grid; + +pub(crate) enum PreparedSummon { + Drone { + lifetime: f64, + }, + Shield { + idle: f64, + interval: f64, + cap: f64, + refill: f64, + }, +} +#[derive(Default)] +pub(crate) struct State { + stocked: bool, + ready_at: f64, + next_pulse: f64, + target: Option, +} +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + Self { + stocked: previous.is_some_and(|s| s.stocked), + ..Default::default() + } + } +} +pub(crate) fn build(raw: &Value, spec: &mut Spec) { + let drone = raw["tokenId"] == "token_10000_silent_healrb"; + let mut protection = Buff { + key: Some("token:untargetable".into()), + permanent: true, + ..Default::default() + }; + protection.runtime.persist = true; + protection.flags.insert("untargetable".into()); + if drone { + // The countdown bar is its lifetime, with damage and healing disabled. + for flag in ["invulnerable", "noHeal", "healFree"] { + protection.flags.insert(flag.into()); + } + spec.combat.heal = true; + spec.combat.projectile = None; + spec.combat.profile.heal = Some(search::Heal { + multi: false, + count: 1., + hp_at_most: 1., + element_heal: false, + }); + spec.combat.profile.heal_attack = true; + spec.extra.tactics = Tactics::PreparedSummon(PreparedSummon::Drone { + lifetime: n(&raw["nativeSkill"], "duration", 10.), + }); + } else { + protection.flags.insert("invulnerable".into()); + spec.combat.profile.no_attack = true; + let talent = talent_at(raw, 0); + spec.extra.tactics = Tactics::PreparedSummon(PreparedSummon::Shield { + idle: n(talent, "interval", 5.), + interval: n(talent, "catsld_t_1[timer][interval].interval", 1.).max(0.01), + cap: n(talent, "max_shield_ratio", 0.), + refill: n(talent, "shield_ratio_each_trigger", 0.), + }); + } + spec.extra.effects.permanent.push(protection); +} + +fn try_drone(k: &mut Context<'_>, token: Id) -> Result { + let unit = k.world.unit(token)?; + let state = unit.operator.tactical.prepared_summon()?; + if !state.stocked + || unit.stats.alive + || unit.removed + || k.world.time + 1e-9 < state.ready_at + || !unit + .summoner + .is_some_and(|owner| Host::tac_up(k.world, owner)) + { + return Ok(false); + } + if !k.redeploy_free(token)? { + return Ok(false); + } + k.world + .unit_mut(token)? + .operator + .tactical + .prepared_summon_mut()? + .stocked = false; + Ok(true) +} + +pub(crate) fn release_drone(k: &mut Context<'_>) -> Result<(), String> { + let token = k + .host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .find(|&id| { + k.world + .unit(id) + .is_ok_and(|u| u.summoner == Some(k.unit) && u.deployment.uid.is_some()) + && k.host + .tac_def(id) + .is_ok_and(|d| d.key == "token_10000_silent_healrb") + }); + if let Some(token) = token { + k.world + .unit_mut(token)? + .operator + .tactical + .prepared_summon_mut()? + .stocked = true; + try_drone(k, token)?; + } + Ok(()) +} + +impl PreparedSummon { + fn shield(&self, k: &mut Context<'_>, connect: bool) -> Result<(), String> { + let Self::Shield { + idle, + interval, + cap, + refill, + } = *self + else { + return Ok(()); + }; + let id = k.unit; + let previous = k + .world + .unit(id)? + .operator + .tactical + .prepared_summon()? + .target; + let valid = |target: Id| { + k.world.unit(target).is_ok_and(|u| { + u.stats.alive + && u.deployed + && u.deployment.kind == crate::battle::deploy::Kind::Operator + }) + }; + let target = if !connect && previous.is_some_and(valid) { + previous + } else { + let keys = k.keys()?; + let mut target = None; + for key in keys { + let tile = [(key / grid::COLS) as i32, (key % grid::COLS) as i32]; + let candidate = + k.host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .find(|&other| { + valid(other) + && k.world.unit(other).is_ok_and(|u| u.deployment.tile == tile) + }); + if let Some(candidate) = candidate { + let occupied = + k.host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .any(|other| { + other != id + && Host::tac_up(k.world, other) + && k.world.unit(other).is_ok_and(|u| { + u.operator + .tactical + .prepared_summon() + .is_ok_and(|s| s.target == Some(candidate)) + }) + }); + if !occupied { + target = Some(candidate); + break; + } + } + } + target + }; + k.world + .unit_mut(id)? + .operator + .tactical + .prepared_summon_mut()? + .target = target; + let Some(target) = target else { + return Ok(()); + }; + let owner = k.world.unit(id)?.summoner.unwrap_or(id); + let hp = k.stat(owner, "maxHp")?; + let active = Host::tac_up(k.world, owner) && k.world.unit(owner)?.operator.active_skill; + let rate = if active { + let raw = &k.host.data.table("chess").unwrap()[&k.host.tac_def(owner)?.key]; + n(&raw["skill"]["bb"], "overwrite_ratio", refill) + } else { + refill + }; + let amount = if connect || previous != Some(target) { + hp * cap + } else if active || k.world.time - k.world.unit(target)?.last_hit_at >= idle - 1e-9 { + hp * rate * interval + } else { + 0. + }; + if amount <= 0. || cap <= 0. { + return Ok(()); + } + if let Some(buff) = k + .world + .unit_mut(target)? + .stats + .buffs_mut() + .iter_mut() + .find(|buff| buff.key.as_deref() == Some("cathy:shield")) + { + buff.shield = (buff.shield + amount).min(hp * cap); + k.world.unit_mut(target)?.stats.mark_dirty(); + } else { + let mut buff = Buff { + key: Some("cathy:shield".into()), + shield: amount.min(hp * cap), + ..Default::default() + }; + buff.runtime.duration = f64::INFINITY; + k.add(target, buff)?; + } + Ok(()) + } +} +impl Behavior for PreparedSummon { + fn handle(&self, k: &mut Context<'_>, event: &mut Event<'_>) -> Result<(), String> { + let id = k.unit; + match event { + Event::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == id => match *self { + Self::Drone { lifetime } => { + k.later(lifetime, |k| k.retreat())?; + } + Self::Shield { interval, .. } => { + k.world + .unit_mut(id)? + .operator + .tactical + .prepared_summon_mut()? + .next_pulse = k.world.time + interval; + self.shield(k, true)?; + } + }, + Event::Death { unit, .. } if *unit == id && matches!(self, Self::Drone { .. }) => { + k.world.unit_mut(id)?.removed = false; + let ready_at = + k.world.time + k.world.unit(id)?.stats.base_number("respawnTime").max(0.); + k.world + .unit_mut(id)? + .operator + .tactical + .prepared_summon_mut()? + .ready_at = ready_at; + try_drone(k, id)?; + } + Event::Tick if matches!(self, Self::Drone { .. }) => { + try_drone(k, id)?; + if k.world + .unit(id)? + .operator + .tactical + .prepared_summon()? + .stocked + { + if let Some(owner) = k + .world + .unit(id)? + .summoner + .filter(|&owner| Host::tac_up(k.world, owner)) + { + let mut buff = Buff { + key: Some("silent:stockFull".into()), + ..Default::default() + }; + buff.runtime.duration = 2. * crate::battle::clock::DT; + buff.flags.insert("noSp".into()); + k.add(owner, buff)?; + } + } + } + Event::Tick if k.up() => { + if let Self::Shield { interval, .. } = *self { + let now = k.world.time; + let state = k + .world + .unit_mut(id)? + .operator + .tactical + .prepared_summon_mut()?; + if now + 1e-9 >= state.next_pulse { + state.next_pulse += interval; + self.shield(k, false)?; + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/qiubai.rs b/crates/engine/src/battle/runtime/kits/qiubai.rs new file mode 100644 index 0000000..5ea20d5 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/qiubai.rs @@ -0,0 +1,456 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "lord", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_qiubai_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_qiubai_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_qiubai_2", + kind: Kind::Duration, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = tactical_mode(raw)?; + + s.extra.lord = Some(Lord { + scale: n(tb, "atk_scale", 0.8), + arts: 0., + skill_full: mode == Mode::Third, + }); + skill_range(raw, s)?; + if mode != Mode::First { + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + } + if mode == Mode::Third { + s.extra.skill_arts = true; + let mut p = s.combat.profile; + p.max_targets = 3.; + s.combat.skill_profile = Some(p); + } + s.extra.tactics = Tactics::Qiubai(Qiubai { + mode, + gap: n(t, "atk_scale_t", n(t, "atk_scale", 0.)), + both: if t["atk_scale_t"].is_null() { + 1. + } else { + n(t, "value", 1.) + }, + module: n(tb, "atk_scale_m", 0.), + first: n(t1, "duration_advanced", 0.), + probability: n(t1, "prob", 0.), + bind: n(t1, "duration", 0.), + skill_bind: n(bb, "duration", 2.), + aoe: n(bb, "aoe_scale", 1.), + begin: n(bb, "sword_begin_atk_scale", 1.), + finish: n(bb, "sword_end_atk_scale", 1.), + aspd: n(bb, "attack_speed", 0.), + stacks: n(bb, "max_stack_cnt", 0.).max(0.) as u32, + crowd: n(t, "cnt", 0.).max(0.) as usize, + crowd_aspd: n(t, "attack_speed", 0.), + gap_key: if t["atk_scale_t"].is_null() { + "qiubai_talent_1[damage]" + } else { + "qiubai_e_002_t[damage]" + }, + }); + Ok(()) +} + +pub(crate) struct Qiubai { + pub mode: Mode, + pub gap: f64, + pub both: f64, + pub module: f64, + pub first: f64, + pub probability: f64, + pub bind: f64, + pub skill_bind: f64, + pub aoe: f64, + pub begin: f64, + pub finish: f64, + pub aspd: f64, + pub stacks: u32, + pub crowd: usize, + pub crowd_aspd: f64, + pub gap_key: &'static str, +} + +#[derive(Default)] +pub(crate) struct State { + pub stacks: u32, + pub hit: std::collections::BTreeMap, +} + +impl Host { + pub(in crate::battle::runtime) fn qiubai_start( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Qiubai, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.qiubai_mut()?.stacks = 0; + if p.mode == Mode::Second { + for a in self.tac_enemies(w, id, None, false)? { + let amount = Self::tac_stat(w, id, "atk")? * p.begin; + self.tac_damage(w, r, id, a, amount, DamageType::Arts, false, "sword")?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn qiubai_end( + &mut self, + c: &skills::Context, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Qiubai, + ) -> Result<(), String> { + r.remove(w, self, id, "qiubai:snow")?; + if p.mode == Mode::Second && c.reason != "death" && Self::tac_up(w, id) { + for a in self.tac_enemies(w, id, None, false)? { + let amount = Self::tac_stat(w, id, "atk")? * p.finish; + self.tac_damage(w, r, id, a, amount, DamageType::Physical, false, "swordEnd")?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn qiubai_skill_tick( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Qiubai, + ) -> Result<(), String> { + if p.mode == Mode::Second { + for a in self.tac_enemies(w, id, None, false)? { + self.advanced_status(w, r, id, a, "sluggish", 0.25, None)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn qiubai_scheduled( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + due: [bool; 5], + p: &Qiubai, + ) -> Result<(), String> { + if due[2] && p.crowd > 0 && p.crowd_aspd != 0. { + if self.tac_enemies(w, id, None, true)?.len() >= p.crowd { + self.component_buff( + w, + r, + id, + "qiubai:crowd", + [("aspd".into(), p.crowd_aspd)].into(), + 0.4, + id, + )?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn qiubai_attack( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + active: bool, + p: &Qiubai, + ) -> Result<(), String> { + if active && p.mode == Mode::Third { + let stack = w + .unit(id)? + .operator + .tactical + .qiubai()? + .stacks + .saturating_add(1) + .min(p.stacks); + w.unit_mut(id)?.operator.tactical.qiubai_mut()?.stacks = stack; + self.component_buff( + w, + r, + id, + "qiubai:snow", + [("aspd".into(), p.aspd * f64::from(stack))].into(), + f64::INFINITY, + id, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn qiubai_impact( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + target: Id, + impact: attacks::Impact, + p: &Qiubai, + ) -> Result<(), String> { + if impact.is_skill && p.mode == Mode::First && Self::tac_up(w, target) { + self.advanced_status(w, r, id, target, "bind", p.skill_bind, None)?; + self.tac_timer( + w, + id, + w.time + p.skill_bind, + 0., + 1, + Task::Explosion { + target, + position: w.unit(target)?.position, + scale: p.aoe, + }, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn qiubai_calculate( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + c: &Qiubai, + q: &mut hit::Request, + ) -> Result<(), String> { + let target = q.hit.target; + if c.gap > 0. { + let mut b = Buff { + key: Some(c.gap_key.into()), + ..Default::default() + }; + b.runtime.source = Some(id); + b.runtime.on_remove = Some(GAP_FINISH); + b.runtime.tick_payload = c.gap; + let bid = r.add( + w, + self, + target, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + if let Some(bid) = bid { + self.tac_timer(w, id, w.time + 0.1, 0., 1, Task::Gap { target, buff: bid })?; + } + } + let seq = w.unit(id)?.deployment.deploy_seq; + let first = + c.first > 0. && w.unit(id)?.operator.tactical.qiubai()?.hit.get(&target) != Some(&seq); + if first { + w.unit_mut(id)? + .operator + .tactical + .qiubai_mut()? + .hit + .insert(target, seq); + self.advanced_status(w, r, id, target, "bind", c.first, None)?; + } else if c.probability > 0. && self.rng.chance(c.probability) { + self.advanced_status(w, r, id, target, "bind", c.bind, None)?; + } + if c.module > 0. { + let amount = Self::tac_stat(w, id, "atk")? * c.module; + self.tac_damage( + w, + r, + id, + target, + amount, + DamageType::Arts, + false, + "lordAddition", + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn qiubai_explosion_timer( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + t: &mut Timer, + ) -> Result { + let id = t.source.ok_or("Operator timer requires a source")?; + let Task::Explosion { + target, + position, + scale, + } = &mut t.kind + else { + return Err("Invalid explosion timer".into()); + }; + + let pos = w.unit(*target).map(|u| u.position).unwrap_or(*position); + for a in self.tac_radius(w, pos, 1.2)? { + let amount = Self::tac_stat(w, id, "atk")? * *scale; + self.tac_damage(w, r, id, a, amount, DamageType::Arts, false, "explosion")?; + } + + Ok(true) + } + pub(in crate::battle::runtime) fn qiubai_gap_timer( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + t: &mut Timer, + ) -> Result { + let Task::Gap { target, buff } = &mut t.kind else { + return Err("Invalid gap timer".into()); + }; + + if w.unit(*target).is_ok() { + r.remove_id(w, self, *target, *buff)?; + } + + Ok(true) + } + pub(in crate::battle::runtime) fn qiubai_gap_removed( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + let b = r.get(w, c.unit, c.buff)?.clone(); + let id = b.runtime.source.ok_or("Missing qiubai buff source")?; + + if w.unit(c.unit)?.stats.hp > 0. { + let def = self.tac_def(id)?; + let Tactics::Qiubai(p) = &def.extra.tactics else { + return Err("Invalid gap callback".into()); + }; + let slug = Self::tac_has(w, c.unit, "sluggish"); + let bind = Self::tac_has(w, c.unit, "bind"); + if slug || bind { + let amount = + Self::tac_stat(w, id, "atk")? * p.gap * if slug && bind { p.both } else { 1. }; + self.tac_damage(w, r, id, c.unit, amount, DamageType::Arts, false, "gap")?; + } + } + return Ok(()); + } +} + +impl Behavior for Qiubai { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::Scheduled(_)) + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + ( + Role::Source, + KitEvent::Buff { + context, + token: GAP_FINISH, + .. + }, + ) => { + k.host.qiubai_gap_removed(k.world, k.buffs, *context)?; + } + + (Role::Source, KitEvent::Attack { .. }) => { + let active = k.active()?; + k.host.qiubai_attack(k.world, id, k.buffs, active, self)?; + } + (Role::Source, KitEvent::Impact(impact)) => { + if let Some(target) = impact.target { + k.host + .qiubai_impact(k.world, id, k.buffs, target, *impact, self)?; + } + } + ( + Role::Source, + KitEvent::Hit { + phase: hit::Phase::Calculate, + request, + }, + ) => { + if k.world.unit(request.hit.target)?.side == health::Side::Enemy { + k.host + .qiubai_calculate(k.world, k.buffs, id, self, request)?; + } + } + _ => {} + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Scheduled(due) => { + let mut hits = + std::mem::take(&mut k.world.unit_mut(id)?.operator.tactical.qiubai_mut()?.hit); + hits.retain(|target, _| k.world.unit(*target).is_ok()); + k.world.unit_mut(id)?.operator.tactical.qiubai_mut()?.hit = hits; + if k.up() { + k.host.qiubai_scheduled(k.world, id, k.buffs, *due, self)?; + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.qiubai_start(k.world, id, k.buffs, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + .. + } if *unit == id => { + k.host.qiubai_skill_tick(k.world, id, k.buffs, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::End, + context, + .. + } if *unit == id => { + k.host.qiubai_end(context, k.world, id, k.buffs, self)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/reed2.rs b/crates/engine/src/battle/runtime/kits/reed2.rs new file mode 100644 index 0000000..265a39f --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/reed2.rs @@ -0,0 +1,275 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "incantationmedic", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[Skill { + id: "skchr_reed2_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "DEFAULT", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + if raw["skill"]["skillId"] != "skchr_reed2_3" { + return Err("Unknown selected skill".into()); + } + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let self_attack = bb + .as_object() + .into_iter() + .flatten() + .find(|(key, _)| { + !key.starts_with("talent@") && (key.as_str() == "atk" || key.ends_with(".atk")) + }) + .map_or(0., |(_, value)| { + value.as_f64().filter(|v| v.is_finite()).unwrap_or(0.) + }); + s.modifiers = [("atkPct".into(), self_attack)].into(); + s.extra.support.incantation = n(&raw["trait"]["bb"], "scale", 0.5); + let mut profile = s.combat.profile; + profile.max_targets = n(bb, "max_target", 1.).floor().max(1.); + s.combat.skill_profile = Some(profile); + s.extra.tactics = Tactics::Reed2(Reed2 { + probability: n(t, "prob", 0.), + skill_probability: n(bb, "talent@prob", n(t, "prob", 0.)), + scorch_atk: n(t, "atk", 0.), + fragile: n(t, "damage_scale", 1.) - 1., + duration: n(t, "duration", 6.), + dot: n(bb, "talent@s3_atk_scale", 0.), + explosion: n(bb, "talent@aoe_scale", 0.), + radius: n(bb, "talent@range_radius", 1.7), + share: n(t1, "scale", 0.), + heal_boost: n(t1, "heal_scale", 1.), + module_damage: n(talent_at(raw, -1), "damage_scale", 1.), + }); + Ok(()) +} +pub(crate) struct Reed2 { + probability: f64, + skill_probability: f64, + scorch_atk: f64, + fragile: f64, + duration: f64, + dot: f64, + explosion: f64, + radius: f64, + share: f64, + heal_boost: f64, + module_damage: f64, +} +#[derive(Default)] +pub(crate) struct State { + accumulator: f64, +} +impl Reed2 { + fn scorch(&self, k: &mut KitContext<'_>, target: Id) -> Result<(), String> { + if !Host::tac_up(k.world, target) { + return Ok(()); + } + let duration = if k.active()? { + k.host + .roster + .as_ref() + .unwrap() + .entry(k.unit)? + .skill() + .map_or(self.duration, |s| s.time_left.max(0.1)) + } else { + self.duration + }; + let mut buff = Buff { + key: Some("reed2:scorch".into()), + ..Default::default() + }; + if self.scorch_atk != 0. { + buff.mods.insert("atkPct".into(), self.scorch_atk); + } + buff.runtime.duration = duration; + buff.runtime.refresh = buffs::Refresh::Extend; + k.add(target, buff)?; + if self.fragile > 0. { + k.status(target, "artsFragile", duration, Some(self.fragile))?; + } + Ok(()) + } + fn explosion(k: &mut KitContext<'_>, position: [f64; 2], _: f64) -> Result<(), String> { + let def = k.host.tac_def(k.unit)?; + let Tactics::Reed2(p) = &def.extra.tactics else { + return Err("Invalid reed2 kit".into()); + }; + let targets = attacks::Hooks::radius_targets( + k.host, + position, + p.radius, + true, + k.world, + k.world.unit_capacity(), + )?; + for target in targets { + let amount = k.stat(k.unit, "atk")? * p.explosion; + let mut request = hit::Request::new( + health::Hit { + source: Some(k.unit), + credit: Some(k.unit), + target, + damage_type: DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.is_skill = true; + request.is_splash = true; + request.dodge_mode = injury::DodgeMode::Ignore; + request.tags.extend(["skill".into(), "scorch".into()]); + k.deal(&mut request)?; + p.scorch(k, target)?; + } + Ok(()) + } +} +impl Behavior for Reed2 { + fn heal_amount( + &self, + _: &World, + unit: Id, + target: Id, + amount: f64, + _: health::HealOptions, + ) -> Result { + Ok(if unit == target { + amount + } else { + amount * self.heal_boost + }) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .reed2_mut()? + .accumulator = 0.; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id => { + let state = k.world.unit_mut(id)?.operator.tactical.reed2_mut()?; + state.accumulator += context.dt; + if state.accumulator + 1e-9 < 1. { + return Ok(()); + } + state.accumulator -= 1.; + if self.dot > 0. { + let amount = k.stat(id, "atk")? * self.dot; + for target in k.host.spawns.as_ref().unwrap().live().to_vec() { + if Host::tac_up(k.world, target) + && !k.world.unit(target)?.hidden + && k.has(target, "reed2:scorch") + { + k.damage(target, amount, DamageType::Arts, true, "scorch")?; + } + } + } + } + KitEvent::Landed { event, request } + if event.source == Some(id) + && k.world.unit(event.target)?.side == health::Side::Enemy + && k.world.unit(event.target)?.stats.alive + && !request.tags.iter().any(|tag| tag == "scorch") => + { + let probability = if k.active()? { + self.skill_probability + } else { + self.probability + }; + if probability >= 1. || probability > 0. && k.host.rng.next_f64() < probability { + self.scorch(k, event.target)?; + } + } + KitEvent::Death { unit, .. } + if k.up() + && k.active()? + && self.explosion > 0. + && k.world.unit(*unit)?.side == health::Side::Enemy + && k.has(*unit, "reed2:scorch") => + { + k.later_at( + 0., + k.world.unit(*unit)?.position, + 0., + false, + Self::explosion, + )?; + } + KitEvent::Heal { event, .. } + if event.source == Some(id) + && event.target != id + && self.share > 0. + && event.amount > 0. => + { + k.heal( + id, + event.amount * self.share, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + KitEvent::Scheduled(due) if due[2] && k.up() && self.module_damage > 1. => { + let keys = k.keys()?; + if search::Host::injured_allies( + k.host, + id, + &keys, + false, + k.world, + k.world.unit_capacity(), + )? + .iter() + .any(|target| *target != id) + { + k.buff( + id, + "reed2:corner", + [("dmgDealtMul".into(), self.module_damage)].into(), + 0.4, + )?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/rmixer.rs b/crates/engine/src/battle/runtime/kits/rmixer.rs new file mode 100644 index 0000000..f333a57 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/rmixer.rs @@ -0,0 +1,513 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "shotprotector", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_rmixer_3", + kind: Kind::Ammo, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: true, + }, + Skill { + id: "skchr_rmixer_1", + kind: Kind::Instant, + sp_type: SpType::Hurt, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_rmixer_2", + kind: Kind::Ammo, + sp_type: SpType::Time, + rule: "TAKE_DAMAGE", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = tactical_mode(raw)?; + + if mode == Mode::First { + s.combat.skill_scale = n(bb, "atk_scale", 1.3); + s.combat.skill_hits = 3; + } else { + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("defPct".into(), n(bb, "def", 0.)), + ("hpPct".into(), n(bb, "max_hp", 0.)), + ] + .into(); + s.extra.effects.ammo_count = n(bb, "attack@trigger_time", 30.); + } + if mode == Mode::Third { + skill_range(raw, s)?; + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + } + s.extra.tactics = Tactics::Rmixer(Rmixer { + mode, + targets: n(bb, "attack@max_target", 3.).max(1.) as usize, + counter_ratio: n(bb, "base_attack_time", 0.6), + reload: n(bb, "charge", 1.), + team_reload: n(bb, "ammo", 0.), + fatal_cost: n(bb, "ammo_cost", 30.), + defence: n(t, "def", 0.), + aspd: n(t, "attack_speed", 0.), + stacks: n(t, "max_stack_cnt", 3.).max(1.) as u32, + duration: n(t, "duration", 10.), + idle: n(t1, "interval", 8.), + shield: n(t1, "shield", 0.15), + reveal: raw["module"]["active"] == true && raw["module"]["id"] == "uniequip_002_rmixer", + }); + Ok(()) +} + +pub(crate) struct Rmixer { + pub mode: Mode, + pub targets: usize, + pub counter_ratio: f64, + pub reload: f64, + pub team_reload: f64, + pub fatal_cost: f64, + pub defence: f64, + pub aspd: f64, + pub stacks: u32, + pub duration: f64, + pub idle: f64, + pub shield: f64, + pub reveal: bool, +} + +pub(crate) struct State { + pub ready: f64, + pub boost: bool, + pub last_attack: f64, + pub shield_lost: f64, + pub pre_hp: f64, +} +impl Default for State { + fn default() -> Self { + Self { + ready: f64::NEG_INFINITY, + boost: Default::default(), + last_attack: f64::NEG_INFINITY, + shield_lost: f64::NEG_INFINITY, + pre_hp: Default::default(), + } + } +} + +impl Host { + pub(in crate::battle::runtime) fn tac_laterano( + &self, + w: &World, + id: Id, + near: bool, + ) -> Result, String> { + let mut out = vec![]; + for &a in self.roster.as_ref().unwrap().ids() { + if a != id + && Self::tac_up(w, a) + && self.tac_def(a)?.laterano + && (!near || body::in_radius(w.unit(a)?, w.unit(id)?.position, 1.5)) + { + out.push(a); + } + } + out.sort_by_key(|a| std::cmp::Reverse(w.unit(*a).unwrap().deployment.deploy_seq)); + Ok(out) + } + pub(in crate::battle::runtime) fn tac_reload( + &mut self, + w: &mut World, + id: Id, + amount: f64, + ) -> Result { + if self.roster.as_ref().unwrap().entry(id)?.skill().is_err() { + return Ok(false); + } + let mut s = self.roster.as_mut().unwrap().take_skill(id)?; + let active = s.bank.active && s.bank.kind == crate::battle::sp::Kind::Ammo; + if active { + s.ammo_left = (s.ammo_left + amount).min(s.ammo_max); + } + self.roster.as_mut().unwrap().restore_skill(id, s)?; + let _ = w; + Ok(active) + } + pub(in crate::battle::runtime) fn rmixer_fatal( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + e: &mut health::Event, + p: &Rmixer, + ) -> Result<(), String> { + if e.stage != health::Stage::Fatal + || e.prevented + || self.holds_undying(w, e.target)? + || w.unit(e.target)?.side != health::Side::Ally + { + return Ok(()); + } + let id = e.target; + if p.mode != Mode::Second || !w.unit(id)?.operator.active_skill { + return Ok(()); + } + self.with_kit_buffs(w, r, |h, w| { + let mut s = h.roster.as_mut().unwrap().take_skill(id)?; + let result = (|| { + if s.ammo_left > 0. { + e.prevented = true; + w.unit_mut(id)?.stats.hp = w + .unit(id)? + .operator + .tactical + .rmixer()? + .pre_hp + .max(1.) + .min(Self::tac_stat(w, id, "maxHp")?); + s.ammo_left = (s.ammo_left - p.fatal_cost).max(0.); + if s.ammo_left <= 0. { + s.end(w, h, "ammo")?; + } + } + Ok(()) + })(); + let restore = h.roster.as_mut().unwrap().restore_skill(id, s); + result.and(restore) + }) + } + pub(in crate::battle::runtime) fn rmixer_start( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Rmixer, + ) -> Result<(), String> { + if p.mode == Mode::Third { + w.unit_mut(id)?.operator.tactical.rmixer_mut()?.ready = f64::NEG_INFINITY; + let mut b = Buff { + key: Some("rmixer:counter".into()), + ..Default::default() + }; + b.runtime.injury.observe = Some(OBSERVE); + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + for a in self.tac_laterano(w, id, false)? { + self.tac_reload(w, a, p.team_reload)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn rmixer_end( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + r.remove(w, self, id, "rmixer:counter")?; + Ok(()) + } + pub(in crate::battle::runtime) fn rmixer_scheduled( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + due: [bool; 5], + p: &Rmixer, + ) -> Result<(), String> { + if due[0] && !Self::tac_has(w, id, "rmixer:shield") { + let since = w + .unit(id)? + .deployment + .deployed_at + .max(w.unit(id)?.operator.tactical.rmixer()?.last_attack) + .max(w.unit(id)?.operator.tactical.rmixer()?.shield_lost); + if w.time - since >= p.idle - 1e-9 { + let amount = Self::tac_stat(w, id, "maxHp")? * p.shield; + let mut b = Buff { + key: Some("rmixer:shield".into()), + shield: amount, + ..Default::default() + }; + b.runtime.on_remove = Some(SHIELD_LOST); + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + } + if due[1] && p.reveal { + for a in self.advanced_enemies(w, id)? { + if Self::tac_has(w, a, "stealth") { + let mut b = Buff { + key: Some("aura:reveal".into()), + flags: ["reveal".into()].into(), + ..Default::default() + }; + b.runtime.duration = 0.25; + r.add( + w, + self, + a, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn rmixer_attack( + &mut self, + w: &mut World, + id: Id, + ) -> Result<(), String> { + if !w.unit(id)?.operator.tactical.rmixer()?.boost { + w.unit_mut(id)?.operator.tactical.rmixer_mut()?.last_attack = w.time; + } + Ok(()) + } + pub(in crate::battle::runtime) fn rmixer_impact( + &mut self, + w: &mut World, + id: Id, + impact: attacks::Impact, + p: &Rmixer, + ) -> Result<(), String> { + if impact.is_skill && p.mode == Mode::First { + for a in self.tac_laterano(w, id, true)? { + if self.tac_reload(w, a, p.reload)? { + break; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn rmixer_observe( + c: &mut settlement::Context<'_, Self>, + target: Id, + ) -> Result<(), String> { + let def = c.host.tac_def(target)?; + let Tactics::Rmixer(p) = &def.extra.tactics else { + return Err("Invalid rmixer observer".into()); + }; + if !c.world.unit(target)?.operator.active_skill + || !skills::can_act(c.world, target)? + || Self::tac_has(c.world, target, "disarm") + || c.world.time < c.world.unit(target)?.operator.tactical.rmixer()?.ready - 1e-9 + { + return Ok(()); + } + let mut ids = c.host.tac_enemies(c.world, target, None, true)?; + if let Some(source) = c.request.hit.source { + if let Some(i) = ids.iter().position(|&a| a == source) { + ids.remove(i); + ids.insert(0, source); + } + } + ids.truncate(p.targets); + c.world + .unit_mut(target)? + .operator + .tactical + .rmixer_mut()? + .ready = c.world.time + Self::tac_stat(c.world, target, "interval")? * p.counter_ratio; + c.world + .unit_mut(target)? + .operator + .tactical + .rmixer_mut()? + .boost = true; + let result = c.host.with_kit_buffs(c.world, c.runtime, |h, w| { + let mut s = h.roster.as_mut().unwrap().take_skill(target)?; + let nested = h.executor.is_none(); + if nested { + h.executor = Some(attacks::Executor::new( + w.unit_capacity(), + crate::battle::operators::Combat::MAX_HITS, + )?); + } + let result = if ids.is_empty() { + w.unit_mut(target)?.attacks += 1; + s.after_attack(w, h, &[], true, false) + } else { + ally::Host::perform( + h, + target, + def.combat.profile, + search::Selection { + targets: ids, + fortress_melee: None, + }, + Some(&mut s), + w, + ) + }; + if nested { + h.executor = None; + } + let restore = h.roster.as_mut().unwrap().restore_skill(target, s); + result.and(restore) + }); + c.world + .unit_mut(target)? + .operator + .tactical + .rmixer_mut()? + .boost = false; + result?; + Ok(()) + } + + pub(in crate::battle::runtime) fn rmixer_shield_lost( + &mut self, + w: &mut World, + id: Id, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.rmixer_mut()?.shield_lost = w.time; + Ok(()) + } +} + +impl Behavior for Rmixer { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::Scheduled(_)) + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + (Role::Source, KitEvent::DamageApplied { event, .. }) => { + if k.up() + && k.world.unit(event.target)?.side == health::Side::Enemy + && event.amount > 0. + { + let mut buff = Buff { + key: Some("rmixer:t1".into()), + mods: [("defFlat".into(), self.defence), ("aspd".into(), self.aspd)].into(), + ..Default::default() + }; + buff.runtime.refresh = buffs::Refresh::Stack; + buff.runtime.max_stacks = self.stacks; + buff.runtime.duration = self.duration; + k.buffs.add( + k.world, + k.host, + id, + buffs::Spec { + buff, + ..Default::default() + }, + )?; + } + } + + ( + Role::Source, + KitEvent::Buff { + context, + token: SHIELD_LOST, + .. + }, + ) => { + k.host.rmixer_shield_lost(k.world, context.unit)?; + } + + (Role::Source, KitEvent::Attack { .. }) => { + k.host.rmixer_attack(k.world, id)?; + } + (Role::Source, KitEvent::Impact(impact)) => { + k.host.rmixer_impact(k.world, id, *impact, self)?; + } + ( + Role::Target, + KitEvent::Hit { + phase: hit::Phase::Hit, + .. + }, + ) => { + k.world.unit_mut(id)?.operator.tactical.rmixer_mut()?.pre_hp = + k.world.unit(id)?.stats.hp; + } + (Role::Target, KitEvent::Fatal(event)) => { + k.host.rmixer_fatal(k.world, k.buffs, event, self)?; + } + _ => {} + } + Ok(()) + } + fn observe_injury( + &self, + c: &mut settlement::Context<'_, Host>, + key: &str, + _: &Buff, + ) -> Result<(), String> { + if key == "rmixer:counter" { + Host::rmixer_observe(c, c.request.hit.target)?; + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Scheduled(due) => { + if k.up() { + k.host.rmixer_scheduled(k.world, id, k.buffs, *due, self)?; + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.rmixer_start(k.world, id, k.buffs, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + k.host.rmixer_end(k.world, id, k.buffs)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/rockr.rs b/crates/engine/src/battle/runtime/kits/rockr.rs new file mode 100644 index 0000000..d32b461 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/rockr.rs @@ -0,0 +1,255 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "funnel", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_rockr_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skcom_magic_rage[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skcom_magic_rage[3]" => Mode::First, + "skchr_rockr_2" => Mode::Second, + _ => return Err("Unknown selected skill".into()), + }; + s.modifiers = [("aspd".into(), n(bb, "attack_speed", 0.))].into(); + s.extra.tactics = Tactics::Rockr(Rockr { + mode: mode, + duration: n(&raw["skill"], "duration", 0.), + funnel: funnel::Parameters::read(raw), + over_atk: n(bb, "atk", 0.), + over_scale: n(bb, "scale", 1.), + rock_period: n(t, "interval", 0.), + rock_stacks: n(t, "max_stack_cnt", 0.).floor().max(0.) as u32, + rock_atk: n(t, "atk", 0.), + }); + Ok(()) +} +pub(crate) struct Rockr { + pub mode: Mode, + pub duration: f64, + pub funnel: funnel::Parameters, + pub over_atk: f64, + pub over_scale: f64, + pub rock_period: f64, + pub rock_stacks: u32, + pub rock_atk: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub funnel: funnel::State, + pub drone_target: Option, + pub drone_previous: Option, + pub drone_scale: f64, + pub drone_cooldown: f64, + pub over_at: f64, + pub overloaded: bool, +} +impl Rockr { + fn first_target(k: &mut KitContext<'_>) -> Result, String> { + let profile = k.host.tac_def(k.unit)?.combat.profile; + let mut enemies = k.enemies(None, true)?; + for enemy in k.world.unit(k.unit)?.blocking().to_vec() { + if !enemies.contains(&enemy) + && targeting::can_target_enemy( + k.world, + k.host, + Some(k.unit), + enemy, + profile.selection, + )? + { + enemies.push(enemy); + } + } + targeting::sort_enemies(k.world, k.host, k.unit, &mut enemies, profile.priority)?; + Ok(enemies.first().copied()) + } +} +impl Behavior for Rockr { + fn payload( + &self, + world: &World, + id: Id, + payload: &mut attacks::Direct, + _: &mut attacks::Area, + ) -> Result<(), String> { + if !(self.mode == Mode::Second && world.unit(id)?.operator.active_skill) { + payload.attachment = Some(self.funnel.attachment(payload.hits, false)); + payload.hits = 1; + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Tick if k.up() && self.rock_period > 0. && self.rock_stacks > 0 => { + let stacks = ((k.world.time - k.world.unit(id)?.deployment.deployed_at + 1e-9) + / self.rock_period) + .floor() + .max(0.) as u32; + let stacks = stacks.min(self.rock_stacks); + let old = k + .world + .unit(id)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("rockr:rock")) + .map_or(0, |b| b.stacks); + if stacks != old && stacks > 0 { + let mut b = Buff { + key: Some("rockr:rock".into()), + mods: [("atkPct".into(), self.rock_atk)].into(), + stacks, + ..Default::default() + }; + b.runtime.max_stacks = self.rock_stacks; + k.add(id, b)?; + } + } + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id && self.mode == Mode::Second => { + let target = Self::first_target(k)?; + let now = k.world.time; + let s = k.world.unit_mut(id)?.operator.tactical.rockr_mut()?; + s.over_at = now + self.duration / 2.; + s.overloaded = false; + s.drone_cooldown = 0.; + s.drone_target = target; + s.drone_scale = s.funnel.scale; + s.drone_previous = s.funnel.target; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id && self.mode == Mode::Second => { + let now = k.world.time; + let over = { + let s = k.world.unit_mut(id)?.operator.tactical.rockr_mut()?; + s.drone_cooldown = (s.drone_cooldown - context.dt).max(0.); + !s.overloaded && now + 1e-9 >= s.over_at + }; + if over { + k.world + .unit_mut(id)? + .operator + .tactical + .rockr_mut()? + .overloaded = true; + k.buff( + id, + "rockr:overload", + [("atkPct".into(), self.over_atk)].into(), + f64::INFINITY, + )?; + } + let old = k.world.unit(id)?.operator.tactical.rockr()?.drone_target; + let target = if let Some(t) = old.filter(|&t| Host::tac_up(k.world, t)) { + if targeting::can_target_enemy( + k.world, + k.host, + Some(id), + t, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? { + Some(t) + } else { + None + } + } else { + None + }; + let target = match target { + Some(t) => Some(t), + None => Self::first_target(k)?, + }; + k.world + .unit_mut(id)? + .operator + .tactical + .rockr_mut()? + .drone_target = target; + if let Some(target) = target { + if k.world.unit(id)?.operator.tactical.rockr()?.drone_cooldown <= 1e-9 { + let interval = k.stat(id, "interval")?; + let state = k.world.unit_mut(id)?.operator.tactical.rockr_mut()?; + let cap = self.funnel.cap + * if state.overloaded { + self.over_scale + } else { + 1. + }; + let scale = if state.drone_previous == Some(target) { + (state.drone_scale + self.funnel.delta).min(cap) + } else { + self.funnel.initial + }; + state.drone_previous = Some(target); + state.drone_scale = scale; + state.drone_cooldown = interval; + let amount = k.stat(id, "atk")? * k.stat(id, "atkScaleMul")? * scale; + k.damage(target, amount, DamageType::Arts, true, "rockr:drone")?; + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + context, + .. + } if *unit == id && self.mode == Mode::Second => { + let now = k.world.time; + let over = { + let s = k.world.unit_mut(id)?.operator.tactical.rockr_mut()?; + s.funnel.scale = s.drone_scale; + s.funnel.target = s.drone_previous; + s.drone_target = None; + let over = if s.overloaded { now - s.over_at } else { 0. }; + s.overloaded = false; + over + }; + k.remove(id, "rockr:overload")?; + if over > 0. && context.reason != "death" && k.up() { + k.status(id, "stun", over, None)?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/rosmon.rs b/crates/engine/src/battle/runtime/kits/rosmon.rs new file mode 100644 index 0000000..1fdcc82 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/rosmon.rs @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "bombarder", + ranged: true, + can_hit_fly: false, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[Skill { + id: "skchr_rosmon_2", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "DEFAULT", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + if raw["skill"]["skillId"] != "skchr_rosmon_2" { + return Err("Unknown selected skill".into()); + } + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ( + "batPct".into(), + flat_bat(raw, n(bb, "base_attack_time", 0.)), + ), + ] + .into(); + s.combat.profile.selection.ground_only = true; + s.combat.area.selection = s.combat.profile.selection; + s.combat.area.splash = Some(Splash { + radius: 0.9, + scale: 1., + hits_fly: false, + fortress_melee: false, + }); + s.combat.skill_area = s.combat.area; + let penetration = n(t, "def_penetrate_fixed", 0.); + if penetration != 0. { + s.extra.effects.permanent.push(persistent( + "rosmon:pierce", + [("defIgnoreFlat".into(), penetration)].into(), + )); + } + let times = n(tb, "attack@times", 2.).floor().max(1.); + let extra = n(bb, "add_times", 0.).floor().max(0.); + if times + extra > 64. { + return Err("Aftershock count exceeds capacity".into()); + } + s.extra.tactics = Tactics::Rosmon(Rosmon { + times: times as u32, + extra: extra as u32, + scale: n(tb, "attack@append_atk_scale", 0.5), + probability: n(bb, "attack@prob", 0.), + stun: n(bb, "attack@stun", 0.), + stable: n(t1, "atk", 0.), + }); + Ok(()) +} +pub(crate) struct Rosmon { + times: u32, + extra: u32, + scale: f64, + probability: f64, + stun: f64, + stable: f64, +} +impl Rosmon { + fn stable(k: &mut KitContext<'_>) -> Result<(), String> { + let def = k.host.tac_def(k.unit)?; + let Tactics::Rosmon(p) = &def.extra.tactics else { + return Err("Invalid rosmon kit".into()); + }; + let mut casters = Vec::new(); + for &id in k.host.roster.as_ref().unwrap().ids() { + if Host::tac_up(k.world, id) && k.host.tac_def(id)?.profession == "CASTER" { + casters.push(id); + } + } + if let Some(target) = k.host.rng.pick(&casters).copied() { + k.buff( + k.unit, + "rosmon:stable", + [("atkPct".into(), p.stable)].into(), + f64::INFINITY, + )?; + k.buff( + target, + "rosmon:stable", + [("atkPct".into(), p.stable)].into(), + f64::INFINITY, + )?; + } + Ok(()) + } + fn aftershock(k: &mut KitContext<'_>, position: [f64; 2], _: f64) -> Result<(), String> { + let def = k.host.tac_def(k.unit)?; + let Tactics::Rosmon(p) = &def.extra.tactics else { + return Err("Invalid rosmon kit".into()); + }; + let radius = if k.active()? { 1.5 } else { 0.9 }; + let targets = attacks::Hooks::radius_targets( + k.host, + position, + radius, + true, + k.world, + k.world.unit_capacity(), + )?; + for target in targets { + if targeting::flying(k.world, target)? { + continue; + } + let amount = k.stat(k.unit, "atk")? * p.scale; + let mut request = hit::Request::new( + health::Hit { + source: Some(k.unit), + credit: Some(k.unit), + target, + damage_type: DamageType::Physical, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.is_splash = true; + request.tags.push("aftershock".into()); + k.deal(&mut request)?; + } + Ok(()) + } +} +impl Behavior for Rosmon { + fn payload( + &self, + w: &World, + unit: Id, + _: &mut attacks::Direct, + area: &mut attacks::Area, + ) -> Result<(), String> { + if w.unit(unit)?.operator.active_skill { + if let Some(splash) = &mut area.splash { + splash.radius = 1.5; + } + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + match event { + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == k.unit && self.stable != 0. => { + k.later(0., Self::stable)?; + } + KitEvent::Impact(impact) + if impact.attacker == k.unit && impact.kind == attacks::VictimKind::Main => + { + let times = (self.times + if k.active()? { self.extra } else { 0 }) + .saturating_sub(1) + .max(1); + for i in 1..=times { + k.later_at(0.3 * i as f64, impact.position, 0., true, Self::aftershock)?; + } + } + KitEvent::Landed { event, request } + if event.source == Some(k.unit) + && k.active()? + && self.stun > 0. + && k.world.unit(event.target)?.side == health::Side::Enemy + && k.world.unit(event.target)?.stats.alive + && (request.is_attack || request.tags.iter().any(|t| t == "aftershock")) => + { + if k.host.rng.next_f64() < self.probability { + k.status(event.target, "stun", self.stun, None)?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/sbell2.rs b/crates/engine/src/battle/runtime/kits/sbell2.rs new file mode 100644 index 0000000..7f4e17f --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/sbell2.rs @@ -0,0 +1,346 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::status; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "phalanx", + ranged: false, + can_hit_fly: false, + physical: false, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_sbell2_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "CUSTOM_RANGE", + attack_override: true, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + if raw["skill"]["skillId"] != "skchr_sbell2_3" { + return Err("Unknown selected skill".into()); + } + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + s.combat.profile.only_while_skill = true; + s.combat.profile.all_in_range = true; + s.combat.profile.range_aoe = true; + s.combat.profile.selection.can_hit_fly = true; + s.combat.area.selection = s.combat.profile.selection; + s.combat.skill_area = s.combat.area; + s.combat.projectile = None; + s.combat.skill_scale = n(bb, "attack@atk_scale_s3", 1.); + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("aspd".into(), n(bb, "attack_speed", 0.)), + ( + "resIgnoreFlat".into(), + n(bb, "magic_resist_penetrate_fixed", 0.), + ), + ] + .into(); + skill_range(raw, s)?; + s.extra.tactics = Tactics::Sbell2(Sbell2 { + guard_def: n(tb, "def", 2.), + guard_res: n(tb, "magic_resistance", 20.), + interval: n(t, "interval", 5.5).max(0.1), + skill_interval: n(bb, "interval", n(t, "interval", 5.5)).max(0.1), + layers: n(t, "max_cast_cnt", 5.).floor().max(1.) as u32, + first: n(t, "first_snow", 0.) > 0., + slow: n(t, "move_speed", 0.), + snow_damage: n(t, "talent_magic_scale", 0.), + cold: n(t1, "cold", 0.), + freeze: n(t1, "freeze", 0.), + enemy_freeze: n(t1, "c2e_freeze", 0.), + restore: n(t1, "hp_ratio", 1.), + lure: n(bb, "attract_time", 0.), + module_damage: n(tm, "damage_scale", 0.), + module_cap: n(tm, "max_valid_stack_cnt", 5.).floor().max(1.) as usize, + }); + Ok(()) +} +pub(crate) struct Sbell2 { + guard_def: f64, + guard_res: f64, + interval: f64, + skill_interval: f64, + layers: u32, + first: bool, + slow: f64, + snow_damage: f64, + cold: f64, + freeze: f64, + enemy_freeze: f64, + restore: f64, + lure: f64, + module_damage: f64, + module_cap: usize, +} +#[derive(Default)] +pub(crate) struct State { + snow: BTreeMap, + last: BTreeMap, + accumulator: f64, + blessed: bool, +} +impl Sbell2 { + fn lay(&self, k: &mut KitContext<'_>) -> Result<(), String> { + for key in k.keys()? { + let tile = [(key / COLS) as i32, (key % COLS) as i32]; + if k.host.grid.as_ref().unwrap().ground_passable(tile, true) { + let layers = k + .world + .unit_mut(k.unit)? + .operator + .tactical + .sbell2_mut()? + .snow + .entry(key) + .or_default(); + *layers = (*layers + 1).min(self.layers); + } + } + Ok(()) + } + fn guard(&self, k: &mut KitContext<'_>) -> Result<(), String> { + k.buff( + k.unit, + "trait:phalanxGuard", + [ + ("defPct".into(), self.guard_def), + ("resFlat".into(), self.guard_res), + ] + .into(), + f64::INFINITY, + ) + } +} +impl Behavior for Sbell2 { + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Fatal(_)) { + -50 + } else { + 0 + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == id => { + self.guard(k)?; + if self.first { + self.lay(k)?; + } + } + KitEvent::Skill { + unit, + event: skills::Event::SkillStart, + .. + } if *unit == id => { + k.remove(id, "trait:phalanxGuard")?; + } + KitEvent::Skill { + unit, + event: skills::Event::SkillEnd, + .. + } if *unit == id && k.up() => { + self.guard(k)?; + } + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id && self.lure > 0. => { + let home = k.world.unit(id)?.deployment.tile; + for enemy in k.enemies(None, true)? { + if targeting::flying(k.world, enemy)? || k.world.unit(enemy)?.boss { + continue; + } + let at = k.world.unit(enemy)?.position; + let mut goal = None; + let mut nearest = f64::INFINITY; + for dr in -1..=1 { + for dc in -1..=1 { + if dr == 0 && dc == 0 { + continue; + } + let tile = [home[0] + dr, home[1] + dc]; + if !k.host.grid.as_ref().unwrap().ground_passable(tile, false) { + continue; + } + let distance = crate::deterministic::math::hypot( + at[0] - tile[0] as f64, + at[1] - tile[1] as f64, + ); + if distance < nearest - 1e-9 { + nearest = distance; + goal = Some(tile.map(|v| v as f64)); + } + } + } + if let Some(point) = goal { + status::apply( + k.world, + k.host, + k.buffs, + Rect::FULL, + enemy, + "attract", + status::Options { + duration: self.lure, + source: Some(id), + point: Some(point), + ..Default::default() + }, + )?; + } + } + } + KitEvent::Tick if k.up() => { + let active = k.active()?; + let state = k.world.unit_mut(id)?.operator.tactical.sbell2_mut()?; + state.accumulator += DT; + if state.accumulator + 1e-9 + >= if active { + self.skill_interval + } else { + self.interval + } + { + state.accumulator = 0.; + self.lay(k)?; + } + if k.world + .unit(id)? + .operator + .tactical + .sbell2()? + .snow + .is_empty() + { + return Ok(()); + } + for enemy in k.host.spawns.as_ref().unwrap().live().to_vec() { + if !Host::tac_up(k.world, enemy) || k.world.unit(enemy)?.hidden { + continue; + } + let pos = k.world.unit(enemy)?.position; + let tile = pos.map(|v| (v + 0.5).floor() as i32); + if !Grid::in_bounds(tile) { + continue; + } + let key = tile[0] as usize * COLS + tile[1] as usize; + let flying = targeting::flying(k.world, enemy)?; + let state = k.world.unit_mut(id)?.operator.tactical.sbell2_mut()?; + if state.last.get(&enemy).copied() != Some(key) { + if let Some(prev) = state.last.insert(enemy, key) { + if !flying { + state.snow.remove(&prev); + } + } + if !flying && state.snow.contains_key(&key) && self.snow_damage > 0. { + let amount = k.stat(id, "atk")? * self.snow_damage; + k.damage(enemy, amount, DamageType::Arts, false, "snow")?; + } + } + if let Some(&layers) = + k.world.unit(id)?.operator.tactical.sbell2()?.snow.get(&key) + { + if k.world.unit(enemy)?.stats.alive && self.slow != 0. { + k.buff( + enemy, + "sbell2:snow", + [("moveMul".into(), (1. + self.slow * layers as f64).max(0.))] + .into(), + 0.2, + )?; + } + } + } + let valid: BTreeSet<_> = k.world.unit_ids().collect(); + k.world + .unit_mut(id)? + .operator + .tactical + .sbell2_mut()? + .last + .retain(|enemy, _| valid.contains(enemy)); + } + KitEvent::Landed { event, request } + if event.target == id + && request.hit.damage_type != DamageType::Elemental + && self.cold > 0. => + { + if let Some(source) = event.source.filter(|&source| { + Host::tac_up(k.world, source) + && k.world + .unit(source) + .is_ok_and(|u| u.side == health::Side::Enemy) + }) { + k.status(source, "cold", self.cold, None)?; + } + } + KitEvent::Fatal(event) + if event.target == id + && !event.prevented + && !k.world.unit(id)?.operator.tactical.sbell2()?.blessed => + { + event.prevented = true; + k.world + .unit_mut(id)? + .operator + .tactical + .sbell2_mut()? + .blessed = true; + let hp = (k.stat(id, "maxHp")? * self.restore).max(1.); + k.world.unit_mut(id)?.stats.hp = hp; + if self.freeze > 0. { + status::apply( + k.world, + k.host, + k.buffs, + Rect::FULL, + id, + "freeze", + status::Options { + source: Some(id), + duration: self.freeze, + force: true, + ..Default::default() + }, + )?; + } + if self.enemy_freeze > 0. { + for enemy in k.enemies(None, true)? { + k.status(enemy, "freeze", self.enemy_freeze, None)?; + } + } + } + KitEvent::Scheduled(due) if due[2] && k.up() && self.module_damage > 0. => { + let count = k.enemies(None, true)?.len().min(self.module_cap); + if count > 0 { + k.buff( + id, + "sbell2:heart", + [("dmgDealtMul".into(), 1. + self.module_damage * count as f64)].into(), + 0.4, + )?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/siege2.rs b/crates/engine/src/battle/runtime/kits/siege2.rs new file mode 100644 index 0000000..e555119 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/siege2.rs @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "artsfghter", + ranged: false, + can_hit_fly: false, + physical: false, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_siege2_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "CUSTOM_RANGE", + attack_override: true, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tb = &raw["trait"]["bb"]; + s.combat.damage = DamageType::Arts; + s.combat.skill_damage = Some(DamageType::True); + s.trigger_range = Some(tactical_grid( + &raw["skill"]["trigger"]["customRangeGrid"], + false, + )?); + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ( + "batPct".into(), + flat_bat(raw, n(bb, "base_attack_time", 0.)), + ), + ] + .into(); + let mut p = s.combat.profile; + p.max_targets = n(bb, "attack@max_target", 1.).floor().max(1.); + s.combat.skill_profile = Some(p); + let grid = raw["talents"] + .as_array() + .and_then(|a| a.iter().find(|t| t["index"] == 0)) + .map(|t| &t["rangeGrid"]) + .ok_or("Missing Siege talent range")?; + s.extra.tactics = Tactics::Siege2(Siege2 { + grid: tactical_grid(grid, false)?, + protection: n(t, "damage_resistance", 0.), + attack: n(t, "atk", 0.), + tremble: n(t1, "not_combat_normal", n(t1, "not_combat", 0.)), + elite: n(t1, "not_combat_elite", n(t1, "not_combat", 0.)), + fragile: n(tb, "damage_scale", 1.) - 1., + speed: n(tb, "attack_speed", 0.), + tremble_scale: n(talent_at(raw, -1), "damage_scale", 1.), + }); + Ok(()) +} +pub(crate) struct Siege2 { + grid: Vec<[i32; 2]>, + protection: f64, + attack: f64, + tremble: f64, + elite: f64, + fragile: f64, + speed: f64, + tremble_scale: f64, +} +#[derive(Default)] +pub(crate) struct State { + lions: Vec, + seen: BTreeSet, +} +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + Self { + seen: previous.map(|s| s.seen.clone()).unwrap_or_default(), + ..Default::default() + } + } +} +impl Behavior for Siege2 { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + for tile in k.summon_tiles(&self.grid, false)? { + if let Some(token) = + k.summon("token_10040_siege2_vlion", tile, skill.time_left)? + { + k.world + .unit_mut(id)? + .operator + .tactical + .siege2_mut()? + .lions + .push(token); + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + for token in + std::mem::take(&mut k.world.unit_mut(id)?.operator.tactical.siege2_mut()?.lions) + { + let owner = k.unit; + k.unit = token; + let result = k.retreat(); + k.unit = owner; + result?; + } + k.world.unit_mut(id)?.operator.advanced.extra_range.clear(); + } + KitEvent::Scheduled(due) if due[2] && k.up() => { + let keys = k.range(&self.grid)?; + let mut allies = k.allies(&keys)?; + if !allies.contains(&id) { + allies.push(id); + } + if self.protection > 0. { + for &ally in &allies { + k.buff( + ally, + "siege2:sigh", + [("physTakenMul".into(), 1. - self.protection)].into(), + 0.4, + )?; + } + } + let count = allies.iter().filter(|&&a| a != id).count(); + if count > 0 && self.attack != 0. { + k.buff( + id, + "siege2:kings", + [("atkPct".into(), self.attack * count as f64)].into(), + 0.4, + )?; + } + if self.speed != 0. && k.world.unit(id)?.blocking().is_empty() { + k.buff(id, "siege2:free", [("aspd".into(), self.speed)].into(), 0.4)?; + } + if self.fragile > 0. { + for target in k.world.unit_ids().collect::>() { + if let Some(blocker) = k.world.unit(target)?.blocked_by() { + if blocker == id || k.world.unit(blocker)?.summoner == Some(id) { + k.status(target, "fragile", 0.4, Some(self.fragile))?; + } + } + } + } + let live = k.world.unit_ids().collect::>(); + k.world + .unit_mut(id)? + .operator + .tactical + .siege2_mut()? + .seen + .retain(|e| live.contains(e)); + } + KitEvent::Tick if k.up() && k.active()? => { + let keys = k.range(&self.grid)?; + let mut targets = Vec::new(); + for ally in k.allies(&keys)? { + for &enemy in k.world.unit(ally)?.blocking() { + if let Some(key) = body::position_key(k.world.unit(enemy)?) { + targets.push(key); + } + } + } + k.world.unit_mut(id)?.operator.advanced.extra_range = targets; + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if self.tremble_scale > 1. && k.has(request.hit.target, "tremble") => { + if request.hit.source.is_some_and(|a| { + a == id || k.world.unit(a).is_ok_and(|u| u.summoner == Some(id)) + }) { + request.damage.mul *= self.tremble_scale; + } + } + KitEvent::Landed { event, .. } + if event.source == Some(id) + && k.world.unit(event.target)?.side == health::Side::Enemy => + { + if !k + .world + .unit(id)? + .operator + .tactical + .siege2()? + .seen + .contains(&event.target) + { + let u = k.world.unit(event.target)?; + let duration = if u.boss || u.targeting.elite { + self.elite + } else { + self.tremble + }; + if duration > 0. { + k.world + .unit_mut(id)? + .operator + .tactical + .siege2_mut()? + .seen + .insert(event.target); + if k.world.unit(event.target)?.stats.alive { + k.status(event.target, "tremble", duration, None)?; + } + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/silent.rs b/crates/engine/src/battle/runtime/kits/silent.rs new file mode 100644 index 0000000..2008af6 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/silent.rs @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "physician", + ranged: false, + can_hit_fly: false, + physical: false, + projectile: "orb", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_silent_2", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skcom_heal_up[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skcom_heal_up[3]" => Mode::First, + "skchr_silent_2" => Mode::Second, + _ => return Err("Unknown selected skill".into()), + }; + healing(s, 1.); + if mode == Mode::First { + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + } else { + s.rule_override = Some(skills::Rule::SpFull); + } + s.extra.tactics = Tactics::Silent(Silent { + aspd: n(t, "attack_speed", 0.), + ground_heal: n(tb, "heal_scale", 1.), + }); + Ok(()) +} +pub(crate) struct Silent { + pub aspd: f64, + pub ground_heal: f64, +} +impl Behavior for Silent { + fn heal_multiplier(&self, w: &World, target: Id) -> Result { + Ok(if w.unit(target)?.ground { + self.ground_heal + } else { + 1. + }) + } + + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + match event { + KitEvent::Scheduled(due) + if (due[3] || k.world.time == 0.) && k.up() && self.aspd != 0. => + { + for target in k.host.roster.as_ref().unwrap().ids().to_vec() { + if Host::tac_up(k.world, target) + && k.host.tac_def(target)?.profession == "MEDIC" + { + if let Some(buff) = k + .world + .unit(target)? + .stats + .buffs() + .iter() + .find(|buff| buff.key.as_deref() == Some("talent:silent")) + { + if buff.runtime.source != Some(k.unit) + && buff.runtime.tick_payload > self.aspd + && buff.runtime.time_left > 0.05 + { + continue; + } + } + let mut buff = Buff { + key: Some("talent:silent".into()), + mods: [("aspd".into(), self.aspd)].into(), + ..Default::default() + }; + buff.runtime.duration = 0.6; + buff.runtime.tick_payload = self.aspd; + k.add(target, buff)?; + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == k.unit && skill.spec.rule == skills::Rule::SpFull => { + super::prepared_summon::release_drone(k)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/skadi2.rs b/crates/engine/src/battle/runtime/kits/skadi2.rs new file mode 100644 index 0000000..fad5365 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/skadi2.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::deploy; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SUPPORT", + branch: "bard", + ranged: false, + can_hit_fly: false, + physical: false, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_skadi2_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "SP_FULL", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + if raw["skill"]["skillId"] != "skchr_skadi2_3" { + return Err("Unknown selected skill".into()); + } + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 1); + let tm = talent_at(raw, -1); + s.combat.profile.no_attack = true; + s.combat.projectile = None; + s.extra.tactics = Tactics::Skadi2(Skadi2 { + regen: n(tb, "attack@atk_to_hp_recovery_ratio", 0.1), + inspire: n(bb, "atk", 0.), + damage: n(bb, "atk_scale", 0.), + loss: n(bb, "hp_ratio", 0.), + nearby_atk: n( + t, + "skadi2_e_003_t_2[atk][1].atk", + n(t, "skadi2_t_2[atk][1].atk", 0.), + ), + abyssal_atk: n( + t, + "skadi2_e_003_t_2[atk][2].atk", + n(t, "skadi2_t_2[atk][2].atk", 0.), + ), + defence: n(t, "skadi2_e_003_t_2[def].def", 0.), + module_count: n(tm, "cnt", f64::INFINITY), + module_atk: n(tm, "atk", 0.), + }); + Ok(()) +} +pub(crate) struct Skadi2 { + regen: f64, + inspire: f64, + damage: f64, + loss: f64, + nearby_atk: f64, + abyssal_atk: f64, + defence: f64, + module_count: f64, + module_atk: f64, +} +#[derive(Default)] +pub(crate) struct State { + pulses: u64, +} +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + Self { + pulses: previous.map_or(0, |s| s.pulses), + } + } +} +impl Skadi2 { + fn inspire(k: &mut KitContext<'_>, target: Id, value: f64) -> Result<(), String> { + if value <= 0. + || matches!( + k.host.tac_def(target)?.extra.tactics, + Tactics::Skadi2(_) | Tactics::Cetsyr(_) + ) + { + return Ok(()); + } + let key = "inspire"; + if k.world.unit(target)?.stats.buffs().iter().any(|b| { + b.key.as_deref() == Some(key) + && b.runtime.source != Some(k.unit) + && b.runtime.tick_payload > value + && b.runtime.time_left > 0.1 + }) { + return Ok(()); + } + let modifiers = crate::battle::stats::Modifiers::aggregate_except( + k.world.unit(target)?.stats.buffs(), + key, + ) + .map_err(str::to_string)?; + let factor = (1. + modifiers.add.get("atkPct").copied().unwrap_or(0.)).max(0.) + * modifiers.mul.get("atkMul").copied().unwrap_or(1.); + let mut buff = Buff { + key: Some(key.into()), + mods: [( + "atkFlat".into(), + if factor > 1e-6 { value / factor } else { value }, + )] + .into(), + ..Default::default() + }; + buff.runtime.duration = 0.75; + buff.runtime.tick_payload = value; + k.add(target, buff)?; + Ok(()) + } +} +impl Behavior for Skadi2 { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + if let KitEvent::Scheduled(due) = event { + if !due[3] || !k.up() { + return Ok(()); + } + let id = k.unit; + let remove: Vec<_> = k + .world + .unit(id)? + .stats + .buffs() + .iter() + .filter(|b| { + b.key.as_ref().is_some_and(|key| { + key == "inspire" || key.starts_with("inspire:") || key.ends_with(":inspire") + }) + }) + .map(|b| b.runtime.id()) + .collect(); + for buff in remove { + k.buffs.remove_id(k.world, k.host, id, buff)?; + } + let keys = k.keys()?; + let allies = k.allies(&keys)?; + let mut others = Vec::new(); + let mut abyssal = false; + for &ally in &allies { + if ally == id || k.world.unit(ally)?.deployment.kind != deploy::Kind::Operator { + continue; + } + others.push(ally); + let def = k.host.tac_def(ally)?; + abyssal |= [ + "char_143_ghost", + "char_263_skadi", + "char_474_glady", + "char_4145_ulpia", + "char_1023_ghost2", + "char_218_cuttle", + ] + .contains(&def.char_id.as_str()); + } + let attack = if abyssal { + self.abyssal_atk + } else if !others.is_empty() { + self.nearby_atk + } else { + 0. + } + if others.len() as f64 >= self.module_count { + self.module_atk + } else { + 0. + }; + let defence = if others.is_empty() { 0. } else { self.defence }; + k.world.unit_mut(id)?.operator.tactical.skadi2_mut()?.pulses += 1; + let active = k.active()?; + let atk = k.stat(id, "atk")?; + if active { + for &ally in &allies { + if ally != id { + Self::inspire(k, ally, atk * self.inspire)?; + } + } + if k.world.unit(id)?.operator.tactical.skadi2()?.pulses % 2 == 0 { + if self.damage > 0. { + for target in k.enemies(None, true)? { + k.damage(target, atk * self.damage, DamageType::True, true, "tide")?; + } + } + let loss = k.stat(id, "maxHp")? * self.loss; + if loss > 0. { + let hp = k.world.unit(id)?.stats.hp; + if hp - loss >= 1. { + k.lose_hp(loss)?; + } else { + k.world.unit_mut(id)?.stats.hp = hp.min(1.); + } + } + } + } else { + for ally in allies { + if self.regen > 0. { + k.buff( + ally, + &format!("trait:bard:{id}"), + [("hpRegen".into(), atk * self.regen)].into(), + 0.75, + )?; + } + } + } + if attack > 0. || defence > 0. { + k.buff( + id, + "skadi2:predator", + [("atkPct".into(), attack), ("defPct".into(), defence)].into(), + 0.75, + )?; + } + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/snhunt.rs b/crates/engine/src/battle/runtime/kits/snhunt.rs new file mode 100644 index 0000000..9468c1f --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/snhunt.rs @@ -0,0 +1,278 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SNIPER", + branch: "hunter", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_snhunt_2", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_snhunt_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let mode = tactical_mode(raw)?; + + s.combat.skill_scale = n(bb, "atk_scale", 1.); + s.extra.tactics = Tactics::Snhunt(Snhunt { + mode, + capacity: n(tb, "value", 8.), + ammo_scale: n(tb, "atk_scale", 1.2), + reload: n(tb, "extra_add", 0.), + moving: n(bb, "atk_scale_1", 1.), + still: n(bb, "atk_scale_2", n(bb, "atk_scale_1", 1.)), + beast: n(t, "atk_scale", 1.), + cold: n(t, "cold", 3.), + }); + Ok(()) +} + +pub(crate) struct Snhunt { + pub mode: Mode, + pub capacity: f64, + pub ammo_scale: f64, + pub reload: f64, + pub moving: f64, + pub still: f64, + pub beast: f64, + pub cold: f64, +} + +#[derive(Default)] +pub(crate) struct State { + pub lock: Option, + pub ammo: f64, + pub reload: f64, + pub previous_ammo: f64, + pub last_attack: f64, +} + +impl Host { + pub(in crate::battle::runtime) fn snhunt_start( + &mut self, + w: &mut World, + id: Id, + p: &Snhunt, + ) -> Result<(), String> { + if p.mode == Mode::Second { + let target = self.tac_enemies(w, id, None, true)?.first().copied(); + w.unit_mut(id)?.operator.tactical.snhunt_mut()?.lock = target; + if let Some(t) = target { + self.tac_fire(w, id, t, ArrowKind::Snow, p.moving, 2)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn snhunt_attack( + &mut self, + w: &mut World, + id: Id, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.snhunt_mut()?.ammo = + (w.unit(id)?.operator.tactical.snhunt()?.ammo - 1.).max(0.); + w.unit_mut(id)?.operator.tactical.snhunt_mut()?.last_attack = w.time; + Ok(()) + } + pub(in crate::battle::runtime) fn snhunt_tick( + &mut self, + w: &mut World, + id: Id, + s: &mut skills::Runtime, + ) -> Result<(), String> { + if w.unit(id)?.operator.tactical.snhunt()?.ammo <= 0. + && s.bank.ready() + && !s.op_cooling(w.time) + && skills::can_act(w, id)? + && !Self::tac_has(w, id, "silence") + { + if !self.tac_enemies(w, id, None, true)?.is_empty() { + s.activate(w, self, "DEFAULT", false)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn snhunt_skill_start( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + p: &Snhunt, + ) -> Result<(), String> { + let target = if p.mode == Mode::Second { + w.unit(id)?.operator.tactical.snhunt()?.lock + } else { + self.tac_enemies(w, id, None, true)?.first().copied() + }; + if let Some(a) = target { + let amount = Self::tac_stat(w, id, "atk")? * p.beast; + self.tac_damage( + w, + r, + id, + a, + amount, + DamageType::Physical, + false, + "cloudbeast", + )?; + if w.unit(a)?.stats.alive { + self.advanced_status(w, r, id, a, "cold", p.cold, None)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn snhunt_reload( + &mut self, + w: &mut World, + id: Id, + p: &Snhunt, + dt: f64, + ) -> Result<(), String> { + let now = w.time; + let m = w.unit_mut(id)?.operator.tactical.snhunt_mut()?; + if now - m.last_attack >= 1. && m.ammo < p.capacity { + m.reload += dt; + if m.reload >= 1. { + m.reload -= 1.; + m.ammo += 1.; + } + } else { + m.reload = 0.; + } + if m.previous_ammo == 0. && m.ammo == 1. { + m.ammo = (m.ammo + p.reload).min(p.capacity); + } + m.previous_ammo = m.ammo; + Ok(()) + } + pub(in crate::battle::runtime) fn snhunt_arrow_scale( + &self, + w: &World, + target: Option, + scale: f64, + p: &Snhunt, + ) -> Result { + if let Some(t) = target { + let u = w.unit(t)?; + let still = u.blocked_by().is_some() + || !u.moving + || Self::tac_has(w, t, "stun") + || Self::tac_has(w, t, "bind"); + return Ok(if still { p.still } else { p.moving }); + } + + Ok(scale) + } +} + +impl State { + pub fn deployed(p: &Snhunt) -> Self { + Self { + ammo: p.capacity, + previous_ammo: p.capacity, + last_attack: f64::NEG_INFINITY, + ..Default::default() + } + } +} + +impl Behavior for Snhunt { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() + } + fn refreshes_skill(&self) -> bool { + true + } + fn profile( + &self, + world: &World, + unit: Id, + _: Option<&skills::Runtime>, + profile: &mut search::AttackProfile, + ) -> Result<(), String> { + if world.unit(unit)?.operator.tactical.snhunt()?.ammo <= 0. { + profile.no_attack = true; + } + Ok(()) + } + fn payload( + &self, + world: &World, + unit: Id, + payload: &mut attacks::Direct, + _: &mut attacks::Area, + ) -> Result<(), String> { + if world.unit(unit)?.operator.tactical.snhunt()?.ammo > 0. { + payload.atk_scale *= self.ammo_scale; + } + Ok(()) + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + (Role::Source, KitEvent::Attack { .. }) => { + k.host.snhunt_attack(k.world, id)?; + } + _ => {} + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.snhunt_start(k.world, id, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::SkillStart, + .. + } if *unit == id => { + k.host.snhunt_skill_start(k.world, k.buffs, id, self)?; + } + KitEvent::Refresh { skill, dt, .. } => { + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + host.snhunt_reload(world, id, self, *dt)?; + if self.mode == Mode::Second { + host.snhunt_tick(world, id, skill)?; + } + Ok(()) + })?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/sntlla.rs b/crates/engine/src/battle/runtime/kits/sntlla.rs new file mode 100644 index 0000000..9fcf2c9 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/sntlla.rs @@ -0,0 +1,261 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "splashcaster", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_sntlla_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skcom_quickattack[3]", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let mode = tactical_mode(raw)?; + + s.combat.area.splash = Some(Splash { + radius: 1., + scale: 1., + hits_fly: true, + fortress_melee: false, + }); + s.combat.skill_area = s.combat.area; + skill_range(raw, s)?; + if mode == Mode::First { + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("aspd".into(), n(bb, "attack_speed", 0.)), + ] + .into(); + } else { + s.modifiers = [( + "batPct".into(), + flat_bat(raw, n(bb, "base_attack_time", 0.)), + )] + .into(); + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + } + s.extra.tactics = Tactics::Sntlla(Sntlla { + mode, + scale: n(bb, "attack@atk_scale", 1.), + cold: n(bb, "attack@cold", 0.), + delay: n(t, "interval", 20.), + attack: n(t, "atk", 0.), + resist: (-n(t, "one_minus_status_resistance", 0.)).clamp(0., 1.), + }); + Ok(()) +} + +pub(crate) struct Sntlla { + pub mode: Mode, + pub scale: f64, + pub cold: f64, + pub delay: f64, + pub attack: f64, + pub resist: f64, +} + +pub(crate) struct State { + pub ready: f64, + pub row: usize, +} +impl Default for State { + fn default() -> Self { + Self { + ready: f64::NEG_INFINITY, + row: Default::default(), + } + } +} + +impl Host { + pub(in crate::battle::runtime) fn sntlla_start( + &mut self, + w: &mut World, + id: Id, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.sntlla_mut()?.ready = 0.; + w.unit_mut(id)?.operator.tactical.sntlla_mut()?.row = 0; + Ok(()) + } + pub(in crate::battle::runtime) fn sntlla_skill_tick( + &mut self, + w: &mut World, + id: Id, + dt: f64, + p: &Sntlla, + ) -> Result<(), String> { + if p.mode == Mode::Second { + let ready = w.unit(id)?.operator.tactical.sntlla()?.ready; + let next = if ready <= 0. { + ready + } else if ready <= dt + 1e-9 { + 0. + } else { + ready - dt + }; + w.unit_mut(id)?.operator.tactical.sntlla_mut()?.ready = next; + if next <= 0. + && skills::can_act(w, id)? + && !Self::tac_has(w, id, "disarm") + && !self.tac_enemies(w, id, None, true)?.is_empty() + { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let tile = w.unit(id)?.deployment.tile; + let dir = self.roster.as_ref().unwrap().entry(id)?.direction; + let row = w.unit(id)?.operator.tactical.sntlla()?.row; + let mut picked = None; + for step in 0..3 { + let index = (row + step) % 3; + let lat = [1, -1, 0][index]; + let candidates: Vec<_> = keys + .iter() + .copied() + .filter(|&k| { + dir.local([(k / COLS) as i32 - tile[0], (k % COLS) as i32 - tile[1]])[0] + == lat + }) + .collect(); + if !candidates.is_empty() { + let index_pick = + (self.rng.next_f64() * candidates.len() as f64).floor() as usize; + picked = Some(candidates[index_pick]); + w.unit_mut(id)?.operator.tactical.sntlla_mut()?.row = (index + 1) % 3; + break; + } + } + if let Some(k) = picked { + let interval = Self::tac_stat(w, id, "interval")?; + w.unit_mut(id)?.operator.tactical.sntlla_mut()?.ready = interval; + w.unit_mut(id)?.attacks += 1; + w.unit_mut(id)?.last_attack_at = w.time; + self.tac_timer( + w, + id, + w.time + 0.3, + 0., + 1, + Task::Icicle { + position: [(k / COLS) as f64, (k % COLS) as f64], + scale: p.scale, + cold: p.cold, + }, + )?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn sntlla_scheduled( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + due: [bool; 5], + p: &Sntlla, + ) -> Result<(), String> { + if due[3] + && w.time - w.unit(id)?.deployment.deployed_at >= p.delay - 1e-9 + && !Self::tac_has(w, id, "sntlla:born") + { + self.component_buff( + w, + r, + id, + "sntlla:born", + [("atkPct".into(), p.attack)].into(), + f64::INFINITY, + id, + )?; + if p.resist > 0. { + self.advanced_status(w, r, id, id, "resist", f64::INFINITY, Some(p.resist))?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn sntlla_icicle_timer( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + t: &mut Timer, + ) -> Result { + let id = t.source.ok_or("Operator timer requires a source")?; + let Task::Icicle { + position, + scale, + cold, + } = &mut t.kind + else { + return Err("Invalid icicle timer".into()); + }; + + let targets = self.tac_radius(w, *position, 1.5)?; + for a in targets { + let amount = Self::tac_stat(w, id, "atk")? * *scale; + self.tac_damage(w, r, id, a, amount, DamageType::Arts, true, "iceSpike")?; + if Self::tac_up(w, a) && *cold > 0. { + self.advanced_status(w, r, id, a, "cold", *cold, None)?; + } + } + + Ok(true) + } +} + +impl Behavior for Sntlla { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::Scheduled(_)) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Scheduled(due) => { + if k.up() { + k.host.sntlla_scheduled(k.world, id, k.buffs, *due, self)?; + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.sntlla_start(k.world, id)?; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id => { + k.host.sntlla_skill_tick(k.world, id, context.dt, self)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/svash2.rs b/crates/engine/src/battle/runtime/kits/svash2.rs new file mode 100644 index 0000000..0dde9d0 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/svash2.rs @@ -0,0 +1,289 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::deploy; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "PIONEER", + branch: "counsellor", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_svash2_2", + kind: crate::battle::sp::Kind::Charges, + sp_type: skills::SpType::Time, + rule: "SKILL_RANGE", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + if raw["skill"]["skillId"] != "skchr_svash2_2" { + return Err("Unknown selected skill".into()); + } + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + s.trigger_range = Some(tactical_grid(&raw["skill"]["rangeGrid"], false)?); + s.extra.tactics = Tactics::Svash2(Svash2 { + grid: tactical_grid(&raw["skill"]["rangeGrid"], false)?, + targets: n(bb, "max_target", 6.).max(1.) as usize, + scale: n(bb, "atk_scale", 1.), + cold: n(bb, "cold", 0.), + cut: n(bb, "cost", 0.), + stacks: n(bb, "max_stack_cnt", 2.).floor().max(1.) as u32, + sp: n(t, "sp", 0.), + respawn: n(t, "respawn_time", 1.), + defence: n(t1, "def", 0.), + regen: n(t1, "hp_recovery_per_sec_by_max_hp_ratio", 0.), + double_after: n(t1, "interval", 15.), + }); + Ok(()) +} +pub(crate) struct Svash2 { + grid: Vec<[i32; 2]>, + targets: usize, + scale: f64, + cold: f64, + cut: f64, + stacks: u32, + sp: f64, + respawn: f64, + defence: f64, + regen: f64, + double_after: f64, +} +#[derive(Default, Clone)] +pub(crate) struct State { + costs: BTreeMap, + casts: BTreeMap, +} +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + previous.cloned().unwrap_or_default() + } +} +impl Svash2 { + fn eye_cost(k: &KitContext<'_>) -> f64 { + k.host + .data + .table("tokens") + .and_then(|t| t.get("token_10057_svash2_eagle2")) + .and_then(|t| t["stats"]["cost"].as_f64()) + .unwrap_or(14.) + } + fn left(k: &KitContext<'_>, unit: Id) -> Result { + let u = k.world.unit(unit)?; + Ok(u.deployment.kind == deploy::Kind::Operator + && u.owner == k.world.unit(k.unit)?.owner + && (unit == k.unit || u.stats.base_number("cost") < Self::eye_cost(k))) + } + fn slash(&self, k: &mut KitContext<'_>) -> Result<(), String> { + let keys = k.range(&self.grid)?; + let mut targets = search::Host::enemies( + k.host, + k.unit, + &keys, + targeting::Profile { + can_hit_fly: true, + ignore_stealth: true, + ..Default::default() + }, + k.world, + k.world.unit_capacity(), + )?; + targeting::sort_enemies( + k.world, + k.host, + k.unit, + &mut targets, + targeting::Priority::None, + )?; + let amount = k.stat(k.unit, "atk")? * self.scale; + for target in targets.into_iter().take(self.targets) { + k.damage(target, amount, DamageType::Physical, true, "svash2")?; + if Host::tac_up(k.world, target) { + k.status(target, "cold", self.cold, None)?; + k.status(target, "reveal", self.cold, None)?; + } + } + Ok(()) + } +} +impl Behavior for Svash2 { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + self.slash(k)?; + let eye = Self::eye_cost(k); + let mut right = Vec::new(); + let mut left = Vec::new(); + for unit in k.host.roster.as_ref().unwrap().ids().to_vec() { + let u = k.world.unit(unit)?; + if unit == id + || u.stats.alive + || u.removed + || u.deployment.kind != deploy::Kind::Operator + { + continue; + } + let cost = u.stats.base_number("cost"); + if cost >= eye { + right.push((unit, cost)); + } else { + left.push((unit, cost)); + } + } + right.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0))); + left.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0))); + let preferred = right.iter().find(|(unit, _)| { + k.host + .tac_def(*unit) + .is_ok_and(|d| ["WARRIOR", "CASTER", "SNIPER"].contains(&d.profession)) + }); + if let Some(&(target, cost)) = preferred.or(right.first()).or(left.first()) { + if self.cut > 0. { + k.world + .unit_mut(id)? + .operator + .tactical + .svash2_mut()? + .costs + .entry(target) + .or_insert(cost); + k.world.unit_mut(target)?.stats.edit_base(|b| { + b.0.insert("cost".into(), (cost - self.cut).max(0.)); + }); + } + } + for (target, _) in left { + let stacks = k + .world + .unit_mut(id)? + .operator + .tactical + .svash2_mut()? + .casts + .entry(target) + .or_default(); + *stacks = (*stacks + 1).min(self.stacks); + } + } + KitEvent::BattleStart if k.up() && self.sp > 0. => { + for unit in k.host.roster.as_ref().unwrap().ids().to_vec() { + if Host::tac_up(k.world, unit) && Self::left(k, unit)? { + let owner = k.unit; + k.unit = unit; + let amount = self.sp; + let result = k.skill(|skill, host, w| { + skill.gain(w, host, amount, "talent", false, false) + }); + k.unit = owner; + result?; + } + } + } + KitEvent::SkillObserved { + unit, + event: skills::Event::Deploy, + skill, + } => { + if k.world.time > 0. + && Self::left(k, *unit)? + && (*unit == id || k.up()) + && self.sp > 0. + { + let amount = self.sp; + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + skill.gain(world, host, amount, "talent", false, false) + })?; + } + if let Some(cost) = k + .world + .unit_mut(id)? + .operator + .tactical + .svash2_mut()? + .costs + .remove(unit) + { + k.world.unit_mut(*unit)?.stats.edit_base(|b| { + b.0.insert("cost".into(), cost); + }); + } + let casts = k + .world + .unit_mut(id)? + .operator + .tactical + .svash2_mut()? + .casts + .remove(unit) + .unwrap_or(0); + let owner = k.unit; + k.unit = *unit; + let result: Result<(), String> = (|| { + for _ in 0..casts { + self.slash(k)?; + } + Ok(()) + })(); + k.unit = owner; + result?; + } + KitEvent::Death { unit, .. } + if Self::left(k, *unit)? + && (*unit == id || k.up()) + && self.respawn > 0. + && self.respawn < 1. => + { + let u = k.world.unit_mut(*unit)?; + if !u.removed && u.deployment.respawn_at.is_finite() { + u.deployment.respawn_at = u.deployment.death_at + + (u.deployment.respawn_at - u.deployment.death_at) * self.respawn; + } + } + KitEvent::Scheduled(due) if due[2] && k.up() => { + let factor = if k.world.time - k.world.unit(id)?.deployment.deployed_at + >= self.double_after - 1e-9 + { + 2. + } else { + 1. + }; + for unit in k.host.roster.as_ref().unwrap().ids().to_vec() { + if Host::tac_up(k.world, unit) && k.faction(unit, "kjeragShip", &["kjerag"])? { + k.buff( + unit, + "svash2:snow", + [ + ("defFlat".into(), self.defence * factor), + ("hpRegenRatio".into(), self.regen * factor), + ] + .into(), + 0.5, + )?; + } + } + } + KitEvent::BeforeStatus(context) + if context.key == "freeze" + && k.world.unit(context.target)?.side == health::Side::Ally + && k.has(context.target, "svash2:snow") => + { + context.cancelled = true; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/swire2.rs b/crates/engine/src/battle/runtime/kits/swire2.rs new file mode 100644 index 0000000..e15c31e --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/swire2.rs @@ -0,0 +1,361 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +const GRID: [[i32; 2]; 9] = [ + [2, 0], + [1, 0], + [0, -2], + [0, -1], + [0, 0], + [0, 1], + [0, 2], + [-1, 0], + [-2, 0], +]; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "SPECIAL", + branch: "merchant", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_swire2_2", + kind: crate::battle::sp::Kind::Passive, + sp_type: skills::SpType::None, + rule: "DEFAULT", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let module = talent_at(raw, -1); + s.extra.tactics = Tactics::Swire2(Swire2 { + cap: n(bb, "sp", 3.), + coin_cost: n(bb, "attack@sp", -1.).abs().max(1.), + scale: n(bb, "atk_scale", 1.), + sluggish: n(bb, "sluggish", 2.), + interval: n(&raw["trait"]["bb"], "interval", 3.).max(0.1), + cost: n(&raw["trait"]["bb"], "cost", -3.).abs(), + initial: n(t, "sp", 1.), + coins: n(t, "trait_sp", 1.), + attack: n(t, "atk", 0.), + stacks: n(t, "max_stack_cnt", 8.).max(1.) as u32, + module: n(module, "atk", 0.), + module_cap: n(module, "max_stack_cnt", 5.).max(1.) as u32, + revive: n(t1, "cost", -5.).abs(), + revive_mul: n(t1, "cost_multi", 2.), + revive_hp: n(t1, "hp_ratio", 0.7), + }); + Ok(()) +} +pub(crate) struct Swire2 { + cap: f64, + coin_cost: f64, + scale: f64, + sluggish: f64, + interval: f64, + cost: f64, + initial: f64, + coins: f64, + attack: f64, + stacks: u32, + module: f64, + module_cap: u32, + revive: f64, + revive_mul: f64, + revive_hp: f64, +} +#[derive(Default)] +pub(crate) struct State { + coins: f64, + saves: u32, + bombs: Vec, + hold: f64, + next_pay: f64, +} +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + Self { + bombs: previous.map(|s| s.bombs.clone()).unwrap_or_default(), + next_pay: previous.map_or(0., |s| s.next_pay), + ..Default::default() + } + } +} +impl Swire2 { + fn throw(&self, k: &mut KitContext<'_>) -> Result<(), String> { + let id = k.unit; + if k.up() + && skills::can_act(k.world, id)? + && k.world.unit(id)?.cadence.cooldown <= 1e-9 + && !k.flag(id, "disarm")? + { + let state = k.world.unit(id)?.operator.tactical.swire2()?; + if state.coins >= self.coin_cost && k.world.time >= state.hold { + let tiles = Self::tiles(k.host, k.world, id)?; + if !tiles.is_empty() { + let mut key = None; + for enemy in k.enemies(Some(&tiles), false)? { + let pos = k.world.unit(enemy)?.position; + let candidate = (pos[0] + 0.5).floor() as usize * COLS + + (pos[1] + 0.5).floor() as usize; + if tiles.contains(&candidate) { + key = Some(candidate); + break; + } + } + let key = key.unwrap_or_else(|| *k.host.rng.pick(&tiles).unwrap()); + let tile = [(key / COLS) as i32, (key % COLS) as i32]; + if let Some(bomb) = k.summon("token_10031_swire2_gdtrap", tile, 0.)? { + let state = k.world.unit_mut(id)?.operator.tactical.swire2_mut()?; + state.coins -= self.coin_cost; + state.bombs.push(bomb); + } else { + let interval = k.stat(id, "interval")?; + k.world.unit_mut(id)?.operator.tactical.swire2_mut()?.hold = + k.world.time + interval; + } + } + } + } + Ok(()) + } + fn tiles(host: &Host, w: &World, id: Id) -> Result, String> { + let grid = host.grid.as_ref().ok_or("Missing Swire grid")?; + let roster = host.roster.as_ref().ok_or("Missing Swire roster")?; + let range = targeting::absolute_range( + &GRID, + w.unit(id)?.deployment.tile, + roster.entry(id)?.direction, + 0, + ); + let mut out = Vec::new(); + for key in range { + let tile = [(key / COLS) as i32, (key % COLS) as i32]; + if grid.in_rect(tile) + && grid.can_stand(tile, false) + && grid.ground_passable(tile, true) + && grid.tiles()[key].height == "LOW" + && !roster.deployment().reserved(w, tile)? + { + out.push(key); + } + } + Ok(out) + } + fn stack(k: &mut KitContext<'_>, key: &str, attack: f64, cap: u32) -> Result<(), String> { + let mut b = Buff { + key: Some(key.into()), + mods: [("atkPct".into(), attack)].into(), + ..Default::default() + }; + b.runtime.refresh = buffs::Refresh::Stack; + b.runtime.max_stacks = cap; + k.add(k.unit, b)?; + Ok(()) + } +} +impl Behavior for Swire2 { + fn can_attack(&self, host: &Host, w: &World, id: Id) -> Result { + let state = w.unit(id)?.operator.tactical.swire2()?; + Ok(state.coins < self.coin_cost + || w.time < state.hold + || Self::tiles(host, w, id)?.is_empty()) + } + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Hit { .. } | KitEvent::Element { .. }) { + 1000 + } else { + 0 + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == id => { + let state = k.world.unit_mut(id)?.operator.tactical.swire2_mut()?; + state.coins = self.initial.min(self.cap); + state.saves = 0; + } + KitEvent::Scheduled(_) + if k.world.time + 1e-9 + >= k.world + .unit(id)? + .operator + .tactical + .swire2()? + .next_pay + .max(self.interval) => + { + let next = k + .world + .unit(id)? + .operator + .tactical + .swire2()? + .next_pay + .max(self.interval) + + self.interval; + k.world + .unit_mut(id)? + .operator + .tactical + .swire2_mut()? + .next_pay = next; + if k.up() { + let dp = k + .host + .roster + .as_ref() + .unwrap() + .dp(k.world.unit(id)?.owner.unwrap()) + .ok_or("Missing merchant DP")?; + if dp >= self.cost { + k.dp(-self.cost)?; + if self.module > 0. { + Self::stack(k, "trait:swire2_module", self.module, self.module_cap)?; + } + if k.active()? { + let coins = k.world.unit(id)?.operator.tactical.swire2()?.coins; + k.world.unit_mut(id)?.operator.tactical.swire2_mut()?.coins = + (coins + self.coins).min(self.cap); + Self::stack(k, "talent:swire2_buyer", self.attack, self.stacks)?; + } + } else { + k.retreat_with_reason("merchant")?; + } + } + } + KitEvent::Fatal(context) if context.target == id && !context.prevented => { + let count = k.world.unit(id)?.operator.tactical.swire2()?.saves; + let cost = + self.revive * powi(self.revive_mul, count as i32).map_err(str::to_string)?; + if k.host + .roster + .as_ref() + .unwrap() + .dp(k.world.unit(id)?.owner.unwrap()) + .is_some_and(|dp| dp + 1e-9 >= cost) + { + k.dp(-cost)?; + k.world.unit_mut(id)?.operator.tactical.swire2_mut()?.saves = count + .checked_add(1) + .ok_or("Swire revive counter exhausted")?; + context.prevented = true; + let hp = k.stat(id, "maxHp")? * self.revive_hp; + k.world.unit_mut(id)?.stats.hp = hp.max(1.); + } + } + KitEvent::Hit { request, .. } + if k.world.unit(request.hit.target)?.summoner == Some(id) + && k.host.tac_def(request.hit.target)?.key == "token_10031_swire2_gdtrap" => + { + request.cancelled = true + } + KitEvent::Element { request, .. } + if k.world.unit(request.damage.hit.target)?.summoner == Some(id) + && k.host.tac_def(request.damage.hit.target)?.key + == "token_10031_swire2_gdtrap" => + { + request.damage.cancelled = true + } + KitEvent::DamageApplied { event, .. } + if k.world.unit(event.target)?.summoner == Some(id) + && k.host.tac_def(event.target)?.key == "token_10031_swire2_gdtrap" => + { + let hp = k.stat(event.target, "maxHp")?; + k.world.unit_mut(event.target)?.stats.hp = hp; + } + KitEvent::Tick => { + let bombs = std::mem::take( + &mut k.world.unit_mut(id)?.operator.tactical.swire2_mut()?.bombs, + ); + // The owner's throw listener precedes the existing bombs' listeners. + // Newly spawned bombs first check contact on the following tick. + self.throw(k)?; + let mut kept = Vec::new(); + for bomb in bombs { + if !Host::tac_up(k.world, bomb) { + continue; + } + let tile = k.world.unit(bomb)?.deployment.tile; + let mut target = None; + for enemy in k.world.unit_ids().collect::>() { + let unit = k.world.unit(enemy)?; + let on_tile = if unit.hit_area.is_some() { + body::on_tile(unit, tile[0], tile[1]) + } else { + (unit.position[0] - f64::from(tile[0])).abs() <= 0.5 + && (unit.position[1] - f64::from(tile[1])).abs() <= 0.5 + }; + if unit.side != health::Side::Enemy || !on_tile { + continue; + } + if targeting::can_target_enemy( + k.world, + k.host, + Some(bomb), + enemy, + targeting::Profile { + ground_only: true, + can_hit_fly: false, + ..Default::default() + }, + )? { + target = Some(enemy); + break; + } + } + if let Some(target) = target { + let raw = + &k.host.data.table("tokens").unwrap()["token_10031_swire2_gdtrap"]; + let owner = k.host.tac_def(id)?; + let switch = n( + &raw["variants"][&owner.key]["skill"]["bb"], + "duration_switch", + 3., + ); + let times = if k.world.time - k.world.unit(bomb)?.deployment.deployed_at + >= switch - 1e-9 + { + 2 + } else { + 1 + }; + let amount = k.stat(id, "atk")? * self.scale; + for _ in 0..times { + if Host::tac_up(k.world, target) { + k.damage(target, amount, DamageType::Physical, true, "trap")?; + } + } + if Host::tac_up(k.world, target) { + k.status(target, "sluggish", self.sluggish, None)?; + } + k.unit = bomb; + let result = k.retreat(); + k.unit = id; + result?; + } else { + kept.push(bomb); + } + } + let state = k.world.unit_mut(id)?.operator.tactical.swire2_mut()?; + kept.append(&mut state.bombs); + state.bombs = kept; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/texas2.rs b/crates/engine/src/battle/runtime/kits/texas2.rs new file mode 100644 index 0000000..e61374d --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/texas2.rs @@ -0,0 +1,451 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent, Role}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "SPECIAL", + branch: "executor", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_texas2_3", + kind: Kind::Duration, + sp_type: SpType::None, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_texas2_1", + kind: Kind::Duration, + sp_type: SpType::None, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_texas2_2", + kind: Kind::Duration, + sp_type: SpType::None, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = tactical_mode(raw)?; + + s.extra.deploy = true; + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.) + n(t, "atk", 0.))].into(); + if mode == Mode::Second { + s.combat.skill_hits = 2; + s.extra.skill_arts = true; + } + s.extra.tactics = Tactics::Texas2(Texas2 { + mode, + swordplay: [ + ("aspd".into(), n(t1, "attack_speed", 8.)), + ("dmgTakenMul".into(), 1. - n(t1, "damage_resistance", 0.25)), + ] + .into(), + grid: tactical_grid(&raw["skill"]["rangeGrid"], true)?, + burst: n(bb, "appear.atk_scale", n(bb, "atk_scale", 1.15)), + burst_stun: n(bb, "appear.stun", 1.5), + scale: n(bb, "atk_scale", 0.85), + interval: n(bb, "texas2_s_3[sword].interval", 1.), + stun: n(bb, "stun", 0.2), + targets: n(bb, "max_target", 2.).max(1.) as usize, + res: n(bb, "magic_resistance", 0.), + res_duration: n(bb, "debuff_duration", 8.), + silence: n(bb, "attack@silence", 5.), + dot: n(bb, "attack@texas2_s_1[dot].dot_damage", 260.), + dot_duration: n(bb, "attack@texas2_s_1[dot].duration", 5.), + dot_interval: n(bb, "attack@texas2_s_1[dot].interval", 1.), + heal: n(t, "hp_ratio", 1.), + lonely: n(tb, "atk", 0.), + }); + Ok(()) +} + +pub(crate) struct Texas2 { + pub mode: Mode, + pub swordplay: Numbers, + pub grid: Vec<[i32; 2]>, + pub burst: f64, + pub burst_stun: f64, + pub scale: f64, + pub interval: f64, + pub stun: f64, + pub targets: usize, + pub res: f64, + pub res_duration: f64, + pub silence: f64, + pub dot: f64, + pub dot_duration: f64, + pub dot_interval: f64, + pub heal: f64, + pub lonely: f64, +} + +pub(crate) struct State { + pub ready: f64, + pub first_kill: bool, + pub recast: bool, + pub starting: bool, +} +impl Default for State { + fn default() -> Self { + Self { + ready: f64::NEG_INFINITY, + first_kill: Default::default(), + recast: Default::default(), + starting: Default::default(), + } + } +} + +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + Self { + first_kill: previous.is_some_and(|s| s.first_kill), + recast: previous.is_some_and(|s| s.recast), + starting: previous.is_some_and(|s| s.starting), + ..Default::default() + } + } +} +impl Host { + pub(in crate::battle::runtime) fn tac_texas_cast( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + p: &Texas2, + ) -> Result<(), String> { + w.unit_mut(id)?.operator.tactical.texas2_mut()?.starting = true; + if p.mode != Mode::First { + let keys = self.tac_keys(w, id, &p.grid)?; + for a in self.tac_enemies(w, id, Some(&keys), true)? { + for _ in 0..if p.mode == Mode::Third { 2 } else { 1 } { + if !w.unit(a)?.stats.alive { + break; + } + let amount = Self::tac_stat(w, id, "atk")? * p.burst; + self.tac_damage(w, r, id, a, amount, DamageType::Arts, false, "burst")?; + } + if w.unit(a)?.stats.alive { + if p.mode == Mode::Third { + self.advanced_status(w, r, id, a, "stun", p.burst_stun, None)?; + } else if p.res != 0. { + self.component_debuff( + w, + r, + id, + a, + Debuff { + key: "texas2:resDown", + stat: "resMul", + value: p.res, + duration: p.res_duration, + strongest: true, + }, + )?; + } + } + } + } + w.unit_mut(id)?.operator.tactical.texas2_mut()?.starting = false; + // The rain's first deadline is one tick early to match the skill countdown. + w.unit_mut(id)?.operator.tactical.texas2_mut()?.ready = w.time + p.interval - DT; + Ok(()) + } + pub(in crate::battle::runtime) fn texas2_finish( + &mut self, + w: &mut World, + s: &mut skills::Runtime, + ) -> Result<(), String> { + let id = s.unit(); + if w.unit(id)?.operator.tactical.texas2()?.recast { + w.unit_mut(id)?.operator.tactical.texas2_mut()?.recast = false; + s.end(w, self, "recast")?; + s.activate(w, self, "kill", true)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn texas2_start( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Texas2, + ) -> Result<(), String> { + self.tac_texas_cast(w, r, id, p)?; + Ok(()) + } + pub(in crate::battle::runtime) fn texas2_scheduled( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + active: bool, + due: [bool; 5], + p: &Texas2, + ) -> Result<(), String> { + if due[1] && p.lonely != 0. { + let tile = w.unit(id)?.deployment.tile; + let lonely = self.roster.as_ref().unwrap().ids().iter().all(|&a| { + a == id + || !Self::tac_up(w, a) + || (w.unit(a).unwrap().deployment.tile[0] - tile[0]).abs() + + (w.unit(a).unwrap().deployment.tile[1] - tile[1]).abs() + != 1 + }); + self.advanced_toggle( + w, + r, + id, + "texas2:module", + lonely, + [("atkPct".into(), p.lonely)].into(), + )?; + } + if p.mode == Mode::Third + && active + && w.time + 1e-9 >= w.unit(id)?.operator.tactical.texas2()?.ready + { + w.unit_mut(id)?.operator.tactical.texas2_mut()?.ready += p.interval; + let keys = self.tac_keys(w, id, &p.grid)?; + for a in self + .tac_enemies(w, id, Some(&keys), true)? + .into_iter() + .take(p.targets) + { + let amount = Self::tac_stat(w, id, "atk")? * p.scale; + self.tac_damage(w, r, id, a, amount, DamageType::Arts, false, "swordRain")?; + if Self::tac_up(w, a) { + self.advanced_status(w, r, id, a, "stun", p.stun, None)?; + } + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn texas2_landed( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + q: &hit::Request, + e: &health::Event, + p: &Texas2, + ) -> Result<(), String> { + if p.mode == Mode::First + && q.is_attack + && Self::tac_up(w, e.target) + && w.unit(id)?.operator.active_skill + { + self.advanced_status(w, r, id, e.target, "silence", p.silence, None)?; + let mut b = Buff { + key: Some(format!("texas2:drizzleDot:{id}")), + ..Default::default() + }; + b.runtime.source = Some(id); + b.runtime.duration = p.dot_duration + 1e-6; + b.runtime.interval = p.dot_interval.max(0.1); + b.runtime.tick_payload = p.dot; + b.runtime.refresh = buffs::Refresh::Extend; + b.runtime.on_tick = Some(DRIZZLE); + r.add( + w, + self, + e.target, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn texas2_kill( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + p: &Texas2, + ) -> Result<(), String> { + if Self::tac_up(w, source) && !w.unit(source)?.operator.tactical.texas2()?.first_kill { + w.unit_mut(source)? + .operator + .tactical + .texas2_mut()? + .first_kill = true; + w.unit_mut(source)?.operator.tactical.texas2_mut()?.recast = true; + r.remove(w, self, source, "texas2:swordplay")?; + let amount = Self::tac_stat(w, source, "maxHp")? * p.heal; + self.tac_heal(w, r, source, source, amount)?; + if w.unit(source)?.operator.tactical.texas2()?.starting { + self.tac_texas_cast(w, r, source, p)?; + } else { + self.texas2_flush_recast(w, r, source)?; + } + } + Ok(()) + } + pub(in crate::battle::runtime) fn texas2_deployed( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + p: &Texas2, + ) -> Result<(), String> { + if Self::tac_up(w, id) && !w.unit(id)?.operator.tactical.texas2()?.first_kill { + r.add( + w, + self, + id, + buffs::Spec { + buff: Buff { + key: Some("texas2:swordplay".into()), + mods: p.swordplay.clone(), + ..Default::default() + }, + ..Default::default() + }, + )?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn texas2_flush_recast( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + if !w.unit(id)?.operator.tactical.texas2()?.recast { + return Ok(()); + } + if let Ok(mut skill) = self.roster.as_mut().unwrap().take_skill(id) { + w.unit_mut(id)?.operator.tactical.texas2_mut()?.recast = false; + let result = self.with_kit_buffs(w, r, |host, world| { + skill.end(world, host, "recast")?; + skill.activate(world, host, "kill", true)?; + Ok(()) + }); + let restore = self.roster.as_mut().unwrap().restore_skill(id, skill); + result.and(restore)?; + } + Ok(()) + } + pub(in crate::battle::runtime) fn texas2_dot_tick( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + ) -> Result<(), String> { + let b = r.get(w, c.unit, c.buff)?.clone(); + let id = b.runtime.source.ok_or("Missing texas2 buff source")?; + + self.tac_damage( + w, + r, + id, + c.unit, + b.runtime.tick_payload, + DamageType::Arts, + false, + "dot", + )?; + Ok(()) + } +} + +impl Behavior for Texas2 { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() || matches!(event, KitEvent::Scheduled(_) | KitEvent::Death { .. }) + } + fn handle_unit( + &self, + k: &mut KitContext<'_>, + role: Role, + event: &mut KitEvent<'_>, + ) -> Result<(), String> { + let id = k.unit; + match (role, event) { + ( + Role::Source, + KitEvent::Buff { + context, + event: buffs::Event::Tick, + token: DRIZZLE, + }, + ) => { + k.host.texas2_dot_tick(k.world, k.buffs, *context)?; + } + + (Role::Source, KitEvent::Landed { event, request }) => { + k.host + .texas2_landed(k.world, id, k.buffs, request, event, self)?; + } + (Role::Source, KitEvent::Kill { .. }) => { + k.host.texas2_kill(k.world, k.buffs, id, self)?; + } + _ => {} + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Death { unit, .. } if *unit == id => { + let state = k.world.unit_mut(id)?.operator.tactical.texas2_mut()?; + state.first_kill = false; + state.recast = false; + state.starting = false; + } + KitEvent::Scheduled(due) => { + if k.up() { + let active = k.active()?; + k.host + .texas2_scheduled(k.world, id, k.buffs, active, *due, self)?; + } + } + + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.texas2_start(k.world, id, k.buffs, self)?; + } + KitEvent::Skill { + unit, + event: skills::Event::SkillStart, + context, + .. + } if *unit == id => { + if context.reason == "deploy" { + k.host.texas2_deployed(k.world, k.buffs, id, self)?; + } + } + KitEvent::Resume { unit, skill } if *unit == id => { + k.host.with_kit_buffs(k.world, k.buffs, |host, world| { + host.texas2_finish(world, skill) + })?; + } + KitEvent::Restored(skills::Event::SkillStart) | KitEvent::Flush => { + k.host.texas2_flush_recast(k.world, k.buffs, id)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/thorn2.rs b/crates/engine/src/battle/runtime/kits/thorn2.rs new file mode 100644 index 0000000..d517c3b --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/thorn2.rs @@ -0,0 +1,353 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{deploy, spatial}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SPECIAL", + branch: "alchemist", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[Skill { + id: "skchr_thorn2_2", + kind: crate::battle::sp::Kind::Charges, + sp_type: skills::SpType::Time, + rule: "DEFAULT", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + if raw["skill"]["skillId"] != "skchr_thorn2_2" { + return Err("Unknown selected skill".into()); + } + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + s.extra.effects.permanent.push(persistent( + "thorn2:mind", + [("atkPct".into(), n(t, "atk", 0.))].into(), + )); + s.extra.tactics = Tactics::Thorn2(Thorn2 { + duration: n(bb, "projectile_delay_time", n(bb, "remaining_time", 12.)), + extend: n(t, "projectile_extend", 0.).min(n(t, "projectile_extend_max", f64::INFINITY)), + radius: n(bb, "projectile_range", 1.1), + grow: n(bb, "value", 0.), + speed: n(bb, "projectile_move_speed", 0.), + healing: n(bb, "heal_scale", 1.).max(0.), + scale: n(bb, "atk_scale", 0.), + regen: n(bb, "hp_recovery_per_sec_ratio_chr", 0.), + road: n(t1, "cnt", 6.), + ally: n(t1, "attack_speed_ally", 0.), + ally_extra: n(t1, "attack_speed_ally_extra", 0.), + enemy: n(t1, "attack_speed_enemy", 0.), + enemy_extra: n(t1, "attack_speed_enemy_extra", 0.), + sp: if raw["isGolden"] == true { + n(tm, "sp_recovery_per_sec", 0.) + } else { + 0. + }, + }); + Ok(()) +} +pub(crate) struct Thorn2 { + duration: f64, + extend: f64, + radius: f64, + grow: f64, + speed: f64, + healing: f64, + scale: f64, + regen: f64, + road: f64, + ally: f64, + ally_extra: f64, + enemy: f64, + enemy_extra: f64, + sp: f64, +} +#[derive(Clone)] +struct Zone { + position: [f64; 2], + velocity: [f64; 2], + age: f64, + accumulator: f64, + duration: f64, + key: String, +} +#[derive(Default, Clone)] +pub(crate) struct State { + zones: Vec, + sequence: u64, + roads: BTreeMap, +} +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + previous.cloned().unwrap_or_default() + } +} +impl Thorn2 { + fn road(k: &mut KitContext<'_>, tile: [i32; 2]) -> Result { + if !Grid::in_bounds(tile) { + return Ok(0); + } + let key = tile[0] as usize * COLS + tile[1] as usize; + if let Some(&length) = k + .world + .unit(k.unit)? + .operator + .tactical + .thorn2()? + .roads + .get(&key) + { + return Ok(length); + } + let grid = k.host.grid.as_ref().unwrap(); + let rect = grid.rect(); + let length = if !grid.ground_passable(tile, true) { + 0 + } else { + let mut horizontal = 1; + let mut vertical = 1; + for sign in [-1, 1] { + for distance in 1..COLS as i32 { + let p = [tile[0], tile[1] + sign * distance]; + if p[1] < rect.c0 || p[1] > rect.c1 || !grid.ground_passable(p, true) { + break; + } + horizontal += 1; + } + for distance in 1..crate::battle::grid::ROWS as i32 { + let p = [tile[0] + sign * distance, tile[1]]; + if p[0] < rect.r0 || p[0] > rect.r1 || !grid.ground_passable(p, true) { + break; + } + vertical += 1; + } + } + horizontal.max(vertical) + }; + k.world + .unit_mut(k.unit)? + .operator + .tactical + .thorn2_mut()? + .roads + .insert(key, length); + Ok(length) + } +} +impl Behavior for Thorn2 { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + let targets = k.enemies(None, true)?; + let mut chosen = None; + for &target in &targets { + if !targeting::flying(k.world, target)? { + chosen = Some(target); + break; + } + } + let position = if let Some(target) = chosen.or_else(|| targets.first().copied()) { + k.world.unit(target)?.position + } else { + let home = k.world.unit(id)?.deployment.tile; + let direction = k.host.roster.as_ref().unwrap().entry(id)?.direction; + let mut best = None; + for key in k.keys()? { + let tile = [(key / COLS) as i32, (key % COLS) as i32]; + let [lateral, forward] = + direction.local([tile[0] - home[0], tile[1] - home[1]]); + if lateral == 0 + && forward > 0 + && best.is_none_or(|(distance, _)| forward > distance) + { + best = Some((forward, tile)); + } + } + let Some((_, tile)) = best else { + return Ok(()); + }; + tile.map(|v| v as f64) + }; + let keys = k.keys()?; + let extended = k.allies(&keys)?.into_iter().any(|a| { + a != id + && k.world + .unit(a) + .is_ok_and(|u| u.deployment.kind == deploy::Kind::Operator) + }); + let source = k.world.unit(id)?.position; + let delta = [position[0] - source[0], position[1] - source[1]]; + let length = crate::deterministic::math::hypot(delta[0], delta[1]); + let length = if length == 0. { 1. } else { length }; + let velocity = delta.map(|d| d / length * self.speed); + let limit = k.host.tactical_limit; + let state = k.world.unit_mut(id)?.operator.tactical.thorn2_mut()?; + if state.zones.len() >= limit { + return Err("Thorn2 zone capacity exceeded".into()); + } + state.sequence = state + .sequence + .checked_add(1) + .ok_or("Thorn2 zone identity overflow")?; + state.zones.push(Zone { + position, + velocity, + age: 0., + accumulator: 0., + duration: self.duration + if extended { self.extend } else { 0. }, + key: format!("thorn2:{id}:{}", state.sequence), + }); + } + KitEvent::Scheduled(due) if due[2] => { + if k.up() { + for target in k.host.roster.as_ref().unwrap().ids().to_vec() { + if !Host::tac_up(k.world, target) { + continue; + } + let value = self.ally + + if Self::road(k, k.world.unit(target)?.deployment.tile)? as f64 + >= self.road + { + self.ally_extra + } else { + 0. + }; + if value != 0. { + k.buff( + target, + "thorn2:vision", + [("aspd".into(), value)].into(), + 0.5, + )?; + } + } + for target in k.host.spawns.as_ref().unwrap().live().to_vec() { + if !Host::tac_up(k.world, target) || k.world.unit(target)?.hidden { + continue; + } + let tile = k + .world + .unit(target)? + .position + .map(|v| (v + 0.5).floor() as i32); + let value = self.enemy + + if Self::road(k, tile)? as f64 >= self.road { + self.enemy_extra + } else { + 0. + }; + if value != 0. { + k.buff( + target, + "thorn2:vision", + [("aspd".into(), value)].into(), + 0.5, + )?; + } + } + } + let mut zones = std::mem::take( + &mut k.world.unit_mut(id)?.operator.tactical.thorn2_mut()?.zones, + ); + let result: Result<(), String> = (|| { + for zone in &mut zones { + zone.age += 0.25; + zone.accumulator += 0.25; + let rect = k.host.grid.as_ref().unwrap().rect(); + zone.position[0] = (zone.position[0] + zone.velocity[0] * 0.25) + .clamp(rect.r0 as f64, rect.r1 as f64); + zone.position[1] = (zone.position[1] + zone.velocity[1] * 0.25) + .clamp(rect.c0 as f64, rect.c1 as f64); + let radius = self.radius + self.grow * zone.age; + let mut foes = Vec::new(); + for target in k.radius(zone.position, radius)? { + if !targeting::flying(k.world, target)? { + foes.push(target); + } + } + for &target in &foes { + k.buff( + target, + "thorn2:rot", + [("healingTakenMul".into(), self.healing)].into(), + 0.5, + )?; + } + if zone.accumulator + 1e-9 >= 1. { + zone.accumulator -= 1.; + let attack = k.stat(id, "atk")?; + for target in foes { + k.damage( + target, + attack * self.scale, + DamageType::Arts, + true, + "alchemy", + )?; + } + if self.regen > 0. { + let allies = k.host.roster.as_ref().unwrap().ids().to_vec(); + for target in spatial::allies_in_radius( + k.world, + &allies, + zone.position, + radius, + None, + false, + k.world.unit_capacity(), + )? { + if !k.flag(target, "isolated")? || target == id { + k.buff( + target, + &format!("{}:regen", zone.key), + [("hpRegen".into(), attack * self.regen)].into(), + 1. + 2. * DT, + )?; + } + } + } + } + } + Ok(()) + })(); + zones.retain(|zone| zone.age < zone.duration - 1e-9); + k.world.unit_mut(id)?.operator.tactical.thorn2_mut()?.zones = zones; + result?; + if self.sp > 0. + && k.up() + && !k + .world + .unit(id)? + .operator + .tactical + .thorn2()? + .zones + .is_empty() + { + k.buff( + id, + "thorn2:module", + [("spRecoveryFlat".into(), self.sp)].into(), + 0.5, + )?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/tinman.rs b/crates/engine/src/battle/runtime/kits/tinman.rs new file mode 100644 index 0000000..06c8d17 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/tinman.rs @@ -0,0 +1,353 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "SPECIAL", + branch: "alchemist", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_tinman_2", + kind: Kind::Instant, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: false, + }, + Skill { + id: "skchr_tinman_1", + kind: Kind::Instant, + sp_type: SpType::Attack, + rule: "DEFAULT", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + let mode = tactical_mode(raw)?; + + s.extra.tactics = Tactics::Tinman(Tinman { + mode, + duration: n(bb, "projectile_delay_time", 10.), + radius: n(bb, "projectile_range", 1.5), + scale: n(bb, "atk_scale", 0.), + regen: n(bb, "hp_recovery_per_sec_ratio", 0.), + weaken: (-n(bb, "atk", 0.)).clamp(0., 1.), + wither: n(t1, "skill@damage_scale", 1.), + sp: n(tm, "sp_recovery_per_sec", 0.), + }); + Ok(()) +} + +pub(crate) struct Tinman { + pub mode: Mode, + pub duration: f64, + pub radius: f64, + pub scale: f64, + pub regen: f64, + pub weaken: f64, + pub wither: f64, + pub sp: f64, +} + +#[derive(Default)] +pub(crate) struct State { + pub sequence: u64, +} + +impl Host { + pub(in crate::battle::runtime) fn tactical_sync_zones( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + let mut timers = std::mem::take(&mut self.tactical_timers); + let result: Result<(), String> = (|| { + for t in &mut timers { + let Task::Zone { + position, + end, + radius, + regen, + wither, + key, + held, + .. + } = &mut t.kind + else { + continue; + }; + let mut covered = std::collections::BTreeSet::new(); + if w.time + 1e-9 < *end { + if *wither > 1. { + for a in self.tac_radius(w, *position, *radius)? { + if targeting::flying(w, a)? { + continue; + } + covered.insert(a); + if !held.get(&a).is_some_and(|b| r.get(w, a, *b).is_ok()) { + let mut b = Buff { + key: Some("tinman:wither".into()), + ..Default::default() + }; + b.runtime.source = t.source; + b.runtime.tick_payload = *wither; + b.runtime.refresh = buffs::Refresh::Independent; + b.runtime.max_stacks = i32::MAX as u32; + b.runtime.injury.on_injury = Some(WITHER); + let bid = r.add( + w, + self, + a, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + if let Some(bid) = bid { + held.insert(a, bid); + } + } + } + } + if *regen > 0. { + for a in self.roster.as_ref().unwrap().ids().to_vec() { + if Self::tac_up(w, a) + && body::in_radius(w.unit(a)?, *position, *radius) + && targeting::aura_selectable(w, a)? + { + covered.insert(a); + if !held.get(&a).is_some_and(|b| r.get(w, a, *b).is_ok()) { + let mut b = Buff { + key: Some(key.clone()), + mods: [("hpRegen".into(), *regen)].into(), + ..Default::default() + }; + b.runtime.source = t.source; + let bid = r.add( + w, + self, + a, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + if let Some(bid) = bid { + held.insert(a, bid); + } + } + } + } + } + } + let departed: Vec<_> = held + .keys() + .copied() + .filter(|a| !covered.contains(a)) + .collect(); + for a in departed { + let b = held.remove(&a).unwrap(); + if w.unit(a).is_ok() { + r.remove_id(w, self, a, b)?; + } + } + } + Ok(()) + })(); + timers.append(&mut self.tactical_timers); + self.tactical_timers = timers; + result + } + pub(in crate::battle::runtime) fn tactical_wither( + e: &mut injury::InjuryEvent, + c: &mut settlement::Context<'_, Self>, + ) -> Result<(), String> { + if c.request.attack_type != hit::AttackType::Buff { + return Ok(()); + } + let strongest = c + .world + .unit(c.request.hit.target)? + .stats + .buffs() + .iter() + .filter(|b| b.key.as_deref() == Some("tinman:wither")) + .max_by(|a, b| { + a.runtime + .tick_payload + .total_cmp(&b.runtime.tick_payload) + .then(b.runtime.id().cmp(&a.runtime.id())) + }) + .map(|b| b.runtime.id()); + if strongest == Some(c.buff) { + e.amount *= c + .runtime + .get(c.world, c.request.hit.target, c.buff)? + .runtime + .tick_payload; + } + Ok(()) + } + pub(in crate::battle::runtime) fn tinman_start( + &mut self, + w: &mut World, + id: Id, + r: &mut buffs::Runtime, + p: &Tinman, + ) -> Result<(), String> { + let candidates = self.tac_enemies(w, id, None, true)?; + let mut target = None; + for &a in &candidates { + if !targeting::flying(w, a)? { + target = Some(a); + break; + } + } + let target = target.or_else(|| candidates.first().copied()); + let position = if let Some(a) = target { + w.unit(a)?.position + } else { + let u = w.unit(id)?; + let v = self.roster.as_ref().unwrap().entry(id)?.direction.vector(); + [ + u.position[0] + f64::from(v[0]), + u.position[1] + f64::from(v[1]), + ] + }; + let attack = Self::tac_stat(w, id, "atk")?; + w.unit_mut(id)?.operator.tactical.tinman_mut()?.sequence += 1; + let sequence = w.unit(id)?.operator.tactical.tinman()?.sequence; + let key = format!("tinman:zone:{id}:{sequence}"); + let interval = if p.mode == Mode::First { 0.25 } else { 1. }; + let at = w.time; + self.tac_timer( + w, + id, + at, + interval, + (p.duration / interval).round().max(1.) as u32 + 1, + Task::Zone { + position, + end: at + p.duration, + radius: p.radius, + attack, + regen: attack * p.regen, + weaken: p.weaken, + wither: p.wither, + key, + held: Default::default(), + pulse: 0, + }, + )?; + self.tactical_sync_zones(w, r)?; + Ok(()) + } + pub(in crate::battle::runtime) fn tinman_zone_timer( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + t: &mut Timer, + ) -> Result { + let id = t.source.ok_or("Operator timer requires a source")?; + let Task::Zone { + position, + end, + radius, + attack, + weaken, + held, + key, + pulse, + .. + } = &mut t.kind + else { + return Err("Invalid zone timer".into()); + }; + + if w.time + 1e-9 >= *end { + for (a, b) in std::mem::take(held) { + if w.unit(a).is_ok() { + r.remove_id(w, self, a, b)?; + } + } + return Ok(false); + } + let p = self.tac_def(id)?; + let Tactics::Tinman(p) = &p.extra.tactics else { + return Err("Invalid alchemy timer".into()); + }; + for a in self.tac_radius(w, *position, *radius)? { + if targeting::flying(w, a)? || Self::tac_has(w, a, "untargetable") { + continue; + } + if *weaken > 0. { + self.advanced_status(w, r, id, a, "weaken", 0.3, Some(*weaken))?; + } + if p.mode == Mode::Second || *pulse % 4 == 0 { + self.tac_damage( + w, + r, + id, + a, + *attack * p.scale, + DamageType::Arts, + false, + "zone", + )?; + } + } + *pulse += 1; + let _ = key; + + Ok(true) + } +} + +impl State { + pub fn redeployed(previous: Option<&Self>) -> Self { + Self { + sequence: previous.map_or(0, |p| p.sequence), + } + } +} + +impl Behavior for Tinman { + fn observes(&self, event: &KitEvent<'_>) -> bool { + event.is_lifecycle() + } + fn sp_gain(&self, host: &Host, unit: Id, context: &mut skills::Context) { + if context.reason == "time" + && host + .tactical_timers + .iter() + .any(|timer| timer.source == Some(unit) && matches!(timer.kind, Task::Zone { .. })) + { + context.amount += self.sp * DT; + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + k.host.tinman_start(k.world, id, k.buffs, self)?; + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/tippi.rs b/crates/engine/src/battle/runtime/kits/tippi.rs new file mode 100644 index 0000000..b0dce45 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/tippi.rs @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "SPECIAL", + branch: "skywalker", + ranged: false, + can_hit_fly: true, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_tippi_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_tippi_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_tippi_1" => Mode::First, + "skchr_tippi_2" => Mode::Second, + _ => return Err("Unknown selected skill".into()), + }; + s.combat.profile.selection.can_hit_fly = true; + s.combat.area.selection = s.combat.profile.selection; + s.combat.skill_area = s.combat.area; + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + s.skill_flags = ["liftoff".into(), "blockFly".into()].into(); + skill_range(raw, s)?; + s.extra.release_on_start = true; + if mode == Mode::Second { + s.rule_override = Some(skills::Rule::Never); + s.combat.skill_hits = 3; + } + let mut observer = persistent("tippi:timerObserver", Numbers::new()); + observer.runtime.injury.observe = Some(OBSERVER); + s.extra.effects.permanent.push(observer); + s.extra.tactics = Tactics::Tippi(Tippi { + mode: mode, + prob: n(t, "prob", 1.), + wait: n(t, "stack_time", 0.).ceil(), + }); + Ok(()) +} +pub(crate) struct Tippi { + pub mode: Mode, + pub prob: f64, + pub wait: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub ready_at: f64, +} +pub(in crate::battle::runtime) const EVADE: u64 = 1500; +pub(in crate::battle::runtime) const OBSERVER: u64 = 1501; +impl Behavior for Tippi { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == id => { + k.world + .unit_mut(id)? + .operator + .tactical + .tippi_mut()? + .ready_at = k.world.time + self.wait; + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + buffs::Hooks::operator_release(k.host, k.world, k.buffs, id)?; + } + KitEvent::Tick if k.up() && self.wait > 0. && self.prob > 0. => { + if !k.has(id, "tippi:evade") + && k.world.time + 1e-9 >= k.world.unit(id)?.operator.tactical.tippi()?.ready_at + { + let mut buff = Buff { + key: Some("tippi:evade".into()), + ..Default::default() + }; + buff.runtime.injury.on_injury = Some(EVADE); + k.add(id, buff)?; + } + } + KitEvent::Hit { + phase: hit::Phase::Applying, + request, + } if request.hit.target == id + && self.mode == Mode::Second + && !request.cancelled + && k.up() => + { + if k.flag(id, "silence")? || !skills::can_act(k.world, id)? { + return Ok(()); + } + let dodgeable = matches!( + request.hit.damage_type, + DamageType::Physical | DamageType::Arts + ) && request.dodge_mode != injury::DodgeMode::Ignore; + let activated = k.skill(|skill, host, world| { + if skill.bank.ready() && !skill.bank.active { + skill.activate(world, host, "TAKE_DAMAGE", false) + } else { + Ok(false) + } + })?; + if activated && dodgeable { + request.cancelled = true; + } + } + _ => {} + } + Ok(()) + } +} +impl Host { + pub(in crate::battle::runtime) fn tippi_injury( + event: &mut injury::InjuryEvent, + c: &mut settlement::Context<'_, Self>, + ) -> Result<(), String> { + if !matches!( + c.request.hit.damage_type, + DamageType::Physical | DamageType::Arts + ) { + return Ok(()); + } + let id = c.request.hit.target; + let def = c.host.tac_def(id)?; + let Tactics::Tippi(p) = &def.extra.tactics else { + return Err("Invalid Tippi injury owner".into()); + }; + if c.dodge(event, if p.prob >= 1. { None } else { Some(p.prob) })? { + c.runtime.remove_id(c.world, c.host, id, c.buff)?; + c.world + .unit_mut(id)? + .operator + .tactical + .tippi_mut()? + .ready_at = c.world.time + p.wait; + } + Ok(()) + } + pub(in crate::battle::runtime) fn tippi_observe( + c: &mut settlement::Context<'_, Self>, + ) -> Result<(), String> { + let id = c.request.hit.target; + let def = c.host.tac_def(id)?; + let Tactics::Tippi(p) = &def.extra.tactics else { + return Err("Invalid Tippi observer owner".into()); + }; + let ready = if Self::tac_up(c.world, id) && !Self::tac_has(c.world, id, "tippi:evade") { + c.world.time + p.wait + } else { + f64::INFINITY + }; + c.world + .unit_mut(id)? + .operator + .tactical + .tippi_mut()? + .ready_at = ready; + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/titi.rs b/crates/engine/src/battle/runtime/kits/titi.rs new file mode 100644 index 0000000..5d74181 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/titi.rs @@ -0,0 +1,479 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::status; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "MEDIC", + branch: "incantationmedic", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_titi_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_titi_1", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_titi_2", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_titi_1" => Mode::First, + "skchr_titi_2" => Mode::Second, + "skchr_titi_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + s.extra.support.incantation = n(&raw["trait"]["bb"], "scale", 0.5); + s.combat.profile.selection.hit_sleep = true; + s.combat.area.selection = s.combat.profile.selection; + s.combat.skill_area = s.combat.area; + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + if mode == Mode::Second { + let mut p = s.combat.profile; + p.no_attack = true; + s.combat.skill_profile = Some(p); + } + if mode == Mode::Third { + let mut p = s.combat.profile; + p.max_targets = n(bb, "attack@max_target", 2.).max(1.); + s.combat.skill_profile = Some(p); + } + s.extra.tactics = Tactics::Titi(Titi { + mode: mode, + still: n(t, "extra_atk_scale", 0.), + dream: n(t, "damage_atk_scale", 0.), + talent_scale: n(bb, "talent_scale", 1.), + vigor_threshold: n(t1, "hp_ratio", 0.5), + vigor: n(t1, "attack_speed", 0.), + sleep: n(bb, "attack@sleep", n(bb, "sleep", 5.)), + prob: n(bb, "attack@prob", 0.), + chain_sleep: n(bb, "sleep", n(bb, "attack@sleep", 5.)), + radius: n(bb, "range_radius", 1.5), + chain_targets: n(bb, "max_target", 1.).max(1.) as usize, + wake_min: n(bb, "min_atk_scale", 1.), + wake_max: n(bb, "max_atk_scale", n(bb, "min_atk_scale", 1.)), + }); + Ok(()) +} +pub(crate) struct Titi { + pub mode: Mode, + pub still: f64, + pub dream: f64, + pub talent_scale: f64, + pub vigor_threshold: f64, + pub vigor: f64, + pub sleep: f64, + pub prob: f64, + pub chain_sleep: f64, + pub radius: f64, + pub chain_targets: usize, + pub wake_min: f64, + pub wake_max: f64, +} +#[derive(Default)] +pub(crate) struct State { + // Wake and spread in sleep-application order. + pub asleep: Vec<(Id, f64)>, + pub wards: Vec, + pub accumulator: f64, +} + +const ALLY_SLEEP: u64 = 1516; +impl Titi { + fn sleeping( + &self, + k: &mut KitContext<'_>, + target: Id, + key: &str, + guard: bool, + ) -> Result<(), String> { + let entered = !k.flag(target, "sleep")?; + let mut buff = Buff { + key: Some(key.into()), + flags: ["sleep".into()].into(), + ..Default::default() + }; + buff.runtime.status = Some("sleep".into()); + if guard { + buff.runtime.interval = 0.2; + buff.runtime.on_tick = Some(ALLY_SLEEP); + } + k.add(target, buff)?; + blocking::release( + k.world, + &mut allies::Blocking { + host: k.host, + buffs: k.buffs, + }, + target, + )?; + status::Hooks::status_applied( + k.host, + &status::Context { + source: Some(k.unit), + target, + key: "sleep".into(), + duration: f64::INFINITY, + value: None, + cancelled: false, + entered, + }, + k.buffs, + k.world, + ) + } + fn spread(&self, k: &mut KitContext<'_>, from: Id) -> Result<(), String> { + let at = k.world.unit(from)?.position; + let mut candidates = Vec::new(); + let nearby = k.radius(at, self.radius)?; + let targets = k.host.tac_selectable(k.world, k.unit, nearby)?; + for target in targets { + if target == from || k.flag(target, "sleep")? { + continue; + } + let taunt = k.stat(target, "taunt")?; + let distance = body::distance(k.world.unit(target)?, at); + candidates.push((taunt, distance, target)); + } + candidates.sort_by(|a, b| { + b.0.total_cmp(&a.0) + .then(a.1.total_cmp(&b.1)) + .then(a.2.cmp(&b.2)) + }); + for (_, _, target) in candidates.into_iter().take(self.chain_targets) { + k.status(target, "sleep", self.chain_sleep, None)?; + } + Ok(()) + } + fn clear(&self, k: &mut KitContext<'_>, key: &str) -> Result<(), String> { + for target in k.host.roster.as_ref().unwrap().ids().to_vec() { + if k.world + .unit(target)? + .stats + .buffs() + .iter() + .any(|buff| buff.key.as_deref() == Some(key) && buff.runtime.source == Some(k.unit)) + { + k.remove(target, key)?; + } + } + Ok(()) + } +} +impl Behavior for Titi { + fn priority(&self, event: &KitEvent<'_>, _: &World, _: Id) -> i32 { + if matches!(event, KitEvent::Fatal(_)) { + 5 + } else { + 0 + } + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id && self.mode == Mode::Second => { + let keys = k.keys()?; + let mut pick = None; + let mut lowest = f64::INFINITY; + for target in k.allies(&keys)? { + if target == id { + continue; + } + let ratio = k.world.unit(target)?.stats.hp / k.stat(target, "maxHp")?; + if ratio < lowest { + lowest = ratio; + pick = Some(target); + } + } + let mut wards = vec![id]; + if let Some(target) = pick { + wards.push(target); + } + for &target in &wards { + self.sleeping(k, target, "titi:ward", false)?; + } + let state = k.world.unit_mut(id)?.operator.tactical.titi_mut()?; + state.wards = wards; + state.accumulator = 0.25; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id && self.mode == Mode::Second => { + let due = { + let s = k.world.unit_mut(id)?.operator.tactical.titi_mut()?; + s.accumulator += context.dt; + if s.accumulator + 1e-9 >= 0.25 { + s.accumulator = 0.; + true + } else { + false + } + }; + if due { + let wards = k.world.unit(id)?.operator.tactical.titi()?.wards.clone(); + let mut pulsed = BTreeSet::new(); + for target in wards { + if !Host::tac_up(k.world, target) || !k.has(target, "titi:ward") { + continue; + } + let at = k.world.unit(target)?.position; + for enemy in k.radius(at, 1.7)? { + let reenter = pulsed.insert(enemy) + && !k.world.unit(enemy)?.stats.buffs().iter().any(|buff| { + buff.runtime.status.as_deref() == Some("sleep") + && buff.runtime.time_left > 0.5 + 1e-9 + }); + k.host.apply_status( + k.world, + k.buffs, + enemy, + "sleep", + status::Options { + duration: 0.5, + source: Some(id), + reenter, + ..Default::default() + }, + )?; + } + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + if self.mode == Mode::Second { + self.clear(k, "titi:ward")?; + k.world + .unit_mut(id)? + .operator + .tactical + .titi_mut()? + .wards + .clear(); + } + if self.mode == Mode::Third { + self.clear(k, "titi:allySleep")?; + } + } + KitEvent::Impact(impact) + if impact.attacker == id + && impact.is_skill + && impact.kind == attacks::VictimKind::Main + && self.mode != Mode::Second => + { + if let Some(target) = impact + .target + .filter(|&target| Host::tac_up(k.world, target)) + { + if !k.flag(target, "sleep")? + && (self.mode == Mode::Third || k.host.rng.chance(self.prob)) + { + k.status(target, "sleep", self.sleep, None)?; + } + } + } + KitEvent::Landed { + event: landed, + request, + } if landed.source == Some(id) + && request.is_attack + && !request.is_splash + && request.hit.damage_type != DamageType::Elemental => + { + let target = landed.target; + if k.world.unit(target)?.side == health::Side::Enemy + && k.world.unit(target)?.stats.alive + && (k.world.unit(target)?.blocked_by().is_some() + || !k.world.unit(target)?.moving + || k.flag(target, "stun")? + || k.flag(target, "noMove")? + || k.stat(target, "moveSpeed")? <= 0.) + { + let scale = if self.mode == Mode::Second && k.active()? { + self.talent_scale + } else { + 1. + }; + let amount = k.stat(id, "atk")? * self.still * scale; + k.damage(target, amount, DamageType::Arts, false, "titiStill")?; + } + } + KitEvent::Scheduled(due) if k.up() => { + if due[4] { + let scale = if self.mode == Mode::Second && k.active()? { + self.talent_scale + } else { + 1. + }; + let amount = k.stat(id, "atk")? * self.dream * scale; + for target in k.host.spawns.as_ref().unwrap().live().to_vec() { + if Host::tac_up(k.world, target) + && !k.world.unit(target)?.hidden + && k.flag(target, "sleep")? + { + k.damage(target, amount, DamageType::Arts, false, "titiDream")?; + } + } + } + if due[2] { + for target in k.host.roster.as_ref().unwrap().ids().to_vec() { + if Host::tac_up(k.world, target) + && k.faction(target, "sargonShip", &["sargon", "minos"])? + && k.world.unit(target)?.stats.hp / k.stat(target, "maxHp")? + > self.vigor_threshold + { + k.buff( + target, + "titi:vigor", + [("aspd".into(), self.vigor)].into(), + 0.5, + )?; + } + } + } + } + KitEvent::Status(context) + if self.mode == Mode::Third + && context.key == "sleep" + && k.world.unit(context.target)?.side == health::Side::Enemy => + { + let time = k.world.time; + let asleep = &mut k.world.unit_mut(id)?.operator.tactical.titi_mut()?.asleep; + if !asleep.iter().any(|&(target, _)| target == context.target) { + asleep.push((context.target, time)); + } + } + KitEvent::Tick if self.mode == Mode::Third => { + let watched = k.world.unit(id)?.operator.tactical.titi()?.asleep.clone(); + for (target, time) in watched { + if !k.world.unit(target).is_ok_and(|u| u.stats.alive) { + k.world + .unit_mut(id)? + .operator + .tactical + .titi_mut()? + .asleep + .retain(|&(other, _)| other != target); + continue; + } + if k.flag(target, "sleep")? { + continue; + } + k.world + .unit_mut(id)? + .operator + .tactical + .titi_mut()? + .asleep + .retain(|&(other, _)| other != target); + if k.up() && k.active()? { + let scale = self.wake_min + + (self.wake_max - self.wake_min) + * ((k.world.time - time) / self.chain_sleep.max(0.1)).min(1.); + let amount = k.stat(id, "atk")? * scale; + k.damage(target, amount, DamageType::Arts, true, "titiWake")?; + self.spread(k, target)?; + } + } + } + KitEvent::Kill { victim } if self.mode == Mode::Third && *victim != id => { + let asleep = &mut k.world.unit_mut(id)?.operator.tactical.titi_mut()?.asleep; + if let Some(index) = asleep.iter().position(|&(target, _)| target == *victim) { + asleep.remove(index); + if k.up() && k.active()? { + self.spread(k, *victim)?; + } + } + } + KitEvent::Fatal(event) + if self.mode == Mode::Third + && event.target != id + && !event.prevented + && k.world.unit(event.target)?.side == health::Side::Ally => + { + if let Some(buff) = k + .world + .unit(event.target)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("titi:allySleep")) + { + if buff.runtime.source == Some(id) { + event.prevented = true; + } + return Ok(()); + } + if k.world.unit(event.target)?.deployment.kind + == crate::battle::deploy::Kind::Operator + && k.up() + && k.active()? + && body::in_range(k.world.unit(event.target)?, &k.keys()?) + { + event.prevented = true; + self.sleeping(k, event.target, "titi:allySleep", true)?; + } + } + KitEvent::Buff { + context, + event: buffs::Event::Tick, + token, + } if *token == ALLY_SLEEP => { + let buff = k.buffs.get(k.world, context.unit, context.buff)?; + if buff.runtime.source == Some(id) + && k.world.unit(context.unit)?.stats.hp >= k.stat(context.unit, "maxHp")? - 1e-6 + { + k.buffs + .remove_id(k.world, k.host, context.unit, context.buff)?; + } + } + _ => {} + } + Ok(()) + } +} + +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + let mut state = Self::default(); + if let Some(previous) = previous { + state.asleep = previous.asleep.clone(); + } + state + } +} diff --git a/crates/engine/src/battle/runtime/kits/ulpia.rs b/crates/engine/src/battle/runtime/kits/ulpia.rs new file mode 100644 index 0000000..d37405d --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/ulpia.rs @@ -0,0 +1,323 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "WARRIOR", + branch: "crusher", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_ulpia_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "CUSTOM_RANGE", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tb = &raw["trait"]["bb"]; + s.modifiers = [ + ("atkPct".into(), n(bb, "atk", 0.)), + ("hpPct".into(), n(bb, "max_hp", 0.)), + ] + .into(); + s.combat.profile.hit_all_blocked = true; + let grid = tactical_grid(&raw["skill"]["trigger"]["customRangeGrid"], false)?; + s.trigger_range = Some(grid.clone()); + if n(tb, "heal_scale", 0.) > 0. { + s.extra.effects.permanent.push(persistent( + "ulpia:module", + [("healingTakenMul".into(), n(tb, "heal_scale", 1.))].into(), + )); + } + s.extra.tactics = Tactics::Ulpia(Ulpia { + reach: grid + .iter() + .filter(|p| p[0] == 0) + .map(|p| p[1]) + .max() + .unwrap_or(1) + .max(1), + radius: n(bb, "projectile_range", 1.5), + scale: n(bb, "atk_scale", 0.), + stun: n(bb, "stun", 0.), + heal: n(t, "value1", 0.), + low_heal: n(t, "value2", 0.), + threshold: n(t, "hp_ratio", 0.5), + hp: n(t1, "max_hp", 0.), + attack: n(t1, "atk", 0.), + cap: n(t1, "max_stack_cnt", 9.).max(1.) as u32, + share_hp: n(t1, "ulpia_t_1[abyssal].max_hp", 0.), + share_attack: n(t1, "ulpia_t_1[abyssal].atk", 0.), + share_cap: n(t1, "ulpia_t_1[abyssal].max_stack_cnt", 9.).max(1.) as u32, + block_threshold: n(t1, "add_block_cnt_stack_cnt", 0.), + blocks: n(t1, "block_cnt", 0.), + blocked_scale: n(tb, "damage_scale", 1.), + }); + Ok(()) +} +pub(crate) struct Ulpia { + reach: i32, + radius: f64, + scale: f64, + stun: f64, + heal: f64, + low_heal: f64, + threshold: f64, + hp: f64, + attack: f64, + cap: u32, + share_hp: f64, + share_attack: f64, + share_cap: u32, + block_threshold: f64, + blocks: f64, + blocked_scale: f64, +} +#[derive(Default)] +pub(crate) struct State { + home: Option<([i32; 2], Id)>, +} +impl Ulpia { + fn stack( + k: &mut KitContext<'_>, + unit: Id, + key: &str, + mods: Numbers, + cap: u32, + ) -> Result<(), String> { + let mut b = Buff { + key: Some(key.into()), + mods, + ..Default::default() + }; + b.runtime.refresh = buffs::Refresh::Stack; + b.runtime.max_stacks = cap; + k.add(unit, b)?; + Ok(()) + } + fn abyssal(k: &KitContext<'_>, unit: Id) -> Result { + Ok( + k.world.unit(unit)?.deployment.kind == crate::battle::deploy::Kind::Operator + && [ + "char_263_skadi", + "char_143_ghost", + "char_218_cuttle", + "char_474_glady", + "char_1023_ghost2", + "char_4145_ulpia", + ] + .contains(&k.host.tac_def(unit)?.char_id.as_str()), + ) + } +} +impl Behavior for Ulpia { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + let origin = k.world.unit(id)?.deployment.tile; + let facing = k + .host + .roster + .as_ref() + .unwrap() + .entry(id)? + .direction + .vector(); + let mut stop = 0; + if k.world.unit(id)?.blocking().iter().all(|&e| { + !Host::tac_up(k.world, e) || k.world.unit(e).unwrap().blocked_by() != Some(id) + }) { + for distance in 1..=self.reach { + let tile = [ + origin[0] + facing[0] * distance, + origin[1] + facing[1] * distance, + ]; + let grid = k.host.grid.as_ref().unwrap(); + if !grid.in_rect(tile) || grid.obstacle(tile) != 0 { + break; + } + stop = distance; + let keys = [tile[0] as usize * COLS + tile[1] as usize]; + if !k.enemies(Some(&keys), true)?.is_empty() { + break; + } + } + } + let anchor = [origin[0] + facing[0] * stop, origin[1] + facing[1] * stop]; + let position = anchor.map(f64::from); + let amount = k.stat(id, "atk")? * self.scale; + for target in k.radius(position, self.radius)? { + k.damage(target, amount, DamageType::Physical, true, "anchor")?; + if Host::tac_up(k.world, target) { + k.status(target, "stun", self.stun, None)?; + } + } + if stop > 0 && k.up() { + let mut destination = None; + for distance in [stop, stop + 1] { + let tile = [ + origin[0] + facing[0] * distance, + origin[1] + facing[1] * distance, + ]; + let grid = k.host.grid.as_ref().unwrap(); + if grid.in_rect(tile) + && tile[1] >= 1 + && tile[1] <= 9 + && grid.can_stand(tile, false) + && grid.obstacle(tile) == 0 + && !k + .host + .roster + .as_ref() + .unwrap() + .deployment() + .reserved(k.world, tile)? + { + destination = Some(tile); + break; + } + } + if let Some(destination) = destination { + if k.move_redeploy(destination, skill, false)? + && k.up() + && skill.bank.active + { + k.world.unit_mut(id)?.deployment.down_at_home = true; + if let Some(marker) = k.summon("token_10039_ulpia_block", origin, 0.)? { + k.world.unit_mut(id)?.operator.tactical.ulpia_mut()?.home = + Some((origin, marker)); + } + } + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + skill, + .. + } if *unit == id => { + if k.up() { + k.world.unit_mut(id)?.deployment.down_at_home = false; + } + if let Some((home, marker)) = k + .world + .unit_mut(id)? + .operator + .tactical + .ulpia_mut()? + .home + .take() + { + let owner = k.unit; + k.unit = marker; + let result = k.retreat(); + k.unit = owner; + result?; + if k.up() { + k.move_redeploy(home, skill, true)?; + } + } + } + KitEvent::Landed { event, request } + if event.target == id + && k.up() + && k.world.unit(id)?.stats.hp > 0. + && event.amount > 0. + && request.hit.damage_type != DamageType::Elemental + && !request.hit.hp_loss => + { + let ratio = k.world.unit(id)?.stats.hp / k.stat(id, "maxHp")?; + let amount = if ratio < self.threshold { + self.low_heal + } else { + self.heal + }; + if amount > 0. { + k.heal( + id, + amount, + health::HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.source == Some(id) + && k.world.unit(request.hit.target)?.blocked_by().is_some() => + { + request.damage.mul *= self.blocked_scale; + } + KitEvent::Death { + unit, + credit: Some(killer), + } if k.up() + && k.world.unit(*unit)?.side == health::Side::Enemy + && (*killer == id || self.block_threshold > 0. && Self::abyssal(k, *killer)?) => + { + Self::stack( + k, + id, + "ulpia:blood", + [("hpFlat".into(), self.hp), ("atkFlat".into(), self.attack)].into(), + self.cap, + )?; + let stacks = k + .world + .unit(id)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("ulpia:blood")) + .map_or(0, |b| b.stacks); + if self.block_threshold > 0. && stacks as f64 >= self.block_threshold { + k.buff( + id, + "ulpia:bloodBlock", + [("blockCnt".into(), self.blocks)].into(), + f64::INFINITY, + )?; + } + if self.share_hp != 0. || self.share_attack != 0. { + for ally in k.host.roster.as_ref().unwrap().ids().to_vec() { + if ally != id && Host::tac_up(k.world, ally) && Self::abyssal(k, ally)? { + Self::stack( + k, + ally, + "ulpia:bloodShare", + [ + ("hpFlat".into(), self.share_hp), + ("atkFlat".into(), self.share_attack), + ] + .into(), + self.share_cap, + )?; + } + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/vigil.rs b/crates/engine/src/battle/runtime/kits/vigil.rs new file mode 100644 index 0000000..7f6e9e3 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/vigil.rs @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "PIONEER", + branch: "tactician", + ranged: true, + can_hit_fly: true, + physical: true, + projectile: "arrow", + projectile_speed: 14., + required_range: None, + skills: &[Skill { + id: "skchr_vigil_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "SP_FULL", + attack_override: true, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + s.combat.skill_hits = 3; + s.extra.tactics = Tactics::Vigil(Vigil { + interval: n(bb, "interval", 1.5).max(0.1), + step: n(bb, "cost", 1.).max(0.01), + cap: n(bb, "value", 0.), + bonus: n(bb, "attack@vigil_s_3.atk_scale", 0.), + penetration: n(talent_at(raw, 1), "def_penetrate_fixed", 0.), + trait_scale: n(&raw["trait"]["bb"], "atk_scale", 1.5), + }); + Ok(()) +} +pub(crate) struct Vigil { + interval: f64, + step: f64, + cap: f64, + bonus: f64, + penetration: f64, + trait_scale: f64, +} +#[derive(Default)] +pub(crate) struct State { + wolf: Option, + accumulator: f64, + paid: f64, + marked: BTreeSet, +} +impl Behavior for Vigil { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == id => { + if let Some(tile) = k.tactical_point()? { + if let Some(wolf) = k.summon("token_10028_vigil_wolf", tile, 0.)? { + k.world.unit_mut(id)?.operator.tactical.vigil_mut()?.wolf = Some(wolf); + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + let state = k.world.unit_mut(id)?.operator.tactical.vigil_mut()?; + state.accumulator = 0.; + state.paid = 0.; + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id => { + let state = k.world.unit_mut(id)?.operator.tactical.vigil_mut()?; + state.accumulator += context.dt; + let mut amount = 0.; + while state.accumulator >= self.interval - 1e-9 + && state.paid + self.step <= self.cap + 1e-9 + { + state.accumulator -= self.interval; + state.paid += self.step; + amount += self.step; + } + if amount > 0. { + k.dp(amount)?; + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + context, + .. + } if *unit == id && context.reason == "duration" => { + let rest = self.cap - k.world.unit(id)?.operator.tactical.vigil()?.paid; + if rest > 1e-9 { + k.dp(rest)?; + k.world.unit_mut(id)?.operator.tactical.vigil_mut()?.paid += rest; + } + } + KitEvent::Death { unit, .. } if *unit == id => { + if let Some(wolf) = k.world.unit(id)?.operator.tactical.vigil()?.wolf { + let owner = k.unit; + k.unit = wolf; + let result = k.retreat(); + k.unit = owner; + result?; + } + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.is_attack => { + if let Some(wolf) = k + .world + .unit(id)? + .operator + .tactical + .vigil()? + .wolf + .filter(|&wolf| Host::tac_up(k.world, wolf)) + { + if k.world.unit(request.hit.target)?.blocked_by() == Some(wolf) { + if request.hit.source == Some(id) { + request.damage.mul *= self.trait_scale; + } + if request.hit.source == Some(id) || request.hit.source == Some(wolf) { + request.damage.penetration.def_flat += self.penetration; + } + } + } + } + KitEvent::Landed { event, request } + if request.is_attack && self.bonus > 0. && k.active()? => + { + if let Some(wolf) = k + .world + .unit(id)? + .operator + .tactical + .vigil()? + .wolf + .filter(|&wolf| Host::tac_up(k.world, wolf)) + { + if (event.source == Some(id) || event.source == Some(wolf)) + && k.world.unit(event.target)?.side == health::Side::Enemy + && Host::tac_up(k.world, event.target) + && k.world.unit(event.target)?.blocked_by() == Some(wolf) + { + let amount = k.stat(id, "atk")? * self.bonus; + let owner = k.unit; + k.unit = event.source.unwrap(); + let result = + k.damage(event.target, amount, DamageType::Arts, true, "vigilBonus"); + k.unit = owner; + result?; + } + } + } + KitEvent::Scheduled(due) if due[0] => { + let mut marked = BTreeSet::new(); + if let Some(wolf) = k + .world + .unit(id)? + .operator + .tactical + .vigil()? + .wolf + .filter(|&wolf| Host::tac_up(k.world, wolf) && k.up()) + { + let def = k.host.tac_def(wolf)?; + if let Tactics::Wolf(p) = &def.extra.tactics { + if p.taunt != 0. { + let own = k.unit; + k.unit = wolf; + for enemy in k.world.unit(wolf)?.blocking().to_vec() { + if Host::tac_up(k.world, enemy) { + k.buff( + enemy, + "token:pack_mark", + [("taunt".into(), p.taunt)].into(), + 0.25, + )?; + marked.insert(enemy); + } + } + k.unit = own; + } + } + } + let previous = std::mem::replace( + &mut k.world.unit_mut(id)?.operator.tactical.vigil_mut()?.marked, + marked.clone(), + ); + for enemy in previous.difference(&marked) { + if k.world.unit(*enemy).is_ok() { + k.remove(*enemy, "token:pack_mark")?; + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/vulpis.rs b/crates/engine/src/battle/runtime/kits/vulpis.rs new file mode 100644 index 0000000..e9981ea --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/vulpis.rs @@ -0,0 +1,304 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{skills::SpType, sp::Kind}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "PIONEER", + branch: "pioneer", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 10.0, + required_range: None, + skills: &[ + Skill { + id: "skchr_vulpis_3", + kind: Kind::Duration, + sp_type: SpType::Time, + rule: "ACTIVE_RANGE", + attack_override: true, + }, + Skill { + id: "skchr_vulpis_1", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "DEFAULT", + attack_override: true, + }, + Skill { + id: "skchr_vulpis_2", + kind: Kind::Charges, + sp_type: SpType::Time, + rule: "SKILL_RANGE", + attack_override: false, + }, + ], + build, +}; +fn build(raw: &Value, _default: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let tb = &raw["trait"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let mode = match raw["skill"]["skillId"].as_str().unwrap_or("") { + "skchr_vulpis_1" => Mode::First, + "skchr_vulpis_2" => Mode::Second, + "skchr_vulpis_3" => Mode::Third, + _ => return Err("Unknown selected skill".into()), + }; + if mode == Mode::Third { + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + let mut p = s.combat.profile; + p.hit_all_blocked = true; + s.combat.skill_profile = Some(p); + s.extra.skill_status = Some(OnHitStatus { + key: "stun", + duration: n(bb, "attack@stun", 0.2), + chance: None, + }); + } + skill_range(raw, s)?; + s.extra.tactics = Tactics::Vulpis(Vulpis { + mode: mode, + dp: n(bb, "cost", 0.), + extra: n(bb, "extra_damage_ratio", 0.), + scale: n(bb, "atk_scale", 1.), + targets: n(bb, "max_target", 6.).max(1.) as usize, + grid: tactical_grid(&raw["skill"]["rangeGrid"], false)?, + sluggish: n(bb, "sluggish", 0.), + stun: n(bb, "stun", 0.), + aspd: n(bb, "attack_speed", 0.), + hunt_scale: n(t, "atk_scale", 0.), + hunt_duration: n(t, "interval", 10.), + dp_bonus: n(t1, "delta_cost_increase_time", 1.) - 1., + quiet: n(t1, "interval", 4.), + regen: n( + t1, + "vulpis_t_2[heal][interval].hp_recovery_per_sec_by_max_hp_ratio", + 0., + ), + block_atk: n(tb, "atk", 0.), + block_def: n(tb, "def", 0.), + }); + Ok(()) +} +pub(crate) struct Vulpis { + pub mode: Mode, + pub dp: f64, + pub extra: f64, + pub scale: f64, + pub targets: usize, + pub grid: Vec<[i32; 2]>, + pub sluggish: f64, + pub stun: f64, + pub aspd: f64, + pub hunt_scale: f64, + pub hunt_duration: f64, + pub dp_bonus: f64, + pub quiet: f64, + pub regen: f64, + pub block_atk: f64, + pub block_def: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub duration: f64, + pub marks: BTreeMap, + pub killed: bool, + pub busy: bool, +} +impl Behavior for Vulpis { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == id => { + if self.mode == Mode::Third { + k.remove(id, "vulpis:camou")?; + let state = k.world.unit_mut(id)?.operator.tactical.vulpis_mut()?; + state.killed = false; + state.duration = skill.time_left; + k.dp(self.dp)?; + k.buff( + id, + "skill:vulpis_aspd", + [("aspd".into(), self.aspd)].into(), + f64::INFINITY, + )?; + } + if self.mode == Mode::Second { + k.dp(self.dp)?; + let keys = k.range(&self.grid)?; + let targets = k.enemies(Some(&keys), true)?; + for target in targets.into_iter().take(self.targets) { + let slow = k.has(target, "sluggish"); + let amount = k.stat(id, "atk")? * self.scale; + k.damage(target, amount, DamageType::Arts, true, "vulpisTorture")?; + if Host::tac_up(k.world, target) { + k.status(target, "sluggish", self.sluggish, None)?; + if slow { + k.status(target, "stun", self.stun, None)?; + } + } + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + skill, + .. + } if *unit == id && self.mode == Mode::Third => { + let duration = k + .world + .unit(id)? + .operator + .tactical + .vulpis()? + .duration + .max(DT); + let aspd = self.aspd * skill.time_left.max(0.) / duration; + if let Some(buff) = k + .world + .unit(id)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("skill:vulpis_aspd")) + .map(|b| b.runtime.id()) + { + k.buffs.edit(k.world, id, buff, |b| { + b.mods = [("aspd".into(), aspd)].into() + })?; + } + } + KitEvent::Skill { + unit, + event: skills::Event::End, + context, + .. + } if *unit == id && self.mode == Mode::Third => { + k.remove(id, "skill:vulpis_aspd")?; + if context.reason != "death" + && k.up() + && k.world.unit(id)?.operator.tactical.vulpis()?.killed + { + let mut buff = Buff { + key: Some("vulpis:camou".into()), + flags: ["camou".into()].into(), + ..Default::default() + }; + buff.runtime.status = Some("camou".into()); + k.add(id, buff)?; + } + } + KitEvent::Impact(impact) + if impact.attacker == id + && impact.is_skill + && self.mode == Mode::First + && impact.kind == attacks::VictimKind::Main => + { + if let Some(target) = impact.target.filter(|&t| Host::tac_up(k.world, t)) { + let amount = k.stat(id, "atk")? * self.extra; + k.damage(target, amount, DamageType::Arts, true, "vulpisPunish")?; + } + k.dp(self.dp)?; + } + KitEvent::Landed { + event: landed, + request, + } if landed.source == Some(id) + && k.world.unit(landed.target)?.side == health::Side::Enemy + && request.hit.damage_type != DamageType::Elemental + && !request.tags.iter().any(|t| t == "vulpisHunt") => + { + if k.world.unit(id)?.operator.tactical.vulpis()?.busy { + return Ok(()); + } + let now = k.world.time; + let started = *k + .world + .unit_mut(id)? + .operator + .tactical + .vulpis_mut()? + .marks + .entry(landed.target) + .or_insert(now); + if now - started <= self.hunt_duration + 1e-9 + && Host::tac_up(k.world, landed.target) + { + k.world.unit_mut(id)?.operator.tactical.vulpis_mut()?.busy = true; + let amount = k.stat(id, "atk")? * self.hunt_scale; + let result = + k.damage(landed.target, amount, DamageType::Arts, false, "vulpisHunt"); + k.world.unit_mut(id)?.operator.tactical.vulpis_mut()?.busy = false; + result?; + } + } + KitEvent::Death { + credit: Some(source), + .. + } if *source == id && k.active()? => { + k.world.unit_mut(id)?.operator.tactical.vulpis_mut()?.killed = true; + } + KitEvent::Scheduled(_) => { + let mut marks = std::mem::take( + &mut k.world.unit_mut(id)?.operator.tactical.vulpis_mut()?.marks, + ); + marks.retain(|target, _| k.world.unit(*target).is_ok()); + k.world.unit_mut(id)?.operator.tactical.vulpis_mut()?.marks = marks; + } + KitEvent::Tick if k.up() => { + if self.dp_bonus > 0. && k.host.tac_leader(k.world, id)? { + k.dp(DT * self.dp_bonus)?; + } + let on = + k.world.time - k.world.unit(id)?.last_hit_at >= self.quiet && self.regen > 0.; + if on && !k.has(id, "talent:vulpis_regen") { + k.buff( + id, + "talent:vulpis_regen", + [("hpRegenRatio".into(), self.regen)].into(), + f64::INFINITY, + )?; + } else if !on { + k.remove(id, "talent:vulpis_regen")?; + } + if self.block_atk > 0. || self.block_def > 0. { + let blocked = !k.world.unit(id)?.blocking().is_empty(); + k.host.advanced_toggle( + k.world, + k.buffs, + id, + "trait:vulpis_block", + blocked, + [ + ("atkPct".into(), self.block_atk), + ("defPct".into(), self.block_def), + ] + .into(), + )?; + } + } + _ => {} + } + Ok(()) + } +} + +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + let mut state = Self::default(); + if let Some(previous) = previous { + state.marks = previous.marks.clone(); + } + state + } +} diff --git a/crates/engine/src/battle/runtime/kits/whitw2.rs b/crates/engine/src/battle/runtime/kits/whitw2.rs new file mode 100644 index 0000000..2080e91 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/whitw2.rs @@ -0,0 +1,449 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::deterministic::math::{atan2, cos, hypot, sin}; +pub(crate) const KIT: Kit = Kit { + position: "RANGED", + profession: "CASTER", + branch: "funnel", + ranged: true, + can_hit_fly: true, + physical: false, + projectile: "bolt", + projectile_speed: 11., + required_range: None, + skills: &[Skill { + id: "skchr_whitw2_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "GDGLOW_SKILL_2", + attack_override: true, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + let bb = &raw["skill"]["bb"]; + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let additional_drones = n(bb, "attack@cnt", 0.).floor().max(0.); + if additional_drones > 63. { + return Err("Released drone count exceeds capacity".into()); + } + s.modifiers = [("atkPct".into(), n(bb, "atk", 0.))].into(); + let mut profile = s.combat.profile; + profile.no_attack = true; + s.combat.skill_profile = Some(profile); + s.extra.tactics = Tactics::Whitw2(Whitw2 { + funnel: funnel::Parameters::read(raw), + spread: n(bb, "attack@times", 1.3).max(0.), + radius: n(bb, "attack@range_radius", 0.9), + damage: n(bb, "attack@magic_atk_scale", 1.), + fear: n(bb, "attack@fear", 0.), + slow: n(bb, "attack@move_speed", 0.), + drones: additional_drones as usize + 1, + interval: n(t, "interval", 20.).max(1.), + cap: n(t, "scale", 1.), + silence: n(t, "attack@silence_duration", 0.), + sp: n(t1, "sp", 0.), + speed: n(t1, "attack_speed", 0.), + }); + Ok(()) +} +pub(crate) struct Whitw2 { + funnel: funnel::Parameters, + spread: f64, + radius: f64, + damage: f64, + fear: f64, + slow: f64, + drones: usize, + interval: f64, + cap: f64, + silence: f64, + sp: f64, + speed: f64, +} +#[derive(Clone, Copy, PartialEq)] +enum Phase { + Spread, + Seek, + Chase, + Lock, +} +struct Drone { + position: [f64; 2], + heading: [f64; 2], + speed: f64, + age: f64, + phase: Phase, + target: Option, + cooldown: f64, + ramp_target: Option, + ramp: f64, + orbit: Option<[f64; 2]>, +} +#[derive(Default)] +pub(crate) struct State { + pub funnel: funnel::State, + stage: u32, + drones: Vec, + accumulator: f64, + honor: BTreeMap, +} +impl Whitw2 { + fn release(k: &mut KitContext<'_>, count: usize) -> Result, String> { + let unit = k.world.unit(k.unit)?; + let dir = k + .host + .roster + .as_ref() + .unwrap() + .entry(k.unit)? + .direction + .vector(); + let angle = atan2(dir[0] as f64, dir[1] as f64); + Ok((0..count) + .map(|index| { + let a = angle + (2. * std::f64::consts::PI * index as f64) / count as f64; + Drone { + position: unit.position, + heading: [sin(a), cos(a)], + speed: 0.1, + age: 0., + phase: Phase::Spread, + target: None, + cooldown: 0., + ramp_target: None, + ramp: 0., + orbit: None, + } + }) + .collect()) + } + fn accelerate(drone: &mut Drone, acceleration: f64, maximum: f64, dt: f64) -> f64 { + let next = (drone.speed + acceleration * dt).min(maximum); + let distance = ((drone.speed + next) / 2.) * dt; + drone.speed = next; + distance + } + fn selectable(k: &mut KitContext<'_>, id: Id) -> Result { + if !k + .world + .unit(id) + .is_ok_and(|u| u.stats.alive && !u.hidden && u.side == health::Side::Enemy) + { + return Ok(false); + } + targeting::can_target_enemy( + k.world, + k.host, + Some(k.unit), + id, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + ) + } + fn fly(&self, k: &mut KitContext<'_>, drone: &mut Drone, dt: f64) -> Result<(), String> { + drone.cooldown = (drone.cooldown - dt).max(0.); + if drone.phase == Phase::Spread { + let distance = Self::accelerate(drone, 1.9, 2., dt); + for axis in 0..2 { + drone.position[axis] += drone.heading[axis] * distance; + } + drone.age += dt; + if drone.age + 1e-9 < self.spread { + return Ok(()); + } + drone.phase = Phase::Seek; + } + if matches!(drone.phase, Phase::Lock | Phase::Chase) + && !Self::selectable(k, drone.target.unwrap())? + { + if drone.phase == Phase::Lock { + let local = [ + (k.host.rng.next_f64() * 2. - 1.) * 0.75, + (k.host.rng.next_f64() * 2. - 1.) * 0.75, + ]; + let direction = k.host.roster.as_ref().unwrap().entry(k.unit)?.direction; + let offset = match direction { + Direction::Right => local, + Direction::Left => [-local[0], -local[1]], + Direction::Up => [local[1], -local[0]], + Direction::Down => [-local[1], local[0]], + }; + let target = k.world.unit(drone.target.unwrap())?; + drone.position = [ + target.position[0] + offset[0], + target.position[1] + offset[1], + ]; + } + k.world.unpin_unit(drone.target.take().unwrap())?; + drone.phase = Phase::Seek; + } + if drone.phase == Phase::Seek { + let mut best = None; + let mut distance = f64::INFINITY; + let mut home_distance = f64::INFINITY; + let own = k.world.unit(k.unit)?.position; + for target in k.world.unit_ids().collect::>() { + if !Self::selectable(k, target)? { + continue; + } + let point = k.world.unit(target)?.position; + let d = hypot(point[0] - drone.position[0], point[1] - drone.position[1]); + let h = hypot(point[0] - own[0], point[1] - own[1]); + if d < distance - 1e-9 || (d <= distance + 1e-9 && h < home_distance - 1e-9) { + best = Some(target); + distance = d; + home_distance = h; + } + } + let Some(target) = best else { + let center = *drone.orbit.get_or_insert([ + drone.position[0] + drone.heading[1] * 0.9, + drone.position[1] - drone.heading[0] * 0.9, + ]); + let a = + atan2(drone.position[0] - center[0], drone.position[1] - center[1]) + dt / 0.9; + drone.position = [center[0] + 0.9 * sin(a), center[1] + 0.9 * cos(a)]; + drone.heading = [cos(a), -sin(a)]; + return Ok(()); + }; + // Keep the final position available until the drone leaves its target. + k.world.pin_unit(target)?; + drone.target = Some(target); + drone.phase = Phase::Chase; + drone.speed = 2.; + drone.orbit = None; + } + let target = drone.target.ok_or("Drone lost its chase target")?; + if drone.phase == Phase::Chase { + let distance = Self::accelerate(drone, 1., 4., dt); + if body::distance(k.world.unit(target)?, drone.position) > distance + 1e-9 { + let point = k.world.unit(target)?.position; + let delta = [point[0] - drone.position[0], point[1] - drone.position[1]]; + let length = hypot(delta[0], delta[1]); + if length > 1e-9 { + drone.heading = [delta[0] / length, delta[1] / length]; + } + for axis in 0..2 { + drone.position[axis] += drone.heading[axis] * distance; + } + return Ok(()); + } + drone.phase = Phase::Lock; + if self.fear > 0. { + k.status(target, "fear", self.fear, None)?; + } + } + drone.position = k.world.unit(target)?.position; + if drone.cooldown > 1e-9 || !k.up() || !Self::selectable(k, target)? { + return Ok(()); + } + drone.cooldown = k.stat(k.unit, "interval")?; + let stage = k.world.unit(k.unit)?.operator.tactical.whitw2()?.stage; + let cap = self.funnel.cap * if stage >= 1 { self.cap } else { 1. }; + drone.ramp = if drone.ramp_target == Some(target) { + (drone.ramp + self.funnel.delta).min(cap) + } else { + self.funnel.initial + }; + drone.ramp_target = Some(target); + let amount = k.stat(k.unit, "atk")? * k.stat(k.unit, "atkScaleMul")? * drone.ramp; + k.damage(target, amount, DamageType::Arts, false, "droneAttack")?; + Ok(()) + } +} +impl Behavior for Whitw2 { + fn payload( + &self, + w: &World, + id: Id, + payload: &mut attacks::Direct, + _: &mut attacks::Area, + ) -> Result<(), String> { + if !w.unit(id)?.operator.active_skill { + let stage = w.unit(id)?.operator.tactical.whitw2()?.stage; + let mut parameters = self.funnel; + if stage >= 1 { + parameters.cap *= self.cap; + } + payload.attachment = Some(parameters.attachment(if stage >= 3 { 2 } else { 1 }, false)); + payload.hits = 1; + } + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + let count = self.drones + + usize::from(k.world.unit(id)?.operator.tactical.whitw2()?.stage >= 3); + let drones = Self::release(k, count)?; + let state = k.world.unit_mut(id)?.operator.tactical.whitw2_mut()?; + state.drones = drones; + state.accumulator = 0.; + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + let drones = std::mem::take( + &mut k.world.unit_mut(id)?.operator.tactical.whitw2_mut()?.drones, + ); + for drone in drones { + if let Some(target) = drone.target { + k.world.unpin_unit(target)?; + } + } + } + KitEvent::Skill { + unit, + event: skills::Event::Tick, + context, + .. + } if *unit == id && k.up() && k.active()? => { + let mut drones = std::mem::take( + &mut k.world.unit_mut(id)?.operator.tactical.whitw2_mut()?.drones, + ); + let result = (|| -> Result { + let count = self.drones + + usize::from(k.world.unit(id)?.operator.tactical.whitw2()?.stage >= 3); + if drones.len() < count { + drones.extend(Self::release(k, count - drones.len())?); + } + for drone in &mut drones { + if !k.up() || !k.active()? { + return Ok(false); + } + self.fly(k, drone, context.dt)?; + } + if !k.up() || !k.active()? { + return Ok(false); + } + let mut near = BTreeSet::new(); + for drone in &drones { + for enemy in k.radius(drone.position, self.radius)? { + if Self::selectable(k, enemy)? { + near.insert(enemy); + } + } + } + if self.slow != 0. { + for &enemy in &near { + k.buff( + enemy, + "whitw2:slow", + [("moveMul".into(), (1. + self.slow).max(0.))].into(), + 0.2, + )?; + } + } + let accumulator = + k.world.unit(id)?.operator.tactical.whitw2()?.accumulator + context.dt; + k.world + .unit_mut(id)? + .operator + .tactical + .whitw2_mut()? + .accumulator = accumulator; + if accumulator + 1e-9 >= 1. { + k.world + .unit_mut(id)? + .operator + .tactical + .whitw2_mut()? + .accumulator -= 1.; + for enemy in near { + if !k.up() || !k.active()? { + return Ok(false); + } + let amount = k.stat(id, "atk")? * self.damage; + k.damage(enemy, amount, DamageType::Arts, true, "dot")?; + } + } + Ok(k.up() && k.active()?) + })(); + if matches!(result, Ok(true)) { + k.world.unit_mut(id)?.operator.tactical.whitw2_mut()?.drones = drones; + } else { + for drone in drones { + if let Some(target) = drone.target { + k.world.unpin_unit(target)?; + } + } + } + result?; + } + KitEvent::Scheduled(due) if due[4] && k.up() => { + let stage = ((k.world.time - k.world.unit(id)?.deployment.deployed_at + 1e-6) + / self.interval) + .floor() + .clamp(0., 3.) as u32; + k.world.unit_mut(id)?.operator.tactical.whitw2_mut()?.stage = stage; + } + KitEvent::Landed { event, request } + if event.source == Some(id) + && self.silence > 0. + && k.world.unit(id)?.operator.tactical.whitw2()?.stage >= 2 + && request.hit.damage_type != DamageType::Elemental + && k.world.unit(event.target)?.side == health::Side::Enemy + && Host::tac_up(k.world, event.target) => + { + k.status(event.target, "silence", self.silence, None)?; + } + KitEvent::SkillObserved { + unit, + event: skills::Event::Deploy, + skill, + } if self.sp > 0. + && k.world.unit(*unit)?.deployment.kind + == crate::battle::deploy::Kind::Operator + && k.world.unit(*unit)?.owner == k.world.unit(id)?.owner + && k.faction(*unit, "siracusaShip", &[])? => + { + let amount = self.sp; + k.host.with_kit_buffs(k.world, k.buffs, |host, w| { + skill.gain(w, host, amount, "talent", false, false) + })?; + } + KitEvent::SkillObserved { + unit, + event: skills::Event::SkillStart, + .. + } if self.speed != 0. + && k.world.unit(*unit)?.deployment.kind + == crate::battle::deploy::Kind::Operator + && k.world.unit(*unit)?.owner == k.world.unit(id)?.owner + && k.faction(*unit, "siracusaShip", &[])? => + { + let sequence = k.world.unit(*unit)?.deployment.deploy_seq; + let previous = k + .world + .unit_mut(id)? + .operator + .tactical + .whitw2_mut()? + .honor + .insert(*unit, sequence); + if previous != Some(sequence) { + k.buff( + *unit, + "whitw2:honor", + [("aspd".into(), self.speed)].into(), + f64::INFINITY, + )?; + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/wolf.rs b/crates/engine/src/battle/runtime/kits/wolf.rs new file mode 100644 index 0000000..29cdaf2 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/wolf.rs @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +pub(crate) struct Wolf { + interval: f64, + block: f64, + guard: f64, + pub taunt: f64, +} +#[derive(Default)] +pub(crate) struct State { + pub count: u32, + return_at: Option, + next_grow: f64, + returning: bool, +} +pub(crate) fn build(raw: &Value, s: &mut Spec) { + let talents = raw["talents"].as_array().cloned().unwrap_or_default(); + let talent = talents.first().map(|t| &t["bb"]).unwrap_or(&Value::Null); + let find = |key: &str, fallback: f64| { + talents + .iter() + .find_map(|t| t["bb"][key].as_f64()) + .unwrap_or(fallback) + }; + s.extra.tactics = Tactics::Wolf(Wolf { + interval: n( + talent, + "vigil_wolf_t_1_enhance[trigger].interval", + n(talent, "interval", 25.), + ), + block: n( + talent, + "vigil_wolf_t_1_enhance[trigger].block_cnt", + n(talent, "block_cnt", 1.), + ), + guard: find("damage_scale", 1.), + taunt: find("taunt_level", 0.), + }); +} +impl State { + pub(crate) fn redeployed(previous: &Self) -> Self { + Self { + returning: previous.returning, + ..Default::default() + } + } +} +impl Wolf { + fn apply(&self, k: &mut KitContext<'_>) -> Result<(), String> { + let count = k.world.unit(k.unit)?.operator.tactical.wolf()?.count; + k.buff( + k.unit, + "token:wolves", + [("blockCnt".into(), self.block * count as f64)].into(), + f64::INFINITY, + )?; + Ok(()) + } +} +impl Behavior for Wolf { + fn payload( + &self, + w: &World, + id: Id, + payload: &mut attacks::Direct, + _: &mut attacks::Area, + ) -> Result<(), String> { + payload.hits = w.unit(id)?.operator.tactical.wolf()?.count.max(1); + Ok(()) + } + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == id => { + let now = k.world.time; + let returning = k.world.unit(id)?.operator.tactical.wolf()?.returning; + let state = k.world.unit_mut(id)?.operator.tactical.wolf_mut()?; + state.count = if returning { 1 } else { 2 }; + state.returning = false; + state.return_at = None; + state.next_grow = now + self.interval; + self.apply(k)?; + } + KitEvent::Fatal(context) + if context.target == id + && !context.prevented + && k.world.unit(id)?.operator.tactical.wolf()?.count > 1 => + { + k.world.unit_mut(id)?.operator.tactical.wolf_mut()?.count -= 1; + self.apply(k)?; + context.prevented = true; + let maximum = k.stat(id, "maxHp")?; + k.world.unit_mut(id)?.stats.hp = maximum; + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.target == id + && request.hit.source.is_some_and(|source| { + k.world + .unit(source) + .is_ok_and(|u| u.blocked_by() == Some(id)) + }) => + { + request.damage.mul *= self.guard + } + KitEvent::Death { unit, .. } if *unit == id => { + let reason = k.world.unit(id)?.deployment.remove_reason.as_deref(); + let owner = k.world.unit(id)?.summoner; + if matches!(reason, Some("killed" | "retreat" | "forced")) + && owner.is_none_or(|owner| Host::tac_up(k.world, owner)) + { + k.world.unit_mut(id)?.removed = false; + let at = k.world.time + self.interval; + let state = k.world.unit_mut(id)?.operator.tactical.wolf_mut()?; + state.count = 0; + state.return_at = Some(at); + let mut buff = Buff { + key: Some("token:wolves".into()), + mods: [("blockCnt".into(), 0.)].into(), + ..Default::default() + }; + buff.runtime.source = Some(id); + k.buffs.add( + k.world, + k.host, + id, + buffs::Spec { + buff, + allow_dead: true, + ..Default::default() + }, + )?; + } + } + KitEvent::Death { unit, .. } if Some(*unit) == k.world.unit(id)?.summoner => { + k.world + .unit_mut(id)? + .operator + .tactical + .wolf_mut()? + .return_at = None; + if k.up() { + k.retreat()?; + } + } + KitEvent::Scheduled(_) => { + if k.up() + && k.world.time + 1e-9 >= k.world.unit(id)?.operator.tactical.wolf()?.next_grow + { + let state = k.world.unit_mut(id)?.operator.tactical.wolf_mut()?; + state.next_grow += self.interval; + if state.count < 3 { + state.count += 1; + self.apply(k)?; + } + } + if k.world + .unit(id)? + .operator + .tactical + .wolf()? + .return_at + .is_some_and(|at| k.world.time + 1e-9 >= at) + { + if k.world + .unit(id)? + .summoner + .is_some_and(|owner| !Host::tac_up(k.world, owner)) + { + k.world + .unit_mut(id)? + .operator + .tactical + .wolf_mut()? + .return_at = None; + } else { + k.world + .unit_mut(id)? + .operator + .tactical + .wolf_mut()? + .returning = true; + if !k.redeploy_free(id)? { + let at = k.world.time + 0.25; + k.world + .unit_mut(id)? + .operator + .tactical + .wolf_mut()? + .return_at = Some(at); + } + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/yanyou.rs b/crates/engine/src/battle/runtime/kits/yanyou.rs new file mode 100644 index 0000000..5c7a745 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/yanyou.rs @@ -0,0 +1,282 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as C, Event as E}; +use super::*; +use crate::battle::targeting::{self, Queries}; +use crate::deterministic::math::hypot; +pub(crate) struct Yanyou { + radius: f64, + speed: f64, + burn: f64, + fragile: f64, + scale: f64, + flame_radius: f64, +} +pub(crate) struct State { + pub keys: Vec, + pub hover: f64, + at: Option<[f64; 2]>, + target: Option, + acc: f64, + aura: f64, +} +impl Default for State { + fn default() -> Self { + Self { + keys: vec![], + hover: 0., + at: None, + target: None, + acc: 0., + aura: 0.2, + } + } +} +pub(crate) fn build(raw: &Value, s: &mut Spec) { + let t = &raw["talents"]["bb"]; + let sk = raw["skills"] + .as_array() + .and_then(|a| a.iter().find(|v| v["prefabKey"] == "Skill_2")) + .unwrap_or(&Value::Null); + s.combat.profile.max_targets = n(t, "1.attack@max_target", 1.); + s.extra.tactics = Tactics::Yanyou(Yanyou { + radius: n(&raw["stats"], "rangeRadius", 2.), + speed: n(&raw["stats"], "moveSpeed", 1.) * 0.5, + burn: n(t, "2.ep_damage_ratio", 0.), + fragile: n(t, "2.damage_scale", 1.) - 1., + scale: n(&sk["bb"], "atk_scale", 0.), + flame_radius: n(&sk["bb"], "range_radius", 0.), + }); +} +impl Yanyou { + fn targets(&self, k: &mut C<'_>, ranged: bool) -> Result, String> { + let keys = k + .world + .unit(k.unit)? + .operator + .tactical + .yanyou()? + .keys + .clone(); + let mut out = Vec::new(); + for id in k.host.spawns.as_ref().unwrap().live().to_vec() { + if targeting::can_target_enemy( + k.world, + k.host, + Some(k.unit), + id, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? && (!ranged || body::in_range(k.world.unit(id)?, &keys)) + { + let taunt = k.stat(id, "taunt")?; + let distance = k.host.remaining_distance(id, k.world)?; + let seq = k.world.unit(id)?.targeting.spawn_seq; + out.push((id, taunt, distance, seq)); + } + } + out.sort_by(|a, b| { + b.1.total_cmp(&a.1) + .then(a.2.total_cmp(&b.2)) + .then(a.3.cmp(&b.3)) + }); + Ok(out.into_iter().map(|x| x.0).collect()) + } + fn lock(&self, k: &mut C<'_>) -> Result, String> { + let t = k.world.unit(k.unit)?.operator.tactical.yanyou()?.target; + if let Some(t) = t { + if k.world.unit(t).is_ok() + && targeting::can_target_enemy( + k.world, + k.host, + Some(k.unit), + t, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? + { + return Ok(Some(t)); + } + } + Ok(None) + } + fn keys(&self, k: &mut C<'_>) -> Result<(), String> { + let pos = k.world.unit(k.unit)?.position; + let s = k.world.unit_mut(k.unit)?.operator.tactical.yanyou_mut()?; + if s.at + .is_some_and(|a| (a[0] - pos[0]).abs() < 0.05 && (a[1] - pos[1]).abs() < 0.05) + { + return Ok(()); + } + s.keys.clear(); + for r in 0..crate::battle::grid::ROWS { + for c in 0..COLS { + if hypot(r as f64 - pos[0], c as f64 - pos[1]) <= self.radius + 1e-9 { + s.keys.push(r * COLS + c); + } + } + } + s.at = Some(pos); + Ok(()) + } +} +impl Behavior for Yanyou { + fn profile( + &self, + w: &World, + id: Id, + skill: Option<&skills::Runtime>, + p: &mut search::AttackProfile, + ) -> Result<(), String> { + p.no_attack = skill + .map(|s| s.bank.active) + .unwrap_or(w.unit(id)?.operator.active_skill); + Ok(()) + } + fn handle(&self, k: &mut C<'_>, e: &mut E<'_>) -> Result<(), String> { + match e { + E::Skill { + unit, + event: skills::Event::Deploy, + .. + } if *unit == k.unit => { + k.world.unit_mut(k.unit)?.motion_fly = true; + self.keys(k)?; + } + E::Skill { + unit, + event: skills::Event::Start, + skill, + .. + } if *unit == k.unit => { + let target = self.targets(k, true)?.first().copied(); + let s = k.world.unit_mut(k.unit)?.operator.tactical.yanyou_mut()?; + s.target = target; + s.acc = 1.; + if target.is_none() { + k.host + .with_kit_buffs(k.world, k.buffs, |h, w| skill.end(w, h, "noTarget"))?; + } + } + E::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == k.unit => { + k.world + .unit_mut(k.unit)? + .operator + .tactical + .yanyou_mut()? + .target = None; + } + E::Skill { + unit, + event: skills::Event::Tick, + skill, + context, + } if *unit == k.unit => { + let target = self.lock(k)?; + let silent = k + .world + .unit_mut(k.unit)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("silence"); + if silent || target.is_none() { + k.host.with_kit_buffs(k.world, k.buffs, |h, w| { + skill.end(w, h, if silent { "silence" } else { "targetLost" }) + })?; + return Ok(()); + } + if !skills::can_act(k.world, k.unit)? { + return Ok(()); + } + let s = k.world.unit_mut(k.unit)?.operator.tactical.yanyou_mut()?; + s.acc += context.dt; + if s.acc < 1. - 1e-9 { + return Ok(()); + } + s.acc -= 1.; + let t = target.unwrap(); + let mut hit = if self.flame_radius > 0. { + k.radius(k.world.unit(t)?.position, self.flame_radius)? + } else { + vec![] + }; + if !hit.contains(&t) { + hit.insert(0, t); + } + let damage = k.stat(k.unit, "atk")? * self.scale; + for enemy in hit { + k.damage(enemy, damage, DamageType::Arts, true, "flame")?; + } + } + E::DamageApplied { event, request } + if event.source == Some(k.unit) + && event.amount > 0. + && request.hit.damage_type != DamageType::Elemental + && k.world.unit(event.target)?.side == health::Side::Enemy + && k.world.unit(event.target)?.stats.hp > 0. => + { + let amount = k.stat(k.unit, "atk")? * self.burn; + if amount > 0. { + k.elemental(event.target, amount, crate::battle::element::Element::Burn)?; + } + } + E::Element { request, .. } if request.damage.hit.target == k.unit => { + request.damage.cancelled = true; + } + E::Tick if k.up() => { + if skills::can_act(k.world, k.unit)? + && !k + .world + .unit_mut(k.unit)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("noMove") + && self.speed > 0. + { + let target = match self.lock(k)? { + Some(t) => Some(t), + None => self.targets(k, false)?.first().copied(), + }; + if let Some(t) = target { + let from = k.world.unit(k.unit)?.position; + let to = k.world.unit(t)?.position; + let hover = k.world.unit(k.unit)?.operator.tactical.yanyou()?.hover; + let dr = to[0] + hover - from[0]; + let dc = to[1] - from[1]; + let d = hypot(dc, dr); + if d > 0.25 + 1e-6 { + let step = (d - 0.25).min(self.speed * DT); + let rect = k.host.rect; + k.world.unit_mut(k.unit)?.position = [ + (from[0] + dr / d * step).clamp(rect.r0 as f64, rect.r1 as f64), + (from[1] + dc / d * step).clamp(rect.c0 as f64, rect.c1 as f64), + ]; + } + } + } + self.keys(k)?; + let s = k.world.unit_mut(k.unit)?.operator.tactical.yanyou_mut()?; + s.aura += DT; + if self.fragile > 0. && s.aura >= 0.2 - 1e-9 { + s.aura = 0.; + for t in k.radius(k.world.unit(k.unit)?.position, 1.5)? { + k.status(t, "elemFragile", 0.4, Some(self.fragile))?; + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/kits/yu.rs b/crates/engine/src/battle/runtime/kits/yu.rs new file mode 100644 index 0000000..dbc7535 --- /dev/null +++ b/crates/engine/src/battle/runtime/kits/yu.rs @@ -0,0 +1,352 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::dispatch::{Behavior, Context as KitContext, Event as KitEvent}; +use super::*; +use crate::battle::{deploy, element, valued}; +pub(crate) const KIT: Kit = Kit { + position: "MELEE", + profession: "TANK", + branch: "primprotector", + ranged: false, + can_hit_fly: false, + physical: true, + projectile: "none", + projectile_speed: 0., + required_range: None, + skills: &[Skill { + id: "skchr_yu_3", + kind: crate::battle::sp::Kind::Duration, + sp_type: skills::SpType::Time, + rule: "CUSTOM_RANGE", + attack_override: false, + }], + build, +}; +fn build(raw: &Value, _: bool, s: &mut Spec) -> Result<(), String> { + if raw["skill"]["skillId"] != "skchr_yu_3" { + return Err("Unknown selected skill".into()); + } + let bb = &raw["skill"]["bb"]; + s.trigger_range = Some(tactical_grid( + &raw["skill"]["trigger"]["customRangeGrid"], + false, + )?); + let t = talent_at(raw, 0); + let t1 = talent_at(raw, 1); + let tm = talent_at(raw, -1); + s.modifiers = [ + ("hpPct".into(), n(bb, "max_hp", 0.)), + ("atkPct".into(), n(bb, "atk", 0.)), + ("defPct".into(), n(bb, "def", 0.)), + ] + .into(); + s.extra.tactics = Tactics::Yu(Yu { + protection: n(t, "damage_resistance", 0.), + dot: suffix_number(t, "atk_scale", 0.), + burn: suffix_number(t, "ep_damage_ratio", 0.), + dot_interval: suffix_number(t, "interval", 1.).max(0.1), + heal_count: n(t1, "cnt", 4.), + heal: n(t1, "hp_recovery_per_sec_by_max_hp_ratio", 0.), + element_heal: n(t1, "ep_heal_ratio", 0.), + heal_interval: n(t1, "interval", 1.).max(0.1), + wall_burn: n(bb, "ep_damage_ratio", 0.), + wall_probability: n(bb, "prob", 0.), + element_scale: n(&raw["trait"]["bb"], "ep_damage_scale", 1.), + module_count: n(tm, "cnt", f64::INFINITY), + module_damage: n(tm, "damage_scale", 1.), + }); + Ok(()) +} +pub(crate) struct Yu { + protection: f64, + dot: f64, + burn: f64, + dot_interval: f64, + heal_count: f64, + heal: f64, + element_heal: f64, + heal_interval: f64, + wall_burn: f64, + wall_probability: f64, + element_scale: f64, + module_count: f64, + module_damage: f64, +} +#[derive(Default)] +pub(crate) struct State { + wall: Option<(usize, f64)>, + touching: BTreeSet, + next_dot: f64, + next_heal: f64, +} +impl State { + pub(crate) fn redeployed(previous: Option<&Self>) -> Self { + Self { + next_dot: previous.map_or(0., |s| s.next_dot), + next_heal: previous.map_or(0., |s| s.next_heal), + ..Default::default() + } + } +} +impl Yu { + fn operators(k: &KitContext<'_>) -> Result, String> { + Ok(k.host + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .filter(|&a| { + k.world.unit(a).is_ok_and(|u| { + Host::tac_up(k.world, a) + && u.deployment.kind == deploy::Kind::Operator + && u.owner == k.world.unit(k.unit).unwrap().owner + }) + }) + .collect()) + } +} +impl Behavior for Yu { + fn handle(&self, k: &mut KitContext<'_>, event: &mut KitEvent<'_>) -> Result<(), String> { + let id = k.unit; + match event { + KitEvent::Skill { + unit, + event: skills::Event::Start, + .. + } if *unit == id => { + let direction = k + .host + .roster + .as_ref() + .unwrap() + .entry(id)? + .direction + .vector(); + let tile = k.world.unit(id)?.deployment.tile; + let axis = if direction[0] == 0 { 1 } else { 0 }; + let state = k.world.unit_mut(id)?.operator.tactical.yu_mut()?; + state.wall = Some((axis, tile[axis] as f64 + 0.5 * direction[axis] as f64)); + state.touching.clear(); + } + KitEvent::Skill { + unit, + event: skills::Event::End, + .. + } if *unit == id => { + let state = k.world.unit_mut(id)?.operator.tactical.yu_mut()?; + state.wall = None; + state.touching.clear(); + } + KitEvent::DamageApplied { event, request } + if self.wall_burn > 0. + && k.up() + && event.amount > 0. + && request.hit.damage_type == DamageType::Arts + && k.world.unit(event.target)?.side == health::Side::Enemy + && k.world.unit(event.target)?.stats.alive => + { + if let (Some(source), Some((axis, value))) = ( + event.source.filter(|&a| { + a != id && k.world.unit(a).is_ok_and(|u| u.side == health::Side::Ally) + }), + k.world.unit(id)?.operator.tactical.yu()?.wall, + ) { + if (k.world.unit(source)?.position[axis] - value) + * (k.world.unit(event.target)?.position[axis] - value) + < 0. + { + let amount = k.stat(id, "atk")? * self.wall_burn; + k.elemental(event.target, amount, element::Element::Burn)?; + } + } + } + KitEvent::ProjectileStep { + id: projectile, + source, + position, + speed, + removable, + cancelled, + } if !**cancelled + && self.wall_probability > 0. + && k.up() + && *removable + && *speed > 0. + && source.is_some_and(|a| { + k.world.unit(a).is_ok_and(|u| u.side == health::Side::Enemy) + }) => + { + if let Some((axis, value)) = k.world.unit(id)?.operator.tactical.yu()?.wall { + let rect = k.host.grid.as_ref().unwrap().rect(); + let inside = if axis == 1 { + position[0] >= rect.r0 as f64 - 0.5 && position[0] <= rect.r1 as f64 + 0.5 + } else { + position[1] >= rect.c0 as f64 - 0.5 && position[1] <= rect.c1 as f64 + 0.5 + }; + let state = k.world.unit_mut(id)?.operator.tactical.yu_mut()?; + if !inside || (position[axis] - value).abs() > 0.15 + 1e-9 { + state.touching.remove(projectile); + } else if state.touching.insert(*projectile) { + if state.touching.len() > k.host.tactical_limit { + return Err("Yu projectile contact capacity exceeded".into()); + } + if k.host.rng.next_f64() < self.wall_probability { + **cancelled = true; + } + } + } + } + KitEvent::Hit { + phase: hit::Phase::Hit, + request, + } if request.hit.damage_type == DamageType::Arts + && self.module_damage > 1. + && k.has(request.hit.target, "burnBurst") => + { + if let Some(source) = request.hit.source { + let shares = source == id + || k.up() + && k.active()? + && k.world.unit(source)?.deployment.kind == deploy::Kind::Operator + && k.world.unit(source)?.owner == k.world.unit(id)?.owner; + if shares && Self::operators(k)?.len() as f64 >= self.module_count { + request.damage.mul *= self.module_damage; + } + } + } + KitEvent::Element { + phase: element::Phase::Hit, + request, + } if request.damage.hit.source == Some(id) + && k.up() + && !k.world.unit(id)?.blocking().is_empty() => + { + request.damage.damage.mul *= self.element_scale; + } + KitEvent::Tick => { + let active: BTreeSet<_> = k + .host + .flights + .as_ref() + .unwrap() + .list() + .iter() + .map(|p| p.id) + .collect(); + k.world + .unit_mut(id)? + .operator + .tactical + .yu_mut()? + .touching + .retain(|p| active.contains(p)); + } + KitEvent::Scheduled(due) => { + let now = k.world.time; + let state = k.world.unit_mut(id)?.operator.tactical.yu_mut()?; + let dot_at = state.next_dot.max(self.dot_interval); + let heal_at = state.next_heal.max(self.heal_interval); + let dot = now + 1e-9 >= dot_at; + let heal = now + 1e-9 >= heal_at; + if dot { + state.next_dot = dot_at + self.dot_interval; + } + if heal { + state.next_heal = heal_at + self.heal_interval; + } + if !k.up() { + return Ok(()); + } + if due[0] && self.protection > 0. && !k.world.unit(id)?.blocking().is_empty() { + valued::apply( + k.world, + k.host, + k.buffs, + id, + valued::Request { + key: "protect", + kind: valued::Kind::Custom(|v| { + [ + ("physTakenMul".into(), 1. - v), + ("artsTakenMul".into(), 1. - v), + ] + .into() + }), + plain: false, + duration: 0.2, + value: self.protection, + source: Some(id), + stack_as: None, + }, + )?; + } + if dot { + for enemy in k.world.unit(id)?.blocking().to_vec() { + if !Host::tac_up(k.world, enemy) { + continue; + } + let attack = k.stat(id, "atk")?; + if self.burn > 0. { + k.elemental(enemy, attack * self.burn, element::Element::Burn)?; + } + if self.dot > 0. && Host::tac_up(k.world, enemy) { + let mut request = hit::Request::new( + health::Hit { + target: enemy, + source: Some(id), + credit: Some(id), + damage_type: DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount: attack * self.dot, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + request.attack_type = hit::AttackType::Buff; + request.calculation = hit::Calculation::Precomputed; + request.tags.extend(["talent".into(), "dot".into()]); + k.deal(&mut request)?; + } + } + } + if heal { + let operators = Self::operators(k)?; + if operators.len() as f64 >= self.heal_count { + let targets = if k.active()? { operators } else { vec![id] }; + for target in targets { + let hp = k.stat(target, "maxHp")?; + if self.heal > 0. { + k.heal( + target, + hp * self.heal * self.heal_interval, + health::HealOptions { + self_heal: true, + silent: true, + ..Default::default() + }, + )?; + } + if self.element_heal > 0. { + element::heal( + k.world, + target, + hp * self.element_heal * self.heal_interval, + None, + )?; + } + } + } + } + } + _ => {} + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/movement_batch.rs b/crates/engine/src/battle/runtime/movement_batch.rs new file mode 100644 index 0000000..8f402c0 --- /dev/null +++ b/crates/engine/src/battle/runtime/movement_batch.rs @@ -0,0 +1,486 @@ +//! Batch event-free movement ticks while keeping the original movement arithmetic. +use super::*; +use crate::battle::clock::Host as _; + +struct Segment { + id: Id, + target: [f64; 2], + position: [f64; 2], + next: [f64; 2], + stride: f64, + terrain: super::super::terrain::State, + radius_squared: f64, +} + +impl Field { + /// Diagnostic/reference switch. Switching execution strategy never resets a battle. + pub fn set_movement_batching(&mut self, enabled: bool) -> Result<(), String> { + self.healthy()?; + self.core.movement_batching = enabled; + Ok(()) + } + + pub fn movement_batch_ticks(&self) -> u64 { + self.clock.movement_ticks() + } + pub fn event_window_stats(&self) -> [u64; 2] { + [self.clock.movement_ticks(), self.core.event_windows] + } +} + +impl Core { + fn movement_segments(&mut self, clock: &Clock) -> Result>, String> { + let h = &self.host; + if !self.movement_batching + || self.boss.is_some() + || h.boss_round.is_some() + || !h.flights.as_ref().unwrap().list().is_empty() + || h.flights.as_ref().unwrap().faulted() + || h.buffs.as_ref().unwrap().faulted() + || h.spawns.as_ref().unwrap().faulted() + || h.content.as_ref().unwrap().faulted() + || !h.devices.movement_quiet() + || !h.movement_bonds_quiet() + || !h.movement_growth_quiet() + || !h.zones.is_empty() + || !h.tactical_timers.is_empty() + || h.tactical_slots != 0 + || !h.pending_skill_starts.is_empty() + || !h.deferred_kit_events.is_empty() + || !h.equipment.clock_quiet() + { + return Ok(None); + } + let spawns = h.spawns.as_ref().unwrap(); + let ids = spawns.live(); + if (ids.is_empty() && spawns.queue.pending().is_empty()) + || self.world.unit_ids().count() != ids.len() + h.roster.as_ref().unwrap().ids().len() + || spawns.retained() != ids.len() + || ids + .iter() + .any(|&id| !event_window::quiet_enemy(h.content.as_ref().unwrap().kit_ref(id))) + { + return Ok(None); + } + let grid = h.grid.as_ref().unwrap(); + let rect = grid.rect(); + let mut segments = Vec::with_capacity(ids.len()); + for &id in ids { + let profile = spawns.definition(id)?.profile; + if matches!(profile.mode, enemy::Mode::Heal) { + return Ok(None); + } + let u = self.world.unit_mut(id)?; + if !u.stats.alive + || !u.stats.cached_clean() + || !u.deployed + || u.hidden + || u.removed + || u.pool.is_some() + || u.hit_area.is_some() + || u.blocked_by().is_some() + || u.enemy.carrier.is_some() + || u.enemy.swing + || u.enemy.targets().is_some() + || u.enemy.pause_until > clock.time() + || u.motion.attack_stand_until > clock.time() + || u.motion.unbalance_until > clock.time() + || u.motion.fear.is_some() + { + return Ok(None); + } + let (flags_empty, stride) = { + let stats = u.stats.stats().map_err(str::to_string)?; + ( + stats.flags.is_empty(), + stats.get(super::super::stats::Stat::MoveSpeed) * 0.5 * DT, + ) + }; + if !flags_empty || !h.terrain.movement_ground_clear(u) { + return Ok(None); + } + let Some(route) = u.motion.route.as_ref() else { + return Ok(None); + }; + let Some(target) = route + .points + .as_ref() + .and_then(|points| points.get(route.point)) + .copied() + else { + return Ok(None); + }; + if route.version != grid.version() + || route.wait_left.is_some() + || route.patrol + || !matches!(route.legs().get(route.leg), Some(motion::Leg::Move { .. })) + || !stride.is_finite() + || stride <= 1e-9 + || !u + .position + .iter() + .chain(target.iter()) + .all(|n| n.is_finite()) + || u.position[0] < rect.r0 as f64 + || u.position[0] > rect.r1 as f64 + || u.position[1] < rect.c0 as f64 + || u.position[1] > rect.c1 as f64 + || target[0] < rect.r0 as f64 + || target[0] > rect.r1 as f64 + || target[1] < rect.c0 as f64 + || target[1] > rect.c1 as f64 + { + return Ok(None); + } + segments.push(Segment { + id, + target, + position: u.position, + next: u.position, + stride, + terrain: u.terrain, + radius_squared: if profile.melee { + 1e-9 + } else { + let radius = u.stats.base_number("rangeRadius") + 0.25; + radius * radius + 1e-9 + }, + }); + } + Ok(Some(segments)) + } + + pub(super) fn run_movement_batch( + &mut self, + clock: &mut Clock, + budget: usize, + ) -> Result { + let Some(mut segments) = self.movement_segments(clock)? else { + return Ok(0); + }; + self.movement_paths.refresh(&self.host, &self.world)?; + if segments + .iter() + .any(|s| !self.movement_paths.clear_at(s.position, s.radius_squared)) + { + return Ok(0); + } + let Some(mut window) = event_window::Window::prepare(&mut self.host, &mut self.world)? + else { + return Ok(0); + }; + if segments.iter().any(|s| !window.clear_at(s.position)) { + return Ok(0); + } + let spawn_at = self + .host + .spawns + .as_ref() + .unwrap() + .queue + .pending() + .front() + .map(|p| p.time); + let mut ticks = 0; + // Plan in local coordinates. Effect changes and route transitions end the window. + // Keep the original floating-point recurrence, then commit the final state once. + while ticks < budget.min(64) { + let tick = clock + .ticks() + .checked_add(ticks as u64) + .ok_or("Battle tick count exhausted")?; + let time = tick as f64 * DT; + let next_time = tick.checked_add(1).ok_or("Battle tick count exhausted")? as f64 * DT; + if next_time >= self.time_limit - 1e-9 + || next_time >= 3600. + || spawn_at.is_some_and(|at| at <= time + 1e-9) + { + break; + } + let mut clear = true; + for segment in &mut segments { + let (next, _, reached, _) = + motion::step_position(segment.position, segment.target, segment.stride); + if reached + || !self.movement_paths.clear_at(next, segment.radius_squared) + || !window.clear_at(next) + || !self + .host + .terrain + .movement_effect_stable(&segment.terrain, next, time) + { + clear = false; + break; + } + segment.next = next; + } + if !clear || !window.project(&mut self.world, time)? { + break; + } + window.accept(); + for segment in &mut segments { + segment.position = segment.next; + if self.host.terrain.active() { + segment.terrain.movement_arrive(segment.position); + } + } + ticks += 1; + } + if ticks > 0 { + self.event_windows = self.event_windows.saturating_add(1); + window.commit(&mut self.host, &mut self.world)?; + self.commitments.clear(); + for segment in segments { + let unit = self.world.unit_mut(segment.id)?; + unit.position = segment.position; + unit.terrain = segment.terrain; + unit.moving = true; + for _ in 0..ticks { + unit.cadence.tick(DT, true); + } + } + // DP and cooldown addition/subtraction retain their original rounding and caps. + for _ in 0..ticks { + self.phase(Phase::Dp, clock)?; + clock.movement_tick()?; + } + self.world.time = clock.time(); + self.host.rebuild_index(&self.world)?; + } + Ok(ticks) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::sync::OnceLock; + + fn data() -> Arc { + static DATA: OnceLock> = OnceLock::new(); + DATA.get_or_init(|| { + let root = std::env::temp_dir().join(format!("arkguard-movement-{}-{}", std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos())); + std::fs::create_dir(&root).unwrap(); + for name in ["config", "chess", "bonds", "garrisons", "items", "bands", "effects", "choices", + "enemies", "factions", "waves", "stages", "bosses", "tokens", "backups"] { + let table = if name == "enemies" { + json!({"enemy_1007_slime": {"stats": {"maxHp": 100, "atk": 10, "moveSpeed": 1.3}}, + "enemy_1005_yokai": {"stats": {"motion": "FLY", "maxHp": 100, "atk": 10, "moveSpeed": 1.7, "rangeRadius": 3.}}, + "enemy_10042_prtrop": {"stats": {"maxHp": 100, "atk": 10, "moveSpeed": 1.}}, + "enemy_9006_actoxi": {"stats": {"maxHp": 1, "atk": 10, "moveSpeed": 0.}, + "talents": {"bb": {"1.projectile_life_time": 2., "1.damage_atk_scale": 0.1}}}, + "enemy_1267_nhpbr": {"stats": {"maxHp": 100, "atk": 10, "moveSpeed": 1.}, + "talents": {"bb": {"PollutedDie.projectile_range": 2., "PollutedDie.projectile_life_time": 0.6, + "PollutedDie.polluted_damage_low": 3., "PollutedDie.polluted_damage_high": 2.}}}}) + } else if name == "chess" { + json!({"chess_char_1_05_a": {"position": "MELEE", "profession": "PIONEER", + "subProfessionId": "charger", "rangeGrid": [[0, 0], [0, 1]], + "stats": {"maxHp": 10000, "atk": 25, "cost": 0, "blockCnt": 1}, + "skill": {"skillId": "skchr_vigna_2", "spType": "INCREASE_WITH_TIME", + "spCost": 10, "duration": 3, "trigger": {"rule": "DEFAULT"}}}, + "chess_char_1_17_a": {"position": "RANGED", "profession": "CASTER", + "subProfessionId": "mystic", "rangeGrid": [[0, 0], [0, 1], [0, 2]], + "stats": {"maxHp": 10000, "atk": 25, "cost": 0, "blockCnt": 0}, + "skill": {"skillId": "skchr_indigo_2", "spType": "INCREASE_WITH_TIME", + "spCost": 10, "duration": 3, "trigger": {"rule": "DEFAULT"}}}}) + } else if name == "effects" { + json!({"test_flawless": {"buffs": [{"key": "env_gbuff_new_with_verify", + "bbStr": {"key": "act1autochess_debuff_9"}, "bb": {"atk": 0.2, "def": 0.1}}]}}) + } else if name == "bonds" { json!({"yanShip": {}}) } else { json!({}) }; + std::fs::write(root.join(format!("{name}.json")), table.to_string()).unwrap(); + } + let catalog = Arc::new(Catalog::load(&root, 1 << 20).unwrap()); + std::fs::remove_dir_all(root).unwrap(); + catalog + }).clone() + } + + fn field(input: &Value, time_limit: f64, enabled: bool) -> Field { + let stage = json!({"rows": vec!["rrrrrrrrrrrrrrrrrrrrr"; 19], "legend": {}}); + field_on(&stage, input, time_limit, enabled) + } + + fn field_on(stage: &Value, input: &Value, time_limit: f64, enabled: bool) -> Field { + let template = Template::parse(input, &Value::Null, &Value::Null, 2048, 512).unwrap(); + let mut field = + Field::new(data(), stage, template, 42, time_limit, Limits::default()).unwrap(); + field.set_movement_batching(enabled).unwrap(); + field + } + + fn input() -> Value { + json!({"routes": [{"motion": "WALK", "start": [10, 2], "end": [10, 18]}], + "spawns": [{"enemyKey": "enemy_1007_slime", "time": 0., "count": 2, "interval": 0.4}, + {"enemyKey": "enemy_1007_slime", "time": 2. + 1e-10, "count": 1}]}) + } + + fn snapshot(field: &mut Field) -> Value { + let states = field.enemy_states().unwrap(); + let mut units = Vec::new(); + for state in states { + let unit = field.unit(state.id).unwrap(); + units.push(json!({"id": state.id, "position": state.position.map(f64::to_bits), + "hp": state.hp.to_bits(), "cooldown": state.cooldown.to_bits(), "flags": state.flags, + "moving": state.moving, "hidden": state.hidden, "leg": state.route_leg, + "motion": format!("{:?}", unit.motion), "enemy": format!("{:?}", unit.enemy), + "cadence": format!("{:?}", unit.cadence), "attacks": unit.attacks, + "buffs": format!("{:?}", unit.stats.buffs()), "rateDirty": unit.stats.rate_dirty, + "terrain": format!("{:?}", unit.terrain), + "regen": unit.regen_acc.to_bits(), "deployed": unit.deployed, "removed": unit.removed, + "pins": field.core.world.unit_pins(state.id).unwrap()})); + } + let index = field.core.host.index.as_ref().unwrap(); + let occupancy: Vec<_> = (0..super::super::super::grid::N) + .map(|key| { + ( + index.any_enemy(&field.core.world, &[key], false).ok(), + index.any_enemy(&field.core.world, &[key], true).ok(), + ) + }) + .collect(); + json!({"ticks": field.ticks(), "time": field.time().to_bits(), "worldTime": field.core.world.time.to_bits(), + "rng": field.rng_state(), "report": field.report().unwrap(), "units": units, "index": occupancy, + "dp": field.core.host.roster.as_ref().unwrap().dp(1).unwrap().to_bits(), + "pending": field.pending_spawns(), "retained": field.retained_units()}) + } + + #[test] + fn targeting_can_query_routes_while_movement_owns_grid() { + let mut f = field(&input(), 40., false); + f.run(1).unwrap(); + let id = f.enemies()[0]; + f.core + .host + .grid + .as_mut() + .unwrap() + .set_obstacle([10, 4], true, super::super::super::grid::CRATE) + .unwrap(); + let mut grid = f.core.host.take_grid(); + let cached = crate::battle::targeting::Queries::remaining_distance( + &mut f.core.host, + id, + &mut f.core.world, + ) + .unwrap(); + let authoritative = motion::remaining_distance(&mut f.core.world, &mut grid, id).unwrap(); + assert_eq!(cached.to_bits(), authoritative.to_bits()); + f.core.host.grid = Some(grid); + } + + #[test] + fn projectile_kill_can_launch_poison_death_projectile() { + use crate::battle::{ + attacks, damage::DamageType, direction::Direction, operators::Placement, projectiles, + }; + for tactical in [false, true] { + let mut f = field(&input(), 40., false); + let source = f + .add_operator( + "chess_char_1_05_a", + Placement { + uid: 1, + home: [10, 9], + direction: Direction::Right, + }, + ) + .unwrap(); + f.run(1).unwrap(); + let target = f + .spawn("enemy_9006_actoxi", &json!({"pos":[10, 11]})) + .unwrap(); + let position = f.unit(target).unwrap().position; + let deployment = f.unit(source).unwrap().deployment.deploy_seq; + let attack_id = f.core.world.next_attack_id().unwrap(); + f.core + .host + .flights + .as_mut() + .unwrap() + .add( + &mut f.core.world, + projectiles::Launch { + from: position, + source: Some(source), + target: Some(target), + to: None, + speed: 10., + hit_dead: false, + max_age: 10., + on_hit: true, + visual: "arrow".into(), + speed_changeable: None, + removable: None, + payload: if tactical { + allies::Shot::Tactical(super::super::tactics::Arrow { + source, + kind: super::super::tactics::ArrowKind::Snow, + scale: 1., + hits: 1, + seen: [target, 0, 0, 0, 0], + count: 1, + }) + } else { + allies::Shot::Ally { + source, + deployment, + attack_id, + payload: attacks::Direct { + attachment: None, + element_heal_ratio: 0., + mode: attacks::Mode::Damage(DamageType::Physical), + hits: 1, + atk_scale: 1., + skill_damage_mul: 1., + target_damage_mul: 1., + split_mul: None, + heal_scale: 1., + is_skill: false, + }, + area: attacks::Area::default(), + } + }, + }, + ) + .unwrap(); + f.run(1).unwrap(); + assert!(!f.enemies().contains(&target)); + let flights = f.core.host.flights.as_ref().unwrap().list(); + assert!(flights + .iter() + .any(|p| matches!(p.payload, allies::Shot::Cloud(_)))); + assert!(f.core.world.unit_pins(source).unwrap() > 0); + } + } + + #[test] + fn replay_frames_do_not_materialize_dirty_stats() { + let mut observed = field(&input(), 40., true); + let mut reference = field(&input(), 40., true); + for _ in 0..60 { + observed.run(1).unwrap(); + reference.run(1).unwrap(); + for field in [&mut observed, &mut reference] { + let ids = field.enemies().to_vec(); + for id in ids { + field + .core + .world + .unit_mut(id) + .unwrap() + .stats + .edit_base(|base| { + *base.0.entry("maxHp".into()).or_default() += 1.; + }); + } + } + let frame = observed.replay_frame().unwrap(); + assert_eq!(frame["tick"], json!(observed.ticks())); + assert_eq!(observed.replay_frame().unwrap(), frame); + } + assert_eq!(snapshot(&mut observed), snapshot(&mut reference)); + assert_eq!(observed.rng_state(), reference.rng_state()); + } +} diff --git a/crates/engine/src/battle/runtime/movement_paths.rs b/crates/engine/src/battle/runtime/movement_paths.rs new file mode 100644 index 0000000..5af21a6 --- /dev/null +++ b/crates/engine/src/battle/runtime/movement_paths.rs @@ -0,0 +1,288 @@ +//! Per-enemy movement prefixes ending before the first possible interaction. +use super::*; +use crate::battle::{body, grid::N, operators::RangeGeometry, stats::Stat}; +use crate::deterministic::math::round_half_even; +use std::collections::{BTreeMap, VecDeque}; + +struct AllyGeometry { + id: Id, + position: [f64; 2], + tile: [i32; 2], + range: Vec, + geometry: RangeGeometry<'static>, +} + +struct Path { + expected: [f64; 2], + target: [f64; 2], + stride: f64, + version: u64, + leg: usize, + point: usize, + positions: VecDeque<[f64; 2]>, +} + +pub(super) struct MovementPaths { + allies: Vec, + danger: [bool; N], + distance: [f64; N], + paths: BTreeMap, + pub(super) updates: u64, + pub(super) fast_updates: u64, +} +impl Default for MovementPaths { + fn default() -> Self { + Self { + allies: Vec::new(), + danger: [false; N], + distance: [f64::INFINITY; N], + paths: BTreeMap::new(), + updates: 0, + fast_updates: 0, + } + } +} + +fn key(position: [f64; 2]) -> Option { + let [r, c] = position.map(round_half_even); + (r.is_finite() + && c.is_finite() + && r >= 0. + && r < super::super::grid::ROWS as f64 + && c >= 0. + && c < COLS as f64) + .then(|| r as usize * COLS + c as usize) +} + +impl MovementPaths { + pub(super) fn refresh(&mut self, h: &Host, w: &World) -> Result<(), String> { + let roster = h.roster.as_ref().unwrap(); + let mut count = 0; + let mut changed = false; + for &id in roster.ids() { + let unit = w.unit(id)?; + if unit.stats.alive && unit.deployed && !unit.hidden { + let geometry = roster.range_geometry(w, id)?; + changed |= self.allies.get(count).is_none_or(|old| { + old.id != id + || old.position != unit.position + || old.tile != unit.deployment.tile + || old.geometry != geometry + }); + count += 1; + } + } + if !changed && count == self.allies.len() { + return Ok(()); + } + let mut allies = Vec::new(); + for &id in roster.ids() { + let unit = w.unit(id)?; + if unit.stats.alive && unit.deployed && !unit.hidden { + let geometry = roster.range_geometry(w, id)?; + allies.push(AllyGeometry { + id, + position: unit.position, + tile: unit.deployment.tile, + range: geometry.keys(), + geometry: geometry.owned(), + }); + } + } + self.paths.clear(); + self.danger.fill(false); + self.distance.fill(f64::INFINITY); + for ally in &allies { + // Include collider overlap and every tile searched by blocking::check. + for &tile in &ally.range { + if let Some(danger) = self.danger.get_mut(tile) { + *danger = true; + } + } + if Grid::in_bounds(ally.tile) { + let tile = ally.tile[0] as usize * COLS + ally.tile[1] as usize; + let (r, c) = (tile / COLS, tile % COLS); + for row in r.saturating_sub(1)..=(r + 1).min(super::super::grid::ROWS - 1) { + for col in c.saturating_sub(1)..=(c + 1).min(COLS - 1) { + self.danger[row * COLS + col] = true; + } + } + } + for (tile, distance) in self.distance.iter_mut().enumerate() { + // Distance to the entire cell is a lower bound for every centre in it. + let dy = ((tile / COLS) as f64 - ally.position[0]).abs(); + let dx = ((tile % COLS) as f64 - ally.position[1]).abs(); + let dy = (dy - 0.5).max(0.); + let dx = (dx - 0.5).max(0.); + *distance = distance.min(dx * dx + dy * dy); + } + } + self.allies = allies; + Ok(()) + } + + pub(super) fn clear_at(&self, position: [f64; 2], radius_squared: f64) -> bool { + let mut clear = true; + body::enemy_collider_keys(position, |key| clear &= !self.danger[key]); + key(position).is_some_and(|key| clear && self.distance[key] > radius_squared) + } + + pub(super) fn retain_live(&mut self, w: &World) { + self.paths + .retain(|&id, _| w.unit(id).is_ok_and(|u| u.stats.alive && !u.removed)); + } + + pub(super) fn step( + &mut self, + w: &mut World, + h: &mut Host, + grid: &Grid, + id: Id, + map_dirty: &mut bool, + ) -> Result { + self.updates = self.updates.saturating_add(1); + let time = w.time; + let u = w.unit_mut(id)?; + let Some(cell) = key(u.position) else { + return Ok(false); + }; + // A stale exclusion can only choose the full update. Every accepted step + // refreshes dirty geometry below before using a cached prefix. + if self.danger[cell] { + return Ok(false); + } + let base_radius = u.stats.base_number("rangeRadius") + 0.25; + if self.distance[cell] <= base_radius * base_radius + 1e-9 { + return Ok(false); + } + if !u.stats.alive + || !u.deployed + || u.hidden + || u.removed + || u.pool.is_some() + || u.hit_area.is_some() + || u.blocked_by().is_some() + || u.enemy.carrier.is_some() + || u.enemy.swing + || u.enemy.targets().is_some() + || u.enemy.pause_until > time + || u.motion.attack_stand_until > time + || u.motion.unbalance_until > time + || u.motion.fear.is_some() + { + self.paths.remove(&id); + return Ok(false); + } + let stats = u.stats.stats().map_err(str::to_string)?; + let stride = stats.get(Stat::MoveSpeed) * 0.5 * DT; + if !stats.flags.is_empty() || !stride.is_finite() || stride <= 1e-9 { + self.paths.remove(&id); + return Ok(false); + } + let Some(route) = u.motion.route.as_ref() else { + return Ok(false); + }; + let Some(target) = route + .points + .as_ref() + .and_then(|points| points.get(route.point)) + .copied() + else { + return Ok(false); + }; + let rect = grid.rect(); + if route.version != grid.version() + || route.wait_left.is_some() + || route.patrol + || !matches!(route.legs().get(route.leg), Some(motion::Leg::Move { .. })) + || !u + .position + .iter() + .chain(target.iter()) + .all(|n| n.is_finite()) + || u.position[0] < rect.r0 as f64 + || u.position[0] > rect.r1 as f64 + || u.position[1] < rect.c0 as f64 + || u.position[1] > rect.c1 as f64 + || target[0] < rect.r0 as f64 + || target[0] > rect.r1 as f64 + || target[1] < rect.c0 as f64 + || target[1] > rect.c1 as f64 + { + return Ok(false); + } + let (position, leg, point) = (u.position, route.leg, route.point); + let profile = enemy::Hooks::profile(h, id, w)?; + if matches!(profile.mode, enemy::Mode::Heal) { + return Ok(false); + } + let radius = + if profile.melee || profile.no_attack || matches!(profile.mode, enemy::Mode::None) { + 0. + } else { + w.unit(id)?.stats.base_number("rangeRadius") + 0.25 + }; + if !radius.is_finite() { + return Ok(false); + } + if *map_dirty { + self.refresh(h, w)?; + *map_dirty = false; + } + let radius_squared = radius * radius + 1e-9; + if !self.clear_at(position, radius_squared) { + return Ok(false); + } + let valid = self.paths.get(&id).is_some_and(|p| { + p.expected.map(f64::to_bits) == position.map(f64::to_bits) + && p.target.map(f64::to_bits) == target.map(f64::to_bits) + && p.stride.to_bits() == stride.to_bits() + && p.version == grid.version() + && p.leg == leg + && p.point == point + && !p.positions.is_empty() + }); + if !valid { + let mut path = Path { + expected: position, + target, + stride, + version: grid.version(), + leg, + point, + positions: VecDeque::new(), + }; + let mut next = position; + // Bound storage by 32 positions per live enemy, independent of episode length. + for _ in 0..32 { + let (position, _, reached, _) = motion::step_position(next, target, stride); + if reached || !self.clear_at(position, radius_squared) { + break; + } + path.positions.push_back(position); + next = position; + } + self.paths.insert(id, path); + } + let path = self.paths.get_mut(&id).unwrap(); + let Some(next) = path.positions.pop_front() else { + return Ok(false); + }; + let unit = w.unit_mut(id)?; + unit.position = next; + unit.moving = true; + unit.cadence.tick(DT, true); + path.expected = next; + self.fast_updates = self.fast_updates.saturating_add(1); + Ok(true) + } +} + +impl Field { + pub fn movement_path_steps(&self) -> [u64; 2] { + [ + self.core.movement_paths.fast_updates, + self.core.movement_paths.updates, + ] + } +} diff --git a/crates/engine/src/battle/runtime/settlement_hooks.rs b/crates/engine/src/battle/runtime/settlement_hooks.rs new file mode 100644 index 0000000..07b4d84 --- /dev/null +++ b/crates/engine/src/battle/runtime/settlement_hooks.rs @@ -0,0 +1,776 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Battle host adapters for damage settlement, status and elemental effects. +use super::*; + +impl Host { + pub(super) fn resolve_hit( + &mut self, + world: &mut World, + buffs: &mut buffs::Runtime, + request: &mut hit::Request, + ) -> Result { + let mut rng = self.rng.clone(); + let result = settlement::resolve(world, buffs, &mut rng, self, request); + // Publish draws consumed before an error as well as successful draws. + self.rng = rng; + result + } +} + +impl settlement::Hooks for Host { + fn damage_cleanup( + &mut self, + token: u64, + target: Id, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + r.remove_id(w, self, target, token)?; + Ok(()) + } + + fn injury( + token: u64, + e: &mut super::super::injury::InjuryEvent, + c: &mut settlement::Context<'_, Self>, + ) -> Result<(), String> { + if token == super::super::equipment::FIXED_REDUCTION { + e.amount = (e.amount + - c.runtime + .get(c.world, c.request.hit.target, c.buff)? + .runtime + .tick_payload) + .max(0.); + return Ok(()); + } + if token == super::super::content::enemies::bosses::gun::SPRING_SHIELD { + return Self::spring_injury(e, c); + } + if token == enemies::ARTS_BARRIER { + return Self::enemy_barrier_injury(e, c); + } + if token == kits::excu2::DODGE { + return Self::excu2_injury(c, e); + } + if token == kits::tippi::EVADE { + return Self::tippi_injury(e, c); + } + if token == tactics::WITHER { + return Self::tactical_wither(e, c); + } + if token == advanced::FLAME_EVADE { + return Self::advanced_evade(e, c); + } + if token != super::super::content::operators::ARMOR_BLOCK { + return Err("Unknown operator injury callback".into()); + } + let probability = c + .runtime + .get(c.world, c.request.hit.target, c.buff)? + .runtime + .tick_payload; + c.block(e, Some(probability))?; + Ok(()) + } + fn observe( + token: u64, + event: super::super::injury::Observation, + c: &mut settlement::Context<'_, Self>, + ) -> Result<(), String> { + if matches!( + token, + super::super::content::enemies::bosses::gun::SPRING_SHIELD + | super::super::content::enemies::bosses::gun::SPRING_SHARE + ) { + return Self::spring_observe(token, event, c); + } + if token == kits::tippi::OBSERVER { + return Self::tippi_observe(c); + } + if token == tactics::OBSERVE { + return Self::kit_observe(c); + } + if token == super::super::content::operators::PROTEGE_COUNTER { + Self::support_counter(c) + } else { + Self::component_observe(c, token) + } + } + + fn damage_notice( + &mut self, + notice: super::super::injury::Notice, + _expected: f64, + q: &mut hit::Request, + _r: &mut buffs::Runtime, + w: &mut World, + _rng: &mut Rng, + ) -> Result<(), String> { + self.advanced_notice(notice, q, w) + } + fn phase_enabled(&self, p: hit::Phase) -> bool { + matches!( + p, + hit::Phase::Hit | hit::Phase::Calculate | hit::Phase::Output | hit::Phase::Applying + ) || p == hit::Phase::BeforeApply && self.equipment.pegasus_damage + || p == hit::Phase::HpDamage && self.bonds_has_share() + } + fn damage_phase( + &mut self, + p: hit::Phase, + q: &mut hit::Request, + amount: &mut f64, + r: &mut buffs::Runtime, + w: &mut World, + rng: &mut Rng, + ) -> Result<(), String> { + if p == hit::Phase::Hit { + self.bonds_hit(w, q)?; + self.growth_hit(w, q)?; + } + if p == hit::Phase::HpDamage { + self.rng = rng.clone(); + let result = self.bond_share(w, r, q, amount); + *rng = self.rng.clone(); + return result; + } + if p == hit::Phase::BeforeApply { + self.rng = rng.clone(); + let result = self.equipment_before_apply(w, r, q); + *rng = self.rng.clone(); + return result; + } + if p == hit::Phase::Hit { + // Profession attack scales form the input to weakness conversion. + if q.is_attack && w.unit(q.hit.target)?.side == health::Side::Enemy { + if let Some(id) = q.hit.source { + if w.unit(id)?.has_operator_kit() { + let entry = self.roster.as_ref().unwrap().entry(id)?; + if matches!( + entry.definition.hit, + super::super::content::operators::HitHandler::Blocked { .. } + ) { + entry.definition.hit.apply(w, id, entry.direction, q, rng)?; + } + } + } + } + self.equipment_retype(w, q)?; + self.rng = rng.clone(); + self.enemy_content_hit(w, q, r)?; + *rng = self.rng.clone(); + } + self.advanced_phase(p, q, r, w)?; + self.rng = rng.clone(); + self.kit_hit_phase(w, r, p, q)?; + *rng = self.rng.clone(); + self.support_phase(p, q, *amount, r, w, rng)?; + self.component_phase(p, q, r, w, rng)?; + if p == hit::Phase::Hit { + self.equipment_hit(w, q)?; + } + if p == hit::Phase::Hit + && w.unit(q.hit.target)?.side == health::Side::Ally + && w.unit(q.hit.target)?.deployment.kind != super::super::deploy::Kind::Device + { + let def = Arc::clone( + &self + .roster + .as_ref() + .unwrap() + .entry(q.hit.target)? + .definition, + ); + def.extra.protect(w, r, self, q.hit.target)?; + } + if let Some(source) = q + .hit + .source + .filter(|&id| w.unit(id).is_ok_and(|u| u.has_operator_kit())) + { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(source)?.definition); + if p == hit::Phase::Hit + && q.is_attack + && def.extra.skill_arts + && q.hit.damage_type == super::super::damage::DamageType::Physical + && w.unit(source)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(format!("skill:{source}").as_str())) + { + q.hit.damage_type = super::super::damage::DamageType::Arts; + } + if p == hit::Phase::Hit + && w.unit(q.hit.target)?.side == health::Side::Enemy + && q.hit.damage_type != super::super::damage::DamageType::Elemental + && !q.tags.iter().any(|t| t == "dot") + && !def.extra.tag_scale.is_empty() + { + let key = &self.spawns.as_ref().unwrap().definition(q.hit.target)?.key; + let tags = &self.data.table("enemies").unwrap()[key]["tags"]; + for (tag, scale) in &def.extra.tag_scale { + if tags.as_array().is_some_and(|a| a.iter().any(|x| x == tag)) { + q.damage.amount *= scale; + } + } + } + if p == hit::Phase::Calculate + && def.extra.weakness + && w.unit(q.hit.target)?.side == health::Side::Enemy + && matches!( + q.hit.damage_type, + super::super::damage::DamageType::Physical + | super::super::damage::DamageType::Arts + ) + { + let ss = w + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .clone(); + let ts = w + .unit_mut(q.hit.target)? + .stats + .stats() + .map_err(str::to_string)? + .clone(); + let mut ign = q.damage.penetration; + ign.def_flat += ss.n("defIgnoreFlat"); + ign.def_pct += ss.n("defIgnorePct"); + ign.res_flat += ss.n("resIgnoreFlat"); + ign.res_pct += ss.n("resIgnorePct"); + let ph = super::super::damage::mitigate( + super::super::damage::attack_input( + q.damage.amount, + super::super::damage::DamageType::Physical, + &ts, + ), + super::super::damage::DamageType::Physical, + &ts, + ign, + 0., + ); + let ar = super::super::damage::mitigate( + super::super::damage::attack_input( + q.damage.amount, + super::super::damage::DamageType::Arts, + &ts, + ), + super::super::damage::DamageType::Arts, + &ts, + ign, + 0., + ); + if ar > ph + 1e-9 { + q.hit.damage_type = super::super::damage::DamageType::Arts; + } else if ph > ar + 1e-9 { + q.hit.damage_type = super::super::damage::DamageType::Physical; + } + } + if p == hit::Phase::Calculate + && w.unit(q.hit.target)?.stats.alive + && w.unit(q.hit.target)?.stats.hp > 0. + && w.unit(q.hit.target)?.side == health::Side::Enemy + { + if let Some(lord) = def + .extra + .lord + .filter(|l| l.arts > 0. && !q.tags.iter().any(|t| t == "ayerBlade")) + { + let value = w + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * lord.arts + * if q.is_skill || w.unit(source)?.operator.active_skill { + def.extra.effects.lord_skill_scale + } else { + 1. + } + * if w.unit(q.hit.target)?.boss || w.unit(q.hit.target)?.targeting.elite { + def.extra.support.elite_scale.unwrap_or(1.) + } else { + 1. + }; + let mut child = hit::Request::new( + health::Hit { + source: Some(source), + credit: Some(source), + target: q.hit.target, + damage_type: super::super::damage::DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + super::super::damage::Damage { + amount: value, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + child.calculation = hit::Calculation::Precomputed; + child.attack_type = hit::AttackType::Addition; + child.tags = vec!["module".into(), "addition".into()]; + settlement::resolve(w, r, rng, self, &mut child)?; + } + } + if p == hit::Phase::Output + && *amount > 0. + && def.extra.self_heal > 0. + && w.unit(source)?.stats.alive + && w.unit(q.hit.target)?.side == health::Side::Enemy + && !q.hit.hp_loss + && q.hit.damage_type != super::super::damage::DamageType::Elemental + { + health::heal( + w, + self, + Some(source), + source, + def.extra.self_heal, + health::HealOptions { + self_heal: true, + ignore_heal_free: true, + ..Default::default() + }, + )?; + } + } + if p == hit::Phase::Hit + && w.unit(q.hit.target)?.side == health::Side::Ally + && w.unit(q.hit.target)?.deployment.kind != super::super::deploy::Kind::Device + { + let effect = self + .roster + .as_ref() + .ok_or("Missing defensive content context")? + .entry(q.hit.target)? + .definition + .incoming_hit; + if let Some(effect) = effect { + effect.apply(w, q)?; + } + } + if p == hit::Phase::Hit && q.is_attack && w.unit(q.hit.target)?.side == health::Side::Enemy + { + if let Some(id) = q.hit.source { + if w.unit(id)?.has_operator_kit() { + let entry = self + .roster + .as_ref() + .ok_or("Missing operator hit context")? + .entry(id)?; + if !matches!( + entry.definition.hit, + super::super::content::operators::HitHandler::Blocked { .. } + ) { + entry.definition.hit.apply(w, id, entry.direction, q, rng)?; + } + } + } + } + if p == hit::Phase::Hit { + self.enemy_chalice_share(w, r, q)?; + self.gun_confession(w, r, q.hit.target)?; + self.enemy_boss_in(w, q)?; + self.enemy_reaction_in(w, q)?; + self.enemy_terrain_in(q); + self.enemy_special_in(w, r, q)?; + } + Ok(()) + } + fn damage_kill( + &mut self, + target: Id, + credit: Option, + r: &mut buffs::Runtime, + w: &mut World, + rng: &mut Rng, + ) -> Result<(), String> { + self.rng = rng.clone(); + let result = self.health_kill(target, credit, r, w); + *rng = self.rng.clone(); + result + } + fn health_kill( + &mut self, + id: Id, + credit: Option, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + if w.unit(id)?.deployment.kind == super::super::deploy::Kind::Device { + return self.kill_device(w, r, id, credit); + } + if w.unit(id)?.side == health::Side::Enemy { + return self.kill_enemy(id, credit, r, w); + } + let mut roster = self.roster.take().ok_or("Missing operator death context")?; + let result = roster.kill(w, r, self, id, credit); + self.roster = Some(roster); + result?; + self.bonds_aura(w, r)?; + self.enemy_other_death(w, r, id)?; + self.kit_event(w, r, &mut kits::dispatch::Event::Death { unit: id, credit })?; + self.flush_kit_events(w, r) + } + fn health_event( + &mut self, + e: &mut health::Event, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + if w.unit(e.target)?.deployment.kind == super::super::deploy::Kind::Device { + return Ok(()); + } + self.component_fatal(e, r, w)?; + self.advanced_fatal(e, r, w)?; + if e.stage == health::Stage::ModifierApplied { + self.spring_modifier(w, r, e.target, e.source, e.credit, e.amount)?; + } + if e.stage == health::Stage::Fatal + && w.unit(e.target)?.side == health::Side::Ally + && w.unit(e.target)?.deployment.kind != crate::battle::deploy::Kind::Device + { + let def = &self + .roster + .as_ref() + .ok_or("Missing fatal content context")? + .entry(e.target)? + .definition; + if def.undying + && w.unit(e.target)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(format!("skill:{}", e.target).as_str())) + { + e.prevented = true; + } + } + if e.stage == health::Stage::Fatal { + self.kit_unit_event( + w, + r, + e.target, + kits::dispatch::Role::Target, + &mut kits::dispatch::Event::Fatal(e), + )?; + self.kit_event(w, r, &mut kits::dispatch::Event::Fatal(e))?; + } + if e.stage == health::Stage::SkillDamaged { + let mut roster = self + .roster + .take() + .ok_or("Missing operator damage context")?; + let result = roster.damaged(w, r, self, e.target); + self.roster = Some(roster); + result?; + self.advanced_flush_starts(w, r)?; + } + Ok(()) + } + fn damage_health_event( + &mut self, + e: &mut health::Event, + q: &mut hit::Request, + r: &mut buffs::Runtime, + w: &mut World, + rng: &mut Rng, + ) -> Result<(), String> { + if e.stage == health::Stage::OnApplied { + self.spring_counter_applied(w, r, q)?; + } + if e.stage == health::Stage::DamageApplied { + self.support_damage_applied(e, q, r, w)?; + self.kit_damage_applied(w, r, e, q)?; + } + if e.stage == health::Stage::Damaged { + self.rng = rng.clone(); + self.enemy_content_taken(w, r, q, e.amount)?; + self.enemy_content_dealt(w, r, q)?; + *rng = self.rng.clone(); + let result = self.advanced_landed(e, q, r, w); + *rng = self.rng.clone(); + result?; + self.support_landed(e, q, r, w)?; + self.rng = rng.clone(); + let result = self.kit_landed(w, r, e, q); + *rng = self.rng.clone(); + result?; + self.component_landed(e, q, r, w)?; + self.rng = rng.clone(); + let result = self.bonds_landed(w, r, q); + *rng = self.rng.clone(); + result?; + self.rng = rng.clone(); + let result = self.equipment_landed(w, r, e, q); + *rng = self.rng.clone(); + result?; + self.choices_damaged(w, r, e, q)?; + if e.amount > 0. + && !q.hit.no_sp + && q.hit.damage_type != super::super::damage::DamageType::Elemental + && w.unit(e.target)?.side == health::Side::Ally + && w.unit(e.target)?.deployment.kind != crate::battle::deploy::Kind::Device + && w.unit(e.target)?.stats.alive + && w.unit(e.target)?.deployed + { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(e.target)?.definition); + if let Some(talent) = &def.extra.sp_hurt { + let source = e.target; + let entry = self.roster.as_ref().unwrap().entry(source)?; + let keys = super::super::targeting::absolute_range( + &talent.grid, + w.unit(source)?.deployment.tile, + entry.direction, + 0, + ); + let ids = self.roster.as_ref().unwrap().ids().to_vec(); + let mut mates = Vec::new(); + for id in ids { + if id != source + && super::super::targeting::aura_selectable(w, id)? + && super::super::body::in_range(w.unit(id)?, &keys) + && !self + .roster + .as_ref() + .unwrap() + .entry(id)? + .skill()? + .bank + .no_skill + { + mates.push(id); + } + } + let mut roster = self.roster.take().unwrap(); + let result = roster.grant_sp(w, r, self, source, talent.amount); + self.roster = Some(roster); + result?; + if let Some(&mate) = rng.pick(&mates) { + let mut roster = self.roster.take().unwrap(); + let result = roster.grant_sp(w, r, self, mate, talent.amount); + self.roster = Some(roster); + result?; + } + } + } + if q.is_attack + && w.unit(e.target)?.side == health::Side::Enemy + && w.unit(e.target)?.stats.alive + { + if let Some(source) = q + .hit + .source + .filter(|&s| w.unit(s).is_ok_and(|u| u.has_operator_kit())) + { + if let Some(dot) = self + .roster + .as_ref() + .unwrap() + .entry(source)? + .definition + .extra + .dot + .filter(|d| d.duration > 0. && d.amount > 0.) + { + let key = &self.spawns.as_ref().unwrap().definition(e.target)?.key; + let sea = self.data.table("enemies").unwrap()[key]["tags"] + .as_array() + .is_some_and(|t| t.iter().any(|x| x == "seamonster")); + let mut b = super::super::stats::Buff { + key: Some(format!("udflow:dot:{source}")), + ..Default::default() + }; + b.runtime.duration = dot.duration; + b.runtime.interval = dot.interval; + b.runtime.source = Some(source); + b.runtime.refresh = buffs::Refresh::Extend; + b.runtime.on_tick = Some(super::super::content::operators::DOT); + b.runtime.tick_payload = if sea { dot.sea } else { dot.amount }; + r.add( + w, + self, + e.target, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + } + } + + if e.hp_removed > 0. + && w.unit(e.target)?.side == health::Side::Enemy + && w.unit(e.target)?.stats.hp > 0. + && q.hit.damage_type != super::super::damage::DamageType::Elemental + && !q.tags.iter().any(|t| t == "burst") + { + if let Some(source) = q.hit.source { + if w.unit(source)?.has_operator_kit() { + let attach = self + .roster + .as_ref() + .ok_or("Missing elemental talent context")? + .entry(source)? + .definition + .element_attach; + if let Some(attach) = attach { + let ratio = if w.unit(e.target)?.element_leader { + attach.leader + } else { + attach.normal + }; + let amount = w + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * ratio; + for element in [ + super::super::element::Element::Neural, + super::super::element::Element::Burn, + super::super::element::Element::Apoptosis, + ] { + let mut effect = super::super::element::Request::new( + Some(source), + Some(source), + e.target, + element, + amount, + ); + effect.damage.tags = vec!["talent".into(), "pithst".into()]; + self.rng = rng.clone(); + let result = super::super::element::apply(w, self, r, &mut effect); + *rng = self.rng.clone(); + result?; + } + } + } + } + } + if let Some(mut effect) = self.content.as_ref().unwrap().damaged(w, q)? { + self.rng = rng.clone(); + let result = super::super::element::apply(w, self, r, &mut effect); + *rng = self.rng.clone(); + result?; + } + } + self.rng = rng.clone(); + let result = self.health_event(e, r, w); + *rng = self.rng.clone(); + result + } +} + +impl super::super::status::Hooks for Host { + fn has_before_status(&self) -> bool { + true + } + fn before_status( + &mut self, + context: &mut super::super::status::Context, + buffs: &mut buffs::Runtime, + world: &mut World, + ) -> Result<(), String> { + self.enemy_special_before_status(context); + self.enemy_caster_before_status(context); + self.kit_event( + world, + buffs, + &mut kits::dispatch::Event::BeforeStatus(context), + )?; + self.equipment_before_status(world, context) + } + fn has_status_applied(&self) -> bool { + true + } + fn status_applied( + &mut self, + c: &super::super::status::Context, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + self.growth_status(w, c)?; + self.enemy_movement_status(w, r, c)?; + self.kit_event(w, r, &mut kits::dispatch::Event::Status(c))?; + self.kit_event(w, r, &mut kits::dispatch::Event::StatusFinished(c))?; + self.advanced_status_applied(c, w) + } +} + +impl super::super::element::Hooks for Host { + fn battle_rect(&self) -> Rect { + self.rect + } + fn element_enabled(&self, phase: super::super::element::Phase) -> bool { + matches!( + phase, + super::super::element::Phase::Hit + | super::super::element::Phase::Burst + | super::super::element::Phase::ModifierApplied + ) + } + fn element_event( + &mut self, + phase: super::super::element::Phase, + request: &mut super::super::element::Request, + amount: f64, + _: f64, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + if phase == super::super::element::Phase::ModifierApplied { + return self.spring_modifier( + w, + r, + request.damage.hit.target, + request.damage.hit.source, + request.damage.hit.credit, + amount, + ); + } + if phase == super::super::element::Phase::Burst { + self.spring_element_burst(w, r, request.damage.hit.target)?; + } + if phase == super::super::element::Phase::Hit + && request.damage.element == Some(super::super::element::Element::Erosion) + && w.unit(request.damage.hit.target)?.boss + { + request.damage.cancelled = true; + } + self.enemy_parasite_element(w, r, phase, request)?; + self.kit_event(w, r, &mut kits::dispatch::Event::Element { phase, request })?; + if phase != super::super::element::Phase::Hit { + return Ok(()); + } + self.kit_element(w, r, request)?; + self.advanced_element(request, w)?; + self.kit_event(w, r, &mut kits::dispatch::Event::ElementLate(request)) + } + fn element_number( + &mut self, + _: Id, + _: f64, + _: super::super::element::Element, + ) -> Result<(), String> { + Ok(()) + } + fn burst_visual( + &mut self, + _: Id, + _: super::super::element::Element, + _: &World, + ) -> Result<(), String> { + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/support.rs b/crates/engine/src/battle/runtime/support.rs new file mode 100644 index 0000000..32b9f9d --- /dev/null +++ b/crates/engine/src/battle/runtime/support.rs @@ -0,0 +1,1964 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Native execution of healer and support components, sharing canonical buffs. +use super::super::{ + attacks, body, + content::operators::*, + damage::{Damage, DamageType}, + direction::Direction, + displacement, + health::HealOptions, + hit, + operators::Definition, + search, skills, + stats::{Buff, Numbers}, + targeting, +}; +use super::*; +use crate::deterministic::math::hypot; +pub(super) struct ZoneState { + source: Id, + position: [f64; 2], + damage: f64, + left: u32, + next: f64, +} +struct Healing<'a> { + options: HealOptions, + host: &'a mut Host, + buffs: &'a mut buffs::Runtime, +} +impl health::Hooks for Healing<'_> { + fn adjust_heal( + &mut self, + source: Option, + target: Id, + amount: f64, + options: HealOptions, + w: &mut World, + ) -> Result { + self.host + .support_heal_amount(w, source, target, amount, options) + } + fn emit(&mut self, e: &mut health::Event, w: &mut World) -> Result<(), String> { + if e.stage == health::Stage::Heal { + self.host.kit_heal_event(w, self.buffs, e, self.options)?; + self.host + .support_overflow(w, self.buffs, e.target, e.amount)?; + if e.amount > 0. && !self.options.regen { + self.buffs.remove(w, self.host, e.target, "ab:bleed")?; + } + } + if e.stage == health::Stage::Damaged && e.kind == health::Kind::HpLoss { + self.host + .helm_taken(w, self.buffs, e.target, e.source, e.credit, e.amount)?; + self.host + .echo_taken(w, self.buffs, e.target, e.source, e.credit)?; + } + settlement::Hooks::health_event(self.host, e, self.buffs, w) + } + fn kill(&mut self, target: Id, credit: Option, w: &mut World) -> Result<(), String> { + settlement::Hooks::health_kill(self.host, target, credit, self.buffs, w) + } +} +impl spatial::Healing for Host { + fn heal_through(&mut self, _: Id, _: Id, _: &mut World) -> Result { + Ok(false) + } +} +impl Host { + pub(super) fn support_trigger_range( + &self, + w: &World, + id: Id, + def: &Definition, + ) -> Result, String> { + if let Some(grid) = &def.trigger_range { + let dir = self + .roster + .as_ref() + .ok_or("Missing trigger roster")? + .entry(id)? + .direction; + Ok(targeting::absolute_range( + grid, + w.unit(id)?.deployment.tile, + dir, + 0, + )) + } else { + self.roster + .as_ref() + .ok_or("Missing trigger roster")? + .range(w, id) + } + } + fn support_allies(&self, w: &mut World, source: Id) -> Result, String> { + let roster = self.roster.as_ref().ok_or("Missing support roster")?; + let keys = roster.range(w, source)?; + let mut ids = Vec::new(); + for &id in roster.ids() { + if targeting::friendly_selectable(w, source, id)? && body::in_range(w.unit(id)?, &keys) + { + ids.push(id); + } + } + Ok(ids) + } + fn support_top(&self, w: &mut World, source: Id) -> Result, String> { + let mut candidates = Vec::new(); + for id in self.support_allies(w, source)? { + let u = w.unit_mut(id)?; + candidates.push(( + id, + u.stats.stats().map_err(str::to_string)?.n("maxHp"), + u.deployment.deploy_seq, + )); + } + candidates.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.2.cmp(&b.2))); + Ok(candidates.first().map(|x| x.0)) + } + pub(super) fn support_heal_amount( + &self, + w: &mut World, + source: Option, + target: Id, + mut amount: f64, + options: HealOptions, + ) -> Result { + if let Some(source) = source.filter(|&id| w.unit(id).is_ok_and(|u| u.has_operator_kit())) { + let def = self.tac_def(source)?; + if let Some(kit) = def.extra.tactics.behavior() { + amount *= kit.heal_multiplier(w, target)?; + } + } + if options.regen || options.restore { + return Ok(amount); + } + let roster = self.roster.as_ref().ok_or("Missing heal content context")?; + let max = w + .unit_mut(target)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp"); + let ratio = if max > 0. { + w.unit(target)?.stats.hp / max + } else { + 0. + }; + if w.unit(target)?.side == health::Side::Ally { + let support = &roster.entry(target)?.definition.extra.support; + if let Some(bonus) = &support.received_heal { + amount *= if ratio < bonus.below { + bonus.low + } else { + bonus.normal + }; + } + } + // Installation order governs multiple copies of the same external modifier. + for &id in roster.ids() { + let u = w.unit(id)?; + let support = &roster.entry(id)?.definition.extra.support; + if u.stats.alive + && u.deployed + && support.top_heal != 0. + && support.top_heal != 1. + && self.support_top(w, id)? == Some(target) + { + amount *= support.top_heal; + } + if source == Some(id) { + // Installed module heal modifiers also apply to lingering off-field heals. + if let Some(bonus) = support.heal_bonus { + let active = w.unit(id)?.operator.active_skill; + let guardian = roster.entry(id)?.definition.profession == "TANK"; + if (!guardian || active && !options.self_heal) + && (ratio < bonus.below || bonus.inclusive && ratio <= bonus.below) + { + amount *= bonus.scale; + } + } + } + } + self.kit_heal_amount(w, source, target, amount, options) + } + fn support_overflow( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + amount: f64, + ) -> Result<(), String> { + if w.unit(id)?.side != health::Side::Ally { + return Ok(()); + } + let ratio = self + .roster + .as_ref() + .ok_or("Missing overflow roster")? + .entry(id)? + .definition + .extra + .support + .overflow; + if ratio <= 0. || amount <= 0. { + return Ok(()); + } + let max = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp"); + let excess = amount - (max - w.unit(id)?.stats.hp); + if excess <= 0. { + return Ok(()); + } + let have = w + .unit(id)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("humus:recycle")) + .map(|b| b.shield) + .unwrap_or(0.); + let value = (have + excess).min(max * ratio); + if value <= have + 1e-6 { + return Ok(()); + } + let mut b = Buff { + key: Some("humus:recycle".into()), + shield: value, + ..Default::default() + }; + b.runtime.source = Some(id); + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + Ok(()) + } + pub(super) fn support_heal( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Option, + target: Id, + amount: f64, + opts: HealOptions, + ) -> Result { + health::heal( + w, + &mut Healing { + options: opts, + host: self, + buffs: r, + }, + source, + target, + amount, + opts, + ) + } + pub(super) fn lose_hp_with_credit( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + hit: health::Hit, + amount: f64, + no_limit: bool, + ) -> Result { + health::lose_hp( + w, + &mut Healing { + options: HealOptions::default(), + host: self, + buffs: r, + }, + hit, + amount, + Default::default(), + no_limit, + ) + } + pub(super) fn support_lose_hp( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + amount: f64, + source: Option, + silent: bool, + ) -> Result<(), String> { + self.lose_hp_with_credit( + w, + r, + health::Hit { + source, + credit: source, + target: id, + damage_type: DamageType::True, + no_sp: true, + silent, + hp_loss: true, + on_applied: false, + }, + amount, + false, + )?; + Ok(()) + } + pub(super) fn support_drain( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + token: u64, + ) -> Result<(), String> { + let mut amount = r.get(w, c.unit, c.buff)?.runtime.tick_payload; + if token == PLASMA_DRAIN { + amount *= w + .unit_mut(c.unit)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp"); + } + health::lose_hp( + w, + &mut Healing { + options: HealOptions::default(), + host: self, + buffs: r, + }, + health::Hit { + source: None, + credit: None, + target: c.unit, + damage_type: DamageType::True, + no_sp: true, + silent: false, + hp_loss: true, + on_applied: false, + }, + amount, + Default::default(), + false, + )?; + Ok(()) + } + fn support_status( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + key: &str, + duration: f64, + value: Option, + ) -> Result<(), String> { + if w.unit(target)?.stats.alive && duration > 0. { + self.apply_status( + w, + r, + target, + key, + super::super::status::Options { + duration, + value, + source: Some(source), + ..Default::default() + }, + )?; + } + Ok(()) + } + fn support_damage( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + source: Id, + target: Id, + amount: f64, + tag: &str, + ) -> Result { + let mut q = hit::Request::new( + health::Hit { + source: Some(source), + credit: Some(source), + target, + damage_type: DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.is_skill = true; + q.tags = vec!["skill".into(), tag.into()]; + if tag == "zone" { + q.dodge_mode = super::super::injury::DodgeMode::Ignore; + q.tags.push("dot".into()); + } + self.resolve_hit(w, r, &mut q) + } + fn support_enemy_aura( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + a: &EnemyAura, + ) -> Result<(), String> { + let up = w.unit(id)?.stats.alive && w.unit(id)?.deployed; + let active = w.unit(id)?.operator.active_skill; + let on = up && (!a.active_only || active); + let keys = if on { + self.roster + .as_ref() + .ok_or("Missing aura roster")? + .range(w, id)? + } else { + vec![] + }; + let all: Vec<_> = w.unit_ids().collect(); + for target in all { + if w.unit(target)?.side != health::Side::Enemy { + continue; + } + let u = w.unit_mut(target)?; + let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + let filter = match a.filter { + AuraFilter::All => true, + AuraFilter::Normal => !u.boss && !u.targeting.elite, + AuraFilter::LowHp(h) => max > 0. && u.stats.hp / max < h, + }; + if on && u.stats.alive && !u.hidden && filter && body::in_range(u, &keys) { + let mut mods = a.mods.clone(); + if a.growth.is_some() { + if let Some(value) = mods.get_mut("dmgTakenMul") { + *value = 1. + (*value - 1.) * w.unit(id)?.operator.support.fragile_scale; + } + } + let mut b = Buff { + key: Some(a.key.into()), + mods, + ..Default::default() + }; + b.runtime.duration = (a.period * 2.).max(0.1) + 0.05; + b.runtime.refresh = buffs::Refresh::Extend; + b.runtime.source = Some(id); + r.add( + w, + self, + target, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } else if w + .unit(target)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(a.key) && b.runtime.source == Some(id)) + { + r.remove(w, self, target, a.key)?; + } + } + Ok(()) + } + fn support_phalanx( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + p: &Phalanx, + active: bool, + ) -> Result<(), String> { + if active { + if p.keep.values().any(|v| *v != 0.) { + self.component_buff( + w, + r, + id, + "trait:mint_keep", + p.keep.clone(), + f64::INFINITY, + id, + )?; + } + self.component_buff( + w, + r, + id, + "talent:mint_taunt", + [("taunt".into(), p.taunt)].into(), + f64::INFINITY, + id, + )?; + } else { + r.remove(w, self, id, "trait:mint_keep")?; + r.remove(w, self, id, "talent:mint_taunt")?; + } + self.support_def_aura(w, r, id, &p.aura, !active) + } + fn support_def_aura( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + a: &StatAura, + on: bool, + ) -> Result<(), String> { + let up = on && w.unit(id)?.stats.alive && w.unit(id)?.deployed; + let keys = if up { + let dir = self + .roster + .as_ref() + .ok_or("Missing ally aura context")? + .entry(id)? + .direction; + targeting::absolute_range( + a.grid.as_ref().ok_or("Missing ally aura grid")?, + w.unit(id)?.deployment.tile, + dir, + 0, + ) + } else { + vec![] + }; + let ids: Vec<_> = w.unit_ids().collect(); + for target in ids { + if w.unit(target)?.side != health::Side::Ally { + continue; + } + if up + && targeting::friendly_selectable(w, id, target)? + && body::in_range(w.unit(target)?, &keys) + { + let mut b = Buff { + key: Some(a.key.into()), + mods: a.mods.clone(), + ..Default::default() + }; + b.runtime.duration = 0.4 + 0.05; + b.runtime.refresh = buffs::Refresh::Extend; + b.runtime.source = Some(id); + r.add( + w, + self, + target, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } else if w + .unit(target)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some(a.key) && b.runtime.source == Some(id)) + { + r.remove(w, self, target, a.key)?; + } + } + Ok(()) + } + fn support_peaks( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + peaks: &[[f64; 2]], + ) -> Result<(), String> { + let u = w.unit_mut(id)?; + let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + let ratio = if max > 0. { u.stats.hp / max } else { 0. }; + let value = peaks + .iter() + .find(|p| ratio > p[0]) + .map(|p| p[1]) + .unwrap_or(0.); + let old = w + .unit(id)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some("humus:peak")) + .and_then(|b| b.mods.get("atkPct")) + .copied() + .unwrap_or(0.); + if old != value { + if value > 0. { + self.component_buff( + w, + r, + id, + "humus:peak", + [("atkPct".into(), value)].into(), + f64::INFINITY, + id, + )?; + } else { + r.remove(w, self, id, "humus:peak")?; + } + } + Ok(()) + } + pub(super) fn support_skill( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + dir: Direction, + def: &Definition, + event: skills::Event, + c: &skills::Context, + s: &mut skills::Runtime, + ) -> Result<(), String> { + let id = s.unit(); + let cfg = &def.extra.support; + if let Some(p) = &cfg.phalanx { + // Profession hooks run after the Kit's start/end callbacks. + if event == skills::Event::SkillStart { + r.remove(w, self, id, "trait:phalanxGuard")?; + } else if event == skills::Event::SkillEnd && w.unit(id)?.stats.alive { + self.component_buff( + w, + r, + id, + "trait:phalanxGuard", + p.guard.clone(), + f64::INFINITY, + id, + )?; + } + } + if event == skills::Event::Start { + if let Some(cook) = &cfg.cook { + let mut b = Buff { + key: Some("sunbr:cook".into()), + mods: [("defPct".into(), cook.defence)].into(), + flags: ["disarm".into()].into(), + ..Default::default() + }; + b.runtime.duration = cook.duration; + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + mods_present: true, + flags_present: true, + ..Default::default() + }, + )?; + } + if let Some(q) = &cfg.quiet { + w.unit_mut(id)?.operator.support.quiet_until = w.time + q.duration; + let keys = self.support_trigger_range(w, id, def)?; + let mut targets = search::Host::enemies( + self, + id, + &keys, + def.combat.profile.selection, + w, + w.unit_capacity(), + )?; + targeting::sort_enemies(w, self, id, &mut targets, def.combat.profile.priority)?; + targets.truncate(q.count); + for target in targets { + self.support_status(w, r, id, target, "sleep", q.duration, None)?; + } + } + if let Some(p) = &cfg.protege { + let target = self.support_top(w, id)?; + w.unit_mut(id)?.operator.support.protege = target; + if let Some(target) = target { + self.component_buff( + w, + r, + target, + "vendla:taunt", + [("taunt".into(), p.taunt)].into(), + s.spec.duration + 0.1, + id, + )?; + let mut b = Buff { + key: Some(format!("vendla:counter:{id}")), + ..Default::default() + }; + b.runtime.duration = s.spec.duration + 0.1; + b.runtime.source = Some(id); + b.runtime.injury.observe = Some(PROTEGE_COUNTER); + r.add( + w, + self, + target, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + } + if let Some(p) = &cfg.plasma { + let mut targets = vec![id]; + let others: Vec<_> = self + .support_allies(w, id)? + .into_iter() + .filter(|&a| a != id) + .collect(); + if let Some(&other) = self.rng.pick(&others) { + targets.push(other); + } + for target in targets { + let mut b = Buff { + key: Some("bldsk:plasma".into()), + mods: [("atkPct".into(), p.attack)].into(), + ..Default::default() + }; + b.runtime.duration = p.duration + 1e-6; + b.runtime.interval = p.interval; + b.runtime.on_tick = Some(PLASMA_DRAIN); + b.runtime.tick_payload = p.ratio; + b.runtime.source = Some(id); + r.add( + w, + self, + target, + buffs::Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } + } + if let Some(zone) = &cfg.zone { + if self.zones.len() >= w.unit_capacity() { + return Err("Lingering area capacity exceeded".into()); + } + let keys = self + .roster + .as_ref() + .ok_or("Missing zone roster")? + .range(w, id)?; + let mut targets = search::Host::enemies( + self, + id, + &keys, + def.combat.profile.selection, + w, + w.unit_capacity(), + )?; + targeting::sort_enemies(w, self, id, &mut targets, def.combat.profile.priority)?; + let position = if let Some(&target) = targets.first() { + w.unit(target)?.position + } else { + let a = w.unit(id)?.position; + let f = dir.vector(); + [a[0] + f64::from(f[0]), a[1] + f64::from(f[1])] + }; + let damage = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * zone.scale; + let pulses = zone.duration.round().max(1.); + if pulses > u32::MAX as f64 { + return Err("Lingering area pulse count exceeded".into()); + } + let state = ZoneState { + source: id, + position, + damage, + left: pulses as u32, + next: w.time, + }; + // An immediate timer first runs in the next scheduler phase. + self.zones.push(state); + } + if let Some(push) = &cfg.push { + self.support_push_cast(w, r, id, dir, push)?; + } + if !cfg.peaks.is_empty() { + self.support_peaks(w, r, id, &cfg.peaks)?; + } + if cfg.deferred.is_some() { + w.unit_mut(id)?.operator.support.debt = 0.; + } + if let Some(p) = &cfg.phalanx { + self.support_phalanx(w, r, id, p, true)?; + } + w.unit_mut(id)?.operator.support.fragile_scale = 1.; + for aura in cfg.enemy_auras.iter().filter(|a| a.active_only) { + self.support_enemy_aura(w, r, id, aura)?; + } + } + if event == skills::Event::Tick { + if cfg.cook.is_some() + && !w.unit(id)?.stats.buffs().iter().any(|b| { + b.key.as_deref() == Some("sunbr:cook") + || b.key.as_deref() == Some("sunbr:serve") + }) + { + self.component_buff( + w, + r, + id, + "sunbr:serve", + [("atkPct".into(), cfg.cook.as_ref().unwrap().attack)].into(), + f64::INFINITY, + id, + )?; + } + if !cfg.peaks.is_empty() { + self.support_peaks(w, r, id, &cfg.peaks)?; + } + for aura in cfg.enemy_auras.iter().filter(|a| a.active_only) { + self.support_enemy_aura(w, r, id, aura)?; + } + } + if event == skills::Event::End { + if cfg.cook.is_some() { + r.remove(w, self, id, "sunbr:cook")?; + r.remove(w, self, id, "sunbr:serve")?; + } + if let Some(target) = w.unit_mut(id)?.operator.support.protege.take() { + if w.unit(target)?.stats.buffs().iter().any(|b| { + b.key.as_deref() == Some("vendla:taunt") && b.runtime.source == Some(id) + }) { + r.remove(w, self, target, "vendla:taunt")?; + } + r.remove(w, self, target, &format!("vendla:counter:{id}"))?; + } + if !cfg.peaks.is_empty() { + r.remove(w, self, id, "humus:peak")?; + } + if let Some(p) = &cfg.phalanx { + if c.reason != "death" && w.unit(id)?.stats.alive && p.burst > 0. { + let keys = self + .roster + .as_ref() + .ok_or("Missing phalanx roster")? + .range(w, id)?; + let mut targets = search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + targeting::sort_enemies( + w, + self, + id, + &mut targets, + def.combat.profile.priority, + )?; + for target in targets { + let amount = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * p.burst; + self.support_damage(w, r, id, target, amount, "burst")?; + } + } + self.support_phalanx(w, r, id, p, false)?; + } + if let Some(d) = &cfg.deferred { + let debt = std::mem::take(&mut w.unit_mut(id)?.operator.support.debt); + if c.reason != "death" && w.unit(id)?.stats.alive && debt > 0. { + let mut b = Buff { + key: Some("gvial:bleed".into()), + ..Default::default() + }; + b.runtime.duration = d.duration + 1e-6; + b.runtime.interval = d.interval; + b.runtime.on_tick = Some(HP_DRAIN); + b.runtime.tick_payload = debt * d.interval / d.duration; + b.runtime.refresh = buffs::Refresh::Independent; + b.runtime.max_stacks = 10; + r.add( + w, + self, + id, + buffs::Spec { + buff: b, + ..Default::default() + }, + )?; + } + } + w.unit_mut(id)?.operator.support.fragile_scale = 1.; + for aura in cfg.enemy_auras.iter().filter(|a| a.active_only) { + self.support_enemy_aura(w, r, id, aura)?; + } + } + Ok(()) + } + fn support_zone_pulse( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + z: &mut ZoneState, + ) -> Result<(), String> { + let ids = self + .spawns + .as_ref() + .ok_or("Missing zone targets")? + .live() + .to_vec(); + let targets = spatial::enemies_in_radius( + w, + self, + &ids, + z.position, + 0.9, + spatial::RadiusRule::Body, + true, + w.unit_capacity(), + )?; + for target in targets { + self.support_status(w, r, z.source, target, "sluggish", 1.05, None)?; + self.support_status(w, r, z.source, target, "silence", 1.05, None)?; + self.support_damage(w, r, z.source, target, z.damage, "zone")?; + } + z.left -= 1; + z.next += 1.; + Ok(()) + } + fn support_push_cast( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + dir: Direction, + p: &PushCast, + ) -> Result<(), String> { + let keys = targeting::absolute_range(&p.grid, w.unit(id)?.deployment.tile, dir, 0); + let all = self + .spawns + .as_ref() + .ok_or("Missing push targets")? + .live() + .to_vec(); + let mut targets = Vec::new(); + for &target in &all { + let u = w.unit_mut(target)?; + if u.stats.alive + && !u.hidden + && !u + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("untargetable") + && body::in_range(u, &keys) + { + targets.push(target); + } + } + let mut pushed: std::collections::BTreeSet<_> = targets.iter().copied().collect(); + for &target in &targets { + let a = w.unit(id)?.position; + let b = w.unit(target)?.position; + let near = hypot(b[0] - a[0], b[1] - a[1]) < 0.25; + let expect = if displacement::displaceable(w, target)? { + let level = + displacement::force_level(w, target, p.force - if near { 2. } else { 0. })?; + displacement::push_tiles(level, true) + } else { + 0. + }; + let options = displacement::Push { + from: Some(displacement::Origin::unit(w, id, dir)?), + direction: Some(dir.vector().map(f64::from)), + fixed_angle: true, + effect: true, + ..Default::default() + }; + let grid = self.grid.take().ok_or("Missing push grid")?; + let result = displacement::push( + w, + &grid, + &mut allies::Blocking { + host: self, + buffs: r, + }, + target, + p.force, + options, + ); + self.grid = Some(grid); + let moved = result?; + self.support_status( + w, + r, + id, + target, + "stun", + if expect > 0. && moved + 0.05 < expect { + p.wall + } else { + p.direct + }, + None, + )?; + } + for target in targets { + let others = spatial::enemies_in_radius( + w, + self, + &all, + w.unit(target)?.position, + 0.6, + spatial::RadiusRule::Body, + false, + w.unit_capacity(), + )?; + for other in others { + if pushed.insert(other) { + self.support_status(w, r, id, other, "stun", p.collision, None)?; + } + } + } + Ok(()) + } + pub(super) fn support_counter(c: &mut settlement::Context<'_, Self>) -> Result<(), String> { + let buff = c.runtime.get(c.world, c.request.hit.target, c.buff)?; + let source = buff.runtime.source.ok_or("Missing protege source")?; + let target = c.request.hit.target; + let Some(enemy) = c.request.hit.source.filter(|&e| { + c.world + .unit(e) + .is_ok_and(|u| u.side == health::Side::Enemy && u.stats.alive) + }) else { + return Ok(()); + }; + let u = c.world.unit(source)?; + if !u.stats.alive + || !u.deployed + || !u.operator.active_skill + || u.operator.support.protege != Some(target) + { + return Ok(()); + } + let def = Arc::clone( + &c.host + .roster + .as_ref() + .ok_or("Missing protege roster")? + .entry(source)? + .definition, + ); + let scale = def + .extra + .support + .protege + .as_ref() + .ok_or("Missing protege configuration")? + .scale; + let amount = c + .world + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * scale; + let mut q = hit::Request::new( + health::Hit { + source: Some(source), + credit: Some(source), + target: enemy, + damage_type: DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.calculation = hit::Calculation::Precomputed; + q.is_skill = true; + q.ignore_select = true; + q.tags.push("counter".into()); + q.trait_ally = Some(target); + c.resolve(&mut q)?; + Ok(()) + } + pub(super) fn support_scheduled(&mut self, w: &mut World) -> Result<(), String> { + let roster = self + .roster + .as_ref() + .ok_or("Missing support scheduler roster")?; + let mut r = self.buffs.take().ok_or("Missing support scheduler buffs")?; + let mut ids = std::mem::take(&mut self.scratch); + ids.clear(); + ids.extend_from_slice(roster.ids()); + let result = (|| { + for &id in &ids { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + let cfg = &def.extra.support; + let up = w.unit(id)?.stats.alive && w.unit(id)?.deployed; + let now = w.time; + if cfg.lavender > 0. { + let next = &mut w.unit_mut(id)?.operator.support.next_lavender; + if *next == 0. { + *next = 0.25; + } + if now + 1e-9 >= *next { + *next += 0.25; + if up { + let value = w + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk") + * cfg.lavender; + for &target in &ids { + if targeting::friendly_selectable(w, id, target)? { + self.component_buff( + w, + &mut r, + target, + &format!("flower:lavender:{id}"), + [("hpRegen".into(), value)].into(), + 0.5, + id, + )?; + } + } + } + } + } + if cfg.sp_aura > 0. || cfg.reveal { + let period = cfg.sp_period.unwrap_or(0.2); + let next = &mut w.unit_mut(id)?.operator.support.next_sp_aura; + if *next == 0. { + *next = period; + } + if now + 1e-9 >= *next { + *next += period; + if up { + if cfg.sp_aura > 0. { + for &target in &ids { + if cfg.sp_profession.is_some_and(|p| { + self.roster + .as_ref() + .unwrap() + .entry(target) + .is_ok_and(|e| e.definition.profession != p) + }) || !targeting::friendly_selectable(w, id, target)? + { + continue; + } + let stronger = w.unit(target)?.stats.buffs().iter().any(|b| { + b.key.as_deref() == Some("aura:spRecovery") + && b.runtime.source != Some(id) + && b.runtime.source.is_some_and(|s| { + w.unit(s).is_ok_and(|u| u.stats.alive) + }) + && b.mods.get("spRecoveryFlat").copied().unwrap_or(0.) + > cfg.sp_aura + }); + if !stronger { + self.component_buff( + w, + &mut r, + target, + "aura:spRecovery", + [("spRecoveryFlat".into(), cfg.sp_aura)].into(), + cfg.sp_duration.unwrap_or(0.25), + id, + )?; + } + } + } + if cfg.reveal { + let keys = self.roster.as_ref().unwrap().range(w, id)?; + let enemies = self.spawns.as_ref().unwrap().live().to_vec(); + for target in enemies { + let u = w.unit_mut(target)?; + if u.stats.alive + && !u.hidden + && body::in_range(u, &keys) + && u.stats + .stats() + .map_err(str::to_string)? + .flags + .contains("stealth") + { + let mut b = Buff { + key: Some("aura:reveal".into()), + flags: ["reveal".into()].into(), + ..Default::default() + }; + b.runtime.duration = 0.25; + r.add( + w, + self, + target, + buffs::Spec { + buff: b, + flags_present: true, + ..Default::default() + }, + )?; + } + } + } + } + } + } + if cfg.support_atk != 0. { + let next = &mut w.unit_mut(id)?.operator.support.next_support_aura; + if now + 1e-9 >= *next { + *next += 0.5; + if up { + for &target in &ids { + if self + .roster + .as_ref() + .unwrap() + .entry(target)? + .definition + .profession + != "SUPPORT" + || !targeting::friendly_selectable(w, id, target)? + { + continue; + } + let stronger = w.unit(target)?.stats.buffs().iter().any(|b| { + b.key.as_deref() == Some("talent:podego") + && b.runtime.source != Some(id) + && b.mods.get("atkPct").copied().unwrap_or(0.) + > cfg.support_atk + && b.runtime.time_left > 0.05 + }); + if !stronger { + self.component_buff( + w, + &mut r, + target, + "talent:podego", + [("atkPct".into(), cfg.support_atk)].into(), + 0.6, + id, + )?; + } + } + } + } + } + if w.unit(id)?.operator.support.next_aura.len() != cfg.enemy_auras.len() { + w.unit_mut(id)?.operator.support.next_aura = vec![0.; cfg.enemy_auras.len()]; + } + for (index, aura) in cfg + .enemy_auras + .iter() + .enumerate() + .filter(|(_, a)| !a.active_only) + { + let next = &mut w.unit_mut(id)?.operator.support.next_aura[index]; + if now + 1e-9 >= *next { + *next += aura.period; + self.support_enemy_aura(w, &mut r, id, aura)?; + } + } + if cfg.reaper > 0. { + if !up { + w.unit_mut(id)?.operator.support.reaper_queue.clear(); + } else if now + 1e-9 >= w.unit(id)?.operator.support.next_reaper { + if let Some(amount) = + w.unit_mut(id)?.operator.support.reaper_queue.pop_front() + { + w.unit_mut(id)?.operator.support.next_reaper = now + 0.12; + self.support_heal( + w, + &mut r, + Some(id), + id, + amount, + HealOptions { + self_heal: true, + ignore_heal_free: true, + ..Default::default() + }, + )?; + } + } + } + if let Some(p) = &cfg.phalanx { + if now + 1e-9 >= w.unit(id)?.operator.support.next_phalanx { + w.unit_mut(id)?.operator.support.next_phalanx += 0.2; + self.support_def_aura( + w, + &mut r, + id, + &p.aura, + !w.unit(id)?.operator.active_skill, + )?; + } + } + if let Some(values) = cfg.block_stats { + if now + 1e-9 >= w.unit(id)?.operator.support.next_block_stats.max(0.1) { + w.unit_mut(id)?.operator.support.next_block_stats = + w.unit(id)?.operator.support.next_block_stats.max(0.1) + 0.1; + if up { + let extra = w.unit(id)?.blocking().len().saturating_sub(1) as f64; + let mods: Numbers = [ + ("atkPct".into(), values[0] + values[2] * extra), + ("defPct".into(), values[1] + values[3] * extra), + ] + .into(); + if !w + .unit(id)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some("gvial:t1") && b.mods == mods) + { + self.component_buff( + w, + &mut r, + id, + "gvial:t1", + mods, + f64::INFINITY, + id, + )?; + } + } + } + } + if cfg.forge.is_some() + && now + 1e-9 >= w.unit(id)?.operator.support.next_forge.max(0.2) + { + w.unit_mut(id)?.operator.support.next_forge = + w.unit(id)?.operator.support.next_forge.max(0.2) + 0.2; + if up && w.unit(id)?.operator.active_skill { + // The source's own passive modifiers are installed by SkillRuntime. + for &target in &ids { + if target != id + && targeting::friendly_selectable(w, id, target)? + && w.unit(target)? + .stats + .buffs() + .iter() + .any(|b| b.key.as_deref() == Some("cathy:shield")) + { + self.component_buff( + w, + &mut r, + target, + &format!("cathy:forge:{id}"), + cfg.forge.as_ref().unwrap().clone(), + 0.25, + id, + )?; + } + } + } + } + } + let mut zones = std::mem::take(&mut self.zones); + let pulses = (|| { + for zone in &mut zones { + if zone.left > 0 && w.time + 1e-9 >= zone.next { + self.support_zone_pulse(w, &mut r, zone)?; + } + } + Ok(()) + })(); + zones.retain(|z| z.left > 0); + self.zones = zones; + pulses + })(); + self.scratch = ids; + self.buffs = Some(r); + result + } + pub(super) fn refresh_support_casts(&mut self, w: &mut World) -> Result<(), String> { + let ids = self + .roster + .as_ref() + .ok_or("Missing support tick roster")? + .ids() + .to_vec(); + for id in ids { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + if !def.extra.support.auto_heal || !skills::can_act(w, id)? { + continue; + } + let entry = self.roster.as_ref().unwrap().entry(id)?; + let s = entry.skill()?; + if !s.bank.ready() + || s.bank.active + || s.op_cooling(w.time) + || w.unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("silence") + { + continue; + } + let keys = self.roster.as_ref().unwrap().range(w, id)?; + if search::Host::injured_allies(self, id, &keys, false, w, w.unit_capacity())? + .is_empty() + { + continue; + } + let mut skill = self.roster.as_mut().unwrap().take_skill(id)?; + let result = skill.activate(w, self, "DEFAULT", false); + self.roster.as_mut().unwrap().restore_skill(id, skill)?; + result?; + } + Ok(()) + } + pub(super) fn support_before_attack( + &mut self, + w: &mut World, + id: Id, + targets: &[Id], + skill: Option<&mut skills::Runtime>, + ) -> Result<(), String> { + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + if def.extra.support.bandage.is_none() { + return Ok(()); + } + let (Some(&target), Some(skill)) = (targets.first(), skill) else { + return Ok(()); + }; + if w.unit(target)?.side != health::Side::Ally + || !skill.bank.ready() + || w.unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("silence") + { + return Ok(()); + } + let u = w.unit_mut(target)?; + let max = u.stats.stats().map_err(str::to_string)?.n("maxHp"); + if max <= 0. || u.stats.hp / max >= 0.5 { + return Ok(()); + } + if skill.activate(w, self, "DEFAULT", false)? { + w.unit_mut(id)?.operator.support.bandage = Some(target); + } + Ok(()) + } + pub(super) fn support_attack( + &mut self, + c: &attacks::Context, + w: &mut World, + ) -> Result<(), String> { + let id = c.attacker; + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + let cfg = &def.extra.support; + let bandage = w.unit_mut(id)?.operator.support.bandage.take(); + if cfg.skill_heal <= 0. && bandage.is_none() { + return Ok(()); + } + let mut r = self.buffs.take().ok_or("Missing attack heal context")?; + let result = (|| { + if cfg.skill_heal > 0. && c.is_skill && w.unit(id)?.stats.alive { + self.support_heal( + w, + &mut r, + Some(id), + id, + cfg.skill_heal, + HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + if let Some(target) = bandage { + if w.unit(target)?.stats.alive { + let amount = w + .unit_mut(target)? + .stats + .stats() + .map_err(str::to_string)? + .n("maxHp") + * cfg.bandage.unwrap_or(0.); + self.support_heal(w, &mut r, Some(id), target, amount, HealOptions::default())?; + } + } + Ok(()) + })(); + self.buffs = Some(r); + result + } + pub(super) fn support_hit( + &mut self, + impact: attacks::Impact, + w: &mut World, + ) -> Result<(), String> { + if impact.heal { + return Ok(()); + } + let id = impact.attacker; + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + let cfg = &def.extra.support; + let mut r = self.buffs.take().ok_or("Missing support hit buffs")?; + let result = (|| { + if cfg.skill_drain_heal > 0. + && w.unit(id)?.operator.active_skill + && impact.amount > 0. + && w.unit(id)?.stats.alive + { + self.support_heal( + w, + &mut r, + Some(id), + id, + impact.amount * cfg.skill_drain_heal, + HealOptions { + self_heal: true, + ..Default::default() + }, + )?; + } + let Some(target) = impact.target.filter(|&t| { + w.unit(t) + .is_ok_and(|u| u.stats.alive && u.side == health::Side::Enemy) + }) else { + return Ok(()); + }; + if let Some([duration, bonus]) = cfg.sluggish { + let key = &self.spawns.as_ref().unwrap().definition(target)?.key; + let beast = self.data.table("enemies").unwrap()[key]["tags"] + .as_array() + .is_some_and(|a| a.iter().any(|t| t == "infection")); + self.support_status( + w, + &mut r, + id, + target, + "sluggish", + duration + if beast { bonus } else { 0. }, + None, + )?; + } + if let Some([value, duration]) = cfg.weaken { + self.support_status(w, &mut r, id, target, "weaken", duration, Some(value))?; + } + if let Some(force) = cfg.radial_push.filter(|_| impact.is_skill) { + let dir = self.roster.as_ref().unwrap().entry(id)?.direction; + let grid = self.grid.take().ok_or("Missing radial push grid")?; + let result = displacement::push( + w, + &grid, + &mut allies::Blocking { + host: self, + buffs: &mut r, + }, + target, + force, + displacement::Push { + from: Some(displacement::Origin::unit(w, id, dir)?), + ..Default::default() + }, + ); + self.grid = Some(grid); + result?; + } + if let Some(force) = cfg + .inward + .filter(|_| w.unit(id).is_ok_and(|u| u.operator.active_skill)) + { + let dir = self.roster.as_ref().unwrap().entry(id)?.direction; + let options = displacement::Push { + from: Some(displacement::Origin::unit(w, id, dir)?), + inward: true, + ..Default::default() + }; + let grid = self.grid.take().ok_or("Missing inward push grid")?; + let result = displacement::push( + w, + &grid, + &mut allies::Blocking { + host: self, + buffs: &mut r, + }, + target, + force, + options, + ); + self.grid = Some(grid); + result?; + } + Ok(()) + })(); + self.buffs = Some(r); + result + } + pub(super) fn support_phase( + &mut self, + p: hit::Phase, + q: &mut hit::Request, + amount: f64, + r: &mut buffs::Runtime, + w: &mut World, + _rng: &mut Rng, + ) -> Result<(), String> { + if p == hit::Phase::Hit + && w.unit(q.hit.target)?.side == health::Side::Ally + && w.unit(q.hit.target)?.deployment.kind != crate::battle::deploy::Kind::Device + { + let def = Arc::clone( + &self + .roster + .as_ref() + .ok_or("Missing incoming support roster")? + .entry(q.hit.target)? + .definition, + ); + if let Some(d) = def + .extra + .support + .deferred + .as_ref() + .filter(|_| w.unit(q.hit.target).is_ok_and(|u| u.operator.active_skill)) + { + q.damage.mul *= 1. - d.resistance; + q.tags.push("gvialDeferred".into()); + } + } + let Some(source) = q + .hit + .source + .filter(|&s| w.unit(s).is_ok_and(|u| u.has_operator_kit())) + else { + return Ok(()); + }; + let def = Arc::clone( + &self + .roster + .as_ref() + .ok_or("Missing outgoing support roster")? + .entry(source)? + .definition, + ); + let cfg = &def.extra.support; + if p == hit::Phase::Hit && w.unit(q.hit.target)?.side == health::Side::Enemy { + if let Some([weight, penetration]) = cfg.heavy_penetration { + if w.unit_mut(q.hit.target)? + .stats + .stats() + .map_err(str::to_string)? + .n("massLevel") + >= weight + { + q.damage.penetration.def_flat += penetration; + } + } + } + if p == hit::Phase::Calculate + && (w.unit(q.hit.target)?.boss || w.unit(q.hit.target)?.targeting.elite) + { + if let Some(scale) = cfg.elite_scale { + q.damage.amount *= scale; + } + } + if p == hit::Phase::Output + && amount > 0. + && cfg.reaper > 0. + && def + .extra + .tactics + .behavior() + .is_none_or(|kit| kit.reaper_eligible(q)) + && w.unit(source)?.stats.alive + && w.unit(source)?.deployed + && w.unit(q.hit.target)?.side == health::Side::Enemy + && !q.hit.hp_loss + && q.hit.damage_type != DamageType::Elemental + { + let now = w.time; + let limit = w + .unit_mut(source)? + .stats + .stats() + .map_err(str::to_string)? + .n("blockCnt") + .floor() + .max(0.) as usize; + let max_pending = w.unit_capacity(); + let heal = cfg.reaper + * self + .tac_def(source)? + .extra + .tactics + .behavior() + .map(|kit| kit.reaper_multiplier(w, source)) + .transpose()? + .unwrap_or(1.); + let m = &mut w.unit_mut(source)?.operator.support; + if now + 1e-9 >= m.reaper_window { + m.reaper_window = now + 0.05; + m.reaper_accepted = 0; + m.reaper_limit = limit; + } + if m.reaper_accepted < m.reaper_limit { + if m.reaper_queue.len() >= max_pending { + return Err("Reaper heal queue capacity exceeded".into()); + } + m.reaper_accepted += 1; + m.reaper_queue.push_back(heal); + } + } + let _ = r; + Ok(()) + } + pub(super) fn support_landed( + &mut self, + e: &health::Event, + q: &hit::Request, + _r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + if q.tags.iter().any(|t| t == "gvialDeferred") + && e.amount > 0. + && w.unit(e.target)?.side == health::Side::Ally + && w.unit(e.target)?.deployment.kind != crate::battle::deploy::Kind::Device + { + let def = Arc::clone( + &self + .roster + .as_ref() + .ok_or("Missing deferred damage roster")? + .entry(e.target)? + .definition, + ); + if let Some(d) = &def.extra.support.deferred { + w.unit_mut(e.target)?.operator.support.debt += + e.amount * d.resistance / (1. - d.resistance); + } + } + Ok(()) + } + pub(super) fn support_damage_applied( + &mut self, + e: &health::Event, + q: &hit::Request, + r: &mut buffs::Runtime, + w: &mut World, + ) -> Result<(), String> { + let Some(source) = e.source.filter(|&s| { + w.unit(s) + .is_ok_and(|u| u.has_operator_kit() && u.stats.alive) + }) else { + return Ok(()); + }; + if w.unit(e.target)?.side != health::Side::Enemy { + return Ok(()); + } + let def = Arc::clone( + &self + .roster + .as_ref() + .ok_or("Missing incantation roster")? + .entry(source)? + .definition, + ); + if def.extra.support.incantation <= 0. { + return Ok(()); + } + let target = if let Some(target) = q.trait_ally { + Some(target) + } else { + let keys = self.roster.as_ref().unwrap().range(w, source)?; + search::Host::injured_allies(self, source, &keys, false, w, w.unit_capacity())? + .first() + .copied() + }; + if let Some(target) = target { + self.support_heal( + w, + r, + Some(source), + target, + e.amount * def.extra.support.incantation, + HealOptions::default(), + )?; + } + Ok(()) + } + pub(super) fn support_enemy_death( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + victim: Id, + ) -> Result<(), String> { + let ids = self + .roster + .as_ref() + .ok_or("Missing death support roster")? + .ids() + .to_vec(); + for &id in &ids { + if !w.unit(id)?.stats.alive || !w.unit(id)?.deployed { + continue; + } + let def = Arc::clone(&self.roster.as_ref().unwrap().entry(id)?.definition); + let cfg = &def.extra.support; + if cfg.death_sp.is_none() && !cfg.enemy_auras.iter().any(|a| a.growth.is_some()) { + continue; + } + let keys = self.roster.as_ref().unwrap().range(w, id)?; + if !body::in_range(w.unit(victim)?, &keys) { + continue; + } + if w.unit(id)?.operator.active_skill + && !w.unit(victim)?.boss + && !w.unit(victim)?.targeting.elite + { + for a in &cfg.enemy_auras { + if let Some([step, cap]) = a.growth { + let m = &mut w.unit_mut(id)?.operator.support; + m.fragile_scale = (m.fragile_scale + step).min(cap); + } + } + } + if let Some([own, other]) = cfg.death_sp { + let mut roster = self.roster.take().unwrap(); + let result = roster.grant_sp(w, r, self, id, own); + self.roster = Some(roster); + result?; + let mut candidates = vec![]; + for target in self.support_allies(w, id)? { + let entry = self.roster.as_ref().unwrap().entry(target)?; + if target != id + && entry.talent_sp_eligible(w.unit(target)?.operator.active_skill) + { + candidates.push(target); + } + } + if let Some(&target) = self.rng.pick(&candidates) { + if self.roster.as_ref().unwrap().entry(target)?.skill().is_ok() { + let mut roster = self.roster.take().unwrap(); + let result = roster.grant_sp(w, r, self, target, other); + self.roster = Some(roster); + result?; + } else { + // The attacker owns its SkillRuntime until this callback returns. + let limit = w + .unit_capacity() + .checked_mul(ids.len()) + .ok_or("SP grant capacity overflow")?; + let pending = &mut w.unit_mut(target)?.operator.support.sp_changes; + if pending.len() >= limit { + return Err("Pending SP grant capacity exceeded".into()); + } + pending.push(crate::battle::content::operators::SpChange::Gain(other)); + } + } + } + } + Ok(()) + } + pub(super) fn support_flush_sp( + &mut self, + w: &mut World, + skill: &mut skills::Runtime, + ) -> Result<(), String> { + let changes = std::mem::take(&mut w.unit_mut(skill.unit())?.operator.support.sp_changes); + for change in changes { + match change { + crate::battle::content::operators::SpChange::Damaged => { + skill.on_damaged(w, self)? + } + crate::battle::content::operators::SpChange::Gain(amount) => { + skill.gain(w, self, amount, "talent", false, false)?; + } + crate::battle::content::operators::SpChange::Bond(amount) => { + skill.gain(w, self, amount, "bond", false, false)?; + } + crate::battle::content::operators::SpChange::Clear => { + skill.bank.clear_inactive(w)? + } + } + } + Ok(()) + } + pub(super) fn support_sp_gain( + &mut self, + w: &mut World, + id: Id, + c: &mut skills::Context, + ) -> Result<(), String> { + if c.reason != "time" { + return Ok(()); + } + let def = Arc::clone( + &self + .roster + .as_ref() + .ok_or("Missing SP modifier roster")? + .entry(id)? + .definition, + ); + if def.extra.support.sp_near <= 0. { + return Ok(()); + } + let keys = self.roster.as_ref().unwrap().range(w, id)?; + if !search::Host::enemies( + self, + id, + &keys, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + w, + w.unit_capacity(), + )? + .is_empty() + { + c.amount += def.extra.support.sp_near * DT; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/tactics.rs b/crates/engine/src/battle/runtime/tactics.rs new file mode 100644 index 0000000..e4668ec --- /dev/null +++ b/crates/engine/src/battle/runtime/tactics.rs @@ -0,0 +1,648 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Tactical Kit callbacks. Timers and projectile payloads obey Field capacities. +use super::super::{ + attacks, body, + content::operators::*, + damage::{Damage, DamageType}, + hit, + operators::Definition, + projectiles, search, targeting, +}; +use super::*; +pub(super) const OBSERVE: u64 = 1401; +pub(super) const WITHER: u64 = 1402; +pub(super) const RAIN: u64 = 1403; +pub(super) const DRIZZLE: u64 = 1404; +pub(super) const SHIELD_LOST: u64 = 1405; +pub(super) const ABNORMAL: &[&str] = &[ + "stun", "freeze", "cold", "sleep", "silence", "fear", "attract", "tremble", "bind", "levitate", + "disarm", "palsy", "sluggish", "slow", +]; +#[derive(Clone, Copy)] +pub(super) enum ArrowKind { + Snow, + Pursuit, +} +#[derive(Clone, Copy)] +pub(super) struct Arrow { + pub source: Id, + pub kind: ArrowKind, + pub scale: f64, + pub hits: u32, + pub seen: [Id; 5], + pub count: usize, +} +pub(super) struct Timer { + pub source: Option, + pub seq: u64, + pub at: f64, + pub interval: f64, + pub left: u32, + pub kind: Task, +} +pub(super) enum Task { + Enemy(super::enemies::EnemyTask), + Callback(fn(&mut kits::dispatch::Context<'_>) -> Result<(), String>), + KeyedCallback { + key: u64, + callback: fn(&mut kits::dispatch::Context<'_>, u64) -> Result<(), String>, + }, + AreaCallback { + position: [f64; 2], + attack: f64, + survives_retreat: bool, + callback: fn(&mut kits::dispatch::Context<'_>, [f64; 2], f64) -> Result<(), String>, + }, + Zone { + position: [f64; 2], + end: f64, + radius: f64, + attack: f64, + regen: f64, + weaken: f64, + wither: f64, + key: String, + held: std::collections::BTreeMap, + pulse: u32, + }, + Storm { + position: [i32; 2], + scale: f64, + chain: attacks::Chain, + }, + Icicle { + position: [f64; 2], + scale: f64, + cold: f64, + }, + Blast { + target: Id, + scale: f64, + element: f64, + }, + Explosion { + target: Id, + position: [f64; 2], + scale: f64, + }, + Gap { + target: Id, + buff: u64, + }, +} + +impl Host { + pub(super) fn tac_def(&self, id: Id) -> Result, String> { + Ok(Arc::clone( + &self + .roster + .as_ref() + .ok_or("Missing tactical roster")? + .entry(id)? + .definition, + )) + } + pub(super) fn tac_stat(w: &mut World, id: Id, k: &str) -> Result { + Self::advanced_stat(w, id, k) + } + pub(super) fn tac_up(w: &World, id: Id) -> bool { + w.unit(id).is_ok_and(|u| u.stats.alive && u.deployed) + } + pub(super) fn tac_has(w: &World, id: Id, k: &str) -> bool { + Self::advanced_has(w, id, k) + } + pub(super) fn tac_abnormal(w: &World, id: Id) -> bool { + w.unit(id).is_ok_and(|u| { + u.stats.buffs().iter().any(|b| { + b.runtime + .status + .as_deref() + .is_some_and(|k| ABNORMAL.contains(&k)) + }) + }) + } + pub(super) fn tac_keys( + &self, + w: &World, + id: Id, + grid: &[[i32; 2]], + ) -> Result, String> { + Ok(targeting::absolute_range( + grid, + w.unit(id)?.deployment.tile, + self.roster.as_ref().unwrap().entry(id)?.direction, + 0, + )) + } + pub(super) fn tac_enemies( + &mut self, + w: &mut World, + id: Id, + keys: Option<&[usize]>, + fly: bool, + ) -> Result, String> { + let range = match keys { + Some(k) => k.to_vec(), + None => self.roster.as_ref().unwrap().range(w, id)?, + }; + let mut ids = search::Host::enemies( + self, + id, + &range, + targeting::Profile { + can_hit_fly: fly, + hit_sleep: self.tac_def(id)?.combat.profile.selection.hit_sleep, + ..Default::default() + }, + w, + w.unit_capacity(), + )?; + targeting::sort_enemies( + w, + self, + id, + &mut ids, + self.tac_def(id)?.combat.profile.priority, + )?; + Ok(ids) + } + pub(super) fn tac_radius( + &mut self, + w: &mut World, + position: [f64; 2], + radius: f64, + ) -> Result, String> { + attacks::Hooks::radius_targets(self, position, radius, false, w, w.unit_capacity()) + } + pub(super) fn tac_selectable( + &mut self, + w: &mut World, + id: Id, + targets: Vec, + ) -> Result, String> { + let mut out = vec![]; + for a in targets { + if targeting::can_target_enemy( + w, + self, + Some(id), + a, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? { + out.push(a); + } + } + Ok(out) + } + pub(super) fn tac_heal_targets( + &self, + w: &mut World, + id: Id, + keys: &[usize], + injured: bool, + ) -> Result, String> { + let mut ids = vec![]; + for a in self.tac_heal_targets_in_order(w, id, keys, injured)? { + let max = Self::tac_stat(w, a, "maxHp")?; + ids.push(( + a, + w.unit(a)?.stats.hp / max, + w.unit(a)?.deployment.deploy_seq, + )); + } + ids.sort_by(|a, b| a.1.total_cmp(&b.1).then(a.2.cmp(&b.2))); + Ok(ids.into_iter().map(|x| x.0).collect()) + } + pub(super) fn tac_heal_targets_in_order( + &self, + w: &mut World, + id: Id, + keys: &[usize], + injured: bool, + ) -> Result, String> { + let mut ids = vec![]; + for &a in self.roster.as_ref().unwrap().ids() { + if !targeting::friendly_selectable(w, id, a)? || !body::in_range(w.unit(a)?, keys) { + continue; + } + let u = w.unit(a)?; + if a != id && (Self::tac_has(w, a, "noHeal") || u.profile_no_heal) { + continue; + } + let max = Self::tac_stat(w, a, "maxHp")?; + if injured && w.unit(a)?.stats.hp >= max - 1e-6 { + continue; + } + ids.push(a); + } + Ok(ids) + } + pub(super) fn tac_heal( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + target: Id, + amount: f64, + ) -> Result { + self.support_heal( + w, + r, + Some(id), + target, + amount, + health::HealOptions::default(), + ) + } + pub(super) fn tac_damage( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + target: Id, + amount: f64, + kind: DamageType, + attack: bool, + tag: &str, + ) -> Result { + let mut q = hit::Request::new( + health::Hit { + source: Some(id), + credit: Some(id), + target, + damage_type: kind, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.is_skill = true; + q.is_attack = attack; + if tag == "iceSpike" { + q.is_splash = true; + q.attack_type = hit::AttackType::Splash; + } + q.tags.push(tag.into()); + if ["zone", "gap", "lordAddition", "mark", "markOwn"].contains(&tag) { + q.calculation = hit::Calculation::Precomputed; + q.attack_type = if tag == "zone" { + hit::AttackType::Buff + } else { + hit::AttackType::Addition + }; + } + if tag == "zone" { + q.hit.source = None; + } + self.resolve_hit(w, r, &mut q) + } + pub(super) fn tac_cleanse( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + ) -> Result<(), String> { + let buffs: Vec<_> = w + .unit(id)? + .stats + .buffs() + .iter() + .filter(|b| { + b.runtime + .status + .as_deref() + .is_some_and(|k| ABNORMAL.contains(&k)) + }) + .map(|b| b.runtime.id()) + .collect(); + for buff in buffs { + r.remove_id(w, self, id, buff)?; + } + Ok(()) + } + pub(super) fn tac_timer( + &mut self, + w: &World, + id: Id, + at: f64, + interval: f64, + left: u32, + kind: Task, + ) -> Result<(), String> { + self.enqueue_timer(Timer { + source: Some(id), + seq: w.unit(id)?.deployment.deploy_seq, + at, + interval, + left, + kind, + }) + } + pub(super) fn enqueue_timer(&mut self, timer: Timer) -> Result<(), String> { + if self.tactical_slots >= self.tactical_limit { + return Err("Tactical timer capacity exceeded".into()); + } + self.tactical_slots += 1; + self.tactical_timers.push(timer); + Ok(()) + } + pub(super) fn tac_arrow_launch( + w: &mut World, + flights: &mut projectiles::System, + from: [f64; 2], + target: Id, + arrow: Arrow, + ) -> Result<(), String> { + flights.add( + w, + projectiles::Launch { + from, + source: Some(arrow.source), + target: Some(target), + to: None, + speed: 16., + hit_dead: matches!(arrow.kind, ArrowKind::Pursuit), + max_age: 10., + on_hit: true, + visual: "arrow".into(), + speed_changeable: None, + removable: None, + payload: allies::Shot::Tactical(arrow), + }, + )?; + Ok(()) + } + pub(super) fn tac_fire( + &mut self, + w: &mut World, + id: Id, + target: Id, + kind: ArrowKind, + scale: f64, + hits: u32, + ) -> Result<(), String> { + let mut seen = [0; 5]; + seen[0] = target; + Self::tac_arrow_launch( + w, + self.flights + .as_mut() + .ok_or("Missing tactical projectiles")?, + w.unit(id)?.position, + target, + Arrow { + source: id, + kind, + scale, + hits, + seen, + count: 1, + }, + ) + } + pub(super) fn tactical_arrow( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + arrow: Arrow, + target: Option, + position: [f64; 2], + ) -> Result<(), String> { + let def = self.tac_def(arrow.source)?; + let mut scale = arrow.scale; + if let Tactics::Snhunt(p) = &def.extra.tactics { + scale = self.snhunt_arrow_scale(w, target, scale, p)?; + } + if let Some(t) = target { + for _ in 0..arrow.hits { + if !w.unit(t)?.stats.alive { + break; + } + let amount = Self::tac_stat(w, arrow.source, "atk")? * scale; + self.tac_damage( + w, + r, + arrow.source, + t, + amount, + DamageType::Physical, + false, + "specialArrow", + )?; + } + } + if matches!(arrow.kind, ArrowKind::Pursuit) && arrow.hits > 1 { + self.archet_continue_arrow(w, arrow, position)?; + } + Ok(()) + } + + pub(super) fn tactical_scheduled(&mut self, w: &mut World) -> Result<(), String> { + let mut r = self.buffs.take().ok_or("Missing tactical buffs")?; + let mut ids = std::mem::take(&mut self.scratch); + let result: Result<(), String> = (|| { + self.flush_kit_events(w, &mut r)?; + ids.clear(); + ids.extend_from_slice(self.roster.as_ref().unwrap().ids()); + enum Due { + Timer(Timer), + KitAura(Id), + Periodic(Id, super::advanced::Periodic), + Equipment(Id, super::super::equipment::Timer), + Bond(super::bonds::Periodic), + } + // Fixed operator periods and dynamically created timers share deadline order. + // Periodic registrations precede combat-created timers when deadlines are equal. + let mut due: Vec<_> = self + .advanced_deadlines(w)? + .into_iter() + .map(|(at, id, kind)| (at, Due::Periodic(id, kind))) + .collect(); + for &id in &ids { + let definition = &self.roster.as_ref().unwrap().entry(id)?.definition; + if matches!(definition.extra.tactics, Tactics::Ines(_)) { + let at = w.unit(id)?.operator.tactical.next[1].max(0.2); + if at <= w.time + 1e-9 { + due.push((at, Due::KitAura(id))); + } + } + } + due.extend( + self.bond_deadlines(w) + .into_iter() + .map(|(at, kind)| (at, Due::Bond(kind))), + ); + due.extend( + self.equipment_deadlines(w) + .into_iter() + .map(|(at, unit, index)| (at, Due::Equipment(unit, index))), + ); + due.extend( + std::mem::take(&mut self.tactical_timers) + .into_iter() + .map(|timer| (timer.at, Due::Timer(timer))), + ); + due.sort_by(|a, b| a.0.total_cmp(&b.0)); + for (_, event) in due { + let mut timer = match event { + Due::Timer(timer) => timer, + Due::KitAura(id) => { + let next = &mut w.unit_mut(id)?.operator.tactical.next[1]; + *next = next.max(0.2) + 0.2; + self.kit_event_for( + w, + &mut r, + id, + &mut kits::dispatch::Event::Scheduled([ + false, true, false, false, false, + ]), + )?; + continue; + } + Due::Periodic(id, kind) => { + self.advanced_periodic(w, &mut r, &ids, id, kind)?; + continue; + } + Due::Bond(kind) => { + self.bond_periodic(w, &mut r, kind)?; + continue; + } + Due::Equipment(unit, index) => { + self.equipment_periodic(w, &mut r, unit, index)?; + continue; + } + }; + if w.time + 1e-9 < timer.at { + self.tactical_timers.push(timer); + continue; + } + let mut complete = true; + if self.tac_run_timer(w, &mut r, &mut timer)? { + timer.left -= 1; + timer.at += timer.interval; + complete = timer.left == 0; + } + if complete { + self.tactical_slots -= 1; + if let Task::Enemy(task) = timer.kind { + for reference in + [timer.source, task.retained_target()].into_iter().flatten() + { + w.unpin_unit(reference)?; + } + } + } else { + self.tactical_timers.push(timer); + } + } + self.tactical_sync_zones(w, &mut r)?; + self.dispatch_scheduled_kits(w, &mut r)?; + self.tactical_sync_injury(w, &mut r)?; + Ok(()) + })(); + self.scratch = ids; + self.buffs = Some(r); + result + } + pub(super) fn tac_leader(&self, w: &World, id: Id) -> Result { + let character = self.tac_def(id)?.char_id.clone(); + Ok(self + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .copied() + .find(|&a| Self::tac_up(w, a) && self.tac_def(a).is_ok_and(|d| d.char_id == character)) + == Some(id)) + } + + pub(super) fn tac_run_timer( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + t: &mut Timer, + ) -> Result { + if let Task::Enemy(task) = &mut t.kind { + return self.enemy_task(w, r, t.source, task, t.left == 1); + } + let id = t.source.ok_or("Operator timer requires a source")?; + if !matches!( + t.kind, + Task::Zone { .. } + | Task::Blast { .. } + | Task::Gap { .. } + | Task::AreaCallback { + survives_retreat: true, + .. + } + ) && (!Self::tac_up(w, id) || w.unit(id)?.deployment.deploy_seq != t.seq) + { + return Ok(false); + } + match &mut t.kind { + Task::Enemy(_) => unreachable!("Enemy timers are handled before operator dispatch"), + Task::KeyedCallback { key, callback } => { + callback( + &mut kits::dispatch::Context { + host: self, + world: w, + buffs: r, + unit: id, + }, + *key, + )?; + Ok(true) + } + Task::AreaCallback { + position, + attack, + callback, + .. + } => { + callback( + &mut kits::dispatch::Context { + host: self, + world: w, + buffs: r, + unit: id, + }, + *position, + *attack, + )?; + Ok(true) + } + Task::Callback(callback) => { + callback(&mut kits::dispatch::Context { + host: self, + world: w, + buffs: r, + unit: id, + })?; + Ok(true) + } + Task::Zone { .. } => self.tinman_zone_timer(w, r, t), + Task::Storm { .. } => self.pasngr_storm_timer(w, r, t), + Task::Icicle { .. } => self.sntlla_icicle_timer(w, r, t), + Task::Blast { .. } => self.philae_blast_timer(w, r, t), + Task::Explosion { .. } => self.qiubai_explosion_timer(w, r, t), + Task::Gap { .. } => self.qiubai_gap_timer(w, r, t), + } + } + + pub(super) fn tac_faction(&self, id: Id, faction: &str) -> Result { + let def = self.tac_def(id)?; + Ok(self.data.table("chess").unwrap()[&def.key]["nationId"] == faction) + } +} +pub(super) const GAP_FINISH: u64 = 1406; diff --git a/crates/engine/src/battle/runtime/terrain.rs b/crates/engine/src/battle/runtime/terrain.rs new file mode 100644 index 0000000..222c117 --- /dev/null +++ b/crates/engine/src/battle/runtime/terrain.rs @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +impl Host { + pub(super) fn field_terrain( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + id: Id, + fresh: bool, + ) -> Result<(), String> { + if self.devices.elevated(w.unit(id)?.deployment.tile) + && w.unit(id)?.side == health::Side::Ally + { + w.unit_mut(id)?.ground = false; + } + Arc::clone(&self.terrain).refresh(w, r, self, id, fresh) + } + pub(super) fn refresh_terrain( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + ) -> Result<(), String> { + if !self.terrain.active() { + return Ok(()); + } + let ids: Vec<_> = self + .roster + .as_ref() + .unwrap() + .ids() + .iter() + .chain(self.spawns.as_ref().unwrap().live()) + .copied() + .collect(); + for id in ids { + self.field_terrain(w, r, id, false)?; + } + Ok(()) + } + pub(super) fn terrain_damage( + &mut self, + w: &mut World, + r: &mut buffs::Runtime, + c: buffs::Context, + deep: bool, + ) -> Result<(), String> { + let amount = r.get(w, c.unit, c.buff)?.runtime.tick_payload; + if amount <= 0. || !w.unit(c.unit)?.stats.alive { + return Ok(()); + } + let mut q = hit::Request::new( + health::Hit { + source: None, + credit: None, + target: c.unit, + damage_type: super::super::damage::DamageType::True, + no_sp: deep, + silent: false, + hp_loss: false, + on_applied: false, + }, + super::super::damage::Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.dodge_mode = super::super::injury::DodgeMode::Ignore; + q.tags = if deep { + vec!["dot".into(), "periodic".into(), "deepsea".into()] + } else { + vec!["terrain".into()] + }; + self.enemy_damage(w, r, &mut q)?; + Ok(()) + } +} diff --git a/crates/engine/src/battle/runtime/turrets.rs b/crates/engine/src/battle/runtime/turrets.rs new file mode 100644 index 0000000..7884857 --- /dev/null +++ b/crates/engine/src/battle/runtime/turrets.rs @@ -0,0 +1,396 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Map turrets share targeting, projectile retention and damage settlement. +use super::devices::{device_position, num, Hooks}; +use super::*; +use crate::battle::{ + cadence, + damage::{Damage, DamageType}, + deploy, projectiles, + stats::{Base, UnitStats}, + targeting, +}; + +pub(super) struct Turret { + id: Id, + alias: String, + keys: Vec, + base_aspd: f64, + aspd_per: f64, + aspd_max: f64, + fragile_per: f64, + fragile_max: f64, + fragile_duration: f64, + cooldown: f64, +} +#[derive(Clone, Copy)] +pub(super) struct Shot { + source: Id, + attack: u64, + fragile: f64, + duration: f64, +} +impl Core { + pub(super) fn spawn_map_unit( + &mut self, + tile: [i32; 2], + stats: &Value, + crate_hp: Option, + ) -> Result { + let base = Base( + [ + ( + "maxHp", + crate_hp + .unwrap_or_else(|| num(&stats["maxHp"], 100.)) + .max(1.), + ), + ("atk", num(&stats["atk"], 0.).max(0.)), + ("def", num(&stats["def"], 0.).max(0.)), + ("res", num(&stats["res"], 0.).clamp(0., 100.)), + ("aspd", num(&stats["aspd"], 100.).max(1.)), + ("bat", num(&stats["bat"], 1.).max(0.001)), + ("blockCnt", if crate_hp.is_some() { 99. } else { 0. }), + ("cost", 0.), + ("spRecovery", 0.), + ("tauntLevel", -1.), + ] + .into_iter() + .map(|(k, v)| (k.into(), v)) + .collect(), + ); + let id = self.world.next_unit_id()?; + let mut u = health::Unit::new(UnitStats::new(base), health::Side::Ally); + u.stats.alive = false; + u.ground = true; + u.owner = if crate_hp.is_none() { Some(1) } else { None }; + u.deployment.kind = deploy::Kind::Device; + u.deployment.home = tile; + self.world.insert_unit(id, u)?; + let mut roster = self.host.roster.take().unwrap(); + let mut buffs = self.host.buffs.take().unwrap(); + let result = (|| { + roster.deployment_mut().register(id, &self.world)?; + roster.deployment_mut().deploy( + &mut self.world, + &mut Hooks { + host: &mut self.host, + buffs: &mut buffs, + }, + id, + deploy::Options::default(), + ) + })(); + self.host.roster = Some(roster); + self.host.buffs = Some(buffs); + result?; + self.host.devices.ids.push(id); + if crate_hp.is_some() { + self.host + .grid + .as_mut() + .unwrap() + .set_obstacle(tile, true, super::super::grid::CRATE)?; + } + Ok(id) + } + fn turret_tile(&self, origin: [i32; 2]) -> Result, String> { + let grid = self.host.grid.as_ref().unwrap(); + let mut best: Option<([f64; 4], [i32; 2])> = None; + let rect = grid.rect(); + for row in rect.r0..=rect.r1 { + for col in rect.c0..=rect.c1 { + let at = [row, col]; + if self + .host + .roster + .as_ref() + .unwrap() + .deployment() + .reserved(&self.world, at)? + { + continue; + } + let exact = at == origin; + let tile = &grid.tiles()[row as usize * COLS + col as usize]; + if !exact && tile.build != "NONE" { + continue; + } + let score = [ + if exact { 0. } else { 1. }, + if !exact && grid.ground_passable(at, true) { + 1. + } else { + 0. + }, + crate::deterministic::math::hypot( + (row - origin[0]) as f64, + (col - origin[1]) as f64, + ), + (row as usize * COLS + col as usize) as f64, + ]; + let less = best.as_ref().is_none_or(|(b, _)| { + for i in 0..4 { + if score[i] < b[i] - 1e-9 { + return true; + } + if score[i] > b[i] + 1e-9 { + return false; + } + } + false + }); + if less { + best = Some((score, at)); + } + } + } + Ok(best.map(|(_, at)| at)) + } + pub(super) fn start_map_devices(&mut self) -> Result<(), String> { + for (tile, hp) in self.host.devices.added.clone() { + if self + .host + .roster + .as_ref() + .unwrap() + .deployment() + .occupant(tile) + .is_none() + { + self.spawn_map_unit(tile, &Value::Null, Some(hp))?; + } + } + let stage = self.host.devices.stage.clone(); + for d in stage["devices"].as_array().into_iter().flatten() { + if d["role"] != "turret" && d["key"] != "trap_1104_aclasert" { + continue; + } + let origin = device_position(d); + let alias = d["alias"].as_str().map(str::to_owned).unwrap_or_else(|| { + format!( + "{}@{},{}", + d["key"].as_str().unwrap_or(""), + origin[0], + origin[1] + ) + }); + let on = self + .host + .devices + .config + .device_overrides + .get(&alias) + .copied() + .unwrap_or_else(|| d["active"].as_bool().unwrap_or(d["hidden"] != true)); + if !on || self.host.devices.turrets.iter().any(|t| t.alias == alias) { + continue; + } + let raw = d.get("raw").unwrap_or(d); + let mut keys = Vec::new(); + for p in raw["rangeTiles"].as_array().into_iter().flatten() { + let at = [ + p[0].as_i64().unwrap_or(-1) as i32, + p[1].as_i64().unwrap_or(-1) as i32, + ]; + if self.host.grid.as_ref().unwrap().in_rect(at) { + let key = at[0] as usize * COLS + at[1] as usize; + if !keys.contains(&key) { + keys.push(key); + } + } + } + if keys.is_empty() { + continue; + } + let Some(tile) = self.turret_tile(origin)? else { + continue; + }; + let stats = &raw["stats"]; + let id = self.spawn_map_unit(tile, stats, None)?; + let skill = &raw["skill"]; + let bb = &skill["bb"]; + let text = skill["desc"] + .as_str() + .or(skill["description"].as_str()) + .unwrap_or(""); + let duration = text + .split_once("持续") + .and_then(|(_, s)| s.split_once('秒')) + .and_then(|(s, _)| s.parse::().ok()) + .unwrap_or(0.); + self.host.devices.turrets.push(Turret { + id, + alias, + keys, + base_aspd: self.world.unit(id)?.stats.base_number("aspd"), + aspd_per: num(&bb["attack_speed_per_stack"], 0.), + aspd_max: num(&bb["max_attack_speed"], f64::INFINITY), + fragile_per: num(&bb["damage_scale_per_stack"], 0.), + fragile_max: num(&bb["max_damage_scale"], f64::INFINITY), + fragile_duration: duration, + cooldown: 0., + }); + } + Ok(()) + } + pub(super) fn tick_turrets(&mut self, dt: f64) -> Result<(), String> { + for i in 0..self.host.devices.turrets.len() { + let t = &mut self.host.devices.turrets[i]; + let id = t.id; + if !self.world.unit(id)?.stats.alive { + continue; + } + t.cooldown = cadence::countdown(t.cooldown, dt); + if t.cooldown > 0. + || self + .world + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .flags + .contains("stun") + { + continue; + } + let layers = self.host.devices.config.top_layers; + let aspd = t.base_aspd + (layers * t.aspd_per).min(t.aspd_max); + if (self.world.unit(id)?.stats.base_number("aspd") - aspd).abs() > 1e-9 { + self.world.unit_mut(id)?.stats.edit_base(|b| { + b.0.insert("aspd".into(), aspd); + }); + } + let keys = t.keys.clone(); + let mut targets = Vec::new(); + for enemy in self.host.spawns.as_ref().unwrap().live().to_vec() { + if super::super::body::in_range(self.world.unit(enemy)?, &keys) + && targeting::can_target_enemy( + &mut self.world, + &mut self.host, + Some(id), + enemy, + targeting::Profile { + can_hit_fly: true, + ..Default::default() + }, + )? + { + targets.push(enemy); + } + } + targeting::sort_enemies( + &mut self.world, + &mut self.host, + id, + &mut targets, + targeting::Priority::None, + )?; + let Some(&target) = targets.first() else { + self.host.devices.turrets[i].cooldown = 0.; + continue; + }; + let attack = self.world.next_attack_id()?; + let time = self.world.time; + let u = self.world.unit_mut(id)?; + u.attacks = u + .attacks + .checked_add(1) + .ok_or("Turret attack count exhausted")?; + u.last_attack_at = time; + u.engaged = true; + let t = &mut self.host.devices.turrets[i]; + let payload = Shot { + source: id, + attack, + fragile: (1. + layers * t.fragile_per).min(t.fragile_max) - 1., + duration: t.fragile_duration, + }; + t.cooldown = self + .world + .unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("interval"); + let from = self.world.unit(id)?.position; + self.host.flights.as_mut().unwrap().add( + &mut self.world, + projectiles::Launch { + from, + source: Some(id), + target: Some(target), + to: None, + speed: 11., + hit_dead: false, + max_age: 10., + on_hit: true, + visual: "bolt".into(), + speed_changeable: None, + removable: None, + payload: allies::Shot::Turret(payload), + }, + )?; + } + Ok(()) + } +} +impl Host { + pub(super) fn turret_impact( + &mut self, + w: &mut World, + shot: Shot, + target: Option, + ) -> Result<(), String> { + let Some(target) = target else { return Ok(()) }; + if !w.unit(target)?.stats.alive { + return Ok(()); + } + let amount = w + .unit_mut(shot.source)? + .stats + .stats() + .map_err(str::to_string)? + .n("atk"); + let mut q = hit::Request::new( + health::Hit { + source: Some(shot.source), + credit: Some(shot.source), + target, + damage_type: DamageType::Arts, + no_sp: false, + silent: false, + hp_loss: false, + on_applied: false, + }, + Damage { + amount, + mul: 1., + resolved: false, + penetration: Default::default(), + }, + ); + q.is_attack = true; + q.attack_id = Some(shot.attack); + let mut buffs = self.buffs.take().unwrap(); + let result = (|| { + self.enemy_damage(w, &mut buffs, &mut q)?; + if shot.fragile > 0. && shot.duration > 0. && w.unit(target)?.stats.alive { + self.apply_status( + w, + &mut buffs, + target, + "fragile", + super::super::status::Options { + source: Some(shot.source), + duration: shot.duration, + value: Some(shot.fragile), + ..Default::default() + }, + )?; + } + Ok(()) + })(); + self.buffs = Some(buffs); + result + } +} diff --git a/crates/engine/src/battle/search.rs b/crates/engine/src/battle/search.rs index 0a9bf3c..fa0dac4 100644 --- a/crates/engine/src/battle/search.rs +++ b/crates/engine/src/battle/search.rs @@ -3,6 +3,7 @@ use super::{ grid::COLS, health::{Id, World}, + stats::Stat, targeting::{self, Priority, Profile, Queries}, }; use std::collections::BTreeMap; @@ -109,11 +110,11 @@ fn take(mut ids: Vec, n: f64) -> Vec { ids.truncate(end); ids } -fn number(w: &mut World, id: Id, key: &str) -> Result { +fn number(w: &mut World, id: Id, stat: Stat) -> Result { w.unit_mut(id)? .stats .stats() - .map(|s| s.n(key)) + .map(|s| s.get(stat)) .map_err(str::to_string) } pub fn acquire( @@ -135,7 +136,7 @@ pub fn acquire( if heal.hp_at_most > 0.0 { let mut eligible = Vec::with_capacity(c.len()); for target in c { - let max = number(w, target, "maxHp")?; + let max = number(w, target, Stat::MaxHp)?; let hp = w.unit(target)?.stats.hp; let ratio = if max > 0.0 { hp / max } else { 0.0 }; if ratio <= heal.hp_at_most + 1e-9 { @@ -162,7 +163,7 @@ pub fn acquire( if p.max_targets > n { n = p.max_targets.floor(); } - let extra = number(w, id, "maxTargets")?.floor().max(0.0); + let extra = number(w, id, Stat::MaxTargets)?.floor().max(0.0); return Ok(Selection { targets: take(c, n + extra), fortress_melee: None, @@ -258,6 +259,9 @@ pub struct Commitments { max_total: usize, } impl Commitments { + pub(crate) fn clear(&mut self) { + self.entries.clear(); + } pub fn new(max_units: usize, max_targets: usize, max_total: usize) -> Result { if [max_units, max_targets, max_total].contains(&0) { return Err("Commitment limits must be positive".into()); diff --git a/crates/engine/src/battle/settlement.rs b/crates/engine/src/battle/settlement.rs index f78cdbc..1c7d5ab 100644 --- a/crates/engine/src/battle/settlement.rs +++ b/crates/engine/src/battle/settlement.rs @@ -23,6 +23,16 @@ pub trait Hooks: buffs::Hooks + Sized { ) -> HookResult { self.kill(target, credit, w) } + fn damage_kill( + &mut self, + target: Id, + credit: Option, + r: &mut Runtime, + w: &mut World, + _rng: &mut Rng, + ) -> HookResult { + self.health_kill(target, credit, r, w) + } fn phase_enabled(&self, _phase: Phase) -> bool { false } @@ -54,7 +64,13 @@ pub trait Hooks: buffs::Hooks + Sized { ) -> HookResult { Ok(()) } - fn damage_cleanup(&mut self, _token: u64, _r: &mut Runtime, _w: &mut World) -> HookResult { + fn damage_cleanup( + &mut self, + _token: u64, + _target: Id, + _r: &mut Runtime, + _w: &mut World, + ) -> HookResult { Err("Deferred injury cleanup handler not installed".into()) } fn health_event( @@ -369,8 +385,8 @@ impl hit::Hooks for Pipeline<'_, H> { ignore_block, ) } - fn cleanup(&mut self, token: u64, w: &mut World) -> HookResult { - self.h.damage_cleanup(token, self.r, w) + fn cleanup(&mut self, token: u64, target: Id, w: &mut World) -> HookResult { + self.h.damage_cleanup(token, target, self.r, w) } fn transfers( &mut self, @@ -400,7 +416,9 @@ impl health::Hooks for DamageEvents<'_, '_, H> { self.pipeline.hit_cap(target, amount) } fn kill(&mut self, target: Id, credit: Option, w: &mut World) -> HookResult { - self.pipeline.kill(target, credit, w) + self.pipeline + .h + .damage_kill(target, credit, self.pipeline.r, w, self.rng) } fn heal_through(&mut self, source: Id, target: Id, w: &World) -> bool { self.pipeline.heal_through(source, target, w) @@ -424,6 +442,27 @@ pub fn resolve( request: &mut Request, ) -> Result { r.call(|r| { + if request.hit.hp_loss { + request.hit.no_sp = true; + if !request.tags.iter().any(|tag| tag == "hpLoss") { + request.tags.push("hpLoss".into()); + } + let hit = request.hit; + let amount = request.damage.amount; + let penetration = request.damage.penetration; + return health::lose_hp( + w, + &mut DamageEvents { + pipeline: &mut Pipeline { h, r }, + request, + rng, + }, + hit, + amount, + penetration, + false, + ); + } // Empty legacy callback argument: the canonical backend never reads or writes it. // BTreeMap::new allocates no pool; all effects remain in World.unit.stats.buffs. let mut unused = Effects::new(1)?; diff --git a/crates/engine/src/battle/skills.rs b/crates/engine/src/battle/skills.rs index 583b785..1fe9f6d 100644 --- a/crates/engine/src/battle/skills.rs +++ b/crates/engine/src/battle/skills.rs @@ -115,6 +115,7 @@ impl Default for Spec { } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Event { + Deploy, ApplyModifiers, RemoveModifiers, RefreshRange, @@ -161,6 +162,9 @@ pub enum Condition { /// Condition handlers only resolve geometric/content predicates; casting policy is /// owned here. Errors fault the runtime and must not become valid rollout samples. pub trait Hooks { + fn can_activate(&mut self, _skill: &Runtime, _w: &mut World) -> Result { + Ok(true) + } fn event( &mut self, event: Event, @@ -172,6 +176,7 @@ pub trait Hooks { fn profile(&mut self, id: Id, w: &mut World) -> Result>; fn has_sp_hook(&self) -> bool; } +#[derive(Clone)] pub struct Runtime { pub bank: Bank, pub spec: Spec, @@ -216,6 +221,18 @@ impl Runtime { faulted: false, }) } + /// Move the canonical state into a nested callback. The caller must put the + /// returned state back before using this runtime again; the vacancy is faulted. + pub(crate) fn take_for_callback(&mut self) -> Result { + let mut vacant = Self::new( + Bank::new(self.unit(), Kind::Passive, 0., 1, 1)?, + Spec::default(), + self.max_depth, + )?; + vacant.bank.no_skill = true; + vacant.faulted = true; + Ok(std::mem::replace(self, vacant)) + } pub fn unit(&self) -> Id { self.bank.unit } @@ -411,6 +428,9 @@ impl Runtime { if !u.stats.alive || !u.deployed { return Ok(false); } + if !h.can_activate(self, w)? { + return Ok(false); + } if !free { let full = self.bank.charges >= self.bank.max_charges() as f64; self.bank.charges -= 1.0; @@ -497,6 +517,14 @@ impl Runtime { } Ok(()) } + pub(crate) fn consume_ammo(&mut self, w: &mut World, h: &mut H) -> Result<()> { + self.ammo_left -= 1.; + self.emit(h, w, Event::AmmoUsed, &mut Context::reason(""))?; + if self.bank.active && self.ammo_left <= 0. { + self.end(w, h, "ammo")?; + } + Ok(()) + } pub fn add_ammo(&mut self, n: f64) { if self.bank.active && self.bank.kind == Kind::Ammo && n.is_finite() { self.ammo_left += n; @@ -548,11 +576,7 @@ impl Runtime { } if self.bank.active && self.bank.kind == Kind::Ammo { if !no_ammo { - self.ammo_left -= 1.0; - self.emit(h, w, Event::AmmoUsed, &mut Context::reason(""))?; - if self.ammo_left <= 0.0 { - self.end(w, h, "ammo")?; - } + self.consume_ammo(w, h)?; } } else if used_override && self.pending && !self.bank.kind.timed() { self.pending = false; @@ -745,136 +769,3 @@ pub fn can_act(w: &mut World, id: Id) -> Result { .flags .contains("stun")) } - -#[cfg(test)] -mod tests { - use super::super::{ - health::{Side, Unit}, - sp, - stats::{Base, Buff, UnitStats}, - }; - use super::*; - struct Host { - recast: bool, - events: Vec, - end_atk: Option, - } - impl Hooks for Host { - fn event( - &mut self, - e: Event, - _: &mut Context, - s: &mut Runtime, - w: &mut World, - ) -> Result<()> { - self.events.push(e); - match e { - Event::ApplyModifiers => w.unit_mut(1)?.stats.put_named_buff( - "skill", - Buff { - mods: [("atkPct".into(), 0.5)].into_iter().collect(), - ..Buff::default() - }, - 4, - )?, - Event::RemoveModifiers => w.unit_mut(1)?.stats.remove_named_buff("skill"), - Event::End => { - self.end_atk = Some(number(w, 1, "atk")?); - if self.recast { - self.recast = false; - s.activate(w, self, "restart", true)?; - } - } - _ => {} - } - Ok(()) - } - fn condition(&mut self, _: Condition, _: &Runtime, _: &mut World) -> Result { - Ok(true) - } - fn profile(&mut self, _: Id, _: &mut World) -> Result> { - Ok(Some(AttackProfile::default())) - } - fn has_sp_hook(&self) -> bool { - false - } - } - fn setup(depth: usize) -> (World, Runtime, Host) { - let mut w = World::new(1, 1, 1).unwrap(); - let mut b = Base::default(); - b.0.insert("atk".into(), 100.0); - let mut u = Unit::new(UnitStats::new(b), Side::Ally); - u.deployed = true; - w.insert_unit(1, u).unwrap(); - let bank = Bank::new(1, Kind::Duration, 3.0, 1, 4).unwrap(); - let s = Runtime::new( - bank, - Spec { - duration: 1.0, - init_sp: 3.0, - modifiers: true, - sp_type: SpType::Attack, - ..Spec::default() - }, - depth, - ) - .unwrap(); - ( - w, - s, - Host { - recast: false, - events: vec![], - end_atk: None, - }, - ) - } - #[test] - fn end_reads_live_modifiers_and_reactivation_keeps_new_cast() { - let (mut w, mut s, mut h) = setup(32); - s.reset(&mut w, &mut h, None).unwrap(); - s.activate(&mut w, &mut h, "manual", false).unwrap(); - h.recast = true; - s.end(&mut w, &mut h, "end").unwrap(); - assert_eq!(h.end_atk, Some(150.0)); - assert!(s.bank.active); - assert_eq!(s.activations, 2); - assert!(!h.events.contains(&Event::RemoveModifiers)); - assert_eq!(number(&mut w, 1, "atk").unwrap(), 150.0); - s.end(&mut w, &mut h, "end").unwrap(); - assert_eq!(number(&mut w, 1, "atk").unwrap(), 100.0); - } - #[test] - fn last_ammo_attack_does_not_recover_attack_sp() { - let (mut w, mut s, mut h) = setup(32); - s.bank.kind = Kind::Ammo; - s.spec.ammo = 1.0; - s.reset(&mut w, &mut h, None).unwrap(); - s.activate(&mut w, &mut h, "manual", false).unwrap(); - s.after_attack(&mut w, &mut h, &[1], true, false).unwrap(); - assert!(!s.bank.active); - assert_eq!(s.bank.total(&mut w).unwrap(), 0.0); - s.after_attack(&mut w, &mut h, &[1], false, false).unwrap(); - assert_eq!(s.bank.sp, 1.0); - } - #[test] - fn recursion_error_faults_skill_without_creating_terminal_result() { - let (mut w, mut s, mut h) = setup(1); - assert!(s.reset(&mut w, &mut h, None).is_err()); - assert!(s.faulted()); - assert!(s.tick(&mut w, &mut h, 1.0 / 30.0).is_err()); - } - #[test] - fn default_cast_skips_operation_cooling_and_time_cast_waits() { - let (mut w, mut s, mut h) = setup(32); - s.bank.kind = sp::Kind::Instant; - s.spec.sp_type = SpType::None; - s.reset(&mut w, &mut h, None).unwrap(); - assert!(s.about_to_attack(&mut w, &mut h).unwrap()); - assert_eq!(s.next_cast_at, f64::NEG_INFINITY); - s.bank.add_charge(&mut w, 1.0).unwrap(); - assert!(!s.about_to_attack(&mut w, &mut h).unwrap()); - w.time = 3.0; - assert!(s.about_to_attack(&mut w, &mut h).unwrap()); - } -} diff --git a/crates/engine/src/battle/sp.rs b/crates/engine/src/battle/sp.rs index 93a1d12..dc5abdc 100644 --- a/crates/engine/src/battle/sp.rs +++ b/crates/engine/src/battle/sp.rs @@ -1,7 +1,10 @@ // SPDX-License-Identifier: GPL-3.0-or-later // Stronghold Protocol 41bbca57 SkillRuntime SP accounting. Cast/trigger/content // state transitions are implemented separately; this owns the charge arithmetic. -use super::health::{Id, World}; +use super::{ + health::{Id, World}, + stats::Stat, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { Instant, @@ -35,6 +38,7 @@ impl Hooks for NoHooks { Ok(()) } } +#[derive(Clone)] pub struct Bank { pub unit: Id, pub kind: Kind, @@ -77,6 +81,13 @@ impl Bank { max_charges, }) } + pub(crate) fn clear_inactive(&mut self, w: &mut World) -> Result<(), String> { + if !self.no_skill && self.kind != Kind::Passive && !self.active && self.cost(w)? > 0. { + self.sp = 0.; + self.charges = 0.; + } + Ok(()) + } pub fn max_charges(&self) -> u32 { self.max_charges } @@ -89,7 +100,7 @@ impl Bank { .stats .stats() .map_err(str::to_string)? - .n("spCostFlat"); + .get(Stat::SpCostFlat); let c = (self.base_cost * self.cost_mul + flat).floor(); Ok(if c.is_finite() { c.max(0.0) @@ -258,7 +269,7 @@ impl Bank { if s.flags.contains("noSp") || !alive || !u.deployed || u.hidden { return Ok(0.0); } - let rate = s.n("spRecovery"); + let rate = s.get(Stat::SpRecovery); if rate > 0.0 { self.gain(w, h, rate * dt, "time", false, false) } else { @@ -266,72 +277,3 @@ impl Bank { } } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::battle::{ - health::{Side, Unit}, - stats::{Base, Buff, UnitStats}, - }; - fn world() -> World { - let mut w = World::new(1, 1, 1).unwrap(); - let mut u = Unit::new(UnitStats::new(Base::default()), Side::Ally); - u.deployed = true; - w.insert_unit(1, u).unwrap(); - w - } - #[test] - fn natural_recovery_ignores_stun_but_obeys_no_sp_and_full_timed_skill_lock() { - let mut w = world(); - let mut bank = Bank::new(1, Kind::Duration, 10.0, 2, 8).unwrap(); - w.unit_mut(1).unwrap().stats.set_buffs(vec![Buff { - flags: ["stun".into()].into_iter().collect(), - ..Buff::default() - }]); - for _ in 0..300 { - bank.recover_time(&mut w, &mut NoHooks, 1.0 / 30.0).unwrap(); - } - assert_eq!(bank.charges, 1.0); - assert_eq!(bank.sp, 0.0); - assert!(bank.ready()); - bank.active = true; - assert_eq!(bank.recover_time(&mut w, &mut NoHooks, 1.0).unwrap(), 0.0); - bank.active = false; - w.unit_mut(1).unwrap().stats.set_buffs(vec![Buff { - flags: ["noSp".into()].into_iter().collect(), - ..Buff::default() - }]); - assert_eq!(bank.recover_time(&mut w, &mut NoHooks, 1.0).unwrap(), 0.0); - assert_eq!( - bank.gain(&mut w, &mut NoHooks, 1.0, "gift", false, true) - .unwrap(), - 1.0 - ); - assert_eq!(bank.sp, 1.0); - } - #[test] - fn free_skills_and_running_skill_carry_are_distinct() { - let mut w = world(); - let mut free = Bank::new(1, Kind::Instant, 0.0, 2, 8).unwrap(); - free.set_total(&mut w, 0.0).unwrap(); - assert_eq!(free.charges, 2.0); - assert!(free.ready()); - assert_eq!( - free.gain(&mut w, &mut NoHooks, 3.0, "time", false, false) - .unwrap(), - 0.0 - ); - let mut timed = Bank::new(1, Kind::Duration, 5.0, 2, 8).unwrap(); - timed.set_total(&mut w, 7.0).unwrap(); - assert_eq!(timed.charges, 1.0); - assert_eq!(timed.sp, 2.0); - timed.active = true; - timed.set_total(&mut w, 0.0).unwrap(); - assert_eq!(timed.total(&mut w).unwrap(), 7.0); - } - #[test] - fn excessive_charge_capacity_is_rejected() { - assert!(Bank::new(1, Kind::Charges, 1.0, 100, 8).is_err()); - } -} diff --git a/crates/engine/src/battle/spatial.rs b/crates/engine/src/battle/spatial.rs index dda23d4..084f0eb 100644 --- a/crates/engine/src/battle/spatial.rs +++ b/crates/engine/src/battle/spatial.rs @@ -3,10 +3,10 @@ use super::{ body, grid::N, - health::{Id, World}, + health::{Id, Side, World}, targeting::{self, Profile, Queries}, }; -use std::collections::BTreeMap; +use std::collections::HashMap; /// Content may permit a particular healer to bypass a target's noHeal flag. /// The target profile's noHeal restriction still applies. pub trait Healing { @@ -60,14 +60,11 @@ pub fn enemies_in_radius( let mut out = vec![]; for id in candidates { if foes { - let f = w - .unit_mut(id)? - .stats - .stats() - .map_err(str::to_string)? - .flags - .clone(); - if f.contains("untargetable") || f.contains("stealth") && q.enemy_stealthed(id, w)? { + let (untargetable, stealth) = { + let f = &w.unit_mut(id)?.stats.stats().map_err(str::to_string)?.flags; + (f.contains("untargetable"), f.contains("stealth")) + }; + if untargetable || stealth && q.enemy_stealthed(id, w)? { continue; } } @@ -189,13 +186,29 @@ pub fn injured_allies( pub struct Index { range: Vec>, tiles: Vec>, - multi: BTreeMap, - huge: BTreeMap, + // Lookup only: bucket insertion order, never hash iteration, orders targets. + membership: HashMap, + range_keys: Vec, + range_used: Vec, + tiles_used: Vec, max_enemies: usize, max_rows: usize, valid: bool, } impl Index { + /// Retired units must leave the index before next frame's scheduled queries. + pub fn retire(&mut self, id: Id) { + if self.membership.remove(&id).is_none() { + return; + } + for &key in &self.range_used { + self.range[key].retain(|&candidate| candidate != id); + } + for &key in &self.tiles_used { + self.tiles[key].retain(|&candidate| candidate != id); + } + } + pub fn new(max_enemies: usize, max_rows: usize) -> Result { if max_enemies == 0 || max_rows == 0 { return Err("Spatial index limits must be positive".into()); @@ -203,8 +216,10 @@ impl Index { Ok(Self { range: vec![vec![]; N], tiles: vec![vec![]; N], - multi: BTreeMap::new(), - huge: BTreeMap::new(), + membership: HashMap::new(), + range_keys: Vec::new(), + range_used: Vec::new(), + tiles_used: Vec::new(), max_enemies, max_rows, valid: false, @@ -212,11 +227,14 @@ impl Index { } pub fn rebuild(&mut self, w: &World, enemies: &[Id]) -> Result<(), String> { self.valid = false; - for bucket in self.range.iter_mut().chain(self.tiles.iter_mut()) { - bucket.clear(); + // Node queries.js only resets the buckets used by the previous build. + for key in self.range_used.drain(..) { + self.range[key].clear(); } - self.multi.clear(); - self.huge.clear(); + for key in self.tiles_used.drain(..) { + self.tiles[key].clear(); + } + self.membership.clear(); if enemies.len() > self.max_enemies { return Err("Spatial enemy capacity exceeded".into()); } @@ -226,20 +244,42 @@ impl Index { if !e.stats.alive || e.hidden { continue; } - let range = body::collider_keys(e); - let tiles = body::keys(e); - if self.multi.insert(id, range.len() > 1).is_some() { + let mut point_range = [0; 4]; + let point_tile = body::position_key(e); + let (range, tiles): (&[usize], &[usize]) = + if e.hit_area.is_some() || e.side == Side::Ally { + // Rectangle coverage is identical for the two indices. + body::keys_into(e, &mut self.range_keys); + (&self.range_keys, &self.range_keys) + } else { + let mut len = 0; + body::enemy_collider_keys(e.position, |key| { + point_range[len] = key; + len += 1; + }); + (&point_range[..len], point_tile.as_slice()) + }; + if self + .membership + .insert(id, (range.len() > 1, e.hit_area.is_some())) + .is_some() + { return Err("Duplicate indexed enemy".into()); } - self.huge.insert(id, e.hit_area.is_some()); rows += range.len() + tiles.len(); if rows > self.max_rows { return Err("Spatial row capacity exceeded; no memberships dropped".into()); } - for k in range { + for &k in range { + if self.range[k].is_empty() { + self.range_used.push(k); + } self.range[k].push(id); } - for k in tiles { + for &k in tiles { + if self.tiles[k].is_empty() { + self.tiles_used.push(k); + } self.tiles[k].push(id); } } @@ -268,9 +308,9 @@ impl Index { }; for &id in bucket { let dedup = if tile_rule { - self.huge[&id] + self.membership[&id].1 } else { - self.multi[&id] + self.membership[&id].0 }; if dedup && !seen.insert(id) { continue; diff --git a/crates/engine/src/battle/spawns.rs b/crates/engine/src/battle/spawns.rs index 9ee54aa..bb8d9c8 100644 --- a/crates/engine/src/battle/spawns.rs +++ b/crates/engine/src/battle/spawns.rs @@ -2,7 +2,7 @@ // Stronghold Protocol 41bbca57 battle/spawns.js: native scheduled/runtime spawning. use super::{ definitions::Enemy, - grid::{Grid, COLS}, + grid::{Grid, Rect, COLS}, health::{Id, World}, ledger::{self, Ledger}, motion::Route, @@ -17,17 +17,26 @@ pub trait Hooks { /// A missing ability is a technical error, never an implicit stats-only enemy. fn spawned(&mut self, id: Id, w: &mut World, runtime: &mut Runtime) -> Result<(), String>; fn release(&mut self, id: Id, w: &mut World) -> Result<(), String>; + /// Physical retirement follows the last projectile/effect reference. + fn retired(&mut self, _id: Id, _w: &mut World) -> Result<(), String> { + Ok(()) + } } pub struct Runtime { + devices: Vec, pub queue: Queue, pub ledger: Ledger, definitions: BTreeMap>, units: BTreeMap>, live: Vec, routes: Vec, + patrol_routes: std::collections::BTreeSet, + path_routes: std::collections::BTreeSet, extra_routes: Vec, + branches: BTreeMap>>, overrides: Value, fallback: Value, + rect: Rect, capacity: usize, max_legs: usize, faulted: bool, @@ -67,13 +76,13 @@ impl Runtime { .get(&id) .ok_or("Missing spawned enemy ledger entry")?; let raw = &data.table("enemies").ok_or("Missing enemy data")?[key]; - let kit = super::content::enemies::Kit::compile( + let definition = super::content::enemies::Definition::compile( key, raw, self.content_overrides(key), entry.tag.as_str(), )?; - content.spawn(w, buffs, h, id, kit, &entry.mods) + content.install(w, buffs, h, id, definition, &entry.mods) } pub fn new( data: &Catalog, @@ -129,9 +138,14 @@ impl Runtime { units: BTreeMap::new(), live: vec![], routes: template.routes, + patrol_routes: template.patrol_routes, + path_routes: Default::default(), extra_routes: template.extra_routes, + branches: template.branches, + devices: template.devices, overrides: template.overrides, fallback, + rect: grid.rect(), capacity, max_legs, faulted: false, @@ -147,6 +161,39 @@ impl Runtime { pub fn retained(&self) -> usize { self.units.len() } + pub(crate) fn branch_phase(&self, name: &str) -> Option> { + self.branches.get(name).and_then(|p| p.first()).cloned() + } + pub(crate) fn branch_phases(&self, name: &str) -> usize { + self.branches.get(name).map(Vec::len).unwrap_or(0) + } + pub(crate) fn tentacle_spots(&self, name: &str, phase: usize) -> Vec<[f64; 2]> { + let Some(phases) = self.branches.get(name).filter(|p| !p.is_empty()) else { + return vec![]; + }; + phases[phase.min(phases.len() - 1)] + .iter() + .filter_map(|a| { + let d = self.devices.iter().find(|d| d["alias"] == a["key"])?; + Some([d["pos"][0].as_f64()?, d["pos"][1].as_f64()?]) + }) + .collect() + } + pub(crate) fn branch_route(&self, name: &str) -> Option { + let entry = self.branches.get(name)?.first()?.first()?; + self.extra_routes + .get(entry["routeIndex"].as_u64()? as usize) + .cloned() + } + pub(crate) fn spawn_runtime( + &mut self, + w: &mut World, + h: &mut H, + key: &str, + options: &Value, + ) -> Result { + self.call(|r| r.spawn_in(w, r.rect, None, h, key, options)) + } pub fn extra_routes(&self) -> &[Value] { &self.extra_routes } @@ -190,38 +237,232 @@ impl Runtime { h: &mut H, key: &str, options: &Value, + ) -> Result { + self.call(|r| r.spawn_in(w, g.rect(), Self::exit(g), h, key, options)) + } + pub(crate) fn remaining_route(&self, w: &World, parent: Id) -> Result { + let unit = w.unit(parent)?; + unit.motion + .route + .as_ref() + .ok_or("Missing parent route")? + .remaining(unit.position, self.rect) + } + pub(crate) fn spawn_child( + &mut self, + w: &mut World, + h: &mut H, + key: &str, + mut route: Route, + position: [f64; 2], + mods: &Value, + source_player: &Value, + counted: Option, + tag: Option<&str>, ) -> Result { self.call(|r| { let def = r .definitions .get(key) + .cloned() .ok_or_else(|| format!("Unknown enemy {key}; no fallback substituted"))?; - if !options.is_object() { - return Err("Expected runtime spawn options".into()); - } - let counted = options["countInTotal"].as_bool().unwrap_or( - !def.not_count_in_total && options["tag"] != "boss" && options["tag"] != "part", - ); - let mut spec = options.clone(); - spec["enemyKey"] = json!(key); - // spawn_pending increments the shared scheduled/runtime spawn sequence. - let p = Pending { - time: w.time, - sequence: 0, - spec, - counted, - in_total: options["inTotal"] == true && counted, - precounted: false, + let position = r.clamp_position(position); + route.spawn = position; + let entry = ledger::Enemy { + key: key.into(), + mods: mods.clone(), + lpr: def.lpr, + source_player: source_player.clone(), + tag: tag.map(Value::from).unwrap_or(Value::Null), + counted: counted.unwrap_or(!def.not_count_in_total), + in_total: false, + boss: false, + no_leak: key == "enemy_5601_entlec", + bounty: 0., }; - r.spawn_pending(w, g, h, p) + r.insert(w, h, def, route, position, entry, false) }) } + pub(crate) fn spawn_part( + &mut self, + w: &mut World, + h: &mut H, + key: &str, + position: [f64; 2], + ) -> Result { + let route = Route::compile( + &json!({"motion":"FLY","start":position,"end":position,"steps":[{"t":"WAIT","s":99999}]}), + self.rect, + self.max_legs, + position, + )?; + let source_player = self.ledger.player().clone(); + self.spawn_child( + w, + h, + key, + route, + position, + &Value::Null, + &source_player, + Some(false), + Some("part"), + ) + } + pub(crate) fn rect(&self) -> Rect { + self.rect + } + fn clamp_position(&self, position: [f64; 2]) -> [f64; 2] { + [ + position[0] + .max(self.rect.r0 as f64 - 0.5) + .min(self.rect.r1 as f64 + 0.5), + position[1] + .max(self.rect.c0 as f64 - 0.5) + .min(self.rect.c1 as f64 + 0.5), + ] + } + fn exit(g: &Grid) -> Option<[usize; 2]> { + g.tiles() + .iter() + .position(|t| t.special.as_deref() == Some("end")) + .map(|i| [i / COLS, i % COLS]) + } + fn spawn_in( + &mut self, + w: &mut World, + rect: Rect, + exit: Option<[usize; 2]>, + h: &mut H, + key: &str, + options: &Value, + ) -> Result { + let def = self + .definitions + .get(key) + .ok_or_else(|| format!("Unknown enemy {key}; no fallback substituted"))?; + if !options.is_object() { + return Err("Expected runtime spawn options".into()); + } + let counted = options["countInTotal"].as_bool().unwrap_or( + !def.not_count_in_total && options["tag"] != "boss" && options["tag"] != "part", + ); + let mut spec = options.clone(); + spec["enemyKey"] = json!(key); + // spawn_pending increments the shared scheduled/runtime spawn sequence. + let p = Pending { + time: w.time, + sequence: 0, + spec, + counted, + in_total: options["inTotal"] == true && counted, + precounted: false, + }; + self.spawn_pending_in(w, rect, exit, h, p) + } + pub(crate) fn path_tiles(&mut self, grid: &mut Grid) -> std::collections::BTreeSet { + let used = self + .queue + .pending() + .iter() + .filter(|p| p.spec["route"].is_null()) + .filter_map(|p| { + Some(p.spec["routeIndex"].as_f64().unwrap_or(0.)) + .filter(|v| v.is_finite() && *v >= 0. && v.fract() == 0.) + .map(|v| v as u64) + }) + .collect::>(); + self.path_routes.extend( + used.into_iter() + .filter(|&index| (index as usize) < self.routes.len()), + ); + let used = &self.path_routes; + let restrict = used.iter().any(|&i| { + self.routes + .get(i as usize) + .is_some_and(|r| r["motion"] != "FLY") + }); + let mut keys = std::collections::BTreeSet::new(); + let rect = grid.rect(); + let point = |v: &Value| { + v.as_array().filter(|a| a.len() >= 2).and_then(|p| { + Some([ + (p[0].as_f64()? + 0.5) + .floor() + .clamp(rect.r0 as f64, rect.r1 as f64) as i32, + (p[1].as_f64()? + 0.5) + .floor() + .clamp(rect.c0 as f64, rect.c1 as f64) as i32, + ]) + }) + }; + for (index, route) in self.routes.iter().enumerate() { + if route["motion"] == "FLY" || (restrict && !used.contains(&(index as u64))) { + continue; + } + let Some(start) = point(&route["start"]) else { + continue; + }; + let mut points = vec![start]; + for checkpoint in route["checkpoints"].as_array().into_iter().flatten() { + if matches!(checkpoint["type"].as_str(), Some("MOVE" | "APPEAR")) { + if let Some(p) = point(&checkpoint["pos"]) { + points.push(p); + } + } + } + if let Some(end) = point(&route["end"]) { + points.push(end); + } + for pair in points.windows(2) { + if let Some(path) = grid + .find_path(pair[0], pair[1], false) + .or_else(|| grid.find_path(pair[0], pair[1], true)) + { + for [r, c] in path { + keys.insert(r as usize * COLS + c as usize); + } + } + } + } + keys + } + pub(crate) fn spawn_candle( + &mut self, + w: &mut World, + grid: &Grid, + h: &mut H, + position: [f64; 2], + hp: f64, + defence: f64, + resistance: f64, + mass: f64, + ) -> Result { + let key = "enemy_5601_entlec"; + let raw = json!({"applyWay":"NONE","notCountInTotal":true,"lifePointReduce":0,"stats":{"maxHp":hp.max(1.),"atk":0,"def":defence,"magicResistance":resistance,"moveSpeed":0,"massLevel":mass}}); + let definition = Enemy::parse(key, &raw)?; + self.definitions.insert(key.into(), Arc::new(definition)); + let tile = position.map(|v| (v + 0.5).floor() as i32); + self.call(|runtime|runtime.spawn_pending(w,grid,h,Pending{time:w.time,sequence:0, + spec:json!({"enemyKey":key,"pos":position,"noLeak":true,"route":{"motion":"WALK","start":tile,"end":tile,"checkpoints":[]}}), + counted:false,in_total:false,precounted:false})) + } fn spawn_pending( &mut self, w: &mut World, g: &Grid, h: &mut H, p: Pending, + ) -> Result { + self.spawn_pending_in(w, g.rect(), Self::exit(g), h, p) + } + fn spawn_pending_in( + &mut self, + w: &mut World, + rect: Rect, + exit: Option<[usize; 2]>, + h: &mut H, + p: Pending, ) -> Result { if self.units.len() >= self.capacity || self.live.len() >= self.capacity { return Err("Enemy roster capacity exceeded; no spawn dropped".into()); @@ -247,7 +488,6 @@ impl Runtime { .unwrap_or(&self.fallback) .clone() }; - let rect = g.rect(); let pos = p.spec["pos"].as_array().filter(|a| a.len() >= 2).map(|a| { [ a[0].as_f64().unwrap_or(f64::NAN), @@ -277,28 +517,50 @@ impl Runtime { .map(|a| a.is_empty()) .unwrap_or(true) { - if let Some((i, _)) = g - .tiles() - .iter() - .enumerate() - .find(|(_, t)| t.special.as_deref() == Some("end")) - { - compiled["end"] = json!([i / COLS, i % COLS]); + if let Some(tile) = exit { + compiled["end"] = json!(tile); } } - let route = Route::compile(&compiled, rect, self.max_legs, pos)?; - let mut unit = def.unit(&p.spec["mods"], pos, w.time)?; + let mut route = Route::compile(&compiled, rect, self.max_legs, pos)?; + route.patrol = if p.spec["route"].is_null() { + let i = waves::number(&p.spec["routeIndex"], 0.); + let index = if i >= 0. && i.fract() == 0. && i < self.routes.len() as f64 { + i as usize + } else { + 0 + }; + self.patrol_routes.contains(&index) + } else { + waves::has_patrol(&p.spec["route"]) + }; + let mut entry = ledger::Enemy::from_pending(&p, def.lpr, self.ledger.player())?; + entry.no_leak = key == "enemy_5601_entlec"; + self.insert(w, h, def, route, pos, entry, p.precounted) + } + fn insert( + &mut self, + w: &mut World, + h: &mut H, + def: Arc, + route: Route, + pos: [f64; 2], + entry: ledger::Enemy, + precounted: bool, + ) -> Result { + if self.units.len() >= self.capacity || self.live.len() >= self.capacity { + return Err("Enemy roster capacity exceeded; no spawn dropped".into()); + } + let mut unit = def.unit(&entry.mods, pos, w.time)?; unit.motion.route = Some(route); unit.owner = Some(1); - unit.boss = p.spec["tag"] == "boss"; - unit.deployment.counted = p.counted; - unit.deployment.in_total = p.in_total; - let entry = ledger::Enemy::from_pending(&p, def.lpr, self.ledger.player())?; + unit.boss = entry.boss; + unit.deployment.counted = entry.counted; + unit.deployment.in_total = entry.in_total; let id = w.next_unit_id()?; unit.targeting.spawn_seq = self.queue.next_sequence()?; unit.deployment.deploy_seq = w.next_deployment_sequence()?; w.insert_unit(id, unit)?; - self.ledger.spawn(id, entry, p.precounted)?; + self.ledger.spawn(id, entry, precounted)?; self.units.insert(id, def); self.live.push(id); h.spawned(id, w, self)?; @@ -328,6 +590,7 @@ impl Runtime { } let u = w.unit(id)?; if u.removed && !u.stats.alive && w.unit_pins(id)? == 0 { + h.retired(id, w)?; w.release_removed(id)?; r.units.remove(&id); } @@ -336,157 +599,3 @@ impl Runtime { }) } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::battle::{ - deploy::{self, Deployment, Options}, - health::{Side, Unit}, - stats::{Base, UnitStats}, - }; - fn fixture() -> (Runtime, World, Grid) { - let grid = Grid::new(&json!({}), super::super::grid::Rect::FULL).unwrap(); - let def = Arc::new(Enemy::parse("enemy_a", &json!({"hp":1000})).unwrap()); - let queue = Queue::new(128).unwrap(); - let ledger = Ledger::new(json!("p"), &queue, 128, 128).unwrap(); - ( - Runtime { - queue, - ledger, - definitions: BTreeMap::from([("enemy_a".into(), def)]), - units: BTreeMap::new(), - live: vec![], - routes: vec![], - extra_routes: vec![], - overrides: Value::Null, - fallback: Value::Null, - capacity: 128, - max_legs: 16, - faulted: false, - depth: 0, - }, - World::new(128, 1, 1).unwrap(), - grid, - ) - } - #[derive(Default)] - struct Host { - fail: bool, - released: usize, - } - impl Hooks for Host { - fn spawned(&mut self, _: Id, _: &mut World, _: &mut Runtime) -> Result<(), String> { - if self.fail { - Err("Enemy ability is not installed".into()) - } else { - Ok(()) - } - } - fn release(&mut self, _: Id, _: &mut World) -> Result<(), String> { - self.released += 1; - Ok(()) - } - } - impl super::super::blocking::Hooks for Host { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - } - impl deploy::Hooks for Host { - fn initialize( - &mut self, - _: Id, - _: Options, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn event( - &mut self, - _: deploy::Event, - _: Id, - _: Option, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn remove_temporary_effects(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - } - #[test] - fn content_failure_is_an_exception_not_a_valid_stats_only_continuation() { - let (mut r, mut w, g) = fixture(); - let mut h = Host { - fail: true, - ..Host::default() - }; - assert!(r.spawn(&mut w, &g, &mut h, "enemy_a", &json!({})).is_err()); - assert!(r.faulted()); - assert_eq!(r.live().len(), 1); - assert!(r.process(&mut w, &g, &mut h).is_err()); - assert!(r.spawn(&mut w, &g, &mut h, "enemy_a", &json!({})).is_err()); - assert_eq!(r.live().len(), 1); - } - #[test] - fn pinned_corpses_drop_owned_hooks_before_releasing_storage() { - let (mut r, mut w, g) = fixture(); - let mut h = Host::default(); - let id = r.spawn(&mut w, &g, &mut h, "enemy_a", &json!({})).unwrap(); - w.pin_unit(id).unwrap(); - r.ledger.kill(id, false).unwrap(); - let u = w.unit_mut(id).unwrap(); - u.removed = true; - u.stats.alive = false; - r.release_removed(&mut w, &mut h).unwrap(); - assert!(r.live().is_empty()); - assert_eq!(r.retained(), 1); - assert_eq!(h.released, 1); - r.release_removed(&mut w, &mut h).unwrap(); - assert_eq!(h.released, 1); - w.unpin_unit(id).unwrap(); - r.release_removed(&mut w, &mut h).unwrap(); - assert_eq!(r.retained(), 0); - assert_eq!(h.released, 1); - assert!(w.unit(id).is_err()); - let next = r.spawn(&mut w, &g, &mut h, "enemy_a", &json!({})).unwrap(); - assert!(next > id); - } - #[test] - fn ally_redeploy_and_enemy_spawn_share_world_identities() { - let (mut r, mut w, g) = fixture(); - let mut h = Host::default(); - let mut a = Unit::new(UnitStats::new(Base::default()), Side::Ally); - a.stats.alive = false; - a.deployment.kind = deploy::Kind::Operator; - a.deployment.home = [10, 5]; - w.insert_unit(7, a).unwrap(); - let mut d = Deployment::new(g.rect(), 128, 1, 99.).unwrap(); - d.register(7, &w).unwrap(); - assert!(d.deploy(&mut w, &mut h, 7, Options::default()).unwrap()); - let id = r.spawn(&mut w, &g, &mut h, "enemy_a", &json!({})).unwrap(); - assert_eq!(id, 8); - assert_eq!(w.unit(id).unwrap().deployment.deploy_seq, 2); - d.retreat(&mut w, &mut h, 7, "retreat", false).unwrap(); - assert!(d.deploy(&mut w, &mut h, 7, Options::default()).unwrap()); - assert_eq!(w.unit(7).unwrap().deployment.deploy_seq, 3); - let (mut fresh, mut world, grid) = fixture(); - let id = fresh - .spawn( - &mut world, - &grid, - &mut Host::default(), - "enemy_a", - &json!({}), - ) - .unwrap(); - assert_eq!(id, 1); - assert_eq!(world.unit(id).unwrap().deployment.deploy_seq, 1); - } -} diff --git a/crates/engine/src/battle/stats.rs b/crates/engine/src/battle/stats.rs index e8e1646..329ebc5 100644 --- a/crates/engine/src/battle/stats.rs +++ b/crates/engine/src/battle/stats.rs @@ -36,6 +36,12 @@ pub struct Modifiers { } impl Modifiers { pub fn aggregate(buffs: &[Buff]) -> Result { + Self::aggregate_iter(buffs.iter()) + } + pub(crate) fn aggregate_except(buffs: &[Buff], key: &str) -> Result { + Self::aggregate_iter(buffs.iter().filter(|b| b.key.as_deref() != Some(key))) + } + fn aggregate_iter<'a>(buffs: impl Iterator) -> Result { let mut out = Self::default(); let mut dodge: BTreeMap<&str, (u64, f64, f64)> = BTreeMap::new(); for b in buffs { @@ -171,20 +177,61 @@ impl Default for Cultivation { } } } +// Only derived combat attributes have a fixed domain. External base/modifier +// maps retain their string keys and their original aggregation order. +macro_rules! stat_keys { + ($($variant:ident => $key:literal),+ $(,)?) => { + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + #[repr(u8)] + pub enum Stat { $($variant),+ } + impl Stat { + const COUNT: usize = [$(stringify!($variant)),+].len(); + #[inline] + pub fn from_name(key: &str) -> Option { + match key { $($key => Some(Self::$variant),)+ _ => None } + } + } + }; +} +stat_keys! { + MaxHp => "maxHp", Atk => "atk", Def => "def", Res => "res", + Aspd => "aspd", Bat => "bat", Interval => "interval", + BlockCnt => "blockCnt", MoveSpeed => "moveSpeed", + RangeExtend => "rangeExtend", BlockRadiusScale => "blockRadiusScale", + BaseRangeExtend => "baseRangeExtend", MassLevel => "massLevel", + MaxTargets => "maxTargets", Taunt => "taunt", SpRecovery => "spRecovery", + HpRegen => "hpRegen", Shield => "shield", + DodgePhys => "dodgePhys", DodgeArts => "dodgeArts", + DefIgnorePct => "defIgnorePct", ResIgnorePct => "resIgnorePct", + DefIgnoreFlat => "defIgnoreFlat", ResIgnoreFlat => "resIgnoreFlat", + ArtsAttackAddition => "artsAttackAddition", SpCostFlat => "spCostFlat", + DmgDealtMul => "dmgDealtMul", PhysDealtMul => "physDealtMul", + ArtsDealtMul => "artsDealtMul", DmgTakenMul => "dmgTakenMul", + PhysTakenMul => "physTakenMul", ArtsTakenMul => "artsTakenMul", + TrueTakenMul => "trueTakenMul", ElemTakenMul => "elemTakenMul", + ElementalTakenMul => "elementalTakenMul", HealingDealtMul => "healingDealtMul", + HealingTakenMul => "healingTakenMul", AtkScaleMul => "atkScaleMul", + RedeployMul => "redeployMul", CostMul => "costMul", +} #[derive(Clone, Debug)] pub struct Stats { - pub numbers: BTreeMap<&'static str, f64>, + numbers: [f64; Stat::COUNT], pub flags: BTreeSet, } impl Stats { + #[inline] + pub fn get(&self, stat: Stat) -> f64 { + self.numbers[stat as usize] + } + /// String boundary for data-driven callers; fixed hot paths use get(). + #[inline] pub fn n(&self, k: &str) -> f64 { - *self.numbers.get(k).expect("Unknown stat") + self.get(Stat::from_name(k).expect("Unknown stat")) } pub fn calculate(b: &Base, mods: &Modifiers, cm: Cultivation, move_floor: f64) -> Self { let a = |k| mods.a(k); let m = |k| mods.m(k); let n = |k| b.n(k); - let mut numbers = BTreeMap::new(); let bhp = if finite(n("maxHp"), 1.0) > 0.0 { finite(n("maxHp"), 1.0) } else { @@ -228,104 +275,84 @@ impl Stats { 1.0 }; let bat = finite(bbat * max(0.1, 1.0 + a("batPct")), bbat); - for (k, v) in [ - ("maxHp", max_hp), - ("atk", atk), - ("def", def), - ("res", res), - ("aspd", aspd), - ("bat", bat), - ("interval", bat * 100.0 / aspd), - ( - "blockCnt", - max(0.0, finite(js_round(n("blockCnt") + a("blockCnt")), 0.0)), - ), - ( - "moveSpeed", - max( - move_floor, - finite( - (n("moveSpeed") + a("moveFlat")) * m("moveMul"), - finite(n("moveSpeed"), 0.0), - ), - ), - ), - ("rangeExtend", max(0.0, js_round(a("rangeExtend")))), - ( - "blockRadiusScale", - max(0.0, finite(a("blockRadiusScale"), 0.0)), - ), - ( - "baseRangeExtend", - max(0.0, finite(js_round(mods.permanent_range), 0.0)), - ), - ( - "massLevel", - max( - 0.0, - finite(finite(n("massLevel"), 0.0) + a("massFlat"), 0.0), - ), - ), - ("maxTargets", a("maxTargets")), - ( - "taunt", - finite(n("tauntLevel"), 0.0) - + a("taunt") - + if mods.flags.contains("taunt") { - 1.0 - } else { - 0.0 - }, - ), - ( - "spRecovery", - max( - 0.0, - finite( - (n("spRecovery") + a("spRecoveryFlat")) * m("spRecoveryMul"), - 0.0, - ), - ), + let mut numbers = [0.0; Stat::COUNT]; + numbers[Stat::MaxHp as usize] = max_hp; + numbers[Stat::Atk as usize] = atk; + numbers[Stat::Def as usize] = def; + numbers[Stat::Res as usize] = res; + numbers[Stat::Aspd as usize] = aspd; + numbers[Stat::Bat as usize] = bat; + numbers[Stat::Interval as usize] = bat * 100.0 / aspd; + numbers[Stat::BlockCnt as usize] = + max(0.0, finite(js_round(n("blockCnt") + a("blockCnt")), 0.0)); + numbers[Stat::MoveSpeed as usize] = max( + move_floor, + finite( + (n("moveSpeed") + a("moveFlat")) * m("moveMul"), + finite(n("moveSpeed"), 0.0), ), - ( - "hpRegen", - finite( - n("hpRecoveryPerSec") + a("hpRegen") + a("hpRegenRatio") * max_hp, - 0.0, - ), + ); + numbers[Stat::RangeExtend as usize] = max(0.0, js_round(a("rangeExtend"))); + numbers[Stat::BlockRadiusScale as usize] = max(0.0, finite(a("blockRadiusScale"), 0.0)); + numbers[Stat::BaseRangeExtend as usize] = + max(0.0, finite(js_round(mods.permanent_range), 0.0)); + numbers[Stat::MassLevel as usize] = max( + 0.0, + finite(finite(n("massLevel"), 0.0) + a("massFlat"), 0.0), + ); + numbers[Stat::MaxTargets as usize] = a("maxTargets"); + numbers[Stat::Taunt as usize] = finite(n("tauntLevel"), 0.0) + + a("taunt") + + if mods.flags.contains("taunt") { + 1.0 + } else { + 0.0 + }; + numbers[Stat::SpRecovery as usize] = max( + 0.0, + finite( + (n("spRecovery") + a("spRecoveryFlat")) * m("spRecoveryMul"), + 0.0, ), - ("shield", mods.shield), + ); + numbers[Stat::HpRegen as usize] = finite( + n("hpRecoveryPerSec") + a("hpRegen") + a("hpRegenRatio") * max_hp, + 0.0, + ); + numbers[Stat::Shield as usize] = mods.shield; + for (stat, key) in [ + (Stat::DodgePhys, "dodgePhys"), + (Stat::DodgeArts, "dodgeArts"), + (Stat::DefIgnorePct, "defIgnorePct"), + (Stat::ResIgnorePct, "resIgnorePct"), ] { - numbers.insert(k, v); - } - for k in ["dodgePhys", "dodgeArts", "defIgnorePct", "resIgnorePct"] { - numbers.insert(k, clamp(a(k), 0.0, 1.0)); + numbers[stat as usize] = clamp(a(key), 0.0, 1.0); } - for k in [ - "defIgnoreFlat", - "resIgnoreFlat", - "artsAttackAddition", - "spCostFlat", + for (stat, key) in [ + (Stat::DefIgnoreFlat, "defIgnoreFlat"), + (Stat::ResIgnoreFlat, "resIgnoreFlat"), + (Stat::ArtsAttackAddition, "artsAttackAddition"), + (Stat::SpCostFlat, "spCostFlat"), ] { - numbers.insert(k, a(k)); + numbers[stat as usize] = a(key); } - for k in [ - "dmgDealtMul", - "physDealtMul", - "artsDealtMul", - "dmgTakenMul", - "physTakenMul", - "artsTakenMul", - "trueTakenMul", - "elemTakenMul", - "elementalTakenMul", - "healingDealtMul", - "healingTakenMul", - "atkScaleMul", - "redeployMul", - "costMul", + for (stat, key) in [ + (Stat::DmgDealtMul, "dmgDealtMul"), + (Stat::PhysDealtMul, "physDealtMul"), + (Stat::ArtsDealtMul, "artsDealtMul"), + (Stat::DmgTakenMul, "dmgTakenMul"), + (Stat::PhysTakenMul, "physTakenMul"), + (Stat::ArtsTakenMul, "artsTakenMul"), + (Stat::TrueTakenMul, "trueTakenMul"), + (Stat::ElemTakenMul, "elemTakenMul"), + (Stat::ElementalTakenMul, "elementalTakenMul"), + (Stat::HealingDealtMul, "healingDealtMul"), + (Stat::HealingTakenMul, "healingTakenMul"), + (Stat::AtkScaleMul, "atkScaleMul"), + (Stat::RedeployMul, "redeployMul"), + (Stat::CostMul, "costMul"), ] { - numbers.insert(k, m(k)); + numbers[stat as usize] = m(key); } let mut flags = mods.flags.clone(); if ["stun", "freeze", "sleep", "levitate"] @@ -351,6 +378,16 @@ pub struct UnitStats { pub rate_dirty: bool, } impl UnitStats { + pub(crate) fn cached_clean(&self) -> bool { + !self.dirty && self.cached.is_some() + } + /// HP remains expressed against this maximum until the next lazy aggregation. + pub(crate) fn observed_max_hp(&self) -> f64 { + self.cached + .as_ref() + .map(|s| s.get(Stat::MaxHp)) + .unwrap_or_else(|| self.base.n("maxHp")) + } pub fn buffs(&self) -> &[Buff] { &self.buffs } @@ -425,7 +462,7 @@ impl UnitStats { let prev = self .cached .as_ref() - .map(|s| s.n("maxHp")) + .map(|s| s.get(Stat::MaxHp)) .unwrap_or(self.base.n("maxHp")); let s = Stats::calculate( &self.base, @@ -436,17 +473,14 @@ impl UnitStats { if self .cached .as_ref() - .map(|old| (old.n("interval") - s.n("interval")).abs() > 1e-9) + .map(|old| (old.get(Stat::Interval) - s.get(Stat::Interval)).abs() > 1e-9) .unwrap_or(true) { self.rate_dirty = true; } - if self.alive && prev > 0.0 && (prev - s.n("maxHp")).abs() > 1e-9 { - self.hp = clamp( - finite(self.hp * (s.n("maxHp") / prev), s.n("maxHp")), - 0.0, - s.n("maxHp"), - ); + let max_hp = s.get(Stat::MaxHp); + if self.alive && prev > 0.0 && (prev - max_hp).abs() > 1e-9 { + self.hp = clamp(finite(self.hp * (max_hp / prev), max_hp), 0.0, max_hp); } self.cached = Some(s); self.dirty = false; @@ -468,59 +502,3 @@ impl UnitStats { }) } } - -#[cfg(test)] -mod tests { - use super::*; - fn hp_buff() -> Buff { - Buff { - mods: [("hpMul".into(), 2.0)].into_iter().collect(), - ..Buff::default() - } - } - #[test] - fn allied_flight_query_does_not_recalculate_hp() { - let mut base = Base::default(); - base.0.insert("maxHp".into(), 100.0); - let mut u = UnitStats::new(base); - u.hp = 25.0; - u.stats().unwrap(); - u.set_buffs(vec![hp_buff()]); - assert!(!u.is_flying(false, false).unwrap()); - assert_eq!(u.hp, 25.0); - assert_eq!(u.stats().unwrap().n("maxHp"), 200.0); - assert_eq!(u.hp, 50.0); - u.stats().unwrap(); - assert_eq!(u.hp, 50.0); - } - #[test] - fn flying_precedence_and_dead_hp_preservation() { - let mut u = UnitStats::new(Base::default()); - let mut b = hp_buff(); - b.flags.insert("groundbind".into()); - b.flags.insert("float".into()); - u.alive = false; - u.hp = 0.25; - u.set_buffs(vec![b.clone()]); - assert!(!u.is_flying(true, true).unwrap()); - assert_eq!(u.hp, 0.25); - b.flags.insert("levitate".into()); - u.set_buffs(vec![b]); - assert!(u.is_flying(true, false).unwrap()); - assert!(u.stats().unwrap().flags.contains("stun")); - } - #[test] - fn invalid_stacks_do_not_commit_partial_stats() { - let mut u = UnitStats::new(Base::default()); - u.stats().unwrap(); - let hp = u.hp; - u.set_buffs(vec![Buff { - stacks: 0, - ..hp_buff() - }]); - assert!(u.stats().is_err()); - assert_eq!(u.hp, hp); - u.set_buffs(vec![]); - assert_eq!(u.stats().unwrap().n("maxHp"), 1.0); - } -} diff --git a/crates/engine/src/battle/status.rs b/crates/engine/src/battle/status.rs index 553ef83..8875a8d 100644 --- a/crates/engine/src/battle/status.rs +++ b/crates/engine/src/battle/status.rs @@ -516,223 +516,3 @@ fn round(x: f64) -> f64 { f + 1.0 } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::battle::{ - health::Unit, - stats::{Base, UnitStats}, - }; - #[derive(Default)] - struct Host { - ended: Vec, - } - impl super::super::health::Hooks for Host { - fn kill(&mut self, _: Id, _: Option, _: &mut World) -> Result<(), String> { - unreachable!() - } - } - impl blocking::Hooks for Host { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, id: Id, _: &mut World) -> Result<(), String> { - self.ended.push(id); - Ok(()) - } - } - impl buffs::Hooks for Host { - fn status(&mut self, _: Id, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - } - impl Hooks for Host { - fn has_before_status(&self) -> bool { - false - } - fn before_status( - &mut self, - _: &mut Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - fn has_status_applied(&self) -> bool { - false - } - fn status_applied( - &mut self, - _: &Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - } - fn world() -> World { - let mut w = World::new(2, 1, 1).unwrap(); - for (id, side) in [(1, Side::Ally), (2, Side::Enemy)] { - let mut u = Unit::new(UnitStats::new(Base::default()), side); - u.deployed = true; - w.insert_unit(id, u).unwrap(); - } - w - } - #[test] - fn control_releases_both_ends_and_force_cannot_bypass_hostile_untargetable_invulnerability() { - let mut w = world(); - let mut h = Host::default(); - let mut r = Runtime::new(8, 16, 16).unwrap(); - for (unit, key) in [(1, "stun"), (2, "sleep")] { - w.unit_mut(1).unwrap().blocking.push(2); - w.unit_mut(2).unwrap().blocked_by = Some(1); - assert!(apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - unit, - key, - Options { - duration: 1.0, - ..Default::default() - } - ) - .unwrap()); - assert!(w.unit(1).unwrap().blocking().is_empty()); - assert!(w.unit(2).unwrap().blocked_by().is_none()); - } - assert_eq!(h.ended, vec![2, 2]); - r.add( - &mut w, - &mut h, - 2, - Spec { - buff: Buff { - key: Some("guard".into()), - flags: ["invulnerable".into(), "untargetable".into()] - .into_iter() - .collect(), - ..Default::default() - }, - flags_present: true, - ..Default::default() - }, - ) - .unwrap(); - assert!(!apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - 2, - "silence", - Options { - source: Some(1), - force: true, - ..Default::default() - } - ) - .unwrap()); - } - #[test] - fn paired_enemy_cold_uses_post_resistance_duration_once() { - let mut w = world(); - let mut h = Host::default(); - let mut r = Runtime::new(8, 16, 16).unwrap(); - for (key, duration, value) in [ - ("resist", 10.0, Some(0.5)), - ("cold", 2.0, None), - ("cold", 3.0, None), - ] { - apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - 2, - key, - Options { - duration, - value, - ..Default::default() - }, - ) - .unwrap(); - } - let buffs = w.unit(2).unwrap().stats.buffs(); - assert!(!buffs.iter().any(|b| b.key.as_deref() == Some("cold"))); - assert_eq!( - buffs - .iter() - .find(|b| b.key.as_deref() == Some("freeze")) - .unwrap() - .runtime - .time_left, - 1.5 - ); - } - #[test] - fn waiting_effect_overflow_faults_without_dropping_the_previous_tail() { - let mut w = world(); - let mut h = Host::default(); - let mut r = Runtime::new(1, 8, 16).unwrap(); - for (value, duration) in [(0.8, 1.0), (0.5, 2.0)] { - valued::apply( - &mut w, - &mut h, - &mut r, - 1, - valued::Request { - key: "fragile", - kind: Kind::Fragile, - plain: false, - duration, - value, - source: None, - stack_as: None, - }, - ) - .unwrap(); - } - assert!(valued::apply( - &mut w, - &mut h, - &mut r, - 1, - valued::Request { - key: "fragile", - kind: Kind::Fragile, - plain: false, - duration: 3.0, - value: 0.3, - source: None, - stack_as: None - } - ) - .is_err()); - assert!(r.faulted()); - assert_eq!( - w.unit(1).unwrap().stats.buffs()[0] - .runtime - .valued - .as_ref() - .unwrap() - .tail - .len(), - 1 - ); - } -} diff --git a/crates/engine/src/battle/targeting.rs b/crates/engine/src/battle/targeting.rs index 84889fc..6b462f2 100644 --- a/crates/engine/src/battle/targeting.rs +++ b/crates/engine/src/battle/targeting.rs @@ -5,19 +5,25 @@ use super::{ direction::Direction, grid::{COLS, N, ROWS}, health::{Id, Side, World}, - stats::Stats, + stats::{Stat, Stats}, }; use std::{cmp::Ordering, collections::BTreeMap}; #[derive(Clone, Copy, Debug, Default)] pub struct Profile { + pub ignore_stealth: bool, pub hit_sleep: bool, pub can_hit_fly: bool, pub doll_hits_fly: bool, pub ground_only: bool, pub block_free: bool, } +/// A source-owned exclusion predicate, available during nested content callbacks. +pub type EnemyFilter = fn(&mut World, Id, Id) -> Result; + #[derive(Clone, Debug, Default)] pub struct State { + pub enemy_filter: Option, + pub melee_operator: bool, pub doll: bool, pub elite: bool, pub ranged_apply_melee: bool, @@ -61,14 +67,10 @@ pub fn enemy_stealthed(w: &mut World, id: Id) -> Result { .any(|off| off.key.as_deref() == Some(key.as_str())) })) } -fn snapshot(w: &mut World, id: Id) -> Result { - w.unit_mut(id)? - .stats - .stats() - .cloned() - .map_err(str::to_string) +fn stats(w: &mut World, id: Id) -> Result<&Stats, String> { + w.unit_mut(id)?.stats.stats().map_err(str::to_string) } -fn flying(w: &mut World, id: Id) -> Result { +pub(crate) fn flying(w: &mut World, id: Id) -> Result { let u = w.unit_mut(id)?; u.stats .is_flying(u.side == Side::Enemy, u.motion_fly) @@ -85,11 +87,11 @@ pub fn can_target_enemy( if !e.stats.alive || e.hidden || !e.deployed { return Ok(false); } - let flags = snapshot(w, enemy)?.flags; + let flags = &stats(w, enemy)?.flags; if flags.contains("untargetable") || (flags.contains("sleep") && !p.hit_sleep) { return Ok(false); } - if flags.contains("stealth") && q.enemy_stealthed(enemy, w)? { + if !p.ignore_stealth && flags.contains("stealth") && q.enemy_stealthed(enemy, w)? { return Ok(false); } let doll = attacker @@ -108,7 +110,7 @@ pub fn can_target_enemy( Ok(true) } pub fn evades_ground(w: &mut World, source: Option, target: Id) -> Result { - if !snapshot(w, target)?.flags.contains("liftoff") { + if !stats(w, target)?.flags.contains("liftoff") { return Ok(false); } if let Some(id) = source { @@ -129,7 +131,7 @@ pub fn can_target_ally( if !a.stats.alive || !a.deployed || a.hidden || a.deployment.kind == Kind::Device { return Ok(false); } - let f = snapshot(w, ally)?.flags; + let f = &stats(w, ally)?.flags; if f.contains("untargetable") || f.contains("sleep") { return Ok(false); } @@ -141,12 +143,19 @@ pub fn can_target_ally( } Ok(!evades_ground(w, Some(enemy), ally)?) } +pub fn friendly_selectable(w: &mut World, source: Id, ally: Id) -> Result { + let u = w.unit(ally)?; + if !u.stats.alive || !u.deployed || u.hidden || u.deployment.kind == Kind::Device { + return Ok(false); + } + Ok(source == ally || !stats(w, ally)?.flags.contains("isolated")) +} pub fn aura_selectable(w: &mut World, ally: Id) -> Result { let a = w.unit(ally)?; if !a.stats.alive || !a.deployed || a.hidden || a.deployment.kind == Kind::Device { return Ok(false); } - let f = snapshot(w, ally)?.flags; + let f = &stats(w, ally)?.flags; Ok(!["untargetable", "sleep", "stealth"] .iter() .any(|k| f.contains(*k))) @@ -221,19 +230,19 @@ pub fn sort_enemies( 0.0 } } - Priority::LowDef => snapshot(w, id)?.n("def"), - Priority::HighDef => -snapshot(w, id)?.n("def"), + Priority::LowDef => stats(w, id)?.get(Stat::Def), + Priority::HighDef => -stats(w, id)?.get(Stat::Def), Priority::LowestHp => w.unit(id)?.stats.hp, Priority::HighestHp => -w.unit(id)?.stats.hp, Priority::LowestHpRatio => { - let max = snapshot(w, id)?.n("maxHp"); + let max = stats(w, id)?.get(Stat::MaxHp); if max > 0.0 { w.unit(id)?.stats.hp / max } else { 0.0 } } - Priority::HighestAtk => -snapshot(w, id)?.n("atk"), + Priority::HighestAtk => -stats(w, id)?.get(Stat::Atk), Priority::Boss => { if w.unit(id)?.boss { 0.0 @@ -249,13 +258,13 @@ pub fn sort_enemies( } } Priority::NotBurst => { - if snapshot(w, id)?.flags.contains("burstLock") { + if stats(w, id)?.flags.contains("burstLock") { 1.0 } else { 0.0 } } - Priority::Heaviest => -snapshot(w, id)?.n("massLevel"), + Priority::Heaviest => -stats(w, id)?.get(Stat::MassLevel), Priority::Ranged => { let u = w.unit(id)?; if u.stats.base_number("rangeRadius") > 0.0 && !u.targeting.ranged_apply_melee { @@ -268,7 +277,7 @@ pub fn sort_enemies( Priority::Farthest => -q.body_distance(id, origin, w)?, Priority::None => 0.0, }; - let taunt = snapshot(w, id)?.n("taunt"); + let taunt = stats(w, id)?.get(Stat::Taunt); let t = if taunt.is_nan() || taunt == 0.0 { 0.0 } else { @@ -310,7 +319,7 @@ pub fn sort_allies( }; let mut keys = Vec::with_capacity(candidates.len()); for &id in candidates.iter() { - let t = snapshot(w, id)?.n("taunt"); + let t = stats(w, id)?.get(Stat::Taunt); let t = if t.is_nan() || t == 0.0 { 0.0 } else { -t }; let u = w.unit(id)?; let seq = if u.deployment.aggro_seq != 0 { @@ -363,6 +372,9 @@ pub fn absolute_range( for &p in grid { add(p); } + if extend == 0 { + return out; + } let mut rows = Vec::new(); let mut max = BTreeMap::new(); for &[r, c] in grid { @@ -387,43 +399,15 @@ pub fn target_count( max_targets: f64, ) -> Result { let base = if hit_all_blocked { - stats.n("blockCnt").floor().max(1.0) + stats.get(Stat::BlockCnt).floor().max(1.0) } else if max_targets == 0.0 || max_targets.is_nan() { 1.0 } else { max_targets }; - let n = (base + stats.n("maxTargets")).floor().max(1.0); + let n = (base + stats.get(Stat::MaxTargets)).floor().max(1.0); if !n.is_finite() || n >= usize::MAX as f64 { return Err("Target count exceeds native capacity".into()); } Ok(n as usize) } - -#[cfg(test)] -mod tests { - use super::*; - use crate::battle::stats::{Base, Buff, Cultivation, Modifiers}; - #[test] - fn attack_target_count_uses_capacity_plus_modifiers_not_current_blocked_count() { - let mut b = Base::default(); - b.0.insert("blockCnt".into(), 3.0); - let m = Modifiers::aggregate(&[Buff { - mods: [("maxTargets".into(), 2.0)].into_iter().collect(), - ..Buff::default() - }]) - .unwrap(); - let s = Stats::calculate(&b, &m, Cultivation::default(), 0.0); - assert_eq!(target_count(&s, true, 1.0).unwrap(), 5); - assert_eq!(target_count(&s, false, 2.0).unwrap(), 4); - assert_eq!(target_count(&s, false, 0.0).unwrap(), 3); - } - #[test] - fn range_extension_preserves_input_row_order_and_deduplicates() { - assert_eq!( - absolute_range(&[[1, 0], [0, 0], [1, 0]], [10, 4], Direction::Right, 1), - vec![11 * 21 + 4, 10 * 21 + 4, 11 * 21 + 5, 10 * 21 + 5] - ); - assert!(absolute_range(&[[0, 0]], [-1, 0], Direction::Right, 0).is_empty()); - } -} diff --git a/crates/engine/src/battle/terrain.rs b/crates/engine/src/battle/terrain.rs new file mode 100644 index 0000000..95e3a8e --- /dev/null +++ b/crates/engine/src/battle/terrain.rs @@ -0,0 +1,490 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Static ground terrain and per-unit contact state. Active devices remain separate. +use super::{ + buffs::{self, Runtime, Spec}, + grid::{Grid, COLS, N}, + health::{Id, Side, Unit, World}, + stats::Buff, + targeting, +}; +use serde_json::Value; +pub(crate) const INFECTION: u64 = 1800; +pub(crate) const DEEPSEA: u64 = 1801; +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Kind { + #[default] + None, + Mire, + Smog, + Deepsea, + Infection, +} +impl Kind { + fn key(self) -> &'static str { + match self { + Self::None => "", + Self::Mire => "terrain:mire", + Self::Smog => "terrain:smog", + Self::Deepsea => "terrain:deepsea", + Self::Infection => "terrain:infection", + } + } +} +#[derive(Clone, Copy, Default)] +#[cfg_attr(test, derive(Debug))] +pub(crate) struct State { + kind: Kind, + entered: f64, + triggers: f64, + stacks: f64, + pub(crate) direction: Option, + air_atk: f64, + air_move: Option, + air_position: Option<[f64; 2]>, +} +impl State { + pub(crate) fn movement_arrive(&mut self, position: [f64; 2]) { + self.air_position = Some(position); + } +} +#[derive(Clone)] +pub(crate) struct Config { + tiles: [Kind; N], + flow: Vec>, + active: bool, + mire_interval: f64, + mire_aspd: f64, + mire_move: f64, + mire_max: f64, + heavy: f64, + deep_damage: f64, + deep_aspd: f64, + deep_move: f64, + infection_damage: f64, + infection_atk: f64, + infection_aspd: f64, + infection_duration: f64, +} +#[derive(Clone, Copy)] +struct Flow { + direction: super::direction::Direction, + atk: [f64; 3], + speed: [f64; 2], +} +fn number(v: &Value, fallback: f64) -> f64 { + v.as_f64() + .or_else(|| v.as_str().and_then(|s| s.parse().ok())) + .filter(|v| v.is_finite()) + .unwrap_or(fallback) +} +fn aspd(v: f64) -> f64 { + if v.abs() < 1. { + v * 100. + } else { + v + } +} +impl Config { + pub(crate) fn compile(stage: &Value, grid: &Grid) -> Result { + let mut tiles = [Kind::None; N]; + for (i, tile) in grid.tiles().iter().enumerate() { + let at = [(i / COLS) as i32, (i % COLS) as i32]; + let rect = grid.rect(); + if at[0] < rect.r0 || at[0] > rect.r1 || at[1] < rect.c0 || at[1] > rect.c1 { + continue; + } + tiles[i] = match tile.terrain.as_deref() { + None => Kind::None, + Some("mire") => Kind::Mire, + Some("smog") => Kind::Smog, + Some("deepsea") => Kind::Deepsea, + Some("infection") => Kind::Infection, + Some(name) => return Err(format!("Field terrain not implemented: {name}")), + }; + } + let controller = |role| { + stage["devices"] + .as_array() + .and_then(|a| a.iter().find(|d| d["role"] == role)) + .map(|d| &d.get("raw").unwrap_or(d)["skill"]["bb"]) + .unwrap_or(&Value::Null) + }; + let m = &stage["special"]["mire"]; + let md = controller("mireController"); + let deep = stage["special"]["deepsea"]["bb"] + .as_object() + .map(|_| &stage["special"]["deepsea"]["bb"]) + .unwrap_or_else(|| controller("tideController")); + let inf = &stage["special"]["infection"]["bb"]; + let interval = number(&m["intervalSec"], 1.); + let duration = number(&inf["duration"], 300.); + let mut flow = vec![None; N]; + for d in stage["devices"].as_array().into_iter().flatten() { + if d["role"] != "blower" || !d["active"].as_bool().unwrap_or(d["hidden"] != true) { + continue; + } + use super::direction::Direction; + let direction = match d["dir"] + .as_str() + .or(d["raw"]["dir"].as_str()) + .unwrap_or("UP") + .to_uppercase() + .as_str() + { + "UP" => Direction::Up, + "DOWN" => Direction::Down, + "LEFT" => Direction::Left, + "RIGHT" => Direction::Right, + _ => continue, + }; + let raw = d.get("raw").unwrap_or(d); + let bb = raw["skill"] + .get("bb") + .unwrap_or(&stage["special"]["blower"]["bb"]); + let f = Flow { + direction, + atk: ["equal", "opposite", "vertical"] + .map(|k| number(&bb[format!("blower_s_character[{k}].atk")], 0.)), + speed: ["equal", "opposite"] + .map(|k| number(&bb[format!("blower_s_enemy[{k}].move_speed")], 0.)), + }; + for p in raw["rangeTiles"].as_array().into_iter().flatten() { + let Some(at) = p[0] + .as_i64() + .zip(p[1].as_i64()) + .map(|(r, c)| [r as i32, c as i32]) + else { + continue; + }; + if grid.in_rect(at) { + flow[at[0] as usize * COLS + at[1] as usize] = Some(f); + } + } + } + Ok(Self { + active: tiles.iter().any(|k| *k != Kind::None) || flow.iter().any(Option::is_some), + flow, + tiles, + mire_interval: if interval > 0. { interval } else { 1. }, + mire_aspd: aspd(number( + m.get("aspdPerStack").unwrap_or(&md["attack_speed"]), + -0.05, + )), + mire_move: number(m.get("moveMulPerStack").unwrap_or(&md["move_speed"]), -0.05), + mire_max: number(m.get("maxStacks").unwrap_or(&md["max_stack_cnt"]), 10.) + .floor() + .max(1.), + heavy: number(m.get("heavyWeight").unwrap_or(&md["value"]), 3.), + deep_damage: number(&deep["sea_drown[enemy].damage"], 40.), + deep_aspd: aspd(number(&deep["sea_drown[enemy].attack_speed"], -0.6)), + deep_move: number(&deep["sea_drown[enemy].move_speed"], 0.6), + infection_damage: number(&inf["damage"], 70.), + infection_atk: number(&inf["atk"], 0.2), + infection_aspd: aspd(number(&inf["attack_speed"], 20.)), + infection_duration: if duration > 0. { duration } else { 300. }, + }) + } + pub(crate) fn active(&self) -> bool { + self.active + } + pub(crate) fn at(&self, position: [f64; 2]) -> Kind { + let [r, c] = position.map(|v| (v + 0.5).floor() as i32); + if Grid::in_bounds([r, c]) { + self.tiles[r as usize * COLS + c as usize] + } else { + Kind::None + } + } + pub(crate) fn movement_ground_clear(&self, unit: &Unit) -> bool { + let kind = self.at(unit.position); + matches!(kind, Kind::None | Kind::Mire) && unit.terrain.kind == kind + } + pub(crate) fn stationary_ground_clear(&self, unit: &Unit) -> bool { + self.at(unit.position) == Kind::None && unit.terrain.kind == Kind::None + } + pub(crate) fn movement_effect_stable( + &self, + state: &State, + position: [f64; 2], + time: f64, + ) -> bool { + if self.at(position) != state.kind { + return false; + } + if state.kind == Kind::Mire + && 1. + ((time - state.entered + 1e-9) / self.mire_interval).floor() > state.triggers + { + return false; + } + let old = state.air_move.unwrap_or(1.); + self.enemy_airflow(position, state.air_position, false, old) == old + } + fn enemy_airflow( + &self, + position: [f64; 2], + previous: Option<[f64; 2]>, + hidden: bool, + old: f64, + ) -> f64 { + let at = position.map(|v| (v + 0.5).floor() as i32); + let flow = if Grid::in_bounds(at) { + self.flow[at[0] as usize * COLS + at[1] as usize] + } else { + None + }; + let mut mul = 1.; + if !hidden { + if let (Some(previous), Some(f)) = (previous, flow) { + let delta = [position[0] - previous[0], position[1] - previous[1]]; + let speed = crate::deterministic::math::hypot(delta[0], delta[1]); + if speed > 1e-6 { + let vector = f.direction.vector(); + let dot = (delta[1] * vector[1] as f64 + delta[0] * vector[0] as f64) / speed; + if dot > 0.7 { + mul = 1. + f.speed[0]; + } else if dot < -0.7 { + mul = 1. + f.speed[1]; + } + } else { + mul = old; + } + } + } + mul.max(0.) + } + pub(crate) fn refresh( + &self, + w: &mut World, + r: &mut Runtime, + h: &mut H, + id: Id, + fresh: bool, + ) -> Result<(), String> { + if !self.active { + return Ok(()); + } + if fresh { + let direction = w.unit(id)?.terrain.direction; + w.unit_mut(id)?.terrain = State { + direction, + ..Default::default() + }; + } + let u = w.unit(id)?; + if !u.stats.alive || !u.deployed || u.deployment.kind == super::deploy::Kind::Device { + return Ok(()); + } + let enemy = u.side == Side::Enemy; + let hidden = u.hidden; + let position = if enemy { + u.position + } else { + u.deployment.tile.map(f64::from) + }; + let mut kind = self.at(position); + if hidden + || targeting::flying(w, id)? + || kind == Kind::Smog && enemy + || kind == Kind::Deepsea && !enemy + { + kind = Kind::None; + } + let state = w.unit(id)?.terrain; + if state.kind != kind { + if !matches!(state.kind, Kind::None | Kind::Infection) { + r.remove(w, h, id, state.kind.key())?; + } + let now = w.time; + w.unit_mut(id)?.terrain = State { + kind, + entered: now, + triggers: 0., + stacks: 0., + ..state + }; + let mut b = Buff::default(); + b.key = Some(kind.key().into()); + match kind { + Kind::Smog => { + b.flags.insert("stealth".into()); + } + Kind::Deepsea => { + b.mods = [ + ("aspd".into(), self.deep_aspd), + ("moveMul".into(), self.deep_move), + ] + .into(); + b.runtime.interval = 1.; + b.runtime.on_tick = Some(DEEPSEA); + b.runtime.tick_payload = self.deep_damage; + } + _ => {} + } + if matches!(kind, Kind::Smog | Kind::Deepsea) { + r.add( + w, + h, + id, + Spec { + mods_present: !b.mods.is_empty(), + flags_present: !b.flags.is_empty(), + buff: b, + ..Default::default() + }, + )?; + } + } + match kind { + Kind::Infection => { + let old = w + .unit(id)? + .stats + .buffs() + .iter() + .find(|b| b.key.as_deref() == Some(kind.key())); + if let Some(b) = old { + if b.runtime.time_left < self.infection_duration { + let bid = b.runtime.id(); + r.edit(w, id, bid, |b| { + b.runtime.time_left = self.infection_duration + })?; + } + } else { + let mut b = Buff::default(); + b.key = Some(kind.key().into()); + b.mods = [ + ("atkPct".into(), self.infection_atk), + ("aspd".into(), self.infection_aspd), + ] + .into(); + b.runtime.duration = self.infection_duration; + b.runtime.interval = 1.; + b.runtime.on_tick = Some(INFECTION); + b.runtime.tick_payload = self.infection_damage; + r.add( + w, + h, + id, + Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } + } + Kind::Mire => { + let state = w.unit(id)?.terrain; + let due = 1. + ((w.time - state.entered + 1e-9) / self.mire_interval).floor(); + if due > state.triggers { + let heavy = enemy + && w.unit_mut(id)? + .stats + .stats() + .map_err(str::to_string)? + .n("massLevel") + >= self.heavy; + let stacks = (state.stacks + + if heavy { 2. } else { 1. } * (due - state.triggers)) + .min(self.mire_max); + w.unit_mut(id)?.terrain.triggers = due; + w.unit_mut(id)?.terrain.stacks = stacks; + if stacks != state.stacks { + let mut b = Buff::default(); + b.key = Some(kind.key().into()); + b.mods.insert("aspd".into(), self.mire_aspd * stacks); + if enemy { + b.mods + .insert("moveMul".into(), (1. + self.mire_move * stacks).max(0.)); + } + r.add( + w, + h, + id, + Spec { + buff: b, + mods_present: true, + ..Default::default() + }, + )?; + } + } + } + _ => {} + } + self.airflow(w, r, h, id) + } + fn airflow( + &self, + w: &mut World, + r: &mut Runtime, + h: &mut H, + id: Id, + ) -> Result<(), String> { + let u = w.unit(id)?; + let enemy = u.side == Side::Enemy; + let position = if enemy { + u.position + } else { + u.deployment.tile.map(f64::from) + }; + let state = u.terrain; + let (value, old, key, neutral) = if enemy { + let mul = self.enemy_airflow( + position, + state.air_position, + u.hidden, + state.air_move.unwrap_or(1.), + ); + w.unit_mut(id)?.terrain.air_position = Some(position); + (mul, state.air_move.unwrap_or(1.), "moveMul", 1.) + } else { + let at = position.map(|v| (v + 0.5).floor() as i32); + let flow = if Grid::in_bounds(at) { + self.flow[at[0] as usize * COLS + at[1] as usize] + } else { + None + }; + let atk = if !u.motion_fly { + flow.map(|f| { + f.atk[match state.direction { + Some(d) if d == f.direction => 0, + Some(d) if d == f.direction.opposite() => 1, + _ => 2, + }] + }) + .unwrap_or(0.) + } else { + 0. + }; + (atk, state.air_atk, "atkPct", 0.) + }; + if value == old { + return Ok(()); + } + if enemy { + w.unit_mut(id)?.terrain.air_move = Some(value); + } else { + w.unit_mut(id)?.terrain.air_atk = value; + } + if value == neutral { + r.remove(w, h, id, "terrain:airflow")?; + } else { + r.add( + w, + h, + id, + Spec { + buff: Buff { + key: Some("terrain:airflow".into()), + mods: [(key.into(), value)].into(), + ..Default::default() + }, + mods_present: true, + ..Default::default() + }, + )?; + } + Ok(()) + } +} diff --git a/crates/engine/src/battle/waves.rs b/crates/engine/src/battle/waves.rs index cc93d44..8931f75 100644 --- a/crates/engine/src/battle/waves.rs +++ b/crates/engine/src/battle/waves.rs @@ -1,6 +1,8 @@ // SPDX-License-Identifier: GPL-3.0-or-later // Stronghold Protocol 41bbca57 simdata.js and battle/spawns.js. // These are engine inputs, never policy observations (future waves are private). +mod bounty; +use bounty::Layout; use serde_json::{json, Value}; use std::collections::VecDeque; @@ -43,6 +45,13 @@ fn cp_type(v: &Value) -> &'static str { "MOVE" } } +pub(crate) fn has_patrol(route: &Value) -> bool { + route["steps"] + .as_array() + .into_iter() + .flatten() + .any(|s| s["t"] == "patrol") +} pub fn normalize_route(v: &Value, max_legs: usize) -> Result { if v.is_null() { return Ok(Value::Null); @@ -113,10 +122,15 @@ pub fn normalize_route(v: &Value, max_legs: usize) -> Result { /// Normalized wave data. Non-SPAWN actions are kept separately so a caller cannot /// accidentally accept an unimplemented content action by dropping it. +#[derive(Clone)] pub struct Template { + bounty_layout: Layout, + pub devices: Vec, + pub patrol_routes: std::collections::BTreeSet, pub routes: Vec, pub spawns: Vec, pub extra_routes: Vec, + pub branches: std::collections::BTreeMap>>, pub overrides: Value, pub max_play_time: Value, pub content_actions: Vec, @@ -139,14 +153,65 @@ impl Template { } a.iter().map(|r| normalize_route(r, max_legs)).collect() }; + let devices = v["devices"].as_array().map(Vec::as_slice).unwrap_or(&[]); + if devices.len() > capacity { + return Err("Wave device capacity exceeded".into()); + } + for device in devices { + if let Some(pos) = device.get("pos") { + if !pos.as_array().is_some_and(|p| { + p.len() == 2 && p.iter().all(|v| v.as_f64().is_some_and(|n| n.is_finite())) + }) { + return Err("Invalid wave device position".into()); + } + } + } let mut out = Self { + bounty_layout: Layout::default(), + devices: devices.to_vec(), routes: routes("routes")?, + patrol_routes: v["routes"] + .as_array() + .into_iter() + .flatten() + .enumerate() + .filter_map(|(i, r)| has_patrol(r).then_some(i)) + .collect(), spawns: vec![], extra_routes: routes("extraRoutes")?, + branches: Default::default(), overrides: v["overrides"].clone(), max_play_time: first(v, &["maxPlayTime", "timeLimit"]).clone(), content_actions: vec![], }; + if let Some(branches) = v["branches"].as_object() { + if branches.len() > capacity { + return Err("Wave branch capacity exceeded".into()); + } + let mut entries = 0usize; + let mut phase_count = 0usize; + for (name, phases) in branches { + let phases = phases.as_array().ok_or("Expected branch phases")?; + phase_count = phase_count + .checked_add(phases.len()) + .ok_or("Branch phase capacity overflow")?; + if phase_count > capacity { + return Err("Branch phase capacity exceeded".into()); + } + let mut parsed = vec![]; + for phase in phases { + let phase = phase.as_array().ok_or("Expected branch phase actions")?; + entries = entries + .checked_add(phase.len()) + .ok_or("Branch capacity overflow")?; + if entries > capacity { + return Err("Branch action capacity exceeded".into()); + } + parsed.push(phase.clone()); + } + out.branches.insert(name.clone(), parsed); + } + } if let Some(a) = v["spawns"].as_array() { if a.len() > capacity { return Err("Wave action capacity exceeded".into()); @@ -340,42 +405,3 @@ impl Queue { self.pending.drain(..) } } - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn overflow_preserves_queue_and_identity() { - let mut q = Queue::new(3).unwrap(); - q.push(&json!({"enemyKey":"a","count":2,"time":1}), true, false) - .unwrap(); - assert!(q.push(&json!({"count":2}), true, false).is_err()); - assert_eq!(q.sequence(), 2); - assert_eq!(q.pending().len(), 2); - assert!(q.pop_due(0.).is_none()); - assert_eq!(q.pop_due(1.).unwrap().sequence, 1); - q.next_sequence().unwrap(); - q.push(&json!({"enemyKey":"b","time":1}), true, false) - .unwrap(); - assert_eq!(q.pop_due(1.).unwrap().sequence, 2); - assert_eq!(q.pop_due(1.).unwrap().sequence, 4); - } - #[test] - fn portal_expansion_and_content_are_never_silently_dropped() { - let v = json!({"cp":[["DISAPPEAR",0,0],["WAIT",0,0,3],["MOVE",5,10]]}); - assert!(normalize_route(&v, 3).is_err()); - let r = normalize_route(&v, 4).unwrap(); - assert_eq!(r["checkpoints"][2]["type"], "APPEAR"); - assert_eq!(normalize_route(&r, 4).unwrap(), r); - let t = Template::parse( - &json!({"spawns":[{"action":"ACTIVATE","key":"a"}]}), - &Value::Null, - &Value::Null, - 1, - 4, - ) - .unwrap(); - assert!(t.spawns.is_empty()); - assert_eq!(t.content_actions.len(), 1); - } -} diff --git a/crates/engine/src/battle/waves/bounty.rs b/crates/engine/src/battle/waves/bounty.rs new file mode 100644 index 0000000..918fa6a --- /dev/null +++ b/crates/engine/src/battle/waves/bounty.rs @@ -0,0 +1,212 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Original action windows needed when bounties join resolved wave actions. +use super::*; +#[derive(Clone, Debug, Default)] +pub(super) struct Layout { + ground: Option, + fly: Option, +} +#[derive(Clone, Debug)] +struct Host { + index: usize, + time: f64, + window: f64, + route: Option, + own: usize, +} +impl Template { + /// Attach original template windows and the generator's resolved action counts. + /// Legacy explicit waves retain the source's no-template fallback. + pub fn configure_bounty_actions( + &mut self, + original: &Value, + actions: &[Value], + slots: &Value, + capacity: usize, + ) -> Result<(), String> { + let list = original["spawns"] + .as_array() + .map(Vec::as_slice) + .unwrap_or(&[]); + if list.len() > capacity || actions.len() > capacity { + return Err("Wave action capacity exceeded".into()); + } + let make = |fly: bool| -> Result, String> { + let spawn = |s: &&Value| { + s.is_object() + && s.get("action").is_none_or(|a| { + a.is_null() || a.as_str().is_some_and(|a| a.eq_ignore_ascii_case("SPAWN")) + }) + }; + let want = &slots[if fly { "NF" } else { "N" }]; + let selected = list + .iter() + .enumerate() + .find(|(_, s)| spawn(s) && first(s, &["key", "enemyKey"]) == want) + .or_else(|| list.iter().enumerate().find(|(_, s)| spawn(s))); + let Some((index, s)) = selected else { + return Ok(None); + }; + let count = s["count"].as_u64().unwrap_or(1).max(1); + if count > 50 { + return Err("Original wave action unit capacity exceeded".into()); + } + let time = number(&s["time"], 0.).max(0.); + let window = count as f64 * number(&s["interval"], 0.).max(0.); + if !window.is_finite() { + return Err("Invalid wave action window".into()); + } + let own = actions + .iter() + .find(|a| a["index"].as_u64() == Some(index as u64)) + .filter(|a| a["valid"] == true && a["server"] != false) + .map_or(0, |a| a["count"].as_u64().unwrap_or(0).min(50) as usize); + Ok(Some(Host { + index, + time, + window, + route: s["routeIndex"] + .as_u64() + .and_then(|n| usize::try_from(n).ok()), + own, + })) + }; + self.bounty_layout = Layout { + ground: make(false)?, + fly: make(true)?, + }; + Ok(()) + } + /// Re-time normal-wave host units around bounty insertions. Boss waves keep + /// their original spawn list, as bountySpawns does in the source boss owner. + pub fn insert_bounties( + &mut self, + additions: Vec, + boss: bool, + capacity: usize, + ) -> Result<(), String> { + if additions.is_empty() { + return Ok(()); + } + if additions.len() > capacity || self.spawns.len() > capacity { + return Err("Bounty spawn capacity exceeded".into()); + } + let mut groups: Vec<(Option, Vec)> = Vec::new(); + for (i, s) in additions.iter().enumerate() { + let fly = matches!(s["mods"]["slot"].as_str(), Some("NF" | "EF")); + let host = if fly { + &self.bounty_layout.fly + } else { + &self.bounty_layout.ground + }; + let index = host.as_ref().map(|h| h.index); + let group = groups + .iter() + .position(|(h, _)| h.as_ref().map(|h| h.index) == index); + let at = group.unwrap_or_else(|| { + groups.push((host.clone(), Vec::new())); + groups.len() - 1 + }); + groups[at].1.push(i); + } + let mut retimed = std::collections::BTreeMap::new(); + let mut extras = Vec::new(); + for (host, ids) in groups { + let own = host.as_ref().map_or(0, |h| h.own); + let time = host.as_ref().map_or(4., |h| h.time); + let window = host.as_ref().map_or(0., |h| h.window); + let mut added = Vec::new(); + for id in ids { + let n = additions[id]["count"].as_u64().unwrap_or(1).clamp(1, 20) as usize; + if added.len() + n > capacity.saturating_mul(20) { + return Err("Bounty unit capacity exceeded".into()); + } + added.extend(std::iter::repeat_n(Some(id), n)); + } + let mut order = vec![None; own]; + if own == 0 { + order = added; + } else { + let total = added.len(); + for (i, id) in added.into_iter().enumerate() { + let at = ((i + 1) * order.len()) / (total + 1); + order.insert(at, id); + } + } + let step = if window > 0. { + (window / order.len() as f64).max(0.05 * window) + } else { + 0. + }; + let mut own_runs = Vec::new(); + let mut start = 0; + while start < order.len() { + let mut end = start + 1; + while end < order.len() && order[end] == order[start] { + end += 1; + } + let count = end - start; + let at = time + start as f64 * step; + if !at.is_finite() { + return Err("Bounty spawn time exceeds finite domain".into()); + } + if let Some(id) = order[start] { + let mut s = additions[id].clone(); + s["time"] = json!(at); + s["count"] = json!(count); + s["interval"] = json!(if count > 1 { step } else { 0. }); + if let Some(h) = &host { + s["actionIndex"] = json!(h.index); + if let Some(route) = h.route.filter(|i| { + self.routes.get(*i).is_some_and(|r| { + let fly = matches!(s["mods"]["slot"].as_str(), Some("NF" | "EF")); + (if fly { + r["motion"] == "FLY" + } else { + r["motion"] != "FLY" && r["motion"] != "E_NUM" + }) && (!boss || r["end"][1].as_f64().is_some_and(|x| x < 10.)) + }) + }) { + s["routeIndex"] = json!(route); + } + } + extras.push(s); + } else { + own_runs.push((at, count, if count > 1 { step } else { 0. })); + } + start = end; + } + if let Some(h) = host.filter(|_| own > 0 && !boss) { + retimed.insert(h.index, own_runs); + } + } + let mut output = Vec::new(); + for s in &self.spawns { + let runs = s["actionIndex"] + .as_u64() + .and_then(|n| usize::try_from(n).ok()) + .and_then(|n| retimed.get(&n)) + .filter(|_| s["tag"] != "bounty"); + if let Some(runs) = runs { + for (time, count, interval) in runs { + let mut s = s.clone(); + s["time"] = json!(time); + s["count"] = json!(count); + s["interval"] = json!(interval); + output.push(s); + } + } else { + output.push(s.clone()); + } + if output.len() + extras.len() > capacity { + return Err("Bounty spawn capacity exceeded".into()); + } + } + output.extend(extras); + if output.len() > capacity { + return Err("Bounty spawn capacity exceeded".into()); + } + self.spawns = output; + Ok(()) + } +} diff --git a/crates/engine/src/data.rs b/crates/engine/src/data.rs index a9ce53a..a691a50 100644 --- a/crates/engine/src/data.rs +++ b/crates/engine/src/data.rs @@ -1,6 +1,6 @@ //! External JSON data only: no game source checkout, Git or Node dependency. use serde_json::Value; -use std::{collections::BTreeMap, fs::File, io::Read, path::Path}; +use std::{collections::BTreeMap, fs::File, io::Read, path::Path, sync::Arc}; const TABLES: &[&str] = &[ "config", @@ -20,17 +20,18 @@ const TABLES: &[&str] = &[ "backups", ]; -#[derive(Debug)] +#[derive(Clone, Debug)] pub struct Definition { pub index: u32, pub table: String, pub id: String, } -#[derive(Debug)] +#[derive(Clone, Debug)] pub struct Catalog { - tables: BTreeMap, + tables: BTreeMap>, definitions: Vec, + base_chess: Arc, } impl Catalog { @@ -58,7 +59,7 @@ impl Catalog { if !value.is_object() { return Err(format!("{name}: expected an object")); } - tables.insert(name.to_string(), value); + tables.insert(name.to_string(), Arc::new(value)); } let mut definitions = Vec::new(); // Stable numeric IDs are independent of file and JSON object insertion order. @@ -76,15 +77,19 @@ impl Catalog { }); } } + let base_chess = Arc::clone(&tables["chess"]); Ok(Self { + base_chess, tables, definitions, }) } pub fn table(&self, name: &str) -> Option<&Value> { - self.tables.get(name) + self.tables.get(name).map(Arc::as_ref) } pub fn definitions(&self) -> &[Definition] { &self.definitions } } + +mod diy; diff --git a/crates/engine/src/data/diy.rs b/crates/engine/src/data/diy.rs new file mode 100644 index 0000000..b472624 --- /dev/null +++ b/crates/engine/src/data/diy.rs @@ -0,0 +1,362 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Per-session bodies for the existing four DIY identities. Tables remain shared. +use super::*; +use serde_json::{json, Map}; + +fn strip_potential(value: &mut Value) { + match value { + Value::Object(map) => { + for key in ["potDown", "potMin", "potBelow"] { + map.remove(key); + } + for value in map.values_mut() { + strip_potential(value); + } + } + Value::Array(values) => values.iter_mut().for_each(strip_potential), + _ => {} + } +} +fn form<'a>(unit: &'a Value, slot: &Value) -> Result<&'a Value, String> { + let s = &slot["status"]; + let key = format!( + "{}/{}/{}/{}", + s["phase"], s["level"], s["skillLevel"], s["equipLevel"] + ); + unit["forms"] + .get(&key) + .ok_or_else(|| format!("Missing DIY form {key}")) +} +fn compose(slot: &Value, unit: &Value, pick: &Value, bonds: &Value) -> Result { + let form = form(unit, slot)?; + let skills = form["skills"].as_array().ok_or("Missing DIY skills")?; + let skill = skills + .iter() + .find(|s| s["index"] == pick["skillIndex"]) + .ok_or("Unknown DIY skill")?; + let module = form["modules"] + .as_array() + .into_iter() + .flatten() + .find(|m| !pick["uniEquipId"].is_null() && m["uniEquipId"] == pick["uniEquipId"]); + let mut record = Map::new(); + for key in [ + "chessId", + "baseId", + "goldenId", + "isGolden", + "tier", + "identifier", + "isHidden", + "isDiy", + "visible", + "chessType", + "backup", + "shopSortId", + "bonds", + "garrisonIds", + "price", + "sellPrice", + "upgradeNum", + "upgradeChessId", + "status", + "diyRequirement", + ] { + if let Some(v) = slot.get(key) { + record.insert(key.into(), v.clone()); + } + } + record.insert("bonds".into(), bonds.clone()); + for key in [ + "charId", + "name", + "appellation", + "rarity", + "profession", + "subProfessionId", + "subProfessionName", + "position", + "nationId", + ] { + if let Some(v) = unit.get(key) { + record.insert(key.into(), v.clone()); + } + } + for key in [ + "stats", + "immunities", + "rangeId", + "rangeGrid", + "dmgType", + "attackKind", + "projectile", + "canHitFly", + "targetPriority", + "trait", + ] { + if let Some(v) = form.get(key) { + record.insert(key.into(), v.clone()); + } + } + if form["placeOnRanged"] == true { + record.insert("placeOnRanged".into(), json!(true)); + } + let mut talents = form["talents"].as_array().cloned().unwrap_or_default(); + for t in &mut talents { + strip_potential(t); + } + if let Some(m) = module { + for (key, value) in m["attr"].as_object().into_iter().flatten() { + let v = record["stats"][key].as_f64().unwrap_or(0.) + + value.as_f64().ok_or("Invalid DIY module attribute")?; + let v = if v.fract() != 0. && v.abs() < 1e6 { + (v * 1e6 + 0.5).floor() / 1e6 + } else { + v + }; + record.get_mut("stats").ok_or("Missing DIY stats")?[key] = json!(v); + } + if !m["traitOverride"].is_null() { + record.insert("trait".into(), m["traitOverride"].clone()); + } + for change in m["talentChanges"].as_array().into_iter().flatten() { + let mut t = change.clone(); + strip_potential(&mut t); + let index = t["talentIndex"].clone(); + let map = t.as_object_mut().ok_or("Invalid DIY module talent")?; + map.remove("talentIndex"); + map.insert("index".into(), index.clone()); + map.insert("fromModule".into(), json!(true)); + if let Some(old) = talents + .iter_mut() + .find(|x| index.as_i64().is_some_and(|i| i >= 0) && x["index"] == index) + { + for key in ["name", "desc", "descRaw", "rangeGrid", "tokenKey"] { + if t[key].is_null() || t[key].as_str() == Some("") { + t[key] = old[key].clone(); + } + } + for key in ["bb", "bbStr"] { + let mut fields = old[key].as_object().cloned().unwrap_or_default(); + fields.extend(t[key].as_object().cloned().unwrap_or_default()); + t[key] = Value::Object(fields); + } + t["hidden"] = json!(old["hidden"] == true && t["hidden"] == true); + *old = t; + } else { + talents.push(t); + } + } + } + talents.retain(|t| { + t["name"].as_str().is_some_and(|s| !s.is_empty()) + || t["desc"].as_str().is_some_and(|s| !s.is_empty()) + || t["bb"].as_object().is_some_and(|m| !m.is_empty()) + || t["tokenKey"].is_string() + }); + let mut tokens = std::collections::BTreeSet::new(); + for id in form["displayTokens"] + .as_array() + .into_iter() + .flatten() + .chain(std::iter::once(&skill["overrideTokenKey"])) + .chain(talents.iter().map(|t| &t["tokenKey"])) + { + if let Some(id) = id + .as_str() + .filter(|_| form["tokens"].as_array().is_some_and(|a| a.contains(id))) + { + tokens.insert(id); + } + } + record.insert("tokens".into(), json!(tokens)); + record.insert("talents".into(), json!(talents)); + record.insert("skill".into(), skill.clone()); + record.insert( + "skills".into(), + json!(skills + .iter() + .map(|s| { + let mut s = s.clone(); + s["isDefault"] = json!(s["index"] == pick["skillIndex"]); + s + }) + .collect::>()), + ); + let level = slot["status"]["equipLevel"].as_u64().unwrap_or(0); + let mid = pick["uniEquipId"].as_str(); + let info = &unit["moduleNames"][mid.unwrap_or("")]; + let module_metadata = if mid.is_some() { + json!({ + "id": pick["uniEquipId"], "name": info["name"], "type": info["typeName"], + "level": level, "active": level > 0 && module.is_some() + }) + } else if level > 0 { + json!({"id": null, "name": null, "type": null, "level": level, "active": false}) + } else { + Value::Null + }; + record.insert("module".into(), module_metadata); + if slot["isGolden"] == true && level > 0 { + record.insert("statsBase".into(), form["stats"].clone()); + record.insert("traitBase".into(), form["trait"].clone()); + let mut ts = form["talents"].clone(); + strip_potential(&mut ts); + record.insert("talentsBase".into(), ts); + let mut mods = form["modules"].as_array().cloned().unwrap_or_default(); + for m in &mut mods { + strip_potential(m); + m["isDefault"] = json!(mid.is_some() && m["uniEquipId"] == pick["uniEquipId"]); + } + record.insert("modules".into(), json!(mods)); + } + let a = &unit["assets"]; + let golden = slot["isGolden"] == true; + let mut assets = Map::new(); + for key in [ + "avatar", + "portrait", + "spine", + "skillIcon", + "subProfIcon", + "voice", + ] { + let alt = format!("{key}Golden"); + let v = if golden { + a.get(&alt).filter(|v| !v.is_null()).or_else(|| a.get(key)) + } else { + a.get(key) + }; + if let Some(v) = v { + assets.insert(key.into(), v.clone()); + } + } + if !assets.contains_key("skillIcon") { + assets.insert("skillIcon".into(), skill["iconId"].clone()); + } + record.insert("assets".into(), Value::Object(assets)); + for key in [ + "kitRef", + "skillSpec", + "talentMods", + "dsl", + "pluginId", + "origin", + ] { + if let Some(v) = form.get(key).or_else(|| unit.get(key)) { + record.insert(key.into(), v.clone()); + } + } + record.insert("diyFor".into(), slot["baseId"].clone()); + Ok(Value::Object(record)) +} +impl Catalog { + pub fn with_diy(&self, picks: &Value) -> Result { + let picks = picks + .as_object() + .filter(|p| p.len() <= 4) + .ok_or("DIY requires at most four slot picks")?; + if picks.is_empty() { + let mut out = self.clone(); + out.tables + .insert("chess".into(), Arc::clone(&self.base_chess)); + out.tables.remove("diy"); + return Ok(out); + } + let backups = self.table("backups").ok_or("Missing backups")?; + let diy = &backups["diy"]; + let mut chess = self.base_chess.as_ref().clone(); + let mut kept = Map::new(); + let mut tiers_seen = std::collections::BTreeSet::new(); + let mut owned_seen = std::collections::BTreeSet::new(); + for (id, input) in picks { + let slot = diy["slots"] + .get(id) + .ok_or_else(|| format!("Unknown DIY slot {id}"))?; + if input.is_null() { + continue; + } + let char_id = input["charId"] + .as_str() + .filter(|id| id.len() <= 64) + .ok_or("Invalid DIY operator")?; + let tier = slot["tier"].to_string(); + let proto = diy["prototypes"][&tier] + .as_array() + .is_some_and(|a| a.contains(&json!(char_id))); + if !proto + && !diy["ownedPool"] + .as_array() + .is_some_and(|a| a.contains(&json!(char_id))) + { + return Err(format!("Operator unavailable in DIY slot {id}")); + } + if !tiers_seen.insert((tier.clone(), char_id)) + || (!proto && !owned_seen.insert(char_id)) + { + return Err("Duplicate DIY operator".into()); + } + let mut pick = input.clone(); + if !pick.is_object() { + return Err("Invalid DIY pick".into()); + } + if proto { + let lock = &diy["locked"][&tier][char_id]; + if !lock.is_object() + || (!pick["skillIndex"].is_null() && pick["skillIndex"] != lock["skillIndex"]) + || (!pick["uniEquipId"].is_null() && pick["uniEquipId"] != lock["uniEquipId"]) + { + return Err("Invalid locked DIY selection".into()); + } + pick = json!({"charId":char_id,"skillIndex":lock["skillIndex"],"uniEquipId":lock["uniEquipId"]}); + } else { + if pick["skillIndex"].as_u64().is_none_or(|i| i > 9) { + return Err("Invalid DIY skill index".into()); + } + if pick["uniEquipId"] == "none" { + pick["uniEquipId"] = Value::Null; + } + pick = json!({"charId":char_id,"skillIndex":pick["skillIndex"],"uniEquipId":pick["uniEquipId"]}); + } + let unit = backups["units"] + .get(char_id) + .ok_or("Missing DIY operator body")?; + let golden_id = slot["goldenId"] + .as_str() + .ok_or("Missing DIY golden identity")?; + let elite = form(unit, &chess[golden_id])?; + if !pick["uniEquipId"].is_null() { + let m = elite["modules"] + .as_array() + .into_iter() + .flatten() + .find(|m| m["uniEquipId"] == pick["uniEquipId"]) + .ok_or("Unknown DIY module")?; + if m["typeName"] + .as_str() + .is_some_and(|t| ["ISW-", "SO-", "RA-"].iter().any(|p| t.starts_with(p))) + { + return Err("DIY module belongs to another mode".into()); + } + } + for key in [id.as_str(), golden_id] { + let mut body = compose( + &chess[key], + unit, + &pick, + &diy["operators"][char_id]["bonds"], + )?; + if proto { + body["diyProto"] = json!(true); + } + chess[key] = body; + } + kept.insert(id.clone(), pick); + } + let mut out = self.clone(); + out.tables.insert("chess".into(), Arc::new(chess)); + out.tables + .insert("diy".into(), Arc::new(Value::Object(kept))); + Ok(out) + } +} diff --git a/crates/engine/src/deterministic/scheduler.rs b/crates/engine/src/deterministic/scheduler.rs index bdddce0..2da6051 100644 --- a/crates/engine/src/deterministic/scheduler.rs +++ b/crates/engine/src/deterministic/scheduler.rs @@ -104,35 +104,3 @@ impl Scheduler { Ok(Some(event)) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn intervals_rearm_before_callback_and_can_cancel_themselves() { - let mut s = Scheduler::new(4).unwrap(); - let repeat = s.schedule("repeat", 2.0, true).unwrap(); - s.schedule("once", 2.0, false).unwrap(); - assert_eq!(s.pop().unwrap().unwrap().payload, "repeat"); - s.schedule("callback", 2.0, false).unwrap(); - assert_eq!(s.pop().unwrap().unwrap().payload, "once"); - assert_eq!(s.pop().unwrap().unwrap().payload, "repeat"); - s.cancel(repeat); - assert_eq!(s.pop().unwrap().unwrap().payload, "callback"); - assert!(s.pop().unwrap().is_none()); - assert_eq!(s.now(), 4.0); - } - - #[test] - fn budget_failure_does_not_change_clock_or_queue() { - let mut s = Scheduler::new(1).unwrap(); - let id = s.schedule(1, f64::INFINITY, false).unwrap(); - assert!(s.schedule(2, 0.0, false).is_err()); - assert_eq!(s.now(), 0.0); - assert_eq!(s.next_at(), Some(0.0)); - s.cancel(id); - assert_eq!(s.schedule(3, -1.0, true).unwrap(), 2); - assert_eq!(s.next_at(), Some(1.0)); - } -} diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs new file mode 100644 index 0000000..edbe8ad --- /dev/null +++ b/crates/engine/src/history.rs @@ -0,0 +1,328 @@ +//! Native decision history: the `arkguardrl.candidates.DecisionHistory` ledger. +//! +//! The history is a view of the public decision context, not a memory of hidden +//! state. It binds the exact public progress stream, groups attempted intents by +//! `decision_id`, masks rejected intents only at the decision that rejected them, +//! and counts PREP attempts so the candidate builder can stop offering prep +//! actions after the native 64-action recovery limit. +//! +//! Python's `_sync` mutates the ledger: a round/phase change clears both the +//! attempt groups and `prep_used`. `blocked`/`snapshot` therefore take `&mut self` +//! here, exactly like the Python methods they replace; taking `&self` would keep +//! attempts from an older context alive after a newer snapshot and diverge on a +//! later record at that older context. `blocked` returns the set of rejected +//! `action_id`s (the Python method returns a `frozenset`) because a boolean can +//! not express which of several candidate intents is masked. + +use crate::identity::{action_id, decision_id, fingerprint}; +use crate::progress::{EXECUTION_SCHEMA, PROGRESS_SCHEMA}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +pub const HISTORY_SCHEMA: &str = "arkguardrl/native-context-attempts-feedback-intent-prep64-v4"; +pub const PREP_ACTION_LIMIT: u64 = 64; + +type Result = std::result::Result; + +fn missing(message: &str) -> String { + message.to_string() +} + +/// JSON integers only: Python's `type(value) is int` excludes booleans and floats. +fn integer(value: &Value) -> Option { + match value { + Value::Number(number) if !number.is_f64() => number + .as_i64() + .map(i128::from) + .or_else(|| number.as_u64().map(i128::from)), + _ => None, + } +} + +/// The numeric value Python's `<`/`<=` comparisons accept for receipt sequences. +fn numeric(value: &Value) -> Option { + match value { + Value::Number(number) => number.as_f64(), + _ => None, + } +} + +#[derive(Clone, Debug, Default)] +pub struct DecisionHistory { + /// Last observed `(round, phase)`; groups are discarded when this changes. + context: Option<(Value, Value)>, + /// Attempted `action_id`s by `decision_id` of the public decision context. + attempts: BTreeMap>, + prep_used: u64, + progress: Option, + state: Option>, + cached_decision: Option<(Arc, String)>, +} + +impl DecisionHistory { + pub fn new() -> Self { + Self::default() + } + + /// Bind the history to the real reset observation and its public progress. + /// + /// Python also rejects a step result here through `result.accepted is not + /// None`. The state/progress signature cannot see that flag, but every real + /// step progress carries `last_execution`, which is checked instead. + pub fn initialize(&mut self, result_state: Arc, progress: &Value) -> Result<()> { + let initialized = self.progress.is_some() + || progress + .get("last_execution") + .is_some_and(|value| !value.is_null()); + if initialized { + return Err("Initialize history exactly once from a real reset result".into()); + } + self.observe(result_state, progress) + } + + /// Bind the public progress stream to this exact observation. + /// + /// A failure leaves the ledger unchanged, so a rejected receipt can be + /// reported without corrupting the stream. + fn observe(&mut self, state: Arc, progress: &Value) -> Result<()> { + let map = progress.as_object().ok_or_else(|| { + missing("Exact public progress stream required; legacy history is incompatible") + })?; + let observation_id = self.observation_id(&state)?; + if map.get("schema").and_then(Value::as_str) != Some(PROGRESS_SCHEMA) + || map.get("observation_id").and_then(Value::as_str) != Some(&observation_id) + { + return Err( + "Exact public progress stream required; legacy history is incompatible".into(), + ); + } + let stream_id = map.get("stream_id").and_then(Value::as_str); + let sequence = map.get("sequence").and_then(integer); + let ordered = stream_id.is_some_and(|id| id.chars().count() == 32) + && sequence.is_some_and(|sequence| sequence >= 1); + if !ordered { + return Err("Public progress stream identity/order is missing".into()); + } + let (stream_id, sequence) = (stream_id.unwrap(), sequence.unwrap()); + if let Some(previous) = self.progress.as_ref() { + let previous_stream = previous.get("stream_id").and_then(Value::as_str); + let previous_sequence = previous + .get("sequence") + .and_then(integer) + .ok_or_else(|| missing("Public progress stream identity/order is missing"))?; + if previous_stream != Some(stream_id) || sequence <= previous_sequence { + return Err("Public progress crossed streams or repeated an observation".into()); + } + } + self.progress = Some(progress.clone()); + self.state = Some(state); + Ok(()) + } + + fn observation_id(&self, state: &Value) -> Result { + let bound_id = self + .progress + .as_ref() + .and_then(|progress| progress.get("observation_id")) + .and_then(Value::as_str); + match (self.state.as_deref(), bound_id) { + // Retaining an Arc prevents this exact allocation from being mutated. + (Some(owned), Some(id)) if std::ptr::eq(owned, state) => Ok(id.to_owned()), + _ => fingerprint(state), + } + } + + /// Record one real attempted step, accepted or rejected, after the fact. + /// + /// `before` is the state the intent was chosen at, `after` is + /// `result.observation`, `receipt` is `result.execution`, `result_progress` + /// is `result.progress` and `accepted` is `result.accepted`. Python also + /// compares `result.action_id`, which the transport derives as + /// `action_id(action)`; recomputing it below is the same identity. + pub fn record( + &mut self, + before: Arc, + after: Arc, + action: &Value, + receipt: &Value, + result_progress: &Value, + accepted: bool, + ) -> Result<()> { + let bound = "History requires the bound real execution receipt"; + let report = receipt.as_object().ok_or_else(|| missing(bound))?; + if report.get("schema").and_then(Value::as_str) != Some(EXECUTION_SCHEMA) { + return Err(bound.into()); + } + // A receipt is boolean about acceptance; `1`/`true` must not alias. + if report.get("accepted") != Some(&Value::Bool(accepted)) { + return Err(bound.into()); + } + let aid = action_id(action)?; + if report.get("action_id").and_then(Value::as_str) != Some(&aid) { + return Err(bound.into()); + } + if report.get("intent") != Some(action) { + return Err(bound.into()); + } + let before_id = self.observation_id(&before)?; + if report.get("before_id").and_then(Value::as_str) != Some(&before_id) { + return Err(bound.into()); + } + if !result_progress.is_object() || result_progress.get("last_execution") != Some(receipt) { + return Err(bound.into()); + } + let previous = self + .progress + .as_ref() + .ok_or_else(|| missing("History execution stream is disconnected"))?; + if previous.get("observation_id").and_then(Value::as_str) != Some(&before_id) { + return Err("History execution stream is disconnected".into()); + } + let previous_sequence = previous.get("sequence").and_then(integer).ok_or_else(|| { + missing("Execution receipt does not continue the current public stream") + })?; + // Python's `report.get("sequence", 0)` only defaults when the key is absent. + let receipt_sequence = match report.get("sequence") { + None => 0.0, + Some(value) => numeric(value).ok_or_else(|| { + missing("Execution receipt does not continue the current public stream") + })?, + }; + let result_sequence = result_progress + .get("sequence") + .and_then(numeric) + .ok_or_else(|| { + missing("Execution receipt does not continue the current public stream") + })?; + let continuing = previous.get("stream_id").and_then(Value::as_str) + == report.get("stream_id").and_then(Value::as_str) + && (previous_sequence as f64) < receipt_sequence + && receipt_sequence <= result_sequence; + if !continuing { + return Err("Execution receipt does not continue the current public stream".into()); + } + self.observe(after, result_progress)?; + let key = self.sync(&before)?; + self.attempts.entry(key).or_default().insert(aid); + // Only a real PREP action consumes the recovery budget; a mandatory + // personal choice is not a prep action. + let prep = before.get("phase").and_then(Value::as_str) == Some("PREP"); + let choice = action.get("t").and_then(Value::as_str) == Some("g.choice"); + if prep && !choice { + self.prep_used += 1; + } + Ok(()) + } + + /// Rejected `action_id`s at this exact public decision context. + pub fn blocked(&mut self, state: &Value) -> Result> { + let key = self.sync(state)?; + Ok(self.attempts.get(&key).cloned().unwrap_or_default()) + } + + /// The v4 snapshot consumed by feature encoding. + pub fn snapshot(&mut self, state: &Value) -> Result { + let observation_id = self.observation_id(state)?; + let bound = self + .progress + .as_ref() + .and_then(|progress| progress.get("observation_id")) + .and_then(Value::as_str) + == Some(observation_id.as_str()); + if !bound { + return Err( + "Initialize/update history with the real environment result before encoding".into(), + ); + } + let key = self.sync(state)?; + let blocked_count = self.attempts.get(&key).map_or(0, BTreeSet::len); + Ok(json!({ + "schema": HISTORY_SCHEMA, + "progress": self.progress.clone().unwrap_or(Value::Null), + "used": self.prep_used, + "limit": PREP_ACTION_LIMIT, + "blocked_count": blocked_count, + })) + } + + /// Python `_sync`: a new round/phase discards every group and the prep count. + fn sync(&mut self, state: &Value) -> Result { + let round = state + .get("round") + .cloned() + .ok_or_else(|| missing("Decision state has no round"))?; + let phase = state + .get("phase") + .cloned() + .ok_or_else(|| missing("Decision state has no phase"))?; + let context = (round, phase); + if self.context.as_ref() != Some(&context) { + self.context = Some(context); + self.attempts.clear(); + self.prep_used = 0; + } + if let Some((owned, key)) = &self.cached_decision { + if std::ptr::eq(owned.as_ref(), state) { + return Ok(key.clone()); + } + } + let key = decision_id(state)?; + if let Some(owned) = self + .state + .as_ref() + .filter(|owned| std::ptr::eq(owned.as_ref(), state)) + { + self.cached_decision = Some((Arc::clone(owned), key.clone())); + } + Ok(key) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn initialized() -> (DecisionHistory, Arc) { + let state = Arc::new(json!({ + "schema": "test", "round": 1, "phase": "PREP", "public": {}, "own": {}, + "personalEnded": false, "gameEnded": false, + })); + let progress = json!({ + "schema": PROGRESS_SCHEMA, "observation_id": fingerprint(&state).unwrap(), + "stream_id": "0".repeat(32), "sequence": 1, + }); + let mut history = DecisionHistory::new(); + history.initialize(state.clone(), &progress).unwrap(); + history.snapshot(&state).unwrap(); + (history, state) + } + + #[test] + fn cached_identity_rejects_a_changed_copy() { + let (mut history, mut state) = initialized(); + let original = state.clone(); + let key = decision_id(&original).unwrap(); + history + .attempts + .insert(key, BTreeSet::from(["attempt".into()])); + Arc::make_mut(&mut state)["own"]["funds"] = json!(10); + assert!(history.snapshot(&state).is_err()); + assert!(history.blocked(&state).unwrap().is_empty()); + assert!(history.blocked(&original).unwrap().contains("attempt")); + assert!(history.snapshot(&original).is_ok()); + } + + #[test] + fn cached_decision_still_resets_context() { + let (mut history, state) = initialized(); + let key = decision_id(&state).unwrap(); + history + .attempts + .insert(key, BTreeSet::from(["attempt".into()])); + let mut next_round = state.as_ref().clone(); + next_round["round"] = json!(2); + assert!(history.blocked(&next_round).unwrap().is_empty()); + assert!(history.blocked(&state).unwrap().is_empty()); + } +} diff --git a/crates/engine/src/identity.rs b/crates/engine/src/identity.rs new file mode 100644 index 0000000..61e0cf6 --- /dev/null +++ b/crates/engine/src/identity.rs @@ -0,0 +1,425 @@ +//! Canonical JSON identities, byte-identical to `arkguardrl.contracts`. +//! +//! Python's `json.dumps(sort_keys=True, separators=(",", ":"), +//! ensure_ascii=False, allow_nan=False)` defines the bytes. That is not +//! `serde_json::to_string`: keys sort by Unicode code point (UTF-8 byte order), +//! floats use `repr` (shortest round-trip, fixed for decpt in -3..=16, `e+NN` +//! beyond, `-0.0` preserved), and non-ASCII strings stay raw UTF-8. So the +//! writer below is explicit, and SHA-256 is implemented on std alone because +//! this crate has no hash dependency. +//! +//! The input domain is `serde_json::Value`: strings contain Unicode scalar +//! values, and integers fit i64/u64. Python's arbitrary-size integers and lone +//! UTF-16 surrogates cannot be represented by that type. Parse JSON with +//! `float_roundtrip` enabled to preserve the original f64 before calling here; +//! the engine already enables it. Nonfinite floats are rejected by the writer +//! (serde_json::Number itself cannot contain them). + +use serde_json::{Map, Value}; + +pub const ACTION_SCHEMA: &str = "arkguardrl/native-intent-v1"; +pub const CONTEXT_SCHEMA: &str = "arkguardrl/decision-context-v1"; + +/// UTF-8 bytes of the canonical form; errors mirror the serializer's refusals. +pub fn canonical(value: &Value) -> Result, String> { + let mut out = Vec::with_capacity(256); + write_value(value, &mut out)?; + Ok(out) +} + +/// Lowercase hex SHA-256 of [`canonical`]. +pub fn fingerprint(value: &Value) -> Result { + Ok(hex(&sha256(&canonical(value)?))) +} + +/// Identity of one native intent, over `{"schema": ACTION_SCHEMA, "intent": action}`. +/// +/// The Python compact key (`board_move`/`hand_move` fast paths, then +/// `_intent_key`) only selects an `lru_cache` slot: `_intent_from_key` rebuilds +/// exactly the original value, and the fast paths' arity checks prove their +/// synthesized move carries no extra field. Its depth/key-count/type limits +/// therefore cannot change these bytes; the board/hand rewrite is mirrored for +/// clarity because it is the only branch that builds a value. +pub fn action_id(action: &Value) -> Result { + let Some(map) = action.as_object() else { + return Err("A native intent must contain a string t".into()); + }; + if !matches!(map.get("t"), Some(Value::String(_))) { + return Err("A native intent must contain a string t".into()); + } + let mut out = Vec::with_capacity(256); + out.extend_from_slice(b"{\"intent\":"); + match board_or_hand_move(map) { + Some(intent) => write_value(&intent, &mut out)?, + None => write_value(action, &mut out)?, + } + out.extend_from_slice(b",\"schema\":"); + write_string(ACTION_SCHEMA, &mut out); + out.push(b'}'); + Ok(hex(&sha256(&out))) +} + +/// Identity of the public decision context, ignoring transport timing fields. +pub fn decision_id(state: &Value) -> Result { + let map = state + .as_object() + .ok_or_else(|| "Decision state must be an object".to_string())?; + let schema = map + .get("schema") + .ok_or_else(|| "Decision state has no schema".to_string())?; + let public = map + .get("public") + .and_then(Value::as_object) + .ok_or_else(|| "Decision state has no public object".to_string())?; + let own = map + .get("own") + .ok_or_else(|| "Decision state has no own".to_string())?; + let personal_end = map + .get("personalEnded") + .ok_or_else(|| "Decision state has no personalEnded".to_string())?; + let game_end = map + .get("gameEnded") + .ok_or_else(|| "Decision state has no gameEnded".to_string())?; + // Canonical key order of the wrapper; written directly to avoid cloning own/public. + let mut out = Vec::with_capacity(512); + out.extend_from_slice(b"{\"gameEnded\":"); + write_value(game_end, &mut out)?; + out.extend_from_slice(b",\"observationSchema\":"); + write_value(schema, &mut out)?; + out.extend_from_slice(b",\"own\":"); + write_value(own, &mut out)?; + out.extend_from_slice(b",\"personalEnded\":"); + write_value(personal_end, &mut out)?; + out.extend_from_slice(b",\"public\":"); + write_public(public, &mut out)?; + out.extend_from_slice(b",\"schema\":"); + write_string(CONTEXT_SCHEMA, &mut out); + out.push(b'}'); + Ok(hex(&sha256(&out))) +} + +/// Rebuild the value `_intent_from_key` yields for a `g.move` fast-path key. +fn board_or_hand_move(action: &Map) -> Option { + if action.get("t")?.as_str()? != "g.move" { + return None; + } + let uid = action.get("uid")?; + let to = action.get("to")?.as_object()?; + if !is_integer(uid) || !matches!(to.get("area"), Some(Value::String(_))) { + return None; + } + let mut inner = Map::new(); + inner.insert("area".into(), to.get("area")?.clone()); + match to.get("area")?.as_str()? { + "board" if action.len() == 4 && to.len() == 3 => { + let row = to.get("row")?; + let col = to.get("col")?; + let dir = action.get("dir")?; + if !is_integer(row) || !is_integer(col) || dir.as_str()?.chars().count() > 256 { + return None; + } + inner.insert("row".into(), row.clone()); + inner.insert("col".into(), col.clone()); + let mut out = Map::new(); + out.insert("t".into(), Value::String("g.move".into())); + out.insert("uid".into(), uid.clone()); + out.insert("to".into(), Value::Object(inner)); + out.insert("dir".into(), dir.clone()); + Some(Value::Object(out)) + } + "hand" if action.len() == 3 && to.len() == 2 => { + let index = to.get("idx")?; + if !is_integer(index) { + return None; + } + inner.insert("idx".into(), index.clone()); + let mut out = Map::new(); + out.insert("t".into(), Value::String("g.move".into())); + out.insert("uid".into(), uid.clone()); + out.insert("to".into(), Value::Object(inner)); + Some(Value::Object(out)) + } + _ => None, + } +} + +/// Python `type(v) is int`: JSON integers, never booleans or floats. +fn is_integer(value: &Value) -> bool { + matches!(value, Value::Number(n) if !n.is_f64() && (n.is_i64() || n.is_u64())) +} + +fn write_public(public: &Map, out: &mut Vec) -> Result<(), String> { + let mut entries: Vec<(&str, &Value)> = public + .iter() + .filter(|(k, _)| !matches!(k.as_str(), "serverNow" | "deadline" | "overtimeAt")) + .map(|(k, v)| (k.as_str(), v)) + .collect(); + entries.sort_unstable_by(|a, b| a.0.cmp(b.0)); + out.push(b'{'); + for (index, (key, value)) in entries.iter().enumerate() { + if index > 0 { + out.push(b','); + } + write_string(key, out); + out.push(b':'); + write_value(value, out)?; + } + out.push(b'}'); + Ok(()) +} + +fn write_value(value: &Value, out: &mut Vec) -> Result<(), String> { + match value { + Value::Null => out.extend_from_slice(b"null"), + Value::Bool(true) => out.extend_from_slice(b"true"), + Value::Bool(false) => out.extend_from_slice(b"false"), + Value::Number(number) => write_number(number, out)?, + Value::String(text) => write_string(text, out), + Value::Array(items) => { + out.push(b'['); + for (index, item) in items.iter().enumerate() { + if index > 0 { + out.push(b','); + } + write_value(item, out)?; + } + out.push(b']'); + } + Value::Object(map) => { + let mut entries: Vec<(&str, &Value)> = + map.iter().map(|(k, v)| (k.as_str(), v)).collect(); + entries.sort_unstable_by(|a, b| a.0.cmp(b.0)); + out.push(b'{'); + for (index, (key, item)) in entries.iter().enumerate() { + if index > 0 { + out.push(b','); + } + write_string(key, out); + out.push(b':'); + write_value(item, out)?; + } + out.push(b'}'); + } + } + Ok(()) +} + +fn write_number(number: &serde_json::Number, out: &mut Vec) -> Result<(), String> { + if number.is_f64() { + return write_float(number.as_f64().unwrap_or(f64::NAN), out); + } + if let Some(value) = number.as_u64() { + out.extend_from_slice(value.to_string().as_bytes()); + } else if let Some(value) = number.as_i64() { + out.extend_from_slice(value.to_string().as_bytes()); + } else { + return Err(format!("Unrepresentable JSON integer {number}")); + } + Ok(()) +} + +/// Python `float.__repr__`, as used by `json.dumps` for every JSON float. +fn write_float(value: f64, out: &mut Vec) -> Result<(), String> { + if !value.is_finite() { + return Err("Out of range float values are not JSON compliant".into()); + } + if value == 0.0 { + out.extend_from_slice(if value.is_sign_negative() { + b"-0.0" + } else { + b"0.0" + }); + return Ok(()); + } + // Rust's shortest formatter can break an exact halfway tie upward, while + // dtoa mode 0 (Python repr) rounds the last digit half-to-even. Take the + // shortest length from `{:e}`, then re-render at that precision, where the + // fixed-precision path rounds the exact binary value correctly. + let shortest = format!("{value:e}"); + let shortest_digits = shortest + .trim_start_matches('-') + .split_once('e') + .map(|(mantissa, _)| mantissa.bytes().filter(|&b| b != b'.').count()) + .ok_or_else(|| format!("Malformed float exponent in {shortest}"))?; + let scientific = format!("{:.1$e}", value, shortest_digits - 1); + let (negative, body) = match scientific.strip_prefix('-') { + Some(rest) => (true, rest), + None => (false, scientific.as_str()), + }; + let (mantissa, exponent) = body + .split_once('e') + .ok_or_else(|| format!("Malformed float exponent in {scientific}"))?; + let exponent: i32 = exponent + .parse() + .map_err(|_| format!("Malformed float exponent in {scientific}"))?; + let mut digits: String = mantissa.chars().filter(|&c| c != '.').collect(); + // A minimal representation cannot end in an insignificant zero, but drop + // one anyway: the decimal point position depends only on the exponent. + while digits.len() > 1 && digits.ends_with('0') { + digits.pop(); + } + let length = digits.len() as i32; + let decpt = exponent + 1; // Decimal point position: value = 0.digits * 10^decpt. + let mut text = String::with_capacity(digits.len() + 8); + if negative { + text.push('-'); + } + if decpt <= -4 || decpt > 16 { + // Python uses exponential notation outside that window, two-digit + // exponent minimum, and no forced ".0" in the mantissa. + text.push(digits.as_bytes()[0] as char); + if length > 1 { + text.push('.'); + text.push_str(&digits[1..]); + } + text.push('e'); + let exponent = decpt - 1; + text.push(if exponent < 0 { '-' } else { '+' }); + let magnitude = exponent.abs(); + if magnitude < 10 { + text.push('0'); + } + text.push_str(&magnitude.to_string()); + } else if decpt <= 0 { + text.push_str("0."); + for _ in 0..(-decpt) { + text.push('0'); + } + text.push_str(&digits); + } else { + let split = decpt as usize; + if split >= digits.len() { + text.push_str(&digits); + for _ in 0..(split - digits.len()) { + text.push('0'); + } + text.push_str(".0"); + } else { + text.push_str(&digits[..split]); + text.push('.'); + text.push_str(&digits[split..]); + } + } + out.extend_from_slice(text.as_bytes()); + Ok(()) +} + +fn write_string(text: &str, out: &mut Vec) { + const HEX: &[u8; 16] = b"0123456789abcdef"; + out.push(b'"'); + let bytes = text.as_bytes(); + let mut start = 0; + for (index, &byte) in bytes.iter().enumerate() { + if byte >= 0x20 && byte != b'"' && byte != b'\\' { + continue; + } + out.extend_from_slice(&bytes[start..index]); + match byte { + b'"' => out.extend_from_slice(b"\\\""), + b'\\' => out.extend_from_slice(b"\\\\"), + 0x08 => out.extend_from_slice(b"\\b"), + 0x0c => out.extend_from_slice(b"\\f"), + b'\n' => out.extend_from_slice(b"\\n"), + b'\r' => out.extend_from_slice(b"\\r"), + b'\t' => out.extend_from_slice(b"\\t"), + 0x00..=0x1f => { + out.extend_from_slice(b"\\u00"); + out.push(HEX[(byte >> 4) as usize]); + out.push(HEX[(byte & 0x0f) as usize]); + } + _ => unreachable!(), + } + start = index + 1; + } + out.extend_from_slice(&bytes[start..]); + out.push(b'"'); +} + +fn hex(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for &byte in bytes { + out.push(HEX[(byte >> 4) as usize] as char); + out.push(HEX[(byte & 0x0f) as usize] as char); + } + out +} + +const SHA256_K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +fn sha256(data: &[u8]) -> [u8; 32] { + let mut state: [u32; 8] = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, + 0x5be0cd19, + ]; + let mut blocks = data.chunks_exact(64); + for block in &mut blocks { + compress(&mut state, block.try_into().unwrap()); + } + let remainder = blocks.remainder(); + let mut tail = [0u8; 128]; + tail[..remainder.len()].copy_from_slice(remainder); + tail[remainder.len()] = 0x80; + let padded = if remainder.len() < 56 { 64 } else { 128 }; + tail[padded - 8..padded].copy_from_slice(&((data.len() as u64).wrapping_mul(8)).to_be_bytes()); + for block in tail[..padded].chunks_exact(64) { + compress(&mut state, block.try_into().unwrap()); + } + let mut digest = [0u8; 32]; + for (index, word) in state.iter().enumerate() { + digest[index * 4..index * 4 + 4].copy_from_slice(&word.to_be_bytes()); + } + digest +} + +fn compress(state: &mut [u32; 8], block: &[u8; 64]) { + let mut schedule = [0u32; 64]; + for index in 0..16 { + schedule[index] = u32::from_be_bytes(block[index * 4..index * 4 + 4].try_into().unwrap()); + } + for index in 16..64 { + let s0 = schedule[index - 15].rotate_right(7) + ^ schedule[index - 15].rotate_right(18) + ^ (schedule[index - 15] >> 3); + let s1 = schedule[index - 2].rotate_right(17) + ^ schedule[index - 2].rotate_right(19) + ^ (schedule[index - 2] >> 10); + schedule[index] = schedule[index - 16] + .wrapping_add(s0) + .wrapping_add(schedule[index - 7]) + .wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = *state; + for index in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let choose = (e & f) ^ (!e & g); + let temp1 = h + .wrapping_add(s1) + .wrapping_add(choose) + .wrapping_add(SHA256_K[index]) + .wrapping_add(schedule[index]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let majority = (a & b) ^ (a & c) ^ (b & c); + let temp2 = s0.wrapping_add(majority); + h = g; + g = f; + f = e; + e = d.wrapping_add(temp1); + d = c; + c = b; + b = a; + a = temp1.wrapping_add(temp2); + } + for (slot, value) in state.iter_mut().zip([a, b, c, d, e, f, g, h]) { + *slot = slot.wrapping_add(value); + } +} diff --git a/crates/engine/src/ledger_reward.rs b/crates/engine/src/ledger_reward.rs new file mode 100644 index 0000000..1244a49 --- /dev/null +++ b/crates/engine/src/ledger_reward.rs @@ -0,0 +1,368 @@ +//! Stateful public reward adapter, matching `arkguardrl.rewards.NativeProgressCore`. +//! The separate low-level `reward` module remains independent of this ledger. +//! +//! The three component sum is a direct CPython `math.fsum` port, so rewards are +//! bit-identical to the Python class on this host. `passed / boss_round` follows +//! Python's correctly rounded integer division while both operands stay within +//! +/-2**53, which covers every native round count; beyond that domain the two +//! f64 conversions can differ from a true rational quotient by one ulp. +use crate::identity::fingerprint; +use serde_json::{json, Value}; + +type Result = std::result::Result; +pub const REWARD_SCHEMA: &str = "arkguardrl/native-solo-progress-core/v1"; +const CORE_BONDS: &[&str] = &[ + "yanShip", + "sargonShip", + "victoriaShip", + "kjeragShip", + "lateranoShip", + "egirShip", + "siracusaShip", + "kazimierzShip", +]; + +fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value> { + v.get(key) + .ok_or_else(|| format!("Missing public field: {key}")) +} +fn integer(v: &Value) -> Option { + match v { + Value::Number(n) if !n.is_f64() => n + .as_i64() + .map(i128::from) + .or_else(|| n.as_u64().map(i128::from)), + _ => None, + } +} +fn boolean(v: &Value, key: &str) -> Result { + field(v, key)? + .as_bool() + .ok_or_else(|| format!("Missing boolean {key}")) +} +fn zero(v: &Value) -> bool { + match v { + Value::Number(n) => n.as_f64() == Some(0.0), + Value::Bool(b) => !*b, + _ => false, + } +} +fn truthy(v: &Value) -> bool { + match v { + Value::Null => false, + Value::Bool(b) => *b, + Value::Number(n) => n.as_f64() != Some(0.0), + Value::String(s) => !s.is_empty(), + Value::Array(a) => !a.is_empty(), + Value::Object(m) => !m.is_empty(), + } +} + +/// Structural validation from observation.py; no catalog or engine queries. +fn validate(state: &Value) -> Result<()> { + if state.get("schema").and_then(Value::as_str) != Some("arkguardrl/native-session-v2") { + return Err("Unsupported native observation schema".into()); + } + let game = boolean(state, "gameEnded")?; + let personal = boolean(state, "personalEnded")?; + let decision = boolean(state, "decisionRequired")?; + if state + .get("revision") + .and_then(integer) + .is_none_or(|v| v < 0) + { + return Err("Invalid native revision".into()); + } + let public = field(state, "public")?; + let own = field(state, "own")?; + if field(state, "phase")? != field(public, "phase")? + || field(state, "round")? != field(public, "round")? + { + return Err("Inconsistent native phase/round".into()); + } + let players = field(public, "players")? + .as_array() + .ok_or("Expected native solo seat")?; + if players.len() != 1 + || field(&players[0], "playerId")? != field(own, "playerId")? + || own.get("seat").and_then(integer) != Some(0) + { + return Err("Expected native solo seat".into()); + } + let alive = field(own, "alive")? + .as_bool() + .ok_or("Missing personal alive flag")?; + if game && !personal { + return Err("Game ended without personal endpoint".into()); + } + if !alive && !personal { + return Err("Personal defeat not marked".into()); + } + if personal && decision { + return Err("Decision after personal endpoint".into()); + } + if !game && state.get("outcome").is_some_and(|v| !v.is_null()) { + return Err("Final outcome before game end".into()); + } + let mut stack = vec![state]; + while let Some(v) = stack.pop() { + match v { + Value::Array(a) => stack.extend(a), + Value::Object(m) => { + for (key, value) in m { + let key = key.to_lowercase(); + if key.contains("seed") || key.contains("rng") || key.contains("hiddenbossid") { + return Err("Forbidden hidden identity in observation".into()); + } + stack.push(value); + } + } + _ => (), + } + } + Ok(()) +} + +fn core(state: &Value) -> Result { + if boolean(state, "personalEnded")? { + return Ok(0.0); + } + let bonds = field(state, "own")? + .get("bonds") + .and_then(Value::as_array) + .ok_or("Explicit public bond list required")?; + let mut layers = 0.0; + for bond in bonds { + if !bond.is_object() { + return Err("Malformed public bond".into()); + } + if bond + .get("bondId") + .and_then(Value::as_str) + .is_some_and(|id| CORE_BONDS.contains(&id)) + && bond.get("active").is_some_and(truthy) + && !bond.get("off").is_some_and(truthy) + { + let value = bond + .get("layers") + .and_then(Value::as_f64) + .ok_or("Active CORE layers must be finite and nonnegative")?; + if !value.is_finite() || value < 0.0 { + return Err("Active CORE layers must be finite and nonnegative".into()); + } + // Python max([0.0, ...]) retains its first argument on ties (including -0). + if value > layers { + layers = value; + } + } + } + Ok(0.1 * (layers / 100.0).tanh()) +} + +/// CPython 3.12 math.fsum for the three bounded finite reward components. +/// Keep separate binary64 operations and the final half-even correction. +/// Source: Python-3.12.13 Modules/mathmodule.c, math_fsum (PSF license). +pub(crate) fn fsum(values: [f64; 3]) -> f64 { + let mut p = [0.0_f64; 3]; + let mut n = 0; + for mut x in values { + let mut i = 0; + for j in 0..n { + let mut y = p[j]; + if x.abs() < y.abs() { + std::mem::swap(&mut x, &mut y); + } + let hi = x + y; + let yr = hi - x; + let lo = y - yr; + if lo != 0.0 { + p[i] = lo; + i += 1; + } + x = hi; + } + n = i; + if x != 0.0 { + p[n] = x; + n += 1; + } + } + let mut hi = 0.0; + let mut lo = 0.0; + if n > 0 { + n -= 1; + hi = p[n]; + while n > 0 { + let x = hi; + n -= 1; + let y = p[n]; + hi = x + y; + let yr = hi - x; + lo = y - yr; + if lo != 0.0 { + break; + } + } + if n > 0 && ((lo < 0.0 && p[n - 1] < 0.0) || (lo > 0.0 && p[n - 1] > 0.0)) { + let y = lo * 2.0; + let x = hi + y; + let yr = x - hi; + if y == yr { + hi = x; + } + } + } + hi +} + +#[derive(Default)] +pub struct NativeProgressCore { + last: Option, + ended: bool, + boss_round: i128, + difficulty: Value, + mode_id: String, + player_id: Value, + progress: f64, + potential: f64, +} +impl NativeProgressCore { + pub fn new() -> Self { + Self::default() + } + pub fn reset(&mut self, state: &Value) -> Result<()> { + if self.last.is_some() { + return Err("Use a fresh reward adapter per episode".into()); + } + validate(state)?; + let public = field(state, "public")?; + self.boss_round = public + .get("bossRound") + .and_then(integer) + .filter(|n| *n >= 1) + .ok_or("Positive public bossRound required")?; + self.difficulty = public.get("difficulty").cloned().unwrap_or(Value::Null); + let difficulty = self + .difficulty + .as_str() + .filter(|s| ["FUNNY", "NORMAL", "HARD", "ABYSS"].contains(s)) + .ok_or("Known native solo difficulty required")?; + self.mode_id = format!("mode_single_{}", difficulty.to_lowercase()); + self.player_id = field(field(state, "own")?, "playerId")?.clone(); + if boolean(state, "personalEnded")? { + return Err("Reset requires a live native episode".into()); + } + let (progress, _) = self.values(state)?; + let potential = core(state)?; + let last = fingerprint(state)?; + self.progress = progress; + self.potential = potential; + self.last = Some(last); + Ok(()) + } + fn values(&self, state: &Value) -> Result<(f64, bool)> { + validate(state)?; + let public = field(state, "public")?; + let own = field(state, "own")?; + if public.get("bossRound").and_then(integer) != Some(self.boss_round) + || public.get("difficulty") != Some(&self.difficulty) + || public.get("modeId").and_then(Value::as_str) != Some(self.mode_id.as_str()) + || own.get("playerId") != Some(&self.player_id) + { + return Err("Reward episode identity changed".into()); + } + let players = public + .get("players") + .and_then(Value::as_array) + .ok_or("Exactly one native non-bot solo player required")?; + if players.len() != 1 || players[0].get("isBot") != Some(&Value::Bool(false)) { + return Err("Exactly one native non-bot solo player required".into()); + } + let round = state + .get("round") + .and_then(integer) + .filter(|v| *v >= 0) + .ok_or("Nonnegative public round required")?; + let mut passed = (round - 1).max(0).min(self.boss_round - 1); + let mut won = false; + if boolean(state, "gameEnded")? { + let outcome = state + .get("outcome") + .filter(|v| v.is_object()) + .ok_or("Clean explicit native outcome required")?; + let victory = outcome.get("victory").and_then(Value::as_bool); + if !outcome.get("errors").is_some_and(zero) + || outcome.get("modeId").and_then(Value::as_str) != Some(self.mode_id.as_str()) + || outcome.get("difficulty") != Some(&self.difficulty) + || victory.is_none() + { + return Err("Clean explicit native outcome required".into()); + } + let settled = outcome + .get("players") + .and_then(Value::as_array) + .ok_or("Exactly one native player result required")?; + if settled.len() != 1 { + return Err("Exactly one native player result required".into()); + } + let player = &settled[0]; + let alive = boolean(own, "alive")?; + let pv = player.get("victory").and_then(Value::as_bool); + let rounds = player.get("roundsPassed").and_then(integer); + if player.get("playerId") != Some(&self.player_id) + || pv.is_none() + || player.get("alive") != Some(&Value::Bool(alive)) + || rounds.is_none_or(|v| v < 0) + || pv != Some(victory.unwrap() && alive) + { + return Err("Inconsistent native solo outcome".into()); + } + won = pv.unwrap(); + passed = rounds.unwrap(); + } else if boolean(state, "personalEnded")? && boolean(own, "alive")? { + return Err("Alive personal endpoint without final outcome is ambiguous".into()); + } + Ok(((passed as f64 / self.boss_round as f64).min(1.0), won)) + } + pub fn step(&mut self, before: &Value, after: &Value) -> Result { + if self.last.is_none() || self.ended || self.last.as_deref() != Some(&fingerprint(before)?) + { + return Err("Disconnected or already-ended reward episode".into()); + } + let (progress, won) = self.values(after)?; + if progress < self.progress { + return Err("Public rounds-passed progress regressed".into()); + } + let potential = core(after)?; + let terminated = boolean(after, "personalEnded")?; + let outcome = if terminated { + if won { + 1.0 + } else { + -1.0 + } + } else { + 0.0 + }; + let progress_reward = 0.5 * (progress - self.progress); + let shaping = potential - self.potential; + let reward = fsum([outcome, progress_reward, shaping]); + let last = fingerprint(after)?; + self.progress = progress; + self.potential = potential; + self.last = Some(last); + self.ended = terminated; + Ok(json!({ + "reward": reward, + "components": { + "outcome": outcome, + "progress": progress_reward, + "core_shaping": shaping, + }, + "progress": progress, + "terminated": terminated, + "victory": if terminated { json!(won) } else { Value::Null }, + "schema": REWARD_SCHEMA, + })) + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4002ffc..0c5e71f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1,5 +1,10 @@ -//! Native 0.3.3 foundations. Full match and battle execution is not implemented yet. +//! Native battle runtime and single-player round execution. pub mod battle; pub mod data; +pub mod identity; +pub mod ledger_reward; +pub mod history; +pub mod progress; pub mod deterministic; pub mod reward; +pub mod solo; diff --git a/crates/engine/src/progress.rs b/crates/engine/src/progress.rs new file mode 100644 index 0000000..de1b48c --- /dev/null +++ b/crates/engine/src/progress.rs @@ -0,0 +1,635 @@ +//! Public-observation execution receipts and per-round progress (`feedback.py`). +//! No simulator counters or queries are used. Observe the immediate command result +//! with action/reply, then each distinct automatic/final observation without them. +use crate::identity::{action_id, decision_id, fingerprint}; +use serde_json::{json, Map, Value}; +use std::{collections::BTreeMap, sync::Arc}; + +pub const EXECUTION_SCHEMA: &str = "arkguardrl/public-execution-report-v2"; +pub const PROGRESS_SCHEMA: &str = "arkguardrl/public-observed-progress-v2"; +const ERRORS: &[&str] = &[ + "NO_FUNDS", + "HAND_FULL", + "BOARD_FULL", + "BAD_TILE", + "BAD_TARGET", + "SOLD_OUT", + "MAX_LEVEL", + "WRONG_PHASE", + "NOT_YOUR_TURN", + "ALREADY", + "TEMP_NOT_EMPTY", + "ELIMINATED", + "NOT_READY", + "BAD_MSG", + "OTHER", +]; +type Result = std::result::Result; + +// JSON integer and string identities never alias, even if str(uid) is equal. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] +enum Uid { + Integer(i128), + Text(String), +} +impl Uid { + fn parse(v: &Value) -> Result { + if let Some(s) = v.as_str() { + return Ok(Self::Text(s.into())); + } + Ok(Self::Integer(integer(v, "piece UID")?)) + } + fn text(&self) -> String { + match self { + Self::Integer(n) => n.to_string(), + Self::Text(s) => s.clone(), + } + } +} +fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value> { + v.as_object() + .and_then(|m| m.get(key)) + .ok_or_else(|| format!("Missing public field: {key}")) +} +fn array<'a>(v: &'a Value, key: &str) -> Result<&'a Vec> { + field(v, key)? + .as_array() + .ok_or_else(|| format!("Expected public array: {key}")) +} +fn integer(v: &Value, name: &str) -> Result { + match v { + Value::Number(n) if !n.is_f64() => n + .as_i64() + .map(i128::from) + .or_else(|| n.as_u64().map(i128::from)), + _ => None, + } + .ok_or_else(|| format!("Expected public integer: {name}")) +} +fn nonnegative(v: &Value, name: &str) -> Result { + let n = integer(v, name)?; + u64::try_from(n).map_err(|_| format!("Missing nonnegative public cumulative counter: {name}")) +} +fn counter(state: &Value, name: &str) -> Result { + nonnegative(field(field(field(state, "own")?, "stats")?, name)?, name) +} +fn int_value(n: i128) -> Result { + if let Ok(n) = i64::try_from(n) { + Ok(json!(n)) + } else if let Ok(n) = u64::try_from(n) { + Ok(json!(n)) + } else { + Err("Public numeric delta exceeds JSON integer range".into()) + } +} +fn delta(a: &Value, b: &Value) -> Result { + if let (Ok(a), Ok(b)) = (integer(a, "delta"), integer(b, "delta")) { + return int_value(b - a); + } + let (a, b) = ( + a.as_f64().ok_or("Expected numeric public delta")?, + b.as_f64().ok_or("Expected numeric public delta")?, + ); + let n = b - a; + if !n.is_finite() { + return Err("Nonfinite public numeric delta".into()); + } + Ok(json!(n)) +} +fn add(a: u64, b: u64) -> Result { + a.checked_add(b) + .ok_or_else(|| "Public progress counter overflow".into()) +} + +// Keep insertion order: Python's owned() overwrites duplicate identities in place, +// and snapshot stringification may map distinct typed identities to the same key. +fn owned(state: &Value, equipped: bool) -> Result> { + let own = field(state, "own")?; + let mut out: Vec<(Uid, String, Value)> = Vec::new(); + for area in ["board", "hand", "temp"] { + for piece in array(own, area)? { + if piece.is_null() { + continue; + } + piece.as_object().ok_or("Expected public piece object")?; + let uid = Uid::parse(field(piece, "uid")?)?; + put_owned(&mut out, uid, area.into(), piece.clone()); + if equipped { + if let Some(items) = piece.get("items") { + for item in items.as_array().ok_or("Expected equipment array")? { + let mut row = Map::new(); + row.insert("kind".into(), json!("item")); + row.extend(item.as_object().ok_or("Expected equipment object")?.clone()); + put_owned( + &mut out, + Uid::parse(field(item, "uid")?)?, + "equipped".into(), + Value::Object(row), + ); + } + } + } + } + } + Ok(out) +} +fn put_owned(out: &mut Vec<(Uid, String, Value)>, uid: Uid, area: String, piece: Value) { + if let Some(row) = out.iter_mut().find(|r| r.0 == uid) { + *row = (uid, area, piece); + } else { + out.push((uid, area, piece)); + } +} +fn descriptor(piece: &Value, area: &str) -> Value { + let mut out = Map::new(); + for key in ["kind", "id", "uid", "row", "col", "dir"] { + if let Some(v) = piece.get(key) { + out.insert(key.into(), v.clone()); + } + } + out.insert("area".into(), json!(area)); + Value::Object(out) +} +fn lookup(rows: &[(Uid, String, Value)], uid: Option<&Value>) -> Result { + let Some(uid) = uid.filter(|v| !v.is_null()) else { + return Ok(Value::Null); + }; + let uid = Uid::parse(uid)?; + Ok(rows + .iter() + .find(|r| r.0 == uid) + .map(|r| descriptor(&r.2, &r.1)) + .unwrap_or(Value::Null)) +} +fn index<'a>(rows: &'a [Value], v: &Value) -> Result> { + let i = integer(v, "action index")?; + Ok(usize::try_from(i) + .ok() + .and_then(|i| rows.get(i)) + .filter(|v| !v.is_null())) +} +fn description(before: &Value, action: &Value) -> Result<(String, Value, Value, Value)> { + let tag = field(action, "t")? + .as_str() + .ok_or("Expected action type string")?; + let kind: String = tag.chars().skip(2).collect(); + let rows = owned(before, true)?; + // Python's get(key, default) only falls back when the key is absent. + let uid = if action.get("uid").is_some() { + action.get("uid") + } else { + action.get("itemUid") + }; + let mut source = lookup(&rows, uid)?; + let mut target = lookup(&rows, action.get("targetUid"))?; + let replaced = lookup(&rows, action.get("replaceUid"))?; + let own = field(before, "own")?; + let shop = field(own, "shop")?; + if matches!(kind.as_str(), "buy" | "reward" | "choice") { + let empty = Vec::new(); + let (slots, idx, area) = match kind.as_str() { + "buy" => (array(shop, "slots")?, field(action, "slot")?, "shop"), + "reward" => ( + match shop.get("rewardOffer").filter(|v| !v.is_null()) { + Some(o) => o + .get("slots") + .map(|v| v.as_array().ok_or("Expected reward slots")) + .transpose()? + .unwrap_or(&empty), + None => &empty, + }, + field(action, "idx")?, + "offer", + ), + _ => { + let choice = if field(before, "phase")? == "PREP" { + own.get("personalChoice") + } else { + field(before, "public")?.get("sp") + }; + ( + match choice.filter(|v| !v.is_null()) { + Some(c) => c + .get("cards") + .map(|v| v.as_array().ok_or("Expected choice cards")) + .transpose()? + .unwrap_or(&empty), + None => &empty, + }, + field(action, "idx")?, + "offer", + ) + } + }; + source = match index(slots, idx)?.filter(|s| s.as_object().is_none_or(|m| !m.is_empty())) { + Some(s) => { + json!({"kind":field(s,"kind")?,"id":s.get("id").unwrap_or(&Value::Null),"area":area}) + } + None => Value::Null, + }; + } else if kind == "band" { + source = json!({"kind":"band","id":field(action,"bandId")?,"area":"offer"}); + } + if kind == "move" { + let empty = json!({}); + let to = action.get("to").unwrap_or(&empty); + match to.get("area").and_then(Value::as_str) { + Some("board") => { + let (row, col) = ( + to.get("row").unwrap_or(&Value::Null), + to.get("col").unwrap_or(&Value::Null), + ); + target = array(own, "board")? + .iter() + .find(|p| { + p.get("row").unwrap_or(&Value::Null) == row + && p.get("col").unwrap_or(&Value::Null) == col + }) + .map(|p| descriptor(p, "board")) + .unwrap_or(Value::Null); + } + Some("hand") => { + target = index(array(own, "hand")?, to.get("idx").unwrap_or(&Value::Null))? + .map(|p| descriptor(p, "hand")) + .unwrap_or(Value::Null); + } + _ => {} + } + } else if ![ + "infoReady", + "band", + "choice", + "buy", + "reward", + "refresh", + "freeze", + "levelUp", + "sell", + "equip", + "art", + "destroy", + "ready", + ] + .contains(&kind.as_str()) + { + return Err("Unknown native action feature identity".into()); + } + Ok((kind, source, target, replaced)) +} + +/// A v2 receipt for the immediate reply, before automatic progression. +pub fn execution_report( + before: &Value, + action: &Value, + after: &Value, + reply: &Value, +) -> Result { + execution_report_inner(before, action, after, reply, None) +} + +fn execution_report_inner( + before: &Value, + action: &Value, + after: &Value, + reply: &Value, + before_id: Option<&str>, +) -> Result { + let accepted = field(reply, "accepted")? + .as_bool() + .ok_or("Real native acceptance/result required")?; + let result = field(reply, "result")?; + result + .as_object() + .ok_or("Real native acceptance/result required")?; + if accepted != (result.get("ok") == Some(&Value::Bool(true))) { + return Err("Native result/acceptance disagree".into()); + } + let error = result.get("error").unwrap_or(&Value::Null); + if error == "INTERNAL" { + return Err("Native INTERNAL is a technical failure, not policy rejection".into()); + } + if !accepted && error.as_str().is_none_or(|s| s.is_empty()) { + return Err("Native rejection omitted its error code".into()); + } + if accepted && truthy(error) { + return Err("Accepted native result contains an error".into()); + } + let (kind, source, target, replaced) = description(before, action)?; + let a = field(before, "own")?; + let b = field(after, "own")?; + let mut changes = Map::new(); + changes.insert( + "funds_delta".into(), + delta(field(a, "funds")?, field(b, "funds")?)?, + ); + for (name, key) in [ + ("spent_delta", "gold"), + ("refreshes_delta", "refreshes"), + ("merges_delta", "merges"), + ] { + changes.insert( + name.into(), + int_value(i128::from(counter(after, key)?) - i128::from(counter(before, key)?))?, + ); + } + changes.insert( + "level_delta".into(), + delta( + field(field(a, "shop")?, "level")?, + field(field(b, "shop")?, "level")?, + )?, + ); + changes.insert( + "deploy_delta".into(), + delta(field(a, "deployCount")?, field(b, "deployCount")?)?, + ); + for (name, key, null) in [ + ("hand_free_delta", "hand", true), + ("temp_used_delta", "temp", false), + ] { + let count = |v: &Value| -> Result { + Ok(array(v, key)? + .iter() + .filter(|v| v.is_null() == null) + .count() as i128) + }; + changes.insert(name.into(), int_value(count(b)? - count(a)?)?); + } + let layers = |own: &Value| -> Result> { + let mut out = BTreeMap::new(); + for row in array(own, "bonds")? { + out.insert( + field(row, "bondId")? + .as_str() + .ok_or("Expected bond ID")? + .into(), + row.get("layers").cloned().unwrap_or(json!(0)), + ); + } + Ok(out) + }; + let la = layers(a)?; + let lb = layers(b)?; + let mut bonds = Map::new(); + let mut keys: Vec<_> = la.keys().chain(lb.keys()).collect(); + keys.sort(); + keys.dedup(); + for key in keys { + let av = la.get(key).cloned().unwrap_or(json!(0)); + let bv = lb.get(key).cloned().unwrap_or(json!(0)); + let d = delta(&av, &bv)?; + if d.as_f64() != Some(0.) { + bonds.insert(key.clone(), d); + } + } + let class = if accepted { + Value::Null + } else { + json!(if ERRORS.contains(&error.as_str().unwrap()) { + error.as_str().unwrap() + } else { + "OTHER" + }) + }; + Ok( + json!({"schema":EXECUTION_SCHEMA,"action_id":action_id(action)?,"action_type":kind, + "decision_id":decision_id(before)?,"before_id":match before_id { + Some(id) => id.to_owned(), + None => fingerprint(before)?, + },"immediate_after_id":fingerprint(after)?, + "round":field(before,"round")?,"phase":field(before,"phase")?,"accepted":accepted, + "error":if accepted {&Value::Null} else {error},"error_class":class,"source":source,"target":target, + "changes":changes,"bond_layer_deltas":bonds,"intent":action,"replaced":replaced}), + ) +} +fn truthy(v: &Value) -> bool { + match v { + Value::Null => false, + Value::Bool(v) => *v, + Value::Number(n) => n.as_f64() != Some(0.), + Value::String(s) => !s.is_empty(), + Value::Array(a) => !a.is_empty(), + Value::Object(m) => !m.is_empty(), + } +} + +/// One ordered stream of trusted, internally owned public JSON snapshots. +#[derive(Clone)] +pub struct PublicProgress { + stream_id: String, + state: Option>, + observation_id: Option, + sequence: u64, + spent: u64, + refreshes: u64, + direct_gains: u64, + spent_known: bool, + refreshes_known: bool, + gains_complete: bool, + exposures: BTreeMap, + last_execution: Option>, +} +impl PublicProgress { + /// Internal constructor: callers supply Python uuid4().hex on every reset. + /// Lowercase hex is an internal constraint, not a public history-schema rule. + pub fn new(stream_id: String) -> Result { + if stream_id.len() != 32 + || !stream_id + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + { + return Err("Expected a lowercase 32-hex stream ID".into()); + } + Ok(Self { + stream_id, + state: None, + observation_id: None, + sequence: 0, + spent: 0, + refreshes: 0, + direct_gains: 0, + spent_known: false, + refreshes_known: false, + gains_complete: false, + exposures: BTreeMap::new(), + last_execution: None, + }) + } + /// Errors leave the entire ledger unchanged, including observation binding. + pub fn observe( + &mut self, + state: Arc, + action: Option<&Value>, + reply: Option<&Value>, + ) -> Result> { + let mut next = self.clone(); + let receipt = next.observe_inner(state, action, reply)?; + *self = next; + Ok(receipt) + } + fn observe_inner( + &mut self, + state: Arc, + action: Option<&Value>, + reply: Option<&Value>, + ) -> Result> { + let sequence = add(self.sequence, 1)?; + let mut receipt = match action { + Some(action) => Some(execution_report_inner( + self.state + .as_deref() + .ok_or("Execution observation needs a preceding state and native reply")?, + action, + &state, + reply.ok_or("Execution observation needs a preceding state and native reply")?, + // The retained Arc binds this identity to the immutable preceding state. + self.observation_id.as_deref(), + )?), + None => { + if reply.is_some() { + return Err("Reply without an executed intent".into()); + } + None + } + }; + if let Some(r) = receipt.as_mut() { + r["stream_id"] = json!(self.stream_id); + r["sequence"] = json!(sequence); + } + // feedback.py compares these as ordered integers and does not re-run schema checks. + let round = integer(field(&state, "round")?, "round")?; + let revision = integer(field(&state, "revision")?, "revision")?; + let gold = counter(&state, "gold")?; + let refreshes = counter(&state, "refreshes")?; + let mut dg = 0; + let mut dr = 0; + let mut adjacent = false; + let changed_round = match self.state.as_deref() { + Some(before) => { + if revision <= integer(field(before, "revision")?, "revision")? { + return Err( + "Public progress requires strictly ordered native observations".into(), + ); + } + dg = gold + .checked_sub(counter(before, "gold")?) + .ok_or("Public cumulative counters regressed")?; + dr = refreshes + .checked_sub(counter(before, "refreshes")?) + .ok_or("Public cumulative counters regressed")?; + let old_round = integer(field(before, "round")?, "round")?; + if round < old_round { + return Err("Cross-episode observation requires a new PublicProgress".into()); + } + adjacent = old_round.checked_add(1) == Some(round); + round != old_round + } + None => true, + }; + if changed_round { + self.spent = 0; + self.refreshes = 0; + self.direct_gains = 0; + self.spent_known = gold == 0 || adjacent && dg == 0; + self.refreshes_known = refreshes == 0 || adjacent && dr == 0; + self.gains_complete = adjacent; + self.exposures.clear(); + } else { + self.spent = add(self.spent, dg)?; + self.refreshes = add(self.refreshes, dr)?; + } + for (uid, _, piece) in owned(&state, false)? { + if field(&piece, "kind")? == "chess" { + self.exposures.entry(uid).or_insert(( + 0, + if changed_round { + self.refreshes_known + } else { + self.state.is_some() + }, + )); + } + } + if let Some(r) = receipt.as_ref() { + self.last_execution = Some(Arc::new(r.clone())); + if r["accepted"] == true && !changed_round { + if r["action_type"] == "refresh" { + for (uid, area, piece) in owned(self.state.as_deref().unwrap(), false)? { + if field(&piece, "kind")? == "chess" + && matches!(area.as_str(), "board" | "hand") + { + let exposure = self.exposures.entry(uid).or_insert((0, false)); + exposure.0 = add(exposure.0, 1)?; + } + } + } + if matches!(r["action_type"].as_str(), Some("buy" | "reward")) + && r["source"]["kind"] == "chess" + { + self.direct_gains = add(self.direct_gains, 1)?; + } + } + } + if self.exposures.len() > 4096 { + return Err("Public per-round progress identity capacity exceeded".into()); + } + self.observation_id = Some(match receipt.as_ref() { + Some(report) => report["immediate_after_id"] + .as_str() + .ok_or("Missing immediate observation identity")? + .to_owned(), + None => fingerprint(&state)?, + }); + self.state = Some(state); + self.sequence = sequence; + Ok(receipt) + } + pub fn snapshot(&self, state: &Value) -> Result { + let observation_id = match self.state.as_deref() { + Some(owned) if std::ptr::eq(owned, state) => self + .observation_id + .clone() + .ok_or("Progress is not bound to this exact public observation")?, + _ => fingerprint(state)?, + }; + if self.observation_id.as_deref() != Some(&observation_id) { + return Err("Progress is not bound to this exact public observation".into()); + } + let mut pieces = Map::new(); + for (uid, _, piece) in owned(state, false)? { + if field(&piece, "kind")? == "chess" { + let (count, complete) = self.exposures.get(&uid).copied().unwrap_or((0, false)); + pieces.insert( + uid.text(), + json!({"visible_pre_refreshes":count,"history_complete":complete}), + ); + } + } + Ok( + json!({"schema":PROGRESS_SCHEMA,"observation_id":observation_id,"stream_id":self.stream_id,"sequence":self.sequence, + "round":field(state,"round")?,"spent":self.spent,"spent_known":self.spent_known,"refreshes":self.refreshes, + "refreshes_known":self.refreshes_known,"direct_chess_gains":self.direct_gains,"direct_gains_complete":self.gains_complete, + "pieces":pieces,"last_execution":self.last_execution.as_deref()}), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cached_snapshot_rejects_a_changed_copy() { + let mut state = Arc::new(json!({ + "round": 1, "revision": 0, + "own": {"stats": {"gold": 0, "refreshes": 0}, "board": [], "hand": [], "temp": []}, + })); + let original = state.clone(); + let mut progress = PublicProgress::new("0".repeat(32)).unwrap(); + progress.observe(state.clone(), None, None).unwrap(); + let expected = progress.snapshot(&original).unwrap(); + Arc::make_mut(&mut state)["own"]["funds"] = json!(10); + assert!(progress.snapshot(&state).is_err()); + assert_eq!(progress.snapshot(&original).unwrap(), expected); + } +} diff --git a/crates/engine/src/reward.rs b/crates/engine/src/reward.rs index 76dcf09..6e19b4b 100644 --- a/crates/engine/src/reward.rs +++ b/crates/engine/src/reward.rs @@ -156,81 +156,3 @@ impl ProgressReward { Ok(components) } } - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn progress_and_terminal_potential_telescope() { - let bonds = [Bond { - id: "yanShip", - active: true, - off: false, - layers: 50.0, - }]; - let initial = Progress { - rounds_passed: 0, - boss_round: 13, - outcome: Outcome::Live, - bonds: &[], - }; - let mut reward = ProgressReward::new(&initial).unwrap(); - let a = reward - .step(&Progress { - rounds_passed: 6, - bonds: &bonds, - ..initial - }) - .unwrap(); - let b = reward - .step(&Progress { - rounds_passed: 13, - outcome: Outcome::Victory, - bonds: &bonds, - ..initial - }) - .unwrap(); - assert_eq!(a.core_shaping, -b.core_shaping); - assert_eq!(a.total() + b.total(), 1.5); - assert!(reward.step(&initial).is_err()); - } - - #[test] - fn inactive_layers_and_live_truncation_do_not_create_rewards() { - let bonds = [Bond { - id: "yanShip", - active: true, - off: true, - layers: f64::NAN, - }]; - let live = Progress { - rounds_passed: 0, - boss_round: 13, - outcome: Outcome::Live, - bonds: &bonds, - }; - let mut reward = ProgressReward::new(&live).unwrap(); - assert_eq!(reward.step(&live).unwrap().total(), 0.0); - let bad = [Bond { - off: false, - ..bonds[0] - }]; - assert!(reward - .step(&Progress { - bonds: &bad, - ..live - }) - .is_err()); - assert_eq!(reward.step(&live).unwrap().total(), 0.0); - assert_eq!( - reward - .step(&Progress { - outcome: Outcome::Loss, - ..live - }) - .unwrap() - .total(), - -1.0 - ); - } -} diff --git a/crates/engine/src/solo.rs b/crates/engine/src/solo.rs new file mode 100644 index 0000000..57bd625 --- /dev/null +++ b/crates/engine/src/solo.rs @@ -0,0 +1,870 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Single-player round execution and settlement. Wave generation and preparation +//! supply validated round plans and lineups. This is an internal match API. +use crate::{ + battle::{ + grid::{Grid, Rect}, + operators::Placement, + runtime::{ + BossConfig, BossKind, BossOvertime, BossRoundConfig, BossRoundOutcome, Field, + FieldResult, Limits, + }, + waves::Template, + }, + data::Catalog, + deterministic::rng::derive_seed, +}; +use serde_json::{json, Value}; +use std::{collections::BTreeSet, sync::Arc}; + +pub mod draft; +mod map; +pub mod mode; +mod player; +use map::DeployMap; +pub mod preparation; +pub mod session; + +const MAX_ROUNDS: usize = 64; +const MAX_LINEUP: usize = 36; +// PlayerState funds use JS integers. Retain exact integer arithmetic at the API. +const MAX_FUNDS: u64 = (1_u64 << 53) - 1; + +pub struct Boss { + pub max_hp: f64, + pub overtime: Option, +} +pub enum RoundKind { + Normal, + FinalAssault(Boss), + HiddenCore(Boss), +} +pub struct RoundPlan { + pub kind: RoundKind, + pub wave: Template, + pub time_limit: f64, + pub income: u64, + pub deploy_cap: usize, +} +/// Eligibility is fixed by mode/difficulty. The preparation owner supplies the +/// active layer sum at Ready, before the Final Assault starts. +pub struct HiddenRule { + pub layer_threshold: f64, + pub min_lp_exclusive: f64, +} +pub struct Config { + pub initial_lp: f64, + pub lp_cap_per_round: u64, + pub keep_funds: bool, + pub hidden: Option, +} +pub struct Operator { + pub key: String, + pub placement: Placement, + pub skill_index: Option, + pub items: Vec, +} +pub struct PreparedRound { + pub operators: Vec, + pub active_layers: f64, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Phase { + Prep, + Draft, + Combat, + Result, + Faulted, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EndReason { + Eliminated, + Defeat, + Victory, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Outcome { + pub victory: bool, + pub hidden_reached: bool, + pub hidden_cleared: bool, + pub reason: EndReason, +} +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Stats { + pub kills: u64, + pub credited_kills: u64, + pub leaks: u64, + pub lp_lost: f64, + pub perfect_rounds: u64, + pub funds_gained: u64, + pub funds_spent: u64, + pub damage: f64, + pub healing: f64, + pub boss_damage: f64, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Snapshot { + pub phase: Phase, + pub round: u32, + pub rounds_passed: u32, + pub lp: f64, + pub funds: u64, + pub pending_funds: u64, + pub stats: Stats, + pub outcome: Option, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Advance { + pub ticks: usize, + pub budget_exhausted: bool, + pub phase: Phase, +} +enum State { + Prep, + Combat { + field: Box, + active_layers: f64, + }, + Result(Outcome), + Faulted(String), +} +pub struct Runner { + data: Arc, + stage: Value, + seed: u32, + config: Config, + plans: Vec>, + boss_index: usize, + index: usize, + state: State, + player: player::Player, + rounds_passed: u32, + limits: Limits, + last_result: Option, + prep: Option, + map: crate::battle::runtime::MapConfig, + draft: Option, + core: Option, +} +impl Runner { + /// Configure an already selected core; offer generation belongs to the selection flow. + pub fn configure_core(&mut self, id: &str) -> Result<(), String> { + self.healthy()?; + if self.index != 0 || self.phase() != Phase::Prep || self.core.is_some() { + return Err("Core must be selected once before the first battle".into()); + } + Field::validate_core(&self.data, id)?; + let hp = self.data.table("bands").unwrap()[id]["totalHp"] + .as_f64() + .filter(|n| n.is_finite() && *n > 0.) + .ok_or("Invalid core life points")?; + self.player.lp = hp; + if let Some(prep) = &mut self.prep { prep.sciurus = id == "band_sciurus"; } + self.core = Some(id.into()); + Ok(()) + } + + /// Map effects persist across rounds and may change only during preparation. + pub fn configure_map(&mut self, map: crate::battle::runtime::MapConfig) -> Result<(), String> { + self.healthy()?; + if self.phase() != Phase::Prep { + return Err("Map configuration requires preparation".into()); + } + let map = map.resolved(&self.data)?; + let boss = !matches!( + self.plans[self.index].as_ref().unwrap().kind, + RoundKind::Normal + ); + let grid = DeployMap::new(&self.stage, &map, boss)?; + if let Some(prep) = &self.prep { + let mut prep = prep.clone(); + let mut player = self.player.clone(); + match prep.change_map(grid, &mut player) { + Ok(()) => { + self.prep = Some(prep); + self.player = player; + } + Err(e) => return Err(e.to_string()), + } + } + self.map = map; + Ok(()) + } + + pub fn new( + data: Arc, + stage: Value, + seed: u32, + config: Config, + plans: Vec, + limits: Limits, + ) -> Result { + Self::build(data, stage, seed, config, plans, limits, None) + } + pub fn new_with_preparation( + data: Arc, + stage: Value, + seed: u32, + config: Config, + plans: Vec, + limits: Limits, + preparation: preparation::Config, + ) -> Result { + Self::build(data, stage, seed, config, plans, limits, Some(preparation)) + } + fn build( + data: Arc, + stage: Value, + seed: u32, + config: Config, + plans: Vec, + limits: Limits, + preparation: Option, + ) -> Result { + if plans.is_empty() + || plans.len() > MAX_ROUNDS + || !config.initial_lp.is_finite() + || config.initial_lp <= 0. + || config.lp_cap_per_round == 0 + || config.lp_cap_per_round > MAX_FUNDS + { + return Err("Invalid single-player round configuration".into()); + } + Grid::new(&stage, Rect::FULL)?; + let boss_index = plans + .iter() + .position(|p| matches!(p.kind, RoundKind::FinalAssault(_))) + .ok_or("Single-player run requires a Final Assault")?; + let hidden = plans.len() == boss_index + 2; + if plans.len() != boss_index + 1 && !hidden + || config.hidden.is_some() != hidden + || plans[..boss_index] + .iter() + .any(|p| !matches!(p.kind, RoundKind::Normal)) + || hidden && !matches!(plans[boss_index + 1].kind, RoundKind::HiddenCore(_)) + { + return Err( + "Expected normal rounds, one Final Assault, then an optional Hidden Core".into(), + ); + } + if let Some(rule) = &config.hidden { + if !rule.layer_threshold.is_finite() + || rule.layer_threshold < 0. + || !rule.min_lp_exclusive.is_finite() + || rule.min_lp_exclusive < 0. + { + return Err("Invalid Hidden Core eligibility".into()); + } + } + for plan in &plans { + if plan.time_limit.is_nan() + || plan.time_limit <= 0. + || plan.income > MAX_FUNDS + || plan.deploy_cap == 0 + || plan.deploy_cap > MAX_LINEUP + { + return Err("Invalid single-player round plan".into()); + } + if let RoundKind::FinalAssault(boss) | RoundKind::HiddenCore(boss) = &plan.kind { + if !boss.max_hp.is_finite() || boss.max_hp < 1. { + return Err("Invalid single-player Boss pool".into()); + } + // Validate the same settings as the public battle entry, without + // constructing a second field or duplicating its LP policy. + super::battle::runtime::validate_boss_round(BossRoundConfig { + life_points: config.initial_lp, + overtime: boss.overtime, + })?; + } + } + let lp = config.initial_lp; + let mut run = Self { + data, + stage, + seed: if seed == 0 { 1 } else { seed }, + config, + plans: plans.into_iter().map(Some).collect(), + boss_index, + index: 0, + state: State::Prep, + player: player::Player { + lp, + ..Default::default() + }, + rounds_passed: 0, + limits, + last_result: None, + prep: None, + map: Default::default(), + draft: None, + core: None, + }; + if let Some(config) = preparation { + let plan = run.plans[0].as_ref().unwrap(); + let boss = !matches!(plan.kind, RoundKind::Normal); + run.prep = Some(preparation::Preparation::new( + Arc::clone(&run.data), + run.seed, + config, + DeployMap::new(&run.stage, &run.map, boss)?, + boss, + plan.deploy_cap, + &mut run.player, + )?); + } + run.start_prep()?; + Ok(run) + } + pub fn phase(&self) -> Phase { + match self.state { + State::Prep if self.draft.as_ref().is_some_and(|d| d.pending.is_some()) => Phase::Draft, + State::Prep => Phase::Prep, + State::Combat { .. } => Phase::Combat, + State::Result(_) => Phase::Result, + State::Faulted(_) => Phase::Faulted, + } + } + fn healthy(&self) -> Result<(), String> { + if let State::Faulted(error) = &self.state { + Err(error.clone()) + } else { + Ok(()) + } + } + pub fn snapshot(&self) -> Result { + self.healthy()?; + let mut lp = self.player.lp; + let mut stats = self.player.stats; + if let State::Combat { field, .. } = &self.state { + if let Some(round) = field.boss_round_state()? { + if round.leak_loss > 0. || round.skill_loss > 0. || round.overtime_loss > 0. { + lp = round.lp.round(); + } + stats.boss_damage = field.match_boss_damage()?; + } + } + Ok(Snapshot { + phase: self.phase(), + round: self.index as u32 + 1, + rounds_passed: self.rounds_passed, + lp, + funds: self.player.funds, + pending_funds: self.player.pending, + stats, + outcome: if let State::Result(outcome) = self.state { + Some(outcome) + } else { + None + }, + }) + } + /// Owned internal diagnostics. Preparation inventories and policy + /// observations are assembled by their respective owners. + pub fn report(&self) -> Result { + let s = self.snapshot()?; + let mut report = json!({"phase":match s.phase {Phase::Prep=>"prep",Phase::Draft=>"draft",Phase::Combat=>"combat",Phase::Result=>"result",Phase::Faulted=>"faulted"}, + "round":s.round,"roundsPassed":s.rounds_passed,"lp":s.lp,"funds":s.funds,"pendingFunds":s.pending_funds, + "stats":{"kills":s.stats.kills,"creditedKills":s.stats.credited_kills,"leaks":s.stats.leaks,"lpLost":s.stats.lp_lost, + "perfectRounds":s.stats.perfect_rounds,"fundsGained":s.stats.funds_gained,"fundsSpent":s.stats.funds_spent, + "damage":s.stats.damage,"healing":s.stats.healing,"bossDamage":s.stats.boss_damage}, + "outcome":s.outcome.map(|o|json!({"victory":o.victory,"hiddenReached":o.hidden_reached,"hiddenCleared":o.hidden_cleared, + "reason":match o.reason {EndReason::Eliminated=>"eliminated",EndReason::Defeat=>"defeat",EndReason::Victory=>"victory"}}))}); + if let Some(prep) = &self.prep { + report["preparation"] = prep.report(&self.player); + } + if let Some(id) = &self.core { + report["core"] = json!(id); + } + if let Some(draft) = &self.draft { + report["draft"] = draft.pending.clone().unwrap_or(Value::Null); + report["draftRng"] = json!(draft.rng.state()); + } + Ok(report) + } + /// The preparation owner charges completed actions once through this entry. + pub fn spend(&mut self, amount: u64) -> Result<(), String> { + self.healthy()?; + if self.phase() != Phase::Prep || amount > self.player.funds { + return Err("Preparation payment rejected".into()); + } + self.player.spend(amount) + } + pub fn enable_preparation(&mut self, config: preparation::Config) -> Result<(), String> { + self.healthy()?; + if self.index != 0 || self.phase() != Phase::Prep || self.prep.is_some() { + return Err("Preparation must be enabled once before the first battle".into()); + } + if config.effects.is_some() { + return Err( + "Preparation effects require new_with_preparation before initial income".into(), + ); + } + let mut player = self.player.clone(); + let plan = self.plans[0].as_ref().unwrap(); + let boss = !matches!(plan.kind, RoundKind::Normal); + let grid = DeployMap::new(&self.stage, &self.map, boss)?; + let mut prep = preparation::Preparation::new( + Arc::clone(&self.data), + self.seed, + config, + grid.clone(), + boss, + plan.deploy_cap, + &mut player, + )?; + prep.begin_round(1, grid, boss, plan.deploy_cap, &mut player, false) + .map_err(|e| e.to_string())?; + self.prep = Some(prep); + self.player = player; + Ok(()) + } + pub fn prep_action(&mut self, action: preparation::Action) -> Result<(), String> { + self.healthy()?; + if let preparation::Action::Draft(index) = action { + return self.pick_draft(index); + } + if self.phase() != Phase::Prep { + return Err("WRONG_PHASE".into()); + } + // Immutable definitions and the deployment map are shared by Arc. The + // bounded mutable preparation draft commits with its wallet and RNG. + let mut next = self + .prep + .as_ref() + .ok_or("Preparation is not enabled")? + .clone(); + let mut player = self.player.clone(); + match next.act(action, &mut player) { + Ok(()) => { + self.prep = Some(next); + self.player = player; + Ok(()) + } + Err(error @ (preparation::Error::Capacity | preparation::Error::Content(_))) => { + self.fail(error.to_string()) + } + Err(error) => Err(error.to_string()), + } + } + pub fn ready_owned(&mut self, active_layers: f64) -> Result<(), String> { + self.healthy()?; + if self.phase() != Phase::Prep { + return Err("WRONG_PHASE".into()); + } + if self + .prep + .as_ref() + .ok_or("Preparation is not enabled")? + .has_effects() + { + return Err("Preparation effects require ready_current".into()); + } + self.ready_preparation(Some(active_layers)) + } + /// Derive Hidden Core eligibility from the owned preparation state. + pub fn ready_current(&mut self) -> Result<(), String> { + self.ready_preparation(None) + } + fn ready_preparation(&mut self, layers: Option) -> Result<(), String> { + self.healthy()?; + if self.phase() != Phase::Prep { + return Err("WRONG_PHASE".into()); + } + let mut next = self + .prep + .as_ref() + .ok_or("Preparation is not enabled")? + .clone(); + next.check_ready()?; + let mut player = self.player.clone(); + if let Err(error) = next.meta_end(&mut player) { + return self.fail(error.to_string()); + } + let prepared = next.prepared(layers.unwrap_or_else(|| next.active_layers())); + let mut map = self.map.clone(); + next.battle_map(&mut map); + self.ready_inner_with_map(prepared, map, next.battle_choices(), next.battle_bonds())?; + if !self.config.keep_funds { + player.funds = 0; + } + next.end_prep(); + self.prep = Some(next); + self.player = player; + Ok(()) + } + /// Board positions stay in preparation coordinates, rows 9–12, cols 2–10. + /// Readiness consumes the plan only after all lineup validation succeeds. + pub fn ready(&mut self, prepared: PreparedRound) -> Result<(), String> { + if self.prep.is_some() { + return Err("Owned preparation requires ready_owned".into()); + } + self.ready_inner(prepared) + } + fn ready_inner(&mut self, prepared: PreparedRound) -> Result<(), String> { + self.ready_inner_with_map(prepared, self.map.clone(), vec![], vec![]) + } + fn ready_inner_with_map( + &mut self, + prepared: PreparedRound, + map: crate::battle::runtime::MapConfig, + choices: Vec, + bonds: Vec, + ) -> Result<(), String> { + self.healthy()?; + if self.phase() != Phase::Prep { + return Err("Ready requires preparation".into()); + } + let plan = self.plans[self.index].as_ref().unwrap(); + if !prepared.active_layers.is_finite() + || prepared.active_layers < 0. + || prepared.operators.len() + > self + .prep + .as_ref() + .map_or(plan.deploy_cap, preparation::Preparation::deploy_cap) + { + return Err("Invalid prepared lineup or active layers".into()); + } + let boss = !matches!(plan.kind, RoundKind::Normal); + let grid = DeployMap::new(&self.stage, &map, boss)?; + let tokens = self + .prep + .as_ref() + .map(|prep| prep.prepared_tokens()) + .unwrap_or_default(); + let mut identities = BTreeSet::new(); + let mut cells = BTreeSet::new(); + for op in &prepared.operators { + let home = op.placement.home; + if op.placement.uid == 0 + || !identities.insert(op.placement.uid) + || !cells.insert(home) + || !(9..=12).contains(&home[0]) + || !(2..=10).contains(&home[1]) + { + return Err("Invalid or duplicate prepared placement".into()); + } + crate::battle::operators::Definition::load_with_loadout( + &self.data, + &op.key, + op.skill_index, + &op.items, + )?; + let record = &self.data.table("chess").unwrap()[&op.key]; + if !grid.can_place(record, home) { + return Err("Prepared operator cannot stand on its deployment tile".into()); + } + } + let mut plan = self.plans[self.index].take().unwrap(); + if let Some(prep) = &self.prep { + if let Err(error) = prep.append_bounties(&mut plan.wave, self.index + 1, boss) { + return self.fail(error); + } + } + let make = || { + let mut field = match plan.kind { + RoundKind::Normal => Field::new( + Arc::clone(&self.data), + &self.stage, + plan.wave, + derive_seed(self.seed, &format!("n:{}:0", self.index + 1)), + plan.time_limit, + self.limits, + )?, + RoundKind::FinalAssault(boss) | RoundKind::HiddenCore(boss) => { + let hidden = self.index > self.boss_index; + let mut field = Field::new_boss( + Arc::clone(&self.data), + &self.stage, + plan.wave, + derive_seed(self.seed, &format!("b1:{}", self.index + 1)), + plan.time_limit, + self.limits, + BossConfig { + kind: if hidden { + BossKind::HiddenCore + } else { + BossKind::FinalAssault + }, + pool: crate::battle::health::Pool { + hp: boss.max_hp, + max_hp: boss.max_hp, + }, + }, + )?; + field.configure_boss_round(BossRoundConfig { + life_points: self.player.team_lp.unwrap_or(self.player.lp), + overtime: boss.overtime, + })?; + field.inherit_boss_damage(self.player.stats.boss_damage)?; + field + } + }; + let follow_wind = + self.prep.is_some() && self.map.cold_wind.is_none() && map.cold_wind.is_some(); + field.configure_map(map)?; + field.configure_choices(&choices)?; + field.configure_bonds(&bonds)?; + if let Some(id) = &self.core { + field.configure_core(id)?; + } + if follow_wind { + field.follow_cold_wind_layers(); + } + field.configure_round_gained_chess( + self.prep + .as_ref() + .map_or(0, preparation::Preparation::gained_chess), + )?; + // Preserve board reading order for unit identities and update order. + // Owners can follow their tokens, so bind them after registration. + let mut lineup = prepared + .operators + .iter() + .enumerate() + .map(|(i, op)| (op.placement.home, false, i)) + .chain( + tokens + .iter() + .enumerate() + .map(|(i, token)| (token.placement.home, true, i)), + ) + .collect::>(); + lineup.sort_by_key(|(home, _, _)| (-home[0], home[1])); + let mut bindings = Vec::new(); + for (_, is_token, index) in lineup { + if is_token { + let token = &tokens[index]; + let owner = prepared + .operators + .iter() + .find(|op| op.placement.uid == token.owner_uid) + .ok_or("Prepared summon owner is missing")?; + let mut placement = crate::battle::operators::Placement { + uid: token.placement.uid, + home: token.placement.home, + direction: token.placement.direction, + }; + if boss { + placement.home[0] -= 7; + } + let id = field.add_prepared_token(&token.key, placement, &owner.key)?; + bindings.push((id, token.owner_uid)); + } else { + let op = &prepared.operators[index]; + let mut placement = crate::battle::operators::Placement { + uid: op.placement.uid, + home: op.placement.home, + direction: op.placement.direction, + }; + if boss { + placement.home[0] -= 7; + } + let id = field.add_operator_with_loadout( + &op.key, + placement, + op.skill_index, + &op.items, + )?; + if self.prep.is_some() && self.data.table("chess").unwrap()[&op.key]["diyProto"] != true { + field.configure_operator_cultivation(id, 3)?; + } + } + } + for (token, owner) in bindings { + field.bind_prepared_token(token, owner)?; + } + Ok::<_, String>(field) + }; + match make() { + Ok(field) => { + if !self.config.keep_funds { + self.player.funds = 0; + } + self.state = State::Combat { + field: Box::new(field), + active_layers: prepared.active_layers, + }; + Ok(()) + } + Err(error) => self.fail(error), + } + } + /// Stops at the next preparation or result. A tick budget never settles an + /// unfinished field and never consumes the next round's preparation. + pub fn advance(&mut self, budget: usize) -> Result { + self.healthy()?; + let State::Combat { + field, + active_layers, + } = &mut self.state + else { + return Ok(Advance { + ticks: 0, + budget_exhausted: false, + phase: self.phase(), + }); + }; + let layers = *active_layers; + let advance = match field.run(budget) { + Ok(value) => value, + Err(error) => return self.fail(error), + }; + if advance.terminated { + let result = match field.result() { + Ok(value) => value, + Err(error) => return self.fail(error), + }; + let gains = field.layer_gains(); + if let Err(error) = self.settle(result, layers, &gains) { + return self.fail(error); + } + if ![ + self.player.stats.damage, + self.player.stats.healing, + self.player.stats.boss_damage, + ] + .iter() + .all(|n| n.is_finite()) + { + return self.fail("Single-player combat statistics overflow".into()); + } + } + Ok(Advance { + ticks: advance.ticks, + budget_exhausted: advance.budget_exhausted, + phase: self.phase(), + }) + } + pub fn field(&self) -> Result, String> { + self.healthy()?; + Ok(if let State::Combat { field, .. } = &self.state { + Some(field) + } else { + None + }) + } + pub fn last_result(&self) -> Result, String> { + self.healthy()?; + Ok(self.last_result) + } + fn start_prep(&mut self) -> Result<(), String> { + let income = self.plans[self.index].as_ref().unwrap().income; + self.player.start_round(income)?; + if let Some(prep) = &mut self.prep { + let plan = self.plans[self.index].as_ref().unwrap(); + let boss = !matches!(plan.kind, RoundKind::Normal); + prep.begin_round( + self.index as u32 + 1, + DeployMap::new(&self.stage, &self.map, boss)?, + boss, + plan.deploy_cap, + &mut self.player, + self.draft.is_some(), + ) + .map_err(|e| e.to_string())?; + if let Some(draft) = &mut self.draft { + draft.pending = + prep.draw_draft(&mut draft.rng, &draft.stage, self.index as u32 + 1)?; + if draft.pending.is_none() { + prep.enter_prep(&mut self.player) + .map_err(|e| e.to_string())?; + } + } + } + self.state = State::Prep; + Ok(()) + } + fn settle( + &mut self, + result: FieldResult, + layers: f64, + gains: &[(String, f64)], + ) -> Result<(), String> { + self.player.stats.kills = add(self.player.stats.kills, result.killed)?; + self.player.stats.credited_kills = + add(self.player.stats.credited_kills, result.credited_kills)?; + self.player.stats.damage += result.damage; + // The source records bounty earnings now and again when pending funds + // reach the next preparation wallet. + let bonus = if let Some(prep) = &mut self.prep { + prep.settle_bounties( + result.counted_leaks == 0 + && result + .boss_round + .is_none_or(|b| b.outcome == Some(BossRoundOutcome::Victory)), + )? + } else { + 0. + }; + self.player.bounty(result.coins + bonus)?; + if let Some(prep) = &mut self.prep { + prep.settle_layers(gains, &mut self.player)?; + } + self.last_result = Some(result); + if let Some(prep) = &mut self.prep { + prep.equipment_battle_result(&mut self.player) + .map_err(|e| e.to_string())?; + } + if self.index < self.boss_index { + let loss = result.counted_leaks.min(self.config.lp_cap_per_round) as f64; + self.player.lp -= loss; + self.player.stats.lp_lost += loss; + self.player.stats.leaks = add(self.player.stats.leaks, result.counted_leaks)?; + self.player.stats.healing += result.healing; + self.player.stats.perfect_rounds += u64::from(result.counted_leaks == 0); + if self.player.lp <= 0. { + self.player.lp = 0.; + self.player.clear(); + if let Some(prep) = &mut self.prep { + prep.eliminate(); + } + self.finish(false, false, EndReason::Eliminated); + return Ok(()); + } + self.rounds_passed = self.index as u32 + 1; + } else { + let round = result.boss_round.unwrap(); + self.player.stats.boss_damage = result.match_boss_damage; + self.player.team_lp = Some(round.lp); + self.player.lp = round.lp.round(); + let won = round.outcome == Some(BossRoundOutcome::Victory); + if self.index > self.boss_index { + self.rounds_passed = self.boss_index as u32 + 1 + u32::from(won); + self.finish(true, won, EndReason::Victory); + return Ok(()); + } + if !won { + self.finish(false, false, EndReason::Defeat); + return Ok(()); + } + self.rounds_passed = self.index as u32 + 1; + let hidden = self.config.hidden.as_ref().is_some_and(|rule| { + layers > rule.layer_threshold && round.lp > rule.min_lp_exclusive + }); + if !hidden { + self.finish(true, false, EndReason::Victory); + return Ok(()); + } + } + self.index += 1; + self.start_prep() + } + fn finish(&mut self, victory: bool, hidden_cleared: bool, reason: EndReason) { + self.state = State::Result(Outcome { + victory, + hidden_reached: self.index > self.boss_index, + hidden_cleared, + reason, + }); + } + fn fail(&mut self, error: String) -> Result { + self.state = State::Faulted(error.clone()); + Err(error) + } +} +fn add(a: u64, b: u64) -> Result { + a.checked_add(b) + .filter(|&n| n <= MAX_FUNDS) + .ok_or_else(|| "Single-player accounting capacity exceeded".into()) +} diff --git a/crates/engine/src/solo/draft.rs b/crates/engine/src/solo/draft.rs new file mode 100644 index 0000000..0ef7671 --- /dev/null +++ b/crates/engine/src/solo/draft.rs @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Single-player SP draft generation. The caller owns the independent draft RNG +//! and supplies live pool availability; generating a draft does not award cards. +use crate::{data::Catalog, deterministic::rng::Rng}; +use serde_json::{json, Value}; +mod bounty; +mod runner; +pub(super) use runner::Flow; + +pub struct Context<'a> { + pub mode: &'a str, + pub stage: Option<&'a str>, + pub round: u32, + pub bond_available: &'a dyn Fn(&str) -> bool, + pub item_available: &'a dyn Fn(&str) -> bool, +} +fn list(v: &Value) -> &[Value] { + v.as_array().map(Vec::as_slice).unwrap_or(&[]) +} +fn num(v: &Value, fallback: f64) -> f64 { + v.as_f64() + .or_else(|| v.as_str().and_then(|s| s.parse().ok())) + .or_else(|| v.as_bool().map(|b| f64::from(u8::from(b)))) + .filter(|n| n.is_finite()) + .unwrap_or(fallback) +} +fn pick(rng: &mut Rng, weights: &[f64]) -> Option { + rng.weighted(weights) + .or_else(|| (!weights.is_empty()).then_some(0)) +} +fn weighted<'a>( + rng: &mut Rng, + entries: &[&'a Value], + weight: impl Fn(&Value) -> f64, +) -> Option<&'a Value> { + pick(rng, &entries.iter().map(|v| weight(v)).collect::>()).map(|i| entries[i]) +} +struct Data<'a> { + catalog: &'a Catalog, + choices: &'a Value, + ctx: &'a Context<'a>, +} +impl Data<'_> { + fn record(&self, table: &str, id: &Value) -> &Value { + id.as_str() + .and_then(|s| self.catalog.table(table)?.get(s)) + .unwrap_or(&Value::Null) + } + fn items(&self, lo: i64, hi: i64) -> Vec { + let mut items: Vec<_> = self + .catalog + .table("items") + .and_then(Value::as_object) + .into_iter() + .flatten() + .filter(|(id, it)| { + it["itemType"] == "EQUIP" + && it["isGolden"] != true + && it["hideInShop"] != true + && it["shopExcluded"] != true + && it["tier"].as_i64().is_some_and(|t| t >= lo && t <= hi) + && (self.ctx.item_available)(id) + }) + .map(|(id, it)| (it["tier"].as_i64().unwrap(), id.clone())) + .collect(); + items.sort(); + items.into_iter().map(|(_, id)| id).collect() + } + fn item_card(&self, id: &str) -> Value { + let it = &self.catalog.table("items").unwrap()[id]; + json!({"kind":"item","id":id,"name":it.get("name").unwrap_or(&json!(id)),"desc":it["desc"].as_str().unwrap_or(""),"tier":it["tier"].as_i64().unwrap_or(1),"price":0}) + } + fn bond_ok(&self, c: &Value) -> bool { + let effect = self.record("effects", &c["effectId"]); + let buffs = list(&effect["buffs"]); + if buffs.is_empty() { + return true; + } + let mut bonds = Vec::new(); + for b in buffs { + match b["key"].as_str() { + Some("single_special_choice_gain_bond_chess") if b["bbStr"]["bond"].is_string() => { + bonds.push(b["bbStr"]["bond"].as_str().unwrap()) + } + Some("global_special_choice_bond_addlayer") => bonds.extend( + b["bbStr"]["bond_list"] + .as_str() + .unwrap_or("") + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()), + ), + _ => return true, + } + } + bonds.is_empty() || bonds.into_iter().any(self.ctx.bond_available) + } + fn tactics(&self, rng: &mut Rng, n: usize) -> Vec { + let pool: Vec<_> = list(&self.choices["cards"]["tactic"]) + .iter() + .filter(|c| { + (c["kind"] != "terrain" || self.ctx.stage.is_some_and(|id| c["stageId"] == id)) + && self.record("effects", &c["effectId"]).is_object() + && self.bond_ok(c) + }) + .collect(); + let spec = &self.choices["tacticDraft"]; + let official = spec.is_object() + && (!spec["rounds"].is_array() + || list(&spec["rounds"]).contains(&json!(self.ctx.round))); + let kinds = if official { list(&spec["kinds"]) } else { &[] }; + let filtered: Vec<_> = pool + .iter() + .copied() + .filter(|c| kinds.is_empty() || kinds.contains(&c["kind"])) + .collect(); + let pool = if filtered.is_empty() { + &pool + } else { + &filtered + }; + (0..n).filter_map(|_|weighted(rng,pool,|c|if official {num(&spec["weights"][c["effectId"].as_str().unwrap_or("")],1.)}else{1.})) + .map(|c|json!({"kind":"tactic","id":c["effectId"],"name":c["name"],"desc":c["desc"].as_str().unwrap_or(""),"tier":null,"team":c["team"]==true,"tacticKind":c["kind"]})).collect() + } + fn shop(&self, rng: &mut Rng, n: usize) -> Option> { + let spec = &self.choices["shopDraft"]; + let slots: Vec<_> = list(&spec["slots"]) + .iter() + .filter(|v| v.is_object()) + .collect(); + if slots.is_empty() + || spec["rounds"].is_array() && !list(&spec["rounds"]).contains(&json!(self.ctx.round)) + { + return None; + } + let coin = spec["coin"] + .as_str() + .filter(|_| self.record("items", &spec["coin"]).is_object()); + let mut out = Vec::new(); + for slot in slots { + let mut kinds: Vec<_> = slot + .as_object() + .unwrap() + .iter() + .filter(|(k, _)| { + if *k == "coin" { + coin.is_some() + } else { + k.parse::().is_ok() + } + }) + .collect(); + // JS Object.entries visits integer-index keys before other keys. + kinds.sort_by_key(|(k, _)| { + k.parse::() + .ok() + .filter(|n| *n < u32::MAX && n.to_string() == **k) + .map_or((1, 0), |n| (0, n)) + }); + let Some(i) = pick( + rng, + &kinds.iter().map(|(_, w)| num(w, 0.)).collect::>(), + ) else { + continue; + }; + let kind = kinds[i].0; + let candidates = if kind == "coin" { + vec![coin.unwrap().to_owned()] + } else { + let tier = kind.parse::().unwrap().clamp(0, 64); + (1..=tier) + .rev() + .map(|t| self.items(t, t)) + .find(|v| !v.is_empty()) + .unwrap_or_else(|| self.items(1, 6)) + }; + if let Some(i) = pick( + rng, + &candidates + .iter() + .map(|id| num(&spec["itemWeights"][id], 1.)) + .collect::>(), + ) { + out.push(self.item_card(&candidates[i])); + } + } + rng.shuffle(&mut out); + out.truncate(n); + Some(out) + } + fn cards(&self, rng: &mut Rng, family: &str, n: usize, sch: &Value) -> Vec { + match family { + "bounty" => self.bounties(rng, n, sch), + "tactic" => self.tactics(rng, n), + "shop" | "supply" => { + if family == "shop" { + if let Some(cards) = self.shop(rng, n) { + return cards; + } + } + let tiers = list(&sch["supplyTiers"]); + let (lo, hi) = if family == "supply" && tiers.len() == 2 { + (num(&tiers[0], 1.) as i64, num(&tiers[1], 6.) as i64) + } else { + (1, 6) + }; + let mut items = self.items(lo, hi); + if items.is_empty() { + items = self.items(1, 6); + } + (0..n) + .filter_map(|_| rng.pick(&items).map(|id| self.item_card(id))) + .collect() + } + _ => vec![], + } + } +} +/// Generate only at a scheduled SP round. Failure preserves the caller's RNG. +/// Availability filters are pure reads of the current match pools. +pub fn generate(data: &Catalog, rng: &mut Rng, ctx: &Context<'_>) -> Result, String> { + let choices = data.table("choices").ok_or("Missing choices")?; + let mode = &data.table("config").ok_or("Missing config")?["modes"][ctx.mode]; + if mode["type"] != "SINGLE" { + return Err("Draft requires a single-player mode".into()); + } + let schedule = &choices["schedule"][ctx.mode]; + if !list(&mode["spRounds"]).contains(&json!(ctx.round)) { + return Ok(None); + } + validate(choices, 0, &mut 100_000)?; + let fallback = json!({"families":[{"family":"supply","weight":1}],"cards":3,"supplyTiers":[1,6.min(1+ctx.round/3)]}); + let sch = schedule["rounds"] + .get(ctx.round.to_string()) + .filter(|v| v.is_object()) + .unwrap_or(&fallback); + let mut next = rng.clone(); + let fams = list(&sch["families"]); + let mut family = pick( + &mut next, + &fams + .iter() + .map(|f| num(&f["weight"], 0.)) + .collect::>(), + ) + .and_then(|i| fams[i]["family"].as_str()) + .unwrap_or("supply") + .to_owned(); + // A missing family list still performs the original one-entry weighted draw. + if fams.is_empty() { + next.next_f64(); + } + let n = sch["cards"] + .as_u64() + .filter(|n| *n > 0) + .map(|n| n.min(6) as usize) + .unwrap_or_else(|| { + choices["format"]["solo"]["cards"] + .as_u64() + .unwrap_or(3) + .min(6) as usize + }); + let d = Data { + catalog: data, + choices, + ctx, + }; + let mut cards = d.cards(&mut next, &family, n, sch); + if cards.is_empty() && family != "supply" { + family = "supply".into(); + cards = d.cards(&mut next, &family, n, sch); + } + let result = if cards.is_empty() { + None + } else { + for (i, c) in cards.iter_mut().enumerate() { + c["idx"] = json!(i); + c["family"] = json!(family); + } + let info = &choices["families"][&family]; + let event = next + .pick(list(&sch["events"][&family])) + .cloned() + .unwrap_or(Value::Null); + let name = info["name"].as_str().unwrap_or(match family.as_str() { + "bounty" => "悬赏决策", + "supply" => "道具补给", + "shop" => "机密商店", + "tactic" => "战术决策", + _ => &family, + }); + Some( + json!({"family":family,"name":name,"desc":info["desc"].as_str().unwrap_or(""),"eventId":event,"cards":cards}), + ) + }; + *rng = next; + Ok(result) +} +fn validate(v: &Value, depth: usize, left: &mut usize) -> Result<(), String> { + if depth > 16 || *left == 0 { + return Err("Draft definition capacity exceeded".into()); + } + *left -= 1; + match v { + Value::Array(a) => { + if a.len() > 4096 { + return Err("Draft list capacity exceeded".into()); + } + for v in a { + validate(v, depth + 1, left)?; + } + } + Value::Object(m) => { + for (k, v) in m { + if ["count", "size", "slots", "open", "perSeries", "maxSeries16"] + .contains(&k.as_str()) + && v.as_u64().is_some_and(|n| n > 64) + { + return Err("Draft draw capacity exceeded".into()); + } + validate(v, depth + 1, left)?; + } + } + _ => (), + } + Ok(()) +} diff --git a/crates/engine/src/solo/draft/bounty.rs b/crates/engine/src/solo/draft/bounty.rs new file mode 100644 index 0000000..213001f --- /dev/null +++ b/crates/engine/src/solo/draft/bounty.rs @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; + +fn id(c: &Value) -> &str { + c["effectId"].as_str().unwrap_or("") +} +fn contains(cards: &[&Value], c: &Value) -> bool { + cards.iter().any(|x| id(x) == id(c)) +} +fn by_ids<'a>(ids: &Value, all: &[&'a Value]) -> Vec<&'a Value> { + list(ids) + .iter() + .filter_map(|v| all.iter().find(|c| c["effectId"] == *v).copied()) + .collect() +} +fn initial<'a>(rng: &mut Rng, rule: &Value, all: &[&'a Value]) -> Vec<&'a Value> { + let mut out = Vec::new(); + let per = rule["perSeries"].as_u64().unwrap_or(1) as usize; + let prefer = list(&rule["prefer"]); + let pref_tiers: Vec<_> = all + .iter() + .filter(|c| prefer.contains(&c["effectId"])) + .map(|c| &c["tier"]) + .collect(); + let mut tiers = list(&rule["tiers"]).to_vec(); + rng.shuffle(&mut tiers); + let ordered: Vec<_> = tiers + .iter() + .filter(|t| pref_tiers.contains(t)) + .chain(tiers.iter().filter(|t| !pref_tiers.contains(t))) + .collect(); + for tier in ordered { + let candidates: Vec<_> = all + .iter() + .copied() + .filter(|c| { + !contains(&out, c) + && c["tier"] == *tier + && list(&rule["series"]).contains(&c["series"]) + && out.iter().filter(|x| x["series"] == c["series"]).count() < per + }) + .collect(); + let preferred: Vec<_> = candidates + .iter() + .copied() + .filter(|c| prefer.contains(&c["effectId"])) + .collect(); + if let Some(c) = rng.pick(if preferred.is_empty() { + &candidates + } else { + &preferred + }) { + out.push(*c); + } + } + out +} +fn hunter<'a>( + rng: &mut Rng, + rule: &Value, + mut out: Vec<&'a Value>, + all: &[&'a Value], + size: usize, +) -> Vec<&'a Value> { + let giants = by_ids(&rule["giants"], all); + if out.len() < size && !out.iter().any(|c| contains(&giants, c)) { + let candidates: Vec<_> = giants + .iter() + .copied() + .filter(|c| !contains(&out, c)) + .collect(); + if let Some(c) = rng.pick(&candidates) { + out.push(*c); + } + } + let mut candidates = by_ids(&rule["cards"], all); + rng.shuffle(&mut candidates); + for c in candidates { + if out.len() >= size { + break; + } + let fits = if list(&rule["onePerSeries"]).contains(&c["series"]) { + !out.iter().any(|x| x["series"] == c["series"]) + } else { + c["series"] != 16 + || out + .iter() + .filter(|x| x["series"] == 16 && !contains(&giants, x)) + .count() + < rule["maxSeries16"].as_u64().unwrap_or(2) as usize + }; + if !contains(&out, c) && fits { + out.push(c); + } + } + out +} +fn structured<'a>(rng: &mut Rng, kind: &str, spec: &Value, all: &[&'a Value]) -> Vec<&'a Value> { + let count = spec["count"].as_u64().unwrap_or(6) as usize; + let groups = list(&spec["groups"]); + let group = if spec["pick"] == "seen" { + pick( + rng, + &groups + .iter() + .map(|g| { + list(&g["seen"]) + .iter() + .filter(|v| v.as_i64().is_some()) + .count() + .max(1) as f64 + }) + .collect::>(), + ) + .map(|i| &groups[i]) + } else { + let slots = groups + .len() + .max(spec["slots"].as_u64().unwrap_or(0) as usize); + let slot = if slots > 0 { + rng.int(slots as u32) as usize + } else { + 0 + }; + groups.get(slot) + }; + let rule = &spec["rule"]; + let mut weights = Vec::new(); + let mut cards = if let Some(group) = group { + let mut cards = Vec::new(); + for (i, key) in list(&group["cards"]).iter().enumerate() { + if let Some(c) = all.iter().find(|c| c["effectId"] == *key) { + cards.push(*c); + weights.push(num(&group["weights"][i], 1.)); + } + } + if kind == "hunter" && num(&group["open"], 0.) > 0. { + let size = cards.len() + num(&group["open"], 0.) as usize; + cards = hunter(rng, rule, cards, all, size); + } + cards + } else if kind == "initial" { + initial(rng, rule, all) + } else if kind == "hunter" { + hunter( + rng, + rule, + vec![], + all, + rule["size"].as_u64().unwrap_or(7) as usize, + ) + } else { + vec![] + }; + weights.resize(cards.len(), 1.); + for w in &mut weights { + if *w == 0. { + *w = 1.; + } + *w = w.max(0.); + } + let mut out = Vec::new(); + while out.len() < count && !cards.is_empty() { + let i = pick(rng, &weights).unwrap(); + out.push(cards.remove(i)); + weights.remove(i); + } + out +} +fn text(v: &Value, multi: bool) -> Value { + if !multi { + return v.clone(); + } + let Some(s) = v.as_str() else { + return v.clone(); + }; + let mut s = s.to_owned(); + for prefix in ["之后的", "后续的", "后续"] { + s = s.replace( + &format!("{prefix}<@ba.vdown>每场作战"), + "接下来<@ba.vup>两场作战", + ); + s = s.replace(&format!("{prefix}每场作战"), "接下来两场作战"); + } + json!(s) +} +impl Data<'_> { + pub(super) fn bounties(&self, rng: &mut Rng, n: usize, sch: &Value) -> Vec { + let kind = sch["bountyDraft"] + .as_str() + .unwrap_or(if self.ctx.round < 8 { + "initial" + } else if self.ctx.round < 11 { + "boss" + } else { + "hunter" + }); + let all: Vec<_> = list(&self.choices["cards"]["bounty"]) + .iter() + .filter(|c| { + (!c["draftPool"].is_string() || c["draftPool"] == kind) + && c["draft"].as_bool().unwrap_or(c["payout"] != "perfect") + && self.record("enemies", &c["enemyKey"]).is_object() + }) + .collect(); + let spec = &self.choices["bountyDrafts"][kind]; + let mut out = if spec.is_object() { + structured(rng, kind, spec, &all) + } else { + vec![] + }; + if out.len() < n { + let mut candidates = all.clone(); + rng.shuffle(&mut candidates); + for c in candidates { + if out.len() >= n { + break; + } + if !contains(&out, c) { + out.push(c); + } + } + } + rng.shuffle(&mut out); + out.truncate(n); + out.into_iter().map(|c|{ + let multi=c["multiRound"]==true||num(&c["rounds"],0.)>=90.; + let rounds=if multi{2}else{c["rounds"].as_u64().unwrap_or(1).clamp(1,99)}; + let desc=json!(c["desc"].as_str().unwrap_or("")); + json!({"kind":"bounty","id":c["effectId"],"name":c["name"],"desc":text(&desc,multi),"descRaw":text(&self.record("effects",&c["effectId"])["descRaw"],multi),"tier":c["tier"],"coin":c["coin"],"payout":c["payout"],"rounds":rounds,"enemyKey":c["enemyKey"],"count":c["count"]}) + }).collect() + } +} diff --git a/crates/engine/src/solo/draft/runner.rs b/crates/engine/src/solo/draft/runner.rs new file mode 100644 index 0000000..26b01ce --- /dev/null +++ b/crates/engine/src/solo/draft/runner.rs @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::solo::{map::DeployMap, Phase, RoundKind, Runner}; + +pub(in crate::solo) struct Flow { + pub stage: String, + pub rng: Rng, + pub pending: Option, +} +impl Runner { + /// Opt into SP decisions before the first battle. Unported picked effects + /// fault the rollout explicitly; they are never removed from the draft pool. + pub fn enable_drafts(&mut self, stage_id: &str) -> Result<(), String> { + self.healthy()?; + if self.index != 0 || self.phase() != Phase::Prep || self.draft.is_some() { + return Err("Drafts must be enabled once before the first battle".into()); + } + let prep = self + .prep + .as_ref() + .filter(|p| p.has_effects()) + .ok_or("Drafts require owned preparation effects")?; + if self.data.table("stages").and_then(|t| t.get(stage_id)) != Some(&self.stage) { + return Err("Draft stage does not match the runner stage".into()); + } + let mode = &self.data.table("config").unwrap()["modes"][prep.draft_mode()]; + if list(&mode["spRounds"]).contains(&json!(1)) { + return Err("First-round drafts must precede preparation initialization".into()); + } + self.draft = Some(Flow { + stage: stage_id.into(), + rng: Rng::new(crate::deterministic::rng::derive_seed(self.seed, "draft")), + pending: None, + }); + Ok(()) + } + /// Select an offered index, once, then run the deferred preparation-start hooks. + pub fn pick_draft(&mut self, index: usize) -> Result<(), String> { + self.healthy()?; + if self.phase() != Phase::Draft { + return Err("WRONG_PHASE".into()); + } + let card = self + .draft + .as_ref() + .and_then(|d| d.pending.as_ref()) + .and_then(|d| d["cards"].get(index)) + .ok_or("BAD_TARGET")? + .clone(); + let mut prep = self.prep.as_ref().unwrap().clone(); + let mut player = self.player.clone(); + let mut map = self.map.clone(); + let apply = (|| { + prep.apply_draft(&card, &mut map, &mut player) + .map_err(|e| e.to_string())?; + map = map.clone().resolved(&self.data)?; + let boss = !matches!( + self.plans[self.index].as_ref().unwrap().kind, + RoundKind::Normal + ); + prep.change_map(DeployMap::new(&self.stage, &map, boss)?, &mut player) + .map_err(|e| e.to_string())?; + prep.enter_prep(&mut player).map_err(|e| e.to_string()) + })(); + if let Err(error) = apply { + return self.fail(error); + } + self.prep = Some(prep); + self.player = player; + self.map = map; + self.draft.as_mut().unwrap().pending = None; + Ok(()) + } +} diff --git a/crates/engine/src/solo/map.rs b/crates/engine/src/solo/map.rs new file mode 100644 index 0000000..17e38c6 --- /dev/null +++ b/crates/engine/src/solo/map.rs @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Preparation placement classes; battle pathing keeps its own occupancy grid. +use crate::battle::{ + grid::{Grid, Rect, COLS, N}, + runtime::MapConfig, +}; +use serde_json::Value; + +#[derive(Clone)] +pub(super) struct DeployMap([u8; 36]); +impl DeployMap { + pub(in crate::solo) fn public_cells(&self) -> Vec { + self.0.iter().enumerate().filter_map(|(i, c)| { + (*c != 0).then(|| serde_json::json!({"row":9+i/9,"col":2+i%9,"kind":if *c==1{"melee"}else{"ranged"}})) + }).collect() + } + + pub fn new(stage: &Value, map: &MapConfig, boss: bool) -> Result { + let grid = Grid::new(stage, if boss { Rect::BOSS } else { Rect::NORMAL })?; + let mut out = Self([0; 36]); + for r in 9..=12 { + for c in 2..=10 { + let row = if boss { r - 7 } else { r }; + let tile = &grid.tiles()[row * COLS + c]; + out.0[(r - 9) * 9 + c - 2] = match (tile.height.as_str(), tile.build.as_str()) { + ("LOW", "ALL" | "MELEE") => 1, + ("HIGH", "ALL" | "RANGED") | ("LOW", "RANGED") => 2, + _ => 0, + }; + } + } + let devices = stage["devices"] + .as_array() + .map(Vec::as_slice) + .unwrap_or(&[]); + if devices.len() > N { + return Err("Stage device capacity exceeded".into()); + } + for d in devices { + let row = d["row"].as_i64().or(d["pos"][0].as_i64()).unwrap_or(-100); + let col = d["col"].as_i64().or(d["pos"][1].as_i64()).unwrap_or(-100); + let row = row.saturating_add(if boss { 7 } else { 0 }); + if !(9..=12).contains(&row) || !(2..=10).contains(&col) { + continue; + } + let alias = d["alias"].as_str().or(d["raw"]["alias"].as_str()); + let active = alias + .and_then(|a| map.device_overrides.get(a)) + .copied() + .unwrap_or_else(|| d["active"].as_bool().unwrap_or(d["hidden"] != true)); + if !active { + continue; + } + let cls = &mut out.0[(row as usize - 9) * 9 + col as usize - 2]; + match d["role"].as_str() { + Some("crate" | "mound") => *cls = 0, + Some("platform") => *cls = 2, + Some("waterPlatform") => { + return Err("Water platform is outside current map support".into()) + } + _ => (), + } + } + Ok(out) + } + pub fn can_place(&self, record: &Value, [row, col]: [i32; 2]) -> bool { + if !(9..=12).contains(&row) || !(2..=10).contains(&col) { + return false; + } + let cls = self.0[(row as usize - 9) * 9 + col as usize - 2]; + let trait_text = record + .get("traitBase") + .filter(|v| !v.is_null()) + .unwrap_or(&record["trait"])["desc"] + .as_str() + .unwrap_or(""); + let ranged = record["position"] != "MELEE" + || record["placeOnRanged"] == true + || trait_text.contains("可以放置于远程位"); + cls == 1 || cls == 2 && ranged + } +} diff --git a/crates/engine/src/solo/mode.rs b/crates/engine/src/solo/mode.rs new file mode 100644 index 0000000..f2e18ec --- /dev/null +++ b/crates/engine/src/solo/mode.rs @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Deterministic single-player setup and resolved round plans. Setup diagnostics +//! include future waves and must not be exposed as a policy observation. +use crate::{ + data::Catalog, + deterministic::rng::{derive_seed, Rng}, +}; +use serde_json::{json, Value}; +use std::collections::BTreeSet; +mod waves; +const ACLOON: &str = "enemy_9012_acloon"; +const CAP: usize = 4096; +pub struct Generated { + pub input: Value, + pub setup: Value, +} +fn n(v: &Value, d: f64) -> f64 { + v.as_f64().filter(|x| x.is_finite()).unwrap_or(d) +} +fn positive(v: &Value, d: usize) -> usize { + v.as_u64() + .and_then(|v| usize::try_from(v).ok()) + .filter(|v| *v > 0) + .unwrap_or(d) +} +fn list(v: &Value) -> &[Value] { + v.as_array().map(Vec::as_slice).unwrap_or(&[]) +} +fn weighted(rng: &mut Rng, pairs: &[(String, f64)]) -> Option { + let w: Vec<_> = pairs.iter().map(|(_, w)| *w).collect(); + rng.weighted(&w) + .or_else(|| (!pairs.is_empty()).then_some(0)) + .map(|i| pairs[i].0.clone()) +} +struct Data<'a> { + data: &'a Catalog, + cfg: &'a Value, + mode: &'a Value, + factions: &'a Value, +} +impl Data<'_> { + fn table(&self, key: &str) -> &Value { + self.data.table(key).unwrap() + } + fn enemy(&self, key: &str) -> &Value { + &self.table("enemies")[key] + } + fn fly(&self, key: &str) -> bool { + let e = self.enemy(key); + e["isFlyEnemy"] + .as_bool() + .unwrap_or(e["stats"]["motion"] == "FLY") + } + fn pick(&self, rng: &mut Rng, kind: &str, round: usize) -> Value { + let g = &self.factions["generation"]; + let half = round <= positive(&g["firstHalfMaxRound"], positive(&g["maxLevelCnt"], 15) / 2); + let mut entries: Vec<_> = self.factions["entries"] + .as_object() + .into_iter() + .flat_map(|m| m.values()) + .filter(|e| { + e["type"] == kind + && (e["firstHalf"] == true) == half + && e["key"] + .as_str() + .is_some_and(|k| k != ACLOON && self.enemy(k).is_object()) + && !list(&self.mode["inactiveEnemyKeys"]).contains(&e["key"]) + }) + .collect(); + entries.sort_by(|a, b| a["key"].as_str().cmp(&b["key"].as_str())); + if entries.is_empty() { + return if kind != "SPECIAL" { + self.pick(rng, "SPECIAL", round) + } else { + Value::Null + }; + } + let weights: Vec<_> = entries.iter().map(|e| n(&e["weight"], 1.)).collect(); + let e = entries[rng.weighted(&weights).unwrap_or(0)]; + let mut attached = |field| { + let keys: Vec<_> = list(&e[field]) + .iter() + .filter_map(|v| v.as_str().or(v["key"].as_str())) + .filter(|k| *k != ACLOON && self.enemy(k).is_object()) + .collect(); + rng.pick(&keys).copied().map(str::to_owned) + }; + let normal = attached("N"); + let elite = attached("E"); + json!({"round":round,"type":e["type"],"key":e["key"],"normal":normal,"elite":elite,"fly":e["fly"].as_bool().unwrap_or_else(||self.fly(e["key"].as_str().unwrap())),"firstHalf":half}) + } +} +/// Generate the legacy solo CLI input shape, plus private setup diagnostics. +/// Manual bans affect only the final pool list, never any RNG stream. +pub fn generate( + data: &Catalog, + seed: u32, + mode_id: &str, + manual_banned: &[String], +) -> Result { + generate_at_revision(data, seed, mode_id, manual_banned, 0) +} +pub(super) fn generate_at_revision( + data: &Catalog, + seed: u32, + mode_id: &str, + manual_banned: &[String], + revision: u32, +) -> Result { + let cfg = data.table("config").ok_or("Missing config")?; + let mode = &cfg["modes"][mode_id]; + if !mode.is_object() || mode["type"] != "SINGLE" { + return Err("Expected a single-player mode".into()); + } + if manual_banned.len() > CAP { + return Err("Manual ban capacity exceeded".into()); + } + let d = Data { + data, + cfg, + mode, + factions: data.table("factions").ok_or("Missing factions")?, + }; + let mut manual = BTreeSet::new(); + for key in manual_banned { + let c = &d.table("chess")[key]; + if !c.is_object() { + return Err(format!("Unknown banned chess: {key}")); + } + manual.insert(c["baseId"].as_str().unwrap_or(key).to_owned()); + } + let seed = seed.max(1); + let salt = if revision == 0 { + "setup".into() + } else { + format!("reroll-setup:{revision}") + }; + let mut rng = Rng::new(derive_seed(seed, &salt)); + let stages: Vec<_> = list(&mode["stages"]) + .iter() + .filter_map(Value::as_str) + .filter_map(|id| { + let s = &d.table("stages")[id]; + (s.is_object() && s["active"] != false && n(&s["weight"], 0.) > 0.) + .then(|| (id.into(), n(&s["weight"], 0.))) + }) + .collect(); + let stage = weighted(&mut rng, &stages) + .or_else(|| { + d.table("stages") + .as_object() + .into_iter() + .flat_map(|m| m.iter()) + .filter(|(_, s)| s["active"] == true) + .map(|(id, _)| id.clone()) + .min() + }) + .ok_or("No active stage")?; + let types = &d.factions["types"]; + let g = &d.factions["generation"]; + let mut chosen: Vec = types + .as_object() + .into_iter() + .flat_map(|m| m.values()) + .filter(|t| t["involveRandom"] == true) + .filter_map(|t| t["type"].as_str().map(str::to_owned)) + .collect(); + if chosen.len() > CAP { + return Err("Faction capacity exceeded".into()); + } + chosen.sort(); + rng.shuffle(&mut chosen); + chosen.truncate( + g["specialEnemyNum"] + .as_u64() + .unwrap_or(3) + .min(chosen.len() as u64) as usize, + ); + let mut factions = chosen.clone(); + factions.sort_by(|a, b| n(&types[a]["sortId"], 9.).total_cmp(&n(&types[b]["sortId"], 9.))); + let boss_pairs = |field: &str| { + mode[field] + .as_object() + .into_iter() + .flat_map(|m| m.iter()) + .filter(|(id, w)| d.table("bosses")[*id].is_object() && n(w, 0.) > 0.) + .map(|(id, w)| (id.clone(), n(w, 0.))) + .collect::>() + }; + let boss = weighted(&mut rng, &boss_pairs("bossWeights")).ok_or("No eligible boss")?; + let hidden_round = mode["hiddenRound"] + .as_u64() + .filter(|r| *r > 0) + .map(|r| r as usize); + let hidden = if hidden_round.is_some() { + weighted(&mut rng, &boss_pairs("hiddenBossWeights")) + } else { + None + }; + let mut schedule_rng = Rng::new(derive_seed(rng.state(), "waves:schedule")); + let max = positive(&g["maxLevelCnt"], 15).min(256); + let fill = g["fillType"] + .as_str() + .or(g["alwaysIncludedType"].as_str()) + .unwrap_or("SPECIAL"); + let mut schedule = Vec::new(); + for kind in &chosen { + for _ in 0..positive(&types[kind]["count"], 3).min(max - schedule.len()) { + schedule.push(kind.clone()); + } + } + schedule.resize(max, fill.into()); + schedule_rng.shuffle(&mut schedule); + let mut picks = vec![Value::Null]; + for (i, kind) in schedule.iter().enumerate() { + picks.push(d.pick(&mut schedule_rng, kind, i + 1)); + } + // Automatic bond bans use the setup stream after setupMatchWaves, not the schedule stream. + let difficulty = mode["difficulty"].as_str().unwrap_or("NORMAL"); + let bonds = d.table("bonds"); + let mut bond_ids: Vec<_> = bonds + .as_object() + .into_iter() + .flat_map(|m| m.keys()) + .cloned() + .collect(); + bond_ids.sort_by(|a, b| { + n(&bonds[a]["identifier"], 99.) + .total_cmp(&n(&bonds[b]["identifier"], 99.)) + .then(a.cmp(b)) + }); + let mut static_off: Vec<_> = list(&mode["inactiveBondIds"]) + .iter() + .filter_map(Value::as_str) + .filter(|b| bonds[*b].is_object()) + .map(str::to_owned) + .collect(); + static_off.sort(); + let mut drawn = Vec::new(); + for (core, key, default) in [ + (true, "core", if difficulty == "FUNNY" { 2 } else { 3 }), + (false, "addon", 4), + ] { + let mut eligible: Vec<_> = bond_ids + .iter() + .filter(|id| { + n(&bonds[*id]["weight"], 0.) > 0. + && !static_off.contains(id) + && (bonds[*id]["isCore"] == true) == core + }) + .cloned() + .collect(); + rng.shuffle(&mut eligible); + eligible.truncate( + cfg["bans"][difficulty][key] + .as_u64() + .unwrap_or(default) + .min(eligible.len() as u64) as usize, + ); + drawn.extend(eligible); + } + drawn.sort(); + let off: BTreeSet<_> = drawn.iter().chain(&static_off).cloned().collect(); + let mut automatic = Vec::new(); + for (id, c) in d.table("chess").as_object().ok_or("Invalid chess table")? { + if c["visible"] == true + && c["isGolden"] != true + && c["isHidden"] != true + && c["isDiy"] != true + && !list(&c["bonds"]).is_empty() + && list(&c["bonds"]) + .iter() + .all(|b| b.as_str().is_some_and(|b| off.contains(b))) + { + automatic.push(id.clone()); + } + } + automatic.sort(); + let banned: BTreeSet<_> = automatic + .iter() + .cloned() + .chain(manual.iter().cloned()) + .collect(); + let boss_round = positive( + &mode["bossRound"], + positive( + &mode["lastRound"], + if mode_id == "mode_single_funny" { + 9 + } else { + 14 + }, + ), + ); + let last = hidden_round + .filter(|_| hidden.is_some()) + .unwrap_or(boss_round); + if last > 64 || boss_round >= last + 1 || hidden_round.is_some_and(|r| r != boss_round + 1) { + return Err("Invalid mode round schedule".into()); + } + let speed = n(&cfg["combatTimeScale"], 2.); + if speed <= 0. { + return Err("Invalid combat time scale".into()); + } + let mut plans = Vec::new(); + for round in 1..=last { + let is_boss = round >= boss_round; + let boss_id = if round > boss_round { + hidden.as_deref().unwrap() + } else { + &boss + }; + plans.push(d.plan( + round, + picks.get(round).unwrap_or(&Value::Null), + is_boss, + boss_id, + speed, + )?); + } + let eligible = hidden.is_some() + && list(&cfg["hiddenCore"]["difficulties"]) + .iter() + .any(|v| v == difficulty); + let hidden_rule=eligible.then(||json!({"layerThreshold":n(&cfg["hiddenCore"]["single"],350.),"minLp":n(&cfg["hiddenCore"]["minTeamLpExclusive"],1.)})); + let setup = json!({"stageId":stage,"factions":factions,"bossId":boss,"hiddenBossId":hidden,"typeSlots":schedule,"picks":picks,"disabledBonds":drawn,"staticInactiveBonds":static_off,"automaticBanned":automatic,"manualBanned":manual,"banned":banned,"rng":rng.state()}); + // Random bond bans restrict the pool; surviving members still activate their bonds. + let input = json!({"seed":seed,"stage":d.table("stages")[&stage],"config":{"lp":n(&cfg["economy"]["defaultStartLp"],28.),"lpCap":cfg["lpCapPerRound"].as_u64().filter(|v|*v>0).unwrap_or(10),"keepFunds":cfg["economy"]["leftoverFundsLost"]==false,"hidden":hidden_rule},"preparation":{"modeId":mode_id,"banned":banned,"effects":{"disabledBonds":[]}},"plans":plans}); + Ok(Generated { input, setup }) +} diff --git a/crates/engine/src/solo/mode/waves.rs b/crates/engine/src/solo/mode/waves.rs new file mode 100644 index 0000000..013781d --- /dev/null +++ b/crates/engine/src/solo/mode/waves.rs @@ -0,0 +1,215 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +impl Data<'_> { + fn power(&self, key: &str) -> f64 { + let e = self.enemy(key); + if let Some(p) = e["attrPower"].as_f64().filter(|p| p.is_finite()) { + return p; + } + let s = &e["stats"]; + let b = &self.factions["generation"]["beFactors"]; + let p = ((n(&s["atk"], 0.) * n(&b["atk"], 5.)) as f32 + + (n(&s["maxHp"], 0.) * n(&b["hp"], 1.)) as f32) as f32; + let p = (p + (n(&s["def"], 0.) * n(&b["def"], 3.)) as f32) as f32; + (p + (n(&s["res"], 0.) * n(&b["res"], 3.)) as f32) as f64 + } + fn replaced(&self, original: &str, count: u64, new: &str) -> u64 { + let factor = |key| { + let x = n(&self.enemy(key)["beFactor"], 1.); + if x > 0. { + x + } else { + 1. + } + }; + let origin = + ((count as f64 * self.power(original)) as f32 as f64 / factor(original)) as f32; + let unit = (self.power(new) / factor(new)) as f32; + let g = &self.factions["generation"]; + let min = g["minReplacedEnemyCount"] + .as_u64() + .unwrap_or(1) + .clamp(1, 50); + let max = g["maxReplacedEnemyCount"] + .as_u64() + .unwrap_or(5) + .clamp(1, 50); + if unit <= 0. { + return min; + } + let ratio = (origin / unit) as f64; + let f = ratio.floor(); + let rounded = if ratio - f == 0.5 { + if f % 2. == 0. { + f + } else { + f + 1. + } + } else { + (ratio + 0.5).floor() + }; + (rounded.min(max as f64).max(min as f64)) as u64 + } + pub(super) fn plan( + &self, + round: usize, + pick: &Value, + boss: bool, + boss_id: &str, + speed: f64, + ) -> Result { + let rc = &self.mode["rounds"][round.to_string()]; + let mut id = if boss { + rc["bossTemplates"][boss_id].as_str().or_else(|| { + rc["bossTemplates"] + .as_object() + .and_then(|m| m.values().find_map(Value::as_str)) + }) + } else { + rc["template"].as_str() + } + .ok_or("Missing round template")? + .to_owned(); + if boss && !id.ends_with("_s") && self.table("waves")[format!("{id}_s")].is_object() { + id.push_str("_s"); + } + let tpl = &self.table("waves")[&id]; + if !tpl.is_object() { + return Err(format!("Unknown round template: {id}")); + } + let original = list(&tpl["spawns"]); + if original.len() > CAP || list(&tpl["routes"]).len() > CAP { + return Err("Mode wave capacity exceeded".into()); + } + let scale = &self.mode["enemyScale"][round.to_string()]; + let common = json!({"hpMul":n(&scale["hp"],1.).max(0.01),"atkMul":n(&scale["atk"],1.).max(0.),"speedMul":n(&scale["speed"],1.).max(0.01)}); + let mut spawns = Vec::new(); + let mut actions = Vec::new(); + for (i, s) in original.iter().enumerate() { + if !s.is_object() + || s["action"] + .as_str() + .is_some_and(|a| !a.eq_ignore_ascii_case("SPAWN")) + { + continue; + } + let Some(key0) = s["key"] + .as_str() + .or(s["enemyKey"].as_str()) + .filter(|k| *k != ACLOON) + else { + continue; + }; + let is_boss = s["tag"] == "boss"; + let part = s["tag"] == "part"; + let count = s["count"].as_u64().unwrap_or(1).clamp(1, 50); + let interval = n(&s["interval"], 0.).max(0.); + let time = n(&s["time"], 0.).max(0.); + let route = s["routeIndex"].as_u64().unwrap_or(0); + let window = count as f64 * interval; + if !window.is_finite() { + return Err("Invalid action window".into()); + } + let mut key = key0; + let mut actual = count; + let mut step = interval; + let configured = &self.factions["generation"]["placeholders"]; + let fallback=self.factions["templateSlots"].as_object().and_then(|m|m.iter().find(|(_,v)|v==&key0)).map(|(slot,_)|json!({"slot":slot,"cls":match slot.as_str(){"E"|"EF"=>"elite","S"|"SF"=>"special",_=>"normal"},"fly":slot.ends_with('F')})).unwrap_or(Value::Null); + let ph = if configured.is_object() { + &configured[key0] + } else { + &fallback + }; + if !is_boss && !part && ph.is_object() && !pick.is_null() { + let new = match ph["cls"].as_str() { + Some("special") => pick["key"].as_str(), + Some("elite") => pick["elite"].as_str(), + _ => pick["normal"].as_str(), + }; + if let Some(new) = new.filter(|k| self.enemy(k).is_object()) { + if self.fly(new) != (ph["fly"] == true) { + actions.push(json!({"index":i,"key":null,"tplKey":key0,"slot":ph.get("slot").or(s.get("slot")),"time":time,"count":0,"tplCount":count,"window":window,"routeIndex":route,"valid":false,"server":false})); + continue; + } + actual = self.replaced(key0, count, new); + step = (window / actual as f64).max(0.05 * window); + key = new; + } + } + if !self.enemy(key).is_object() { + continue; + } + let slot = s["slot"] + .as_str() + .filter(|s| !s.is_empty()) + .unwrap_or_else( + || match (self.fly(key), self.enemy(key)["rank"] == "ELITE") { + (true, true) => "EF", + (true, false) => "NF", + (false, true) => "E", + _ => "N", + }, + ); + let mut mods = common.clone(); + if is_boss { + mods.as_object_mut().unwrap().remove("hpMul"); + } else { + let supply = n(&scale["supplyHp"], 1.); + if supply > 0. && supply != 1. { + mods["supplyHpMul"] = json!(supply); + } + } + mods["slot"] = json!(slot); + let mut spawn = json!({"time":time,"enemyKey":key,"routeIndex":route,"count":actual,"interval":if actual>1 {step}else{0.},"mods":mods,"actionIndex":i}); + if !s["tag"].is_null() { + spawn["tag"] = s["tag"].clone(); + } + if s["unharmful"] == true || part { + spawn["countInTotal"] = json!(false); + } + spawns.push(spawn); + actions.push(json!({"index":i,"key":key,"tplKey":key0,"slot":s["slot"],"time":time,"count":actual,"tplCount":count,"window":window,"routeIndex":route,"valid":true,"server":!is_boss&&s["group"].as_str().is_none_or(|g|g.is_empty())})); + } + let income = self.cfg["economy"]["income"][round].as_u64().unwrap_or( + (3 + round as u64).min(self.cfg["economy"]["incomeCap"].as_u64().unwrap_or(12)), + ); + let time = n( + &rc["combatTimeLimit"], + n(&self.mode["combatTimeLimit"][round.to_string()], 60.), + ); + let mut plan = json!({"kind":if !boss {"normal"}else if self.mode["hiddenRound"].as_u64()==Some(round as u64){"hidden"}else{"boss"},"timeLimit":if boss {Value::Null}else{json!(if time>0.{time*speed}else{60.*speed})},"income":income,"deployCap":positive(&self.cfg["economy"]["deployCap"],8),"templateId":id,"spawnActions":actions,"spawns":spawns,"routes":list(&tpl["routes"]),"extraRoutes":list(&tpl["extraRoutes"]),"overrides":if tpl["overrides"].is_object(){tpl["overrides"].clone()}else{json!({})},"actions":[]}); + plan["devices"] = json!(list(&tpl["devices"])); + plan["branches"] = if tpl["branches"].is_object() { + tpl["branches"].clone() + } else { + json!({}) + }; + if boss { + let boss = &self.table("bosses")[boss_id]; + let diff = self.mode["difficulty"].as_str().unwrap_or("NORMAL"); + let hp = boss["bloodPoint"][diff] + .as_f64() + .or_else(|| { + boss["bloodPoint"] + .as_object() + .and_then(|m| m.values().find_map(Value::as_f64)) + }) + .unwrap_or(500000.); + let share = n( + &self.mode["bossHpScale"]["solo"], + n(&self.cfg["bossHpScale"]["solo"], 1.), + ); + plan["maxHp"] = json!((hp * if share > 0. { share } else { 1. } + 0.5) + .floor() + .max(1.)); + let after = n(&rc["levelMaxPlayTime"], 0.); + let after = if after > 0. { + after + } else { + n(&self.cfg["bossOvertimeAfter"], 150.).max(0.) + }; + plan["overtime"] = json!({"afterReal":after,"combatTimeScale":speed,"lpPerSecond":n(&self.cfg["bossOvertimeDrainPerSec"],1.).max(0.)}); + } + Ok(plan) + } +} diff --git a/crates/engine/src/solo/player.rs b/crates/engine/src/solo/player.rs new file mode 100644 index 0000000..3b91897 --- /dev/null +++ b/crates/engine/src/solo/player.rs @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::{add, Stats, MAX_FUNDS}; + +#[derive(Clone, Default)] +pub(super) struct Player { + pub lp: f64, + pub team_lp: Option, + pub funds: u64, + pub pending: u64, + pub round_spent: u64, + pub stats: Stats, +} +impl Player { + pub fn spend(&mut self, amount: u64) -> Result<(), String> { + if amount > self.funds { + return Err("Insufficient preparation funds".into()); + } + let spent = add(self.stats.funds_spent, amount)?; + let round_spent = add(self.round_spent, amount)?; + self.funds -= amount; + self.stats.funds_spent = spent; + self.round_spent = round_spent; + Ok(()) + } + pub fn earn(&mut self, amount: u64) -> Result<(), String> { + let funds = add(self.funds, amount)?; + let gained = add(self.stats.funds_gained, amount)?; + self.funds = funds; + self.stats.funds_gained = gained; + Ok(()) + } + pub fn start_round(&mut self, income: u64) -> Result<(), String> { + self.round_spent = 0; + self.earn(add(income, self.pending)?)?; + self.pending = 0; + Ok(()) + } + pub fn bounty(&mut self, amount: f64) -> Result<(), String> { + let amount = amount.trunc().max(0.); + if !amount.is_finite() || amount > MAX_FUNDS as f64 { + return Err("Invalid battle bounty total".into()); + } + let pending = add(self.pending, amount as u64)?; + let gained = add(self.stats.funds_gained, amount as u64)?; + self.pending = pending; + self.stats.funds_gained = gained; + Ok(()) + } + pub fn clear(&mut self) { + self.funds = 0; + self.pending = 0; + } +} diff --git a/crates/engine/src/solo/preparation.rs b/crates/engine/src/solo/preparation.rs new file mode 100644 index 0000000..b668073 --- /dev/null +++ b/crates/engine/src/solo/preparation.rs @@ -0,0 +1,1202 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Single-player shop, inventory, bond membership and preparation effects. +use super::map::DeployMap; +use super::{add, player::Player, Operator, PreparedRound, MAX_FUNDS}; +use crate::{ + battle::{direction::Direction, operators::Placement}, + data::Catalog, + deterministic::rng::{derive_seed, Rng}, +}; +use serde_json::{json, Value}; +use std::{ + collections::{BTreeMap, BTreeSet, VecDeque}, + sync::Arc, +}; +mod arts; +mod bonds; +mod bounties; +mod consumables; +mod drafts; +mod effects; +mod equipment; +mod equipment_lifecycle; +mod input; +mod items; +pub use bonds::EffectsConfig; +use effects::{Hook, Meta}; +use items::GainSource; +mod rules; +mod summons; +mod view; +use rules::Rules; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Chess, + Item, + Token, +} +impl Kind { + fn name(self) -> &'static str { + match self { + Self::Chess => "chess", + Self::Item => "item", + Self::Token => "token", + } + } +} +pub struct Grant { + pub kind: Kind, + pub key: String, +} +pub struct Config { + pub mode_id: String, + pub banned: Vec, + pub initial: Vec, + pub capacity: usize, + pub effects: Option, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Destination { + Hand(usize), + Board { + home: [i32; 2], + direction: Direction, + }, +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Action { + Draft(usize), + Choice { + index: usize, + id: String, + }, + Buy(usize), + Refresh, + Freeze, + LevelUp, + Sell(u64), + Destroy(u64), + PickReward(usize), + Move { + uid: u64, + to: Destination, + }, + Equip { + item: u64, + target: u64, + replace: Option, + }, + Unequip(u64), + Art { + item: u64, + tile: [i32; 2], + direction: Direction, + }, +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + BadTarget, + SoldOut, + NoFunds, + HandFull, + BoardFull, + BadTile, + MaxLevel, + Capacity, + Content(String), +} +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::BadTarget => "BAD_TARGET", + Self::SoldOut => "SOLD_OUT", + Self::NoFunds => "NO_FUNDS", + Self::HandFull => "HAND_FULL", + Self::BoardFull => "BOARD_FULL", + Self::BadTile => "BAD_TILE", + Self::MaxLevel => "MAX_LEVEL", + Self::Capacity => "Preparation capacity exceeded", + Self::Content(message) => message, + }) + } +} +#[derive(Clone)] +struct Piece { + uid: u64, + kind: Kind, + key: String, + copies: u64, + count: u64, + owner_uid: Option, + direction: Option, + refresh_seen: u64, + sale_charge: u32, + items: Vec, +} +#[derive(Clone, Copy)] +enum Location { + Hand(usize), + Temp(usize), + Board([i32; 2]), +} +#[derive(Clone)] +struct Slot { + kind: Kind, + key: String, + price: f64, + frozen: bool, + sold: bool, +} +#[derive(Clone)] +struct Offer { + tier: usize, + slots: Vec, +} +#[derive(Clone)] +struct Stock { + cap: i64, + left: i64, + tier: usize, +} +#[derive(Clone, Default)] +struct Counts { + buys: u64, + sells: u64, + refreshes: u64, + merges: u64, + item_merges: u64, + items_equipped: u64, +} +#[derive(Clone, Default)] +struct RoundCounts { + sciurus_bought: bool, + buys: u64, + sells: u64, + refreshes: u64, + gained_chess: u64, + cauldron: BTreeMap, + arts: u64, +} +#[derive(Clone)] +pub(super) struct Preparation { + pub(in crate::solo) sciurus: bool, + rules: Arc, + personal_choice: Option, + draft_effects: drafts::DraftEffects, + bounties: Vec, + meta: Option, + free_refreshes: u64, + grid: Arc, + boss: bool, + deploy_cap: usize, + deploy_min: usize, + round_income: u64, + capacity: usize, + rng: Rng, + uid: u64, + pool: BTreeMap, + debt: BTreeMap, + hand: [Option; 10], + temp: Vec>, + board: BTreeMap<[i32; 2], Piece>, + board_insertion: Vec<[i32; 2]>, + level: usize, + upgrade_price: f64, + frozen: bool, + slots: Vec>, + layout: [usize; 2], + offers: VecDeque, + counts: Counts, + round: RoundCounts, +} +impl Preparation { + pub fn new( + data: Arc, + seed: u32, + config: Config, + grid: DeployMap, + boss: bool, + deploy_cap: usize, + player: &mut Player, + ) -> Result { + if !(15..=4096).contains(&config.capacity) + || config.initial.len() > config.capacity + || config.banned.len() > 4096 + { + return Err("Invalid preparation limits".into()); + } + let meta = config + .effects + .map(|cfg| { + Meta::new( + &data, + &data.table("config").unwrap()["modes"][&config.mode_id], + seed, + cfg, + ) + }) + .transpose()?; + let rules = Arc::new(Rules::load(data, &config.mode_id)?); + let mut banned: BTreeSet<_> = config.banned.into_iter().collect(); + if let Some(meta) = &meta { + for (key, rec) in rules.data.table("chess").unwrap().as_object().unwrap() { + if rec["diyFor"].is_string() + && rec["bonds"].as_array().is_some_and(|bonds| { + !bonds.is_empty() + && bonds.iter().all(|b| { + meta.rules + .bonds + .iter() + .any(|rule| Some(rule.id.as_str()) == b.as_str() && rule.off) + }) + }) + { + banned.insert(key.clone()); + } + } + } + let pool: BTreeMap<_, _> = rules + .chess + .values() + .filter(|c| c.shop && !banned.contains(&c.key) && c.cap.unwrap_or(0) > 0) + .map(|c| { + ( + c.key.clone(), + Stock { + cap: c.cap.unwrap() as i64, + left: c.cap.unwrap() as i64, + tier: c.tier, + }, + ) + }) + .collect(); + let total = pool + .values() + .try_fold(0_u64, |sum, e| add(sum, e.cap as u64))?; + if total > MAX_FUNDS { + return Err("Preparation stock capacity exceeded".into()); + } + let upgrade_price = rules.upgrades[0]; + let mut prep = Self { + sciurus: false, + personal_choice: None, + draft_effects: Default::default(), + bounties: Vec::new(), + rules, + meta, + free_refreshes: 0, + grid: Arc::new(grid), + boss, + deploy_cap, + deploy_min: 0, + round_income: 0, + capacity: config.capacity, + rng: Rng::new(derive_seed(seed, "shop")), + uid: 0, + pool, + debt: BTreeMap::new(), + hand: std::array::from_fn(|_| None), + temp: vec![None; 5], + board: BTreeMap::new(), + board_insertion: Vec::new(), + level: 1, + upgrade_price, + frozen: false, + slots: vec![], + layout: [0, 0], + offers: VecDeque::new(), + counts: Counts::default(), + round: RoundCounts::default(), + }; + prep.recompute_meta(player).map_err(|e| e.to_string())?; + for grant in config.initial { + prep.gain(grant.kind, &grant.key, GainSource::Grant, player) + .map_err(|e| e.to_string())?; + } + Ok(prep) + } + pub fn begin_round( + &mut self, + round: u32, + grid: DeployMap, + boss: bool, + deploy_cap: usize, + player: &mut Player, + defer_prep: bool, + ) -> Result<(), Error> { + self.grid = Arc::new(grid); + self.boss = boss; + self.deploy_cap = deploy_cap.max(self.deploy_min); + self.round = RoundCounts::default(); + if round > 1 { + self.upgrade_price = (self.upgrade_price - 1.).max(0.); + } + for (_, owner) in self.owner_positions() { + self.grant_tokens(owner)?; + } + self.roll(true); + self.frozen = false; + for slot in self.slots.iter_mut().flatten() { + slot.frozen = false; + } + self.evict_illegal()?; + self.meta_begin(round, player, defer_prep) + } + pub fn change_map(&mut self, grid: DeployMap, player: &mut Player) -> Result<(), Error> { + self.grid = Arc::new(grid); + self.evict_illegal()?; + self.recompute_meta(player) + } + fn evict_illegal(&mut self) -> Result<(), Error> { + let mut evicted: Vec<_> = self + .board + .iter() + .filter(|(at, p)| !self.legal(p, **at)) + .map(|(at, _)| *at) + .collect(); + evicted.sort_by_key(|at| (-at[0], at[1])); + for at in evicted { + let Some(piece) = self.remove_board(&at) else { + continue; + }; + if piece.kind == Kind::Chess { + self.remove_tokens(piece.uid); + } + self.stow(piece)?; + } + self.refill(); + Ok(()) + } + pub fn end_prep(&mut self) { + self.meta_combat(); + for slot in &mut self.slots { + if slot.as_ref().is_some_and(|s| s.sold || !s.frozen) { + *slot = None; + } + } + } + // JS Map iteration controls which token UID survives stack recombination. + fn insert_board(&mut self, at: [i32; 2], piece: Piece) { + if !self.board.contains_key(&at) { + self.board_insertion.push(at); + } + self.board.insert(at, piece); + } + fn remove_board(&mut self, at: &[i32; 2]) -> Option { + let piece = self.board.remove(at); + if piece.is_some() { + self.board_insertion.retain(|key| key != at); + } + piece + } + /// Node boardOrder: descending row, then left to right. + fn board_order(&self) -> Vec<([i32; 2], &Piece)> { + let mut board: Vec<_> = self.board.iter().map(|(at, p)| (*at, p)).collect(); + board.sort_by_key(|(at, _)| (-at[0], at[1])); + board + } + /// Bookkeeping only: no merge, callback or deployment ordering implied. + fn pieces(&self) -> impl Iterator { + self.temp + .iter() + .chain(&self.hand) + .flatten() + .chain(self.board.values()) + } + fn locations(&self) -> Vec { + self.temp + .iter() + .enumerate() + .filter_map(|(i, p)| p.as_ref().map(|_| Location::Temp(i))) + .chain( + self.hand + .iter() + .enumerate() + .filter_map(|(i, p)| p.as_ref().map(|_| Location::Hand(i))), + ) + .chain( + self.board_order() + .into_iter() + .map(|(at, _)| Location::Board(at)), + ) + .collect() + } + fn piece(&self, loc: Location) -> &Piece { + match loc { + Location::Hand(i) => self.hand[i].as_ref().unwrap(), + Location::Temp(i) => self.temp[i].as_ref().unwrap(), + Location::Board(at) => &self.board[&at], + } + } + fn piece_mut(&mut self, loc: Location) -> &mut Piece { + match loc { + Location::Hand(i) => self.hand[i].as_mut().unwrap(), + Location::Temp(i) => self.temp[i].as_mut().unwrap(), + Location::Board(at) => self.board.get_mut(&at).unwrap(), + } + } + fn take(&mut self, loc: Location) -> Piece { + match loc { + Location::Hand(i) => self.hand[i].take().unwrap(), + Location::Temp(i) => self.temp[i].take().unwrap(), + Location::Board(at) => self.remove_board(&at).unwrap(), + } + } + fn put(&mut self, loc: Location, piece: Piece) { + match loc { + Location::Hand(i) => self.hand[i] = Some(piece), + Location::Temp(i) => self.temp[i] = Some(piece), + Location::Board(at) => { + self.insert_board(at, piece); + } + } + } + fn find(&self, uid: u64) -> Option { + // UIDs are unique; lookup does not need board reading order. + self.temp + .iter() + .position(|p| p.as_ref().is_some_and(|p| p.uid == uid)) + .map(Location::Temp) + .or_else(|| { + self.hand + .iter() + .position(|p| p.as_ref().is_some_and(|p| p.uid == uid)) + .map(Location::Hand) + }) + .or_else(|| { + self.board + .iter() + .find(|(_, p)| p.uid == uid) + .map(|(at, _)| Location::Board(*at)) + }) + } + fn free_hand(&self) -> Option { + self.hand.iter().rposition(Option::is_none) + } + fn len(&self) -> usize { + self.pieces().map(|p| 1 + p.items.len()).sum() + } + fn stow(&mut self, piece: Piece) -> Result<(), Error> { + if let Some(i) = self.free_hand() { + self.hand[i] = Some(piece); + return Ok(()); + } + if self.len() >= self.capacity { + return Err(Error::Capacity); + } + if self.temp.len() <= 5 { + if let Some(i) = self.temp.iter().rposition(Option::is_none) { + self.temp[i] = Some(piece); + return Ok(()); + } + } + self.temp.push(Some(piece)); + Ok(()) + } + fn refill(&mut self) { + for j in (0..5).rev().chain(5..self.temp.len()) { + if self.temp[j].is_some() { + let Some(i) = self.free_hand() else { break }; + self.hand[i] = self.temp[j].take(); + } + } + if self.temp.len() > 5 { + let pending = (0..5) + .rev() + .chain(5..self.temp.len()) + .filter_map(|i| self.temp[i].take()) + .collect::>(); + self.temp = vec![None; 5]; + for (i, piece) in pending.into_iter().enumerate() { + if i < 5 { + self.temp[4 - i] = Some(piece); + } else { + self.temp.push(Some(piece)); + } + } + } + } + fn legal(&self, piece: &Piece, home: [i32; 2]) -> bool { + match piece.kind { + Kind::Chess => self + .grid + .can_place(&self.rules.data.table("chess").unwrap()[&piece.key], home), + Kind::Token => self.token_legal(piece, home), + Kind::Item => false, + } + } + fn stock_take(&mut self, key: &str, n: u64) -> u64 { + if let Some(e) = self.pool.get_mut(key) { + e.left -= n as i64; + n + } else { + 0 + } + } + fn return_copies(&mut self, piece: &Piece) { + if let Some(e) = self.pool.get_mut(&self.rules.chess[&piece.key].base) { + e.left = (e.left + piece.copies as i64).min(e.cap); + } + } + fn item_left(&self, key: &str) -> Option { + let card = &self.rules.items[key]; + let cap = card.cap?; + let held = self + .pieces() + .flat_map(|p| std::iter::once(p).chain(&p.items)) + .filter(|p| p.kind == Kind::Item && self.rules.items[&p.key].base == card.base) + .map(|p| self.rules.items[&p.key].copies) + .sum(); + Some(cap.saturating_sub(held)) + } + fn item_available(&self, key: &str) -> bool { + self.item_left(key) + .is_none_or(|left| left >= self.rules.items[key].copies) + } + fn release_item(&mut self, piece: &Piece) { + let card = &self.rules.items[&piece.key]; + if let Some(debt) = self.debt.get_mut(&card.base) { + *debt = debt.saturating_sub(card.copies); + if *debt == 0 { + self.debt.remove(&card.base); + } + } + } + fn new_piece(&mut self, kind: Kind, key: &str, copies: u64) -> Result { + self.uid = add(self.uid, 1).map_err(|_| Error::Capacity)?; + Ok(Piece { + uid: self.uid, + kind, + key: key.into(), + copies, + count: 1, + owner_uid: None, + direction: None, + refresh_seen: 0, + sale_charge: 0, + items: Vec::new(), + }) + } + fn gain( + &mut self, + kind: Kind, + key: &str, + source: GainSource, + player: &mut Player, + ) -> Result, Error> { + let card = self.rules.card(kind, key).ok_or(Error::BadTarget)?; + let displayed = matches!(source, GainSource::Displayed); + let unlimited = + matches!(source, GainSource::FixedGift) && self.rules.fixed_gifts.contains(&card.base); + if kind == Kind::Item && !displayed && !unlimited && !self.item_available(key) { + return Ok(None); + } + let (base, upgrade, need, golden_copies) = ( + card.base.clone(), + card.upgrade.clone(), + card.merge, + card.copies, + ); + let matches: Vec<_> = self + .locations() + .into_iter() + .filter(|loc| { + let p = self.piece(*loc); + p.kind == kind && p.key == key + }) + .collect(); + let deferred = kind == Kind::Item && self.meta.as_ref().is_some_and(|m| m.defer_items > 0); + let count = if kind == Kind::Item { + self.item_locations(key).len() + } else { + matches.len() + }; + let merges = !deferred && need > 1 && count + 1 >= need; + if !merges && self.len() >= self.capacity { + return Err(Error::Capacity); + } + if merges && kind == Kind::Chess && self.offers.len() >= self.capacity { + return Err(Error::Capacity); + } + let left = if kind == Kind::Item { + self.item_left(key) + } else { + None + }; + let copies = if kind == Kind::Chess { + self.stock_take(&base, golden_copies) + } else { + 0 + }; + let incoming = self.new_piece(kind, key, copies)?; + if kind == Kind::Chess { + self.round.gained_chess = + add(self.round.gained_chess, 1).map_err(|_| Error::Capacity)?; + } + let owned = if merges && kind == Kind::Item { + self.merge_items(key, Some(incoming), player)? + } else if merges { + let mut copies = incoming.copies; + let mut tiles = Vec::new(); + let mut returned = Vec::new(); + for loc in matches.into_iter().take(need - 1) { + let mut p = self.take(loc); + self.remove_tokens(p.uid); + returned.append(&mut p.items); + self.record_refresh_merge(&p); + copies += p.copies; + if let Location::Board(at) = loc { + tiles.push((at, p.direction)); + } + } + let key = upgrade.unwrap(); + if kind == Kind::Chess { + let extra = self.rules.chess[&key].copies.saturating_sub(copies); + copies += self.stock_take(&base, extra); + } + let mut elite = self.new_piece(kind, &key, copies)?; + let uid = elite.uid; + tiles.sort_by_key(|(at, _)| (at[1], -at[0])); + if let Some((at, dir)) = tiles.into_iter().find(|(at, _)| self.legal(&elite, *at)) { + elite.direction = dir; + self.insert_board(at, elite); + } else { + self.stow(elite)?; + } + for item in returned { + self.stow(item)?; + } + self.check_item_merges(player)?; + if self.board.values().any(|p| p.uid == uid) { + self.grant_tokens(uid)?; + } + self.counts.merges = add(self.counts.merges, 1).map_err(|_| Error::Capacity)?; + self.reward(); + uid + } else { + let uid = incoming.uid; + self.stow(incoming)?; + uid + }; + if displayed && kind == Kind::Item { + if let Some(left) = left { + let shortfall = golden_copies.saturating_sub(left); + if shortfall > 0 { + let debt = self.debt.entry(base).or_default(); + *debt = add(*debt, shortfall).map_err(|_| Error::Capacity)?; + } + } + } + if merges && kind == Kind::Chess { + self.dispatch_meta(Hook::Merge, None, player)?; + } + self.refill(); + self.recompute_meta(player)?; + let piece = (kind == Kind::Chess).then(|| self.piece(self.find(owned).unwrap()).clone()); + if piece.is_some() { + self.cauldron_gain(player)?; + } + self.dispatch_meta(Hook::Gain, piece, player)?; + self.refill(); + self.recompute_meta(player)?; + Ok(Some(owned)) + } + // Shared stock is sampled first, then the seat's DIY stock in pick order. + // In solo both have the same accounting owner, so take/give use the key map. + fn stock_entries(&self) -> impl Iterator { + self.pool + .iter() + .filter(|(key, _)| self.rules.data.table("chess").unwrap()[*key]["isDiy"] != true) + .chain( + self.rules + .data + .table("diy") + .and_then(Value::as_object) + .into_iter() + .flat_map(|picks| picks.keys()) + .filter_map(|key| self.pool.get_key_value(key)), + ) + } + fn roll_chess( + &mut self, + max_tier: usize, + tier: Option, + exclude: &[String], + ) -> Option { + let eligible: Vec<_> = self + .stock_entries() + .filter(|(key, e)| { + e.left > 0 + && tier.map_or(e.tier <= max_tier, |t| e.tier == t) + && !exclude.contains(key) + }) + .map(|(key, e)| (key.clone(), e.left as f64)) + .collect(); + let weights: Vec<_> = eligible.iter().map(|(_, w)| *w).collect(); + self.rng.weighted(&weights).map(|i| eligible[i].0.clone()) + } + fn roll_item(&mut self) -> Option { + let mut counts = BTreeMap::::new(); + let mut total = 0_u64; + for e in self + .pool + .iter() + .filter(|(key, _)| self.rules.data.table("chess").unwrap()[*key]["isDiy"] != true) + .map(|(_, e)| e) + .filter(|e| e.left > 0 && e.tier <= self.level) + { + *counts.entry(e.tier).or_default() += e.left as u64; + total += e.left as u64; + } + let tier = if total > 0 { + let mut r = self.rng.next_f64(); + let mut picked = *counts.keys().next_back().unwrap(); + for (tier, n) in counts { + r -= n as f64 / total as f64; + if r < 0. { + picked = tier; + break; + } + } + picked + } else { + 1 + self.rng.int(self.level as u32) as usize + }; + for t in (1..=tier).rev().chain(tier + 1..=6) { + let list: Vec<_> = self + .rules + .items + .values() + .filter(|c| c.shop && c.tier == t && self.item_available(&c.key)) + .map(|c| c.key.clone()) + .collect(); + if !list.is_empty() { + return self.rng.pick(&list).cloned(); + } + } + None + } + fn roll(&mut self, keep: bool) { + let old = std::mem::take(&mut self.slots); + let layout = self.rules.slots[self.level - 1]; + for (kind, start, n) in [ + (Kind::Chess, 0, layout[0]), + (Kind::Item, self.layout[0], layout[1]), + ] { + for i in 0..n { + let previous = if i < self.layout[if kind == Kind::Chess { 0 } else { 1 }] { + old.get(start + i) + .and_then(Option::as_ref) + .filter(|s| keep && s.kind == kind && s.frozen && !s.sold) + .cloned() + } else { + None + }; + let slot = previous.or_else(|| { + let key = if kind == Kind::Chess { + self.roll_chess(self.level, None, &[]) + } else { + self.roll_item() + }?; + Some(Slot { + kind, + price: self.rules.card(kind, &key).unwrap().price, + key, + frozen: self.frozen, + sold: false, + }) + }); + self.slots.push(slot); + } + } + self.layout = layout; + } + fn reward(&mut self) { + let tier = (self.level as i64 + self.rules.reward_offset) + .min(self.rules.reward_max_tier as i64) + .max(0) as usize; + let mut keys = Vec::new(); + for _ in 0..self.rules.reward_count { + for t in (1..=tier).rev() { + if let Some(key) = self.roll_chess(6, Some(t), &keys) { + keys.push(key); + break; + } + } + } + if !keys.is_empty() { + self.offers.push_back(Offer { + tier, + slots: keys + .into_iter() + .map(|key| Slot { + kind: Kind::Chess, + key, + price: self.rules.reward_price, + frozen: false, + sold: false, + }) + .collect(), + }); + } + } + fn charge(&mut self, account: &mut Player, price: f64) -> Result<(), Error> { + if (account.funds as f64) < price { + return Err(Error::NoFunds); + } + let price = price.trunc().max(0.) as u64; + account.spend(price).map_err(|_| Error::Capacity)?; + Ok(()) + } + pub fn act(&mut self, action: Action, account: &mut Player) -> Result<(), Error> { + match action { + Action::Draft(_) => return Err(Error::BadTarget), + Action::Choice { index, id } => self.pick_bounty(index, &id)?, + Action::Art { + item, + tile, + direction, + } => self.use_art(item, tile, direction, account)?, + Action::Buy(i) => { + let slot = self + .slots + .get(i) + .and_then(Option::as_ref) + .ok_or(Error::BadTarget)? + .clone(); + if slot.sold { + return Err(Error::SoldOut); + } + let price = if slot.kind == Kind::Chess { + self.meta_price(&slot.key, slot.price)? + } else { + slot.price.round().max(0.) + }; + if (account.funds as f64) < price { + return Err(Error::NoFunds); + } + if self.free_hand().is_none() { + return Err(Error::HandFull); + } + self.charge(account, price)?; + if slot.kind == Kind::Chess + && self.own_bonds(&slot.key).iter().any(|b| b == "kjeragShip") + { + self.round.sciurus_bought = true; + } + self.slots[i].as_mut().unwrap().sold = true; + let purchased = self.gain(slot.kind, &slot.key, GainSource::Displayed, account)?; + self.counts.buys = add(self.counts.buys, 1).map_err(|_| Error::Capacity)?; + self.round.buys = add(self.round.buys, 1).map_err(|_| Error::Capacity)?; + self.dispatch_meta(Hook::Buy, None, account)?; + self.upgrade_purchase(purchased, slot.kind, account)?; + } + Action::PickReward(i) => { + let slot = self + .offers + .front() + .and_then(|o| o.slots.get(i)) + .ok_or(Error::BadTarget)? + .clone(); + if slot.sold { + return Err(Error::SoldOut); + } + if self.free_hand().is_none() { + return Err(Error::HandFull); + } + self.charge(account, slot.price.trunc().max(0.))?; + self.offers.pop_front(); + self.gain(slot.kind, &slot.key, GainSource::Displayed, account)?; + } + Action::Refresh => { + if self.free_refreshes > 0 { + self.free_refreshes -= 1; + } else { + self.charge(account, self.rules.refresh)?; + } + self.frozen = false; + self.roll(false); + self.counts.refreshes = + add(self.counts.refreshes, 1).map_err(|_| Error::Capacity)?; + self.round.refreshes = add(self.round.refreshes, 1).map_err(|_| Error::Capacity)?; + self.dispatch_meta(Hook::Refresh, None, account)?; + } + Action::Freeze => { + self.frozen = !self.frozen; + for slot in self.slots.iter_mut().flatten().filter(|s| !s.sold) { + slot.frozen = self.frozen; + } + } + Action::LevelUp => { + if self.level >= self.rules.slots.len() { + return Err(Error::MaxLevel); + } + self.charge(account, self.upgrade_price)?; + self.level += 1; + self.upgrade_price = self.rules.upgrades[self.level - 1]; + let layout = self.rules.slots[self.level - 1]; + let mut slots = std::mem::take(&mut self.slots); + let mut items = slots.split_off(self.layout[0]); + slots.resize(layout[0].max(slots.len()), None); + items.resize(layout[1].max(items.len()), None); + self.layout = [slots.len(), items.len()]; + slots.extend(items); + self.slots = slots; + self.dispatch_meta(Hook::LevelUp, None, account)?; + } + Action::Sell(uid) => { + let loc = self.find(uid).ok_or(Error::BadTarget)?; + if self.piece(loc).kind != Kind::Chess { + return Err(Error::BadTarget); + } + let mut piece = self.take(loc); + self.remove_tokens(piece.uid); + for item in piece.items.drain(..) { + self.stow(item)?; + } + self.return_copies(&piece); + self.dispatch_meta(Hook::Sold, Some(piece.clone()), account)?; + self.equipment_event(equipment_lifecycle::Event::Sold, account)?; + account + .earn(self.rules.chess[&piece.key].sell) + .map_err(|_| Error::Capacity)?; + self.counts.sells = add(self.counts.sells, 1).map_err(|_| Error::Capacity)?; + self.round.sells = add(self.round.sells, 1).map_err(|_| Error::Capacity)?; + self.check_item_merges(account)?; + self.refill(); + } + Action::Destroy(uid) => { + let loc = self.find(uid).ok_or(Error::BadTarget)?; + if self.piece(loc).kind != Kind::Item { + return Err(Error::BadTarget); + } + let piece = self.take(loc); + self.release_item(&piece); + self.destroy_art(&piece, account)?; + self.refill(); + } + Action::Move { uid, to } => self.move_piece(uid, to)?, + Action::Equip { + item, + target, + replace, + } => self.equip(item, target, replace, account)?, + Action::Unequip(_) => return Err(Error::BadTarget), + } + self.recompute_meta(account) + } + fn move_chess_or_item(&mut self, uid: u64, to: Destination) -> Result<(), Error> { + let from = self.find(uid).ok_or(Error::BadTarget)?; + match to { + Destination::Hand(i) => { + if i >= 10 { + return Err(Error::BadTarget); + } + if matches!(from,Location::Hand(j) if i==j) { + return Ok(()); + } + if let (Location::Board(at), Some(other)) = (from, &self.hand[i]) { + if other.kind == Kind::Chess { + if !self.legal(other, at) { + return Err(Error::BadTile); + } + } else { + let free = self.free_hand().ok_or(Error::HandFull)?; + self.hand[free] = Some(self.take(from)); + self.refill(); + return Ok(()); + } + } + let piece = self.take(from); + if let Some(mut other) = self.hand[i].take() { + if matches!(from, Location::Board(_)) { + other.direction = Some(piece.direction.unwrap_or(Direction::Right)); + } + self.put(from, other); + } + self.hand[i] = Some(piece); + } + Destination::Board { home, direction } => { + if self.piece(from).kind != Kind::Chess { + return Err(Error::BadTarget); + } + if !self.legal(self.piece(from), home) { + return Err(Error::BadTile); + } + if let Location::Board(at) = from { + if at == home { + self.board.get_mut(&at).unwrap().direction = Some(direction); + return Ok(()); + } + if let Some(other) = self.board.get(&home) { + if !(other.kind == Kind::Token && other.owner_uid == Some(uid)) + && !self.legal(other, at) + { + return Err(Error::BadTile); + } + } + } else if self.board.get(&home).is_none_or(|p| p.kind != Kind::Chess) + && self + .board + .values() + .filter(|p| p.kind == Kind::Chess) + .count() + >= self.deploy_cap + { + return Err(Error::BoardFull); + } + let mut piece = self.take(from); + if let Some(other) = self.remove_board(&home) { + if other.kind == Kind::Token && !matches!(from, Location::Board(_)) { + let prefer = match from { + Location::Hand(i) => Some(i), + _ => None, + }; + self.return_token(other, prefer, true)?; + } else { + self.put(from, other); + } + } + piece.direction = Some(direction); + self.insert_board(home, piece); + } + } + Ok(()) + } + pub fn has_effects(&self) -> bool { + self.meta.is_some() + } + pub(crate) fn battle_map(&self, map: &mut crate::battle::runtime::MapConfig) { + let Some(meta) = &self.meta else { + return; + }; + map.top_layers = meta.bonds.values().map(|b| b.layers).fold(0., f64::max); + if map.cold_wind.is_none() { + map.cold_wind = meta.cold_wind(); + } + } + pub(crate) fn battle_bonds(&self) -> Vec { + let Some(meta) = &self.meta else { + return vec![]; + }; + meta.bonds + .iter() + .map(|(id, state)| crate::battle::runtime::BattleBond { + id: id.clone(), + tier: state.tier, + layers: state.layers, + }) + .collect() + } + pub(crate) fn settle_layers( + &mut self, + gains: &[(String, f64)], + player: &mut Player, + ) -> Result<(), String> { + for (id, amount) in gains { + self.add_layers(id, *amount, false, player) + .map_err(|e| e.to_string())?; + } + Ok(()) + } + + pub fn active_layers(&self) -> f64 { + self.meta.as_ref().map_or(0., Meta::active_sum) + } + pub fn check_ready(&self) -> Result<(), String> { + if self.personal_choice.is_some() { + return Err("BAD_TARGET".into()); + } + if self.temp.iter().any(Option::is_some) { + return Err("TEMP_NOT_EMPTY".into()); + } + Ok(()) + } + pub fn deploy_cap(&self) -> usize { + self.deploy_cap + } + pub fn gained_chess(&self) -> u64 { + self.round.gained_chess + } + pub fn prepared(&self, active_layers: f64) -> PreparedRound { + let operators = self + .board_order() + .into_iter() + .filter(|(_, p)| p.kind == Kind::Chess) + .map(|(home, p)| Operator { + key: p.key.clone(), + placement: Placement { + uid: p.uid, + home, + direction: p.direction.unwrap_or(Direction::Right), + }, + skill_index: None, + items: p.items.iter().map(|p| p.key.clone()).collect(), + }) + .collect(); + PreparedRound { + operators, + active_layers, + } + } + pub fn eliminate(&mut self) { + for loc in self.locations() { + let p = self.take(loc); + for item in &p.items { + self.release_item(item); + } + if p.kind == Kind::Chess { + self.return_copies(&p); + } else if p.kind == Kind::Item { + self.release_item(&p); + } + } + self.slots.clear(); + self.offers.clear(); + self.bounties.clear(); + self.personal_choice = None; + let states = self.bond_states(); + if let Some(meta) = &mut self.meta { + meta.bonds = states; + } + } + fn piece_report(p: &Piece) -> Value { + let mut out = json!({"uid":p.uid,"kind":p.kind.name(),"id":p.key,"poolCopies":p.copies,"count":p.count,"ownerUid":p.owner_uid,"dir":p.direction.map(Direction::name)}); + if !p.items.is_empty() { + out["items"] = json!(p.items.iter().map(Self::piece_report).collect::>()); + } + out + } + pub fn report(&self, player: &Player) -> Value { + let piece = Self::piece_report; + let slot = |s: &Slot| json!({"kind":s.kind.name(),"id":s.key,"price":s.price,"frozen":s.frozen,"sold":s.sold}); + let board = self + .board_order() + .into_iter() + .map(|(home, p)| json!({"row":home[0],"col":home[1],"piece":piece(p)})) + .collect::>(); + let mut report = json!({"deployCap":self.deploy_cap,"roundIncome":self.round_income,"rng":self.rng.state(),"uid":self.uid,"level":self.level,"upgradePrice":self.upgrade_price,"frozen":self.frozen,"slots":self.slots.iter().map(|s|s.as_ref().map(&slot)).collect::>(), + "hand":self.hand.iter().map(|p|p.as_ref().map(&piece)).collect::>(),"temp":self.temp.iter().map(|p|p.as_ref().map(&piece)).collect::>(),"board":board, + "offers":self.offers.iter().map(|o|json!({"tier":o.tier,"slots":o.slots.iter().map(&slot).collect::>()})).collect::>(), + "personalChoice":self.personal_choice.as_ref().map(bounties::Choice::report),"bounties":self.bounties.iter().map(bounties::Bounty::report).collect::>(), + "pool":self.pool.iter().map(|(key,e)|(key.clone(),json!({"cap":e.cap,"left":e.left.max(0),"rawLeft":e.left}))).collect::>(),"itemDebt":self.debt, + "stats":{"buys":self.counts.buys,"sells":self.counts.sells,"refreshes":self.counts.refreshes,"merges":self.counts.merges,"itemMerges":self.counts.item_merges,"itemsEquipped":self.counts.items_equipped}, + "round":{"buys":self.round.buys,"sells":self.round.sells,"refreshes":self.round.refreshes,"spent":player.round_spent,"gainedChess":self.round.gained_chess,"arts":self.round.arts}}); + if self.draft_effects.sequence > 0 { + report["draftEffects"] = json!({"sequence":self.draft_effects.sequence,"upgrades":self.draft_effects.upgrades.iter().map(|u|json!({"id":u.id,"kind":u.kind.name(),"left":u.left})).collect::>()}); + } + if !self.draft_effects.battle.is_empty() { + report["draftEffects"]["battle"] = json!(self + .draft_effects + .battle + .iter() + .map(|(id, seq)| json!({"effectId":id,"sequence":seq})) + .collect::>()); + } + if let Some(meta) = &self.meta { + report["effects"] = meta.report(self.free_refreshes); + } + report + } +} diff --git a/crates/engine/src/solo/preparation/arts.rs b/crates/engine/src/solo/preparation/arts.rs new file mode 100644 index 0000000..e36b28b --- /dev/null +++ b/crates/engine/src/solo/preparation/arts.rs @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Tile-targeted preparation actions. The caller commits only a successful draft. +use super::*; +impl Preparation { + pub(super) fn use_art( + &mut self, + uid: u64, + tile: [i32; 2], + direction: Direction, + player: &mut Player, + ) -> Result<(), Error> { + let loc = self.find(uid).ok_or(Error::BadTarget)?; + let item = self.piece(loc).clone(); + let raw = &self.rules.data.table("items").unwrap()[&item.key]; + if item.kind != Kind::Item || raw["itemType"] != "MAGIC" { + return Err(Error::BadTarget); + } + if !(9..=12).contains(&tile[0]) || !(2..=10).contains(&tile[1]) { + return Err(Error::BadTile); + } + let limit = self.rules.data.table("config").unwrap()["economy"]["maxArtsPerRound"] + .as_u64() + .filter(|n| *n > 0) + .unwrap_or(2); + if self.round.arts >= limit { + return Err(Error::BadTarget); + } + if self.meta.is_none() { + return Err(Error::Content("Arts require preparation effects".into())); + } + let buffs = raw["buffs"] + .as_array() + .ok_or_else(|| Error::Content("Missing art effects".into()))?; + if buffs.iter().any(|b| b["key"] == "trap_create_self_choice") + && buffs.iter().all(|b| { + matches!( + b["key"].as_str(), + Some("trap_create_self_choice" | "trap_disney_special") + ) + }) + { + self.bounty_art(&item.key)?; + } else if buffs.len() == 1 && buffs[0]["key"] == "trap_copy_front_char" { + let default = vec![json!([0, 0])]; + let range = raw["rangeGrid"] + .as_array() + .filter(|a| !a.is_empty()) + .unwrap_or(&default); + if range.len() > self.capacity { + return Err(Error::Capacity); + } + let mut target = None; + for offset in range { + let r = offset[0] + .as_i64() + .and_then(|v| i32::try_from(v).ok()) + .ok_or(Error::BadTarget)?; + let c = offset[1] + .as_i64() + .and_then(|v| i32::try_from(v).ok()) + .ok_or(Error::BadTarget)?; + if r == i32::MIN || c == i32::MIN { + return Err(Error::BadTarget); + } + let [dr, dc] = direction.rotate([r, c]); + let at = [ + tile[0].checked_add(dr).ok_or(Error::BadTarget)?, + tile[1].checked_add(dc).ok_or(Error::BadTarget)?, + ]; + if let Some(p) = self.board.get(&at).filter(|p| p.kind == Kind::Chess) { + target = Some(p.clone()); + break; + } + } + let target = target.ok_or(Error::BadTarget)?; + // Snapshot before acquisition: merging can remove the original carrier and its items. + if self + .gain(Kind::Chess, &target.key, GainSource::Grant, player)? + .is_none() + { + return Err(Error::HandFull); + } + for equipped in target.items { + self.gain(Kind::Item, &equipped.key, GainSource::Grant, player)?; + } + } else { + return Err(Error::Content(format!("Unsupported art: {}", item.key))); + } + if let Some(loc) = self.find(uid) { + self.take(loc); + } + self.release_item(&item); + self.round.arts = add(self.round.arts, 1).map_err(|_| Error::Capacity)?; + self.refill(); + Ok(()) + } +} diff --git a/crates/engine/src/solo/preparation/bonds.rs b/crates/engine/src/solo/preparation/bonds.rs new file mode 100644 index 0000000..c27913c --- /dev/null +++ b/crates/engine/src/solo/preparation/bonds.rs @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::{Kind, Preparation}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Default)] +pub struct EffectsConfig { + pub disabled_bonds: Vec, + pub layers: BTreeMap, + pub count_bonus: BTreeMap, +} +pub(super) struct Bond { + pub id: String, + pub core: bool, + pub off: bool, + pub mode: Counting, + pub thresholds: Vec, + pub downward: Option, + pub raw: Value, +} +#[derive(Clone, Copy)] +pub(super) enum Counting { + Board, + HandAndBoard, + Elites, +} +#[derive(Clone, Debug, PartialEq)] +pub(super) struct State { + pub count: f64, + pub tier: usize, + pub layers: f64, + pub harmony: u8, +} +impl State { + pub fn active(&self) -> bool { + self.tier > 0 + } +} +impl Bond { + pub fn load(data: &Value, mode: &Value, disabled: &[String]) -> Result, String> { + let table = data.as_object().ok_or("Missing bond definitions")?; + if table.len() > 256 || disabled.len() > 256 { + return Err("Bond definition capacity exceeded".into()); + } + if disabled.iter().any(|id| !table.contains_key(id)) { + return Err("Unknown disabled bond".into()); + } + let mut ids: Vec<_> = table.keys().cloned().collect(); + ids.sort_by(|a, b| { + table[a]["identifier"] + .as_f64() + .unwrap_or(99.) + .total_cmp(&table[b]["identifier"].as_f64().unwrap_or(99.)) + .then(a.cmp(b)) + }); + ids.into_iter() + .map(|id| { + let raw = &table[&id]; + let mut thresholds = raw["thresholds"] + .as_array() + .filter(|a| !a.is_empty()) + .map(|a| { + a.iter() + .filter_map(Value::as_f64) + .filter(|v| v.is_finite()) + .collect::>() + }) + .unwrap_or_else(|| { + vec![raw["activeCount"] + .as_f64() + .filter(|v| v.is_finite()) + .unwrap_or(2.)] + }); + if thresholds.len() > 64 { + return Err("Bond tier capacity exceeded".into()); + } + thresholds.sort_by(f64::total_cmp); + let off = disabled.contains(&id) + || mode["inactiveBondIds"] + .as_array() + .is_some_and(|a| a.iter().any(|v| v == &id)); + let downward = + (raw["thresholdTemplate"] == "count_threshold_downward").then(|| { + raw["maxCount"] + .as_f64() + .filter(|v| v.is_finite()) + .unwrap_or_else(|| thresholds.first().copied().unwrap_or(f64::NAN)) + }); + let mode = if raw["countMode"] == "BOARD_ALL_CHESS" + || raw["thresholdTemplate"] == "count_threshold_upward_golden" + { + Counting::Elites + } else if raw["countMode"] == "BOARD_AND_DECK" { + Counting::HandAndBoard + } else { + Counting::Board + }; + Ok(Self { + id, + core: raw["isCore"] == true, + off, + mode, + thresholds, + downward, + raw: raw.clone(), + }) + }) + .collect() + } + fn tier(&self, count: f64) -> usize { + if let Some(max) = self.downward { + usize::from( + count >= self.thresholds.first().copied().unwrap_or(f64::NAN) && count <= max, + ) + } else { + self.thresholds.iter().filter(|n| count >= **n).count() + } + } + pub fn buff(&self, key: &str) -> Value { + let Some(buff) = self.raw["buffs"] + .as_array() + .and_then(|a| a.iter().find(|b| b["key"] == key)) + else { + return json!({}); + }; + let mut out = buff["bb"].as_object().cloned().unwrap_or_default(); + if let Some(strings) = buff["bbStr"].as_object() { + out.extend(strings.clone()); + } + Value::Object(out) + } +} +impl Preparation { + pub(super) fn own_bonds(&self, key: &str) -> Vec { + self.rules.data.table("chess").unwrap()[key]["bonds"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + } + pub(super) fn piece_bonds(&self, piece: &super::Piece) -> Vec { + let Some(loc) = self.find(piece.uid) else { + return self.own_bonds(&piece.key); + }; + let live = self.piece(loc); + let items: Vec<_> = live.items.iter().map(|p| p.key.clone()).collect(); + crate::battle::equipment::bonds(&self.rules.data, &live.key, &items) + } + pub(super) fn bond_states(&self) -> BTreeMap { + let Some(meta) = &self.meta else { + return BTreeMap::new(); + }; + let mut board = BTreeMap::>::new(); + let mut variants = BTreeMap::>::new(); + let mut hand = BTreeMap::>::new(); + let mut elites = 0; + for piece in self.board.values() { + if piece.kind != Kind::Chess { + continue; + } + let base = &self.rules.chess[&piece.key].base; + let golden = self.rules.data.table("chess").unwrap()[&piece.key]["isGolden"] == true; + elites += usize::from(golden); + for bond in self.piece_bonds(piece) { + board.entry(bond.clone()).or_default().insert(base.clone()); + variants + .entry(bond) + .or_default() + .insert((base.clone(), golden)); + } + } + for piece in self.hand.iter().flatten().filter(|p| p.kind == Kind::Chess) { + for bond in self.piece_bonds(piece) { + hand.entry(bond) + .or_default() + .insert(self.rules.chess[&piece.key].base.clone()); + } + } + let mut raw = BTreeMap::new(); + for bond in &meta.rules.bonds { + let count = match bond.mode { + Counting::Elites => elites, + Counting::HandAndBoard => board + .get(&bond.id) + .into_iter() + .flatten() + .chain(hand.get(&bond.id).into_iter().flatten()) + .collect::>() + .len(), + Counting::Board => board.get(&bond.id).map_or(0, BTreeSet::len), + }; + raw.insert( + bond.id.clone(), + (count as f64 + f64::from(*meta.bonus.get(&bond.id).unwrap_or(&0))).max(0.), + ); + } + let harmony = meta + .rules + .bonds + .iter() + .find(|b| b.id == "maniShip" && !b.off) + .is_some_and(|b| b.tier(raw[&b.id]) > 0); + let mut out = BTreeMap::new(); + for bond in &meta.rules.bonds { + if bond.off { + continue; + } + let h = u8::from( + harmony && bond.core && board.get(&bond.id).is_some_and(|s| !s.is_empty()), + ); + let count = raw[&bond.id] + f64::from(h); + let mut tier = bond.tier(count); + if bond.id == "deputShip" && tier > 0 { + let count = variants.get(&bond.id).map_or(0, BTreeSet::len) as f64 + + f64::from(*meta.bonus.get(&bond.id).unwrap_or(&0)); + tier = 1; + for (i, n) in bond.thresholds.iter().enumerate().skip(1) { + if count >= *n { + tier = i + 1; + } + } + } + out.insert( + bond.id.clone(), + State { + count, + tier, + layers: *meta.layers.get(&bond.id).unwrap_or(&0.), + harmony: h, + }, + ); + } + out + } +} diff --git a/crates/engine/src/solo/preparation/bounties.rs b/crates/engine/src/solo/preparation/bounties.rs new file mode 100644 index 0000000..f50884b --- /dev/null +++ b/crates/engine/src/solo/preparation/bounties.rs @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +#[derive(Clone)] +pub(super) struct Choice { + id: String, + round: u32, + source: String, + cards: Vec, +} +#[derive(Clone)] +pub(super) struct Bounty { + id: String, + card: Value, + left: u32, +} +impl Choice { + pub(super) fn report(&self) -> Value { + json!({"id":self.id,"round":self.round,"sourceItemId":self.source,"cards":self.cards}) + } +} +impl Bounty { + pub(super) fn report(&self) -> Value { + json!({"id":self.id,"card":self.card,"roundsLeft":self.left}) + } +} +impl Preparation { + pub(super) fn add_bounty(&mut self, card: &Value) -> Result<(), Error> { + if self.bounties.len() >= self.capacity { + return Err(Error::Capacity); + } + let key = card["enemyKey"].as_str().ok_or(Error::BadTarget)?; + if !self.rules.data.table("enemies").unwrap()[key].is_object() { + return Err(Error::BadTarget); + } + let multi = card["multiRound"] == true || card["rounds"].as_f64().is_some_and(|r| r >= 90.); + let rounds = if multi { + 2 + } else { + card["rounds"].as_u64().unwrap_or(1).clamp(1, 99) as u32 + }; + let coin = effects::n(&card["coin"], 0.).trunc().max(0.); + if coin > MAX_FUNDS as f64 { + return Err(Error::Capacity); + } + self.uid = add(self.uid, 1).map_err(|_| Error::Capacity)?; + self.bounties.push(Bounty { id:format!("bounty:{}",self.uid), left:rounds, card:json!({ + "effectId":card.get("effectId").or(card.get("id")), "name":card["name"].as_str().unwrap_or("悬赏"), + "desc":card["desc"].as_str().unwrap_or(""),"tier":card["tier"].as_u64().unwrap_or(1), + "coin":coin as u64,"payout":if card["payout"]=="perfect" {"perfect"} else {"kill"}, + "rounds":rounds,"multiRound":multi,"enemyKey":key,"count":card["count"].as_u64().unwrap_or(1).clamp(1,20) + }) }); + Ok(()) + } + pub(super) fn bounty_art(&mut self, item: &str) -> Result<(), Error> { + let customer = self.rules.data.table("items").unwrap()[item]["buffs"] + .as_array() + .unwrap() + .iter() + .any(|b| b["key"] == "trap_disney_special"); + if !customer && self.personal_choice.is_some() { + return Err(Error::BadTarget); + } + let inactive = &self.rules.data.table("config").unwrap()["modes"][&self.rules.mode_id] + ["inactiveEnemyKeys"]; + let cards = self.rules.data.table("choices").unwrap()["cards"]["bounty"] + .as_array() + .ok_or(Error::BadTarget)?; + if cards.len() > 4096 { + return Err(Error::Capacity); + } + let mut eligible: Vec<_> = cards + .iter() + .filter(|c| { + let family = c["effectId"] + .as_str() + .and_then(|s| s.strip_prefix("enemyeffect_b_")) + .is_some_and(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())); + (if customer { + family + } else { + c["payout"] == "perfect" + }) && c["enemyKey"] + .as_str() + .is_some_and(|k| self.rules.data.table("enemies").unwrap()[k].is_object()) + && !inactive + .as_array() + .is_some_and(|a| a.contains(&c["enemyKey"])) + }) + .cloned() + .collect(); + if customer && eligible.is_empty() { + let perfect = self.rules.data.table("items").unwrap()[item]["desc"] + .as_str() + .is_some_and(|d| d.contains("完美")); + let fallback: Vec<_> = cards + .iter() + .filter(|c| { + c["tier"].as_f64().is_some_and(|n| n <= 2.) + && c["payout"] == if perfect { "perfect" } else { "kill" } + && c["enemyKey"].as_str().is_some_and(|k| { + self.rules.data.table("enemies").unwrap()[k].is_object() + }) + && !inactive + .as_array() + .is_some_and(|a| a.contains(&c["enemyKey"])) + }) + .cloned() + .collect(); + let card = self + .meta + .as_mut() + .unwrap() + .rng + .pick(&fallback) + .cloned() + .ok_or(Error::BadTarget)?; + return self.add_bounty(&card); + } + if eligible.is_empty() { + return Err(Error::BadTarget); + } + self.meta.as_mut().unwrap().rng.shuffle(&mut eligible); + eligible.truncate(3); + if customer { + let card = self + .meta + .as_mut() + .unwrap() + .rng + .pick(&eligible) + .unwrap() + .clone(); + self.add_bounty(&card) + } else { + self.uid = add(self.uid, 1).map_err(|_| Error::Capacity)?; + self.personal_choice = Some(Choice { + id: format!("solo.choice.{}", self.uid), + round: self.meta.as_ref().unwrap().round, + source: item.into(), + cards: eligible, + }); + Ok(()) + } + } + pub(super) fn pick_bounty(&mut self, index: usize, id: &str) -> Result<(), Error> { + let choice = self + .personal_choice + .as_ref() + .filter(|c| c.id == id && self.meta.as_ref().is_some_and(|m| m.round == c.round)) + .ok_or(Error::BadTarget)?; + let card = choice.cards.get(index).ok_or(Error::BadTarget)?.clone(); + self.add_bounty(&card)?; + self.personal_choice = None; + Ok(()) + } + pub(super) fn destroy_art(&mut self, item: &Piece, player: &mut Player) -> Result<(), Error> { + if let Some(buffs) = self.rules.data.table("items").unwrap()[&item.key]["buffs"].as_array() + { + for buff in buffs { + if buff["key"] == "trap_disney_special" { + let n = effects::n( + buff["bbStr"].get("count").unwrap_or(&buff["bb"]["count"]), + 1., + ) + .trunc() + .max(0.); + if n > MAX_FUNDS as f64 { + return Err(Error::Capacity); + } + player.earn(n as u64).map_err(|_| Error::Capacity)?; + } + } + } + Ok(()) + } + pub(in crate::solo) fn settle_bounties(&mut self, perfect: bool) -> Result { + let mut coin = 0u64; + for b in &mut self.bounties { + if perfect && b.card["payout"] == "perfect" { + coin = add(coin, b.card["coin"].as_u64().unwrap())?; + } + b.left -= 1; + } + self.bounties.retain(|b| b.left > 0); + Ok(coin as f64) + } + /// Compile bounty enemies, then let the wave owner insert them into action windows. + pub(in crate::solo) fn append_bounties( + &self, + wave: &mut crate::battle::waves::Template, + round: usize, + boss: bool, + ) -> Result<(), String> { + if wave.spawns.len() + self.bounties.len() > self.capacity { + return Err("Bounty spawn capacity exceeded".into()); + } + let scale = &self.rules.data.table("config").unwrap()["modes"][&self.rules.mode_id] + ["enemyScale"][round.to_string()]; + let mut additions = Vec::new(); + for b in &self.bounties { + let e = + &self.rules.data.table("enemies").unwrap()[b.card["enemyKey"].as_str().unwrap()]; + let fly = e["isFlyEnemy"] + .as_bool() + .unwrap_or(e["stats"]["motion"] == "FLY"); + let motion = |r: &&Value| { + if fly { + r["motion"] == "FLY" + } else { + r["motion"] != "FLY" && r["motion"] != "E_NUM" + } + }; + let route = wave + .routes + .iter() + .enumerate() + .find(|(_, r)| { + motion(r) && (!boss || r["end"][1].as_f64().is_some_and(|x| x < 10.)) + }) + .or_else(|| wave.routes.iter().enumerate().find(|(_, r)| motion(r))) + .map_or(0, |(i, _)| i); + let mut mods = json!({"hpMul":effects::n(&scale["hp"],1.).max(0.01),"atkMul":effects::n(&scale["atk"],1.).max(0.),"speedMul":effects::n(&scale["speed"],1.).max(0.01), + "slot":match (fly,e["rank"]=="ELITE") {(true,true)=>"EF",(true,false)=>"NF",(false,true)=>"E",_=>"N"},"bountyId":b.id}); + let supply = effects::n(&scale["supplyHp"], 1.); + if supply > 0. && supply != 1. { + mods["supplyHpMul"] = json!(supply); + } + let mut spawn = json!({"time":4,"enemyKey":b.card["enemyKey"],"routeIndex":route,"count":b.card["count"],"interval":0,"mods":mods,"tag":"bounty"}); + if b.card["payout"] != "perfect" && b.card["coin"].as_u64().unwrap() > 0 { + spawn["bounty"] = json!({"coins":b.card["coin"]}); + } + additions.push(spawn); + } + wave.insert_bounties(additions, boss, self.capacity) + } +} diff --git a/crates/engine/src/solo/preparation/consumables.rs b/crates/engine/src/solo/preparation/consumables.rs new file mode 100644 index 0000000..d76dc3c --- /dev/null +++ b/crates/engine/src/solo/preparation/consumables.rs @@ -0,0 +1,273 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Consume-on-equip actions. The outer preparation draft makes refusals atomic. +use super::*; +use effects::n; + +pub(super) enum Effect { + Coins { min: u32, max: u32 }, + Layers(f64), + Shop(u32), + Recruit(u32), + Income(u64), + Pending(u64), + Deployment(usize), + Offer { count: u32, sacrifice: bool }, + Mimic, + Promote { delayed: bool }, +} +pub(super) fn compile(data: &Catalog, key: &str) -> Result, Error> { + let raw = &data.table("items").unwrap()[key]; + if !matches!( + raw["kind"].as_str(), + Some("consume_on_equip" | "consume_on_equip_or_delayed") + ) { + return Ok(None); + } + let buffs = raw["buffs"] + .as_array() + .filter(|a| a.len() == 1) + .ok_or_else(|| Error::Content(format!("Unsupported consumable: {key}")))?; + let b = &buffs[0]; + let value = |name: &str| n(b["bbStr"].get(name).unwrap_or(&b["bb"][name]), 0.); + let count = |name: &str| -> Result { + let v = value(name).trunc(); + if !(0. ..=u32::MAX as f64).contains(&v) { + return Err(Error::Content(format!( + "Invalid consumable count: {key}/{name}" + ))); + } + Ok(v as u32) + }; + let effect = match b["key"].as_str().unwrap_or("") { + "equip_destory_gain_random_coin" => { + let min = count("min")?; + let max = count("max")?.max(min); + if max - min == u32::MAX { + return Err(Error::Capacity); + } + Effect::Coins { min, max } + } + "use_equip_reward_char_chess_bond_layer" => Effect::Layers(value("layer")), + "use_equip_reward_random_char_chess_in_shop" => Effect::Shop(count("count")?.max(1)), + "use_equip_reward_char_chess_with_same_bond" => Effect::Recruit(count("count")?.max(1)), + "gain_coin_when_round_start" => Effect::Income(count("count")? as u64), + "use_equip_gain_coin_when_next_round_start" => Effect::Pending(count("count")? as u64), + "equip_destory_deployment_cnt_change" => { + Effect::Deployment(count("count")?.min(12) as usize) + } + "use_equip_reward_special_goods_char_chess" => Effect::Offer { + count: count("refresh_cnt")?.max(1), + sacrifice: false, + }, + "use_equip_recruit_new_char_and_give_char_to_player_most_bond" => Effect::Offer { + count: count("refresh_cnt")?.max(1), + sacrifice: true, + }, + "use_equip_reward_char_chess" => Effect::Mimic, + "use_equip_upgrade_char" => Effect::Promote { delayed: false }, + "equip_round_start_upgrade_char" => Effect::Promote { delayed: true }, + _ => return Err(Error::Content(format!("Unsupported consumable: {key}"))), + }; + Ok(Some(effect)) +} +impl Preparation { + pub(super) fn consume_equipment( + &mut self, + uid: u64, + target: u64, + replace: Option, + effect: Effect, + player: &mut Player, + ) -> Result<(), Error> { + if self.meta.is_none() { + return Err(Error::Content( + "Consumables require preparation effects".into(), + )); + } + if matches!(effect, Effect::Shop(n) | Effect::Recruit(n) | Effect::Offer { count: n, .. } if n as usize > self.capacity) + { + return Err(Error::Capacity); + } + if matches!(effect, Effect::Promote { .. }) + && self.rules.data.table("chess").unwrap()[&self.piece(self.find(target).unwrap()).key] + ["isGolden"] + == true + { + return Err(Error::BadTarget); + } + let keep = matches!(effect, Effect::Promote { delayed: true }); + let item = self.piece(self.find(uid).unwrap()).clone(); + let loc = self.find(target).unwrap(); + let cap = self.rules.equip_cap; + let holder = self.piece_mut(loc); + let off = if holder.items.len() >= cap { + let at = replace.map_or(0, |id| { + holder.items.iter().position(|p| p.uid == id).unwrap() + }); + Some(holder.items.remove(at)) + } else { + None + }; + // The removed slot no longer contributes identity to the effect. + let holder = self.piece(self.find(target).unwrap()).clone(); + let bonds = self.piece_bonds(&holder); + match effect { + Effect::Promote { delayed } => { + if !delayed { + self.promote_equipped_holder(target)?; + } + } + Effect::Offer { count, sacrifice } => { + let tier = self.rules.chess[&holder.key].tier; + if sacrifice { + let mut removed = self.take(self.find(target).unwrap()); + for equipped in removed.items.drain(..) { + self.stow(equipped)?; + } + self.return_copies(&removed); + self.check_item_merges(player)?; + self.recompute_meta(player)?; + } + let mut keys = Vec::new(); + for _ in 0..count { + let picked = if sacrifice { + (1..=tier) + .rev() + .find_map(|t| self.roll_meta_chess(6, 1, Some(t), None, &keys)) + } else { + self.roll_meta_chess(self.level, 1, None, Some(&bonds), &keys) + }; + if let Some(key) = picked { + keys.push(key); + } + } + if !keys.is_empty() { + if self.offers.len() >= self.capacity { + return Err(Error::Capacity); + } + self.offers.push_back(Offer { + tier: if sacrifice { + tier + } else { + (self.level as i64 + self.rules.reward_offset) + .clamp(0, self.rules.reward_max_tier as i64) + as usize + }, + slots: keys + .into_iter() + .take(6) + .map(|key| Slot { + kind: Kind::Chess, + key, + price: self.rules.reward_price, + frozen: false, + sold: false, + }) + .collect(), + }); + } + } + Effect::Mimic => { + let base = self.rules.chess[&holder.key].base.clone(); + let owned = self + .chess_locations() + .into_iter() + .filter(|loc| self.piece(*loc).key == base) + .count(); + let key = if owned >= 2 { + Some(base) + } else { + let eligible: Vec<_> = self + .pool + .keys() + .filter(|key| self.own_bonds(key).iter().any(|b| bonds.contains(b))) + .cloned() + .collect(); + let weights = vec![1.; eligible.len()]; + self.meta + .as_mut() + .unwrap() + .rng + .weighted(&weights) + .map(|i| eligible[i].clone()) + }; + if let Some(key) = key { + self.gain(Kind::Chess, &key, GainSource::Grant, player)?; + } + } + Effect::Coins { min, max } => { + let amount = min + self.meta.as_mut().unwrap().rng.int(max - min + 1); + player.earn(amount as u64).map_err(|_| Error::Capacity)?; + } + Effect::Layers(amount) => { + for bond in bonds { + self.add_layers(&bond, amount, false, player)?; + } + } + Effect::Shop(count) => { + let mut tried = BTreeSet::new(); + let mut granted = 0; + while granted < count { + let choices: Vec<_> = self + .slots + .iter() + .enumerate() + .filter(|(i, slot)| { + !tried.contains(i) + && slot + .as_ref() + .is_some_and(|s| s.kind == Kind::Chess && !s.sold) + }) + .map(|(i, _)| i) + .collect(); + let Some(index) = self.meta.as_mut().unwrap().rng.pick(&choices).copied() + else { + break; + }; + let key = self.slots[index].as_ref().unwrap().key.clone(); + if self.grant_recruit(&key, player)? { + self.slots[index] = None; + granted += 1; + } else { + tried.insert(index); + } + } + } + Effect::Recruit(count) => { + for _ in 0..count { + if let Some(key) = + self.roll_meta_chess(self.level.clamp(1, 6), 1, None, Some(&bonds), &[]) + { + self.grant_recruit(&key, player)?; + } + } + } + Effect::Income(amount) => { + self.round_income = add(self.round_income, amount).map_err(|_| Error::Capacity)? + } + Effect::Pending(amount) => { + player.pending = add(player.pending, amount).map_err(|_| Error::Capacity)? + } + Effect::Deployment(min) => { + self.deploy_min = self.deploy_min.max(min); + self.deploy_cap = self.deploy_cap.max(self.deploy_min); + } + } + if let Some(off) = off { + self.release_item(&off); + } + if let Some(loc) = self.find(uid) { + self.take(loc); + } + if keep { + self.piece_mut(self.find(target).unwrap()).items.push(item); + } else { + self.release_item(&item); + } + self.counts.items_equipped = + add(self.counts.items_equipped, 1).map_err(|_| Error::Capacity)?; + self.check_item_merges(player)?; + self.refill(); + Ok(()) + } +} diff --git a/crates/engine/src/solo/preparation/drafts.rs b/crates/engine/src/solo/preparation/drafts.rs new file mode 100644 index 0000000..84d271d --- /dev/null +++ b/crates/engine/src/solo/preparation/drafts.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::{battle::runtime::MapConfig, solo::draft}; +#[derive(Clone, Default)] +pub(super) struct DraftEffects { + pub sequence: u64, + pub upgrades: Vec, + pub battle: Vec<(String, u64)>, + pub maps: Vec<(String, u64)>, +} +#[derive(Clone)] +pub(super) struct Upgrade { + pub id: String, + pub kind: Kind, + pub left: u64, +} +impl Preparation { + pub(super) fn upgrade_purchase( + &mut self, + uid: Option, + kind: Kind, + player: &mut Player, + ) -> Result<(), Error> { + let Some(uid) = uid else { + return Ok(()); + }; + for i in 0..self.draft_effects.upgrades.len() { + if self.draft_effects.upgrades[i].kind != kind { + continue; + } + let Some(loc) = self.find(uid) else { + break; + }; + let piece = self.piece(loc); + let table = if kind == Kind::Chess { + "chess" + } else { + "items" + }; + if self.rules.data.table(table).unwrap()[&piece.key]["isGolden"] == true { + break; + } + let Some(upgrade) = self + .rules + .card(kind, &piece.key) + .and_then(|c| c.upgrade.clone()) + else { + break; + }; + if kind == Kind::Item { + // The purchased normal already owns one copy. No overdraw for + // this extra copy: retain the charge until stock permits it. + if self.item_left(&piece.key).is_some_and(|n| n < 1) { + break; + } + self.piece_mut(loc).key = upgrade; + } else { + self.promote_equipped_holder(uid)?; + } + self.draft_effects.upgrades[i].left -= 1; + self.recompute_meta(player)?; + // Later refs see the same purchased piece, now golden, and keep their charge. + break; + } + self.draft_effects.upgrades.retain(|u| u.left > 0); + Ok(()) + } + pub(in crate::solo) fn battle_choices(&self) -> Vec { + let bench_units = self.hand.iter().chain(&self.temp).flatten().count(); + self.draft_effects + .battle + .iter() + .map(|(id, sequence)| crate::battle::runtime::BattleChoice { + effect_id: id.clone(), + sequence: *sequence, + bench_units, + }) + .collect() + } + pub(in crate::solo) fn draft_mode(&self) -> &str { + &self.rules.mode_id + } + pub(in crate::solo) fn draw_draft( + &self, + rng: &mut Rng, + stage: &str, + round: u32, + ) -> Result, String> { + let bond_available = |id: &str| { + self.meta + .as_ref() + .is_some_and(|m| m.rules.bonds.iter().any(|b| b.id == id && !b.off)) + && self + .pool + .keys() + .any(|key| self.own_bonds(key).iter().any(|b| b == id)) + }; + draft::generate( + &self.rules.data, + rng, + &draft::Context { + mode: &self.rules.mode_id, + stage: Some(stage), + round, + bond_available: &bond_available, + item_available: &|id| self.item_available(id), + }, + ) + } + pub(in crate::solo) fn apply_draft( + &mut self, + card: &Value, + map: &mut MapConfig, + player: &mut Player, + ) -> Result<(), Error> { + let id = card["id"].as_str().ok_or(Error::BadTarget)?; + match card["kind"].as_str() { + Some("item") => { + self.gain(Kind::Item, id, GainSource::Grant, player)?; + } + Some("bounty") => { + let record = self.rules.data.table("choices").unwrap()["cards"]["bounty"] + .as_array() + .and_then(|a| a.iter().find(|c| c["effectId"] == id)) + .ok_or(Error::BadTarget)? + .clone(); + self.add_bounty(&record)?; + } + Some("tactic") => { + let buffs = self.rules.data.table("effects").unwrap()[id]["buffs"] + .as_array() + .ok_or(Error::BadTarget)? + .clone(); + let mut changes_map = false; + let mut battle = false; + for buff in buffs { + let count = effects::n(&buff["bb"]["count"], 1.).trunc().max(0.); + if count < 0. || count > MAX_FUNDS as f64 { + return Err(Error::Capacity); + } + match buff["key"].as_str() { + Some("auto_chess_change_map") => changes_map = true, + Some( + "env_gbuff_new" + | "env_gbuff_new_with_verify" + | "char_respawntime_mul" + | "global_special_choice_prep_finish_bench_at_least" + | "global_special_choice_prep_finish_bench_at_most" + | "global_special_choice_prep_finish_same_row_at_least", + ) => battle = true, + Some( + "single_special_choice_gloden_equip_chess" + | "single_special_choice_gloden_char_chess", + ) => { + let count = count.trunc() as u64; + if count > 0 { + if self.draft_effects.upgrades.len() + + self.draft_effects.battle.len() + >= self.capacity + { + return Err(Error::Capacity); + } + let kind = + if buff["key"] == "single_special_choice_gloden_equip_chess" { + Kind::Item + } else { + Kind::Chess + }; + self.draft_effects.sequence = add(self.draft_effects.sequence, 1) + .map_err(|_| Error::Capacity)?; + self.draft_effects.upgrades.push(Upgrade { + id: format!("choice:{id}#{}", self.draft_effects.sequence), + kind, + left: count, + }); + } + } + Some("global_special_choice_gain_equip") => { + for _ in 0..count.min(32.).ceil() as usize { + let pool = buff["bbStr"]["pool"].as_str(); + let valid = pool.is_some_and(|id| { + self.rules.data.table("choices").unwrap()["pools"][id]["kind"] + == "equip" + }); + let mut key = if valid { + self.roll_meta_item(pool, 6, false)? + } else { + None + }; + if key.is_none() { + let items: Vec<_> = self + .rules + .items + .values() + .filter(|c| { + c.shop && c.tier == 1 && self.item_available(&c.key) + }) + .map(|c| c.key.clone()) + .collect(); + key = self.meta.as_mut().unwrap().rng.pick(&items).cloned(); + } + if let Some(key) = key { + self.gain(Kind::Item, &key, GainSource::Grant, player)?; + } + } + } + Some("single_special_choice_gain_bond_chess") => { + let bond = buff["bbStr"]["bond"] + .as_str() + .ok_or(Error::BadTarget)? + .to_owned(); + for _ in 0..count.min(32.).ceil() as usize { + let bonds = [bond.clone()]; + let key = self + .roll_meta_chess(self.level.max(1), 1, None, Some(&bonds), &[]) + .or_else(|| { + self.roll_meta_chess(6, 1, None, Some(&bonds), &[]) + }); + if let Some(key) = key { + self.grant_recruit(&key, player)?; + } + } + } + Some("global_special_choice_bond_addlayer") => { + for bond in buff["bbStr"]["bond_list"] + .as_str() + .unwrap_or("") + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + { + self.add_layers(bond, count, false, player)?; + } + } + Some("global_special_choice_gain_coin") => { + player.earn(count as u64).map_err(|_| Error::Capacity)? + } + Some("global_special_choice_refresh_free") => { + self.free_refreshes = add(self.free_refreshes, count as u64) + .map_err(|_| Error::Capacity)? + } + Some("global_special_choice_all_activated") => (), + _ => { + return Err(Error::Content(format!( + "Draft effect not implemented: {id}: {}", + buff["key"] + ))) + } + } + } + if battle { + if self.draft_effects.battle.len() + self.draft_effects.upgrades.len() + >= self.capacity + { + return Err(Error::Capacity); + } + let sequence = + add(self.draft_effects.sequence, 1).map_err(|_| Error::Capacity)?; + crate::battle::runtime::BattleChoice { + effect_id: id.into(), + sequence, + bench_units: 0, + } + .validate(&self.rules.data) + .map_err(Error::Content)?; + self.draft_effects.battle.push((id.into(), sequence)); + self.draft_effects.sequence = sequence; + } + if changes_map { + let switches = MapConfig { + effects: vec![id.into()], + ..Default::default() + } + .resolved(&self.rules.data) + .map_err(Error::Content)?; + map.device_overrides.extend(switches.device_overrides); + map.validate().map_err(Error::Content)?; + self.draft_effects.sequence = + add(self.draft_effects.sequence, 1).map_err(|_| Error::Capacity)?; + if self.draft_effects.maps.len() >= self.capacity { + return Err(Error::Capacity); + } + self.draft_effects + .maps + .push((id.into(), self.draft_effects.sequence)); + } + } + _ => return Err(Error::BadTarget), + } + self.recompute_meta(player) + } +} diff --git a/crates/engine/src/solo/preparation/effects.rs b/crates/engine/src/solo/preparation/effects.rs new file mode 100644 index 0000000..532057b --- /dev/null +++ b/crates/engine/src/solo/preparation/effects.rs @@ -0,0 +1,978 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::{ + bonds::{Bond, EffectsConfig, State}, + items::{GainSource, ItemSource}, + Error, Kind, Location, Piece, Preparation, +}; +use crate::{ + data::Catalog, + deterministic::rng::{derive_seed, Rng}, + solo::{add, player::Player, Phase, MAX_FUNDS}, +}; +use serde_json::{json, Value}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; + +mod dispatch; +mod recruits; +use dispatch::{Call, Origin, Refresh}; +use recruits::Recruit; + +#[derive(Clone, Debug, PartialEq)] +pub(super) enum Hook { + Gain, + Sold, + PrepStart, + PrepEnd, + Refresh, + Price, + RoundStart, + Buy, + Merge, + LevelUp, + Active, + Layers(String), +} +#[derive(Clone)] +enum Method { + Shop, + Acquired, + Hand, + Row, + Tiers, +} +#[derive(Clone)] +enum Formula { + Fixed(f64), + Method(Method, f64), + Spent { per: f64, layer: f64 }, + Refresh { multi: f64, max: f64 }, +} +#[derive(Clone)] +enum Targets { + Own, + Named(Vec), + Multiple(Vec<(String, f64)>), +} +#[derive(Clone)] +enum Effect { + Layers { + targets: Targets, + formula: Formula, + active: bool, + row_min: Option, + }, + Most { + count: f64, + diversity: bool, + }, + Hand(f64), + Position { + behind: bool, + count: f64, + }, + FirstRefresh { + ids: Vec, + count: f64, + at: f64, + active: bool, + }, + Pending { + count: f64, + condition: Vec, + }, + Free(f64), + Discount(f64), + Items { + source: ItemSource, + count: f64, + rounds: Vec, + }, + Recruit(Recruit), + Trigger { + hook: Option, + scope: TriggerScope, + }, + Copy { + hook: Hook, + key: String, + }, + RandomLayers { + count: f64, + repeats: f64, + }, + ForwardLayers(f64), + Unsupported(String), +} +#[derive(Clone)] +enum TriggerScope { + Front(f64), + Farthest, +} +#[derive(Clone)] +struct Rule { + hook: Hook, + board_only: bool, + effect: Effect, +} +pub(super) struct Rules { + pub bonds: Vec, + garrisons: BTreeMap, +} +#[derive(Clone)] +pub(super) struct Meta { + pub rules: Arc, + pub layers: BTreeMap, + pub bonus: BTreeMap, + pub bonds: BTreeMap, + pub rng: Rng, + pub defer_items: usize, + hammer_paid: f64, + pub round: u32, + phase: Phase, + depth: usize, + refresh: Option, + ended_round: Option, + visi_paid: f64, + mira_paid: f64, + discount: u8, +} +pub(super) fn n(v: &Value, fallback: f64) -> f64 { + v.as_f64() + .or_else(|| v.as_str().and_then(|s| s.parse().ok())) + .filter(|v| v.is_finite()) + .unwrap_or(fallback) +} +fn ids_of_bonds(v: &Value) -> Vec { + v.as_str() + .unwrap_or("") + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect() +} +impl Hook { + fn garrison(event: &str) -> Option { + Some(match event { + "SERVER_GAIN" => Self::Gain, + "SERVER_CHESS_SOLD" => Self::Sold, + "SERVER_PREP_START" => Self::PrepStart, + "SERVER_PREP_FIN" => Self::PrepEnd, + "SERVER_REFRESH_SHOP" => Self::Refresh, + "SERVER_PRICE" => Self::Price, + _ => return None, + }) + } +} +impl Rule { + fn load(id: &str, raw: &Value) -> Option { + let hook = Hook::garrison(raw["eventType"].as_str()?)?; + let bb = &raw["bb"]; + let s = &raw["bbStr"]; + let desc = raw["desc"].as_str().unwrap_or(""); + let active = + !desc.contains("无需激活") && (desc.contains("已激活") || desc.contains("激活且")); + let count = n(&bb["count"], 0.); + let named = Targets::Named(ids_of_bonds(&s["bond"])); + let effect = match raw["effectKey"].as_str().unwrap_or("") { + "SERVER_ADD_BOND_CHESS_ALL" => Effect::Layers { + targets: Targets::Own, + formula: Formula::Fixed(count), + active, + row_min: None, + }, + "SERVER_ADD_BOND" => Effect::Layers { + targets: named, + formula: Formula::Fixed(count), + active, + row_min: (s["conditionkey"] == "character_same_row") + .then(|| n(&bb["check_count"], 0.)), + }, + "SERVER_ADD_MULTIPLE_BOND" => { + let counts = ids_of_bonds(&s["count"]) + .iter() + .map(|s| s.parse::().unwrap_or(0.)) + .collect::>(); + Effect::Layers { + targets: Targets::Multiple( + ids_of_bonds(&s["bond"]) + .into_iter() + .enumerate() + .map(|(i, b)| { + ( + b, + counts + .get(i) + .or_else(|| counts.last()) + .copied() + .unwrap_or(0.), + ) + }) + .collect(), + ), + formula: Formula::Fixed(1.), + active, + row_min: None, + } + } + "SERVER_ADD_BOND_METHOD" => { + let method = match s["add_method"].as_str().unwrap_or("") { + "shoplv" => Some(Method::Shop), + "round_gain_char" => Some(Method::Acquired), + "hand_count" => Some(Method::Hand), + "same_row" => Some(Method::Row), + "same_bond_diff_lv" => Some(Method::Tiers), + _ => None, + }; + if let Some(method) = method { + Effect::Layers { + targets: named, + formula: Formula::Method(method, n(&bb["multi"], 1.)), + active, + row_min: None, + } + } else { + Effect::Unsupported(format!("SERVER_ADD_BOND_METHOD {}", s["add_method"])) + } + } + "SERVER_ADD_BOND_ROUND_COIN_COST" => Effect::Layers { + targets: named, + formula: Formula::Spent { + per: count.max(1.), + layer: n(&bb["layer"], 0.), + }, + active, + row_min: None, + }, + "SERVER_ADD_REFRESH_CNT_MULTIPLIER_BOND_LAYER" => Effect::Layers { + targets: named, + formula: Formula::Refresh { + multi: n(&bb["multiplier"], 0.), + max: n(&bb["max_layer"], 0.), + }, + active, + row_min: None, + }, + "SERVER_ADD_BOND_ACTIVATED_MOST_LAYER" => Effect::Most { + count, + diversity: false, + }, + "SERVER_ADD_ACT_BOND_DIFF_LV_MOST_LAYER" => Effect::Most { + count: n(&bb["multi"], 1.), + diversity: true, + }, + "SERVER_ADD_BOND_IN_HAND" => Effect::Hand(count), + "SERVER_ADD_BOND_POSITION" => Effect::Position { + behind: s["dir"] == "behind", + count, + }, + "SERVER_GAIN_BOND_LAYER_BY_REFRESH_CNT" => Effect::FirstRefresh { + ids: ids_of_bonds(&s["bond"]), + count: n(&bb["layer"], 0.), + at: n(&bb["refresh_cnt"], 1.), + active, + }, + "SERVER_ONCE_GOLD" => Effect::Pending { + count, + condition: vec![], + }, + "SERVER_ONCE_GOLD_WITH_BOND_CONDITION" => Effect::Pending { + count, + condition: ids_of_bonds(&s["bond"]), + }, + "SERVER_GAIN_CHAR" => Effect::Recruit(Recruit::Fixed { + key: s["chess"].as_str().unwrap_or("").into(), + count: n(&bb["count"], 1.), + }), + "SERVER_POOL_CHAR" => Effect::Recruit(Recruit::Pool { + key: s["pool"].as_str().unwrap_or("").into(), + count: n(&bb["count"], 1.), + row_min: (s["conditionkey"] == "character_same_row") + .then(|| n(&bb["check_count"], 0.)), + }), + "SERVER_MOST_BOND" => Effect::Recruit(Recruit::Most { + row_min: (s["conditionkey"] == "character_same_row") + .then(|| n(&bb["check_count"], 0.)), + }), + "SERVER_SELL_CHESS_GAIN_SPECIAL_GOODS" => Effect::Recruit(Recruit::Offer { + pools: (1..=6) + .map(|i| s[format!("pool{i}")].as_str().unwrap_or("").into()) + .collect(), + fallback: s["max_pool"].as_str().unwrap_or("").into(), + }), + "SERVER_TRIGGER_ANOTHER" => Effect::Trigger { + hook: Hook::garrison(s["event"].as_str().unwrap_or("SERVER_GAIN")), + scope: if s["scope"] == "front" { + TriggerScope::Front(1.) + } else { + TriggerScope::Farthest + }, + }, + "SERVER_TRIGGER_FRONT_COUNT" => Effect::Trigger { + hook: Hook::garrison(s["event"].as_str().unwrap_or("SERVER_GAIN")), + scope: TriggerScope::Front(n(&bb["count"], 1.)), + }, + "SERVER_FRONT_SAME_EFFECT_PREP_FIN" | "SERVER_FRONT_SAME_EFFECT_PREP_START" => { + Effect::Copy { + hook: if raw["effectKey"] == "SERVER_FRONT_SAME_EFFECT_PREP_FIN" { + Hook::PrepEnd + } else { + Hook::PrepStart + }, + key: raw["effectKey"].as_str().unwrap().into(), + } + } + "SERVER_ADD_BOND_ACTIVATED_RANDOM" => Effect::RandomLayers { + count, + repeats: n(&bb["rand_count"], 1.), + }, + "SERVER_ADD_BOND_FRONT_ALL_LAYER" => Effect::ForwardLayers(count), + "SERVER_GAIN_EQUIP" => Effect::Items { + source: ItemSource::Fixed(s["chess"].as_str().unwrap_or("").into()), + count: n(&bb["count"], 1.), + rounds: vec![], + }, + "SERVER_POOL_EQUIP" | "SERVER_GAIN_RANDOM_EQUIP_CHESS_IN_POOL" => Effect::Items { + source: ItemSource::Pool { + id: s["pool"].as_str().unwrap_or("").into(), + golden: raw["effectKey"] == "SERVER_POOL_EQUIP" && id.ends_with("_b"), + fallback: raw["effectKey"] == "SERVER_GAIN_RANDOM_EQUIP_CHESS_IN_POOL", + }, + count: n(&bb["count"], 1.), + rounds: ids_of_bonds(&s["round_list"]) + .iter() + .map(|s| s.parse().unwrap_or(-1.)) + .collect(), + }, + "SERVER_GAIN_FREE_REFRESH_COUNT" => Effect::Free(n(&bb["count"], 1.)), + "SERVER_CHESS_PRICE" => Effect::Discount(n(&bb["price"], 0.)), + key => Effect::Unsupported(key.into()), + }; + Some(Self { + hook, + board_only: s["conditionkey"] == "character_target_inboard", + effect, + }) + } +} +impl Meta { + pub fn new( + data: &Catalog, + mode: &Value, + seed: u32, + config: EffectsConfig, + ) -> Result { + let bonds = Bond::load(data.table("bonds").unwrap(), mode, &config.disabled_bonds)?; + if config.layers.len() > 256 || config.count_bonus.len() > 256 { + return Err("Bond state capacity exceeded".into()); + } + for (id, amount) in &config.layers { + if !amount.is_finite() || *amount < 0. || !bonds.iter().any(|b| &b.id == id) { + return Err("Invalid initial bond layers".into()); + } + } + for id in config.count_bonus.keys() { + if !bonds.iter().any(|b| &b.id == id) { + return Err("Unknown bond count bonus".into()); + } + } + let garrisons = data.table("garrisons").unwrap().as_object().unwrap(); + if garrisons.len() > 4096 { + return Err("Garrison definition capacity exceeded".into()); + } + let rules = Rules { + bonds, + garrisons: garrisons + .iter() + .filter_map(|(id, raw)| Rule::load(id, raw).map(|r| (id.clone(), r))) + .collect(), + }; + Ok(Self { + rules: Arc::new(rules), + layers: config.layers, + bonus: config.count_bonus, + bonds: BTreeMap::new(), + rng: Rng::new(derive_seed(seed, "meta")), + defer_items: 0, + hammer_paid: 0., + round: 0, + phase: Phase::Prep, + depth: 0, + refresh: None, + ended_round: None, + visi_paid: 0., + mira_paid: 0., + discount: 0, + }) + } + fn active(&self, id: &str) -> bool { + self.bonds.get(id).is_some_and(State::active) + } + fn buff(&self, id: &str, key: &str) -> Value { + self.rules + .bonds + .iter() + .find(|b| b.id == id) + .map(|b| b.buff(key)) + .unwrap_or_else(|| json!({})) + } + pub fn cold_wind(&self) -> Option { + let bond = self.rules.bonds.iter().find(|b| b.id == "kjeragShip")?; + let state = self.bonds.get(&bond.id)?; + let bb = self.buff(&bond.id, "env_gbuff_new"); + let need = n(&bb["power_bond_char_cnt"], 0.); + let reached = need > 0. + && (state.count >= need + || bond + .thresholds + .iter() + .position(|v| *v == need) + .is_some_and(|i| state.tier >= i + 1)); + let interval = n(&bb["bond_eff_kjerag[storm].interval"], 0.); + if !state.active() || !reached || interval <= 0. { + return None; + } + Some(crate::battle::runtime::ColdWind { + interval, + duration: n(&bb["bond_eff_kjerag[storm].base_time"], 0.) + + n(&bb["bond_eff_kjerag[storm].time_per_stack"], 0.) * state.layers, + first: None, + }) + } + pub fn active_sum(&self) -> f64 { + self.rules + .bonds + .iter() + .filter_map(|b| self.bonds.get(&b.id)) + .filter(|b| b.active()) + .fold(0., |sum, b| sum + b.layers) + } + pub fn report(&self, free: u64) -> Value { + json!({"rng":self.rng.state(),"round":self.round,"layers":self.layers,"bonds":self.bonds.iter().map(|(id,b)| {let mut v=json!({"count":b.count,"tier":b.tier,"active":b.active(),"layers":b.layers});if b.harmony>0 {v["harmony"]=json!(b.harmony);} (id.clone(),v)}).collect::>(),"freeRefreshes":free,"activatedLayers":self.active_sum(),"visiPaid":self.visi_paid,"miraPaid":self.mira_paid,"hammerPaid":self.hammer_paid,"discount":self.discount,"prepEndedRound":self.ended_round}) + } +} +impl Preparation { + pub(super) fn recompute_meta(&mut self, player: &mut Player) -> Result<(), Error> { + let states = self.bond_states(); + let Some(meta) = &mut self.meta else { + return Ok(()); + }; + let changed = states.iter().any(|(id, b)| b.active() != meta.active(id)); + meta.bonds = states; + if changed { + self.dispatch_meta(Hook::Active, None, player)?; + } + Ok(()) + } + pub(in crate::solo::preparation) fn add_layers( + &mut self, + id: &str, + amount: f64, + active: bool, + player: &mut Player, + ) -> Result<(), Error> { + let Some(meta) = &mut self.meta else { + return Ok(()); + }; + if !amount.is_finite() + || amount <= 0. + || !meta.rules.bonds.iter().any(|b| b.id == id) + || active && !meta.active(id) + { + return Ok(()); + } + let before = *meta.layers.get(id).unwrap_or(&0.); + let gained = amount.floor().min((999. - before).max(0.)); + if gained <= 0. { + return Ok(()); + } + meta.layers.insert(id.into(), before + gained); + self.recompute_meta(player)?; + self.dispatch_meta(Hook::Layers(id.into()), None, player) + } + fn member_tiers(&self, bond: &str) -> usize { + self.board + .values() + .filter(|p| p.kind == Kind::Chess && self.piece_bonds(p).iter().any(|b| b == bond)) + .map(|p| self.rules.chess[&p.key].tier) + .collect::>() + .len() + } + fn same_row(&self, piece: &Piece) -> usize { + let Some(Location::Board(at)) = self.find(piece.uid) else { + return 0; + }; + self.board + .iter() + .filter(|(p, c)| p[0] == at[0] && c.kind == Kind::Chess) + .count() + } + fn formula(&self, f: &Formula, piece: &Piece, bond: &str, player: &Player) -> f64 { + match f { + Formula::Fixed(n) => *n, + Formula::Method(method, multi) => { + *multi + * match method { + Method::Shop => self.level as f64, + Method::Acquired => self.round.gained_chess as u32 as i32 as f64, + Method::Hand => self + .hand + .iter() + .flatten() + .filter(|p| p.kind == Kind::Chess) + .count() as f64, + Method::Row => self.same_row(piece) as f64, + Method::Tiers => self.member_tiers(bond) as f64, + } + } + Formula::Spent { per, layer } => { + (player.round_spent as u32 as i32 as f64 / per).floor() * layer + } + Formula::Refresh { multi, max } => { + let n = self.round.refreshes as u32 as i32 as f64 * multi; + if *max > 0. { + n.min(*max) + } else { + n + } + } + } + } + fn run_rule(&mut self, rule: &Rule, call: &Call, player: &mut Player) -> Result<(), Error> { + let piece = &call.piece; + match &rule.effect { + Effect::Layers { + targets, + formula, + active, + row_min, + } => { + if !self.row_condition(*row_min, call, &rule.hook) { + return Ok(()); + } + let bonds = match targets { + Targets::Own => self + .piece_bonds(piece) + .into_iter() + .map(|b| (b, 1.)) + .collect(), + Targets::Named(ids) => ids.iter().cloned().map(|b| (b, 1.)).collect(), + Targets::Multiple(ids) => ids.clone(), + }; + for (bond, scale) in bonds { + let amount = self.formula(formula, piece, &bond, player) * scale; + self.add_layers(&bond, amount, *active, player)?; + } + } + Effect::Most { count, diversity } => { + let meta = self.meta.as_ref().unwrap(); + let mut best = None; + let mut layers = -1.; + for bond in &meta.rules.bonds { + if let Some(state) = meta.bonds.get(&bond.id).filter(|s| s.active()) { + if state.layers > layers { + layers = state.layers; + best = Some(bond.id.clone()); + } + } + } + if let Some(bond) = best { + let n = if *diversity { + self.member_tiers(&bond) as f64 * count + } else { + *count + }; + self.add_layers(&bond, n, true, player)?; + } + } + Effect::Hand(count) => { + let keys = self + .hand + .iter() + .flatten() + .filter(|p| p.kind == Kind::Chess) + .cloned() + .collect::>(); + for p in keys { + for bond in self.piece_bonds(&p) { + self.add_layers(&bond, *count, true, player)?; + } + } + } + Effect::Position { behind, count } => { + let Some(Location::Board(at)) = self.find(piece.uid) else { + return Ok(()); + }; + let [r, c] = piece + .direction + .unwrap_or(crate::battle::direction::Direction::Right) + .vector(); + let sign = if *behind { -1 } else { 1 }; + let mut keys = vec![piece.clone()]; + if let Some(other) = self + .board + .get(&[at[0] + sign * r, at[1] + sign * c]) + .filter(|p| p.kind == Kind::Chess && p.uid != piece.uid) + { + keys.push(other.clone()); + } + for p in keys { + for bond in self.piece_bonds(&p) { + self.add_layers(&bond, *count, true, player)?; + } + } + } + Effect::FirstRefresh { + ids, + count, + at, + active, + } => { + if call.triggered { + return Ok(()); + } + let loc = self.find(piece.uid); + let p = match loc { + Some(Location::Hand(i)) => self.hand[i].as_mut().unwrap(), + Some(Location::Temp(i)) => self.temp[i].as_mut().unwrap(), + Some(Location::Board(at)) => self.board.get_mut(&at).unwrap(), + None => match self + .meta + .as_mut() + .unwrap() + .refresh + .as_mut() + .and_then(|r| r.merged.get_mut(&piece.uid)) + { + Some(p) => p, + None => return Ok(()), + }, + }; + p.refresh_seen = add(p.refresh_seen, 1).map_err(|_| Error::Capacity)?; + if p.refresh_seen as f64 == *at { + for bond in ids { + self.add_layers(bond, *count, *active, player)?; + } + } + } + Effect::Pending { count, condition } => { + if call.origin != Origin::Hand + || condition.is_empty() + || condition + .iter() + .any(|b| self.meta.as_ref().unwrap().active(b)) + { + let n = count.trunc().max(0.); + if n > MAX_FUNDS as f64 { + return Err(Error::Capacity); + } + player.pending = add(player.pending, n as u64).map_err(|_| Error::Capacity)?; + } + } + Effect::Free(count) => { + let n = count.trunc().max(0.); + if n > MAX_FUNDS as f64 { + return Err(Error::Capacity); + } + self.free_refreshes = + add(self.free_refreshes, n as u64).map_err(|_| Error::Capacity)?; + } + Effect::Discount(_) => (), + Effect::Items { + source, + count, + rounds, + } => { + if rounds.is_empty() || rounds.contains(&(self.meta.as_ref().unwrap().round as f64)) + { + self.grant_items(source, *count, player)?; + } + } + Effect::Recruit(recruit) => self.recruit(recruit, call, &rule.hook, player)?, + Effect::Trigger { + hook: Some(hook), + scope, + } if *hook != Hook::Price => match scope { + TriggerScope::Front(count) => { + for n in 1..=count.clamp(0., 8.).floor() as i32 { + if let Some(target) = self.front(piece, n) { + self.trigger_garrisons(&target, None, hook, player)?; + } + } + } + TriggerScope::Farthest => { + let mut candidates = self.board_pieces(); + candidates.sort_by_key(|(at, _)| (-at[0], -at[1])); + if let Some(target) = candidates + .into_iter() + .map(|(_, p)| p) + .find(|p| p.uid != piece.uid && self.has_hook(p, hook)) + { + self.trigger_garrisons(&target, None, hook, player)?; + } + } + }, + Effect::Trigger { .. } => (), + Effect::Copy { hook, key } => { + let mut target = self.front(piece, 1); + for _ in 0..8 { + let Some(p) = &target else { break }; + let traits = self + .garrison_ids(&p.key) + .into_iter() + .filter(|id| { + self.meta + .as_ref() + .unwrap() + .rules + .garrisons + .get(id) + .is_some_and(|r| r.hook == *hook) + }) + .collect::>(); + if traits.is_empty() { + return Ok(()); + } + if !traits.iter().all(|id| { + self.rules.data.table("garrisons").unwrap()[id]["effectKey"] == *key + }) { + break; + } + target = self.front(p, 1); + } + if let Some(target) = target.filter(|p| p.uid != piece.uid) { + self.trigger_garrisons(&target, Some(piece), hook, player)?; + } + } + Effect::RandomLayers { count, repeats } => { + let meta = self.meta.as_ref().unwrap(); + let active = meta + .rules + .bonds + .iter() + .filter(|b| meta.active(&b.id)) + .map(|b| b.id.clone()) + .collect::>(); + for _ in 0..repeats.clamp(0., 10.).ceil() as usize { + if let Some(id) = self.meta.as_mut().unwrap().rng.pick(&active).cloned() { + self.add_layers(&id, *count, true, player)?; + } + } + } + Effect::ForwardLayers(count) => { + if let Some(Location::Board(at)) = self.find(piece.uid) { + let [r, c] = piece + .direction + .unwrap_or(crate::battle::direction::Direction::Right) + .vector(); + for (other, p) in self.board_pieces() { + if (other[0] - at[0]) * c == (other[1] - at[1]) * r + && (other[0] - at[0]) * r + (other[1] - at[1]) * c > 0 + { + for bond in self.piece_bonds(&p) { + self.add_layers(&bond, *count, true, player)?; + } + } + } + } + } + Effect::Unsupported(key) => { + return Err(Error::Content(format!( + "Unsupported preparation effect: {key}" + ))) + } + } + Ok(()) + } + fn settle_meta_milestones(&mut self, hook: &Hook, player: &mut Player) -> Result<(), Error> { + for id in ["victoriaShip", "visiShip", "miraShip"] { + if matches!(hook,Hook::Layers(b) if b!=id) + || !matches!( + hook, + Hook::Layers(_) + | Hook::Active + | Hook::RoundStart + | Hook::PrepStart + | Hook::PrepEnd + | Hook::Buy + | Hook::Gain + | Hook::Sold + | Hook::Merge + ) + { + continue; + } + let meta = self.meta.as_ref().unwrap(); + if !meta.active(id) { + continue; + } + if id == "victoriaShip" { + let b = meta.buff(id, "bond_layer_added_reward_equip"); + let step = n(&b["layer"], 0.).floor(); + if step > 0. { + let due = (meta.layers.get(id).copied().unwrap_or(0.) / step).floor(); + let count = n(&b["count"], 1.).floor().max(0.); + if count > self.capacity as f64 { + return Err(Error::Capacity); + } + for _ in 0..100 { + let meta = self.meta.as_mut().unwrap(); + if meta.hammer_paid >= due { + break; + } + meta.hammer_paid += 1.; + for _ in 0..count as usize { + if let Some(key) = self.roll_meta_item(b["pool"].as_str(), 6, false)? { + self.gain(Kind::Item, &key, GainSource::Grant, player)?; + } + } + } + } + continue; + } + let b = meta.buff(id, "bond_layer_gain_coin"); + let step = n(&b["layer"], 0.); + let count = n(&b["count"], 0.); + if step > 0. && count > 0. { + let due = (meta.layers.get(id).copied().unwrap_or(0.) / step).floor(); + let paid = if id == "visiShip" { + meta.visi_paid + } else { + meta.mira_paid + }; + if due > paid { + let gain = (due - paid) * count; + if !gain.is_finite() || gain > MAX_FUNDS as f64 { + return Err(Error::Capacity); + } + let pending = meta.phase == Phase::Prep && meta.ended_round == Some(meta.round); + let meta = self.meta.as_mut().unwrap(); + if id == "visiShip" { + meta.visi_paid = due; + } else { + meta.mira_paid = due; + } + if pending { + player.pending = add(player.pending, gain.trunc() as u64) + .map_err(|_| Error::Capacity)?; + } else { + player + .earn(gain.trunc() as u64) + .map_err(|_| Error::Capacity)?; + } + } + } + if id == "visiShip" { + let meta = self.meta.as_mut().unwrap(); + let b = meta.buff(id, "bond_multi_layer_char_goods_price_bond_discount"); + let own = meta.buff(id, "bond_layer_char_goods_price_bond_discount"); + let all = meta.buff(id, "bond_layer_char_goods_price_discount"); + let layers = meta.layers.get(id).copied().unwrap_or(0.); + let t = if layers >= n(&b["layer2"], n(&all["layer"], f64::INFINITY)) { + 2 + } else if layers >= n(&b["layer1"], n(&own["layer"], f64::INFINITY)) { + 1 + } else { + 0 + }; + meta.discount = meta.discount.max(t); + } + } + Ok(()) + } + pub(super) fn meta_price(&self, key: &str, price: f64) -> Result { + let Some(meta) = &self.meta else { + return Ok(price.round().max(0.)); + }; + let mut price = price; + for id in self.rules.data.table("chess").unwrap()[key]["garrisonIds"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if let Some(rule) = meta + .rules + .garrisons + .get(id) + .filter(|r| r.hook == Hook::Price) + { + match &rule.effect { + Effect::Discount(n) => price = (price - n).max(0.), + Effect::Unsupported(k) => { + return Err(Error::Content(format!( + "Unsupported preparation effect: {k}" + ))) + } + _ => (), + } + } + } + if meta.discount > 0 { + let b = meta.buff( + "visiShip", + "bond_multi_layer_char_goods_price_bond_discount", + ); + let old = meta.buff("visiShip", "bond_layer_char_goods_price_discount"); + let own = meta.buff("visiShip", "bond_layer_char_goods_price_bond_discount"); + let bond = b["bond"] + .as_str() + .or(own["bond"].as_str()) + .unwrap_or("visiShip"); + if meta.discount >= 2 || self.own_bonds(key).iter().any(|id| id == bond) { + price = (price - n(&b["discount"], n(&old["discount"], n(&own["discount"], 0.)))) + .max(0.); + } + } + if self.sciurus && !self.round.sciurus_bought && self.own_bonds(key).iter().any(|b| b == "kjeragShip") { + price = price.min(1.); + } + Ok(price.round().max(0.)) + } + pub(super) fn meta_begin( + &mut self, + round: u32, + player: &mut Player, + defer_prep: bool, + ) -> Result<(), Error> { + if let Some(meta) = &mut self.meta { + meta.round = round; + meta.phase = Phase::Prep; + } + for piece in self + .hand + .iter_mut() + .chain(&mut self.temp) + .flatten() + .chain(self.board.values_mut()) + { + piece.refresh_seen = 0; + } + self.recompute_meta(player)?; + self.dispatch_meta(Hook::RoundStart, None, player)?; + self.equipment_event(super::equipment_lifecycle::Event::RoundStart, player)?; + player + .earn(self.round_income) + .map_err(|_| Error::Capacity)?; + if defer_prep { + return Ok(()); + } + self.enter_prep(player) + } + pub(in crate::solo) fn enter_prep(&mut self, player: &mut Player) -> Result<(), Error> { + self.check_item_merges(player)?; + self.dispatch_meta(Hook::PrepStart, None, player)?; + self.recompute_meta(player) + } + pub(in crate::solo) fn meta_end(&mut self, player: &mut Player) -> Result<(), Error> { + self.dispatch_meta(Hook::PrepEnd, None, player) + } + pub(super) fn meta_combat(&mut self) { + if let Some(meta) = &mut self.meta { + meta.phase = Phase::Combat; + } + } +} diff --git a/crates/engine/src/solo/preparation/effects/dispatch.rs b/crates/engine/src/solo/preparation/effects/dispatch.rs new file mode 100644 index 0000000..298e27d --- /dev/null +++ b/crates/engine/src/solo/preparation/effects/dispatch.rs @@ -0,0 +1,390 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Origin { + Board, + Hand, + Temp, + Gain, + Sold, + Trigger, +} +impl Origin { + fn at(loc: Location) -> Self { + match loc { + Location::Board(_) => Self::Board, + Location::Hand(_) => Self::Hand, + Location::Temp(_) => Self::Temp, + } + } +} +#[derive(Clone)] +pub(super) struct Call { + pub piece: Piece, + pub copied_from: Option, + pub origin: Origin, + pub triggered: bool, +} +#[derive(Clone)] +pub(super) struct Refresh { + witnesses: Vec<(Piece, Origin)>, + pub merged: BTreeMap, +} +impl Preparation { + pub(super) fn board_pieces(&self) -> Vec<([i32; 2], Piece)> { + let mut board: Vec<_> = self.board.iter().map(|(at, p)| (*at, p.clone())).collect(); + board.sort_by_key(|(at, _)| (-at[0], at[1])); + board + } + pub(super) fn garrison_ids(&self, key: &str) -> Vec { + self.rules.data.table("chess").unwrap()[key]["garrisonIds"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + } + pub(super) fn has_hook(&self, piece: &Piece, hook: &Hook) -> bool { + let rules = &self.meta.as_ref().unwrap().rules.garrisons; + self.garrison_ids(&piece.key) + .iter() + .any(|id| rules.get(id).is_some_and(|r| r.hook == *hook)) + } + pub(super) fn front(&self, piece: &Piece, distance: i32) -> Option { + let Location::Board(at) = self.find(piece.uid)? else { + return None; + }; + let [r, c] = piece + .direction + .unwrap_or(crate::battle::direction::Direction::Right) + .vector(); + self.board + .get(&[at[0] + distance * r, at[1] + distance * c]) + .filter(|p| p.kind == Kind::Chess && p.uid != piece.uid) + .cloned() + } + pub(super) fn row_condition(&self, minimum: Option, call: &Call, hook: &Hook) -> bool { + let Some(minimum) = minimum else { return true }; + let chess = self.rules.data.table("chess").unwrap(); + let copied_exception = *hook == Hook::PrepStart + && chess[&call.piece.key]["charId"] == "char_128_plosis" + && call.copied_from.as_ref().is_some_and(|p| { + matches!( + chess[&p.key]["charId"].as_str(), + Some("char_474_glady" | "char_2026_yu") + ) + }); + copied_exception || self.same_row(&call.piece) as f64 >= minimum + } + pub(in crate::solo::preparation) fn record_refresh_merge(&mut self, piece: &Piece) { + if let Some(refresh) = self.meta.as_mut().and_then(|m| m.refresh.as_mut()) { + if refresh.witnesses.iter().any(|(p, _)| p.uid == piece.uid) { + refresh.merged.insert(piece.uid, piece.clone()); + } + } + } + fn gain_repeat(&self, hook: &Hook) -> Result { + let meta = self.meta.as_ref().unwrap(); + if *hook != Hook::Gain || !meta.active("investShip") { + return Ok(1); + } + let bond = meta + .rules + .bonds + .iter() + .find(|b| b.id == "investShip") + .unwrap(); + let count = n(&bond.raw["bb"]["count"], 2.); + let base = if count > 1. && count.fract() == 0. { + count as usize + } else { + 2 + }; + let threshold = bond.raw["layerMilestones"] + .as_array() + .and_then(|a| { + a.iter().find_map(|m| { + let v = n(&m["layer"], 0.); + (v > 0.).then_some(v) + }) + }) + .unwrap_or_else(|| { + let v = n(&bond.raw["bb"]["layer"], 100.); + if v > 0. { + v + } else { + 100. + } + }); + let repeat = base + .checked_add(usize::from(meta.bonds["investShip"].layers >= threshold)) + .ok_or(Error::Capacity)?; + if repeat > 4096 { + return Err(Error::Capacity); + } + Ok(repeat) + } + fn run_garrisons( + &mut self, + hook: &Hook, + call: &Call, + player: &mut Player, + ) -> Result<(), Error> { + let donor = call.copied_from.as_ref().unwrap_or(&call.piece); + let ids = self.garrison_ids(&donor.key); + let mut call = call.clone(); + for id in ids { + if call.triggered { + call.origin = self + .find(call.piece.uid) + .map_or(Origin::Trigger, Origin::at); + } + let Some(mut rule) = self + .meta + .as_ref() + .unwrap() + .rules + .garrisons + .get(&id) + .filter(|r| r.hook == *hook) + .cloned() + else { + continue; + }; + if !call.triggered && call.origin == Origin::Hand && rule.board_only { + continue; + } + if let Effect::Layers { + targets: Targets::Named(targets), + formula: Formula::Fixed(_), + .. + } = &mut rule.effect + { + let table = self.rules.data.table("garrisons").unwrap(); + let raw = &table[&id]; + for sibling in self.garrison_ids(&call.piece.key) { + let other = &table[&sibling]; + if sibling != id + && other["effectType"] == "SERVER_ADD_MULTIPLE_BOND" + && other["eventType"] == raw["eventType"] + && other["desc"] == raw["desc"] + { + let covered = ids_of_bonds(&other["bbStr"]["bond"]); + targets.retain(|bond| !covered.contains(bond)); + } + } + } + for _ in 0..self.gain_repeat(hook)? { + self.run_rule(&rule, &call, player)?; + } + } + Ok(()) + } + pub(super) fn trigger_garrisons( + &mut self, + donor: &Piece, + receiver: Option<&Piece>, + hook: &Hook, + player: &mut Player, + ) -> Result<(), Error> { + if *hook == Hook::Price || self.meta.as_ref().unwrap().depth >= 6 { + return Ok(()); + } + // Trigger only garrisons. Global/bond callbacks belong to the enclosing event. + let receiver = receiver.unwrap_or(donor); + if self.find(donor.uid).is_none() || self.find(receiver.uid).is_none() { + return Ok(()); + } + let call = Call { + piece: receiver.clone(), + copied_from: (receiver.uid != donor.uid).then(|| donor.clone()), + origin: self.find(receiver.uid).map_or(Origin::Trigger, Origin::at), + triggered: true, + }; + self.meta.as_mut().unwrap().depth += 1; + let result = self.run_garrisons(hook, &call, player); + self.meta.as_mut().unwrap().depth -= 1; + result + } + fn owned_garrisons(&mut self, hook: &Hook, player: &mut Player) -> Result<(), Error> { + if *hook == Hook::Refresh { + let witnesses = self + .meta + .as_ref() + .unwrap() + .refresh + .as_ref() + .unwrap() + .witnesses + .clone(); + for (witness, original) in witnesses { + let live = self + .find(witness.uid) + .filter(|loc| !matches!(loc, Location::Temp(_))) + .map(|loc| (self.piece(loc).clone(), Origin::at(loc))); + let merged = self + .meta + .as_ref() + .unwrap() + .refresh + .as_ref() + .unwrap() + .merged + .get(&witness.uid) + .cloned() + .map(|p| (p, original)); + if let Some((piece, origin)) = live.or(merged) { + self.run_garrisons( + hook, + &Call { + piece, + copied_from: None, + origin, + triggered: false, + }, + player, + )?; + } + } + } else { + // Prep events snapshot the board, then walk the current hand slots. + for (_, piece) in self.board_pieces() { + self.run_garrisons( + hook, + &Call { + piece, + copied_from: None, + origin: Origin::Board, + triggered: false, + }, + player, + )?; + } + for i in 0..self.hand.len() { + if let Some(piece) = self.hand[i] + .as_ref() + .filter(|p| p.kind == Kind::Chess) + .cloned() + { + self.run_garrisons( + hook, + &Call { + piece, + copied_from: None, + origin: Origin::Hand, + triggered: false, + }, + player, + )?; + } + } + } + Ok(()) + } + pub(in crate::solo::preparation) fn dispatch_meta( + &mut self, + hook: Hook, + piece: Option, + player: &mut Player, + ) -> Result<(), Error> { + let Some(meta) = &mut self.meta else { + return Ok(()); + }; + if meta.depth >= 6 { + return Ok(()); + } + meta.depth += 1; + if hook == Hook::PrepEnd { + meta.ended_round = Some(meta.round); + meta.defer_items += 1; + } + if hook == Hook::Refresh { + let witnesses = self + .board_pieces() + .into_iter() + .map(|(_, p)| (p, Origin::Board)) + .chain( + self.hand + .iter() + .flatten() + .filter(|p| p.kind == Kind::Chess) + .cloned() + .map(|p| (p, Origin::Hand)), + ) + .collect(); + self.meta.as_mut().unwrap().refresh = Some(Refresh { + witnesses, + merged: BTreeMap::new(), + }); + } + let result = (|| { + self.settle_meta_milestones(&hook, player)?; + if hook == Hook::PrepEnd { + let meta = self.meta.as_ref().unwrap(); + if let Some(state) = meta.bonds.get("deputShip").filter(|b| b.active()) { + let buff = meta.buff("deputShip", "bond_activated_add_layer"); + let amount = if state.tier >= 2 { + n(&buff["more_layer"], n(&buff["layer"], 0.)) + } else { + n(&buff["layer"], 0.) + }; + let active = meta + .rules + .bonds + .iter() + .filter(|b| meta.active(&b.id)) + .map(|b| b.id.clone()) + .collect::>(); + for id in active { + self.add_layers(&id, amount, true, player)?; + } + } + } + if hook == Hook::Refresh && self.free_refreshes == 0 { + let meta = self.meta.as_ref().unwrap(); + if meta.active("miraShip") { + let b = meta.buff("miraShip", "bond_refresh_shop_next_free"); + let chance = (n(&b["baseprob"], 0.) + + n(&b["prob"], 0.) * meta.layers.get("miraShip").copied().unwrap_or(0.)) + .clamp(0., 1.); + if self.meta.as_mut().unwrap().rng.next_f64() < chance { + self.free_refreshes = + add(self.free_refreshes, 1).map_err(|_| Error::Capacity)?; + } + } + } + if matches!(hook, Hook::Gain | Hook::Sold) { + if let Some(piece) = piece.filter(|p| p.kind == Kind::Chess) { + self.run_garrisons( + &hook, + &Call { + piece, + copied_from: None, + origin: if hook == Hook::Gain { + Origin::Gain + } else { + Origin::Sold + }, + triggered: false, + }, + player, + )?; + } + } else if matches!(hook, Hook::PrepStart | Hook::PrepEnd | Hook::Refresh) { + self.owned_garrisons(&hook, player)?; + } + Ok(()) + })(); + let meta = self.meta.as_mut().unwrap(); + if hook == Hook::Refresh { + meta.refresh = None; + } + if hook == Hook::PrepEnd { + meta.defer_items -= 1; + } + meta.depth -= 1; + result + } +} diff --git a/crates/engine/src/solo/preparation/effects/recruits.rs b/crates/engine/src/solo/preparation/effects/recruits.rs new file mode 100644 index 0000000..e83e1eb --- /dev/null +++ b/crates/engine/src/solo/preparation/effects/recruits.rs @@ -0,0 +1,245 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::super::{Offer, Slot}; +use super::*; + +#[derive(Clone)] +pub(super) enum Recruit { + Fixed { + key: String, + count: f64, + }, + Pool { + key: String, + count: f64, + row_min: Option, + }, + Most { + row_min: Option, + }, + Offer { + pools: Vec, + fallback: String, + }, +} +impl Preparation { + fn recruit_available(&self, key: &str) -> bool { + self.rules + .chess + .get(key) + .is_some_and(|c| self.pool.get(&c.base).is_none_or(|e| e.left > 0)) + } + pub(in crate::solo::preparation) fn grant_recruit( + &mut self, + key: &str, + player: &mut Player, + ) -> Result { + if !self.recruit_available(key) { + return Ok(false); + } + Ok(self + .gain(Kind::Chess, key, GainSource::Grant, player)? + .is_some()) + } + pub(in crate::solo::preparation) fn roll_meta_chess( + &mut self, + max_tier: usize, + min_tier: usize, + tier: Option, + bonds: Option<&[String]>, + exclude: &[String], + ) -> Option { + let eligible: Vec<_> = self + .stock_entries() + .filter(|(key, e)| { + e.left > 0 + && tier.map_or(e.tier <= max_tier, |tier| e.tier == tier) + && e.tier >= min_tier + && !exclude.contains(key) + && bonds + .is_none_or(|bonds| self.own_bonds(key).iter().any(|b| bonds.contains(b))) + }) + .map(|(key, e)| (key.clone(), e.left as f64)) + .collect(); + let weights: Vec<_> = eligible.iter().map(|p| p.1).collect(); + self.meta + .as_mut() + .unwrap() + .rng + .weighted(&weights) + .map(|i| eligible[i].0.clone()) + } + fn roll_chess_pool(&mut self, pool_id: &str) -> Result, Error> { + let pool = &self.rules.data.table("choices").unwrap()["pools"][pool_id]; + if pool["kind"] != "chess" { + return Ok(None); + } + if ["items", "weighted"] + .iter() + .any(|key| pool[key].as_array().is_some_and(|a| a.len() > 4096)) + { + return Err(Error::Capacity); + } + let golden = pool["golden"] == true; + let picked = if let Some(weighted) = pool["weighted"].as_array().filter(|a| !a.is_empty()) { + let pairs: Vec<_> = weighted + .iter() + .filter_map(|p| p.as_array()) + .filter_map(|p| { + let id = p.first()?.as_str()?; + self.recruit_available(id).then(|| { + ( + id.to_owned(), + n(p.get(1).unwrap_or(&Value::Null), 0.).max(0.), + ) + }) + }) + .collect(); + let weights: Vec<_> = pairs.iter().map(|p| p.1).collect(); + self.meta + .as_mut() + .unwrap() + .rng + .weighted(&weights) + .or_else(|| (!pairs.is_empty()).then_some(0)) + .map(|i| pairs[i].0.clone()) + } else if let Some(items) = pool["items"].as_array().filter(|a| !a.is_empty()) { + let candidates: Vec<_> = items + .iter() + .filter_map(Value::as_str) + .filter(|id| self.recruit_available(id)) + .map(str::to_owned) + .collect(); + self.meta.as_mut().unwrap().rng.pick(&candidates).cloned() + } else { + let max = if pool["maxTier"] == "shopLevel" { + self.level.clamp(1, 6) + } else { + pool["maxTier"].as_u64().map_or(6, |n| n as usize) + }; + let min = pool["minTier"].as_u64().map_or(1, |n| n as usize); + let tier = pool["tier"].as_u64().map(|n| n as usize); + let bond = pool["bond"].as_str().map(str::to_owned); + self.roll_meta_chess(max, min, tier, bond.as_ref().map(std::slice::from_ref), &[]) + }; + Ok(picked.map(|key| { + if golden { + self.rules.chess[&key].upgrade.clone().unwrap_or(key) + } else { + key + } + })) + } + pub(super) fn recruit( + &mut self, + recruit: &Recruit, + call: &Call, + hook: &Hook, + player: &mut Player, + ) -> Result<(), Error> { + match recruit { + Recruit::Fixed { key, count } => { + for _ in 0..count.clamp(0., 10.).ceil() as usize { + self.grant_recruit(key, player)?; + } + } + Recruit::Pool { + key, + count, + row_min, + } => { + if self.row_condition(*row_min, call, hook) { + for _ in 0..count.clamp(0., 10.).ceil() as usize { + if let Some(key) = self.roll_chess_pool(key)? { + self.grant_recruit(&key, player)?; + } + } + } + } + Recruit::Most { row_min } => { + if !self.row_condition(*row_min, call, hook) { + return Ok(()); + } + let meta = self.meta.as_ref().unwrap(); + let mut best = Vec::new(); + let mut count = 0.; + for bond in &meta.rules.bonds { + let current = meta.bonds.get(&bond.id).map_or(0., |s| s.count); + if current > count { + count = current; + best.clear(); + best.push(bond.id.clone()); + } else if current == count && current > 0. { + best.push(bond.id.clone()); + } + } + if best.len() > 1 { + self.meta.as_mut().unwrap().rng.shuffle(&mut best); + } + for bond in best { + if let Some(key) = + self.roll_meta_chess(6, 1, None, Some(std::slice::from_ref(&bond)), &[]) + { + if self.grant_recruit(&key, player)? { + break; + } + } + } + } + Recruit::Offer { pools, fallback } => { + let pool = pools + .get(self.level - 1) + .filter(|s| !s.is_empty()) + .unwrap_or(fallback); + let tier = self.rules.data.table("choices").unwrap()["pools"][pool]["tier"] + .as_u64() + .map(|n| n as usize); + let mut keys = Vec::new(); + for _ in 0..self.rules.reward_count * 4 { + if keys.len() >= self.rules.reward_count { + break; + } + if let Some(key) = self.roll_chess_pool(pool)? { + if !keys.contains(&key) { + keys.push(key); + } + } + } + let offer_tier = tier.unwrap_or( + (self.level as i64 + self.rules.reward_offset) + .min(self.rules.reward_max_tier as i64) + .max(0) as usize, + ); + if keys.is_empty() && tier.is_some_and(|t| t > 0) { + for _ in 0..self.rules.reward_count { + for t in (1..=offer_tier).rev() { + if let Some(key) = self.roll_chess(6, Some(t), &keys) { + keys.push(key); + break; + } + } + } + } + if !keys.is_empty() { + if self.offers.len() >= self.capacity { + return Err(Error::Capacity); + } + self.offers.push_back(Offer { + tier: offer_tier, + slots: keys + .into_iter() + .take(6) + .map(|key| Slot { + kind: Kind::Chess, + key, + price: self.rules.reward_price, + frozen: false, + sold: false, + }) + .collect(), + }); + } + } + } + Ok(()) + } +} diff --git a/crates/engine/src/solo/preparation/equipment.rs b/crates/engine/src/solo/preparation/equipment.rs new file mode 100644 index 0000000..00092a7 --- /dev/null +++ b/crates/engine/src/solo/preparation/equipment.rs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::{add, Error, Kind, Location, Piece, Player, Preparation}; + +pub(super) enum ItemLocation { + Loose(Location), + Equipped { holder: u64, uid: u64 }, +} +impl Preparation { + pub(super) fn chess_locations(&self) -> Vec { + let mut out: Vec<_> = self + .board_order() + .into_iter() + .map(|(at, _)| Location::Board(at)) + .collect(); + out.extend(self.hand.iter().enumerate().filter_map(|(i, p)| { + p.as_ref() + .filter(|p| p.kind == Kind::Chess) + .map(|_| Location::Hand(i)) + })); + out.extend(self.temp.iter().enumerate().filter_map(|(i, p)| { + p.as_ref() + .filter(|p| p.kind == Kind::Chess) + .map(|_| Location::Temp(i)) + })); + out + } + pub(super) fn item_locations(&self, key: &str) -> Vec { + let mut out: Vec<_> = self + .locations() + .into_iter() + .filter(|loc| { + let p = self.piece(*loc); + p.kind == Kind::Item && p.key == key + }) + .map(ItemLocation::Loose) + .collect(); + for loc in self.chess_locations() { + let holder = self.piece(loc); + out.extend(holder.items.iter().filter(|p| p.key == key).map(|p| { + ItemLocation::Equipped { + holder: holder.uid, + uid: p.uid, + } + })); + } + out + } + pub(super) fn take_item(&mut self, loc: ItemLocation) -> Piece { + match loc { + ItemLocation::Loose(loc) => self.take(loc), + ItemLocation::Equipped { holder, uid } => { + let loc = self.find(holder).unwrap(); + let p = self.piece_mut(loc); + let at = p.items.iter().position(|p| p.uid == uid).unwrap(); + p.items.remove(at) + } + } + } + pub(super) fn equip( + &mut self, + item: u64, + target: u64, + replace: Option, + player: &mut Player, + ) -> Result<(), Error> { + let from = self.find(item).ok_or(Error::BadTarget)?; + let p = self.piece(from); + if p.kind != Kind::Item + || self.rules.data.table("items").unwrap()[&p.key]["itemType"] != "EQUIP" + { + return Err(Error::BadTarget); + } + let key = p.key.clone(); + let to = self.find(target).ok_or(Error::BadTarget)?; + let owner = self.piece(to); + if owner.kind != Kind::Chess || !self.rules.bench_equip && !matches!(to, Location::Board(_)) + { + return Err(Error::BadTarget); + } + if replace.is_some_and(|uid| !owner.items.iter().any(|p| p.uid == uid)) { + return Err(Error::BadTarget); + } + if let Some(effect) = super::consumables::compile(&self.rules.data, &key)? { + return self.consume_equipment(item, target, replace, effect, player); + } + crate::battle::equipment::compile(&self.rules.data, &key).map_err(Error::Content)?; + let item = self.take(from); + let need = self.rules.items[&key].merge; + if need > 1 && self.item_locations(&key).len() + 1 >= need { + self.merge_items(&key, Some(item), player)?; + } else { + // Detaching the incoming item does not move its carrier. + let to = self.find(target).unwrap(); + if self.piece(to).items.len() >= self.rules.equip_cap { + let at = replace.map_or(0, |uid| { + self.piece(to) + .items + .iter() + .position(|p| p.uid == uid) + .unwrap() + }); + let old = self.piece_mut(to).items.remove(at); + self.release_item(&old); + } + self.piece_mut(to).items.push(item); + self.counts.items_equipped = + add(self.counts.items_equipped, 1).map_err(|_| Error::Capacity)?; + self.check_item_merges(player)?; + } + self.refill(); + Ok(()) + } +} + +impl Preparation { + pub(super) fn cauldron_gain(&mut self, player: &mut Player) -> Result<(), Error> { + let mut live = std::collections::BTreeSet::new(); + let mut rewards = Vec::new(); + let table = self.rules.data.table("items").unwrap(); + for location in self.locations() { + let holder = self.piece(location); + if holder.kind != Kind::Chess { + continue; + } + for item in &holder.items { + let Some(buffs) = table[&item.key]["buffs"].as_array() else { + continue; + }; + for buff in buffs { + if buff["key"] != "equip_with_another_gain_coin_when_gain_char" { + continue; + } + live.insert(item.uid); + let bond = buff["bbStr"]["bond"].as_str().unwrap_or("yanShip"); + if !self.piece_bonds(holder).iter().any(|id| id == bond) { + continue; + } + let partners = buff["bbStr"]["other_equip"].as_str().unwrap_or(""); + let family = |id: &str| { + id.strip_suffix("_a") + .or_else(|| id.strip_suffix("_b")) + .unwrap_or(id) + .to_owned() + }; + if !holder.items.iter().any(|other| { + other.uid != item.uid + && partners.split(',').any(|id| { + !id.trim().is_empty() && family(id.trim()) == family(&other.key) + }) + }) { + continue; + } + let n = |key| { + super::effects::n(buff["bbStr"].get(key).unwrap_or(&buff["bb"][key]), 0.) + }; + let cap = n("max").max(0.).trunc() as u32; + if self.round.cauldron.get(&item.uid).copied().unwrap_or(0) < cap { + rewards.push((item.uid, n("count").max(0.).trunc() as u64)); + } + } + } + } + self.round.cauldron.retain(|uid, _| live.contains(uid)); + for (uid, amount) in rewards { + *self.round.cauldron.entry(uid).or_default() += 1; + player.earn(amount).map_err(|_| Error::Capacity)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/solo/preparation/equipment_lifecycle.rs b/crates/engine/src/solo/preparation/equipment_lifecycle.rs new file mode 100644 index 0000000..9dc418c --- /dev/null +++ b/crates/engine/src/solo/preparation/equipment_lifecycle.rs @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Carried preparation effects retain their state on the equipment itself. +use super::*; + +#[derive(Clone, Copy)] +pub(super) enum Event { + RoundStart, + Sold, + BattleResult, +} + +impl Preparation { + pub(super) fn promote_equipped_holder(&mut self, uid: u64) -> Result<(), Error> { + let loc = self.find(uid).ok_or(Error::BadTarget)?; + let p = self.piece(loc); + if self.rules.data.table("chess").unwrap()[&p.key]["isGolden"] == true { + return Ok(()); + } + let card = &self.rules.chess[&p.key]; + let Some(key) = card.upgrade.clone() else { + return Ok(()); + }; + let base = card.base.clone(); + let extra = self.rules.chess[&key].copies.saturating_sub(p.copies); + let copies = self.stock_take(&base, extra); + let p = self.piece_mut(loc); + p.key = key; + p.copies += copies; + self.grant_tokens(uid)?; + Ok(()) + } + pub(in crate::solo) fn equipment_battle_result( + &mut self, + player: &mut Player, + ) -> Result<(), Error> { + self.equipment_event(Event::BattleResult, player) + } + pub(super) fn equipment_event( + &mut self, + event: Event, + player: &mut Player, + ) -> Result<(), Error> { + if self.meta.is_none() { + return Ok(()); + } + let mut calls = Vec::new(); + for loc in self.chess_locations() { + let holder = self.piece(loc); + for item in &holder.items { + let raw = &self.rules.data.table("items").unwrap()[&item.key]; + if let Some(buffs) = raw["buffs"].as_array() { + for buff in buffs { + let applies = matches!( + (event, buff["key"].as_str()), + (Event::RoundStart, Some("equip_round_start_upgrade_char")) + | (Event::Sold, Some("sell_char_count_gain_equip_owner_bond")) + | (Event::BattleResult, Some("char_chess_transformation_equip")) + ); + if applies { + let count = effects::n( + buff["bbStr"].get("count").unwrap_or(&buff["bb"]["count"]), + 8., + ) + .trunc() + .max(1.); + if count > u32::MAX as f64 { + return Err(Error::Capacity); + } + calls.push((holder.uid, item.uid, count as u32)); + } + } + } + } + } + for (uid, item_uid, need) in calls { + let Some(loc) = self.find(uid) else { + continue; + }; + let Some(at) = self.piece(loc).items.iter().position(|p| p.uid == item_uid) else { + continue; + }; + match event { + Event::RoundStart => { + let item = self.piece_mut(loc).items.remove(at); + self.release_item(&item); + self.promote_equipped_holder(uid)?; + } + Event::Sold => { + let item = &mut self.piece_mut(loc).items[at]; + item.sale_charge += 1; + if item.sale_charge < need { + continue; + } + item.sale_charge = 0; + let bonds = self.piece_bonds(self.piece(loc)); + if let Some(key) = self.roll_meta_chess(self.level, 1, None, Some(&bonds), &[]) + { + self.grant_recruit(&key, player)?; + } + } + Event::BattleResult => { + let tier = (self.rules.chess[&self.piece(loc).key].tier + 1).min(6); + let Some(key) = self.roll_meta_chess(6, 1, Some(tier), None, &[]) else { + continue; + }; + let mut holder = self.take(loc); + self.remove_tokens(holder.uid); + self.return_copies(&holder); + for item in holder.items.drain(..) { + self.stow(item)?; + } + self.check_item_merges(player)?; + self.gain(Kind::Chess, &key, GainSource::Grant, player)?; + } + } + self.recompute_meta(player)?; + } + Ok(()) + } +} diff --git a/crates/engine/src/solo/preparation/input.rs b/crates/engine/src/solo/preparation/input.rs new file mode 100644 index 0000000..193e576 --- /dev/null +++ b/crates/engine/src/solo/preparation/input.rs @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::{Action, Destination}; +use crate::battle::direction::Direction; +use serde_json::Value; + +pub(super) fn keys(value: &Value, allowed: &[&str]) -> Result<(), String> { + let object = value + .as_object() + .ok_or("Expected preparation input object")?; + if let Some(key) = object.keys().find(|key| !allowed.contains(&key.as_str())) { + return Err(format!("Unsupported preparation input: {key}")); + } + Ok(()) +} +impl Action { + /// Parse the original g.* preparation intent shape at the external boundary. + pub fn parse(value: &Value) -> Result { + let kind = value["t"] + .as_str() + .ok_or("Expected preparation intent type")?; + keys( + value, + match kind { + "g.choice" => &["t", "idx", "choiceId"], + "g.art" => &["t", "itemUid", "row", "col", "dir"], + "g.buy" => &["t", "slot"], + "g.reward" => &["t", "idx"], + "g.unequip" => &["t", "itemUid"], + "g.equip" => &["t", "itemUid", "targetUid", "replaceUid"], + "g.sell" | "g.destroy" => &["t", "uid"], + "g.move" => &["t", "uid", "to", "dir"], + "g.refresh" | "g.freeze" | "g.levelUp" => &["t"], + _ => return Err(format!("Unsupported preparation intent: {kind}")), + }, + )?; + let index = |key| { + value[key] + .as_u64() + .and_then(|v| usize::try_from(v).ok()) + .ok_or("Expected preparation slot index") + }; + let uid = || value["uid"].as_u64().ok_or("Expected preparation uid"); + Ok(match kind { + "g.choice" if value.get("choiceId").is_none() => Self::Draft(index("idx")?), + "g.choice" => Self::Choice { + index: index("idx")?, + id: value["choiceId"] + .as_str() + .ok_or("Expected choice id")? + .into(), + }, + "g.art" => Self::Art { + item: value["itemUid"].as_u64().ok_or("Expected art uid")?, + tile: { + let coordinate = |key: &str| { + value[key] + .as_i64() + .and_then(|v| i32::try_from(v).ok()) + .ok_or("Expected art coordinate") + }; + [coordinate("row")?, coordinate("col")?] + }, + direction: match value + .get("dir") + .filter(|v| !v.is_null()) + .map(Value::as_str) + .unwrap_or(Some("RIGHT")) + { + Some("RIGHT") => Direction::Right, + Some("UP") => Direction::Up, + Some("DOWN") => Direction::Down, + Some("LEFT") => Direction::Left, + _ => return Err("Invalid art facing".into()), + }, + }, + "g.buy" => Self::Buy(index("slot")?), + "g.reward" => Self::PickReward(index("idx")?), + "g.equip" => Self::Equip { + item: value["itemUid"].as_u64().ok_or("Expected equipment uid")?, + target: value["targetUid"].as_u64().ok_or("Expected carrier uid")?, + replace: value + .get("replaceUid") + .filter(|v| !v.is_null()) + .map(|v| v.as_u64().ok_or("Expected replaced equipment uid")) + .transpose()?, + }, + "g.unequip" => { + Self::Unequip(value["itemUid"].as_u64().ok_or("Expected equipment uid")?) + } + "g.sell" => Self::Sell(uid()?), + "g.destroy" => Self::Destroy(uid()?), + "g.refresh" => Self::Refresh, + "g.freeze" => Self::Freeze, + "g.levelUp" => Self::LevelUp, + "g.move" => { + let to = &value["to"]; + let destination = match to["area"] + .as_str() + .ok_or("Expected preparation destination")? + { + "hand" => { + keys(to, &["area", "idx"])?; + Destination::Hand( + to["idx"] + .as_u64() + .and_then(|v| usize::try_from(v).ok()) + .ok_or("Expected hand index")?, + ) + } + "board" => { + keys(to, &["area", "row", "col", "dir"])?; + let dir = value + .get("dir") + .or_else(|| to.get("dir")) + .filter(|v| !v.is_null()); + let direction = match dir + .map(|v| v.as_str().ok_or("Expected facing string")) + .transpose()? + .unwrap_or("RIGHT") + { + "RIGHT" => Direction::Right, + "UP" => Direction::Up, + "DOWN" => Direction::Down, + "LEFT" => Direction::Left, + _ => return Err("Invalid preparation facing".into()), + }; + let coordinate = |key| { + to[key] + .as_i64() + .and_then(|v| i32::try_from(v).ok()) + .ok_or("Expected preparation board coordinate") + }; + Destination::Board { + home: [coordinate("row")?, coordinate("col")?], + direction, + } + } + _ => return Err("Invalid preparation destination".into()), + }; + Self::Move { + uid: uid()?, + to: destination, + } + } + _ => unreachable!(), + }) + } +} diff --git a/crates/engine/src/solo/preparation/items.rs b/crates/engine/src/solo/preparation/items.rs new file mode 100644 index 0000000..56d57b1 --- /dev/null +++ b/crates/engine/src/solo/preparation/items.rs @@ -0,0 +1,226 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::{add, Error, Hook, Kind, Piece, Player, Preparation}; +use serde_json::Value; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Clone, Copy)] +pub(super) enum GainSource { + Grant, + Displayed, + FixedGift, +} +#[derive(Clone)] +pub(super) enum ItemSource { + Fixed(String), + Pool { + id: String, + golden: bool, + fallback: bool, + }, +} +impl Preparation { + pub(super) fn merge_items( + &mut self, + key: &str, + incoming: Option, + player: &mut Player, + ) -> Result { + let card = &self.rules.items[key]; + let need = card.merge - usize::from(incoming.is_some()); + let upgrade = card.upgrade.clone().unwrap(); + let consumed: Vec<_> = self.item_locations(key).into_iter().take(need).collect(); + for loc in consumed { + self.take_item(loc); + } + let elite = self.new_piece(Kind::Item, &upgrade, 0)?; + let uid = elite.uid; + self.stow(elite)?; + self.counts.item_merges = add(self.counts.item_merges, 1).map_err(|_| Error::Capacity)?; + self.dispatch_meta(Hook::Merge, None, player)?; + Ok(uid) + } + pub(super) fn check_item_merges(&mut self, player: &mut Player) -> Result<(), Error> { + // Original scan order chooses the first mergeable key in hand, then temp. + // Consumption still takes temp copies before hand copies. + let limit = + self.hand.len() + self.temp.len() + self.pieces().map(|p| p.items.len()).sum::(); + for _ in 0..limit { + let mut counts = BTreeMap::new(); + let mut order = Vec::new(); + for p in self + .hand + .iter() + .chain(&self.temp) + .flatten() + .chain( + self.chess_locations() + .iter() + .flat_map(|loc| self.piece(*loc).items.iter()), + ) + .filter(|p| p.kind == Kind::Item && self.rules.items[&p.key].merge > 1) + { + let count = counts.entry(p.key.clone()).or_insert(0); + if *count == 0 { + order.push(p.key.clone()); + } + *count += 1; + } + let Some(key) = order + .into_iter() + .find(|key| counts[key] >= self.rules.items[key].merge) + else { + break; + }; + self.merge_items(&key, None, player)?; + } + Ok(()) + } + pub(super) fn grant_items( + &mut self, + source: &ItemSource, + count: f64, + player: &mut Player, + ) -> Result<(), Error> { + for _ in 0..count.clamp(0., 10.).ceil() as usize { + let (key, kind) = match source { + ItemSource::Fixed(id) => ( + self.rules.items.contains_key(id).then(|| id.clone()), + GainSource::FixedGift, + ), + ItemSource::Pool { + id, + golden, + fallback, + } => { + let valid = + self.rules.data.table("choices").unwrap()["pools"][id]["kind"] == "equip"; + let mut item = if valid { + self.roll_meta_item(Some(id), self.level, *golden)? + } else { + None + }; + if item.is_none() && *fallback { + item = self.roll_meta_item(None, self.level, false)?; + } + (item, GainSource::Grant) + } + }; + if let Some(key) = key { + self.gain(Kind::Item, &key, kind, player)?; + } + } + Ok(()) + } + pub(super) fn roll_meta_item( + &mut self, + pool_id: Option<&str>, + max_tier: usize, + golden: bool, + ) -> Result, Error> { + let pool = &self.rules.data.table("choices").unwrap()["pools"][pool_id.unwrap_or("")]; + for key in ["weighted", "items", "also"] { + if pool[key].as_array().is_some_and(|a| a.len() > 4096) { + return Err(Error::Capacity); + } + } + if pool["tiers"].as_array().is_some_and(|a| a.len() > 64) { + return Err(Error::Capacity); + } + let equip = pool["kind"] == "equip"; + if golden && equip { + if let (Some(pairs), Some(weights)) = ( + pool["weighted"].as_array(), + pool["goldenWeights"].as_array(), + ) { + if pairs.len() == weights.len() { + // Elite pool weights intentionally roll before the stock refusal. + let pairs: Vec<_> = pairs + .iter() + .zip(weights) + .filter_map(|(p, w)| { + let id = p[0].as_str()?; + self.rules + .items + .contains_key(id) + .then(|| (id.to_owned(), super::effects::n(w, 0.).max(0.))) + }) + .filter(|pair| pair.1 > 0.) + .collect(); + let weights: Vec<_> = pairs.iter().map(|p| p.1).collect(); + if let Some(i) = self.meta.as_mut().unwrap().rng.weighted(&weights) { + return Ok(Some(pairs[i].0.clone())); + } + } + } + } + let mut pairs = Vec::<(String, f64)>::new(); + if let Some(weighted) = pool["weighted"] + .as_array() + .filter(|a| equip && !a.is_empty()) + { + for p in weighted { + if let Some(id) = p[0] + .as_str() + .filter(|id| self.rules.items.contains_key(*id) && self.item_available(id)) + { + let weight = super::effects::n(&p[1], 0.).max(0.); + if let Some(pair) = pairs.iter_mut().find(|p| p.0 == id) { + pair.1 = weight; + } else { + pairs.push((id.into(), weight)); + } + } + } + } else if let Some(items) = pool["items"].as_array().filter(|a| equip && !a.is_empty()) { + for id in items + .iter() + .filter_map(Value::as_str) + .filter(|id| self.rules.items.contains_key(*id)) + { + pairs.push((id.into(), 1.)); + } + } else { + let tiers = pool["tiers"].as_array().filter(|a| equip && !a.is_empty()); + let high = if equip && pool["maxTier"] != "shopLevel" { + 6 + } else { + max_tier.clamp(1, 6) + }; + let tiers: Vec<_> = tiers + .map(|a| a.iter().filter_map(Value::as_u64).collect()) + .unwrap_or_else(|| (1..=high as u64).collect()); + for tier in tiers { + pairs.extend( + self.rules + .items + .values() + .filter(|c| c.shop && c.tier as u64 == tier) + .map(|c| (c.key.clone(), 1.)), + ); + } + } + if equip { + for id in pool["also"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter(|id| self.rules.items.contains_key(*id)) + { + if !pairs.iter().any(|p| p.0 == id) { + pairs.push((id.into(), 1.)); + } + } + } + let mut seen = BTreeSet::new(); + pairs.retain(|p| seen.insert(p.0.clone()) && self.item_available(&p.0)); + let weights: Vec<_> = pairs.iter().map(|p| p.1).collect(); + Ok(self + .meta + .as_mut() + .unwrap() + .rng + .weighted(&weights) + .map(|i| pairs[i].0.clone())) + } +} diff --git a/crates/engine/src/solo/preparation/rules.rs b/crates/engine/src/solo/preparation/rules.rs new file mode 100644 index 0000000..1d54f6d --- /dev/null +++ b/crates/engine/src/solo/preparation/rules.rs @@ -0,0 +1,331 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::Kind; +use crate::data::Catalog; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; + +pub(super) struct Card { + pub key: String, + pub base: String, + pub tier: usize, + pub upgrade: Option, + pub merge: usize, + pub copies: u64, + pub price: f64, + pub sell: u64, + pub cap: Option, + pub shop: bool, +} +pub(super) struct Rules { + pub mode_id: String, + pub data: Arc, + pub chess: BTreeMap, + pub items: BTreeMap, + pub fixed_gifts: BTreeSet, + pub equip_cap: usize, + pub bench_equip: bool, + pub slots: Vec<[usize; 2]>, + pub upgrades: Vec, + pub refresh: f64, + pub reward_count: usize, + pub reward_offset: i64, + pub reward_max_tier: usize, + pub reward_price: f64, +} +fn number(v: &Value, fallback: f64) -> f64 { + v.as_f64().filter(|v| v.is_finite()).unwrap_or(fallback) +} +fn positive(v: &Value, fallback: usize) -> usize { + v.as_u64() + .and_then(|v| usize::try_from(v).ok()) + .filter(|v| *v > 0) + .unwrap_or(fallback) +} +fn merge(to: &mut Value, from: &Value) { + if let (Some(to), Some(from)) = (to.as_object_mut(), from.as_object()) { + for (key, value) in from { + merge(to.entry(key.clone()).or_insert(Value::Null), value); + } + } else { + *to = from.clone(); + } +} +impl Rules { + pub fn load(data: Arc, mode_id: &str) -> Result { + let cfg = data.table("config").unwrap(); + let mode = &cfg["modes"][mode_id]; + if !mode.is_object() || !(mode["type"] == "SINGLE" || mode_id.starts_with("mode_single_")) { + return Err("Preparation requires a known single-player mode".into()); + } + let mut economy = cfg["economy"].clone(); + if mode["economy"].is_object() { + merge(&mut economy, &mode["economy"]); + } + let levels = positive(&mode["maxShopLevel"], 6); + if levels > 32 { + return Err("Shop level capacity exceeded".into()); + } + let defaults = [[3, 1], [4, 1], [4, 1], [5, 1], [5, 1], [5, 1]]; + let slots = (1..=levels) + .map(|level| { + let d = defaults[(level - 1).min(5)]; + let s = &mode["shopSlots"][level.to_string()]; + [ + s["chess"] + .as_u64() + .map(|v| v.min(8) as usize) + .unwrap_or(d[0]), + s["item"] + .as_u64() + .map(|v| v.min(4) as usize) + .unwrap_or(d[1]), + ] + }) + .collect(); + let upgrade_defaults = [5., 8., 11., 12., 13.]; + let upgrades = (0..levels) + .map(|i| { + if i + 1 == levels { + 0. + } else { + if let Some(prices) = mode["upgradePrices"].as_array() { + number(prices.get(i).unwrap_or(&Value::Null), 99.).max(0.) + } else { + upgrade_defaults.get(i).copied().unwrap_or(99.) + } + } + }) + .collect(); + let mut chess = BTreeMap::new(); + let mut items = BTreeMap::new(); + let golden_copies = positive(&economy["goldenCopies"], 3) as u64; + for (kind, table, out) in [ + (Kind::Chess, "chess", &mut chess), + (Kind::Item, "items", &mut items), + ] { + let raw = data.table(table).unwrap().as_object().unwrap(); + if raw.len() > 4096 { + return Err("Preparation definition capacity exceeded".into()); + } + for (key, rec) in raw { + let golden = rec["isGolden"] == true; + let tier = rec["tier"] + .as_u64() + .filter(|v| *v > 0 && *v <= 64) + .unwrap_or(1) as usize; + let base = if kind == Kind::Chess { + rec["baseId"] + .as_str() + .map(str::to_owned) + .unwrap_or_else(|| { + if golden { + key.strip_suffix("_b") + .map(|s| format!("{s}_a")) + .unwrap_or(key.clone()) + } else { + key.clone() + } + }) + } else { + key.strip_suffix("_b") + .map(|s| format!("{s}_a")) + .unwrap_or(key.clone()) + }; + let upgrade = if kind == Kind::Chess { + rec["goldenId"] + .as_str() + .filter(|id| raw.contains_key(*id)) + .map(str::to_owned) + .or_else(|| { + let alt = key + .strip_suffix("_a") + .map(|s| format!("{s}_b")) + .unwrap_or(key.clone()); + raw.contains_key(&alt).then_some(alt) + }) + } else { + rec["upgradeChessId"] + .as_str() + .or(rec["goldenId"].as_str()) + .filter(|id| raw.contains_key(*id)) + .map(str::to_owned) + }; + let recipe = if kind == Kind::Chess { + rec["upgradeNum"] + .as_u64() + .filter(|v| *v > 0) + .map(|v| v as usize) + .unwrap_or_else(|| { + economy["mergeCountOverrides"][key] + .as_i64() + .map(|v| v.max(0) as usize) + .unwrap_or(positive(&economy["mergeCount"], 3)) + }) + } else { + rec["upgradeNum"] + .as_u64() + .map(|v| v as usize) + .unwrap_or(positive(&economy["itemMergeCount"], 2)) + }; + let merge = if golden + || upgrade.is_none() + || kind == Kind::Item + && (rec["itemType"] != "EQUIP" || rec["mergeable"] != true) + { + 0 + } else { + recipe + }; + let form = if golden { "golden" } else { "normal" }; + let price = if kind == Kind::Chess { + let fallback = [0., 2., 3., 3., 3., 4., 4.] + .get(tier) + .copied() + .unwrap_or(3.); + let row = &economy["chessPrice"][tier.to_string()]; + rec["price"] + .as_f64() + .filter(|v| v.is_finite() && *v >= 0.) + .unwrap_or_else(|| number(&row[form], fallback)) + } else { + rec["price"] + .as_f64() + .filter(|v| v.is_finite() && *v >= 0.) + .unwrap_or(2.) + }; + let override_price = mode["economy"]["chessPrice"][tier.to_string()][form] + .as_f64() + .filter(|v| v.is_finite() && *v >= 0.); + let price = if kind == Kind::Chess { + override_price.unwrap_or(price) + } else { + price + }; + let sell = number( + &mode["economy"]["chessSell"][tier.to_string()][form], + f64::NAN, + ); + let sell = if sell >= 0. { + sell + } else { + rec["sellPrice"] + .as_f64() + .filter(|v| v.is_finite() && *v >= 0.) + .unwrap_or_else(|| { + number(&economy["chessSell"][tier.to_string()][form], 1.) + }) + }; + let shop = if kind == Kind::Chess { + (rec["visible"] == true && rec["isDiy"] != true || rec["diyFor"].is_string()) + && !golden + && rec["isHidden"] != true + && rec["tier"].as_i64().is_some() + } else { + !golden + && rec["hideInShop"] != true + && rec["shopExcluded"] != true + && rec["itemType"] == "EQUIP" + && rec["tier"].as_i64().is_some() + }; + let cap = if kind == Kind::Chess { + Some( + economy["poolCopiesOverrides"][&base] + .as_u64() + .or(economy["poolCopies"][tier.to_string()].as_u64()) + .unwrap_or([0, 12, 14, 18, 16, 8, 5].get(tier).copied().unwrap_or(10)), + ) + } else { + let normal = raw.get(&base).unwrap_or(&Value::Null); + let shop_base = normal["isGolden"] != true + && normal["hideInShop"] != true + && normal["shopExcluded"] != true + && normal["itemType"] == "EQUIP" + && normal["tier"].as_i64().is_some(); + if shop_base { + economy["itemPoolCopiesOverrides"][&base] + .as_u64() + .or(economy["itemPoolCopies"][normal["tier"].to_string()].as_u64()) + } else { + None + } + }; + if !price.is_finite() + || price.abs() > super::super::MAX_FUNDS as f64 + || sell.abs() > super::super::MAX_FUNDS as f64 + || cap.is_some_and(|v| v > super::super::MAX_FUNDS) + || recipe > 4096 + || golden_copies > 4096 + { + return Err("Preparation numeric capacity exceeded".into()); + } + out.insert( + key.clone(), + Card { + key: key.clone(), + base, + tier, + upgrade, + merge, + copies: if kind == Kind::Chess { + if golden { + golden_copies + } else { + 1 + } + } else if golden { + 2 + } else { + 1 + }, + price, + sell: sell.trunc().max(0.) as u64, + cap, + shop, + }, + ); + } + } + let reward = &economy["rewardOffer"]; + let fixed_gifts = data + .table("garrisons") + .unwrap() + .as_object() + .unwrap() + .values() + .filter(|g| g["effectKey"] == "SERVER_GAIN_EQUIP") + .filter_map(|g| g["bbStr"]["chess"].as_str()) + .map(str::to_owned) + .collect(); + let equip_cap = positive(&economy["equipPerChess"], 2); + if equip_cap > 16 { + return Err("Equipment slot capacity exceeded".into()); + } + let bench_equip = cfg["version"]["rules"]["benchEquip"] != false; + Ok(Self { + mode_id: mode_id.into(), + equip_cap, + bench_equip, + fixed_gifts, + data, + chess, + items, + slots, + upgrades, + refresh: number(&economy["refreshPrice"], 1.).max(0.), + reward_count: positive(&reward["count"], 3).min(6), + reward_offset: reward["tierOffset"].as_i64().unwrap_or(1), + reward_max_tier: positive(&reward["maxTier"], 6).min(64), + reward_price: number(&reward["price"], 0.).max(0.), + }) + } + pub fn card(&self, kind: Kind, key: &str) -> Option<&Card> { + match kind { + Kind::Chess => self.chess.get(key), + Kind::Item => self.items.get(key), + Kind::Token => None, + } + } +} diff --git a/crates/engine/src/solo/preparation/summons.rs b/crates/engine/src/solo/preparation/summons.rs new file mode 100644 index 0000000..57115b9 --- /dev/null +++ b/crates/engine/src/solo/preparation/summons.rs @@ -0,0 +1,327 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Placeable summon inventory, bound to the deployed owner's UID. +use super::*; + +pub(in crate::solo) struct PreparedToken { + pub key: String, + pub placement: Placement, + pub owner_uid: u64, +} + +impl Preparation { + pub(super) fn owner_positions(&self) -> Vec<([i32; 2], u64)> { + self.board_insertion + .iter() + .map(|at| (*at, &self.board[at])) + .filter(|(_, p)| p.kind == Kind::Chess) + .map(|(at, p)| (at, p.uid)) + .collect() + } + fn token_stack(&self, key: &str, owner_uid: Option) -> Option { + let matches = |p: &Piece| p.kind == Kind::Token && p.key == key && p.owner_uid == owner_uid; + self.hand + .iter() + .position(|p| p.as_ref().is_some_and(matches)) + .map(Location::Hand) + .or_else(|| { + self.temp + .iter() + .position(|p| p.as_ref().is_some_and(matches)) + .map(Location::Temp) + }) + } + pub(super) fn grant_tokens(&mut self, owner_uid: u64) -> Result<(), Error> { + let Some(owner) = self + .board + .values() + .find(|p| p.uid == owner_uid && p.kind == Kind::Chess) + else { + return Ok(()); + }; + let data = &self.rules.data; + let rec = &data.table("chess").unwrap()[&owner.key]; + let mut stock = Vec::new(); + for key in rec["tokens"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + let token = &data.table("tokens").unwrap()[key]; + if token["kind"] != "summon" || token["placeable"] != true { + continue; + } + let base = self.rules.chess[&owner.key].base.as_str(); + let variant = token["variants"] + .get(&owner.key) + .or_else(|| token["variants"].get(base)); + if variant.is_some_and(|v| { + !v["sources"] + .as_array() + .is_some_and(|sources| sources.iter().any(|s| s == "talent" || s == "skill")) + }) { + continue; + } + let count = variant + .and_then(|v| v["stats"]["deployLimit"].as_u64()) + .filter(|n| *n > 0) + .or_else(|| token["deployLimit"].as_u64().filter(|n| *n > 0)) + .unwrap_or(1) + .min(9); + stock.push((key.to_owned(), count)); + } + for (key, count) in stock { + let held: u64 = self + .pieces() + .filter(|p| p.kind == Kind::Token && p.key == key && p.owner_uid == Some(owner_uid)) + .map(|p| p.count) + .sum(); + if held >= count { + continue; + } + if let Some(loc) = self.token_stack(&key, Some(owner_uid)) { + self.piece_mut(loc).count += count - held; + } else { + if self.len() >= self.capacity { + return Err(Error::Capacity); + } + let mut token = self.new_piece(Kind::Token, &key, 0)?; + token.count = count - held; + token.owner_uid = Some(owner_uid); + self.stow(token)?; + } + } + Ok(()) + } + pub(super) fn remove_tokens(&mut self, owner_uid: u64) { + let locations: Vec<_> = self + .locations() + .into_iter() + .filter(|&loc| { + let p = self.piece(loc); + p.kind == Kind::Token && p.owner_uid == Some(owner_uid) + }) + .collect(); + for loc in locations { + self.take(loc); + } + } + pub(super) fn return_token( + &mut self, + mut token: Piece, + prefer: Option, + allow_temp: bool, + ) -> Result<(), Error> { + token.direction = None; + if let Some(loc) = self.token_stack(&token.key, token.owner_uid) { + self.piece_mut(loc).count = + add(self.piece(loc).count, token.count).map_err(|_| Error::Capacity)?; + } else if let Some(i) = prefer.filter(|&i| self.hand[i].is_none()) { + self.hand[i] = Some(token); + } else if allow_temp || self.free_hand().is_some() { + self.stow(token)?; + } else { + return Err(Error::HandFull); + } + Ok(()) + } + pub(super) fn token_legal(&self, piece: &Piece, home: [i32; 2]) -> bool { + let token = &self.rules.data.table("tokens").unwrap()[&piece.key]; + if !self.grid.can_place(token, home) { + return false; + } + let Some((at, owner)) = self + .board + .iter() + .find(|(_, p)| p.kind == Kind::Chess && Some(p.uid) == piece.owner_uid) + else { + return false; + }; + let fixed = piece.key == "token_10032_jesca2_jckshd"; + if token["ownerRange"] != true && token["ownerRangeOutside"] != true && !fixed { + return true; + } + let offsets: Vec<[i32; 2]> = if fixed { + vec![[0, 1], [1, 0], [0, -1], [-1, 0]] + } else { + let raw = &self.rules.data.table("chess").unwrap()[&owner.key]["rangeGrid"]; + match serde_json::from_value(raw.clone()) { + Ok(grid) => grid, + Err(_) => return false, + } + }; + let keys = crate::battle::targeting::absolute_range( + &offsets, + *at, + owner.direction.unwrap_or(Direction::Right), + 0, + ); + let inside = + keys.contains(&(home[0] as usize * crate::battle::grid::COLS + home[1] as usize)); + if token["ownerRangeOutside"] == true { + !inside + } else { + inside + } + } + fn move_token(&mut self, from: Location, to: Destination) -> Result<(), Error> { + match to { + Destination::Hand(i) => { + if i >= self.hand.len() { + return Err(Error::BadTarget); + } + if matches!(from, Location::Board(_)) { + let token = self.take(from); + self.return_token(token, Some(i), false)?; + } else { + let token = self.take(from); + if let Some(other) = self.hand[i].take() { + self.put(from, other); + } + self.hand[i] = Some(token); + } + } + Destination::Board { home, direction } => { + let source = self.piece(from).clone(); + if let Location::Board(old) = from { + if old == home { + if !self.legal(&source, home) { + return Err(Error::BadTile); + } + self.board.get_mut(&home).unwrap().direction = Some(direction); + return Ok(()); + } + let mut token = self.take(from); + let other = self.remove_board(&home); + if let Some(other) = other { + self.insert_board(old, other); + } + token.direction = Some(direction); + self.insert_board(home, token); + if !self.legal(&self.board[&home], home) + || self.board.get(&old).is_some_and(|p| !self.legal(p, old)) + { + return Err(Error::BadTile); + } + } else { + if self.board.contains_key(&home) || !self.legal(&source, home) { + return Err(Error::BadTile); + } + let mut token = if source.count > 1 { + if self.len() >= self.capacity { + return Err(Error::Capacity); + } + self.piece_mut(from).count -= 1; + let mut token = self.new_piece(Kind::Token, &source.key, 0)?; + token.owner_uid = source.owner_uid; + token + } else { + self.take(from) + }; + token.direction = Some(direction); + self.insert_board(home, token); + } + } + } + Ok(()) + } + pub(super) fn move_piece(&mut self, uid: u64, to: Destination) -> Result<(), Error> { + let from = self.find(uid).ok_or(Error::BadTarget)?; + let mut old_owners = self.owner_positions(); + old_owners.sort_by_key(|(_, owner)| *owner == uid); + let board_swap_order = match (from, to) { + (Location::Board(old), Destination::Board { home, .. }) + if old != home && self.board.contains_key(&home) => + { + Some(self.board_insertion.clone()) + } + _ => None, + }; + let token = self.piece(from).kind == Kind::Token; + if token { + self.move_token(from, to)?; + } else { + if matches!(from, Location::Board(_)) && matches!(to, Destination::Hand(_)) { + self.remove_tokens(uid); + } + self.move_chess_or_item(uid, to)?; + } + if let Some(order) = board_swap_order { + self.board_insertion = order; + } + for (old, owner) in old_owners { + let now = self + .board + .iter() + .find(|(_, p)| p.uid == owner) + .map(|(at, _)| *at); + if now.is_none() { + self.remove_tokens(owner); + } else if now != Some(old) { + let lifted: Vec<_> = self + .board_insertion + .iter() + .copied() + .filter(|at| { + let p = &self.board[at]; + p.kind == Kind::Token + && p.owner_uid == Some(owner) + && !(token && p.uid == uid) + }) + .collect(); + for at in lifted { + let p = self.remove_board(&at).unwrap(); + self.return_token(p, None, true)?; + } + } + } + let illegal: Vec<_> = self + .board + .iter() + .filter(|(at, p)| p.kind == Kind::Token && !self.legal(p, **at)) + .map(|(at, _)| *at) + .collect(); + if matches!((from, to), (Location::Board(old), Destination::Board { home, .. }) if old == home) + { + let needs_slot: BTreeSet<_> = illegal + .iter() + .map(|at| &self.board[at]) + .filter(|p| self.token_stack(&p.key, p.owner_uid).is_none()) + .map(|p| (&p.key, p.owner_uid)) + .collect(); + let available = self + .hand + .iter() + .chain(&self.temp) + .filter(|p| p.is_none()) + .count(); + if needs_slot.len() > available { + return Err(Error::HandFull); + } + } + for at in illegal { + let p = self.remove_board(&at).unwrap(); + self.return_token(p, None, true)?; + } + for (_, owner) in self.owner_positions() { + self.grant_tokens(owner)?; + } + self.refill(); + Ok(()) + } + pub(in crate::solo) fn prepared_tokens(&self) -> Vec { + self.board_order() + .into_iter() + .filter(|(_, p)| p.kind == Kind::Token) + .map(|(home, p)| PreparedToken { + key: p.key.clone(), + owner_uid: p.owner_uid.unwrap(), + placement: Placement { + uid: p.uid, + home, + direction: p.direction.unwrap_or(Direction::Right), + }, + }) + .collect() + } +} diff --git a/crates/engine/src/solo/preparation/view.rs b/crates/engine/src/solo/preparation/view.rs new file mode 100644 index 0000000..da29ee7 --- /dev/null +++ b/crates/engine/src/solo/preparation/view.rs @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Explicit public projection. Never derive policy input by filtering diagnostics. +use super::*; +impl Preparation { + pub(in crate::solo) fn public_view(&self, player: &Player) -> Result { + let piece = |p: &Piece| { + let table = match p.kind { + Kind::Chess => "chess", + Kind::Item => "items", + Kind::Token => "tokens", + }; + let rec = &self.rules.data.table(table).unwrap()[&p.key]; + json!({"uid":p.uid,"kind":p.kind.name(),"id":p.key,"golden":rec["isGolden"]==true, + "tier":rec["tier"],"count":p.count,"ownerUid":p.owner_uid, + "items":p.items.iter().map(|i|json!({"uid":i.uid,"id":i.key})).collect::>()}) + }; + // Prices in the public protocol are nonnegative integer currency. + let slot = |s: &Slot| json!({"kind":s.kind.name(),"id":s.key,"price":s.price as u64,"sold":s.sold,"frozen":s.frozen}); + let slots = self + .slots + .iter() + .map(|s| { + s.as_ref() + .map(|s| { + let mut v = slot(s); + let price = if s.kind == Kind::Chess { + self.meta_price(&s.key, s.price) + .map_err(|e| e.to_string())? + } else { + s.price.round().max(0.) + }; + v["price"] = json!(price as u64); + Ok::<_, String>(v) + }) + .transpose() + }) + .collect::, _>>()?; + let board = self + .board_order() + .into_iter() + .map(|(at, p)| { + let mut v = piece(p); + v["row"] = json!(at[0]); + v["col"] = json!(at[1]); + v["dir"] = json!(p.direction.unwrap_or(Direction::Right).name()); + v + }) + .collect::>(); + let mut bonds = Vec::new(); + if let Some(meta) = &self.meta { + for b in &meta.rules.bonds { + if let Some(s) = meta.bonds.get(&b.id) { + if s.count > 0. || s.layers > 0. || s.active() { + let mut v = json!({"bondId":b.id,"count":s.count,"layers":s.layers,"tier":s.tier,"active":s.active(),"thresholds":b.thresholds,"countsHand":matches!(b.mode,bonds::Counting::HandAndBoard)}); + if s.harmony > 0 { + v["harmony"] = json!(s.harmony); + } + bonds.push(v); + } + } else if b.off { + let mut ids = BTreeSet::new(); + for p in self.board.values().chain( + self.hand + .iter() + .flatten() + .filter(|_| matches!(b.mode, bonds::Counting::HandAndBoard)), + ) { + if p.kind == Kind::Chess && self.piece_bonds(p).contains(&b.id) { + ids.insert(self.rules.chess[&p.key].base.clone()); + } + } + if !ids.is_empty() { + bonds.push(json!({"bondId":b.id,"count":ids.len(),"layers":meta.layers.get(&b.id).copied().unwrap_or(0.),"tier":0,"active":false,"off":true,"thresholds":b.thresholds,"countsHand":matches!(b.mode,bonds::Counting::HandAndBoard)})); + } + } + } + } + bonds.sort_by(|a, b| { + (a["off"] == true) + .cmp(&(b["off"] == true)) + .then_with(|| (b["active"] == true).cmp(&(a["active"] == true))) + .then_with(|| { + b["layers"] + .as_f64() + .unwrap_or(0.) + .total_cmp(&a["layers"].as_f64().unwrap_or(0.)) + }) + }); + let mut effects = Vec::new(); + for (id, seq) in self + .draft_effects + .battle + .iter() + .chain(&self.draft_effects.maps) + { + effects.push(json!({"id":format!("{id}#{seq}"),"iconId":id,"iconKind":"choice"})); + } + for u in &self.draft_effects.upgrades { + effects.push(json!({"id":u.id,"iconId":u.id,"iconKind":"choice","counter":u.left})); + } + for b in &self.bounties { + let b = b.report(); + effects.push(json!({"id":b["id"],"iconId":b["card"]["effectId"],"iconKind":"choice","counter":b["roundsLeft"]})); + } + Ok( + json!({"t":"m.private","playerId":"solo","seat":0,"alive":player.lp>0.,"lp":player.lp,"funds":player.funds, + "ready":false,"canReady":self.check_ready().is_ok(),"personalChoice":self.personal_choice.as_ref().map(bounties::Choice::report), + "hand":self.hand.iter().map(|p|p.as_ref().map(&piece)).collect::>(), + "temp":self.temp.iter().map(|p|p.as_ref().map(&piece)).collect::>(),"board":board, + "shop":{"level":self.level,"maxLevel":self.rules.slots.len(), + "upgradePrice":if self.level>=self.rules.slots.len(){0}else{self.upgrade_price as u64}, + "refreshPrice":if self.free_refreshes>0{0}else{self.rules.refresh as u64},"freeRefreshes":self.free_refreshes,"frozen":self.frozen, + "slots":slots, + "rewardOffer":self.offers.front().map(|o|json!({"tier":o.tier,"queued":self.offers.len()-1,"slots":o.slots.iter().map(&slot).collect::>() }))}, + "deployCap":self.deploy_cap,"deployCount":self.board.values().filter(|p|p.kind==Kind::Chess).count(), + "deployment":{"field":if self.boss{"bossL"}else{"normal"},"cells":self.grid.public_cells()}, + "bonds":bonds,"effects":effects,"loadout":{},"ops":{},"diy":self.rules.data.table("diy").cloned().unwrap_or_else(||json!({})),"standIns":[], + "stats":{"gold":player.stats.funds_spent,"refreshes":self.counts.refreshes,"merges":self.counts.merges, + "kills":player.stats.kills,"leaks":player.stats.leaks,"dmgDealt":player.stats.damage.round()}}), + ) + } +} diff --git a/crates/engine/src/solo/session.rs b/crates/engine/src/solo/session.rs new file mode 100644 index 0000000..686e640 --- /dev/null +++ b/crates/engine/src/solo/session.rs @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Persistent native execution boundary. Diagnostics are NOT policy observations. +//! A tick budget suspends combat; it never fabricates an episode truncation. +use super::{preparation::Action, Phase, Runner}; +use crate::data::Catalog; +use serde_json::{json, Value}; +use std::sync::Arc; +mod setup; +mod spatial; +mod view; + +/// Bounded work per call; callers can resume the same battle with advance(). +pub const MAX_TICK_BUDGET: usize = 108_000; + +pub struct Session { + run: Runner, + revision: u64, + fault: Option, + public_setup: Value, + preview: Vec, + spatial: std::sync::Mutex, +} +impl Session { + /// Only Desperation is supported. Core choice is an experiment parameter. + pub fn new( + data: Arc, + seed: u32, + core: &str, + banned: &[String], + ) -> Result { + Self::new_at_revision(data, seed, core, banned, 0) + } + pub fn new_at_revision( + data: Arc, + seed: u32, + core: &str, + banned: &[String], + setup_revision: u32, + ) -> Result { + let (run, public_setup) = setup::start(data, seed, core, banned, setup_revision)?; + let mut session = Self::from_runner(run); + session.public_setup = public_setup; + Ok(session) + } + pub(in crate::solo) fn from_runner(run: Runner) -> Self { + Self { + run, + revision: 0, + fault: None, + public_setup: json!({}), + preview: vec![], + spatial: std::sync::Mutex::new(spatial::Cache::default()), + } + } + fn healthy(&self) -> Result<(), String> { + if let Some(error) = &self.fault { + Err(error.clone()) + } else { + Ok(()) + } + } + fn check_budget(&self, budget: usize) -> Result<(), String> { + self.healthy()?; + if budget > MAX_TICK_BUDGET { + return Err("Tick budget exceeds per-call limit".into()); + } + if self.revision == u64::MAX { + return Err("Session revision exhausted".into()); + } + Ok(()) + } + fn fail(&mut self, error: String) -> Result { + self.fault = Some(error.clone()); + Err(error) + } + /// Internal inspection only: includes pool and RNG state, never feed to a policy. + pub fn diagnostics(&self) -> Result { + self.healthy()?; + self.run.report() + } + pub fn replay_frame(&self) -> Result { + self.healthy()?; + match self.run.field()? { + Some(field) => { + let mut frame = field.replay_frame()?; + frame["round"] = json!(self.run.snapshot()?.round); + Ok(frame) + } + None => Ok(Value::Null), + } + } + /// Diagnostic only. None means that no battle is currently suspended. + pub fn movement_batch_ticks(&self) -> Result, String> { + self.healthy()?; + Ok(self.run.field()?.map(|field| field.movement_batch_ticks())) + } + pub fn movement_path_steps(&self) -> Result, String> { + self.healthy()?; + Ok(self.run.field()?.map(|field| field.movement_path_steps())) + } + pub fn event_window_stats(&self) -> Result, String> { + self.healthy()?; + Ok(self.run.field()?.map(|field| field.event_window_stats())) + } + fn receipt( + &self, + accepted: Option, + rejection: Option<&str>, + ticks: usize, + ) -> Result { + let s = self.run.snapshot()?; + Ok(json!({ + "revision": self.revision, + "phase": match s.phase { + Phase::Prep => "prep", Phase::Draft => "draft", Phase::Combat => "combat", + Phase::Result => "result", Phase::Faulted => "faulted", + }, + "round": s.round, + "terminated": s.phase == Phase::Result, + "decisionRequired": matches!(s.phase, Phase::Prep | Phase::Draft), + "budgetExhausted": s.phase == Phase::Combat, + "accepted": accepted, "rejection": rejection, "ticks": ticks, + })) + } + pub fn status(&self) -> Result { + self.healthy()?; + self.receipt(None, None, 0) + } + /// Submit exactly one preparation/draft intent. g.ready advances only the + /// resulting battle, stopping at the next decision or the supplied budget. + /// Malformed input does not consume a revision; rule rejection does. + pub fn step(&mut self, value: &Value, budget: usize) -> Result { + self.check_budget(budget)?; + if !matches!(self.run.phase(), Phase::Prep | Phase::Draft) { + return Err( + "Step requires a decision; resume combat with advance or reset an ended session" + .into(), + ); + } + let ready = value["t"] == "g.ready"; + let action = if ready { + if value + .as_object() + .is_none_or(|o| o.keys().any(|k| k != "t" && k != "ready")) + || value.get("ready").is_some_and(|v| v != true) + { + return Err("g.ready requires ready=true when supplied".into()); + } + None + } else { + Some(Action::parse(value)?) + }; + if ready && self.run.phase() == Phase::Prep { + self.preview = self.current_preview()?; + } + let result = if let Some(action) = action { + self.run.prep_action(action) + } else { + self.run.ready_current() + }; + match result { + Err(error) if self.run.phase() != Phase::Faulted && is_rejection(&error) => { + self.revision += 1; + self.receipt(Some(false), Some(&error), 0) + } + Err(error) => self.fail(error), + Ok(()) => { + self.revision += 1; + let advance = match self.run.advance(budget) { + Ok(a) => a, + Err(error) => return self.fail(error), + }; + self.receipt(Some(true), None, advance.ticks) + } + } + } + /// Resume a suspended battle without replaying its ready action or settlement. + pub fn advance(&mut self, budget: usize) -> Result { + self.check_budget(budget)?; + if self.run.phase() != Phase::Combat { + return Err("Advance requires suspended combat".into()); + } + let advance = match self.run.advance(budget) { + Ok(a) => a, + Err(error) => return self.fail(error), + }; + self.revision += 1; + self.receipt(None, None, advance.ticks) + } +} +fn is_rejection(error: &str) -> bool { + matches!( + error, + "BAD_TARGET" + | "SOLD_OUT" + | "NO_FUNDS" + | "HAND_FULL" + | "BOARD_FULL" + | "BAD_TILE" + | "MAX_LEVEL" + | "TEMP_NOT_EMPTY" + | "WRONG_PHASE" + ) +} diff --git a/crates/engine/src/solo/session/setup.rs b/crates/engine/src/solo/session/setup.rs new file mode 100644 index 0000000..f2e9083 --- /dev/null +++ b/crates/engine/src/solo/session/setup.rs @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Convert the generated, private mode plan into a live runner once per reset. +use super::*; +use crate::battle::{runtime::BossOvertime, waves::Template}; +use crate::solo::{preparation, Boss, Config, HiddenRule, RoundKind, RoundPlan}; + +pub(super) fn start( + data: Arc, + seed: u32, + core: &str, + banned: &[String], + setup_revision: u32, +) -> Result<(Runner, Value), String> { + crate::battle::runtime::Field::validate_core(&data, core)?; + let generated = super::super::mode::generate_at_revision( + &data, + seed, + "mode_single_abyss", + banned, + setup_revision, + )?; + let input = generated.input; + let cfg = &input["config"]; + let number = |v: &Value| { + v.as_f64() + .ok_or_else(|| "Invalid generated number".to_owned()) + }; + let integer = |v: &Value| { + v.as_u64() + .ok_or_else(|| "Invalid generated integer".to_owned()) + }; + let config = Config { + initial_lp: number(&cfg["lp"])?, + lp_cap_per_round: integer(&cfg["lpCap"])?, + keep_funds: cfg["keepFunds"] + .as_bool() + .ok_or("Invalid generated keepFunds")?, + hidden: if cfg["hidden"].is_null() { + None + } else { + Some(HiddenRule { + layer_threshold: number(&cfg["hidden"]["layerThreshold"])?, + min_lp_exclusive: number(&cfg["hidden"]["minLp"])?, + }) + }, + }; + let limits = crate::battle::runtime::Limits::default(); + let plans = input["plans"] + .as_array() + .ok_or("Missing generated plans")? + .iter() + .map(|p| { + let boss = || -> Result { + let o = &p["overtime"]; + Ok(Boss { + max_hp: number(&p["maxHp"])?, + overtime: if o.is_null() { + None + } else { + Some(BossOvertime { + after_real_seconds: number(&o["afterReal"])?, + combat_time_scale: number(&o["combatTimeScale"])?, + lp_per_real_second: number(&o["lpPerSecond"])?, + }) + }, + }) + }; + let kind = match p["kind"].as_str() { + Some("normal") => RoundKind::Normal, + Some("boss") => RoundKind::FinalAssault(boss()?), + Some("hidden") => RoundKind::HiddenCore(boss()?), + _ => return Err("Invalid generated round kind".into()), + }; + let mut wave = Template::parse( + p, + &Value::Null, + &Value::Null, + limits.units, + limits.route_legs, + )?; + if let Some(id) = p["templateId"].as_str() { + wave.configure_bounty_actions( + &data.table("waves").ok_or("Missing waves")?[id], + p["spawnActions"] + .as_array() + .ok_or("Missing generated spawn actions")?, + &data.table("factions").ok_or("Missing factions")?["templateSlots"], + limits.units, + )?; + } + wave.spawns = p["spawns"] + .as_array() + .ok_or("Missing generated spawns")? + .clone(); + Ok(RoundPlan { + kind, + wave, + time_limit: if p["timeLimit"].is_null() && p["kind"] != "normal" { + f64::INFINITY + } else { + number(&p["timeLimit"])? + }, + income: integer(&p["income"])?, + deploy_cap: usize::try_from(integer(&p["deployCap"])?) + .map_err(|_| "Invalid generated deployment cap")?, + }) + }) + .collect::, String>>()?; + let strings = |v: &Value| -> Result, String> { + serde_json::from_value(v.clone()).map_err(|e| e.to_string()) + }; + let mut banned = strings(&input["preparation"]["banned"])?; + let off: std::collections::BTreeSet<_> = generated.setup["disabledBonds"] + .as_array() + .into_iter() + .flatten() + .chain( + generated.setup["staticInactiveBonds"] + .as_array() + .into_iter() + .flatten(), + ) + .filter_map(Value::as_str) + .collect(); + for (id, rec) in data.table("chess").unwrap().as_object().unwrap() { + if rec["diyFor"] == id.as_str() + && rec["bonds"].as_array().is_some_and(|bs| { + !bs.is_empty() + && bs + .iter() + .all(|b| b.as_str().is_some_and(|b| off.contains(b))) + }) + { + banned.push(id.clone()); + } + } + let prep = preparation::Config { + mode_id: "mode_single_abyss".into(), + banned, + initial: vec![], + capacity: 256, + effects: Some(preparation::EffectsConfig { + disabled_bonds: strings(&input["preparation"]["effects"]["disabledBonds"])?, + ..Default::default() + }), + }; + let mut run = Runner::new_with_preparation( + data, + input["stage"].clone(), + seed.max(1), + config, + plans, + limits, + prep, + )?; + run.configure_map(Default::default())?; + run.configure_core(core)?; + run.enable_drafts( + generated.setup["stageId"] + .as_str() + .ok_or("Missing generated stage ID")?, + )?; + let setup = &generated.setup; + let mode = &run.data.table("config").unwrap()["modes"]["mode_single_abyss"]; + let disabled: std::collections::BTreeSet<_> = setup["disabledBonds"] + .as_array() + .into_iter() + .flatten() + .chain( + setup["staticInactiveBonds"] + .as_array() + .into_iter() + .flatten(), + ) + .filter_map(Value::as_str) + .collect(); + let public = json!({"modeId":"mode_single_abyss","difficulty":"ABYSS", + "stageId":setup["stageId"],"factions":setup["factions"],"bossId":setup["bossId"], + "disabledBonds":disabled,"drawnDisabledBonds":setup["disabledBonds"],"bannedChess":setup["banned"], + "bossRound":run.boss_index+1,"lastRound":mode["lastRound"].as_u64().unwrap_or((run.boss_index+1) as u64), + "hiddenRound":mode["hiddenRound"],"offers":[]}); + Ok((run, public)) +} diff --git a/crates/engine/src/solo/session/spatial.rs b/crates/engine/src/solo/session/spatial.rs new file mode 100644 index 0000000..7c8e759 --- /dev/null +++ b/crates/engine/src/solo/session/spatial.rs @@ -0,0 +1,509 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Decision-time geometry derived from public map data, templates and previews. +use super::*; +use crate::battle::{ + grid::{Grid, Rect, BLOCK, COLS, CRATE, N}, + waves::{has_patrol, normalize_route}, +}; +use crate::deterministic::math::round_half_even; + +const MAX_ROUTES: usize = 64; +const MAX_CHECKPOINTS: usize = 256; +const MAX_PATH_CELLS: usize = 65_536; +const MAX_BYTES: usize = 8 << 20; + +fn position(value: &Value) -> Result<[f64; 2], String> { + let coordinates = value.as_array().ok_or("Invalid public spatial position")?; + if coordinates.len() != 2 { + return Err("Invalid public spatial position".into()); + } + let row = coordinates[0] + .as_f64() + .ok_or("Invalid public spatial row")?; + let col = coordinates[1] + .as_f64() + .ok_or("Invalid public spatial column")?; + if !row.is_finite() || !col.is_finite() { + return Err("Non-finite public spatial position".into()); + } + Ok([row, col]) +} + +fn cell(point: [f64; 2]) -> Result<[i32; 2], String> { + let point = point.map(round_half_even); + if point[0] < 0. + || point[0] >= crate::battle::grid::ROWS as f64 + || point[1] < 0. + || point[1] >= COLS as f64 + { + return Err("Public spatial position outside the stage".into()); + } + Ok(point.map(|n| n as i32)) +} + +fn segment( + grid: &mut Grid, + from: [f64; 2], + to: [f64; 2], + checkpoint: Option, + flying: bool, + remaining: &mut usize, +) -> Result { + let start = cell(from)?; + let end = cell(to)?; + let path = if flying { + None + } else { + grid.find_path(start, end, false) + }; + let size = path.as_ref().map_or(0, Vec::len); + *remaining = remaining + .checked_sub(size) + .ok_or("Public spatial path capacity exceeded")?; + Ok(json!({"from":from,"to":to,"checkpoint":checkpoint,"groundCells":path})) +} + +fn route(raw: &Value, grid: &mut Grid, remaining: &mut usize) -> Result { + let mut route = normalize_route(raw, MAX_CHECKPOINTS)?; + // E_NUM entries are reserved template slots with no concrete route yet. + if raw["motion"] == "E_NUM" { + route["motion"] = json!("E_NUM"); + route["segments"] = json!([]); + route["repeatFrom"] = Value::Null; + return Ok(route); + } + let flying = route["motion"] == "FLY"; + let mut cursor = position(&route["start"])?; + cell(cursor)?; + let mut segments = Vec::new(); + let patrol = has_patrol(raw); + for (index, checkpoint) in route["checkpoints"].as_array().unwrap().iter().enumerate() { + match checkpoint["type"].as_str() { + Some("MOVE") => { + let target = position(&checkpoint["pos"])?; + segments.push(segment( + grid, + cursor, + target, + Some(index), + flying, + remaining, + )?); + cursor = target; + } + Some("APPEAR") => { + cursor = position(&checkpoint["pos"])?; + cell(cursor)?; + } + Some("WAIT" | "DISAPPEAR") => {} + _ => return Err("Unsupported public route checkpoint".into()), + } + } + let (checkpoint, end) = if patrol { + let checkpoints = route["checkpoints"].as_array().unwrap(); + let index = checkpoints + .iter() + .position(|cp| cp["type"] == "MOVE") + .ok_or("Patrol route has no movement checkpoint")?; + for checkpoint in &checkpoints[..index] { + if checkpoint["type"] == "APPEAR" { + cursor = position(&checkpoint["pos"])?; + } + } + (Some(index), position(&checkpoints[index]["pos"])?) + } else { + (None, position(&route["end"])?) + }; + segments.push(segment(grid, cursor, end, checkpoint, flying, remaining)?); + route["segments"] = json!(segments); + route["repeatFrom"] = json!(if patrol { Some(0) } else { None:: }); + Ok(route) +} + +#[derive(Default)] +pub(super) struct Cache { + map: Option>, + routes: Option, + key: String, +} + +#[derive(PartialEq)] +struct MapKey { + stage_id: Value, + boss: bool, + overrides: std::collections::BTreeMap, +} + +struct MapGeometry { + key: MapKey, + grid: Grid, + fields: String, +} + +struct RouteHint { + base: bool, + flying: bool, + gate: Value, + start: Value, +} + +struct RouteGeometry { + templates: Vec, + fields: String, + hints: Vec, +} + +impl MapGeometry { + fn new(stage: &Value, key: MapKey) -> Result { + let boss = key.boss; + let bounds = if boss { Rect::BOSS } else { Rect::NORMAL }; + let mut stage = stage.clone(); + if stage["legend"].is_null() { + stage["legend"] = stage["tiles"].clone(); + } + if stage["rows"].is_null() { + stage["rows"] = stage["grid"].clone(); + } + let mut grid = Grid::new(&stage, bounds).map_err(str::to_string)?; + let raw_devices = stage["devices"] + .as_array() + .map(Vec::as_slice) + .unwrap_or(&[]); + if raw_devices.len() > N { + return Err("Public spatial device capacity exceeded".into()); + } + let mut devices = Vec::new(); + for device in raw_devices { + let alias = device["alias"].as_str().or(device["raw"]["alias"].as_str()); + let active = alias + .and_then(|alias| key.overrides.get(alias)) + .copied() + .unwrap_or_else(|| { + device["active"] + .as_bool() + .unwrap_or(device["hidden"] != true) + }); + if !active && device["hidden"] == true { + continue; + } + let at = if device["pos"].is_array() { + position(&device["pos"])? + } else { + position(&json!([device["row"], device["col"]]))? + }; + let at = cell(at)?; + let bit = match device["role"].as_str() { + Some("crate") => Some(CRATE), + Some("platform" | "mound") => Some(BLOCK), + _ => None, + }; + if let Some(bit) = bit.filter(|_| active) { + grid.set_obstacle(at, true, bit)?; + } + let mut visible = json!({"key":device["key"],"alias":alias,"role":device["role"], + "position":at,"direction":device["dir"],"active":active}); + for key in ["rangeGrid", "rangeTiles"] { + if let Some(value) = device.get(key) { + if value.as_array().is_some_and(|a| a.len() > N) { + return Err("Public spatial device range capacity exceeded".into()); + } + visible[key] = value.clone(); + } + } + devices.push(visible); + } + let mut tiles = Vec::with_capacity(N); + for (index, tile) in grid.tiles().iter().enumerate() { + let at = [(index / COLS) as i32, (index % COLS) as i32]; + tiles.push(json!({"position":at,"key":tile.key,"height":tile.height, + "build":tile.build,"pass":tile.pass,"terrain":tile.terrain,"special":tile.special, + "obstacle":grid.obstacle(at),"elevated":grid.obstacle(at) & BLOCK != 0,"groundPassable":grid.ground_passable(at,false), + "flyPassable":grid.fly_passable(at)})); + } + let fields = json!({"stageId":&key.stage_id, + "field":if boss {"bossL"} else {"normal"},"coordinates":"stage", + "boardOffset":if boss {[7,0]} else {[0,0]}, + "fieldBounds":[bounds.r0,bounds.c0,bounds.r1,bounds.c1], + "tiles":tiles,"devices":devices}) + .to_string(); + if fields.len() > MAX_BYTES { + return Err("Public spatial byte capacity exceeded".into()); + } + Ok(Self { key, grid, fields }) + } +} + +impl RouteGeometry { + fn new( + templates: &[String], + waves: &Value, + boss: bool, + grid: &mut Grid, + ) -> Result { + let mut routes = Vec::new(); + let mut remaining = MAX_PATH_CELLS; + for template in templates { + for (set, key) in [("base", "routes"), ("extra", "extraRoutes")] { + let raw = waves[template][key] + .as_array() + .map(Vec::as_slice) + .unwrap_or(&[]); + if raw.len() > MAX_ROUTES.saturating_sub(routes.len()) { + return Err("Public spatial route capacity exceeded".into()); + } + for (index, raw) in raw.iter().enumerate() { + let mut geometry = route(raw, grid, &mut remaining)?; + geometry["templateId"] = json!(template); + geometry["routeSet"] = json!(set); + geometry["templateRouteIndex"] = json!(index); + let row = geometry["start"][0] + .as_f64() + .ok_or("Missing public route start")?; + geometry["gate"] = json!(if row + if boss { 13. } else { 6. } >= 18. { + "upper" + } else { + "lower" + }); + routes.push(geometry); + } + } + } + let hints = routes + .iter() + .map(|route| RouteHint { + base: route["routeSet"] == "base", + flying: route["motion"] == "FLY", + gate: route["gate"].clone(), + start: route["start"].clone(), + }) + .collect(); + let fields = json!({"templateIds":templates,"routes":routes}).to_string(); + Ok(Self { + templates: templates.to_vec(), + fields, + hints, + }) + } +} + +impl Session { + /// Owned compatibility projection. The Python transport uses the serialized + /// entry point to avoid rebuilding and reserializing the static geometry. + pub fn public_spatial(&self) -> Result { + serde_json::from_str(&self.public_spatial_json()?).map_err(|error| error.to_string()) + } + + pub fn public_spatial_json(&self) -> Result { + self.project_spatial(|cache, header, effects, tail| { + join_fields(&[ + header, + &cache.map.as_ref().unwrap().fields, + effects, + &cache.routes.as_ref().unwrap().fields, + tail, + ]) + }) + } + + /// The key identifies public geometry within the catalog. Only resend its + /// static fields when the consumer does not already hold this key. + pub fn public_spatial_update( + &self, + known_geometry: Option<&str>, + ) -> Result<(String, Option, String), String> { + self.project_spatial(|cache, header, effects, tail| { + let geometry = if known_geometry == Some(cache.key.as_str()) { + None + } else { + Some(join_fields(&[ + &cache.map.as_ref().unwrap().fields, + &cache.routes.as_ref().unwrap().fields, + ])?) + }; + Ok(( + cache.key.clone(), + geometry, + join_fields(&[header, effects, tail])?, + )) + }) + } + + fn project_spatial( + &self, + encode: impl FnOnce(&Cache, &str, &str, &str) -> Result, + ) -> Result { + self.healthy()?; + let phase = match self.run.phase() { + Phase::Prep => "PREP", + Phase::Draft => "SP_DRAFT", + _ => return Err("Public spatial projection requires a decision boundary".into()), + }; + let run = &self.run; + let round_number = run.snapshot()?.round; + let preview = self.current_preview()?; + let mode = &run + .data + .table("config") + .ok_or("Missing public mode configuration")?["modes"]["mode_single_abyss"]; + let round = &mode["rounds"][round_number.to_string()]; + let boss = round["isBoss"] == true; + let mut templates = Vec::new(); + if let Some(template) = round["template"].as_str() { + templates.push(template.to_owned()); + } else { + let bosses = run + .data + .table("bosses") + .ok_or("Missing public boss definitions")?; + for (id, template) in round["bossTemplates"].as_object().into_iter().flatten() { + if preview.iter().any(|enemy| { + enemy["boss"] == true && enemy["enemyKey"] == bosses[id]["enemyKey"] + }) { + templates.push( + template + .as_str() + .ok_or("Invalid public route template")? + .to_owned(), + ); + } + } + } + if templates.is_empty() { + return Err("Current route template is not publicly identifiable".into()); + } + let effective_map = run.map.clone().resolved(&run.data)?; + let key = MapKey { + stage_id: self.public_setup["stageId"].clone(), + boss, + overrides: effective_map.device_overrides, + }; + let mut cache = self + .spatial + .lock() + .map_err(|_| "Public spatial cache is poisoned")?; + if cache.map.as_ref().is_none_or(|map| map.key != key) { + let map = MapGeometry::new(&run.stage, key)?; + cache.map = Some(Box::new(map)); + cache.routes = None; + } + if cache + .routes + .as_ref() + .is_none_or(|routes| routes.templates != templates) + { + let waves = run + .data + .table("waves") + .ok_or("Missing public route templates")?; + let map = cache.map.as_mut().unwrap(); + let routes = RouteGeometry::new(&templates, waves, boss, &mut map.grid)?; + if map.fields.len() + routes.fields.len() > MAX_BYTES { + return Err("Public spatial byte capacity exceeded".into()); + } + let geometry_key = json!([ + &map.key.stage_id, + map.key.boss, + &map.key.overrides, + &templates + ]) + .to_string(); + if geometry_key.len() > MAX_BYTES { + return Err("Public spatial key exceeds byte limit".into()); + } + cache.key = geometry_key; + cache.routes = Some(routes); + } + let map = cache.map.as_ref().unwrap(); + let routes = cache.routes.as_ref().unwrap(); + let associations: Vec<_> = preview + .iter() + .enumerate() + .map(|(index, enemy)| { + let candidates: Vec<_> = routes + .hints + .iter() + .enumerate() + .filter(|(_, route)| { + route.base + && route.flying == (enemy["fly"] == true) + && route.gate == enemy["gate"] + && (enemy["start"].is_null() || route.start == enemy["start"]) + }) + .map(|(index, _)| index) + .collect(); + json!({"previewIndex":index,"routeCandidates":candidates}) + }) + .collect(); + let header = json!({"schema":"arkguardrl/public-spatial/v1","revision":self.revision, + "round":round_number,"phase":phase}) + .to_string(); + let effects = json!({"mapEffects":run.map.effects}).to_string(); + let tail = + json!({"previewRoutes":associations,"pathBasis":"public-map-default"}).to_string(); + if header.len() + map.fields.len() + effects.len() + routes.fields.len() + tail.len() - 4 + > MAX_BYTES + { + return Err("Public spatial byte capacity exceeded".into()); + } + encode(&cache, &header, &effects, &tail) + } +} + +fn join_fields(fields: &[&str]) -> Result { + // Each fragment is a nonempty JSON object serialized by serde_json. + let capacity = fields.iter().map(|s| s.len()).sum::() - fields.len() + 1; + if capacity > MAX_BYTES { + return Err("Public spatial byte capacity exceeded".into()); + } + let mut out = String::with_capacity(capacity); + out.push('{'); + for (index, fields) in fields.iter().enumerate() { + if index > 0 { + out.push(','); + } + out.push_str(&fields[1..fields.len() - 1]); + } + out.push('}'); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn route_geometry_preserves_patrol_and_teleport_boundaries() { + let stage = json!({"rows":vec!["r".repeat(COLS); crate::battle::grid::ROWS]}); + let mut grid = Grid::new(&stage, Rect::BOSS).unwrap(); + let mut remaining = MAX_PATH_CELLS; + let patrol = route( + &json!({"start":[4,10],"end":[2,2],"steps":[ + {"t":"patrol","p":[3,9]}, {"t":"patrol","p":[2,3]}, + {"t":"patrol","p":[5,9]} + ]}), + &mut grid, + &mut remaining, + ) + .unwrap(); + assert_eq!(patrol["repeatFrom"], 0); + let segments = patrol["segments"].as_array().unwrap(); + assert_eq!(segments.last().unwrap()["from"], json!([5., 9.])); + assert_eq!(segments.last().unwrap()["to"], json!([3., 9.])); + assert!(segments + .iter() + .all(|segment| segment["to"] != json!([2., 2.]))); + + let portal = route( + &json!({"start":[2,10],"end":[2,2],"checkpoints":[ + {"type":"DISAPPEAR","pos":[2,8]}, {"type":"MOVE","pos":[4,3]} + ]}), + &mut grid, + &mut remaining, + ) + .unwrap(); + assert!(portal["repeatFrom"].is_null()); + assert_eq!(portal["checkpoints"][1]["type"], "APPEAR"); + assert_eq!(portal["segments"][0]["from"], json!([4., 3.])); + assert_eq!(portal["segments"][0]["to"], json!([4., 3.])); + } +} diff --git a/crates/engine/src/solo/session/view.rs b/crates/engine/src/solo/session/view.rs new file mode 100644 index 0000000..cccc0bf --- /dev/null +++ b/crates/engine/src/solo/session/view.rs @@ -0,0 +1,156 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use super::*; +use crate::solo::RoundKind; +impl Session { + pub(super) fn current_preview(&self) -> Result, String> { + let run = &self.run; + let Some(plan) = run.plans.get(run.index).and_then(Option::as_ref) else { + return Ok(self.preview.clone()); + }; + let boss = !matches!(plan.kind, RoundKind::Normal); + let mut wave = plan.wave.clone(); + if let Some(prep) = &run.prep { + prep.append_bounties(&mut wave, run.index + 1, boss)?; + } + let mut out = Vec::new(); + // The public drawer retains the original wave actions. Interleaving + // bounties splits those actions only for combat scheduling; expose the + // added bounty runs without also exposing those internal wave splits. + let spawns = plan.wave.spawns.iter().chain( + wave.spawns + .iter() + .filter(|s| s["tag"] == "bounty" && !plan.wave.spawns.contains(s)), + ); + for s in spawns { + if s["tag"] == "part" { + continue; + } + let Some(key) = s["enemyKey"].as_str() else { + continue; + }; + let e = &run.data.table("enemies").ok_or("Missing enemies")?[key]; + let route = wave + .routes + .get(s["routeIndex"].as_u64().unwrap_or(0) as usize); + let start = route.map(|r| &r["start"]).unwrap_or(&Value::Null); + let upper = start[0] + .as_f64() + .is_some_and(|r| r + if boss { 13. } else { 6. } >= 18.); + let tag = if s["tag"] == "boss" { + json!("boss") + } else if s["tag"] == "bounty" { + json!("bounty") + } else { + Value::Null + }; + let mut row = json!({"enemyKey":key,"count":s["count"].as_u64().unwrap_or(1).max(1), + "t":s["time"].as_f64().unwrap_or(0.).max(0.),"gate":if upper{"upper"}else{"lower"}, + "fly":e["isFlyEnemy"].as_bool().unwrap_or(e["stats"]["motion"]=="FLY"), + "elite":tag=="boss" || e["rank"].as_str().is_some_and(|r|r!="NORMAL"), + "boss":tag=="boss","source":if tag=="bounty"{"bounty"}else{"wave"},"tag":tag}); + if tag == "boss" && start.is_array() { + row["start"] = start.clone(); + } + out.push(row); + } + out.sort_by(|a, b| { + a["t"] + .as_f64() + .unwrap() + .total_cmp(&b["t"].as_f64().unwrap()) + }); + Ok(out) + } + /// Detached, explicitly allowlisted public state for the existing model schema. + pub fn observation(&self) -> Result { + self.healthy()?; + let run = &self.run; + let s = run.snapshot()?; + let ended = s.phase == Phase::Result; + let phase = match s.phase { + Phase::Prep => "PREP", + Phase::Draft => "SP_DRAFT", + Phase::Combat => "COMBAT", + Phase::Result => "RESULT", + Phase::Faulted => return Err("Faulted session".into()), + }; + let mut own = run + .prep + .as_ref() + .ok_or("Public observation requires owned preparation")? + .public_view(&run.player)?; + own["bandId"] = json!(run.core); + if let Some(core) = &run.core { + let band = &run.data.table("bands").ok_or("Missing bands")?[core]; + let id = band["effectId"] + .as_str() + .filter(|s| !s.is_empty()) + .unwrap_or(core); + let icon = band["iconId"] + .as_str() + .filter(|s| !s.is_empty()) + .unwrap_or(core); + own["effects"] + .as_array_mut() + .unwrap() + .insert(0, json!({"id":id,"iconId":icon,"iconKind":"band"})); + } + own["lp"] = json!(s.lp); + // Boss settlement can exhaust team LP without eliminating the player. + // Only ordinary-round elimination clears the board and ready flag. + let eliminated = s + .outcome + .is_some_and(|o| o.reason == crate::solo::EndReason::Eliminated); + own["alive"] = json!(!eliminated); + own["ready"] = json!(s.phase == Phase::Combat || (ended && !eliminated)); + own["canReady"] = json!(s.phase == Phase::Prep && own["canReady"] == true); + own["nextEnemies"] = if eliminated { + json!([]) + } else { + json!(self.current_preview()?) + }; + let mut public = self.public_setup.clone(); + public["phase"] = json!(phase); + public["round"] = json!(s.round); + public["players"] = json!([{"playerId":"solo","seat":0,"isBot":false,"alive":own["alive"],"lp":s.lp,"bandId":run.core}]); + public["sp"] = run + .draft + .as_ref() + .and_then(|d| d.pending.clone()) + .unwrap_or(Value::Null); + if public["sp"].is_object() { + public["sp"]["turn"] = json!("solo"); + public["sp"]["taken"] = json!({}); + if let Some(cards) = public["sp"]["cards"].as_array_mut() { + for (i, card) in cards.iter_mut().enumerate() { + let mut visible = json!({"idx":i,"kind":card["kind"],"id":card["id"], + "name":card["name"],"desc":card["desc"],"tier":card["tier"],"soldOut":false}); + match card["kind"].as_str() { + Some("bounty") => { + for key in ["descRaw", "coin", "payout", "rounds", "enemyKey", "count"] + { + visible[key] = card[key].clone(); + } + } + Some("item") => visible["price"] = json!(0), + Some("tactic") => { + visible["team"] = card["team"].clone(); + visible["tacticKind"] = card["tacticKind"].clone(); + } + _ => (), + } + *card = visible; + } + } + } + let outcome=s.outcome.map(|o|json!({"errors":0,"modeId":"mode_single_abyss","difficulty":"ABYSS","victory":o.victory, + "hiddenReached":o.hidden_reached,"hiddenCleared":o.hidden_cleared, + "reason":match o.reason {crate::solo::EndReason::Eliminated=>"eliminated",crate::solo::EndReason::Defeat=>"defeat",crate::solo::EndReason::Victory=>"victory"}, + "players":[{"playerId":"solo","alive":own["alive"],"victory":o.victory && own["alive"]==true,"roundsPassed":s.rounds_passed}]})); + Ok( + json!({"schema":"arkguardrl/native-session-v2","revision":self.revision,"phase":phase,"round":s.round, + "gameEnded":ended,"personalEnded":ended,"decisionRequired":matches!(s.phase,Phase::Prep|Phase::Draft), + "public":public,"own":own,"outcome":outcome}), + ) + } +} diff --git a/crates/engine/tests/area_reference.rs b/crates/engine/tests/area_reference.rs deleted file mode 100644 index 9f693d4..0000000 --- a/crates/engine/tests/area_reference.rs +++ /dev/null @@ -1,411 +0,0 @@ -use arkguard_engine::{ - battle::{ - attacks::{self, Area, Chain, Splash, VictimKind}, - body::HitArea, - damage::DamageType, - health::{self, Side, Unit, World}, - hit, - injury::Effects, - search::AttackProfile, - skills::{self, Runtime}, - spatial::{self, RadiusRule}, - stats::{Base, Buff, UnitStats}, - targeting::{Profile, Queries}, - }, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Host { - cfg: Value, - trace: Vec, - enemies: Vec, - effects: Option, - rng: Rng, -} -impl Queries for Host { - fn enemy_stealthed(&mut self, id: u64, w: &mut World) -> Result { - let u = w.unit_mut(id)?; - let f = &u.stats.stats().map_err(str::to_string)?.flags; - Ok(f.contains("stealth") && !f.contains("reveal")) - } - fn skip_enemy(&mut self, _: Option, _: u64, _: &mut World) -> Result { - Ok(false) - } - fn remaining_distance(&mut self, _: u64, _: &mut World) -> Result { - unreachable!() - } - fn body_distance(&mut self, _: u64, _: [f64; 2], _: &mut World) -> Result { - unreachable!() - } -} -impl health::Hooks for Host { - fn kill(&mut self, id: u64, _: Option, w: &mut World) -> Result<(), String> { - let u = w.unit_mut(id)?; - u.stats.hp = 0.; - u.stats.alive = false; - u.deployed = false; - self.trace.push(json!(["kill", id])); - Ok(()) - } -} -impl hit::Hooks for Host {} -impl skills::Hooks for Host { - fn event( - &mut self, - _: skills::Event, - _: &mut skills::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - fn condition( - &mut self, - _: skills::Condition, - _: &Runtime, - _: &mut World, - ) -> Result { - unreachable!() - } - fn profile(&mut self, _: u64, _: &mut World) -> Result, String> { - unreachable!() - } - fn has_sp_hook(&self) -> bool { - false - } -} -impl attacks::Hooks for Host { - fn has_before_attack(&self) -> bool { - false - } - fn before_attack(&mut self, _: &mut attacks::Context, _: &mut World) -> Result<(), String> { - unreachable!() - } - fn engage(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn damage(&mut self, w: &mut World, r: &mut hit::Request) -> Result { - self.trace.push(json!([ - "hit", - r.hit.target, - bits(r.damage.amount), - bits(r.damage.mul), - r.hit.no_sp, - r.is_splash, - r.tags, - r.attack_id.unwrap() - ])); - let mut effects = self.effects.take().unwrap(); - let mut rng = self.rng.clone(); - let result = hit::resolve(w, &mut effects, &mut rng, self, r); - self.effects = Some(effects); - self.rng = rng; - result - } - fn radius_targets( - &mut self, - origin: [f64; 2], - radius: f64, - splash: bool, - w: &mut World, - limit: usize, - ) -> Result, String> { - let enemies = self.enemies.clone(); - spatial::enemies_in_radius( - w, - self, - &enemies, - origin, - radius, - if splash { - RadiusRule::Centre - } else { - RadiusRule::Body - }, - splash, - limit, - ) - } - fn chain_link(&mut self, from: u64, to: u64, _: &mut World) -> Result<(), String> { - self.trace.push(json!(["link", from, to])); - Ok(()) - } - fn sluggish( - &mut self, - _: u64, - target: u64, - duration: f64, - _: &mut World, - ) -> Result<(), String> { - self.trace.push(json!(["slow", target, bits(duration)])); - Ok(()) - } - fn each_hit( - &mut self, - c: attacks::Impact, - _: Option<&mut Runtime>, - w: &mut World, - ) -> Result<(), String> { - let kind = match c.kind { - VictimKind::Main => "main", - VictimKind::Splash => "splash", - VictimKind::Chain => "chain", - }; - self.trace.push(json!([ - "each", - c.target.unwrap(), - kind, - bits(c.amount), - c.main, - c.attack_id, - c.is_skill - ])); - if c.kind == VictimKind::Main { - if self.cfg["move"] == true { - w.unit_mut(c.target.unwrap())?.position[1] += 0.6; - } - if self.cfg["changeAtk"] == true { - w.unit_mut(1)?.stats.edit_base(|base| { - base.0.insert("atk".into(), 999.); - }); - } - } - Ok(()) - } - fn after_hit( - &mut self, - c: attacks::Impact, - _: Option<&mut Runtime>, - _: &mut World, - ) -> Result<(), String> { - self.trace.push(json!([ - "after", - c.target, - bits(c.amount), - bits(c.position[1]), - bits(c.position[0]), - c.is_skill - ])); - Ok(()) - } - fn attack( - &mut self, - _: &mut attacks::Context, - _: Option<&mut Runtime>, - _: &mut World, - ) -> Result<(), String> { - Ok(()) - } - fn after_attack( - &mut self, - _: &attacks::Context, - _: Option<&mut Runtime>, - _: &mut World, - ) -> Result<(), String> { - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; splash/chain settlement"] -fn area_payload_matches() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/area.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let c = &v["cfg"]; - let mut w = World::new(13, 1, 1).unwrap(); - let mut base = Base::default(); - base.0.insert("maxHp".into(), 1000.); - base.0.insert("atk".into(), 60.25); - let mut u = Unit::new(UnitStats::new(base), Side::Ally); - u.deployed = true; - w.insert_unit(1, u).unwrap(); - let mut enemies = vec![]; - for d in v["records"].as_array().unwrap() { - let id = d["id"].as_u64().unwrap(); - let mut base = Base::default(); - for (k, x) in [("maxHp", 1000.), ("def", 20.), ("res", 30.)] { - base.0.insert(k.into(), x); - } - let mut u = Unit::new(UnitStats::new(base), Side::Enemy); - u.stats.hp = d["hp"].as_f64().unwrap(); - u.stats.alive = d["alive"] == true; - u.deployed = d["deployed"] == true; - u.hidden = d["hidden"] == true; - u.motion_fly = d["fly"] == true; - u.position = [d["y"].as_f64().unwrap(), d["x"].as_f64().unwrap()]; - u.targeting.spawn_seq = d["seq"].as_u64().unwrap(); - if d["huge"] == true { - u.hit_area = HitArea::new(4.95, 2.95, 0., 1.); - } - u.stats.set_buffs(vec![Buff { - flags: ["sleep", "stealth", "reveal", "untargetable"] - .into_iter() - .filter(|k| d[*k] == true) - .map(str::to_string) - .collect(), - ..Buff::default() - }]); - w.insert_unit(id, u).unwrap(); - enemies.push(id); - } - let mut h = Host { - cfg: c.clone(), - trace: vec![], - enemies, - effects: Some(Effects::new(32).unwrap()), - rng: Rng::new(42), - }; - let p = attacks::Direct { - mode: attacks::Mode::Damage(match c["type"].as_str().unwrap() { - "arts" => DamageType::Arts, - "true" => DamageType::True, - "elemental" => DamageType::Elemental, - _ => DamageType::Physical, - }), - hits: c["hits"].as_u64().unwrap() as u32, - atk_scale: 1.25, - skill_damage_mul: 1.15, - target_damage_mul: c["mul"].as_f64().unwrap(), - split_mul: c["split"].as_f64(), - heal_scale: 1., - is_skill: c["skill"] == true, - }; - let area = Area { - selection: Profile { - can_hit_fly: c["canHitFly"] == true, - ground_only: c["groundOnly"] == true, - ..Profile::default() - }, - fortress_melee: c["fortressMelee"] == true, - splash: if c["splash"] == true { - Some(Splash { - radius: 1.5, - scale: v["splashScale"].as_f64().unwrap(), - hits_fly: c["splashFly"] == true, - fortress_melee: c["fortressSplash"] == true, - }) - } else { - None - }, - chain: if c["chain"] == true { - Some(Chain { - count: c["count"].as_f64().unwrap(), - radius: c["radius"].as_f64().unwrap(), - falloff: c["falloff"].as_f64().unwrap(), - sluggish: c["sluggish"].as_f64().unwrap(), - }) - } else { - None - }, - }; - attacks::Executor::new(16, 8) - .unwrap() - .impact_at( - &mut w, - &mut h, - 1, - c["main"].as_u64(), - 17, - p, - area, - [10., 6.], - None, - ) - .unwrap(); - assert_eq!(json!(h.trace), v["trace"], "trace case {c}"); - assert_eq!( - json!(h - .enemies - .iter() - .map(|id| bits(w.unit(*id).unwrap().stats.hp)) - .collect::>()), - v["hp"], - "hp case {c}" - ); - assert_eq!( - json!(h - .enemies - .iter() - .map(|id| w.unit(*id).unwrap().stats.alive) - .collect::>()), - v["alive"] - ); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 512); -} - -#[test] -fn area_capacity_errors_do_not_clip_or_emit_after_hit() { - let mut w = World::new(3, 1, 1).unwrap(); - for (id, side) in [(1, Side::Ally), (2, Side::Enemy), (3, Side::Enemy)] { - let mut u = Unit::new(UnitStats::new(Base::default()), side); - u.deployed = true; - w.insert_unit(id, u).unwrap(); - } - let mut h = Host { - cfg: Value::Null, - trace: vec![], - enemies: vec![2, 3], - effects: Some(Effects::new(8).unwrap()), - rng: Rng::new(42), - }; - let p = attacks::Direct { - mode: attacks::Mode::Damage(DamageType::Physical), - hits: 1, - atk_scale: 1.0, - skill_damage_mul: 1.0, - target_damage_mul: 1.0, - split_mul: None, - heal_scale: 1.0, - is_skill: false, - }; - let mut executor = attacks::Executor::new(2, 1).unwrap(); - for count in [0.0, 3.0, 2.1, f64::NAN, f64::INFINITY] { - let area = Area { - chain: Some(Chain { - count, - radius: 1.7, - falloff: 0.15, - sluggish: 0.0, - }), - ..Default::default() - }; - assert!(executor - .impact_at(&mut w, &mut h, 1, None, 1, p, area, [0.0, 0.0], None) - .is_err()); - assert!(h.trace.is_empty()); - } - let area = Area { - splash: Some(Splash { - radius: 1.0, - scale: 1.0, - hits_fly: false, - fortress_melee: false, - }), - ..Default::default() - }; - assert!(attacks::Executor::new(1, 1) - .unwrap() - .impact_at(&mut w, &mut h, 1, None, 1, p, area, [0.0, 0.0], None) - .is_err()); - assert!(h.trace.is_empty()); - assert_eq!(w.unit(2).unwrap().stats.hp, 1.0); - assert_eq!(w.unit(3).unwrap().stats.hp, 1.0); -} diff --git a/crates/engine/tests/blocking_reference.rs b/crates/engine/tests/blocking_reference.rs deleted file mode 100644 index a26b91e..0000000 --- a/crates/engine/tests/blocking_reference.rs +++ /dev/null @@ -1,137 +0,0 @@ -use arkguard_engine::battle::{ - blocking::{self, Hooks}, - deploy::{self, Deployment, Kind, Options}, - grid::{Grid, Rect}, - health::{Side, Unit, World}, - stats::{Base, Buff, UnitStats}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -struct Host { - trace: Vec, -} -impl Hooks for Host { - fn blocked(&mut self, b: u64, e: u64, _: &mut World) -> Result<(), String> { - self.trace.push(json!(["blocked", b, e])); - Ok(()) - } - fn ended(&mut self, e: u64, _: &mut World) -> Result<(), String> { - self.trace.push(json!(["ended", e])); - Ok(()) - } -} -impl deploy::Hooks for Host { - fn initialize( - &mut self, - _: u64, - _: Options, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn event( - &mut self, - _: deploy::Event, - _: u64, - _: Option, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn remove_temporary_effects(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; contact blocking only"] -fn contact_and_release_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/blocking.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let d = &v["scenario"]; - let mut rows = vec!["r".repeat(21); 19]; - if d["fence"] == true { - rows[10].replace_range(4..5, "b"); - } - let g = Grid::new(&json!({"rows":rows}), Rect::FULL).unwrap(); - let mut w = World::new(3, 1, 1).unwrap(); - let mut dep = Deployment::new(Rect::FULL, 3, 1, 99.0).unwrap(); - let mut h = Host { trace: vec![] }; - for (id, tile) in [(1, [10, 4]), (2, [10, 5])] { - let mut b = Base::default(); - b.0.insert("blockCnt".into(), d["cap"].as_f64().unwrap()); - let mut u = Unit::new(UnitStats::new(b), Side::Ally); - u.deployment.kind = if d["device"] == true { - Kind::Device - } else { - Kind::Operator - }; - u.deployment.home = tile; - u.deployment.tile = tile; - u.ground = d["ground"] == true; - u.profile_block_fly = d["profileFly"] == true; - u.stats.set_buffs(vec![Buff { - mods: [("blockRadiusScale".into(), d["radius"].as_f64().unwrap())] - .into_iter() - .collect(), - flags: ["blockFly", "sleep"] - .into_iter() - .filter(|k| d[*k] == true) - .map(str::to_string) - .collect(), - ..Buff::default() - }]); - w.insert_unit(id, u).unwrap(); - dep.register(id, &w).unwrap(); - dep.deploy(&mut w, &mut h, id, Options::default()).unwrap(); - } - let mut e = Unit::new(UnitStats::new(Base::default()), Side::Enemy); - e.position = [d["y"].as_f64().unwrap(), d["x"].as_f64().unwrap()]; - e.motion_fly = d["fly"] == true; - e.block_weight = d["weight"].as_f64().unwrap(); - e.hidden = d["hidden"] == true; - e.moving = true; - e.stats.set_buffs(vec![Buff { - flags: if d["unblockable"] == true { - ["unblockable".into()].into_iter().collect() - } else { - Default::default() - }, - ..Buff::default() - }]); - w.insert_unit(3, e).unwrap(); - let mut checks = vec![]; - for _ in 0..2 { - checks.push(blocking::check(&mut w, &dep, &g, &mut h, 3).unwrap()); - } - let held = w.unit(3).unwrap().blocked_by(); - if d["i"].as_u64().unwrap() % 2 == 1 { - blocking::unblock(&mut w, &mut h, 3).unwrap(); - } else { - for id in [1, 2] { - blocking::release(&mut w, &mut h, id).unwrap(); - } - } - checks.push(blocking::check(&mut w, &dep, &g, &mut h, 3).unwrap()); - let actual = json!({"checks":checks,"held":held,"final":w.unit(3).unwrap().blocked_by(),"lists":[w.unit(1).unwrap().blocking(),w.unit(2).unwrap().blocking()],"moving":w.unit(3).unwrap().moving,"trace":h.trace}); - let mut expected = v.clone(); - expected.as_object_mut().unwrap().remove("scenario"); - assert_eq!(actual, expected, "case {d}"); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 1024); -} diff --git a/crates/engine/tests/body_reference.rs b/crates/engine/tests/body_reference.rs deleted file mode 100644 index 9c30dc5..0000000 --- a/crates/engine/tests/body_reference.rs +++ /dev/null @@ -1,241 +0,0 @@ -use arkguard_engine::battle::{ - body::{self, HitArea}, - health::{Side, Unit, World}, - spatial::{self, Index}, - stats::{Base, Buff, UnitStats}, - targeting::{Profile, Queries}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Query { - skip: bool, - through: bool, -} -impl spatial::Healing for Query { - fn heal_through(&mut self, _: u64, _: u64, _: &mut World) -> Result { - Ok(self.through) - } -} -impl Queries for Query { - fn enemy_stealthed(&mut self, _: u64, _: &mut World) -> Result { - Ok(false) - } - fn skip_enemy(&mut self, _: Option, id: u64, _: &mut World) -> Result { - Ok(self.skip && id == 3) - } - fn remaining_distance(&mut self, _: u64, _: &mut World) -> Result { - unreachable!() - } - fn body_distance(&mut self, id: u64, p: [f64; 2], w: &mut World) -> Result { - Ok(body::distance(w.unit(id)?, p)) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; collider and spatial queries"] -fn geometry_and_index_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/body.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut bodies = 0; - let mut indices = 0; - let mut healing = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - if v["healing"] == true { - let mut w = World::new(9, 1, 1).unwrap(); - let mut ids = vec![]; - for d in v["records"].as_array().unwrap() { - let id = d["id"].as_u64().unwrap(); - let mut base = Base::default(); - base.0.insert("maxHp".into(), d["maxHp"].as_f64().unwrap()); - let mut u = Unit::new(UnitStats::new(base), Side::Ally); - u.stats.hp = d["hp"].as_f64().unwrap(); - u.deployment.tile = [ - d["tile"][0].as_i64().unwrap() as i32, - d["tile"][1].as_i64().unwrap() as i32, - ]; - u.deployment.deploy_seq = d["seq"].as_u64().unwrap(); - if d["device"] == true { - u.deployment.kind = arkguard_engine::battle::deploy::Kind::Device; - } - u.stats.alive = d["alive"] == true; - u.deployed = d["deployed"] == true; - u.hidden = d["hidden"] == true; - u.profile_no_heal = d["profileNoHeal"] == true; - u.element_buildup[0] = d["element"].as_f64().unwrap(); - u.stats.set_buffs(vec![Buff { - flags: if d["noHeal"] == true { - ["noHeal".into()].into_iter().collect() - } else { - Default::default() - }, - ..Buff::default() - }]); - w.insert_unit(id, u).unwrap(); - ids.push(id); - } - let mut q = Query { - skip: false, - through: v["through"] == true, - }; - assert_eq!( - json!(spatial::injured_allies( - &mut w, - &mut q, - &ids, - &[216, 218], - v["healer"].as_u64(), - v["includeElement"] == true, - 9 - ) - .unwrap()), - v["targets"], - "healing {}", - v["i"] - ); - let overflow = spatial::injured_allies( - &mut w, - &mut q, - &ids, - &[216, 218], - v["healer"].as_u64(), - v["includeElement"] == true, - 0, - ); - assert_eq!( - overflow.is_err(), - !v["targets"].as_array().unwrap().is_empty() - ); - healing += 1; - continue; - } - if v["body"] == true { - let mut u = Unit::new( - UnitStats::new(Base::default()), - if v["side"] == "ally" { - Side::Ally - } else { - Side::Enemy - }, - ); - u.position = [v["y"].as_f64().unwrap(), v["x"].as_f64().unwrap()]; - let a = &v["area"]; - if !a.is_null() { - u.hit_area = HitArea::new( - a["w"].as_f64().unwrap(), - a["h"].as_f64().unwrap(), - a["dx"].as_f64().unwrap(), - a["dy"].as_f64().unwrap(), - ); - } - let keys = [214, 215, 235, 236, 237]; - let actual = json!({"keys":body::keys(&u),"collider":body::collider_keys(&u),"on":body::on_tile(&u,10,4),"inKeys":body::in_keys(&u,&keys),"inRange":body::in_range(&u,&keys),"distance":bits(body::distance(&u,[10.0,4.0])),"radius":body::in_radius(&u,[10.0,4.0],2.0),"reach":bits(body::tile_reach(&u,10,4))}); - for (k, a) in actual.as_object().unwrap() { - assert_eq!(*a, v[k], "{k} body {}", v["i"]); - } - bodies += 1; - continue; - } - let mut w = World::new(7, 1, 1).unwrap(); - w.insert_unit(1, Unit::new(UnitStats::new(Base::default()), Side::Ally)) - .unwrap(); - let mut ids = vec![]; - for d in v["records"].as_array().unwrap() { - let id = d["id"].as_u64().unwrap(); - let mut u = Unit::new(UnitStats::new(Base::default()), Side::Enemy); - u.position = [d["y"].as_f64().unwrap(), d["x"].as_f64().unwrap()]; - u.stats.alive = d["alive"] == true; - u.deployed = d["deployed"] == true; - u.hidden = d["hidden"] == true; - u.motion_fly = d["fly"] == true; - if d["huge"] == true { - u.hit_area = HitArea::new(4.95, 2.95, 0.0, 1.0); - } - u.stats.set_buffs(vec![Buff { - flags: ["sleep", "untargetable"] - .into_iter() - .filter(|k| d[*k] == true) - .map(str::to_string) - .collect(), - ..Buff::default() - }]); - w.insert_unit(id, u).unwrap(); - ids.push(id); - } - let mut index = Index::new(7, 4000).unwrap(); - index.rebuild(&w, &ids).unwrap(); - let mut q = Query { - skip: v["skip"] == true, - through: false, - }; - let p = Profile { - can_hit_fly: v["fly"] == true, - hit_sleep: v["hitSleep"] == true, - ..Profile::default() - }; - let keys: Vec<_> = v["keys"] - .as_array() - .unwrap() - .iter() - .map(|x| x.as_u64().unwrap() as usize) - .collect(); - assert_eq!( - json!(index - .enemies( - &mut w, - &mut q, - &keys, - Some(1), - p, - v["rangeTiles"] == true, - 64 - ) - .unwrap()), - v["enemies"], - "index {}", - v["i"] - ); - assert_eq!( - json!(index - .enemies(&mut w, &mut q, &keys, Some(1), p, true, 64) - .unwrap()), - v["tiles"] - ); - assert_eq!( - index.any_enemy(&w, &keys, v["rangeTiles"] == true).unwrap(), - v["any"] == true - ); - indices += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(bodies, 1024); - assert_eq!(indices, 128); - assert_eq!(healing, 256); -} -#[test] -fn invalid_or_overflowed_rebuild_cannot_reuse_previous_index() { - let mut w = World::new(1, 1, 1).unwrap(); - let mut e = Unit::new(UnitStats::new(Base::default()), Side::Enemy); - e.position = [10.0, 4.0]; - e.deployed = true; - w.insert_unit(1, e).unwrap(); - let mut idx = Index::new(1, 2).unwrap(); - idx.rebuild(&w, &[1]).unwrap(); - assert!(idx.any_enemy(&w, &[214], false).unwrap()); - assert!(idx.rebuild(&w, &[1, 1]).is_err()); - assert!(idx.any_enemy(&w, &[214], false).is_err()); - w.unit_mut(1).unwrap().hit_area = HitArea::new(4.95, 2.95, 0.0, 1.0); - assert!(idx.rebuild(&w, &[1]).is_err()); - assert!(idx.any_enemy(&w, &[214], false).is_err()); -} diff --git a/crates/engine/tests/buffs_reference.rs b/crates/engine/tests/buffs_reference.rs deleted file mode 100644 index d3b06d0..0000000 --- a/crates/engine/tests/buffs_reference.rs +++ /dev/null @@ -1,238 +0,0 @@ -use arkguard_engine::battle::{ - buffs::{self, BuffId, Context, Event, Refresh, Runtime, Spec}, - health::{self, Side, Unit, World}, - stats::{Base, Buff}, -}; -use serde_json::{json, Value}; -use std::{ - collections::BTreeSet, - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -fn spec(d: &Value) -> Spec { - let mut b = Buff::default(); - b.key = Some(d["key"].as_str().unwrap().into()); - b.stacks = d["stacks"].as_u64().unwrap_or(1) as u32; - b.shield = d["shield"].as_f64().unwrap_or(0.); - if let Some(m) = d["mods"].as_object() { - b.mods = m - .iter() - .map(|(k, v)| (k.clone(), v.as_f64().unwrap())) - .collect(); - } - if let Some(f) = d["flags"].as_object() { - b.flags = f - .iter() - .filter(|(_, v)| **v == true) - .map(|(k, _)| k.clone()) - .collect(); - } - b.runtime.duration = if d["duration"] == "inf" { - f64::INFINITY - } else { - d["duration"].as_f64().unwrap_or(f64::INFINITY) - }; - b.runtime.max_stacks = d["cap"].as_u64().unwrap_or(1) as u32; - b.runtime.refresh = match d["refresh"].as_str().unwrap_or("replace") { - "extend" => Refresh::Extend, - "stack" => Refresh::Stack, - "independent" => Refresh::Independent, - "keep" => Refresh::Keep, - _ => Refresh::Replace, - }; - b.runtime.visible = d["visible"] == true; - b.runtime.status = d["status"].as_str().map(str::to_string); - b.runtime.persist = d["persist"] == true; - b.runtime.interval = d["interval"].as_f64().unwrap_or(0.0); - b.runtime.shield_hits = d["hits"].as_u64().unwrap_or(0) as u32; - b.runtime.on_tick = d["tick"].as_u64(); - b.runtime.on_remove = d["remove"].as_u64(); - b.runtime.on_expire = d["expire"].as_u64(); - Spec { - buff: b, - mods_present: d["mods"].is_object(), - flags_present: d["flags"].is_object(), - allow_dead: d["allowDead"] == true, - } -} -struct Host { - trace: Vec, - spawned: BTreeSet, - nested: bool, -} -impl health::Hooks for Host { - fn kill(&mut self, _: u64, _: Option, _: &mut World) -> Result<(), String> { - unreachable!() - } -} -impl buffs::Hooks for Host { - fn status(&mut self, unit: u64, key: &str, on: bool) -> Result<(), String> { - self.trace - .push(json!(["status", unit, key, if on { 1 } else { 0 }])); - Ok(()) - } - fn callback( - &mut self, - token: u64, - event: Event, - c: Context, - r: &mut Runtime, - w: &mut World, - ) -> Result<(), String> { - let b = r.get(w, c.unit, c.buff)?; - let key = b.key.clone().unwrap(); - let attached = w - .unit(c.unit)? - .stats - .buffs() - .iter() - .any(|b| b.runtime.id() == c.buff); - let event_name = match event { - Event::Tick => "tick", - Event::Remove => "remove", - Event::Expire => "expire", - }; - self.trace.push(json!([ - event_name, - c.buff, - bits(c.dt), - bits(b.runtime.time_left), - bits(b.runtime.accumulator), - attached - ])); - if event != Event::Tick { - if token == 4 { - r.remove(w, self, c.unit, "b")?; - } - if token == 5 { - r.add( - w, - self, - c.unit, - spec(&json!({"key":key,"duration":0.4,"tick":1,"mods":{"atkPct":0.2}})), - )?; - } - return Ok(()); - } - match token { - 2 => { - r.remove_id(w, self, c.unit, c.buff)?; - } - 3 => { - if self.spawned.insert(c.buff) { - r.add( - w, - self, - c.unit, - spec( - &json!({"key":"child","duration":0.15,"tick":1,"mods":{"atkPct":0.1}}), - ), - )?; - } - } - 6 => { - r.add( - w, - self, - c.unit, - spec(&json!({"key":key,"duration":0.2,"tick":1,"mods":{"atkPct":0.3}})), - )?; - } - 7 => { - let u = w.unit_mut(c.unit)?; - u.stats.hp = 0.; - u.stats.alive = false; - u.deployed = false; - } - 8 => { - if !self.nested { - self.nested = true; - let result = r.tick(w, self, &[c.unit], c.dt / 2.); - self.nested = false; - result?; - } - } - _ => {} - } - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; timed buff sequences"] -fn buff_lifetimes_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/buffs.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let mut w = World::new(1, 1, 1).unwrap(); - let mut base = Base::default(); - for (k, n) in [ - ("maxHp", 1000.), - ("atk", 60.), - ( - "hpRegen", - if v["i"].as_u64().unwrap() % 2 == 1 { - 2.3 - } else { - 10. - }, - ), - ] { - base.0.insert(k.into(), n); - } - let mut u = Unit::new( - arkguard_engine::battle::stats::UnitStats::new(base), - Side::Ally, - ); - u.stats.hp = 950.; - u.deployed = true; - w.insert_unit(1, u).unwrap(); - let mut h = Host { - trace: vec![], - spawned: BTreeSet::new(), - nested: false, - }; - let mut r = Runtime::new(256, 1024, 64).unwrap(); - let mut states = vec![]; - for d in v["ops"].as_array().unwrap() { - match d["op"].as_str().unwrap() { - "add" => { - r.add(&mut w, &mut h, 1, spec(d)).unwrap(); - } - "remove" => { - r.remove(&mut w, &mut h, 1, d["key"].as_str().unwrap()) - .unwrap(); - } - _ => { - let dt = d["dt"].as_f64().unwrap(); - w.time += dt; - r.tick(&mut w, &mut h, &[1], dt).unwrap(); - } - } - let u = w.unit_mut(1).unwrap(); - let atk = u.stats.stats().unwrap().n("atk"); - states.push(json!({"hp":bits(u.stats.hp),"regen":bits(u.regen_acc),"alive":u.stats.alive,"atk":bits(atk),"buffs":u.stats.buffs().iter().map(|b|json!({"id":b.runtime.id(),"key":b.key,"stacks":b.stacks,"cap":b.runtime.max_stacks,"duration":bits(b.runtime.duration),"left":bits(b.runtime.time_left),"acc":bits(b.runtime.accumulator),"shield":bits(b.shield),"hits":b.runtime.shield_hits})).collect::>()})); - } - for (j, (a, b)) in states - .iter() - .zip(v["states"].as_array().unwrap()) - .enumerate() - { - assert_eq!(a, b, "case {} operation {j}", v["i"]); - } - assert_eq!(json!(h.trace), v["trace"], "trace {}", v["i"]); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 256); -} diff --git a/crates/engine/tests/clock_reference.rs b/crates/engine/tests/clock_reference.rs deleted file mode 100644 index 463e8db..0000000 --- a/crates/engine/tests/clock_reference.rs +++ /dev/null @@ -1,153 +0,0 @@ -use arkguard_engine::battle::clock::{Clock, End, EndState, Host, Phase}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -const PHASES: [Phase; 15] = [ - Phase::Start, - Phase::Scheduled, - Phase::Spawns, - Phase::Dp, - Phase::Buffs, - Phase::AttackCommit, - Phase::Enemies, - Phase::EnemyIndex, - Phase::Allies, - Phase::Rate, - Phase::Projectiles, - Phase::Redeploy, - Phase::Boss, - Phase::TickHook, - Phase::EndCheck, -]; -fn name(p: Phase) -> &'static str { - match p { - Phase::Start => "start", - Phase::Scheduled => "scheduled", - Phase::Spawns => "spawns", - Phase::Dp => "dp", - Phase::Buffs => "buffs", - Phase::AttackCommit => "attackCommit", - Phase::Enemies => "enemies", - Phase::EnemyIndex => "enemyIndex", - Phase::Allies => "allies", - Phase::Rate => "rate", - Phase::Projectiles => "projectiles", - Phase::Redeploy => "redeploy", - Phase::Boss => "boss", - Phase::TickHook => "tickHook", - Phase::EndCheck => "endCheck", - } -} -struct Driver { - stop: Option, - reenter: bool, - hook: bool, - removed: bool, - trace: Vec, - policy: Option, - reason: Option, -} -impl Host for Driver { - fn phase(&mut self, p: Phase, c: &mut Clock) -> Result<(), String> { - if self.policy.is_none() { - self.trace.push(name(p).into()); - } - if self.reenter { - c.step(self)?; - } - if p == Phase::Start { - c.mark_started(); - } - if self.stop == Some(p) { - c.force_end(self, "requested".into())?; - } - Ok(()) - } - fn compact_enemies(&mut self, _: &mut Clock) -> Result<(), String> { - if self.policy.is_none() { - self.trace.push("compact".into()); - } - Ok(()) - } - fn has_removed(&self) -> bool { - self.removed - } - fn release_removed(&mut self, _: &mut Clock) -> Result<(), String> { - self.trace.push("release".into()); - self.removed = false; - Ok(()) - } - fn has_tick_hook(&self) -> bool { - self.hook - } - fn end_state(&self) -> Option { - self.policy - } - fn finish(&mut self, e: &End, _: &Clock) -> Result<(), String> { - let r = match e { - End::Cleared => "cleared", - End::Timeout => "timeout", - End::Forced => "forced", - }; - self.reason = Some(r.into()); - self.trace.push(format!("finish:{r}")); - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; lifecycle orchestration only"] -fn tick_order_and_end_policy_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/clock.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let policy = v["policy"] == true; - let mut h = Driver { - stop: if policy || v["stop"] == -1 { - None - } else { - Some(PHASES[v["stop"].as_u64().unwrap() as usize]) - }, - reenter: v["reenter"] == true, - hook: v["hook"] == true, - removed: !policy, - trace: vec![], - policy: None, - reason: None, - }; - if policy { - h.policy = Some(EndState { - shared_hp: v["shared"].as_f64(), - boss_like: v["boss"] == true, - auto_finish: v["auto"] == true, - pending_spawns: v["pending"] == true, - enemy_alive: v["enemy"] == true, - pending_holds: v["hold"] == true, - time_limit: if v["timeout"] == true { 0.0 } else { 10.0 }, - max_battle_time: 180.0, - }); - } - let mut c = Clock::new(); - c.run_steps(&mut h, if policy { 1 } else { 3 }).unwrap(); - if policy { - assert_eq!(json!(h.reason), v["reason"], "policy {v}"); - } else { - assert_eq!(json!(h.trace), v["trace"], "case {v}"); - assert_eq!(c.time().to_bits(), v["time"].as_f64().unwrap().to_bits()); - assert_eq!(c.ticks(), v["ticks"].as_u64().unwrap()); - assert_eq!(c.finished(), v["finished"] == true); - } - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 256); -} diff --git a/crates/engine/tests/combat_reference.rs b/crates/engine/tests/combat_reference.rs deleted file mode 100644 index bb24abf..0000000 --- a/crates/engine/tests/combat_reference.rs +++ /dev/null @@ -1,1099 +0,0 @@ -//! Continuous integration: real native search + skill + damage/HP paths against -//! upstream updateAlly/performAttack/resolveDamage. Real spatial queries, scripted movement. -use arkguard_engine::{ - battle::{ - ally, attacks, blocking, body, buffs, - content::enemies as enemy_content, - damage::DamageType, - element::{self, Element}, - enemy, - grid::{Grid, Rect}, - health::{self, Side, Unit, World}, - hit, motion, - projectiles::{self, Launch, Projectile, System}, - search::{self, AttackProfile, Commitments, Heal, Selection}, - settlement, - skills::{self, Condition, Context, Event, Rule, Runtime, SpType, Spec}, - sp::{Bank, Kind}, - spatial::{self, Index}, - stats::{Base, Buff, UnitStats}, - status, - targeting::{Profile, Queries}, - }, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -#[derive(Clone, Copy)] -enum Shot { - Ally(u64, u64, attacks::Direct, attacks::Area), - Enemy(enemy::Delivery), -} -struct Host { - d: Value, - trace: Vec, - index: Option, - enemies: Vec, - grid: Option, - stored: u32, - executor: Option, - flights: Option>, - buffs: Option, - rng: Rng, - content: Option, -} -impl Host { - fn move_target(&mut self, w: &mut World, inside: bool) -> Result<(), String> { - let e = w.unit_mut(2)?; - if self.d["mobile"] != true { - e.position = [10.0, if inside { 6.0 } else { 8.0 }]; - e.deployment.tile = [10, if inside { 6 } else { 8 }]; - } - self.index.as_mut().unwrap().rebuild(w, &self.enemies) - } - fn base_profile(&self) -> AttackProfile { - AttackProfile { - heal: if self.d["healer"] == true { - Some(Heal { - multi: false, - count: 1.0, - hp_at_most: 0.0, - element_heal: false, - }) - } else { - None - }, - heal_attack: self.d["healer"] == true, - ..AttackProfile::default() - } - } -} -impl Queries for Host { - fn skip_enemy(&mut self, _: Option, _: u64, _: &mut World) -> Result { - Ok(false) - } - fn remaining_distance(&mut self, _: u64, _: &mut World) -> Result { - Ok(5.0) - } - fn body_distance(&mut self, id: u64, p: [f64; 2], w: &mut World) -> Result { - Ok(body::distance(w.unit(id)?, p)) - } -} -impl spatial::Healing for Host { - fn heal_through(&mut self, _: u64, _: u64, _: &mut World) -> Result { - Ok(false) - } -} -impl search::Host for Host { - fn enemies( - &mut self, - id: u64, - keys: &[usize], - p: Profile, - w: &mut World, - limit: usize, - ) -> Result, String> { - let index = self.index.take().unwrap(); - let result = index.enemies(w, self, keys, Some(id), p, false, limit); - self.index = Some(index); - result - } - fn injured_allies( - &mut self, - id: u64, - keys: &[usize], - include_element: bool, - w: &mut World, - limit: usize, - ) -> Result, String> { - let allies: &[u64] = if self.d["healer"] == true { - &[1, 2] - } else { - &[1] - }; - spatial::injured_allies(w, self, allies, keys, Some(id), include_element, limit) - } - fn has_ally_targets(&self) -> bool { - false - } - fn ally_targets( - &mut self, - _: u64, - _: &[usize], - _: &mut World, - _: usize, - ) -> Result, String> { - Ok(vec![]) - } - fn profile(&mut self, _: u64, _: &mut World) -> Result, String> { - Ok(Some(self.base_profile())) - } - fn range(&mut self, _: u64, _: &World) -> Result, String> { - Ok(vec![216]) - } - fn skill_active(&self, _: u64, _: &World) -> Result { - Ok(false) - } - fn can_attack(&mut self, _: u64, _: AttackProfile, _: &mut World) -> Result { - Ok(true) - } -} -impl blocking::Hooks for Host { - fn blocked(&mut self, _: u64, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl motion::Hooks for Host { - fn check_block(&mut self, _: u64, _: &mut World, _: &mut Grid) -> Result { - Ok(false) - } - fn hidden(&mut self, id: u64, on: bool, w: &mut World) -> Result<(), String> { - w.unit_mut(id)?.hidden = on; - Ok(()) - } - fn cut_attack_stand(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn leak(&mut self, id: u64, w: &mut World) -> Result<(), String> { - let u = w.unit_mut(id)?; - u.stats.alive = false; - u.deployed = false; - self.trace.push(json!(["leak"])); - Ok(()) - } -} -impl health::Hooks for Host { - fn kill(&mut self, id: u64, _: Option, w: &mut World) -> Result<(), String> { - let u = w.unit_mut(id)?; - u.stats.hp = 0.0; - u.stats.alive = false; - u.deployed = false; - self.trace.push(json!(["kill"])); - Ok(()) - } -} -impl buffs::Hooks for Host { - fn burst_damage( - &mut self, - r: &mut hit::Request, - runtime: &mut buffs::Runtime, - w: &mut World, - ) -> Result { - let mut rng = self.rng.clone(); - let result = settlement::resolve(w, runtime, &mut rng, self, r); - self.rng = rng; - result - } - fn status(&mut self, _: u64, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - token: u64, - _: buffs::Event, - c: buffs::Context, - r: &mut buffs::Runtime, - w: &mut World, - ) -> Result<(), String> { - if token != 1 { - return Err("Unknown fixture buff callback".into()); - } - self.trace.push(json!(["pulse"])); - r.edit(w, c.unit, c.buff, |b| b.stacks += 1) - } -} -impl status::Hooks for Host { - fn has_before_status(&self) -> bool { - false - } - fn before_status( - &mut self, - _: &mut status::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Unexpected status hook".into()) - } - fn has_status_applied(&self) -> bool { - false - } - fn status_applied( - &mut self, - _: &status::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Unexpected status hook".into()) - } -} -impl element::Hooks for Host { - fn battle_rect(&self) -> Rect { - Rect::FULL - } - fn element_enabled(&self, _: element::Phase) -> bool { - false - } - fn element_event( - &mut self, - _: element::Phase, - _: &mut element::Request, - _: f64, - _: f64, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Unexpected element hook".into()) - } - fn element_number(&mut self, _: u64, _: f64, _: Element) -> Result<(), String> { - Ok(()) - } - fn burst_visual(&mut self, _: u64, _: Element, _: &World) -> Result<(), String> { - Ok(()) - } -} -impl settlement::Hooks for Host { - fn damage_health_event( - &mut self, - e: &mut health::Event, - request: &mut hit::Request, - r: &mut buffs::Runtime, - w: &mut World, - rng: &mut Rng, - ) -> Result<(), String> { - if e.stage == health::Stage::Damaged { - if let Some(mut req) = self.content.as_ref().unwrap().damaged(w, request)? { - self.rng = rng.clone(); - let result = element::apply(w, self, r, &mut req); - *rng = self.rng.clone(); - result?; - } - } - Ok(()) - } -} -impl skills::Hooks for Host { - fn event( - &mut self, - event: Event, - _: &mut Context, - _: &mut Runtime, - w: &mut World, - ) -> Result<(), String> { - match event { - Event::ApplyModifiers => { - let mut r = self.buffs.take().unwrap(); - let result = r.add( - w, - self, - 1, - buffs::Spec { - buff: Buff { - key: Some("skill".into()), - mods: [("atkPct".into(), 0.5)].into_iter().collect(), - ..Default::default() - }, - mods_present: true, - ..Default::default() - }, - ); - self.buffs = Some(r); - result?; - } - Event::RemoveModifiers => { - let mut r = self.buffs.take().unwrap(); - let result = r.remove(w, self, 1, "skill"); - self.buffs = Some(r); - result?; - } - Event::Start => self.trace.push(json!(["start"])), - Event::End => self.trace.push(json!(["end"])), - Event::SkillStart => self.trace.push(json!(["skillStart"])), - Event::SkillEnd => self.trace.push(json!(["skillEnd"])), - Event::AmmoUsed => self.trace.push(json!(["ammoUsed"])), - _ => {} - } - Ok(()) - } - fn condition(&mut self, _: Condition, _: &Runtime, w: &mut World) -> Result { - if self.d["healer"] == true { - Ok(!search::Host::injured_allies(self, 1, &[216], false, w, 8)?.is_empty()) - } else { - Ok(!search::Host::enemies(self, 1, &[216], Profile::default(), w, 8)?.is_empty()) - } - } - fn profile(&mut self, _: u64, _: &mut World) -> Result, String> { - Ok(Some(self.base_profile())) - } - fn has_sp_hook(&self) -> bool { - false - } -} -impl ally::Host for Host { - fn effective_profile( - &mut self, - _: u64, - _: Option<&Runtime>, - _: &mut World, - ) -> Result, String> { - Ok(Some(self.base_profile())) - } - fn range_changed(&mut self, _: u64, _: &mut World) -> Result { - Ok(false) - } - fn refresh_range(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn has_store_energy(&self, _: u64, _: AttackProfile) -> bool { - self.d["store"] == true - } - fn store_energy(&mut self, _: u64, _: AttackProfile, _: &mut World) -> Result { - self.trace.push(json!(["store"])); - if self.stored >= 2 { - return Ok(false); - } - self.stored += 1; - Ok(true) - } - fn perform( - &mut self, - id: u64, - _: AttackProfile, - selected: Selection, - skill: Option<&mut Runtime>, - w: &mut World, - ) -> Result<(), String> { - let used = skill - .as_deref() - .map(|s| s.attack_override() || s.targeting_override()) - .unwrap_or(false); - let payload = attacks::Direct { - mode: if self.d["healer"] == true { - attacks::Mode::Heal - } else { - attacks::Mode::Damage(DamageType::Physical) - }, - hits: self.d["hits"].as_u64().unwrap() as u32, - atk_scale: if used { 1.5 } else { 1.0 }, - skill_damage_mul: 1.0, - target_damage_mul: 1.0, - split_mul: None, - heal_scale: 1.0, - is_skill: used, - }; - let area = attacks::Area { - splash: if self.d["splash"] == true { - Some(attacks::Splash { - radius: 1.5, - scale: 0.7, - hits_fly: false, - fortress_melee: false, - }) - } else { - None - }, - chain: if self.d["chain"] == true { - Some(attacks::Chain { - count: 4.0, - radius: 1.7, - falloff: 0.15, - sluggish: 0.0, - }) - } else { - None - }, - ..Default::default() - }; - let mut executor = self.executor.take().ok_or("Reentrant test executor")?; - let result = if self.d["ranged"] == true && self.d["healer"] != true { - let Some(prepared) = executor.prepare(w, self, id, &selected.targets, payload)? else { - self.executor = Some(executor); - return Ok(()); - }; - for &target in &prepared.context.targets { - let from = w.unit(id)?.position; - self.flights - .as_mut() - .ok_or("Reentrant fixture flight queue")? - .add( - w, - Launch { - from, - source: Some(id), - target: Some(target), - to: None, - speed: 14.0, - hit_dead: area.splash.is_some(), - max_age: 10.0, - on_hit: true, - visual: "arrow".into(), - speed_changeable: None, - removable: None, - payload: Shot::Ally(id, prepared.attack_id, payload, area), - }, - )?; - } - executor.finish(w, self, prepared, skill) - } else { - executor.perform_area(w, self, id, &selected.targets, payload, area, skill) - }; - self.executor = Some(executor); - result - } -} -impl attacks::Hooks for Host { - fn radius_targets( - &mut self, - origin: [f64; 2], - radius: f64, - splash: bool, - w: &mut World, - limit: usize, - ) -> Result, String> { - let enemies = self.enemies.clone(); - spatial::enemies_in_radius( - w, - self, - &enemies, - origin, - radius, - if splash { - spatial::RadiusRule::Centre - } else { - spatial::RadiusRule::Body - }, - splash, - limit, - ) - } - fn chain_link(&mut self, _: u64, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn sluggish(&mut self, _: u64, _: u64, _: f64, _: &mut World) -> Result<(), String> { - Err("Fixture has no status handler".into()) - } - fn has_before_attack(&self) -> bool { - false - } - fn before_attack(&mut self, _: &mut attacks::Context, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn engage(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn damage(&mut self, w: &mut World, r: &mut hit::Request) -> Result { - let mut runtime = self.buffs.take().ok_or("Reentrant fixture buff runtime")?; - let mut rng = self.rng.clone(); - let result = settlement::resolve(w, &mut runtime, &mut rng, self, r); - self.buffs = Some(runtime); - self.rng = rng; - result - } - fn each_hit( - &mut self, - _: attacks::Impact, - _: Option<&mut Runtime>, - _: &mut World, - ) -> Result<(), String> { - Ok(()) - } - fn after_hit( - &mut self, - _: attacks::Impact, - _: Option<&mut Runtime>, - _: &mut World, - ) -> Result<(), String> { - Ok(()) - } - fn attack( - &mut self, - _: &mut attacks::Context, - _: Option<&mut Runtime>, - _: &mut World, - ) -> Result<(), String> { - Ok(()) - } - fn after_attack( - &mut self, - _: &attacks::Context, - _: Option<&mut Runtime>, - _: &mut World, - ) -> Result<(), String> { - Ok(()) - } -} -impl enemy::Hooks for Host { - fn profile(&mut self, _: u64, _: &mut World) -> Result { - Ok(enemy::Profile { - melee: false, - animation: Some(enemy::Animation { - duration: 0.8, - hit: Some(0.3), - }), - ..Default::default() - }) - } - fn allies_in_radius( - &mut self, - id: u64, - radius: f64, - w: &mut World, - limit: usize, - ) -> Result, String> { - spatial::allies_in_radius(w, &[1], w.unit(id)?.position, radius, None, false, limit) - } - fn enemies_in_radius( - &mut self, - id: u64, - radius: f64, - w: &mut World, - limit: usize, - ) -> Result, String> { - let ids = self.enemies.clone(); - let origin = w.unit(id)?.position; - spatial::enemies_in_radius( - w, - self, - &ids, - origin, - radius, - spatial::RadiusRule::Body, - false, - limit, - ) - } - fn can_target(&mut self, _: u64, _: u64, _: &mut World) -> Result { - Ok(true) - } - fn enemy_event_enabled(&self, _: enemy::Event) -> bool { - false - } - fn enemy_event( - &mut self, - _: enemy::Event, - _: &mut enemy::Context, - _: &mut buffs::Runtime, - _: &mut World, - _: &mut Grid, - _: &mut Rng, - ) -> Result<(), String> { - Err("Unexpected enemy hook".into()) - } - fn attack_visual(&mut self, _: u64, _: u64, _: &str) -> Result<(), String> { - Ok(()) - } - fn palsy_visual(&mut self, _: u64, _: &World) -> Result<(), String> { - Ok(()) - } - fn deliver( - &mut self, - d: enemy::Delivery, - r: &mut buffs::Runtime, - w: &mut World, - rng: &mut Rng, - ) -> Result<(), String> { - if d.projectile { - self.flights.as_mut().unwrap().add( - w, - Launch { - from: w.unit(d.source)?.position, - source: Some(d.source), - target: Some(d.target), - to: None, - speed: 10.0, - hit_dead: false, - max_age: 10.0, - on_hit: true, - visual: "enemy".into(), - speed_changeable: None, - removable: None, - payload: Shot::Enemy(d), - }, - )?; - } else { - enemy::impact(w, r, rng, self, d, Some(d.target))?; - } - Ok(()) - } -} -struct FlightHost<'a> { - host: &'a mut Host, - skill: &'a mut Runtime, -} -impl projectiles::Hooks for FlightHost<'_> { - fn has_step(&self) -> bool { - false - } - fn step( - &mut self, - _: &mut Projectile, - _: &mut System, - _: &mut World, - ) -> Result { - Ok(false) - } - fn impact( - &mut self, - p: &mut Projectile, - target: Option, - _: &mut System, - w: &mut World, - ) -> Result<(), String> { - match p.payload { - Shot::Ally(id, attack_id, payload, area) => { - let mut executor = self.host.executor.take().unwrap(); - let result = executor.impact_at( - w, - self.host, - id, - target, - attack_id, - payload, - area, - p.position, - Some(self.skill), - ); - self.host.executor = Some(executor); - result - } - Shot::Enemy(d) => { - let mut runtime = self.host.buffs.take().unwrap(); - let mut rng = self.host.rng.clone(); - let result = enemy::impact(w, &mut runtime, &mut rng, self.host, d, target); - self.host.buffs = Some(runtime); - self.host.rng = rng; - result.map(|_| ()) - } - } - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; continuous 240-tick combat fixtures"] -fn native_composition_matches_continuous_attacks() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/combat.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let d = &v["scenario"]; - let mut w = World::new(6, 1, 1).unwrap(); - let mut base = Base::default(); - for (k, x) in [ - ( - "maxHp", - if d["i"].as_u64().unwrap() >= 84 { - 100000. - } else { - 1000. - }, - ), - ("atk", 80.0), - ("bat", 0.2), - ] { - base.0.insert(k.into(), x); - } - let mut u = Unit::new(UnitStats::new(base), Side::Ally); - u.deployed = true; - u.position = [10.0, 4.0]; - u.deployment.tile = [10, 4]; - w.insert_unit(1, u).unwrap(); - let mut base = Base::default(); - base.0.insert( - "maxHp".into(), - if d["dead"] == true { 500.0 } else { 100000.0 }, - ); - base.0.insert("def".into(), 20.0); - base.0.insert( - "atk".into(), - if d["i"].as_u64().unwrap() >= 84 { - d["contentRaw"]["stats"]["atk"].as_f64().unwrap() - } else { - 30. - }, - ); - base.0.insert("res".into(), 30.0); - base.0.insert("moveSpeed".into(), 2.0); - base.0.insert("rangeRadius".into(), 3.0); - let mut e = Unit::new( - UnitStats::new(base), - if d["healer"] == true { - Side::Ally - } else { - Side::Enemy - }, - ); - if d["healer"] == true { - e.stats.hp = 100.0; - } - e.deployed = true; - e.position = [10.0, 6.0]; - e.deployment.tile = [10, 6]; - e.targeting.spawn_seq = 1; - if d["mobile"] == true { - e.motion.route=Some(motion::Route::compile(&json!({"checkpoints":[{"type":"WAIT","time":0.2},{"type":"MOVE","pos":[10,9]},{"type":"MOVE","pos":[10,6]}],"end":[10,9]}),Rect::FULL,64,e.position).unwrap()); - } - w.insert_unit(2, e).unwrap(); - let mut enemies = if d["healer"] == true { vec![] } else { vec![2] }; - let mut extra_ids = vec![]; - if d["i"].as_u64().unwrap() >= 24 && d["healer"] != true { - for j in 0..4 { - let mut base = Base::default(); - base.0.insert( - "maxHp".into(), - if d["dead"] == true { 500.0 } else { 100000.0 }, - ); - base.0.insert("def".into(), 20.0); - let mut e = Unit::new(UnitStats::new(base), Side::Enemy); - e.position = [10.0, 6.8 + j as f64 * 0.6]; - e.motion_fly = j % 2 == 1; - e.deployed = true; - e.targeting.spawn_seq = j + 2; - let id = j + 3; - w.insert_unit(id, e).unwrap(); - enemies.push(id); - extra_ids.push(id); - } - } - let bank = Bank::new( - 1, - match d["kind"].as_str().unwrap() { - "duration" => Kind::Duration, - "ammo" => Kind::Ammo, - _ => Kind::Instant, - }, - 2.0, - 1, - 8, - ) - .unwrap(); - let spec = Spec { - duration: 0.3, - ammo: 2.0, - sp_type: SpType::Attack, - rule: Rule::parse(d["rule"].as_str().unwrap()), - attack: d["attack"] == true, - modifiers: true, - ..Spec::default() - }; - let mut s = Runtime::new(bank, spec, 64).unwrap(); - let mut h = Host { - d: d.clone(), - trace: vec![], - index: Some(Index::new(6, 256).unwrap()), - enemies, - grid: Some( - Grid::new( - &json!({"rows":vec!["r".repeat(21);19],"legend":{}}), - Rect::FULL, - ) - .unwrap(), - ), - stored: 0, - executor: Some(attacks::Executor::new(8, 8).unwrap()), - flights: Some(System::new(128).unwrap()), - buffs: Some(buffs::Runtime::new(16, 256, 64).unwrap()), - rng: Rng::new(42), - content: None, - }; - h.move_target(&mut w, true).unwrap(); - let mut content = enemy_content::Runtime::new(6).unwrap(); - if let Some(key) = d["contentKey"].as_str() { - let mut buffs = h.buffs.take().unwrap(); - content - .spawn( - &mut w, - &mut buffs, - &mut h, - 2, - enemy_content::Kit::compile(key, &d["contentRaw"], &Value::Null, None).unwrap(), - &Value::Null, - ) - .unwrap(); - h.buffs = Some(buffs); - } - h.content = Some(content); - s.reset(&mut w, &mut h, None).unwrap(); - let mut cache = Commitments::new(1, 8, 8).unwrap(); - let mut states = vec![]; - for tick in 0..240 { - w.time = tick as f64 / 30.0; - if (40..60).contains(&d["i"].as_u64().unwrap()) && d["healer"] != true && tick == 0 { - let el = [ - Element::Burn, - Element::Neural, - Element::Necrosis, - Element::Apoptosis, - Element::Erosion, - ][d["i"].as_u64().unwrap() as usize % 5]; - let mut r = h.buffs.take().unwrap(); - element::apply( - &mut w, - &mut h, - &mut r, - &mut element::Request::new(Some(1), Some(1), 2, el, 1100.0), - ) - .unwrap(); - h.buffs = Some(r); - } - if d["shooterDeath"] == true && tick == 2 { - let u = w.unit_mut(1).unwrap(); - u.stats.alive = false; - u.deployed = false; - u.removed = true; - s.end(&mut w, &mut h, "death").unwrap(); - } - if d["healer"] == true { - let e = w.unit_mut(2).unwrap(); - e.stats.hp = (e.stats.hp - 3.0).max(1.0); - } - - let mut buffs = h.buffs.take().unwrap(); - if d["healer"] != true && d["i"].as_u64().unwrap() >= 24 { - if tick % 31 == 0 { - let mut b = Buff { - key: Some("battleShield".into()), - shield: 50.0, - ..Default::default() - }; - b.runtime.duration = 0.3; - buffs - .add( - &mut w, - &mut h, - 2, - buffs::Spec { - buff: b, - ..Default::default() - }, - ) - .unwrap(); - } - if tick % 37 == 0 { - let mut b = Buff { - key: Some("protection".into()), - mods: [("dmgTakenMul".into(), 0.8), ("dodgePhys".into(), 0.2)] - .into_iter() - .collect(), - ..Default::default() - }; - b.runtime.duration = 0.5; - buffs - .add( - &mut w, - &mut h, - 2, - buffs::Spec { - buff: b, - mods_present: true, - ..Default::default() - }, - ) - .unwrap(); - } - } - - if d["i"].as_u64().unwrap() >= 36 && tick % 23 == 0 { - let mut b = Buff { - key: Some("pulse".into()), - mods: [("atkPct".into(), 0.1)].into_iter().collect(), - ..Default::default() - }; - b.runtime.duration = 0.4; - b.runtime.interval = 0.1; - b.runtime.on_tick = Some(1); - buffs - .add( - &mut w, - &mut h, - 1, - buffs::Spec { - buff: b, - mods_present: true, - ..Default::default() - }, - ) - .unwrap(); - } - let units: Vec<_> = (1..=if extra_ids.is_empty() { 2 } else { 6 }).collect(); - if d["mobile"] == true { - if tick == 20 { - status::apply( - &mut w, - &mut h, - &mut buffs, - Rect::FULL, - 2, - "fear", - status::Options { - duration: 0.6, - source: Some(1), - ..Default::default() - }, - ) - .unwrap(); - } - if tick == 40 { - status::apply( - &mut w, - &mut h, - &mut buffs, - Rect::FULL, - 2, - "attract", - status::Options { - duration: 0.6, - point: Some([10.0, 6.0]), - ..Default::default() - }, - ) - .unwrap(); - } - if tick == 90 { - h.grid - .as_mut() - .unwrap() - .set_obstacle([10, 7], true, 1) - .unwrap(); - } - if tick == 130 { - h.grid - .as_mut() - .unwrap() - .set_obstacle([10, 7], false, 1) - .unwrap(); - } - } - if d.get("contentKey").is_some() { - for (at, key, duration) in [ - (12, "reveal", 0.8), - (90, "reveal", 0.8), - (40, "silence", 0.3), - (120, "silence", 0.3), - ] { - if tick == at { - status::apply( - &mut w, - &mut h, - &mut buffs, - Rect::FULL, - 2, - key, - status::Options { - duration, - ..Default::default() - }, - ) - .unwrap(); - } - } - } - buffs.tick(&mut w, &mut h, &units, 1.0 / 30.0).unwrap(); - h.buffs = Some(buffs); - - h.move_target(&mut w, tick % 17 < 12).unwrap(); - w.unit_mut(1) - .unwrap() - .stats - .put_named_buff( - "control", - Buff { - flags: if d["stun"] == true && (30..45).contains(&tick) { - ["stun".into()].into_iter().collect() - } else { - Default::default() - }, - ..Buff::default() - }, - 8, - ) - .unwrap(); - cache.capture(&mut w, &mut h, &[1], 1.0 / 30.0).unwrap(); - if d["mobile"] == true && w.unit(2).unwrap().stats.alive { - let mut buffs = h.buffs.take().unwrap(); - let mut grid = h.grid.take().unwrap(); - let mut rng = h.rng.clone(); - enemy::update( - &mut w, - &mut grid, - &mut buffs, - &mut rng, - &mut h, - 2, - 1.0 / 30.0, - 8, - ) - .unwrap(); - h.buffs = Some(buffs); - h.grid = Some(grid); - h.rng = rng; - } - h.move_target(&mut w, (tick + 1) % 17 < 12).unwrap(); - if w.unit(1).unwrap().stats.alive && w.unit(1).unwrap().deployed { - s.tick(&mut w, &mut h, 1.0 / 30.0).unwrap(); - } - ally::update(&mut w, &mut h, &cache, 1, Some(&mut s), 1.0 / 30.0, 8).unwrap(); - let mut flights = h.flights.take().unwrap(); - flights - .update( - &mut w, - &mut FlightHost { - host: &mut h, - skill: &mut s, - }, - 1.0 / 30.0, - ) - .unwrap(); - h.flights = Some(flights); - let mut buffs = h.buffs.take().unwrap(); - let mut content = h.content.take().unwrap(); - content - .tick(&mut w, &mut buffs, &mut h, &[2], 1. / 30.) - .unwrap(); - h.content = Some(content); - h.buffs = Some(buffs); - if d["stop"] == true && tick == 100 { - s.end(&mut w, &mut h, "stopped").unwrap(); - } - let atk = w.unit_mut(1).unwrap().stats.stats().unwrap().n("atk"); - let element_lock = element::locked(&mut w, 2).unwrap(); - let enemy_stats = w.unit_mut(2).unwrap().stats.stats().unwrap(); - let (enemy_atk, enemy_res, enemy_shield) = ( - enemy_stats.n("atk"), - enemy_stats.n("res"), - enemy_stats.n("shield"), - ); - let u = w.unit(1).unwrap(); - let e = w.unit(2).unwrap(); - states.push(json!({"sourceElement":u.element_buildup.map(bits),"hp":bits(e.stats.hp),"sourceHp":bits(u.stats.hp),"enemyCd":bits(e.cadence.cooldown),"enemyAttacks":e.attacks,"attackSequence":w.attack_sequence(),"alive":e.stats.alive,"position":e.position.map(bits),"moving":e.moving,"element":e.element_buildup.map(bits),"elementLock":element_lock,"enemyAtk":bits(enemy_atk),"enemyRes":bits(enemy_res),"shield":bits(enemy_shield),"rng":h.rng.state(),"otherHp":extra_ids.iter().map(|id|bits(w.unit(*id).unwrap().stats.hp)).collect::>(),"flights":h.flights.as_ref().unwrap().list().len(),"cd":bits(u.cadence.cooldown),"had":u.cadence.had_target,"attacks":u.attacks,"sp":bits(s.bank.sp),"charges":bits(s.bank.charges),"active":s.bank.active,"pending":s.pending,"time":bits(s.time_left),"ammo":bits(s.ammo_left),"last":bits(u.last_attack_at),"atk":bits(atk)})); - } - for (tick, (a, b)) in states - .iter() - .zip(v["states"].as_array().unwrap()) - .enumerate() - { - assert_eq!(a, b, "tick {tick} case {d}"); - } - assert_eq!(json!(h.trace), v["trace"], "events {d}"); - h.flights.as_mut().unwrap().clear(&mut w).unwrap(); - enemy::clear(&mut w, 2).unwrap(); - assert_eq!(w.unit_pins(1).unwrap(), 0); - assert_eq!(w.unit_pins(2).unwrap(), 0); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 96); -} diff --git a/crates/engine/tests/definitions_reference.rs b/crates/engine/tests/definitions_reference.rs deleted file mode 100644 index d571158..0000000 --- a/crates/engine/tests/definitions_reference.rs +++ /dev/null @@ -1,85 +0,0 @@ -use arkguard_engine::battle::{damage::DamageType, definitions::Enemy, enemy::Mode}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(n: f64) -> String { - format!("{:016x}", n.to_bits()) -} -fn canonical(v: &mut Value) { - match v { - Value::Number(n) => { - let x = n.as_f64().unwrap(); - if x.fract() == 0. && x.abs() < i64::MAX as f64 { - *v = json!(x as i64); - } - } - Value::Array(a) => a.iter_mut().for_each(canonical), - Value::Object(o) => o.values_mut().for_each(canonical), - _ => {} - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; every enemy definition and actual spawnEnemy"] -fn every_enemy_definition_and_spawn_match() { - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap(); - let script = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/definitions.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(root) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let c: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let key = c["key"].as_str().unwrap(); - let d = Enemy::parse(key, &c["raw"]) - .unwrap() - .with_overrides(&c["overrides"]); - let mut actual = snapshot(&d); - let mut expected = c["output"].clone(); - canonical(&mut actual); - canonical(&mut expected); - assert_eq!(actual, expected, "definition {key}"); - let mut u = d.unit(&c["mods"], [10., 6.], 0.).unwrap(); - let base: serde_json::Map<_, _> = d - .base - .0 - .keys() - .map(|k| (k.clone(), json!(bits(u.stats.base_number(k))))) - .collect(); - let fly = u.stats.is_flying(true, u.motion_fly).unwrap(); - let actual = json!({"base":base,"hp":bits(u.stats.hp),"blockWeight":bits(u.block_weight),"fly":fly,"staticBody":u.static_body,"immune":u.immune,"position":u.position.map(bits)}); - assert_eq!(actual, c["unit"], "spawn {key}"); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert!(count > 200); - eprintln!("{count} real enemy definitions and spawns"); -} -#[test] -fn invalid_spawns_fail_before_creating_units() { - let d = Enemy::parse("enemy_a", &json!({"hp":1000})).unwrap(); - assert!(d.unit(&json!({"hpMul":f64::MAX}), [0.; 2], 0.).is_err()); - assert!(d.unit(&Value::Null, [f64::NAN, 0.], 0.).is_err()); - assert!(Enemy::parse("enemy_a", &Value::Null).is_err()); -} - -fn snapshot(d: &Enemy) -> Value { - let mode = match d.profile.mode { - Mode::None => "none", - Mode::Heal => "heal", - Mode::Damage(DamageType::Physical) => "phys", - Mode::Damage(DamageType::Arts) => "arts", - Mode::Damage(DamageType::True) => "true", - Mode::Damage(DamageType::Elemental) => "elemental", - }; - json!({"key":d.key,"base":d.base.0,"dmgType":mode,"melee":d.profile.melee,"motion":if d.fly{"FLY"}else{"WALK"},"leader":d.leader, - "lpr":d.lpr,"blockWeight":d.block_weight,"immune":d.immune,"epResistance":d.ep_resistance,"elementalResistance":d.elemental_resistance, - "notCountInTotal":d.not_count_in_total,"hitArea":d.hit_area.map(|a|json!({"w":a.width,"h":a.height,"dx":a.dx,"dy":a.dy})), - "attackAnim":d.profile.animation.map(|a|json!({"dur":a.duration,"hit":a.hit})),"attackMoves":d.profile.attack_moves,"staticBody":d.static_body}) -} diff --git a/crates/engine/tests/deploy_reference.rs b/crates/engine/tests/deploy_reference.rs deleted file mode 100644 index 062bf79..0000000 --- a/crates/engine/tests/deploy_reference.rs +++ /dev/null @@ -1,178 +0,0 @@ -use arkguard_engine::battle::{ - deploy::{Deployment, Event, Hooks, Kind, Options}, - grid::Rect, - health::{Side, Unit, World}, - stats::{Base, UnitStats}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Host { - revive: bool, - trace: Vec, -} -impl arkguard_engine::battle::blocking::Hooks for Host { - fn blocked(&mut self, _: u64, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl Hooks for Host { - fn initialize( - &mut self, - _: u64, - _: Options, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn event( - &mut self, - e: Event, - id: u64, - _: Option, - w: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - let name = match e { - Event::Kill => { - if self.revive { - w.unit_mut(id)?.stats.hp = 15.0; - } - "kill" - } - Event::Death => "death", - Event::Deploy => "deploy", - _ => return Ok(()), - }; - self.trace.push(json!([name, id])); - Ok(()) - } - fn remove_temporary_effects(&mut self, id: u64, w: &mut World) -> Result<(), String> { - w.unit_mut(id)?.stats.set_buffs(vec![]); - Ok(()) - } -} -fn make(kind: Kind, home: [i32; 2]) -> Unit { - let mut b = Base::default(); - for (k, v) in [("maxHp", 100.0), ("cost", 7.0), ("respawnTime", 3.0)] { - b.0.insert(k.into(), v); - } - let mut u = Unit::new(UnitStats::new(b), Side::Ally); - u.stats.alive = false; - u.owner = Some(1); - u.deployment.kind = kind; - u.deployment.uid = Some(1); - u.deployment.home = home; - u.deployment.tile = home; - u -} -fn view(w: &World, id: u64) -> Value { - let u = w.unit(id).unwrap(); - json!({"alive":u.stats.alive,"deployed":u.deployed,"removed":u.removed,"hp":bits(u.stats.hp),"down":Deployment::is_down(w,id).unwrap(),"body":u.deployment.body,"rest":Deployment::rest_tile(w,id).unwrap(),"respawn":bits(u.deployment.respawn_at)}) -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; deployment lifecycle only"] -fn deploy_death_redeploy_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/deploy.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let d = &v["scenario"]; - let mut w = World::new(3, 1, 1).unwrap(); - let mut dep = Deployment::new( - Rect { - r0: 9, - r1: 12, - c0: 2, - c1: 10, - }, - 3, - 1, - 99.0, - ) - .unwrap(); - dep.set_dp(1, 20.0).unwrap(); - w.insert_unit( - 1, - make( - if d["token"] == true { - Kind::Token - } else { - Kind::Operator - }, - [9, 2], - ), - ) - .unwrap(); - w.insert_unit( - 2, - make( - Kind::Operator, - if d["foreign"] == true { - [10, 4] - } else { - [12, 10] - }, - ), - ) - .unwrap(); - dep.register(1, &w).unwrap(); - dep.register(2, &w).unwrap(); - let mut h = Host { - revive: d["revive"] == true, - trace: vec![], - }; - dep.deploy(&mut w, &mut h, 1, Options::default()).unwrap(); - dep.deploy(&mut w, &mut h, 2, Options::default()).unwrap(); - if d["foreign"] == true { - assert!(dep.relocate(&mut w, &mut h, 2, [12, 9]).unwrap()); - } - assert!(dep.relocate(&mut w, &mut h, 1, [10, 4]).unwrap()); - if d["homeTaken"] == true { - assert!(dep.relocate(&mut w, &mut h, 2, [9, 2]).unwrap()); - } - w.unit_mut(1).unwrap().deployment.down_at_home = d["downHome"] == true; - w.time = 1.0; - if d["retreat"] == true { - dep.retreat( - &mut w, - &mut h, - 1, - if d["raid"] == true { "raid" } else { "retreat" }, - d["permanent"] == true, - ) - .unwrap(); - } else { - dep.kill(&mut w, &mut h, 1, None).unwrap(); - } - assert_eq!(view(&w, 1), v["before"], "before {d}"); - w.time = 5.0; - dep.check_redeploys(&mut w, &mut h).unwrap(); - let mut after = view(&w, 1); - let u = w.unit(1).unwrap(); - after["seq"] = json!(u.deployment.deploy_seq); - after["tile"] = json!(u.deployment.tile); - after["dp"] = json!(bits(dep.dp(1).unwrap())); - assert_eq!(after, v["after"], "after {d}"); - assert_eq!(json!(h.trace), v["trace"], "trace {d}"); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 384); -} diff --git a/crates/engine/tests/displacement_reference.rs b/crates/engine/tests/displacement_reference.rs deleted file mode 100644 index 332118c..0000000 --- a/crates/engine/tests/displacement_reference.rs +++ /dev/null @@ -1,219 +0,0 @@ -use arkguard_engine::{ - battle::{ - blocking, - deploy::{self, Deployment, Options}, - direction::Direction, - displacement::{self, Origin, Pull, Push}, - grid::{Grid, Rect}, - health::{Id, Side, Unit, World}, - motion::Route, - stats::{Base, Buff, UnitStats}, - }, - data::Catalog, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(n: f64) -> String { - format!("{:016x}", n.to_bits()) -} -fn pair(v: &Value) -> [f64; 2] { - [v[0].as_f64().unwrap(), v[1].as_f64().unwrap()] -} -#[derive(Default)] -struct Host { - ended: u64, -} -impl blocking::Hooks for Host { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: Id, _: &mut World) -> Result<(), String> { - self.ended += 1; - Ok(()) - } -} -impl deploy::Hooks for Host { - fn initialize( - &mut self, - _: Id, - _: Options, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn event( - &mut self, - _: deploy::Event, - _: Id, - _: Option, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn remove_temporary_effects(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; push/pull forces, collisions and unbalance"] -fn displacement_physics_matches() { - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap(); - let data = Catalog::load(&Path::new(&root).join("data"), 64 << 20).unwrap(); - let script = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/displacement.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(root) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut cases = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let c = &v["cfg"]; - let mut stage = data.table("stages").unwrap()[c["stageId"].as_str().unwrap()].clone(); - stage["legend"] = stage["tiles"].clone(); - let rect = Rect::NORMAL; - let grid = Grid::new(&stage, rect).unwrap(); - let mut w = World::new(2, 1, 1).unwrap(); - let mut h = Host::default(); - let mut base = Base::default(); - base.0.insert("maxHp".into(), 1000.); - base.0 - .insert("massLevel".into(), c["mass"].as_f64().unwrap()); - let mut e = Unit::new( - UnitStats::new(base), - if c["ally"] == true { - Side::Ally - } else { - Side::Enemy - }, - ); - e.position = pair(&c["position"]); - e.stats.alive = c["dead"] != true; - e.deployed = true; - e.boss = c["boss"] == true; - e.static_body = c["static"] == true; - e.motion_fly = c["fly"] == true; - e.motion.unbalance_until = c["hold"].as_f64().unwrap_or(f64::NEG_INFINITY); - e.motion.attack_stand_until = 3.; - let mut route = Route::compile(&json!({"end":[10,8]}), rect, 8, e.position).unwrap(); - route.points = Some(vec![[10., 5.]]); - e.motion.route = Some(route); - if c["noDisplace"] == true { - let mut b = Buff::default(); - b.flags.insert("noDisplace".into()); - e.stats.set_buffs(vec![b]); - } - w.insert_unit(1, e).unwrap(); - let mut base = Base::default(); - base.0.insert("maxHp".into(), 1000.); - base.0.insert("blockCnt".into(), 3.); - let mut a = Unit::new(UnitStats::new(base), Side::Ally); - a.deployment.kind = deploy::Kind::Operator; - a.deployment.home = [10, 5]; - a.stats.alive = false; - a.ground = true; - w.insert_unit(2, a).unwrap(); - let mut d = Deployment::new(rect, 2, 1, 99.).unwrap(); - d.register(2, &w).unwrap(); - d.deploy(&mut w, &mut h, 2, Options::default()).unwrap(); - blocking::check(&mut w, &d, &grid, &mut h, 1).unwrap(); - let direction = match c["dir"].as_str().unwrap() { - "RIGHT" => Direction::Right, - "UP" => Direction::Up, - "LEFT" => Direction::Left, - _ => Direction::Down, - }; - for (j, op) in v["ops"].as_array().unwrap().iter().enumerate() { - w.time = j as f64 * 0.07; - w.unit_mut(1).unwrap().motion.attack_stand_until = w.time + 0.4; - let force = op["force"].as_f64().unwrap(); - let dir = [ - op["dir"]["y"].as_f64().unwrap(), - op["dir"]["x"].as_f64().unwrap(), - ]; - let from = Origin { - position: pair(&op["from"]["position"]), - forward: op["from"]["forward"] - .as_array() - .map(|_| pair(&op["from"]["forward"])), - unit: Some(2), - }; - let push = Push { - from: Some(from), - fixed: op["fixed"] == true, - fixed_angle: op["fixedAngle"] == true, - effect: op["effect"] == true, - ..Push::default() - }; - let moved = match op["op"].as_u64().unwrap() { - 0 => displacement::push( - &mut w, - &grid, - &mut h, - 1, - force, - Push { - inward: op["inward"] == true, - ..push - }, - ), - 1 => displacement::push( - &mut w, - &grid, - &mut h, - 1, - force, - Push { - direction: Some(dir), - ..push - }, - ), - 2 => { - let center = Origin::unit(&w, 2, direction).unwrap(); - displacement::pull( - &mut w, - &grid, - &mut h, - 1, - force, - Pull { - to: pair(&op["to"]), - center: Some(center), - stop: op["stop"].as_f64().unwrap(), - }, - ) - } - 3 => displacement::pull_to_front(&mut w, &grid, &mut h, 1, 2, direction, force), - 4 => displacement::displace( - &mut w, - &grid, - &mut h, - 1, - dir, - op["distance"].as_f64().unwrap(), - ), - 5 => displacement::push_distance(&mut w, 1, force, op["effect"] == true), - 6 => { - displacement::unbalance(&mut w, 1, op["distance"].as_f64().unwrap()).map(|_| 0.) - } - _ => unreachable!(), - } - .unwrap(); - let level = displacement::force_level(&mut w, 1, force).unwrap(); - let e = w.unit(1).unwrap(); - let actual = json!({"moved":bits(moved),"position":e.position.map(bits),"until":bits(e.motion.unbalance_until),"stand":bits(e.motion.attack_stand_until),"blocked":e.blocked_by(),"blocking":w.unit(2).unwrap().blocking(),"cached":e.motion.route.as_ref().unwrap().points.is_some(),"ended":h.ended,"level":bits(level),"tables":([displacement::push_tiles(force,op["effect"]==true),displacement::push_hold(force),displacement::pull_hold(force)].map(bits))}); - assert_eq!(actual, v["states"][j], "case {cases} op {j}: {op}"); - } - cases += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(cases, 320); -} diff --git a/crates/engine/tests/element_reference.rs b/crates/engine/tests/element_reference.rs deleted file mode 100644 index 1dffab7..0000000 --- a/crates/engine/tests/element_reference.rs +++ /dev/null @@ -1,396 +0,0 @@ -use arkguard_engine::{ - battle::{ - blocking, - buffs::{self, Runtime, Spec}, - element::{self, Element, Phase}, - grid::Rect, - health::{self, Side, Unit, World}, - hit::{self, AttackType}, - settlement, - sp::{Bank, Kind}, - stats::{Base, Buff, UnitStats}, - status, - }, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -fn kind(k: arkguard_engine::battle::damage::DamageType) -> &'static str { - use arkguard_engine::battle::damage::DamageType::*; - match k { - Physical => "phys", - Arts => "arts", - True => "true", - Elemental => "elemental", - } -} -struct Host { - cfg: Value, - trace: Vec, - rng: Rng, - bank: Option, -} -impl health::Hooks for Host { - fn kill(&mut self, id: u64, _: Option, w: &mut World) -> Result<(), String> { - let u = w.unit_mut(id)?; - u.stats.hp = 0.; - u.stats.alive = false; - u.deployed = false; - self.trace.push(json!(["kill", id])); - Ok(()) - } -} -impl settlement::Hooks for Host {} -impl blocking::Hooks for Host { - fn blocked(&mut self, _: u64, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl buffs::Hooks for Host { - fn status(&mut self, u: u64, key: &str, on: bool) -> Result<(), String> { - self.trace - .push(json!(["status", u, key, if on { 1 } else { 0 }])); - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - fn burst_damage( - &mut self, - r: &mut hit::Request, - runtime: &mut Runtime, - w: &mut World, - ) -> Result { - let attack = match r.attack_type { - AttackType::Buff => "BUFF", - AttackType::Normal => "NORMAL", - _ => unreachable!(), - }; - self.trace.push(json!([ - "hpHit", - r.hit.source, - r.hit.credit, - bits(r.damage.amount), - kind(r.hit.damage_type), - r.hit.no_sp, - attack, - r.tags, - r.element.map(|e| e.name()) - ])); - let mut rng = self.rng.clone(); - let result = settlement::resolve(w, runtime, &mut rng, self, r); - self.rng = rng; - result - } - fn burst_sp_loss(&mut self, _: u64, amount: f64, w: &mut World) -> Result<(), String> { - element::drain_sp(w, self.bank.as_mut(), amount) - } -} -impl status::Hooks for Host { - fn has_before_status(&self) -> bool { - false - } - fn before_status( - &mut self, - _: &mut status::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - fn has_status_applied(&self) -> bool { - false - } - fn status_applied( - &mut self, - _: &status::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } -} -impl element::Hooks for Host { - fn battle_rect(&self) -> Rect { - Rect::FULL - } - fn element_enabled(&self, p: Phase) -> bool { - p != Phase::Hit || self.cfg["hooks"] == true - } - fn element_event( - &mut self, - p: Phase, - g: &mut element::Request, - amount: f64, - added: f64, - r: &mut Runtime, - w: &mut World, - ) -> Result<(), String> { - let i = self.cfg["i"].as_u64().unwrap(); - match p { - Phase::Hit => { - self.trace.push(json!([ - "elementHit", - bits(g.damage.damage.amount), - bits(g.damage.damage.mul) - ])); - if i % 19 == 0 { - g.damage.cancelled = true; - } - if i % 23 == 0 { - g.damage.damage.amount *= 1.5; - } - if i % 29 == 0 { - g.convert_to_hp = Some(arkguard_engine::battle::damage::DamageType::Arts); - } - } - Phase::ModifierApplied => { - self.trace - .push(json!(["modifierApplied", bits(amount), bits(added)])) - } - Phase::Damaged => self.trace.push(json!(["damaged", bits(amount)])), - Phase::Applied => self.trace.push(json!(["elementApplied", bits(amount)])), - Phase::Burst => { - self.trace.push(json!([ - "elementBurst", - g.damage.element.unwrap().name(), - element::locked(w, 1)? - ])); - let got = element::apply( - w, - self, - r, - &mut element::Request::new( - Some(2), - Some(2), - 1, - g.damage.element.unwrap(), - 1000.0, - ), - )?; - self.trace.push(json!(["nested", bits(got)])); - if i % 41 == 0 { - let u = w.unit_mut(1)?; - u.stats.alive = false; - u.stats.hp = 0.; - u.deployed = false; - } - } - } - Ok(()) - } - fn element_number(&mut self, target: u64, amount: f64, e: Element) -> Result<(), String> { - self.trace.push(json!([ - "dmg", - target, - (amount + 0.5).floor() as u64, - e.name() - ])); - Ok(()) - } - fn burst_visual(&mut self, _: u64, _: Element, _: &World) -> Result<(), String> { - self.trace.push(json!(["burstVisual"])); - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; gauge and burst/HP timelines"] -fn elemental_timelines_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/element.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let c = &v["cfg"]; - let i = c["i"].as_u64().unwrap(); - let mut w = World::new(2, 1, 1).unwrap(); - let side = if c["side"] == "ally" { - Side::Ally - } else { - Side::Enemy - }; - let mut base = Base::default(); - for (k, n) in [ - ("maxHp", if i % 17 == 0 { 300.0 } else { 30000.0 }), - ("atk", 100.0), - ("def", 100.0), - ("res", 30.0), - ] { - base.0.insert(k.into(), n); - } - let mut u = Unit::new(UnitStats::new(base), side); - u.deployed = true; - u.enemy_entity = c["entity"] == true; - u.element_leader = c["leader"] == true; - u.ep_resistance = c["ep"].as_f64().unwrap(); - u.element_buildup[0] = 120.; - u.element_buildup[1] = 120.; - w.insert_unit(1, u).unwrap(); - let mut base = Base::default(); - base.0.insert("atk".into(), 999.0); - let mut u = Unit::new( - UnitStats::new(base), - if side == Side::Ally { - Side::Enemy - } else { - Side::Ally - }, - ); - u.deployed = true; - w.insert_unit(2, u).unwrap(); - let mut bank = Bank::new( - 1, - match c["skill"].as_str().unwrap() { - "passive" => Kind::Passive, - "instant" => Kind::Instant, - _ => Kind::Duration, - }, - 3.0, - 3, - 8, - ) - .unwrap(); - bank.set_total(&mut w, 8.0).unwrap(); - bank.active = c["active"] == true; - bank.no_skill = c["noSkill"] == true; - let mut h = Host { - cfg: c.clone(), - trace: vec![], - rng: Rng::new(42), - bank: Some(bank), - }; - let mut r = Runtime::new(64, 256, 64).unwrap(); - r.add( - &mut w, - &mut h, - 2, - Spec { - buff: Buff { - key: Some("source".into()), - mods: [("dmgDealtMul".into(), 2.0)].into_iter().collect(), - ..Default::default() - }, - mods_present: true, - ..Default::default() - }, - ) - .unwrap(); - r.add( - &mut w, - &mut h, - 1, - Spec { - buff: Buff { - key: Some("baseline".into()), - mods: [ - ("elemTakenMul".into(), if i % 3 == 0 { 1.3 } else { 1.0 }), - ("dodgePhys".into(), if i % 5 == 0 { 0.3 } else { 0.0 }), - ("dodgeArts".into(), if i % 7 == 0 { 0.3 } else { 0.0 }), - ] - .into_iter() - .collect(), - flags: ["sleep", "invulnerable"] - .into_iter() - .filter(|k| { - if *k == "sleep" { - c["sleep"] == true - } else { - c["invul"] == true - } - }) - .map(str::to_string) - .collect(), - ..Default::default() - }, - mods_present: true, - flags_present: true, - ..Default::default() - }, - ) - .unwrap(); - let mut states = vec![]; - for op in v["ops"].as_array().unwrap() { - let result = match op["op"].as_str().unwrap() { - "hit" => { - let mut req = element::Request::new( - Some(2), - Some(2), - 1, - Element::parse(op["element"].as_str().unwrap()).unwrap(), - op["amount"].as_f64().unwrap(), - ); - req.damage.damage.mul = 1.1; - req.damage.ignore_sleep = i % 3 == 0; - Some(element::apply(&mut w, &mut h, &mut r, &mut req).unwrap()) - } - "heal" => Some( - element::heal( - &mut w, - 1, - op["amount"].as_f64().unwrap(), - op["element"].as_str().and_then(Element::parse), - ) - .unwrap(), - ), - "remove" => Some( - r.remove(&mut w, &mut h, 1, op["key"].as_str().unwrap()) - .unwrap() as f64, - ), - _ => { - let dt = op["dt"].as_f64().unwrap(); - w.time += dt; - r.tick(&mut w, &mut h, &[1, 2], dt).unwrap(); - None - } - }; - let locked = element::locked(&mut w, 1).unwrap(); - let time = w.time; - let view = element::view(&mut w, 1, time).unwrap().map(|v| { - json!([ - v.element.name(), - bits(v.fill), - bits(v.cooldown_end), - bits(v.cooldown) - ]) - }); - let sp = h.bank.as_ref().unwrap().total(&mut w).unwrap(); - let u = w.unit_mut(1).unwrap(); - let s = u.stats.stats().unwrap(); - let (atk, def, res) = (s.n("atk"), s.n("def"), s.n("res")); - states.push(json!({"result":result.map(bits),"hp":bits(u.stats.hp),"alive":u.stats.alive,"gauges":u.element_buildup.map(bits),"locked":locked,"view":view,"atk":bits(atk),"def":bits(def),"res":bits(res),"sp":bits(sp),"elemStat":bits(w.unit(2).unwrap().element_damage_dealt),"dmgStat":bits(w.unit(2).unwrap().damage_dealt),"rng":h.rng.state(),"buffs":w.unit(1).unwrap().stats.buffs().iter().map(|b|json!({"key":b.key,"stacks":b.stacks,"left":bits(b.runtime.time_left),"duration":bits(b.runtime.duration),"acc":bits(b.runtime.accumulator)})).collect::>()})); - } - for (j, (a, b)) in states - .iter() - .zip(v["states"].as_array().unwrap()) - .enumerate() - { - assert_eq!(a, b, "case {c} operation {j}"); - } - assert_eq!(json!(h.trace), v["trace"], "trace {c}"); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 320); -} diff --git a/crates/engine/tests/enemy_content_reference.rs b/crates/engine/tests/enemy_content_reference.rs deleted file mode 100644 index 218a51d..0000000 --- a/crates/engine/tests/enemy_content_reference.rs +++ /dev/null @@ -1,431 +0,0 @@ -use arkguard_engine::{ - battle::{ - blocking, buffs, - content::enemies::{Kit, Runtime}, - damage::{Damage, DamageType, Penetration}, - deploy::{self, Deployment, Options}, - grid::{Grid, Rect}, - health::{self, Hit, Id, Side, Unit, World}, - hit, settlement, spawns, - stats::{Base, Buff, UnitStats}, - status, - targeting::{self, Profile, Queries}, - waves::Template, - }, - data::Catalog, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} - -#[test] -fn unsupported_kits_and_invalid_capacity_never_become_plain_enemies() { - assert!(Kit::compile("enemy_unknown", &json!({}), &Value::Null, None).is_err()); - // A content alias selects the implementation; restoration belongs to the - // actual enemy's identity, as ab.key does in the original implementation. - let kit = Kit::compile( - "enemy_custom", - &json!({"effectRef":"enemy_1283_sgkill"}), - &Value::Null, - None, - ) - .unwrap(); - assert!(matches!(kit, Kit::Stealth { restore: 3. })); - let mut w = World::new(2, 1, 1).unwrap(); - for id in 1..=2 { - w.insert_unit(id, Unit::new(UnitStats::new(Base::default()), Side::Enemy)) - .unwrap(); - } - let mut r = buffs::Runtime::new(4, 4, 8).unwrap(); - let mut h = Host::default(); - let mut content = Runtime::new(1).unwrap(); - content - .spawn( - &mut w, - &mut r, - &mut h, - 1, - Kit::Stealth { restore: 3. }, - &Value::Null, - ) - .unwrap(); - assert!(content - .spawn( - &mut w, - &mut r, - &mut h, - 2, - Kit::Times { arts_only: false }, - &Value::Null - ) - .is_err()); - assert!(content.faulted()); - assert!(r.faulted()); - assert_eq!(content.retained(), 1); - assert!(w.unit(2).unwrap().stats.buffs().is_empty()); - assert!(content.tick(&mut w, &mut r, &mut h, &[1], 0.1).is_err()); -} - -#[test] -fn removed_content_releases_capacity_and_callback_errors_fault_the_owner() { - let mut w = World::new(2, 1, 1).unwrap(); - for id in 1..=2 { - w.insert_unit(id, Unit::new(UnitStats::new(Base::default()), Side::Enemy)) - .unwrap(); - } - let mut r = buffs::Runtime::new(4, 4, 8).unwrap(); - let mut h = Host::default(); - let mut content = Runtime::new(1).unwrap(); - content - .spawn(&mut w, &mut r, &mut h, 1, Kit::Plain, &Value::Null) - .unwrap(); - content.remove(1); - assert_eq!(content.retained(), 0); - content - .spawn( - &mut w, - &mut r, - &mut h, - 2, - Kit::Refraction { - res: 70., - hp_pct: 1., - }, - &Value::Null, - ) - .unwrap(); - content.tick(&mut w, &mut r, &mut h, &[2], 0.1).unwrap(); - let id = w.unit(2).unwrap().stats.buffs()[0].runtime.id(); - r.edit(&mut w, 2, id, |b| b.runtime.on_remove = Some(999)) - .unwrap(); - let mut b = Buff::default(); - b.key = Some("silence".into()); - b.flags.insert("silence".into()); - r.add( - &mut w, - &mut h, - 2, - buffs::Spec { - buff: b, - ..Default::default() - }, - ) - .unwrap(); - assert!(content.tick(&mut w, &mut r, &mut h, &[2], 0.1).is_err()); - assert!(content.faulted()); - assert!(content.tick(&mut w, &mut r, &mut h, &[2], 0.1).is_err()); -} -#[derive(Default)] -struct Host { - ended: Vec, -} -struct SpawnHost<'a> { - data: &'a Catalog, - content: &'a mut Runtime, - buffs: &'a mut buffs::Runtime, - host: &'a mut Host, -} -impl spawns::Hooks for SpawnHost<'_> { - fn spawned(&mut self, id: Id, w: &mut World, r: &mut spawns::Runtime) -> Result<(), String> { - r.install_content(self.data, w, self.buffs, self.content, self.host, id) - } - fn release(&mut self, id: Id, _: &mut World) -> Result<(), String> { - self.content.remove(id); - Ok(()) - } -} -impl health::Hooks for Host { - fn kill(&mut self, id: Id, _: Option, w: &mut World) -> Result<(), String> { - let u = w.unit_mut(id)?; - u.stats.hp = 0.; - u.stats.alive = false; - u.deployed = false; - u.removed = true; - Ok(()) - } -} -impl buffs::Hooks for Host { - fn status(&mut self, _: Id, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Unexpected content callback".into()) - } -} -impl settlement::Hooks for Host {} -impl blocking::Hooks for Host { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, id: Id, _: &mut World) -> Result<(), String> { - self.ended.push(id); - Ok(()) - } -} -impl deploy::Hooks for Host { - fn initialize( - &mut self, - _: Id, - _: Options, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn event( - &mut self, - _: deploy::Event, - _: Id, - _: Option, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn remove_temporary_effects(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl status::Hooks for Host { - fn has_before_status(&self) -> bool { - false - } - fn before_status( - &mut self, - _: &mut status::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Unexpected before-status hook".into()) - } - fn has_status_applied(&self) -> bool { - false - } - fn status_applied( - &mut self, - _: &status::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Unexpected status-applied hook".into()) - } -} -impl Queries for Host { - fn skip_enemy(&mut self, _: Option, _: Id, _: &mut World) -> Result { - Ok(false) - } - fn remaining_distance(&mut self, _: Id, _: &mut World) -> Result { - Err("No priority selector".into()) - } - fn body_distance(&mut self, _: Id, _: [f64; 2], _: &mut World) -> Result { - Err("No body query".into()) - } -} -fn view(w: &mut World, h: &mut Host, rng: &Rng) -> Value { - let stealth = targeting::enemy_stealthed(w, 1).unwrap(); - let selectable = targeting::can_target_enemy( - w, - h, - Some(10000), - 1, - Profile { - can_hit_fly: true, - ..Profile::default() - }, - ) - .unwrap(); - let u = w.unit_mut(1).unwrap(); - let s = u.stats.stats().unwrap().clone(); - let stats: serde_json::Map<_, _> = ["maxHp", "res", "atk"] - .map(|k| (k.into(), json!(bits(s.n(k))))) - .into_iter() - .collect(); - let buffs:Vec<_>=u.stats.buffs().iter().map(|b|{let mods:serde_json::Map<_,_>=b.mods.iter().map(|(k,n)|(k.clone(),json!(bits(*n)))).collect();json!({"key":b.key,"left":bits(b.runtime.time_left),"persist":b.runtime.persist,"visible":b.runtime.visible,"stacks":b.stacks,"flags":b.flags,"mods":mods,"restore":if b.flags.contains("stealth"){Some(bits(b.runtime.stealth_restore.unwrap_or(3.)))}else{None}})}).collect(); - json!({"hp":bits(u.stats.hp),"alive":u.stats.alive,"stealth":stealth,"selectable":selectable,"blocked":u.blocked_by(),"stats":stats,"flags":s.flags,"buffs":buffs,"rng":rng.state()}) -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; original supported enemy kits, statuses and damage"] -fn original_enemy_content_matches() { - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap(); - let data = Catalog::load(&Path::new(&root).join("data"), 64 << 20).unwrap(); - let script = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/enemy-content.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(&root) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut cases = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let key = v["key"].as_str().unwrap(); - let mut w = World::new(2, 1, 1).unwrap(); - let mut h = Host::default(); - let g = Grid::new(&json!({"rows":vec!["r".repeat(21);19]}), Rect::FULL).unwrap(); - let mut r = buffs::Runtime::new(32, 64, 32).unwrap(); - let mut content = Runtime::new(2).unwrap(); - let template = Template::parse( - &json!({"spawns":[],"overrides":{key:v["overrides"]}}), - &Value::Null, - &Value::Null, - 2, - 32, - ) - .unwrap(); - let mut spawns = spawns::Runtime::new(&data, template, &g, json!("p"), 2, 32, 32).unwrap(); - let id = spawns - .spawn( - &mut w, - &g, - &mut SpawnHost { - data: &data, - content: &mut content, - buffs: &mut r, - host: &mut h, - }, - key, - &json!({"pos":[10,5.2],"mods":v["mods"],"tag":v["tag"]}), - ) - .unwrap(); - assert_eq!(id, 1); - let mut b = Base::default(); - b.0.insert("maxHp".into(), 1000.); - b.0.insert("atk".into(), 120.); - b.0.insert("blockCnt".into(), 3.); - let mut a = Unit::new(UnitStats::new(b), Side::Ally); - a.ground = true; - a.stats.alive = false; - a.deployment.home = [10, 5]; - a.deployment.kind = deploy::Kind::Operator; - w.insert_unit(10000, a).unwrap(); - let mut d = Deployment::new(Rect::FULL, 2, 1, 99.).unwrap(); - d.register(10000, &w).unwrap(); - d.deploy(&mut w, &mut h, 10000, Options::default()).unwrap(); - let mut rng = Rng::new(42); - assert_eq!(view(&mut w, &mut h, &rng), v["states"][0], "spawn {key}"); - for (j, op) in v["ops"].as_array().unwrap().iter().enumerate() { - w.time = op["time"].as_f64().unwrap(); - if op["half"] == true { - w.unit_mut(1).unwrap().stats.hp *= 0.7; - } - if let Some(key) = op["status"].as_str() { - status::apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - 1, - key, - status::Options { - duration: 0.4, - ..Default::default() - }, - ) - .unwrap(); - } - if op["block"] == true { - blocking::check(&mut w, &d, &g, &mut h, 1).unwrap(); - } - if op["unblock"] == true { - blocking::unblock(&mut w, &mut h, 1).unwrap(); - } - for id in std::mem::take(&mut h.ended) { - blocking::restore_stealth(&mut w, &mut r, &mut h, id).unwrap(); - } - if op["extra"] == true { - let mut b = Buff::default(); - b.key = Some("otherStealth".into()); - b.flags.insert("stealth".into()); - b.runtime.duration = 1.5; - b.runtime.stealth_restore = Some(0.3); - r.add( - &mut w, - &mut h, - 1, - buffs::Spec { - buff: b, - flags_present: true, - ..Default::default() - }, - ) - .unwrap(); - } - let kind = match op["hit"].as_str() { - Some("arts") => DamageType::Arts, - Some("true") => DamageType::True, - Some("elemental") => DamageType::Elemental, - _ => DamageType::Physical, - }; - let hit = Hit { - source: Some(10000), - credit: Some(10000), - target: 1, - damage_type: kind, - no_sp: true, - silent: false, - hp_loss: false, - on_applied: false, - }; - if op.get("hit").is_some() { - let mut req = hit::Request::new( - hit, - Damage { - amount: 5.7, - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - ); - req.is_attack = true; - settlement::resolve(&mut w, &mut r, &mut rng, &mut h, &mut req).unwrap(); - } - if op["loss"] == true { - health::lose_hp( - &mut w, - &mut h, - Hit { - source: None, - credit: None, - damage_type: DamageType::True, - ..hit - }, - 0.3, - Penetration::default(), - false, - ) - .unwrap(); - } - w.unit_mut(1).unwrap().enemy.carrier = if op["carrier"] == true { - Some(10000) - } else { - None - }; - r.tick(&mut w, &mut h, &[1, 10000], 0.1).unwrap(); - content.tick(&mut w, &mut r, &mut h, &[1], 0.1).unwrap(); - assert_eq!( - view(&mut w, &mut h, &rng), - v["states"][j + 1], - "{key} step {j} {op}" - ); - } - cases += 1; - } - assert!(child.wait().unwrap().success()); - assert!(cases >= 100); - eprintln!("{cases} original-kit timelines"); -} diff --git a/crates/engine/tests/enemy_element_reference.rs b/crates/engine/tests/enemy_element_reference.rs deleted file mode 100644 index bb0f563..0000000 --- a/crates/engine/tests/enemy_element_reference.rs +++ /dev/null @@ -1,449 +0,0 @@ -use arkguard_engine::{ - battle::{ - blocking, buffs, - content::enemies::{Kit, Runtime}, - damage::{Damage, DamageType, Penetration}, - definitions::Enemy, - element::{self, Element}, - grid::Rect, - health::{self, Hit, Id, Side, Unit, World}, - hit, settlement, - stats::{Base, Buff, UnitStats}, - status, - }, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(n: f64) -> String { - format!("{:016x}", n.to_bits()) -} -fn kind(k: DamageType) -> &'static str { - match k { - DamageType::Physical => "phys", - DamageType::Arts => "arts", - DamageType::True => "true", - DamageType::Elemental => "elemental", - } -} -struct Host { - content: Runtime, - rng: Rng, - trace: Vec, - fail: bool, -} -impl health::Hooks for Host { - fn kill(&mut self, id: Id, _: Option, w: &mut World) -> Result<(), String> { - let u = w.unit_mut(id)?; - u.stats.hp = 0.; - u.stats.alive = false; - u.deployed = false; - if u.side == Side::Ally { - let kept = u - .stats - .buffs() - .iter() - .filter(|b| b.runtime.persist) - .cloned() - .collect(); - u.stats.set_buffs(kept); - } - Ok(()) - } -} -impl settlement::Hooks for Host { - fn damage_health_event( - &mut self, - e: &mut health::Event, - request: &mut hit::Request, - r: &mut buffs::Runtime, - w: &mut World, - rng: &mut Rng, - ) -> Result<(), String> { - if e.stage == health::Stage::Damaged { - if self.fail { - return Err("Enemy damage callback failed".into()); - } - self.trace.push(json!([ - e.source, - e.target, - request.is_attack, - request.attack_id, - kind(request.hit.damage_type), - bits(e.amount), - w.unit(2)?.stats.alive, - bits(w.unit(2)?.stats.hp) - ])); - if let Some(mut req) = self.content.damaged(w, request)? { - self.rng = rng.clone(); - let result = element::apply(w, self, r, &mut req); - *rng = self.rng.clone(); - result?; - } - } - Ok(()) - } -} -impl buffs::Hooks for Host { - fn status(&mut self, _: Id, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Unexpected callback".into()) - } - fn burst_damage( - &mut self, - request: &mut hit::Request, - r: &mut buffs::Runtime, - w: &mut World, - ) -> Result { - let mut rng = self.rng.clone(); - let result = settlement::resolve(w, r, &mut rng, self, request); - self.rng = rng; - result - } - fn burst_sp_loss(&mut self, _: Id, amount: f64, w: &mut World) -> Result<(), String> { - element::drain_sp(w, None, amount) - } -} -impl blocking::Hooks for Host { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl status::Hooks for Host { - fn has_before_status(&self) -> bool { - false - } - fn before_status( - &mut self, - _: &mut status::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Unexpected status hook".into()) - } - fn has_status_applied(&self) -> bool { - false - } - fn status_applied( - &mut self, - _: &status::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Unexpected status hook".into()) - } -} -impl element::Hooks for Host { - fn battle_rect(&self) -> Rect { - Rect::NORMAL - } - fn element_enabled(&self, p: element::Phase) -> bool { - p == element::Phase::Damaged - } - fn element_event( - &mut self, - _: element::Phase, - req: &mut element::Request, - amount: f64, - _: f64, - _: &mut buffs::Runtime, - w: &mut World, - ) -> Result<(), String> { - self.trace.push(json!([ - req.damage.hit.source, - req.damage.hit.target, - req.damage.is_attack, - req.damage.attack_id, - "element", - bits(amount), - w.unit(2)?.stats.alive, - bits(w.unit(2)?.stats.hp) - ])); - Ok(()) - } - fn element_number(&mut self, _: Id, _: f64, _: Element) -> Result<(), String> { - Ok(()) - } - fn burst_visual(&mut self, _: Id, _: Element, _: &World) -> Result<(), String> { - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; actual elemental enemy procs and nested bursts"] -fn elemental_attack_procs_match_original_damage_callbacks() { - let script = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/enemy-element.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut cases = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let key = v["key"].as_str().unwrap(); - let mut w = World::new(2, 1, 1).unwrap(); - let def = Enemy::parse(key, &v["raw"]).unwrap(); - w.insert_unit(1, def.unit(&Value::Null, [10., 5.], 0.).unwrap()) - .unwrap(); - let mut base = Base::default(); - for (k, n) in [("maxHp", 100000.), ("atk", 0.), ("def", 70.), ("res", 20.)] { - base.0.insert(k.into(), n); - } - let mut a = Unit::new(UnitStats::new(base), Side::Ally); - a.deployed = true; - a.position = [10., 5.]; - w.insert_unit(2, a).unwrap(); - let mut r = buffs::Runtime::new(32, 128, 64).unwrap(); - let mut content = Runtime::new(2).unwrap(); - let mut h = Host { - content: Runtime::new(2).unwrap(), - rng: Rng::new(42), - trace: vec![], - fail: false, - }; - content - .spawn( - &mut w, - &mut r, - &mut h, - 1, - Kit::compile(key, &v["raw"], &v["overrides"], None).unwrap(), - &Value::Null, - ) - .unwrap(); - h.content = content; - for (j, op) in v["ops"].as_array().unwrap().iter().enumerate() { - w.time = op["time"].as_f64().unwrap(); - if let Some(atk) = op["atk"].as_f64() { - w.unit_mut(1).unwrap().stats.edit_base(|b| { - b.0.insert("atk".into(), atk); - }); - } - if op["silence"] == true { - status::apply( - &mut w, - &mut h, - &mut r, - Rect::NORMAL, - 1, - "silence", - status::Options { - duration: 1., - ..Default::default() - }, - ) - .unwrap(); - } - for (key, flag, duration) in [("guard", "invulnerable", 0.8), ("dodge", "", 3.)] { - if op[key] == true { - let mut b = Buff::default(); - b.key = Some(key.into()); - b.runtime.duration = duration; - if key == "dodge" { - b.mods.insert("dodgePhys".into(), 0.3); - b.mods.insert("dodgeArts".into(), 0.4); - } else { - b.flags.insert(flag.into()); - } - r.add( - &mut w, - &mut h, - 2, - buffs::Spec { - buff: b, - ..Default::default() - }, - ) - .unwrap(); - } - } - if op["deathTarget"] == true { - w.unit_mut(2).unwrap().stats.hp = 1.; - } - if op["sourceDead"] == true { - let u = w.unit_mut(1).unwrap(); - u.stats.alive = false; - u.deployed = false; - } - let k = match op["kind"].as_str().unwrap() { - "arts" => DamageType::Arts, - "true" => DamageType::True, - "elemental" => DamageType::Elemental, - _ => DamageType::Physical, - }; - for _ in 0..op["multi"].as_u64().unwrap() { - let hit = Hit { - source: Some(1), - credit: Some(1), - target: 2, - damage_type: k, - no_sp: true, - silent: false, - hp_loss: false, - on_applied: false, - }; - let mut req = hit::Request::new( - hit, - Damage { - amount: op["amount"].as_f64().unwrap(), - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - ); - req.is_attack = op["attack"] == true; - req.attack_id = op["attackId"].as_u64(); - req.is_projectile = true; - let mut rng = h.rng.clone(); - settlement::resolve(&mut w, &mut r, &mut rng, &mut h, &mut req).unwrap(); - h.rng = rng; - } - r.tick(&mut w, &mut h, &[1, 2], 0.1).unwrap(); - let s = w.unit_mut(2).unwrap().stats.stats().unwrap().clone(); - let a = w.unit(2).unwrap(); - let actual = json!({"hp":bits(a.stats.hp),"alive":a.stats.alive,"gauges":a.element_buildup.map(bits),"flags":s.flags,"res":bits(s.n("res")),"def":bits(s.n("def")),"rng":h.rng.state(),"sourceDamage":bits(w.unit(1).unwrap().damage_dealt),"taken":bits(a.damage_taken),"buffs":a.stats.buffs().iter().map(|b|json!({"key":b.key,"left":bits(b.runtime.time_left)})).collect::>()}); - assert_eq!(actual, v["states"][j], "{key} case {cases} step {j} {op}"); - } - let expected = v["trace"].as_array().unwrap(); - assert_eq!( - h.trace.len(), - expected.len(), - "trace length {key} case {cases}" - ); - for (i, (a, b)) in h.trace.iter().zip(expected).enumerate() { - assert_eq!(a, b, "metadata {key} case {cases} event {i}"); - } - cases += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(cases, 42); -} - -#[test] -fn damage_callback_failure_preserves_real_state_and_rejects_continuation() { - let mut w = World::new(2, 1, 1).unwrap(); - for (id, side) in [(1, Side::Enemy), (2, Side::Ally)] { - let mut base = Base::default(); - base.0.insert("maxHp".into(), 100.); - let mut u = Unit::new(UnitStats::new(base), side); - u.deployed = true; - w.insert_unit(id, u).unwrap(); - } - let mut h = Host { - content: Runtime::new(2).unwrap(), - rng: Rng::new(42), - trace: vec![], - fail: true, - }; - let mut r = buffs::Runtime::new(4, 8, 8).unwrap(); - let mut rng = Rng::new(42); - let hit = Hit { - source: Some(1), - credit: Some(1), - target: 2, - damage_type: DamageType::True, - no_sp: true, - silent: false, - hp_loss: false, - on_applied: false, - }; - let mut req = hit::Request::new( - hit, - Damage { - amount: 10., - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - ); - req.attack_id = Some(7); - assert!(settlement::resolve(&mut w, &mut r, &mut rng, &mut h, &mut req).is_err()); - assert!(r.faulted()); - assert_eq!(w.unit(2).unwrap().stats.hp, 90.); - assert_eq!(req.attack_id, Some(7)); - assert!(settlement::resolve(&mut w, &mut r, &mut rng, &mut h, &mut req).is_err()); - assert_eq!(w.unit(2).unwrap().stats.hp, 90.); -} - -#[test] -fn enemy_element_rider_does_not_trigger_on_friendly_fire() { - let mut w = World::new(3, 1, 1).unwrap(); - for (id, side) in [(1, Side::Enemy), (2, Side::Enemy), (3, Side::Ally)] { - let mut base = Base::default(); - base.0.insert("atk".into(), 100.); - let mut u = Unit::new(UnitStats::new(base), side); - u.deployed = true; - w.insert_unit(id, u).unwrap(); - } - let mut content = Runtime::new(3).unwrap(); - let mut r = buffs::Runtime::new(4, 8, 8).unwrap(); - let mut host = Host { - content: Runtime::new(3).unwrap(), - rng: Rng::new(42), - trace: vec![], - fail: false, - }; - content - .spawn( - &mut w, - &mut r, - &mut host, - 1, - Kit::Element { - kind: Element::Burn, - ratio: 0.5, - }, - &Value::Null, - ) - .unwrap(); - let hit = Hit { - source: Some(1), - credit: Some(1), - target: 2, - damage_type: DamageType::Physical, - no_sp: false, - silent: false, - hp_loss: false, - on_applied: false, - }; - let mut req = hit::Request::new( - hit, - Damage { - amount: 0., - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - ); - req.is_attack = true; - assert!(content.damaged(&mut w, &req).unwrap().is_none()); - req.hit.target = 3; - assert_eq!( - content - .damaged(&mut w, &req) - .unwrap() - .unwrap() - .damage - .damage - .amount, - 50. - ); -} diff --git a/crates/engine/tests/enemy_reference.rs b/crates/engine/tests/enemy_reference.rs deleted file mode 100644 index 4360690..0000000 --- a/crates/engine/tests/enemy_reference.rs +++ /dev/null @@ -1,774 +0,0 @@ -use arkguard_engine::{ - battle::{ - blocking, - buffs::{self, Runtime}, - damage::DamageType, - deploy::{self, Deployment, Kind, Options}, - direction::Direction, - displacement::{self, Origin, Push}, - enemy::{self, Animation, Context, Delivery, Event, Mode, Profile}, - events, - grid::{Grid, Rect}, - health::{self, Side, Unit, World}, - motion, - projectiles::{self, Launch, Projectile, System}, - settlement, - spatial::{self, RadiusRule}, - stats::{Base, UnitStats}, - status, - targeting::{self, Queries}, - }, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -fn dmg(k: DamageType) -> &'static str { - match k { - DamageType::Physical => "phys", - DamageType::Arts => "arts", - DamageType::True => "true", - DamageType::Elemental => "elemental", - } -} -struct Host { - cfg: Value, - tick: u32, - events: Option>, - trace: Vec, - deployment: Option, - flights: Option>, -} -impl health::Hooks for Host { - fn kill(&mut self, id: u64, _: Option, w: &mut World) -> Result<(), String> { - let u = w.unit_mut(id)?; - u.stats.hp = 0.; - u.stats.alive = false; - u.deployed = false; - self.trace.push(json!(["kill", id])); - Ok(()) - } -} -impl buffs::Hooks for Host { - fn status(&mut self, _: u64, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } -} -impl settlement::Hooks for Host { - fn phase_enabled(&self, p: arkguard_engine::battle::hit::Phase) -> bool { - p == arkguard_engine::battle::hit::Phase::Hit - } - fn damage_phase( - &mut self, - _: arkguard_engine::battle::hit::Phase, - r: &mut arkguard_engine::battle::hit::Request, - _: &mut f64, - _: &mut Runtime, - _: &mut World, - _: &mut Rng, - ) -> Result<(), String> { - self.trace.push(json!([ - "hit", - r.hit.source.unwrap(), - r.hit.target, - bits(r.damage.amount), - dmg(r.hit.damage_type), - r.attack_id.unwrap(), - r.is_projectile - ])); - Ok(()) - } -} -impl blocking::Hooks for Host { - fn blocked(&mut self, _: u64, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl deploy::Hooks for Host { - fn initialize( - &mut self, - _: u64, - _: Options, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn event( - &mut self, - _: deploy::Event, - _: u64, - _: Option, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn remove_temporary_effects(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl status::Hooks for Host { - fn has_before_status(&self) -> bool { - false - } - fn before_status( - &mut self, - _: &mut status::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - fn has_status_applied(&self) -> bool { - false - } - fn status_applied( - &mut self, - _: &status::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } -} -impl motion::Hooks for Host { - fn check_block(&mut self, id: u64, w: &mut World, g: &mut Grid) -> Result { - let d = self.deployment.take().unwrap(); - let result = blocking::check(w, &d, g, self, id); - self.deployment = Some(d); - result - } - fn hidden(&mut self, id: u64, on: bool, w: &mut World) -> Result<(), String> { - w.unit_mut(id)?.hidden = on; - Ok(()) - } - fn cut_attack_stand(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn leak(&mut self, id: u64, w: &mut World) -> Result<(), String> { - let u = w.unit_mut(id)?; - u.stats.alive = false; - u.deployed = false; - self.trace.push(json!(["leak"])); - Ok(()) - } -} -impl Queries for Host { - fn enemy_stealthed(&mut self, _: u64, _: &mut World) -> Result { - Ok(false) - } - fn skip_enemy(&mut self, _: Option, _: u64, _: &mut World) -> Result { - Ok(false) - } - fn remaining_distance(&mut self, _: u64, _: &mut World) -> Result { - unreachable!() - } - fn body_distance(&mut self, _: u64, _: [f64; 2], _: &mut World) -> Result { - unreachable!() - } -} -impl enemy::Hooks for Host { - fn profile(&mut self, _: u64, _: &mut World) -> Result { - let c = &self.cfg; - Ok(Profile { - mode: match c["mode"].as_str().unwrap() { - "heal" => Mode::Heal, - "none" => Mode::None, - "arts" => Mode::Damage(DamageType::Arts), - "true" => Mode::Damage(DamageType::True), - _ => Mode::Damage(DamageType::Physical), - }, - melee: c["melee"] == true, - attack_moves: c["moves"] == true, - deferred: c["deferred"] == true, - shot: "shell".into(), - selection: targeting::Profile { - block_free: c["blockFree"] == true, - ..Default::default() - }, - max_targets: c["maxTargets"].as_f64().unwrap(), - atk_scale: if self.tick >= 80 { 1.5 } else { 1.2 }, - animation: c["clip"].as_object().map(|_| Animation { - duration: c["clip"]["dur"].as_f64().unwrap(), - hit: c["clip"]["hit"].as_f64(), - }), - ..Default::default() - }) - } - fn allies_in_radius( - &mut self, - id: u64, - radius: f64, - w: &mut World, - limit: usize, - ) -> Result, String> { - spatial::allies_in_radius( - w, - &[2, 3, 4], - w.unit(id)?.position, - radius, - None, - false, - limit, - ) - } - fn enemies_in_radius( - &mut self, - id: u64, - radius: f64, - w: &mut World, - limit: usize, - ) -> Result, String> { - let origin = w.unit(id)?.position; - spatial::enemies_in_radius( - w, - self, - &[1, 5], - origin, - radius, - RadiusRule::Body, - false, - limit, - ) - } - fn can_target(&mut self, _: u64, ally: u64, _: &mut World) -> Result { - Ok(self.cfg["skip"] != true || ally != 3) - } - fn enemy_event_enabled(&self, event: Event) -> bool { - self.events - .as_ref() - .map(|bus| bus.has_hook(&event)) - .unwrap_or(false) - } - fn enemy_event( - &mut self, - event: Event, - c: &mut Context, - r: &mut Runtime, - w: &mut World, - _: &mut Grid, - _: &mut Rng, - ) -> Result<(), String> { - let mut bus = self.events.take().unwrap(); - let result = bus.emit( - &event, - &mut events::Context::new(c), - &mut Handler { h: self, r, w }, - ); - self.events = Some(bus); - result - } - fn attack_visual(&mut self, source: u64, target: u64, visual: &str) -> Result<(), String> { - self.trace.push(json!(["atk", source, target, visual])); - Ok(()) - } - fn palsy_visual(&mut self, _: u64, _: &World) -> Result<(), String> { - self.trace.push(json!(["palsy"])); - Ok(()) - } - fn deliver( - &mut self, - d: Delivery, - r: &mut Runtime, - w: &mut World, - rng: &mut Rng, - ) -> Result<(), String> { - if d.projectile { - self.flights.as_mut().unwrap().add( - w, - Launch { - from: w.unit(d.source)?.position, - source: Some(d.source), - target: Some(d.target), - to: None, - speed: 10.0, - hit_dead: false, - max_age: 10.0, - on_hit: true, - visual: "enemy".into(), - speed_changeable: None, - removable: None, - payload: d, - }, - )?; - } else { - enemy::impact(w, r, rng, self, d, Some(d.target))?; - } - Ok(()) - } -} -fn callback_bus() -> events::Runtime { - let mut bus = events::Runtime::new(16, 16, 64, 256).unwrap(); - for (event, token) in [ - (Event::AttackStart, 1), - (Event::PalsyTrigger, 2), - (Event::BeforeAttack, 3), - (Event::Attack, 4), - ] { - bus.on(event, token, 0.0, Some(1), false).unwrap(); - } - bus -} -impl Host { - fn dispatch( - &mut self, - event: Event, - c: &mut Context, - r: &mut Runtime, - w: &mut World, - ) -> Result<(), String> { - match event { - Event::AttackStart => { - self.trace.push(json!(["start", c.targets])); - if self.cfg["interrupt"] == true { - let mut b = arkguard_engine::battle::stats::Buff { - key: Some("interrupt".into()), - flags: ["stun".into()].into_iter().collect(), - ..Default::default() - }; - b.runtime.duration = 0.2; - r.add( - w, - self, - 1, - buffs::Spec { - buff: b, - flags_present: true, - ..Default::default() - }, - )?; - } - } - Event::PalsyTrigger => { - self.trace.push(json!([ - "palsyTrigger", - r.get(w, 1, c.palsy.unwrap())?.stacks - ])); - c.keep = self.cfg["keep"] == true; - } - Event::BeforeAttack => { - self.trace.push(json!(["before", c.targets])); - if self.cfg["cancel"] == true { - c.targets.clear(); - } - } - Event::Attack => { - self.trace.push(json!(["attack", c.targets, c.deployments])); - if self.cfg["i"].as_u64().unwrap() % 13 == 0 { - let atk = w.unit(1)?.stats.base_number("atk"); - w.unit_mut(1)?.stats.edit_base(|b| { - b.0.insert("atk".into(), atk + 1.0); - }); - } - } - } - Ok(()) - } -} -struct Handler<'a> { - h: &'a mut Host, - r: &'a mut Runtime, - w: &'a mut World, -} -impl<'a, 'b> events::Host for Handler<'a> { - fn hook( - &mut self, - _: u64, - token: u64, - c: &mut events::Context<&'b mut Context>, - _: &mut events::Runtime, - ) -> Result<(), String> { - let event = match token { - 1 => Event::AttackStart, - 2 => Event::PalsyTrigger, - 3 => Event::BeforeAttack, - 4 => Event::Attack, - _ => return Err("Unknown enemy callback token".into()), - }; - self.h.dispatch(event, c.value, self.r, self.w) - } -} -struct Flight<'a> { - h: &'a mut Host, - r: &'a mut Runtime, - rng: &'a mut Rng, -} -impl projectiles::Hooks for Flight<'_> { - fn has_step(&self) -> bool { - false - } - fn step( - &mut self, - _: &mut Projectile, - _: &mut System, - _: &mut World, - ) -> Result { - Ok(false) - } - fn impact( - &mut self, - p: &mut Projectile, - target: Option, - _: &mut System, - w: &mut World, - ) -> Result<(), String> { - enemy::impact(w, self.r, self.rng, self.h, p.payload, target)?; - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; full enemy updates with real blocking and shots"] -fn enemy_updates_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/enemy.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let c = &v["cfg"]; - let i = c["i"].as_u64().unwrap(); - let mut w = World::new(5, 1, 1).unwrap(); - let mut g = Grid::new( - &json!({"rows":vec!["r".repeat(21);19],"legend":{}}), - Rect::FULL, - ) - .unwrap(); - let mut h = Host { - cfg: c.clone(), - tick: 0, - events: Some(callback_bus()), - trace: vec![], - deployment: Some(Deployment::new(Rect::FULL, 3, 1, 99.0).unwrap()), - flights: Some(System::new(64).unwrap()), - }; - let mut r = Runtime::new(32, 256, 64).unwrap(); - let mut rng = Rng::new(i as u32 + 1); - let mut base = Base::default(); - for (k, n) in [ - ("maxHp", 100000.0), - ("atk", 40.0), - ("def", 10.0), - ("bat", c["bat"].as_f64().unwrap()), - ("rangeRadius", 3.0), - ("moveSpeed", 1.0), - ] { - base.0.insert(k.into(), n); - } - let mut e = Unit::new(UnitStats::new(base), Side::Enemy); - e.position = [10.0, 8.0]; - e.deployed = true; - e.motion.route = Some( - motion::Route::compile( - &json!({"checkpoints":[{"type":"WAIT","time":0.1}],"end":[10,4]}), - Rect::FULL, - 32, - e.position, - ) - .unwrap(), - ); - w.insert_unit(1, e).unwrap(); - for (j, tile) in [[10, 6], [10, 7], [11, 7]].into_iter().enumerate() { - let id = j as u64 + 2; - let mut base = Base::default(); - base.0.insert( - "maxHp".into(), - if i % 19 == 0 && j == 0 { - 80.0 - } else { - 100000.0 - }, - ); - base.0.insert("blockCnt".into(), 2.0); - let mut u = Unit::new(UnitStats::new(base), Side::Ally); - u.ground = true; - u.deployment.kind = Kind::Operator; - u.deployment.home = tile; - u.deployment.tile = tile; - w.insert_unit(id, u).unwrap(); - let mut dep = h.deployment.take().unwrap(); - dep.register(id, &w).unwrap(); - dep.deploy(&mut w, &mut h, id, Options::default()).unwrap(); - h.deployment = Some(dep); - } - let mut base = Base::default(); - base.0.insert("maxHp".into(), 30000.0); - let mut u = Unit::new(UnitStats::new(base), Side::Enemy); - u.position = [10.0, 8.0]; - u.stats.hp = 500.0; - u.deployed = true; - w.insert_unit(5, u).unwrap(); - status::apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - 1, - "palsy", - status::Options { - value: Some((i % 3 + 1) as f64), - duration: 2.0, - ..Default::default() - }, - ) - .unwrap(); - let mut states = vec![]; - for tick in 0..180 { - h.tick = tick; - w.time = tick as f64 / 30.0; - if tick == 3 { - w.unit_mut(2).unwrap().position = [15.0, 15.0]; - } - if tick == 30 { - w.unit_mut(2).unwrap().position = [10.0, 6.0]; - } - for (at, id, key, duration) in [ - (20, 1, "stun", 0.2), - (45, 3, "sleep", 0.2), - (65, 1, "disarm", 0.25), - (104, 1, "levitate", 0.1), - ] { - if tick == at { - status::apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - id, - key, - status::Options { - duration, - ..Default::default() - }, - ) - .unwrap(); - } - } - if tick == 90 { - status::apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - 1, - "fear", - status::Options { - duration: 0.25, - source: Some(2), - ..Default::default() - }, - ) - .unwrap(); - } - if tick == 110 { - status::apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - 1, - "attract", - status::Options { - duration: 0.25, - point: Some([10.0, 8.0]), - ..Default::default() - }, - ) - .unwrap(); - } - if tick == 100 { - w.unit_mut(1).unwrap().motion.unbalance_until = w.time + 0.3; - } - if tick == 85 || tick == 145 { - let from = Origin::unit(&w, 2, Direction::Right).unwrap(); - displacement::push( - &mut w, - &g, - &mut h, - 1, - if tick == 85 { 1. } else { 3. }, - Push { - from: Some(from), - direction: if tick == 145 { Some([0., 1.]) } else { None }, - fixed: tick == 145, - ..Push::default() - }, - ) - .unwrap(); - } - if tick == 115 { - displacement::pull_to_front(&mut w, &g, &mut h, 1, 3, Direction::Right, 2.) - .unwrap(); - } - if tick == 80 { - let atk = w.unit(1).unwrap().stats.base_number("atk"); - w.unit_mut(1).unwrap().stats.edit_base(|b| { - b.0.insert("atk".into(), atk + 3.0); - }); - } - if tick == 130 && i % 9 == 0 { - let e = w.unit_mut(1).unwrap(); - e.stats.alive = false; - e.deployed = false; - } - let e = w.unit_mut(1).unwrap(); - e.enemy.carrier = if (70..75).contains(&tick) { - Some(5) - } else { - None - }; - e.hidden = (50..55).contains(&tick); - e.enemy.pause_until = if (60..64).contains(&tick) { - 3.0 - } else { - f64::NEG_INFINITY - }; - r.tick(&mut w, &mut h, &[1, 2, 3, 4, 5], 1.0 / 30.0) - .unwrap(); - enemy::update(&mut w, &mut g, &mut r, &mut rng, &mut h, 1, 1.0 / 30.0, 5).unwrap(); - let mut flights = h.flights.take().unwrap(); - flights - .update( - &mut w, - &mut Flight { - h: &mut h, - r: &mut r, - rng: &mut rng, - }, - 1.0 / 30.0, - ) - .unwrap(); - h.flights = Some(flights); - let e = w.unit(1).unwrap(); - states.push(json!({"hp":(1..=5).map(|id|bits(w.unit(id).unwrap().stats.hp)).collect::>(),"alive":(1..=5).map(|id|w.unit(id).unwrap().stats.alive).collect::>(),"pos":e.position.map(bits),"moving":e.moving,"cd":bits(e.cadence.cooldown),"swing":e.enemy.swing,"targets":e.enemy.targets(),"stand":bits(e.motion.attack_stand_until),"unbalance":bits(e.motion.unbalance_until),"blocked":e.blocked_by(),"attacks":e.attacks,"last":bits(e.last_attack_at),"flights":h.flights.as_ref().unwrap().list().len(),"rng":rng.state(),"palsy":e.stats.buffs().iter().find(|b|b.key.as_deref()==Some("palsy")).map(|b|b.stacks).unwrap_or(0)})); - } - for (t, (a, b)) in states - .iter() - .zip(v["states"].as_array().unwrap()) - .enumerate() - { - assert_eq!(a, b, "scenario {c} tick {t}"); - } - assert_eq!(json!(h.trace), v["trace"], "trace {c}"); - h.flights.as_mut().unwrap().clear(&mut w).unwrap(); - enemy::clear(&mut w, 1).unwrap(); - for id in 1..=5 { - assert_eq!(w.unit_pins(id).unwrap(), 0); - } - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 144); -} - -fn boundary_fixture() -> (World, Grid, Runtime, Rng, Host) { - let mut w = World::new(5, 1, 1).unwrap(); - for id in 1..=5 { - let mut base = Base::default(); - for (k, n) in [ - ("maxHp", 1000.0), - ("atk", 40.0), - ("bat", 1.0), - ("rangeRadius", 3.0), - ] { - base.0.insert(k.into(), n); - } - let mut u = Unit::new( - UnitStats::new(base), - if id == 1 || id == 5 { - Side::Enemy - } else { - Side::Ally - }, - ); - u.deployed = true; - u.position = if id == 1 || id == 5 { - [10.0, 8.0] - } else { - [10.0, 6.0] - }; - u.deployment.kind = Kind::Operator; - w.insert_unit(id, u).unwrap(); - } - let g = Grid::new( - &json!({"rows":vec!["r".repeat(21);19],"legend":{}}), - Rect::FULL, - ) - .unwrap(); - let h = Host { - cfg: json!({"i":1,"mode":"phys","melee":false,"moves":false,"deferred":false,"blockFree":false,"maxTargets":1,"clip":{"dur":1.0,"hit":0.5},"skip":false,"keep":false,"cancel":false,"interrupt":false}), - tick: 0, - events: Some(callback_bus()), - trace: vec![], - deployment: Some(Deployment::new(Rect::FULL, 3, 1, 99.0).unwrap()), - flights: Some(System::new(16).unwrap()), - }; - (w, g, Runtime::new(16, 32, 16).unwrap(), Rng::new(42), h) -} -#[test] -fn locked_targets_cannot_be_freed_and_owner_removal_releases_them() { - let (mut w, mut g, mut r, mut rng, mut h) = boundary_fixture(); - assert!(enemy::attack(&mut w, &mut g, &mut r, &mut rng, &mut h, 1, 0.0, 5).unwrap()); - assert!(w.unit(1).unwrap().enemy.swing); - for id in 2..=4 { - assert_eq!(w.unit_pins(id).unwrap(), 1); - } - let u = w.unit_mut(2).unwrap(); - u.removed = true; - u.stats.alive = false; - u.deployed = false; - assert!(w.release_removed(2).is_err()); - w.unit_mut(1).unwrap().removed = true; - w.release_removed(1).unwrap(); - for id in 2..=4 { - assert_eq!(w.unit_pins(id).unwrap(), 0); - } - w.release_removed(2).unwrap(); -} -#[test] -fn enemy_query_overflow_is_a_fault_without_truncating_or_pinning_targets() { - let (mut w, mut g, mut r, mut rng, mut h) = boundary_fixture(); - assert!(enemy::update(&mut w, &mut g, &mut r, &mut rng, &mut h, 1, 1.0 / 30.0, 1).is_err()); - assert!(r.faulted()); - assert!(!w.unit(1).unwrap().enemy.swing); - assert_eq!(w.attack_sequence(), 0); - for id in 1..=5 { - assert_eq!(w.unit_pins(id).unwrap(), 0); - } -} -#[test] -fn world_attack_identity_is_shared_and_restarts_with_a_new_world() { - let (mut w, mut g, mut r, mut rng, mut h) = boundary_fixture(); - assert_eq!(w.next_attack_id().unwrap(), 1); - enemy::attack(&mut w, &mut g, &mut r, &mut rng, &mut h, 1, 0.0, 5).unwrap(); - w.unit_mut(1).unwrap().cadence.cooldown = 0.0; - enemy::attack(&mut w, &mut g, &mut r, &mut rng, &mut h, 1, 1.0 / 30.0, 5).unwrap(); - assert_eq!(w.attack_sequence(), 2); - assert_eq!(w.next_attack_id().unwrap(), 3); - assert_eq!(World::new(1, 1, 1).unwrap().next_attack_id().unwrap(), 1); - h.flights.as_mut().unwrap().clear(&mut w).unwrap(); - enemy::clear(&mut w, 1).unwrap(); -} diff --git a/crates/engine/tests/events_reference.rs b/crates/engine/tests/events_reference.rs deleted file mode 100644 index 0aad4f2..0000000 --- a/crates/engine/tests/events_reference.rs +++ /dev/null @@ -1,223 +0,0 @@ -use arkguard_engine::battle::events::{self, Context, Handle, Runtime}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -fn num(v: &Value) -> f64 { - if v == "inf" { - f64::INFINITY - } else if v == "nan" { - f64::NAN - } else { - v.as_f64().unwrap() - } -} -struct Payload { - value: i64, - depth: u32, - added: bool, -} -struct Host { - trace: Vec, - handles: Vec, - timers: Vec, - nesting: bool, -} -impl events::Host for Host { - fn hook( - &mut self, - _: Handle, - token: u64, - c: &mut Context, - r: &mut Runtime, - ) -> Result<(), String> { - self.trace - .push(json!(["hook", token, c.value.value, c.value.depth])); - match token { - 1 => c.value.value += 1, - 2 => { - if let Some(id) = self.handles.last() { - r.off(*id); - } - } - 3 => { - if !c.value.added { - c.value.added = true; - self.handles.push(r.on("B".into(), 1, 0.0, Some(2), false)?); - } - } - 4 => { - if c.value.depth < 2 { - let mut nested = Context::new(Payload { - value: c.value.value, - depth: c.value.depth + 1, - added: false, - }); - r.emit(&"B".into(), &mut nested, self)?; - c.value.value = nested.value.value; - } - } - 5 => r.off_owner(Some(1)), - 6 => c.stop_propagation = true, - 7 => { - if c.value.depth < 1 { - let mut nested = Context::new(Payload { - value: c.value.value, - depth: c.value.depth + 1, - added: false, - }); - r.emit(&"A".into(), &mut nested, self)?; - c.value.value = nested.value.value; - } - } - 8 => { - if let Some(id) = self.handles.first() { - r.off(*id); - } - } - 9 => { - if let Some(id) = self.timers.last() { - r.cancel(*id); - } - } - _ => unreachable!(), - } - Ok(()) - } - fn timer(&mut self, id: Handle, token: u64, r: &mut Runtime) -> Result<(), String> { - let s = r.timer(id).unwrap(); - self.trace.push(json!([ - "timer", - token, - id, - s.count, - bits(s.due), - s.cancelled - ])); - match token { - 2 => { - if !self.nesting { - self.timers.push(r.after(0.0, 1, Some(2), false)?); - self.nesting = true; - let result = r.run_scheduled(self); - self.nesting = false; - result?; - } - } - 3 => r.cancel(id), - 4 => r.off_owner(Some(1)), - 5 => r.emit( - &"A".into(), - &mut Context::new(Payload { - value: 7, - depth: 0, - added: false, - }), - self, - )?, - 6 => { - let s = r.timer_mut(id).unwrap(); - s.due -= 0.05; - s.interval = 0.1; - } - 7 => r.timer_mut(id).unwrap().interval = 0.0, - _ => {} - } - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; hook and tick timer timelines"] -fn callback_timelines_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/events.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let mut r = Runtime::new(128, 256, 64, 8192).unwrap(); - let mut h = Host { - trace: vec![], - handles: vec![], - timers: vec![], - nesting: false, - }; - let mut states = vec![]; - for op in v["ops"].as_array().unwrap() { - let mut value = None; - match op["op"].as_str().unwrap() { - "on" => h.handles.push( - r.on( - op["key"].as_str().unwrap().into(), - op["token"].as_u64().unwrap(), - num(&op["priority"]), - op["owner"].as_u64(), - op["once"] == true, - ) - .unwrap(), - ), - "emit" => { - let mut c = Context::new(Payload { - value: op["value"].as_i64().unwrap(), - depth: op["depth"].as_u64().unwrap() as u32, - added: false, - }); - r.emit(&op["key"].as_str().unwrap().to_string(), &mut c, &mut h) - .unwrap(); - value = Some(json!([c.value.value, c.stop_propagation])); - } - "timer" => { - let token = op["token"].as_u64().unwrap(); - h.timers.push( - if op["every"] == true { - r.every( - num(&op["seconds"]), - token, - op["owner"].as_u64(), - op["immediate"] == true, - ) - } else { - r.after( - num(&op["seconds"]), - token, - op["owner"].as_u64(), - op["holds"] == true, - ) - } - .unwrap(), - ); - } - "run" => { - r.set_time(r.time() + op["dt"].as_f64().unwrap()).unwrap(); - r.run_scheduled(&mut h).unwrap(); - } - "off" => r.off_key( - &op["key"].as_str().unwrap().to_string(), - op["token"].as_u64(), - ), - _ => r.off_owner(op["owner"].as_u64()), - } - states.push(json!({"value":value,"hooks":[r.handles(&"A".into()),r.handles(&"B".into())],"timers":h.timers.iter().filter_map(|id|r.timer(*id).filter(|s|!s.cancelled).map(|s|json!({"id":id,"due":bits(s.due),"interval":bits(s.interval),"count":s.count,"holds":s.holds_battle}))).collect::>(),"holds":r.pending_holds()})); - } - for (j, (a, b)) in states - .iter() - .zip(v["states"].as_array().unwrap()) - .enumerate() - { - assert_eq!(a, b, "case {} step {j}", v["i"]); - } - assert_eq!(json!(h.trace), v["trace"], "trace {}", v["i"]); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 256); -} diff --git a/crates/engine/tests/field_reference.rs b/crates/engine/tests/field_reference.rs deleted file mode 100644 index 4433e04..0000000 --- a/crates/engine/tests/field_reference.rs +++ /dev/null @@ -1,802 +0,0 @@ -use arkguard_engine::{ - battle::{ - damage::{Damage, DamageType, Penetration}, - health::Hit, - hit, - runtime::{Field, Limits}, - waves::Template, - }, - data::Catalog, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, - sync::Arc, -}; -fn fixture_data() -> Arc { - // Minimal independently authored data, not bundled game data. - static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let serial = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let root = std::env::temp_dir().join(format!("arkguard-field-{}-{serial}", std::process::id())); - std::fs::create_dir(&root).unwrap(); - for key in [ - "config", - "chess", - "bonds", - "garrisons", - "items", - "bands", - "effects", - "choices", - "enemies", - "factions", - "waves", - "stages", - "bosses", - "tokens", - "backups", - ] { - let value = if key == "enemies" { - json!({"enemy_1007_slime":{"hp":100,"atk":10,"moveSpeed":1},"enemy_1005_yokai_2":{"hp":1000,"atk":10,"range":5,"applyWay":"RANGED","bat":0.1,"moveSpeed":0.1},"enemy_1200_msfjin":{"hp":30},"enemy_9011_acrefr":{"hp":100,"talents":{"bb":{"Refracting.max_hp":1,"Refracting.magic_resistance":70}}},"enemy_unported":{}}) - } else if key == "chess" { - let mut chess = json!({"chess_char_1_02_a":{"stats":{"maxHp":100,"atk":20,"def":5,"bat":1.2,"blockCnt":3,"cost":5,"respawnTime":3}, - "skill":{"skillId":"skchr_yak_2","duration":2,"initSp":1,"spCost":1,"spType":"INCREASE_WITH_TIME","trigger":{"rule":"TAKE_DAMAGE"},"bb":{"max_hp":0.3,"def":0.1,"magic_resistance":0.6}}, - "talents":[{"index":0,"bb":{"magic_resistance":7}}],"rangeGrid":[[0,0]],"position":"MELEE","profession":"TANK","subProfessionId":"protector"}}); - for (id, skill, profession, branch, bb, talent, tb) in [ - ( - "chess_char_1_03_a", - "skchr_leizi_2", - "CASTER", - "chain", - json!({"atk":0.8}), - json!({"atk_scale":1.2}), - json!({"attack@max_target":3,"attack@sluggish":0.5}), - ), - ( - "chess_char_1_11_a", - "skcom_atk_up[2]", - "SUPPORT", - "slower", - json!({"atk":0.35}), - json!({"sluggish":0.1}), - json!({"sluggish":0.8}), - ), - ( - "chess_char_1_14_a", - "skchr_greyy_2", - "CASTER", - "splashcaster", - json!({"attack_speed":50,"talent_scale":1.6}), - json!({"sluggish":0.4}), - json!({}), - ), - ] { - chess[id] = json!({"stats":{"maxHp":100,"atk":20,"bat":1.,"cost":5,"respawnTime":3}, - "skill":{"skillId":skill,"duration":2,"initSp":1,"spCost":1,"spType":"INCREASE_WITH_TIME","trigger":{"rule":"DEFAULT"},"bb":bb}, - "talents":[{"index":0,"bb":talent}],"trait":{"bb":tb},"rangeGrid":[[0,0],[0,1],[0,2]],"position":"RANGED","profession":profession,"subProfessionId":branch}); - } - chess["chess_char_1_07_a"] = json!({"stats":{"maxHp":100,"atk":20,"bat":1.,"cost":5,"respawnTime":3}, - "skill":{"skillId":"skchr_prove_1","skillType":"PASSIVE","duration":0,"initSp":0,"spCost":0,"maxChargeTime":0,"spType":"ON_DEPLOY","trigger":{"rule":"DEFAULT"},"bb":{"hp_ratio_drop":0.2,"atk_scale_up":0.12}}, - "talents":[{"index":0,"bb":{"prob":1.,"prob2":1.,"atk_scale":1.5}}],"rangeGrid":[[0,0],[0,1],[0,2]],"position":"RANGED","profession":"SNIPER","subProfessionId":"closerange"}); - chess - } else { - json!({}) - }; - std::fs::write(root.join(format!("{key}.json")), value.to_string()).unwrap(); - } - let result = Catalog::load(&root, 1 << 20); - std::fs::remove_dir_all(root).unwrap(); - Arc::new(result.unwrap()) -} -fn stage() -> Value { - json!({"rows":vec!["r".repeat(21);19]}) -} -fn template(key: &str, count: usize) -> Template { - Template::parse(&json!({"routes":[{"start":[10,10],"end":[10,0]}],"spawns":[{"enemyKey":key,"count":count,"time":0}]}),&Value::Null,&Value::Null,32,16).unwrap() -} -#[test] -fn field_budget_preserves_successor_and_owned_outputs() { - let data = fixture_data(); - let mut a = Field::new( - Arc::clone(&data), - &stage(), - template("enemy_1007_slime", 2), - 42, - 30., - Limits::default(), - ) - .unwrap(); - let mut b = Field::new( - data, - &stage(), - template("enemy_1007_slime", 2), - 42, - 30., - Limits::default(), - ) - .unwrap(); - let initial = a.report().unwrap(); - assert!(a.run(0).unwrap().budget_exhausted); - assert_eq!(a.ticks(), 0); - assert!(a.run(17).unwrap().budget_exhausted); - let output = a.enemy_states().unwrap(); - let old_position = output[0].position; - for _ in 0..17 { - b.run(1).unwrap(); - } - assert_eq!(view(&mut a), view(&mut b)); - a.run(13).unwrap(); - assert_eq!(output[0].position, old_position); - assert_eq!(initial["resolved"], 0); - assert_ne!(a.enemy_states().unwrap()[0].position, old_position); - assert!(!a.finished()); - let id = a.enemies()[0]; - let before = view(&mut a); - assert!(a.spawn("enemy_unported", &json!({})).is_err()); - assert!(!a.faulted()); - assert_eq!(before, view(&mut a)); - assert!(a.unit(id).unwrap().stats.alive); - a.force_end(true).unwrap(); - assert!(a.finished()); - assert_eq!(a.report().unwrap()["resolved"], 2); - assert_eq!(a.run(20).unwrap().ticks, 0); - assert!(!b.finished()); -} -#[test] -fn field_constructor_rejects_unimplemented_mechanics_before_execution() { - let data = fixture_data(); - assert!(Field::new( - Arc::clone(&data), - &stage(), - template("enemy_unported", 1), - 42, - 3., - Limits::default() - ) - .is_err()); - let mut device = stage(); - device["devices"] = json!([{"key":"trap_unported","pos":[10,5],"active":true}]); - assert!(Field::new( - Arc::clone(&data), - &device, - template("enemy_1007_slime", 1), - 42, - 3., - Limits::default() - ) - .is_err()); - let mut terrain = stage(); - terrain["legend"] = json!({"r":{"terrain":"infection"}}); - assert!(Field::new( - Arc::clone(&data), - &terrain, - template("enemy_1007_slime", 1), - 42, - 3., - Limits::default() - ) - .is_err()); - assert!(Field::new( - data, - &stage(), - template("enemy_1007_slime", 1), - 42, - 3., - Limits { - units: 0, - ..Limits::default() - } - ) - .is_err()); -} -#[test] -fn technical_content_failure_is_never_a_terminal_rollout() { - let mut field = Field::new( - fixture_data(), - &stage(), - template("enemy_1200_msfjin", 1), - 42, - 3., - Limits { - buffs_per_unit: 1, - ..Limits::default() - }, - ) - .unwrap(); - assert!(field.run(1).is_err()); - assert!(field.faulted()); - assert!(!field.finished()); - assert!(field.report().is_err()); - assert!(field.enemy_states().is_err()); - assert!(field.run(1).is_err()); - assert!(field.force_end(true).is_err()); -} -#[test] -fn removed_units_release_storage_and_new_fields_restart_identities() { - let data = fixture_data(); - let mut f = Field::new( - Arc::clone(&data), - &stage(), - template("enemy_1007_slime", 2), - 0, - 3., - Limits::default(), - ) - .unwrap(); - f.run(1).unwrap(); - let h = Hit { - source: None, - credit: None, - target: 1, - damage_type: DamageType::True, - no_sp: true, - silent: false, - hp_loss: false, - on_applied: false, - }; - let mut q = hit::Request::new( - h, - Damage { - amount: 200., - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - ); - f.damage(&mut q).unwrap(); - assert_eq!(f.retained_units(), 2); - f.run(1).unwrap(); - assert_eq!(f.retained_units(), 1); - assert!(f.unit(1).is_err()); - assert_eq!(f.report().unwrap()["killed"], 1); - let id = f.spawn("enemy_1007_slime", &json!({"pos":[10,8]})).unwrap(); - assert_eq!(id, 3); - let mut fresh = Field::new( - data, - &stage(), - template("enemy_1007_slime", 1), - 0, - 3., - Limits::default(), - ) - .unwrap(); - fresh.run(1).unwrap(); - assert_eq!(fresh.enemies(), &[1]); -} -fn bits(n: f64) -> String { - format!("{:016x}", n.to_bits()) -} -fn view(f: &mut Field) -> Value { - let states = f.enemy_states().unwrap(); - let reason = f.reason().map(|r| match r { - arkguard_engine::battle::clock::End::Cleared => "cleared", - arkguard_engine::battle::clock::End::Timeout => "timeout", - _ => "forced", - }); - let units:Vec<_>=states.into_iter().map(|e|json!({"id":e.id,"key":e.key,"pos":e.position.map(bits),"hp":bits(e.hp),"maxHp":bits(e.max_hp),"atk":bits(e.atk),"res":bits(e.res),"cd":bits(e.cooldown),"moving":e.moving,"hidden":e.hidden,"leg":e.route_leg,"spawn":e.spawn_sequence,"deploy":e.deployment_sequence,"element":e.element.map(bits),"flags":e.flags})).collect(); - json!({"time":bits(f.time()),"ticks":f.ticks(),"finished":f.finished(),"reason":reason,"pending":f.pending_spawns(),"sequence":f.spawn_sequence(),"rng":f.rng_state(),"units":units,"report":f.report().unwrap()}) -} -fn canonical(v: &mut Value) { - match v { - Value::Number(n) => { - let x = n.as_f64().unwrap(); - if x.fract() == 0. && x.abs() < i64::MAX as f64 { - *v = json!(x as i64); - } - } - Value::Array(a) => a.iter_mut().for_each(canonical), - Value::Object(o) => o.values_mut().for_each(canonical), - _ => {} - } -} -fn encode_bits(v: &mut Value) { - match v { - Value::Number(n) => *v = json!(bits(n.as_f64().unwrap())), - Value::Array(a) => a.iter_mut().for_each(encode_bits), - Value::Object(o) => o.values_mut().for_each(encode_bits), - _ => {} - } -} -fn combat_view(f: &mut Field) -> Value { - let enemies:Vec<_>=f.enemy_states().unwrap().into_iter().map(|e|json!({ - "id":e.id,"key":e.key,"pos":e.position,"hp":e.hp,"maxHp":e.max_hp,"atk":e.atk,"res":e.res,"cd":e.cooldown, - "moving":e.moving,"hidden":e.hidden,"leg":e.route_leg,"spawn":e.spawn_sequence,"deploy":e.deployment_sequence, - "element":e.element,"flags":e.flags,"buffs":f.unit(e.id).unwrap().stats.buffs().iter().map(|b|json!({"key":b.key,"left":b.runtime.time_left,"stacks":b.stacks,"persist":b.runtime.persist})).collect::>() - })).collect(); - let reason = f.reason().map(|r| match r { - arkguard_engine::battle::clock::End::Cleared => "cleared", - arkguard_engine::battle::clock::End::Timeout => "timeout", - _ => "forced", - }); - let mut out = json!({"time":f.time(),"ticks":f.ticks(),"finished":f.finished(),"reason":reason,"rng":f.rng_state(), - "dp":f.deployment_points().unwrap(),"projectiles":f.projectile_count(),"enemies":enemies,"allies":f.ally_states().unwrap(),"report":f.report().unwrap()}); - encode_bits(&mut out); - out -} -fn first_difference(a: &Value, b: &Value, path: &str) -> Option { - if a == b { - return None; - } - match (a, b) { - (Value::Object(a), Value::Object(b)) => { - for key in a.keys().chain(b.keys()) { - if let Some(d) = first_difference( - a.get(key).unwrap_or(&Value::Null), - b.get(key).unwrap_or(&Value::Null), - &format!("{path}.{key}"), - ) { - return Some(d); - } - } - } - (Value::Array(a), Value::Array(b)) if a.len() == b.len() => { - for (i, (a, b)) in a.iter().zip(b).enumerate() { - if let Some(d) = first_difference(a, b, &format!("{path}[{i}]")) { - return Some(d); - } - } - } - _ => {} - } - Some(format!("{path}: native={a} reference={b}")) -} -fn operator_home(home: [i32; 2]) -> arkguard_engine::battle::operators::Placement { - arkguard_engine::battle::operators::Placement { - uid: 1, - home, - direction: arkguard_engine::battle::direction::Direction::Right, - } -} -#[test] -fn ranged_fields_share_native_delivery_and_keep_main_hit_status_scope() { - let data = fixture_data(); - for (key, victims, status_victims) in [ - ("chess_char_1_03_a", 3, 3), - ("chess_char_1_11_a", 1, 1), - ("chess_char_1_14_a", 4, 1), - ] { - let mut f = Field::new( - Arc::clone(&data), - &stage(), - template("enemy_1007_slime", 4), - 42, - 30., - Limits::default(), - ) - .unwrap(); - f.add_operator(key, operator_home([10, 8])).unwrap(); - f.run(1).unwrap(); - assert_eq!(f.unit(1).unwrap().attacks, 1); - assert_eq!(f.projectile_count(), 1); - let output = f.ally_states().unwrap(); - f.run(7).unwrap(); - assert_eq!( - f.enemies() - .iter() - .filter(|id| f.unit(**id).unwrap().damage_taken > 0.) - .count(), - victims, - "{key}" - ); - assert_eq!( - f.enemies() - .iter() - .filter(|id| !f.unit(**id).unwrap().stats.buffs().is_empty()) - .count(), - status_victims, - "{key}" - ); - assert_eq!(output[0]["activations"], 0); - f.run(100).unwrap(); - assert!( - f.ally_states().unwrap()[0]["activations"].as_u64().unwrap() >= 1, - "{key}" - ); - } -} -#[test] -fn unsupported_range_offsets_fail_before_operator_installation() { - use arkguard_engine::battle::operators::Definition; - let data = fixture_data(); - let mut raw = data.table("chess").unwrap()["chess_char_1_03_a"].clone(); - raw["rangeGrid"] = json!([[i32::MIN, 0]]); - assert!(Definition::compile("chess_char_1_03_a", &raw).is_err()); - raw["rangeGrid"] = json!(vec![[0, 0]; 400]); - assert!(Definition::compile("chess_char_1_03_a", &raw).is_err()); -} -#[test] -fn allied_field_pauses_rejects_invalid_setup_and_preserves_output_ownership() { - let data = fixture_data(); - let create = || { - Field::new( - Arc::clone(&data), - &stage(), - template("enemy_1007_slime", 2), - 42, - 30., - Limits::default(), - ) - .unwrap() - }; - let mut a = create(); - let mut b = create(); - assert!(a - .add_operator("chess_unported", operator_home([10, 6])) - .is_err()); - assert!(a - .add_operator("chess_char_1_02_a", operator_home([-1, 6])) - .is_err()); - assert!(!a.faulted()); - assert_eq!( - a.add_operator("chess_char_1_02_a", operator_home([10, 6])) - .unwrap(), - 1 - ); - assert!(a - .add_operator("chess_char_1_02_a", operator_home([10, 6])) - .is_err()); - b.add_operator("chess_char_1_02_a", operator_home([10, 6])) - .unwrap(); - a.run(300).unwrap(); - for _ in 0..10 { - b.run(30).unwrap(); - } - assert_eq!(combat_view(&mut a), combat_view(&mut b)); - let old = a.ally_states().unwrap(); - let saved = old.clone(); - assert!(!a.unit(1).unwrap().blocking().is_empty()); - let before = combat_view(&mut a); - assert!(a - .add_operator("chess_char_1_02_a", operator_home([11, 6])) - .is_err()); - assert!(a.retreat_operator(999).is_err()); - assert_eq!(combat_view(&mut a), before); - a.run(900).unwrap(); - assert_eq!(old, saved); - assert!(a.finished()); - assert_eq!(a.report().unwrap()["killed"], 2); - assert_eq!(a.unit(1).unwrap().deployment.kills, 2); -} -#[test] -fn passive_hit_callbacks_preserve_main_hit_rng_scope_and_continuous_hp_scaling() { - let mut f = Field::new( - fixture_data(), - &stage(), - template("enemy_1007_slime", 1), - 42, - 30., - Limits::default(), - ) - .unwrap(); - f.add_operator("chess_char_1_07_a", operator_home([10, 8])) - .unwrap(); - f.run(1).unwrap(); - assert_eq!(f.ally_states().unwrap()[0]["active"], true); - assert!(f.unit(1).unwrap().stats.buffs().is_empty()); - let mut q = hit::Request::new( - Hit { - source: Some(1), - credit: Some(1), - target: 2, - damage_type: DamageType::True, - no_sp: false, - silent: false, - hp_loss: false, - on_applied: false, - }, - Damage { - amount: 10., - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - ); - let seed = f.rng_state(); - q.is_attack = true; - q.tags.push("chain".into()); - assert_eq!(f.damage(&mut q).unwrap(), 10.); - assert_eq!(f.rng_state(), seed); - q.damage.amount = 10.; - q.is_attack = false; - q.tags.clear(); - assert_eq!(f.damage(&mut q).unwrap(), 10.); - assert_eq!(f.rng_state(), seed); - q.damage.amount = 10.; - q.is_attack = true; - q.is_splash = true; - let dealt = f.damage(&mut q).unwrap(); - assert_eq!(f.rng_state(), seed); - assert_eq!(q.damage.amount, 11.2); - assert_eq!(dealt, 80. - (80. - 11.2)); - q.damage.amount = 0.; - q.is_splash = false; - assert_eq!(f.damage(&mut q).unwrap(), 0.); - assert_ne!(f.rng_state(), seed); -} -#[test] -fn external_field_commands_use_current_successor_time_for_death_and_respawn() { - let mut f = Field::new( - fixture_data(), - &stage(), - template("enemy_1007_slime", 2), - 42, - 30., - Limits::default(), - ) - .unwrap(); - f.add_operator("chess_char_1_02_a", operator_home([10, 6])) - .unwrap(); - f.run(30).unwrap(); - let at = f.time(); - f.retreat_operator(1).unwrap(); - assert_eq!(f.unit(1).unwrap().deployment.death_at, at); - assert_eq!(f.unit(1).unwrap().deployment.respawn_at, at + 3.); - f.run(100).unwrap(); - assert!(f.unit(1).unwrap().stats.alive); - assert_eq!(f.unit(1).unwrap().deployment.deploy_seq, 4); // two enemy deployments precede redeploy - let mut q = hit::Request::new( - Hit { - source: None, - credit: None, - target: 1, - damage_type: DamageType::True, - no_sp: true, - silent: false, - hp_loss: false, - on_applied: false, - }, - Damage { - amount: 1., - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - ); - let at = f.time(); - f.damage(&mut q).unwrap(); - assert_eq!(f.unit(1).unwrap().last_hit_at, at); - let id = f.spawn("enemy_1007_slime", &json!({"pos":[10,9]})).unwrap(); - assert_eq!(f.unit(id).unwrap().deployment.deployed_at, at); -} -#[test] -fn projectile_capacity_failure_faults_the_field_without_truncating_flights() { - let mut f = Field::new( - fixture_data(), - &stage(), - template("enemy_1005_yokai_2", 3), - 42, - 30., - Limits { - projectiles: 1, - ..Default::default() - }, - ) - .unwrap(); - f.add_operator("chess_char_1_02_a", operator_home([10, 6])) - .unwrap(); - assert!(f.run(1).is_err()); - assert!(f.faulted()); - assert_eq!(f.projectile_count(), 1); - assert!(!f.finished()); - assert!(f.report().is_err()); - assert!(f.ally_states().is_err()); -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; concrete full-content allied field"] -fn allied_fields_match_full_battle() { - use arkguard_engine::battle::{direction::Direction, operators::Placement}; - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap(); - let data = Arc::new(Catalog::load(&Path::new(&root).join("data"), 64 << 20).unwrap()); - let script = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/field-allies.mjs"); - let mut child = Command::new("node") - .args([script.to_str().unwrap(), &root]) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut cases = 0; - let mut ticks = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let o = &v["options"]; - let mut template = Template::parse(o, &Value::Null, &Value::Null, 32, 128).unwrap(); - template.spawns = o["spawns"].as_array().unwrap().clone(); - let mut field = Field::new( - Arc::clone(&data), - &o["stage"], - template, - o["seed"].as_u64().unwrap() as u32, - o["timeLimit"].as_f64().unwrap(), - Limits::default(), - ) - .unwrap(); - for u in o["players"][0]["units"].as_array().unwrap() { - field - .add_operator( - u["chessId"].as_str().unwrap(), - Placement { - uid: u["uid"].as_u64().unwrap(), - home: [ - u["row"].as_i64().unwrap() as i32, - u["col"].as_i64().unwrap() as i32, - ], - direction: match u["dir"].as_str().unwrap_or("RIGHT") { - "RIGHT" => Direction::Right, - "UP" => Direction::Up, - "LEFT" => Direction::Left, - "DOWN" => Direction::Down, - _ => panic!("Unknown reference direction"), - }, - }, - ) - .unwrap(); - } - for (i, expected) in v["states"].as_array().unwrap().iter().enumerate() { - for op in v["ops"] - .as_array() - .unwrap() - .iter() - .filter(|op| op["tick"].as_u64() == Some(i as u64)) - { - if op["op"] == "retreat" { - field.retreat_operator(op["id"].as_u64().unwrap()).unwrap(); - } else { - let mut q = hit::Request::new( - Hit { - source: None, - credit: None, - target: op["id"].as_u64().unwrap(), - damage_type: DamageType::True, - no_sp: true, - silent: false, - hp_loss: false, - on_applied: false, - }, - Damage { - amount: op["amount"].as_f64().unwrap(), - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - ); - field.damage(&mut q).unwrap(); - } - } - field.run(1).unwrap_or_else(|e| { - panic!( - "case {cases} tick {i} key {}: {e}", - o["spawns"][0]["enemyKey"] - ) - }); - if let Some(diff) = first_difference(&combat_view(&mut field), expected, "") { - panic!( - "case {cases} tick {i} key {}: {diff}", - o["spawns"][0]["enemyKey"] - ); - } - ticks += 1; - } - cases += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(cases, 116); - eprintln!("Compared {cases} allied fields / {ticks} ticks"); -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; concrete native Field against full upstream Battle"] -fn concrete_fields_match_full_content() { - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap(); - let data = Arc::new(Catalog::load(&Path::new(&root).join("data"), 64 << 20).unwrap()); - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/field.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(&root) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut cases = 0; - let mut ticks = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let o = &v["options"]; - let mut t = Template::parse(o, &Value::Null, &Value::Null, 256, 128).unwrap(); - t.spawns = o["spawns"].as_array().unwrap().clone(); - let mut f = Field::new( - Arc::clone(&data), - &o["stage"], - t, - o["seed"].as_u64().unwrap() as u32, - o["timeLimit"].as_f64().unwrap(), - Limits { - units: 256, - ..Limits::default() - }, - ) - .unwrap(); - assert!(f.run(0).unwrap().budget_exhausted); - assert_eq!(f.ticks(), 0); - for (i, expected) in v["states"].as_array().unwrap().iter().enumerate() { - for op in v["ops"] - .as_array() - .unwrap() - .iter() - .filter(|x| x["tick"].as_u64() == Some(i as u64)) - { - match op["op"].as_str().unwrap() { - "spawn" => { - f.spawn(op["key"].as_str().unwrap(), &op["options"]) - .unwrap(); - } - "hitChain" => { - for _ in 0..30 { - let h = Hit { - source: op["source"].as_u64(), - credit: op["source"].as_u64(), - target: op["id"].as_u64().unwrap(), - damage_type: DamageType::True, - no_sp: false, - silent: false, - hp_loss: false, - on_applied: false, - }; - let mut q = hit::Request::new( - h, - Damage { - amount: 0., - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - ); - q.is_attack = true; - q.attack_id = Some(700); - f.damage(&mut q).unwrap(); - } - } - "damage" => { - let h = Hit { - source: None, - credit: None, - target: op["id"].as_u64().unwrap(), - damage_type: DamageType::True, - no_sp: false, - silent: false, - hp_loss: false, - on_applied: false, - }; - f.damage(&mut hit::Request::new( - h, - Damage { - amount: op["spec"]["amount"].as_f64().unwrap(), - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - )) - .unwrap(); - } - _ => unreachable!(), - } - } - let advanced = f.run(1).unwrap(); - assert_eq!(advanced.ticks, 1); - let mut actual = view(&mut f); - let mut expected = expected.clone(); - canonical(&mut actual); - canonical(&mut expected); - assert_eq!(actual, expected, "field {cases} tick {i}"); - ticks += 1; - } - let report = f.report().unwrap(); - let before = report.clone(); - assert_eq!(f.run(17).unwrap().ticks, 0); - assert_eq!(report, before); - assert!(!f.faulted()); - cases += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(cases, 78); - eprintln!("{cases} concrete full-content fields; {ticks} ticks"); -} diff --git a/crates/engine/tests/grid_reference.rs b/crates/engine/tests/grid_reference.rs deleted file mode 100644 index 917c262..0000000 --- a/crates/engine/tests/grid_reference.rs +++ /dev/null @@ -1,180 +0,0 @@ -use arkguard_engine::battle::{ - direction::{Direction, Placement}, - grid::{bresenham_tiles, segment_tiles, Grid, Rect, BLOCK, COLS, CRATE}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn point(v: &Value) -> [i32; 2] { - [v[0].as_i64().unwrap() as i32, v[1].as_i64().unwrap() as i32] -} -fn direction(v: &Value) -> Direction { - Direction::ALL - .into_iter() - .find(|d| d.name() == v.as_str().unwrap()) - .unwrap() -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT, Node and external stage data; no matches"] -fn all_stage_fields_match() { - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap(); - let stages: Value = - serde_json::from_slice(&std::fs::read(Path::new(&root).join("data/stages.json")).unwrap()) - .unwrap(); - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/grid.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(&root) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut grid = None; - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - match v["kind"].as_str().unwrap() { - "direction" => { - let d = direction(&v["d"]); - let p = [ - v["r"].as_i64().unwrap() as i32, - v["c"].as_i64().unwrap() as i32, - ]; - assert_eq!(json!(d.rotate(p)), v["rotated"]); - assert_eq!(json!(d.local(p)), v["local"]); - assert_eq!(d.mirror().name(), v["mirror"]); - assert_eq!(d.opposite().name(), v["opposite"]); - assert_eq!( - Direction::from_delta(p[0] as f64, p[1] as f64, d).name(), - v["delta"] - ); - } - "placement" => { - let p = Placement { - boss_like: v["battle"] != "normal", - right_side: v["side"] == "R", - field_coords: v["field"].as_bool().unwrap(), - row_offset: v["offset"].as_i64().map(|x| x as i32), - col_offset: if v["side"] == "R" { 8 } else { 0 }, - }; - let abs = v["abs"].as_bool().unwrap(); - assert_eq!(json!(p.map_tile(point(&v["p"]), abs)), v["tile"]); - assert_eq!(p.map_dir(Direction::Right, abs).name(), v["dir"]); - } - "line" => { - assert_eq!( - json!(bresenham_tiles(point(&v["a"]), point(&v["b"]))), - v["bresenham"] - ); - assert_eq!( - json!(segment_tiles(point(&v["a"]), point(&v["b"]))), - v["segment"] - ); - } - "grid" => { - let mut stage = stages[v["id"].as_str().unwrap()].clone(); - if !stage["tiles"].is_null() { - stage["legend"] = stage["tiles"].clone(); - } - let r = &v["rect"]; - let mut g = Grid::new( - &stage, - Rect { - r0: r["r0"].as_i64().unwrap() as i32, - r1: r["r1"].as_i64().unwrap() as i32, - c0: r["c0"].as_i64().unwrap() as i32, - c1: r["c1"].as_i64().unwrap() as i32, - }, - ) - .unwrap(); - if v["obstacles"] == true { - g.set_obstacle([9, 8], true, CRATE).unwrap(); - g.set_obstacle([10, 8], true, BLOCK).unwrap(); - g.set_obstacle([9, 8], true, BLOCK).unwrap(); - g.set_obstacle([9, 8], false, BLOCK).unwrap(); - } - for (k, t) in g.tiles().iter().enumerate() { - assert_eq!( - json!([t.glyph, t.key, t.height, t.build, t.pass, t.terrain, t.special]), - v["tiles"][k], - "stage {} tile {k}", - v["id"] - ); - let p = [(k / COLS) as i32, (k % COLS) as i32]; - assert_eq!( - json!([ - g.ground_passable(p, false), - g.walkable(p, false), - g.fly_passable(p), - g.can_stand(p, false), - g.can_stand(p, true) - ]), - v["queries"][k] - ); - } - assert_eq!(g.version(), v["version"].as_u64().unwrap()); - grid = Some(g); - } - "straight" => { - assert_eq!( - grid.as_ref().unwrap().straight_clear( - v["x"].as_f64().unwrap(), - v["y"].as_f64().unwrap(), - point(&v["end"]) - ), - v["value"].as_bool().unwrap() - ); - } - "flow" => { - let f = grid.as_mut().unwrap().flow_field( - point(&v["end"]), - v["diagonal"].as_bool().unwrap(), - v["ignore"].as_bool().unwrap(), - ); - for (name, values) in [ - ("dist", &f.dist), - ("parent", &f.parent), - ("pen", &f.pen), - ("next", &f.next), - ("official", &f.official), - ("cost", &f.cost), - ("deep", &f.deep), - ] { - assert_eq!( - json!(values.as_slice()), - v[name], - "stage {} field {name}, rect {}, end {}, diagonal {}, ignore {}", - v["id"], - v["rect"], - v["end"], - v["diagonal"], - v["ignore"] - ); - } - for path in v["paths"].as_array().unwrap() { - let start = point(&path["start"]); - let length = Grid::field_length(&f, start); - if path["length"].is_null() { - assert!(length.is_infinite()); - } else { - assert_eq!(length.to_bits(), path["length"].as_f64().unwrap().to_bits()); - } - let waypoints = grid.as_mut().unwrap().waypoints( - start, - point(&v["end"]), - v["diagonal"].as_bool().unwrap(), - v["ignore"].as_bool().unwrap(), - ); - assert_eq!(json!(waypoints), path["waypoints"]); - } - count += 1; - } - _ => panic!("unknown case"), - } - } - assert!(child.wait().unwrap().success()); - assert!(count > 0); - eprintln!("Compared {count} complete fields"); -} diff --git a/crates/engine/tests/health_reference.rs b/crates/engine/tests/health_reference.rs deleted file mode 100644 index 309ba59..0000000 --- a/crates/engine/tests/health_reference.rs +++ /dev/null @@ -1,208 +0,0 @@ -use arkguard_engine::battle::{ - damage::{DamageType, Penetration}, - health::{self, Event, HealOptions, Hit, Hooks, PlayerTotals, Pool, Side, Stage, Unit, World}, - stats::{Base, Buff, UnitStats}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Host { - d: Value, - trace: Vec, - shield: f64, -} -impl Hooks for Host { - fn emit(&mut self, e: &mut Event, w: &mut World) -> Result<(), String> { - let name = match e.stage { - Stage::Fatal => "fatal", - Stage::HpChanged => "hpChanged", - Stage::ModifierApplied => "modifierApplied", - Stage::DamageApplied => "damageApplied", - Stage::Damaged => "damaged", - Stage::Heal => "heal", - Stage::SkillDamaged => { - self.trace.push(json!(["skill"])); - return Ok(()); - } - Stage::OnApplied => { - self.trace.push(json!(["applied"])); - return Ok(()); - } - }; - self.trace.push(json!([name, bits(e.amount)])); - if e.stage == Stage::Fatal { - match self.d["fatal"].as_u64().unwrap() { - 1 => e.prevented = true, - 2 => w.unit_mut(2).unwrap().stats.hp = 5.0, - 3 => w.unit_mut(2).unwrap().stats.alive = false, - _ => {} - } - } - if e.stage == Stage::Heal { - e.amount *= 0.5; - } - Ok(()) - } - fn kill(&mut self, t: u64, _: Option, w: &mut World) -> Result<(), String> { - self.trace.push(json!(["kill"])); - let u = w.unit_mut(t).unwrap(); - u.stats.alive = false; - u.deployed = false; - Ok(()) - } - fn hit_cap(&mut self, _: u64, n: f64) -> Result<(), String> { - self.trace.push(json!(["hitCap", bits(n)])); - Ok(()) - } - fn heal_through(&mut self, _: u64, _: u64, _: &World) -> bool { - self.d["through"] == true - } - fn overheal( - &mut self, - _: u64, - excess: f64, - max: f64, - _: Option, - _: &mut World, - ) -> Result<(), String> { - self.shield = max.min(self.shield + excess); - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; HP functions only"] -fn health_and_healing_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/health.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let d = &v["scenario"]; - let mut base = Base::default(); - base.0.insert("maxHp".into(), 100.0); - base.0.insert("atk".into(), 100.0); - let mut source = Unit::new(UnitStats::new(base.clone()), Side::Ally); - source.owner = Some(10); - source.deployed = true; - source.stats.set_buffs(vec![Buff { - mods: [("healingDealtMul".into(), 1.2)].into_iter().collect(), - ..Buff::default() - }]); - base.0.insert("atk".into(), 0.0); - base.0.insert("def".into(), 25.0); - base.0.insert("res".into(), 30.0); - let mut target = Unit::new( - UnitStats::new(base), - if d["targetAlly"] == true { - Side::Ally - } else { - Side::Enemy - }, - ); - target.stats.hp = 37.0; - target.deployed = true; - target.skill = true; - target.boss = d["boss"] == true; - target.stats.set_buffs(vec![Buff { - mods: [("healingTakenMul".into(), 1.3)].into_iter().collect(), - flags: ["noHeal", "healFree", "hitCount", "hitCountArts"] - .into_iter() - .filter(|k| d[*k] == true) - .map(str::to_string) - .collect(), - ..Buff::default() - }]); - if d["pool"] == true { - target.pool = Some(1); - } - let mut world = World::new(2, 1, 1).unwrap(); - world.insert_unit(1, source).unwrap(); - world.insert_unit(2, target).unwrap(); - world - .insert_pool( - 1, - Pool { - hp: 63.0, - max_hp: 100.0, - }, - ) - .unwrap(); - world.insert_player(10, PlayerTotals::default()).unwrap(); - world.time = 5.0; - world.boss_battle = true; - let mut host = Host { - d: d.clone(), - trace: vec![], - shield: 0.0, - }; - let amount = d["amount"].as_f64().unwrap(); - let self_ = d["self"] == true; - let source = if self_ { 2 } else { 1 }; - let result = if d["heal"] == true { - health::heal( - &mut world, - &mut host, - Some(source), - 2, - amount, - HealOptions { - regen: d["mode"] == "regen", - restore: d["mode"] == "restore", - overheal: true, - ..HealOptions::default() - }, - ) - .unwrap() - } else { - let hit = Hit { - target: 2, - source: Some(1), - credit: Some(source), - damage_type: match d["type"].as_str().unwrap() { - "phys" => DamageType::Physical, - "arts" => DamageType::Arts, - "true" => DamageType::True, - _ => DamageType::Elemental, - }, - no_sp: d["noSp"] == true, - silent: false, - hp_loss: false, - on_applied: true, - }; - if d["loss"] == true { - health::lose_hp( - &mut world, - &mut host, - hit, - amount, - Penetration::default(), - false, - ) - .unwrap() - } else { - health::apply_hp_decrease(&mut world, &mut host, hit, amount).unwrap() - } - }; - let t = world.unit(2).unwrap(); - let c = world.unit(source).unwrap(); - let pp = world.player(10).unwrap(); - let actual = json!({"result":bits(result),"hp":bits(t.stats.hp),"alive":t.stats.alive,"deployed":t.deployed,"taken":bits(t.damage_taken),"damage":bits(c.damage_dealt),"healing":bits(c.healing_done),"last":bits(t.last_hit_at),"pool":bits(world.pool(1).unwrap().hp),"pp":{"damageDealt":bits(pp.damage),"bossDamage":bits(pp.boss_damage),"healingDone":bits(pp.healing)},"shield":bits(host.shield),"trace":host.trace}); - let mut expected = v.clone(); - expected.as_object_mut().unwrap().remove("scenario"); - assert_eq!(actual, expected, "case {d}"); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 768); -} diff --git a/crates/engine/tests/hit_reference.rs b/crates/engine/tests/hit_reference.rs deleted file mode 100644 index 123eb1f..0000000 --- a/crates/engine/tests/hit_reference.rs +++ /dev/null @@ -1,254 +0,0 @@ -use arkguard_engine::{ - battle::{ - damage::{Damage, DamageType, Penetration}, - health::{self, Hit, Side, Unit, World}, - hit::{self, Calculation, Phase, Request}, - injury::{DodgeMode, Effect, Effects, Notice}, - stats::{Base, Buff, UnitStats}, - }, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Host { - d: Value, - trace: Vec, - sleep: bool, - liftoff: bool, - invulnerable: bool, -} -impl Host { - fn update(&self, w: &mut World) -> Result<(), String> { - w.unit_mut(2)?.stats.set_buffs(vec![Buff { - mods: [ - ("artsAttackAddition".into(), 7.0), - ("dmgTakenMul".into(), 1.2), - ] - .into_iter() - .collect(), - flags: [ - ("sleep", self.sleep), - ("liftoff", self.liftoff), - ("invulnerable", self.invulnerable), - ] - .into_iter() - .filter(|(_, v)| *v) - .map(|(k, _)| k.into()) - .collect(), - ..Buff::default() - }]); - Ok(()) - } -} -impl health::Hooks for Host { - fn emit(&mut self, e: &mut health::Event, _: &mut World) -> Result<(), String> { - let name = match e.stage { - health::Stage::Fatal => "fatal", - health::Stage::HpChanged => "hpChanged", - health::Stage::ModifierApplied => "modifierApplied", - health::Stage::DamageApplied => "damageApplied", - health::Stage::Damaged => "damaged", - _ => panic!("unexpected health event"), - }; - self.trace.push(json!([name, bits(e.amount)])); - Ok(()) - } - fn kill(&mut self, id: u64, _: Option, w: &mut World) -> Result<(), String> { - self.trace.push(json!(["kill"])); - w.unit_mut(id)?.stats.alive = false; - w.unit_mut(id)?.deployed = false; - Ok(()) - } - fn hit_cap(&mut self, _: u64, n: f64) -> Result<(), String> { - self.trace.push(json!(["hitCap", bits(n)])); - Ok(()) - } -} -impl hit::Hooks for Host { - fn enabled(&self, _: Phase) -> bool { - true - } - fn phase( - &mut self, - p: Phase, - r: &mut Request, - a: &mut f64, - w: &mut World, - _: &mut Effects, - _: &mut Rng, - ) -> Result<(), String> { - let (name, amount) = match p { - Phase::Hit => ("hit", r.damage.amount), - Phase::Calculate => ("damageCalculate", r.damage.amount), - Phase::CalculateTarget => ("damageCalculateTarget", r.damage.amount), - Phase::Output => ("damageOutput", *a), - Phase::BeforeApply => ("damageBeforeApply", *a), - Phase::Applying => ("damageApplying", *a), - Phase::HpDamage => ("hpDamage", *a), - }; - self.trace.push(json!([name, bits(amount)])); - let action = self.d["action"].as_u64().unwrap(); - if p == Phase::Hit { - if action == 1 { - r.cancelled = true; - } - if action == 3 { - self.invulnerable = true; - self.update(w)?; - } - if action == 4 { - self.liftoff = true; - self.update(w)?; - } - } - if p == Phase::CalculateTarget { - if action == 2 { - w.unit_mut(2)?.stats.alive = false; - } - if action == 5 { - w.unit_mut(2)?.stats.edit_base(|b| { - b.0.insert("def".into(), 120.0); - }); - } - } - if p == Phase::Output && action == 6 { - *a *= 0.5; - r.dodge_mode = DodgeMode::Ignore; - } - if p == Phase::HpDamage && action == 7 { - *a = 3.0; - } - Ok(()) - } - fn notice( - &mut self, - n: Notice, - _: f64, - _: &mut Request, - _: &mut World, - _: &mut Effects, - _: &mut Rng, - ) -> Result<(), String> { - self.trace.push(match n { - Notice::Block { cancelled } => json!(["block", cancelled]), - Notice::Dodge { cancelled, .. } => json!(["dodge", cancelled]), - }); - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; HP-damage pipeline only"] -fn hit_pipeline_matches() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/hit.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let d = &v["scenario"]; - let mut w = World::new(2, 1, 1).unwrap(); - let mut base = Base::default(); - base.0.insert("maxHp".into(), 1000.0); - let mut s = Unit::new( - UnitStats::new(base.clone()), - if d["enemy"] == true { - Side::Enemy - } else { - Side::Ally - }, - ); - s.deployed = true; - s.motion_fly = d["fly"] == true; - s.hits_sleep = d["hitSleep"] == true; - w.insert_unit(1, s).unwrap(); - base.0.insert("def".into(), 60.0); - base.0.insert("res".into(), 30.0); - let mut t = Unit::new(UnitStats::new(base), Side::Ally); - t.deployed = true; - t.hidden = d["hidden"] == true; - t.boss = d["boss"] == true; - w.insert_unit(2, t).unwrap(); - w.time = 3.0; - w.boss_battle = true; - let mut host = Host { - d: d.clone(), - trace: vec![], - sleep: d["sleep"] == true, - liftoff: d["liftoff"] == true, - invulnerable: false, - }; - host.update(&mut w).unwrap(); - let mut effects = Effects::new(8).unwrap(); - let dodge = d["dodge"].as_f64().unwrap(); - effects - .insert(Effect { - mods: Some( - [ - ("dmgTakenMul".into(), 1.2), - ("dodgePhys".into(), dodge), - ("dodgeArts".into(), dodge), - ] - .into_iter() - .collect(), - ), - shield: d["shield"].as_f64().unwrap(), - ..Effect::default() - }) - .unwrap(); - let mut r = Request::new( - Hit { - target: 2, - source: if d["source"] == true { Some(1) } else { None }, - credit: if d["source"] == true { Some(1) } else { None }, - damage_type: match d["type"].as_str().unwrap() { - "phys" => DamageType::Physical, - "arts" => DamageType::Arts, - "true" => DamageType::True, - _ => DamageType::Elemental, - }, - no_sp: true, - silent: true, - hp_loss: false, - on_applied: false, - }, - Damage { - amount: d["amount"].as_f64().unwrap(), - mul: 1.0, - penetration: Penetration::default(), - resolved: false, - }, - ); - r.calculation = match d["calculation"].as_str().unwrap() { - "resolved" => Calculation::Resolved, - "precomputed" => Calculation::Precomputed, - _ => Calculation::Formula, - }; - r.ignore_select = d["ignoreSelect"] == true; - r.dodge_mode = match d["mode"].as_str().unwrap() { - "ignore" => DodgeMode::Ignore, - "normal" => DodgeMode::Normal, - _ => DodgeMode::Uncancellable, - }; - let mut rng = Rng::new(d["i"].as_u64().unwrap() as u32 + 1); - let result = hit::resolve(&mut w, &mut effects, &mut rng, &mut host, &mut r).unwrap(); - let target = w.unit(2).unwrap(); - let actual = json!({"result":bits(result),"hp":bits(target.stats.hp),"alive":target.stats.alive,"deployed":target.deployed,"shield":bits(effects.get(1).unwrap().shield),"taken":bits(target.damage_taken),"damage":bits(w.unit(1).unwrap().damage_dealt),"rng":rng.state(),"trace":host.trace}); - let mut expected = v.clone(); - expected.as_object_mut().unwrap().remove("scenario"); - assert_eq!(actual, expected, "scenario {d}"); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 1024); -} diff --git a/crates/engine/tests/injury_reference.rs b/crates/engine/tests/injury_reference.rs deleted file mode 100644 index a67d00f..0000000 --- a/crates/engine/tests/injury_reference.rs +++ /dev/null @@ -1,212 +0,0 @@ -use arkguard_engine::{ - battle::{ - damage::DamageType, - injury::{ - self, DodgeMode, Effect, EffectId, Effects, HookResult, Hooks, InjuryEvent, Notice, - Observation, Outcome, - }, - }, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn kind(s: &str) -> DamageType { - match s { - "phys" => DamageType::Physical, - "arts" => DamageType::Arts, - "true" => DamageType::True, - _ => DamageType::Elemental, - } -} -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -fn outcome(o: Option) -> Value { - match o { - None => Value::Null, - Some(o) => json!(match o { - Outcome::Zero => "zero", - Outcome::Blocked => "blocked", - Outcome::Dodged => "dodged", - }), - } -} -struct Driver { - descriptors: Vec, - trace: Vec, -} -impl Hooks for Driver { - fn injury( - &mut self, - id: EffectId, - event: &mut InjuryEvent, - effects: &mut Effects, - rng: &mut Rng, - ) -> HookResult { - let d = self.descriptors[id as usize - 1].clone(); - self.trace.push(json!(["injury", id, bits(event.amount)])); - match d["action"].as_u64().unwrap() { - 1 => event.amount *= d["scale"].as_f64().unwrap(), - 2 => { - event.block(Some(d["probability"].as_f64().unwrap()), self, effects, rng)?; - } - 3 => { - event.dodge(Some(d["probability"].as_f64().unwrap()), self, effects, rng)?; - } - 4 => effects.remove(d["remove"].as_u64().unwrap()), - _ => {} - } - event.defer(id)?; - Ok(()) - } - fn observe( - &mut self, - id: EffectId, - event: Observation, - _: &mut Effects, - _: &mut Rng, - ) -> HookResult { - self.trace.push(json!([ - "observe", - id, - bits(event.amount), - event.cancelled, - outcome(event.outcome) - ])); - Ok(()) - } - fn notice(&mut self, n: Notice, _: &mut Effects, _: &mut Rng) -> HookResult { - self.trace.push(match n { - Notice::Block { cancelled } => json!(["block", cancelled]), - Notice::Dodge { cancelled, amount } => json!(["dodge", cancelled, bits(amount)]), - }); - Ok(()) - } - fn cleanup(&mut self, token: u64) -> HookResult { - self.trace.push(json!(["cleanup", token])); - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; injury effects only"] -fn ordered_effects_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/injury.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let descriptors = v["descriptors"].as_array().unwrap().clone(); - let mut set = Effects::new(32).unwrap(); - let t = kind(v["type"].as_str().unwrap()); - for d in &descriptors { - let mods = d["mods"].as_object().map(|o| { - o.iter() - .map(|(k, v)| (k.clone(), v.as_f64().unwrap())) - .collect() - }); - let reduction = d["reduction"].as_f64().map(|r| { - let mut values = [0.0; 4]; - values[match t { - DamageType::Physical => 0, - DamageType::Arts => 1, - DamageType::True => 2, - DamageType::Elemental => 3, - }] = r; - values - }); - set.insert(Effect { - key: d["key"].as_str().unwrap().into(), - priority: d["priority"].as_f64().unwrap(), - stacks: d["stacks"].as_u64().unwrap() as u32, - mods, - shield: d["shield"].as_f64().unwrap(), - shield_hits: d["hits"].as_u64().unwrap() as u32, - shield_types: d["shieldTypes"] - .as_array() - .map(|a| a.iter().map(|v| kind(v.as_str().unwrap())).collect()), - keep_empty_shield: d["keep"] == true, - reduction, - injury: d["action"] != 0, - observer: d["observer"] == true, - ..Effect::default() - }) - .unwrap(); - } - set.dirty = false; - let mut rng = Rng::new(v["i"].as_u64().unwrap() as u32 + 1); - let mut hooks = Driver { - descriptors, - trace: vec![], - }; - let mode = match v["mode"].as_str().unwrap() { - "ignore" => DodgeMode::Ignore, - "normal" => DodgeMode::Normal, - _ => DodgeMode::Uncancellable, - }; - let result = injury::execute( - &mut set, - &mut rng, - &mut hooks, - v["amount"].as_f64().unwrap(), - t, - mode, - v["ignoreBlock"] == true, - ) - .unwrap(); - assert_eq!( - json!({"amount":bits(result.amount),"cancelled":result.cancelled,"outcome":outcome(result.outcome),"notifyZero":result.notify_zero}), - v["result"], - "case {}", - v["i"] - ); - let mut applied = None; - let settled = result - .settle( - &mut hooks, - |a| { - applied = Some(a); - Ok(a) - }, - 0.0, - ) - .unwrap(); - if let Some(a) = applied { - let pos = hooks - .trace - .iter() - .position(|e| e[0] == "cleanup") - .unwrap_or(hooks.trace.len()); - hooks.trace.insert(pos, json!(["apply", bits(a)])); - } - assert_eq!(bits(settled), v["settled"].as_str().unwrap()); - assert_eq!( - hooks.trace, - v["trace"].as_array().unwrap().clone(), - "case {}", - v["i"] - ); - assert_eq!(rng.state() as u64, v["rng"].as_u64().unwrap()); - for expected in v["state"].as_array().unwrap() { - let e = set.get(expected["id"].as_u64().unwrap()); - assert_eq!(e.is_some(), expected["active"] == true); - if let Some(e) = e { - assert_eq!(bits(e.shield), expected["shield"].as_str().unwrap()); - assert_eq!(e.shield_hits as u64, expected["hits"].as_u64().unwrap()); - } - } - // Reference markDirty is called once after shield consumption; removal also dirties - // the native set immediately, including removal from inside an injury callback. - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 1024); -} diff --git a/crates/engine/tests/motion_reference.rs b/crates/engine/tests/motion_reference.rs deleted file mode 100644 index 72f8213..0000000 --- a/crates/engine/tests/motion_reference.rs +++ /dev/null @@ -1,248 +0,0 @@ -use arkguard_engine::{ - battle::{ - blocking, - buffs::{self, Runtime}, - grid::{Grid, Rect}, - health::{self, Side, Unit, World}, - motion::{self, Route}, - stats::{Base, UnitStats}, - status::{self, Options}, - }, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Host { - trace: Vec, -} -impl health::Hooks for Host { - fn kill(&mut self, _: u64, _: Option, _: &mut World) -> Result<(), String> { - unreachable!() - } -} -impl blocking::Hooks for Host { - fn blocked(&mut self, _: u64, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl buffs::Hooks for Host { - fn status(&mut self, _: u64, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } -} -impl status::Hooks for Host { - fn has_before_status(&self) -> bool { - false - } - fn before_status( - &mut self, - _: &mut status::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } - fn has_status_applied(&self) -> bool { - false - } - fn status_applied( - &mut self, - _: &status::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } -} -impl motion::Hooks for Host { - fn check_block(&mut self, _: u64, _: &mut World, _: &mut Grid) -> Result { - Ok(false) - } - fn hidden(&mut self, id: u64, on: bool, w: &mut World) -> Result<(), String> { - w.unit_mut(id)?.hidden = on; - self.trace.push(json!(["hidden", on])); - Ok(()) - } - fn cut_attack_stand(&mut self, _: u64, _: &mut World) -> Result<(), String> { - self.trace.push(json!(["cut"])); - Ok(()) - } - fn leak(&mut self, id: u64, w: &mut World) -> Result<(), String> { - let u = w.unit_mut(id)?; - u.stats.alive = false; - u.deployed = false; - self.trace.push(json!(["leak"])); - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; route, fear and attraction movement"] -fn movement_timelines_match() { - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap(); - let stages: Value = - serde_json::from_slice(&std::fs::read(Path::new(&root).join("data/stages.json")).unwrap()) - .unwrap(); - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/motion.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(&root) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let i = v["i"].as_u64().unwrap(); - let mut stage = stages[v["stage"].as_str().unwrap()].clone(); - stage["legend"] = stage - .get("tiles") - .or_else(|| stage.get("legend")) - .cloned() - .unwrap(); - if !v["synthetic"].is_null() { - stage = v["synthetic"].clone(); - } - let mut g = Grid::new(&stage, Rect::FULL).unwrap(); - let mut w = World::new(2, 1, 1).unwrap(); - let pos = [v["pos"][0].as_f64().unwrap(), v["pos"][1].as_f64().unwrap()]; - let tile = |k: &str| { - [ - v[k][0].as_i64().unwrap() as i32, - v[k][1].as_i64().unwrap() as i32, - ] - }; - let mut base = Base::default(); - base.0.insert( - "moveSpeed".into(), - if i >= 104 { 30.0 } else { 2.0 + (i % 4) as f64 }, - ); - let mut u = Unit::new(UnitStats::new(base), Side::Enemy); - u.position = pos; - u.motion_fly = v["fly"] == true; - u.deployed = true; - u.motion.route = Some(Route::compile(&v["route"], Rect::FULL, 128, pos).unwrap()); - w.insert_unit(1, u).unwrap(); - let mut src = Unit::new(UnitStats::new(Base::default()), Side::Ally); - src.position = [pos[0] - 1.0, pos[1] - 2.0]; - src.deployed = true; - w.insert_unit(2, src).unwrap(); - let mut r = Runtime::new(16, 64, 16).unwrap(); - let mut h = Host { trace: vec![] }; - let mut rng = Rng::new(i as u32 + 1); - let mut states = vec![]; - for tick in 0..v["ticks"].as_u64().unwrap() { - w.time = tick as f64 / 30.0; - if tick == 2 { - status::apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - 1, - "fear", - Options { - duration: 0.8, - source: Some(if i % 5 == 0 { 1 } else { 2 }), - ..Default::default() - }, - ) - .unwrap(); - } - if tick == 8 { - status::apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - 1, - "attract", - Options { - duration: 1.5, - point: Some(tile("dest").map(|x| x as f64)), - ..Default::default() - }, - ) - .unwrap(); - } - if tick == 20 { - let u = w.unit_mut(1).unwrap(); - u.position[1] += 0.3; - u.position[0] -= 0.2; - } - if tick == 25 { - g.set_obstacle(tile("middle"), true, 1).unwrap(); - } - if tick == 45 { - g.set_obstacle(tile("middle"), false, 1).unwrap(); - } - if tick == 35 { - status::apply( - &mut w, - &mut h, - &mut r, - Rect::FULL, - 1, - "fear", - Options { - duration: 0.4, - source: Some(2), - ..Default::default() - }, - ) - .unwrap(); - } - r.tick(&mut w, &mut h, &[1, 2], 1.0 / 30.0).unwrap(); - if w.unit(1).unwrap().stats.alive { - motion::update( - &mut w, - &mut g, - &mut r, - &mut rng, - &mut h, - 1, - 1.0 / 30.0, - (50..55).contains(&tick), - false, - ) - .unwrap(); - } - let distance = motion::remaining_distance(&mut w, &mut g, 1).unwrap(); - let u = w.unit(1).unwrap(); - let route = u.motion.route.as_ref().unwrap(); - let fear=u.motion.fear.as_ref().map(|m|json!({"seq":m.sequence.map(|x|x as i64).unwrap_or(-1),"tiles":m.tiles,"point":m.point,"key":m.key,"goal":m.goal.map(bits),"points":m.points.as_ref().map(|p|p.iter().map(|p|p.map(bits)).collect::>())})); - let attract=u.stats.buffs().iter().find(|b|b.runtime.status.as_deref()==Some("attract")).map(|b|json!({"point":b.runtime.attract_path.as_ref().map(|a|a.point).unwrap_or(0),"points":b.runtime.attract_path.as_ref().map(|a|a.points.iter().map(|p|p.map(bits)).collect::>())})); - states.push(json!({"pos":u.position.map(bits),"moving":u.moving,"alive":u.stats.alive,"hidden":u.hidden,"rng":rng.state(),"leg":route.leg,"wait":route.wait_left.map(bits),"distance":bits(distance),"fear":fear,"attract":attract})); - } - for (tick, (a, b)) in states - .iter() - .zip(v["states"].as_array().unwrap()) - .enumerate() - { - assert_eq!(a, b, "scenario {} tick {tick}", v["i"]); - } - assert_eq!(json!(h.trace), v["trace"]); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 112); -} diff --git a/crates/engine/tests/operator_reference.rs b/crates/engine/tests/operator_reference.rs deleted file mode 100644 index 60d9fef..0000000 --- a/crates/engine/tests/operator_reference.rs +++ /dev/null @@ -1,476 +0,0 @@ -use arkguard_engine::battle::{ - blocking, buffs, - damage::{Damage, DamageType, Penetration}, - direction::Direction, - grid::{Grid, Rect}, - health::{self, Hit, Id, World}, - hit, - operators::{Definition, DeployOrder, Limits, Placement, Roster}, - settlement, - stats::{Base, Buff, UnitStats}, -}; -use arkguard_engine::deterministic::rng::Rng; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; - -struct Host { - roster: Option, - grid: Option, -} -impl Host { - fn call( - &mut self, - f: impl FnOnce(&mut Roster, &Grid, &mut Self) -> Result, - ) -> Result { - let mut roster = self.roster.take().ok_or("Missing roster context")?; - let grid = self.grid.take().ok_or("Missing grid context")?; - let result = f(&mut roster, &grid, self); - self.roster = Some(roster); - self.grid = Some(grid); - result - } -} -impl health::Hooks for Host { - fn kill(&mut self, _: Id, _: Option, _: &mut World) -> Result<(), String> { - Err("Death requires the active buff context".into()) - } -} -impl buffs::Hooks for Host { - fn status(&mut self, _: Id, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("Unexpected fixture buff callback".into()) - } -} -impl settlement::Hooks for Host { - fn health_kill( - &mut self, - id: Id, - credit: Option, - r: &mut buffs::Runtime, - w: &mut World, - ) -> Result<(), String> { - self.call(|roster, _, h| roster.kill(w, r, h, id, credit)) - } - fn health_event( - &mut self, - e: &mut health::Event, - r: &mut buffs::Runtime, - w: &mut World, - ) -> Result<(), String> { - if e.stage == health::Stage::SkillDamaged { - self.call(|roster, _, h| roster.damaged(w, r, h, e.target))?; - } - Ok(()) - } -} -fn setup(capacity: usize, max_buffs: usize) -> (World, buffs::Runtime, Host) { - setup_order(capacity, max_buffs, DeployOrder::Column) -} -fn setup_order( - capacity: usize, - max_buffs: usize, - deploy_order: DeployOrder, -) -> (World, buffs::Runtime, Host) { - let grid = Grid::new(&json!({"rows":vec!["r".repeat(21);19]}), Rect::NORMAL).unwrap(); - let roster = Roster::new( - &grid, - 1, - Limits { - units: capacity, - dp_initial: 99., - deploy_order, - ..Default::default() - }, - ) - .unwrap(); - ( - World::new(8, 1, 1).unwrap(), - buffs::Runtime::new(max_buffs, 64, 32).unwrap(), - Host { - roster: Some(roster), - grid: Some(grid), - }, - ) -} -fn authored() -> Definition { - // Independent authored record: no game assets or data bundled in the test. - Definition::compile("chess_char_1_02_a",&json!({ - "stats":{"maxHp":100,"def":20,"res":5},"skill":{"skillId":"skchr_yak_2", - "duration":2,"initSp":1,"spCost":1,"spType":"INCREASE_WITH_TIME","trigger":{"rule":"TAKE_DAMAGE"}, - "bb":{"max_hp":0.3,"def":0.1,"magic_resistance":0.6}}, - "talents":[{"index":0,"bb":{"magic_resistance":7}}],"rangeGrid":[[0,0]], - "position":"MELEE","profession":"TANK","subProfessionId":"protector" - })).unwrap() -} -fn add( - w: &mut World, - r: &mut buffs::Runtime, - h: &mut Host, - d: Definition, - uid: u64, - tile: [i32; 2], -) -> Result { - h.call(|roster, g, h| { - roster.add( - w, - r, - h, - g, - d, - Placement { - uid, - home: tile, - direction: Direction::Right, - }, - ) - }) -} -fn damage( - w: &mut World, - r: &mut buffs::Runtime, - h: &mut Host, - amount: f64, - no_sp: bool, - kind: DamageType, -) -> Result { - let mut q = hit::Request::new( - Hit { - target: 1, - source: None, - credit: None, - damage_type: kind, - no_sp, - silent: false, - hp_loss: false, - on_applied: false, - }, - Damage { - amount, - mul: 1., - resolved: false, - penetration: Penetration::default(), - }, - ); - settlement::resolve(w, r, &mut Rng::new(42), h, &mut q) -} -fn bits(n: f64) -> String { - format!("{:016x}", n.to_bits()) -} -fn view(w: &mut World, h: &Host) -> Value { - let roster = h.roster.as_ref().unwrap(); - let order: Vec<_> = roster - .ids() - .iter() - .map(|id| { - let u = w.unit(*id).unwrap(); - json!([u.deployment.uid, u.deployment.deploy_seq]) - }) - .collect(); - let u = w.unit_mut(1).unwrap(); - let s = u.stats.stats().unwrap().clone(); - let roster = h.roster.as_ref().unwrap(); - let k = roster.entry(1).unwrap().skill().unwrap(); - let stats: serde_json::Map<_, _> = ["maxHp", "atk", "def", "res", "blockCnt", "interval"] - .into_iter() - .map(|n| (n.into(), json!(bits(s.n(n))))) - .collect(); - let buffs: Vec<_> = u - .stats - .buffs() - .iter() - .map(|b| { - let mods: serde_json::Map<_, _> = b - .mods - .iter() - .map(|(k, v)| (k.clone(), json!(bits(*v)))) - .collect(); - json!({"key":b.key,"mods":mods,"persist":b.runtime.persist}) - }) - .collect(); - json!({"hp":bits(u.stats.hp),"alive":u.stats.alive,"deployed":u.deployed,"removed":u.removed, - "stats":stats,"order":order,"dp":bits(roster.dp(1).unwrap()),"deploy":u.deployment.deploy_seq,"aggro":u.deployment.aggro_seq, - "respawn":bits(u.deployment.respawn_at),"death":bits(u.deployment.death_at),"reason":u.deployment.remove_reason, - "body":u.deployment.body,"ground":u.ground,"element":u.element_buildup.map(bits),"buffs":buffs, - "skill":{"active":k.bank.active,"sp":bits(k.bank.sp),"charges":bits(k.bank.charges),"left":bits(k.time_left), - "activations":k.activations,"readyAt":bits(k.op_ready_at)}}) -} -#[test] -fn roster_rejections_preserve_units_and_identities() { - let (mut w, mut r, mut h) = setup(1, 8); - assert!(add(&mut w, &mut r, &mut h, authored(), 1, [0, 0]).is_err()); - assert_eq!( - add(&mut w, &mut r, &mut h, authored(), 1, [10, 5]).unwrap(), - 1 - ); - assert!(add(&mut w, &mut r, &mut h, authored(), 2, [10, 6]).is_err()); - assert!(!h.roster.as_ref().unwrap().faulted()); - assert_eq!(w.next_unit_id().unwrap(), 2); - assert!(Definition::compile("chess_unported", &json!({})).is_err()); -} -#[test] -fn death_ends_skill_in_canonical_context_and_redeploy_resets_it() { - let (mut w, mut r, mut h) = setup(2, 8); - add(&mut w, &mut r, &mut h, authored(), 1, [10, 5]).unwrap(); - h.call(|roster, g, h| roster.deploy_initial(&mut w, &mut r, h, g)) - .unwrap(); - w.time = 3.; - damage(&mut w, &mut r, &mut h, 0., true, DamageType::True).unwrap(); - assert!( - !h.roster - .as_ref() - .unwrap() - .entry(1) - .unwrap() - .skill() - .unwrap() - .bank - .active - ); - damage(&mut w, &mut r, &mut h, 0., false, DamageType::True).unwrap(); - assert!( - h.roster - .as_ref() - .unwrap() - .entry(1) - .unwrap() - .skill() - .unwrap() - .bank - .active - ); - damage(&mut w, &mut r, &mut h, 10000., false, DamageType::True).unwrap(); - let u = w.unit(1).unwrap(); - assert!(!u.stats.alive); - assert!(!u.removed); - assert_eq!(u.stats.buffs().len(), 1); - assert_eq!(u.stats.buffs()[0].key.as_deref(), Some("talent:yak")); - assert!( - !h.roster - .as_ref() - .unwrap() - .entry(1) - .unwrap() - .skill() - .unwrap() - .bank - .active - ); - w.time = 73.; - h.call(|roster, g, h| roster.check_redeploys(&mut w, &mut r, h, g)) - .unwrap(); - assert!(w.unit(1).unwrap().stats.alive); - assert_eq!(w.unit(1).unwrap().deployment.deploy_seq, 2); - assert_eq!(h.roster.as_ref().unwrap().dp(1), Some(89.)); - assert_eq!( - w.unit_mut(1).unwrap().stats.stats().unwrap().n("maxHp"), - 100. - ); -} -#[test] -fn effect_overflow_faults_roster_and_never_runs_an_incomplete_skill() { - let (mut w, mut r, mut h) = setup(1, 1); - add(&mut w, &mut r, &mut h, authored(), 1, [10, 5]).unwrap(); - h.call(|roster, g, h| roster.deploy_initial(&mut w, &mut r, h, g)) - .unwrap(); - w.time = 3.; - assert!(damage(&mut w, &mut r, &mut h, 0., false, DamageType::True).is_err()); - assert!(h.roster.as_ref().unwrap().faulted()); - assert!(h - .call(|roster, _, h| roster.tick_skills(&mut w, &mut r, h, 1. / 30.)) - .is_err()); -} -#[test] -fn operator_death_releases_blocked_enemies_in_the_same_buff_context() { - struct Contact; - impl blocking::Hooks for Contact { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Err("Unexpected contact release".into()) - } - } - let (mut w, mut r, mut h) = setup(1, 8); - add(&mut w, &mut r, &mut h, authored(), 1, [10, 5]).unwrap(); - h.call(|roster, g, h| roster.deploy_initial(&mut w, &mut r, h, g)) - .unwrap(); - let mut enemy = health::Unit::new(UnitStats::new(Base::default()), health::Side::Enemy); - enemy.position = [10., 5.2]; - enemy.deployed = true; - w.insert_unit(2, enemy).unwrap(); - let mut cloak = Buff { - key: Some("cloak".into()), - ..Default::default() - }; - cloak.flags.insert("stealth".into()); - cloak.runtime.persist = true; - r.add( - &mut w, - &mut h, - 2, - buffs::Spec { - buff: cloak, - flags_present: true, - ..Default::default() - }, - ) - .unwrap(); - assert!(blocking::check( - &mut w, - h.roster.as_ref().unwrap().deployment(), - h.grid.as_ref().unwrap(), - &mut Contact, - 2 - ) - .unwrap()); - damage(&mut w, &mut r, &mut h, 10000., false, DamageType::True).unwrap(); - assert!(w.unit(1).unwrap().blocking().is_empty()); - assert_eq!(w.unit(2).unwrap().blocked_by(), None); - assert!(w - .unit(2) - .unwrap() - .stats - .buffs() - .iter() - .any(|b| b.key.as_deref() == Some("stealthOff:cloak"))); - assert!(!arkguard_engine::battle::targeting::enemy_stealthed(&mut w, 2).unwrap()); - r.tick(&mut w, &mut h, &[2], 3.).unwrap(); - assert!(arkguard_engine::battle::targeting::enemy_stealthed(&mut w, 2).unwrap()); -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; default original operator lifecycle"] -fn default_operators_match_original_deployment_hp_and_skills() { - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").expect("Set reference root"); - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/operators.mjs"); - let mut child = Command::new("node") - .args([script.to_str().unwrap(), &root]) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut cases = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let (mut w, mut r, mut h) = setup_order( - 3, - 8, - if v["orderRule"] == "rowBottomUp" { - DeployOrder::RowBottomUp - } else { - DeployOrder::Column - }, - ); - add( - &mut w, - &mut r, - &mut h, - Definition::compile(v["key"].as_str().unwrap(), &v["raw"]).unwrap(), - 1, - [10, 5], - ) - .unwrap(); - add( - &mut w, - &mut r, - &mut h, - Definition::compile(v["key"].as_str().unwrap(), &v["raw"]).unwrap(), - 2, - [12, 5], - ) - .unwrap(); - add( - &mut w, - &mut r, - &mut h, - Definition::compile(v["key"].as_str().unwrap(), &v["raw"]).unwrap(), - 3, - [9, 4], - ) - .unwrap(); - h.call(|roster, g, h| roster.deploy_initial(&mut w, &mut r, h, g)) - .unwrap(); - assert_eq!(view(&mut w, &h), v["states"][0], "{} initial", v["key"]); - for (t, expected) in v["states"].as_array().unwrap().iter().skip(1).enumerate() { - w.time = t as f64 / 30.; - for op in v["ops"] - .as_array() - .unwrap() - .iter() - .filter(|op| op["tick"].as_u64() == Some(t as u64)) - { - match op["op"].as_str().unwrap() { - "damage" => { - damage( - &mut w, - &mut r, - &mut h, - op["amount"].as_f64().unwrap(), - op["noSp"] == true, - if op["type"] == "arts" { - DamageType::Arts - } else { - DamageType::True - }, - ) - .unwrap(); - } - "gain" => { - h.call(|roster, _, h| { - roster.grant_sp(&mut w, &mut r, h, 1, op["amount"].as_f64().unwrap()) - }) - .unwrap(); - } - "retreat" => h - .call(|roster, _, h| roster.retreat(&mut w, &mut r, h, 1)) - .unwrap(), - "buff" => { - let mut buff = Buff { - key: Some("discard-on-death".into()), - mods: [("defFlat".into(), 21.)].into(), - ..Default::default() - }; - buff.runtime.duration = 100.; - r.add( - &mut w, - &mut h, - 1, - buffs::Spec { - buff, - mods_present: true, - ..Default::default() - }, - ) - .unwrap(); - } - _ => panic!("Unknown oracle operation"), - } - } - r.tick(&mut w, &mut h, &[1], 1. / 30.).unwrap(); - h.call(|roster, _, h| roster.tick_skills(&mut w, &mut r, h, 1. / 30.)) - .unwrap(); - h.call(|roster, g, h| roster.check_redeploys(&mut w, &mut r, h, g)) - .unwrap(); - assert_eq!( - &view(&mut w, &h), - expected, - "{} case {cases} tick {t}", - v["key"] - ); - } - cases += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(cases, 4); -} diff --git a/crates/engine/tests/projectiles_reference.rs b/crates/engine/tests/projectiles_reference.rs deleted file mode 100644 index a609589..0000000 --- a/crates/engine/tests/projectiles_reference.rs +++ /dev/null @@ -1,186 +0,0 @@ -use arkguard_engine::battle::{ - health::{Side, Unit, World}, - projectiles::{self, Launch, Projectile, System}, - stats::{Base, UnitStats}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Host { - d: Value, - trace: Vec, - spawned: bool, -} -fn fixed(from: [f64; 2], to: [f64; 2], token: u64) -> Launch { - Launch { - from, - source: None, - target: None, - to: Some(to), - speed: 12.0, - hit_dead: false, - max_age: 10.0, - on_hit: true, - visual: "arrow".into(), - speed_changeable: None, - removable: None, - payload: token, - } -} -impl projectiles::Hooks for Host { - fn has_step(&self) -> bool { - true - } - fn step( - &mut self, - p: &mut Projectile, - s: &mut System, - w: &mut World, - ) -> Result { - self.trace.push(json!([ - "step", - p.payload, - bits(p.position[1]), - bits(p.position[0]) - ])); - if self.d["spawnStep"] == true && !self.spawned { - self.spawned = true; - s.add(w, fixed(p.position, [2.0, 3.0], 10))?; - } - Ok(self.d["cancel"] == true && p.payload == 2) - } - fn impact( - &mut self, - p: &mut Projectile, - target: Option, - s: &mut System, - w: &mut World, - ) -> Result<(), String> { - self.trace.push(json!([ - "impact", - p.payload, - target, - bits(p.position[1]), - bits(p.position[0]) - ])); - if self.d["spawnHit"] == true && p.payload < 10 { - s.add(w, fixed(p.position, [0.0, 0.0], p.payload + 100))?; - } - Ok(()) - } -} -fn world() -> World { - let mut w = World::new(2, 1, 1).unwrap(); - w.insert_unit(1, Unit::new(UnitStats::new(Base::default()), Side::Ally)) - .unwrap(); - let mut target = Unit::new(UnitStats::new(Base::default()), Side::Enemy); - target.position = [1.0, 2.0]; - target.deployment.deploy_seq = 1; - target.deployed = true; - w.insert_unit(2, target).unwrap(); - w -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; projectile flight fixtures"] -fn flight_and_callback_order_match() { - let script = - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/projectiles.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let d = &v["scenario"]; - let mut w = world(); - let mut s = System::new(32).unwrap(); - let mut h = Host { - d: d.clone(), - trace: vec![], - spawned: false, - }; - for token in [1, 2] { - s.add( - &mut w, - Launch { - from: [0.0, 0.0], - source: Some(1), - target: Some(2), - to: None, - speed: d["speed"].as_f64().unwrap(), - hit_dead: d["hitDead"] == true, - max_age: d["maxAge"].as_f64().unwrap(), - on_hit: true, - visual: "arrow".into(), - speed_changeable: None, - removable: None, - payload: token, - }, - ) - .unwrap(); - } - let mut states = vec![]; - for tick in 0..30 { - let target = w.unit_mut(2).unwrap(); - target.position = [1.0 + tick as f64 * 0.01, 2.0 + tick as f64 * 0.03]; - if d["die"] == true && tick == 2 { - target.stats.alive = false; - } - if d["hide"] == true && tick == 2 { - target.hidden = true; - } - if d["redeploy"] == true && tick == 3 { - target.stats.alive = true; - target.hidden = false; - target.deployment.deploy_seq += 1; - } - s.update(&mut w, &mut h, 0.1).unwrap(); - states.push(json!(s.list().iter().map(|p|json!({"token":p.payload,"x":bits(p.position[1]),"y":bits(p.position[0]),"tx":bits(p.destination[1]),"ty":bits(p.destination[0]),"age":bits(p.age),"target":p.target})).collect::>())); - } - assert_eq!(json!(states), v["states"], "flight {d}"); - assert_eq!(json!(h.trace), v["trace"], "events {d}"); - s.clear(&mut w).unwrap(); - assert_eq!(w.unit_pins(1).unwrap(), 0); - assert_eq!(w.unit_pins(2).unwrap(), 0); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 128); -} -#[test] -fn retained_units_and_capacity_are_released_on_clear_and_failure() { - let mut w = world(); - let mut s = System::new(1).unwrap(); - let mut p = fixed([0.0, 0.0], [1.0, 2.0], 1); - p.source = Some(1); - p.target = Some(2); - s.add(&mut w, p.clone()).unwrap(); - assert!(s.add(&mut w, p.clone()).is_err()); - assert_eq!(w.unit_pins(1).unwrap(), 1); - w.unit_mut(1).unwrap().removed = true; - assert!(w.release_removed(1).is_err()); - s.clear(&mut w).unwrap(); - assert_eq!(w.unit_pins(1).unwrap(), 0); - w.release_removed(1).unwrap(); - let mut w = world(); - let mut s = System::new(1).unwrap(); - s.add(&mut w, p).unwrap(); - let mut h = Host { - d: json!({"spawnStep":true}), - trace: vec![], - spawned: false, - }; - assert!(s.update(&mut w, &mut h, 0.01).is_err()); - assert!(s.faulted()); - assert_eq!(w.unit_pins(1).unwrap(), 0); - assert_eq!(w.unit_pins(2).unwrap(), 0); -} diff --git a/crates/engine/tests/radius_reference.rs b/crates/engine/tests/radius_reference.rs deleted file mode 100644 index 2a4cd6c..0000000 --- a/crates/engine/tests/radius_reference.rs +++ /dev/null @@ -1,117 +0,0 @@ -use arkguard_engine::battle::{ - body::HitArea, - deploy::Kind, - health::{Side, Unit, World}, - spatial::{self, RadiusRule}, - stats::{Base, Buff, UnitStats}, - targeting::Queries, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -struct Query { - revealed: Vec, -} -impl Queries for Query { - fn enemy_stealthed(&mut self, id: u64, _: &mut World) -> Result { - Ok(!self.revealed[id as usize - 1]) - } - fn skip_enemy(&mut self, _: Option, _: u64, _: &mut World) -> Result { - unreachable!() - } - fn remaining_distance(&mut self, _: u64, _: &mut World) -> Result { - unreachable!() - } - fn body_distance(&mut self, _: u64, _: [f64; 2], _: &mut World) -> Result { - unreachable!() - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; actual area queries"] -fn radius_queries_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/radius.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let mut w = World::new(12, 1, 1).unwrap(); - let mut ids = vec![]; - let mut q = Query { revealed: vec![] }; - for d in v["records"].as_array().unwrap() { - let id = d["id"].as_u64().unwrap(); - let mut u = Unit::new(UnitStats::new(Base::default()), Side::Enemy); - u.position = [d["y"].as_f64().unwrap(), d["x"].as_f64().unwrap()]; - u.stats.alive = d["alive"] == true; - u.deployed = d["deployed"] == true; - u.hidden = d["hidden"] == true; - u.owner = d["owner"].as_u64(); - if d["device"] == true { - u.deployment.kind = Kind::Device; - } - if d["huge"] == true { - u.hit_area = HitArea::new(4.95, 2.95, 0., 1.); - } - u.stats.set_buffs(vec![Buff { - flags: ["stealth", "untargetable"] - .into_iter() - .filter(|k| d[*k] == true) - .map(str::to_string) - .collect(), - ..Buff::default() - }]); - q.revealed.push(d["revealed"] == true); - w.insert_unit(id, u).unwrap(); - ids.push(id); - } - let radius = v["radius"].as_f64().unwrap(); - for (key, rule, foes) in [ - ("centre", RadiusRule::Centre, false), - ("body", RadiusRule::Body, false), - ("foes", RadiusRule::Body, true), - ("collider", RadiusRule::Collider, true), - ] { - assert_eq!( - json!(spatial::enemies_in_radius( - &mut w, - &mut q, - &ids, - [10., 4.], - radius, - rule, - foes, - 12 - ) - .unwrap()), - v[key], - "{key} case {}", - v["i"] - ); - } - assert_eq!( - json!(spatial::allies_in_radius( - &w, - &ids, - [10., 4.], - radius, - v["owner"].as_u64(), - v["devices"] == true, - 12 - ) - .unwrap()), - v["allies"], - "allies {}", - v["i"] - ); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 256); -} diff --git a/crates/engine/tests/reference.rs b/crates/engine/tests/reference.rs deleted file mode 100644 index 0a588a4..0000000 --- a/crates/engine/tests/reference.rs +++ /dev/null @@ -1,109 +0,0 @@ -use arkguard_engine::deterministic::{ - math, - rng::{derive_seed, Rng}, - scheduler::Scheduler, -}; -use serde_json::Value; -use std::{path::Path, process::Command}; -fn float(v: &Value) -> f64 { - f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) -} -fn same(actual: f64, expected: &Value) { - let expected = float(expected); - if expected.is_nan() { - assert!(actual.is_nan()); - } else { - assert_eq!( - actual.to_bits(), - expected.to_bits(), - "{actual} != {expected}" - ); - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; runs primitives only"] -fn matches_upstream_bits() { - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").expect("Set ARKGUARD_REFERENCE_ROOT"); - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/primitives.mjs"); - let output = Command::new("node").arg(script).arg(root).output().unwrap(); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - for line in String::from_utf8(output.stdout).unwrap().lines() { - let v: Value = serde_json::from_str(line).unwrap(); - match v["kind"].as_str().unwrap() { - "helpers" => { - let mut r = Rng::new(v["seed"].as_u64().unwrap() as u32); - same(r.next_f64(), &v["first"]); - same(r.clone().next_f64(), &v["clone"]); - assert_eq!(r.int(0), 0); - assert_eq!(r.pick::(&[]), None); - assert_eq!(r.weighted(&[0.0, -1.0]), None); - let mut shuffled = [0, 1, 2, 3, 4, 5, 6, 7]; - r.shuffle(&mut shuffled); - assert_eq!(serde_json::json!(shuffled), v["shuffled"]); - let weights = [-1.0, 0.0, 1.0, 2.0, 3.0]; - for expected in v["weighted"].as_array().unwrap() { - let index = r.weighted(&weights).unwrap(); - assert_eq!(weights[index], expected.as_f64().unwrap()); - } - assert_eq!(r.state() as u64, v["state"].as_u64().unwrap()); - } - "rng" => { - let mut r = Rng::new(v["seed"].as_u64().unwrap() as u32); - for x in v["values"].as_array().unwrap() { - assert_eq!(r.next_f64(), x.as_f64().unwrap()); - } - assert_eq!(r.state() as u64, v["state"].as_u64().unwrap()); - } - "derive" => assert_eq!( - derive_seed( - v["seed"].as_u64().unwrap() as u32, - v["salt"].as_str().unwrap() - ) as u64, - v["value"].as_u64().unwrap() - ), - "math" => { - let x = float(&v["x"]); - same(math::sin(x), &v["sin"]); - same(math::cos(x), &v["cos"]); - same(math::round_half_even(x), &v["round"]); - } - "pair" => { - let x = float(&v["x"]); - let y = float(&v["y"]); - same(math::hypot(x, y), &v["hypot"]); - same(math::atan2(y, x), &v["atan2"]); - } - "power" => same( - math::powi(float(&v["x"]), v["n"].as_i64().unwrap() as i32).unwrap(), - &v["value"], - ), - "scheduler" => { - let mut s = Scheduler::new(4).unwrap(); - let id = s.schedule("repeat", 2.0, true).unwrap(); - s.schedule("once", 2.0, false).unwrap(); - let mut events = vec![]; - while let Some(e) = s.pop().unwrap() { - events.push(serde_json::json!([e.payload, s.now()])); - if e.payload == "repeat" { - if s.now() == 4.0 { - s.cancel(id); - } else { - s.schedule("callback", 2.0, false).unwrap(); - } - } - } - let expected = v["events"].as_array().unwrap(); - assert_eq!(events.len(), expected.len()); - for (actual, expected) in events.iter().zip(expected) { - assert_eq!(actual[0], expected[0]); - assert_eq!(actual[1].as_f64(), expected[1].as_f64()); - } - } - _ => panic!("Unknown case"), - } - } -} diff --git a/crates/engine/tests/search_reference.rs b/crates/engine/tests/search_reference.rs deleted file mode 100644 index 4d879f2..0000000 --- a/crates/engine/tests/search_reference.rs +++ /dev/null @@ -1,259 +0,0 @@ -use arkguard_engine::{ - battle::{ - blocking, - deploy::{self, Deployment, Options}, - grid::{Grid, Rect}, - health::{Id, Side, Unit, World}, - search::{self, AttackProfile, Commitments, Heal}, - stats::{Base, Buff, UnitStats}, - targeting::{Priority, Profile, Queries}, - }, - deterministic::math::hypot, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -struct Host { - fixture: Value, - p: AttackProfile, -} -impl Queries for Host { - fn enemy_stealthed(&mut self, _: Id, _: &mut World) -> Result { - Ok(false) - } - fn skip_enemy(&mut self, _: Option, _: Id, _: &mut World) -> Result { - Ok(false) - } - fn remaining_distance(&mut self, id: Id, _: &mut World) -> Result { - Ok(10.0 - id as f64) - } - fn body_distance(&mut self, id: Id, p: [f64; 2], w: &mut World) -> Result { - let q = w.unit(id)?.position; - Ok(hypot(q[0] - p[0], q[1] - p[1])) - } -} -impl Host { - fn list(&self, key: &str) -> Vec { - self.fixture[key] - .as_array() - .unwrap() - .iter() - .map(|v| v.as_u64().unwrap()) - .collect() - } -} -impl search::Host for Host { - fn enemies( - &mut self, - _: Id, - keys: &[usize], - _: Profile, - _: &mut World, - _: usize, - ) -> Result, String> { - Ok(self.list(if keys[0] == 1 { "enemies" } else { "near" })) - } - fn injured_allies( - &mut self, - _: Id, - _: &[usize], - _: bool, - _: &mut World, - _: usize, - ) -> Result, String> { - Ok(self.list("heal")) - } - fn has_ally_targets(&self) -> bool { - !self.list("extra").is_empty() || !self.list("nearExtra").is_empty() - } - fn ally_targets( - &mut self, - _: Id, - keys: &[usize], - _: &mut World, - _: usize, - ) -> Result, String> { - Ok(self.list(if keys[0] == 1 { "extra" } else { "nearExtra" })) - } - fn profile(&mut self, _: Id, _: &mut World) -> Result, String> { - Ok(Some(self.p)) - } - fn range(&mut self, _: Id, _: &World) -> Result, String> { - Ok(vec![1]) - } - fn skill_active(&self, _: Id, _: &World) -> Result { - Ok(true) - } - fn can_attack(&mut self, _: Id, _: AttackProfile, _: &mut World) -> Result { - Ok(true) - } -} -struct Deploy; -impl blocking::Hooks for Deploy { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl deploy::Hooks for Deploy { - fn initialize( - &mut self, - _: Id, - _: Options, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn event( - &mut self, - _: deploy::Event, - _: Id, - _: Option, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn remove_temporary_effects(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -fn setup(v: &Value) -> (World, Host) { - let d = &v["scenario"]; - let mut w = World::new(9, 1, 1).unwrap(); - for id in 1..=9 { - let mut base = Base::default(); - base.0.insert("maxHp".into(), 100.0); - base.0.insert("blockCnt".into(), 3.0); - let mut u = Unit::new( - UnitStats::new(base), - if id == 1 || id == 9 { - Side::Ally - } else { - Side::Enemy - }, - ); - u.deployment.kind = deploy::Kind::Operator; - u.deployment.home = [10, 4]; - u.position = [10.0, 4.0]; - u.ground = true; - u.stats.hp = id as f64 * 10.0; - u.deployed = true; - u.targeting.spawn_seq = 10 - id; - w.insert_unit(id, u).unwrap(); - } - if d["blocked"] == true { - let mut dep = Deployment::new(Rect::FULL, 9, 1, 99.0).unwrap(); - dep.register(1, &w).unwrap(); - w.unit_mut(1).unwrap().deployed = false; - dep.deploy(&mut w, &mut Deploy, 1, Options::default()) - .unwrap(); - w.unit_mut(1).unwrap().stats.hp = 10.0; - let g = Grid::new(&json!({"rows":vec!["r".repeat(21);19]}), Rect::FULL).unwrap(); - assert!(blocking::check(&mut w, &dep, &g, &mut Deploy, 2).unwrap()); - } - let a = w.unit_mut(1).unwrap(); - a.stats.set_buffs(vec![Buff { - mods: [("maxTargets".into(), d["extraTargets"].as_f64().unwrap())] - .into_iter() - .collect(), - ..Buff::default() - }]); - a.cadence.cooldown = d["cooldown"].as_f64().unwrap(); - a.cadence.had_target = d["had"].as_bool(); - let p = AttackProfile { - selection: Profile { - can_hit_fly: true, - ..Profile::default() - }, - priority: Priority::LowestHp, - heal: if d["heal"] == true { - Some(Heal { - multi: d["multi"] == true, - count: d["healCount"].as_f64().unwrap(), - hp_at_most: d["hpAtMost"].as_f64().unwrap(), - element_heal: false, - }) - } else { - None - }, - heal_attack: d["heal"] == true, - fortress: d["fortress"] == true, - all_in_range: d["all"] == true, - range_aoe: d["rangeAoe"] == true, - hit_all_blocked: d["hitAll"] == true, - max_targets: d["maxTargets"].as_f64().unwrap(), - ..AttackProfile::default() - }; - ( - w, - Host { - fixture: v["fixture"].clone(), - p, - }, - ) -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; acquire and commitment only"] -fn acquisition_and_commitment_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/search.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let (mut w, mut h) = setup(&v); - let p = h.p; - let got = search::acquire(&mut w, &mut h, 1, &[1], p, 32).unwrap(); - assert_eq!(json!(got.targets), v["selected"], "case {}", v["scenario"]); - assert_eq!(json!(got.fortress_melee), v["melee"]); - let mut cache = Commitments::new(2, 32, 32).unwrap(); - cache.capture(&mut w, &mut h, &[1], 1.0 / 30.0).unwrap(); - assert_eq!( - json!(cache.targets(&mut w, &mut h, 1, p).unwrap()), - v["raw"], - "capture {}", - v["scenario"] - ); - w.unit_mut(2).unwrap().stats.alive = false; - w.unit_mut(3).unwrap().stats.set_buffs(vec![Buff { - flags: ["untargetable".into()].into_iter().collect(), - ..Buff::default() - }]); - assert_eq!( - json!(cache.targets(&mut w, &mut h, 1, p).unwrap()), - v["fallback"], - "fallback {}", - v["scenario"] - ); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 512); -} -#[test] -fn overflow_invalidates_previous_snapshot_and_empty_tick_replaces_it() { - let v = json!({"scenario":{"blocked":false,"extraTargets":0,"cooldown":0,"heal":false,"fortress":false,"maxTargets":5},"fixture":{"enemies":[3,4],"near":[],"extra":[],"nearExtra":[],"heal":[]}}); - let (mut w, mut h) = setup(&v); - let p = h.p; - let mut cache = Commitments::new(2, 4, 4).unwrap(); - cache.capture(&mut w, &mut h, &[1], 1.0 / 30.0).unwrap(); - assert!(!cache.targets(&mut w, &mut h, 1, p).unwrap().is_empty()); - h.fixture["enemies"] = json!([2, 3, 4, 5, 6]); - assert!(cache.capture(&mut w, &mut h, &[1], 1.0 / 30.0).is_err()); - assert!(cache.targets(&mut w, &mut h, 1, p).unwrap().is_empty()); - h.fixture["enemies"] = json!([3]); - cache.capture(&mut w, &mut h, &[1], 1.0 / 30.0).unwrap(); - cache.capture(&mut w, &mut h, &[], 1.0 / 30.0).unwrap(); - assert!(cache.targets(&mut w, &mut h, 1, p).unwrap().is_empty()); -} diff --git a/crates/engine/tests/settlement_reference.rs b/crates/engine/tests/settlement_reference.rs deleted file mode 100644 index 596cb86..0000000 --- a/crates/engine/tests/settlement_reference.rs +++ /dev/null @@ -1,286 +0,0 @@ -use arkguard_engine::{ - battle::{ - buffs::{self, Refresh, Runtime, Spec}, - damage::{Damage, DamageType, Penetration}, - health::{self, Hit, Side, Unit, World}, - hit::Request, - injury::{DodgeMode, InjuryEvent, Notice, Observation, Outcome}, - settlement::{self, Context}, - stats::{Base, Buff, UnitStats}, - }, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -fn kind(s: &str) -> DamageType { - match s { - "phys" => DamageType::Physical, - "arts" => DamageType::Arts, - "elemental" => DamageType::Elemental, - _ => DamageType::True, - } -} -fn spec(d: &Value) -> Spec { - let mut b = Buff { - key: d["key"].as_str().map(str::to_string), - stacks: d["stacks"].as_u64().unwrap_or(1) as u32, - shield: d["shield"].as_f64().unwrap_or(0.0), - ..Default::default() - }; - if let Some(m) = d["mods"].as_object() { - b.mods = m - .iter() - .map(|(k, v)| (k.clone(), v.as_f64().unwrap())) - .collect(); - } - b.runtime.duration = if d["duration"] == "inf" { - f64::INFINITY - } else { - d["duration"].as_f64().unwrap_or(f64::INFINITY) - }; - b.runtime.visible = d["visible"] == true; - b.runtime.shield_hits = d["shieldHits"].as_u64().unwrap_or(0) as u32; - b.runtime.refresh = match d["refresh"].as_str().unwrap_or("replace") { - "extend" => Refresh::Extend, - "stack" => Refresh::Stack, - _ => Refresh::Replace, - }; - b.runtime.max_stacks = d["maxStacks"].as_u64().unwrap_or(1) as u32; - b.runtime.on_remove = if d["remove"] == true { Some(9) } else { None }; - b.runtime.injury = buffs::Injury { - priority: d["injuryPriority"].as_f64().unwrap_or(0.0), - reduction: d["damageReduction"].as_object().map(|_| { - ["phys", "arts", "true", "elemental"] - .map(|k| d["damageReduction"][k].as_f64().unwrap_or(0.0)) - }), - reduction_group: d["reductionGroup"].as_str().map(str::to_string), - shield_types: d["shieldType"] - .as_array() - .map(|a| a.iter().map(|v| kind(v.as_str().unwrap())).collect()), - keep_empty_shield: d["keepEmptyShield"] == true, - on_injury: d["injury"].as_u64(), - observe: if d["observe"] == true { Some(1) } else { None }, - }; - Spec { - buff: b, - mods_present: d["mods"].is_object(), - flags_present: d["flags"].is_object(), - ..Default::default() - } -} -fn request(d: &Value) -> Request { - let mut r = Request::new( - Hit { - target: 1, - source: None, - credit: None, - damage_type: kind(d["type"].as_str().unwrap()), - no_sp: true, - silent: false, - hp_loss: false, - on_applied: false, - }, - Damage { - amount: d["amount"].as_f64().unwrap(), - mul: 1.0, - penetration: Penetration::default(), - resolved: false, - }, - ); - r.dodge_mode = match d["dodgeMode"].as_str().unwrap_or("normal") { - "ignore" => DodgeMode::Ignore, - "uncancellable" => DodgeMode::Uncancellable, - _ => DodgeMode::Normal, - }; - r.ignore_block = d["ignoreCancelReasons"] - .as_array() - .map(|a| a.iter().any(|v| v == "block")) - .unwrap_or(false); - r -} -struct Host { - trace: Vec, - nesting: bool, -} -impl health::Hooks for Host { - fn kill(&mut self, _: u64, _: Option, _: &mut World) -> Result<(), String> { - self.trace.push(json!(["kill"])); - Ok(()) - } -} -impl buffs::Hooks for Host { - fn status(&mut self, u: u64, key: &str, on: bool) -> Result<(), String> { - self.trace - .push(json!(["status", u, key, if on { 1 } else { 0 }])); - Ok(()) - } - fn callback( - &mut self, - token: u64, - _: buffs::Event, - c: buffs::Context, - r: &mut Runtime, - w: &mut World, - ) -> Result<(), String> { - assert_eq!(token, 9); - self.trace.push(json!([ - "remove", - c.buff, - bits(r.get(w, c.unit, c.buff)?.runtime.time_left) - ])); - Ok(()) - } -} -impl settlement::Hooks for Host { - fn injury(token: u64, e: &mut InjuryEvent, c: &mut Context<'_, Self>) -> Result<(), String> { - c.host.trace.push(json!(["injury", c.buff, bits(e.amount)])); - match token { - 1 => e.amount *= 0.7, - 2 => { - c.block(e, Some(0.2))?; - } - 3 => { - e.defer(7)?; - e.amount = (e.amount - 3.0).max(0.0); - } - 4 => { - if !c.host.nesting { - c.runtime.remove_id(c.world, c.host, 1, c.buff)?; - c.host.nesting = true; - let result = c.resolve(&mut request(&json!({"type":"true","amount":4}))); - c.host.nesting = false; - result?; - } - } - 5 => { - c.runtime.remove(c.world, c.host, 1, "b")?; - } - 6 => { - if !c - .world - .unit(1)? - .stats - .buffs() - .iter() - .any(|b| b.key.as_deref() == Some("late")) - { - c.runtime.add(c.world,c.host,1,spec(&json!({"key":"late","duration":0.3,"mods":{"dmgTakenMul":0.8},"observe":true})))?; - } - } - _ => unreachable!(), - } - Ok(()) - } - fn observe(_: u64, e: Observation, c: &mut Context<'_, Self>) -> Result<(), String> { - let attached = c - .world - .unit(1)? - .stats - .buffs() - .iter() - .any(|b| b.runtime.id() == c.buff); - let outcome = e.outcome.map(|o| match o { - Outcome::Zero => "zero", - Outcome::Blocked => "blocked", - Outcome::Dodged => "dodged", - }); - c.host.trace.push(json!([ - "observe", - c.buff, - bits(e.amount), - e.cancelled, - outcome, - attached - ])); - c.runtime.edit(c.world, 1, c.buff, |b| b.shield += 2.0) - } - fn damage_notice( - &mut self, - n: Notice, - _: f64, - _: &mut Request, - _: &mut Runtime, - _: &mut World, - _: &mut Rng, - ) -> Result<(), String> { - let (k, cancelled) = match n { - Notice::Block { cancelled } => ("block", cancelled), - Notice::Dodge { cancelled, .. } => ("dodge", cancelled), - }; - self.trace.push(json!([k, cancelled])); - Ok(()) - } - fn damage_cleanup(&mut self, token: u64, _: &mut Runtime, _: &mut World) -> Result<(), String> { - self.trace.push(json!(["cleanup", token])); - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; canonical buff/HP settlement"] -fn canonical_buffs_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/settlement.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let mut w = World::new(1, 1, 1).unwrap(); - let mut base = Base::default(); - for (k, n) in [("maxHp", 10000.0), ("def", 20.0), ("res", 30.0)] { - base.0.insert(k.into(), n); - } - let mut u = Unit::new(UnitStats::new(base), Side::Ally); - u.deployed = true; - w.insert_unit(1, u).unwrap(); - let mut r = Runtime::new(32, 256, 64).unwrap(); - let mut h = Host { - trace: vec![], - nesting: false, - }; - let mut rng = Rng::new(v["i"].as_u64().unwrap() as u32 + 1); - for d in v["descriptors"].as_array().unwrap() { - r.add(&mut w, &mut h, 1, spec(d)).unwrap(); - } - let mut states = vec![]; - for op in v["ops"].as_array().unwrap() { - let result = if let Some(dt) = op["tick"].as_f64() { - w.time += dt; - r.tick(&mut w, &mut h, &[1], dt).unwrap(); - None - } else if !op["add"].is_null() { - r.add(&mut w, &mut h, 1, spec(&op["add"])).unwrap(); - None - } else { - Some( - settlement::resolve(&mut w, &mut r, &mut rng, &mut h, &mut request(&op["hit"])) - .unwrap(), - ) - }; - let u = w.unit_mut(1).unwrap(); - let shield = u.stats.stats().unwrap().n("shield"); - states.push(json!({"result":result.map(bits),"hp":bits(u.stats.hp),"taken":bits(u.damage_taken),"rng":rng.state(),"shield":bits(shield),"buffs":u.stats.buffs().iter().map(|b|json!({"id":b.runtime.id(),"key":b.key,"stacks":b.stacks,"shield":bits(b.shield),"hits":b.runtime.shield_hits,"left":bits(b.runtime.time_left)})).collect::>()})); - } - for (j, (a, b)) in states - .iter() - .zip(v["states"].as_array().unwrap()) - .enumerate() - { - assert_eq!(a, b, "case {} step {j}", v["i"]); - } - assert_eq!(json!(h.trace), v["trace"], "trace {}", v["i"]); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 256); -} diff --git a/crates/engine/tests/skills_reference.rs b/crates/engine/tests/skills_reference.rs deleted file mode 100644 index 8c15392..0000000 --- a/crates/engine/tests/skills_reference.rs +++ /dev/null @@ -1,222 +0,0 @@ -use arkguard_engine::battle::{ - health::{Side, Unit, World}, - search::AttackProfile, - skills::{self, Condition, Context, Event, Rule, Runtime, SpType, Spec}, - sp::{Bank, Kind}, - stats::{Base, Buff, UnitStats}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Host { - d: Value, - trace: Vec, - installed: bool, - restarted: bool, -} -impl skills::Hooks for Host { - fn event( - &mut self, - event: Event, - c: &mut Context, - s: &mut Runtime, - w: &mut World, - ) -> Result<(), String> { - match event { - Event::ApplyModifiers => { - self.installed = true; - self.trace.push(json!(["add"])); - } - Event::RemoveModifiers => { - self.installed = false; - self.trace.push(json!(["remove"])); - } - Event::RefreshRange => self.trace.push(json!(["range"])), - Event::Start => self.trace.push(json!(["start", c.reason])), - Event::End => { - self.trace.push(json!(["end", c.reason, self.installed])); - if self.d["reactivate"] == true && !self.restarted && c.reason == "stopped" { - self.restarted = true; - s.activate(w, self, "restart", true)?; - } - } - Event::SkillStart => { - self.trace.push(json!(["skillStart"])); - if s.bank.kind == Kind::Ammo { - s.add_ammo(1.0); - } - } - Event::SkillEnd => self.trace.push(json!(["skillEnd"])), - Event::DisplayOn => self.trace.push(json!(["display", 1])), - Event::DisplayOff => self.trace.push(json!(["display", 0])), - Event::PassiveWindow => self.trace.push(json!(["after"])), - Event::Tick => { - self.trace.push(json!(["tick", bits(c.dt)])); - if self.d["tickExtend"] == true { - s.extend(0.1); - } - } - Event::Attack => { - self.trace.push(json!(["attack"])); - if self.d["freeAmmo"] == true { - c.no_ammo = true; - } - } - Event::AmmoUsed => self.trace.push(json!(["ammoUsed"])), - Event::SpGain => { - self.trace.push(json!(["gain", c.reason, bits(c.amount)])); - c.amount *= 0.75; - } - } - Ok(()) - } - fn condition(&mut self, c: Condition, _: &Runtime, _: &mut World) -> Result { - Ok(match c { - Condition::ExtraWithoutAttack => false, - _ => self.d["condition"] == true, - }) - } - fn profile(&mut self, _: u64, _: &mut World) -> Result, String> { - Ok(Some(AttackProfile { - no_attack: self.d["noAttack"] == true, - ..AttackProfile::default() - })) - } - fn has_sp_hook(&self) -> bool { - true - } -} -fn snap(s: &Runtime, w: &mut World) -> Value { - json!({"sp":bits(s.bank.sp),"charges":bits(s.bank.charges),"active":s.bank.active,"pending":s.pending,"time":bits(s.time_left),"ammo":bits(s.ammo_left),"maxAmmo":bits(s.ammo_max),"activations":s.activations,"last":bits(s.last_start),"op":bits(s.op_ready_at),"next":bits(s.next_cast_at),"attack":s.attack_override(),"targeting":s.targeting_override(),"total":bits(s.bank.total(w).unwrap())}) -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; skill lifecycle sequences"] -fn lifecycle_sequences_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/skills.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let d = &v["scenario"]; - let mut w = World::new(1, 1, 1).unwrap(); - let mut base = Base::default(); - base.0.insert("maxHp".into(), 100.0); - base.0.insert("atk".into(), 10.0); - let mut u = Unit::new(UnitStats::new(base), Side::Ally); - u.deployed = true; - w.insert_unit(1, u).unwrap(); - let none = d["noSkill"] == true; - let kind = if none { - Kind::Instant - } else { - match d["kind"].as_str().unwrap() { - "charges" => Kind::Charges, - "duration" => Kind::Duration, - "ammo" => Kind::Ammo, - "toggle" => Kind::Toggle, - "passive" => Kind::Passive, - _ => Kind::Instant, - } - }; - let mut bank = Bank::new(1, kind, 3.0, 2, 16).unwrap(); - bank.no_skill = none; - let spec = if none { - Spec::default() - } else { - Spec { - duration: d["duration"].as_f64().unwrap(), - ammo: 2.0, - init_sp: 6.0, - sp_type: match d["spType"].as_str().unwrap() { - "attack" => SpType::Attack, - "hurt" => SpType::Hurt, - "none" => SpType::None, - _ => SpType::Time, - }, - manual: d["manual"] == true, - rule: Rule::parse(d["rule"].as_str().unwrap()), - attack: d["attack"] == true, - targeting: d["targeting"] == true, - modifiers: d["mod"] == true, - range_change: d["targeting"] == true, - trigger_allies: d["allies"] == true, - activate_on_deploy: d["deploy"] == true, - on_tick: true, - on_attack: true, - ..Spec::default() - } - }; - let mut s = Runtime::new(bank, spec, 64).unwrap(); - let mut h = Host { - d: d.clone(), - trace: vec![], - installed: false, - restarted: false, - }; - s.reset(&mut w, &mut h, None).unwrap(); - w.unit_mut(1).unwrap().stats.set_buffs(vec![Buff { - flags: ["noSp", "stun", "silence"] - .into_iter() - .filter(|k| d[*k] == true) - .map(str::to_string) - .collect(), - ..Buff::default() - }]); - let mut states = vec![snap(&s, &mut w)]; - for op in 0..13 { - match op { - 0 => { - s.activate(&mut w, &mut h, "manual", false).unwrap(); - } - 1 => { - w.time = 1.0 / 30.0; - s.tick(&mut w, &mut h, 1.0 / 30.0).unwrap(); - } - 2 => s.after_attack(&mut w, &mut h, &[1], true, true).unwrap(), - 3 => s.after_attack(&mut w, &mut h, &[1], true, false).unwrap(), - 4 => { - s.add_ammo(2.0); - s.extend(0.2); - } - 5 => { - w.time = 0.5; - s.tick(&mut w, &mut h, 0.5).unwrap(); - } - 6 => s.end(&mut w, &mut h, "stopped").unwrap(), - 7 => { - s.activate(&mut w, &mut h, "free", true).unwrap(); - } - 8 => s.on_damaged(&mut w, &mut h).unwrap(), - 9 => { - s.about_to_attack(&mut w, &mut h).unwrap(); - } - 10 => { - w.time = 4.0; - s.tick(&mut w, &mut h, 0.1).unwrap(); - } - 11 => { - w.time = 5.0; - s.tick(&mut w, &mut h, 3.0).unwrap(); - } - _ => s.end(&mut w, &mut h, "death").unwrap(), - }; - states.push(snap(&s, &mut w)); - } - assert_eq!(json!(states), v["states"], "state {d}"); - assert_eq!(json!(h.trace), v["trace"], "events {d}"); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 384); -} diff --git a/crates/engine/tests/sp_reference.rs b/crates/engine/tests/sp_reference.rs deleted file mode 100644 index 2cfa1c6..0000000 --- a/crates/engine/tests/sp_reference.rs +++ /dev/null @@ -1,120 +0,0 @@ -use arkguard_engine::battle::{ - health::{Side, Unit, World}, - sp::{Bank, Hooks, Kind}, - stats::{Base, Buff, UnitStats}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Host { - enabled: bool, - mutate: bool, - trace: Vec, -} -impl Hooks for Host { - fn has_gain_hook(&self) -> bool { - self.enabled - } - fn gain(&mut self, a: &mut f64, r: &str, b: &mut Bank, w: &mut World) -> Result<(), String> { - self.trace.push(json!(["spGain", r, bits(*a)])); - *a *= 0.5; - if self.mutate { - b.set_multiplier(w, 0.5)?; - } - Ok(()) - } -} -fn snap(b: &Bank, w: &mut World, result: Option) -> Value { - json!({"result":result.map(bits),"sp":bits(b.sp),"charges":bits(b.charges),"cost":bits(b.cost(w).unwrap()),"total":bits(b.total(w).unwrap()),"ready":b.ready(),"mul":bits(b.cost_multiplier())}) -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; SP accounting only"] -fn charge_accounting_matches() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/sp.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let d = &v["scenario"]; - let mut w = World::new(1, 1, 1).unwrap(); - let mut u = Unit::new(UnitStats::new(Base::default()), Side::Ally); - u.deployed = true; - u.stats.set_buffs(vec![Buff { - mods: [("spCostFlat".into(), v["flat"].as_f64().unwrap())] - .into_iter() - .collect(), - flags: if d["noSp"] == true { - ["noSp".into()].into_iter().collect() - } else { - Default::default() - }, - ..Buff::default() - }]); - w.insert_unit(1, u).unwrap(); - let kind = if d["noSkill"] == true { - Kind::Instant - } else { - match d["kind"].as_str().unwrap() { - "charges" => Kind::Charges, - "duration" => Kind::Duration, - "ammo" => Kind::Ammo, - "toggle" => Kind::Toggle, - "passive" => Kind::Passive, - _ => Kind::Instant, - } - }; - let mut b = Bank::new( - 1, - kind, - d["cost"].as_f64().unwrap(), - d["charges"].as_u64().unwrap() as u32, - 32, - ) - .unwrap(); - b.no_skill = d["noSkill"] == true; - let mut h = Host { - enabled: d["hook"] == true, - mutate: d["mutate"] == true, - trace: vec![], - }; - b.set_total(&mut w, d["total"].as_f64().unwrap()).unwrap(); - b.active = d["active"] == true; - let mut states = vec![snap(&b, &mut w, None)]; - for (amount, reason, silent, ignore) in [ - (1.0 / 30.0, "time", false, false), - (5.0, "gift", false, true), - (3.0, "init", true, false), - ] { - let got = b - .gain(&mut w, &mut h, amount, reason, silent, ignore) - .unwrap(); - states.push(snap(&b, &mut w, Some(got))); - } - b.set_multiplier(&mut w, 0.7).unwrap(); - states.push(snap(&b, &mut w, None)); - b.set_total(&mut w, 7.5).unwrap(); - states.push(snap(&b, &mut w, None)); - b.add_charge(&mut w, 0.5).unwrap(); - states.push(snap(&b, &mut w, None)); - b.set_multiplier(&mut w, f64::NAN).unwrap(); - states.push(snap(&b, &mut w, None)); - b.gain(&mut w, &mut h, 100.0, "hurt", false, false).unwrap(); - states.push(snap(&b, &mut w, None)); - assert_eq!(json!(states), v["states"], "case {d}"); - assert_eq!(json!(h.trace), v["trace"]); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 768); -} diff --git a/crates/engine/tests/spawns_reference.rs b/crates/engine/tests/spawns_reference.rs deleted file mode 100644 index 767609a..0000000 --- a/crates/engine/tests/spawns_reference.rs +++ /dev/null @@ -1,394 +0,0 @@ -//! A headless native tick composition, against actual Battle.step. Content is -//! disabled on both sides; this does not certify any enemy's special ability. -use arkguard_engine::{ - battle::{ - blocking, body, buffs, - clock::{self, Clock, End, EndState, Phase, DT}, - enemy::{self, Delivery, Profile}, - grid::{Grid, Rect}, - health::{self, Id, World}, - motion, settlement, - spatial::{self, RadiusRule}, - spawns, - targeting::Queries, - waves::Template, - }, - data::Catalog, - deterministic::rng::Rng, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, - sync::Arc, -}; -fn bits(n: f64) -> String { - format!("{:016x}", n.to_bits()) -} -struct Host { - spawns: Option, - released: Vec, -} -impl Host { - fn remove(&mut self, id: Id, killed: bool, w: &mut World) -> Result<(), String> { - if killed { - self.spawns.as_mut().unwrap().ledger.kill(id, false)?; - } else { - self.spawns.as_mut().unwrap().ledger.leak(id)?; - } - enemy::clear(w, id)?; - let time = w.time; - let u = w.unit_mut(id)?; - u.stats.alive = false; - u.deployed = false; - u.removed = true; - u.deployment.death_at = time; - u.deployment.remove_reason = Some(if killed { "killed" } else { "leak" }.into()); - if killed { - u.stats.hp = 0.; - } - Ok(()) - } -} -impl spawns::Hooks for Host { - fn spawned(&mut self, id: Id, w: &mut World, r: &mut spawns::Runtime) -> Result<(), String> { - assert_eq!(r.definition(id)?.key, r.ledger.alive()[&id].key); - assert!(w.unit(id)?.deployed); - Ok(()) - } - fn release(&mut self, id: Id, _: &mut World) -> Result<(), String> { - assert!(!self.released.contains(&id)); - self.released.push(id); - Ok(()) - } -} -impl health::Hooks for Host { - fn kill(&mut self, id: Id, _: Option, w: &mut World) -> Result<(), String> { - self.remove(id, true, w) - } -} -impl buffs::Hooks for Host { - fn status(&mut self, _: Id, _: &str, _: bool) -> Result<(), String> { - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut buffs::Runtime, - _: &mut World, - ) -> Result<(), String> { - Err("No content callbacks in bare reference".into()) - } -} -impl settlement::Hooks for Host {} -impl blocking::Hooks for Host { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Err("No blockers in fixture".into()) - } - fn ended(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl motion::Hooks for Host { - fn check_block(&mut self, _: Id, _: &mut World, _: &mut Grid) -> Result { - Ok(false) - } - fn hidden(&mut self, id: Id, on: bool, w: &mut World) -> Result<(), String> { - w.unit_mut(id)?.hidden = on; - Ok(()) - } - fn cut_attack_stand(&mut self, id: Id, w: &mut World) -> Result<(), String> { - w.unit_mut(id)?.motion.attack_stand_until = f64::NEG_INFINITY; - Ok(()) - } - fn leak(&mut self, id: Id, w: &mut World) -> Result<(), String> { - self.remove(id, false, w) - } -} -impl Queries for Host { - fn enemy_stealthed(&mut self, _: Id, _: &mut World) -> Result { - Ok(false) - } - fn skip_enemy(&mut self, _: Option, _: Id, _: &mut World) -> Result { - Ok(false) - } - fn remaining_distance(&mut self, _: Id, _: &mut World) -> Result { - Err("No allied priority selector in fixture".into()) - } - fn body_distance(&mut self, id: Id, p: [f64; 2], w: &mut World) -> Result { - Ok(body::distance(w.unit(id)?, p)) - } -} -impl enemy::Hooks for Host { - fn profile(&mut self, id: Id, _: &mut World) -> Result { - Ok(self - .spawns - .as_ref() - .unwrap() - .definition(id)? - .profile - .clone()) - } - fn allies_in_radius( - &mut self, - _: Id, - _: f64, - _: &mut World, - _: usize, - ) -> Result, String> { - Ok(vec![]) - } - fn enemies_in_radius( - &mut self, - id: Id, - radius: f64, - w: &mut World, - limit: usize, - ) -> Result, String> { - let ids = self.spawns.as_ref().unwrap().live().to_vec(); - let p = w.unit(id)?.position; - spatial::enemies_in_radius(w, self, &ids, p, radius, RadiusRule::Body, false, limit) - } - fn can_target(&mut self, _: Id, _: Id, _: &mut World) -> Result { - Ok(true) - } - fn enemy_event_enabled(&self, _: enemy::Event) -> bool { - false - } - fn enemy_event( - &mut self, - _: enemy::Event, - _: &mut enemy::Context, - _: &mut buffs::Runtime, - _: &mut World, - _: &mut Grid, - _: &mut Rng, - ) -> Result<(), String> { - Err("No content in fixture".into()) - } - fn attack_visual(&mut self, _: Id, _: Id, _: &str) -> Result<(), String> { - Ok(()) - } - fn palsy_visual(&mut self, _: Id, _: &World) -> Result<(), String> { - Ok(()) - } - fn deliver( - &mut self, - _: Delivery, - _: &mut buffs::Runtime, - _: &mut World, - _: &mut Rng, - ) -> Result<(), String> { - Err("No allied targets in fixture".into()) - } -} -struct Field { - world: World, - grid: Grid, - buffs: buffs::Runtime, - rng: Rng, - host: Host, - time_limit: f64, -} -impl clock::Host for Field { - fn phase(&mut self, p: Phase, c: &mut Clock) -> Result<(), String> { - self.world.time = c.time(); - match p { - Phase::Start => c.mark_started(), - Phase::Spawns => { - let mut r = self.host.spawns.take().unwrap(); - let result = r.process(&mut self.world, &self.grid, &mut self.host); - self.host.spawns = Some(r); - result?; - } - Phase::Buffs => { - let ids = self.host.spawns.as_ref().unwrap().live().to_vec(); - self.buffs.tick(&mut self.world, &mut self.host, &ids, DT)?; - } - Phase::Enemies => { - let ids = self.host.spawns.as_ref().unwrap().live().to_vec(); - for id in ids { - enemy::update( - &mut self.world, - &mut self.grid, - &mut self.buffs, - &mut self.rng, - &mut self.host, - id, - DT, - 512, - )?; - let u = self.world.unit_mut(id)?; - let r = self.grid.rect(); - let m = 0.5 - 1. / 1048576.; - u.position[0] = u.position[0].max(r.r0 as f64 - m).min(r.r1 as f64 + m); - u.position[1] = u.position[1].max(r.c0 as f64 - m).min(r.c1 as f64 + m); - } - } - _ => {} - } - Ok(()) - } - fn compact_enemies(&mut self, _: &mut Clock) -> Result<(), String> { - self.host.spawns.as_mut().unwrap().compact(&self.world) - } - fn has_removed(&self) -> bool { - true - } - fn release_removed(&mut self, _: &mut Clock) -> Result<(), String> { - let mut r = self.host.spawns.take().unwrap(); - let result = r.release_removed(&mut self.world, &mut self.host); - self.host.spawns = Some(r); - result - } - fn has_tick_hook(&self) -> bool { - false - } - fn end_state(&self) -> Option { - let r = self.host.spawns.as_ref().unwrap(); - Some(EndState { - shared_hp: None, - boss_like: false, - auto_finish: true, - pending_spawns: !r.queue.pending().is_empty(), - enemy_alive: !r.live().is_empty(), - pending_holds: false, - time_limit: self.time_limit, - max_battle_time: 3600., - }) - } - fn finish(&mut self, reason: &End, _: &Clock) -> Result<(), String> { - if *reason == End::Timeout { - let r = self.host.spawns.as_mut().unwrap(); - r.ledger.timeout(&mut r.queue)?; - } - Ok(()) - } -} -fn view(f: &Field, c: &Clock) -> Value { - let r = f.host.spawns.as_ref().unwrap(); - let reason = c.reason().map(|r| match r { - End::Cleared => "cleared", - End::Timeout => "timeout", - End::Forced => "forced", - }); - let units:Vec<_>=r.live().iter().map(|&id|{let u=f.world.unit(id).unwrap();json!({"id":id,"key":r.definition(id).unwrap().key,"pos":u.position.map(bits),"hp":bits(u.stats.hp),"cd":bits(u.cadence.cooldown),"hidden":u.hidden,"moving":u.moving,"leg":u.motion.route.as_ref().unwrap().leg,"spawn":u.targeting.spawn_seq,"deploy":u.deployment.deploy_seq})}).collect(); - json!({"time":bits(c.time()),"ticks":c.ticks(),"finished":c.finished(),"reason":reason,"pending":r.queue.pending().len(),"sequence":r.queue.sequence(),"units":units,"report":r.ledger.report(c.time(),reason)}) -} -fn canonical(v: &mut Value) { - match v { - Value::Number(n) => { - let x = n.as_f64().unwrap(); - if x.fract() == 0. && x.abs() < i64::MAX as f64 { - *v = json!(x as i64); - } - } - Value::Array(a) => a.iter_mut().for_each(canonical), - Value::Object(o) => o.values_mut().for_each(canonical), - _ => {} - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; native spawn/buff/enemy/tick/end composition"] -fn native_spawn_to_result_matches_headless_battle() { - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap(); - let data = Arc::new(Catalog::load(&Path::new(&root).join("data"), 64 << 20).unwrap()); - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/spawns.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(root) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut cases = 0; - let mut ticks = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let o = &v["options"]; - let mut stage = data.table("stages").unwrap()[o["stageId"].as_str().unwrap()].clone(); - stage["legend"] = stage["tiles"].clone(); - let rect = Rect::NORMAL; - let grid = Grid::new(&stage, rect).unwrap(); - let mut template = Template::parse( - &json!({"spawns":o["spawns"],"routes":o["routes"],"overrides":o["enemyOverrides"]}), - &Value::Null, - &Value::Null, - 512, - 256, - ) - .unwrap(); - // This oracle supplies Battle's explicit SpawnSpecs, rather than calling - // spawnsFromTemplate (which deliberately has a narrower input contract). - template.spawns = o["spawns"].as_array().unwrap().clone(); - let spawns = - spawns::Runtime::new(&data, template, &grid, json!("p"), 512, 512, 256).unwrap(); - let mut f = Field { - world: World::new(512, 1, 1).unwrap(), - grid, - buffs: buffs::Runtime::new(64, 512, 32).unwrap(), - rng: Rng::new(o["seed"].as_u64().unwrap() as u32), - host: Host { - spawns: Some(spawns), - released: vec![], - }, - time_limit: o["timeLimit"].as_f64().unwrap(), - }; - let mut c = Clock::new(); - for (t, expected) in v["states"].as_array().unwrap().iter().enumerate() { - if t == 6 { - for id in f.host.spawns.as_ref().unwrap().live() { - f.world.unit_mut(*id).unwrap().stats.hp *= 0.5; - } - } - for op in v["ops"] - .as_array() - .unwrap() - .iter() - .filter(|o| o["tick"].as_u64() == Some(t as u64)) - { - match op["op"].as_str().unwrap() { - "spawn" => { - let mut r = f.host.spawns.take().unwrap(); - r.spawn( - &mut f.world, - &f.grid, - &mut f.host, - op["key"].as_str().unwrap(), - &op["def"], - ) - .unwrap(); - f.host.spawns = Some(r); - } - "kill" => f - .host - .remove(op["id"].as_u64().unwrap(), true, &mut f.world) - .unwrap(), - _ => unreachable!(), - } - } - c.step(&mut f).unwrap(); - let mut actual = view(&f, &c); - let mut expected = expected.clone(); - canonical(&mut actual); - canonical(&mut expected); - assert_eq!(actual, expected, "case {cases} tick {t}"); - ticks += 1; - // Zero budget is a genuine pause, including immediately before termination. - assert_eq!(c.run_steps(&mut f, 0).unwrap(), 0); - } - let owned = view(&f, &c); - let before = owned.clone(); - if !c.finished() { - c.run_steps(&mut f, 3).unwrap(); - } - assert_eq!(owned, before); - assert!(!f.host.spawns.as_ref().unwrap().faulted()); - cases += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(cases, 40); - eprintln!("{cases} headless battle timelines; {ticks} ticks"); -} diff --git a/crates/engine/tests/stats_reference.rs b/crates/engine/tests/stats_reference.rs deleted file mode 100644 index 39bc6c8..0000000 --- a/crates/engine/tests/stats_reference.rs +++ /dev/null @@ -1,151 +0,0 @@ -use arkguard_engine::battle::{ - damage::{self, Damage, DamageType, Penetration}, - stats::{Base, Buff, Cultivation, Numbers, Stats, UnitStats}, -}; -use serde_json::Value; -use std::{ - collections::{BTreeMap, BTreeSet}, - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn numbers(v: &Value) -> Numbers { - v.as_object() - .unwrap() - .iter() - .map(|(k, v)| (k.clone(), v.as_f64().unwrap())) - .collect() -} -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -fn same(x: f64, v: &Value) { - let expected = u64::from_str_radix(v.as_str().unwrap(), 16).unwrap(); - if f64::from_bits(expected).is_nan() { - assert!(x.is_nan()); - } else { - assert_eq!(bits(x), v.as_str().unwrap(), "{x}"); - } -} -fn check(s: &Stats, v: &Value) { - assert_eq!(s.numbers.len(), v["numbers"].as_object().unwrap().len()); - for (k, &x) in &s.numbers { - same(x, &v["numbers"][k]); - } - assert_eq!(serde_json::json!(s.flags), v["flags"]); -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; numeric formulas only"] -fn stats_and_damage_match_bits() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/stats.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let mut base = Base::default(); - base.0.extend(numbers(&v["base"])); - let hp = base.0["maxHp"] * 0.37; - let mut u = UnitStats::new(base); - u.hp = hp; - u.set_cultivation(Cultivation { - hp: v["cm"]["hp"].as_f64().unwrap(), - atk: v["cm"]["atk"].as_f64().unwrap(), - def: v["cm"]["def"].as_f64().unwrap(), - }); - u.set_move_floor(v["floor"].as_f64().unwrap()); - u.set_buffs( - v["buffs"] - .as_array() - .unwrap() - .iter() - .map(|b| Buff { - key: None, - mods: numbers(&b["mods"]), - flags: b["flags"] - .as_object() - .unwrap() - .iter() - .filter(|(_, v)| v.as_bool().unwrap()) - .map(|(k, _)| k.clone()) - .collect(), - stacks: b["stacks"].as_u64().unwrap() as u32, - shield: b["shield"].as_f64().unwrap(), - permanent: b["permanent"] == true, - ..Buff::default() - }) - .collect(), - ); - let s = u.stats().unwrap().clone(); - check(&s, &v["first"]); - same(u.hp, &v["hp"]); - u.set_buffs(vec![]); - check(u.stats().unwrap(), &v["second"]); - same(u.hp, &v["hpAfter"]); - let target = Stats { - numbers: ["def", "res"] - .into_iter() - .map(|name| { - let value = &v["target"]["numbers"][name]; - ( - name, - f64::from_bits(u64::from_str_radix(value.as_str().unwrap(), 16).unwrap()), - ) - }) - .collect::>(), - flags: BTreeSet::new(), - }; - let d = &v["dmg"]; - let dmg = Damage { - amount: d["amount"].as_f64().unwrap(), - mul: d["mul"].as_f64().unwrap(), - resolved: d["calculation"] == "resolved", - penetration: Penetration { - def_flat: d["defIgnoreFlat"].as_f64().unwrap(), - def_pct: d["defIgnorePct"].as_f64().unwrap(), - res_flat: d["resIgnoreFlat"].as_f64().unwrap(), - res_pct: d["resIgnorePct"].as_f64().unwrap(), - }, - }; - let ep = v["ep"].as_f64().unwrap(); - for expected in v["damages"].as_array().unwrap() { - let kind = match expected["type"].as_str().unwrap() { - "phys" => DamageType::Physical, - "arts" => DamageType::Arts, - "true" => DamageType::True, - _ => DamageType::Elemental, - }; - same( - damage::mitigate(dmg.amount, kind, &target, dmg.penetration, ep), - &expected["mitigate"], - ); - same( - damage::attack_input(dmg.amount, kind, &s), - &expected["input"], - ); - same( - damage::expected(dmg, kind, &target, ep), - &expected["expected"], - ); - same( - damage::calculate(dmg, kind, &target, Some(&s), ep), - &expected["base"], - ); - same( - damage::calculate(dmg, kind, &target, None, ep), - &expected["noSource"], - ); - same( - damage::estimate(dmg.amount, kind, &s), - &expected["estimate"], - ); - } - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 768); -} diff --git a/crates/engine/tests/status_reference.rs b/crates/engine/tests/status_reference.rs deleted file mode 100644 index 959d0a0..0000000 --- a/crates/engine/tests/status_reference.rs +++ /dev/null @@ -1,253 +0,0 @@ -use arkguard_engine::battle::{ - blocking, - buffs::{self, Refresh, Runtime, Spec}, - grid::Rect, - health::{self, Side, Unit, World}, - stats::{Base, Buff, UnitStats}, - status::{self, Options}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Host { - cfg: Value, - trace: Vec, -} -impl health::Hooks for Host { - fn kill(&mut self, _: u64, _: Option, _: &mut World) -> Result<(), String> { - unreachable!() - } -} -impl blocking::Hooks for Host { - fn blocked(&mut self, _: u64, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: u64, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl buffs::Hooks for Host { - fn status(&mut self, u: u64, key: &str, on: bool) -> Result<(), String> { - self.trace - .push(json!(["status", u, key, if on { 1 } else { 0 }])); - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } -} -impl status::Hooks for Host { - fn has_before_status(&self) -> bool { - self.cfg["before"] == true - } - fn before_status( - &mut self, - c: &mut status::Context, - _: &mut Runtime, - w: &mut World, - ) -> Result<(), String> { - self.trace.push(json!([ - "before", - c.key, - bits(c.duration), - c.value.map(bits) - ])); - let i = self.cfg["i"].as_u64().unwrap(); - if i % 17 == 0 { - c.cancelled = true; - } - if i % 19 == 0 { - w.unit_mut(1)?.stats.alive = false; - } - if i % 5 == 0 { - c.duration *= 0.5; - } - if i % 7 == 0 { - c.value = Some(0.8); - } - if i % 11 == 0 { - c.duration = f64::NAN; - } - Ok(()) - } - fn has_status_applied(&self) -> bool { - true - } - fn status_applied( - &mut self, - c: &status::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - self.trace.push(json!([ - "applied", - c.key, - bits(c.duration), - c.value.map(bits), - c.entered - ])); - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; all catalogue status applications"] -fn catalogue_statuses_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/status.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let c = &v["cfg"]; - let mut w = World::new(2, 1, 1).unwrap(); - let side = if c["side"] == "ally" { - Side::Ally - } else { - Side::Enemy - }; - let mut base = Base::default(); - for (k, n) in [ - ("maxHp", 1000.0), - ("atk", 100.0), - ("def", 100.0), - ("res", 30.0), - ("massLevel", c["mass"].as_f64().unwrap()), - ] { - base.0.insert(k.into(), n); - } - let mut u = Unit::new(UnitStats::new(base), side); - u.position = [10.0, 6.0]; - u.deployed = true; - u.motion_fly = c["fly"] == true; - u.immune = c["immune"] - .as_array() - .unwrap() - .iter() - .map(|v| v.as_str().unwrap().into()) - .collect(); - w.insert_unit(1, u).unwrap(); - let mut u = Unit::new( - UnitStats::new(Base::default()), - if side == Side::Ally { - Side::Enemy - } else { - Side::Ally - }, - ); - u.position = [9.5, 4.5]; - u.motion_fly = c["sourceFly"] == true; - u.deployed = true; - w.insert_unit(2, u).unwrap(); - let mut r = Runtime::new(128, 1024, 64).unwrap(); - let mut h = Host { - cfg: c.clone(), - trace: vec![], - }; - let initial = Buff { - key: Some("initial".into()), - flags: v["flags"] - .as_object() - .unwrap() - .iter() - .filter(|(_, v)| **v == true) - .map(|(k, _)| k.clone()) - .collect(), - ..Default::default() - }; - r.add( - &mut w, - &mut h, - 1, - Spec { - buff: initial, - flags_present: true, - ..Default::default() - }, - ) - .unwrap(); - let mut states = vec![]; - for op in v["ops"].as_array().unwrap() { - let accepted = if let Some(dt) = op["tick"].as_f64() { - w.time += dt; - r.tick(&mut w, &mut h, &[1, 2], dt).unwrap(); - None - } else { - Some( - status::apply( - &mut w, - &mut h, - &mut r, - Rect { - r0: 2, - r1: 16, - c0: 3, - c1: 17, - }, - 1, - op["key"].as_str().unwrap(), - Options { - duration: if op["duration"] == "inf" { - f64::INFINITY - } else { - op["duration"].as_f64().unwrap() - }, - value: op["value"].as_f64(), - source: op["source"].as_u64(), - force: op["force"] == true, - refresh: op["refresh"].as_str().map(|s| match s { - "replace" => Refresh::Replace, - "keep" => Refresh::Keep, - _ => Refresh::Extend, - }), - point: op["point"] - .as_array() - .map(|p| [p[0].as_f64().unwrap(), p[1].as_f64().unwrap()]), - resist_applied: op["resistApplied"] == true, - stack_as: op["stackAs"].as_f64(), - reenter: op["reenter"] == true, - ignore_select: op["ignoreSelect"] == true, - }, - ) - .unwrap(), - ) - }; - let resist = status::resist_of(&w, 1).unwrap(); - let u = w.unit_mut(1).unwrap(); - let s = u.stats.stats().unwrap(); - let stats: Vec<_> = ["atk", "def", "res", "moveSpeed", "dmgTakenMul", "aspd"] - .into_iter() - .map(|k| bits(s.n(k))) - .collect(); - let flags: Vec<_> = s.flags.iter().cloned().collect(); - states.push(json!({"accepted":accepted,"alive":u.stats.alive,"resist":bits(resist),"stats":stats,"flags":flags,"buffs":u.stats.buffs().iter().map(|b|json!({"id":b.runtime.id(),"key":b.key,"stacks":b.stacks,"left":bits(b.runtime.time_left),"duration":bits(b.runtime.duration),"acc":bits(b.runtime.accumulator),"attract":b.runtime.attract,"fear":b.runtime.fear.map(|f|json!({"seq":f.sequence,"hit":f.hit.map(bits),"source":f.source.map(bits),"self":f.self_fear}))})).collect::>()})); - } - for (j, (a, b)) in states - .iter() - .zip(v["states"].as_array().unwrap()) - .enumerate() - { - assert_eq!(a, b, "case {} operation {j}", c["i"]); - } - assert_eq!(json!(h.trace), v["trace"], "trace {}", c["i"]); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 384); -} diff --git a/crates/engine/tests/targeting_reference.rs b/crates/engine/tests/targeting_reference.rs deleted file mode 100644 index 71e053f..0000000 --- a/crates/engine/tests/targeting_reference.rs +++ /dev/null @@ -1,242 +0,0 @@ -use arkguard_engine::{ - battle::{ - blocking, cadence, - deploy::{self, Deployment, Options}, - direction::Direction, - health::{Id, Side, Unit, World}, - stats::{Base, Buff, UnitStats}, - targeting::{self, Priority, Profile, Queries}, - }, - deterministic::math::hypot, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -struct Context { - records: Vec, - skip: bool, -} -impl Queries for Context { - fn enemy_stealthed(&mut self, id: Id, w: &mut World) -> Result { - let e = w.unit_mut(id)?; - let f = &e.stats.stats().map_err(str::to_string)?.flags; - Ok(f.contains("stealth") && !f.contains("reveal") && e.blocked_by().is_none()) - } - fn skip_enemy(&mut self, _: Option, id: Id, _: &mut World) -> Result { - Ok(self.skip && id == 6) - } - fn remaining_distance(&mut self, id: Id, _: &mut World) -> Result { - Ok(self.records[id as usize - 1]["remaining"] - .as_f64() - .unwrap_or(f64::INFINITY)) - } - fn body_distance(&mut self, id: Id, origin: [f64; 2], w: &mut World) -> Result { - let p = w.unit(id)?.position; - Ok(hypot(p[1] - origin[1], p[0] - origin[0])) - } -} -struct Host; -impl blocking::Hooks for Host { - fn blocked(&mut self, _: Id, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } - fn ended(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -impl deploy::Hooks for Host { - fn initialize( - &mut self, - _: Id, - _: Options, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn event( - &mut self, - _: deploy::Event, - _: Id, - _: Option, - _: &mut World, - _: &mut Deployment, - ) -> Result<(), String> { - Ok(()) - } - fn remove_temporary_effects(&mut self, _: Id, _: &mut World) -> Result<(), String> { - Ok(()) - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; targeting and cadence only"] -fn filters_priorities_and_commit_gate_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/targeting.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut targets = 0; - let mut cadence_cases = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - if v["cadence"] == true { - let p = &v["profile"]; - let state = cadence::State { - cooldown: v["cd"].as_f64().unwrap(), - had_target: v["had"].as_bool(), - }; - let profile = cadence::Profile { - no_attack: p["noAttack"] == true, - only_while_skill: p["noAttackUnlessSkill"] == true, - heal_attack: p["dmgType"] == "heal", - all_in_range: p["allInRange"] == true, - range_aoe: p["rangeAoe"] == true, - }; - assert_eq!( - state.may_commit( - 1.0 / 30.0, - v["act"] == true, - v["disarm"] == true, - v["active"] == true, - profile - ), - v["commit"] == true, - "{v}" - ); - assert_eq!( - cadence::countdown(state.cooldown, 1.0 / 30.0).to_bits(), - v["countdown"].as_f64().unwrap().to_bits() - ); - cadence_cases += 1; - continue; - } - let records = v["records"].as_array().unwrap().clone(); - let mut w = World::new(6, 1, 1).unwrap(); - let mut dep = - Deployment::new(arkguard_engine::battle::grid::Rect::FULL, 6, 1, 99.0).unwrap(); - for d in &records { - let id = d["id"].as_u64().unwrap(); - let mut base = Base::default(); - base.0.extend( - d["base"] - .as_object() - .unwrap() - .iter() - .map(|(k, v)| (k.clone(), v.as_f64().unwrap())), - ); - if id == 1 { - base.0.insert("blockCnt".into(), 10.0); - } - let mut u = Unit::new( - UnitStats::new(base), - if id == 1 { Side::Ally } else { Side::Enemy }, - ); - u.position = [10.0, 4.0]; - u.deployment.home = [10, 4]; - u.deployment.kind = deploy::Kind::Operator; - u.ground = true; - u.deployed = true; - w.insert_unit(id, u).unwrap(); - } - dep.register(1, &w).unwrap(); - w.unit_mut(1).unwrap().deployed = false; - dep.deploy(&mut w, &mut Host, 1, Options::default()) - .unwrap(); - let grid = arkguard_engine::battle::grid::Grid::new( - &json!({"rows":vec!["r".repeat(21);19]}), - arkguard_engine::battle::grid::Rect::FULL, - ) - .unwrap(); - assert!(blocking::check(&mut w, &dep, &grid, &mut Host, 2).unwrap()); - for d in &records { - let id = d["id"].as_u64().unwrap(); - let u = w.unit_mut(id).unwrap(); - u.position = [d["y"].as_f64().unwrap(), d["x"].as_f64().unwrap()]; - u.stats.hp = d["hp"].as_f64().unwrap(); - u.stats.alive = d["alive"] == true; - u.deployed = d["deployed"] == true; - u.hidden = d["hidden"] == true; - u.motion_fly = d["motion"] == "FLY"; - u.targeting.spawn_seq = d["spawn"].as_u64().unwrap(); - u.targeting.elite = d["elite"] == true; - u.targeting.ranged_apply_melee = d["apply"] == "MELEE"; - u.boss = d["boss"] == true; - u.deployment.deploy_seq = id; - u.deployment.aggro_seq = d["aggro"].as_u64().unwrap(); - u.stats.set_buffs(vec![Buff { - flags: d["flags"].as_object().unwrap().keys().cloned().collect(), - ..Buff::default() - }]); - } - w.unit_mut(1).unwrap().targeting.doll = v["doll"] == true; - let p = &v["profile"]; - let profile = Profile { - hit_sleep: p["hitSleep"] == true, - can_hit_fly: p["canHitFly"] == true, - doll_hits_fly: p["dollHitsFly"] == true, - ground_only: p["groundOnly"] == true, - block_free: p["blockFree"] == true, - }; - let mut ctx = Context { - records, - skip: p["skip"] == true, - }; - let priorities = [ - Priority::None, - Priority::Fly, - Priority::LowDef, - Priority::HighDef, - Priority::Ranged, - Priority::LowestHp, - Priority::HighestHp, - Priority::LowestHpRatio, - Priority::HighestAtk, - Priority::Boss, - Priority::Elite, - Priority::NotBurst, - Priority::Ground, - Priority::Heaviest, - Priority::Nearest, - Priority::Farthest, - ]; - for (i, priority) in priorities.into_iter().enumerate() { - let mut c = [2, 3, 4, 5, 6]; - targeting::sort_enemies(&mut w, &mut ctx, 1, &mut c, priority).unwrap(); - assert_eq!( - json!(c), - v["enemyOrder"][i], - "sort {priority:?} case {}", - v["i"] - ); - } - let mut allies = [5, 1, 4, 3]; - targeting::sort_allies(&mut w, 2, &mut allies, profile).unwrap(); - assert_eq!(json!(allies), v["allyOrder"]); - for expected in v["filters"].as_array().unwrap() { - let id = expected["id"].as_u64().unwrap(); - let actual = json!({"id":id,"enemy":targeting::can_target_enemy(&mut w,&mut ctx,Some(1),id,profile).unwrap(),"ally":targeting::can_target_ally(&mut w,2,id,true,profile).unwrap(),"aura":targeting::aura_selectable(&mut w,id).unwrap(),"area":targeting::area_selectable(&mut w,Some(2),id).unwrap()}); - assert_eq!(actual, *expected, "filter case {}", v["i"]); - } - for (i, dir) in Direction::ALL.into_iter().enumerate() { - assert_eq!( - json!(targeting::absolute_range( - &[[0, 0], [1, 1], [0, 1], [1, -1], [0, 0]], - [10, 4], - dir, - (v["i"].as_u64().unwrap() % 24) as u32 - )), - v["ranges"][i] - ); - } - targets += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(targets, 512); - assert_eq!(cadence_cases, 1024); -} diff --git a/crates/engine/tests/valued_reference.rs b/crates/engine/tests/valued_reference.rs deleted file mode 100644 index 352c191..0000000 --- a/crates/engine/tests/valued_reference.rs +++ /dev/null @@ -1,196 +0,0 @@ -use arkguard_engine::battle::{ - buffs::{self, Runtime, Spec}, - health::{self, Side, Unit, World}, - stats::{Base, Buff, UnitStats}, - valued::{self, Kind, Request}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(x: f64) -> String { - format!("{:016x}", x.to_bits()) -} -struct Host { - trace: Vec, -} -impl health::Hooks for Host { - fn kill(&mut self, _: u64, _: Option, _: &mut World) -> Result<(), String> { - unreachable!() - } -} -impl buffs::Hooks for Host { - fn status(&mut self, u: u64, key: &str, on: bool) -> Result<(), String> { - self.trace - .push(json!(["status", u, key, if on { 1 } else { 0 }])); - Ok(()) - } - fn callback( - &mut self, - _: u64, - _: buffs::Event, - _: buffs::Context, - _: &mut Runtime, - _: &mut World, - ) -> Result<(), String> { - unreachable!() - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; strongest-effect timelines"] -fn strongest_timelines_match() { - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/valued.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut count = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let v: Value = serde_json::from_str(&line.unwrap()).unwrap(); - let name = v["name"].as_str().unwrap(); - let kind = match name { - "slow" => Kind::Slow, - "fragile" => Kind::Fragile, - "artsFragile" => Kind::ArtsFragile, - "physFragile" => Kind::PhysFragile, - "elemFragile" => Kind::ElemFragile, - "weaken" => Kind::Weaken, - "aspdDown" => Kind::AspdDown, - "defDown" => Kind::DefDown, - "resDown" => Kind::ResDown, - "resist" => Kind::Resist, - _ => Kind::Custom(|v| [("atkPct".into(), v)].into_iter().collect()), - }; - let mut w = World::new(1, 1, 1).unwrap(); - let mut base = Base::default(); - for (k, x) in [ - ("maxHp", 1000.0), - ("atk", 100.0), - ("def", 100.0), - ("res", 30.0), - ("moveSpeed", 1.0), - ] { - base.0.insert(k.into(), x); - } - let mut u = Unit::new(UnitStats::new(base), Side::Ally); - u.deployed = true; - w.insert_unit(1, u).unwrap(); - let mut r = Runtime::new(64, 256, 64).unwrap(); - let mut h = Host { trace: vec![] }; - if name == "resist" { - let mut b = Buff { - key: Some("palsy".into()), - stacks: 3, - ..Default::default() - }; - b.runtime.status = Some("palsy".into()); - b.runtime.visible = true; - b.runtime.max_stacks = 3; - r.add( - &mut w, - &mut h, - 1, - Spec { - buff: b, - ..Default::default() - }, - ) - .unwrap(); - } - let mut states = vec![]; - for op in v["ops"].as_array().unwrap() { - match op["op"].as_str().unwrap() { - "tick" => { - let dt = op["dt"].as_f64().unwrap(); - w.time += dt; - r.tick(&mut w, &mut h, &[1], dt).unwrap(); - } - "remove" => { - r.remove(&mut w, &mut h, 1, name).unwrap(); - } - "raw" => { - let mut b = Buff { - key: Some(name.into()), - mods: [("atkPct".into(), 0.01)].into_iter().collect(), - ..Default::default() - }; - b.runtime.status = if name == "plain" { - None - } else { - Some(name.into()) - }; - b.runtime.duration = op["duration"].as_f64().unwrap(); - r.add( - &mut w, - &mut h, - 1, - Spec { - buff: b, - mods_present: true, - ..Default::default() - }, - ) - .unwrap(); - } - _ => { - valued::apply( - &mut w, - &mut h, - &mut r, - 1, - Request { - key: name, - kind, - plain: name == "plain", - duration: if op["duration"] == "inf" { - f64::INFINITY - } else { - op["duration"].as_f64().unwrap() - }, - value: op["value"].as_f64().unwrap(), - source: op["source"].as_u64(), - stack_as: if name == "plain" { - None - } else { - op["stackAs"].as_f64() - }, - }, - ) - .unwrap(); - } - } - let u = w.unit_mut(1).unwrap(); - let s = u.stats.stats().unwrap(); - let stats: Vec<_> = [ - "atk", - "def", - "res", - "moveSpeed", - "dmgTakenMul", - "artsTakenMul", - "physTakenMul", - "elementalTakenMul", - "aspd", - ] - .iter() - .map(|k| bits(s.n(k))) - .collect(); - states.push(json!({"stats":stats,"buffs":u.stats.buffs().iter().map(|b|{let e=b.runtime.valued.as_ref();json!({"id":b.runtime.id(),"key":b.key,"stacks":b.stacks,"duration":bits(b.runtime.duration),"left":bits(b.runtime.time_left),"acc":bits(b.runtime.accumulator),"value":e.filter(|e|e.value_present).map(|e|bits(e.value)),"as":e.and_then(|e|e.stack_as).map(bits),"tail":e.map(|e|e.tail.iter().map(|e|json!({"value":bits(e.value),"as":e.stack_as.map(bits),"until":bits(e.until)})).collect::>()).unwrap_or_default()})}).collect::>()})); - } - for (j, (a, b)) in states - .iter() - .zip(v["states"].as_array().unwrap()) - .enumerate() - { - assert_eq!(a, b, "case {} op {j} {name}", v["i"]); - } - assert_eq!(json!(h.trace), v["trace"], "trace {}", v["i"]); - count += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!(count, 384); -} diff --git a/crates/engine/tests/waves_reference.rs b/crates/engine/tests/waves_reference.rs deleted file mode 100644 index 28f48bb..0000000 --- a/crates/engine/tests/waves_reference.rs +++ /dev/null @@ -1,152 +0,0 @@ -use arkguard_engine::battle::{ - ledger::{Enemy, Ledger}, - waves::{Pending, Queue, Template}, -}; -use serde_json::{json, Value}; -use std::{ - io::{BufRead, BufReader}, - path::Path, - process::{Command, Stdio}, -}; -fn bits(n: f64) -> String { - format!("{:016x}", n.to_bits()) -} -fn queue_view(q: &Queue) -> Value { - json!(q.pending().iter().map(|p|json!({"time":bits(p.time),"sequence":p.sequence,"key":p.spec["enemyKey"],"counted":p.counted,"inTotal":p.in_total,"precounted":p.precounted})).collect::>()) -} -fn same(a: &Value, b: &Value, ctx: &str) { - match (a, b) { - (Value::Number(a), Value::Number(b)) => assert_eq!( - a.as_f64().unwrap().to_bits(), - b.as_f64().unwrap().to_bits(), - "{ctx}: {a} vs {b}" - ), - (Value::Array(a), Value::Array(b)) => { - assert_eq!(a.len(), b.len(), "{ctx}"); - for (i, (a, b)) in a.iter().zip(b).enumerate() { - same(a, b, &format!("{ctx}[{i}]")); - } - } - (Value::Object(a), Value::Object(b)) => { - assert_eq!(a.len(), b.len(), "{ctx}: {a:?} vs {b:?}"); - for (k, a) in a { - same(a, &b[k], &format!("{ctx}.{k}")); - } - } - _ => assert_eq!(a, b, "{ctx}"), - } -} -#[test] -#[ignore = "Requires ARKGUARD_REFERENCE_ROOT and Node; all wave templates and actual Battle billing"] -fn templates_and_solo_accounting_match() { - let root = std::env::var("ARKGUARD_REFERENCE_ROOT").unwrap(); - let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/reference/waves.mjs"); - let mut child = Command::new("node") - .arg(script) - .arg(root) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut templates = 0; - let mut timelines = 0; - for line in BufReader::new(child.stdout.take().unwrap()).lines() { - let c: Value = serde_json::from_str(&line.unwrap()).unwrap(); - if c["kind"] == "template" { - let t = Template::parse( - &c["input"], - &c["opts"]["mods"], - &c["opts"]["tag"], - 8192, - 4096, - ) - .unwrap(); - if c.get("queue").is_some() { - let mut q = Queue::new(8192).unwrap(); - for s in &t.spawns { - let excluded = c["excluded"].as_array().unwrap().contains(&s["enemyKey"]); - q.push(s, true, excluded).unwrap(); - } - assert_eq!(queue_view(&q), c["queue"], "{}", c["key"]); - } - let mut output = json!({"routes":t.routes,"spawns":t.spawns,"maxPlayTime":t.max_play_time,"overrides":t.overrides,"extraRoutes":t.extra_routes}); - if c["output"].get("maxPlayTime").is_none() { - for k in ["maxPlayTime", "overrides", "extraRoutes"] { - output.as_object_mut().unwrap().remove(k); - } - } - same(&output, &c["output"], c["key"].as_str().unwrap()); - templates += 1; - continue; - } - let mut q = Queue::new(128).unwrap(); - for s in c["spawns"].as_array().unwrap() { - q.push( - s, - true, - c["enemies"][s["enemyKey"].as_str().unwrap()]["notCountInTotal"] == true, - ) - .unwrap(); - } - let pending:Vec<_>=q.pending().iter().map(|p|json!({"time":bits(p.time),"sequence":p.sequence,"key":p.spec["enemyKey"],"counted":p.counted,"inTotal":p.in_total,"precounted":p.precounted})).collect(); - assert_eq!(json!(pending), c["queue"]); - let mut l = Ledger::new(json!("p"), &q, 128, 128).unwrap(); - let mut id = 0; - same(&l.report(0., None), &c["states"][0], "initial"); - let spawn = |p: &Pending, l: &mut Ledger| { - let raw = &c["enemies"][p.spec["enemyKey"].as_str().unwrap()]; - Enemy::from_pending(p, raw["lpr"].as_f64().unwrap_or(1.), l.player()).unwrap() - }; - for (i, op) in c["ops"].as_array().unwrap().iter().enumerate() { - let time = op["time"].as_f64().unwrap(); - let mut reason = None; - match op["op"].as_str().unwrap() { - "process" => { - while let Some(p) = q.pop_due(time) { - id += 1; - let e = spawn(&p, &mut l); - l.spawn(id, e, p.precounted).unwrap(); - q.next_sequence().unwrap(); - } - } - "spawn" => { - let s = &op["def"]; - let counted = s["countInTotal"] - .as_bool() - .unwrap_or(s["tag"] != "part" && s["tag"] != "boss"); - let p = Pending { - time, - sequence: q.next_sequence().unwrap(), - spec: s.clone(), - counted, - in_total: s["inTotal"] == true && counted, - precounted: false, - }; - id += 1; - let e = spawn(&p, &mut l); - l.spawn(id, e, false).unwrap(); - } - "kill" => l.kill(op["id"].as_u64().unwrap(), false).unwrap(), - "leak" => l.leak(op["id"].as_u64().unwrap()).unwrap(), - "timeout" => { - l.timeout(&mut q).unwrap(); - reason = Some("timeout"); - } - "forced" => reason = Some("forced"), - _ => unreachable!(), - } - same( - &l.report(time, reason), - &c["states"][i + 1], - &format!("timeline {timelines} op {i} {op}"), - ); - } - timelines += 1; - } - assert!(child.wait().unwrap().success()); - assert_eq!( - templates, 39, - "38 external wave templates plus research aliases" - ); - assert_eq!(timelines, 160); - eprintln!("{templates} templates; {timelines} real Battle accounting timelines"); -} diff --git a/crates/python/Cargo.toml b/crates/python/Cargo.toml index c208354..ae913bb 100644 --- a/crates/python/Cargo.toml +++ b/crates/python/Cargo.toml @@ -13,6 +13,9 @@ crate-type = ["cdylib"] arkguard-engine = { path = "../engine" } pyo3 = { version = "=0.27.2", features = ["extension-module"] } +serde_json = "=1.0.149" +serde = { version = "=1.0.228", features = ["derive"] } + [build-dependencies] pyo3-build-config = "=0.27.2" diff --git a/crates/python/src/candidate_inputs.rs b/crates/python/src/candidate_inputs.rs new file mode 100644 index 0000000..7d92aa3 --- /dev/null +++ b/crates/python/src/candidate_inputs.rs @@ -0,0 +1,351 @@ +//! Candidate parameters from the current owned public ledger and static metadata. +use super::*; +use crate::candidates::{build, Prepared}; +use std::collections::BTreeSet; + +fn natural(v: &Value, key: &str) -> Result { + field(v, key)? + .as_u64() + .ok_or_else(|| format!("Invalid public {key}")) +} +fn boolean(v: &Value, key: &str) -> Result { + field(v, key)? + .as_bool() + .ok_or_else(|| format!("Missing public boolean {key}")) +} +fn cell(row: &Value) -> Result { + let (r, c) = (integer(field(row, "row")?)?, integer(field(row, "col")?)?); + if !(9..13).contains(&r) || !(2..11).contains(&c) { + return Err("Malformed public board occupancy".into()); + } + Ok(((r - 9) * 9 + c - 2) as usize) +} + +impl PolicyEncoder { + pub fn current_candidates( + &self, + state: &Value, + history: &Value, + blocked: &BTreeSet, + ) -> Result> { + let own = field(state, "own")?; + let public = field(state, "public")?; + if get(public, "modeId") != "mode_single_abyss" || truth(get(public, "offers")) { + return Err("Only Desperation public policy is maintained".into()); + } + if get(own, "diy") != &self.diy { + return Err("DIY configuration differs from the resolved public catalog".into()); + } + for key in ["loadout", "ops"] { + if object(field(own, key)?)?.len() != 0 { + return Err(format!("Nondefault or unknown {key} is unsupported")); + } + } + if !array(field(own, "standIns")?)?.is_empty() || truth(get(public, "rerollVote")) { + return Err("Unresolved public stand-ins or setup vote".into()); + } + let terminal = boolean(state, "personalEnded")?; + let phase = string(state, "phase")?; + if terminal { + return build(Vec::new(), None, blocked, true); + } + if !boolean(state, "decisionRequired")? { + return Err("No player decision; advance the environment, do not invent wait".into()); + } + let mut prefix = Vec::new(); + let mut prepared = None; + match phase { + "INFO_CHECK" => { + prefix.push(serde_json::json!({ + "t": "g.infoReady", "setupRevision": natural(public, "setupRevision")? + })); + } + "BAND_DRAFT" => { + let draft = field(public, "draft")?; + if get(draft, "turn") != get(own, "playerId") { + return Err("Native solo draft is not this player's turn".into()); + } + let picks = object(field(draft, "picks")?)?; + for band in &self.bands { + if !picks.values().any(|v| v.as_str() == Some(band)) { + prefix.push(serde_json::json!({"t": "g.band", "bandId": band})); + } + } + } + "SP_DRAFT" | "PREP" if phase == "SP_DRAFT" || truth(get(own, "personalChoice")) => { + let choice = if phase == "SP_DRAFT" { + field(public, "sp")? + } else { + field(own, "personalChoice")? + }; + let cards = array(field(choice, "cards")?)?; + if !(1..=6).contains(&cards.len()) { + return Err("Unknown mandatory choice domain".into()); + } + if phase == "SP_DRAFT" && get(choice, "turn") != get(own, "playerId") { + return Err("Native solo SP draft is not this player's turn".into()); + } + for (index, card) in cards.iter().enumerate() { + if !["item", "bounty", "tactic"].contains(&string(card, "kind")?) { + return Err("Unknown public choice card kind".into()); + } + if phase == "SP_DRAFT" { + if natural(card, "idx")? != index as u64 { + return Err("Unknown SP card position/stock availability".into()); + } + let sold = boolean(card, "soldOut")?; + if object(field(choice, "taken")?)?.contains_key(&index.to_string()) || sold + { + continue; + } + } + let mut action = serde_json::json!({"t": "g.choice", "idx": index}); + if phase == "PREP" { + if get(choice, "round") != get(state, "round") { + return Err("Unknown personal choice identity".into()); + } + action["choiceId"] = Value::String(string(choice, "id")?.to_owned()); + } + prefix.push(action); + } + } + "PREP" => { + if boolean(own, "ready")? || !boolean(own, "alive")? { + return Err("No active prep decision".into()); + } + let recovery = + natural(history, "used")? >= arkguard_engine::history::PREP_ACTION_LIMIT; + let hand = array(field(own, "hand")?)?; + let temp = array(field(own, "temp")?)?; + if hand.len() != 10 { + return Err("Malformed public piece area".into()); + } + let ready = boolean(own, "canReady")?; + if ready { + if temp.iter().any(truth) { + return Err("canReady disagrees with public temporary reserve".into()); + } + prefix.push(serde_json::json!({"t": "g.ready", "ready": true})); + } + let shop = field(own, "shop")?; + if !recovery { + let funds = natural(own, "funds")?; + if hand.iter().any(Value::is_null) { + for (name, action, index_key, limit) in [ + ("slots", "g.buy", "slot", 16), + ("rewardOffer", "g.reward", "idx", 6), + ] { + let slots = if name == "slots" { + array(field(shop, name)?)?.as_slice() + } else if truth(get(shop, name)) { + array(field(get(shop, name), "slots")?)?.as_slice() + } else { + &[] + }; + if slots.len() > limit { + return Err("Shop/reward exceeds native protocol domain".into()); + } + for (index, slot) in slots.iter().enumerate() { + if !truth(slot) { + continue; + } + if !["chess", "item"].contains(&string(slot, "kind")?) { + return Err("Unknown shop kind or availability".into()); + } + if !boolean(slot, "sold")? && natural(slot, "price")? <= funds { + let mut intent = serde_json::json!({"t": action}); + intent[index_key] = serde_json::json!(index); + prefix.push(intent); + } + } + } + } + if funds >= natural(shop, "refreshPrice")? { + prefix.push(serde_json::json!({"t": "g.refresh"})); + } + prefix.push(serde_json::json!({"t": "g.freeze"})); + if natural(shop, "level")? < natural(shop, "maxLevel")? + && funds >= natural(shop, "upgradePrice")? + { + prefix.push(serde_json::json!({"t": "g.levelUp"})); + } + } + prepared = Some(self.piece_inputs(own, recovery, ready)?); + } + _ => return Err("Unsupported actionable native phase".into()), + } + for action in &mut prefix { + action.as_object_mut().unwrap().sort_keys(); + } + build(prefix, prepared, blocked, false) + } + + fn piece_inputs(&self, own: &Value, recovery: bool, ready: bool) -> Result { + let full = natural(own, "deployCount")? >= natural(own, "deployCap")?; + if recovery && ready { + return Ok((Vec::new(), 0, full, recovery, true)); + } + let mut locations = HashMap::new(); + let mut pieces = Vec::new(); + let mut uids = HashSet::new(); + let mut occupied = 0_u64; + for (area, name) in ["board", "hand", "temp"].into_iter().enumerate() { + for row in array(field(own, name)?)? { + if row.is_null() { + if area == 0 { + return Err("Null board occupant".into()); + } + continue; + } + let uid = natural(row, "uid")?; + if uid == 0 || !uids.insert(uid) { + return Err("Duplicate/invalid public UID".into()); + } + if !["chess", "token", "item"].contains(&string(row, "kind")?) { + return Err("Unknown public piece kind".into()); + } + self.definition(&identity(string(row, "kind")?, string(row, "id")?))?; + if area == 0 { + let bit = 1 << cell(row)?; + if occupied & bit != 0 || string(row, "kind")? == "item" { + return Err("Malformed public board occupancy".into()); + } + occupied |= bit; + } + for item in array(field(row, "items")?)? { + let uid = natural(item, "uid")?; + if uid == 0 || !uids.insert(uid) { + return Err("Duplicate/invalid equipment UID".into()); + } + self.definition(&identity("item", string(item, "id")?))?; + } + locations.insert(uid, (area, row)); + pieces.push((area, row)); + } + } + if pieces + .iter() + .filter(|(area, row)| *area == 0 && get(row, "kind") == "chess") + .count() as u64 + != natural(own, "deployCount")? + { + return Err("Public chess capacity disagrees with occupancy".into()); + } + let deployment = field(own, "deployment")?; + if !["normal", "bossL", "bossR"].contains(&string(deployment, "field")?) { + return Err("Missing visible deployment map".into()); + } + let mut terrain = [0_u64; 3]; + for tile in array(field(deployment, "cells")?)? { + let bit = 1 << cell(tile)?; + let kind = match string(tile, "kind")? { + "melee" => 1, + "ranged" => 2, + _ => return Err("Unknown deployment cell".into()), + }; + if terrain[0] & bit != 0 { + return Err("Unknown/duplicate deployment cell".into()); + } + terrain[0] |= bit; + terrain[kind] |= bit; + } + let mut prepared = Vec::with_capacity(pieces.len()); + for (area, row) in pieces { + let def = self.definition(&identity(string(row, "kind")?, string(row, "id")?))?; + let mut kind = match string(row, "kind")? { + "chess" => 0, + "token" => 1, + _ => 2, + }; + let mut mask = 0; + if !recovery || area == 2 { + if kind < 2 { + if terrain[0] != 0 { + mask = match string(&def.domain, "placement")? { + "all" => terrain[0], + "melee" => terrain[1], + "high" => terrain[2], + _ => return Err("Missing or unknown public placement position".into()), + }; + } + if kind == 1 && area != 0 { + let owner = locations.get(&natural(row, "ownerUid")?); + mask &= match owner { + Some((0, owner)) if get(owner, "kind") == "chess" => { + self.token_cells(row, owner, &def.domain)? + } + _ => 0, + } & !occupied; + } + } else { + kind = match string(&def.domain, "itemType")? { + "EQUIP" => 2, + "MAGIC" => 3, + _ => return Err("Unknown item capability".into()), + }; + } + } + let position = if area == 0 { cell(row)? as i8 } else { -1 }; + let direction = if area == 0 { + DIRECTIONS + .iter() + .position(|d| get(row, "dir").as_str() == Some(*d)) + .ok_or("Malformed public board occupancy")? as i8 + } else { + -1 + }; + prepared.push(( + natural(row, "uid")?, + area as u8, + kind, + position, + direction, + mask, + array(field(row, "items")?)? + .iter() + .map(|v| natural(v, "uid")) + .collect::>()?, + )); + } + let empty = array(field(own, "hand")?)? + .iter() + .enumerate() + .filter(|(_, v)| v.is_null()) + .fold(0_u16, |mask, (i, _)| mask | (1 << i)); + Ok((prepared, empty, full, recovery, ready)) + } + + fn token_cells(&self, token: &Value, owner: &Value, domain: &Value) -> Result { + let adjacent = get(token, "id") == "token_10032_jesca2_jckshd"; + let range = get(domain, "ownerRange"); + let outside = get(domain, "ownerRangeOutside"); + if !adjacent && range != &Value::Bool(true) && outside != &Value::Bool(true) { + return Ok(crate::candidates::CELL_MASK); + } + let owner_cell = cell(owner)?; + let (r, c) = ((owner_cell / 9) as i64 + 9, (owner_cell % 9) as i64 + 2); + let def = self.definition(&identity("chess", string(owner, "id")?))?; + let mut allowed = 0; + for target in 0..36 { + let (row, col) = (target / 9 + 9, target % 9 + 2); + let inside = def.ranges.iter().any(|&(dr, dc)| { + let (dr, dc) = match get(owner, "dir").as_str() { + Some("RIGHT") => (dr, dc), + Some("UP") => (dc, -dr), + Some("LEFT") => (-dr, -dc), + Some("DOWN") => (-dc, dr), + _ => (i64::MAX, i64::MAX), + }; + r.checked_add(dr) == Some(row) && c.checked_add(dc) == Some(col) + }); + if if adjacent { + (row - r).abs() + (col - c).abs() == 1 + } else { + (!truth(range) || inside) && (!truth(outside) || !inside) + } { + allowed |= 1 << target; + } + } + Ok(allowed) + } +} diff --git a/crates/python/src/candidates.rs b/crates/python/src/candidates.rs new file mode 100644 index 0000000..ad56b42 --- /dev/null +++ b/crates/python/src/candidates.rs @@ -0,0 +1,74 @@ +//! Complete candidate filtering and encoding share the owned native decision. +#[path = "../../../arkguardrl_core/native/src/prep_domain.rs"] +mod domain; +use arkguard_engine::identity::{action_id, canonical}; +use serde_json::{json, Value}; +use std::collections::{BTreeSet, HashSet}; + +pub type Prepared = (Vec, u16, bool, bool, bool); +pub(crate) const CELL_MASK: u64 = domain::MASK; + +const DIRECTIONS: [&str; 4] = ["RIGHT", "UP", "DOWN", "LEFT"]; + +fn intent(action: domain::Action) -> Value { + use domain::Action::*; + match action { + Sell(uid) => json!({"t": "g.sell", "uid": uid}), + Destroy(uid) => json!({"t": "g.destroy", "uid": uid}), + Hand(uid, idx) => json!({"t": "g.move", "uid": uid, "to": {"area": "hand", "idx": idx}}), + Board(uid, cell, dir) => json!({"t": "g.move", "uid": uid, + "to": {"area": "board", "row": 9 + cell / 9, "col": 2 + cell % 9}, "dir": DIRECTIONS[dir]}), + Equip(uid, target, old) => { + let mut action = json!({"t": "g.equip", "itemUid": uid, "targetUid": target}); + if let Some(old) = old { + action["replaceUid"] = json!(old); + } + action + } + Art(uid, cell, dir) => json!({"t": "g.art", "itemUid": uid, + "row": 9 + cell / 9, "col": 2 + cell % 9, "dir": DIRECTIONS[dir]}), + } +} + +pub fn build( + prefix: Vec, + prepared: Option, + blocked: &BTreeSet, + terminal: bool, +) -> Result, String> { + let pieces = match prepared { + Some((pieces, empty, full, recovery, ready)) => { + if pieces.len() > 128 + || empty >= 1 << 10 + || pieces.iter().any(|p| { + p.0 == 0 + || p.1 > 2 + || p.2 > 3 + || p.5 & !domain::MASK != 0 + || (p.1 == 0 && (!(0..36).contains(&p.3) || !(0..4).contains(&p.4))) + }) + { + return Err("Invalid PREP piece or board coordinate".into()); + } + domain::enumerate(&pieces, empty, full, recovery, ready) + } + None => Vec::new(), + }; + let mut actions = Vec::new(); + let mut seen = HashSet::new(); + for action in prefix.into_iter().chain(pieces.into_iter().map(intent)) { + if !seen.insert(canonical(&action)?) + || (!blocked.is_empty() && blocked.contains(&action_id(&action)?)) + { + continue; + } + actions.push(action); + if actions.len() > 16384 { + return Err("Native candidate hard cap exceeded; domain was not sliced".into()); + } + } + if actions.is_empty() && !terminal { + return Err("History/public domain exhausted; no fallback wait or forced Ready".into()); + } + Ok(actions) +} diff --git a/crates/python/src/ledger.rs b/crates/python/src/ledger.rs new file mode 100644 index 0000000..3c1107a --- /dev/null +++ b/crates/python/src/ledger.rs @@ -0,0 +1,131 @@ +//! One public ledger per native decision session, including automatic combat. +use arkguard_engine::{ + history::DecisionHistory, ledger_reward::NativeProgressCore, progress::PublicProgress, + solo::session::Session, +}; +use serde_json::{json, Value}; +use std::collections::BTreeSet; +use std::sync::Arc; + +pub struct DecisionLedger { + pub state: Arc, + history: DecisionHistory, + pub policy_history: Value, + pub blocked: BTreeSet, + progress: PublicProgress, + reward: NativeProgressCore, +} + +impl DecisionLedger { + pub fn new(state: Arc, stream_id: String) -> Result { + let mut progress = PublicProgress::new(stream_id)?; + progress.observe(Arc::clone(&state), None, None)?; + let mut history = DecisionHistory::new(); + history.initialize(Arc::clone(&state), &progress.snapshot(&state)?)?; + let mut reward = NativeProgressCore::new(); + reward.reset(&state)?; + Ok(Self { + state, + history, + policy_history: Value::Null, + blocked: BTreeSet::new(), + progress, + reward, + }) + } + + pub fn snapshot( + &mut self, + execution: Option, + reward: Option, + advances: usize, + ) -> Result { + self.policy_history = self.history.snapshot(&self.state)?; + self.blocked = self.history.blocked(&self.state)?; + #[derive(serde::Serialize)] + struct Snapshot<'a> { + observation: &'a Value, + history: &'a Value, + blocked: &'a BTreeSet, + execution: Option, + reward: Option, + advances: usize, + } + serde_json::to_string(&Snapshot { + observation: &self.state, + history: &self.policy_history, + blocked: &self.blocked, + execution, + reward, + advances, + }) + .map_err(|error| error.to_string()) + } + + pub fn step( + &mut self, + session: &mut Session, + action: &Value, + tick_budget: usize, + max_advances: usize, + ) -> Result { + let before = Arc::clone(&self.state); + // Preserve the immediate receipt before advancing the resulting battle. + let mut transport = session.step(action, 0)?; + let accepted = transport["accepted"] + .as_bool() + .ok_or("Missing action acceptance")?; + let mut reply = json!({"accepted": accepted, "result": {"ok": accepted}}); + if !accepted { + reply["result"]["error"] = transport["rejection"].clone(); + } + let immediate = Arc::new(session.observation()?); + let execution = self + .progress + .observe(immediate.clone(), Some(action), Some(&reply))? + .ok_or("Missing execution report")?; + let mut after = immediate; + let mut advances = 0; + while transport["budgetExhausted"] == true { + if advances >= max_advances { + return Err("Combat budget exhausted before a decision boundary".into()); + } + transport = session.advance(tick_budget)?; + advances += 1; + if transport["budgetExhausted"] != true { + after = Arc::new(session.observation()?); + self.progress.observe(after.clone(), None, None)?; + } + } + let progress = self.progress.snapshot(&after)?; + self.history.record( + before.clone(), + after.clone(), + action, + &execution, + &progress, + accepted, + )?; + let reward = self.reward.step(&before, &after)?; + self.state = after; + self.snapshot(Some(execution), Some(reward), advances) + } +} + +/// One bounded current domain. The binding keeps its token counter across resets. +pub struct PolicyDomain { + pub revision: u64, + pub token: u64, + pub actions: Vec, +} +impl PolicyDomain { + pub fn selected(&self, revision: u64, token: u64, index: usize) -> Result { + if self.revision != revision || self.token != token { + return Err("Stale native candidate domain".into()); + } + self.actions + .get(index) + .cloned() + .ok_or_else(|| "Select a current unpadded candidate index".into()) + } +} diff --git a/crates/python/src/lib.rs b/crates/python/src/lib.rs index c4f6cd3..eef9a9c 100644 --- a/crates/python/src/lib.rs +++ b/crates/python/src/lib.rs @@ -1,6 +1,11 @@ -//! Development binding for the native foundations. No incomplete Gym environment is registered. +//! Development bindings for native data and persistent execution. No Gym environment is registered. use arkguard_engine::{data::Catalog, deterministic::rng}; use pyo3::{exceptions::PyValueError, prelude::*}; +use std::sync::Arc; +mod policy; +mod session; +mod ledger; +mod candidates; #[pyfunction] fn derive_seed(seed: u32, salt: &str) -> u32 { @@ -9,7 +14,7 @@ fn derive_seed(seed: u32, salt: &str) -> u32 { #[pyclass(frozen)] struct NativeCatalog { - inner: Catalog, + inner: Arc, } #[pymethods] @@ -17,10 +22,47 @@ impl NativeCatalog { #[new] fn new(py: Python<'_>, data_root: String, max_bytes: usize) -> PyResult { py.detach(|| Catalog::load(std::path::Path::new(&data_root), max_bytes)) - .map(|inner| Self { inner }) + .map(|inner| Self { + inner: Arc::new(inner), + }) .map_err(PyValueError::new_err) } + fn with_diy(&self, py: Python<'_>, picks_json: &str) -> PyResult { + if picks_json.len() > 4096 { + return Err(PyValueError::new_err("DIY configuration exceeds byte limit")); + } + py.detach(|| { + let picks = serde_json::from_str(picks_json).map_err(|e| format!("{e}"))?; + self.inner.with_diy(&picks).map(|inner| Self { + inner: Arc::new(inner), + }) + }) + .map_err(PyValueError::new_err) + } + + fn public_tables(&self, py: Python<'_>) -> String { + py.detach(|| { + let mut out = serde_json::Map::new(); + for name in [ + "bands", + "chess", + "items", + "tokens", + "config", + "bonds", + "garrisons", + "enemies", + "choices", + "effects", + ] { + out.insert(name.into(), self.inner.table(name).unwrap().clone()); + } + if let Some(picks) = self.inner.table("diy") { out.insert("diy".into(), picks.clone()); } + serde_json::Value::Object(out).to_string() + }) + } + fn definitions(&self) -> Vec<(u32, String, String)> { self.inner .definitions() @@ -33,6 +75,7 @@ impl NativeCatalog { #[pymodule] fn _native(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; + m.add_class::()?; m.add_function(wrap_pyfunction!(derive_seed, m)?)?; Ok(()) } diff --git a/crates/python/src/policy.rs b/crates/python/src/policy.rs new file mode 100644 index 0000000..83310ce --- /dev/null +++ b/crates/python/src/policy.rs @@ -0,0 +1,1233 @@ +//! Public-state projection and dynamic policy wire layout (v7). +//! Static metadata is compiled once from PublicCatalog, never from engine internals. +use serde_json::Value; +use std::collections::{HashMap, HashSet}; + +#[path = "candidate_inputs.rs"] +mod candidate_inputs; + +type Result = std::result::Result; +const MAX_ENTITIES: usize = 128; +const MAX_ENEMIES: usize = 64; +const MAX_ACTIONS: usize = 16384; +const OBS_DIM: usize = 4784; +const ACTION_DIM: usize = 41; +const BOND_START: usize = 42 + 128 * 28; +const GRID_START: usize = BOND_START + 23 * 5; +const ENEMY_START: usize = GRID_START + 36 * 5; +const CONTROL_START: usize = ENEMY_START + 64 * 12; +const DIRECTIONS: [&str; 4] = ["RIGHT", "UP", "DOWN", "LEFT"]; +const PHASES: [&str; 12] = [ + "INFO_CHECK", + "BAND_DRAFT", + "BATTLE_CHECK", + "ROUND_START", + "SP_DRAFT", + "PREP", + "COMBAT", + "UNITE", + "SETTLE", + "FINAL_ASSAULT", + "HIDDEN_CORE", + "RESULT", +]; +const ACTIONS: [&str; 14] = [ + "infoReady", + "band", + "choice", + "buy", + "reward", + "refresh", + "freeze", + "levelUp", + "sell", + "move", + "equip", + "art", + "destroy", + "ready", +]; +const MOVES: [&str; 6] = [ + "deploy", + "reserve_replace", + "reposition", + "board_swap", + "withdraw", + "reserve_move", +]; +const SCHEDULES: [&str; 19] = [ + "buy", "levelUp", "refresh", "freeze", "sell", "deploy", "replace", "adjust", "withdraw", + "equip", "art", "destroy", "ready", "confirm", "band", "bandSkip", "choice", "reward", "wait", +]; +const BONDS: [&str; 23] = [ + "arcaneShip", + "deputShip", + "egirShip", + "emptyShip", + "indomShip", + "investShip", + "kazimierzShip", + "kjeragShip", + "lateranoShip", + "maniShip", + "miraShip", + "preciShip", + "raidShip", + "sargonShip", + "siracusaShip", + "skillfulShip", + "soloShip", + "steadShip", + "suntShip", + "swiftShip", + "victoriaShip", + "visiShip", + "yanShip", +]; +const ERRORS: [&str; 15] = [ + "NO_FUNDS", + "HAND_FULL", + "BOARD_FULL", + "BAD_TILE", + "BAD_TARGET", + "SOLD_OUT", + "MAX_LEVEL", + "WRONG_PHASE", + "NOT_YOUR_TURN", + "ALREADY", + "TEMP_NOT_EMPTY", + "ELIMINATED", + "NOT_READY", + "BAD_MSG", + "OTHER", +]; +const CHANGES: [&str; 8] = [ + "funds_delta", + "spent_delta", + "refreshes_delta", + "merges_delta", + "level_delta", + "deploy_delta", + "hand_free_delta", + "temp_used_delta", +]; +const AREAS: [&str; 8] = [ + "board", + "hand", + "temp", + "equipped", + "shop", + "offer", + "faction", + "active_effect", +]; +const EMPTY: Value = Value::Null; + +fn object(v: &Value) -> Result<&serde_json::Map> { + v.as_object().ok_or_else(|| "Expected public object".into()) +} +fn array(v: &Value) -> Result<&Vec> { + v.as_array().ok_or_else(|| "Expected public array".into()) +} +fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value> { + object(v)? + .get(key) + .ok_or_else(|| format!("Missing public field: {key}")) +} +fn get<'a>(v: &'a Value, key: &str) -> &'a Value { + v.get(key).unwrap_or(&EMPTY) +} +fn text(v: &Value) -> Result<&str> { + v.as_str().ok_or_else(|| "Expected public string".into()) +} +fn string<'a>(v: &'a Value, key: &str) -> Result<&'a str> { + text(field(v, key)?) +} +fn number(v: &Value) -> Result { + v.as_f64() + .filter(|n| n.is_finite()) + .ok_or_else(|| "Structured features require finite public numbers".into()) +} +fn num(v: &Value, key: &str, default: f64) -> Result { + match v.get(key) { + Some(n) => number(n), + None => Ok(default), + } +} +fn integer(v: &Value) -> Result { + v.as_i64().ok_or_else(|| "Expected public integer".into()) +} +fn index(v: &Value) -> Result { + let n = integer(v)?; + usize::try_from(n).map_err(|_| "Expected nonnegative public index".into()) +} +// Python truthiness is used only by the original boolean/default expressions. +fn truth(v: &Value) -> bool { + match v { + Value::Null => false, + Value::Bool(b) => *b, + Value::Number(n) => n.as_f64().unwrap_or(0.) != 0., + Value::String(s) => !s.is_empty(), + Value::Array(a) => !a.is_empty(), + Value::Object(o) => !o.is_empty(), + } +} +fn bit(b: bool) -> f64 { + if b { + 1. + } else { + 0. + } +} +// Python float(bool/number) admits both JSON booleans and numbers. +fn float_value(v: &Value) -> Result { + match v { + Value::Bool(b) => Ok(bit(*b)), + Value::Null => Err("Structured features require finite public numbers".into()), + _ => number(v), + } +} +fn float_field(v: &Value, key: &str, default: f64) -> Result { + match v.get(key) { + Some(value) => float_value(value), + None => Ok(default), + } +} +fn scalar(v: f64, scale: f64) -> f64 { + (v / scale).tanh() +} +fn flags(out: &mut Vec, value: &Value, vocabulary: &[&str]) { + out.extend( + vocabulary + .iter() + .map(|key| bit(value.as_str() == Some(*key))), + ); +} +fn identity(kind: &str, id: &str) -> (String, String) { + (kind.to_owned(), id.to_owned()) +} +fn cell(row: i64, col: i64) -> Option { + if (9..13).contains(&row) && (2..11).contains(&col) { + Some(((row - 9) * 9 + col - 2) as usize) + } else { + None + } +} +// Python tuple/dict keys treat integral floats as their integer counterparts. +fn coord(v: &Value) -> Result> { + let n = number(v)?; + if n.fract() != 0. || n.abs() > 1e15 { + return Ok(None); + } + Ok(Some(n as i64)) +} + +fn uid(v: &Value) -> Result { + // JSON object keys in progress use str(uid), while refs preserve UID type. + match v { + Value::String(s) => Ok(format!("s:{s}")), + Value::Number(_) if v.as_i64().is_some() || v.as_u64().is_some() => Ok(format!("n:{v}")), + _ => Err("Invalid public UID".into()), + } +} +fn progress_uid(v: &Value) -> Result { + match v { + Value::String(s) => Ok(s.clone()), + Value::Number(_) => { + uid(v)?; + Ok(v.to_string()) + } + Value::Null => Ok("None".into()), + _ => Err("Invalid public UID".into()), + } +} +fn optional_object(v: &Value) -> Result<&Value> { + if !v.is_null() { + object(v)?; + } + Ok(v) +} +fn optional_array<'a>(v: &'a Value, key: &str) -> Result<&'a [Value]> { + match v.get(key) { + None => Ok(&[]), + Some(a) => Ok(array(a)?.as_slice()), + } +} + +#[derive(Clone)] +struct Definition { + index: usize, + ranges: Vec<(i64, i64)>, + air: bool, + base: String, + golden: bool, + upgrade: f64, + domain: Value, +} + +pub struct Encoded { + pub observation: Vec, + pub candidates: Vec, + pub schedules: Vec, + pub experts: Vec, +} + +pub struct PolicyEncoder { + definitions: HashMap<(String, String), Definition>, + entities: HashMap<(String, String), usize>, + enemies: HashMap, + bands: Vec, + choices: HashMap<(String, String), Value>, + config: Value, + diy: Value, +} + +struct Entity { + row: Value, + area: usize, + definition: (String, String), +} +struct Projection { + entities: Vec, + uids: HashMap, + shop: HashMap, + offer: HashMap, + choice: HashMap, + bands: HashMap, + families: HashMap, + occupied: HashMap<(i64, i64), usize>, +} +impl Projection { + fn new() -> Self { + Self { + entities: Vec::with_capacity(MAX_ENTITIES), + uids: HashMap::with_capacity(MAX_ENTITIES), + shop: HashMap::new(), + offer: HashMap::new(), + choice: HashMap::new(), + bands: HashMap::new(), + families: HashMap::new(), + occupied: HashMap::with_capacity(36), + } + } + fn add(&mut self, row: Value, area: usize, definition: (String, String)) -> Result { + if self.entities.len() >= MAX_ENTITIES { + return Err("Public entity capacity exceeded; no truncation".into()); + } + self.entities.push(Entity { + row, + area, + definition, + }); + Ok(self.entities.len()) + } + fn reference(&self, value: &Value) -> Result { + if value.is_null() { + return Ok(0); + } + self.uids + .get(&uid(value)?) + .copied() + .ok_or_else(|| "Unknown public entity UID reference".into()) + } + // Receipts may refer to a piece sold/merged away since the prior decision. + fn receipt_reference(&self, value: &Value) -> Result { + if value.is_null() { + return Ok(0); + } + Ok(self.uids.get(&uid(value)?).copied().unwrap_or(0)) + } +} + +impl PolicyEncoder { + pub fn new(metadata: &Value) -> Result { + let mut definitions = HashMap::new(); + let mut definition_indices = HashSet::new(); + let rows = array(field(metadata, "definitions")?)?; + for row in rows { + let kind = string(row, "kind")?; + let id = string(row, "id")?; + let i = index(field(row, "index")?)?; + if i == 0 || i > rows.len() || !definition_indices.insert(i) { + return Err("Invalid definition index".into()); + } + let mut ranges = Vec::new(); + for pair in array(field(row, "ranges")?)? { + let p = array(pair)?; + if p.len() != 2 { + return Err("Invalid static observation range".into()); + } + let (a, b) = (integer(&p[0])?, integer(&p[1])?); + if !(-128..=128).contains(&a) || !(-128..=128).contains(&b) { + return Err("Invalid static observation range".into()); + } + ranges.push((a, b)); + } + if ranges.len() > 24 { + return Err("Static range capacity exceeded".into()); + } + let def = Definition { + domain: get(row, "domain").clone(), + index: i, + ranges, + air: field(row, "air")? + .as_bool() + .ok_or("Invalid definition air flag")?, + base: string(row, "base")?.to_owned(), + golden: field(row, "isGolden")? + .as_bool() + .ok_or("Invalid definition golden flag")?, + upgrade: if truth(get(row, "upgradeNum")) { + number(get(row, "upgradeNum"))? + } else { + 0. + }, + }; + if definitions.insert(identity(kind, id), def).is_some() { + return Err("Duplicate definition identity".into()); + } + } + let mut entities = HashMap::new(); + let mut indices = HashSet::new(); + let entity_rows = array(field(metadata, "entities")?)?; + if entity_rows.len() >= 1024 { + return Err("Catalog entity vocabulary exceeds contract".into()); + } + for row in entity_rows { + let (kind, id) = (string(row, "kind")?, string(row, "id")?); + let i = index(field(row, "index")?)?; + if i == 0 + || i >= 1024 + || !indices.insert(i) + || entities.insert(identity(kind, id), i).is_some() + { + return Err("Invalid catalog entity index".into()); + } + } + // Historical draft order is catalog.band_ids (sortId/mode filtered), + // not the lexicographic catalog embedding order. + let mut bands = Vec::new(); + let mut seen_bands = HashSet::new(); + for id in optional_array(metadata, "band_ids")? { + let id = text(id)?; + if !entities.contains_key(&identity("band", id)) || !seen_bands.insert(id) { + return Err("Unknown or duplicate public draft band".into()); + } + bands.push(id.to_owned()); + } + let mut enemies = HashMap::new(); + let mut indices = HashSet::new(); + let enemy_rows = array(field(metadata, "enemies")?)?; + if enemy_rows.len() >= 2048 { + return Err("Catalog enemy vocabulary exceeds contract".into()); + } + for row in enemy_rows { + let i = index(field(row, "index")?)?; + if i == 0 + || i >= 2048 + || !indices.insert(i) + || enemies.insert(string(row, "id")?.to_owned(), i).is_some() + { + return Err("Invalid catalog enemy index".into()); + } + } + let mut choices = HashMap::new(); + for row in array(field(metadata, "choices")?)? { + let (kind, id) = (string(row, "kind")?, string(row, "id")?); + if !["bounty", "tactic"].contains(&kind) + || !definitions.contains_key(&identity(kind, id)) + || choices.insert(identity(kind, id), row.clone()).is_some() + { + return Err("Invalid canonical public choice".into()); + } + } + let config = field(metadata, "config")?.clone(); + object(&config)?; + Ok(Self { + definitions, + entities, + enemies, + bands, + choices, + config, + diy: metadata + .get("diy") + .cloned() + .unwrap_or_else(|| serde_json::json!({})), + }) + } + + fn definition(&self, key: &(String, String)) -> Result<&Definition> { + self.definitions + .get(key) + .ok_or_else(|| format!("Unknown public definition: {}/{}", key.0, key.1)) + } + fn row_key(&self, row: &Value) -> Result<(String, String)> { + let kind = string(row, "kind")?; + let id = string(row, "id")?; + let key = identity(kind, id); + self.definition(&key)?; + if kind == "bounty" || kind == "tactic" { + let choice_key = identity( + kind, + text(row.get("effectId").unwrap_or(field(row, "id")?))?, + ); + let canonical = self + .choices + .get(&choice_key) + .ok_or("Unknown public choice effect")?; + for field in ["enemyKey", "payout", "coin", "count", "rounds"] { + if let Some(value) = row.get(field) { + if !python_equal(value, get(canonical, field)) { + return Err(format!( + "Public choice differs from pinned definition: {field}" + )); + } + } + } + } + Ok(key) + } + fn effect_key(&self, effect: &Value) -> Result<(String, String)> { + let mut id = match effect.get("id") { + Some(v) => text(v)?, + None => "", + } + .split('#') + .next() + .unwrap_or(""); + if id.starts_with("bounty:") { + id = get(effect, "iconId").as_str().unwrap_or(""); + } + for kind in ["bounty", "tactic"] { + let key = identity(kind, id); + if self.choices.contains_key(&key) { + return Ok(key); + } + } + let key = identity("effect", "unresolved"); + self.definition(&key)?; + Ok(key) + } + + fn project(&self, state: &Value) -> Result { + let own = field(state, "own")?; + let public = field(state, "public")?; + let shop = field(own, "shop")?; + let phase = string(state, "phase")?; + let mut p = Projection::new(); + for (area, name) in AREAS[..3].iter().enumerate() { + for row in array(field(own, name)?)? { + if !truth(row) { + continue; + } + let reference = p.add(row.clone(), area, self.row_key(row)?)?; + if p.uids.insert(uid(field(row, "uid")?)?, reference).is_some() { + return Err("Duplicate public UID".into()); + } + for item in optional_array(row, "items")? { + let mut equipped = object(item)?.clone(); + equipped + .entry("kind") + .or_insert(Value::String("item".into())); + equipped.insert("ownerUid".into(), field(row, "uid")?.clone()); + let equipped = Value::Object(equipped); + let reference = p.add(equipped.clone(), 3, self.row_key(&equipped)?)?; + if p.uids + .insert(uid(field(item, "uid")?)?, reference) + .is_some() + { + return Err("Duplicate public UID".into()); + } + } + } + } + for (i, row) in array(field(shop, "slots")?)?.iter().enumerate() { + if truth(row) && !truth(get(row, "sold")) { + let r = p.add(row.clone(), 4, self.row_key(row)?)?; + p.shop.insert(i, r); + } + } + let reward = optional_object(get(shop, "rewardOffer"))?; + for (i, row) in optional_array(reward, "slots")?.iter().enumerate() { + if truth(row) && !truth(get(row, "sold")) { + let r = p.add(row.clone(), 5, self.row_key(row)?)?; + p.offer.insert(i, r); + } + } + let choice = match phase { + "PREP" => get(own, "personalChoice"), + "SP_DRAFT" => get(public, "sp"), + _ => &EMPTY, + }; + optional_object(choice)?; + if let Some(taken) = choice.get("taken") { + object(taken)?; + } + for (i, row) in optional_array(choice, "cards")?.iter().enumerate() { + if !truth(get(row, "soldOut")) && get(choice, "taken").get(i.to_string()).is_none() { + let r = p.add(row.clone(), 5, self.row_key(row)?)?; + p.choice.insert(i, r); + } + } + for effect in optional_array(own, "effects")? { + if get(effect, "iconKind").as_str() != Some("band") { + let key = self.effect_key(effect)?; + let mut row = serde_json::Map::new(); + row.insert("kind".into(), Value::String("effect".into())); + row.insert("id".into(), Value::Null); + row.insert("counter".into(), get(effect, "counter").clone()); + p.add(Value::Object(row), 7, key)?; + } + } + if truth(get(own, "bandId")) { + let id = text(get(own, "bandId"))?; + let row = simple_row("band", id); + p.add(row.clone(), 6, self.row_key(&row)?)?; + } + if phase == "BAND_DRAFT" { + if self.bands.is_empty() { + return Err("BAND_DRAFT requires ordered public band_ids metadata".into()); + } + let picks = get(get(public, "draft"), "picks"); + if !picks.is_null() { + object(picks)?; + } + for id in &self.bands { + if picks + .as_object() + .is_some_and(|m| m.values().any(|v| v.as_str() == Some(id.as_str()))) + { + continue; + } + let row = simple_row("band", id); + let r = p.add(row.clone(), 5, self.row_key(&row)?)?; + p.bands.insert(id.clone(), r); + } + } + for (i, entity) in p.entities.iter().enumerate() { + if entity.area == 0 { + let row = coord(field(&entity.row, "row")?)?.ok_or("Invalid public board row")?; + let col = + coord(field(&entity.row, "col")?)?.ok_or("Invalid public board column")?; + if cell(row, col).is_none() || p.occupied.insert((row, col), i + 1).is_some() { + return Err("Invalid or duplicate public board cell".into()); + } + } + if get(&entity.row, "kind").as_str() == Some("chess") && entity.area < 3 { + let def = self.definition(&entity.definition)?; + let counts = p.families.entry(def.base.clone()).or_insert([0; 4]); + counts[if def.golden { 3 } else { entity.area }] += 1; + } + } + if p.occupied.len() > 36 { + return Err("Public board capacity exceeded".into()); + } + Ok(p) + } + + pub fn encode(&self, state: &Value, history: &Value, actions: &[Value]) -> Result { + if actions.len() > MAX_ACTIONS { + return Err("Public action capacity exceeded; no truncation".into()); + } + let own = field(state, "own")?; + let public = field(state, "public")?; + let phase = string(state, "phase")?; + if !PHASES.contains(&phase) { + return Err("Unknown public phase".into()); + } + if string(public, "modeId")? != "mode_single_abyss" { + return Err("Only Desperation public policy is maintained".into()); + } + let progress = field(history, "progress")?; + if string(progress, "schema")? != "arkguardrl/public-observed-progress-v2" { + return Err("Structured v7 requires observation-bound public progress".into()); + } + // The Python boundary verifies observation/history fingerprints. No private reads. + let p = self.project(state)?; + let mut observation = vec![0_f64; OBS_DIM]; + let global = self.global(state, history)?; + if global.len() != 42 { + return Err("Invalid global feature shape".into()); + } + observation[..42].copy_from_slice(&global); + let exposures = field(progress, "pieces")?; + object(exposures)?; + for (i, e) in p.entities.iter().enumerate() { + let row = &e.row; + let def = self.definition(&e.definition)?; + let out = &mut observation[42 + i * 28..42 + (i + 1) * 28]; + out[0] = def.index as f64; + out[1] = 1.; + out[2] = p.reference(get(row, "ownerUid"))? as f64; + let items = optional_array(row, "items")?; + if items.len() > 2 { + return Err("Public equipment reference capacity exceeded".into()); + } + for (j, item) in items.iter().enumerate() { + out[3 + j] = p.reference(field(item, "uid")?)? as f64; + } + out[5 + e.area] = 1.; + let exposure = exposures + .get(progress_uid(get(row, "uid"))?) + .unwrap_or(&EMPTY); + optional_object(exposure)?; + let counter = get(row, "counter"); + let numbers = [ + num(row, "price", 0.)?, + num(row, "row", -1.)?, + num(row, "col", -1.)?, + num(row, "count", 0.)?, + num(row, "coin", 0.)?, + num(row, "count", 0.)?, + num(row, "rounds", 0.)?, + num(exposure, "visible_pre_refreshes", 0.)?, + float_field(exposure, "history_complete", 0.)?, + if truth(counter) { number(counter)? } else { 0. }, + bit(counter.is_number()), + ]; + let scales = [30., 20., 21., 10., 10., 10., 10., 10., 1., 10., 1.]; + for j in 0..11 { + out[13 + j] = if j == 8 || j == 10 { + numbers[j] + } else { + scalar(numbers[j], scales[j]) + }; + } + if let Some(direction) = DIRECTIONS + .iter() + .position(|d| get(row, "dir").as_str() == Some(d)) + { + out[24 + direction] = 1.; + } + } + let mut visible = HashMap::new(); + for bond in array(field(own, "bonds")?)? { + let id = string(bond, "bondId")?; + if !BONDS.contains(&id) { + return Err("Unknown visible bond".into()); + } + visible.insert(id, bond); + } + let disabled = array(field(public, "disabledBonds")?)?; + for (i, key) in BONDS.iter().enumerate() { + let b = visible.get(key).copied().unwrap_or(&EMPTY); + let out = &mut observation[BOND_START + i * 5..BOND_START + (i + 1) * 5]; + out.copy_from_slice(&[ + scalar(num(b, "count", 0.)?, 12.), + scalar(num(b, "layers", 0.)?, 100.), + float_field(b, "active", 0.)?, + scalar(num(b, "tier", 0.)?, 3.), + if truth(get(b, "off")) { + float_value(get(b, "off"))? + } else { + bit(disabled.iter().any(|v| v.as_str() == Some(key))) + }, + ]); + } + let tiles = array(field(field(own, "deployment")?, "cells")?)?; + if tiles.len() > 36 { + return Err("Public deployment cell capacity exceeded".into()); + } + for tile in tiles { + let row = coord(field(tile, "row")?)?.ok_or("Invalid public deployment cell")?; + let col = coord(field(tile, "col")?)?.ok_or("Invalid public deployment cell")?; + let at = cell(row, col).ok_or("Invalid public deployment cell")?; + observation[GRID_START + at * 5] = 1.; + observation[GRID_START + at * 5 + 1] = bit(string(tile, "kind")? == "ranged"); + } + let mut coverage = [0_u32; 36]; + let mut air_coverage = [0_u32; 36]; + for (&(row, col), &reference) in &p.occupied { + let e = &p.entities[reference - 1]; + let def = self.definition(&e.definition)?; + let direction = DIRECTIONS + .iter() + .position(|d| get(&e.row, "dir").as_str() == Some(d)) + .ok_or("Invalid public board direction")?; + observation[GRID_START + cell(row, col).unwrap() * 5 + 2] = reference as f64; + for &(dr, dc) in &def.ranges { + let (r, c) = match direction { + 0 => (dr, dc), + 1 => (dc, -dr), + 2 => (-dc, dr), + _ => (-dr, -dc), + }; + if let Some(at) = cell(row + r, col + c) { + coverage[at] += 1; + air_coverage[at] += u32::from(def.air); + } + } + } + for at in 0..36 { + observation[GRID_START + at * 5 + 3] = scalar(coverage[at] as f64, 6.); + observation[GRID_START + at * 5 + 4] = scalar(air_coverage[at] as f64, 6.); + } + let enemies = array(field(own, "nextEnemies")?)?; + if enemies.len() > MAX_ENEMIES { + return Err("Public enemy capacity exceeded; no truncation".into()); + } + for (i, enemy) in enemies.iter().enumerate() { + let id = string(enemy, "enemyKey")?; + let def = self.definition(&identity("enemy", id))?; + let catalog = self + .enemies + .get(id) + .ok_or("Unknown visible enemy identity")?; + let out = &mut observation[ENEMY_START + i * 12..ENEMY_START + (i + 1) * 12]; + out[..8].copy_from_slice(&[ + def.index as f64, + 1., + *catalog as f64, + scalar(num(enemy, "count", 0.)?, 10.), + scalar(num(enemy, "t", 0.)?, 120.), + float_field(enemy, "fly", 0.)?, + float_field(enemy, "elite", 0.)?, + float_field(enemy, "boss", 0.)?, + ]); + if let Some(gate) = ["lower", "upper", "left", "right"] + .iter() + .position(|key| get(enemy, "gate").as_str() == Some(key)) + { + out[8 + gate] = 1.; + } + } + let control = self.control(state, history, &p)?; + if control.len() != 95 { + return Err("Invalid control feature shape".into()); + } + observation[CONTROL_START..].copy_from_slice(&control); + let mut candidates = Vec::with_capacity(actions.len() * ACTION_DIM); + let mut schedules = Vec::with_capacity(actions.len()); + let mut experts = Vec::with_capacity(actions.len()); + for action in actions { + let (row, schedule, expert) = self.action(state, &p, action)?; + if row.len() != ACTION_DIM { + return Err("Invalid action feature shape".into()); + } + candidates.extend(row.into_iter().map(|v| v as f32)); + schedules.push(schedule); + experts.push(expert); + } + if observation.iter().any(|v| !v.is_finite()) || candidates.iter().any(|v| !v.is_finite()) { + return Err("Nonfinite policy features".into()); + } + // All nonlinear calculations and arithmetic above stay f64, matching Python. + let observation: Vec = observation.into_iter().map(|v| v as f32).collect(); + if observation.iter().any(|v| !v.is_finite()) { + return Err("Public observation exceeds finite f32 layout".into()); + } + Ok(Encoded { + observation, + candidates, + schedules, + experts, + }) + } + + fn global(&self, state: &Value, history: &Value) -> Result> { + let own = field(state, "own")?; + let public = field(state, "public")?; + let shop = field(own, "shop")?; + let progress = field(history, "progress")?; + let round = number(field(state, "round")?)?; + let mode_id = string(public, "modeId")?; + let mode = field(field(&self.config, "modes")?, mode_id)?; + let economy = mode + .get("economy") + .unwrap_or(field(&self.config, "economy")?); + let level_value = field(shop, "level")?; + let level = integer(level_value)?; + let maximum = integer(field(mode, "maxShopLevel")?)?; + let next = (level + 1).min(maximum); + let slots = field(mode, "shopSlots")?; + let current = field(slots, &level.to_string())?; + let following = field(slots, &next.to_string())?; + let scale = get( + get(mode, "enemyScale"), + &integer(field(state, "round")?)?.to_string(), + ); + let hand = array(field(own, "hand")?)?; + let temp = array(field(own, "temp")?)?; + let mut out = vec![ + scalar(round, 20.), + scalar(number(field(public, "lastRound")?)? - round, 20.), + scalar(number(field(public, "bossRound")?)? - round, 20.), + scalar(number(field(own, "lp")?)?, 30.), + scalar(number(field(own, "funds")?)?, 30.), + scalar(number(level_value)?, 6.), + scalar(number(field(shop, "upgradePrice")?)?, 30.), + scalar(number(field(shop, "refreshPrice")?)?, 10.), + scalar(number(field(shop, "freeRefreshes")?)?, 10.), + float_value(field(shop, "frozen")?)?, + scalar( + number(field(own, "deployCap")?)? - number(field(own, "deployCount")?)?, + 12., + ), + scalar(hand.iter().filter(|v| v.is_null()).count() as f64, 10.), + scalar(temp.iter().filter(|v| !v.is_null()).count() as f64, 5.), + scalar(number(field(progress, "spent")?)?, 30.), + float_value(field(progress, "spent_known")?)?, + scalar(number(field(progress, "refreshes")?)?, 10.), + float_value(field(progress, "refreshes_known")?)?, + scalar(number(field(progress, "direct_chess_gains")?)?, 10.), + float_value(field(progress, "direct_gains_complete")?)?, + ]; + for value in [ + maximum as f64, + next as f64, + number(field(current, "chess")?)?, + number(field(following, "chess")?)?, + number(field(current, "item")?)?, + number(field(following, "item")?)?, + ] { + out.push(scalar(value, 6.)); + } + let carry = array(field(economy, "leftoverFundsKeptByBands")?)? + .iter() + .any(|v| python_equal(v, get(own, "bandId"))); + out.extend([ + bit(carry), + 1., + scalar(num(scale, "hp", 1.)?, 3.), + scalar(num(scale, "atk", 1.)?, 3.), + scalar(num(scale, "speed", 1.)?, 3.), + ]); + flags(&mut out, field(state, "phase")?, &PHASES); + Ok(out) + } + + fn control(&self, state: &Value, history: &Value, p: &Projection) -> Result> { + let report = field(field(history, "progress")?, "last_execution")?; + optional_object(report)?; + let mut refs = Vec::with_capacity(3); + let mut definitions = Vec::with_capacity(3); + for role in ["source", "target", "replaced"] { + let e = optional_object(get(report, role))?; + refs.push(p.receipt_reference(get(e, "uid"))? as f64); + let kind = get(e, "kind").as_str().unwrap_or(""); + let definition = if ["chess", "item", "token", "band"].contains(&kind) { + let id = field(e, "id")?; + id.as_str() + .and_then(|id| self.entities.get(&identity(kind, id))) + .copied() + .unwrap_or(0) + } else { + 0 + }; + definitions.push(definition as f64); + } + let mut out = refs; + out.extend(definitions); + // history used/limit must be valid even outside PREP, as in project(). + let used = number(field(history, "used")?)?; + let limit = number(field(history, "limit")?)?; + if string(state, "phase")? == "PREP" { + if limit == 0. { + return Err("Zero public preparation budget".into()); + } + out.extend([1., ((limit - used) / limit).max(0.)]); + } else { + out.extend([0., 0.]); + } + out.extend([ + bit(!report.is_null()), + bit(truth(report) && truth(field(report, "accepted")?)), + bit(truth(report) && python_equal(field(report, "round")?, field(state, "round")?)), + ]); + flags(&mut out, get(report, "action_type"), &ACTIONS); + flags(&mut out, get(report, "error_class"), &ERRORS); + let changes = optional_object(get(report, "changes"))?; + for (i, key) in CHANGES.iter().enumerate() { + out.push(scalar( + num(changes, key, 0.)?, + if i < 2 { 30. } else { 10. }, + )); + } + let deltas = optional_object(get(report, "bond_layer_deltas"))?; + for key in BONDS { + out.push(scalar(num(deltas, key, 0.)?, 100.)); + } + let intent = optional_object(get(report, "intent"))?; + let to = optional_object(get(intent, "to"))?; + flags(&mut out, get(intent, "dir"), &DIRECTIONS); + flags(&mut out, get(to, "area"), &["board", "hand"]); + let values = [ + to.get("row").unwrap_or(get(intent, "row")), + to.get("col").unwrap_or(get(intent, "col")), + get(to, "idx"), + get(intent, "slot"), + get(intent, "idx"), + get(get(report, "source"), "row"), + get(get(report, "source"), "col"), + get(get(report, "target"), "row"), + get(get(report, "target"), "col"), + ]; + for value in values { + out.extend([ + if value.is_null() { + 0. + } else { + scalar(number(value)?, 21.) + }, + bit(!value.is_null()), + ]); + } + Ok(out) + } + + fn action( + &self, + state: &Value, + p: &Projection, + action: &Value, + ) -> Result<(Vec, i64, i64)> { + let t = string(action, "t")?; + let kind = t.get(2..).ok_or("Invalid native action type")?; + if !ACTIONS.contains(&kind) { + return Err("Unknown native action feature identity".into()); + } + let own = field(state, "own")?; + let shop = field(own, "shop")?; + let has_subject = ["buy", "reward", "choice", "band"].contains(&kind); + // Subject actions project a catalog identity instead of an instance UID. + let mut source = if has_subject { + 0 + } else { + p.reference(action.get("uid").unwrap_or(get(action, "itemUid")))? + }; + let mut target = p.reference(get(action, "targetUid"))?; + let replaced = p.reference(get(action, "replaceUid"))?; + let mut subject = 0; + let mut destination = serde_json::Map::new(); + let mut cost = 0.; + let mut semantic = kind; + if kind == "move" { + if source == 0 { + return Err("Move requires known public source UID".into()); + } + let to = field(action, "to")?; + destination = object(to)?.clone(); + let area = string(to, "area")?; + let location = &p.entities[source - 1]; + if area == "board" { + let row = coord(field(to, "row")?)?; + let col = coord(field(to, "col")?)?; + target = row + .zip(col) + .and_then(|cell| p.occupied.get(&cell).copied()) + .unwrap_or(0); + semantic = if location.area == 0 { + if target != 0 && target != source { + "board_swap" + } else { + "reposition" + } + } else if target != 0 { + "reserve_replace" + } else { + "deploy" + }; + } else if area == "hand" { + let slot = integer(field(to, "idx")?)?; + let hand = array(field(own, "hand")?)?; + let occupant = usize::try_from(slot) + .ok() + .and_then(|i| hand.get(i)) + .unwrap_or(&EMPTY); + target = if occupant.is_null() { + 0 + } else { + p.reference(field(occupant, "uid")?)? + }; + semantic = if location.area == 0 { + "withdraw" + } else { + "reserve_move" + }; + } else { + return Err("Unknown public move destination area".into()); + } + } else { + for key in ["row", "col"] { + if let Some(v) = action.get(key) { + destination.insert(key.to_owned(), v.clone()); + } + } + if ["buy", "reward", "choice"].contains(&kind) { + let key = if kind == "buy" { "slot" } else { "idx" }; + let slot = integer(field(action, key)?)?; + let slots = if kind == "buy" { + field(shop, "slots")? + } else if kind == "reward" { + get(get(shop, "rewardOffer"), "slots") + } else { + let choice = if string(state, "phase")? == "PREP" { + get(own, "personalChoice") + } else { + get(field(state, "public")?, "sp") + }; + get(choice, "cards") + }; + let row = if slots.is_null() { + &EMPTY + } else { + usize::try_from(slot) + .ok() + .and_then(|i| slots.as_array().and_then(|a| a.get(i))) + .unwrap_or(&EMPTY) + }; + cost = if row.is_null() { + 0. + } else { + num(row, "price", 0.)? + }; + source = 0; // purchase/choice descriptor has no instance UID + let map = if kind == "buy" { + &p.shop + } else if kind == "reward" { + &p.offer + } else { + &p.choice + }; + subject = usize::try_from(slot) + .ok() + .and_then(|i| map.get(&i)) + .copied() + .ok_or("Unknown public offer reference")?; + } else if kind == "band" { + source = 0; + subject = *p + .bands + .get(string(action, "bandId")?) + .ok_or("Unknown public band offer reference")?; + } else if kind == "levelUp" { + cost = number(field(shop, "upgradePrice")?)?; + } else if kind == "refresh" { + cost = if number(field(shop, "freeRefreshes")?)? > 0. { + 0. + } else { + number(field(shop, "refreshPrice")?)? + }; + } + } + let row = if subject > 0 { + &p.entities[subject - 1].row + } else { + &EMPTY + }; + let subject_entity = if subject > 0 { + Some(&p.entities[subject - 1]) + } else if source > 0 { + Some(&p.entities[source - 1]) + } else { + None + }; + let mut counts = [0; 4]; + let mut needed = 0.; + if let Some(entity) = subject_entity { + let def = self.definition(&entity.definition)?; + // Python uses rec={} for non-chess; family lookup then uses row.id. + let base = if get(&entity.row, "kind").as_str() == Some("chess") { + needed = def.upgrade; + Some(def.base.as_str()) + } else { + get(&entity.row, "id").as_str() + }; + if let Some(base) = base { + counts = p.families.get(base).copied().unwrap_or([0; 4]); + } + } + let to = Value::Object(destination); + let row_value = to.get("row").unwrap_or(get(action, "row")); + let col_value = to.get("col").unwrap_or(get(action, "col")); + let destination = if row_value.is_null() || col_value.is_null() { + 0 + } else { + // Python dict lookup accepts numerically equal integer/float cells. + let r = number(row_value)?; + let c = number(col_value)?; + if r.fract() == 0. && c.fract() == 0. { + cell(r as i64, c as i64).map(|i| i + 1).unwrap_or(0) + } else { + 0 + } + }; + let mut out = vec![ + source as f64, + target as f64, + replaced as f64, + subject as f64, + destination as f64, + ]; + flags(&mut out, get(action, "dir"), &DIRECTIONS); + flags(&mut out, &Value::String(kind.to_owned()), &ACTIONS); + flags(&mut out, &Value::String(semantic.to_owned()), &MOVES); + out.extend([ + scalar(cost, 30.), + scalar(num(row, "coin", 0.)?, 10.), + scalar(num(row, "count", 0.)?, 10.), + scalar(num(row, "rounds", 0.)?, 10.), + ]); + out.extend(counts.into_iter().map(|n| scalar(n as f64, 3.))); + out.extend([ + scalar(needed, 3.), + scalar( + (needed - (counts[0] + counts[1] + counts[2]) as f64).max(0.), + 3., + ), + bit(get(&to, "area").as_str() == Some("hand")), + scalar(num(&to, "idx", -1.)?, 10.), + ]); + let schedule = if kind == "move" { + match semantic { + "deploy" => "deploy", + "reserve_replace" => "replace", + "withdraw" => "withdraw", + "reposition" | "board_swap" | "reserve_move" => "adjust", + _ => return Err("Unknown public movement intent".into()), + } + } else if kind == "infoReady" { + "confirm" + } else { + kind + }; + let schedule = SCHEDULES + .iter() + .position(|s| *s == schedule) + .ok_or("Unknown explicit native decision intent")? as i64; + let expert = i64::from( + ![ + "buy", "refresh", "freeze", "levelUp", "band", "choice", "reward", + ] + .contains(&kind), + ); + Ok((out, schedule, expert)) + } +} + +fn simple_row(kind: &str, id: &str) -> Value { + let mut row = serde_json::Map::new(); + row.insert("kind".into(), Value::String(kind.to_owned())); + row.insert("id".into(), Value::String(id.to_owned())); + Value::Object(row) +} +// Python public choice comparison treats 1 and 1.0 (and booleans) as equal. +fn python_equal(a: &Value, b: &Value) -> bool { + match (a, b) { + (Value::Number(_), Value::Number(_)) => a.as_f64() == b.as_f64(), + (Value::Bool(x), Value::Number(_)) | (Value::Number(_), Value::Bool(x)) => { + let n = if a.is_number() { a } else { b }; + n.as_f64() == Some(bit(*x)) + } + (Value::Array(x), Value::Array(y)) => { + x.len() == y.len() && x.iter().zip(y).all(|(a, b)| python_equal(a, b)) + } + (Value::Object(x), Value::Object(y)) => { + x.len() == y.len() + && x.iter() + .all(|(k, v)| y.get(k).is_some_and(|other| python_equal(v, other))) + } + _ => a == b, + } +} diff --git a/crates/python/src/session.rs b/crates/python/src/session.rs new file mode 100644 index 0000000..aee99ed --- /dev/null +++ b/crates/python/src/session.rs @@ -0,0 +1,535 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use crate::NativeCatalog; +use arkguard_engine::{data::Catalog, solo::session::Session}; +use pyo3::{ + exceptions::{PyRuntimeError, PyValueError}, + prelude::*, + types::PyBytes, +}; +use std::sync::Arc; + +/// Persistent execution API; JSON diagnostics are deliberately separate from receipts. +/// No policy observation or Gym registration is implied by this development binding. +#[pyclass] +pub struct NativeSolo { + data: Arc, + core: String, + banned: Vec, + setup_revision: u32, + session: Option, + public: Option>, + policy: Option, + ledger: Option, + domain: Option, + policy_token: u64, +} +impl NativeSolo { + fn live(&mut self) -> PyResult<&mut Session> { + self.session + .as_mut() + .ok_or_else(|| PyRuntimeError::new_err("Reset required")) + } + fn step_decision_value( + &mut self, + py: Python<'_>, + action: &serde_json::Value, + tick_budget: usize, + max_advances: usize, + ) -> PyResult { + let retired = self.domain.take(); + let mut ledger = self + .ledger + .take() + .ok_or_else(|| PyRuntimeError::new_err("Reset a decision session before stepping"))?; + let result = py.detach(|| { + drop(retired); + ledger + .step(self.live()?, action, tick_budget, max_advances) + .map_err(PyRuntimeError::new_err) + }); + match result { + Ok(result) => { + self.public = Some(ledger.state.clone()); + self.ledger = Some(ledger); + Ok(result) + } + Err(error) => { + self.close(); + Err(error) + } + } + } +} +#[pymethods] +impl NativeSolo { + #[new] + #[pyo3(signature = (catalog, core, banned=None, diy_json=None, setup_revision=0))] + fn new( + catalog: &NativeCatalog, + core: String, + banned: Option>, + diy_json: Option<&str>, + setup_revision: u32, + ) -> PyResult { + if !matches!( + core.as_str(), + "band_amiya" | "band_sarkazb" | "band_chen" | "band_sciurus" + ) { + return Err(PyValueError::new_err("Unsupported core")); + } + let banned = banned.unwrap_or_default(); + if banned.len() > 4096 || banned.iter().any(|s| s.len() > 256) { + return Err(PyValueError::new_err("Manual bans exceed capacity")); + } + let data = if let Some(picks) = diy_json { + if picks.len() > 4096 { + return Err(PyValueError::new_err( + "DIY configuration exceeds byte limit", + )); + } + let picks = + serde_json::from_str(picks).map_err(|e| PyValueError::new_err(format!("{e}")))?; + Arc::new( + catalog + .inner + .with_diy(&picks) + .map_err(PyValueError::new_err)?, + ) + } else { + Arc::clone(&catalog.inner) + }; + Ok(Self { + data, + core, + banned, + setup_revision, + session: None, + public: None, + policy: None, + ledger: None, + domain: None, + policy_token: 0, + }) + } + /// Replace the episode, retaining immutable definitions. A failed reset + /// leaves no old episode available to accidentally continue. + fn reset(&mut self, py: Python<'_>, seed: u32) -> PyResult { + self.session = None; + self.public = None; + self.ledger = None; + self.domain = None; + let session = py + .detach(|| { + Session::new_at_revision( + Arc::clone(&self.data), + seed, + &self.core, + &self.banned, + self.setup_revision, + ) + }) + .map_err(PyRuntimeError::new_err)?; + let status = session + .status() + .map_err(PyRuntimeError::new_err)? + .to_string(); + self.session = Some(session); + Ok(status) + } + fn step(&mut self, py: Python<'_>, action_json: &str, tick_budget: usize) -> PyResult { + if action_json.len() > 4096 { + return Err(PyValueError::new_err("Action exceeds byte limit")); + } + let action = serde_json::from_str(action_json) + .map_err(|e: serde_json::Error| PyValueError::new_err(e.to_string()))?; + self.public = None; + self.ledger = None; + self.domain = None; + let live = self.live()?; + py.detach(|| live.step(&action, tick_budget)) + .map(|v| v.to_string()) + .map_err(PyRuntimeError::new_err) + } + fn advance(&mut self, py: Python<'_>, tick_budget: usize) -> PyResult { + self.public = None; + self.ledger = None; + self.domain = None; + let live = self.live()?; + py.detach(|| live.advance(tick_budget)) + .map(|v| v.to_string()) + .map_err(PyRuntimeError::new_err) + } + fn observation(&mut self, py: Python<'_>) -> PyResult { + py.detach(|| { + if self.public.is_none() { + self.public = Some(Arc::new( + self.live()? + .observation() + .map_err(PyRuntimeError::new_err)?, + )); + } + Ok(self.public.as_ref().unwrap().to_string()) + }) + } + fn reset_decision(&mut self, py: Python<'_>, seed: u32, stream_id: String) -> PyResult { + self.reset(py, seed)?; + let result = py.detach(|| { + let state = Arc::new( + self.live()? + .observation() + .map_err(PyRuntimeError::new_err)?, + ); + let mut ledger = crate::ledger::DecisionLedger::new(state, stream_id) + .map_err(PyValueError::new_err)?; + let result = ledger + .snapshot(None, None, 0) + .map_err(PyValueError::new_err)?; + self.public = Some(ledger.state.clone()); + self.ledger = Some(ledger); + Ok(result) + }); + if result.is_err() { + self.close(); + } + result + } + fn step_decision( + &mut self, + py: Python<'_>, + action_json: &str, + tick_budget: usize, + max_advances: usize, + ) -> PyResult { + if action_json.len() > 4096 || !(1..=108000).contains(&tick_budget) { + return Err(PyValueError::new_err( + "Invalid decision action size or tick budget", + )); + } + let action = + serde_json::from_str(action_json).map_err(|e| PyValueError::new_err(format!("{e}")))?; + self.step_decision_value(py, &action, tick_budget, max_advances) + } + + fn step_index( + &mut self, + py: Python<'_>, + revision: u64, + token: u64, + index: usize, + tick_budget: usize, + max_advances: usize, + ) -> PyResult { + if !(1..=108000).contains(&tick_budget) { + return Err(PyValueError::new_err("Invalid decision tick budget")); + } + let action = self + .domain + .as_ref() + .ok_or_else(|| { + PyValueError::new_err("Build a native candidate domain before stepping") + })? + .selected(revision, token, index) + .map_err(PyValueError::new_err)?; + self.step_decision_value(py, &action, tick_budget, max_advances) + } + /// Compile public model metadata once, outside the per-decision path. + fn configure_policy(&mut self, py: Python<'_>, metadata_json: &[u8]) -> PyResult<()> { + if metadata_json.len() > 8 << 20 { + return Err(PyValueError::new_err("Policy metadata exceeds byte limit")); + } + let encoder = py + .detach(|| { + let metadata = serde_json::from_slice(metadata_json).map_err(|e| e.to_string())?; + crate::policy::PolicyEncoder::new(&metadata) + }) + .map_err(PyValueError::new_err)?; + self.policy = Some(encoder); + self.domain = None; + Ok(()) + } + /// Read the same allowlisted Rust state as observation(), with no Python + /// state projection or numeric tuples. History contains only public progress. + fn encode_policy<'py>( + &mut self, + py: Python<'py>, + expected_revision: u64, + history_json: &[u8], + actions_json: &[u8], + ) -> PyResult<( + Bound<'py, PyBytes>, + Bound<'py, PyBytes>, + Bound<'py, PyBytes>, + Bound<'py, PyBytes>, + )> { + if history_json.len() > 1 << 20 || actions_json.len() > 8 << 20 { + return Err(PyValueError::new_err("Policy input exceeds byte limit")); + } + self.live()?; + let state = self + .public + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("Observe before numeric encoding"))?; + if state["revision"].as_u64() != Some(expected_revision) { + return Err(PyValueError::new_err( + "Numeric observation revision mismatch", + )); + } + let encoder = self + .policy + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("Configure policy before numeric encoding"))?; + let encoded = py + .detach(|| { + let history = serde_json::from_slice(history_json).map_err(|e| e.to_string())?; + let actions: Vec = + serde_json::from_slice(actions_json).map_err(|e| e.to_string())?; + encoder.encode(state, &history, &actions) + }) + .map_err(PyValueError::new_err)?; + policy_buffers(py, &encoded) + } + fn encode_ledger_policy<'py>( + &mut self, + py: Python<'py>, + expected_revision: u64, + actions_json: &[u8], + ) -> PyResult> { + if actions_json.len() > 8 << 20 { + return Err(PyValueError::new_err("Policy input exceeds byte limit")); + } + let ledger = self + .ledger + .as_mut() + .ok_or_else(|| PyRuntimeError::new_err("Reset a decision session before encoding"))?; + if ledger.state["revision"].as_u64() != Some(expected_revision) { + return Err(PyValueError::new_err( + "Numeric observation revision mismatch", + )); + } + let encoder = self + .policy + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("Configure policy before numeric encoding"))?; + let encoded = py + .detach(|| { + let actions: Vec = + serde_json::from_slice(actions_json).map_err(|e| e.to_string())?; + encoder.encode(&ledger.state, &ledger.policy_history, &actions) + }) + .map_err(PyValueError::new_err)?; + policy_buffers(py, &encoded) + } + fn status(&mut self) -> PyResult { + self.live()? + .status() + .map(|v| v.to_string()) + .map_err(PyRuntimeError::new_err) + } + fn build_ledger_policy<'py>( + &mut self, + py: Python<'py>, + expected_revision: u64, + prefix_json: &[u8], + prepared: Option, + ) -> PyResult<( + String, + Bound<'py, PyBytes>, + Bound<'py, PyBytes>, + Bound<'py, PyBytes>, + Bound<'py, PyBytes>, + )> { + if prefix_json.len() > 8 << 20 { + return Err(PyValueError::new_err("Policy input exceeds byte limit")); + } + let ledger = self + .ledger + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("Reset a decision session before encoding"))?; + if ledger.state["revision"].as_u64() != Some(expected_revision) { + return Err(PyValueError::new_err( + "Numeric observation revision mismatch", + )); + } + let encoder = self + .policy + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("Configure policy before numeric encoding"))?; + let (actions, encoded) = py + .detach(|| { + let prefix = serde_json::from_slice(prefix_json).map_err(|e| e.to_string())?; + let actions = crate::candidates::build( + prefix, + prepared, + &ledger.blocked, + ledger.state["personalEnded"] == true, + )?; + let encoded = encoder.encode(&ledger.state, &ledger.policy_history, &actions)?; + Ok::<_, String>(( + serde_json::to_string(&actions).map_err(|e| e.to_string())?, + encoded, + )) + }) + .map_err(PyValueError::new_err)?; + let (observation, candidates, schedules, experts) = policy_buffers(py, &encoded)?; + Ok((actions, observation, candidates, schedules, experts)) + } + fn build_current_policy<'py>( + &mut self, + py: Python<'py>, + expected_revision: u64, + ) -> PyResult<(u64, String, PolicyBuffers<'py>)> { + let ledger = self + .ledger + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("Reset a decision session before encoding"))?; + if ledger.state["revision"].as_u64() != Some(expected_revision) { + return Err(PyValueError::new_err( + "Numeric observation revision mismatch", + )); + } + let policy = self + .policy + .as_ref() + .ok_or_else(|| PyRuntimeError::new_err("Configure policy before numeric encoding"))?; + let token = self + .policy_token + .checked_add(1) + .ok_or_else(|| PyRuntimeError::new_err("Candidate token overflow"))?; + let retired = self.domain.take(); + let (actions, json, encoded) = py + .detach(|| { + drop(retired); + let actions = policy.current_candidates( + &ledger.state, + &ledger.policy_history, + &ledger.blocked, + )?; + let encoded = policy.encode(&ledger.state, &ledger.policy_history, &actions)?; + let json = serde_json::to_string(&actions).map_err(|e| e.to_string())?; + Ok::<_, String>((actions, json, encoded)) + }) + .map_err(PyValueError::new_err)?; + let buffers = policy_buffers(py, &encoded)?; + self.policy_token = token; + self.domain = Some(crate::ledger::PolicyDomain { + revision: expected_revision, + token, + actions, + }); + Ok((token, json, buffers)) + } + /// Private debugging data, including RNG and pool state. Not a policy input. + fn diagnostics(&mut self, py: Python<'_>) -> PyResult { + let live = self.live()?; + py.detach(|| live.diagnostics()) + .map(|v| v.to_string()) + .map_err(PyRuntimeError::new_err) + } + #[pyo3(signature = (expected_revision=None))] + fn public_spatial( + &mut self, + py: Python<'_>, + expected_revision: Option, + ) -> PyResult { + let live = self.live()?; + let (spatial, revision) = py + .detach(|| { + let spatial = live.public_spatial_json()?; + let revision = live.status()?["revision"] + .as_u64() + .ok_or("Missing session revision")?; + Ok::<_, String>((spatial, revision)) + }) + .map_err(PyRuntimeError::new_err)?; + if expected_revision.is_some_and(|expected| expected != revision) { + return Err(PyValueError::new_err("Public spatial revision mismatch")); + } + Ok(spatial) + } + #[pyo3(signature = (geometry_key=None, expected_revision=None))] + fn public_spatial_update( + &mut self, + py: Python<'_>, + geometry_key: Option<&str>, + expected_revision: Option, + ) -> PyResult<(String, Option, String)> { + if geometry_key.is_some_and(|key| key.len() > 8 << 20) { + return Err(PyValueError::new_err( + "Public spatial key exceeds byte limit", + )); + } + let live = self.live()?; + py.detach(|| { + let status = live.status().map_err(PyRuntimeError::new_err)?; + if expected_revision + .is_some_and(|expected| status["revision"].as_u64() != Some(expected)) + { + return Err(PyValueError::new_err("Public spatial revision mismatch")); + } + live.public_spatial_update(geometry_key) + .map_err(PyRuntimeError::new_err) + }) + } + fn replay_frame(&mut self, py: Python<'_>) -> PyResult { + let live = self.live()?; + py.detach(|| live.replay_frame()) + .map(|frame| frame.to_string()) + .map_err(PyRuntimeError::new_err) + } + fn movement_batch_ticks(&mut self) -> PyResult> { + self.live()? + .movement_batch_ticks() + .map_err(PyRuntimeError::new_err) + } + fn movement_path_steps(&mut self) -> PyResult> { + self.live()? + .movement_path_steps() + .map_err(PyRuntimeError::new_err) + } + fn event_window_stats(&mut self) -> PyResult> { + self.live()? + .event_window_stats() + .map_err(PyRuntimeError::new_err) + } + fn close(&mut self) { + self.session = None; + self.public = None; + self.ledger = None; + self.domain = None; + } +} + +type PolicyBuffers<'py> = ( + Bound<'py, PyBytes>, + Bound<'py, PyBytes>, + Bound<'py, PyBytes>, + Bound<'py, PyBytes>, +); + +fn policy_buffers<'py>( + py: Python<'py>, + encoded: &crate::policy::Encoded, +) -> PyResult> { + let floats = |values: &[f32]| { + PyBytes::new_with(py, values.len() * 4, |bytes| { + for (out, value) in bytes.chunks_exact_mut(4).zip(values) { + out.copy_from_slice(&value.to_le_bytes()); + } + Ok(()) + }) + }; + let ints = |values: &[i64]| { + PyBytes::new_with(py, values.len() * 8, |bytes| { + for (out, value) in bytes.chunks_exact_mut(8).zip(values) { + out.copy_from_slice(&value.to_le_bytes()); + } + Ok(()) + }) + }; + Ok(( + floats(&encoded.observation)?, + floats(&encoded.candidates)?, + ints(&encoded.schedules)?, + ints(&encoded.experts)?, + )) +} diff --git a/docs/NATIVE-033.md b/docs/NATIVE-033.md index 9cb8ce7..0a67c69 100644 --- a/docs/NATIVE-033.md +++ b/docs/NATIVE-033.md @@ -1,12 +1,21 @@ -# 0.3.3 原生迁移 +# 0.3.3 原生运行时与迁移笔记 + +当前入口为 `ArkGuardRL-v1`,支持原生账本、候选参数准备、索引执行、slots 并行、公开空间增量输入和渲染回放。当前验收及用法见 [性能与验收说明](../benchmarks/README.md)。 + +下文按阶段保留迁移实现笔记,其中测试命令、数量、main 状态与待办描述属于对应历史阶段。测试源码及对照夹具已按要求移除。 目标:Rust 完整环境内核 + Python 薄 Gymnasium 接口。行为基线为 Stronghold Protocol `41bbca5712ac08394bbc4d5b4e3411c6be1634b6`(0.3.3);训练保留在 ArkGuardRL。 运行数据由用户另行提供,不打包素材、权重或轨迹。 +当前仅维护绝境(`mode_single_abyss`)。后续迁移、内容补齐与验收均以绝境为范围;标准等其他模式不列入维护目标。历史多模式实现和测试记录不构成支持承诺。 +迁移及上线范围限定第二期下半(`act2autochess` / `V2_2`),以本期可入池干员为准 +(`visible=true`、`isHidden=false`、`isDiy=false`)。已移除干员和旧卡位不列入后续目标,同名干员使用本期卡位。 +本期干员按外部数据 `skill` 指定的默认技能实现,普通/精英版本使用同一技能, +天赋、职业特性和模组仍随对应版本接入。每人保留独立 Kit,技能注册与运行对照均按此单技能范围执行,其他技能在安装前拒绝。 + +单人范围已接入全部 42 个战斗装备系列和 14 个准备期装备系列,共 112 个普通/高级定义。三个法术已接入显式波次的单人流程;悬赏插入已支持原始动作窗口;按种子生成地图、阵营和波次及手动禁卡入口已接入。本期地图机关、准备期部署限制及谢拉格寒风自动触发已接入。绝境机变、战斗盟约及成长结转已接入;核心维护阿米娅、歌利亚、陈、休露丝,由实验配置指定,不设置核心选择动作。公开策略观测及 Gymnasium 适配已接通,Rust slots 批量实验入口与真实记录验证结果见 `benchmarks/README.md`。 -**目前不能发布为完整原生环境。** 正式安装仍提供旧 Node 环境;`crates/python` 只有数据目录 -和种子派生的开发绑定,未注册 `ArkGuardRL-v1`。完整局内状态机、原生批量接口、 -逐决策整局对照及完整 env 单线程至少 5 倍的性能验收都尚未完成。 +原生 Gym 入口为 `arkguardrl_core.native_gym` 注册的 `ArkGuardRL-v1`,Node 兼容入口为 `ArkGuardRL-v0`。Windows CI 构建三个原生模块;当前真实记录验收覆盖 63 份对局,已知差异与自选特征限制详见上方验收说明。 ## 已实现 @@ -17,28 +26,74 @@ - 1/30 秒阶段调度、技能/SP 生命周期、攻击锁定、直接/群体/链式攻击及追踪弹道。 - 路线/传送门、恐惧/诱导、推拉碰撞、失衡、敌方攻击前后摇及命中时属性读取。 - 波次转换、刷怪、预统计/运行时敌人、击杀/漏怪/赏金、超时扣除未生成敌人。 -- 78 种敌人的完整能力组合:原版纯属性敌人、基础隐匿、14 种频次单位、基础折射/镜膜, - 以及 7 种元素攻击敌人。未支持的内容报错,不退化为普通攻击。 -- 原生友军已接入角峰、惊蛰、地灵、格雷伊、普罗旺斯的普通/精英默认版本(10 个定义),含默认技能、天赋、 +- 本期 249 种敌人的完整能力组合。包含原版纯属性敌人、基础隐匿、14 种频次单位、基础折射/镜膜与元素攻击, + 以及寒霜光环、攻击计数眩晕/强化、受击减防/奔跑/全场增益、低血量强化、次数盾、多目标攻击、周期强化/自伤和死亡爆炸, + 以及囚犯解放、深池方阵/伙友联动、重新隐匿后的强化标记、攻击眩晕、受击暴露、范围元素攻击、 + 死亡派生、断刃、范围隐匿、烹泉溅射、出血、周期范围伤害、逐火重生、石像飞行、污染区域、死亡毒雾、敌方防御光环、冲锋、夺弹、延迟炮击、悬浮坠落、失衡反应、点燃与召唤联动、载客、死亡强化与增益区域、攻击回合技能、持续施法、法术屏障、沿路线闪现、投弹与吞噬、寄生附着、转译和多形态重生。 + 未支持的内容报错,不退化为普通攻击。 +- 基础地形接入沼泽叠层、烟雾隐匿、深水水蚀和源石污染区接触效果,含部署、移动、再部署与飞行判定。 +- 原生友军已接入角峰、惊蛰、地灵、格雷伊、普罗旺斯、艾丝黛尔、红豆、德克萨斯、送葬人、蛇屠箱、幽灵鲨、灰毫、诗怀雅、盟约·辅助干员、宴、砾、拉普兰德、雷蛇、深巡,以及下述新增干员的普通/精英默认版本(236 个定义),含默认技能、天赋、 连锁/溅射、命中停顿、部署、死亡/撤退清理及扣费再部署;Field 连接双向弹道和 DP 回复。 内容沿用原版 Kit / SkillSpec / 事件回调结构,共享原生计算机制。 命中回调保留连续血量倍率、正前方判定及暴击 RNG 顺序;被动技能与普通攻击分开结算。 + 角峰、惊蛰、格雷伊普通/精英版本另支持一技能:生命回复、保留衰减的连锁、原时长停顿。 + 普罗旺斯另支持二技能的攻击增益、80% 血量门槛与攻击前重选目标;不叠加一技能倍率。 + 艾丝黛尔支持两个技能、受击回 SP、群攻近卫选敌、技能禁疗、附近敌人死亡自疗,以及精英模组的血量条件物理减伤。 + 红豆两个技能接入单次攻击随机增益、技能攻击间隔变化、精英模组低血量倍率与击杀回复 DP。 + 德克萨斯支持两个瞬发技能、初始/施法 DP 与剑雨范围伤害/眩晕;送葬人支持两个技能、全范围攻击、 + 二连击、命中时前排倍率和天赋固定无视防御。 + 蛇屠箱支持壳状防御/条件防御,幽灵鲨支持技能不死/结束眩晕,灰毫支持要塞远近攻击/地形天赋, + 诗怀雅支持近战光环/技能放大与扩展,盟约·辅助干员支持按序附加三种元素损伤;均接入其普通/精英可选技能。 + 宴支持部署扣血/法伤、低血攻速/庇护及自疗,砾支持部署护盾/防御衰减和低费防御光环, + 拉普兰德支持沉默、领主远程衰减、模组附伤与双目标法伤,雷蛇支持受击回 SP/随机友军充能、 + 伤害抵挡及技能眩晕,深巡支持持续法伤、技能扩展射程与停顿;均接入双技能,精英哨戒铁卫接入揭隐。 + 新增隐现、野鬃、崖心、泡泡、协律、折桠、能天使、断崖、斯卡蒂、松果、流星、寒芒克洛丝、风笛、莱恩哈特、星熊的独立 Kit, + 覆盖其普通/精英与全部可选技能,包含弹药支援、推拉、伤判抵挡/反伤、友军增益、复活、充能与多段攻击。 + 继续接入刺玫、古米、波登可、小满、休谟斯、调香师、见行者、薄绿、海霓、初雪、凯瑟琳、白面鸮、银灰、百炼嘉维尔、华法琳的独立 Kit, + 覆盖普通/精英及全部可选技能,连接治疗模式、咒愈、回复光环、持续区域、收割者排队自疗、延迟扣血、推拉与复合天赋。 + 凯瑟琳按未部署支援装置的棋盘运行,支援装置的部署和护盾仍随 token 系统后续接入。 + 该批次已通过测试目标编译检查,运行验证已由用户手动完成。 + 第二期下半继续接入哈洛德、莫斯提马、水月、阿罗玛、卡涅利安、泥岩、焰尾、远牙、铃兰、山、史尔特尔、安洁莉娜、五费录武官、歌蕾蒂娅、灵知, + 普通/精英和全部技能均有独立 Kit 构建器。本期可入池名单中的已迁移干员合计 58 名(本期共 112 名);历史定义另用于已有对照。 + 本批补齐元素治疗/减损、蓄力与标记、护盾层数、闪避反击、持续 DP、全场额外射程、回复/失重光环、龙卷与冻结延长/结束爆发。 + 该批运行测试已由用户手动验证通过。 + 继续接入莎草、锡人、菲莱、雪猎、瑕光、空弦、信仰搅拌机、缄默德克萨斯、塞雷娅、玛恩纳、寒檀、异客、仇白、佩佩、流明。 + 每名干员独立 Kit,覆盖普通/精英及全部可选技能。该批完成后为 73/112 名,运行验证已由用户手动完成。 + 本批连接连锁治疗/护盾、炼金持续区域、元素屏障、猎手装填、伤判反击、首次击杀重开技能、解放者蓄力、延迟冰凌/雷暴和异常状态治疗。 + 本批继续接入跃跃、深靛、赫默、洛洛、蒂比、至简、忍冬、耶拉、伊内丝、魔王、圣约送葬人、缇缇、烛煌、号角、归溟幽灵鲨、妮芙、塑心、溯光星源、锏、纯烬艾雅法拉。 + 每人一个独立 Kit,覆盖普通/精英及已接入技能,烛煌仅支持三技能。该批完成后累计实现 93/112 名,运行对照已由用户验证通过。 + 最后 19 名接入普通/精英独立 Kit,本期累计 112/112 名,按约定只支持一个技能。 + 夕支持一技能;风丸、琳琅诗怀雅、凛御银灰、引星棘刺、迷迭香、新约能天使支持二技能;伺夜、乌尔比安、隐德来希、蕾缪安、圣聆初雪、余、浊心斯卡蒂、维娜·维多利亚、焰影苇草、缪尔赛思、耀骑士临光、荒芜拉普兰德支持三技能。 + 同时支持目录中 `GAIN_BUFF` 类作战特质的持久属性倍率,以及 `attr_common_global_buff` 的自然 SP、攻击、生命和攻速加成,其他特质仍待迁移。 + `Field::add_operator_with_skill` 按外部 `skills[].index` 选择,未知或未实现技能报错;模组和潜能仍用默认值。 - 保留原有进度奖励公式;其输入仍需由未来 match 层的真实结算产生。 -各模块仍通过显式 Rust host 接口连接内容。数据归一化覆盖全部 249 个外部敌人定义, -**不代表其能力都已实现**。通用技能生命周期与攻击计算通过对照,也不代表全部原版干员技能已完成。 +干员的职业/攻击元数据、技能列表与行为都由独立 Kit 提供,公共层保留注册及共享机制。 +每个干员的 Kit 位于 `battle/content/operators/` 的独立文件,普通/精英与技能共用构建器。 +加载时把外部参数组合为有类型的技能、攻击和增益规格;特殊命中与攻击前选敌通过内容回调执行。 +Field 负责固定阶段与事件入口,干员数值、倍率及目标条件留在 Kit 内;尚未引入 JSON 战斗解释器。 + +各模块仍通过显式 Rust host 接口连接内容。本期 249 个外部敌人定义已接入普通单人 Field。 +干员技能支持范围按本页的独立 Kit 与单技能约定执行。 不迁移渲染、音画、特效或显示事件;只保留影响运算的前摇、伤害帧等时序。 ## 具体执行入口 `battle::runtime::Field` 已直接拥有 World、RNG、刷怪、内容、增益和时钟, 独立执行部署→刷怪/DP→状态→攻击锁定→敌人更新→友军技能/攻击→弹道→再部署→内容 tick→结算。 -当前支持普通单人场、上述 10 个默认干员定义和敌人;其他干员、装备/盟约、地图战斗装置、特殊地形、 -Boss/部件尚未接入该入口,遇到未支持输入报错。它不是 Gymnasium 环境。 +当前支持普通单人场、单人 Boss/隐秘核心场、上述 236 个普通/精英干员定义和本期 249 个敌人定义。 +首领与部件保留身份标签,召唤、换代和触手动作接入有界分支及预设路线。 +装备已支持纯属性、攻击/治疗触发、技能叠层、受伤隐匿和持续自损。本期机关、特殊地形和地图效果见末尾验收记录;战斗盟约继续迁移。 +Boss 场已接入同场首领副本共用血池,以及单人 LP、超时扣血和胜负结算。 +`solo::Runner` 已接收准备好的波次与阵容,执行连续普通回合、最终攻势、隐秘核心与终局。 +基础商店、持有棋子、合成奖励与上阵操作已连接单人调度器。 +准备期已接入盟约成员与激活计数、持久层数、数值类特质、远见/奇迹经济与助力结算。 +干员赠送、松果招募奖励、铃兰触发与白面鸮/塞雷娅特质复制已接入准备期。 +装备已贯通准备期配发与战斗。后续连接其余装备、召唤物准备与模式波次生成,再接合法动作、观测和 Gymnasium。 `run(tick_budget)` 同步返回推进步数、自然结束及预算耗尽;预算耗尽保留真实后继状态, 不转成超时或重开。技术错误使执行入口失效,不能继续采样或返回有效结算。 -`report()` / `enemy_states()` / `ally_states()` 返回独立拥有的数据;它们是内部战斗诊断接口,不能作为策略观测。 +`report()` / `enemy_states()` / `ally_states()` / `boss_state()` / `boss_round_state()` 返回独立拥有的数据;它们是内部战斗诊断接口,不能作为策略观测。 资源容量按创建参数限制,超限报错而不裁剪。数据文件字节预算仍不等于解析后的总内存预算。 开发期可直接运行 Rust 入口,无需 Node: @@ -47,30 +102,573 @@ Boss/部件尚未接入该入口,遇到未支持输入报错。它不是 Gymna cargo run -p arkguard-engine --release --example field -- /path/to/data input.json 1800 ``` +Boss 输入在上述格式中增加 `"kind":"boss"` 或 `"kind":"hidden"`,以及 +`"bossPool":{"maxHp":100000,"hp":100000}`。省略 `hp` 使用满血,`maxHp` 至少为 1。 +这两种场的缺省时限为无限,仍保留 3600 秒硬上限。CLI 的 `row`/`col` 沿用战场绝对坐标, +Boss 场范围为行 0–5、列 0–20。Rust 入口为 `Field::new_boss(..., BossConfig)`。 + +单人回合可增加 `"bossRound":{"lp":10,"overtime":{"afterReal":120,"combatTimeScale":2,"lpPerSecond":1}}`。 +`overtime` 可省略,存在时按战场时钟折算真实秒,超过 `afterReal` 后逐整秒扣血。 +Rust 使用 `configure_boss_round(BossRoundConfig)`,`boss_round_state()` 和报告的 `bossRound` 返回剩余 LP、各类损失及终局原因。 + 输入使用原版的 `stage` 或 `stageId`、`routes`、`spawns`、`seed`、`timeLimit`; 友军可省略,或添加 `{"players":[{"playerId":"p","units":[{"chessId":"chess_char_1_02_a","uid":1,"row":10,"col":6}]}]}`。 -当前只接受已支持的默认干员,不接受物品或配装覆盖。例如地形可用 `{"rows":["..."]}` 的原版形状; +可用 `"skillIndex"` 选择对应 Kit 已接入的技能;不接受物品、模组或潜能覆盖。例如地形可用 `{"rows":["..."]}` 的原版形状; 实际关卡包含尚未移植的装置/地形时会报错。 此工具用于开发运算,不计作完整环境或性能验收。 +连续单人回合使用 `solo::Runner`。`RoundPlan` 提供波次、收入、时限与部署上限, +`ready(PreparedRound)` 接收当前准备期的阵容和激活盟约层数,`advance(tick_budget)` 推进到下一准备期或终局。 +`spend` 为准备期动作提供扣款入口。非法阵容在消耗回合计划前拒绝,执行错误使整局失效。 +该入口接收预先准备的波次。阵容可由 `PreparedRound` 提供,或通过 `enable_preparation` 启用持有库存,随后用 `prep_action` 操作并调用 `ready_owned`。 +启用准备期内容使用 `new_with_preparation`,初始获得先于首轮收入,`ready_current` 从持有状态计算激活层数。 +其余装备效果、召唤物准备、模式波次生成及战斗盟约效果/成长结转继续连接。 + +```sh +cargo run -p arkguard-engine --offline --release --example solo -- /path/to/data planned-run.json 100000 +``` + +单人 CLI 输入包含 `stage`、`seed`、`config` 和 `plans`。 +`config` 使用 `lp`、`lpCap`、`keepFunds` 与可选的 `hidden`,后者含 `layerThreshold` 和 `minLp`。 +每项计划使用 Field 的 `routes`、`spawns`、`overrides` 等波次形状,另提供 `kind`、`timeLimit`、`income`、`deployCap`、 +`prepared` 和可选的 `spend`。Boss 计划增加 `maxHp` 与可选的 `overtime`。 +`prepared.units` 沿用 `chessId`、`uid`、`row`、`col`、`dir`,可选 `skillIndex` 与装备 ID 数组 `items`。`prepared.activeLayers` 提供准备完成时的激活层数。 +所有准备坐标使用行 9–12、列 2–10,单人调度器将 Boss 场位置向上平移 7 行。 +输出 `ticks`、`budgetExhausted` 和整局诊断 `state`。 + +操作驱动的准备期在顶层增加 `"preparation":{"modeId":"mode_single_normal"}`。 +可选的 `banned` 指定禁用基础干员,`initial` 以 `{"kind":"chess","id":"..."}` 或 `{"kind":"item","id":"..."}` 设定初始获得, +`capacity` 限制持有库存与奖励队列,默认 256。商店使用模式及全局经济数据和独立 shop RNG。 +手动 ban 入口沿用 `preparation.banned`,例如 `{"modeId":"mode_single_normal","banned":["chess_char_1_02_a"]}`。 +这是原版的卡池禁用:从商店及按卡池抽取的奖励中移除基础干员,初始配置、定向赠送和直接复制仍沿用各自规则。 +后续按种子生成模式的入口必须保留此参数,将手动名单与自动 ban 结果取并集;手动名单不参与地图、阵营、Boss、波次的 RNG 抽取,同一种子修改手动名单不应改变这些生成结果。该模式生成入口尚待实现。 +各回合以 `actions` 替代 `prepared.units`,沿用 `g.buy`、`g.refresh`、`g.freeze`、`g.levelUp`、`g.sell`、`g.destroy`、`g.reward` 和 `g.move` 的消息形状。 +`prepared.activeLayers` 可继续提供层数,省略时为 0。CLI 执行本回合操作后上阵,棋子库存会保留到下一准备期。 +`g.equip` 使用 `itemUid`、`targetUid` 与可选的 `replaceUid`。装备槽满时销毁指定装备,省略时销毁最早配发的一件。手动 `g.unequip` 沿用原版锁定规则。出售与晋升返还装备,已装备物品参与库存和合并,持有阵容会自动携带装备进入战斗。 +已支持全部 42 个战斗装备系列、84 个普通/高级定义。包含维式重锤、坚守盾牌、不屈弹射器、萨尔贡浓茶、激光发射器、阿戈尔重刃、蜂鸣器与变形同构体,以及源石溶剂、奥术法阵、精准狙击镜、炎国短刀、突袭手雷、有限加速器、伪装服、防暴盾、休眠子裔、卡西米尔竞技旗、浓缩嗅盐、催泪瓦斯、谢拉格不融冰、护盾无人机、叙拉古正装、迅捷作战粮、歌利亚头盔、拉特兰桥夹、双模机械臂、战栗/坚固/加速/灼燃维式重锤、蒸汽之心、铳骑之威、耶拉冈德之泪、天马之盔、天马之枪、海沟实验体、黄沙罗盘、M3 茧甲、天师古鼎、骑士戒律与家族徽章。变形同构体更新准备期盟约成员计数。尚未接入的装备效果在配发或加载阵容时拒绝,动作草稿回滚。 +增加 `"preparation":{"modeId":"mode_single_normal","effects":{}}` 启用准备期内容。 +`effects` 可选 `layers`、`countBonus` 和 `disabledBonds`,均按盟约 ID 配置。 +启用后由持有状态计算激活层数,回合输入中的 `prepared.activeLayers` 省略或取 0。 +支持当前 23 类盟约的成员计数与激活、999 层增长上限,以及层数/金币/免费刷新/价格类特质。 +远见返金与永久折扣、奇迹刷新随机判定、投资人获得时重复、调和计数及助力准备结束加层已接入。 +准备结束新增的里程碑返金作为下回合待收入资金保留。技术错误回滚动作草稿并使执行入口失效。 +固定装备赠送、加权装备池、指定回合装备赠送与维多利亚重锤奖励已接入。准备结束时的装备延后到下一准备期合并,新增溢出保留。干员赠送沿用库存、溢出与精锐合成,松果售出奖励使用独立 meta RNG 抽取,合成奖励继续使用 shop RNG。 +复制按接收者的位置和盟约结算,支持前方复制链及触发获得时特质,深度上限沿用原版。 +准备事件按棋盘快照和实时手牌派发;主动刷新固定见证者,赠送完成合成后仍处理原有副本,新精锐从下次刷新起计数。 +其余装备效果、战斗盟约效果与层数成长结转仍待连接。 + + ## 验证 ```sh -cargo test -p arkguard-engine --offline --release -ARKGUARD_REFERENCE_ROOT=/path/to/game cargo test -p arkguard-engine --offline --release -- --include-ignored -PYO3_PYTHON=/path/to/python3 cargo build -p arkguard-python --offline +cargo test -p arkguard-engine --offline --release --lib +ARKGUARD_REFERENCE_ROOT=/path/to/game cargo test -p arkguard-engine --offline --release --lib operator_skill_definitions -- --ignored +ARKGUARD_REFERENCE_ROOT=/path/to/game cargo test -p arkguard-engine --offline --release --test field_reference operator_effects_checkpoints -- --ignored +ARKGUARD_REFERENCE_ROOT=/path/to/game cargo test -p arkguard-engine --offline --release --test field_reference equipment_effects_checkpoints -- --ignored +ARKGUARD_REFERENCE_ROOT=/path/to/game cargo test -p arkguard-engine --offline --release --test preparation_reference -- --include-ignored ``` +干员技能定义与战斗效果分别使用一个入口,输出保留干员、技能和场景信息。 +日常按改动范围运行相关测试。上述准备期对照覆盖基础经济及内容事件;完整历史逐帧对照仍可手动运行。 + Node 仅在 `tools/reference/` 中充当开发期上游对照。数值、RNG、事件次序与连续状态逐位比较; 不通过放宽误差掩盖分支差异。连续战斗覆盖 96 组、23,040 tick;具体 Field 入口另对照 上游完整内容模式下的 78 个空棋盘战场。另检查预算暂停、结果所有权、reset 隔离、 退场回收、未实现内容拒绝及技术错误失效。 角峰默认内容另有 18,000 tick 生命周期对照,覆盖多干员部署排序、零伤害/noSp、技能结束、 致命伤害、撤退与再部署;死亡同步释放阻挡、隐匿恢复及增益容量异常另行验证。 -带友军的具体 Field 另对照 116 个完整上游战场、160,680 tick,覆盖全部已支持敌人, -以及长战斗中的技能、元素爆发、四方向施法、待敌开技、射手死亡后的弹道、撤退和再部署; -检查单次/分段推进一致、弹道容量、返回值所有权,以及非攻击/溅射/连锁的随机回调范围。 +历史逐 tick 对照中的带友军 Field 覆盖 224 个完整上游战场、498,599 tick,覆盖全部已支持敌人, +以及角峰/惊蛰/格雷伊的一技能、艾丝黛尔的技能与自疗/减伤、普罗旺斯二技能的停火与混合血量选敌、长战斗中的技能、元素爆发、四方向施法、待敌开技、射手死亡后的弹道、撤退和再部署; +检查单次/分段推进一致、弹道容量、返回值所有权,以及非攻击/溅射/连锁的随机回调范围;另覆盖红豆/德克萨斯/送葬人合队。 + +日常按改动领域运行原生回归和相关对照。 +上一批五名干员的 22 个普通/精英、双技能、合队及隐匿敌人检查点场景已经通过。 +前一批 15 名干员另提供 68 个普通/精英技能组合与 2 个合队场景,按检查点抽查; +新增 14 项原生回归测试覆盖弹药、抵挡后的反伤、泡泡防御反伤/清理、斯卡蒂复活重置、队伍天赋安装顺序/重复来源、折桠自疗/受击开技施加战栗、 +寒芒克洛丝命中计数、充能容量、技能运行时借用期间的射程读取、领主四方向碰撞体边界伤害,以及三/四/五连击完整结算和超限定义拒绝。 +该批次另检查外部数据中的全部技能定义。 +前一批技能定义检查与 70 个检查点场景已由用户手动运行通过。原有完整对照保留为手动诊断。 +本次新增 21 项原生回归测试,覆盖治疗选敌/倍率、咒愈反击、古米治疗模式与烹制清理、波登可切换与持续区域、 +收割者排队/溢出盾、禁疗目标的回复光环、延迟扣血、阵法护甲/结束爆发、敌方光环清理、自然 SP 加成、 +血浆流失、技能借用期间的击杀回 SP/RNG、阵法对空触发、见行者高台再部署退款、医疗 SP 光环、凯瑟琳被动、全队再部署天赋,以及普通/精英作战特质的自然 SP 加成和再部署保留。 +该批次的技能定义检查 检查新批次 64 个普通/精英技能组合, +该批次的战斗对照 提供这 64 个组合与 2 个合队场景,并注入友军损血以覆盖治疗。 +这两项与新增回归测试已由用户手动运行通过。 + + +第二期下半上一批提供 20 项原生回归测试,以及该批次的技能定义检查的 84 个普通/精英技能组合, +该批次的战斗对照 覆盖这 84 个组合与 2 个合队场景。两项外部数据测试均核对本期可入池标记。 -后续关键工作是完整干员/敌人/盟约/装备/Boss 内容、战斗与局内状态机连接, + +本批增加 24 项原生回归测试,覆盖连锁治疗及护盾、无目标拒绝开技、退场后区域回复、元素屏障、空弹匣装填、 +睡眠选敌、破盾充能、致命伤弹药抵挡、首次击杀重施法、治疗充能、蓄力/阻挡切换、延迟抵抗、雷暴清理、 +仇白延迟附伤与攻速上限、佩佩跨次技能攻速及流明的选择性弹药消耗,以及 Kit 重部署状态、延迟事件顺序与容量、旧部署事件清理。 +该批次的技能定义检查 检查 80 个普通/精英技能组合,该批次的战斗对照 覆盖它们和两个合队场景。 +这 15 名干员的定义、参数、专属状态与运行行为集中在 `crates/engine/src/battle/runtime/kits/<干员>.rs`。 +共享层负责分发及有界定时调度,延迟生命周期事件保留原始上下文和部署序号。 +该批运行验证已由用户手动完成。 + + +本批 20 名新增 34 项普通原生测试,另有手动运行的该批次的技能定义检查 检查 102 个普通/精英技能组合, +该批次的战斗对照 覆盖这 102 个组合及 2 个合队场景。烛煌按用户要求仅支持三技能,显式选择一、二技能会在安装前拒绝,合队场景也使用三技能。每名干员的定义、参数、状态和行为位于自己的 Kit 文件。 +新增回环投射物返程、秘术师储能、驭械术师附加伤害及独立浮游单元、影哨、微尘、弹药追加、睡眠保护、倒地/替身、元素伤害与治疗等路径。 +本批的运行对照已由用户验证通过。外部数据与 Node 对照测试保留 `#[ignore]`,须使用下面的 `--ignored` 显式运行。 + + +engine 全量测试包含历史批次、技能定义和其他 Node 对照,使用 `--include-ignored` 执行普通及手动测试。 + +```sh +export ARKGUARD_REFERENCE_ROOT=/Users/harco/Programs/Stronghold-Protocol +cargo test -p arkguard-engine --offline --release --no-fail-fast -- --include-ignored +``` + +结构整理将最近两批 35 名独立 Kit 的技能生命周期、周期调度和攻击配置统一接入 `Behavior`。 +开始、结束、刷新及延迟事件归还由各 Kit 实现,公共分发层集中维护有界队列、部署序号、执行顺序和上下文恢复。 +初始化刷新传入零步长,帧末刷新传入实际步长,逐帧 `Tick` 由 `TickHook` 发出。 +第一轮新增 4 项生命周期回归测试。 +第二轮将最近两批 Kit 的攻击、伤害、治疗、击杀、元素与状态回调纳入公共接口,来源、目标和全局观察回调按原顺序路由。 +伤判与增益回调使用 Buff 的提供者定位 Kit,保留来源退场后的持续效果。额外补充 10 项交互回归测试。 +更早批次的组件式内容,以及区域和伤判效果安装等公共机制仍需继续整理。 +本轮完成测试目标编译检查,运行验证由用户手动执行。 + +后续关键工作是盟约、装备、Boss 战入口与战斗装置,以及战斗与局内状态机连接, 再接合法动作、公开结构化观测、Gymnasium、批量执行及整局性能验收。 这些完成前保留现有可运行链路,不将旧接口冒充原生 `ArkGuardRL-v1`。 + +最后一批新增 11 项原生回归,覆盖单技能限制、实际技能激活、替身、召唤物当帧行动与到期、战术点复活、流形复制、心烛清理,以及默认/浮点路线编号和刷怪队列清空后的战术点路径保留。该批次的技能定义检查 检查 38 个普通/精英默认技能,并拒绝其余技能;该批次的战斗对照 覆盖 38 个单人场景及 3 个合队场景。 + + +最后一批验收已运行 `cargo test -p arkguard-engine --offline --release --no-fail-fast -- --include-ignored`,201 项库测试与 82 项集成测试全部通过,0 失败、0 忽略。新批次 41 场对照累计 93,953 帧。`cargo check --workspace --offline` 通过。 + + +敌人能力批次新增 23 种敌人,完整能力覆盖增至 101 种。定义和有界计数状态放在 `content/enemies/abilities.rs`,运行时回调放在 `runtime/enemies.rs`,复用公共伤害、状态、Buff 和选择规则。敌人内容 tick 按敌人顺序执行,沉默暂停相应能力的计时与计数。新增 7 项原生边界回归与 `enemy_ability_batch_checkpoints`,46 场覆盖原始配置、波次技能覆盖和沉默/冻结干员协同,累计 104,988 帧。 + +本批已执行包含全部 ignored 用例的 engine release 全量验收,208 项库测试与 83 项集成测试全部通过,0 失败、0 忽略。 + + +敌人联动批次新增 20 种,完整能力覆盖增至 121 种。`content/enemies/families.rs` 保存族群参数和解放/破隐的独立状态,`runtime/enemies/families.rs` 接入攻击、受击与逐帧回调。重犯在解放攻击命中前强化,并通过单次广播解放场上其他囚犯;方阵只计算附近同定义的其他单位,伙友效果按各自规则筛选目标。新增 8 项原生边界回归与 `enemy_family_batch_checkpoints`,44 场覆盖参数覆盖、沉默/冻结协同和混合敌群,累计 103,420 帧。 + +本批已执行包含全部 ignored 用例的 engine release 全量验收,216 项库测试与 84 项集成测试全部通过,0 失败、0 忽略。`cargo check --workspace --offline` 通过。 + + +死亡派生与持续伤害批次新增 17 种,能力覆盖增至 138 种。`enemy_split_batch_checkpoints` 提供 38 场对照、89,856 帧,另有 8 项机制回归,覆盖剩余等待/传送路线、倍率与赏金继承、敌人更新中的反伤分裂、断刃清空冷却、范围隐匿、出血来源和治疗清理,以及巢涌者脉冲闪避。 + +本轮结构清理将派生目标在内容安装时编译保存,死亡结算传递类型化路线与刷怪数据,外部 JSON 入口和派生单位共用创建/统计逻辑。四条刷怪调用链通过同一借用范围恢复上下文。伤害种类、技能标记、闪避与选择规则通过 `hit::Request` 显式表达。持续效果引用的单位由 Buff 生命周期保活,覆盖替换、到期、容量失败和跳过回调的撤退清理。新增 8 项回归覆盖这些约束,并将敌人内容清理延后到实体最终回收,保留在途命中的附加能力。 + +敌人状态与事件分发的进一步收敛,以及更早干员的多套内容管线合并,仍需后续整理。 + +本轮已完成含全部 ignored 用例的 engine release 全量验收,232 项库测试与 85 项集成测试全部通过,0 失败、0 忽略。`cargo check --workspace --offline`、`git diff --check` 与参考脚本语法检查通过。 + + +形态与区域批次新增 12 种敌人,能力覆盖增至 150 种。重生和石像切换使用独立状态枚举,区域伤害复用有界定时器。形态计时随实际死亡取消,污染和燃烧区域保留来源直到结束,死亡毒雾按原版使用无来源弹道与区域。新增 11 项回归覆盖免死窗口、重复重生、真击杀计数、净化、次数盾、飞行、重叠污染、沉默、来源回收、战车 SP 和容量故障。`enemy_form_batch_checkpoints` 覆盖 28 场、50,897 帧。 + +本批已执行含全部 ignored 用例的 engine release 全量验收,243 项库测试与 86 项集成测试全部通过,0 失败、0 忽略。工作区编译检查与参考脚本语法检查通过。 + + +支援与受击机制批次新增 15 种敌人,能力覆盖增至 165 种。包含御4、两种护障、远眺、新手祭司学徒、异质裂兽·α、澪、萨卡兹穿刺手、萨卡兹悖谬暴虐兵长、萨科塔之翼/之眼、心虚设计师、两种帝国炮火先兆者和血珀。参数编译与计数状态集中在 `content/enemies/reactions.rs`,回调复用公共伤害、状态、治疗和有界调度。新增 12 项回归,另有 `enemy_reaction_batch_checkpoints` 的 35 场完整战斗对照,累计 71,712 帧,覆盖原始/覆盖参数、沉默/冻结、敌方光环与职业/技能弹药合队。 + +本批已执行含全部 ignored 用例的 engine release 全量验收,255 项库测试与 87 项集成测试全部通过,0 失败、0 忽略。工作区编译检查、参考脚本语法检查和差异空白检查通过。 + + +移动与生命周期批次新增 13 种敌人,能力覆盖增至 178 种。接入掠海漂移体、吉兆飞鳞、弧光锋卫、冒失的小弟、雪孩子、拥霜羽兽、假想敌:骨刺、卷心籽、灼藤、枯朽萃聚使徒、枯朽之种、主角阵营角色和简饲源石虫。形态状态、位移观察与施法冷却分别建模,召唤与死亡派生共用类型化刷怪入口,自爆单位复用追踪弹道并在弹道清除后回收。新增 14 项原生边界回归,`enemy_motion_batch_checkpoints` 覆盖 30 场、67,364 帧,包含冻结/推拉协同、点燃、召唤和两次致命伤害。 + +本批修正状态回调的适用范围,避免刷怪时的抵抗状态访问借出的内容上下文。扣血的元素伤害也按原版触发受击能力,元素损伤累计仍走独立入口。已执行含全部 ignored 用例的 engine release 全量验收,269 项库测试与 88 项集成测试全部通过,0 失败、0 忽略。工作区编译检查、参考脚本语法检查与差异空白检查通过。 + + +悬赏与支援批次新增 13 种敌人,能力覆盖增至 191 种。包含碎骨、遗弃者、邪魔的利刃、纠缠藤蔓、两种圆仔、喷气人、水遁忍者、萨科塔昂首、骸骨拷打者、咸鳞汁推荐者、越长尘和伊利昂的木驮兽。载客保留乘客身份并按生命周期保活,死亡和漏怪均释放乘客,卸载重置对应剩余路线。漏怪回调接收当前移动随机数流。新增 14 项原生边界回归,`enemy_leader_batch_checkpoints` 覆盖 34 场、76,052 帧,包含死亡/漏怪卸载、死亡派生、沉默/冻结/推拉和区域残留。 + +本批已执行含全部 ignored 用例的 engine release 全量验收,283 项库测试与 89 项集成测试全部通过,0 失败、0 忽略。工作区编译检查、参考脚本语法检查与差异空白检查通过。 + + +施法与屏障批次新增 11 种敌人,能力覆盖增至 202/249 种。包含重弩突袭者、死亡之眼、自行炮、节日爵士乐手、W、鼠王、迷路的巨像、陷落雪祀、泥岩、墓碑和弑君者。技能按优先级占用攻击回合,冷却纳入技能动画时长。延迟攻击和持续施法使用有界定时器,锁定目标和来源随任务保活,到期、打断和容量失败均释放引用。法术屏障在伤判阶段吸收对应伤害,并在本次结算结束后移除属性加成。 + +固定周期的干员效果与动态定时任务按实际截止时间合并排序,避免同帧灵知脆弱刷新改变刺玫反击伤害。新增 10 项原生回归,覆盖攻击回合、随机数消耗、屏障破裂与闪避、持续施法打断、死亡后 C4、引用回滚、链式伤害、闪现和截止时间排序。`enemy_caster_batch_checkpoints` 覆盖 28 场、64,348 帧。 + +本批已执行含全部 ignored 用例的 engine release 全量验收,293 项库测试与 90 项集成测试全部通过,0 失败、0 忽略。工作区全目标编译检查、参考脚本语法检查和差异空白检查通过。 + + +地形与联动批次新增 12 种敌人,能力覆盖增至 214/249 种。包含潜水员、两种码头水手、两种枯朽前锋、两种奇美拉、灵幛、愧悔魂灵圣杯、腐败骑士、凋零骑士和庞贝。源石接触保留离开后的剩余时长与伤害节拍,潜水员清理水蚀,奇美拉污染按单位和周期去重,圣杯在减伤前分出输入伤害。双骑士复用攻击回合和有界延迟任务,庞贝的阻挡爆炸计时随眩晕暂停,灼烧按目标 Buff 生命周期保留来源。 + +基础地形使用静态棋盘配置与单位接触状态,部署和移动共用刷新入口。友方增益选择独立于敌方范围攻击的筛选规则,并统一检查孤立。新增 13 项原生回归,`enemy_terrain_batch_checkpoints` 覆盖 34 场、80,406 帧,包含四类地形、沉默/冻结、重叠污染、圣杯合队和双骑士死亡联动。 + +本批已执行含全部 ignored 用例的 engine release 全量验收,306 项库测试与 91 项集成测试全部通过,0 失败、0 忽略。工作区全目标编译检查、参考脚本语法检查和差异空白检查通过。 + + +重生与特殊机制批次新增 9 种敌人,能力覆盖增至 223/249 种。包含暴鸰、假想敌:黑云、假想敌:淤困、帝国的甲胄、转译基底·α、乌顶巨角卢鲁、杰斯顿·威廉姆斯、巨大的丑东西和复仇者。单次重生共用净化、免死窗口、恢复比例、冷却和路线缓存处理,具体形态保留独立状态与回调。转译分支使用状态枚举,阻挡触发在移动边界完成 Buff 安装。投弹缓存释放时攻击力,吞噬和附着按任务及 Buff 生命周期保留引用。 + +新增 13 项原生回归,覆盖转译免伤和控制免疫、投弹打断与落地等待、吞噬者死亡、附着去重与元素爆发扩散、囚犯解放、驾驶员形态、半血重生、角力失衡和入场连击。`enemy_special_batch_checkpoints` 覆盖 27 场、56,409 帧。 + +本批已执行含全部 ignored 用例的 engine release 全量验收,319 项库测试与 92 项集成测试全部通过,0 失败、0 忽略。工作区全目标编译检查、参考脚本语法检查和差异空白检查通过。 + + +多形态首领批次新增 6 种敌人,能力覆盖增至 229/249 种。包含自在、锏、扎罗、自制投石机、卢西恩和不祥幻影。重生复用统一状态转换和冷却重置,恐惧流失走生命流失接口,技力清空与回复按发生顺序结算。投石机逐弹调度,同一轮共享最后有效瞄准点,支持子帧间隔和施法者死亡后的落点结算。 + +新增 16 项原生回归及 18 场原版对照。含全部 ignored 用例的 engine release 全量验收通过,335 项库测试与 93 项集成测试全部通过,0 失败、0 忽略。工作区全目标编译检查、参考脚本语法检查和差异空白检查通过。剩余 20 种集中在 Boss 与部件联动,Boss 战入口的共享血池和镜像流程仍待接入。 + + +王权与整列攻击批次新增 5 种,能力覆盖增至 234/249 种。包含阿利斯泰尔、未装配刀片、防护背心、冲击式施术单元和“萨米的意志”。装备按落点生成、按时间活化并消耗,接入方向屏障和一次性法伤攻击。萨米使用独立攻击节拍,复用技能仲裁和持续伤害结算。技能扣除的 LP 累计到终局结果。 + +新增 14 项原生回归和 15 场原版对照。含全部 ignored 用例的 engine release 全量验收通过,349 项库测试与 94 项集成测试全部通过,0 失败、0 忽略。工作区全目标编译、脚本语法、格式和差异空白检查通过。剩余 15 种涉及胄、铳、管、弦、余音、昆图斯及其部件,Boss 战共享血池和镜像入口仍待接入。 + +胄与部件联动批次新增 5 种,能力覆盖增至 239/249 种。包含胄、胄隐秘核心、斩胄之剑、破胄之锤和刺胄之弹。召唤与部件换代复用刷怪入口,传递伤害走生命流失结算并保留击杀归属。部件支持悬浮、俯冲、击落和换代,炮弹支持击破和落地范围持续伤害。来源随召唤物和持续效果保活,死亡、漏怪和到期释放引用。 + +新增 15 项原生回归和 16 场原版对照,覆盖分支容量、换代失败、来源退场和帧预算恢复。含全部 ignored 用例的 engine release 全量验收通过,364 项库测试与 95 项集成测试全部通过,0 失败、0 忽略。工作区全目标编译、脚本语法、格式和差异空白检查通过。剩余 10 种涉及铳、簧、管、弦、余音、昆图斯及其部件。 + +铳与三盾联动批次新增 5 种,能力覆盖增至 244/249 种。包含铳的普通与隐秘核心版本,以及法术、元素和频次护盾的三种碎铳之簧。接入最高防御索敌、同目标攻速叠层、侵蚀、冲锋、盲信之誓、簧的追逐和巡逻循环。三种护盾复用有序伤判链,保留再生后的安装顺序。法术簧按伤害、治疗和元素调整值传递,其余簧按伤判阶段传递,生命流失保留击杀归属并避免再次传递。反击期间的受击技能处理复用有界队列。 + +新增 15 项原生回归和 20 场原版对照,包含三盾同场、双铳追逐、击杀归属、护盾再生、巡逻及帧预算恢复。含全部 ignored 用例的 engine release 全量验收通过,379 项库测试与 96 项集成测试全部通过,0 失败、0 忽略。工作区全目标编译、脚本语法、格式和差异空白检查通过。剩余 5 种为管的两个版本、弦、余音和昆图斯,Boss 战共享血池、镜像和整局连接仍待接入。 + +管弦与昆图斯批次完成最后 5 种敌人,能力覆盖增至 249/249 种。管与弦复用召唤分支,余音支持双形态、频次生命、受击脉冲及合奏,连锁反击按有界队列结算。昆图斯按三阶段切换技能与初始冷却,触手跨阶段消耗分支,崩坍和物种爆发复用有界延迟任务。元素持续伤害按 Buff 生命周期保留伤害归属单位,死亡后的持续结算与引用释放均有原生回归。 + +新增 18 项原生回归与 22 场原版对照,覆盖形态联动、连锁反击、延迟任务、分支耗尽、阶段冷却和帧预算恢复。含全部 ignored 用例的 engine release 全量验收通过,397 项库测试与 97 项集成测试全部通过,0 失败、0 忽略。组合测试在清理弹道后核对活跃元素效果的保活引用,移除效果后检查所有引用释放。工作区全目标编译、脚本语法、格式和差异空白检查通过。后续继续接入 Boss 战共享血池、镜像与整局状态机。 + +单人 Boss 场入口接入最终攻势与隐秘核心。首领在内容初始化前绑定血池,帧末同步同场副本并处理死亡,血池清空优先结束战斗。正血池保持空场运行,领袖单次伤害按取整后的 30 万阈值整次取消,胄的无人机传递保留限伤例外。共享血池不足 1 的残量一次结清并全额记账。状态施加统一读取当前战场边界,普通场继续使用原入口与结算规则。 + +新增 13 项原生回归和 26 场原版对照。含全部 ignored 用例的 engine release 全量验收通过,410 项库测试与 98 项集成测试全部通过,0 失败、0 忽略。工作区全目标编译、格式、脚本语法和差异空白检查通过,CLI 实测覆盖 Boss 清场、隐秘核心超时、普通场输入和非法血池拒绝。单人整局的准备、回合切换及终局调度继续推进。 + + +单人 Boss 回合接入 LP 与胜负结算。自然漏怪按数据中的 LPR 扣除,包含未计入击杀总数的首领和部件;技能扣血按事件顺序结算。超时流失复用原版按整真实秒累计的规则,每帧战斗完成后执行。超时账单中的存活和未出生敌人保留原有报告语义。血池清空与 LP 耗尽同帧时沿用单人服务器的胜利优先级,战斗自然超时仍先完成自身结算。计算预算耗尽保留进行中的回合,技术错误使状态和报告失效。 + +新增 13 项原生回归与 12 场原版单人回合对照,对照直接调用原版 MatchBoss 的 LP 与超时处理。含全部 ignored 用例的 engine release 全量验收通过,423 项库测试与 99 项集成测试全部通过,0 失败、0 忽略。CLI 验证预算暂停、LP 归零、超时、胜利和非法设置拒绝;工作区全目标编译、格式、脚本语法及差异空白检查通过。后续优先连接单人准备期、普通回合、Boss 回合与终局,再接动作、观测和 Gymnasium。 + + +单人连续回合调度接入 `solo::Runner`。状态枚举约束准备、战斗、终局和执行错误,普通回合按漏怪个数及回合上限扣 LP,结转收入与赏金,淘汰后结束。最终攻势胜利按准备完成时的激活层数及剩余原始 LP 判断隐秘核心资格,隐秘核心失败仍保留整局胜利。准备坐标、独立战斗种子、Boss LP 取整展示与原始扣血池分别沿用原版规则。`Field::result()` 提供有类型的结算数据,包含伤害、治疗、击杀、漏怪与赏金。Boss 血池回调按每次命中的原始扣血金额连续累计整局伤害,跨隐秘核心保留累加顺序;战斗伤害报告继续使用 HP 差值。 + +新增 16 项原生回归及 13 条原版连续回合对照,共 3,985 帧。含全部 ignored 用例的 engine release 全量验收通过,439 项库测试与 100 项集成测试全部通过,0 失败、0 忽略。单人 CLI 的 13 条终局输出与原版逐项一致,另验证计算预算边界与非法输入拒绝。工作区全目标编译、格式、脚本语法及差异空白检查通过。当前仍接收已准备的波次与阵容,下一部分继续连接商店、库存、盟约、装备及模式波次生成,形成可直接决策的单人准备期。 + + +基础单人准备期连接商店、持有库存与原版 g.* 操作。商店展示保留复制加权抽取,已展示的干员与物品允许库存透支;出售和销毁返还份数并偿还物品欠额。支持刷新、冻结、升级空栏位、购买、出售、移动/交换、自动精锐化、物品合并和合成奖励选择。手牌满时即使能立即合成也拒绝购买,溢出队列按原版可见栏与隐藏队列顺序补入空手牌。`ready_owned` 从当前持有棋盘生成战斗输入并跨回合保留库存。资金和财务统计统一归属玩家状态,失败操作的有界事务草稿一并回滚钱包、库存和 RNG;资源超限使整局失效。 + +新增 14 项原生回归及 32 组原版基础准备期对照,共 3,327 个检查点,对照隔离准备期内容事件与召唤物系统。含全部 ignored 用例的 engine release 全量验收通过,453 项库测试与 101 项集成测试全部通过,0 失败、0 忽略。命令行验证购买至 Boss 终局、预算边界及重复购买拒绝,原有 13 个提供固定阵容的场景仍可运行。工作区全目标编译、格式、脚本语法和差异空白检查通过。准备期特质/盟约事件、装备使用、召唤物准备和模式波次生成继续列为单人可用的后续连接项。 + +准备期内容通过可选 `effects` 配置连接单人调度器。支持 23 类盟约的成员、激活与层数计数,以及数值类特质、远见返金/折扣、奇迹刷新、投资人重复、调和计数和助力结算。初始获得先于首轮收入,准备结束返金结转下回合,`ready_current` 使用实际激活层数。相同描述的多盟约特质覆盖重复字段,避免旧隐藏干员重复加层。 + +新增 9 项原生回归和 48 组原版准备期内容对照,共 5,474 个检查点。包含全部 ignored 用例的 release 全量验收通过,462 项库测试与 102 项集成测试通过,0 失败、0 忽略。CLI 验证预算恢复、层数上限、普通场至 Boss 终局、未支持内容拒绝及隐藏干员初始状态对照。工作区全目标编译、格式、脚本语法和差异空白检查通过。赠送/复制类特质、维多利亚重锤、装备使用、召唤物准备、战斗盟约效果与成长结转、模式波次生成继续连接。 + + +干员分批检查的 14 个入口收敛为 `operator_skill_definitions` 与 `operator_effects_checkpoints`。前者按当前池检查技能支持范围,后者保留原有 490 个战斗场景,失败信息包含批次、阵容、技能与 tick。各干员的独有原生断言继续保留。固定装备赠送、加权池赠送、指定回合赠送和重锤奖励共用获得/库存/合并逻辑,准备结束赠送延后到下一准备期合并并保留溢出。 + +本轮通过 459 项库测试、合并后的干员战斗对照与准备期对照。准备期包含原有 32 组基础场景和 60 组内容场景,共 10,193 个检查点,相关测试 0 失败、0 忽略。CLI 验证装备赠送、预算恢复、终局和未支持内容拒绝,原基础准备期输入仍跑通胜利。工作区全目标编译、格式与脚本检查通过。干员赠送/复制类特质、装备使用、召唤物准备、战斗盟约和模式波次生成继续连接。 + + +准备期干员赠送、松果售出招募、铃兰再触发和白面鸮/塞雷娅复制已连接。调用上下文分别保存特质来源与接收者,复制使用接收者的位置和盟约,并保留原版白面鸮复制歌蕾蒂娅/余时的行条件例外。复制链与再触发共用深度限制。准备事件保留棋盘快照与实时手牌顺序,刷新记录原有副本;赠送合成后继续处理被合成副本,新精锐从下次刷新开始计数。 + +本轮通过 462 项库测试及准备期的 32 组基础对照、84 组内容对照,共 13,030 个检查点,相关测试 0 失败、0 忽略。新增 3 项合并原生回归覆盖复制上下文/循环、刷新合成见证者、赠送库存与松果随机数。CLI 四组赠送/复制动作在预算 0 和 1 时的准备状态与原版逐项一致。工作区全目标编译、格式、脚本语法和差异检查通过。装备使用、召唤物准备、战斗盟约与模式波次生成继续连接。 + +### 装备配发与战斗输入 + +首批 8 个装备系列、16 个普通/高级定义已连接准备期与战斗,包含纯属性装备和变形同构体。配发沿用原版槽位、换装销毁、晋升/出售返还及已装备物品参与合并的规则。战斗在初次部署前统一安装持久增益,死亡与再部署复用现有生命周期。复杂装备效果仍待迁移。 + +本轮 466 项库测试通过,包含全部 ignored 用例。准备期对照共 32 组基础场景与 100 组内容场景、15,049 个检查点。装备共用一个战斗对照入口,53 个场景、127,200 tick 通过,覆盖叠加、重复装备、死亡及再部署。CLI 四组装备动作在预算 0 和 1 时与原版逐项一致,旧输入可运行到胜利。原有 13 条单人连续回合对照、工作区全目标编译及格式检查通过。复杂装备、召唤物准备、战斗盟约与模式波次生成继续迁移。 + + +### 装备触发与混装 + +新增 14 个装备系列、28 个普通/高级定义,累计支持 22 个系列、44 个定义。装备参数编译为有类型的效果,计数与一次性触发状态由战斗拥有。攻击、治疗、状态和伤害继续使用公共结算,持续自损保留无来源真实伤害及携带者归属,死亡和再部署沿用持久增益规则。混装对照修正了全场职业光环对隐匿友军的筛选,以及莎草治疗护盾晚于装备护盾的事件优先级。 + +本轮 467 项 release 库测试通过,包含全部 ignored 用例。装备仍共用一个对照入口,162 个原版场景通过,覆盖单件、重复装备、普通/高级混装、控制免疫血量边界及 9 组多干员联动。新增一项原生回归检查持续自损的伤害记账、参数覆盖与预算恢复。单人 CLI 验证新装备配发至终局及旧输入兼容,工作区全目标编译、格式和脚本语法检查通过。其余装备、召唤物准备、战斗盟约与模式波次生成继续迁移。 + + +### 部署、弹药与装备光环 + +新增叙拉古正装、迅捷作战粮、歌利亚头盔、拉特兰桥夹和双模机械臂,共 10 个普通/高级定义,累计支持 27/42 个战斗装备系列。部署与弹药事件复用恢复后的技能上下文,回技力按共享盟约成员计数,头盔区分初始阵容与当前前方占位。侧向光环与 Kit 定时任务共用截止时间排序,携带者退场期间继续推进节拍。弱点伤害在普通命中回调前选择物理或法术类型。 + +剩余 15 个战斗装备系列、14 个准备期/消耗类装备系列及 3 个法术。单人完整决策仍需接入战斗盟约及成长结转、召唤物准备、模式波次、合法动作与观测,再连接 Gym 接口及完成性能验收。 + +本轮 468 项 release 库测试与同一入口的 217 个装备对照场景通过,相关测试 0 失败、0 忽略。新增一项整局回归验证光环预算恢复、退场到期及再部署恢复。CLI 部署、光环/弱点及弹药三组输入在预算 0、1 和终局均通过,旧输入仍可运行到胜利。工作区全目标编译、格式及脚本语法检查通过。 + + +### 重锤与蒸汽之心 + +四类维式重锤和蒸汽之心共新增 10 个普通/高级定义,战斗装备达到 32/42 个系列。重锤共享同类计数、参数和定时刷新,蒸汽之心按场上重锤类型及携带者身份借用效果。场上类型缓存随部署和退场失效,不死窗口按部署记录,退出后重新部署可再次触发。已有不死与替身切换按致命伤害优先级处理,信仰搅拌机在不死窗口内保留保护弹药。 + +组合对照修正了两处 Kit 时序,洛洛的天赋加攻在帧末 tick 更新,归溟幽灵鲨的队伍生命加成在开战事件安装。装备增益由单一入口按安装顺序派发,旧 Roster 安装入口已删除。 + +本轮 469 项 release 库测试和同一入口的 276 个装备对照场景通过,相关测试 0 失败、0 忽略。新增一项原生回归覆盖不死窗口延续、到期死亡及再部署重置。单人 CLI 不死、加速及借用三组输入在预算 0、1 和终局均通过,旧输入保持胜利。工作区全目标编译、格式及脚本检查通过。剩余 10 个战斗装备系列、14 个准备期/消耗装备系列及 3 个法术,战斗盟约、召唤物准备、波次生成与环境接口继续迁移。 + +### 铳骑之威与耶拉冈德之泪 + +新增两个系列、4 个普通/高级定义,战斗装备达到 34/42 系列。铳骑按拉特兰身份触发额外子弹,配合桥夹提高伤害;耶拉冈德之泪按谢拉格身份对范围内寒冷/冻结目标定时造成法术伤害,配合不融冰提高倍率。配套装备统一按系列识别,沿用已有索敌、伤害和定时调度。盟约身份使用自身及变形同构体赋予的身份,和弦等战斗盟约扩展仍待接入。 + +469 项 release 库测试和同一装备入口的 300 个原版对照场景通过,0 失败、0 忽略。新增场景覆盖普通/高级配套组合、非对应盟约携带者、死亡再部署。两组单人 CLI 在预算 0、1 与完整终局通过。工作区全目标编译、格式及脚本检查通过。剩余 8 个战斗装备系列、14 个准备期/消耗装备系列和 3 个法术,后续仍需战斗盟约、召唤物准备、模式波次与环境接口。 + +### 天马套装、海沟实验体与黄沙罗盘 + +新增四个系列、8 个普通/高级定义,战斗装备达到 38/42 系列。天马追加伤害在父伤害伤判前结算,保留无来源及携带者归属;追加先击杀时停止父伤害。头盔回血沿用持久增益的定时生命周期。海沟以伤判回调执行固定减伤,受击反击独立计算冷却,重刃配套追加一次。罗盘按部署、首次非死亡技能结束及同盟约施法处理技力,保留忽略阻回规则。装备技能事件统一按安装顺序分发。 + +新增一项原生回归覆盖天马追加击杀、禁止递归追加与回血预算恢复。470 项 release 库测试、同一装备入口的 352 个原版对照场景通过,0 失败、0 忽略。三组配套的单人 CLI 在预算 0、1 与完整终局通过,工作区全目标编译、格式及脚本检查通过。战斗装备剩余 M3 茧甲、天师古鼎、骑士戒律、家族徽章四个系列;准备期装备、法术、战斗盟约、召唤物准备、模式波次及环境接口仍待完成。 + +### 最后四个战斗装备系列 + +M3 茧甲、天师古鼎、骑士戒律和家族徽章已接入,战斗装备达到 42/42 系列、84 个普通/高级定义。茧甲保留死亡及部署事件,免费原地再部署,次数按整场战斗计;骑士戒律提供技能窗口光环和延迟退场;家族徽章按隐匿期间的节拍积累攻击,离开隐匿后的首次伤害消耗增益并触发正装配套。古鼎读取准备期本回合获得干员数,并在配短刀时按装备 UID 和回合限制金币奖励。 + +部署使用与寻路网格共享的只读地块,敌人行动中的即时复活不再借用可变寻路状态。混装对照补齐耀骑士临光“耀阳”在前一位部署干员为卡西米尔成员时的额外命中。 + +471 项 release 库测试、405 个装备原版场景和 490 个干员原版场景通过,0 失败、0 忽略。准备期 32 个基础场景及扩展后的 106 个效果场景通过,新增场景覆盖古鼎金币上限、跨回合重置和身份/配套限制。四组单人 CLI 在预算 0、1 和胜利终局通过,工作区全目标编译及格式、脚本检查通过。剩余 14 个准备期/消耗装备系列及 3 个法术;和弦身份、装备借用等战斗盟约联动,召唤物准备、模式波次与环境接口仍需接入。 + +### 准备期消耗装备 + +接入盟约之币、随身身份牌、紧急调度券、精打细算玩偶、简易通讯机、见钱眼开玩偶、骑士储蓄罐和人事部文档,共 8 个系列、16 个普通/高级定义。消费沿用准备期事务,满槽先移除被替换装备,再计算身份及奖励;商店赠送和同盟约招募复用库存、获得和合并逻辑。即时金币、下回合金币与持续回合收入分别结算,文档提升的部署上限贯穿后续准备期和实际出战。准备期内容仍通过 `preparation.effects: {}` 启用。 + +473 项 release 库测试、32 个基础准备期场景及 138 个效果对照场景通过,0 失败、0 忽略;沿用同一准备期效果测试入口。原生回归覆盖满槽替换、重复消费拒绝、跨回合收益及 9 人出战。普通/高级两组 CLI 在预算 0、1 和胜利终局通过,旧输入保持胜利,工作区全目标编译、格式及脚本语法检查通过。 + +准备期装备剩余寻呼模块、信标、拟态物质、博士投影、商业包装方案和突变细胞。另有 3 个法术、战斗盟约联动、召唤物准备、模式波次与环境接口待完成。 + +### 准备期选择与复制 + +寻呼模块、信标和拟态物质接入普通/高级定义。寻呼模块按剩余库存抽取不重复的同盟约候选;信标销毁携带者并归还装备和库存,提供同阶候选、不足时向低阶补齐,沿用免费选择队列,不触发出售收益。单人范围不处理信标的队友赠送。拟态物质在已有两名初始干员时补第三张,否则按同盟约身份等权抽取,允许超出剩余库存获得,获得和合成仍走公共流程。 + +474 项 release 库测试通过,包含信标归还装备、不触发出售及拟态合成的原生回归。准备期对照扩展到 32 个基础场景和 154 个效果场景,沿用原有两个入口,0 失败、0 忽略。普通/高级 CLI 验证消费、领取选择奖励及连续战斗,预算 0、1 和胜利终局均通过。工作区全目标编译、格式与脚本语法检查通过。准备期装备仅剩博士投影、商业包装方案和突变细胞,其余单人环境缺口不变。 + + +### 最后三个准备期装备系列 + +博士投影、商业包装方案和突变细胞已接入普通/高级定义。投影按品质立即或下回合原地晋升,拒绝精锐目标,保留其他装备;包装计数随装备保留,每达到出售次数门槛抽取同盟约初始干员;细胞在战后销毁携带者、归还全部装备,再获得高一阶且最高六阶的初始干员。装备事件先记录携带者与装备 UID,执行前确认仍在原携带者身上,避免销毁、合并期间漏执行或重复执行。 + +475 项 release 库测试、准备期 32 个基础场景和 178 个效果场景全部通过,0 失败、0 忽略,包含跨回合出售计数、满槽替换、精锐目标拒绝及战后变异。原生回归验证预算暂停不提前触发、结算不重复执行、投影保留装备及细胞腾出原部署格。普通/高级 CLI 在预算 0、1 和胜利终局通过,工作区全目标编译、格式与脚本语法检查通过。下一步为剩余法术及单人环境连接工作。 + + +### 画卷与法术使用入口 + +新增原版 `g.art {itemUid,row,col,dir?}` 动作,按道具范围与朝向选取棋盘目标,读取配置中的每回合法术次数上限,只在成功使用后消费道具并计数。画卷复制干员的当前品质,允许超库存获得干员;先记录目标装备,再依次获得复制装备,避免合成移除携带者后漏复制。复制装备保持未装备状态,沿用库存、自动合成和溢出队列。非法目标、越界和超过次数上限均回滚。 + +476 项 release 库测试及准备期原版对照的 32 个基础场景、194 个效果场景通过,0 失败、0 忽略,覆盖四朝向、普通/精锐、复制触发合成和跨回合次数恢复。原生回归覆盖装备合成时仍复制后续装备、拒绝操作不改动状态。CLI 在预算 0、1 和跨回合胜利终局通过,工作区全目标编译、格式和脚本语法检查通过。教鞭和“神秘顾客”仍需悬赏选择、敌人生成与结算连接,使用时明确拒绝。 + + +### 教鞭与悬赏结算 + +教鞭保留最多三个战术特训候选,通过 `g.choice {idx,choiceId}` 确认,`choiceId` 读取准备期报告的 `personalChoice.id`;选择未完成时拒绝准备,过期 ID、越界及重复选择不改动状态。“神秘顾客”直接抽取一项悬赏,主动销毁时获得金币,单人没有队友传递。抽取沿用 Meta RNG 和模式禁用敌人规则。 + +悬赏持有独立剩余场次,击杀奖金复用战斗记账,完美奖励在回合结算时进入待发资金,多轮悬赏可延续到 Boss。当前 `RoundPlan` 接受已展开的显式波次,新增敌人按原版无模板分支在第 4 秒加入,按移动类型及 Boss 半场选择路线,应用该模式回合的敌人倍率。尚未接入的模式波次生成器需保留原始动作元数据,才能实现悬赏穿插原波次并重排出生间隔;这里没有把追加敌人当成该流程的替代实现。 + +新增准备期对照覆盖教鞭选择、选择前拒绝出战、过期 ID、重复选择、次数限制和主动销毁奖励。原生回归验证额外敌人刷出、击杀/完美奖励、未完美不奖励、剩余场次及逐帧预算恢复不重复发钱。CLI 经过选择、使用、销毁和连续战斗到达胜利终局。 + +本轮 477 项 release 库测试、32 个基础准备期场景和 206 个效果对照场景通过,0 失败、0 忽略。工作区全目标编译、格式和脚本语法检查通过。 + + +### 悬赏插入原始动作窗口 + +波次现在可通过 `Template::configure_bounty_actions` 保留原始模板动作窗口和生成后的有效单位数。悬赏按地面/飞行类型选择原动作,在其单位序列中插入并重新计算出生间隔;普通关重排原动作单位,Boss/隐藏回合按原版只追加计算后的悬赏单位。路线继续检查移动类型及 Boss 半场。超过容量时保留原波次,不提交半次修改。 + +单人 CLI 计划可选传入 `templateId` 和 `spawnActions`,后者是原版波次生成结果的 `actions`,与准备操作的 `actions` 分开。旧显式波次输入保持原来的第 4 秒追加行为。这里完成的是悬赏时序及模板信息接入,按种子选地图、阵营、Boss 和自动展开模式各回合的生成器仍未迁移。 + +478 项原生测试通过,0 失败、0 忽略。原有单人对照入口同时验证 13 组流程、3985 帧和四种模式含隐藏回合的 216 组悬赏动作窗口,未新增测试入口。新模板输入在预算 0、1 和胜利终局通过,旧 CLI 输入保持胜利;工作区全目标编译、格式和脚本语法检查通过。 + + +### 种子生成与手动禁卡 + +`solo::mode::generate` 按种子选择地图、阵营、Boss、隐藏 Boss,生成各回合波次及悬赏动作窗口,并执行模式自动禁用盟约和卡池规则。手动禁卡与自动禁卡取并集,精锐 ID 归一到基础卡、重复项去重,未知 ID 拒绝;手动禁卡不消耗 RNG,不改变地图、阵营或波次。 + +单人开发 CLI 接受以下简化输入,旧显式计划输入继续有效: + +```json +{"seed":42,"modeId":"mode_single_normal","preparation":{"banned":["chess_char_1_02_a"]}} +``` + +```sh +cargo run --offline -p arkguard-engine --example solo -- /path/to/data /path/to/input.json 0 +``` + +现有生成器可解析 funny、normal、hard、abyss 四种 `mode_single_*` 模式,但仅维护及验收 abyss(绝境)。`preparation` 可省略,也保留初始物品、容量和效果设置;可选 `roundActions` 按回合提供准备期动作数组。输出的 `setup` 包含未来波次诊断信息,不得用作策略观测。预算 0 可查看生成及初始准备状态;无动作输入不会自动组队。 + +原有单人对照入口新增 28 组模式/种子组合,验证地图、阵营、自动禁卡、Boss、全部波次及动作窗口与原版一致,并验证手动禁卡不扰动生成结果。重复/精锐禁卡归一与未知 ID 拒绝也有回归覆盖。 + +### 阻隔工事寻路与拆除 + +阻隔工事已连接寻路、占位、阻挡和销毁。工事格保持原版 1000 的寻路代价,有通路时绕行;必须穿过时由工事阻挡敌人,普通索敌不会选中工事。阻挡后沿用原版攻击与延迟拆除,不能攻击的敌人也可拆路;拆除清除占位、阻挡和路径缓存。工事不进入干员专属的技能、受击天赋或 SP 回调,修复堵路后攻击工事报 `Unknown operator identity` 的问题。 + +原有 Field 对照入口新增 `stage_device_checkpoints`,debug/release 均通过,11 组、6,979 帧与原版一致,覆盖绕行、堵路、无攻击敌人、飞行、连续两道工事、被阻挡敌人死亡、提前拆除和显隐配置。另有不依赖外部数据的回归,验证绕行/拆除与分步预算恢复。原生库测试 477 项及 Field 测试 24 项通过;需要外部数据的测试除上述工事对照外,本轮未重跑。工作区全目标编译检查通过。 + +funny、normal、hard、abyss 四种模式的种子 42 均已从生成/准备进入战斗,并完成首帧推进,原工事开战阻塞已解除。这只验证开战入口,不代表随机地图完整整局验收;该工事批次之后的地图机关进度见下节;战斗盟约与环境接口仍需继续连接。 + + +### 本期地图机关与地图效果 + +覆盖本期 8 张地图:战场 #01–04 与下半期 #05–08,包含普通场和单人 Boss 场。阻隔工事、射击台、源石流、沼泽、烟雾、深水水蚀、活性源石,以及效果启动的“双眼皮”和寒风均已接入。旧上半期 #05–07 的水上平台、沙尘暴和树丛不在本次范围。 + +“双眼皮”沿用原版范围、空位选择、索敌、法术追踪弹道、最高盟约层数强化和命中脆弱。最高层数可实时更新,已发射弹道保留来源及发射时的脆弱参数。寒风按独立周期调度,重复寒冷触发冻结,支持不中断周期地更新持续时间。机关容量受场地和单位上限约束,超限使当前运行失效,不裁剪单位。 + +`Field::configure_map(MapConfig)` 在加入阵容前配置,`Runner::configure_map` 仅接受准备期调用并跨回合保留配置;每场战斗重新创建机关及计时器。准备期与开战校验共用机关部署规则:工事和土堆不可部署,射击台只接受远程及可上高台的干员;地图变化后,不合法的干员退回手牌或暂存区,并重新计算盟约。普通场和 Boss 场分别读取对应地图区域。准备期内容提供准备结束后的最高盟约层数,禁用盟约不参与炮台强化。`update_map_layers` 与 `update_cold_wind_duration` 供战斗成长事件更新效果。机关在开战阶段安装,保留干员、机关和敌人的原版身份及部署顺序。 + +`field` 和 `solo` 开发入口均接受可选 `map`,种子生成模式同样支持。例如: + +```json +{"seed":42,"modeId":"mode_single_normal","map":{"effects":["aceffect_band_43","map_m01_1"],"deviceOverrides":{},"coldWind":{"interval":5,"duration":2}}} +``` + +`effects` 从外部数据加载已选中的地图效果,例如机械援助及本期地图卡;只接受 `auto_chess_change_map` 的机关开关,不把其他效果当成已实现。`deviceOverrides` 是 alias 到布尔值的覆盖,优先于效果记录。直接构造 Field 或无准备期内容时可用 `topLayers` 提供炮台层数;启用准备期内容时从真实盟约状态读取。谢拉格达到六人档会在开战时自动启动寒风,持续时间读取准备结束后的层数;下一场重新判断,人数不足或盟约禁用不会触发。显式 `coldWind` 配置优先,供独立场景验证使用。机变地图卡也可经下述选牌流程修改机关;特质触发的战斗成长已接入炮台层数和自动寒风持续时间更新,显式寒风覆盖保持原值。 + +对照覆盖全部 8 张地图的普通/Boss 场、默认/显式开关/数据效果三种配置,以及独立机关场景。原生回归另检查预算暂停恢复、非法配置不覆盖已有配置、单位容量耗尽、跨回合重建和准备期配置限制。部署规则对照逐格核验本期地图在普通/Boss 场及地图卡覆盖后的近战、远程合法位置;寒风回归检查五人/六人档、禁用盟约、准备结束层数和下场撤下成员。 + +本轮含全部 ignored 用例的 release 全量验收通过:482 项库测试、99 项集成测试,共 581 项,0 失败、0 忽略。其中地图机关入口覆盖 75 组逐帧对照。工作区全目标编译、格式、参考脚本语法及差异空白检查通过。四种模式的种子 42 携带机械援助均从生成、准备运行至正常淘汰终局;另验证预算 0 保持准备期、预算 1 保留战斗后继状态。这些无阵容流程检查不作为策略表现或完整环境性能验收。 + +### 单人机变抽牌与选牌 + +`solo::draft::generate` 接入补给、机密商店、战术决策及 initial/boss/hunter 三类悬赏的候选生成。保留按组抽悬赏、重复商店/战术牌、地图限制、可用盟约和装备库存过滤、空池回退、事件 ID 抽取及独立 draft RNG。抽牌不预扣库存。原版对照覆盖四种单人模式、本期八张地图、96 个种子和库存过滤,共 9,216 个回合检查点,逐项比较完整候选与后继随机数状态。 + +已有准备期效果的 Runner 可在第一场战斗前调用 `enable_drafts(stage_id)`。机变回合在收入和回合开始效果之后进入 `Phase::Draft`,普通准备动作与 Ready 暂停;`pick_draft(index)` 或 `g.choice` 不带 `choiceId` 选择候选,再执行准备开始效果。带 `choiceId` 的个人悬赏选择保持原义。越界选择保持状态,重复选择拒绝;选牌效果及准备开始效果一起提交,内容/容量错误使运行失效,不提交部分奖励。 + +已接通免费装备、悬赏、地图开关、资金、免费刷新、盟约加层、随机装备补给、盟约驰援及下一次购买升级。地图卡即时重检部署位置,跨回合保留开关;随机奖励使用 meta RNG,不影响后续机变。友方战斗牌自愈、火力、征召、无瑕、锐利也已接入。9 张敌方减益牌不在绝境牌池中,不列入迁移待办。已有其他模式入口选到未实现效果仍明确报错,不能将该局作为有效 rollout。 + +整备/升华在普通商店购买及购买合成之后检查所得棋子。成功升级保留 UID,消耗一个对应次数;已有高级版本、无法升级或装备缺少第二份库存时保留次数。次数跨回合保留,多次选牌按引用顺序生效;奖励商店和普通获得不触发。干员晋升补足原版池占用,不生成合成奖励。选牌引用使用独立序号,地图卡也不占用棋子 UID。随机装备补给按注册处理器的规则在池抽取失败时回退到一阶装备。 + +开发入口默认行为不变。种子模式传 `"drafts":true` 启用;显式计划模式传 `"drafts":"地图 ID"`,并要求输入地图与该数据记录一致。选择放在对应回合动作数组的首项,例如 `{"t":"g.choice","idx":0}`。缺少选择时 CLI 返回当前 `draft` 状态和三张候选,不自动代选;`draftRng` 属于内部诊断,不是策略观测。 + +本次含 ignored 对照的 release 全量回归通过:489 项库测试、100 项集成测试,共 589 项。新增回归覆盖抽牌容量/随机数、阶段暂停、准备开始效果延后、普通/Boss 地图卡、免费奖励、悬赏入波次、即时战术效果和未实现选牌的原子失效。显式空波次 CLI 场景验证第 6 回合等待选择、补入选择后继续至第 7 回合结算;该检查不代表完整内容或策略性能验收。 + +购买升级接线后,含 ignored 对照的 release 全量回归为 492 项库测试、100 项集成测试,共 592 项,全部通过。新增原版注册处理器对照覆盖 11 个场景、44 个状态检查点,比较升级次数、引用序号、棋子 UID、池占用、装备欠账、合成奖励及随机数;另验证次数跨回合保留和地图卡不占用棋子 UID。 + + +友方战术牌在准备结束效果执行后统计手牌及暂存区,跨回合重新判定;征召在战斗开始按存活且已部署的干员判定同排人数。静态属性保留到再部署,无瑕随满血状态增删、重复选择按百分比相加;自愈先治疗再重判满血,并排除禁疗、生命流失、元素累积和致死伤害。重复选牌使用独立效果引用,不占用棋子 UID。 + +按当前原版 schedule,绝境第 3、9 回合只有悬赏,第 11 回合可抽悬赏、机密商店或战术决策;战术决策仅抽 ally 类,排除地图改造和敌方削弱,但包含上述 5 张友方战斗牌。该限制由原始候选数据决定,不为绕过未实现效果而过滤牌池。 + +友方战术牌接线后,含 ignored 原版对照的 release 全量回归通过:494 项库测试、101 项集成测试,共 595 项,0 失败、0 忽略。新增 36 组逐帧对照覆盖备战席门槛、同排人数、重复选牌、伤后自愈与满血加成、死亡再部署及禁疗/召唤干员场景;另验证跨回合保留、备战席重算和未知属性的原子失效。工作区全目标编译、格式及脚本语法检查通过。 + +### 绝境战斗盟约:精准、助力 + +准备结束后的盟约档位与层数通过 `Field::configure_bonds` 传入战斗。精准一档强化成员攻击,二档扩展到所有远程干员并提供物理/法术穿透;助力强化全体干员防御并缩短再部署时间。数值读取外部盟约数据,在首次部署前安装持久属性,与装备及战术牌百分比加成共用结算。每场重新取准备期状态,禁用或未激活的盟约不安装效果。 + +精准、助力已接通开战属性和战斗加层后的刷新。其他盟约本体的战斗效果仍按绝境范围逐项迁移。独立战斗入口接受数据中已知盟约的状态快照,未迁移的盟约属性不因此生效;错误配置不覆盖已有状态。 + +该批次含 ignored 原版对照的 release 全量回归通过:495 项库测试、102 项集成测试,共 597 项,0 失败、0 忽略。新增 21 组逐帧对照覆盖未激活/两档效果、不同层数、成员与非成员、两种盟约组合及死亡再部署;绝境流程回归验证准备结束加层、禁用盟约与撤下成员。工作区全目标编译、格式及参考脚本检查通过。 + + +### 战斗特质成长、实时刷新与结转 + +已接入当前期特质的部署、开技能、击杀、倒地、弹药消耗、首次进入冻结/沉睡/晕眩,以及替身切换事件。赠予特质按来源位置、范围和盟约身份发放并去重。加层按实际激活盟约、同行/同列条件和单场次数计算;最高层盟约目标使用原始数据顺序打破平局。魔王额外加层不占来源特质上限,塑心的上限跨目标盟约共享,总层数封顶 999。 + +战斗保留独立层数和按首次触发顺序记录的增量。层数立即写入,精准/助力与按层数生效的干员属性合并到原版的延迟刷新阶段;炮台和自动寒风读取实时层数。支持按层数提高属性、缩短再部署、部署限时增益及对束缚/停顿目标的伤害倍率。正常战斗结束后仅结转增量,通过准备期层数事件结算奖励;预算暂停不结转,下一场重置特质次数。Boss 和隐藏 Boss 保留已有层数效果,但禁止战斗加层。 + +新增原版处理器对照将成长目标统一接到已迁移的精准/助力,隔离尚未迁移的盟约本体效果;逐帧比较完整战斗状态、随机数、实时层数及增量,覆盖 100 组本期干员和组合场景,每场最长 65 秒,并检查死亡再部署和同排门槛。绝境原生回归另检查跨回合结转一次、封顶、Boss 禁用,以及准备结束和战斗部署加层对自动寒风的影响。尚未迁移的盟约本体或盟约核心产生的事件随对应内容继续接线,不能将此批次视为完整绝境环境。 + +本批次含 ignored 原版对照的 release 全量回归通过:496 项库测试、103 项集成测试,共 599 项,0 失败、0 忽略。准备期专用对照显式排除战斗成长,真实战斗与结转由上述独立回归覆盖。另修复已清理敌人残留索敌索引、塑心一技能空属性增益,以及魔王吟游治疗/模组检查的回调顺序。工作区全目标编译、格式及参考脚本语法检查通过。 + +### 绝境盟约战斗效果(续) + +已接入维多利亚的装备伤害与精英装备攻击加成、谢拉格的伤害与寒冷目标倍率、拉特兰的弹药扩容和消耗弹药累计攻击、萨尔贡的独立限层计时攻速与六人档攻击。基础战斗入口也会按谢拉格档位自动启动寒风;显式地图覆盖仍优先。萨尔贡的娜仁图亚核心借装备分支随核心选择系统继续迁移。 + +附加盟约新增迅捷、灵巧、奥术、协防、独行、绝技:技能结束的独立概率回技力、邻接光环(阵亡保留、撤退移除)、同名取最高法伤易伤、承伤与输出倍率、每次部署技力,以及精英和其召唤物的技能费用。调和生效时,成员享受核心盟约与对应装备成员效果,但不改写原生盟约列表。 + +新增原版对照覆盖档位关闭/两档、0/40/200 层、普通/精英成员、装备、死亡再部署、战斗成长、调和与召唤物,每场最长 65 秒。组合场景还检查流形的额外技能触发范围与分裂体的部署初始化,并修正缪尔赛思援军增伤应在防御结算前乘入攻击伤害。 + +该批次之后仍待实现的内容见下节。本节不表示完整绝境环境已完成。 + +该批次 100 组原版对照通过;包含 ignored 对照的 release 工作区回归共 600 项通过,0 失败、0 忽略。格式、参考脚本语法与 diff 检查通过;未提交,main 保持 `6af66bf`。 + + +### 叙拉古、卡西米尔与盟约运行时拆分 + +叙拉古按每次部署时的层数提供限时攻速与六人档隐匿;普通伤害在隐匿及结束后的窗口内参与伪随机判定,触发真伤和恐惧。连续失败累计、成功重置在成员间共享,排除溅射、持续伤害、附加伤害、装备与盟约追伤。死亡直接丢弃隐匿,不伪造结束窗口;再部署的落地技能先于本次部署增益。 + +卡西米尔累计所有干员的部署次数,为成员提供有上限的攻击加成;战斗加层刷新上限。六人档区分阻挡与非阻挡:前者周期范围真伤与晕眩,后者在普通伤害后追加无来源、保留归属的真伤。召唤物不计入部署次数,调和成员沿用核心盟约资格。 + +盟约运行时拆为属性、部署、伤害、光环和技能事件模块。只读参数与弹药计数、技能费用初始化、光环刷新及两个核心的状态分开存放;周期效果合入已有的截止时间调度队列。击杀回调与移除后的死亡回调分开;攻击伤害结算期间归还真实技能状态,使德克萨斯首次击杀可以同步重放技能,避免借用状态导致的延迟回调。 + +剩余本体效果为炎、阿戈尔、坚守、突袭、不屈;核心三选一及各核心的准备/战斗效果仍需继续迁移。 + +本批次盟约对照扩展至 154 组,覆盖部署与再部署、不同层数/档位、阻挡周期伤害、普通伤害追伤、调和成员及德克萨斯击杀重放。另修复耀骑士临光的阻挡目标模组倍率误用于盟约伤害;原生伪随机测试独立检查长期触发率和连续失败上限,不依赖某个随机种子的序列。 + +包含 ignored 原版对照的 release 工作区回归通过:497 项库测试、104 项集成测试,共 601 项,0 失败、0 忽略。全目标编译、格式、参考脚本语法与差异空白检查通过。未提交,main 保持 `6af66bf`。 + + +### 坚守:生命上限、分摊与反伤 + +坚守按实时层数提高所有干员的生命上限。二档将非成员受到的实际伤害,在护盾与伤害减免结算后按比例分给在场成员;份额均分,使用无来源、已结算真伤,不重复减免、不递归分摊,也不消耗成员的反伤冷却。成员离场后不再承担份额。 + +成员反伤各自计时,造成无来源法伤但保留伤害归属,并施加脆弱。无来源伤害会消耗反伤机会;生命流失不触发分摊或反伤。显式生命流失请求现在走已有的生命流失结算,避免被普通伤害入口错误施加减免。 + +剩余盟约本体为炎、阿戈尔、突袭、不屈;核心三选一及核心专属效果仍待实现。 + +本批次盟约原版对照扩展至 175 组并全部通过,新增多人分摊、成员阵亡、反伤冷却、生命流失,以及协防/助力组合。新增独立回归验证 50 点伤害按 40% 分摊后为原目标 30 点、两名成员各 10 点,并检查反伤归属及无来源伤害消耗冷却。52 项 Field 测试分批通过,497 项库测试(含 3 项外部数据对照)和生命/伤害结算对照通过。本轮未重复全工作区 release 验收;未提交,main 未变。 + + +### 不屈:即时再部署、倒地技力与替身储存 + +不屈对近战定位干员生效,包含非成员,也不取决于实际站在高台还是地面。倒地、普通撤退和商人撤退按实时层数判定免费原地再部署;同一时刻最多触发一次即时再部署,避免复活循环。二档只在倒地时给在场干员技力,保留被借用技能的待结算增量和 `bond` 来源,不把撤退或替身切换算成倒地。 + +替身切换时判定成功后,储存一次免费再部署机会,下次部署消耗,不额外重复抽取。不屈按死亡回调优先级接在 M3 茧甲之后;保留原始退场原因,因此被更早效果复活的干员仍可触发该次倒地技力。商人撤退原因改为在回调前写入,避免复活后又写回旧退场状态。 + +死亡回调按优先级区分退场记录、复活和后续清理:伊内丝先留下影哨,复活后清理攻击偷取;德克萨斯在死亡回调中清理首杀状态;倒地成长在不屈后结算。史尔特尔的余烬撤退复用统一回调与有界定时器,按截止时间和部署批次执行,避免漏掉不屈判定或提前刷新复活后的模组。 + +同时修复致死回调消耗的随机状态被外层伤害覆盖、风丸同一帧连续替身/倒地/再部署导致重复爆发,以及诗怀雅先处理旧炸弹爆炸而错误改变新炸弹落点的问题。剩余盟约本体为炎、阿戈尔、突袭;核心三选一及核心专属效果仍待实现。 + +本批次盟约原版对照扩展至 224 组并全部通过,覆盖非成员近战、高台定位排除、替身储存、同帧重复倒地、手动/商人/余烬撤退与茧甲组合。53 项 Field 测试(release,含 ignored)和 497 项库测试(含外部数据对照)通过;全目标编译、格式、参考脚本语法与 diff 检查通过。本轮未重复全工作区 release 验收;未提交,main 保持 `6af66bf`。 + +### 突袭:选敌、跳跃与复活重选 + +突袭每 0.25 秒检查成员:技能就绪(含仍在生效的落地技能)或空闲达到阈值,且射程内没有可攻击敌人或隐匿地面敌人时,按剩余路程、身份顺序尝试前八名地面目标。排除飞行、睡眠、不可选中目标,落点必须属于绝境当前部署区域、地形合法且未被活单位、倒地身体或待部署单位占用,并能覆盖敌人体积。近战优先可阻挡的道路,再比较距离和朝向局部坐标。 + +跳跃走真实撤退和免费再部署,保留原归位位置;分别恢复技力和充能,在部署回调前恢复,跳过被动、零费用或已启动的落地技能。落地失败则尝试正常归位。跳跃后攻血与攻速增益随实时层数刷新,退场清除;层数里程碑仍给全队加成。 + +即时倒地复活后额外重选一次:先刷新邻近阻挡,未阻挡时按嘲讽、剩余路程和身份排序;普通撤退、定时再部署和突袭自身跳跃不触发这次重选。复活标记按干员保存部署批次,状态规模受阵容上限约束。 + +伊内丝影哨周期接入统一截止时间排序,避免同帧跳跃后错误按新位置提前刷新揭露。新增突袭成员、远距离跳跃、落地技能、突袭与不屈组合,并在盟约对照中逐检查点比较干员位置。剩余盟约本体为炎、阿戈尔;核心三选一及核心专属效果仍待迁移。 + +本批次 265 组盟约原版对照、全部 53 项 Field 测试(release,含 ignored)及 498 项库测试(含外部数据对照)通过。全目标编译、格式、参考脚本语法与 diff 检查通过。本轮未重复其他集成测试的全工作区 release 验收;未提交,main 保持 `6af66bf`。 + +### 阿戈尔:吞噬链与首次倒地复活 + +成员生命加成在部署前生效,实时成长继续刷新。开场按列从左到右、同列从高行到低行建立身前标记,沿阿戈尔成员传播;禁止重复、自标记及相互标记。先完整建立标记并继承目标基础攻击(最终加算)和阻挡数,再按标记顺序结算由目标自身造成、归属标记者的物理生命流失。标记者先倒地仍会结算其标记;目标倒地或切换部署批次后取消剩余标记。每个实际被吞噬目标只贡献一次自身费用档位的成长,沿用实时刷新和战后增量结转。 + +五人档每名成员只响应首次未被更早复活效果接管的倒地,最多消耗黑板指定的复活次数。开场吞噬期间先收集倒地成员,全部标记结束后按列、行升序复活;战中则立即复活,优先于不屈,晚于茧甲。复活使用原有免费再部署流程,恢复生命、重置技力并触发部署效果。当前绝境数据的海沟实验体为反伤版本,不引入历史版本的四邻吞噬效果。 + +剩余盟约本体为炎;核心三选一及核心专属效果仍待迁移。 + +本批次 290 组盟约对照及全部 53 项 Field 测试(release,含 ignored)通过;覆盖长链超出复活名额、反向标记、不屈、茧甲、替身以及不同层数。498 项库测试、全目标编译、格式、脚本语法和 diff 检查通过。未重复其他集成测试的全工作区 release 验收;未提交,main 保持 `6af66bf`。 + +### 炎:炎佑召唤与战斗 + +成员攻击加成随层数刷新。开场六人档召唤一只炎佑,九人档召唤两只并施加攻击倍率和伤害减免;模板攻击、生命叠加在场原生炎成员对应属性总和的 30%,调和资格不纳入汇总。炎佑归属玩家,不挂到某名干员名下;出生位置优先不可部署地形并靠近场地中心,避开占用与地图干员预留格。 + +炎佑作为飞行友军追踪场上最高优先级目标,动态计算圆形射程,普通攻击最多命中三名敌人,造成法伤并追加灼燃积累。它免疫元素损伤,周期施加元素脆弱。祛恶之焰使用真实技力和持续技能流程,锁定目标、停止普攻,每秒围绕目标重新选取范围受害者;控制期间暂停输出,沉默或目标失效结束技能。第二只炎佑保留独立的悬停偏移、技力和锁定状态。 + +本批次 308 组盟约对照及全部 53 项 Field 测试(release,含 ignored)通过,新增单双炎佑、不同层数、调和、绝技及地图预留格组合,并断言炎佑实际普攻和施放技能。498 项库测试通过;旧装备夹具补齐现在会参与战斗的炎盟约参数。全目标编译、格式、脚本语法和 diff 检查通过。未重复其他集成测试的全工作区 release 验收;未提交,main 保持 `6af66bf`。 + +盟约本体效果已接齐;核心三选一、核心专属效果与完整绝境迁移验收仍待完成。 + +### 核心范围:阿米娅、歌利亚、陈 + +按当前维护范围,仅支持这三种核心。`Runner::configure_core` 在首场战斗前配置一次,校验成功后采用核心初始生命并跨回合保存;开发用 `solo` JSON 的可选 `core` 字段和 Field 独立配置入口保留。动作和观察维度不变,范围外核心明确拒绝,失败配置不改变玩家状态。核心作为实验变量直接配置,不生成开局三选一,不加入策略动作空间,也不再列为迁移缺口。 + +阿米娅按激活盟约数施加最高档攻击和生命加成;歌利亚仅将初始生命设为 45;陈将干员对敌人的物理/法术伤害改为减伤后较高的类型,相同时保留原类型,复用装备弱点伤害的穿透和减伤计算。移除伊奥莱塔、埃芒加德实现及验收,不再将其他核心列作迁移目标。 + +本批次 352 组盟约与核心原版对照、全部 53 项 Field 测试(release,含 ignored)及 499 项库测试通过,覆盖陈对高防御、高法抗目标的两种伤害转换,以及歌利亚初始生命和跨回合保留。全目标编译、格式、参考脚本语法与 diff 检查通过。未重复其他集成测试的全工作区 release 验收;未提交,main 保持 `6af66bf`。 + + +### 持久原生会话与 Python 执行入口 + +`solo::session::Session` 与开发绑定 `NativeSolo` 已接通绝境种子生成、准备期、机变选择、战斗和结算。构造时指定三个受支持核心之一及手动禁卡;多个会话共享只读 `NativeCatalog`,各自保存状态。`reset(seed)` 替换整局,`step(action_json, tick_budget)` 提交一个原有 `g.*` 动作(包含 `g.ready`),自动推进至下一个决策或预算边界;`advance(tick_budget)` 仅续跑已暂停的战斗。每次最多推进 108000 帧,允许预算为零,预算耗尽不表示 episode 截断。 + +返回回执区分正常拒绝、待决策、战斗暂停和真实终局。格式错误不消耗 revision;规则拒绝保留钱包、库存和 RNG。内容或执行错误使会话失效,不伪造终局。Python 的生成、动作和战斗调用释放 GIL;`close()` 释放当前对局,随后可重新 reset。`diagnostics()` 明确是含私有状态的调试入口,不作为策略观测;本批不改变模型输入或注册新 Gym 环境。 + +开发验证入口:先运行 `cargo build --release -p arkguard-python` 和 `cargo build --release -p arkguard-engine --example solo`,再以 `ARKGUARD_REFERENCE_ROOT`、`ARKGUARD_NATIVE_LIBRARY`(所构建的 `_native` 动态库路径)和 `ARKGUARD_SOLO_BINARY`(solo 示例路径)运行 `python -m unittest discover -s tests -p test_native_session.py`。 + +本批 504 项库测试(含外部数据对照)、4 项真实 PyO3 集成测试通过;三个核心 × 三个种子的 9 组结果与现有 solo 入口一致,整局分段推进与连续推进一致,另覆盖机变边界、重复选择、无效输入及技术故障。全目标编译、格式与 diff 检查通过。尚未完成面向策略的观测/动作适配和逐决策整局原版对照;未提交,main 保持 `6af66bf`。 + + +### 原生公开观测、候选动作与 Gymnasium + +`Session::observation()` 从各状态所有者显式投影公开字段:商店有效价格、库存及装备、部署格、盟约计数/层数、机变和悬赏效果、当前回合敌人预览及真实终局。未来波次、隐藏 Boss 身份、RNG、库存池及内部计数不进入观测;准备期结束后保留当前敌人预览,下一回合重建。公开布局按原版顺序输出。策略数据目录直接复用原生 Catalog,不要求源码 Git 状态或源文件指纹。 + +`ArkGuardRL-v1` 沿用 v7 的 4784 维动态观测、41 维候选特征、分组、历史与奖励,核心由构造参数固定。候选掩码仍表示公开可提交的动作域,游戏规则可拒绝其中的动作;padding/越界不执行,候选超限不裁剪。动作立即回执与自动战斗后继分别进入进度记录。Gym 在下一决策/真实终局才返回,预算在决策边界可截断,半场耗尽计算上限则报错并释放对局。普通 reset、关闭后 reset、Gym 种子延续、观测所有权及多环境隔离均保留。 + +使用方法见 README 的原生开发入口。`native_library` 指向与运行 Python 匹配的对局动态库,特征内核仍由现有安装流程构建。旧 `ArkGuardRL-v0` 通过同样的工厂接口继续使用原有后端。本批公开状态对照移除了开发 oracle 对无关源码工作区改动的拒绝及源码身份检查;运行时不依赖 oracle。 + +本批 506 项库测试(含外部数据对照)、12 项真实 Python 会话/Gym 集成测试通过,包含三个核心整局、种子与观测隔离、机变边界、候选越界/超限、预算失败及购买部署战斗链路。两组初始公开状态、一组准备期动作及首场战后公开状态与原版一致;新增折扣观测与实扣金额回归。旧观测验证单测通过,未配置 0.3.1 引擎的 7 项旧入口集成测试未运行。全目标编译、格式、脚本语法及 diff 检查通过;未提交,main 保持 `6af66bf`。 + +### 整局逐决策对照 + +新增 `tests/test_native_rollout.py`,将原生会话与原版 Match 的每次购买、部署、机变选择及战后决策边界逐项比较,覆盖三核心 × 两种种子 × 空阵容/购买部署阵容,共 12 组淘汰终局。比较钱包、库存、商店、部署、盟约计数与层数、效果、敌人预览、累计战绩及终局结算;不以原生入口之间互相比对代替原版验证。 + +对照修正了五处差异:悬赏预览保留原波次,避免展示战斗内部拆分;自持有干员接入原版默认练度的独立属性乘算;随机禁用盟约仅限制卡池,不关闭仍可获得成员的盟约效果;公开效果列表补入核心;机变卡按公开协议投影,不暴露内部执行字段。模式静态禁用仍生效,底层独立 Field 不自动添加练度。 + +本批 506 项 Rust 库测试、14 项 Python 集成测试及原版单人生命周期对照通过;全目标编译、格式、参考脚本语法及 diff 检查通过。胜利与隐藏 Boss 的整局逐决策对照、批量接口及性能验收仍未完成。未提交,main 保持 `6af66bf`。 + +### 后期结局与奖励对照 + +新增三核心 × 四种结局的 12 组逐决策对照:最终突袭胜利/失败、隐藏核心胜利/失败。两端读取同一临时数据目录;夹具提高初始生命及首名干员的属性/射程,降低 Boss 血量和精准激活人数,并切换隐藏门槛,以稳定到达对应分支。所有回合仍经正常购买、部署、选择和战斗推进;隐藏失败通过进入第 15 回合后出售阵容触发,并以每次 97 帧验证续跑。夹具验证后期流程,不代表原难度通关验收,原始数据文件不变。 + +修正 Boss 终局公开状态:保留准备标记、阵容和敌人预览;团队生命归零不等于普通回合淘汰。隐藏核心失败仍按原版计整局胜利,避免奖励适配器误判为失败。公开结算补充 `hiddenReached`、`hiddenCleared` 和 `reason`;模型输入维度不变。逐决策对照同时验证奖励适配器,明确断言隐藏成功与失败、玩家存活标记和终局奖惩。 + +本批原数据 12 组及后期夹具 12 组对照全部通过,506 项 Rust 库测试、15 项 Python 集成测试通过;全目标编译、格式、参考脚本语法及 diff 检查通过。原难度胜利/隐藏核心的整局对照、批量接口与性能验收仍未完成。未提交,main 保持 `6af66bf`。 diff --git a/pyproject.toml b/pyproject.toml index 92b50aa..8c114b4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,7 +21,7 @@ namespaces = false [tool.setuptools.package-data] "arkguardrl.engine" = ["*.mjs"] "arkguardrl_core.routes" = ["*.mjs"] -"arkguardrl_core" = ["native/Cargo.toml", "native/Cargo.lock", "native/src/*.rs"] +"arkguardrl_core" = ["native/Cargo.toml", "native/Cargo.lock", "native/build.rs", "native/src/*.rs"] [[tool.setuptools-rust.ext-modules]] target = "arkguardrl_core._rust_routes" diff --git a/tests/test_gym_env.py b/tests/test_gym_env.py deleted file mode 100644 index 7ee37c6..0000000 --- a/tests/test_gym_env.py +++ /dev/null @@ -1,178 +0,0 @@ -"""Native integration checks: set ARKGUARD_ENGINE_ROOT to the external game checkout.""" -from copy import deepcopy -from contextlib import closing -from functools import partial -import os -import unittest - -import gymnasium as gym -import numpy as np -from gymnasium.utils.env_checker import check_reset_seed_determinism -from gymnasium.utils.passive_env_checker import env_step_passive_checker - -from arkguardrl_core.gym_env import ArkGuardEnv -from arkguardrl.observation import SCHEMA, validate_state - -ENGINE = os.environ.get('ARKGUARD_ENGINE_ROOT') - - -def equal_observations(test, first, second): - test.assertEqual(first.keys(), second.keys()) - for key in first: - np.testing.assert_array_equal(first[key], second[key]) - - -class ObservationValidationTests(unittest.TestCase): - def test_nested_mutation_is_checked_after_successful_validation(self): - state = dict(schema=SCHEMA, revision=0, phase='PREP', round=1, - gameEnded=False, personalEnded=False, decisionRequired=True, - public={'phase': 'PREP', 'round': 1, 'players': [{'playerId': 'p'}]}, - own={'playerId': 'p', 'seat': 0, 'alive': True, 'extension': []}) - expected = validate_state(state) - for key in ('masterSEED', 'rNgState', 'hiddenBossId', 'x'*256+'Seed'): - state['own']['extension'].append({'nested': [{key: 1}]}) - with self.assertRaisesRegex(ValueError, 'Forbidden hidden identity'): - validate_state(state) - state['own']['extension'].clear() - self.assertEqual(validate_state(state), expected) - - -@unittest.skipUnless(ENGINE, 'Set ARKGUARD_ENGINE_ROOT for native integration tests') -class GymEnvTests(unittest.TestCase): - def test_seed_ownership_and_native_reuse(self): - with ArkGuardEnv(ENGINE) as env: - check_reset_seed_determinism(env) - first, info = env.reset(seed=0) - saved = deepcopy(first) - pid = env._pool.session._process.pid - result = env_step_passive_checker(env, env.action_space.sample(mask=first['action_mask'])) - self.assertTrue(env.observation_space.contains(result[0])) - equal_observations(self, saved, first) - again, info_again = env.reset(seed=0) - equal_observations(self, saved, again) - self.assertEqual(info, info_again) - self.assertEqual(pid, env._pool.session._process.pid) - continued, info_continued = env.reset() - env.reset(seed=0) - repeated, info_repeated = env.reset() - equal_observations(self, continued, repeated) - self.assertEqual(info_continued, info_repeated) - env.reset(seed=2**80) - raw = env._result.observation - native = env._session.environment._state - count = len(native['own']['shop']['slots']) - raw['own']['shop']['slots'].append({'mutated': True}) - self.assertEqual(len(native['own']['shop']['slots']), count) - env.close() - - def test_mask_rejection_does_not_advance(self): - with ArkGuardEnv(ENGINE) as env: - observation, info = env.reset(seed=42) - revision = env._result.observation['revision'] - for action in (info['candidate_count'], -1, 0.5, True): - with self.assertRaises(gym.error.InvalidAction): - env.step(action) - self.assertEqual(env._result.observation['revision'], revision) - env.step(env.action_space.sample(mask=observation['action_mask'])) - - def test_truncation_preserves_actual_successor(self): - for limits, reason in (({'max_decisions': 1}, 'decision-budget'), - ({'wall_seconds': 1e-9}, 'wall-budget')): - with ArkGuardEnv(ENGINE, **limits) as env: - env.reset(seed=42) - observation, reward, terminated, truncated, info = env.step(0) - self.assertFalse(terminated) - self.assertTrue(truncated) - self.assertEqual(reward, 0.) - self.assertEqual(info['reason'], reason) - self.assertEqual(info['phase'], 'BAND_DRAFT') - self.assertGreater(observation['action_mask'].sum(), 0) - with self.assertRaises(gym.error.ResetNeeded): - env.step(0) - env.reset(seed=42) - - def test_candidate_overflow_is_not_silently_clipped(self): - with ArkGuardEnv(ENGINE, max_candidates=1) as env: - env.reset(seed=42) - with self.assertRaisesRegex(ValueError, 'no actions were dropped'): - env.step(0) - self.assertIsNone(env._pool.session) - - def test_natural_terminal_observation(self): - rng = np.random.default_rng(np.random.SeedSequence(123).spawn(1)[0]) - with ArkGuardEnv(ENGINE) as env: - observation, _ = env.reset(seed=42) - for _ in range(1024): - action = int(rng.integers(observation['action_mask'].sum())) - observation, _, terminated, truncated, _ = env.step(action) - if terminated or truncated: - break - self.assertTrue(terminated) - self.assertFalse(truncated) - self.assertTrue(env._result.observation['personalEnded']) - self.assertEqual(observation['action_mask'].sum(), 0) - self.assertTrue(env.observation_space.contains(observation)) - self.assertIsNone(env._session) - with self.assertRaises(gym.error.ResetNeeded): - env.step(0) - env.reset(seed=42) - - def test_matches_native_transition_and_reward(self): - from arkguardrl.decision_session import DecisionSession - from arkguardrl.rewards import NativeProgressCore - from arkguardrl_core.routes.session import RouteEnv - with ArkGuardEnv(ENGINE, max_decisions=16) as env: - observation, info = env.reset(seed=42) - native = RouteEnv(ENGINE, deadline=float('inf'), max_decisions=16) - with DecisionSession(native, env.catalog) as session: - result = session.reset(seed=info['engine_seed'], difficulty='ABYSS') - reward = NativeProgressCore() - reward.reset(result.observation) - for _ in range(16): - decision = session.decision() - if _ % 4 == 0: - self.assertIsNone(env._pool.session._geometry) - self.assertEqual(env._session.environment.geometry(), session.environment.geometry()) - count = len(decision.actions) - np.testing.assert_array_equal(observation['observation'], np.asarray(decision.observation_features, np.float32)) - np.testing.assert_array_equal(observation['candidates'][:count], np.asarray(decision.candidate_features, np.float32)) - self.assertEqual(int(observation['action_mask'].sum()), count) - before = result.observation - result = session.step(decision.actions[0]) - expected_reward = reward.step(before, result.observation)['reward'] - observation, actual_reward, terminated, truncated, info = env.step(0) - self.assertEqual((actual_reward, terminated, truncated, info['accepted']), - (expected_reward, result.terminated, result.truncated, result.accepted)) - if terminated or truncated: - break - - def test_sync_async_shared_memory_and_partial_reset(self): - factories = [partial(ArkGuardEnv, ENGINE, max_decisions=limit) for limit in (2, 3)] - mode = gym.vector.AutoresetMode.DISABLED - with closing(gym.vector.SyncVectorEnv(factories, autoreset_mode=mode)) as sync, \ - closing(gym.vector.AsyncVectorEnv(factories, context='spawn', daemon=False, - shared_memory=True, autoreset_mode=mode)) as async_: - first, _ = sync.reset(seed=[42, 43]) - second, _ = async_.reset(seed=[42, 43]) - rng = np.random.default_rng(7) - for _ in range(8): - equal_observations(self, first, second) - saved = deepcopy(second) - actions = np.asarray([rng.integers(mask.sum()) for mask in first['action_mask']]) - a, b = sync.step(actions), async_.step(actions) - equal_observations(self, saved, second) - first, second = a[0], b[0] - for x, y in zip(a[1:4], b[1:4]): - np.testing.assert_array_equal(x, y) - equal_observations(self, first, second) - done = a[2] | a[3] - if done.any(): - final = deepcopy(second) - first, _ = sync.reset(options={'reset_mask': done.copy()}) - second, _ = async_.reset(options={'reset_mask': done.copy()}) - for key in second: - np.testing.assert_array_equal(second[key][~done], final[key][~done]) - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_reference033.py b/tests/test_reference033.py deleted file mode 100644 index 272a4fe..0000000 --- a/tests/test_reference033.py +++ /dev/null @@ -1,49 +0,0 @@ -"""Development oracle checks; explicitly opt in with ARKGUARD_REFERENCE_ROOT.""" -import json -import os -from pathlib import Path -import subprocess -import unittest - -ENGINE = os.environ.get('ARKGUARD_REFERENCE_ROOT') -BRIDGE = Path(__file__).resolve().parents[1] / 'tools/reference/session.mjs' - - -@unittest.skipUnless(ENGINE, 'Set ARKGUARD_REFERENCE_ROOT to the 0.3.3 reference checkout') -class ReferenceTests(unittest.TestCase): - def request(self, commands): - result = subprocess.run(['node', str(BRIDGE), ENGINE], - input=''.join(json.dumps(c) + '\n' for c in commands), - text=True, capture_output=True, timeout=20, check=True) - replies = [json.loads(line) for line in result.stdout.splitlines()] - self.assertEqual(len(replies), len(commands), result.stderr) - return replies - - def test_all_difficulties_and_seed_reuse(self): - commands = [] - for difficulty in ('FUNNY', 'NORMAL', 'HARD', 'ABYSS'): - for _ in range(2): - commands.extend([{'cmd': 'reset', 'seed': 42, 'difficulty': difficulty}, - {'cmd': 'step', 'action': {'t': 'g.infoReady'}}]) - commands.append({'cmd': 'close'}) - replies = self.request(commands) - for reply in replies: - self.assertTrue(reply['ok'], reply) - for i in range(0, 16, 4): - self.assertEqual(replies[i]['state'], replies[i + 2]['state']) - self.assertEqual(replies[i + 1]['state'], replies[i + 3]['state']) - self.assertEqual(replies[i]['state']['phase'], 'INFO_CHECK') - self.assertEqual(replies[i + 1]['state']['phase'], 'BAND_DRAFT') - self.assertTrue(replies[i + 1]['accepted']) - self.assertFalse(replies[i + 1]['truncated']) - - def test_bad_budget_fails_closed(self): - replies = self.request([{'cmd': 'reset', 'seed': 42}, - {'cmd': 'step', 'action': {'t': 'g.infoReady'}, 'maxCallbacks': 0}]) - self.assertTrue(replies[0]['ok']) - self.assertFalse(replies[1]['ok']) - self.assertEqual(replies[1]['error'], 'Invalid callback budget') - - -if __name__ == '__main__': - unittest.main() diff --git a/tools/reference/area.mjs b/tools/reference/area.mjs deleted file mode 100644 index a8ca6a1..0000000 --- a/tools/reference/area.mjs +++ /dev/null @@ -1,16 +0,0 @@ -// Actual ai.resolveHit + radius queries + HP settlement, with synchronous callbacks. -import path from 'node:path';import {pathToFileURL} from 'node:url'; -const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const {resolveHit}=await imp('server/sim/ai.js');const {Unit}=await imp('server/sim/units.js'); -const {BattleQueries}=await imp('server/sim/battle/queries.js');const {resolveDamage}=await imp('server/sim/attack/hit.js');const {makeDamageInfo}=await imp('server/sim/attack/helpers.js');const {normHitArea}=await imp('server/sim/body.js');const {createRng}=await imp('server/sim/rng.js'); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<512;i++){ - const cfg={i,type:['phys','arts','true','elemental'][i%4],hits:1+i%3,split:i%5===0?.5:null,mul:i%7===0?0:.75,skill:i%2===0,splash:i%3!==0,chain:i%4!==0,count:[0,1,3,4.2][i%4],radius:i%7===0?0:1.7,falloff:i%11===0?0:.15,sluggish:i%5===0?.3:0,canHitFly:i%3===0,groundOnly:i%7===0,splashFly:i%5===0,fortressMelee:i%11===0,fortressSplash:i%13===0,main:i%17===0?null:2,move:i%5===0,changeAtk:i%7===0}; - const records=Array.from({length:12},(_,j)=>({id:j+2,x:6+[0,.6,-.6,1.2,-1.2,2.4,-2.4,0,0,1.2,-1.2,3][j],y:10+[0,0,0,0,0,0,0,.6,-.6,.6,-.6,0][j],hp:(i+j)%13===0?30:1000,fly:j%4===1,alive:!(j===0&&i%19===0),deployed:!(j===7&&i%7===0),hidden:j===6&&i%3===0,stealth:j===8&&i%5===0,reveal:i%7===0,sleep:j===9&&i%3===0,untargetable:j===10&&i%11===0,huge:j===11,seq:12-j})); - const source=new Unit({id:1,side:'ally',base:{maxHp:1000,atk:60.25}});source.deployed=true; - const enemies=records.map(d=>{const u=new Unit({id:d.id,side:'enemy',x:d.x,y:d.y,motion:d.fly?'FLY':'WALK',base:{maxHp:1000,def:20,res:30}});u.hp=d.hp;u.alive=d.alive;u.deployed=d.deployed;u.hidden=d.hidden;u.spawnSeq=d.seq;u.hitArea=d.huge?normHitArea({w:4.95,h:2.95,dx:0,dy:1}):null;u.buffs=[{stacks:1,mods:{},flags:{stealth:d.stealth,reveal:d.reveal,sleep:d.sleep,untargetable:d.untargetable},shield:0}];return u;}); - const trace=[];const b={enemies,time:0,rng:createRng(42),_hooks:{},kind:'normal',enemiesInRadius:BattleQueries.prototype.enemiesInRadius,foesInRadius:BattleQueries.prototype.foesInRadius,_safe:fn=>fn(),_ev(e){if(e[0]==='atk')trace.push(['link',e[1],e[2]]);},_pp:()=>null,_skills:{onDamaged(){}},kill(t){t.alive=false;t.deployed=false;t.hp=0;trace.push(['kill',t.id]);},applyStatus(t,key,o){trace.push(['slow',t.id,bits(o.duration)]);},dealDamage(s,t,r){trace.push(['hit',t.id,bits(r.amount),bits(r.mul??1),!!r.noSp,!!r.isSplash,r.tags??[],r.attackId]);return resolveDamage(this,{source:s,credit:s,target:t,dmg:makeDamageInfo(r)});}}; - const profile={dmgType:cfg.type,atkScale:1.25,hits:cfg.hits,hitDmgMul:cfg.split,dmgMul:cfg.mul,skillDmgMul:1.15,canHitFly:cfg.canHitFly,groundOnly:cfg.groundOnly,splashRadius:cfg.splash?1.5:0,splashScale:i%13===0?0:.7,splashHitsFly:cfg.splashFly,fortressMeleeSplash:cfg.fortressSplash,chain:cfg.chain?{count:cfg.count,radius:cfg.radius,falloff:cfg.falloff,sluggish:cfg.sluggish}:null,onEachHit(b,u,t,c){trace.push(['each',t.id,c.kind,bits(c.dealt),c.main?.id??null,c.attackId,c.isSkill]);if(c.kind==='main'){if(cfg.move)t.x+=.6;if(cfg.changeAtk){u.base.atk=999;u.markDirty();}}},afterHit(b,u,t,c){trace.push(['after',t?.id??null,bits(c.dealt),bits(c.x),bits(c.y),c.isSkill]);}}; - resolveHit(b,source,profile,cfg.main?enemies[0]:null,{attackId:17,isSkill:cfg.skill,fortressMelee:cfg.fortressMelee,index:0},6,10); - process.stdout.write(JSON.stringify({cfg,records,splashScale:profile.splashScale,trace,hp:enemies.map(u=>bits(u.hp)),alive:enemies.map(u=>u.alive)})+'\n'); -} diff --git a/tools/reference/blocking.mjs b/tools/reference/blocking.mjs deleted file mode 100644 index 0cd14ae..0000000 --- a/tools/reference/blocking.mjs +++ /dev/null @@ -1,15 +0,0 @@ -// Real upstream block contact/release functions; no matches/data. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const{Grid}=await imp('server/sim/grid.js');const{BattleBlocking}=await imp('server/sim/battle/blocking.js'); -for(let i=0;i<1024;i++){ - const d={i,fly:i%3===0,blockFly:i%4===0,profileFly:i%13===0,ground:i%17!==0,fence:i%19===0,sleep:i%23===0,unblockable:i%29===0,hidden:i%31===0,device:i%7===0,cap:i%4,weight:1+i%2,radius:(i%3)*.23,x:4+(i%11-5)/10,y:10+(Math.floor(i/11)%11-5)/10}; - const stage={rows:Array(19).fill('r'.repeat(21))};if(d.fence)stage.rows[10]=stage.rows[10].slice(0,4)+'b'+stage.rows[10].slice(5); - const grid=new Grid(stage,{r0:0,r1:18,c0:0,c1:20});const occ=Array(399).fill(null);const units=[]; - for(const [id,row,col]of[[1,10,4],[2,10,5]]){const u=new Unit({id,kind:d.device?'device':'op',side:'ally',tileR:row,tileC:col,base:{blockCnt:d.cap}});u.deployed=true;u.ground=d.ground;u.profile={blockFly:d.profileFly};u.buffs=[{stacks:1,mods:{blockRadiusScale:d.radius},flags:{blockFly:d.blockFly,sleep:d.sleep}}];occ[row*21+col]=u;units.push(u);} - const enemy=new Unit({id:3,side:'enemy',kind:'enemy',x:d.x,y:d.y,motion:d.fly?'FLY':'WALK'});enemy.blockWeight=d.weight;enemy.hidden=d.hidden;enemy.buffs=[{stacks:1,flags:{unblockable:d.unblockable}}];enemy.moving=true; - const trace=[];const b={grid,_occ:occ,_hooks:{blocked:true},emit(n,e){trace.push([n,e.blocker.id,e.enemy.id]);},_stealthSwitch(e){trace.push(['ended',e.id]);},_blockerFor:BattleBlocking.prototype._blockerFor}; - const checks=[];checks.push(BattleBlocking.prototype._checkBlock.call(b,enemy));checks.push(BattleBlocking.prototype._checkBlock.call(b,enemy));const held=enemy.blockedBy?.id??null; - if(i%2)BattleBlocking.prototype._unblock.call(b,enemy);else for(const u of units)BattleBlocking.prototype.releaseBlocked.call(b,u); - checks.push(BattleBlocking.prototype._checkBlock.call(b,enemy)); - process.stdout.write(JSON.stringify({scenario:d,checks,held,final:enemy.blockedBy?.id??null,lists:units.map(u=>u.blocking.map(e=>e.id)),moving:enemy.moving,trace})+'\n'); -} diff --git a/tools/reference/body.mjs b/tools/reference/body.mjs deleted file mode 100644 index a490469..0000000 --- a/tools/reference/body.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Real collider helpers and BattleQueries index; no match or assets. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const body=await imp('server/sim/body.js');const{Unit}=await imp('server/sim/units.js');const{BattleQueries}=await imp('server/sim/battle/queries.js');const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<1024;i++){ - const x=(i%31-5)/2+[0,.4,.4999999999,.5000000001][i%4],y=(Math.floor(i/31)%25-3)/2; - const area=i%3===0?{w:4.95,h:2.95,dx:i%2?.3:0,dy:1}:i%7===0?{w:1,h:1,dx:0,dy:0}:null; - const u={x,y,side:i%2?'enemy':'ally',hitArea:body.normHitArea(area)};const origin=[10,4];const tiles=[214,215,235,236,237]; - process.stdout.write(JSON.stringify({body:true,i,x,y,area,side:u.side,keys:body.bodyKeys(u),collider:body.colliderKeys(u),on:body.bodyOnTile(u,10,4),inKeys:body.bodyInKeys(u,tiles),inRange:body.bodyInRange(u,tiles),distance:bits(body.bodyDist(u,origin[1],origin[0])),radius:body.bodyInRadius(u,origin[1],origin[0],2),reach:bits(body.bodyTileReach(u,10,4))})+'\n'); -} -for(let i=0;i<128;i++){ - const records=Array.from({length:6},(_,j)=>({id:j+2,x:4.4+(j%3)*.2,y:10.49+Math.floor(j/3)*.3,huge:j%3===0,hidden:i%7===0&&j===2,alive:!(i%5===0&&j===3),deployed:!(i%11===0&&j===1),fly:j%2===1,sleep:i%13===0&&j===0,untargetable:i%17===0&&j===4})); - const enemies=records.map(d=>{const u=new Unit({id:d.id,side:'enemy',kind:'enemy',x:d.x,y:d.y,motion:d.fly?'FLY':'WALK'});u.alive=d.alive;u.deployed=d.deployed;u.hidden=d.hidden;u.hitArea=d.huge?body.normHitArea({w:4.95,h:2.95,dx:0,dy:1}):null;u.buffs=[{stacks:1,mods:{},flags:{sleep:d.sleep,untargetable:d.untargetable},shield:0}];return u;}); - const b={enemies,_eb:Array.from({length:399},()=>[]),_et:Array.from({length:399},()=>[]),_ebUsed:[],_etUsed:[],enemiesOnTiles:BattleQueries.prototype.enemiesOnTiles};BattleQueries.prototype._buildEnemyIndex.call(b); - const attacker=new Unit({id:1,side:'ally'});attacker.profile={rangeTiles:i%2===0};const p={canHitFly:i%3===0,hitSleep:i%5===0,skipEnemy:e=>i%7===0&&e.id===3}; - const keys=[214,235,215,236,214,999];const ids=list=>list.map(u=>u.id); - process.stdout.write(JSON.stringify({index:true,i,records,rangeTiles:attacker.profile.rangeTiles,fly:p.canHitFly,hitSleep:p.hitSleep,skip:i%7===0,keys,enemies:ids(BattleQueries.prototype.enemiesInKeys.call(b,keys,attacker,p)),tiles:ids(BattleQueries.prototype.enemiesOnTiles.call(b,keys,attacker,p)),any:BattleQueries.prototype.anyEnemyInKeys.call(b,keys,attacker)})+'\n'); -} -for(let i=0;i<256;i++){ - const records=Array.from({length:9},(_,j)=>({id:j+1,tile:[10,j%2?6:8],hp:[100,1000-5e-7,1000][(i+j)%3],maxHp:1000,seq:(j*7+i)%9,alive:!(i%5===0&&j===3),deployed:!(i%7===0&&j===2),hidden:i%11===0&&j===4,device:j===5,noHeal:(i+j)%3===0,profileNoHeal:i%13===0&&j===1,element:j===6?1:0})); - const allies=records.map(d=>{const u=new Unit({id:d.id,side:'ally',kind:d.device?'device':'op',x:d.tile[1],y:d.tile[0],base:{maxHp:d.maxHp}});u.hp=d.hp;u.deploySeq=d.seq;u.alive=d.alive;u.deployed=d.deployed;u.hidden=d.hidden;u.profile={noHeal:d.profileNoHeal};u.buffs=[{mods:{},flags:{noHeal:d.noHeal},stacks:1,shield:0}];u.elem.burn=d.element;return u;}); - const healer=i%2?allies[1]:null;const through=i%3===0;if(healer)healer.profile.healThrough=()=>through; - const b={allyUnits:allies};const keys=[216,218]; - process.stdout.write(JSON.stringify({healing:true,i,records,keys,healer:healer?.id??null,through,includeElement:i%2===0,targets:BattleQueries.prototype.injuredAlliesInKeys.call(b,keys,healer,i%2===0).map(u=>u.id)})+'\n'); -} diff --git a/tools/reference/buffs.mjs b/tools/reference/buffs.mjs deleted file mode 100644 index 5887610..0000000 --- a/tools/reference/buffs.mjs +++ /dev/null @@ -1,29 +0,0 @@ -// Real BattleStatus add/remove/tick with nested callbacks, no assets or match. -import path from 'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{BattleStatus}=await imp('server/sim/battle/status.js');const{makeBuff}=await imp('server/sim/buffs.js');const{Unit}=await imp('server/sim/units.js');const{heal}=await imp('server/sim/attack/heal.js'); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<256;i++){ - const base=makeBuff({}).seq;const u=new Unit({id:1,side:'ally',base:{maxHp:1000,hpRegen:i%2?2.3:10,atk:60}});u.hp=950;u.deployed=true;const trace=[];let nested=false; - const b={units:[u],time:0,_hooks:{},_safe:fn=>fn(),_ev(e){if(e[0]==='status')trace.push(e);},_pp:()=>null,heal(source,target,amount,opts){return heal(this,source,target,amount,opts);}}; - for(const key of ['addBuff','removeBuff','_removeBuffAt','_tickBuffs'])b[key]=BattleStatus.prototype[key]; - function callback(token,event,{unit,buff,dt}){ - trace.push([event,buff.seq-base,bits(dt??0),bits(buff.timeLeft),bits(buff._acc),unit.buffs.includes(buff)]); - if(event!=='tick'){ - if(token===4)b.removeBuff(unit,'b'); - if(token===5)b.addBuff(unit,desc({key:buff.key,duration:.4,tick:1,mods:{atkPct:.2}})); - return; - } - if(token===2)b.removeBuff(unit,buff); - if(token===3&&!buff.data.spawned){buff.data.spawned=true;b.addBuff(unit,desc({key:'child',duration:.15,tick:1,mods:{atkPct:.1}}));} - if(token===6)b.addBuff(unit,desc({key:buff.key,duration:.2,tick:1,mods:{atkPct:.3}})); - if(token===7){unit.hp=0;unit.alive=false;unit.deployed=false;} - if(token===8&&!nested){nested=true;try{b._tickBuffs(dt/2);}finally{nested=false;}} - } - function desc(d){return{key:d.key,duration:d.duration==='inf'?Infinity:d.duration,stacks:d.stacks,maxStacks:d.cap,refresh:d.refresh,mods:d.mods??null,flags:d.flags??null,shield:d.shield,shieldHits:d.hits,persist:d.persist,visible:d.visible,status:d.status,allowDead:d.allowDead,interval:d.interval,onTick:d.tick?c=>callback(d.tick,'tick',c):null,onRemove:d.remove?c=>callback(d.remove,'remove',c):null,onExpire:d.expire?c=>callback(d.expire,'expire',c):null};} - const ops=[];for(let j=0;j<36;j++){ - if(j%5<2){const tick=[null,1,2,3,6,8,i%16===0?7:1][(i+j)%7];ops.push({op:'add',key:['a','b','a','c'][(i+j)%4],duration:[.05,.2,.5,'inf',0,-1][(i+j)%6],stacks:1+(i+j)%3,cap:1+(i+j)%4,refresh:['replace','extend','stack','independent','keep'][(i+Math.floor(j/5))%5],mods:j%3===0?null:j%3===1?{}:{atkPct:.1},flags:j%3===0?null:j%3===1?{}:{noHeal:true},shield:(i+j)%3*10,hits:(i+j)%2,persist:i%3===0,visible:true,status:i%11===0?'shared':null,allowDead:j%3===0,interval:[0,.1,.01][(i+j)%3],tick,remove:(i+j)%3===0?4:1,expire:(i+j)%3===0?5:1});} - else if(j%5===3)ops.push({op:'remove',key:['a','b','c'][j%3]});else ops.push({op:'tick',dt:[0,.03,.4,.5][(i+j)%4]}); - } - const states=[];for(const op of ops){if(op.op==='add')b.addBuff(u,desc(op));else if(op.op==='remove')b.removeBuff(u,op.key);else{b.time+=op.dt;b._tickBuffs(op.dt);}const s=u.s;states.push({hp:bits(u.hp),regen:bits(u._regenAcc??0),alive:u.alive,atk:bits(s.atk),buffs:u.buffs.map(x=>({id:x.seq-base,key:x.key,stacks:x.stacks,cap:x.maxStacks,duration:bits(x.duration),left:bits(x.timeLeft),acc:bits(x._acc),shield:bits(x.shield),hits:x.shieldHits}))});} - process.stdout.write(JSON.stringify({i,ops,states,trace})+'\n'); -} diff --git a/tools/reference/clock.mjs b/tools/reference/clock.mjs deleted file mode 100644 index 53936bc..0000000 --- a/tools/reference/clock.mjs +++ /dev/null @@ -1,14 +0,0 @@ -// Real BattleLifecycle methods with instrumented phase bodies; no matches/data. -import path from'node:path';import{pathToFileURL}from'node:url'; -const root=path.resolve(process.argv[2]);const{BattleLifecycle}=await import(pathToFileURL(path.join(root,'server/sim/battle/lifecycle.js'))); -const phases=['start','scheduled','spawns','dp','buffs','attackCommit','enemies','enemyIndex','allies','rate','projectiles','redeploy','boss','tickHook','endCheck']; -for(let stop=-1;stopenemy,_hasPendingEnemySchedules:()=>hold,time:1/30,timeLimit:timeout?0:10,_finish(r){reason=r;},_timeout(){reason='timeout';}}; - BattleLifecycle.prototype._checkEnd.call(b); - process.stdout.write(JSON.stringify({policy:true,shared,boss,auto,pending,enemy,hold,timeout,reason})+'\n'); -} diff --git a/tools/reference/combat.mjs b/tools/reference/combat.mjs deleted file mode 100644 index 51111dd..0000000 --- a/tools/reference/combat.mjs +++ /dev/null @@ -1,31 +0,0 @@ -// Continuous skill + search + real updateAlly/performAttack/resolveDamage integration. -// Real geometry, range index and skill conditions; movement is a phase fixture. -import fs from'node:fs';import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Grid}=await imp('server/sim/grid.js');const fear=await imp('server/sim/fear.js');const E=await imp('server/sim/attack/element.js');const{BattleStatus}=await imp('server/sim/battle/status.js');const{makeBuff}=await imp('server/sim/buffs.js');const{BattleQueries}=await imp('server/sim/battle/queries.js');const{ProjectileSystem}=await imp('server/sim/projectiles.js');const{heal}=await imp('server/sim/attack/heal.js');const{Unit}=await imp('server/sim/units.js');const{SkillRuntime}=await imp('server/sim/skills.js');const ai=await imp('server/sim/ai.js');const{resolveDamage}=await imp('server/sim/attack/hit.js');const{makeDamageInfo}=await imp('server/sim/attack/helpers.js');const{canTargetEnemy}=await imp('server/sim/targeting.js');const{createRng}=await imp('server/sim/rng.js'); -const{KITS}=await imp('server/sim/content/enemies.js');const{abOf,attach}=await imp('server/sim/content/enemies/helpers.js');const enemyData=JSON.parse(fs.readFileSync(path.join(root,'data/enemies.json'),'utf8')); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<96;i++){ - const d={i,kind:['instant','duration','ammo'][i%3],rule:i%4===0?'SP_FULL':'DEFAULT',attack:i%3===0,hits:1+i%2,dead:i%5===0,stop:i%7===0,store:i%11===0,stun:i%13===0,ranged:i%2===1,shooterDeath:i===23,healer:i%6===4,splash:i>=24&&i%3!==0,chain:i>=24&&i%4!==0,mobile:i>=48&&i%6!==4}; - if(i>=60){d.contentKey=['enemy_1009_lurker','enemy_1200_msfjin','enemy_1204_msfhu','enemy_9011_acrefr'][i%4];d.contentRaw=enemyData[d.contentKey];d.healer=false;d.mobile=true;} - if(i>=84){d.contentKey=['enemy_1305_mhslim','enemy_1305_mhslim_2','enemy_2021_syfish'][i%3];d.contentRaw=enemyData[d.contentKey];d.dead=false;} - const u=new Unit({id:1,side:'ally',kind:'op',x:4,y:10,base:{maxHp:i>=84?100000:1000,atk:80,bat:.2}});u.deployed=true;u.rangeKeys=[216];u.baseRangeKeys=[216];u.profile={attack:d.ranged?'ranged':'melee',dmgType:d.healer?'heal':'phys',heal:d.healer?{mode:'single'}:null,atkScale:1,hits:d.hits,projectile:d.ranged?'arrow':'none',storeEnergy:d.store?(b,a)=>{trace.push(['store']);if(stored>=2)return false;stored++;return true;}:null}; - const e=new Unit({id:2,side:d.healer?'ally':'enemy',kind:d.healer?'op':'enemy',base:{maxHp:d.dead?500:100000,def:20,atk:i>=84?d.contentRaw.stats.atk:30,res:30,moveSpeed:2,rangeRadius:3}});e.deployed=true;if(d.healer)e.hp=100;e.spawnSeq=1;e.x=6;e.y=10;e.tileR=10;e.tileC=6;let stored=0;const trace=[];const grid=new Grid({rows:Array(19).fill('r'.repeat(21)),legend:{}},{r0:0,r1:18,c0:0,c1:20});if(d.mobile){e.profile={};e.def={dmgType:'phys',applyWay:'RANGED',attackAnim:{dur:.8,hit:.3}};e.spawnY=e.y;e.spawnX=e.x;e.route={legs:ai.compileRoute({checkpoints:[{type:'WAIT',time:.2},{type:'MOVE',pos:[10,9]},{type:'MOVE',pos:[10,6]}],end:[10,9]}),legIdx:0,pts:null,ptIdx:0,waitLeft:null};} - const extras=i>=24&&!d.healer?Array.from({length:4},(_,j)=>{const a=new Unit({id:j+3,side:'enemy',kind:'enemy',x:6.8+j*.6,y:10,motion:j%2?'FLY':'WALK',base:{maxHp:d.dead?500:100000,def:20}});a.deployed=true;a.spawnSeq=j+2;return a;}):[];const enemies=d.healer?[]:[e,...extras];u.profile.splashRadius=d.splash?1.5:0;u.profile.splashScale=.7;u.profile.chain=d.chain?{count:4,radius:1.7,falloff:.15}:null; - const baseBuff=makeBuff({key:'control',flags:{},mods:{}});u.buffs=[baseBuff]; - const b={time:0,dt:1/30,_attackSeq:0,_hooks:{skillStart:true,skillEnd:true,ammoUsed:true},allyUnits:d.healer?[u,e]:[u],enemies,_eb:Array.from({length:399},()=>[]),_et:Array.from({length:399},()=>[]),_ebUsed:[],_etUsed:[],rng:createRng(42),kind:'normal',rangeChanged:()=>false,_refreshRange(){},remainingDistance:()=>5, - enemiesInKeys:BattleQueries.prototype.enemiesInKeys,enemiesInRadius:BattleQueries.prototype.enemiesInRadius,foesInRadius:BattleQueries.prototype.foesInRadius,enemiesOnTiles:BattleQueries.prototype.enemiesOnTiles,blockedTargets:()=>[],_allyTargets:null,injuredAlliesInKeys:BattleQueries.prototype.injuredAlliesInKeys,alliesInRadius:BattleQueries.prototype.alliesInRadius, - grid,units:[u,e,...extras],_checkBlock:()=>false,_cutAttackStand(){},_setHidden(e,on){e.hidden=on;},leak(e){e.alive=false;e.deployed=false;trace.push(['leak']);},rect:{r0:0,r1:18,c0:0,c1:20},fx(){},_unblock(){},releaseBlocked(){},applyStatus:BattleStatus.prototype.applyStatus,resistOf:BattleStatus.prototype.resistOf,_setAttractPoint:BattleStatus.prototype._setAttractPoint,_applyValuedStatus:BattleStatus.prototype._applyValuedStatus,addBuff:BattleStatus.prototype.addBuff,removeBuff:BattleStatus.prototype.removeBuff,_removeBuffAt:BattleStatus.prototype._removeBuffAt,_tickBuffs:BattleStatus.prototype._tickBuffs,_ev(){},_pp(){return null;},_safe:fn=>fn(), - emit(name,c){if(name==='damaged'){if(c.source?.mem.ab&&c.dmg?.isAttack&&c.dmg.type!=='element')for(const a of c.source.mem.ab.list)if(a.dealt&&!(a.sil&&c.source.s.flags.silence))a.dealt(c,b,c.source,a,c.source.mem.ab);return;}trace.push([name]);},_skills:{onDamaged(t){t.skill?.onDamaged();}},kill(t){t.hp=0;t.alive=false;t.deployed=false;trace.push(['kill']);}, - heal(source,target,amount){return heal(this,source,target,amount);},dealDamage(source,target,request){if(arguments.length===1){const q=source;return resolveDamage(this,{source:q.source??null,credit:q.credit??q.source??null,target:q.target,dmg:makeDamageInfo(q)});}if(request.type==='element')return E.applyElement(this,{source,credit:source,target,dmg:makeDamageInfo(request)});return resolveDamage(this,{source,credit:source,target,dmg:makeDamageInfo(request)});},isAllyTarget:()=>false};b.projectiles=new ProjectileSystem(b);b.addProjectile=p=>b.projectiles.add(p); - if(d.contentKey){b._hooks.damaged=true;e.defId=d.contentKey;Object.assign(e.def,{raw:d.contentRaw,talent:d.contentRaw.talents.bb});attach(b,e,KITS[d.contentKey](abOf(b,e),e,b));} - const spec={kind:d.kind,duration:.3,ammo:2,spCost:2,initSp:0,charges:1,spType:'attack',trigger:d.rule,attack:d.attack?{atkScale:1.5}:null,mods:{atkPct:.5},onStart(){trace.push(['start']);},onEnd(){trace.push(['end']);}}; - const skill=new SkillRuntime(b,u,{spCost:2,spType:'attack',skillType:'MANUAL'},spec);u.skill=skill;BattleQueries.prototype._buildEnemyIndex.call(b);skill.reset();const move=(inside,advance=false)=>{if(d.mobile){if(advance)ai.updateEnemy(b,e,b.dt);}else{e.x=inside?6:8;e.tileC=inside?6:8;}BattleQueries.prototype._buildEnemyIndex.call(b);}; - const states=[];for(let tick=0;tick<240;tick++){ - b.time=tick/30;if(i>=40&&i<60&&!d.healer&&tick===0)E.applyElement(b,{source:u,credit:u,target:e,dmg:{amount:1100,mul:1,type:'element',element:['burn','neural','necrosis','apoptosis','erosion'][i%5]}});if(d.shooterDeath&&tick===2){u.alive=false;u.deployed=false;u.removed=true;skill.end('death');}if(d.healer)e.hp=Math.max(1,e.hp-3);if(i>=24&&!d.healer){if(tick%31===0)b.addBuff(e,{key:'battleShield',duration:.3,shield:50});if(tick%37===0)b.addBuff(e,{key:'protection',duration:.5,mods:{dmgTakenMul:.8,dodgePhys:.2}});}if(i>=36&&tick%23===0)b.addBuff(u,{key:'pulse',duration:.4,interval:.1,mods:{atkPct:.1},onTick({unit,buff}){trace.push(['pulse']);buff.stacks++;unit.markDirty();}});if(d.mobile){if(tick===20)b.applyStatus(e,'fear',{duration:.6,source:u});if(tick===40)b.applyStatus(e,'attract',{duration:.6,point:[10,6]});if(tick===90)grid.setObstacle(10,7,true);if(tick===130)grid.setObstacle(10,7,false);}if(d.contentKey&&[12,90].includes(tick))b.applyStatus(e,'reveal',{duration:.8});if(d.contentKey&&[40,120].includes(tick))b.applyStatus(e,'silence',{duration:.3});b._tickBuffs(b.dt);move(tick%17<12);baseBuff.flags.stun=d.stun&&tick>=30&&tick<45;u.markDirty(); - ai.noteAttackCommit(b,b.dt);move((tick+1)%17<12,true); - if(u.alive&&u.deployed)skill.tick(b.dt);ai.updateAlly(b,u,b.dt);b.projectiles.update(b.dt);if(e.alive&&!e.mem.carrier&&e.mem.ab)for(const a of e.mem.ab.list)if(a.tick)a.tick(b,e,a,b.dt);if(d.stop&&tick===100)skill.end('stopped'); - void e.s; // Materialize the canonical lazy max-HP ratio before reading HP. - states.push({sourceElement:['burn','neural','necrosis','apoptosis','erosion'].map(el=>bits(u.elem[el])),hp:bits(e.hp),sourceHp:bits(u.hp),enemyCd:bits(e.atkCd),enemyAttacks:e.stats.attacks,attackSequence:b._attackSeq,alive:e.alive,position:[bits(e.y),bits(e.x)],moving:e.moving,element:['burn','neural','necrosis','apoptosis','erosion'].map(el=>bits(e.elem[el])),elementLock:E.burstLocked(e),enemyAtk:bits(e.s.atk),enemyRes:bits(e.s.res),shield:bits(e.s.shield),rng:b.rng.state(),otherHp:extras.map(a=>bits(a.hp)),flights:b.projectiles.list.length,cd:bits(u.atkCd),had:u.trait.hadTarget??null,attacks:u.stats.attacks,sp:bits(skill.sp),charges:bits(skill.charges),active:skill.active,pending:skill.pending,time:bits(skill.timeLeft),ammo:bits(skill.ammoLeft),last:bits(u.lastAttackAt),atk:bits(u.s.atk)}); - } - process.stdout.write(JSON.stringify({scenario:d,states,trace})+'\n'); -} diff --git a/tools/reference/definitions.mjs b/tools/reference/definitions.mjs deleted file mode 100644 index 134f212..0000000 --- a/tools/reference/definitions.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Development-only normalization/spawn oracle; no content abilities are exercised. -import fs from 'node:fs';import path from 'node:path';import{pathToFileURL}from'node:url'; -const root=path.resolve(process.argv[2]); -const{normalizeEnemy}=await import(pathToFileURL(path.join(root,'server/sim/simdata.js'))); -const{Battle}=await import(pathToFileURL(path.join(root,'server/sim/Battle.js'))); -const raw=JSON.parse(fs.readFileSync(path.join(root,'data/enemies.json'),'utf8')); -Object.assign(raw,{ - enemy_alias:{rank:'boss',staticBody:true,stats:{hp:'1234',attackSpeed:0,baseAttackTime:'1.3',range:'2.2',spd:'0.8',magicResistance:'23',elementRes:'11',elementDmgRes:12,immunities:{stunImmune:true},otherImmunities:['sleepImmune']},dmg:'ELEMENT',hitArea:{w:'2',h:3,dx:0.2,dy:-0.1},attackAnim:{dur:1,hit:3},attackMoves:true}, - enemy_heal:{applyWay:'RANGED',dmg:'HEAL',hp:345,atk:100,range:4,motion:'FLY',immune:['freezeImmune'],extra:{epResistance:12,epDamageResistance:23,hpRecoveryPerSec:7}}, -}); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -let i=0; -for(const[key,r]of Object.entries(raw)){ - const overrides=i%3?{}:{stats:{hp:1234.5,atk:234.6,def:34.7,res:80,aspd:123,bat:0.7,rangeRadius:2.3,moveSpeed:0.65,massLevel:4,blockCnt:3,lpr:2}}; - const mods=i%2?{hpMul:1.25,atkMul:0.8,defMul:2,resMul:0,speedMul:1.3}:{hpMul:0,atkMul:-2,defMul:-1}; - const b=new Battle({content:'none',recordEvents:false,data:{enemies:{[key]:r}},enemyOverrides:{[key]:overrides},logger:{warn(){},error(){}}}); - const e=b.spawnEnemy(key,{pos:[10,6],mods}),d=e.def; - const base={maxHp:d.maxHp,atk:d.atk,def:d.def,res:d.res,aspd:d.aspd,bat:d.bat,rangeRadius:d.rangeRadius,moveSpeed:d.moveSpeed,massLevel:d.massLevel,blockCnt:0,spRecovery:0,tauntLevel:d.tauntLevel,hpRecoveryPerSec:d.hpRecoveryPerSec}; - const output={key,base,dmgType:d.dmgType,melee:d.applyWay==='MELEE',motion:d.motion,leader:d.rank==='BOSS',lpr:d.lpr,blockWeight:d.blockCnt,immune:[...d.immune].sort(),epResistance:d.epResistance,elementalResistance:d.epDamageResistance,notCountInTotal:d.notCountInTotal,hitArea:d.hitArea,attackAnim:d.attackAnim,attackMoves:d.attackMoves,staticBody:d.staticBody}; - const unit={base:Object.fromEntries(Object.keys(base).map(k=>[k,bits(e.base[k])])),hp:bits(e.hp),blockWeight:bits(e.blockWeight),fly:e.isFlying,staticBody:!!e.def.staticBody,immune:[...d.immune].sort(),position:[bits(e.y),bits(e.x)]}; - console.log(JSON.stringify({key,raw:r,overrides,mods,output,unit}));i++; -} diff --git a/tools/reference/deploy.mjs b/tools/reference/deploy.mjs deleted file mode 100644 index a2d4c08..0000000 --- a/tools/reference/deploy.mjs +++ /dev/null @@ -1,25 +0,0 @@ -// Direct upstream deployment methods with explicit skill/content stubs. No matches/data. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const{BattleDeploy}=await imp('server/sim/battle/deploy.js');const{BattleTiles}=await imp('server/sim/battle/tiles.js');const{Grid}=await imp('server/sim/grid.js'); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<384;i++){ - const d={i,token:i%5===0,foreign:i%3===0,homeTaken:i%7===0,downHome:i%11===0,raid:i%13===0,permanent:i%17===0,revive:i%19===0,retreat:i%2===0}; - const trace=[];const grid=new Grid({rows:Array(19).fill('r'.repeat(21))},{r0:9,r1:12,c0:2,c1:10}); - const make=(id,kind,tile)=>{const u=new Unit({id,uid:id,side:'ally',kind,tileR:tile[0],tileC:tile[1],base:{maxHp:100,cost:7,respawnTime:3}});u.skill={active:false,reset(){},setSpTotal(){}};u.alive=false;return u;}; - const a=make(1,d.token?'token':'op',[9,2]),b=make(2,'op',d.foreign?[10,4]:[12,10]);a.ownerId='p';b.ownerId='p'; - const ps={dp:20};const btl={time:0,grid,_occ:Array(399).fill(null),_deploySeq:0,allyUnits:[a,b],units:[a,b],flags:{startOpCooldown:3,dpMax:99},_hooks:{kill:true,death:true,deploy:true},_toRelease:[],kind:'normal',_startDeploying:false, - log(){},_ev(){},_refreshRange(){},_cutAttackStand(){},releaseBlocked(){},_unblock(){},_pp(){return {deaths:0};},getPlayer(){return ps;}, - emit(name,e){trace.push([name,e.unit?.id??e.victim.id]);if(name==='kill'&&d.revive)e.victim.hp=15;},_safe(fn){fn();}}; - for(const name of ['_deploy','kill','retreat','_remove','redeploy','_checkRedeploys'])btl[name]=BattleDeploy.prototype[name]; - for(const name of ['isDown','restTile','downOn','isReservedTile','_layBody','relocate'])btl[name]=BattleTiles.prototype[name]; - btl._deploy(a);btl._deploy(b); - if(d.foreign)btl.relocate(b,12,9); - btl.relocate(a,10,4);a.downAtHome=d.downHome; - if(d.homeTaken)btl.relocate(b,9,2); - btl.time=1; - if(d.retreat)btl.retreat(a,{reason:d.raid?'raid':'retreat',permanent:d.permanent});else btl.kill(a,null); - const before={alive:a.alive,deployed:a.deployed,removed:a.removed,hp:bits(a.hp),down:btl.isDown(a),body:a.body,rest:btl.restTile(a),respawn:bits(a.respawnAt)}; - btl.time=5;btl._checkRedeploys(); - const after={alive:a.alive,deployed:a.deployed,removed:a.removed,hp:bits(a.hp),down:btl.isDown(a),body:a.body,rest:btl.restTile(a),respawn:bits(a.respawnAt),seq:a.deploySeq,tile:[a.tileR,a.tileC],dp:bits(ps.dp)}; - process.stdout.write(JSON.stringify({scenario:d,before,after,trace})+'\n'); -} diff --git a/tools/reference/displacement.mjs b/tools/reference/displacement.mjs deleted file mode 100644 index 986ec04..0000000 --- a/tools/reference/displacement.mjs +++ /dev/null @@ -1,37 +0,0 @@ -// Headless force/weight/collision oracle. No fx or display state is recorded. -import fs from'node:fs';import path from'node:path';import{pathToFileURL}from'node:url'; -const root=path.resolve(process.argv[2]);const{Battle}=await import(pathToFileURL(path.join(root,'server/sim/Battle.js'))); -const{Unit}=await import(pathToFileURL(path.join(root,'server/sim/units.js'))); -const{pushTiles,pushUnbalance,pullUnbalance}=await import(pathToFileURL(path.join(root,'server/sim/battle/displacement.js'))); -const stages=JSON.parse(fs.readFileSync(path.join(root,'data/stages.json'),'utf8')); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<320;i++){ - const stageId=Object.keys(stages)[i%13],position=i%3?[10.05,5.1]:[10,8]; - const cfg={stageId,position,mass:(i%11)*.5,static:i%7===0,boss:i%13===0,ally:i%17===0,dead:i%19===0,fly:i%5===0,noDisplace:i%23===0,hold:i%5===0?2:null,dir:['RIGHT','UP','LEFT','DOWN'][i%4]}; - const b=new Battle({stage:{...stages[stageId],devices:[]},content:'none',recordEvents:false}); - let ended=0;b._stealthSwitch=()=>{ended++;};b.fx=()=>{}; - const e=new Unit({id:1,side:cfg.ally?'ally':'enemy',kind:'enemy',x:position[1],y:position[0],motion:cfg.fly?'FLY':'WALK',def:{staticBody:cfg.static},base:{maxHp:1000,massLevel:cfg.mass}}); - e.alive=!cfg.dead;e.deployed=true;e.isBoss=cfg.boss;e.unbalanceUntil=cfg.hold??-Infinity;e.atkStandUntil=3; - e.route={pts:[[10,5]],legs:[],legIdx:0};if(cfg.noDisplace)e.buffs=[{key:'immune',flags:{noDisplace:true}}]; - const a=new Unit({id:2,side:'ally',kind:'op',x:5,y:10,dir:cfg.dir,base:{blockCnt:3,maxHp:1000}});a.deployed=true;a.ground=true; - b.units=[e,a];b.allyUnits=[a];b.enemies=[e];b._occ[10*21+5]=a;b._checkBlock(e); - const ops=[],states=[]; - for(let j=0;j<20;j++){ - b.time=j*.07;e.atkStandUntil=b.time+.4; - const force=((i+j)%15-5)*.5,dir={x:[1,-1,0,.7][j%4],y:[0,.7,-1,1][(i+j)%4]}; - const from=j%5===0?{x:e.x,y:e.y,fwd:a.fwd}:a; - const op={op:j%7,force,dir,from:{position:[from.y,from.x],forward:from.fwd??null},fixed:i%3===0,fixedAngle:i%4===0,inward:i%6===0,effect:i%2===0,to:[9+(i%4),2+(j%9)],stop:[-.1,0,.6708,2][j%4],distance:((i+j)%11-2)*.43}; - let moved; - switch(op.op){ - case 0:moved=b.push(e,force,{from,inward:op.inward,effect:op.effect});break; - case 1:moved=b.push(e,force,{from,dir,fixed:op.fixed,fixedAngle:op.fixedAngle,effect:op.effect});break; - case 2:moved=b.pull(e,force,{to:{x:op.to[1],y:op.to[0]},center:a,stop:op.stop});break; - case 3:moved=b.pullToFront(e,a,force);break; - case 4:moved=b.displace(e,dir,op.distance);break; - case 5:moved=b.pushDistance(e,force,{effect:op.effect});break; - case 6:b._unbalance(e,op.distance);moved=0;break; - } - ops.push(op);states.push({moved:bits(moved),position:[bits(e.y),bits(e.x)],until:bits(e.unbalanceUntil),stand:bits(e.atkStandUntil),blocked:e.blockedBy?.id??null,blocking:a.blocking.map(e=>e.id),cached:!!e.route.pts,ended,level:bits(b.forceLevel(e,force)),tables:[pushTiles(force,op.effect),pushUnbalance(force),pullUnbalance(force)].map(bits)}); - } - console.log(JSON.stringify({cfg,ops,states})); -} diff --git a/tools/reference/element.mjs b/tools/reference/element.mjs deleted file mode 100644 index ce629b9..0000000 --- a/tools/reference/element.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Actual element.js + status/buff timers + HP/injury pipeline, including nested burst hooks. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const E=await imp('server/sim/attack/element.js');const{BattleStatus}=await imp('server/sim/battle/status.js');const{Unit}=await imp('server/sim/units.js');const{SkillRuntime}=await imp('server/sim/skills.js');const{resolveDamage}=await imp('server/sim/attack/hit.js');const{makeDamageInfo,damageAttackType}=await imp('server/sim/attack/helpers.js');const{createRng}=await imp('server/sim/rng.js'); -const names=['burn','neural','necrosis','apoptosis','erosion'];const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<320;i++){ - const cfg={i,element:names[i%5],side:i%2?'enemy':'ally',entity:i%4!==0,leader:i%7===0,ep:[0,10,105,-5,20][i%5],hooks:i%2===0,skill:['duration','instant','passive'][i%3],active:i%13===0,noSkill:i%11===0,sleep:i%17===0,invul:i%31===0}; - const u=new Unit({id:1,side:cfg.side,kind:cfg.entity?'enemy':'op',base:{maxHp:i%17===0?300:30000,atk:100,def:100,res:30}});u.deployed=true;u.def={epResistance:cfg.ep,rank:cfg.leader?'BOSS':'NORMAL'};const src=new Unit({id:2,side:cfg.side==='ally'?'enemy':'ally',kind:'op',base:{atk:999}});src.deployed=true; - const trace=[];const b={units:[u,src],time:0,rng:createRng(42),kind:'normal',rect:{r0:0,r1:18,c0:0,c1:20},_attackSeq:0,_hooks:{elementHit:cfg.hooks,modifierApplied:true,damaged:true,elementApplied:true,elementBurst:true},_safe:f=>f(),after:()=>0,_pp:()=>null,_skills:{onDamaged(){}},_ev(e){if(e[0]==='status'||e[0]==='dmg'&&!this.hpDepth&&names.includes(e[3]))trace.push(e);},_unblock(){},releaseBlocked(){},fx(name){if(name==='burst')trace.push(['burstVisual']);},kill(t){t.hp=0;t.alive=false;t.deployed=false;trace.push(['kill',t.id]);},emit(name,c){ - if(name==='elementHit'){trace.push([name,bits(c.dmg.amount),bits(c.dmg.mul)]);if(i%19===0)c.dmg.cancel=true;if(i%23===0)c.dmg.amount*=1.5;if(i%29===0)c.dmg.type='arts';} - if(name==='modifierApplied'&&c.kind==='elementDamage')trace.push([name,bits(c.amount),bits(c.gaugeAdded)]); - if(name==='damaged'&&c.type==='element')trace.push([name,bits(c.amount)]); - if(name==='elementApplied')trace.push([name,bits(c.amount)]); - if(name==='elementBurst'){trace.push([name,c.element,E.burstLocked(u)]);const got=E.applyElement(b,{source:src,credit:src,target:u,dmg:makeDamageInfo({amount:1000,type:'element',element:c.element})});trace.push(['nested',bits(got)]);if(i%41===0){u.alive=false;u.hp=0;u.deployed=false;}} - return c; - },dealDamage(...args){let c;if(args.length===1){const d=args[0];c={source:d.source??null,credit:d.credit??d.source??null,target:d.target,dmg:makeDamageInfo(d)};}else{c={source:args[0],credit:args[3]?.credit??args[0],target:args[1],dmg:makeDamageInfo(args[2])};} - trace.push(['hpHit',c.source?.id??null,c.credit?.id??null,bits(c.dmg.amount),c.dmg.type,!!c.dmg.noSp,damageAttackType(c.dmg),c.dmg.tags,c.dmg.element??null]);this.hpDepth=(this.hpDepth??0)+1;try{return resolveDamage(this,c);}finally{this.hpDepth--;}}}; - for(const key of['addBuff','removeBuff','_removeBuffAt','_tickBuffs','_applyValuedStatus','applyStatus','resistOf','_setAttractPoint'])b[key]=BattleStatus.prototype[key]; - b.addBuff(src,{key:'source',mods:{dmgDealtMul:2}});b.addBuff(u,{key:'baseline',mods:{elemTakenMul:i%3===0?1.3:1,dodgePhys:i%5===0?.3:0,dodgeArts:i%7===0?.3:0},flags:{sleep:cfg.sleep,invulnerable:cfg.invul}}); - const sk=new SkillRuntime(b,u,{spCost:3,spType:'attack',skillType:'MANUAL'},{kind:cfg.skill,spCost:3,charges:3,initSp:8});u.skill=sk;sk.reset();sk.active=cfg.active;sk.noSkill=cfg.noSkill; - u.elem.burn=120;u.elem.neural=120;const ops=[{op:'hit',element:cfg.element,amount:u.gaugeMax+100}]; - for(let j=0;j<44;j++)ops.push(j%11===0?{op:'hit',element:names[(i+j)%5],amount:700}:j%7===0?{op:'heal',element:j%2?null:names[(i+j)%5],amount:250}:j===38?{op:'remove',key:`${cfg.element}Burst`}:{op:'tick',dt:[.1,.5,1][(i+j)%3]}); - const states=[];for(const op of ops){let result=null;if(op.op==='hit')result=E.applyElement(b,{source:src,credit:src,target:u,dmg:makeDamageInfo({amount:op.amount,mul:1.1,type:'element',element:op.element,ignoreSleep:i%3===0})});else if(op.op==='heal')result=E.healElement(u,op.amount,op.element);else if(op.op==='remove')result=b.removeBuff(u,op.key);else{b.time+=op.dt;b._tickBuffs(op.dt);}const s=u.s;const view=E.elementView(u,b.time);states.push({result:result==null?null:bits(result),hp:bits(u.hp),alive:u.alive,gauges:names.map(n=>bits(u.elem[n])),locked:E.burstLocked(u),view:view?[view[0],...view.slice(1).map(bits)]:null,atk:bits(s.atk),def:bits(s.def),res:bits(s.res),sp:bits(sk.spTotal),elemStat:bits(src.stats.elem??0),dmgStat:bits(src.stats.dmg),rng:b.rng.state(),buffs:u.buffs.map(x=>({key:x.key,stacks:x.stacks,left:bits(x.timeLeft),duration:bits(x.duration),acc:bits(x._acc)}))});} - process.stdout.write(JSON.stringify({cfg,ops,states,trace})+'\n'); -} diff --git a/tools/reference/enemy-content.mjs b/tools/reference/enemy-content.mjs deleted file mode 100644 index 5fc011d..0000000 --- a/tools/reference/enemy-content.mjs +++ /dev/null @@ -1,36 +0,0 @@ -// Original enemy handlers, HP settlement and block timers; no renderer or match. -import fs from 'node:fs';import path from 'node:path';import {pathToFileURL} from 'node:url'; -const root=path.resolve(process.argv[2]),imp=p=>import(pathToFileURL(path.join(root,p))); -const {Battle}=await imp('server/sim/Battle.js'),{Unit}=await imp('server/sim/units.js'); -const content=await imp('server/sim/content/enemies.js'); -const {kitStealth,kitRefraction}=await imp('server/sim/content/enemies/archetypes.js'); -const {enemyStealthed,canTargetEnemy}=await imp('server/sim/targeting.js'); -const data=JSON.parse(fs.readFileSync(path.join(root,'data/enemies.json'),'utf8')); -const selected=Object.keys(data).filter(k=>content.STATS_ONLY[k]||content.KITS[k]===kitStealth||content.KITS[k]===kitRefraction||k==='enemy_9011_acrefr'||/^enemy_(1196_msfyin|1198_msfshu|1200_msfjin|1202_msfzhi|1204_msfhu|1208_msfji|1210_msfden)(_2)?$/.test(k)); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(const key of selected)for(let variant=0;variant<2;variant++){ - const overrides=variant?{talents:{bb:{'refracting.magic_resistance':17.5,'Refracting.magic_resistance':23.5,'Refracting.max_hp':.5}}}:{}; - const mods=variant?{hpMul:1.3,supplyHpMul:1.5}:{hpMul:1},tag=variant?'duck':null; - const b=new Battle({seed:42,content:'none',recordEvents:false,rect:{r0:0,r1:18,c0:0,c1:20},stage:{rows:Array(19).fill('r'.repeat(21)),legend:{}},data:{enemies:data},enemyOverrides:{[key]:overrides}}); - content.install(b); - const e=b.spawnEnemy(key,{pos:[10,5.2],mods,tag}); - const a=new Unit({id:10000,side:'ally',kind:'op',x:5,y:10,base:{maxHp:1000,atk:120,blockCnt:3}});a.deployed=true;a.ground=true; - b.units.push(a);b.allyUnits.push(a);b._occ[215]=a; - const view=()=>{const s=e.s;return {hp:bits(e.hp),alive:e.alive,stealth:enemyStealthed(e),selectable:canTargetEnemy(a,e,{canHitFly:true}),blocked:e.blockedBy?.id??null,stats:Object.fromEntries(['maxHp','res','atk'].map(k=>[k,bits(s[k])])),flags:Object.keys(s.flags).filter(k=>s.flags[k]).sort(),buffs:e.buffs.map(x=>({key:x.key,left:bits(x.timeLeft),persist:!!x.persist,visible:!!x.visible,stacks:x.stacks,flags:Object.keys(x.flags??{}).filter(k=>x.flags[k]).sort(),mods:Object.fromEntries(Object.entries(x.mods??{}).map(([k,n])=>[k,bits(n)])),restore:x.flags?.stealth?bits(x.data?.stealthRestore??3):null})),rng:b.rng.state()};}; - const states=[view()],ops=[]; - for(let j=0;j<86;j++){ - b.time=j*.1;let op={time:b.time}; - if(j===3){op.half=true;e.hp*=.7;} - if([4,31,61].includes(j)){op.status='silence';b.applyStatus(e,'silence',{duration:.4});} - if([10,52].includes(j)){op.status='reveal';b.applyStatus(e,'reveal',{duration:.4});} - if([14,28,48].includes(j)){op.block=true;b._checkBlock(e);} - if([18,29,50].includes(j)){op.unblock=true;b._unblock(e);} - if(j===25){op.extra=true;b.addBuff(e,{key:'otherStealth',duration:1.5,flags:{stealth:true},data:{stealthRestore:.3}});} - if(j%13===11){op.hit=['phys','arts','true','elemental'][(j+variant)%4];b.dealDamage(a,e,{amount:5.7,type:op.hit,isAttack:true,noSp:true});} - if(j===70){op.loss=true;b.loseHp(e,.3);} - e.mem.carrier=j>=34&&j<37?a:null;op.carrier=!!e.mem.carrier; - b._tickBuffs(.1);b.emit('tick',{dt:.1}); - ops.push(op);states.push(view()); - } - console.log(JSON.stringify({key,raw:data[key],overrides,mods,tag,ops,states})); -} diff --git a/tools/reference/enemy-element.mjs b/tools/reference/enemy-element.mjs deleted file mode 100644 index 8f9a36d..0000000 --- a/tools/reference/enemy-element.mjs +++ /dev/null @@ -1,28 +0,0 @@ -// Original on-hit elemental kits + real nested HP/gauge/burst settlement. -import fs from'node:fs';import path from'node:path';import{pathToFileURL}from'node:url'; -const root=path.resolve(process.argv[2]),imp=p=>import(pathToFileURL(path.join(root,p))); -const{Battle}=await imp('server/sim/Battle.js'),{Unit}=await imp('server/sim/units.js'),{install}=await imp('server/sim/content/enemies.js'); -const enemies=JSON.parse(fs.readFileSync(path.join(root,'data/enemies.json'),'utf8')); -const keys=['enemy_1148_dssbr','enemy_1148_dssbr_2','enemy_1305_mhslim','enemy_1305_mhslim_2','enemy_2021_syfish','enemy_1229_darmy','enemy_1229_darmy_2']; -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(const key of keys)for(let variant=0;variant<6;variant++){ - const overrides=variant%2?{talents:{bb:{'epdamage.attack@ep_damage_ratio':.8,'EpDamage.attack@ep_damage_ratio':.6}}}:{}; - const b=new Battle({seed:42,content:'none',recordEvents:false,data:{enemies},enemyOverrides:{[key]:overrides}});install(b); - const e=b.spawnEnemy(key,{pos:[10,5]}),a=new Unit({id:2,side:'ally',kind:'op',base:{maxHp:100000,atk:0,def:70,res:20}});a.deployed=true;a.x=5;a.y=10;b.units.push(a);b.allyUnits.push(a); - const trace=[]; - // Zero is upstream's sentinel for 'no attack identity'; native uses None. - b.on('damaged',c=>trace.push([c.source?.id??null,c.target.id,!!c.dmg?.isAttack,c.dmg?.attackId||null,c.dmg?.type??'true',bits(c.amount),a.alive,bits(a.hp)]),{priority:100}); - const states=[],ops=[]; - for(let j=0;j<180;j++){ - b.time=j*.1;const op={time:b.time,attack:j%5!==0,amount:j%11===0?0:17.5,kind:['phys','arts','true','elemental'][j%4],attackId:j+1,multi:1+j%3,sourceDead:j>=160,deathTarget:variant===5&&j===140}; - if(j===30){op.atk=700.3;e.base.atk=op.atk;e.markDirty();} - if(j===50){op.silence=true;b.applyStatus(e,'silence',{duration:1});} - if(j===85){op.guard=true;b.addBuff(a,{key:'guard',duration:.8,flags:{invulnerable:true}});} - if(variant===2&&j===65){op.dodge=true;b.addBuff(a,{key:'dodge',duration:3,mods:{dodgePhys:.3,dodgeArts:.4}});} - if(op.deathTarget)a.hp=1;if(op.sourceDead){e.alive=false;e.deployed=false;} - for(let k=0;kbits(a.elem[k])),flags:Object.keys(a.s.flags).filter(k=>a.s.flags[k]).sort(),res:bits(a.s.res),def:bits(a.s.def),rng:b.rng.state(),sourceDamage:bits(e.stats.dmg),taken:bits(a.stats.taken),buffs:a.buffs.map(b=>({key:b.key,left:bits(b.timeLeft)}))});ops.push(op); - } - console.log(JSON.stringify({key,raw:enemies[key],overrides,ops,states,trace})); -} diff --git a/tools/reference/enemy.mjs b/tools/reference/enemy.mjs deleted file mode 100644 index 2cc031c..0000000 --- a/tools/reference/enemy.mjs +++ /dev/null @@ -1,44 +0,0 @@ -// Actual updateEnemy + blocking + buff/HP/projectile systems, no match assets. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{BattleDisplacement}=await imp('server/sim/battle/displacement.js');const{BattleHooks}=await imp('server/sim/battle/hooks.js');const ai=await imp('server/sim/ai.js');const{Unit}=await imp('server/sim/units.js');const{Grid}=await imp('server/sim/grid.js');const{BattleStatus}=await imp('server/sim/battle/status.js');const{BattleBlocking}=await imp('server/sim/battle/blocking.js');const{BattleQueries}=await imp('server/sim/battle/queries.js');const{ProjectileSystem}=await imp('server/sim/projectiles.js');const{resolveDamage}=await imp('server/sim/attack/hit.js');const{makeDamageInfo}=await imp('server/sim/attack/helpers.js');const{heal}=await imp('server/sim/attack/heal.js');const{createRng}=await imp('server/sim/rng.js'); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<144;i++){ - const cfg={i,mode:['phys','arts','true','heal','none'][i%5],melee:i%3===0,moves:i%7===0,deferred:i%11===0,blockFree:i%13===0,clip:i%4===0?null:{dur:[.4,.8,1.2][i%3],hit:i%7===0?null:.3},maxTargets:1+i%3,bat:[.4,.8,1][i%3],skip:i%17===0,keep:i%5===0,cancel:i%23===0,interrupt:i%29===0}; - const e=new Unit({id:1,side:'enemy',kind:'enemy',x:8,y:10,base:{maxHp:100000,atk:40,def:10,bat:cfg.bat,rangeRadius:3,moveSpeed:1}});e.deployed=true;e.def={dmgType:cfg.mode,applyWay:cfg.melee?'MELEE':'RANGED',attackMoves:cfg.moves,attackAnim:cfg.clip};e.profile={blockFree:cfg.blockFree,maxTargets:cfg.maxTargets,deferHit:cfg.deferred,shot:'shell',atkScale:1.2,canTarget:a=>!cfg.skip||a.id!==3};e.spawnY=10;e.spawnX=8;e.route={legs:ai.compileRoute({checkpoints:[{type:'WAIT',time:.1}],end:[10,4]}),legIdx:0,pts:null,ptIdx:0,waitLeft:null}; - const allies=[[10,6],[10,7],[11,7]].map((p,j)=>{const a=new Unit({id:j+2,side:'ally',kind:'op',x:p[1],y:p[0],base:{maxHp:i%19===0&&j===0?80:100000,blockCnt:2}});a.deployed=true;a.ground=true;a.deploySeq=j+1;a.aggroSeq=j+1;return a;}); - const partner=new Unit({id:5,side:'enemy',kind:'enemy',x:8,y:10,base:{maxHp:30000}});partner.hp=500;partner.deployed=true; - const grid=new Grid({rows:Array(19).fill('r'.repeat(21)),legend:{}},{r0:0,r1:18,c0:0,c1:20});const trace=[];const b={units:[e,...allies,partner],allyUnits:allies,enemies:[e,partner],grid,time:0,rng:createRng(i+1),kind:'normal',rect:grid.rect,_attackSeq:0,_occ:Array(399).fill(null),_hooks:{enemyAttackStart:true,palsyTrigger:true,beforeAttack:true,attack:true},_safe:f=>f(),_pp:()=>null,_skills:{onDamaged(){}},_ev(ev){if(ev[0]==='atk')trace.push(ev);},fx(name){if(name==='palsy')trace.push(['palsy']);},_cutAttackStand(){},_setHidden(u,on){u.hidden=on;},leak(u){u.alive=false;u.deployed=false;trace.push(['leak']);},kill(u){u.hp=0;u.alive=false;u.deployed=false;trace.push(['kill',u.id]);},emit(name,c){ - if(name==='enemyAttackStart'){trace.push(['start',c.targets.map(u=>u.id)]);if(cfg.interrupt)b.addBuff(e,{key:'interrupt',duration:.2,flags:{stun:true}});} - if(name==='palsyTrigger'){trace.push(['palsyTrigger',c.buff.stacks]);c.keep=cfg.keep;} - if(name==='beforeAttack'){trace.push(['before',c.targets.map(u=>u.id)]);if(cfg.cancel)c.targets=[];} - if(name==='attack'){trace.push(['attack',c.targets.map(u=>u.id),[...c.targetDeployments].map(([u,s])=>[u.id,s])]);if(i%13===0){e.base.atk+=1;e.markDirty();}} - return c;},dealDamage(source,target,req){trace.push(['hit',source.id,target.id,bits(req.amount),req.type,req.attackId,!!req.isProjectile]);return resolveDamage(this,{source,credit:source,target,dmg:makeDamageInfo(req)});},heal(source,target,amount){return heal(this,source,target,amount);}}; - for(const a of allies)b._occ[a.tileR*21+a.tileC]=a; - for(const key of['addBuff','removeBuff','_removeBuffAt','_tickBuffs','_applyValuedStatus','applyStatus','resistOf','_setAttractPoint'])b[key]=BattleStatus.prototype[key]; - for(const key of['_checkBlock','_blockerFor','_unblock','releaseBlocked'])b[key]=BattleBlocking.prototype[key];b._stealthSwitch=()=>{}; - for(const key of ['forceLevel','push','pull','pullToFront','pushDistance','_displaceable','_staticForce','_unbalance','displace'])b[key]=BattleDisplacement.prototype[key]; - b.alliesInRadius=BattleQueries.prototype.alliesInRadius;b.enemiesInRadius=BattleQueries.prototype.enemiesInRadius;b.projectiles=new ProjectileSystem(b);b.addProjectile=p=>b.projectiles.add(p); - const dispatch=b.emit;b._hooks=Object.create(null);b._emitDepth=0;b._frameName=[];b._frameOwner=[];b._frameCtx=[];b._handlerError=(label,owner,error)=>{throw error;};b.on=BattleHooks.prototype.on;b.off=BattleHooks.prototype.off;b.emit=BattleHooks.prototype.emit;for(const name of ['enemyAttackStart','palsyTrigger','beforeAttack','attack'])b.on(name,c=>dispatch.call(b,name,c),{owner:e}); - b.applyStatus(e,'palsy',{value:i%3+1,duration:2});const states=[]; - for(let tick=0;tick<180;tick++){ - b.time=tick/30; - if(tick===3){allies[0].x=15;allies[0].y=15;} - if(tick===30){allies[0].x=6;allies[0].y=10;} - if(tick===20)b.applyStatus(e,'stun',{duration:.2}); - if(tick===45)b.applyStatus(allies[1],'sleep',{duration:.2}); - if(tick===65)b.applyStatus(e,'disarm',{duration:.25}); - if(tick===90)b.applyStatus(e,'fear',{duration:.25,source:allies[0]}); - if(tick===110)b.applyStatus(e,'attract',{duration:.25,point:[10,8]}); - if(tick===85)b.push(e,1,{from:allies[0]}); - if(tick===115)b.pullToFront(e,allies[1],2); - if(tick===145)b.push(e,3,{from:allies[0],dir:{x:1,y:0},fixed:true}); - if(tick===100)e.unbalanceUntil=b.time+.3; - if(tick===104)b.applyStatus(e,'levitate',{duration:.1}); - if(tick===80){e.profile.atkScale=1.5;e.base.atk+=3;e.markDirty();} - if(tick===130&&i%9===0){e.alive=false;e.deployed=false;} - e.mem.carrier=tick>=70&&tick<75?partner:null;e.hidden=tick>=50&&tick<55;e.pauseUntil=tick>=60&&tick<64?3:-Infinity; - b._tickBuffs(1/30);ai.updateEnemy(b,e,1/30);b.projectiles.update(1/30); - states.push({hp:b.units.map(u=>bits(u.hp)),alive:b.units.map(u=>u.alive),pos:[bits(e.y),bits(e.x)],moving:e.moving,cd:bits(e.atkCd),swing:!!e.swing,targets:e.swingTargets?.map(u=>u.id)??null,stand:bits(e.atkStandUntil??-Infinity),unbalance:bits(e.unbalanceUntil??-Infinity),blocked:e.blockedBy?.id??null,attacks:e.stats.attacks,last:bits(e.lastAttackAt),flights:b.projectiles.list.length,rng:b.rng.state(),palsy:e.findBuff('palsy')?.stacks??0}); - } - process.stdout.write(JSON.stringify({cfg,states,trace})+'\n'); -} diff --git a/tools/reference/events.mjs b/tools/reference/events.mjs deleted file mode 100644 index bee9db2..0000000 --- a/tools/reference/events.mjs +++ /dev/null @@ -1,42 +0,0 @@ -// Real battle/hooks.js bus and timers, including reentrant once and owner removal. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const{BattleHooks}=await import(pathToFileURL(path.join(root,'server/sim/battle/hooks.js'))); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');};const num=x=>x==='inf'?Infinity:x==='nan'?NaN:x; -for(let i=0;i<256;i++){ - const trace=[],handles=[],timers=[];let nesting=false;const b={_hooks:Object.create(null),_sched:[],time:0,_emitDepth:0,_runDepth:0,_frameCtx:[],_frameName:[],_frameOwner:[],_handlerError(label,owner,e){throw e;}}; - for(const key of['on','off','offOwner','hasHook','emit','after','every','_runScheduled','_compactDue','_safe','_chain'])b[key]=BattleHooks.prototype[key]; - const hb=b.on('unused',()=>{}).seq;b.off('unused');const tb=b.after(0,()=>{}).seq;b._sched=[]; - const hookFns=new Map(),timerFns=new Map(); - const hook=token=>{if(!hookFns.has(token))hookFns.set(token,c=>{ - trace.push(['hook',token,c.value,c.depth]); - if(token===1)c.value++; - if(token===2&&handles.length)b.off(handles[handles.length-1]); - if(token===3&&!c.added){c.added=true;handles.push(b.on('B',hook(1),{owner:2}));} - if(token===4&&c.depth<2){const nested={value:c.value,depth:c.depth+1};b.emit('B',nested);c.value=nested.value;} - if(token===5)b.offOwner(1); - if(token===6)c.stopPropagation=true; - if(token===7&&c.depth<1){const nested={value:c.value,depth:c.depth+1};b.emit('A',nested);c.value=nested.value;} - if(token===8&&handles.length)b.off(handles[0]); - if(token===9&&timers.length)timers[timers.length-1].cancel(); - });return hookFns.get(token);}; - const timer=token=>{if(!timerFns.has(token))timerFns.set(token,(b,s)=>{ - trace.push(['timer',token,s.seq-tb,s.count,bits(s.due),s.cancelled]); - if(token===2&&!nesting){timers.push(b.after(0,timer(1),{owner:2}));nesting=true;try{b._runScheduled();}finally{nesting=false;}} - if(token===3)s.cancel();if(token===4)b.offOwner(1);if(token===5)b.emit('A',{value:7,depth:0}); - if(token===6){s.due-=.05;s.interval=.1;}if(token===7)s.interval=0; - });return timerFns.get(token);}; - const ops=[];for(let j=0;j<48;j++){ - const n=(i+j)%8; - if(n<3)ops.push({op:'on',key:j%2?'A':'B',token:1+(i+j)%9,priority:[0,2,-1,'inf'][j%4],owner:j%3===0?null:j%3,once:j%5===0}); - else if(n===3)ops.push({op:'emit',key:j%2?'A':'B',value:j,depth:0}); - else if(n===4)ops.push({op:'timer',every:j%2===0,seconds:[0,.03,.1,'inf','nan'][(i+j)%5],token:1+j%7,owner:j%3===0?null:j%3,immediate:j%3===0,holds:j%2===0}); - else if(n===5)ops.push({op:'run',dt:[0,.1,.5,2][j%4]}); - else if(n===6)ops.push({op:'off',key:j%2?'A':'B',token:j%3===0?null:1+(i+j)%9});else ops.push({op:'owner',owner:j%3===0?null:j%3}); - } - // Ensure every seed exercises interval catch-up and an immediate one-shot. - ops.unshift({op:'timer',every:true,seconds:.03,token:1+i%7,owner:1,immediate:true,holds:false}); - ops.push({op:'run',dt:2},{op:'emit',key:'A',value:1,depth:0},{op:'run',dt:.1}); - const states=[];for(const op of ops){let value=null;if(op.op==='on')handles.push(b.on(op.key,hook(op.token),{priority:num(op.priority),owner:op.owner,once:op.once}));else if(op.op==='emit'){const c={value:op.value,depth:op.depth};b.emit(op.key,c);value=[c.value,!!c.stopPropagation];}else if(op.op==='timer'){const opts={owner:op.owner,immediate:op.immediate,holdsBattle:op.holds};timers.push(op.every?b.every(num(op.seconds),timer(op.token),opts):b.after(num(op.seconds),timer(op.token),opts));}else if(op.op==='run'){b.time+=op.dt;b._runScheduled();}else if(op.op==='off')b.off(op.key,op.token==null?undefined:hook(op.token));else b.offOwner(op.owner); - states.push({value,hooks:['A','B'].map(k=>(b._hooks[k]??[]).map(h=>h.seq-hb)),timers:b._sched.filter(s=>!s.cancelled).map(s=>({id:s.seq-tb,due:bits(s.due),interval:bits(s.interval),count:s.count??null,holds:s.holdsBattle})),holds:b._sched.some(s=>!s.cancelled&&s.holdsBattle)}); - } - process.stdout.write(JSON.stringify({i,ops,states,trace})+'\n'); -} diff --git a/tools/reference/field-allies.mjs b/tools/reference/field-allies.mjs deleted file mode 100644 index d063d6d..0000000 --- a/tools/reference/field-allies.mjs +++ /dev/null @@ -1,50 +0,0 @@ -// Concrete native solo field oracle with original default operators and all -// admitted enemy kits. Includes full Battle phases and long skill/redeploy fights. -import fs from'node:fs';import path from'node:path';import{pathToFileURL}from'node:url'; -const root=path.resolve(process.argv[2]),imp=p=>import(pathToFileURL(path.join(root,p))); -const{Battle}=await imp('server/sim/Battle.js'),content=await imp('server/sim/content/enemies.js'); -const{kitStealth,kitRefraction}=await imp('server/sim/content/enemies/archetypes.js'); -const data=Object.fromEntries(['config','chess','bonds','garrisons','items','bands','effects','choices','enemies','factions','waves','stages','bosses','tokens','backups'].map(k=>[k,JSON.parse(fs.readFileSync(path.join(root,'data',k+'.json'),'utf8'))])); -const keys=Object.keys(data.enemies).filter(k=>content.STATS_ONLY[k]||content.KITS[k]===kitStealth||content.KITS[k]===kitRefraction||k==='enemy_9011_acrefr'||/^enemy_(1196_msfyin|1198_msfshu|1200_msfjin|1202_msfzhi|1204_msfhu|1208_msfji|1210_msfden|1148_dssbr|1305_mhslim|2021_syfish|1229_darmy)(_2)?$/.test(k)); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -const encode=x=>typeof x==='number'?(Number.isFinite(x)?bits(x):null):Array.isArray(x)?x.map(encode):x&&typeof x==='object'?Object.fromEntries(Object.entries(x).map(([k,v])=>[k,encode(v)])):x; -const stage={rows:Array(19).fill('r'.repeat(21)),legend:{}}; -const cases=[...keys.map((key,i)=>({key,seed:i+21,long:false})),...['enemy_1007_slime',keys.find(k=>k.includes('lurker')),'enemy_1148_dssbr','enemy_1305_mhslim','enemy_2021_syfish','enemy_1229_darmy'].map((key,i)=>({key,seed:i+600,long:true}))]; -const ranged=['1_03','1_11','1_14','1_07'].flatMap(k=>['a','b'].map(v=>'chess_char_'+k+'_'+v)); -for(const operator of ranged)for(const dir of ['RIGHT','UP','LEFT','DOWN'])cases.push({key:'enemy_1007_slime',operator,dir,seed:1000+cases.length,long:true}); -for(const c of cases){ - if(!data.enemies[c.key])throw Error('Missing oracle enemy '+c.key); - let routes=[{start:[10,10],end:[10,0]},{start:[11,10],end:[11,0]}]; - let spawns=[{enemyKey:c.key,time:0,count:2,interval:.2,mods:{hpMul:c.long?100:1.5,atkMul:c.long?.7:3}}, - {enemyKey:'enemy_1007_slime',time:.3,routeIndex:1,mods:{hpMul:c.long?100:1.5,atkMul:1.5}}]; - let units=[{chessId:'chess_char_1_02_a',uid:1,row:10,col:6},{chessId:'chess_char_1_02_b',uid:2,row:11,col:6}]; - if(c.operator){ - const home=c.dir==='DOWN'?[11,5]:[10,5],vec={RIGHT:[0,1],UP:[1,0],LEFT:[0,-1],DOWN:[-1,0]}[c.dir]; - const distance=c.operator.includes('1_07')&&['UP','LEFT'].includes(c.dir)?1:2; - const target=[home[0]+distance*vec[0],home[1]+distance*vec[1]]; - units=[{chessId:c.operator,uid:1,row:home[0],col:home[1],dir:c.dir}]; - routes=[{start:target,end:[10,0],checkpoints:[{type:'WAIT',time:150}]}]; - spawns=[{enemyKey:c.key,time:c.dir==='UP'?70:0,count:4,interval:.2,mods:{hpMul:500,atkMul:.1}}]; - } - const options={stage,routes,spawns,seed:c.seed,timeLimit:c.operator?110:c.long?150:12,players:[{playerId:'p',units}]}; - const b=new Battle({...options,data,content:'full',recordEvents:false}); - const report=()=>{const r=b.result(),p=r.perPlayer.p,pp={};for(const k of['killed','total','leaked','perfect','killedInTotal','leakedInTotal','resolved','creditedKills','coins'])pp[k]=p[k];return {...Object.fromEntries(['time','reason','killed','total','resolved','errors'].map(k=>[k,r[k]])),perPlayer:{p:pp},...(r.unspawned?{unspawned:r.unspawned}:{})};}; - const view=()=>({time:b.time,ticks:b.tickCount,finished:b.finished,reason:b.reason,rng:b.rng.state(),dp:b.players[0].dp,projectiles:b.projectiles.list.length, - enemies:b.enemies.filter(e=>e.alive).map(e=>{const s=e.s;return{id:e.id,key:e.defId,pos:[e.y,e.x],hp:e.hp,maxHp:s.maxHp,atk:s.atk,res:s.res,cd:e.atkCd,moving:e.moving,hidden:e.hidden,leg:e.route.legIdx,spawn:e.spawnSeq,deploy:e.deploySeq,element:['burn','neural','necrosis','apoptosis','erosion'].map(k=>e.elem[k]),flags:Object.keys(s.flags).filter(k=>s.flags[k]).sort(),buffs:e.buffs.map(x=>({key:x.key,left:x.timeLeft,stacks:x.stacks,persist:!!x.persist}))};}), - allies:b.allyUnits.map(u=>{const s=u.s,k=u.skill;return{id:u.id,key:u.defId,hp:u.hp,maxHp:s.maxHp,atk:s.atk,def:s.def,res:s.res,cd:u.atkCd, - alive:u.alive,deployed:u.deployed,removed:u.removed,blocking:u.blocking.map(e=>e.id),deploy:u.deploySeq,aggro:u.aggroSeq,body:u.body??null, - death:u.deathAt,respawn:u.respawnAt,reason:u.removeReason??null,ground:u.ground,element:['burn','neural','necrosis','apoptosis','erosion'].map(k=>u.elem[k]), - flags:Object.keys(s.flags).filter(k=>s.flags[k]).sort(),buffs:u.buffs.map(b=>({key:b.key,left:b.timeLeft,stacks:b.stacks,persist:!!b.persist})), - sp:k.sp,charges:k.charges,left:k.timeLeft,active:k.active,activations:k.activations,attacks:u.stats.attacks,dealt:u.stats.dmg,taken:u.stats.taken};}),report:report()}); - const states=[],ops=[];let killedShooter=false; - for(let t=0;t<(c.operator?3300:c.long?4500:360)&&!b.finished;t++){ - if((c.long&&!c.operator&&t===1800)||(c.operator&&c.dir==='LEFT'&&t===1201)){b.retreat(b.allyUnits[0]);ops.push({tick:t,op:'retreat',id:b.allyUnits[0].id});} - if(c.operator&&c.dir==='DOWN'&&!killedShooter&&b.allyUnits[0].skill.active&&b.projectiles.list.some(p=>p.source===b.allyUnits[0])){ - b.dealDamage(null,b.allyUnits[0],{amount:1e9,type:'true',noSp:true});ops.push({tick:t,op:'damage',id:b.allyUnits[0].id,amount:1e9});killedShooter=true; - } - b.step();states.push(encode(view())); - } - if(b.errorCount)throw Error(c.key+': '+b.errorCount+' oracle errors'); - if(c.operator&&c.dir==='DOWN'&&!killedShooter)throw Error('Missing in-flight source death '+c.operator); - console.log(JSON.stringify({options,ops,states})); -} diff --git a/tools/reference/field.mjs b/tools/reference/field.mjs deleted file mode 100644 index 9a1279e..0000000 --- a/tools/reference/field.mjs +++ /dev/null @@ -1,26 +0,0 @@ -// Concrete native field oracle: full upstream content, empty allied roster. -import fs from'node:fs';import path from'node:path';import{pathToFileURL}from'node:url'; -const root=path.resolve(process.argv[2]),imp=p=>import(pathToFileURL(path.join(root,p))); -const{Battle}=await imp('server/sim/Battle.js'),content=await imp('server/sim/content/enemies.js'); -const{kitStealth,kitRefraction}=await imp('server/sim/content/enemies/archetypes.js'); -const data=Object.fromEntries(['config','chess','bonds','garrisons','items','bands','effects','choices','enemies','factions','waves','stages','bosses','tokens','backups'].map(k=>[k,JSON.parse(fs.readFileSync(path.join(root,'data',k+'.json'),'utf8'))])); -const keys=Object.keys(data.enemies).filter(k=>content.STATS_ONLY[k]||content.KITS[k]===kitStealth||content.KITS[k]===kitRefraction||k==='enemy_9011_acrefr'||/^enemy_(1196_msfyin|1198_msfshu|1200_msfjin|1202_msfzhi|1204_msfhu|1208_msfji|1210_msfden|1148_dssbr|1305_mhslim|2021_syfish|1229_darmy)(_2)?$/.test(k)); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -const stage={rows:Array(19).fill('r'.repeat(21)),legend:{}}; -for(let i=0;i{const r=b.result(),p=r.perPlayer.p,pp={};for(const k of['killed','total','leaked','perfect','killedInTotal','leakedInTotal','resolved','creditedKills','coins'])pp[k]=p[k];return structuredClone({...Object.fromEntries(['time','reason','killed','total','resolved','errors'].map(k=>[k,r[k]])),perPlayer:{p:pp},...(r.unspawned?{unspawned:r.unspawned}:{})});}; - const view=()=>({time:bits(b.time),ticks:b.tickCount,finished:b.finished,reason:b.reason,pending:b._pending.length,sequence:b._spawnSeq,rng:b.rng.state(),units:b.enemies.filter(e=>e.alive).map(e=>{const s=e.s;return{id:e.id,key:e.defId,pos:[bits(e.y),bits(e.x)],hp:bits(e.hp),maxHp:bits(s.maxHp),atk:bits(s.atk),res:bits(s.res),cd:bits(e.atkCd),moving:e.moving,hidden:e.hidden,leg:e.route.legIdx,spawn:e.spawnSeq,deploy:e.deploySeq,element:['burn','neural','necrosis','apoptosis','erosion'].map(k=>bits(e.elem[k])),flags:Object.keys(s.flags).filter(k=>s.flags[k]).sort()};}),report:report()}); - const states=[],ops=[]; - for(let t=0;t<400&&!b.finished;t++){ - if(t===15){const target=b.enemies.find(e=>e.alive);if(target){const spec={amount:target.hp*.3,type:'true'};b.dealDamage(null,target,spec);ops.push({tick:t,op:'damage',id:target.id,spec});}} - if(t===30){const target=b.enemies.find(e=>e.alive);if(target){const spec={amount:target.hp+100,type:'true'};b.dealDamage(null,target,spec);ops.push({tick:t,op:'damage',id:target.id,spec});}} - if(t===35){const options={pos:[10,8],route:routes[0],bounty:{coins:3},mods:{speedMul:1.2},inTotal:i%3===0};b.spawnEnemy(key,options);ops.push({tick:t,op:'spawn',key,options});} - if(t===40){const source=b.enemies.find(e=>e.alive&&e.defId===key),target=b.enemies.find(e=>e.alive&&e!==source);if(source&&target){for(let j=0;j<30;j++)b.dealDamage(source,target,{amount:0,type:'true',isAttack:true,attackId:700});ops.push({tick:t,op:'hitChain',source:source.id,id:target.id});}} - b.step();states.push(view()); - } - console.log(JSON.stringify({options,ops,states})); -} diff --git a/tools/reference/grid.mjs b/tools/reference/grid.mjs deleted file mode 100644 index d5e69f7..0000000 --- a/tools/reference/grid.mjs +++ /dev/null @@ -1,43 +0,0 @@ -// Development-only geometry oracle. Reads external stage data; no match or training. -import fs from 'node:fs'; -import path from 'node:path'; -import {pathToFileURL} from 'node:url'; -const root=path.resolve(process.argv[2]); -const {Grid,bresenhamTiles,segmentTiles,straightClear}=await import(pathToFileURL(path.join(root,'server/sim/grid.js'))); -const dir=await import(pathToFileURL(path.join(root,'server/sim/dir.js'))); -const {BattlePlayers}=await import(pathToFileURL(path.join(root,'server/sim/battle/players.js'))); -const out=x=>process.stdout.write(JSON.stringify(x)+'\n'); -for(const d of dir.DIRS) for(let r=-3;r<=3;r++) for(let c=-3;c<=3;c++) - out({kind:'direction',d,r,c,rotated:dir.rotateOffset(r,c,d),local:dir.toLocal(r,c,d),mirror:dir.mirrorDir(d),opposite:dir.oppositeDir(d),delta:dir.dirFromDelta(r,c,d)}); -for (const kind of ['normal','boss','hidden']) for(const side of ['L','R']) for(const field of [false,true]) for(const abs of [false,true]) for(const offset of [null,-2]) { - const context={kind,_boardTile:BattlePlayers.prototype._boardTile}; - const ps={mirror:kind!=='normal'&&side==='R',coords:field?'field':'board',rowOffset:offset,colOffset:side==='R'?8:0}; - for(const p of [[9,2],[12,10],[2,18],[0,0]]) - out({kind:'placement',battle:kind,side,field,abs,offset,p,tile:BattlePlayers.prototype.mapTile.call(context,ps,...p,abs),dir:BattlePlayers.prototype.mapDir.call(context,ps,'RIGHT',abs)}); -} -for(let r=0;r<19;r+=3) for(let c=0;c<21;c+=3) { - const a=[r,c],b=[18-r,20-c];out({kind:'line',a,b,bresenham:bresenhamTiles(a,b),segment:segmentTiles(a,b)}); -} -const stages=JSON.parse(fs.readFileSync(path.join(root,'data/stages.json'),'utf8')); -const rects=[{r0:0,r1:18,c0:0,c1:20},{r0:9,r1:12,c0:2,c1:10},{r0:0,r1:5,c0:0,c1:20}]; -for(const [id,raw] of Object.entries(stages)) { - const stage={...raw,legend:raw.tiles??raw.legend}; - for(const rect of rects) for(const obstacles of [false,true]) { - const g=new Grid(stage,rect); - if(obstacles){g.setObstacle(9,8,true,'crate');g.setObstacle(10,8,true);g.setObstacle(9,8,true);g.setObstacle(9,8,false);} - const queries=[]; - for(let r=0;r<19;r++)for(let c=0;c<21;c++)queries.push([g.groundPassable(r,c),g.walkable(r,c),g.flyPassable(r,c),g.canStand(r,c),g.canStand(r,c,{ranged:true})]); - const tiles=g.tiles.map(t=>[t.glyph,t.key,t.height,t.build,t.pass,t.terrain??null,t.special??null]); - out({kind:'grid',id,rect,obstacles,tiles,queries,version:g.version}); - for (const end of [[9,2],[2,18],[12,10]]) for (const start of [[9,10],[12,10],[2,2]]) for(const delta of [[0,0],[.25,-.25],[.5,.5],[-.5,-.5]]) { - const x=start[1]+delta[1],y=start[0]+delta[0]; - out({kind:'straight',x,y,end,value:straightClear(g,x,y,{x:end[1],y:end[0]})}); - } - for(const end of [[9,2],[2,2],[2,18],[-1,0]])for(const diagonal of [true,false])for(const ignore of [false,true]) { - const f=g.flowField(...end,{allowDiagonal:diagonal,ignoreObstacles:ignore}); - const fields=Object.fromEntries(['dist','parent','pen','next','official','cost','deep'].map(k=>[k,Array.from(f[k])])); - const paths=[[9,10],[12,10],[2,18],[2,2]].map(start=>({start,waypoints:g.waypoints(...start,...end,{allowDiagonal:diagonal,ignoreObstacles:ignore}),length:Number.isFinite(g.fieldLength(f,start[0]*21+start[1]))?g.fieldLength(f,start[0]*21+start[1]):null})); - out({kind:'flow',id,rect,obstacles,end,diagonal,ignore,paths,...fields}); - } - } -} diff --git a/tools/reference/health.mjs b/tools/reference/health.mjs deleted file mode 100644 index 063dd79..0000000 --- a/tools/reference/health.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// HP and healing oracle; no match, assets or training. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const{applyHpDecrease,loseHp}=await imp('server/sim/attack/health.js');const{heal}=await imp('server/sim/attack/heal.js'); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<768;i++){ - const scenario={i,type:['phys','arts','true','elemental'][i%4],heal:i%3===0,loss:i%3===1,pool:i%11===0,boss:i%7===0,amount:i%17===0?300000:i%29===0?299999.1:(i*37)%230,self:i%13===0,targetAlly:i%2===0,fatal:i%4,mode:['heal','regen','restore'][Math.floor(i/3)%3],noHeal:i%5===0,healFree:i%7===0,noSp:i%9===0,through:i%11===0,hitCount:i%13===0,hitCountArts:i%17===0}; - const d=scenario;const source=new Unit({id:1,side:'ally',base:{maxHp:100,atk:100}});source.ownerId=10;source.deployed=true; - const target=new Unit({id:2,side:d.targetAlly?'ally':'enemy',base:{maxHp:100,def:25,res:30}});target.hp=37;target.deployed=true;target.isBoss=d.boss;target.skill={}; - target.buffs=[{stacks:1,mods:{healingTakenMul:1.3},flags:{noHeal:d.noHeal,healFree:d.healFree,hitCount:d.hitCount,hitCountArts:d.hitCountArts},shield:0}];source.buffs=[{stacks:1,mods:{healingDealtMul:1.2},shield:0}]; - source.profile={healThrough:()=>d.through};const pool={hp:63,maxHp:100,damage(pid,a){this.hp=Math.max(0,this.hp-a);}};if(d.pool)target.bossPool=pool; - const credit=d.self?target:source;const trace=[];const pp={damageDealt:0,bossDamage:0,healingDone:0};let shield=0; - const stages=['fatal','hpChanged','modifierApplied','damageApplied','damaged','heal']; - const battle={_safe(fn){fn();},time:5,kind:'boss',_hooks:Object.fromEntries(stages.map(k=>[k,true])),_pp:()=>pp, - emit(stage,e){trace.push([stage,bits(e.amount)]);if(stage==='fatal'){if(d.fatal===1)e.prevented=true;if(d.fatal===2)target.hp=5;if(d.fatal===3)target.alive=false;}if(stage==='heal')e.amount*=.5;}, - _syncBossHp(t){t.hp=t.s.maxHp*Math.min(1,t.bossPool.hp/t.bossPool.maxHp);},_internalError(label,e){throw e;},fx(k,e){trace.push([k,bits(e.n)]);},_ev(){}, - _skills:{onDamaged(){trace.push(['skill']);}},kill(t,c){trace.push(['kill']);t.alive=false;t.deployed=false;}, - addBuff(t,b){shield=Math.min(100,shield+b.shield);},};target.findBuff=()=>shield?{shield}:null; - const dmg={type:d.type,noSp:d.noSp,silent:false,defIgnoreFlat:0,defIgnorePct:0,resIgnoreFlat:0,resIgnorePct:0}; - let result;if(d.heal)result=heal(battle,d.self?target:source,target,d.amount,{mode:d.mode,overheal:true});else{const ctx={source,credit,target,dmg,onApplied(){trace.push(['applied']);}};result=d.loss?loseHp(battle,ctx,d.amount):applyHpDecrease(battle,ctx,d.amount);} - process.stdout.write(JSON.stringify({scenario:d,result:bits(result),hp:bits(target.hp),alive:target.alive,deployed:target.deployed,taken:bits(target.stats.taken),damage:bits(credit.stats.dmg),healing:bits((d.self?target:source).stats.heal),last:bits(target.lastHitAt),pool:bits(pool.hp),pp:Object.fromEntries(Object.entries(pp).map(([k,v])=>[k,bits(v)])),shield:bits(shield),trace})+'\n'); -} diff --git a/tools/reference/hit.mjs b/tools/reference/hit.mjs deleted file mode 100644 index 3e5c8e2..0000000 --- a/tools/reference/hit.mjs +++ /dev/null @@ -1,19 +0,0 @@ -// HP-damage pipeline oracle; no match or data loading. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const{resolveDamage}=await imp('server/sim/attack/hit.js');const{createRng}=await imp('server/sim/rng.js');const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<1024;i++){ - const d={i,type:['phys','arts','true','elemental'][i%4],action:Math.floor(i/4)%8,calculation:['formula','precomputed','resolved'][Math.floor(i/32)%3],source:i%13!==0,enemy:i%7===0,sleep:i%17===0,hitSleep:i%11===0,liftoff:i%19===0,hidden:i%37===0,fly:i%23===0,ignoreSelect:i%29===0,boss:i%41===0,amount:i%43===0?300000:i%211+50,shield:i%9===0?300:20,dodge:i%5===0?.8:0,mode:['ignore','normal','uncancellable'][Math.floor(i/96)%3]}; - const source=new Unit({id:1,side:d.enemy?'enemy':'ally',base:{maxHp:1000}});source.deployed=true;source.motion=d.fly?'FLY':'WALK';source.profile={hitSleep:d.hitSleep}; - const target=new Unit({id:2,side:'ally',base:{maxHp:1000,def:60,res:30}});target.deployed=true;target.hidden=d.hidden;target.isBoss=d.boss; - const baseBuff={stacks:1,mods:{artsAttackAddition:7},flags:{sleep:d.sleep,liftoff:d.liftoff},shield:0};const shieldBuff={stacks:1,mods:{dmgTakenMul:1.2,dodgePhys:d.dodge,dodgeArts:d.dodge},flags:null,shield:d.shield,shieldHits:0,seq:1,key:'shield'};target.buffs=[baseBuff,shieldBuff]; - const trace=[];const rng=createRng(i+1);const phases=['hit','damageCalculate','damageCalculateTarget','damageOutput','damageBeforeApply','damageApplying','hpDamage'];const health=['fatal','hpChanged','modifierApplied','damageApplied','damaged']; - const battle={time:3,kind:'boss',rng,_hooks:Object.fromEntries([...phases,...health,'block','dodge'].map(k=>[k,true])),_pp(){return null;},_safe(fn){fn();},_internalError(k,e){throw e;},_ev(){},_removeBuffAt(t,j){t.buffs.splice(j,1);},fx(k,e){if(k==='hitCap')trace.push(['hitCap',bits(e.n)]);}, - emit(stage,e){if(phases.includes(stage)){trace.push([stage,bits(e.amount??e.dmg.amount)]); - if(stage==='hit'){if(d.action===1)e.dmg.cancel=true;if(d.action===3){baseBuff.flags.invulnerable=true;target.markDirty();}if(d.action===4){baseBuff.flags.liftoff=true;target.markDirty();}} - if(stage==='damageCalculateTarget'){if(d.action===2)target.alive=false;if(d.action===5){target.base.def=120;target.markDirty();}} - if(stage==='damageOutput'&&d.action===6){e.amount*=.5;e.dmg.dodgeMode='ignore';}if(stage==='hpDamage'&&d.action===7)e.amount=3; - }else if(stage==='block'||stage==='dodge')trace.push([stage,e.cancelled]);else trace.push([stage,bits(e.amount)]);},kill(t){trace.push(['kill']);t.alive=false;t.deployed=false;}}; - const dmg={amount:d.amount,type:d.type,mul:1,defIgnoreFlat:0,defIgnorePct:0,resIgnoreFlat:0,resIgnorePct:0,calculation:d.calculation,ignoreSelect:d.ignoreSelect,dodgeMode:d.mode,silent:true,noSp:true}; - const result=resolveDamage(battle,{source:d.source?source:null,credit:d.source?source:null,target,dmg}); - process.stdout.write(JSON.stringify({scenario:d,result:bits(result),hp:bits(target.hp),alive:target.alive,deployed:target.deployed,shield:bits(shieldBuff.shield),taken:bits(target.stats.taken),damage:bits(source.stats.dmg),rng:rng.state(),trace})+'\n'); -} diff --git a/tools/reference/injury.mjs b/tools/reference/injury.mjs deleted file mode 100644 index b6d1732..0000000 --- a/tools/reference/injury.mjs +++ /dev/null @@ -1,26 +0,0 @@ -// Ordered injury oracle: no matches, assets or model loading. -import path from'node:path';import{pathToFileURL}from'node:url'; -const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{injuryEffects,settleEffects}=await imp('server/sim/attack/effects.js');const{createRng}=await imp('server/sim/rng.js'); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');};const random=createRng(843); -for(let i=0;i<1024;i++){ - const type=['phys','arts','true','elemental'][i%4],mode=['ignore','normal','uncancellable'][Math.floor(i/4)%3],ignoreBlock=!!(i%2); - const descriptors=Array.from({length:1+i%8},(_,j)=>({id:j+1,key:'group'+j%2,priority:j%3,stacks:1+j%3, - mods:j%3===0?null:{dmgTakenMul:.5+random(),physTakenMul:.5+random(),artsTakenMul:.5+random(),elementalTakenMul:.5+random(),dodgePhys:random(),dodgeArts:random()}, - shield:random()<.5?random()*80:0,hits:random()<.2?1:0,shieldTypes:j%3===0?null:['phys','arts'],keep:!!(j%2), - reduction:j%4===0?random()*20:null,action:j%5,observer:!!(j%2),scale:random()*2,probability:random(),remove:((j+1)%(1+i%8))+1})); - const trace=[];const rng=createRng(i+1);const target={buffs:[],markDirty(){trace.push(['dirty']);}}; - const remove=id=>{target.buffs=target.buffs.filter(b=>b.id!==id);}; - const buffs=descriptors.map(d=>({id:d.id,key:d.key,injuryPriority:d.priority,seq:d.id,stacks:d.stacks,mods:d.mods,shield:d.shield,shieldHits:d.hits,shieldType:d.shieldTypes,keepEmptyShield:d.keep, - damageReduction:d.reduction==null?null:{[type]:d.reduction}, - injury:d.action===0?null:e=>{trace.push(['injury',d.id,bits(e.amount)]);if(d.action===1)e.amount*=d.scale;if(d.action===2)e.block(d.probability);if(d.action===3)e.dodge(d.probability);if(d.action===4)remove(d.remove);e.defer(()=>trace.push(['cleanup',d.id]));}, - observeInjury:d.observer?e=>trace.push(['observe',d.id,bits(e.amount),e.cancelled,e.outcome]):null})); - target.buffs=buffs.slice(); - const battle={rng,_safe(fn){fn();},_internalError(label,e){throw e;},_removeBuffAt(t,index){t.buffs.splice(index,1);trace.push(['remove',buffs.find(b=>!t.buffs.includes(b)&&!b._removed)?.id??0]);for(const b of buffs)if(!t.buffs.includes(b))b._removed=true;}}; - const amount=i%29===0?0:random()*200; - const result=injuryEffects(battle,target,amount,type,{dodgeMode:mode,context:{dmg:{ignoreCancelReasons:ignoreBlock?['block']:[]}},onBlock:c=>trace.push(['block',c]),onDodge:(c,a)=>trace.push(['dodge',c,bits(a)])}); - // Dirty is a cache invalidation detail, tracked separately from observable callbacks. - const dirty=trace.some(x=>x[0]==='dirty');const settled=settleEffects(battle,result,a=>{trace.push(['apply',bits(a)]);return a;}); - const state=buffs.map(b=>({id:b.id,active:target.buffs.includes(b),shield:bits(b.shield),hits:b.shieldHits})); - process.stdout.write(JSON.stringify({i,type,mode,ignoreBlock,descriptors,amount,result:{amount:bits(result.amount),cancelled:result.cancelled,outcome:result.outcome,notifyZero:result.notifyZero},settled:bits(settled),state,dirty,rng:rng.state(),trace:trace.filter(x=>!['dirty','remove'].includes(x[0]))})+'\n'); -} diff --git a/tools/reference/motion.mjs b/tools/reference/motion.mjs deleted file mode 100644 index f6611e3..0000000 --- a/tools/reference/motion.mjs +++ /dev/null @@ -1,30 +0,0 @@ -// Drive upstream movement functions directly. Export private functions in memory; -// the external checkout is never modified and this adapter is development-only. -import fs from'node:fs';import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const source=fs.readFileSync(path.join(root,'server/sim/ai.js'),'utf8').replace(/from\s+(['"])(\.\.?\/[^'"]+)\1/g,(_,q,p)=>`from ${q}${pathToFileURL(path.resolve(root,'server/sim',p))}${q}`)+'\nexport {advanceRoute,moveAttracted};'; -const ai=await import('data:text/javascript;base64,'+Buffer.from(source).toString('base64')); -const fear=await imp('server/sim/fear.js');const{Grid}=await imp('server/sim/grid.js');const{BattleStatus}=await imp('server/sim/battle/status.js');const{Unit}=await imp('server/sim/units.js');const{createRng}=await imp('server/sim/rng.js'); -const stages=JSON.parse(fs.readFileSync(path.join(root,'data/stages.json'),'utf8'));const stageIds=Object.keys(stages);const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<112;i++){ - const raw=stages[stageIds[i%stageIds.length]];let stage={...raw,legend:raw.tiles??raw.legend};if(i>=104){const rows=Array.from({length:19},()=>Array(21).fill('r'));rows[10][6]='I';rows[10][9]='O';rows[10][12]='E';stage={rows:rows.map(r=>r.join('')),legend:{}};}const rect={r0:0,r1:18,c0:0,c1:20},g=new Grid(stage,rect); - const tiles=g.tiles.map((t,k)=>[t,k]).filter(([t,k])=>t.pass==='ALL'&&g.walkable((k/21)|0,k%21,true)).map(([,k])=>[(k/21)|0,k%21]);if(tiles.length<3)throw Error('fixture map lacks walkable tiles'); - const pick=j=>tiles[(i*7+j*13)%tiles.length];const start=i>=104?[10,5]:pick(0),dest=i>=104?[10,6]:pick(1),middle=i>=104?[10,5]:pick(2);const fly=i%3===0;const pos=[start[0]+(i%2?.25:0),start[1]+(i%2?-.25:0)]; - const u=new Unit({id:1,side:'enemy',kind:'enemy',x:pos[1],y:pos[0],motion:fly?'FLY':'WALK',base:{moveSpeed:i>=104?30:2+i%4,atk:0}});u.deployed=true;u.spawnY=pos[0];u.spawnX=pos[1];const src=new Unit({id:2,side:'ally',x:pos[1]-2,y:pos[0]-1});src.deployed=true; - const route={checkpoints:[{type:'WAIT',time:.2},{type:'MOVE',pos:middle},{type:'DISAPPEAR'},{type:'WAIT',time:.3},{type:'APPEAR',pos:middle}],end:dest};u.route={legs:ai.compileRoute(route,rect),legIdx:0,pts:null,ptIdx:0,waitLeft:null}; - const trace=[];const b={grid:g,rect,units:[u,src],time:0,rng:createRng(i+1),_hooks:{},_safe:f=>f(),_ev(){},_cutAttackStand(){trace.push(['cut']);},_setHidden(e,on){e.hidden=on;trace.push(['hidden',on]);},_checkBlock(){return false;},leak(e){e.alive=false;e.deployed=false;trace.push(['leak']);},_unblock(){},releaseBlocked(){}}; - for(const key of['addBuff','removeBuff','_removeBuffAt','_tickBuffs','_applyValuedStatus','applyStatus','resistOf','_setAttractPoint'])b[key]=BattleStatus.prototype[key]; - const ticks=i>=104?360:160;const states=[];for(let tick=0;tick=50&&tick<55)u.moving=false;else ai.moveAttracted(b,u,1/30);}else ai.advanceRoute(b,u,1/30,u.route,tick>=50&&tick<55);}} - const m=u.mem.fearMove;const a=u.buffs.find(x=>x.status==='attract')?.data.attract; - states.push({pos:[bits(u.y),bits(u.x)],moving:u.moving,alive:u.alive,hidden:u.hidden,rng:b.rng.state(),leg:u.route.legIdx,wait:u.route.waitLeft==null?null:bits(u.route.waitLeft),distance:bits(ai.remainingDistance(b,u)),fear:m?{seq:m.seq,tiles:[...m.tiles],point:m.i,key:m.k??null,goal:m.goal?[bits(m.goal.y),bits(m.goal.x)]:null,points:m.pts?.map(p=>[bits(p.y),bits(p.x)])??null}:null,attract:a?{point:a.i,points:a.pts?.map(p=>[bits(p.y),bits(p.x)])??null}:null}); - } - process.stdout.write(JSON.stringify({i,stage:stageIds[i%stageIds.length],synthetic:i>=104?stage:null,ticks,pos,fly,route,middle,dest,states,trace})+'\n'); -} diff --git a/tools/reference/operators.mjs b/tools/reference/operators.mjs deleted file mode 100644 index 94ffeb9..0000000 --- a/tools/reference/operators.mjs +++ /dev/null @@ -1,44 +0,0 @@ -// Original default-operator lifecycle oracle. Full content installation; drive -// deployment, skill, buff and HP boundaries directly, without allied AI/rendering. -import fs from 'node:fs';import path from 'node:path';import{pathToFileURL}from'node:url'; -const root=path.resolve(process.argv[2]); -const{Battle}=await import(pathToFileURL(path.join(root,'server/sim/Battle.js'))); -const data=Object.fromEntries(['config','chess','bonds','garrisons','items','bands','effects','choices','enemies','factions','waves','stages','bosses','tokens','backups'].map(k=>[k,JSON.parse(fs.readFileSync(path.join(root,'data',k+'.json'),'utf8'))])); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(const key of ['chess_char_1_02_a','chess_char_1_02_b'])for(let mode=0;mode<2;mode++){ - const orderRule=mode?'rowBottomUp':'column'; - const inputData=mode?{...data,config:{...data.config,version:{...data.config.version,rules:{deployOrder:orderRule}}}}:data; - const b=new Battle({seed:42,content:'full',recordEvents:false,autoFinish:false,data:inputData, - stage:{rows:Array(19).fill('r'.repeat(21)),legend:{}}, - flags:{dpInit:99,dpMax:99,dpPerSec:0},players:[{playerId:'p',units:[{chessId:key,uid:1,row:10,col:5},{chessId:key,uid:2,row:12,col:5},{chessId:key,uid:3,row:9,col:4}]}]}); - b.start();const u=b.allyUnits[0]; - const view=()=>{const s=u.s,k=u.skill;return{hp:bits(u.hp),alive:u.alive,deployed:u.deployed,removed:u.removed, - stats:Object.fromEntries(['maxHp','atk','def','res','blockCnt','interval'].map(n=>[n,bits(s[n])])), - order:b.allyUnits.map(a=>[a.uid,a.deploySeq]),dp:bits(b.players[0].dp),deploy:u.deploySeq,aggro:u.aggroSeq,respawn:bits(u.respawnAt),death:bits(u.deathAt), - reason:u.removeReason??null,body:u.body??null,ground:u.ground,element:Object.values(u.elem).map(bits), - skill:{active:k.active,sp:bits(k.sp),charges:bits(k.charges),left:bits(k.timeLeft),activations:k.activations??null,readyAt:bits(k.opReadyAt)}, - buffs:u.buffs.map(x=>({key:x.key,mods:Object.fromEntries(Object.entries(x.mods??{}).map(([k,n])=>[k,bits(n)])),persist:!!x.persist}))};}; - const states=[view()],ops=[]; - for(let t=0;t<4500;t++){ - b.time=t/30; - const damage=(amount,type='true',noSp=false)=>{b.dealDamage(null,u,{amount,type,noSp});ops.push({tick:t,op:'damage',amount,type,noSp});}; - if(mode===0){ - if(t===1500)damage(123.5); - if(t===1510)damage(0,'arts'); - if(t===2500)damage(1000000); - }else{ - if(t===10){u.skill.gainSp(100,'talent');ops.push({tick:t,op:'gain',amount:100});} - if(t===20)damage(0); - if(t===90)damage(0,'true',true); - if(t===91)damage(0); - if(t===120){b.addBuff(u,{key:'discard-on-death',duration:100,mods:{defFlat:21}});ops.push({tick:t,op:'buff'});} - if(t===180){b.retreat(u);ops.push({tick:t,op:'retreat'});} - if(t===2100){u.skill.gainSp(100,'talent');ops.push({tick:t,op:'gain',amount:100});damage(1000000);} - } - b._tickBuffs(1/30); - if(u.alive&&u.deployed)u.skill.tick(1/30); - b._checkRedeploys();states.push(view()); - } - if(b.errorCount)throw Error('oracle errors '+b.errorCount); - console.log(JSON.stringify({key,raw:data.chess[key],orderRule,ops,states})); -} diff --git a/tools/reference/primitives.mjs b/tools/reference/primitives.mjs deleted file mode 100644 index 8b2ca97..0000000 --- a/tools/reference/primitives.mjs +++ /dev/null @@ -1,41 +0,0 @@ -// Emit independent upstream results; no game data or match execution needed. -import path from 'node:path'; -import {pathToFileURL} from 'node:url'; -const root = path.resolve(process.argv[2]); -const imp = p => import(pathToFileURL(path.join(root, p)).href); -const {createRng, deriveSeed} = await imp('server/sim/rng.js'); -const math = await imp('server/sim/detmath.js'); -const {VirtualScheduler} = await imp('server/match/scheduler.js'); -const bits = x => { const b = Buffer.alloc(8); b.writeDoubleBE(x); return b.toString('hex'); }; -const out = value => process.stdout.write(JSON.stringify(value) + '\n'); -for (const seed of [0, 1, 42, 0xffffffff, 0x80000000]) { - const rng = createRng(seed); - out({kind:'rng', seed, values:Array.from({length:1024}, () => rng()), state:rng.state()}); - for (const salt of ['setup','shop','waves','draft','bots','meta','盟约😀']) - out({kind:'derive', seed, salt, value:deriveSeed(seed,salt)}); -} -const random = createRng(123); -for (const seed of [1, 42, 0x928d860b]) { - const rng = createRng(seed); - const first = rng(); - const cloned = rng.clone(); - const values = [rng.int(0), rng.pick([]) ?? null, rng.weighted([0, -1], x => x) ?? null]; - const shuffled = rng.shuffle([0,1,2,3,4,5,6,7]); - const weights = [-1,0,1,2,3]; - const weighted = Array.from({length:32}, () => rng.weighted(weights, x => x)); - out({kind:'helpers', seed, first:bits(first), clone:bits(cloned()), values, shuffled, weighted, state:rng.state()}); -} -const inputs = [-0, 0, 1e-300, -1e-300, 0.5, -0.5, 1.5, -2.5, Math.PI/4, Math.PI/2, Math.PI, -Math.PI, 1e6, 1e100]; -for (let i=0;i<2048;i++) inputs.push((random()-.5)*1e6); -for (const x of inputs) { - out({kind:'math', x:bits(x), sin:bits(math.sin(x)), cos:bits(math.cos(x)), round:bits(math.roundHalfEven(x))}); - for (const y of [-0, 0, 1, -1, x/2]) - out({kind:'pair', x:bits(x), y:bits(y), hypot:bits(math.hypot(x,y)), atan2:bits(math.atan2(y,x))}); -} -for (const x of [-0,0,-2,-.1,.1,.9,1.01,2,100]) - for (const n of [-32,-3,-1,0,1,2,3,32,100]) - out({kind:'power', x:bits(x), n, value:bits(math.powi(x,n))}); -const s=new VirtualScheduler({start:0});const events=[]; -let handle=s.setInterval(()=>{events.push(['repeat',s.now()]);if(s.now()===4)s.clearInterval(handle);else s.setTimeout(()=>events.push(['callback',s.now()]),2);},2); -s.setTimeout(()=>events.push(['once',s.now()]),2);s.runAll({maxSteps:10}); -out({kind:'scheduler',events}); diff --git a/tools/reference/projectiles.mjs b/tools/reference/projectiles.mjs deleted file mode 100644 index 963964d..0000000 --- a/tools/reference/projectiles.mjs +++ /dev/null @@ -1,12 +0,0 @@ -// Real ProjectileSystem with explicit flight/impact callback fixtures. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const{ProjectileSystem}=await imp('server/sim/projectiles.js');const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<128;i++){ - const d={i,hitDead:i%2===0,speed:[0,2,12][i%3],maxAge:i%5===0?.2:10,die:i%7===0,hide:i%11===0,redeploy:i%13===0,cancel:i%17===0,spawnStep:i%3===0,spawnHit:i%5===0}; - const source=new Unit({id:1,side:'ally'}),target=new Unit({id:2,side:'enemy',x:2,y:1});target.deploySeq=1;target.deployed=true;const trace=[];let sys;let spawned=false; - const impact=c=>{trace.push(['impact',c.projectile.data,c.target?.id??null,bits(c.x),bits(c.y)]);if(d.spawnHit&&c.projectile.data<10)sys.add({from:{x:c.x,y:c.y},to:{x:0,y:0},speed:12,data:c.projectile.data+100,onHit:impact});}; - const b={_hooks:{projectileStep:true},emit(n,c){const p=c.projectile;trace.push(['step',p.data,bits(p.x),bits(p.y)]);if(d.spawnStep&&!spawned){spawned=true;sys.add({from:{x:p.x,y:p.y},to:{x:3,y:2},speed:12,data:10,onHit:impact});}if(d.cancel&&p.data===2)c.cancel=true;},_safe:fn=>fn()};sys=new ProjectileSystem(b); - for(let token=1;token<=2;token++)sys.add({from:source,target,speed:d.speed,hitDead:d.hitDead,maxAge:d.maxAge,data:token,onHit:impact}); - const states=[];for(let tick=0;tick<30;tick++){target.x=2+tick*.03;target.y=1+tick*.01;if(d.die&&tick===2)target.alive=false;if(d.hide&&tick===2)target.hidden=true;if(d.redeploy&&tick===3){target.alive=true;target.hidden=false;target.deploySeq++;}sys.update(.1);states.push(sys.list.map(p=>({token:p.data,x:bits(p.x),y:bits(p.y),tx:bits(p.tx),ty:bits(p.ty),age:bits(p.age),target:p.target?.id??null})));} - process.stdout.write(JSON.stringify({scenario:d,states,trace})+'\n'); -} diff --git a/tools/reference/radius.mjs b/tools/reference/radius.mjs deleted file mode 100644 index 532f008..0000000 --- a/tools/reference/radius.mjs +++ /dev/null @@ -1,15 +0,0 @@ -// Stronghold Protocol 0.3.3 actual radius selectors; no assets or match engine. -import path from 'node:path'; -import {pathToFileURL} from 'node:url'; -const root=path.resolve(process.argv[2]); -const {BattleQueries}=await import(pathToFileURL(path.join(root,'server/sim/battle/queries.js'))); -const {Unit}=await import(pathToFileURL(path.join(root,'server/sim/units.js'))); -const {normHitArea}=await import(pathToFileURL(path.join(root,'server/sim/body.js'))); -for(let i=0;i<256;i++){ - const records=Array.from({length:12},(_,j)=>({id:j+1,x:4+(j%4)*.6,y:10+Math.floor(j/4)*.49,huge:j%3===0,owner:j%2+1,device:j===2,alive:!(i%5===0&&j===3),deployed:!(i%7===0&&j===4),hidden:i%11===0&&j===5,stealth:(i+j)%7===0,untargetable:(i+j)%11===0,revealed:(i+j)%3===0})); - const units=side=>records.map(d=>{const u=new Unit({id:d.id,side,kind:d.device?'device':'enemy',x:d.x,y:d.y});u.alive=d.alive;u.deployed=d.deployed;u.hidden=d.hidden;u.ownerId=d.owner;u.hitArea=d.huge?normHitArea({w:4.95,h:2.95,dx:0,dy:1}):null;u.buffs=[{mods:{},flags:{stealth:d.stealth,reveal:d.revealed,untargetable:d.untargetable},stacks:1,shield:0}];return u;}); - const b={enemies:units('enemy'),allyUnits:units('ally'),enemiesInRadius:BattleQueries.prototype.enemiesInRadius,foesInRadius:BattleQueries.prototype.foesInRadius}; - const radius=[0,.1,.4999999999,1,2,-.1][i%6],owner=i%2?1:null,devices=i%3===0; - const ids=x=>x.map(u=>u.id); - process.stdout.write(JSON.stringify({i,records,radius,owner,devices,centre:ids(b.enemiesInRadius(4,10,radius,true)),body:ids(b.enemiesInRadius(4,10,radius)),foes:ids(b.foesInRadius(4,10,radius)),collider:ids(BattleQueries.prototype.foesInColliderRadius.call(b,4,10,radius)),allies:ids(BattleQueries.prototype.alliesInRadius.call(b,4,10,radius,owner,{includeDevices:devices}))})+'\n'); -} diff --git a/tools/reference/search.mjs b/tools/reference/search.mjs deleted file mode 100644 index 96cce24..0000000 --- a/tools/reference/search.mjs +++ /dev/null @@ -1,14 +0,0 @@ -// Real acquireTargets and noteAttackCommit with explicit range-query fixtures. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const ai=await imp('server/sim/ai.js');const{canTargetEnemy}=await imp('server/sim/targeting.js'); -for(let i=0;i<512;i++){ - const d={i,heal:i%5===0,multi:i%3===0,hpAtMost:i%2?.5:0,healCount:i%4,extraTargets:i%3,maxTargets:i%5,fortress:i%7===0,blocked:i%4===0,all:i%11===0,rangeAoe:i%13===0,hitAll:i%17===0,empty:i%3===0,hasExtra:i%2===0,nearExtra:i%19===0,cooldown:i%23===0?1:1/30,had:i%29===0?false:null}; - const units=Array.from({length:9},(_,j)=>{const id=j+1;const u=new Unit({id,side:id===1||id===9?'ally':'enemy',kind:'op',tileR:10,tileC:4,base:{maxHp:100,blockCnt:3}});u.deployed=true;u.hp=id*10;u.spawnSeq=10-id;u.rangeKeys=[1];return u;});const u=units[0];u.buffs=[{stacks:1,mods:{maxTargets:d.extraTargets},flags:{}}];u.atkCd=d.cooldown;u.trait.hadTarget=d.had;u.skill={active:true,attackOverride:()=>null,targetingOverride:()=>null};if(d.blocked){u.blocking=[units[1]];units[1].blockedBy=u;} - const p={heal:d.heal?{mode:d.multi?'multi':'single',count:d.healCount,hpAtMost:d.hpAtMost}:null,dmgType:d.heal?'heal':'phys',fortress:d.fortress,allInRange:d.all,rangeAoe:d.rangeAoe,hitAllBlocked:d.hitAll,maxTargets:d.maxTargets,priority:'lowestHp',canHitFly:true};u.profile=p; - const fixture={enemies:d.empty?[]:[4,3,5],near:d.empty?[6,7]:[],extra:d.hasExtra&&!d.empty?[9]:[],nearExtra:d.nearExtra?[9]:[],heal:[2,3,4,5,6,7,8,9]};const map=ids=>ids.map(id=>units[id-1]); - const b={allyUnits:[u],_allyTargets:d.hasExtra||d.nearExtra?new Set([9]):null,remainingDistance:e=>10-e.id,enemiesInKeys(keys){return map(keys[0]===1?fixture.enemies:fixture.near);},injuredAlliesInKeys:()=>map(fixture.heal),allyTargetsInKeys(keys){return map(keys[0]===1?fixture.extra:fixture.nearExtra);},blockedTargets(a,prof){return a.blocking.filter(e=>canTargetEnemy(a,e,prof));}}; - const state={};const selected=ai.acquireTargets(b,u,p,state).map(t=>t.id);ai.noteAttackCommit(b,1/30);const raw=b._attackCommit?.get(1)?.map(t=>t.id)??[]; - units[1].alive=false;units[2].buffs=[{stacks:1,mods:{},flags:{untargetable:true}}];units[2].markDirty(); - const fallback=raw.filter(id=>canTargetEnemy(u,units[id-1],p)); - process.stdout.write(JSON.stringify({scenario:d,fixture,selected,melee:state.fortressMelee??null,raw,fallback})+'\n'); -} diff --git a/tools/reference/settlement.mjs b/tools/reference/settlement.mjs deleted file mode 100644 index 2e85a9e..0000000 --- a/tools/reference/settlement.mjs +++ /dev/null @@ -1,26 +0,0 @@ -// Canonical buff/HP pipeline with nested damage and snapshot callbacks. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const{BattleStatus}=await imp('server/sim/battle/status.js');const{makeBuff}=await imp('server/sim/buffs.js');const{makeDamageInfo}=await imp('server/sim/attack/helpers.js');const{resolveDamage}=await imp('server/sim/attack/hit.js');const{createRng}=await imp('server/sim/rng.js'); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<256;i++){ - const base=makeBuff({}).seq,u=new Unit({id:1,side:'ally',kind:'op',base:{maxHp:10000,def:20,res:30}});u.deployed=true;const trace=[];let nesting=false; - const b={units:[u],time:0,kind:'normal',rng:createRng(i+1),_hooks:{block:true,dodge:true},_safe:f=>f(),_internalError(k,e){throw e;},_pp:()=>null,_skills:{onDamaged(){}},_ev(e){if(e[0]==='status')trace.push(e);},fx(){},kill(t){t.hp=0;t.alive=false;t.deployed=false;trace.push(['kill']);},emit(name,c){trace.push([name,c.cancelled]);},dealDamage(d){return resolveDamage(this,{source:null,credit:null,target:u,dmg:makeDamageInfo(d)});}}; - for(const key of['addBuff','removeBuff','_removeBuffAt','_tickBuffs'])b[key]=BattleStatus.prototype[key]; - function spec(d){return {...d,duration:d.duration==='inf'?Infinity:d.duration,injury:d.injury?e=>{ - trace.push(['injury',e.buff.seq-base,bits(e.amount)]); - if(d.injury===1)e.amount*=.7; - if(d.injury===2)e.block(.2); - if(d.injury===3){e.defer(()=>trace.push(['cleanup',7]));e.amount=Math.max(0,e.amount-3);} - if(d.injury===4&&!nesting){b.removeBuff(u,e.buff);nesting=true;try{b.dealDamage({amount:4,type:'true',noSp:true});}finally{nesting=false;}} - if(d.injury===5)b.removeBuff(u,'b'); - if(d.injury===6&&!u.findBuff('late'))b.addBuff(u,spec({key:'late',duration:.3,mods:{dmgTakenMul:.8},observe:true})); - }:null,observeInjury:d.observe?e=>{trace.push(['observe',e.buff.seq-base,bits(e.amount),e.cancelled,e.outcome,u.buffs.includes(e.buff)]);e.buff.shield+=2;u.markDirty();}:null,onRemove:d.remove?({buff})=>trace.push(['remove',buff.seq-base,bits(buff.timeLeft)]):null};} - const descriptors=[ - {key:'shield',duration:'inf',shield:25,shieldHits:i%3,shieldType:i%4===0?['phys','arts']:null,visible:true,mods:i%5===0?{}:null,flags:i%7===0?{}:null,onRemove:null,remove:true,keepEmptyShield:i%11===0}, - {key:'b',duration:1.1,stacks:2,mods:{dmgTakenMul:.8,dodgePhys:.25,dodgeArts:.25},damageReduction:{phys:5,arts:10,true:3,elemental:2},reductionGroup:'same',injuryPriority:i%2?2:0,observe:i%3===0}, - {key:'c',duration:1.5,mods:null,damageReduction:{phys:8,arts:7,true:4,elemental:6},reductionGroup:'same',injuryPriority:1,injury:1+i%6,observe:true,remove:true} - ];for(const d of descriptors)b.addBuff(u,spec(d)); - const ops=[];for(let j=0;j<18;j++){if(j%3===2)ops.push({tick:.2});else if(j%5===4)ops.push({add:{key:'shield',duration:.5,shield:35,visible:true,refresh:['replace','extend','stack'][i%3],maxStacks:3,remove:true}});else ops.push({hit:{amount:40+j*3,type:['phys','arts','true','elemental'][(i+j)%4],dodgeMode:['normal','ignore','uncancellable'][(i+j)%3],ignoreCancelReasons:i%13===0?['block']:[],noSp:true}});} - const states=[];for(const op of ops){let result=null;if(op.tick!=null){b.time+=op.tick;b._tickBuffs(op.tick);}else if(op.add)b.addBuff(u,spec(op.add));else result=b.dealDamage(op.hit);const s=u.s;states.push({result:result==null?null:bits(result),hp:bits(u.hp),taken:bits(u.stats.taken),rng:b.rng.state(),shield:bits(s.shield),buffs:u.buffs.map(x=>({id:x.seq-base,key:x.key,stacks:x.stacks,shield:bits(x.shield),hits:x.shieldHits,left:bits(x.timeLeft)}))});} - process.stdout.write(JSON.stringify({i,descriptors,ops,states,trace})+'\n'); -} diff --git a/tools/reference/skills.mjs b/tools/reference/skills.mjs deleted file mode 100644 index 1c43004..0000000 --- a/tools/reference/skills.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// Skill lifecycle oracle. Real runtime, explicit content/trigger fixtures; no matches/data. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const{SkillRuntime}=await imp('server/sim/skills.js');const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<384;i++){ - const d={i,kind:['instant','charges','duration','ammo','toggle','passive'][i%6],rule:['DEFAULT','SP_FULL','SEARCH','CUSTOM_RANGE','SKILL_RANGE','ACTIVE_RANGE','GDGLOW_SKILL_2','TAKE_DAMAGE','NEVER','AUTO_STOP'][Math.floor(i/6)%10],duration:i%3?.2:0,ammo:2,spType:['time','attack','hurt','none'][Math.floor(i/60)%4],attack:i%2===0,mod:i%3===0,targeting:i%4===0,allies:i%5===0,manual:i%7!==0,reactivate:i%17===0,freeAmmo:i%11===0,tickExtend:i%13===0,noSp:i%19===0,stun:i%23===0,silence:i%29===0,noAttack:i%31===0,condition:i%3!==0,deploy:i%37===0,noSkill:i%41===0}; - const u=new Unit({id:1,side:'ally',kind:'op',base:{maxHp:100,atk:10}});u.deployed=true;u.profile={noAttack:d.noAttack}; - const trace=[];let skill;let installed=false;let restarted=false; - const spec={kind:d.kind,duration:d.duration,ammo:d.ammo,spCost:3,initSp:6,charges:2,spType:d.spType,activateOnDeploy:d.deploy,trigger:{rule:d.rule,allies:d.allies},attack:d.attack?{}:null,mods:d.mod?{atkPct:.5}:null,targeting:d.targeting?{rangeGrid:[[0,0]]}:null, - onStart(c){trace.push(['start',c.reason]);},onEnd(c){trace.push(['end',c.reason,installed]);if(d.reactivate&&!restarted&&c.reason==='stopped'){restarted=true;skill.activate('restart',{free:true});}},onTick(c){trace.push(['tick',bits(c.dt)]);if(d.tickExtend)skill.extend(.1);},onAttack(c){trace.push(['attack']);if(d.freeAmmo)c.noAmmo=true;}}; - const b={time:0,_hooks:{skillStart:true,skillEnd:true,ammoUsed:true,spGain:true},_safe:fn=>fn(),_ev(e){trace.push(['display',e[2]]);},after(){trace.push(['after']);},addBuff(){installed=true;trace.push(['add']);},removeBuff(){installed=false;trace.push(['remove']);},_refreshRange(){trace.push(['range']);},emit(name,c){if(name==='spGain'){trace.push(['gain',c.reason,bits(c.amount)]);c.amount*=.75;}else{trace.push([name]);if(name==='skillStart'&&d.kind==='ammo')skill.addAmmo(1);}},rangeChanged:()=>false,anyEnemyInKeys:()=>d.condition}; - skill=new SkillRuntime(b,u,{skillType:d.manual?'MANUAL':'AUTO',spCost:3,maxCharges:2},d.noSkill?null:spec); - skill._defaultCondition=()=>d.condition;skill._allyTriggerSatisfied=()=>d.condition;skill._tickRuleSatisfied=()=>skill.rule==='SP_FULL'||d.condition; - const states=[];const snap=()=>states.push({sp:bits(skill.sp),charges:bits(skill.charges),active:skill.active,pending:skill.pending,time:bits(skill.timeLeft),ammo:bits(skill.ammoLeft),maxAmmo:bits(skill.ammoMax),activations:skill.activations,last:bits(skill.lastStart),op:bits(skill.opReadyAt),next:bits(skill.nextCastAt),attack:!!skill.attackOverride(),targeting:!!skill.targetingOverride(),total:bits(skill.spTotal)}); - skill.reset();u.buffs=[{stacks:1,mods:{},flags:{noSp:d.noSp,stun:d.stun,silence:d.silence},shield:0}];u.markDirty();snap(); - const actions=[()=>skill.activate('manual'),()=>{b.time=1/30;skill.tick(1/30);},()=>skill.onAttackPerformed([u],true,true),()=>skill.onAttackPerformed([u],true,false),()=>{skill.addAmmo(2);skill.extend(.2);},()=>{b.time=.5;skill.tick(.5);},()=>skill.end('stopped'),()=>skill.activate('free',{free:true}),()=>skill.onDamaged(),()=>skill.onAboutToAttack(),()=>{b.time=4;skill.tick(.1);},()=>{b.time=5;skill.tick(3);},()=>skill.end('death')]; - for(const action of actions){action();snap();} - process.stdout.write(JSON.stringify({scenario:d,states,trace})+'\n'); -} diff --git a/tools/reference/sp.mjs b/tools/reference/sp.mjs deleted file mode 100644 index 5555581..0000000 --- a/tools/reference/sp.mjs +++ /dev/null @@ -1,14 +0,0 @@ -// Real SkillRuntime SP methods; no skill content callbacks or matches. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const{SkillRuntime}=await imp('server/sim/skills.js');const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<768;i++){ - const d={i,kind:['instant','charges','duration','ammo','toggle','passive'][i%6],cost:i%11,charges:1+i%3,noSkill:i%37===0,noSp:i%7===0,active:i%5===0,hook:i%3===0,mutate:i%13===0,total:i%31+.25}; - const u=new Unit({id:1,side:'ally',kind:'op'});u.deployed=true;u.buffs=[{stacks:1,mods:{spCostFlat:i%3-1},flags:{noSp:d.noSp},shield:0}];let skill;const trace=[]; - const b={_hooks:d.hook?{spGain:true}:{},emit(name,e){trace.push([name,e.reason,bits(e.amount)]);e.amount*=.5;if(d.mutate){skill.spCostMul=.5;}}}; - skill=new SkillRuntime(b,u,{spCost:d.cost,maxCharges:d.charges},d.noSkill?null:{kind:d.kind,spCost:d.cost,charges:d.charges}); - skill.setSpTotal(d.total);skill.active=d.active; - const states=[];const snap=result=>{states.push({result:result==null?null:bits(result),sp:bits(skill.sp),charges:bits(skill.charges),cost:bits(skill.spCost),total:bits(skill.spTotal),ready:skill.ready,mul:bits(skill.spCostMul)});};snap(null); - snap(skill.gainSp(1/30,'time'));snap(skill.gainSp(5,'gift',false,{ignoreLock:true}));snap(skill.gainSp(3,'init',true)); - skill.spCostMul=.7;snap(null);skill.setSpTotal(7.5);snap(null);skill.addCharge(.5);snap(null);skill.spCostMul=NaN;snap(null);skill.gainSp(100,'hurt');snap(null); - process.stdout.write(JSON.stringify({scenario:d,flat:i%3-1,states,trace})+'\n'); -} diff --git a/tools/reference/spawns.mjs b/tools/reference/spawns.mjs deleted file mode 100644 index 96c0a3b..0000000 --- a/tools/reference/spawns.mjs +++ /dev/null @@ -1,28 +0,0 @@ -// No renderer: real headless Battle.step with content disabled to isolate the -// native wave/unit/tick boundary. Content abilities have separate parity tests. -import fs from'node:fs';import path from'node:path';import{pathToFileURL}from'node:url'; -const root=path.resolve(process.argv[2]);const{Battle}=await import(pathToFileURL(path.join(root,'server/sim/Battle.js'))); -const stages=JSON.parse(fs.readFileSync(path.join(root,'data/stages.json'),'utf8')); -const enemies=JSON.parse(fs.readFileSync(path.join(root,'data/enemies.json'),'utf8')); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -for(let i=0;i<40;i++){ - const stageId=Object.keys(stages)[i%13],keys=Object.keys(enemies); - const spawns=Array.from({length:i===0?0:7},(_,j)=>({enemyKey:keys[(i*7+j)%keys.length],time:j%2?j*0.07:0,count:j===0?2:1,interval:.1,routeIndex:j%2,mods:{hpMul:1.2,speedMul:i%3?1.4:0.3},countInTotal:j%4!==0,tag:j===4?'part':null})); - spawns.push({enemyKey:'enemy_1007_slime',time:20,count:2}); - if(i%5===0)spawns.length=0; - const routes=[{start:[9,10],end:[9,i%2?9:2],checkpoints:[]},{start:[12,10],end:[9,2],steps:[{t:'WAIT',s:.17},{t:'DISAPPEAR'},{t:'WAIT',s:.1},{t:'MOVE',p:[10,9]}]}]; - const options={stageId,seed:i+1,timeLimit:i%3?8:2.5,players:[{playerId:'p',units:[]}],spawns,routes,enemyOverrides:i%2?{}:{enemy_1007_slime:{stats:{moveSpeed:2.4}}}}; - // Isolate terrain/path physics. Stage devices create real allied combatants - // even with content:'none', and belong to their own upcoming content port. - const b=new Battle({...options,stage:{...stages[stageId],devices:[]},data:{enemies,stages},content:'none',recordEvents:false,logger:{warn(){},error(){}}}); - const report=()=>{const r=b.result(),p=r.perPlayer.p,pp={};for(const k of ['killed','total','leaked','perfect','killedInTotal','leakedInTotal','resolved','creditedKills','coins'])pp[k]=p[k];return structuredClone({...Object.fromEntries(['time','reason','killed','total','resolved','errors'].map(k=>[k,r[k]])),perPlayer:{p:pp},...(r.unspawned?{unspawned:r.unspawned}:{})});}; - const view=()=>({time:bits(b.time),ticks:b.tickCount,finished:b.finished,reason:b.reason,pending:b._pending.length,sequence:b._spawnSeq,units:b.enemies.filter(e=>e.alive).map(e=>({id:e.id,key:e.defId,pos:[bits(e.y),bits(e.x)],hp:bits(e.hp),cd:bits(e.atkCd),hidden:e.hidden,moving:e.moving,leg:e.route.legIdx,spawn:e.spawnSeq,deploy:e.deploySeq})),report:report()}); - const states=[],ops=[]; - for(let t=0;t<280&&!b.finished;t++){ - if(t===6)for(const e of b.enemies)if(e.alive)e.hp*=.5; - if(t===9){const def={pos:[9,9.8],route:routes[0],mods:{speedMul:.7}};const e=b.spawnEnemy('enemy_1007_slime',def);ops.push({tick:t,op:'spawn',key:e.defId,def});} - if(t===30){const e=b.enemies.find(e=>e.alive&&!e.isBoss);if(e){b.kill(e);ops.push({tick:t,op:'kill',id:e.id});}} - b.step();states.push(view()); - } - console.log(JSON.stringify({options,ops,states})); -} diff --git a/tools/reference/stats.mjs b/tools/reference/stats.mjs deleted file mode 100644 index 81f4f3f..0000000 --- a/tools/reference/stats.mjs +++ /dev/null @@ -1,30 +0,0 @@ -// Numeric battle oracle: no matches or game data. -import path from 'node:path';import{pathToFileURL}from'node:url'; -const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const{aggregateMods,ADD_KEYS,MUL_KEYS}=await imp('server/sim/buffs.js'); -const calc=await imp('server/sim/attack/calculation.js');const{createRng}=await imp('server/sim/rng.js'); -const rng=createRng(74581);const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -const encoded=s=>({numbers:Object.fromEntries(Object.entries(s).filter(([,v])=>typeof v==='number').map(([k,v])=>[k,bits(v)])),flags:Object.keys(s.flags).filter(k=>s.flags[k]).sort()}); -const out=x=>process.stdout.write(JSON.stringify(x)+'\n'); -for(let i=0;i<768;i++){ - const base={maxHp:100+rng()*1000,atk:rng()*2000,def:rng()*1000,res:rng()*150,aspd:rng()*800-100,bat:rng()*4,blockCnt:rng()*5,moveSpeed:rng()*3,spRecovery:rng()*2,massLevel:rng()*5,hpRecoveryPerSec:rng(),tauntLevel:rng()*2}; - const buffs=[];for(let j=0;j({mods:b.mods,flags:b.flags,stacks:b.stacks,shield:b.shield,permanent:b.persist&&b.duration===Infinity})); - unit.buffs=[];unit.markDirty();const second=encoded(unit.s);const hpAfter=bits(unit.hp); - const target=new Unit({base:{maxHp:1,def:rng()*2000,res:rng()*150}}).s; - const dmg={amount:rng()*3000,mul:rng()*3,defIgnoreFlat:rng()*100,defIgnorePct:rng()*2-.5,resIgnoreFlat:rng()*30,resIgnorePct:rng()*2-.5,calculation:i%2?'resolved':'formula'}; - const ep=rng()*150;const targetUnit={def:{epDamageResistance:ep}}; - const damages=['phys','arts','true','elemental'].map(type=>({type,mitigate:bits(calc.mitigate(dmg.amount,type,target,{...dmg,elementalRes:ep})),input:bits(calc.attackInput(dmg.amount,type,s)),expected:bits(calc.officialExpectedAmount(dmg,type,target,targetUnit)),base:bits(calc.calculateBaseDamage(dmg,type,target,s,targetUnit)),noSource:bits(calc.calculateBaseDamage(dmg,type,target,null,targetUnit)),estimate:bits(calc.estimateTargetDamage(dmg.amount,type,s))})); - out({base,buffs:serialized,cm,floor,first,hp,second,hpAfter,target:encoded(target),dmg,ep,damages}); -} diff --git a/tools/reference/status.mjs b/tools/reference/status.mjs deleted file mode 100644 index 4fe2c5d..0000000 --- a/tools/reference/status.mjs +++ /dev/null @@ -1,17 +0,0 @@ -// Catalogue statuses and actual BattleStatus application, including hook mutations. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{BattleStatus}=await imp('server/sim/battle/status.js');const{makeBuff}=await imp('server/sim/buffs.js');const{Unit}=await imp('server/sim/units.js'); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -const names=['stun','freeze','cold','sleep','slow','sluggish','bind','fragile','artsFragile','physFragile','elemFragile','silence','fear','tremble','disarm','stealth','camou','reveal','invulnerable','levitate','groundbind','palsy','taunt','weaken','aspdDown','defDown','resDown','unblockable','attract','resist','burnBurst','neuralBurst','necrosisBurst','apoptosisBurst','erosionBurst']; -for(let i=0;i<384;i++){ - const cfg={i,side:i%2?'enemy':'ally',fly:i%3===0,sourceFly:i%5===0,mass:i%7===0?5:2,immune:['stun','frozen','sleep','silence','levitate','feared','palsy'].filter((x,j)=>(i+j)%7===0),before:i%2===0}; - const base=makeBuff({}).seq;const u=new Unit({id:1,side:cfg.side,x:6,y:10,motion:cfg.fly?'FLY':'WALK',base:{maxHp:1000,atk:100,def:100,res:30,massLevel:cfg.mass}});u.deployed=true;u.def={immune:new Set(cfg.immune)}; - const source=new Unit({id:2,side:cfg.side==='enemy'?'ally':'enemy',x:4.5,y:9.5,motion:cfg.sourceFly?'FLY':'WALK'});source.deployed=true; - const trace=[];const b={units:[u,source],time:0,rect:{r0:2,r1:16,c0:3,c1:17},_hooks:{beforeStatus:cfg.before,statusApplied:true},_safe:f=>f(),_ev:e=>trace.push(e),_unblock(){},releaseBlocked(){},emit(name,c){if(name==='beforeStatus'){trace.push(['before',c.status,bits(c.duration),c.value==null?null:bits(c.value)]);if(i%17===0)c.cancel=true;if(i%19===0)u.alive=false;if(i%5===0)c.duration*=.5;if(i%7===0)c.value=.8;if(i%11===0)c.duration=NaN;}else trace.push(['applied',c.status,bits(c.duration),c.value==null?null:bits(c.value),c.entered]);return c;}}; - for(const key of['addBuff','removeBuff','_removeBuffAt','_tickBuffs','_applyValuedStatus','applyStatus','resistOf','_setAttractPoint'])b[key]=BattleStatus.prototype[key]; - const flags={invulnerable:i%37===0,untargetable:i%37===0,liftoff:i%13===0,groundbind:i%4===0};b.addBuff(u,{key:'initial',flags}); - const ops=[{key:'resist',duration:6,value:.5},{key:'palsy',duration:6,value:3},{key:'cold',duration:1},{key:'cold',duration:1.5}]; - for(let j=0;j<50;j++){if(j%4===3)ops.push({tick:[.1,.5,2,5][(i+j)%4]});else ops.push({key:names[(i+j*7)%names.length],duration:[.2,.5,2,'inf',0,-1][(i+j)%6],value:j%5===0?null:[.3,.7,2,-30][(i+j)%4],source:j%3===0?null:j%3===1?1:2,force:j%7===0,refresh:j%5===0?['replace','extend','keep'][j%3]:null,point:j%2?[4.5,19.5]:null,resistApplied:j%13===0,stackAs:j%7===0?.9:null,reenter:j%11===0,ignoreSelect:j%17===0});} - const states=[];for(const op of ops){let accepted=null;if(op.tick!=null){b.time+=op.tick;b._tickBuffs(op.tick);}else{const o={...op,duration:op.duration==='inf'?Infinity:op.duration,source:op.source===1?u:op.source===2?source:null};accepted=b.applyStatus(u,op.key,o);}const s=u.s;states.push({accepted,alive:u.alive,resist:bits(b.resistOf(u)),stats:['atk','def','res','moveSpeed','dmgTakenMul','aspd'].map(k=>bits(s[k])),flags:Object.keys(s.flags).filter(k=>s.flags[k]).sort(),buffs:u.buffs.map(x=>({id:x.seq-base,key:x.key,stacks:x.stacks,left:bits(x.timeLeft),duration:bits(x.duration),acc:bits(x._acc),attract:x.data.attract?[x.data.attract.r,x.data.attract.c]:null,fear:x.data.fear?{seq:x.data.fear.seq,hit:[bits(x.data.fear.hy),bits(x.data.fear.hx)],source:[bits(x.data.fear.sy),bits(x.data.fear.sx)],self:x.data.fear.self}:null}))});} - process.stdout.write(JSON.stringify({cfg,flags,ops,states,trace})+'\n'); -} diff --git a/tools/reference/targeting.mjs b/tools/reference/targeting.mjs deleted file mode 100644 index a1f3292..0000000 --- a/tools/reference/targeting.mjs +++ /dev/null @@ -1,23 +0,0 @@ -// Target filters, sort keys and pre-movement attack commit gates, without matches/data. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{Unit}=await imp('server/sim/units.js');const t=await imp('server/sim/targeting.js');const ai=await imp('server/sim/ai.js');const{createRng}=await imp('server/sim/rng.js');const rng=createRng(52893); -const priorities=[null,'fly','lowDef','highDef','ranged','lowestHp','highestHp','lowestHpRatio','highestAtk','boss','elite','notBurst','ground','heaviest','nearest','farthest']; -for(let i=0;i<512;i++){ - const flags=['sleep','untargetable','stealth','reveal','stealthOff','liftoff','camou','groundbind','levitate','float','burstLock']; - const records=Array.from({length:6},(_,j)=>({id:j+1,side:j===0?'ally':'enemy',flags:Object.fromEntries(flags.filter(()=>rng()<.15).map(k=>[k,true])),hp:10+rng()*90,base:{maxHp:100,atk:rng()*100,def:rng()*100,res:rng()*100,massLevel:rng()*5,rangeRadius:j%2},spawn:1+j%3,aggro:j%3,motion:j%2?'FLY':'WALK',elite:j%3===0,boss:j%4===0,apply:j%2?'MELEE':'RANGED',hidden:rng()<.05,alive:rng()>.05,deployed:rng()>.05,remaining:j%3?rng()*30:null,x:4+rng(),y:10+rng()})); - const units=records.map(d=>{const u=new Unit({id:d.id,side:d.side,kind:'op',x:d.x,y:d.y,base:d.base,motion:d.motion});u.buffs=[{key:'stealthA',stacks:1,mods:{},flags:d.flags,shield:0}];u.hp=d.hp;u.alive=d.alive;u.deployed=d.deployed;u.hidden=d.hidden;u.spawnSeq=d.spawn;u.aggroSeq=d.aggro;u.deploySeq=d.id;u.isBoss=d.boss;u.def={rank:d.elite?'ELITE':'NORMAL',applyWay:d.apply};u.findBuff=()=>null;return u;}); - const profile={hitSleep:i%3===0,canHitFly:i%2===0,dollHitsFly:i%5===0,groundOnly:i%7===0,blockFree:i%11===0,skipEnemy:e=>e.id===6&&i%13===0};units[0].trait.doll=i%2===1;units[1].blockedBy=units[0];units[0].blocking=[units[1]]; - const battle={remainingDistance:e=>records[e.id-1].remaining??Infinity}; - const enemyOrder=priorities.map(priority=>t.sortEnemyTargets(battle,units[0],units.slice(1),priority).map(u=>u.id)); - const allyOrder=t.sortAllyTargets(Object.assign(units[1],{profile}),[units[4],units[0],units[3],units[2]]).map(u=>u.id); - const filters=units.slice(1).map(e=>({id:e.id,enemy:t.canTargetEnemy(units[0],e,profile),ally:t.canTargetAlly(units[1],e,true),aura:t.auraSelectable(units[1],e),area:t.areaSelectable(units[1],e)})); - const grid=[[0,0],[1,1],[0,1],[1,-1],[0,0]];const ranges=['UP','RIGHT','DOWN','LEFT'].map(dir=>t.absoluteRangeKeys(grid,10,4,dir,i%24)); - process.stdout.write(JSON.stringify({i,records,profile:{...profile,skip:i%13===0},doll:units[0].trait.doll,enemyOrder,allyOrder,filters,ranges})+'\n'); -} -for(let i=0;i<1024;i++){ - const cd=[0,-1,1/30,1/30+1e-9,1/30+2e-9,.5,1][i%7],act=i%3!==0,disarm=i%5===0,active=i%7===0,had=i%11===0?false:undefined; - const profile={noAttack:i%13===0,noAttackUnlessSkill:i%17===0,heal:i%19===0?{}:null,dmgType:i%19===0?'heal':'phys',allInRange:i%23===0,rangeAoe:i%29===0}; - const u=new Unit({id:1,side:'ally',kind:'op'});u.alive=act;u.deployed=true;u.atkCd=cd;u.profile=profile;u.skill={active,attackOverride:()=>null,targetingOverride:()=>null};u.trait.hadTarget=had;u.buffs=[{stacks:1,flags:{disarm},mods:{},shield:0}];const enemy=new Unit({id:2,side:'enemy',kind:'enemy'});enemy.deployed=true; - const b={allyUnits:[u],enemiesInKeys:()=>[enemy],remainingDistance:()=>1};ai.noteAttackCommit(b,1/30); - process.stdout.write(JSON.stringify({cadence:true,cd,act,disarm,active,had:had??null,profile,commit:!!b._attackCommit?.has(1),countdown:ai.attackCountdown(cd,1/30)})+'\n'); -} diff --git a/tools/reference/valued.mjs b/tools/reference/valued.mjs deleted file mode 100644 index 8f66ee0..0000000 --- a/tools/reference/valued.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Real strongest-effect waiting chains, expiry resumption and resist decay. -import path from'node:path';import{pathToFileURL}from'node:url';const root=path.resolve(process.argv[2]);const imp=p=>import(pathToFileURL(path.join(root,p))); -const{BattleStatus}=await imp('server/sim/battle/status.js');const{makeBuff,STATUS}=await imp('server/sim/buffs.js');const{Unit}=await imp('server/sim/units.js'); -const bits=x=>{const b=Buffer.alloc(8);b.writeDoubleBE(x);return b.toString('hex');}; -const names=['slow','fragile','artsFragile','physFragile','elemFragile','weaken','aspdDown','defDown','resDown','resist','plain']; -for(let i=0;i<384;i++){ - const name=names[i%names.length],plain=name==='plain',base=makeBuff({}).seq,u=new Unit({id:1,side:'ally',base:{maxHp:1000,atk:100,def:100,res:30,moveSpeed:1}});u.deployed=true;const trace=[]; - const b={units:[u],time:0,_safe:f=>f(),_ev(e){trace.push(e);}};for(const key of['addBuff','removeBuff','_removeBuffAt','_tickBuffs','_applyValuedStatus','applyStrongest'])b[key]=BattleStatus.prototype[key]; - if(name==='resist')b.addBuff(u,{key:'palsy',stacks:3,maxStacks:3,status:'palsy',visible:true}); - const ops=[];for(let j=0;j<48;j++){ - if(j%4===2)ops.push({op:'tick',dt:[.1,.3,1,5][(i+j)%4]}); - else if(j%17===0)ops.push({op:'raw',duration:.2}); - else if(j%11===0)ops.push({op:'remove'}); - else ops.push({op:'apply',duration:[.2,.5,2,6,'inf'][(i*3+j)%5],value:[.1,.3,-.3,.7,1.1,-30,20][(i+j*3)%7],stackAs:(i+j)%5===0?.9:null,source:j%2?1:null}); - } - const states=[];const duration=x=>x==='inf'?Infinity:x; - for(const op of ops){ - if(op.op==='tick'){b.time+=op.dt;b._tickBuffs(op.dt);}else if(op.op==='remove')b.removeBuff(u,name);else if(op.op==='raw')b.addBuff(u,{key:name,status:plain?null:name,duration:op.duration,mods:{atkPct:.01}}); - else if(plain)b.applyStrongest(u,name,{duration:duration(op.duration),value:op.value,mods:v=>({atkPct:v}),source:op.source?u:null}); - else b._applyValuedStatus(u,name,STATUS[name],duration(op.duration),op.value,op.source?u:null,op.stackAs); - const s=u.s;states.push({stats:['atk','def','res','moveSpeed','dmgTakenMul','artsTakenMul','physTakenMul','elementalTakenMul','aspd'].map(k=>bits(s[k])),buffs:u.buffs.map(x=>{const tail=[];for(let t=x.data.tail;t;t=t.tail)tail.push({value:bits(t.value),as:t.stackAs==null?null:bits(t.stackAs),until:bits(t.until)});return{id:x.seq-base,key:x.key,stacks:x.stacks,duration:bits(x.duration),left:bits(x.timeLeft),acc:bits(x._acc),value:x.data.value==null?null:bits(x.data.value),as:x.data.stackAs==null?null:bits(x.data.stackAs),tail};})}); - } - process.stdout.write(JSON.stringify({i,name,ops,states,trace})+'\n'); -} diff --git a/tools/reference/waves.mjs b/tools/reference/waves.mjs deleted file mode 100644 index 036ad3d..0000000 --- a/tools/reference/waves.mjs +++ /dev/null @@ -1,49 +0,0 @@ -// Development-only oracle: real 0.3.3 template conversion and solo Battle billing. -import fs from 'node:fs'; -import path from 'node:path'; -import { pathToFileURL } from 'node:url'; -const root = path.resolve(process.argv[2]); -const {spawnsFromTemplate} = await import(pathToFileURL(path.join(root,'server/sim/simdata.js'))); -const {Battle} = await import(pathToFileURL(path.join(root,'server/sim/Battle.js'))); -const bits = x => { const b=Buffer.alloc(8); b.writeDoubleBE(x); return b.toString('hex'); }; -const raw=JSON.parse(fs.readFileSync(path.join(root,'data/waves.json'),'utf8')); -const catalogEnemies=JSON.parse(fs.readFileSync(path.join(root,'data/enemies.json'),'utf8')); -const queueView=b=>b._pending.map(p=>({time:bits(p.time),sequence:p.seq,key:p.enemyKey,counted:p.counted,inTotal:p.inTotal,precounted:!!p.precounted})); -for (const [key,tpl] of Object.entries(raw)) { - const opts={mods:{hpMul:1.25,atkMul:0.7},tag:'wave'}; - const output=spawnsFromTemplate(tpl,opts); - const b=new Battle({content:'none',recordEvents:false,spawns:output.spawns,data:{enemies:catalogEnemies},logger:{warn(){},error(){}}}); - const excluded=Object.keys(catalogEnemies).filter(k=>catalogEnemies[k].notCountInTotal); - console.log(JSON.stringify({kind:'template',key,input:tpl,opts,output,queue:queueView(b),excluded})); -} -// Old research-shaped template; aliases and cumulative timings use upstream code. -const tpl={routes:[{m:'F',s:{r:9,c:10},e:[9,2],cp:[['DISAPPEAR',0,0],['WAIT',0,0,3],['MOVE',9,5]]}],waves:[ - {preDelay:0.2,postDelay:0.3,fragments:[{preDelay:0.4,actions:[{key:'enemy_a',n:3,int:0.1,pre:0.2,route:0}]},{preDelay:0.3,actions:[{key:'enemy_b',n:2,int:0.7}]}]}, - {preDelay:0.6,fragments:[{actions:[{enemyKey:'enemy_c',count:1,preDelay:0.2}]}]}]}; -console.log(JSON.stringify({kind:'template',key:'research',input:tpl,opts:{},output:spawnsFromTemplate(tpl)})); -const enemies={enemy_a:{stats:{hp:400,atk:0,moveSpeed:1},lpr:2},enemy_b:{stats:{hp:500},notCountInTotal:true},enemy_c:{stats:{hp:600},lpr:3}}; -const project = b => { - const r=b.result(),p=r.perPlayer.p; - const pp={}; for(const k of ['killed','total','leaked','perfect','killedInTotal','leakedInTotal','resolved','creditedKills','coins'])pp[k]=p[k]; - return structuredClone({...Object.fromEntries(['time','reason','killed','total','resolved','errors'].map(k=>[k,r[k]])),perPlayer:{p:pp},...(r.unspawned?{unspawned:r.unspawned}:{})}); -}; -for(let i=0;i<160;i++) { - const spawns=[ - {enemyKey:'enemy_a',time:0.1*(i%3),count:3,interval:0.1,bounty:{coins:2}}, - {enemyKey:'enemy_b',time:0.1,count:2,interval:0.15,countInTotal:i%2===0}, - {enemyKey:'enemy_c',time:3,count:2,tag:i%3===0?'boss':i%3===1?'part':null}, - {enemyKey:'enemy_a',time:0.3,sourcePlayerId:'other',mods:{hpMul:1.2}}, - ]; - const b=new Battle({seed:1,content:'none',recordEvents:false,players:[{playerId:'p',units:[]}],spawns,data:{enemies},logger:{warn(){},error(){}}}); - const queue=queueView(b); - const ops=[],states=[project(b)]; - for(let k=0;k<12;k++){ - const time=k*0.1;b.time=time; - if(k===2){ const def={enemyKey:'enemy_a',tag:i%4===0?'part':null,countInTotal:i%7===0?false:undefined,inTotal:i%5===0,bounty:{coins:3},sourcePlayerId:'runtime'}; - b.spawnEnemy(def.enemyKey,def);ops.push({op:'spawn',time,def});states.push(project(b)); } - b._processSpawns();ops.push({op:'process',time});states.push(project(b)); - if(k%3===i%3){const e=b.enemies.find(e=>e.alive);if(e){const op=k%2?'kill':'leak';b[op](e);ops.push({op,time,id:e.id});states.push(project(b));}} - } - b.time=1.2;b.forceEnd(i%2?'timeout':'forced');ops.push({op:i%2?'timeout':'forced',time:b.time});states.push(project(b)); - console.log(JSON.stringify({kind:'billing',enemies,spawns,queue,ops,states})); -}