diff --git a/Cargo.lock b/Cargo.lock index 85a62e5..05bf84b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -36,7 +36,7 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "funrounds-core" -version = "0.3.0-alpha.test.2" +version = "0.4.0-alpha.test.3" dependencies = [ "rand", "serde", @@ -45,7 +45,7 @@ dependencies = [ [[package]] name = "funrounds-plugin" -version = "0.3.0-alpha.test.2" +version = "0.4.0-alpha.test.3" dependencies = [ "funrounds-core", "plugify", @@ -166,9 +166,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" dependencies = [ "serde_core", ] @@ -186,9 +186,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.1.8+spec-1.1.0" +version = "1.2.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" dependencies = [ "indexmap", "serde_core", @@ -201,9 +201,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] @@ -219,9 +219,9 @@ dependencies = [ [[package]] name = "toml_writer" -version = "1.1.3+spec-1.1.0" +version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" [[package]] name = "unicode-ident" @@ -231,6 +231,6 @@ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" diff --git a/Cargo.toml b/Cargo.toml index b662030..3ffd354 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ members = ["crates/funrounds-core", "crates/funrounds-plugin"] resolver = "3" [workspace.package] -version = "0.3.0-alpha.test.2" +version = "0.4.0-alpha.test.3" edition = "2024" rust-version = "1.99" authors = ["Mai Ooizumi"] diff --git a/README.md b/README.md index 17cf693..3b47bcf 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,10 @@ # FunRounds-CS2 [![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](LICENSE) -[![Version](https://img.shields.io/badge/Version-0.3.0--alpha-informational.svg)](Cargo.toml) +[![Version](https://img.shields.io/badge/Version-0.4.0--alpha-informational.svg)](Cargo.toml) [![Rust Version](https://img.shields.io/badge/Rust-1.99.1+-orange.svg)](rust-toolchain.toml) [![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20x64-lightgrey.svg)]() -[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.0.6-success.svg)](https://github.com/untrustedmodders/plugify) +[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.3.1-success.svg)](https://github.com/untrustedmodders/plugify) **高性能、高安全性的 Counter-Strike 2 专用服务端特殊娱乐回合插件**
A high-performance, safe, and modular special rounds plugin for Counter-Strike 2 dedicated servers. @@ -19,11 +19,11 @@ ### 项目简介 / Overview -**FunRounds-CS2** 是基于 Rust 与 C++20 原生扩展开发、面向 Counter-Strike 2 专用服务端的特殊娱乐回合(Fun Rounds)插件,运行于 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架和 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 之上。 -**FunRounds-CS2** is a modern special rounds plugin for Counter-Strike 2 dedicated servers developed in Rust and native C++20, running atop [Plugify](https://github.com/untrustedmodders/plugify) and [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk). +**FunRounds-CS2** 是基于 Rust 与 C++20 原生扩展开发、面向 Counter-Strike 2 专用服务端的特殊娱乐回合(Fun Rounds)插件,运行于 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架和 [S2SDK](https://github.com/Mai-Ooizumi/plugify-plugin-s2sdk/tree/funrounds) 之上。 +**FunRounds-CS2** is a modern special rounds plugin for Counter-Strike 2 dedicated servers developed in Rust and native C++20, running atop [Plugify](https://github.com/untrustedmodders/plugify) and [S2SDK](https://github.com/Mai-Ooizumi/plugify-plugin-s2sdk/tree/funrounds). -在每个回合开始时(或由管理员实时指定),插件无缝应用多维度的玩法突变:修改玩家属性、物理参数、动态配装、后坐与视角机制、特殊战斗判定、小鸡生态及 C4 玩法,同时保证严格的崩溃隔离与无残留状态恢复。 -At the start of each round (or on administrative demand), it seamlessly applies multi-dimensional gameplay mutators: altering player attributes, physics, dynamic loadouts, recoil/camera mechanics, combat rules, chicken ecology, and bomb systems—with zero-leak state restoration and crash isolation. +在每个回合开始时(或由管理员实时指定),插件无缝应用多维度的玩法突变:修改玩家属性、机动物理、动态配装、后坐与视角机制、特殊战斗判定、小鸡生态及 C4 玩法,同时保证严格的崩溃隔离与无残留状态恢复。 +At the start of each round (or on administrative demand), it seamlessly applies multi-dimensional gameplay mutators: altering player attributes, mobility physics, dynamic loadouts, recoil/camera mechanics, combat rules, chicken ecology, and bomb systems—with zero-leak state restoration and crash isolation. --- @@ -31,14 +31,51 @@ | 维度 / Category | 玩法与机制说明 / Description | | :--- | :--- | -| **基础属性与物理**
Attributes & Physics | 生命值(1~10000 或随机区间)、护甲头盔、重力倍率、移速倍率、地面摩擦力、自动连跳(Bunnyhop)、地面加速度与反向倒车行走(`ground_reverse`)、全局时间流速(`time_scale`)及周期性变重力/变移速。
Health (fixed or random range), armor, gravity, speed multiplier, friction, auto-bunnyhopping, ground acceleration, ground reverse walking, time scale, and periodic oscillation. | -| **视觉与相机视角**
Visuals & Camera | 第三人称视角(`third_person`)、幽灵按行动隐身(`ghost`,支持呼吸心跳音效与距离感知)、夜视仪(`fr_nvg`)、准星/雷达隐藏(`hide_hud`)、模型 RGB 着色、半透明外观与开镜限制。
Third person camera, stealth ghost mode with breathing audio cues, night vision, HUD hiding, model RGB tint, translucency, and scope restrictions. | -| **射击与自推反冲**
Recoil & Knockback | 开火自身反冲自推(`fr_knock` 支持地面与空中切换)、后坐力与散布消除、开枪镜头震动冲击与衰减(`recoil_view` / `view_punch_decay`)、快速切枪(`fast_switch`)及射击引爆掉落手雷。
Shooting self-push knockback (ground/air modes), recoil & spread suppression, view-punch intensity/decay, fast switch, and shooting dropped grenades. | -| **动态配装与弹药**
Loadouts & Ammo | 阵营武器清理与定向配发、4 种弹药模式(原生 / 无限备弹 / 无限弹匣 / 单发换填)、电击枪充能、手雷自动补充(HE/闪光/烟雾/诱饵/燃烧弹)、击杀升级换枪(`kill_loadout`)与随机抽枪。
Team-specific weapon clearing/giving, 4 ammo modes (inherit/reserve/clip/single-shot), taser recharge, grenade refills, kill-progression, and random loadouts. | -| **特殊战斗判定**
Combat Modifiers | 造成伤害吸血、反弹伤害(`reflect_damage`)、按当前生命动态缩放伤害/移速/衰减、能量吸收护盾、开枪自伤(未命中扣血)、诱饵弹躲避球碰撞杀伤(`dodgeball`)、右键飞刀投掷弹射与命中持续燃烧(`afterburn`)。
Vampiric lifesteal, reflect damage, HP-scaled damage/speed/decay, energy shield, miss penalty self-damage, decoy dodgeball, throwing knives, and afterburn. | -| **C4 炸弹与自爆**
C4 Objectives & Suicide | 3 种炸弹模式(原生 C4 / 鸡背 C4 / 便携可携带 C4)、自定义安放/拆除/爆炸耗时、炸弹弹跳、4 色引线拆包剪线小游戏(`fr_wire`)、现金购买 C4(`fr_c4`)及引爆炸弹自爆(`fr_suicide`)。
3 bomb types (native, chicken, carry), custom timers, bomb bouncing, 4-color wire cutting minigame, C4 purchasing, and suicide detonation. | -| **小鸡生态与回血**
Chicken & Healthshots | 普通小鸡比例刷新生态、互动吃鸡回血与未消化自爆风险机制、小鸡连锁爆炸;自定义医疗针回血比例与上限控制(`healthshot`,支持 `fr_healthshot` 购买)。
Chicken population scaling, eating chickens with digestion risk & chain explosions; custom healthshot healing ratios with cash purchase. | -| **经济与多语言**
Economy & i18n | 任意位置购买、阵营购买权限、回合保底现金与被动收入;内置完整中英多语言本地化(`zh-CN` / `en`),优先跟随客户端语言。
Buy anywhere, team purchase access, round money floor, passive income, and built-in bilingual i18n matching client preferences. | +| **基础属性与物理**
Attributes & Physics | 生命值(1~10000 或随机区间)、护甲头盔(护甲最高 1000)、重力倍率、移速倍率、地面摩擦力、自动连跳(Bunnyhop)、地面加速度与反向行走(`ground_reverse`)、全局时间流速(`time_scale`)及周期性变重力/变移速。
Health (up to 10,000 or random range), armor/helmets (armor up to 1,000), gravity/speed multipliers, friction, auto-bunnyhopping, ground acceleration/reverse walking, time scale, and periodic gravity/speed oscillation. | +| **动作与机动能力**
Movement & Mobility | 空中辅助转向加速(`autostrafe`)、空中贴墙挂墙(`wall_hang`)、准星瞄准点抓钩牵引(`grapple`)及地图特定区域蹦床弹射(`trampoline`)。
Air-strafe directional acceleration assist, wall hang upon contact, grapple hook pulling to target, and map-specific trampoline launch zones. | +| **视觉与相机视角**
Visuals & Camera | 第三人称视角(`third_person`)、幽灵按行动隐身(`ghost`,支持呼吸心跳音效与距离感知)、大头模式(`big_head`,依据 KD 动态缩放头部)、夜视仪(`fr_nvg`)、准星/雷达隐藏(`hide_hud`)、模型 RGB 着色、半透明外观与开镜限制。
Third-person camera, stealth ghost mode with breathing cues, KD-scaled big head mode, night vision, HUD hiding, model RGB tint, translucency, and scope restrictions. | +| **射击与自推反冲**
Recoil & Knockback | 开火自身反冲自推(`fr_knock` 支持地面与空中切换)、后坐力与散布消除、开火概率换枪/掉枪(`weapon_on_fire`)、子弹命中爆炸(`explosive_bullets`)、开枪镜头震动冲击与衰减及快速切枪(`fast_switch`)。
Shooting self-push knockback (ground/air modes), recoil & spread suppression, fire-triggered weapon drop/switch, explosive bullets, view-punch intensity/decay, and fast switch. | +| **动态配装与武器**
Loadouts & Weapons | 规范化物品 ID、命名武器组(`[weapon_groups]` 支持 `@group` 引用)、阵营清理与定向配发、4 种弹药模式(原生 / 无限备弹 / 无限弹匣 / 单发换填)、电击枪充能、击杀升级换枪(`kill_loadout`)与独立随机配装。
Canonical weapon IDs, named weapon groups (`@group`), team filtering, 4 ammo modes (inherit/reserve/clip/single-shot), taser recharge, kill-progression, and random loadouts. | +| **投掷物与特殊战术**
Grenades & Tactical | 投掷手雷自动补充、接近敌人近炸引信(`proximity_fuse`)、HE 手雷寻的追踪飞行(`he_guidance`)、HE 爆风推力、烟雾区域治疗(`medical_smoke`)、诱饵弹躲避球碰撞杀伤(`dodgeball`)、右键飞刀及长效闪光(`long_flash`)。
Grenade replenishment, proximity fuse, guided HE tracking, HE blast impulse, medical smoke healing, decoy dodgeball, throwing knives, and extended flash duration. | +| **特殊战斗与生存惩罚**
Combat & Hazards | 造成伤害吸血、伤害反弹(`reflect_damage`)、动态生命曲线、友军射击转治疗(`friendly_fire_heal`)、脱战自愈(`regeneration`)、低速扣血惩罚(`dont_stop`)、熔岩地面(`hot_floor`)、死亡殉爆(`death_explosion`)与队杀限制。
Vampiric lifesteal, reflect damage, dynamic HP scaling, friendly fire healing, passive regeneration, low-speed penalty, hot floor lava damage, death explosion, and teamkill limits. | +| **C4 目标与小鸡生态**
C4 Objectives & Chickens | 3 种炸弹模式(原生 C4 / 鸡背 C4 / 便携可携带 C4)、自定义耗时与弹跳、4 色引线拆包剪线小游戏(`fr_wire`)、现金购买 C4(`fr_c4`)与自爆(`fr_suicide`);普通小鸡生态刷新、吃鸡回血与自爆、小鸡回血光环(`chicken_aura`)及医疗针。
3 bomb types (native, chicken, carry), custom timers, bomb bouncing, 4-color wire cutting minigame, C4 purchasing & suicide detonation; chicken population scaling, chicken digestion risk, chicken healing aura, and healthshots. | + +
+点击展开查看全部详细玩法特性与机制列表 / Click to expand full gameplay feature details + +- **规范化装备系统 / Canonical Equipment & Weapon Groups** + - **规范物品 ID**:全面采用无 `weapon_` 前缀的标准物品标识符(如 `famas`, `p250`, `hegrenade`, `flashbang`, `smokegrenade`, `decoy`, `molotov`, `incgrenade` 等)。
Canonical weapon IDs omitting the legacy `weapon_` prefix across all loadouts and abilities. + - **命名武器组**:支持在配置顶层定义 `[weapon_groups]`,模式中通过 `@group_name` 语法引用与组合复用。
Defines top-level `[weapon_groups]` referenced concisely via `@group_name` in mode loadouts. + - **扩展护甲上限**:初始护甲支持设定至最高 `1000` 点。
Initial armor configurable up to 1,000 points. + +- **动作与机动能力 / Movement & Mobility** + - **空中辅助加速 (`autostrafe`)**:空中自动对齐偏航速度并施加辅助加速,带来顺滑的空速增益体验。
Assists aerial strafe alignment and acceleration for enhanced air control. + - **空中挂墙 (`wall_hang`)**:在空中贴靠墙面且按住跳跃键时进入挂壁悬停状态。
Suspends players on vertical surfaces when touching walls while holding the jump key. + - **抓钩绳索 (`grapple`)**:瞄准任意场景表面并按下使用键,以配置的最大速度与拉力牵引玩家快速位移。
Fires a grappling hook towards crosshair contact points, pulling the player at configured speeds. + - **区域蹦床 (`trampoline`)**:在指定竞技地图(如 Dust2、Mirage)内置点位踩入即触发高空垂直弹射。
Designated map trigger zones launching players into the air with vertical impulse. + +- **射击与战斗突变 / Weaponry & Combat Mutators** + - **爆炸子弹 (`explosive_bullets`)**:开火命中产生范围爆炸、伤害与击退效果,支持独立冷却、伤害与半径区间。
Bullet impacts detonate with configurable cooldowns, radius, and damage ranges. + - **开火失控 (`weapon_on_fire`)**:射击时有几率触发强制切换下一武器或直接脱手掉落当前武器。
Firing carries a randomized chance to forcefully switch or drop the active weapon. + - **动态大头 (`big_head`)**:根据玩家当场击杀/死亡比率(KD)动态缩放头部模型大小与爆头判定框。
Scales head hitboxes dynamically based on individual kill-to-death ratios. + - **友伤转治疗 (`friendly_fire_heal`)**:命中友军不仅免除误伤,还可按固定数值或伤害比例为队友恢复生命。
Converts friendly fire into healing via fixed values or proportional damage ratios. + - **脱战自愈 (`regeneration`)**:脱离交火经过指定冷却延迟后,按固定周期自动恢复生命值。
Passively regenerates health after a period of staying out of combat. + +- **高阶投掷物机制 / Advanced Grenades** + - **近炸引信 (`proximity_fuse`)**:手雷飞行至敌方玩家感知半径内时触发近炸,直接缩短延时提前起爆。
Grenades trigger early proximity detonation upon detecting nearby enemies. + - **寻的追踪手雷 (`he_guidance`)**:高爆手雷出膛后自动以配置转向角速度寻的并追踪飞行轨迹中的敌人。
HE grenades automatically track and steer toward nearby enemies in range. + - **爆风推力 (`hegrenade_impulse`)**:高爆手雷爆炸产生额外物理冲量,推开爆心周围的目标。
Applies customizable directional impulse and knockback to players caught in HE explosions. + - **医疗烟雾 (`medical_smoke`)**:友方烟雾弹扩散范围内为处于其中的队友持续恢复生命。
Smoke clouds grant periodic healing to allied players inside the active smoke radius. + - **长效致盲 (`long_flash`)**:按倍率延长闪光弹全白致盲时间,并受最大保护上限时间限制。
Multiplies flashbang blind durations up to a configured ceiling cap. + +- **环境惩罚与规则机制 / Environmental Hazards & Rules** + - **止步惩罚 (`dont_stop`)**:玩家水平移速低于安全阈值并超过宽限时间后,将持续受到失速扣血惩罚。
Inflicts periodic health loss if a player's horizontal speed stays below a minimum threshold. + - **熔岩地面 (`hot_floor`)**:持续接触地面超过安全秒数后持续扣血,久留不离开则直接被火焰点燃。
Standing continuously on the ground burns the player and eventually sets them on fire. + - **死亡殉爆 (`death_explosion`)**:每回合随机从双方阵营赋予特定玩家死亡自爆装药,阵亡瞬间引发致命爆炸。
Designates a quota of players per team to trigger a massive explosion upon dying. + - **队杀限制 (`teamkill_limit`)**:严格限制单回合队杀次数,超额直接触发惩罚。
Enforces a threshold on teamkills before triggering punishments. + - **周期性参数波动 (`periodic_speed` / `periodic_gravity`)**:支持配置随机时间间隔,按自定义离散数值或连续区间周期刷新重力与移速。
Periodically mutates speed and gravity multipliers using custom value sets or intervals. + +
点击展开架构与可靠性设计 / Click to expand Architecture & Reliability @@ -58,7 +95,7 @@ ### 项目目录结构 / Project Layout ```text -├── bindings/ # Plugify S2SDK 接口清单 (123 项接口定义) / Provider manifest +├── bindings/ # Plugify S2SDK 接口清单 (164 项接口定义) / Provider manifest (164 methods) ├── config/ # 示例配置文件及多语言包 / Configurations & i18n files │ ├── funrounds.example.toml # 示例配置 / Reference configuration │ └── i18n/ # 本地化翻译文件 (zh-CN.toml, en.toml) / Localization catalogs @@ -80,7 +117,7 @@ - Counter-Strike 2 专用服务端(Windows x64 或 Linux x64)
Counter-Strike 2 Dedicated Server (Windows x64 or Linux x64) - 已安装并运行 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架
[Plugify](https://github.com/untrustedmodders/plugify) framework installed and active -- 已配置并加载 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 插件(版本 `3.0.6`)
[S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) plugin (version `3.0.6`) active in Plugify +- 已配置并加载 [S2SDK](https://github.com/Mai-Ooizumi/plugify-plugin-s2sdk/tree/funrounds) 插件(版本 `=3.3.1`)
[S2SDK](https://github.com/Mai-Ooizumi/plugify-plugin-s2sdk/tree/funrounds) plugin (version `=3.3.1`) active in Plugify #### 目录部署 / Deployment Structure @@ -118,7 +155,7 @@ game/csgo/addons/plugify/ | :--- | :--- | :--- | | `fr_status` | 无
None | 查看当前回合状态、运行阶段、底层能力就绪状态及故障排查信息。
Displays current mode, phase, capability readiness, and fault diagnoses. | | `fr_list` | 无
None | 列出配置池中所有已启用的特殊模式列表。
Lists all loaded and enabled round modes in the pool. | -| `fr_next` | `` | 指定下一回合的模式 ID,或恢复随机抽取 (`random`)。
Queues a specific mode ID or random selection for the next round. | +| `fr_next` | `>` | 指定下一回合的模式 ID(支持直接传 ID 或 `id `),或恢复随机抽取 (`random`)。
Queues a specific mode ID (`fr_next ` or `fr_next id `) or random selection (`random`) for the next round. | | `fr_reload` | 无
None | 校验并重载配置文件与多语言文本,重载成功于下一回合生效。
Validates and schedules configuration and i18n reload for the next round. | | `fr_enable` | `<0 \| 1>` | 插件总启停开关:`1` 为启用,`0` 为停用。
Master switch: disables (`0`) or enables (`1`) the plugin. | @@ -151,6 +188,10 @@ diagnostics = false # 诊断日志开关 / Diagnostic logging [i18n] default_language = "zh-CN" # 服务端缺省语言("zh-CN" 或 "en")/ Default language +# 可选命名武器组 / Optional named weapon groups +# [weapon_groups] +# basic = ["famas", "p250"] + # 全局默认模板(模式内未设置的字段将继承此处) / Global defaults [defaults] gravity = 1.0 @@ -161,7 +202,7 @@ id = "example" # 模式唯一标识 / Unique mode identifier enabled = true # 是否启用该模式 / Whether mode enters the pool name_key = "mode.example.name" # 多语言名称键 / Localized name key description_key = "mode.example.description" # 多语言说明键 / Localized description key -weapons = ["weapon_famas", "weapon_p250"] +weapons = ["famas", "p250"] # 规范物品 ID / Canonical weapon IDs # 阵营装备配发与清理 / Team equipment distribution clear_weapons = "all" # 配发前清理武器的队伍 (none / all / terrorists / counter_terrorists) @@ -170,7 +211,7 @@ give_knife = "all" # 配发刀具的队伍 # 基础属性与移动 / Attributes & movement health = 120 # 初始生命值 (1~10000 或随机范围 { min = 100, max = 150 }) -armor = 50 # 初始护甲值 (0~255 或随机范围 { min = 0, max = 100 }) +armor = 50 # 初始护甲值 (0~1000 或随机范围 { min = 0, max = 100 }) gravity = 1.0 # 重力倍率 ((0, 10],1.0 为正常重力) speed = 1.0 # 移速倍率 ((0, 10]) self_push = true # 开启开火自推反冲 / Recoil self-push @@ -180,11 +221,13 @@ ammo = "reserve" # 弹药规则 (inherit / reserve / clip / single_sh headshots = "normal" # 爆头规则 (normal / only / disabled) fast_switch = true # 快速切枪开关 / Fast switch -# 特殊玩法机制选开 / Optional mutators +# 可选玩法突变示例 / Optional mutator examples +# autostrafe = true # 空中辅助转向加速 / Air-strafe assist +# explosive_bullets = { cooldown_seconds = 1.5, damage = 30, radius = 120 } # 爆炸子弹 / Explosive bullets +# wall_hang = true # 空中贴墙挂墙 / Wall hang +# grapple = { max_distance = 1000.0, max_speed = 600.0, pull_gain = 4.0 } # 抓钩绳索 / Grapple hook # lifesteal = true # 吸血恢复 / Vampiric lifesteal -# suicide = true # 允许自爆玩法 / Suicide blast -# third_person = { distance = 64.0, follow_eyes = true, return_strength = 2.0 } # 第三人称 -# bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, bounce = false } # 特殊炸弹 +# third_person = { distance = 64.0, follow_eyes = true, return_strength = 2.0 } # 第三人称 / Third-person ```
diff --git a/README_EN.md b/README_EN.md index 434a143..b2e98b7 100644 --- a/README_EN.md +++ b/README_EN.md @@ -3,10 +3,10 @@ # FunRounds-CS2 [![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](LICENSE) -[![Version](https://img.shields.io/badge/Version-0.3.0--alpha-informational.svg)](Cargo.toml) +[![Version](https://img.shields.io/badge/Version-0.4.0--alpha-informational.svg)](Cargo.toml) [![Rust Version](https://img.shields.io/badge/Rust-1.99.1+-orange.svg)](rust-toolchain.toml) [![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20x64-lightgrey.svg)]() -[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.0.6-success.svg)](https://github.com/untrustedmodders/plugify) +[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.3.1-success.svg)](https://github.com/untrustedmodders/plugify) **A high-performance, safe, and modular special rounds plugin for Counter-Strike 2 dedicated servers.** @@ -18,9 +18,9 @@ ### Overview -**FunRounds-CS2** is a modern Counter-Strike 2 server plugin developed in Rust and native C++20, built atop the [Plugify](https://github.com/untrustedmodders/plugify) framework and [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk). +**FunRounds-CS2** is a modern Counter-Strike 2 server plugin developed in Rust and native C++20, built atop the [Plugify](https://github.com/untrustedmodders/plugify) framework and [S2SDK](https://github.com/Mai-Ooizumi/plugify-plugin-s2sdk/tree/funrounds). -At the start of each round (or on administrative demand), it seamlessly applies multi-dimensional gameplay mutators—altering player attributes, physics, dynamic loadouts, recoil/camera mechanics, combat rules, chicken ecology, and bomb systems—with zero-leak state restoration and crash isolation. +At the start of each round (or on administrative demand), it seamlessly applies multi-dimensional gameplay mutators—altering player attributes, mobility physics, dynamic loadouts, recoil/camera mechanics, combat rules, chicken ecology, and bomb systems—with zero-leak state restoration and crash isolation. --- @@ -28,14 +28,51 @@ At the start of each round (or on administrative demand), it seamlessly applies | Category | Description | | :--- | :--- | -| **Attributes & Physics** | Health (1–10,000 or random range), armor/helmets, gravity scaling, speed multiplier, friction, auto-bunnyhopping, ground acceleration, ground reverse walking (`ground_reverse`), time scale (`time_scale`), and periodic speed/gravity oscillation. | -| **Visuals & Camera** | Third person camera (`third_person`), stealth ghost mode with breathing audio cues and distance awareness (`ghost`), night vision (`fr_nvg`), crosshair/radar hiding (`hide_hud`), model RGB tinting, translucency, and scope restrictions. | -| **Recoil & Knockback** | Weapon recoil self-push knockback (`fr_knock` supports ground and air modes), recoil & spread suppression, view-punch intensity/decay (`recoil_view` / `view_punch_decay`), fast switch (`fast_switch`), and shooting dropped grenades. | -| **Loadouts & Ammunition** | Team-specific weapon clearing and granting, 4 ammo modes (inherit / reserve / clip / single-shot), taser recharge intervals, automatic grenade replenishment (HE/flash/smoke/decoy/molotov), kill progression (`kill_loadout`), and random draws. | -| **Combat Modifiers** | Vampiric lifesteal, reflect damage (`reflect_damage`), HP-scaled damage/speed/decay, energy absorption shield, miss penalty self-damage, decoy dodgeball collisions (`dodgeball`), throwing knives with bouncing, and afterburn damage. | -| **C4 Objectives & Suicide** | 3 bomb types (native, chicken, carry), custom timers, bomb bouncing, 4-color wire cutting minigame (`fr_wire`), C4 cash purchasing (`fr_c4`), and C4 suicide explosions (`fr_suicide`). | -| **Chicken & Healthshots** | Chicken population scaling, eating chickens with digestion risk & chain explosions; custom healthshot healing ratios with cash purchase (`fr_healthshot`). | -| **Economy & i18n** | Buy anywhere, team purchase access, round money floor, passive income; built-in bilingual i18n (`zh-CN` / `en`) automatically matching client language. | +| **Attributes & Physics** | Health (up to 10,000 or random range), armor/helmets (armor up to 1,000), gravity scaling, speed multiplier, friction, auto-bunnyhopping, ground acceleration, ground reverse walking (`ground_reverse`), time scale (`time_scale`), and periodic speed/gravity oscillation. | +| **Movement & Mobility** | Air-strafe directional acceleration assist (`autostrafe`), wall hang upon contact (`wall_hang`), grapple hook pulling to target (`grapple`), and map-specific trampoline launch zones (`trampoline`). | +| **Visuals & Camera** | Third person camera (`third_person`), stealth ghost mode with breathing audio cues and distance awareness (`ghost`), dynamic KD-scaled big head mode (`big_head`), night vision (`fr_nvg`), crosshair/radar hiding (`hide_hud`), model RGB tinting, translucency, and scope restrictions. | +| **Recoil & Knockback** | Weapon recoil self-push knockback (`fr_knock` supports ground and air modes), recoil & spread suppression, weapon drop/switch on fire (`weapon_on_fire`), explosive bullets (`explosive_bullets`), view-punch intensity/decay, and fast switch (`fast_switch`). | +| **Loadouts & Weapons** | Canonical weapon IDs, named weapon groups (`[weapon_groups]` referenced via `@group`), team-specific weapon clearing and granting, 4 ammo modes (inherit / reserve / clip / single-shot), taser recharge intervals, kill progression (`kill_loadout`), and random draws. | +| **Grenades & Tactical** | Automatic grenade replenishment, proximity fuse detonation (`proximity_fuse`), guided HE tracking (`he_guidance`), HE blast impulse (`hegrenade_impulse`), medical smoke healing (`medical_smoke`), decoy dodgeball collisions (`dodgeball`), throwing knives, and extended flash duration (`long_flash`). | +| **Combat & Hazards** | Vampiric lifesteal, reflect damage (`reflect_damage`), dynamic HP curves, friendly fire healing (`friendly_fire_heal`), passive regeneration (`regeneration`), low-speed penalty (`dont_stop`), hot floor lava damage (`hot_floor`), death explosion (`death_explosion`), and teamkill limits. | +| **C4 Objectives & Chickens** | 3 bomb types (native, chicken, carry), custom timers, bomb bouncing, 4-color wire cutting minigame (`fr_wire`), C4 cash purchasing (`fr_c4`), and C4 suicide explosions (`fr_suicide`); chicken population scaling, eating chickens with digestion risk, chicken healing aura (`chicken_aura`), and healthshots. | + +
+Click to expand full gameplay feature details + +- **Canonical Equipment & Weapon Groups** + - **Canonical Weapon IDs**: Fully transitions to standard IDs without the legacy `weapon_` prefix (e.g. `famas`, `p250`, `hegrenade`, `flashbang`, `smokegrenade`, `decoy`, `molotov`, `incgrenade`). + - **Named Weapon Groups**: Supports top-level `[weapon_groups]` definitions referenced succinctly as `@group_name` across modes. + - **Expanded Armor Cap**: Initial armor can be configured up to `1000` points. + +- **Movement & Mobility** + - **Air-Strafe Assist (`autostrafe`)**: Automatically aligns horizontal velocity with viewing angles to provide smooth aerial acceleration. + - **Wall Hang (`wall_hang`)**: Suspends players on vertical surfaces while touching walls and holding the jump key. + - **Grapple Hook (`grapple`)**: Shoots a grappling tether towards surfaces upon pressing the use key, pulling the player at configured speeds. + - **Map Trampolines (`trampoline`)**: Designated geographic trigger areas (e.g. Dust2, Mirage) launching players upwards with high vertical velocity. + +- **Weaponry & Combat Mutators** + - **Explosive Bullets (`explosive_bullets`)**: Bullet impacts detonate with configurable cooldowns, radius, and damage ranges. + - **Weapon Fire Mishap (`weapon_on_fire`)**: Firing carries a randomized chance to forcefully switch to the next weapon or drop the active weapon. + - **Big Head (`big_head`)**: Scales head hitbox dimensions dynamically according to the player's live kill-to-death ratio (KD). + - **Friendly Fire Healing (`friendly_fire_heal`)**: Converts friendly fire into healing via fixed values or proportional damage ratios. + - **Passive Regeneration (`regeneration`)**: Passively regenerates health after a period of staying out of combat. + +- **Advanced Grenades** + - **Proximity Fuse (`proximity_fuse`)**: Grenades detonate early upon detecting nearby enemy players within a specified trigger radius. + - **Guided HE Tracking (`he_guidance`)**: High explosive grenades steer toward nearby enemies in flight at a configured turn rate. + - **HE Blast Impulse (`hegrenade_impulse`)**: High explosive grenades apply customizable directional physical impulse and knockback. + - **Medical Smoke (`medical_smoke`)**: Smoke clouds grant periodic healing to allied players inside the active cloud. + - **Extended Flash (`long_flash`)**: Multiplies flashbang blind durations up to a configured ceiling cap. + +- **Environmental Hazards & Rules** + - **Low-Speed Hazard (`dont_stop`)**: Inflicts periodic health penalties if a player's horizontal speed stays below a minimum threshold past the grace period. + - **Hot Floor Lava (`hot_floor`)**: Standing continuously on the ground burns the player with damage, eventually igniting them. + - **Death Explosion (`death_explosion`)**: Designates a quota of players per team to trigger a massive explosion upon dying. + - **Teamkill Limit (`teamkill_limit`)**: Enforces a strict threshold on teamkills per round before punishing the offender. + - **Periodic Parameter Waves (`periodic_speed` / `periodic_gravity`)**: Randomly mutates gravity and speed multipliers at periodic intervals using discrete values or continuous ranges. + +
Click to expand Architecture & Reliability @@ -55,7 +92,7 @@ At the start of each round (or on administrative demand), it seamlessly applies ### Project Layout ```text -├── bindings/ # Plugify S2SDK provider bindings (123 methods) +├── bindings/ # Plugify S2SDK provider bindings (164 methods) ├── config/ # Reference configurations and i18n catalogs │ ├── funrounds.example.toml # Reference configuration │ └── i18n/ # Localization files (zh-CN.toml, en.toml) @@ -77,7 +114,7 @@ At the start of each round (or on administrative demand), it seamlessly applies - Counter-Strike 2 Dedicated Server (Windows x64 or Linux x64) - [Plugify](https://github.com/untrustedmodders/plugify) installed and active on your CS2 server -- [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) plugin (version `3.0.6`) active in Plugify +- [S2SDK](https://github.com/Mai-Ooizumi/plugify-plugin-s2sdk/tree/funrounds) plugin (version `=3.3.1`) active in Plugify #### Deployment @@ -112,74 +149,80 @@ game/csgo/addons/plugify/ | Command | Arguments | Description | | :--- | :--- | :--- | -| `fr_status` | None | Displays current mode, phase, engine capabilities, and fault diagnoses. | +| `fr_status` | None | Displays current mode, phase, capability readiness, and fault diagnoses. | | `fr_list` | None | Lists all loaded and enabled round modes in the pool. | -| `fr_next` | `` | Queues a specific mode ID or random mode for the next round. | +| `fr_next` | `>` | Queues a specific mode ID (`fr_next ` or `fr_next id `) or random selection (`random`) for the next round. | | `fr_reload` | None | Validates and schedules configuration and i18n reload for the next round. | | `fr_enable` | `<0 \| 1>` | Master switch: disables (`0`) or enables (`1`) the plugin. | #### Player Commands (Console & Chat) -| Console Command | Chat Alias | Arguments | Description | +| Console | Chat Alias | Arguments | Description | | :--- | :--- | :--- | :--- | -| `fr_info` | `!info` / `!frinfo` | None | Displays the current round mode, ID, and description in chat. | +| `fr_info` | `!info` / `!frinfo` | None | Displays current round mode name, ID, and description in chat. | | `fr_help` | `!help` / `!frhelp` | None | Displays available player commands and usage instructions. | -| `fr_knock` | `!knock` | `[0\|1\|2]` | Sets or cycles shooting self-push (`0`: off, `1`: ground & air, `2`: airborne only [default]; cycle without args). | -| `fr_c4` | `!c4` | None | Purchases an extra C4 at the configured price when allowed. | -| `fr_suicide` | `!suicide` | None | Triggers a suicide explosion with held or purchased C4 when allowed. | -| `fr_chicken` | `!chicken` | None | Buys an ordinary chicken at the configured price. | -| `fr_healthshot` | `!healthshot` | None | Buys a healthshot at the configured price. | +| `fr_knock` | `!knock` | `[0\|1\|2]` | Configures recoil self-push (`0`: off, `1`: ground & air, `2`: airborne only [default]; cycle without args). | +| `fr_c4` | `!c4` | None | T players purchase extra C4 at the configured price when allowed. | +| `fr_suicide` | `!suicide` | None | Triggers suicide explosion with held or purchased C4 when allowed. | +| `fr_chicken` | `!chicken` | None | Purchases an ordinary chicken at the configured price. | +| `fr_healthshot` | `!healthshot` | None | Purchases a healthshot at the configured price. | | `fr_nvg` | `!nvg` | None | Toggles night vision. | -| `fr_wire` | `!wire` | `` | Selects planting or quick-defusing wire color (`blue`, `yellow`, `red`, `green`). | +| `fr_wire` | `!wire` | `` | Selects planting or quick-defusing wire color (blue, yellow, red, green). | --- ### Configuration -The configuration uses strict TOML format with support for global `[defaults]` template inheritance: +Configuration uses strict TOML syntax with a global `[defaults]` template for field inheritance: ```toml -# Top-level settings -diagnostics = false # Diagnostic logging (default: false) +# Global settings +diagnostics = false # Diagnostic logging -# Internationalization +# i18n [i18n] -default_language = "en" # Server default language ("zh-CN" or "en") +default_language = "zh-CN" # Default language ("zh-CN" or "en") + +# Optional named weapon groups +# [weapon_groups] +# basic = ["famas", "p250"] -# Global default template (mode-level fields take precedence) +# Global defaults [defaults] gravity = 1.0 bunnyhop = false [[modes]] -id = "example" # Unique mode identifier (ASCII, alphanumeric, '_' or '-') -enabled = true # Whether this mode enters the round pool +id = "example" # Unique mode identifier +enabled = true # Whether mode enters the pool name_key = "mode.example.name" # Localized name key description_key = "mode.example.description" # Localized description key -weapons = ["weapon_famas", "weapon_p250"] +weapons = ["famas", "p250"] # Canonical weapon IDs -# Team loadout control -clear_weapons = "all" # Team to clear weapons before granting (none / all / terrorists / counter_terrorists) -give_weapons = "all" # Team to receive candidates -give_knife = "all" # Team to receive knife +# Team equipment distribution +clear_weapons = "all" # Teams to strip (none / all / terrorists / counter_terrorists) +give_weapons = "all" # Teams to give candidates +give_knife = "all" # Teams to give knives # Attributes & movement -health = 120 # Initial health (1-10000, or random range { min = 100, max = 150 }) -armor = 50 # Initial armor (0-255, or random range { min = 0, max = 100 }) -gravity = 1.0 # Gravity multiplier ((0, 10], 1.0 is normal gravity) +health = 120 # Initial health (1–10000 or range { min = 100, max = 150 }) +armor = 50 # Initial armor (0–1000 or range { min = 0, max = 100 }) +gravity = 1.0 # Gravity multiplier ((0, 10], 1.0 is normal) speed = 1.0 # Speed multiplier ((0, 10]) -self_push = true # Weapon recoil self-push +self_push = true # Recoil self-push -# Recoil & view -ammo = "reserve" # Ammo mode (inherit / reserve / clip / single_shot) +# Shooting & view dynamics +ammo = "reserve" # Ammo rule (inherit / reserve / clip / single_shot) headshots = "normal" # Headshot rule (normal / only / disabled) -fast_switch = true # Fast weapon switch +fast_switch = true # Fast switch -# Optional mutators +# Optional mutator examples +# autostrafe = true # Air-strafe assist +# explosive_bullets = { cooldown_seconds = 1.5, damage = 30, radius = 120 } # Explosive bullets +# wall_hang = true # Wall hang +# grapple = { max_distance = 1000.0, max_speed = 600.0, pull_gain = 4.0 } # Grapple hook # lifesteal = true # Vampiric lifesteal -# suicide = true # Suicide blast gameplay -# third_person = { distance = 64.0, follow_eyes = true, return_strength = 2.0 } -# bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, bounce = false } +# third_person = { distance = 64.0, follow_eyes = true, return_strength = 2.0 } # Third-person ```
@@ -194,17 +237,17 @@ Refer to [config/funrounds.example.toml](config/funrounds.example.toml) for full #### 1. Build Rust Plugin -Requires Rust `1.99.1` (automatically managed by `rust-toolchain.toml`): +Requires Rust `1.99.1` (automatically handled by `rust-toolchain.toml`): ```bash -# Code formatting check and Clippy analysis +# Formatting & Clippy lint checks cargo fmt --all -- --check cargo clippy --workspace --all-targets --locked -- -D warnings -# Execute test suite +# Execute full test suite cargo test --workspace --locked -# Build optimized release binaries +# Build Release binaries cargo build --release --workspace --locked ``` @@ -213,7 +256,7 @@ cargo build --release --workspace --locked Requires Python 3.10+, CMake 3.25+, and a C++20 compiler (MSVC 2022+ or GCC 11+): ```bash -# Build native module to output directory +# Build native companion into dist/native python scripts/build-native.py --output-dir dist/native ``` diff --git a/README_ZH.md b/README_ZH.md index de7bce0..f90f6c6 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -3,10 +3,10 @@ # FunRounds-CS2 [![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](LICENSE) -[![Version](https://img.shields.io/badge/Version-0.3.0--alpha-informational.svg)](Cargo.toml) +[![Version](https://img.shields.io/badge/Version-0.4.0--alpha-informational.svg)](Cargo.toml) [![Rust Version](https://img.shields.io/badge/Rust-1.99.1+-orange.svg)](rust-toolchain.toml) [![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20x64-lightgrey.svg)]() -[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.0.6-success.svg)](https://github.com/untrustedmodders/plugify) +[![Framework](https://img.shields.io/badge/Framework-Plugify%20%2B%20S2SDK%203.3.1-success.svg)](https://github.com/untrustedmodders/plugify) **高性能、高安全性的 Counter-Strike 2 专用服务端特殊娱乐回合插件** @@ -18,9 +18,9 @@ ### 项目简介 -**FunRounds-CS2** 是基于 Rust 与 C++20 原生扩展开发、面向 Counter-Strike 2 专用服务端的特殊娱乐回合(Fun Rounds)插件。本项目构建于 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架和 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 扩展之上。 +**FunRounds-CS2** 是基于 Rust 与 C++20 原生扩展开发、面向 Counter-Strike 2 专用服务端的特殊娱乐回合(Fun Rounds)插件。本项目构建于 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架和 [S2SDK](https://github.com/Mai-Ooizumi/plugify-plugin-s2sdk/tree/funrounds) 扩展之上。 -插件在每个回合开始时(或由管理员实时指定)无缝应用多维度的玩法突变:修改玩家属性、物理参数、动态配装、后坐与视角机制、特殊战斗规则、小鸡生态及 C4 玩法,同时保证严格的崩溃隔离与无残留状态恢复。 +插件在每个回合开始时(或由管理员实时指定)无缝应用多维度的玩法突变:修改玩家属性、机动物理、动态配装、后坐与视角机制、特殊战斗规则、小鸡生态及 C4 玩法,同时保证严格的崩溃隔离与无残留状态恢复。 --- @@ -28,14 +28,51 @@ | 玩法维度 | 特性机制概要 | | :--- | :--- | -| **基础属性与物理** | 生命值(1~10000 或区间随机)、护甲头盔、重力倍率、移速倍率、地面摩擦力、自动连跳(Bunnyhop)、地面加速度与反向倒车行走(`ground_reverse`)、全局时间流速(`time_scale`)及周期性变重力/变移速。 | -| **视觉与相机视角** | 第三人称视角(`third_person`)、幽灵按行动隐身(`ghost`,支持呼吸心跳音效与距离感知)、夜视仪(`fr_nvg`)、准星/雷达隐藏(`hide_hud`)、模型 RGB 着色、半透明外观与开镜限制。 | -| **射击与自推反冲** | 开火自身反冲自推(`fr_knock` 支持地面与空中切换)、后坐力与散布消除、开枪镜头震动冲击与衰减(`recoil_view` / `view_punch_decay`)、快速切枪(`fast_switch`)及射击引爆掉落手雷。 | -| **动态配装与弹药** | 阵营武器清理与定向配发、4 种弹药模式(原生 / 无限备弹 / 无限弹匣 / 单发换装)、电击枪充能、手雷自动补充(HE/闪光/烟雾/诱饵/燃烧弹)、击杀升级换枪(`kill_loadout`)与随机抽枪。 | -| **特殊战斗判定** | 造成伤害吸血、反弹伤害(`reflect_damage`)、按当前生命动态缩放伤害/移速/衰减、能量吸收护盾、开枪自伤(未命中扣血)、诱饵弹躲避球碰撞杀伤(`dodgeball`)、右键飞刀投掷弹射与命中持续燃烧(`afterburn`)。 | -| **C4 炸弹与自爆** | 3 种炸弹模式(原生 C4 / 鸡背 C4 / 便携可携带 C4)、自定义安放/拆除/爆炸耗时、炸弹弹跳、4 色引线拆包剪线小游戏(`fr_wire`)、现金购买 C4(`fr_c4`)及引爆炸弹自爆(`fr_suicide`)。 | -| **小鸡生态与回血** | 普通小鸡比例刷新生态、互动吃鸡回血与未消化自爆风险机制、小鸡连锁爆炸;自定义医疗针回血比例与上限控制(`healthshot`,支持 `fr_healthshot` 购买)。 | -| **经济与多语言** | 任意位置购买、阵营购买权限、回合保底现金与被动收入;内置完整中英多语言本地化(`zh-CN` / `en`),优先跟随客户端语言。 | +| **基础属性与物理** | 生命值(1~10000 或区间随机)、护甲头盔(护甲最高 1000)、重力倍率、移速倍率、地面摩擦力、自动连跳(Bunnyhop)、地面加速度与反向行走(`ground_reverse`)、全局时间流速(`time_scale`)及周期性变重力/变移速。 | +| **动作与机动能力** | 空中辅助转向加速(`autostrafe`)、空中贴墙挂墙(`wall_hang`)、准星瞄准点抓钩牵引(`grapple`)及地图特定区域蹦床弹射(`trampoline`)。 | +| **视觉与相机视角** | 第三人称视角(`third_person`)、幽灵按行动隐身(`ghost`,支持呼吸心跳音效与距离感知)、大头模式(`big_head`,依据 KD 动态缩放头部)、夜视仪(`fr_nvg`)、准星/雷达隐藏(`hide_hud`)、模型 RGB 着色、半透明外观与开镜限制。 | +| **射击与自推反冲** | 开火自身反冲自推(`fr_knock` 支持地面与空中切换)、后坐力与散布消除、开火概率换枪/掉枪(`weapon_on_fire`)、子弹命中爆炸(`explosive_bullets`)、开枪镜头震动冲击与衰减及快速切枪(`fast_switch`)。 | +| **动态配装与武器** | 规范化物品 ID、命名武器组(`[weapon_groups]` 支持 `@group` 引用)、阵营清理与定向配发、4 种弹药模式(原生 / 无限备弹 / 无限弹匣 / 单发换装)、电击枪充能、击杀升级换枪(`kill_loadout`)与独立随机配装。 | +| **投掷物与特殊战术** | 投掷手雷自动补充、接近敌人近炸引信(`proximity_fuse`)、HE 手雷寻的追踪飞行(`he_guidance`)、HE 爆风推力、烟雾区域治疗(`medical_smoke`)、诱饵弹躲避球碰撞杀伤(`dodgeball`)、右键飞刀及长效闪光(`long_flash`)。 | +| **特殊战斗与生存惩罚** | 造成伤害吸血、伤害反弹(`reflect_damage`)、动态生命曲线、友军射击转治疗(`friendly_fire_heal`)、脱战自愈(`regeneration`)、低速扣血惩罚(`dont_stop`)、熔岩地面(`hot_floor`)、死亡殉爆(`death_explosion`)与队杀限制。 | +| **C4 目标与小鸡生态** | 3 种炸弹模式(原生 C4 / 鸡背 C4 / 便携可携带 C4)、自定义耗时与弹跳、4 色引线拆包剪线小游戏(`fr_wire`)、现金购买 C4(`fr_c4`)与自爆(`fr_suicide`);普通小鸡生态刷新、吃鸡回血与自爆、小鸡回血光环(`chicken_aura`)及医疗针。 | + +
+点击展开查看全部详细玩法特性与机制列表 + +- **规范化装备系统** + - **规范物品 ID**:全面采用无 `weapon_` 前缀的标准物品标识符(如 `famas`, `p250`, `hegrenade`, `flashbang`, `smokegrenade`, `decoy`, `molotov`, `incgrenade` 等)。 + - **命名武器组**:支持在配置顶层定义 `[weapon_groups]`,模式中通过 `@group_name` 语法引用与组合复用。 + - **扩展护甲上限**:初始护甲支持设定至最高 `1000` 点。 + +- **动作与机动能力** + - **空中辅助加速 (`autostrafe`)**:空中自动对齐偏航速度并施加辅助加速,带来顺滑的空速增益体验。 + - **空中挂墙 (`wall_hang`)**:在空中贴靠墙面且按住跳跃键时进入挂壁悬停状态。 + - **抓钩绳索 (`grapple`)**:瞄准任意场景表面并按下使用键,以配置的最大速度与拉力牵引玩家快速位移。 + - **区域蹦床 (`trampoline`)**:在指定竞技地图(如 Dust2、Mirage)内置点位踩入即触发高空垂直弹射。 + +- **射击与战斗突变** + - **爆炸子弹 (`explosive_bullets`)**:开火命中产生范围爆炸、伤害与击退效果,支持独立冷却、伤害与半径区间。 + - **开火失控 (`weapon_on_fire`)**:射击时有几率触发强制切换下一武器或直接脱手掉落当前武器。 + - **动态大头 (`big_head`)**:根据玩家当场击杀/死亡比率(KD)动态缩放头部模型大小与爆头判定框。 + - **友伤转治疗 (`friendly_fire_heal`)**:命中友军不仅免除误伤,还可按固定数值或伤害比例为队友恢复生命。 + - **脱战自愈 (`regeneration`)**:脱离交火经过指定冷却延迟后,按固定周期自动恢复生命值。 + +- **高阶投掷物机制** + - **近炸引信 (`proximity_fuse`)**:手雷飞行至敌方玩家感知半径内时触发近炸,直接缩短延时提前起爆。 + - **寻的追踪手雷 (`he_guidance`)**:高爆手雷出膛后自动以配置转向角速度寻的并追踪飞行轨迹中的敌人。 + - **爆风推力 (`hegrenade_impulse`)**:高爆手雷爆炸产生额外物理冲量,推开爆心周围的目标。 + - **医疗烟雾 (`medical_smoke`)**:友方烟雾弹扩散范围内为处于其中的队友持续恢复生命。 + - **长效致盲 (`long_flash`)**:按倍率延长闪光弹全白致盲时间,并受最大保护上限时间限制。 + +- **环境惩罚与规则机制** + - **止步惩罚 (`dont_stop`)**:玩家水平移速低于安全阈值并超过宽限时间后,将持续受到失速扣血惩罚。 + - **熔岩地面 (`hot_floor`)**:持续接触地面超过安全秒数后持续扣血,久留不离开则直接被火焰点燃。 + - **死亡殉爆 (`death_explosion`)**:每回合随机从双方阵营赋予特定玩家死亡自爆装药,阵亡瞬间引发致命爆炸。 + - **队杀限制 (`teamkill_limit`)**:严格限制单回合队杀次数,超额直接触发惩罚。 + - **周期性参数波动 (`periodic_speed` / `periodic_gravity`)**:支持配置随机时间间隔,按自定义离散数值或连续区间周期刷新重力与移速。 + +
点击展开架构与可靠性设计 @@ -55,7 +92,7 @@ ### 项目目录结构 ```text -├── bindings/ # Plugify S2SDK 接口清单 (123 项接口定义) +├── bindings/ # Plugify S2SDK 接口清单 (164 项接口定义) ├── config/ # 示例配置文件及多语言包 │ ├── funrounds.example.toml # 示例配置 │ └── i18n/ # 本地化翻译文件 (zh-CN.toml, en.toml) @@ -77,7 +114,7 @@ - Counter-Strike 2 专用服务端(Windows x64 或 Linux x64) - 服务端已安装配置 [Plugify](https://github.com/untrustedmodders/plugify) 插件框架 -- 服务端已加载并运行 [S2SDK](https://github.com/untrustedmodders/plugify-plugin-s2sdk) 插件(版本 `3.0.6`) +- 服务端已加载并运行 [S2SDK](https://github.com/Mai-Ooizumi/plugify-plugin-s2sdk/tree/funrounds) 插件(版本 `=3.3.1`) #### 部署步骤 @@ -101,29 +138,29 @@ game/csgo/addons/plugify/ │ └── funrounds-native.dll (或 lib*.so) # 原生动态库 ├── funrounds-native.pplugin # 原生插件清单 └── gamedata/ - └── funrounds-native.jsonc # Gamedata 特征与偏移文件 + └── funrounds-native.jsonc # Gamedata 特征与偏移 ``` --- ### 指令列表 -#### 管理员与服务端控制台指令(Console / RCON) +#### 管理员与控制台指令(Console / RCON) | 控制台指令 | 参数 | 说明 | | :--- | :--- | :--- | | `fr_status` | 无 | 查看当前回合状态、运行阶段、底层能力就绪状态及故障排查信息。 | -| `fr_list` | 无 | 列出当前配置池中所有已启用的特殊模式列表。 | -| `fr_next` | `` | 指定下一回合的模式 ID,或恢复随机抽取 (`random`)。 | +| `fr_list` | 无 | 列出配置池中所有已启用的特殊模式列表。 | +| `fr_next` | `>` | 指定下一回合的模式 ID(支持直接传 ID 或 `id `),或恢复随机抽取 (`random`)。 | | `fr_reload` | 无 | 校验并重载配置文件与多语言文本,重载成功于下一回合生效。 | | `fr_enable` | `<0 \| 1>` | 插件总启停开关:`1` 为启用,`0` 为停用。 | -#### 玩家控制台与聊天指令 +#### 玩家控制台与聊天快捷指令 -| 控制台指令 | 聊天快捷指令 | 参数 | 说明 | +| 控制台指令 | 聊天指令 | 参数 | 说明 | | :--- | :--- | :--- | :--- | | `fr_info` | `!info` / `!frinfo` | 无 | 在聊天栏中查看当前回合模式名称、编号与玩法说明。 | -| `fr_help` | `!help` / `!frhelp` | 无 | 查看插件帮助信息及玩家可用指令。 | +| `fr_help` | `!help` / `!frhelp` | 无 | 查看插件帮助信息及玩家可用指令列表。 | | `fr_knock` | `!knock` | `[0\|1\|2]` | 设置或切换开火自推反冲(`0` 关闭,`1` 地空全开,`2` 仅空中 [默认],无参依次切换)。 | | `fr_c4` | `!c4` | 无 | 进攻方在模式允许时按配置价格购买额外 C4。 | | `fr_suicide` | `!suicide` | 无 | 允许自爆时使用所持或购买的 C4 启动自爆。 | @@ -136,50 +173,56 @@ game/csgo/addons/plugify/ ### 配置说明 -配置文件采用严格 TOML 语法解析。支持 `[defaults]` 全局继承模板为所有模式提供默认参数: +配置文件采用严格 TOML 语法解析。支持 `[defaults]` 模板为所有模式提供基础属性继承: ```toml -# 顶层全局设置 -diagnostics = false # 是否开启诊断日志(默认 false) +# 全局设置 +diagnostics = false # 诊断日志开关 # 多语言配置 [i18n] default_language = "zh-CN" # 服务端缺省语言("zh-CN" 或 "en") -# 全局默认模板(模式内未单独设置的字段将继承此处) +# 可选命名武器组 +# [weapon_groups] +# basic = ["famas", "p250"] + +# 全局默认模板(模式内未设置的字段将继承此处) [defaults] gravity = 1.0 bunnyhop = false [[modes]] -id = "example" # 模式唯一标识(仅允许字母、数字、'_' 或 '-') -enabled = true # 是否启用该模式并加入随机池 -name_key = "mode.example.name" # 引用 i18n/*.toml 中的多语言文本键 -description_key = "mode.example.description" -weapons = ["weapon_famas", "weapon_p250"] +id = "example" # 模式唯一标识 +enabled = true # 是否启用该模式 +name_key = "mode.example.name" # 多语言名称键 +description_key = "mode.example.description" # 多语言说明键 +weapons = ["famas", "p250"] # 规范物品 ID -# 阵营发放与清理 -clear_weapons = "all" # 发放前清理武器队伍 (none / all / terrorists / counter_terrorists) -give_weapons = "all" # 发放候选武器队伍 -give_knife = "all" # 发放刀具队伍 +# 阵营装备配发与清理 +clear_weapons = "all" # 配发前清理武器的队伍 (none / all / terrorists / counter_terrorists) +give_weapons = "all" # 配发候选武器的队伍 +give_knife = "all" # 配发刀具的队伍 # 基础属性与移动 -health = 120 # 初始生命值 (1~10000,或区间随机 { min = 100, max = 150 }) -armor = 50 # 初始护甲值 (0~255,或区间随机 { min = 0, max = 100 }) -gravity = 1.0 # 重力倍率 (0.0 < g <= 10.0,1.0 为正常重力) -speed = 1.0 # 移速倍率 +health = 120 # 初始生命值 (1~10000 或随机范围 { min = 100, max = 150 }) +armor = 50 # 初始护甲值 (0~1000 或随机范围 { min = 0, max = 100 }) +gravity = 1.0 # 重力倍率 ((0, 10],1.0 为正常重力) +speed = 1.0 # 移速倍率 ((0, 10]) self_push = true # 开启开火自推反冲 # 射击与视角控制 -ammo = "reserve" # 弹药模式 (inherit / reserve / clip / single_shot) +ammo = "reserve" # 弹药规则 (inherit / reserve / clip / single_shot) headshots = "normal" # 爆头规则 (normal / only / disabled) fast_switch = true # 快速切枪开关 -# 特殊玩法机制选开 +# 可选玩法突变示例 +# autostrafe = true # 空中辅助转向加速 +# explosive_bullets = { cooldown_seconds = 1.5, damage = 30, radius = 120 } # 爆炸子弹 +# wall_hang = true # 空中贴墙挂墙 +# grapple = { max_distance = 1000.0, max_speed = 600.0, pull_gain = 4.0 } # 抓钩绳索 # lifesteal = true # 吸血恢复 -# suicide = true # 允许自爆玩法 -# third_person = { distance = 64.0, follow_eyes = true, return_strength = 2.0 } # 第三人称视角 -# bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, bounce = false } # 特殊炸弹 +# third_person = { distance = 64.0, follow_eyes = true, return_strength = 2.0 } # 第三人称 ```
@@ -194,23 +237,23 @@ fast_switch = true # 快速切枪开关 #### 1. 编译 Rust 插件 -编译前请确保安装了 Rust `1.99.1`(可通过仓库内的 `rust-toolchain.toml` 自动匹配)。 +工具链要求:Rust `1.99.1`(由 `rust-toolchain.toml` 自动匹配): ```bash -# 代码格式化检查与 Clippy 静态检查 +# 代码格式化与 Clippy 严格静态检查 cargo fmt --all -- --check cargo clippy --workspace --all-targets --locked -- -D warnings -# 运行全量自动化单元测试 +# 执行全量自动化单元测试 cargo test --workspace --locked -# 编译 Release 发布版本 +# 编译 Release 发布产物 cargo build --release --workspace --locked ``` -#### 2. 编译原生 C++ 扩展 +#### 2. 编译原生 C++ 伴侣扩展 -需要 Python 3.10+、CMake 3.25+ 以及对应平台的 C++20 编译器(MSVC 2022+ 或 GCC 11+): +要求 Python 3.10+、CMake 3.25+ 以及对应平台的 C++20 编译器(MSVC 2022+ 或 GCC 11+): ```bash # 构建原生扩展并输出至 dist/native diff --git a/bindings/s2sdk.pplugin b/bindings/s2sdk.pplugin index a4d2650..cd4894d 100644 --- a/bindings/s2sdk.pplugin +++ b/bindings/s2sdk.pplugin @@ -1,6 +1,6 @@ { "$schema": "https://raw.githubusercontent.com/untrustedmodders/plugify/refs/heads/main/schemas/plugin.schema.json", - "version": "3.0.6", + "version": "3.3.1", "name": "s2sdk", "description": "Provides functionality for other plugins from Source 2 engine", "author": "untrustedmodders", @@ -3494,6 +3494,382 @@ "retType": { "type": "void" } + }, + { + "name": "GetClientKills", + "group": "Clients", + "description": "Retrieves the number of kills for a client.", + "funcName": "GetClientKills", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The index of the player's slot." + } + ], + "retType": { + "type": "int32", + "description": "The number of kills the client has, or 0 if the player slot is invalid." + } + }, + { + "name": "GetClientDeaths", + "group": "Clients", + "description": "Retrieves the number of deaths for a client.", + "funcName": "GetClientDeaths", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The index of the player's slot." + } + ], + "retType": { + "type": "int32", + "description": "The number of deaths the client has, or 0 if the player slot is invalid." + } + }, + { + "name": "GetEventFloat", + "group": "Events", + "description": "Retrieves the float value of a game event's key.", + "funcName": "GetEventFloat", + "paramTypes": [ + { + "name": "event", + "type": "ptr64", + "ref": false, + "description": "A pointer to the IGameEvent object containing event data." + }, + { + "name": "key", + "type": "string", + "ref": false, + "description": "The key for which to retrieve the float value." + } + ], + "retType": { + "type": "float", + "description": "The float value associated with the key." + } + }, + { + "name": "CreateConVarBool", + "group": "Cvars", + "description": "Creates a new boolean console variable.", + "funcName": "CreateConVarBool", + "paramTypes": [ + { + "name": "name", + "type": "string", + "ref": false, + "description": "The name of the console variable." + }, + { + "name": "defaultValue", + "type": "bool", + "ref": false, + "description": "The default value for the console variable." + }, + { + "name": "description", + "type": "string", + "ref": false, + "description": "A brief description of the console variable." + }, + { + "name": "flags", + "type": "int64", + "ref": false, + "description": "Flags that define the behavior of the console variable.", + "enum": "ConVarFlag" + }, + { + "name": "hasMin", + "type": "bool", + "ref": false, + "description": "Indicates if a minimum value is provided." + }, + { + "name": "min", + "type": "bool", + "ref": false, + "description": "The minimum value if hasMin is true." + }, + { + "name": "hasMax", + "type": "bool", + "ref": false, + "description": "Indicates if a maximum value is provided." + }, + { + "name": "max", + "type": "bool", + "ref": false, + "description": "The maximum value if hasMax is true." + } + ], + "retType": { + "type": "uint64", + "description": "A handle to the created console variable data." + } + }, + { + "name": "ChangeClientTeam", + "group": "Clients", + "description": "Changes the player's team.", + "funcName": "ChangeClientTeam", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The index of the player's slot." + }, + { + "name": "team", + "type": "int32", + "ref": false, + "description": "The team index to change the client to.", + "enum": "CSTeam" + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "FakeClientCommand", + "group": "Commands", + "description": "Executes a client command on the server without network communication.", + "funcName": "FakeClientCommand", + "paramTypes": [ + { + "name": "playerSlot", + "type": "int32", + "ref": false, + "description": "The index of the client." + }, + { + "name": "command", + "type": "string", + "ref": false, + "description": "The command to be executed by the client." + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "GetCurrentMap", + "group": "Engine", + "description": "Returns the current map name.", + "funcName": "GetCurrentMap", + "paramTypes": [], + "retType": { + "type": "string", + "description": "A reference to a string where the current map name will be stored." + } + }, + { + "name": "GetGameDirectory", + "group": "Engine", + "description": "Returns the path of the game's directory.", + "funcName": "GetGameDirectory", + "paramTypes": [], + "retType": { + "type": "string", + "description": "A reference to a string where the game directory path will be stored." + } + }, + { + "name": "TraceLine", + "group": "Trace", + "description": "Performs a line trace between two points.", + "funcName": "TraceLine", + "paramTypes": [ + { + "name": "startPos", + "type": "vec3", + "ref": false, + "description": "Trace start position" + }, + { + "name": "endPos", + "type": "vec3", + "ref": false, + "description": "Trace end position" + }, + { + "name": "mask", + "type": "int32", + "ref": false, + "description": "Trace mask" + }, + { + "name": "ignoreHandle", + "type": "int32", + "ref": false, + "description": "Entity handle to ignore during trace" + }, + { + "name": "outPos", + "type": "vec3", + "ref": true, + "description": "Output: position of impact" + }, + { + "name": "outFraction", + "type": "double", + "ref": true, + "description": "Output: fraction of trace completed" + }, + { + "name": "outHit", + "type": "bool", + "ref": true, + "description": "Output: whether a hit occurred" + }, + { + "name": "outEntHit", + "type": "int32", + "ref": true, + "description": "Output: handle of entity hit" + }, + { + "name": "outStartSolid", + "type": "bool", + "ref": true, + "description": "Output: whether trace started inside solid" + } + ], + "retType": { + "type": "bool", + "description": "True if trace hit something, false otherwise" + } + }, + { + "name": "OnEntitySpawned_Register", + "group": "Listeners", + "description": "Register callback to event.", + "funcName": "OnEntitySpawned_Register", + "paramTypes": [ + { + "name": "callback", + "type": "function", + "ref": false, + "description": "Function callback.", + "prototype": "OnEntitySpawnedCallback" + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "OnEntitySpawned_Unregister", + "group": "Listeners", + "description": "Unregister callback to event.", + "funcName": "OnEntitySpawned_Unregister", + "paramTypes": [ + { + "name": "callback", + "type": "function", + "ref": false, + "description": "Function callback.", + "prototype": "OnEntitySpawnedCallback" + } + ], + "retType": { + "type": "void" + } + }, + { + "name": "GetEntSchemaColor", + "group": "Schema", + "description": "Retrieves a color value from an entity's schema.", + "funcName": "GetEntSchemaColor", + "paramTypes": [ + { + "name": "entityHandle", + "type": "int32", + "ref": false, + "description": "The handle of the entity from which the value is to be retrieved." + }, + { + "name": "className", + "type": "string", + "ref": false, + "description": "The name of the class." + }, + { + "name": "memberName", + "type": "string", + "ref": false, + "description": "The name of the schema member." + }, + { + "name": "element", + "type": "int32", + "ref": false, + "description": "Element # (starting from 0) if schema is an array." + } + ], + "retType": { + "type": "vec4", + "description": "A color value at the given schema offset." + } + }, + { + "name": "SetEntSchemaColor", + "group": "Schema", + "description": "Sets a color value in an entity's schema.", + "funcName": "SetEntSchemaColor", + "paramTypes": [ + { + "name": "entityHandle", + "type": "int32", + "ref": false, + "description": "The handle of the entity from which the value is to be retrieved." + }, + { + "name": "className", + "type": "string", + "ref": false, + "description": "The name of the class." + }, + { + "name": "memberName", + "type": "string", + "ref": false, + "description": "The name of the schema member." + }, + { + "name": "value", + "type": "vec4", + "ref": false, + "description": "The color value to set." + }, + { + "name": "changeState", + "type": "bool", + "ref": false, + "description": "If true, change will be sent over the network." + }, + { + "name": "element", + "type": "int32", + "ref": false, + "description": "Element # (starting from 0) if schema is an array." + } + ], + "retType": { + "type": "void", + "description": "A color value at the given schema offset." + } } ], "classes": [], @@ -3612,6 +3988,22 @@ "type": "void", "description": "" } + }, + { + "name": "OnEntitySpawnedCallback", + "funcName": "OnEntitySpawnedCallback", + "description": "Called when an entity is spawned.", + "paramTypes": [ + { + "name": "entityHandle", + "type": "int32", + "description": "The spawned entity handle" + } + ], + "retType": { + "type": "void", + "description": "" + } } ], "enums": [ diff --git a/config/funrounds.example.toml b/config/funrounds.example.toml index b1ec3de..db4fca0 100644 --- a/config/funrounds.example.toml +++ b/config/funrounds.example.toml @@ -63,6 +63,10 @@ diagnostics = false [i18n] default_language = "zh-CN" +# [weapon_groups]:可选命名武器组,模式用 weapons = "@basic" 引用。 +# [weapon_groups] +# basic = ["famas", "p250"] + # [defaults]:全局默认模板(仅接受玩法字段;模式内单独设置优先) # 可用 false 显式重置可选继承项(如 color, bomb, respawn 等) # 示例: @@ -80,11 +84,11 @@ enabled = true name_key = "mode.example.name" description_key = "mode.example.description" -# weapons:受支持的 CS2 装备候选列表(按主武器、副武器和额外装备抽取;不含刀具,刀具由 give_knife 配置) -weapons = ["weapon_famas", "weapon_p250"] +# weapons:按主武器、副武器和额外装备抽取。使用不带 weapon_ 前缀的物品 ID;刀具由 give_knife 配发。 +weapons = ["famas", "p250"] # health:初始生命(整数 1~10000,或随机范围 { min = 100, max = 150 },默认 100) health = 120 -# armor:初始护甲(整数 0~255,或随机范围 { min = 0, max = 100 },默认 0) +# armor:初始护甲(整数 0~1000,或随机范围 { min = 0, max = 100 },默认 0) armor = 50 # gravity:重力倍率((0, 10],1.0 为正常重力,<1.0 降低重力) gravity = 1.0 @@ -108,13 +112,15 @@ give_weapons = "all" # ammo = "inherit" # self_damage:开火自伤设置(kind = "miss_penalty" 未命中扣血 / kind = "native", amount = 0.1 每次自扣伤害) # self_damage = { kind = "miss_penalty" } -# weapon_damage:特定武器伤害倍率(电击枪与刀具可分别设置,默认 1.0) +# weapon_damage:按物品 ID 设置伤害倍率(有限非负数,未指定的物品用 1.0) # weapon_damage = { taser = 1.0, knife = 1.0 } -# taser_charge:电击枪充能冷却时间(秒,需 weapons 包含 weapon_taser) +# taser_charge:电击枪充能冷却时间(秒,需 weapons 包含 taser) # taser_charge = 12.0 # bunnyhop:开启自动连跳及移动参数优化(省略时不覆盖服务端设置) # bunnyhop = true +# autostrafe:在空中辅助转向加速(默认 false) +# autostrafe = true # friction:地面摩擦力参数(有限非负数,省略时不覆盖服务端设置) # friction = 2.0 # no_spread:移除武器散布(省略时不覆盖服务端设置) @@ -125,8 +131,9 @@ give_weapons = "all" # recoil_view = 1.0 # fast_switch:快速切枪开关(默认 false) # fast_switch = true -# replenish:投掷后自动补充的手雷类型列表(可选 he / flash / smoke / decoy / molotov / incendiary) -# replenish = ["he"] +# replenish:投掷后自动补充,所列物品也需加入 weapons。 +# 可选 hegrenade / flashbang / smokegrenade / decoy / molotov / incgrenade。 +# replenish = ["hegrenade"] # random_loadout:从候选池独立随机抽取配装(与 kill_loadout 互斥) # random_loadout = true @@ -134,7 +141,7 @@ give_weapons = "all" # suicide = true # random_damage:是否开启浮动随机战斗伤害(默认 false) # random_damage = true -# kill_loadout:击杀敌人后自动升级换枪(kill_loadout_start 可设 "glock" 或 "random") +# kill_loadout:击杀敌人后自动换枪;初始配装可选 "random" 或 "glock"(需在候选中加入 glock)。 # kill_loadout = true # kill_loadout_start = "random" # lifesteal:击中敌人吸血恢复生命与护甲(默认 false) @@ -156,7 +163,7 @@ give_weapons = "all" # 可用内联表设置: # bomb = { kind = "native", plant_time = 3.0, explode_time = 45.0, defuse_kit_time = 5.0, defuse_time = 10.0, bounce = false } -# dodgeball:诱饵弹命中触发躲避球直接伤害(需 weapons 包含 weapon_decoy) +# dodgeball:诱饵弹命中触发躲避球直接伤害(需 weapons 包含 decoy) # dodgeball = true # throwing_knives:右键投掷飞刀及弹射判定(需配发刀具) # throwing_knives = true @@ -166,7 +173,7 @@ give_weapons = "all" # no_scope = true # fov:设定玩家视野角度(整数 1~179) # fov = 90 -# hide_hud:隐藏指定 HUD 元素列表(可选 "radar", "crosshair") +# hide_hud:隐藏指定 HUD 元素(可选 "all"、"radar"、"crosshair";勿与旧键 hide_radar 同时填写) # hide_hud = ["radar", "crosshair"] # hide_crosshair_after:延迟隐藏准星时间(秒,需搭配 hide_hud 中的 crosshair 使用) # hide_crosshair_after = 1.0 @@ -179,10 +186,10 @@ give_weapons = "all" # health_decay = true # self_push:开火产生自身反冲推力(可通过指令 fr_knock 切换模式) # self_push = true -# periodic_speed:移速周期性波浪起伏变化(默认 false) -# periodic_speed = true -# periodic_gravity:重力周期性高低起伏变化(默认 false) -# periodic_gravity = true +# periodic_speed / periodic_gravity:每隔指定秒数随机更新倍率。 +# true 使用内置分布,false 关闭;自定义时用正数列表 values 或正数闭区间 min/max。 +# periodic_speed = { interval_seconds = 8.0, values = [0.9, 1.1] } +# periodic_gravity = { interval_seconds = 8.0, min = 0.8, max = 1.2 } # c4_count:进攻方(T)普通 C4 数量上限(整数 0~255;设为 0 完全禁用普通 C4) # c4_count = 1 @@ -204,13 +211,13 @@ give_weapons = "all" # fall_damage_scale = 1.0 # 坠落伤害倍率 # time_scale = 1.0 # 游戏全局时间流速倍率 # ground_acceleration = 5.0 # 地面加速度 -# ground_reverse = 5.0 # 地面输入反向加速度(倒车行走) +# ground_reverse = 5.0 # 地面输入反向加速度;需省略 ground_acceleration 或将其设为 0 # round_money_floor = 1000 # 每回合保底现金 # money_income = { interval = 10.0, amount = 100 } # 定期发放被动收入 # buy_access = "all" # 允许购买物品的队伍 # buy_anywhere = "all" # 允许在地图任意位置购买的队伍 # shoot_dropped_grenades = true # 允许射击引爆掉落的手雷 -# hide_player_identification = true# 隐藏玩家瞄准识别信息 +# hide_player_identification = true # 隐藏玩家瞄准识别信息 # third_person:第三人称视角 # third_person = { distance = 64.0, follow_eyes = true, clip_camera_offset = true, return_strength = 2.0 } @@ -225,3 +232,26 @@ give_weapons = "all" # health_curve:自定义生命缩放曲线(覆盖内置 health_damage / health_speed 曲线) # health_decay_settings:自定义额外生命衰减速率与保底百分比 + +# 下列能力各自可选;每一行都是独立示例,不需要一起启用。 +# damage_multiplier = 1.1 # 通用伤害倍率(有限非负数) +# inferno_damage = 12.0 # 地面燃烧伤害(有限非负数) +# teamkill_limit = 2 # 触发队杀惩罚的次数阈值(正整数) +# death_explosion = { t = 1, ct = 0 } # 每回合从各队选出死亡时爆炸的玩家人数上限;整数 0~255,0 关闭 +# explosive_bullets = { cooldown_seconds = 1.5, damage = 30, radius = 120 } # 子弹命中爆炸;伤害和半径支持正整数或区间 +# hegrenade_impulse = { impulse = 220.0 } # HE 爆炸施加推力(有限非负数) +# proximity_fuse = { radius = 128.0, delay_seconds = 0.5, grenades = ["hegrenade"] } # 接近敌人时触发引信;不支持诱饵弹 +# he_guidance = { range = 1000.0, turn_rate_degrees_per_second = 90.0, max_speed = 700.0, max_guidance_seconds = 2.0 } # HE 追踪,参数均为正数 +# wall_hang = true # 空中贴墙并按住跳跃时挂墙 +# grapple = { max_distance = 1000.0, max_speed = 600.0, pull_gain = 4.0 } # 使用键拉向瞄准点,参数均为正数 +# friendly_fire_heal = { kind = "fixed", amount = 8 } # 友军命中转治疗;或用 kind = "damage_ratio" 和 ratio +# regeneration = { delay_seconds = 4.0, interval_seconds = 2.0, heal = 3 } # 脱离战斗后延迟并定时回血 +# chicken_aura = { radius = 100.0, interval_seconds = 2.0, heal_percent = 2.0 } # 普通鸡附近定时回血,需配置普通鸡生态 +# healing_cap_base_multiple = 1.2 # 上述治疗能力使用的初始生命上限倍率(有限正数) +# medical_smoke = true # 烟雾区域内治疗友军 +# trampoline = true # 在受支持地图的固定区域内弹起玩家 +# dont_stop = { minimum_horizontal_speed = 60.0, grace_seconds = 3.0, damage_interval_seconds = 1.0, damage = 2 } # 移速过低时扣血 +# hot_floor = { grounded_seconds = 3.0, damage_interval_seconds = 1.0, damage = 2, ignite_after_seconds = 6.0 } # 持续站地扣血,久留则点燃 +# weapon_on_fire = { chance = 0.15, switch_weight = 2, drop_weight = 1, cooldown_seconds = 1.0 } # 开火后按概率切枪或掉枪;权重至少一个为正 +# long_flash = { duration_multiplier = 1.5, duration_cap_seconds = 8.0 } # 延长闪光效果,不缩短原生时长 +# big_head = { min_scale = 0.9, max_scale = 1.3 } # 头部缩放区间,倍率为正且 min_scale <= max_scale diff --git a/config/i18n/en.toml b/config/i18n/en.toml index 3439122..9991760 100644 --- a/config/i18n/en.toml +++ b/config/i18n/en.toml @@ -18,9 +18,10 @@ "command.next" = "[FunRounds] Next mode: {mode}" "command.no_config" = "[FunRounds] No valid configuration found." "command.reload" = "[FunRounds] Configuration and texts queued for the next round." -"command.usage" = "Usage: fr_status | fr_list | fr_next | fr_reload | fr_enable <0|1> | fr_info | fr_help | fr_knock [0|1|2] | fr_chicken | fr_healthshot | fr_nvg | fr_wire " +"command.usage" = "Usage: fr_status | fr_list | fr_next | fr_next id | fr_reload | fr_enable <0|1> | fr_info | fr_help | fr_knock [0|1|2] | fr_chicken | fr_healthshot | fr_nvg | fr_wire " "command.wire_usage" = "Usage: fr_wire " "config.unavailable" = "Configuration unavailable." +"death_explosion.armed" = "[FunRounds] You are rigged to explode when you die this life!" "feedback.error" = "[FunRounds] Error: {error}" "healthshot.already_owned" = "You already have a healthshot." "healthshot.pending" = "Healthshot transaction in progress." @@ -66,6 +67,7 @@ "team.finished" = "[FunRounds] Team deathmatch finished: T {t} : {ct} CT" "team.info" = "\nScore: T {t} : {ct} CT\nTime remaining: {seconds}s" "team.waiting" = "\nScore: T 0 : 0 CT\nTime: starts after freeze time" +"trampoline.launched" = "Trampoline launched!" "warmup.description" = "Warmup round" "warmup.name" = "Warmup" "welcome" = "[FunRounds] Plugin version {version} loaded." diff --git a/config/i18n/zh-CN.toml b/config/i18n/zh-CN.toml index 96280d2..3bccc5d 100644 --- a/config/i18n/zh-CN.toml +++ b/config/i18n/zh-CN.toml @@ -18,9 +18,10 @@ "command.next" = "[FunRounds] 下一模式:{mode}" "command.no_config" = "[FunRounds] 未找到有效配置" "command.reload" = "[FunRounds] 配置与多语言文本已排队,将于下一回合生效" -"command.usage" = "用法:fr_status | fr_list | fr_next | fr_reload | fr_enable <0|1> | fr_info | fr_help | fr_knock [0|1|2] | fr_chicken | fr_healthshot | fr_nvg | fr_wire " +"command.usage" = "用法:fr_status | fr_list | fr_next | fr_next id | fr_reload | fr_enable <0|1> | fr_info | fr_help | fr_knock [0|1|2] | fr_chicken | fr_healthshot | fr_nvg | fr_wire " "command.wire_usage" = "用法:fr_wire " "config.unavailable" = "配置暂不可用" +"death_explosion.armed" = "[FunRounds] 你被绑上了炸药:本条命死亡时会引爆!" "feedback.error" = "[FunRounds] 错误:{error}" "healthshot.already_owned" = "已持有医疗针,无需重复购买" "healthshot.pending" = "医疗针事务处理中" @@ -66,6 +67,7 @@ "team.finished" = "[FunRounds] 团队死斗结束 T {t} : {ct} CT" "team.info" = "\n比分:T {t} : {ct} CT\n剩余时间:{seconds}s" "team.waiting" = "\n比分:T 0 : 0 CT\n剩余时间:计时未开始(冻结结束后开始)" +"trampoline.launched" = "蹦床触发!" "warmup.description" = "热身回合" "warmup.name" = "热身" "welcome" = "[FunRounds] 插件版本 {version} 已加载" diff --git a/crates/funrounds-core/assets/i18n/en.toml b/crates/funrounds-core/assets/i18n/en.toml new file mode 100644 index 0000000..61f2266 --- /dev/null +++ b/crates/funrounds-core/assets/i18n/en.toml @@ -0,0 +1,84 @@ +[messages] +"c4.owned" = "[FunRounds] You already have C4." +"c4.owned_suicide" = "[FunRounds] You already have C4; inspect it to start suicide." +"c4.pending" = "A C4 transaction is in progress." +"c4.purchased" = "[FunRounds] C4 purchased." +"c4.purchased_inspect" = "[FunRounds] C4 purchased; inspect it to start suicide." +"c4.purchased_start" = "[FunRounds] C4 purchased; suicide requested." +"c4.request" = "[FunRounds] Buying C4 for {price} cash." +"c4.t_required" = "Only Ts can buy C4." +"c4.unavailable" = "C4 purchase or suicide is unavailable now." +"chicken.pending" = "A chicken transaction is in progress." +"chicken.position_invalid" = "Cannot place a chicken at your current position." +"chicken.purchased" = "[FunRounds] Chicken purchased." +"chicken.request" = "[FunRounds] Buying a chicken for {price} cash." +"chicken.team_required" = "Join a playing team to buy a chicken." +"chicken.unavailable" = "Chicken purchases are unavailable." +"command.enabled" = "[FunRounds] enabled={enabled}; activation begins at the next round" +"command.next" = "[FunRounds] Next mode={mode}" +"command.no_config" = "[FunRounds] No valid active configuration." +"command.reload" = "[FunRounds] Valid configuration and texts queued for the next round." +"command.usage" = "Usage: fr_status | fr_list | fr_next | fr_next id | fr_reload | fr_enable <0|1> | fr_info | fr_help | fr_knock [0|1|2] | fr_chicken | fr_healthshot | fr_nvg | fr_wire " +"command.wire_usage" = "Usage: fr_wire " +"config.unavailable" = "Configuration is unavailable." +"death_explosion.armed" = "[FunRounds] You are rigged to explode when you die this life!" +"feedback.error" = "[FunRounds] Error: {error}" +"healthshot.already_owned" = "You already have a healthshot." +"healthshot.pending" = "A healthshot transaction is in progress." +"healthshot.purchased" = "[FunRounds] Healthshot purchased." +"healthshot.request" = "[FunRounds] Buying a healthshot for {price} cash." +"healthshot.team_required" = "Join a playing team to buy a healthshot." +"healthshot.unavailable" = "Healthshot purchases are unavailable." +"help.body" = "fr_info / !info / !frinfo — Show the current mode\nfr_help / !help / !frhelp — Show help\nfr_knock [0|1|2] / !knock [0|1|2] — Self-push: 0 off, 1 ground and air, 2 airborne only (default); omit the value to cycle\nfr_c4 / !c4 — T players can buy C4 at the configured cash price when ordinary purchases are allowed\nfr_suicide / !suicide — Start a suicide blast with owned or newly purchased C4 when enabled\nfr_chicken / !chicken — Buy one ordinary chicken at the configured cash price\nfr_healthshot / !healthshot — Buy one healthshot at the configured cash price\nfr_nvg / !nvg — Toggle night vision\nfr_wire / !wire — Choose a plant or defuse wire; otherwise keep the mode's normal timer" +"info.mode" = "State: {phase}\nMode: {id} {name}\nDescription: {description}" +"info.ordinary" = "Current mode: ordinary gameplay" +"info.shield" = "\nActual shield: {shield}" +"knock.airborne" = "Airborne only" +"knock.always" = "Ground and air" +"knock.off" = "Off" +"mode.chat.id" = "Round ID: {id}" +"mode.console" = "[FunRounds] Mode name: {name}\n[FunRounds] Mode ID: {id}" +"mode.example.description" = "Demonstrates basic equipment and player attributes" +"mode.example.name" = "Generic example" +"nvg.alive_required" = "Night vision requires an alive in-game player." +"nvg.disabled" = "[FunRounds] Night vision disabled." +"nvg.enabled" = "[FunRounds] Night vision enabled." +"phase.ordinary" = "Ordinary gameplay" +"phase.preparing" = "Preparing" +"phase.running" = "Running" +"phase.warmup" = "Warmup" +"player.alive_required" = "An alive in-game player is required." +"player.life_pending" = "Your current life is not ready yet." +"preference.failed" = "Self-push: {value} (save failed: {error})" +"preference.queued" = "Self-push: {value} (saved)." +"preference.save_failed" = "Failed to save self-push preference: {error}" +"preference.session" = "Self-push: {value} (this session only)." +"preference.unchanged" = "Self-push: {value} (unchanged)." +"public.unavailable" = "FunRounds public actions are unavailable." +"purchase.c4_t_only" = "Only Ts can buy C4." +"purchase.cancelled" = "Purchase cancelled." +"purchase.debit" = "Cash charge failed: {error}" +"purchase.insufficient" = "Buying {item} requires {price} cash." +"purchase.item.c4" = "C4" +"purchase.item.chicken" = "chicken" +"purchase.item.healthshot" = "healthshot" +"purchase.ownership_changed" = "Delivery failed; cash ownership changed, refund not completed: {error}" +"purchase.refund_failed" = "Delivery failed; refund failed: {error}" +"purchase.refunded" = "Delivery failed; cash refunded: {error}" +"suicide.ct_broadcast" = "[FunRounds] A CT is destroying C4!" +"suicide.start_broadcast" = "[FunRounds] Suicide started; explosion in five seconds!" +"suicide.started" = "Suicide has already started." +"team.finished" = "[FunRounds] Team match finished T {t} : {ct} CT" +"team.info" = "\nScore: T {t} : {ct} CT\nTime remaining: {seconds}s" +"team.waiting" = "\nScore: T 0 : 0 CT\nTime: starts after freeze time" +"trampoline.launched" = "Trampoline launched!" +"warmup.description" = "Warmup round" +"warmup.name" = "Warmup" +"welcome" = "[FunRounds] Plugin version {version} loaded." +"wire.ct_required" = "Only the current CT defuser can cut a wire." +"wire.defuse_help" = "[FunRounds] Cut Blue / Yellow / Red / Green using !wire or fr_wire ; otherwise keep the normal timer." +"wire.defused" = "[FunRounds] Correct {wire} wire; native quick defuse requested." +"wire.exploded" = "[FunRounds] Wrong {wire} wire; native explosion requested." +"wire.no_defuse" = "You have not started defusing this supported native C4." +"wire.plant_help" = "[FunRounds] Choose Blue / Yellow / Red / Green with !wire or fr_wire ; otherwise random." +"wire.plant_selected" = "[FunRounds] Planting wire selected: {wire}." diff --git a/crates/funrounds-core/assets/i18n/zh-CN.toml b/crates/funrounds-core/assets/i18n/zh-CN.toml new file mode 100644 index 0000000..5d43a9a --- /dev/null +++ b/crates/funrounds-core/assets/i18n/zh-CN.toml @@ -0,0 +1,84 @@ +[messages] +"c4.owned" = "[FunRounds] 已有C4,无需重复购买" +"c4.owned_suicide" = "[FunRounds] 已有C4,无需重复购买;使用C4按F可启动自爆" +"c4.pending" = "C4事务正在处理" +"c4.purchased" = "[FunRounds] C4购买成功" +"c4.purchased_inspect" = "[FunRounds] C4购买成功;按F启动自爆" +"c4.purchased_start" = "[FunRounds] C4购买成功并开启自爆" +"c4.request" = "[FunRounds] 正在购买C4,价格{price}现金" +"c4.t_required" = "只有T可以购买C4" +"c4.unavailable" = "现在不能购买C4或自爆" +"chicken.pending" = "正在处理鸡" +"chicken.position_invalid" = "当前位置无法买鸡" +"chicken.purchased" = "[FunRounds] 鸡购买成功" +"chicken.request" = "[FunRounds] 正在购买鸡,价格{price}现金" +"chicken.team_required" = "现在不能购买鸡" +"chicken.unavailable" = "鸡购买当前不可用" +"command.enabled" = "[FunRounds] enabled={enabled};下一回合开始应用" +"command.next" = "[FunRounds] 下一模式={mode}" +"command.no_config" = "[FunRounds] 没有有效的配置" +"command.reload" = "[FunRounds] 有效配置和文本已排队,将于下一回合应用" +"command.usage" = "用法:fr_status | fr_list | fr_next | fr_next id | fr_reload | fr_enable <0|1> | fr_info | fr_help | fr_knock [0|1|2] | fr_chicken | fr_healthshot | fr_nvg | fr_wire " +"command.wire_usage" = "用法:fr_wire " +"config.unavailable" = "配置不可用" +"death_explosion.armed" = "[FunRounds] 你被绑上了炸药:本条命死亡时会引爆!" +"feedback.error" = "[FunRounds] 错误:{error}" +"healthshot.already_owned" = "已有医疗针,无需重复购买" +"healthshot.pending" = "医疗针事务正在处理" +"healthshot.purchased" = "[FunRounds] 医疗针购买成功" +"healthshot.request" = "[FunRounds] 正在购买医疗针,价格{price}现金" +"healthshot.team_required" = "现在不能购买医疗针" +"healthshot.unavailable" = "医疗针购买当前不可用" +"help.body" = "fr_info / !info / !frinfo — 查看当前模式\nfr_help / !help / !frhelp — 查看帮助\nfr_knock [0|1|2] / !knock [0|1|2] — 开枪击退:0关闭/1地面及空中/2仅空中(默认);无参数依次切换\nfr_c4 / !c4 — T队在允许普通购买时,按配置现金价格购买C4\nfr_suicide / !suicide — 允许自爆时,使用已有C4或购买后自爆\nfr_chicken / !chicken — 购买一只普通鸡,使用配置现金价格\nfr_healthshot / !healthshot — 购买一支医疗针,使用配置现金价格\nfr_nvg / !nvg — 切换夜视仪\nfr_wire / !wire — 选安包剪线或当前拆弹剪线;不选则不使用此机制" +"info.mode" = "状态:{phase}\n模式:{id} {name}\n说明:{description}" +"info.ordinary" = "当前模式:普通游戏" +"info.shield" = "\n实际护盾:{shield}" +"knock.airborne" = "仅空中" +"knock.always" = "地面及空中" +"knock.off" = "关闭" +"mode.chat.id" = "回合编号 : {id}" +"mode.console" = "[FunRounds] 回合名称 : {name}\n[FunRounds] 回合编号 : {id}" +"mode.example.description" = "演示基础配装与玩家属性" +"mode.example.name" = "通用示例" +"nvg.alive_required" = "你死了,无法使用夜视仪" +"nvg.disabled" = "[FunRounds] 夜视仪已关闭" +"nvg.enabled" = "[FunRounds] 夜视仪已开启" +"phase.ordinary" = "普通游戏" +"phase.preparing" = "准备" +"phase.running" = "进行" +"phase.warmup" = "热身" +"player.alive_required" = "你死了,无法使用" +"player.life_pending" = "角色未就绪,暂无法使用" +"preference.failed" = "开枪击退:{value}(保存失败:{error})" +"preference.queued" = "开枪击退:{value}" +"preference.save_failed" = "开枪击退偏好保存失败:{error}" +"preference.session" = "开枪击退:{value}(仅本次会话)" +"preference.unchanged" = "开枪击退:{value}(设置未更改)" +"public.unavailable" = "FunRounds公共行为当前不可用" +"purchase.c4_t_only" = "只有T可以购买C4" +"purchase.cancelled" = "购买已取消" +"purchase.debit" = "现金扣款失败:{error}" +"purchase.insufficient" = "购买{item}需要{price}现金" +"purchase.item.c4" = "C4" +"purchase.item.chicken" = "鸡" +"purchase.item.healthshot" = "医疗针" +"purchase.ownership_changed" = "发放失败,现金所有权已改变,退款未完成:{error}" +"purchase.refund_failed" = "发放失败,退款失败:{error}" +"purchase.refunded" = "发放失败,已退还现金:{error}" +"suicide.ct_broadcast" = "[FunRounds] CT正在销毁C4!" +"suicide.start_broadcast" = "[FunRounds] 自爆已启动,五秒后爆炸!" +"suicide.started" = "已启动自爆" +"team.finished" = "[FunRounds] 团队竞技结束 T {t} : {ct} CT" +"team.info" = "\n比分:T {t} : {ct} CT\n剩余时间:{seconds}s" +"team.waiting" = "\n比分:T 0 : 0 CT\n剩余时间:计时未开始(冻结结束后开始)" +"trampoline.launched" = "蹦床触发!" +"warmup.description" = "热身回合" +"warmup.name" = "热身" +"welcome" = "[FunRounds] FunRounds!插件版本 {version} 已加载" +"wire.ct_required" = "剪线需要是CT才可以" +"wire.defuse_help" = "[FunRounds] 选择正确的线可以快速拆包:蓝Blue/黄Yellow/红Red/绿Green;输入 !wire 或 fr_wire " +"wire.defused" = "[FunRounds] {wire} 剪线中" +"wire.exploded" = "[FunRounds] {wire} 线错了" +"wire.no_defuse" = "还没有开始拆包" +"wire.plant_help" = "[FunRounds] 安包时可选剪线颜色:蓝Blue/黄Yellow/红Red/绿Green;输入 !wire 或 fr_wire ;不选则随机。" +"wire.plant_selected" = "[FunRounds] 已选择安包剪线颜色 {wire}。" diff --git a/crates/funrounds-core/src/abilities.rs b/crates/funrounds-core/src/abilities.rs new file mode 100644 index 0000000..565ce53 --- /dev/null +++ b/crates/funrounds-core/src/abilities.rs @@ -0,0 +1,830 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use crate::AttributeValue; +use crate::GrenadeKind; +use serde::Deserialize; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum HealingAmount { + Fixed(i32), + Percent(f32), +} + +impl HealingAmount { + /// Converts configured healing to whole HP using the current life's spawn health. + /// Percentage values use human-readable percentage points (e.g. 5.0 means 5%). + pub fn amount(self, base_health: i32) -> Option { + match self { + Self::Fixed(amount) => (amount > 0).then_some(amount), + Self::Percent(percent) if base_health > 0 && finite_positive(percent) => { + let amount = (f64::from(base_health) * f64::from(percent) / 100.0).floor(); + (amount >= 1.0).then_some(amount.min(f64::from(i32::MAX)) as i32) + } + Self::Percent(_) => None, + } + } + + fn validate(self) -> Result<(), &'static str> { + match self { + Self::Fixed(amount) if amount > 0 => Ok(()), + Self::Percent(percent) if finite_positive(percent) => Ok(()), + Self::Fixed(_) => Err("heal must be a positive integer"), + Self::Percent(_) => Err("heal_percent must be a positive finite percentage"), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ExplosiveBulletsSettings { + pub cooldown_seconds: f32, + pub damage: AttributeValue, + pub radius: AttributeValue, +} + +impl Default for ExplosiveBulletsSettings { + fn default() -> Self { + Self { + cooldown_seconds: 1.0, + damage: AttributeValue::Range(crate::AttributeRange { min: 75, max: 180 }), + radius: AttributeValue::Range(crate::AttributeRange { min: 225, max: 450 }), + } + } +} + +impl ExplosiveBulletsSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !self.cooldown_seconds.is_finite() || self.cooldown_seconds < 0.0 { + return Err("explosive_bullets needs a finite nonnegative cooldown_seconds"); + } + if !self.damage.validate(1, u16::MAX) || !self.radius.validate(1, u16::MAX) { + return Err("explosive_bullets damage and radius must be positive fixed values or ordered ranges"); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HeGrenadeImpulseSettings { + pub impulse: f32, +} + +impl Default for HeGrenadeImpulseSettings { + fn default() -> Self { + Self { impulse: 300.0 } + } +} + +impl HeGrenadeImpulseSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !self.impulse.is_finite() || self.impulse < 0.0 { + return Err("hegrenade_impulse impulse must be finite and nonnegative"); + } + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ProximityFuseSettings { + pub radius: f32, + pub delay_seconds: f32, + pub grenades: Vec, +} + +impl Default for ProximityFuseSettings { + fn default() -> Self { + Self { + radius: 200.0, + delay_seconds: 0.0, + grenades: vec![ + GrenadeKind::He, + GrenadeKind::Flash, + GrenadeKind::Smoke, + GrenadeKind::Molotov, + GrenadeKind::Incendiary, + ], + } + } +} + +impl ProximityFuseSettings { + pub fn validate(&self) -> Result<(), &'static str> { + if !finite_positive(self.radius) { + return Err("proximity_fuse radius must be positive and finite"); + } + if !self.delay_seconds.is_finite() || self.delay_seconds < 0.0 { + return Err("proximity_fuse delay_seconds must be finite and non-negative"); + } + if self.grenades.is_empty() { + return Err("proximity_fuse grenades must contain at least one supported grenade type"); + } + if self.grenades.contains(&GrenadeKind::Decoy) { + return Err("proximity_fuse does not support decoy grenades"); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GrappleSettings { + pub max_distance: f32, + pub max_speed: f32, + pub pull_gain: f32, +} + +impl Default for GrappleSettings { + fn default() -> Self { + Self { + max_distance: 32768.0, + max_speed: 800.0, + pull_gain: 6.0, + } + } +} + +impl GrappleSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !finite_positive(self.max_distance) || !finite_positive(self.max_speed) || !finite_positive(self.pull_gain) { + return Err("grapple max_distance, max_speed and pull_gain must be positive and finite"); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HeGuidanceSettings { + pub range: f32, + pub turn_rate_degrees_per_second: f32, + pub max_speed: f32, + pub max_guidance_seconds: f32, +} + +impl Default for HeGuidanceSettings { + fn default() -> Self { + Self { + range: 2400.0, + turn_rate_degrees_per_second: 120.0, + max_speed: 1200.0, + max_guidance_seconds: 8.0, + } + } +} + +impl HeGuidanceSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !finite_positive(self.range) + || !finite_positive(self.turn_rate_degrees_per_second) + || !finite_positive(self.max_speed) + || !finite_positive(self.max_guidance_seconds) + { + return Err("he_guidance range, turn_rate_degrees_per_second, max_speed and max_guidance_seconds must be positive and finite"); + } + Ok(()) + } +} + +/// Whether a trace result qualifies as an airborne wall contact for wall hang. +/// Trace reach, entity identity and the movement hull are checked by the adapter. +pub fn wall_hang_contact_eligible( + is_walk: bool, + airborne: bool, + jump_held: bool, + hit_world: bool, + start_solid: bool, + gap: f32, + normal_z: f32, +) -> bool { + is_walk + && airborne + && jump_held + && hit_world + && !start_solid + && gap.is_finite() + && (0.0..=0.75).contains(&gap) + && normal_z.is_finite() + && normal_z.abs() <= 0.25 +} + +/// Turns an existing projectile velocity toward a target direction without adding speed. +/// The adapter supplies game-time delta; a nonpositive delta permits speed capping but no turn. +pub fn turn_projectile_velocity( + current_velocity: [f32; 3], + target_direction: [f32; 3], + delta_seconds: f32, + settings: HeGuidanceSettings, +) -> Option<[f32; 3]> { + settings.validate().ok()?; + if current_velocity.iter().chain(target_direction.iter()).any(|value| !value.is_finite()) || !delta_seconds.is_finite() { + return None; + } + let current_speed = length(current_velocity); + let target_length = length(target_direction); + if !current_speed.is_finite() || !target_length.is_finite() || target_length <= f32::EPSILON { + return None; + } + let speed = current_speed.min(settings.max_speed); + if speed <= f32::EPSILON { + return Some([0.0; 3]); + } + let direction = scale(current_velocity, 1.0 / current_speed); + let target = scale(target_direction, 1.0 / target_length); + let angle = dot(direction, target).clamp(-1.0, 1.0).acos(); + let max_turn = if delta_seconds > 0.0 { + (degrees_to_radians(settings.turn_rate_degrees_per_second) * delta_seconds).min(std::f32::consts::PI) + } else { + 0.0 + }; + let turned = if angle <= max_turn || angle <= f32::EPSILON { + target + } else if max_turn <= 0.0 { + direction + } else { + let axis = cross(direction, target); + let axis_length = length(axis); + let axis = if axis_length > f32::EPSILON { + scale(axis, 1.0 / axis_length) + } else { + // Antiparallel vectors have no unique turn axis; choose a stable perpendicular. + let reference = if direction[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; + let perpendicular = cross(direction, reference); + scale(perpendicular, 1.0 / length(perpendicular)) + }; + let radians = max_turn.min(angle); + let (sin, cos) = radians.sin_cos(); + let axis_cross_direction = cross(axis, direction); + let projection = dot(axis, direction); + [ + direction[0] * cos + axis_cross_direction[0] * sin + axis[0] * projection * (1.0 - cos), + direction[1] * cos + axis_cross_direction[1] * sin + axis[1] * projection * (1.0 - cos), + direction[2] * cos + axis_cross_direction[2] * sin + axis[2] * projection * (1.0 - cos), + ] + }; + Some(scale(turned, speed)) +} + +fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn length(value: [f32; 3]) -> f32 { + dot(value, value).sqrt() +} + +fn scale(value: [f32; 3], scalar: f32) -> [f32; 3] { + [value[0] * scalar, value[1] * scalar, value[2] * scalar] +} + +fn degrees_to_radians(degrees: f32) -> f32 { + degrees * std::f32::consts::PI / 180.0 +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FriendlyFireHealSettings { + pub kind: FriendlyFireHealKind, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum FriendlyFireHealKind { + Fixed { amount: u16 }, + DamageRatio { ratio: f32 }, +} + +impl Default for FriendlyFireHealSettings { + fn default() -> Self { + Self { + kind: FriendlyFireHealKind::Fixed { amount: 10 }, + } + } +} + +impl FriendlyFireHealSettings { + pub fn validate(self) -> Result<(), &'static str> { + match self.kind { + FriendlyFireHealKind::Fixed { amount: 0 } => Err("friendly_fire_heal fixed amount must be positive"), + FriendlyFireHealKind::Fixed { .. } => Ok(()), + FriendlyFireHealKind::DamageRatio { ratio } if finite_positive(ratio) => Ok(()), + FriendlyFireHealKind::DamageRatio { .. } => Err("friendly_fire_heal ratio must be positive and finite"), + } + } + + /// Returns whole HP: fixed amount or floor(ratio × accumulated direct damage). + pub fn healing(self, damage_sum: f64) -> i32 { + match self.kind { + FriendlyFireHealKind::Fixed { amount } => i32::from(amount), + FriendlyFireHealKind::DamageRatio { ratio } if damage_sum.is_finite() && damage_sum > 0.0 && finite_positive(ratio) => { + (damage_sum * f64::from(ratio)).floor().clamp(0.0, f64::from(i32::MAX)) as i32 + } + FriendlyFireHealKind::DamageRatio { .. } => 0, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RegenerationSettings { + pub delay_seconds: f32, + pub interval_seconds: f32, + pub heal: HealingAmount, +} + +impl Default for RegenerationSettings { + fn default() -> Self { + Self { + delay_seconds: 5.0, + interval_seconds: 1.0, + heal: HealingAmount::Fixed(2), + } + } +} + +impl RegenerationSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !finite_positive(self.delay_seconds) || !finite_positive(self.interval_seconds) { + return Err("regeneration needs positive finite delays"); + } + self.heal.validate() + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ChickenAuraSettings { + pub radius: f32, + pub interval_seconds: f32, + pub heal: HealingAmount, +} + +impl Default for ChickenAuraSettings { + fn default() -> Self { + Self { + radius: 200.0, + interval_seconds: 1.0, + heal: HealingAmount::Fixed(3), + } + } +} + +impl ChickenAuraSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !finite_positive(self.radius) || !finite_positive(self.interval_seconds) { + return Err("chicken_aura needs positive finite radius and interval"); + } + self.heal.validate() + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DontStopSettings { + pub minimum_horizontal_speed: f32, + pub grace_seconds: f32, + pub damage_interval_seconds: f32, + pub damage: i32, +} + +impl Default for DontStopSettings { + fn default() -> Self { + Self { + minimum_horizontal_speed: 20.0, + grace_seconds: 1.5, + damage_interval_seconds: 1.0, + damage: 5, + } + } +} + +impl DontStopSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !finite_nonnegative(self.minimum_horizontal_speed) + || !finite_nonnegative(self.grace_seconds) + || !finite_positive(self.damage_interval_seconds) + || self.damage <= 0 + { + return Err("dont_stop needs finite nonnegative speed/grace, a positive interval and positive damage"); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HotFloorSettings { + pub grounded_seconds: f32, + pub damage_interval_seconds: f32, + pub damage: i32, + pub ignite_after_seconds: f32, + pub burn_duration_seconds: f32, + pub burn_damage_fraction: f32, + pub burn_minimum_damage: f32, +} + +impl Default for HotFloorSettings { + fn default() -> Self { + Self { + grounded_seconds: 2.0, + damage_interval_seconds: 0.5, + damage: 3, + ignite_after_seconds: 4.0, + burn_duration_seconds: 5.0, + burn_damage_fraction: 0.01, + burn_minimum_damage: 1.0, + } + } +} + +impl HotFloorSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !finite_positive(self.grounded_seconds) + || !finite_positive(self.damage_interval_seconds) + || self.damage <= 0 + || !finite_positive(self.ignite_after_seconds) + || !finite_positive(self.burn_duration_seconds) + || !finite_nonnegative(self.burn_damage_fraction) + || !finite_nonnegative(self.burn_minimum_damage) + { + return Err("hot_floor needs positive finite ground/damage/ignite/burn times, positive damage, and finite nonnegative burn damage"); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WeaponOnFireSettings { + pub chance: f32, + pub switch_weight: u32, + pub drop_weight: u32, + pub cooldown_seconds: f32, +} + +impl Default for WeaponOnFireSettings { + fn default() -> Self { + Self { + chance: 0.1, + switch_weight: 3, + drop_weight: 1, + cooldown_seconds: 1.0, + } + } +} + +impl WeaponOnFireSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !self.chance.is_finite() + || !(0.0..=1.0).contains(&self.chance) + || (self.switch_weight == 0 && self.drop_weight == 0) + || !finite_nonnegative(self.cooldown_seconds) + { + return Err("weapon_on_fire needs chance between 0 and 1, at least one positive action weight, and a finite nonnegative cooldown"); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct LongFlashSettings { + pub duration_multiplier: f32, + pub duration_cap_seconds: f32, +} + +impl Default for LongFlashSettings { + fn default() -> Self { + Self { + duration_multiplier: 3.0, + duration_cap_seconds: 12.0, + } + } +} + +impl LongFlashSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !self.duration_multiplier.is_finite() || self.duration_multiplier < 1.0 || !finite_nonnegative(self.duration_cap_seconds) { + return Err("long_flash needs a finite duration_multiplier >= 1 and finite nonnegative extension cap"); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BigHeadSettings { + pub min_scale: f32, + pub max_scale: f32, +} + +impl Default for BigHeadSettings { + fn default() -> Self { + Self { + min_scale: 0.5, + max_scale: 2.0, + } + } +} + +impl BigHeadSettings { + pub fn validate(self) -> Result<(), &'static str> { + if !finite_positive(self.min_scale) || !finite_positive(self.max_scale) || self.min_scale > self.max_scale { + return Err("big_head needs positive finite scales with min_scale <= max_scale"); + } + Ok(()) + } +} + +fn finite_positive(value: f32) -> bool { + value.is_finite() && value > 0.0 +} + +fn finite_nonnegative(value: f32) -> bool { + value.is_finite() && value >= 0.0 +} + +/// Returns the next health value, or None when the player should not be healed. +/// Existing health above the configured ceiling is never reduced. +pub fn healing_target(base_health: i32, current_health: i32, amount: i32, cap_base_multiple: f32) -> Option { + if base_health <= 0 || !finite_positive(cap_base_multiple) || amount <= 0 || current_health <= 0 { + return None; + } + let cap = (f64::from(base_health) * f64::from(cap_base_multiple)).floor(); + if !cap.is_finite() { + return None; + } + let cap = cap.min(f64::from(i32::MAX)) as i32; + let healed = current_health.saturating_add(amount).min(cap); + (healed > current_health).then_some(healed) +} + +/// Uses the player's real match kills/deaths. Clamp bounds are validated in configuration. +pub fn big_head_scale(kills: u32, deaths: u32, min_scale: f32, max_scale: f32) -> f32 { + let ratio = (f64::from(kills) + 1.0) / (f64::from(deaths) + 1.0); + (ratio as f32).clamp(min_scale, max_scale) +} + +/// Multiplies the native duration up to `duration_cap_seconds`; an already later +/// native or plugin deadline is preserved. +pub fn extended_flash_deadline( + now: f64, + native_deadline: f64, + current_deadline: f64, + duration_multiplier: f32, + duration_cap_seconds: f32, +) -> Option { + if !now.is_finite() + || !native_deadline.is_finite() + || !current_deadline.is_finite() + || !duration_multiplier.is_finite() + || duration_multiplier < 1.0 + || !duration_cap_seconds.is_finite() + || duration_cap_seconds < 0.0 + || native_deadline <= now + { + return None; + } + let duration = ((native_deadline - now) * f64::from(duration_multiplier)).min(f64::from(duration_cap_seconds)); + let target = now + duration; + target.is_finite().then_some(current_deadline.max(native_deadline).max(target)) +} + +macro_rules! settings_input { + ($name:ident, $settings:ident, { $($field:ident : $kind:ty),+ $(,)? }) => { + #[derive(Clone, Debug, Default, Deserialize)] + #[serde(default, deny_unknown_fields)] + pub(super) struct $name { $(pub(super) $field: Option<$kind>,)+ } + + impl $name { + pub(super) fn resolve(self, base: Option<$settings>) -> $settings { + let base = base.unwrap_or_default(); + $settings { $($field: self.$field.unwrap_or(base.$field),)+ } + } + } + }; +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(super) struct RegenerationInput { + pub(super) delay_seconds: Option, + pub(super) interval_seconds: Option, + pub(super) heal: Option, + pub(super) heal_percent: Option, +} + +impl RegenerationInput { + pub(super) fn resolve(self, base: Option) -> Result { + let base = base.unwrap_or_default(); + let heal = resolve_healing_amount(self.heal, self.heal_percent, base.heal, "regeneration")?; + Ok(RegenerationSettings { + delay_seconds: self.delay_seconds.unwrap_or(base.delay_seconds), + interval_seconds: self.interval_seconds.unwrap_or(base.interval_seconds), + heal, + }) + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(super) struct ChickenAuraInput { + pub(super) radius: Option, + pub(super) interval_seconds: Option, + pub(super) heal: Option, + pub(super) heal_percent: Option, +} + +impl ChickenAuraInput { + pub(super) fn resolve(self, base: Option) -> Result { + let base = base.unwrap_or_default(); + let heal = resolve_healing_amount(self.heal, self.heal_percent, base.heal, "chicken_aura")?; + Ok(ChickenAuraSettings { + radius: self.radius.unwrap_or(base.radius), + interval_seconds: self.interval_seconds.unwrap_or(base.interval_seconds), + heal, + }) + } +} + +fn resolve_healing_amount(heal: Option, heal_percent: Option, inherited: HealingAmount, ability: &str) -> Result { + match (heal, heal_percent) { + (Some(_), Some(_)) => Err(format!("{ability}: configure either heal or heal_percent, not both")), + (Some(amount), None) => Ok(HealingAmount::Fixed(amount)), + (None, Some(percent)) => Ok(HealingAmount::Percent(percent)), + (None, None) => Ok(inherited), + } +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(super) enum FriendlyFireHealKindInput { + Fixed, + DamageRatio, +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(super) struct FriendlyFireHealInput { + pub(super) kind: Option, + pub(super) amount: Option, + pub(super) ratio: Option, +} + +impl FriendlyFireHealInput { + pub(super) fn resolve(self, base: Option) -> Result { + if self.amount.is_some() && self.ratio.is_some() { + return Err("configure either amount or ratio, not both".into()); + } + let base = base.unwrap_or_default(); + let inherited_kind = match base.kind { + FriendlyFireHealKind::Fixed { .. } => FriendlyFireHealKindInput::Fixed, + FriendlyFireHealKind::DamageRatio { .. } => FriendlyFireHealKindInput::DamageRatio, + }; + let kind = self.kind.unwrap_or(inherited_kind); + let changed_kind = self.kind.is_some_and(|kind| kind != inherited_kind); + let settings = match kind { + FriendlyFireHealKindInput::Fixed => { + if self.ratio.is_some() { + return Err("kind = 'fixed' does not accept ratio".into()); + } + let inherited = match base.kind { + FriendlyFireHealKind::Fixed { amount } if !changed_kind => Some(amount), + _ => None, + }; + FriendlyFireHealSettings { + kind: FriendlyFireHealKind::Fixed { + amount: self.amount.or(inherited).unwrap_or(10), + }, + } + } + FriendlyFireHealKindInput::DamageRatio => { + if self.amount.is_some() { + return Err("kind = 'damage_ratio' does not accept amount".into()); + } + let inherited = match base.kind { + FriendlyFireHealKind::DamageRatio { ratio } if !changed_kind => Some(ratio), + _ => None, + }; + FriendlyFireHealSettings { + kind: FriendlyFireHealKind::DamageRatio { + ratio: self.ratio.or(inherited).ok_or("kind = 'damage_ratio' requires ratio")?, + }, + } + } + }; + settings.validate()?; + Ok(settings) + } +} + +settings_input!(ExplosiveBulletsInput, ExplosiveBulletsSettings, { + cooldown_seconds: f32, + damage: AttributeValue, + radius: AttributeValue, +}); + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(super) struct HeGrenadeImpulseInput { + pub(super) impulse: Option, +} + +impl HeGrenadeImpulseInput { + pub(super) fn resolve(self, base: Option) -> HeGrenadeImpulseSettings { + let base = base.unwrap_or_default(); + HeGrenadeImpulseSettings { + impulse: self.impulse.unwrap_or(base.impulse), + } + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(super) struct ProximityFuseInput { + pub(super) radius: Option, + pub(super) delay_seconds: Option, + pub(super) grenades: Option>, +} + +impl ProximityFuseInput { + pub(super) fn resolve(self, base: Option) -> Result { + let base = base.unwrap_or_default(); + let grenades = match self.grenades { + Some(items) => items + .into_iter() + .map(|item| GrenadeKind::from_config_id(&item).map_err(|error| format!("grenades: {error}"))) + .collect::, _>>()?, + None => base.grenades, + }; + let settings = ProximityFuseSettings { + radius: self.radius.unwrap_or(base.radius), + delay_seconds: self.delay_seconds.unwrap_or(base.delay_seconds), + grenades, + }; + settings.validate().map_err(str::to_owned)?; + Ok(settings) + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(super) struct GrappleInput { + pub(super) max_distance: Option, + pub(super) max_speed: Option, + pub(super) pull_gain: Option, +} + +impl GrappleInput { + pub(super) fn resolve(self, base: Option) -> GrappleSettings { + let base = base.unwrap_or_default(); + GrappleSettings { + max_distance: self.max_distance.unwrap_or(base.max_distance), + max_speed: self.max_speed.unwrap_or(base.max_speed), + pull_gain: self.pull_gain.unwrap_or(base.pull_gain), + } + } +} + +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub(super) struct HeGuidanceInput { + pub(super) range: Option, + pub(super) turn_rate_degrees_per_second: Option, + pub(super) max_speed: Option, + pub(super) max_guidance_seconds: Option, +} + +impl HeGuidanceInput { + pub(super) fn resolve(self, base: Option) -> HeGuidanceSettings { + let base = base.unwrap_or_default(); + HeGuidanceSettings { + range: self.range.unwrap_or(base.range), + turn_rate_degrees_per_second: self.turn_rate_degrees_per_second.unwrap_or(base.turn_rate_degrees_per_second), + max_speed: self.max_speed.unwrap_or(base.max_speed), + max_guidance_seconds: self.max_guidance_seconds.unwrap_or(base.max_guidance_seconds), + } + } +} + +settings_input!(DontStopInput, DontStopSettings, { + minimum_horizontal_speed: f32, + grace_seconds: f32, + damage_interval_seconds: f32, + damage: i32, +}); +settings_input!(HotFloorInput, HotFloorSettings, { + grounded_seconds: f32, + damage_interval_seconds: f32, + damage: i32, + ignite_after_seconds: f32, + burn_duration_seconds: f32, + burn_damage_fraction: f32, + burn_minimum_damage: f32, +}); +settings_input!(WeaponOnFireInput, WeaponOnFireSettings, { + chance: f32, + switch_weight: u32, + drop_weight: u32, + cooldown_seconds: f32, +}); +settings_input!(LongFlashInput, LongFlashSettings, { + duration_multiplier: f32, + duration_cap_seconds: f32, +}); +settings_input!(BigHeadInput, BigHeadSettings, { + min_scale: f32, + max_scale: f32, +}); diff --git a/crates/funrounds-core/src/autostrafe.rs b/crates/funrounds-core/src/autostrafe.rs new file mode 100644 index 0000000..db4241f --- /dev/null +++ b/crates/funrounds-core/src/autostrafe.rs @@ -0,0 +1,25 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use std::f32::consts::{PI, TAU}; + +/// The native AirMove step consumes forward and left input relative to aim. +pub fn air_strafe_input(yaw: f32, vx: f32, vy: f32) -> Option<(f32, f32)> { + let aim = yaw.to_radians(); + let speed = vx.hypot(vy); + if !aim.is_finite() || !speed.is_finite() { + return None; + } + let heading = vy.atan2(vx); + let turn = (aim - heading + PI).rem_euclid(TAU) - PI; + if speed >= 30.0 && turn.abs() < 2.0_f32.to_radians() { + return None; + } + let wish = if speed < 30.0 { + aim + } else { + heading + (20.0 / speed).acos().copysign(turn) + }; + let (left, forward) = (wish - aim).sin_cos(); + Some((200.0 * forward, 200.0 * left)) +} diff --git a/crates/funrounds-core/src/bin/validate-config.rs b/crates/funrounds-core/src/bin/validate-config.rs index 6ade75b..7883381 100644 --- a/crates/funrounds-core/src/bin/validate-config.rs +++ b/crates/funrounds-core/src/bin/validate-config.rs @@ -10,39 +10,35 @@ fn validate_file(path: &Path) -> Result<(), String> { } fn validate_bundle(config: &Config, directory: &Path, allow_fallback: bool) -> Result<(), String> { - let zh_path = directory.join("zh-CN.toml"); - let en_path = directory.join("en.toml"); - let catalogs = if allow_fallback { - let mut catalogs = Vec::new(); - for (language, path) in [("zh-CN", &zh_path), ("en", &en_path)] { - if let Some(catalog) = read_catalog_if_present(path)? { - catalogs.push((language.to_owned(), catalog)); + let mut catalogs = Vec::new(); + match fs::read_dir(directory) { + Ok(entries) => { + for entry in entries { + let path = entry.map_err(|error| format!("{}: {error}", directory.display()))?.path(); + if path + .extension() + .and_then(|ext| ext.to_str()) + .is_some_and(|ext| ext.eq_ignore_ascii_case("toml")) + && fs::metadata(&path).map_err(|error| format!("{}: {error}", path.display()))?.is_file() + { + let language = path.file_stem().unwrap_or_default().to_string_lossy().into_owned(); + let source = fs::read_to_string(&path).map_err(|error| format!("{}: {error}", path.display()))?; + let catalog = TextCatalog::parse_for_language(&source, &language).map_err(|error| format!("{}: {error}", path.display()))?; + catalogs.push((language, catalog)); + } } } - catalogs - } else { - let zh = read_catalog(&zh_path)?; - let en = read_catalog(&en_path)?; - TextBundle::validate_complete_catalogs(&zh, &en).map_err(|error| format!("{}: {error}", directory.display()))?; - vec![("zh-CN".into(), zh), ("en".into(), en)] - }; + Err(error) if allow_fallback && error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(format!("{}: {error}", directory.display())), + } + catalogs.sort_by(|(a, _), (b, _)| a.cmp(b)); let bundle = TextBundle::load(config.default_language.as_str(), catalogs)?; - bundle.validate_config(config) -} - -fn read_catalog(path: &Path) -> Result { - let source = fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))?; - TextCatalog::parse(&source).map_err(|error| format!("{}: {error}", path.display())) -} - -fn read_catalog_if_present(path: &Path) -> Result, String> { - match fs::read_to_string(path) { - Ok(source) => TextCatalog::parse(&source) - .map(Some) - .map_err(|error| format!("{}: {error}", path.display())), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), - Err(error) => Err(format!("{}: {error}", path.display())), + if !allow_fallback { + bundle + .validate_complete_catalogs() + .map_err(|error| format!("{}: {error}", directory.display()))?; } + bundle.validate_config(config) } fn run() -> Result<(), String> { diff --git a/crates/funrounds-core/src/combat.rs b/crates/funrounds-core/src/combat.rs index 9a49aaa..dea124b 100644 --- a/crates/funrounds-core/src/combat.rs +++ b/crates/funrounds-core/src/combat.rs @@ -17,11 +17,7 @@ pub fn weapon_damage_scale(mode: &Mode, weapon: Option<&str>, player_attack: boo if !player_attack { return 1.0; } - match weapon { - Some("weapon_taser") => mode.weapon_damage.taser, - Some("weapon_knife" | "weapon_knife_t") => mode.weapon_damage.knife, - _ => 1.0, - } + weapon.map_or(1.0, |id| mode.weapon_damage.multiplier(id)) } #[derive(Debug)] @@ -101,7 +97,7 @@ pub fn combat_hit(mode: &Mode, life: &mut CombatLife, eligible: bool, allowed_se if !(eligible || allowed_self) { return (false, None); } - if eligible && knife && mode.weapon_damage.knife == 0.0 { + if eligible && knife && mode.weapon_damage.multiplier("knife") == 0.0 { return (true, None); } if life.absorb(incoming) { diff --git a/crates/funrounds-core/src/equipment.rs b/crates/funrounds-core/src/equipment.rs index 9b2cbe8..919c361 100644 --- a/crates/funrounds-core/src/equipment.rs +++ b/crates/funrounds-core/src/equipment.rs @@ -6,7 +6,7 @@ use rand::seq::IndexedRandom; #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] -/// Inventory category for supported weapon classnames. +/// Inventory category for supported canonical item IDs. pub enum WeaponSlot { Primary = 0, Secondary = 1, @@ -15,51 +15,77 @@ pub enum WeaponSlot { Extra = 3, } -/// Returns the loadout slot used by a supported weapon classname. +/// Converts a canonical item ID to the engine classname used at the adapter boundary. +const ITEM_CLASSES: &[(&str, &str)] = &[ + ("ak47", "weapon_ak47"), + ("m4a1", "weapon_m4a1"), + ("m4a1_silencer", "weapon_m4a1_silencer"), + ("galilar", "weapon_galilar"), + ("famas", "weapon_famas"), + ("aug", "weapon_aug"), + ("sg556", "weapon_sg556"), + ("mag7", "weapon_mag7"), + ("awp", "weapon_awp"), + ("ssg08", "weapon_ssg08"), + ("g3sg1", "weapon_g3sg1"), + ("scar20", "weapon_scar20"), + ("mac10", "weapon_mac10"), + ("mp9", "weapon_mp9"), + ("mp7", "weapon_mp7"), + ("mp5sd", "weapon_mp5sd"), + ("ump45", "weapon_ump45"), + ("p90", "weapon_p90"), + ("bizon", "weapon_bizon"), + ("nova", "weapon_nova"), + ("xm1014", "weapon_xm1014"), + ("sawedoff", "weapon_sawedoff"), + ("m249", "weapon_m249"), + ("negev", "weapon_negev"), + ("glock", "weapon_glock"), + ("hkp2000", "weapon_hkp2000"), + ("usp_silencer", "weapon_usp_silencer"), + ("p250", "weapon_p250"), + ("fiveseven", "weapon_fiveseven"), + ("tec9", "weapon_tec9"), + ("cz75a", "weapon_cz75a"), + ("deagle", "weapon_deagle"), + ("elite", "weapon_elite"), + ("revolver", "weapon_revolver"), + ("knife", "weapon_knife"), + ("taser", "weapon_taser"), + ("hegrenade", "weapon_hegrenade"), + ("flashbang", "weapon_flashbang"), + ("smokegrenade", "weapon_smokegrenade"), + ("molotov", "weapon_molotov"), + ("incgrenade", "weapon_incgrenade"), + ("decoy", "weapon_decoy"), + ("c4", "weapon_c4"), +]; + +/// Converts a canonical item ID to the engine classname used at the adapter boundary. +pub fn item_classname(item: &str) -> Option<&'static str> { + ITEM_CLASSES.iter().find_map(|(id, classname)| (*id == item).then_some(*classname)) +} + +/// Normalizes a canonical item ID, event item name, or engine classname to its canonical ID. +pub fn item_id(item: &str) -> Option<&'static str> { + let item = item.strip_prefix("weapon_").unwrap_or(item); + match item { + "knife_t" | "knife_ct" | "knife_default_ct" | "knife_default_t" | "knife_projectile" => Some("knife"), + _ => ITEM_CLASSES.iter().find_map(|(id, _)| (*id == item).then_some(*id)), + } +} + +/// Returns the loadout slot used by a supported canonical item ID. pub fn weapon_slot(weapon: &str) -> Option { match weapon { - "weapon_ak47" - | "weapon_m4a1" - | "weapon_m4a1_silencer" - | "weapon_galilar" - | "weapon_famas" - | "weapon_aug" - | "weapon_sg556" - | "weapon_mag7" - | "weapon_awp" - | "weapon_ssg08" - | "weapon_g3sg1" - | "weapon_scar20" - | "weapon_mac10" - | "weapon_mp9" - | "weapon_mp7" - | "weapon_mp5sd" - | "weapon_ump45" - | "weapon_p90" - | "weapon_bizon" - | "weapon_nova" - | "weapon_xm1014" - | "weapon_sawedoff" - | "weapon_m249" - | "weapon_negev" => Some(WeaponSlot::Primary), - "weapon_glock" - | "weapon_hkp2000" - | "weapon_usp_silencer" - | "weapon_p250" - | "weapon_fiveseven" - | "weapon_tec9" - | "weapon_cz75a" - | "weapon_deagle" - | "weapon_elite" - | "weapon_revolver" => Some(WeaponSlot::Secondary), - "weapon_knife" => Some(WeaponSlot::Knife), - "weapon_taser" - | "weapon_hegrenade" - | "weapon_flashbang" - | "weapon_smokegrenade" - | "weapon_molotov" - | "weapon_incgrenade" - | "weapon_decoy" => Some(WeaponSlot::Extra), + "ak47" | "m4a1" | "m4a1_silencer" | "galilar" | "famas" | "aug" | "sg556" | "mag7" | "awp" | "ssg08" | "g3sg1" | "scar20" | "mac10" + | "mp9" | "mp7" | "mp5sd" | "ump45" | "p90" | "bizon" | "nova" | "xm1014" | "sawedoff" | "m249" | "negev" => Some(WeaponSlot::Primary), + "glock" | "hkp2000" | "usp_silencer" | "p250" | "fiveseven" | "tec9" | "cz75a" | "deagle" | "elite" | "revolver" => { + Some(WeaponSlot::Secondary) + } + "knife" => Some(WeaponSlot::Knife), + "taser" | "hegrenade" | "flashbang" | "smokegrenade" | "molotov" | "incgrenade" | "decoy" => Some(WeaponSlot::Extra), _ => None, } } @@ -70,10 +96,10 @@ impl Mode { if self.kill_loadout { match self.kill_loadout_start.unwrap_or(KillLoadoutStart::Glock) { KillLoadoutStart::Glock => { - if !self.weapons.iter().any(|weapon| weapon == "weapon_glock") { + if !self.weapons.iter().any(|weapon| weapon == "glock") { return Err(format!("{}: kill loadout requires an initial Glock", self.id)); } - return Ok(vec!["weapon_glock"]); + return Ok(vec!["glock"]); } KillLoadoutStart::Random => {} } @@ -90,7 +116,7 @@ impl Mode { } let mut candidates: [Vec<&str>; 4] = Default::default(); for weapon in &self.weapons { - if weapon == "weapon_knife" { + if weapon == "knife" { return Err(format!("{}: knife is configured separately from equipment", self.id)); } let slot = weapon_slot(weapon).ok_or_else(|| format!("{}: unsupported weapon: {weapon}", self.id))?; @@ -119,7 +145,7 @@ impl Mode { fn loadout_candidates(&self) -> Vec<&str> { let mut candidates = Vec::new(); - for weapon in self.weapons.iter().map(String::as_str).filter(|weapon| *weapon != "weapon_knife") { + for weapon in self.weapons.iter().map(String::as_str).filter(|weapon| *weapon != "knife") { if !candidates.contains(&weapon) { candidates.push(weapon); } @@ -129,12 +155,12 @@ impl Mode { } pub fn self_push_force(weapon: &str) -> Option { - match weapon { - "weapon_nova" | "weapon_mag7" | "weapon_sawedoff" | "weapon_xm1014" | "weapon_ssg08" => Some(700.0), - "weapon_awp" | "weapon_scar20" | "weapon_g3sg1" => Some(1300.0), - "weapon_deagle" | "weapon_revolver" => Some(450.0), - "weapon_taser" => Some(135.0), - _ if matches!(weapon_slot(weapon), Some(WeaponSlot::Primary | WeaponSlot::Secondary)) => Some(135.0), + match crate::item_id(weapon)? { + "nova" | "mag7" | "sawedoff" | "xm1014" | "ssg08" => Some(700.0), + "awp" | "scar20" | "g3sg1" => Some(1300.0), + "deagle" | "revolver" => Some(450.0), + "taser" => Some(135.0), + weapon if matches!(weapon_slot(weapon), Some(WeaponSlot::Primary | WeaponSlot::Secondary)) => Some(135.0), _ => None, } } @@ -149,7 +175,7 @@ mod tests { fn generic_example_selects_one_item_per_listed_slot() { let config = Config::parse(include_str!("../../../config/funrounds.example.toml")).unwrap(); let mut rng = StdRng::seed_from_u64(0); - assert_eq!(config.modes[0].select_equipment(&mut rng).unwrap(), ["weapon_famas", "weapon_p250"]); + assert_eq!(config.modes[0].select_equipment(&mut rng).unwrap(), ["famas", "p250"]); } #[test] @@ -159,11 +185,11 @@ mod tests { .modes .remove(0); let mut rng = StdRng::seed_from_u64(0); - mode.weapons = vec!["weapon_famas".into(), "weapon_famas".into()]; - assert_eq!(mode.select_equipment(&mut rng).unwrap(), ["weapon_famas"]); - mode.weapons = vec!["weapon_knife".into()]; + mode.weapons = vec!["famas".into(), "famas".into()]; + assert_eq!(mode.select_equipment(&mut rng).unwrap(), ["famas"]); + mode.weapons = vec!["knife".into()]; assert!(mode.select_equipment(&mut rng).is_err()); - mode.weapons = vec!["weapon_shield".into()]; + mode.weapons = vec!["shield".into()]; assert!(mode.select_equipment(&mut rng).is_err()); mode.weapons.clear(); assert!(mode.select_equipment(&mut rng).unwrap().is_empty()); @@ -172,52 +198,44 @@ mod tests { #[test] fn recognizes_all_ordinary_guns_and_extra_equipment() { let primaries = [ - "weapon_ak47", - "weapon_m4a1", - "weapon_m4a1_silencer", - "weapon_galilar", - "weapon_famas", - "weapon_aug", - "weapon_sg556", - "weapon_mag7", - "weapon_awp", - "weapon_ssg08", - "weapon_g3sg1", - "weapon_scar20", - "weapon_mac10", - "weapon_mp9", - "weapon_mp7", - "weapon_mp5sd", - "weapon_ump45", - "weapon_p90", - "weapon_bizon", - "weapon_nova", - "weapon_xm1014", - "weapon_sawedoff", - "weapon_m249", - "weapon_negev", + "ak47", + "m4a1", + "m4a1_silencer", + "galilar", + "famas", + "aug", + "sg556", + "mag7", + "awp", + "ssg08", + "g3sg1", + "scar20", + "mac10", + "mp9", + "mp7", + "mp5sd", + "ump45", + "p90", + "bizon", + "nova", + "xm1014", + "sawedoff", + "m249", + "negev", ]; let secondaries = [ - "weapon_glock", - "weapon_hkp2000", - "weapon_usp_silencer", - "weapon_p250", - "weapon_fiveseven", - "weapon_tec9", - "weapon_cz75a", - "weapon_deagle", - "weapon_elite", - "weapon_revolver", - ]; - let extras = [ - "weapon_taser", - "weapon_hegrenade", - "weapon_flashbang", - "weapon_smokegrenade", - "weapon_molotov", - "weapon_incgrenade", - "weapon_decoy", + "glock", + "hkp2000", + "usp_silencer", + "p250", + "fiveseven", + "tec9", + "cz75a", + "deagle", + "elite", + "revolver", ]; + let extras = ["taser", "hegrenade", "flashbang", "smokegrenade", "molotov", "incgrenade", "decoy"]; assert!( primaries .iter() @@ -228,12 +246,12 @@ mod tests { .iter() .all(|weapon| matches!(weapon_slot(weapon), Some(super::WeaponSlot::Secondary))) ); - assert!(matches!(weapon_slot("weapon_knife"), Some(super::WeaponSlot::Knife))); + assert!(matches!(weapon_slot("knife"), Some(super::WeaponSlot::Knife))); assert!(extras.iter().all(|weapon| matches!(weapon_slot(weapon), Some(super::WeaponSlot::Extra)))); assert_eq!(primaries.len(), 24); assert_eq!(secondaries.len(), 10); assert_eq!(extras.len(), 7); - assert!(weapon_slot("weapon_c4").is_none()); + assert!(weapon_slot("c4").is_none()); } #[test] @@ -242,7 +260,7 @@ mod tests { .unwrap() .modes .remove(0); - mode.weapons = vec!["weapon_famas".into(), "weapon_p250".into(), "weapon_hegrenade".into()]; + mode.weapons = vec!["famas".into(), "p250".into(), "hegrenade".into()]; let mut rng = StdRng::seed_from_u64(44); let equipment = mode.select_equipment(&mut rng).unwrap(); assert_eq!(equipment.len(), 3); @@ -258,7 +276,7 @@ mod tests { .modes .remove(0); mode.random_loadout = true; - mode.weapons = vec!["weapon_famas".into(), "weapon_p250".into()]; + mode.weapons = vec!["famas".into(), "p250".into()]; let mut rng = StdRng::seed_from_u64(5); for _ in 0..2 { let loadout = mode.select_equipment(&mut rng).unwrap(); @@ -270,8 +288,8 @@ mod tests { mode.random_loadout = false; mode.kill_loadout = true; - mode.weapons = vec!["weapon_glock".into(), "weapon_famas".into()]; - assert_eq!(mode.select_equipment(&mut rng).unwrap(), ["weapon_glock"]); + mode.weapons = vec!["glock".into(), "famas".into()]; + assert_eq!(mode.select_equipment(&mut rng).unwrap(), ["glock"]); let kill_weapon = mode.select_kill_weapon_excluding(&mut rng, &[]).unwrap(); assert!(mode.weapons.iter().any(|weapon| weapon == kill_weapon)); } diff --git a/crates/funrounds-core/src/ghost.rs b/crates/funrounds-core/src/ghost.rs index c914db5..4c792fe 100644 --- a/crates/funrounds-core/src/ghost.rs +++ b/crates/funrounds-core/src/ghost.rs @@ -7,6 +7,7 @@ use serde::Deserialize; #[derive(Clone, Copy, Debug, PartialEq)] pub struct GhostSettings { pub team: TeamFilter, + pub speed_multiplier: f32, pub crouch_alpha: u8, pub slow_walk_alpha: u8, pub normal_alpha: u8, @@ -22,6 +23,7 @@ impl Default for GhostSettings { fn default() -> Self { Self { team: TeamFilter::Terrorists, + speed_multiplier: 1.0, crouch_alpha: 0, slow_walk_alpha: 13, normal_alpha: 127, @@ -47,7 +49,8 @@ pub enum GhostPose { pub struct GhostFrame { pub pose: GhostPose, pub horizontal_speed: f32, - pub bunny_hop: bool, + pub grounded: bool, + pub crouching: bool, pub attacking: bool, pub reloading: bool, pub using: bool, @@ -58,7 +61,8 @@ impl Default for GhostFrame { Self { pose: GhostPose::Normal, horizontal_speed: 0.0, - bunny_hop: false, + grounded: true, + crouching: false, attacking: false, reloading: false, using: false, @@ -68,18 +72,28 @@ impl Default for GhostFrame { #[derive(Clone, Copy, Debug, Default)] pub struct GhostState { + airborne_hidden: bool, reloading: bool, reveal_until: f32, } impl GhostState { pub fn alpha(&mut self, settings: GhostSettings, frame: GhostFrame, now: f32) -> u8 { + if frame.grounded { + self.airborne_hidden = false; + } else if frame.crouching && frame.horizontal_speed.is_finite() && frame.horizontal_speed >= 1.0 { + self.airborne_hidden = true; + } let reloading = frame.reloading; if reloading || self.reloading { self.reveal_until = now + settings.reveal_delay; } self.reloading = reloading; - ghost_alpha(settings, frame, reloading, self.reveal_until, now) + if self.airborne_hidden && !reloading && now >= self.reveal_until { + settings.crouch_alpha + } else { + ghost_alpha(settings, frame, reloading, self.reveal_until, now) + } } } @@ -87,7 +101,7 @@ pub fn ghost_alpha(settings: GhostSettings, frame: GhostFrame, reloading: bool, if reloading || now < reveal_until { return settings.normal_alpha; } - if frame.bunny_hop || !frame.horizontal_speed.is_finite() { + if !frame.horizontal_speed.is_finite() { return pose_alpha(settings, frame.pose); } if frame.horizontal_speed <= settings.speed_reveal_start { @@ -111,6 +125,7 @@ const fn pose_alpha(settings: GhostSettings, pose: GhostPose) -> u8 { #[serde(default, deny_unknown_fields)] pub(crate) struct GhostInput { team: Option, + speed_multiplier: Option, crouch_alpha: Option, slow_walk_alpha: Option, normal_alpha: Option, @@ -126,6 +141,7 @@ impl GhostInput { pub(crate) fn resolve(self, base: GhostSettings) -> GhostSettings { GhostSettings { team: self.team.unwrap_or(base.team), + speed_multiplier: self.speed_multiplier.unwrap_or(base.speed_multiplier), crouch_alpha: self.crouch_alpha.unwrap_or(base.crouch_alpha), slow_walk_alpha: self.slow_walk_alpha.unwrap_or(base.slow_walk_alpha), normal_alpha: self.normal_alpha.unwrap_or(base.normal_alpha), @@ -141,6 +157,9 @@ impl GhostInput { impl GhostSettings { pub(crate) fn validate(self) -> Result<(), String> { + if !self.speed_multiplier.is_finite() || self.speed_multiplier <= 0.0 { + return Err("ghost speed_multiplier must be finite and positive".into()); + } if !self.reveal_delay.is_finite() || self.reveal_delay < 0.0 { return Err("ghost reveal_delay must be finite and non-negative".into()); } diff --git a/crates/funrounds-core/src/lib.rs b/crates/funrounds-core/src/lib.rs index a874a8e..a6234e6 100644 --- a/crates/funrounds-core/src/lib.rs +++ b/crates/funrounds-core/src/lib.rs @@ -2,7 +2,19 @@ // SPDX-License-Identifier: AGPL-3.0-or-later use serde::Deserialize; -use std::collections::HashSet; +use std::collections::{BTreeMap, HashSet}; + +mod abilities; +use abilities::{ + BigHeadInput, ChickenAuraInput, DontStopInput, ExplosiveBulletsInput, FriendlyFireHealInput, GrappleInput, HeGrenadeImpulseInput, + HeGuidanceInput, HotFloorInput, LongFlashInput, ProximityFuseInput, RegenerationInput, WeaponOnFireInput, +}; +pub use abilities::{ + BigHeadSettings, ChickenAuraSettings, DontStopSettings, ExplosiveBulletsSettings, FriendlyFireHealKind, FriendlyFireHealSettings, + GrappleSettings, HeGrenadeImpulseSettings, HeGuidanceSettings, HealingAmount, HotFloorSettings, LongFlashSettings, ProximityFuseSettings, + RegenerationSettings, WeaponOnFireSettings, big_head_scale, extended_flash_deadline, healing_target, turn_projectile_velocity, + wall_hang_contact_eligible, +}; mod attributes; pub use attributes::{AttributeRange, AttributeValue, HelmetValue, LifeAttributes, RandomHelmet}; @@ -26,14 +38,16 @@ pub use third_person::ThirdPersonSettings; mod rounds; pub use rounds::{Capabilities, NextMode, Phase, RoundController, RoundGeneration, RoundKey}; mod players; -pub use players::{PlayerIdentity, PlayerTask, PlayerTracker}; +pub use players::{PlayerIdentity, PlayerTask, PlayerTracker, TeamkillCounter}; mod rules; pub use rules::{ - DODGEBALL_DAMAGE_MULTIPLIER, LIFESTEAL_MAX_HEALTH, MovementScale, PeriodicMovement, THROWING_KNIFE_BODY_DAMAGE, THROWING_KNIFE_ELASTICITY, - THROWING_KNIFE_GRAVITY, THROWING_KNIFE_HEAD_DAMAGE, THROWING_KNIFE_HEADSHOT_DISTANCE, THROWING_KNIFE_LIFETIME, THROWING_KNIFE_SPEED, - TeamDeathmatch, TeamResult, dodgeball_damage, lifesteal_recovery, low_health_finish, + DODGEBALL_DAMAGE_MULTIPLIER, LIFESTEAL_MAX_HEALTH, MovementScale, PeriodicDistribution, PeriodicMovement, PeriodicSetting, + THROWING_KNIFE_BODY_DAMAGE, THROWING_KNIFE_ELASTICITY, THROWING_KNIFE_GRAVITY, THROWING_KNIFE_HEAD_DAMAGE, THROWING_KNIFE_HEADSHOT_DISTANCE, + THROWING_KNIFE_LIFETIME, THROWING_KNIFE_SPEED, TeamDeathmatch, TeamResult, dodgeball_damage, lifesteal_recovery, low_health_finish, + shockwave_impulse, }; mod health; +pub mod regions; use health::{HealthCurveInput, HealthDecayInput}; mod text; pub use text::{TextBundle, TextCatalog}; @@ -41,11 +55,14 @@ mod combat; pub use combat::{CombatLife, combat_hit, weapon_damage_scale}; mod random_damage; pub use random_damage::{RandomDamage, random_damage}; +mod autostrafe; mod suicide; -pub use suicide::{SuicideSequence, suicide_blast_damage}; +pub use autostrafe::air_strafe_input; +pub use suicide::{DeathExplosion, SuicideSequence, suicide_blast_damage}; mod equipment; mod money; pub use equipment::{WeaponSlot, self_push_force, weapon_slot}; +pub use equipment::{item_classname, item_id}; pub use health::{HealthBand, HealthCurve, HealthDecay}; pub use money::{money_floor, money_income_credit, next_money_income_due}; @@ -89,26 +106,40 @@ struct SelfDamageInput { amount: Option, } -#[derive(Clone, Copy, Debug, Deserialize, PartialEq)] -#[serde(default, deny_unknown_fields)] -pub struct WeaponDamage { - #[serde(default = "one")] - pub taser: f32, - #[serde(default = "one")] - pub knife: f32, -} +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(transparent)] +pub struct WeaponDamage(BTreeMap); -impl Default for WeaponDamage { - fn default() -> Self { - Self { taser: 1.0, knife: 1.0 } +impl WeaponDamage { + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn configured(&self, id: &str) -> Option { + self.0.get(id).copied() + } + + pub fn multiplier(&self, id: &str) -> f32 { + self.configured(id).unwrap_or(1.0) } -} -fn one() -> f32 { - 1.0 + fn validate(&self) -> Result<(), String> { + for (id, multiplier) in &self.0 { + if let Some(bare) = id.strip_prefix("weapon_") { + return Err(format!("weapon_damage.{id}: use weapon_damage.{bare}")); + } + if equipment::weapon_slot(id).is_none() { + return Err(format!("weapon_damage.{id}: unknown weapon ID")); + } + if !multiplier.is_finite() || *multiplier < 0.0 { + return Err(format!("weapon_damage.{id}: multiplier must be finite and non-negative")); + } + } + Ok(()) + } } -pub const VERSION: &str = "0.3-Alpha Test 2"; +pub const VERSION: &str = "0.4-Alpha Test 3"; #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -226,8 +257,7 @@ impl TeamFilter { } } -#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Hash)] -#[serde(rename_all = "snake_case")] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum GrenadeKind { He, Flash, @@ -238,6 +268,41 @@ pub enum GrenadeKind { } impl GrenadeKind { + pub(crate) fn from_config_id(item: &str) -> Result { + match item { + "hegrenade" => Ok(Self::He), + "flashbang" => Ok(Self::Flash), + "smokegrenade" => Ok(Self::Smoke), + "decoy" => Ok(Self::Decoy), + "molotov" => Ok(Self::Molotov), + "incgrenade" => Ok(Self::Incendiary), + "he" => Err("use canonical item ID 'hegrenade' instead of legacy alias 'he'".into()), + "flash" => Err("use canonical item ID 'flashbang' instead of legacy alias 'flash'".into()), + "smoke" => Err("use canonical item ID 'smokegrenade' instead of legacy alias 'smoke'".into()), + "incendiary" => Err("use canonical item ID 'incgrenade' instead of legacy alias 'incendiary'".into()), + value if value.starts_with("weapon_") => { + let canonical = value.strip_prefix("weapon_").unwrap_or(value); + if matches!(canonical, "hegrenade" | "flashbang" | "smokegrenade" | "decoy" | "molotov" | "incgrenade") { + Err(format!("use canonical item ID '{canonical}' without the 'weapon_' prefix")) + } else { + Err(format!("unsupported grenade item ID '{item}'")) + } + } + _ => Err(format!("unsupported grenade item ID '{item}'")), + } + } + + pub const fn item_id(self) -> &'static str { + match self { + Self::He => "hegrenade", + Self::Flash => "flashbang", + Self::Smoke => "smokegrenade", + Self::Decoy => "decoy", + Self::Molotov => "molotov", + Self::Incendiary => "incgrenade", + } + } + pub const fn classname(self) -> &'static str { match self { Self::He => "weapon_hegrenade", @@ -250,6 +315,18 @@ impl GrenadeKind { } } +impl<'de> Deserialize<'de> for GrenadeKind { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + use serde::de::Error; + + let item = String::deserialize(deserializer)?; + Self::from_config_id(&item).map_err(D::Error::custom) + } +} + #[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum WinCondition { @@ -356,6 +433,7 @@ pub struct Mode { pub weapon_damage: WeaponDamage, pub taser_charge: Option, pub bunnyhop: Option, + pub autostrafe: bool, pub friction: Option, pub time_scale: Option, pub ground_acceleration: Option, @@ -367,6 +445,7 @@ pub struct Mode { pub replenish: Vec, pub random_loadout: bool, pub suicide: bool, + pub death_explosion: DeathExplosion, pub random_damage: bool, pub kill_loadout: bool, pub kill_loadout_start: Option, @@ -394,11 +473,12 @@ pub struct Mode { pub health_curve: HealthCurve, pub health_decay_settings: HealthDecay, pub self_push: bool, - pub periodic_speed: bool, - pub periodic_gravity: bool, + pub periodic_speed: Option, + pub periodic_gravity: Option, pub c4_count: Option, pub c4_buy: bool, pub round_respawn: RoundRespawn, + pub hide_all_hud: bool, pub hide_radar: Option, pub hide_player_identification: Option, pub respawn: Option, @@ -409,6 +489,16 @@ pub struct Mode { pub buy_access: Option, pub buy_anywhere: Option, pub friendly_fire_scale: Option, + pub damage_multiplier: f32, + pub explosive_bullets: Option, + pub friendly_fire_heal: Option, + pub inferno_damage: Option, + pub teamkill_limit: Option, + pub hegrenade_impulse: Option, + pub proximity_fuse: Option, + pub wall_hang: bool, + pub grapple: Option, + pub he_guidance: Option, pub teammates_as_enemies: Option, pub random_spawn: Option, pub drop_weapons: Option, @@ -417,6 +507,16 @@ pub struct Mode { pub fall_damage_scale: Option, pub ordinary_chickens: bool, pub chicken_eating: Option, + pub regeneration: Option, + pub chicken_aura: Option, + pub medical_smoke: bool, + pub trampoline: bool, + pub healing_cap_base_multiple: f32, + pub dont_stop: Option, + pub hot_floor: Option, + pub weapon_on_fire: Option, + pub long_flash: Option, + pub big_head: Option, } #[derive(Clone, Debug, PartialEq)] @@ -434,7 +534,7 @@ struct WarmupInput { } impl WarmupInput { - fn into_config(mut self) -> Result { + fn into_config(mut self, weapon_groups: &BTreeMap>) -> Result { if self.mode.id.is_some() || self.mode.name.is_some() || self.mode.description.is_some() @@ -446,7 +546,11 @@ impl WarmupInput { if self.respawn_delay.is_some() && self.mode.respawn.is_some() { return Err("warmup: use respawn_delay or respawn, not both".into()); } + if self.mode.death_explosion.is_some_and(DeathExplosion::enabled) { + return Err("warmup: death_explosion requires a competitive round".into()); + } let enabled = self.mode.enabled.unwrap_or(true); + self.mode.resolve_weapons(weapon_groups, "warmup")?; self.mode.id = Some("warmup".into()); self.mode.enabled = Some(true); self.mode.name_key = Some("warmup.name".into()); @@ -481,16 +585,60 @@ enum OptionalOverride { Value(T), } +#[derive(Clone, Debug, Deserialize)] +#[serde(untagged)] +enum WeaponSelection { + List(Vec), + Group(String), +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(untagged)] +enum PeriodicSettingInput { + Enabled(bool), + Custom(PeriodicSettingFields), +} + #[derive(Clone, Debug, Default, Deserialize)] #[serde(default, deny_unknown_fields)] -struct WeaponDamageOverride { - taser: Option, - knife: Option, +struct PeriodicSettingFields { + interval_seconds: Option, + values: Option>, + min: Option, + max: Option, +} + +impl PeriodicSettingInput { + fn resolve(self, name: &str) -> Result, String> { + match self { + Self::Enabled(false) => Ok(None), + Self::Enabled(true) => Ok(Some(PeriodicSetting { + interval_seconds: 10.0, + distribution: PeriodicDistribution::Legacy, + })), + Self::Custom(fields) => { + let interval_seconds = fields.interval_seconds.ok_or_else(|| format!("{name}.interval_seconds is required"))?; + let distribution = match (fields.values, fields.min, fields.max) { + (Some(values), None, None) => PeriodicDistribution::Tiers(values), + (None, Some(min), Some(max)) => PeriodicDistribution::Range { min, max }, + (None, None, None) => return Err(format!("{name} requires either values or both min and max")), + _ => return Err(format!("{name} requires either values or both min and max, not both")), + }; + let setting = PeriodicSetting { + interval_seconds, + distribution, + }; + setting.validate().map_err(|error| format!("{name}: {error}"))?; + Ok(Some(setting)) + } + } + } } #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] enum HudElement { + All, Radar, Crosshair, } @@ -504,7 +652,7 @@ struct ModeInput { description: Option, name_key: Option, description_key: Option, - weapons: Option>, + weapons: Option, health: Option, armor: Option, gravity: Option, @@ -517,9 +665,10 @@ struct ModeInput { headshots: Option, ammo: Option, self_damage: Option>, - weapon_damage: Option, + weapon_damage: Option, taser_charge: Option>, bunnyhop: Option, + autostrafe: Option, friction: Option>, time_scale: Option>, ground_acceleration: Option>, @@ -531,6 +680,7 @@ struct ModeInput { replenish: Option>, random_loadout: Option, suicide: Option, + death_explosion: Option, random_damage: Option, kill_loadout: Option, kill_loadout_start: Option, @@ -557,8 +707,8 @@ struct ModeInput { health_curve: Option, health_decay_settings: Option, self_push: Option, - periodic_speed: Option, - periodic_gravity: Option, + periodic_speed: Option, + periodic_gravity: Option, c4_count: Option>, c4_buy: Option, round_respawn: Option, @@ -572,6 +722,16 @@ struct ModeInput { buy_access: Option>, buy_anywhere: Option>, friendly_fire_scale: Option, + damage_multiplier: Option>, + explosive_bullets: Option>, + friendly_fire_heal: Option>, + inferno_damage: Option>, + teamkill_limit: Option>, + hegrenade_impulse: Option>, + proximity_fuse: Option>, + wall_hang: Option, + grapple: Option>, + he_guidance: Option>, teammates_as_enemies: Option, random_spawn: Option, drop_weapons: Option, @@ -580,6 +740,16 @@ struct ModeInput { fall_damage_scale: Option, ordinary_chickens: Option, chicken_eating: Option, + regeneration: Option>, + chicken_aura: Option>, + medical_smoke: Option, + trampoline: Option, + healing_cap_base_multiple: Option, + dont_stop: Option>, + hot_floor: Option>, + weapon_on_fire: Option>, + long_flash: Option>, + big_head: Option>, ghost: Option>, afterburn: Option>, third_person: Option>, @@ -598,6 +768,8 @@ struct RawConfig { healthshot: Option, #[serde(default)] defaults: ModeInput, + #[serde(default)] + weapon_groups: BTreeMap>, warmup: Option, modes: Vec, #[serde(default)] @@ -618,6 +790,38 @@ impl Default for I18nInput { } } +fn resolved_weapon_list(selection: Option, owner: &str) -> Result>, String> { + match selection { + None => Ok(None), + Some(WeaponSelection::List(weapons)) => Ok(Some(weapons)), + Some(WeaponSelection::Group(_)) => Err(format!("{owner}.weapons weapon group reference was not resolved")), + } +} + +fn choose_periodic( + mode: Option, + defaults: Option, + name: &str, +) -> Result, String> { + mode.or(defaults).map(|setting| setting.resolve(name)).transpose().map(Option::flatten) +} + +fn equipment_input_error(owner: &str, item: &str) -> String { + if item == "knife" || item == "weapon_knife" { + return format!("{owner}: knife is configured separately from equipment; use give_knife"); + } + if let Some(id) = item.strip_prefix("weapon_") + && item_classname(id).is_some() + { + return format!("{owner}: use canonical item ID '{id}' without the 'weapon_' prefix"); + } + format!("{owner}: equipment item '{item}' is not in the supported CS2 item whitelist") +} + +fn supported_equipment_id(item: &str) -> bool { + weapon_slot(item).is_some() && item != "knife" +} + fn choose(mode: Option, defaults: Option, fallback: T) -> T { mode.or(defaults).unwrap_or(fallback) } @@ -669,6 +873,68 @@ fn merge_afterburn( apply(mode, apply(defaults, None)?) } +fn merge_ability( + mode: Option>, + defaults: Option>, + name: &str, + resolve: impl Fn(T, Option) -> S, +) -> Result, String> { + fn resolve_default(setting: Option>, name: &str, resolve: &impl Fn(T, Option) -> S) -> Result, String> { + match setting { + None | Some(OptionalOverride::Clear(false)) => Ok(None), + Some(OptionalOverride::Clear(true)) => Err(format!("{name}: only false clears an optional setting")), + Some(OptionalOverride::Value(input)) => Ok(Some(resolve(input, None))), + } + } + + let inherited = resolve_default(defaults, name, &resolve)?; + match mode { + None => Ok(inherited), + Some(OptionalOverride::Clear(false)) => Ok(None), + Some(OptionalOverride::Clear(true)) => Err(format!("{name}: only false clears an optional setting")), + Some(OptionalOverride::Value(input)) => Ok(Some(resolve(input, inherited))), + } +} + +fn merge_ability_result( + mode: Option>, + defaults: Option>, + name: &str, + resolve: impl Fn(T, Option) -> Result, +) -> Result, String> { + fn resolve_input(input: T, base: Option, name: &str, resolve: &impl Fn(T, Option) -> Result) -> Result, String> { + resolve(input, base).map(Some).map_err(|error| format!("{name}: {error}")) + } + let inherited = match defaults { + None | Some(OptionalOverride::Clear(false)) => None, + Some(OptionalOverride::Clear(true)) => return Err(format!("{name}: only false clears an optional setting")), + Some(OptionalOverride::Value(input)) => resolve_input(input, None, name, &resolve)?, + }; + match mode { + None => Ok(inherited), + Some(OptionalOverride::Clear(false)) => Ok(None), + Some(OptionalOverride::Clear(true)) => Err(format!("{name}: only false clears an optional setting")), + Some(OptionalOverride::Value(input)) => resolve_input(input, inherited, name, &resolve), + } +} + +fn merge_friendly_fire_heal( + mode: Option>, + defaults: Option>, +) -> Result, String> { + let inherited = match defaults { + None | Some(OptionalOverride::Clear(false)) => None, + Some(OptionalOverride::Clear(true)) => return Err("friendly_fire_heal: only false clears an optional setting".into()), + Some(OptionalOverride::Value(input)) => Some(input.resolve(None).map_err(|error| format!("friendly_fire_heal: {error}"))?), + }; + match mode { + None => Ok(inherited), + Some(OptionalOverride::Clear(false)) => Ok(None), + Some(OptionalOverride::Clear(true)) => Err("friendly_fire_heal: only false clears an optional setting".into()), + Some(OptionalOverride::Value(input)) => input.resolve(inherited).map(Some).map_err(|error| format!("friendly_fire_heal: {error}")), + } +} + fn merge_third_person( mode: Option>, defaults: Option>, @@ -802,6 +1068,69 @@ fn merge_self_damage( } impl ModeInput { + fn resolve_weapons(&mut self, weapon_groups: &BTreeMap>, owner: &str) -> Result<(), String> { + let Some(selection) = self.weapons.take() else { return Ok(()) }; + self.weapons = Some(WeaponSelection::List(match selection { + WeaponSelection::List(weapons) => weapons, + WeaponSelection::Group(reference) => { + let Some(name) = reference.strip_prefix('@') else { + return Err(format!("{owner}.weapons must be an array or an '@group' reference")); + }; + weapon_groups + .get(name) + .cloned() + .ok_or_else(|| format!("{owner}.weapons references unknown weapon group '{name}'"))? + } + })); + Ok(()) + } + + fn validate_native_effect_inputs(&self) -> Result<(), String> { + if let Some(setting) = &self.periodic_speed { + setting.clone().resolve("periodic_speed")?; + } + if let Some(setting) = &self.periodic_gravity { + setting.clone().resolve("periodic_gravity")?; + } + if let Some(damage) = &self.weapon_damage { + damage.validate()?; + } + if matches!(&self.inferno_damage, Some(OptionalOverride::Clear(true))) { + return Err("inferno_damage: only false clears an optional setting".into()); + } + if matches!(&self.inferno_damage, Some(OptionalOverride::Value(value)) if !value.is_finite() || *value < 0.0) { + return Err("inferno_damage must be finite and nonnegative".into()); + } + if matches!(&self.teamkill_limit, Some(OptionalOverride::Clear(true))) { + return Err("teamkill_limit: only false clears an optional setting".into()); + } + if matches!(&self.teamkill_limit, Some(OptionalOverride::Value(0))) { + return Err("teamkill_limit must be a positive integer".into()); + } + if matches!(&self.hegrenade_impulse, Some(OptionalOverride::Clear(true))) { + return Err("hegrenade_impulse: only false clears an optional setting".into()); + } + if let Some(OptionalOverride::Value(input)) = &self.hegrenade_impulse { + HeGrenadeImpulseInput { impulse: input.impulse } + .resolve(None) + .validate() + .map_err(str::to_owned)?; + } + if matches!(&self.grapple, Some(OptionalOverride::Clear(true))) { + return Err("grapple: only false clears an optional setting".into()); + } + if matches!(&self.he_guidance, Some(OptionalOverride::Clear(true))) { + return Err("he_guidance: only false clears an optional setting".into()); + } + if let Some(OptionalOverride::Value(input)) = &self.grapple { + input.clone().resolve(None).validate().map_err(str::to_owned)?; + } + if let Some(OptionalOverride::Value(input)) = &self.he_guidance { + input.clone().resolve(None).validate().map_err(str::to_owned)?; + } + Ok(()) + } + fn validate_hud(&self) -> Result<(), String> { let Some(hud) = &self.hide_hud else { return Ok(()) }; if self.hide_radar.is_some() { @@ -826,18 +1155,10 @@ impl ModeInput { let description = resolve_mode_label(self.description, self.description_key.as_deref(), &id, "description")?; let kill_loadout = choose(self.kill_loadout, defaults.kill_loadout, false); let kill_loadout_start = self.kill_loadout_start.or(if kill_loadout { defaults.kill_loadout_start } else { None }); - let weapon_damage = WeaponDamage { - taser: choose( - self.weapon_damage.as_ref().and_then(|damage| damage.taser), - defaults.weapon_damage.as_ref().and_then(|damage| damage.taser), - 1.0, - ), - knife: choose( - self.weapon_damage.as_ref().and_then(|damage| damage.knife), - defaults.weapon_damage.as_ref().and_then(|damage| damage.knife), - 1.0, - ), - }; + let mut weapon_damage = defaults.weapon_damage.clone().unwrap_or_default(); + if let Some(overrides) = self.weapon_damage { + weapon_damage.0.extend(overrides.0); + } let armor = choose(self.armor, defaults.armor, AttributeValue::Fixed(0)); let helmet = self.helmet.or(defaults.helmet).unwrap_or(match armor { AttributeValue::Fixed(value) => HelmetValue::Fixed(value > 0), @@ -855,6 +1176,8 @@ impl ModeInput { defaults.kill_protection, defaults.combat_protection, ); + let weapons = resolved_weapon_list(self.weapons, &id)?; + let default_weapons = resolved_weapon_list(defaults.weapons.clone(), &id)?; Ok(Mode { id, enabled, @@ -862,7 +1185,7 @@ impl ModeInput { description, name_key: self.name_key, description_key: self.description_key, - weapons: choose(self.weapons, defaults.weapons.clone(), Vec::new()), + weapons: choose(weapons, default_weapons, Vec::new()), health: choose(self.health, defaults.health, AttributeValue::Fixed(100)), armor, gravity: choose(self.gravity, defaults.gravity, 1.0), @@ -878,6 +1201,7 @@ impl ModeInput { weapon_damage, taser_charge: choose_optional(self.taser_charge, defaults.taser_charge.clone(), "taser_charge")?, bunnyhop: self.bunnyhop.or(defaults.bunnyhop), + autostrafe: choose(self.autostrafe, defaults.autostrafe, false), friction: choose_optional(self.friction, defaults.friction.clone(), "friction")?, time_scale: choose_optional(self.time_scale, defaults.time_scale.clone(), "time_scale")?, ground_acceleration: choose_optional(self.ground_acceleration, defaults.ground_acceleration.clone(), "ground_acceleration")?, @@ -889,6 +1213,7 @@ impl ModeInput { replenish: choose(self.replenish, defaults.replenish.clone(), Vec::new()), random_loadout: choose(self.random_loadout, defaults.random_loadout, false), suicide: choose(self.suicide, defaults.suicide, false), + death_explosion: choose(self.death_explosion, defaults.death_explosion, DeathExplosion::default()), random_damage: choose(self.random_damage, defaults.random_damage, false), kill_loadout, kill_loadout_start, @@ -923,8 +1248,8 @@ impl ModeInput { health_curve: self.health_curve.unwrap_or_default().resolve(defaults.health_curve.as_ref()), health_decay_settings: self.health_decay_settings.unwrap_or_default().resolve(defaults.health_decay_settings), self_push: choose(self.self_push, defaults.self_push, false), - periodic_speed: choose(self.periodic_speed, defaults.periodic_speed, false), - periodic_gravity: choose(self.periodic_gravity, defaults.periodic_gravity, false), + periodic_speed: choose_periodic(self.periodic_speed, defaults.periodic_speed.clone(), "periodic_speed")?, + periodic_gravity: choose_periodic(self.periodic_gravity, defaults.periodic_gravity.clone(), "periodic_gravity")?, c4_count: choose_optional(self.c4_count, defaults.c4_count.clone(), "c4_count")?, c4_buy: choose(self.c4_buy, defaults.c4_buy, false), round_respawn: self @@ -932,6 +1257,11 @@ impl ModeInput { .or(defaults.round_respawn) .map(RoundRespawnInput::resolve) .unwrap_or_default(), + hide_all_hud: self + .hide_hud + .as_ref() + .or(defaults.hide_hud.as_ref()) + .is_some_and(|selection| selection.contains(&HudElement::All)), hide_radar: self.hide_hud.as_ref().map_or_else( || { self.hide_radar.or_else(|| { @@ -952,6 +1282,33 @@ impl ModeInput { buy_access: choose_optional(self.buy_access, defaults.buy_access.clone(), "buy_access")?, buy_anywhere: choose_optional(self.buy_anywhere, defaults.buy_anywhere.clone(), "buy_anywhere")?, friendly_fire_scale: self.friendly_fire_scale.or(defaults.friendly_fire_scale), + damage_multiplier: choose_optional(self.damage_multiplier, defaults.damage_multiplier.clone(), "damage_multiplier")?.unwrap_or(1.0), + explosive_bullets: merge_ability( + self.explosive_bullets, + defaults.explosive_bullets.clone(), + "explosive_bullets", + ExplosiveBulletsInput::resolve, + )?, + friendly_fire_heal: merge_friendly_fire_heal(self.friendly_fire_heal, defaults.friendly_fire_heal.clone())?, + inferno_damage: choose_optional(self.inferno_damage, defaults.inferno_damage.clone(), "inferno_damage")?, + teamkill_limit: choose_optional(self.teamkill_limit, defaults.teamkill_limit.clone(), "teamkill_limit")?, + hegrenade_impulse: merge_ability( + self.hegrenade_impulse, + defaults.hegrenade_impulse.clone(), + "hegrenade_impulse", + HeGrenadeImpulseInput::resolve, + )?, + proximity_fuse: merge_ability_result( + self.proximity_fuse, + defaults.proximity_fuse.clone(), + "proximity_fuse", + ProximityFuseInput::resolve, + )?, + wall_hang: choose(self.wall_hang, defaults.wall_hang, false), + grapple: merge_ability(self.grapple, defaults.grapple.clone(), "grapple", |input, base| input.resolve(base))?, + he_guidance: merge_ability(self.he_guidance, defaults.he_guidance.clone(), "he_guidance", |input, base| { + input.resolve(base) + })?, teammates_as_enemies: self.teammates_as_enemies.or(defaults.teammates_as_enemies), random_spawn: self.random_spawn.or(defaults.random_spawn), drop_weapons: self.drop_weapons.or(defaults.drop_weapons), @@ -960,6 +1317,31 @@ impl ModeInput { fall_damage_scale: self.fall_damage_scale.or(defaults.fall_damage_scale), ordinary_chickens: choose(self.ordinary_chickens, defaults.ordinary_chickens, true), chicken_eating: self.chicken_eating.or(defaults.chicken_eating), + regeneration: merge_ability_result( + self.regeneration, + defaults.regeneration.clone(), + "regeneration", + RegenerationInput::resolve, + )?, + chicken_aura: merge_ability_result( + self.chicken_aura, + defaults.chicken_aura.clone(), + "chicken_aura", + ChickenAuraInput::resolve, + )?, + medical_smoke: choose(self.medical_smoke, defaults.medical_smoke, false), + trampoline: choose(self.trampoline, defaults.trampoline, false), + healing_cap_base_multiple: choose(self.healing_cap_base_multiple, defaults.healing_cap_base_multiple, 1.0), + dont_stop: merge_ability(self.dont_stop, defaults.dont_stop.clone(), "dont_stop", DontStopInput::resolve)?, + hot_floor: merge_ability(self.hot_floor, defaults.hot_floor.clone(), "hot_floor", HotFloorInput::resolve)?, + weapon_on_fire: merge_ability( + self.weapon_on_fire, + defaults.weapon_on_fire.clone(), + "weapon_on_fire", + WeaponOnFireInput::resolve, + )?, + long_flash: merge_ability(self.long_flash, defaults.long_flash.clone(), "long_flash", LongFlashInput::resolve)?, + big_head: merge_ability(self.big_head, defaults.big_head.clone(), "big_head", BigHeadInput::resolve)?, }) } } @@ -1024,7 +1406,13 @@ impl Config { } pub fn parse(source: &str) -> Result { - let mut input: RawConfig = toml::from_str(source).map_err(|error| error.to_string())?; + let mut input: RawConfig = toml::from_str(source).map_err(|error| { + if error.message().contains("unknown field `he_shockwave`") { + format!("{error}\nUse hegrenade_impulse and weapon_damage.hegrenade = 0.0 for the former impulse-only behavior.") + } else { + error.to_string() + } + })?; if input.defaults.id.is_some() || input.defaults.enabled.is_some() || input.defaults.name.is_some() @@ -1034,18 +1422,27 @@ impl Config { { return Err("[defaults] may contain capability settings only".into()); } + for (name, weapons) in &input.weapon_groups { + if let Some(item) = weapons.iter().find(|item| !supported_equipment_id(item)) { + return Err(equipment_input_error(&format!("weapon_groups.{name}"), item)); + } + } input.defaults.validate_hud()?; + input.defaults.validate_native_effect_inputs()?; + input.defaults.resolve_weapons(&input.weapon_groups, "defaults")?; let defaults = input.defaults.clone(); - let warmup = input.warmup.map(WarmupInput::into_config).transpose()?; + let warmup = input.warmup.map(|warmup| warmup.into_config(&input.weapon_groups)).transpose()?; let chicken = input.chicken.map(ChickenInput::resolve).transpose()?; let healthshot = input.healthshot.map(HealthshotInput::resolve).transpose()?; let default_language = input.i18n.default_language; - if !matches!(default_language.as_str(), "zh-CN" | "en") { - return Err(format!("i18n.default_language must be zh-CN or en, got {default_language:?}")); - } + text::validate_language(&default_language).map_err(|error| format!("i18n.default_language: {error}"))?; let modes = std::mem::take(&mut input.modes) .into_iter() - .map(|mode| mode.into_mode(&defaults)) + .map(|mut mode| { + let owner = mode.id.clone().unwrap_or_else(|| "mode".into()); + mode.resolve_weapons(&input.weapon_groups, &owner)?; + mode.into_mode(&defaults) + }) .collect::, _>>()?; let config = Self { default_language, @@ -1075,6 +1472,57 @@ impl Config { } } for mode in self.modes.iter().chain(self.warmup.iter().map(|warmup| &warmup.mode)) { + if !mode.healing_cap_base_multiple.is_finite() || mode.healing_cap_base_multiple <= 0.0 { + return Err(format!("{}: healing_cap_base_multiple must be finite and positive", mode.id)); + } + if let Some(settings) = mode.regeneration { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = mode.chicken_aura { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if !mode.damage_multiplier.is_finite() || mode.damage_multiplier < 0.0 { + return Err(format!("{}: damage_multiplier must be finite and nonnegative", mode.id)); + } + if mode.inferno_damage.is_some_and(|damage| !damage.is_finite() || damage < 0.0) { + return Err(format!("{}: inferno_damage must be finite and nonnegative", mode.id)); + } + if mode.teamkill_limit == Some(0) { + return Err(format!("{}: teamkill_limit must be a positive integer", mode.id)); + } + if let Some(settings) = mode.explosive_bullets { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = mode.friendly_fire_heal { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = mode.hegrenade_impulse { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = &mode.proximity_fuse { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = mode.grapple { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = mode.he_guidance { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = mode.dont_stop { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = mode.hot_floor { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = mode.weapon_on_fire { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = mode.long_flash { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } + if let Some(settings) = mode.big_head { + settings.validate().map_err(|error| format!("{}: {error}", mode.id))?; + } if let Some(afterburn) = mode.afterburn { afterburn.validate().map_err(|error| format!("{}: {error}", mode.id))?; } @@ -1109,12 +1557,13 @@ impl Config { { return Err(format!("{}: invalid health, armor or gravity", mode.id)); } - if mode - .weapons - .iter() - .any(|weapon| equipment::weapon_slot(weapon).is_none() || weapon == "weapon_knife") - { - return Err(format!("{}: equipment must use the supported CS2 weapon whitelist", mode.id)); + if mode.weapons.iter().any(|weapon| !supported_equipment_id(weapon)) { + let weapon = mode + .weapons + .iter() + .find(|weapon| !supported_equipment_id(weapon)) + .expect("invalid item found"); + return Err(equipment_input_error(&mode.id, weapon)); } if !mode.speed.is_finite() || mode.speed <= 0.0 || mode.speed > 10.0 { return Err(format!("{}: speed must be finite, positive and at most 10", mode.id)); @@ -1122,7 +1571,7 @@ impl Config { if mode.taser_charge.is_some_and(|value| !value.is_finite() || value < 0.0) { return Err(format!("{}: taser charge must be finite and non-negative", mode.id)); } - if mode.taser_charge.is_some() && !mode.weapons.iter().any(|weapon| weapon == "weapon_taser") { + if mode.taser_charge.is_some() && !mode.weapons.iter().any(|weapon| weapon == "taser") { return Err(format!("{}: taser charge requires a taser equipment candidate", mode.id)); } if mode.random_loadout && mode.kill_loadout { @@ -1136,7 +1585,7 @@ impl Config { } if mode.kill_loadout && mode.kill_loadout_start.unwrap_or(KillLoadoutStart::Glock) == KillLoadoutStart::Glock - && !mode.weapons.iter().any(|weapon| weapon == "weapon_glock") + && !mode.weapons.iter().any(|weapon| weapon == "glock") { return Err(format!("{}: kill loadout candidates must include the initial Glock", mode.id)); } @@ -1177,23 +1626,14 @@ impl Config { }) { return Err(format!("{}: bomb times must be finite and non-negative", mode.id)); } - if !mode.weapon_damage.taser.is_finite() - || mode.weapon_damage.taser < 0.0 - || !mode.weapon_damage.knife.is_finite() - || mode.weapon_damage.knife < 0.0 - { - return Err(format!("{}: weapon damage multipliers must be finite and non-negative", mode.id)); - } + mode.weapon_damage.validate().map_err(|error| format!("{}: {error}", mode.id))?; if matches!(mode.self_damage, Some(SelfDamage::Native { amount }) if !amount.is_finite() || amount < 0.0) || mode.reflect_damage.is_some_and(|value| !value.is_finite() || value < 0.0) { return Err(format!("{}: self and reflected damage must be finite and non-negative", mode.id)); } - if mode - .friendly_fire_scale - .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value)) - { - return Err(format!("{}: friendly fire scale must be finite and between 0 and 1", mode.id)); + if mode.friendly_fire_scale.is_some_and(|value| !value.is_finite() || value < 0.0) { + return Err(format!("{}: friendly fire scale must be finite and nonnegative", mode.id)); } if mode.fall_damage_scale.is_some_and(|value| !value.is_finite() || value < 0.0) { return Err(format!("{}: fall damage scale must be finite and non-negative", mode.id)); @@ -1207,7 +1647,7 @@ impl Config { { return Err(format!("{}: money income needs a positive finite interval and positive amount", mode.id)); } - if mode.dodgeball && !mode.weapons.iter().any(|weapon| weapon == "weapon_decoy") { + if mode.dodgeball && !mode.weapons.iter().any(|weapon| weapon == "decoy") { return Err(format!("{}: dodgeball requires decoy equipment", mode.id)); } if mode.throwing_knives && mode.give_knife == TeamFilter::None { @@ -1216,7 +1656,7 @@ impl Config { if mode .replenish .iter() - .any(|kind| !mode.weapons.iter().any(|weapon| weapon == kind.classname())) + .any(|kind| !mode.weapons.iter().any(|weapon| weapon == kind.item_id())) { return Err(format!("{}: replenishment requires each grenade in the equipment candidates", mode.id)); } @@ -1258,7 +1698,7 @@ mod tests { let mode = &config.modes[0]; assert_eq!(mode.id, "example"); assert!(mode.enabled); - assert_eq!(mode.weapons, ["weapon_famas", "weapon_p250"]); + assert_eq!(mode.weapons, ["famas", "p250"]); assert_eq!( (mode.health, mode.armor, mode.gravity), (AttributeValue::Fixed(120), AttributeValue::Fixed(50), 1.0) @@ -1269,7 +1709,6 @@ mod tests { fn public_catalogs_localize_the_generic_example_with_matching_placeholders() { let zh = TextCatalog::parse(include_str!("../../../config/i18n/zh-CN.toml")).unwrap(); let en = TextCatalog::parse(include_str!("../../../config/i18n/en.toml")).unwrap(); - TextBundle::validate_complete_catalogs(&zh, &en).unwrap(); for source in [ include_str!("../../../config/i18n/zh-CN.toml"), include_str!("../../../config/i18n/en.toml"), @@ -1300,6 +1739,17 @@ mod tests { } } + #[test] + fn legacy_classnames_and_grenade_aliases_report_canonical_ids() { + let source = EXAMPLE.replace("famas", "weapon_famas"); + let error = Config::parse(&source).unwrap_err(); + assert!(error.contains("canonical item ID 'famas'"), "{error}"); + + let source = EXAMPLE.replace("# replenish = [\"hegrenade\"]", "replenish = [\"he\"]"); + let error = Config::parse(&source).unwrap_err(); + assert!(error.contains("canonical item ID 'hegrenade'"), "{error}"); + } + #[test] fn diagnostics_defaults_off_and_requires_an_explicit_boolean() { let source = EXAMPLE.replace("diagnostics = false", ""); @@ -1315,10 +1765,10 @@ mod tests { EXAMPLE.replace("enabled = true", "enabled = false"), EXAMPLE.replace("health = 120", "health = 0"), EXAMPLE.replace("gravity = 1.0", "gravity = nan"), - EXAMPLE.replace("weapon_famas", "weapon_shield"), + EXAMPLE.replace("famas", "shield"), EXAMPLE.replace( - "weapons = [\"weapon_famas\", \"weapon_p250\"]", - "weapons = [\"weapon_famas\", \"weapon_p250\"]\nammo = \"unsupported\"", + "weapons = [\"famas\", \"p250\"]", + "weapons = [\"famas\", \"p250\"]\nammo = \"unsupported\"", ), EXAMPLE.replace("# view_punch_decay = 5.0", "view_punch_decay = -1.0"), EXAMPLE.replace( diff --git a/crates/funrounds-core/src/players.rs b/crates/funrounds-core/src/players.rs index 7b40cc9..c45cb3d 100644 --- a/crates/funrounds-core/src/players.rs +++ b/crates/funrounds-core/src/players.rs @@ -26,6 +26,30 @@ pub struct PlayerTracker { next_connection: u64, } +#[derive(Debug, Default)] +pub struct TeamkillCounter { + count: u32, + seen_victims: Vec, +} + +impl TeamkillCounter { + /// Counts a distinct victim life once and resets the count when `limit` is reached. + /// Seen identities remain recorded until the caller replaces or drops this counter. + pub fn record(&mut self, victim: PlayerIdentity, limit: u32) -> bool { + if limit == 0 || self.seen_victims.contains(&victim) { + return false; + } + self.seen_victims.push(victim); + self.count = self.count.saturating_add(1); + if self.count >= limit { + self.count = 0; + true + } else { + false + } + } +} + impl PlayerTracker { pub fn connect(&mut self, slot: i32) -> bool { if slot < 0 || self.players.contains_key(&slot) { diff --git a/crates/funrounds-core/src/regions.rs b/crates/funrounds-core/src/regions.rs new file mode 100644 index 0000000..c7774da --- /dev/null +++ b/crates/funrounds-core/src/regions.rs @@ -0,0 +1,138 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use crate::PlayerIdentity; + +pub const MEDICAL_SMOKE_RADIUS: f32 = 160.0; +pub const MEDICAL_SMOKE_HEAL: i32 = 5; +pub const MEDICAL_SMOKE_INTERVAL_SECONDS: f64 = 1.0; + +pub const TRAMPOLINE_RADIUS: f32 = 130.0; +pub const TRAMPOLINE_HALF_HEIGHT: f32 = 32.0; +pub const TRAMPOLINE_REARM_MARGIN: f32 = 16.0; +pub const TRAMPOLINE_LAUNCH_Z: f32 = 700.0; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Position { + pub x: f32, + pub y: f32, + pub z: f32, +} + +impl Position { + pub fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() && self.z.is_finite() + } + + pub fn within_sphere(self, center: Self, radius: f32) -> bool { + if !self.is_finite() || !center.is_finite() || !radius.is_finite() || radius < 0.0 { + return false; + } + let dx = f64::from(self.x) - f64::from(center.x); + let dy = f64::from(self.y) - f64::from(center.y); + let dz = f64::from(self.z) - f64::from(center.z); + let radius = f64::from(radius); + dx * dx + dy * dy + dz * dz <= radius * radius + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TrampolineRegion { + pub center: Position, +} + +impl TrampolineRegion { + pub fn contains(self, position: Position) -> bool { + if !position.is_finite() || !self.center.is_finite() { + return false; + } + let dx = f64::from(position.x) - f64::from(self.center.x); + let dy = f64::from(position.y) - f64::from(self.center.y); + dx * dx + dy * dy <= f64::from(TRAMPOLINE_RADIUS).powi(2) && (position.z - self.center.z).abs() <= TRAMPOLINE_HALF_HEIGHT + } + + pub fn outside_rearm(self, position: Position) -> bool { + if !position.is_finite() || !self.center.is_finite() { + return false; + } + let dx = f64::from(position.x) - f64::from(self.center.x); + let dy = f64::from(position.y) - f64::from(self.center.y); + let radius = f64::from(TRAMPOLINE_RADIUS + TRAMPOLINE_REARM_MARGIN); + dx * dx + dy * dy > radius * radius || (position.z - self.center.z).abs() > TRAMPOLINE_HALF_HEIGHT + TRAMPOLINE_REARM_MARGIN + } +} + +/// Returns the only regions supported by the first trampoline capability. +pub fn fixed_trampoline_region(map: &str) -> Option { + let center = if map.eq_ignore_ascii_case("de_dust2") { + Position { + x: -1141.0, + y: -808.0, + z: 117.0, + } + } else if map.eq_ignore_ascii_case("de_nuke") { + Position { + x: 1105.0, + y: -950.0, + z: -767.97, + } + } else { + return None; + }; + Some(TrampolineRegion { center }) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TrampolineStep { + pub rearmed: bool, + pub triggered: bool, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TrampolineLatch { + identity: Option, + armed: bool, +} + +impl TrampolineLatch { + /// Preserve a launch across control transfer of the same live pawn. + pub fn rebind(&mut self, identity: PlayerIdentity) -> bool { + if self.identity.is_none_or(|previous| previous.pawn_handle != identity.pawn_handle) { + return false; + } + self.identity = Some(identity); + true + } + + /// Observe one live player's sampled state. A new life starts armed only outside the region. + pub fn observe(&mut self, identity: PlayerIdentity, position: Position, grounded: bool, region: TrampolineRegion) -> TrampolineStep { + if self.identity != Some(identity) { + self.identity = Some(identity); + self.armed = !region.contains(position); + return TrampolineStep::default(); + } + + let rearmed = !self.armed && grounded && region.outside_rearm(position); + if rearmed { + self.armed = true; + } + let triggered = self.armed && grounded && region.contains(position); + if triggered { + self.armed = false; + } + TrampolineStep { rearmed, triggered } + } + + pub fn clear(&mut self) { + *self = Self::default(); + } +} + +/// Teammate healing needs a real CS team and is intentionally unavailable in FFA modes. +pub const fn medical_smoke_team(team: i32, teammates_are_enemies: bool) -> Option { + if !teammates_are_enemies && matches!(team, 2 | 3) { + Some(team) + } else { + None + } +} diff --git a/crates/funrounds-core/src/rounds.rs b/crates/funrounds-core/src/rounds.rs index 3eef068..f9f293f 100644 --- a/crates/funrounds-core/src/rounds.rs +++ b/crates/funrounds-core/src/rounds.rs @@ -1,7 +1,7 @@ // Copyright (C) 2026 Mai Ooizumi // SPDX-License-Identifier: AGPL-3.0-or-later -use crate::{Ammo, Config, Headshots, Mode, RoundRespawn, TeamFilter, WeaponDamage, WinCondition}; +use crate::{Ammo, Config, GrenadeKind, Headshots, Mode, RoundRespawn, TeamFilter, WeaponDamage, WinCondition}; use rand::{Rng, seq::SliceRandom}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -18,6 +18,7 @@ pub struct Capabilities { pub ammo: bool, pub taser_charge: bool, pub bunnyhop: bool, + pub autostrafe: bool, pub friction: bool, pub time_scale: bool, pub ground_acceleration: bool, @@ -32,6 +33,7 @@ pub struct Capabilities { pub grenade_replenishment: bool, pub random_loadout: bool, pub suicide: bool, + pub death_explosion: bool, pub random_damage: bool, pub kill_loadout: bool, pub lifesteal: bool, @@ -63,6 +65,30 @@ pub struct Capabilities { pub health_damage: bool, pub health_speed: bool, pub health_decay: bool, + pub regeneration: bool, + pub chicken_aura: bool, + pub medical_smoke: bool, + pub trampoline: bool, + pub explosive_bullets: bool, + pub friendly_fire_heal: bool, + pub inferno_damage: bool, + pub teamkill_punishment: bool, + pub hide_all_hud: bool, + pub hegrenade_impulse: bool, + pub damage_multiplier: bool, + pub proximity_he: bool, + pub proximity_flash: bool, + pub proximity_smoke: bool, + pub proximity_molotov: bool, + pub proximity_incendiary: bool, + pub wall_hang: bool, + pub grapple: bool, + pub he_guidance: bool, + pub dont_stop: bool, + pub hot_floor: bool, + pub weapon_on_fire: bool, + pub long_flash: bool, + pub big_head: bool, pub self_push: bool, pub periodic_speed: bool, pub periodic_gravity: bool, @@ -119,7 +145,7 @@ impl Capabilities { } fn missing_for_stage(self, mode: &Mode, require_ct_bomb_no_defuse: bool) -> Vec<&'static str> { - [ + let mut missing: Vec<_> = [ (mode.clear_weapons != TeamFilter::None, self.clear_weapons, "clear_weapons"), ( mode.give_weapons != TeamFilter::None && !mode.weapons.is_empty(), @@ -141,6 +167,7 @@ impl Capabilities { (mode.ammo == Ammo::SingleShot, self.single_shot, "single_shot"), (mode.taser_charge.is_some(), self.taser_charge, "taser_charge"), (mode.bunnyhop.is_some(), self.bunnyhop, "bunnyhop"), + (mode.autostrafe, self.autostrafe, "autostrafe"), (mode.friction.is_some(), self.friction, "friction"), (mode.time_scale.is_some(), self.time_scale, "time_scale"), (mode.ground_acceleration.is_some(), self.ground_acceleration, "ground_acceleration"), @@ -154,6 +181,7 @@ impl Capabilities { (!mode.replenish.is_empty(), self.grenade_replenishment, "grenade_replenishment"), (mode.random_loadout, self.random_loadout, "random_loadout"), (mode.suicide, self.suicide, "suicide"), + (mode.death_explosion.enabled(), self.death_explosion, "death_explosion"), (mode.random_damage, self.random_damage, "random_damage"), (mode.kill_loadout, self.kill_loadout, "kill_loadout"), (mode.lifesteal, self.lifesteal, "lifesteal"), @@ -202,9 +230,32 @@ impl Capabilities { (mode.health_damage, self.health_damage, "health_damage"), (mode.health_speed, self.health_speed, "health_speed"), (mode.health_decay, self.health_decay, "health_decay"), + (mode.regeneration.is_some(), self.regeneration, "regeneration"), + (mode.chicken_aura.is_some(), self.chicken_aura, "chicken_aura"), + ( + mode.medical_smoke, + self.medical_smoke && mode.teammates_as_enemies != Some(true), + "medical_smoke", + ), + (mode.trampoline, self.trampoline, "trampoline"), + (mode.explosive_bullets.is_some(), self.explosive_bullets, "explosive_bullets"), + (mode.friendly_fire_heal.is_some(), self.friendly_fire_heal, "friendly_fire_heal"), + (mode.inferno_damage.is_some(), self.inferno_damage, "inferno_damage"), + (mode.teamkill_limit.is_some(), self.teamkill_punishment, "teamkill_punishment"), + (mode.hide_all_hud, self.hide_all_hud, "hide_all_hud"), + (mode.hegrenade_impulse.is_some(), self.hegrenade_impulse, "hegrenade_impulse"), + (mode.wall_hang, self.wall_hang, "wall_hang"), + (mode.grapple.is_some(), self.grapple, "grapple"), + (mode.he_guidance.is_some(), self.he_guidance, "he_guidance"), + (mode.damage_multiplier != 1.0, self.damage_multiplier, "damage_multiplier"), + (mode.dont_stop.is_some(), self.dont_stop, "dont_stop"), + (mode.hot_floor.is_some(), self.hot_floor, "hot_floor"), + (mode.weapon_on_fire.is_some(), self.weapon_on_fire, "weapon_on_fire"), + (mode.long_flash.is_some(), self.long_flash, "long_flash"), + (mode.big_head.is_some(), self.big_head, "big_head"), (mode.self_push, self.self_push, "self_push"), - (mode.periodic_speed, self.periodic_speed, "periodic_speed"), - (mode.periodic_gravity, self.periodic_gravity, "periodic_gravity"), + (mode.periodic_speed.is_some(), self.periodic_speed, "periodic_speed"), + (mode.periodic_gravity.is_some(), self.periodic_gravity, "periodic_gravity"), (mode.c4_count.is_some(), self.c4_assignment, "c4_assignment"), (mode.c4_buy, self.c4_purchase, "c4_purchase"), (mode.round_respawn == RoundRespawn::Dead, self.round_respawn, "round_respawn"), @@ -236,7 +287,23 @@ impl Capabilities { .into_iter() .filter(|(required, available, _)| *required && !*available) .map(|(_, _, name)| name) - .collect() + .collect(); + if let Some(settings) = &mode.proximity_fuse { + for grenade in &settings.grenades { + let (supported, capability) = match grenade { + GrenadeKind::He => (self.proximity_he, "proximity_he"), + GrenadeKind::Flash => (self.proximity_flash, "proximity_flash"), + GrenadeKind::Smoke => (self.proximity_smoke, "proximity_smoke"), + GrenadeKind::Molotov => (self.proximity_molotov, "proximity_molotov"), + GrenadeKind::Incendiary => (self.proximity_incendiary, "proximity_incendiary"), + GrenadeKind::Decoy => continue, + }; + if !supported && !missing.contains(&capability) { + missing.push(capability); + } + } + } + missing } } diff --git a/crates/funrounds-core/src/rules.rs b/crates/funrounds-core/src/rules.rs index 664bedb..b865cb9 100644 --- a/crates/funrounds-core/src/rules.rs +++ b/crates/funrounds-core/src/rules.rs @@ -28,49 +28,128 @@ pub fn low_health_finish(health: i32) -> bool { health <= 1 } +/// Returns an additive velocity impulse in the direction from the blast to the target. +/// The result is a normalized direction multiplied by `impulse`, in Source units per second. +pub fn shockwave_impulse(origin: [f32; 3], center: [f32; 3], impulse: f32) -> Option<[f32; 3]> { + if !impulse.is_finite() || impulse < 0.0 || origin.into_iter().chain(center).any(|value| !value.is_finite()) { + return None; + } + + let direction = std::array::from_fn::<_, 3, _>(|axis| f64::from(center[axis]) - f64::from(origin[axis])); + let length = direction[0].hypot(direction[1]).hypot(direction[2]); + if !length.is_finite() || length == 0.0 { + return None; + } + + let magnitude = f64::from(impulse); + let result = direction.map(|component| (component / length * magnitude) as f32); + result.into_iter().all(f32::is_finite).then_some(result) +} + #[derive(Clone, Copy, Debug, PartialEq)] pub struct MovementScale { - pub speed: f32, - pub gravity: f32, + pub speed: Option, + pub gravity: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum PeriodicDistribution { + Tiers(Vec), + Range { min: f32, max: f32 }, + Legacy, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct PeriodicSetting { + pub interval_seconds: f32, + pub distribution: PeriodicDistribution, +} + +impl PeriodicSetting { + pub fn validate(&self) -> Result<(), &'static str> { + if !self.interval_seconds.is_finite() || self.interval_seconds <= 0.0 { + return Err("periodic movement interval must be finite and positive"); + } + match &self.distribution { + PeriodicDistribution::Tiers(values) if values.is_empty() => Err("periodic movement tiers must not be empty"), + PeriodicDistribution::Tiers(values) if values.iter().any(|value| !value.is_finite() || *value <= 0.0) => { + Err("periodic movement tiers must be finite and positive") + } + PeriodicDistribution::Range { min, max } if !min.is_finite() || !max.is_finite() || *min <= 0.0 || *max < *min => { + Err("periodic movement range must be finite, positive, and ordered") + } + _ => Ok(()), + } + } + + fn sample(&self, speed: bool, rng: &mut impl Rng) -> f32 { + match &self.distribution { + PeriodicDistribution::Tiers(values) => values[rng.random_range(0..values.len())], + PeriodicDistribution::Range { min, max } if min == max => *min, + PeriodicDistribution::Range { min, max } => rng.random_range(*min..=*max), + PeriodicDistribution::Legacy if speed => match rng.random_range(0..=5) { + 0 => 0.3, + 1 => 0.7, + _ => rng.random_range(1..=10) as f32, + }, + PeriodicDistribution::Legacy => rng.random_range(0.001..=4.0), + } + } } pub struct PeriodicMovement { - next_update: f32, - current: Option, + speed: Option<(PeriodicSetting, f32)>, + gravity: Option<(PeriodicSetting, f32)>, + current: MovementScale, } impl PeriodicMovement { - pub fn start(now: f32) -> Result { - if !now.is_finite() || now < 0.0 || !(now + 10.0).is_finite() { + pub fn start(now: f32, speed: Option, gravity: Option) -> Result { + if !now.is_finite() || now < 0.0 { return Err("periodic movement needs a finite non-negative start time".into()); } + let next_due = |setting: &PeriodicSetting| -> Result { + setting.validate().map_err(str::to_owned)?; + let due = now + setting.interval_seconds; + due.is_finite() + .then_some(due) + .ok_or_else(|| "periodic movement schedule is not finite".to_owned()) + }; + let speed = speed.map(|setting| next_due(&setting).map(|due| (setting, due))).transpose()?; + let gravity = gravity.map(|setting| next_due(&setting).map(|due| (setting, due))).transpose()?; Ok(Self { - next_update: now + 10.0, - current: None, + speed, + gravity, + current: MovementScale { speed: None, gravity: None }, }) } pub fn update(&mut self, now: f32, rng: &mut impl Rng) -> Option { - if !now.is_finite() || now < self.next_update { + if !now.is_finite() || now < 0.0 { return None; } - let roll = rng.random_range(0..=5); - let speed = match roll { - 0 => 0.3, - 1 => 0.7, - _ => rng.random_range(1..=10) as f32, - }; - let movement = MovementScale { - speed, - gravity: rng.random_range(0.001..=4.0), - }; - self.current = Some(movement); - self.next_update = now + 10.0; - Some(movement) + let mut movement = MovementScale { speed: None, gravity: None }; + if let Some((setting, due)) = &mut self.speed + && now >= *due + { + let value = setting.sample(true, rng); + movement.speed = Some(value); + self.current.speed = Some(value); + *due = now + setting.interval_seconds; + } + if let Some((setting, due)) = &mut self.gravity + && now >= *due + { + let value = setting.sample(false, rng); + movement.gravity = Some(value); + self.current.gravity = Some(value); + *due = now + setting.interval_seconds; + } + (movement.speed.is_some() || movement.gravity.is_some()).then_some(movement) } pub fn current(&self) -> Option { - self.current + (self.current.speed.is_some() || self.current.gravity.is_some()).then_some(self.current) } } diff --git a/crates/funrounds-core/src/suicide.rs b/crates/funrounds-core/src/suicide.rs index 76b5449..daf4a2e 100644 --- a/crates/funrounds-core/src/suicide.rs +++ b/crates/funrounds-core/src/suicide.rs @@ -2,6 +2,20 @@ // SPDX-License-Identifier: AGPL-3.0-or-later use crate::PlayerTask; +use serde::Deserialize; + +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(default, deny_unknown_fields)] +pub struct DeathExplosion { + pub t: u8, + pub ct: u8, +} + +impl DeathExplosion { + pub fn enabled(self) -> bool { + self.t != 0 || self.ct != 0 + } +} const FULL_DAMAGE_RADIUS: f32 = 400.0; const FALLOFF_BASE: f32 = 1000.0; diff --git a/crates/funrounds-core/src/text.rs b/crates/funrounds-core/src/text.rs index 561b970..7ff2f02 100644 --- a/crates/funrounds-core/src/text.rs +++ b/crates/funrounds-core/src/text.rs @@ -5,8 +5,8 @@ use crate::{Config, Mode}; use serde::Deserialize; use std::collections::{BTreeMap, BTreeSet, HashMap}; -const ZH_CN: &str = include_str!("../../../config/i18n/zh-CN.toml"); -const EN: &str = include_str!("../../../config/i18n/en.toml"); +const ZH_CN: &str = include_str!("../assets/i18n/zh-CN.toml"); +const EN: &str = include_str!("../assets/i18n/en.toml"); #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] @@ -46,8 +46,7 @@ impl TextCatalog { validate_language(language)?; let embedded = TextCatalog::parse(match language { "zh-CN" => ZH_CN, - "en" => EN, - _ => unreachable!(), + _ => EN, })?; validate_shared_placeholders(self, &embedded, language, "embedded") } @@ -87,17 +86,17 @@ impl TextBundle { ("en".to_owned(), TextCatalog::parse(EN)?), ]); Self::validate_complete_pair(&embedded["zh-CN"], &embedded["en"])?; - let mut external = HashMap::new(); + let mut external: HashMap = HashMap::new(); for (language, catalog) in catalogs { validate_language(&language)?; catalog.validate_language(&language)?; + for (other_language, other) in &external { + catalog.validate_compatible_with(&language, other, other_language)?; + } if external.insert(language.clone(), catalog).is_some() { return Err(format!("duplicate text catalog for language {language}")); } } - if let (Some(zh), Some(en)) = (external.get("zh-CN"), external.get("en")) { - zh.validate_compatible_with("zh-CN", en, "en")?; - } Ok(Self { default_language: default_language.into(), external, @@ -110,35 +109,27 @@ impl TextBundle { candidates: impl IntoIterator)>, ) -> Result<(Self, Vec), String> { validate_language(default_language)?; - let mut accepted = Vec::new(); + let mut candidates = candidates.into_iter().collect::>(); + // Give the configured default priority, then resolve secondary conflicts deterministically. + candidates.sort_by(|(a, _), (b, _)| (a != default_language, a).cmp(&(b != default_language, b))); + let mut accepted: Vec<(String, TextCatalog)> = Vec::new(); let mut reports = Vec::new(); for (language, candidate) in candidates { match candidate.and_then(|catalog| { catalog.validate_language(&language)?; + for (other_language, other) in &accepted { + if language == *other_language { + return Err(format!("duplicate text catalog for language {language}")); + } + catalog.validate_compatible_with(&language, other, other_language)?; + } Ok(catalog) }) { Ok(catalog) => accepted.push((language, catalog)), Err(error) => reports.push(format!("{language} rejected: {error}")), } } - if let Some(default) = accepted - .iter() - .find(|(language, _)| language == default_language) - .map(|(_, catalog)| catalog.clone()) - { - accepted.retain(|(language, catalog)| { - if language == default_language { - return true; - } - match default.validate_compatible_with(default_language, catalog, language) { - Ok(()) => true, - Err(error) => { - reports.push(format!("{language} rejected: {error}")); - false - } - } - }); - } else { + if !accepted.iter().any(|(language, _)| language == default_language) { reports.push(format!("{default_language} missing or invalid; embedded text will be used")); } Ok((Self::load(default_language, accepted)?, reports)) @@ -149,7 +140,7 @@ impl TextBundle { config: &Config, ) -> Result<(Self, Vec), String> { let (mut bundle, mut reports) = Self::load_startup(default_language, candidates)?; - let embedded_default = bundle.embedded.get(default_language).expect("supported locale"); + let embedded_default = bundle.embedded.get(default_language).unwrap_or(&bundle.embedded["en"]); bundle.external.retain(|language, catalog| { if let Err(error) = validate_catalog_mode_values(config, language, catalog, embedded_default) { reports.push(format!("{language} rejected: {error}")); @@ -160,19 +151,20 @@ impl TextBundle { }); Ok((bundle, reports)) } + pub fn external_languages(&self) -> impl Iterator { + self.external.keys().map(String::as_str) + } + /// New locales use the built-in English catalog only after external per-key fallback. + fn embedded_for(&self, language: &str) -> &TextCatalog { + self.embedded.get(language).unwrap_or(&self.embedded["en"]) + } /// Keys absent from this locale's external catalog and therefore resolved by fallback. pub fn missing_keys(&self, language: &str) -> Vec { let Some(catalog) = self.external.get(language) else { - return self - .embedded - .get(&self.default_language) - .map(|c| c.keys().map(str::to_owned).collect()) - .unwrap_or_default(); + return self.embedded_for(&self.default_language).keys().map(str::to_owned).collect(); }; - self.embedded - .get(&self.default_language) - .into_iter() - .flat_map(|c| c.keys()) + self.embedded_for(&self.default_language) + .keys() .filter(|key| catalog.get(key).is_none()) .map(str::to_owned) .collect() @@ -189,10 +181,7 @@ impl TextBundle { { return catalog.render(key, args); } - self.embedded - .get(&self.default_language) - .expect("supported bundle always contains embedded server-default text") - .render(key, args) + self.embedded_for(&self.default_language).render(key, args) } /// Resolve a global label for a nominated server default, rather than falling /// back through the current server's different default language. @@ -203,10 +192,10 @@ impl TextBundle { { return catalog.render(key, args); } - self.embedded[language].render(key, args) + self.embedded_for(language).render(key, args) } - /// Strict package validation: both catalogs must be complete and use matching placeholders. + /// The two built-in catalogs must have the same keys and placeholders. fn validate_complete_pair(zh_cn: &TextCatalog, en: &TextCatalog) -> Result<(), String> { if zh_cn.messages.keys().ne(en.messages.keys()) { let missing_en: Vec<_> = zh_cn.messages.keys().filter(|key| !en.messages.contains_key(*key)).cloned().collect(); @@ -222,19 +211,21 @@ impl TextBundle { } Ok(()) } - pub fn validate_complete_catalogs(zh_cn: &TextCatalog, en: &TextCatalog) -> Result<(), String> { - Self::validate_complete_pair(zh_cn, en)?; - let embedded_zh = TextCatalog::parse(ZH_CN)?; - let embedded_en = TextCatalog::parse(EN)?; - for (language, supplied, embedded) in [("zh-CN", zh_cn, &embedded_zh), ("en", en, &embedded_en)] { - for key in embedded.keys() { - let text = supplied - .get(key) - .ok_or_else(|| format!("{language} catalog is missing required built-in key {key:?}"))?; - if placeholders(text)? != placeholders(embedded.get(key).expect("embedded key"))? { - return Err(format!("{language} catalog {key:?} placeholder set differs from built-in text")); + /// Distribution catalogs must contain all built-in keys and the same custom keys. + pub fn validate_complete_catalogs(&self) -> Result<(), String> { + let default = self + .external + .get(&self.default_language) + .ok_or_else(|| format!("missing default-language catalog: {}", self.default_language))?; + for (language, catalog) in &self.external { + for key in self.embedded_for(&self.default_language).keys().chain(default.keys()) { + if catalog.get(key).is_none() { + return Err(format!("{language} catalog is missing required text key {key:?}")); } } + if catalog.keys().ne(default.keys()) { + return Err(format!("{language} and {} catalog keys differ", self.default_language)); + } } Ok(()) } @@ -245,7 +236,7 @@ impl TextBundle { self.default_language, config.default_language )); } - let embedded_default = self.embedded.get(&self.default_language).expect("supported default locale"); + let embedded_default = self.embedded_for(&self.default_language); let external_default = self.external.get(&self.default_language); for mode in &config.modes { validate_mode_keys(mode, external_default, embedded_default, &self.external)?; @@ -334,11 +325,17 @@ fn validate_shared_placeholders(a: &TextCatalog, b: &TextCatalog, language_a: &s } Ok(()) } -fn validate_language(language: &str) -> Result<(), String> { - if matches!(language, "zh-CN" | "en") { +pub(crate) fn validate_language(language: &str) -> Result<(), String> { + if language.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) + && language + .split(['-', '_']) + .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_alphanumeric())) + { Ok(()) } else { - Err(format!("unsupported text language: {language:?}")) + Err(format!( + "invalid text language {language:?}; use an ASCII language code such as zh-CN, en or pt-BR" + )) } } fn validate_key(key: &str) -> Result<(), String> { diff --git a/crates/funrounds-plugin/src/afterburn.rs b/crates/funrounds-plugin/src/afterburn.rs index 7e5183d..a7aa06f 100644 --- a/crates/funrounds-plugin/src/afterburn.rs +++ b/crates/funrounds-plugin/src/afterburn.rs @@ -62,6 +62,7 @@ struct Life { flame: Option, ignite_pending: bool, waiting_external_effect: bool, + damage_sources: [Option<(f64, funrounds_core::AfterburnSettings)>; 2], } #[derive(Default)] @@ -86,7 +87,7 @@ impl Afterburns { return false; } match self.lives.get_mut(&player.slot) { - Some(life) if life.task == task && life.player == player => life.deadline = deadline, + Some(life) if life.task == task && life.player == player => life.deadline = life.deadline.max(deadline), _ => { self.clear_slot(player.slot); self.lives.insert( @@ -98,6 +99,7 @@ impl Afterburns { flame: None, ignite_pending: false, waiting_external_effect: false, + damage_sources: [None, None], }, ); } @@ -105,10 +107,50 @@ impl Afterburns { true } + pub fn refresh_source( + &mut self, + task: PlayerTask, + player: LivePlayer, + now: f64, + settings: funrounds_core::AfterburnSettings, + hot_floor: bool, + ) -> bool { + if !self.refresh(task, player, now, settings.duration_seconds) { + return false; + } + let life = self.matching_life_mut(task, player).expect("just refreshed life"); + life.damage_sources[usize::from(hot_floor)] = Some((now + f64::from(settings.duration_seconds), settings)); + true + } + + pub fn tick_damage(&self, task: PlayerTask, player: LivePlayer, now: f64, health: i32) -> Option { + self.lives + .get(&player.slot) + .filter(|life| life.task == task && life.player == player)? + .damage_sources + .iter() + .flatten() + .filter(|(deadline, _)| *deadline > now) + .map(|(_, settings)| settings.tick_damage(health)) + .reduce(f32::max) + } + + pub fn hot_floor_active(&self, task: PlayerTask, player: LivePlayer, now: f64) -> bool { + self.lives + .get(&player.slot) + .is_some_and(|life| life.task == task && life.player == player && life.damage_sources[1].is_some_and(|(deadline, _)| deadline > now)) + } + pub fn entries(&self) -> Vec<(PlayerTask, LivePlayer, f64)> { self.lives.values().map(|life| (life.task, life.player, life.deadline)).collect() } + pub fn is_active(&self, task: PlayerTask, player: LivePlayer, now: f64) -> bool { + self.lives + .get(&player.slot) + .is_some_and(|life| life.task == task && life.player == player && life.deadline > now) + } + pub fn queue_ignite(&mut self, task: PlayerTask, player: LivePlayer) -> bool { let Some(life) = self.matching_life_mut(task, player) else { return false; diff --git a/crates/funrounds-plugin/src/autostrafe.rs b/crates/funrounds-plugin/src/autostrafe.rs new file mode 100644 index 0000000..a916659 --- /dev/null +++ b/crates/funrounds-plugin/src/autostrafe.rs @@ -0,0 +1,84 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use crate::fault::{Fault, Mechanism}; +use crate::{RUNTIME, callbacks_active, contain_failure, funrounds_native}; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +pub fn available() -> bool { + unsafe { + match ( + funrounds_native::__funrounds_native_HasAirMoveSupport, + funrounds_native::__funrounds_native_SetAirMoveAssist, + ) { + (Some(query), Some(_)) => query(), + _ => false, + } + } +} + +#[derive(Default, PartialEq, Eq)] +pub enum AirStrafe { + #[default] + Detached, + Attached, + CleanupPending, +} + +impl AirStrafe { + pub fn is_clean(&self) -> bool { + *self == Self::Detached + } + + pub fn retry_cleanup(&mut self) { + if *self == Self::CleanupPending { + *self = Self::Attached; + } + } + + pub fn apply(&mut self, active: bool) -> Result<(), Fault> { + self.apply_with(active, |active| funrounds_native::SetAirMoveAssist(active, assist)) + } + + fn apply_with(&mut self, active: bool, mut set: impl FnMut(bool) -> bool) -> Result<(), Fault> { + if *self == Self::CleanupPending || active == (*self == Self::Attached) { + return Ok(()); + } + if active && set(true) { + *self = Self::Attached; + return Ok(()); + } + if set(false) { + *self = Self::Detached; + return if active { + Err(Fault::mechanism(Mechanism::Autostrafe, "AirMove hook activation failed")) + } else { + Ok(()) + }; + } + *self = Self::CleanupPending; + Err(Fault::global("AirMove hook detach unconfirmed")) + } +} + +unsafe extern "C" fn assist(slot: i32, pawn: i32, controller: i32, yaw: f32, vx: f32, vy: f32, forward: &mut f32, left: &mut f32) -> bool { + catch_unwind(AssertUnwindSafe(|| { + if !callbacks_active() + || !RUNTIME + .try_lock() + .is_ok_and(|guard| guard.as_ref().is_some_and(|runtime| runtime.air_strafe_allowed(slot, pawn, controller))) + { + return false; + } + if let Some((f, l)) = funrounds_core::air_strafe_input(yaw, vx, vy) { + (*forward, *left) = (f, l); + true + } else { + false + } + })) + .unwrap_or_else(|_| { + contain_failure("AirMove assist callback panic contained"); + false + }) +} diff --git a/crates/funrounds-plugin/src/bombs.rs b/crates/funrounds-plugin/src/bombs.rs index c88785f..36a42b0 100644 --- a/crates/funrounds-plugin/src/bombs.rs +++ b/crates/funrounds-plugin/src/bombs.rs @@ -350,6 +350,13 @@ pub struct Action { } impl Action { + pub(crate) fn cleanup_chicken(self) -> Option { + match self.kind { + ActionKind::Cleanup { chicken, .. } => chicken, + _ => None, + } + } + pub fn is_cleanup(self) -> bool { matches!(self.kind, ActionKind::Cleanup { .. } | ActionKind::RemoveEntity { .. }) } @@ -431,6 +438,7 @@ pub fn capabilities( imports!(chicken; __s2sdk_CreateEntityByName, __s2sdk_DispatchSpawn, __s2sdk_SetEntityParent, __s2sdk_AcceptEntityInput, __s2sdk_GetEntityParent, __s2sdk_SetEntityLocalOrigin, + __s2sdk_GetEntityModelScale, __s2sdk_SetEntityModelScale, __s2sdk_GetEntityAngRotation, __s2sdk_GetEntityAbsOrigin, __s2sdk_SetEntityAbsOrigin, __s2sdk_TeleportEntity, __s2sdk_RemoveEntity, ); @@ -660,6 +668,7 @@ pub struct Bombs { quick_defuse: QuickDefuse, pending_plant: Option, newly_planted_native_scale: Option, + newly_created_chicken_scale: Option<(i32, i32)>, native_model_scale_restores: HashSet, planted: Option, completed_chicken: Option, @@ -686,6 +695,7 @@ impl Bombs { self.prestart_cleanup = true; self.prestart_retiring.clear(); self.newly_planted_native_scale = None; + self.newly_created_chicken_scale = None; } pub fn finish_round_prestart_cleanup(&mut self) { @@ -830,6 +840,7 @@ impl Bombs { // Capture it before requiring a player or an active weapon for the optional timing write. self.before_plant = Some((round, entity_handles("planted_c4").into_iter().collect())); self.newly_planted_native_scale = None; + self.newly_created_chicken_scale = None; self.plant_task = task.filter(|task| task.round == round); self.quick_defuse.begin_plant(self.plant_task); self.arming = None; @@ -848,6 +859,19 @@ impl Bombs { }); } + pub(crate) fn is_carrier_chicken(&self, handle: i32) -> bool { + self.planted + .into_iter() + .chain(self.completed_chicken) + .any(|bomb| bomb.chicken == Some(handle)) + || self.retiring.contains(&handle) + || self.pending_actions.values().any(|action| action.cleanup_chicken() == Some(handle)) + } + + pub(crate) fn take_chicken_model_scale_candidate(&mut self) -> Option<(i32, i32)> { + self.newly_created_chicken_scale.take() + } + pub fn take_native_model_scale_candidate(&mut self) -> Option { self.newly_planted_native_scale.take() } @@ -1097,7 +1121,7 @@ impl Bombs { .take_installation(round, &entity_handles("planted_c4")) .map_err(|error| Fault::mechanism(Mechanism::CtBombNoDefuse, error))?; if self.planted.is_some() || self.completed_chicken.is_some() { - return Err("second authoritative planted bomb refused".into()); + return Err(Fault::global("second authoritative planted bomb refused")); } self.planted = Some(Planted { handle, @@ -1592,7 +1616,7 @@ impl Bombs { let result = match action.kind { ActionKind::SpawnChicken { .. } => ActionResult::Chicken(handle), ActionKind::SpawnProxy { .. } => ActionResult::Proxy(handle), - _ => return Err("non-creation bomb action returned a partial creation".into()), + _ => return Err(Fault::global("non-creation bomb action returned a partial creation")), }; (Ok(result), Some(error)) } @@ -1604,6 +1628,9 @@ impl Bombs { if let Some(planted) = self.tracked_planted_mut(round, bomb).filter(|planted| planted.kind == BombKind::Chicken) { planted.chicken = Some(chicken); planted.spawn_pending = false; + if accept_business && !self.cleanup_requested && creation_error.is_none() { + self.newly_created_chicken_scale = Some((bomb, chicken)); + } if self.cleanup_requested || (!accept_business && !self.display_until_prestart) || creation_error.is_some() { self.include_in_queued_cleanup(round, bomb, Some(chicken), None); } @@ -1710,7 +1737,7 @@ impl Bombs { self.prestart_retiring.remove(&handle); Err(error) } - _ => Err("bomb engine action returned an unexpected result".into()), + _ => Err(Fault::global("bomb engine action returned an unexpected result")), }; if let Some(error) = creation_error { if accept_business || error.scope == crate::fault::Scope::Global { @@ -1822,8 +1849,8 @@ impl Bombs { } fn cleanup_active(&mut self) -> Result<(), String> { - if let Some(bomb) = self.planted.filter(|bomb| bomb.kind == BombKind::Native) { - self.native_model_scale_restores.insert(bomb.handle); + if let Some(bomb) = self.planted { + self.queue_native_model_scale_restore(bomb); } self.pending_explosion = None; self.arming = None; @@ -1834,6 +1861,7 @@ impl Bombs { self.plant_weapon = None; self.pending_plant = None; self.newly_planted_native_scale = None; + self.newly_created_chicken_scale = None; self.bouncing.clear(); self.cleanup_requested = true; self.display_until_prestart = false; @@ -1854,8 +1882,14 @@ impl Bombs { } fn queue_native_model_scale_restore(&mut self, bomb: Planted) { - if bomb.kind == BombKind::Native { - self.native_model_scale_restores.insert(bomb.handle); + match bomb.kind { + BombKind::Native => { + self.native_model_scale_restores.insert(bomb.handle); + } + BombKind::Chicken => { + self.native_model_scale_restores.extend(bomb.chicken); + } + BombKind::Carry => {} } } @@ -1869,6 +1903,7 @@ impl Bombs { self.plant_weapon = None; self.pending_plant = None; self.newly_planted_native_scale = None; + self.newly_created_chicken_scale = None; self.native_model_scale_restores.clear(); self.planted = None; self.completed_chicken = None; diff --git a/crates/funrounds-plugin/src/chicken_entities.rs b/crates/funrounds-plugin/src/chicken_entities.rs index 7f806af..ee71c53 100644 --- a/crates/funrounds-plugin/src/chicken_entities.rs +++ b/crates/funrounds-plugin/src/chicken_entities.rs @@ -8,6 +8,8 @@ use funrounds_core::{ }; use plugify::{Str, Vec3}; +pub(crate) const EXPLOSION_PARTICLE: &str = "particles/explosions_fx/explosion_hegrenade.vpcf"; + const BASE_ENTITY: &str = "CBaseEntity"; const EXPLOSION: &str = "CEnvExplosion"; const ZERO: Vec3 = Vec3 { x: 0.0, y: 0.0, z: 0.0 }; @@ -34,8 +36,11 @@ pub(crate) fn available() -> bool { use crate::s2sdk; let imports = unsafe { - std::ptr::addr_of!(s2sdk::__s2sdk_CreateEntityByName).read().is_some() + std::ptr::addr_of!(s2sdk::__s2sdk_FindEntityByClassname).read().is_some() + && std::ptr::addr_of!(s2sdk::__s2sdk_GetEntityClassname).read().is_some() + && std::ptr::addr_of!(s2sdk::__s2sdk_CreateEntityByName).read().is_some() && std::ptr::addr_of!(s2sdk::__s2sdk_DispatchSpawn).read().is_some() + && std::ptr::addr_of!(s2sdk::__s2sdk_DispatchSpawn2).read().is_some() && std::ptr::addr_of!(s2sdk::__s2sdk_RemoveEntity).read().is_some() && std::ptr::addr_of!(s2sdk::__s2sdk_IsValidEntHandle).read().is_some() && std::ptr::addr_of!(s2sdk::__s2sdk_EntHandleToEntPointer).read().is_some() @@ -58,6 +63,7 @@ pub(crate) fn available() -> bool { && std::ptr::addr_of!(s2sdk::__s2sdk_GetClientTeam).read().is_some() }; imports + && crate::suicide::resource_probe().available() && ["m_iHealth", "m_bTakesDamage", "m_lifeState"] .into_iter() .all(|field| s2sdk::GetSchemaOffset(&Str::from_str(BASE_ENTITY), &Str::from_str(field)) >= 0) @@ -83,7 +89,7 @@ pub(crate) fn spawn(origin: Vec3) -> Result { if pointer == 0 || s2sdk::EntPointerToEntHandle(pointer) != handle { return Err("chicken pointer unavailable after spawn".into()); } - // The supported build spawns chickens invulnerable. Keep the normal engine death path. + // Ensure our newly created ordinary chicken uses the normal damage/death path. s2sdk::SetEntSchema2(pointer, &Str::from_str(BASE_ENTITY), &Str::from_str("m_bTakesDamage"), 1, true, 0); if s2sdk::GetEntSchema2(pointer, &Str::from_str(BASE_ENTITY), &Str::from_str("m_bTakesDamage"), 0) != 1 || s2sdk::GetEntSchema2(pointer, &Str::from_str(BASE_ENTITY), &Str::from_str("m_iHealth"), 0) <= 0 @@ -133,7 +139,8 @@ pub(crate) fn position(handle: i32) -> Option { Some(crate::s2sdk::GetEntityAbsOrigin(handle)) } -pub(crate) fn prepare_blast(source: i32, attacker: Option, origin: Vec3, config: ChickenBlastConfig) -> Result<(i32, i32), String> { +/// Shared native explosion setup; behavior registration remains consumer-owned. +pub(crate) fn prepare_explosion(source: i32, attacker: Option, origin: Vec3, config: ChickenBlastConfig) -> Result<(i32, i32), String> { use crate::s2sdk; if !s2sdk::IsValidEntHandle(source) { @@ -227,6 +234,22 @@ fn inflictor_matches(effect: usize, source: i32) -> bool { crate::s2sdk::GetEntSchemaEnt2(effect, &Str::from_str(EXPLOSION), &Str::from_str("m_hInflictor"), 0) == source } +pub(crate) fn detonate_blast(effect: i32, chicken: i32, attacker: i32) { + // Dead or consumed chickens still have a solid hull, which blocks their own + // blast traces. Use the inherited CDynamicProp input to update physics while + // retaining the chicken handle as the inflictor until damage has completed. + crate::s2sdk::AcceptEntityInput( + chicken, + &Str::from_str("DisableCollision"), + chicken, + chicken, + &plugify::Var::default(), + crate::s2sdk::FieldType::Auto, + 0, + ); + detonate(effect, attacker); +} + pub(crate) fn detonate(effect: i32, source: i32) { crate::s2sdk::AcceptEntityInput( effect, @@ -273,6 +296,7 @@ fn same_position(left: Vec3, right: Vec3) -> bool { #[derive(Clone, Debug, PartialEq, Eq)] struct Chicken { + created: bool, round: RoundGeneration, dead: bool, blast_pending: bool, @@ -280,8 +304,8 @@ struct Chicken { killer_weapon: Option, } -/// Full-handle ownership for ordinary chickens and temporary chicken blasts. -/// Map entities are never inferred to be ours from classname alone. +/// Full-handle behavior registration, separate from creation ownership. +/// External chickens participate without granting lifecycle deletion rights. #[derive(Default)] pub(crate) struct Chickens { chickens: HashMap, @@ -290,12 +314,21 @@ pub(crate) struct Chickens { impl Chickens { pub(crate) fn track(&mut self, handle: i32, round: RoundGeneration) -> bool { + self.register(handle, round, true) + } + + pub(crate) fn discover(&mut self, handle: i32, round: RoundGeneration) -> bool { + self.register(handle, round, false) + } + + fn register(&mut self, handle: i32, round: RoundGeneration, created: bool) -> bool { if self.chickens.contains_key(&handle) || self.explosions.contains_key(&handle) { return false; } self.chickens.insert( handle, Chicken { + created, round, dead: false, blast_pending: false, @@ -306,11 +339,18 @@ impl Chickens { true } - pub(crate) fn owns(&self, handle: i32, round: RoundGeneration) -> bool { + pub(crate) fn contains(&self, handle: i32, round: RoundGeneration) -> bool { self.chickens.get(&handle).is_some_and(|chicken| chicken.round == round) } pub(crate) fn owned_handles(&self, round: RoundGeneration) -> Vec { + self.active_handles(round) + .into_iter() + .filter(|handle| self.chickens[handle].created) + .collect() + } + + pub(crate) fn active_handles(&self, round: RoundGeneration) -> Vec { let mut handles = self .chickens .iter() @@ -320,17 +360,16 @@ impl Chickens { handles } - /// Keep living ordinary chickens across a round generation change. Dead or stale - /// handles are returned for removal; temporary blast ownership is round-scoped. + /// Retag living registrations; only plugin-created stale entities may be removed. pub(crate) fn advance_round(&mut self, round: RoundGeneration, mut alive: impl FnMut(i32) -> bool) -> Vec { - let mut stale = self - .chickens - .iter() - .filter_map(|(&handle, chicken)| (chicken.dead || !alive(handle)).then_some(handle)) - .collect::>(); - for handle in &stale { - self.chickens.remove(handle); - } + let mut stale = Vec::new(); + self.chickens.retain(|&handle, chicken| { + let keep = !chicken.dead && alive(handle); + if !keep && chicken.created { + stale.push(handle); + } + keep + }); for chicken in self.chickens.values_mut() { chicken.round = round; chicken.dead = false; @@ -341,7 +380,6 @@ impl Chickens { stale.extend(self.explosions.keys().copied()); self.explosions.clear(); stale.sort_unstable(); - stale.dedup(); stale } @@ -484,7 +522,7 @@ impl Chickens { } pub(crate) fn damage_blocked(&self, damage: EntityDamageSource, round: RoundGeneration, chain: ChickenDamageChainConfig) -> bool { - if !self.owns(damage.victim, round) { + if !self.contains(damage.victim, round) { return false; } let cause = if damage.damage_type & (1 << 3) != 0 { @@ -508,12 +546,20 @@ impl Chickens { self.explosions.clear(); } + pub(crate) fn registered_handles(&self) -> Vec { + self.chickens.keys().copied().collect() + } + pub(crate) fn clear(&mut self) -> Vec { - let mut handles = self.chickens.keys().chain(self.explosions.keys()).copied().collect::>(); + let mut handles = self + .chickens + .iter() + .filter_map(|(&handle, chicken)| chicken.created.then_some(handle)) + .chain(self.explosions.keys().copied()) + .collect::>(); self.chickens.clear(); self.explosions.clear(); handles.sort_unstable(); - handles.dedup(); handles } diff --git a/crates/funrounds-plugin/src/commands.rs b/crates/funrounds-plugin/src/commands.rs index 8c3de26..469d04a 100644 --- a/crates/funrounds-plugin/src/commands.rs +++ b/crates/funrounds-plugin/src/commands.rs @@ -59,6 +59,7 @@ impl Command { ["fr_reload"] => Ok(Self::Reload), ["fr_enable", "0"] => Ok(Self::Enable(false)), ["fr_enable", "1"] => Ok(Self::Enable(true)), + ["fr_next", "id", id] if !id.is_empty() => Ok(Self::Next(NextMode::Id((*id).into()))), ["fr_next", "random"] => Ok(Self::Next(NextMode::Random)), ["fr_next", id] if !id.is_empty() => Ok(Self::Next(NextMode::Id((*id).into()))), _ => Err("command.usage"), @@ -88,7 +89,7 @@ pub fn client_executable(name: &str) -> bool { ) } -pub fn status_reply_parts(message: &str) -> impl Iterator { +pub fn line_reply_parts(message: &str) -> impl Iterator { // The recovery fixture exposed native single-reply truncation at 2047 bytes. message.lines().flat_map(|mut line| { std::iter::from_fn(move || { @@ -145,12 +146,12 @@ mod tests { "恢复错误".repeat(500), "write failed;".repeat(200) ); - let parts = status_reply_parts(&message).collect::>(); + let parts = line_reply_parts(&message).collect::>(); assert!(parts.len() > 2); assert!(parts.iter().all(|part| !part.is_empty() && part.len() <= 1024)); assert_eq!(parts.concat(), message); assert_eq!( - status_reply_parts("recovery=Stopped\nfaults=Global:[failure]\nexcluded=sample:[equipment]").collect::>(), + line_reply_parts("recovery=Stopped\nfaults=Global:[failure]\nexcluded=sample:[equipment]").collect::>(), ["recovery=Stopped", "faults=Global:[failure]", "excluded=sample:[equipment]",] ); } diff --git a/crates/funrounds-plugin/src/damage.rs b/crates/funrounds-plugin/src/damage.rs index 94a4271..668ab25 100644 --- a/crates/funrounds-plugin/src/damage.rs +++ b/crates/funrounds-plugin/src/damage.rs @@ -250,8 +250,20 @@ pub fn capture_weapon_class(weapon: i32, inflictor: i32, weapon_kind: i32) -> Op } } -pub fn weapon_scale_class(classname: &str) -> &str { - classname.strip_suffix("_projectile").unwrap_or(classname) +pub fn weapon_scale_id(classname: &str) -> &str { + let id = classname.strip_prefix("weapon_").unwrap_or(classname); + let id = id.strip_suffix("_projectile").unwrap_or(id); + if crate::projectiles::knife_fire_event(id) { "knife" } else { id } +} + +impl Damage { + pub fn is_native_he(&self) -> bool { + !self.skip_plugin_rules + && self.damage_type & DMG_FALL == 0 + && self.inflictor != -1 + && s2sdk::IsValidEntHandle(self.inflictor) + && s2sdk::GetEntityClassname(self.inflictor).as_str() == "hegrenade_projectile" + } } fn normalize_event_weapon(classname: &str) -> Option { @@ -288,7 +300,7 @@ pub struct EntityBridge { impl EntityBridge { pub fn subscribe(callback: crate::funrounds_native::EntityDamagePreCallback) -> (Option, bool) { - // These three imports are optional additions to the native ABI. + // These three imports were added after the original native ABI. // They are optional for existing installations, so check the whole new // surface before calling any generated wrapper (which expects imports). let imports_available = unsafe { diff --git a/crates/funrounds-plugin/src/effects.rs b/crates/funrounds-plugin/src/effects.rs index cd3b706..777b1ba 100644 --- a/crates/funrounds-plugin/src/effects.rs +++ b/crates/funrounds-plugin/src/effects.rs @@ -24,7 +24,7 @@ pub(crate) use ghost::{ pub(crate) use recoil::{firearm_event, recoil_schema_probe, recoil_shake_probe}; pub(crate) use render::probe as translucent_probe; pub(crate) use third_person::{discard_map_targets as discard_third_person_map_targets, probe as third_person_probe}; -pub(crate) use view::{crosshair_probe, fov_probe, no_scope_probe}; +pub(crate) use view::{crosshair_probe, fov_probe, hide_all_hud_probe, no_scope_probe}; pub(crate) use weapon_rules::{fast_switch_probe, single_shot_probe}; pub(crate) fn c4_removal_probe() -> crate::capability::Probe { @@ -75,6 +75,9 @@ pub struct Effect { helmet: bool, gravity: f32, gravity_written: Option, + gravity_relinquished: bool, + temporary_movement: Option, + movement_wait_for_release: u64, was_on_ladder: bool, speed: f32, base_speed: f32, @@ -107,6 +110,19 @@ struct OwnedRgb { written: [Option; 3], } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum TemporaryMovementOwner { + WallHang, + Grapple, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct TemporaryMovement { + owner: TemporaryMovementOwner, + previous_gravity: f32, + installed_gravity: f32, +} + impl Effect { pub fn capture( player: LivePlayer, @@ -131,11 +147,16 @@ impl Effect { diagnostics, health: s2sdk::GetClientHealth(player.slot), armor: s2sdk::GetClientArmor(player.slot), - max_health: mode_max_health(mode, attributes.health).map(|_| read_max_health(player)).transpose()?, + max_health: mode_max_health(mode, attributes.health) + .map(|_| read_max_health(player).map_err(Fault::round)) + .transpose()?, max_health_written: None, - helmet: player.helmet()?, + helmet: player.helmet().map_err(Fault::round)?, gravity: s2sdk::GetClientGravity(player.slot), gravity_written: None, + gravity_relinquished: false, + temporary_movement: None, + movement_wait_for_release: 0, was_on_ladder: false, speed: s2sdk::GetClientSpeed(player.slot), base_speed: mode.speed, @@ -166,8 +187,12 @@ impl Effect { if self.round != round || self.identity.pawn_handle != identity.pawn_handle || player.pawn_handle as u32 != identity.pawn_handle { return Err(Fault::cancelled("effect pawn changed during bot takeover")); } + // A takeover may replace the controller while retaining this exact pawn. + // Move the lease to the new current LivePlayer before trying to restore it. self.player = player; self.identity = identity; + self.movement_wait_for_release |= (1 << 1) | (1 << 5); + self.release_temporary_movement()?; self.weapon_rules.takeover(player, mode); if let Some(translucent) = &mut self.translucent { translucent.takeover(player, identity, round)?; @@ -200,7 +225,28 @@ impl Effect { } fn update_fixed_gravity_after_ladder(&mut self, mode: &Mode) -> Result<(), Fault> { - if mode.periodic_gravity || self.gravity_written.is_none() { + if let Some(temporary) = self.temporary_movement { + if read_move_type(self.player).map_err(|error| Fault::mechanism(Mechanism::Classic, error))? == SOURCE2_MOVE_TYPE_LADDER { + self.was_on_ladder = true; + } + let current = s2sdk::GetClientGravity(self.player.slot); + if speed_matches(current, temporary.installed_gravity) { + return Ok(()); + } + // Use the same ownership decision as explicit release: a ladder's + // native reset must not revoke the mode's gravity for this life. + self.release_temporary_movement()?; + } + if self.gravity_relinquished { + return Ok(()); + } + if mode.periodic_gravity.is_some() { + if read_move_type(self.player).map_err(|error| Fault::mechanism(Mechanism::PeriodicGravity, error))? == SOURCE2_MOVE_TYPE_LADDER { + self.was_on_ladder = true; + } + return Ok(()); + } + if self.gravity_written.is_none() { self.was_on_ladder = false; return Ok(()); } @@ -211,6 +257,7 @@ impl Effect { self.was_on_ladder = true; if self.gravity_written.is_some_and(|written| !speed_matches(current_gravity, written)) && !speed_matches(current_gravity, 1.0) { self.gravity_written = None; + self.gravity_relinquished = true; self.was_on_ladder = false; } return Ok(()); @@ -223,6 +270,7 @@ impl Effect { .map_err(|error| Fault::mechanism(Mechanism::Classic, error))?; } else { self.gravity_written = None; + self.gravity_relinquished = true; } } Ok(()) @@ -296,25 +344,32 @@ impl Effect { health = decayed; } } - if (mode.health_speed || mode.periodic_speed || !speed_matches(self.base_speed, 1.0)) && !speed_owned { + if (mode.health_speed + || mode.periodic_speed.is_some() + || !speed_matches(self.base_speed, 1.0) + || mode.ghost.is_some_and(|ghost| ghost.speed_multiplier != 1.0)) + && !speed_owned + { + let base_speed = composed_speed(self.base_speed, ghost_speed_multiplier(mode, self.player.slot), 1.0) + .map_err(|error| Fault::mechanism(Mechanism::Classic, error))?; let health_scale = if mode.health_speed { mode.health_curve.scaling(health, self.attributes.health).1 } else { 1.0 }; - let periodic_scale = if mode.periodic_speed { - self.movement_scale.map_or(1.0, |movement| movement.speed) + let periodic_scale = if mode.periodic_speed.is_some() { + self.movement_scale.and_then(|movement| movement.speed).unwrap_or(1.0) } else { 1.0 }; let mechanism = if mode.health_speed { Mechanism::HealthSpeed - } else if mode.periodic_speed { + } else if mode.periodic_speed.is_some() { Mechanism::PeriodicSpeed } else { Mechanism::Classic }; - let speed = composed_speed(self.base_speed, health_scale, periodic_scale).map_err(|error| Fault::mechanism(mechanism, error))?; + let speed = composed_speed(base_speed, health_scale, periodic_scale).map_err(|error| Fault::mechanism(mechanism, error))?; if !speed_matches(s2sdk::GetClientSpeed(slot), speed) { self.speed_written = Some(speed); s2sdk::SetClientSpeed(slot, speed); @@ -330,8 +385,24 @@ impl Effect { if LivePlayer::resolve(self.player.slot) != Some(self.player) { return Err(Fault::cancelled("player identity changed before periodic movement update")); } - let periodic_speed = (mode.periodic_speed && !speed_owned) - .then(|| { + if movement.gravity.is_some() && self.temporary_movement.is_none() && !self.gravity_relinquished { + let on_ladder = self.was_on_ladder + && read_move_type(self.player).map_err(|error| Fault::mechanism(Mechanism::PeriodicGravity, error))? == SOURCE2_MOVE_TYPE_LADDER; + let current_gravity = s2sdk::GetClientGravity(self.player.slot); + if self.gravity_written.is_some_and(|written| !speed_matches(current_gravity, written)) + && !(self.was_on_ladder && speed_matches(current_gravity, 1.0)) + { + self.gravity_written = None; + self.gravity_relinquished = true; + } + if !on_ladder { + self.was_on_ladder = false; + } + } + let periodic_speed = movement + .speed + .filter(|_| mode.periodic_speed.is_some() && !speed_owned) + .map(|periodic_scale| { let health_scale = if mode.health_speed { mode.health_curve .scaling(s2sdk::GetClientHealth(self.player.slot), self.attributes.health) @@ -339,15 +410,29 @@ impl Effect { } else { 1.0 }; - composed_speed(self.base_speed, health_scale, movement.speed) + let base_speed = composed_speed(self.base_speed, ghost_speed_multiplier(mode, self.player.slot), 1.0)?; + composed_speed(base_speed, health_scale, periodic_scale) }) .transpose() .map_err(|error| Fault::mechanism(Mechanism::PeriodicSpeed, error))?; - let periodic_gravity = mode.periodic_gravity.then_some(mode.gravity * movement.gravity); - if self.movement_scale == Some(movement) - && periodic_speed.is_none_or(|speed| speed_owned || speed_matches(s2sdk::GetClientSpeed(self.player.slot), speed)) - && periodic_gravity.is_none_or(|gravity| speed_matches(s2sdk::GetClientGravity(self.player.slot), gravity)) - { + let periodic_gravity = movement + .gravity + .filter(|_| mode.periodic_gravity.is_some()) + .map(|scale| composed_gravity(mode.gravity, scale)) + .transpose() + .map_err(|error| Fault::mechanism(Mechanism::PeriodicGravity, error))? + .filter(|_| self.temporary_movement.is_none() && !self.gravity_relinquished); + let speed_matches_current = movement.speed.is_none() + || speed_owned + || mode.periodic_speed.is_none() + || periodic_speed.is_some_and(|speed| speed_matches(s2sdk::GetClientSpeed(self.player.slot), speed)); + let gravity_matches_current = movement.gravity.is_none() + || mode.periodic_gravity.is_none() + || self.temporary_movement.is_some() + || self.gravity_relinquished + || periodic_gravity.is_some_and(|gravity| speed_matches(s2sdk::GetClientGravity(self.player.slot), gravity)); + if speed_matches_current && gravity_matches_current { + self.movement_scale = Some(merge_movement_scale(self.movement_scale, movement)); return Ok(()); } if let Some(speed) = periodic_speed.filter(|_| !speed_owned) @@ -367,11 +452,197 @@ impl Effect { if periodic_gravity.is_some_and(|gravity| !speed_matches(s2sdk::GetClientGravity(self.player.slot), gravity)) { return Err(Fault::mechanism(Mechanism::PeriodicGravity, "periodic gravity write failed")); } - self.movement_scale = Some(movement); + self.movement_scale = Some(merge_movement_scale(self.movement_scale, movement)); + Ok(()) + } + + pub(crate) fn temporary_movement_owner(&self) -> Option { + self.temporary_movement.map(|state| state.owner) + } + + pub(crate) fn movement_waits_for_release(&self, button_mask: u64) -> bool { + self.movement_wait_for_release & button_mask != 0 + } + + pub(crate) fn observe_movement_buttons(&mut self, buttons: u64) { + self.movement_wait_for_release &= buttons; + } + + pub(crate) fn interrupt_temporary_movement(&mut self) -> Result<(), Fault> { + let movement_buttons = (1 << 1) | (1 << 5); + self.stop_temporary_movement(movement_buttons) + } + + pub(crate) fn stop_temporary_movement(&mut self, wait_for_release: u64) -> Result<(), Fault> { + self.movement_wait_for_release |= s2sdk::GetClientButtons(self.player.slot, 0) & wait_for_release; + self.release_temporary_movement() + } + + pub(crate) fn acquire_temporary_movement(&mut self, owner: TemporaryMovementOwner, gravity: f32) -> Result<(), Fault> { + let mechanism = match owner { + TemporaryMovementOwner::WallHang => Mechanism::WallHang, + TemporaryMovementOwner::Grapple => Mechanism::Grapple, + }; + if !gravity.is_finite() { + return Err(Fault::mechanism(mechanism, "temporary movement gravity is not finite")); + } + if let Some(existing) = self.temporary_movement { + if existing.owner == owner { + return Ok(()); + } + self.release_temporary_movement()?; + } + if self.gravity_relinquished || LivePlayer::resolve_present(self.player.slot) != Some(self.player) { + return Err(Fault::cancelled("temporary movement pawn is stale or gravity ownership was relinquished")); + } + let previous = s2sdk::GetClientGravity(self.player.slot); + if !previous.is_finite() { + return Err(Fault::mechanism(mechanism, "temporary movement gravity snapshot is not finite")); + } + if !speed_matches(previous, gravity) { + s2sdk::SetClientGravity(self.player.slot, gravity); + } + let current = s2sdk::GetClientGravity(self.player.slot); + if !speed_matches(current, gravity) { + return Err(Fault::mechanism(mechanism, "temporary movement gravity write failed")); + } + self.temporary_movement = Some(TemporaryMovement { + owner, + previous_gravity: previous, + installed_gravity: gravity, + }); + Ok(()) + } + + pub(crate) fn release_temporary_movement(&mut self) -> Result<(), Fault> { + let Some(state) = self.temporary_movement else { + return Ok(()); + }; + if !s2sdk::IsValidEntHandle(self.player.pawn_handle) + || s2sdk::EntHandleToEntPointer(self.player.pawn_handle) == 0 + || s2sdk::EntPointerToEntHandle(s2sdk::EntHandleToEntPointer(self.player.pawn_handle)) != self.player.pawn_handle + { + // The captured entity no longer exists; its old property cannot be reached or affect a new life. + self.temporary_movement = None; + self.gravity_written = None; + return Ok(()); + } + if LivePlayer::resolve_present(self.player.slot) != Some(self.player) { + return Err(Fault::cancelled( + "captured movement pawn is still valid but no longer current; snapshot retained", + )); + } + let current = s2sdk::GetClientGravity(self.player.slot); + if !speed_matches(current, state.installed_gravity) { + let mechanism = match state.owner { + TemporaryMovementOwner::WallHang => Mechanism::WallHang, + TemporaryMovementOwner::Grapple => Mechanism::Grapple, + }; + let ladder_reset = speed_matches(current, 1.0) + && (self.was_on_ladder + || read_move_type(self.player).map_err(|error| Fault::mechanism(mechanism, error))? == SOURCE2_MOVE_TYPE_LADDER); + if ladder_reset { + self.was_on_ladder = true; + self.movement_wait_for_release |= s2sdk::GetClientButtons(self.player.slot, 0) & ((1 << 1) | (1 << 5)); + } else { + // A second writer owns gravity now; do not reclaim it this life. + self.temporary_movement = None; + self.gravity_written = None; + self.gravity_relinquished = true; + self.movement_wait_for_release |= s2sdk::GetClientButtons(self.player.slot, 0) & ((1 << 1) | (1 << 5)); + return Ok(()); + } + } + if !speed_matches(current, state.previous_gravity) { + s2sdk::SetClientGravity(self.player.slot, state.previous_gravity); + } + if !speed_matches(s2sdk::GetClientGravity(self.player.slot), state.previous_gravity) { + let mechanism = match state.owner { + TemporaryMovementOwner::WallHang => Mechanism::WallHang, + TemporaryMovementOwner::Grapple => Mechanism::Grapple, + }; + return Err(Fault::mechanism(mechanism, "temporary movement gravity restoration failed")); + } + self.temporary_movement = None; + Ok(()) + } + + pub(crate) fn update_wall_hang(&mut self, enabled: bool) -> Result<(), Fault> { + const IN_JUMP: u64 = 1 << 1; + const ON_GROUND: i32 = 1; + let active_owner = self.temporary_movement_owner(); + if (!enabled && active_owner.is_none()) || active_owner == Some(TemporaryMovementOwner::Grapple) { + return Ok(()); + } + if LivePlayer::resolve_present(self.player.slot) != Some(self.player) { + return Err(Fault::cancelled("player identity changed before wall-hang update")); + } + let buttons = s2sdk::GetClientButtons(self.player.slot, 0); + self.observe_movement_buttons(buttons); + if !enabled { + self.movement_wait_for_release |= buttons & IN_JUMP; + self.release_temporary_movement()?; + return Ok(()); + } + let jump_held = wall_hang_jump_held(self.player)?; + if !crate::funrounds_native::HasPlayerMovementHullSupport() { + return Err(Fault::mechanism(Mechanism::WallHang, "native movement-hull support became unavailable")); + } + if self.movement_waits_for_release(IN_JUMP) { + return Ok(()); + } + let walk = s2sdk::GetEntityMoveType(self.player.pawn_handle) == s2sdk::MoveType::Walk; + let airborne = s2sdk::GetClientFlags(self.player.slot) & ON_GROUND == 0; + if !walk || !airborne || !jump_held { + if active_owner == Some(TemporaryMovementOwner::WallHang) { + if !walk && jump_held { + self.movement_wait_for_release |= IN_JUMP; + } + self.release_temporary_movement()?; + if self.diagnostics { + s2sdk::PrintToServer(&Str::from_str(&format!( + "[FunRounds] wall_hang=released slot={} pawn={} reason={}", + self.player.slot, + self.player.pawn_handle, + if !walk { + "movement_type" + } else if !airborne { + "landed" + } else { + "jump_released" + }, + ))); + } + } + return Ok(()); + } + let touching_world = wall_hang_world_contact(self.player)?; + if active_owner == Some(TemporaryMovementOwner::WallHang) { + if !touching_world { + self.release_temporary_movement()?; + if self.diagnostics { + s2sdk::PrintToServer(&Str::from_str(&format!( + "[FunRounds] wall_hang=released slot={} pawn={} reason=contact_lost qualification_retained=1", + self.player.slot, self.player.pawn_handle + ))); + } + return Ok(()); + } + stop_temporary_player_velocity(self.player, Mechanism::WallHang)?; + } else if touching_world { + self.acquire_temporary_movement(TemporaryMovementOwner::WallHang, 0.0)?; + stop_temporary_player_velocity(self.player, Mechanism::WallHang)?; + if self.diagnostics { + s2sdk::PrintToServer(&Str::from_str(&format!( + "[FunRounds] wall_hang=latched slot={} pawn={} gravity=0", + self.player.slot, self.player.pawn_handle + ))); + } + } Ok(()) } - pub fn self_push(&self, player: LivePlayer, weapon: &str) -> Result<(), Fault> { + pub fn self_push(&mut self, player: LivePlayer, weapon: &str) -> Result<(), Fault> { if player != self.player || LivePlayer::resolve(player.slot) != Some(player) { return Err(Fault::cancelled("player identity changed before self-push")); } @@ -387,6 +658,7 @@ impl Effect { if self_push_suppressed(buttons, s2sdk::GetClientFlags(player.slot)) { return Ok(()); } + self.interrupt_temporary_movement()?; let before = s2sdk::GetClientAbsVelocity(player.slot); let angles = s2sdk::GetClientEyeAngles(player.slot); let velocity = self_push_velocity(before, angles, force); @@ -416,35 +688,38 @@ impl Effect { ensure_equipment_action_current(¤t)?; let result: Result<(), Fault> = (|| { if let Some(max_health) = mode_max_health(mode, self.attributes.health) { - self.write_owned_max_health(max_health) - .map_err(|error| Fault::mechanism(Mechanism::Classic, error))?; + self.write_owned_max_health(max_health).map_err(Fault::round)?; } s2sdk::SetClientHealth(self.player.slot, i32::from(self.attributes.health)); s2sdk::SetClientArmor(self.player.slot, i32::from(self.attributes.armor)); - self.player.set_helmet(self.attributes.helmet)?; - if !speed_matches(s2sdk::GetClientSpeed(self.player.slot), mode.speed) { - self.speed_written = Some(mode.speed); - s2sdk::SetClientSpeed(self.player.slot, mode.speed); + self.player.set_helmet(self.attributes.helmet).map_err(Fault::round)?; + let speed = composed_speed(self.base_speed, ghost_speed_multiplier(mode, self.player.slot), 1.0).map_err(Fault::round)?; + if !speed_matches(s2sdk::GetClientSpeed(self.player.slot), speed) { + self.speed_written = Some(speed); + s2sdk::SetClientSpeed(self.player.slot, speed); } - if !speed_matches(s2sdk::GetClientSpeed(self.player.slot), mode.speed) { - return Err(Fault::mechanism(Mechanism::Classic, "base speed write verification failed")); + if !speed_matches(s2sdk::GetClientSpeed(self.player.slot), speed) { + return Err(Fault::round("base speed write verification failed")); } - self.write_owned_gravity(mode.gravity) - .map_err(|error| Fault::mechanism(Mechanism::Classic, error))?; + self.write_owned_gravity(mode.gravity).map_err(Fault::round)?; if let (Some(_), Some(rgb)) = (&self.color, mode.color) { self.write_owned_rgb(rgb.map(f32::from)) .map_err(|error| Fault::mechanism(Mechanism::Color, error))?; } self.view.apply(self.player, self.round, mode, s2sdk::GetGameTime())?; self.weapon_rules.update(self.player, mode)?; + if s2sdk::GetClientHealth(self.player.slot) != i32::from(self.attributes.health) { + return Err(Fault::round("health write verification failed")); + } + if s2sdk::GetClientArmor(self.player.slot) != i32::from(self.attributes.armor) { + return Err(Fault::round("armor write verification failed")); + } + if self.player.helmet().map_err(Fault::round)? != self.attributes.helmet { + return Err(Fault::round("helmet write verification failed")); + } let gravity = s2sdk::GetClientGravity(self.player.slot); - if s2sdk::GetClientHealth(self.player.slot) != i32::from(self.attributes.health) - || s2sdk::GetClientArmor(self.player.slot) != i32::from(self.attributes.armor) - || self.player.helmet()? != self.attributes.helmet - || !gravity.is_finite() - || (gravity - mode.gravity).abs() > 0.0001 - { - return Err("engine property write verification failed".into()); + if !gravity.is_finite() || (gravity - mode.gravity).abs() > 0.0001 { + return Err(Fault::round("gravity write verification failed")); } Ok(()) })(); @@ -518,7 +793,7 @@ impl Effect { .filter(|handle| s2sdk::IsValidEntHandle(*handle)) .map(|handle| (handle, s2sdk::GetEntityClassname(handle).to_string())) .collect::>(); - return Err(Fault::global(format!( + return Err(Fault::round(format!( "deferred loadout confirmation failed slot={} requested={} handle={} valid={valid} returned_class={} expected_definition={:?} actual_definition={item_definition_label} owner={} pawn={} in_inventory={} current_weapons={current_weapons:?} issued_tick={} current_tick={current_tick}", self.player.slot, pending.requested, @@ -640,7 +915,7 @@ impl Effect { } pub(crate) fn recovery_complete(&self) -> bool { - self.equipment_restored() && self.third_person.is_clean() + self.equipment_restored() && self.third_person.is_clean() && self.temporary_movement.is_none() } pub fn rollback_ready(&self) -> bool { @@ -658,6 +933,9 @@ impl Effect { { errors.push(error); } + if let Err(error) = self.release_temporary_movement() { + errors.push(error.to_string()); + } if let Err(error) = self.restore_failed_equipment(refills, true) { errors.push(error); } @@ -723,8 +1001,10 @@ impl Effect { } pub fn restore_retired_state(&mut self, refills: &mut equipment::Refills) -> Result<(), String> { + let movement = self.release_temporary_movement().map_err(|error| error.to_string()); finish_rollback( [ + movement, self.translucent.as_mut().map_or(Ok(()), render::Translucent::restore), self.restore_failed_equipment(refills, false), self.restore_owned_max_health(), @@ -790,6 +1070,9 @@ impl Effect { } fn write_owned_gravity(&mut self, gravity: f32) -> Result<(), String> { + if self.gravity_relinquished || self.temporary_movement.is_some() { + return Ok(()); + } let before = s2sdk::GetClientGravity(self.player.slot); if !speed_matches(before, gravity) { s2sdk::SetClientGravity(self.player.slot, gravity); @@ -804,6 +1087,9 @@ impl Effect { } fn restore_owned_gravity(&mut self) -> Result<(), String> { + if self.temporary_movement.is_some() || self.gravity_relinquished { + return Ok(()); + } if LivePlayer::resolve_present(self.player.slot) != Some(self.player) { return Ok(()); } @@ -931,6 +1217,12 @@ fn run_equipment_action(current: &impl Fn() -> bool, action: impl FnOnce() -> Ok(result) } +fn ghost_speed_multiplier(mode: &Mode, slot: i32) -> f32 { + mode.ghost + .filter(|settings| settings.team.matches(s2sdk::GetClientTeam(slot) as i32)) + .map_or(1.0, |settings| settings.speed_multiplier) +} + fn composed_speed(base: f32, health: f32, periodic: f32) -> Result { let speed = base * health * periodic; if !speed.is_finite() || speed <= 0.0 { @@ -939,6 +1231,22 @@ fn composed_speed(base: f32, health: f32, periodic: f32) -> Result Result { + let gravity = base * periodic; + if !base.is_finite() || base <= 0.0 || !periodic.is_finite() || periodic <= 0.0 || !gravity.is_finite() || gravity <= 0.0 { + return Err("combined movement gravity must be finite and positive"); + } + Ok(gravity) +} + +fn merge_movement_scale(current: Option, update: funrounds_core::MovementScale) -> funrounds_core::MovementScale { + let current = current.unwrap_or(funrounds_core::MovementScale { speed: None, gravity: None }); + funrounds_core::MovementScale { + speed: update.speed.or(current.speed), + gravity: update.gravity.or(current.gravity), + } +} + fn owned_speed_to_restore(before: f32, written: Option, current: f32) -> Option { written.filter(|last| speed_matches(current, *last)).map(|_| before) } @@ -1014,7 +1322,8 @@ fn read_max_health(player: LivePlayer) -> Result { } fn read_move_type(player: LivePlayer) -> Result { - if LivePlayer::resolve(player.slot) != Some(player) { + // Cleanup also reads the captured pawn after death, before it is removed. + if LivePlayer::resolve_present(player.slot) != Some(player) { return Err("player identity changed before move-type access".into()); } if s2sdk::GetSchemaOffset(&Str::from_str(MOVE_TYPE_CLASS), &Str::from_str(MOVE_TYPE_FIELD)) < 0 { @@ -1032,6 +1341,186 @@ fn read_move_type(player: LivePlayer) -> Result { )) } +fn wall_hang_jump_held(player: LivePlayer) -> Result { + const IN_JUMP: i64 = 1 << 1; + let fail = |reason: &str| Fault::mechanism(Mechanism::WallHang, reason); + if LivePlayer::resolve_present(player.slot) != Some(player) { + return Err(Fault::cancelled("player identity changed before jump state read")); + } + for (class, field) in [ + ("CBasePlayerPawn", "m_pMovementServices"), + ("CPlayer_MovementServices", "m_nQueuedButtonDownMask"), + ("CPlayer_MovementServices", "m_nQueuedButtonChangeMask"), + ("CPlayer_MovementServices", "m_nButtons"), + ("CInButtonState", "m_pButtonStates"), + ] { + if s2sdk::GetSchemaOffset(&Str::from_str(class), &Str::from_str(field)) < 0 { + return Err(fail("live player jump-input schema unavailable")); + } + } + let pawn = s2sdk::EntHandleToEntPointer(player.pawn_handle); + if pawn == 0 || s2sdk::EntPointerToEntHandle(pawn) != player.pawn_handle { + return Err(Fault::cancelled("player pawn handle changed before jump state read")); + } + let movement = s2sdk::GetEntSchema2(pawn, &Str::from_str("CBasePlayerPawn"), &Str::from_str("m_pMovementServices"), 0) as usize; + if movement == 0 { + return Err(fail("live player movement services unavailable")); + } + let button_state = s2sdk::GetEntSchema2(movement, &Str::from_str("CPlayer_MovementServices"), &Str::from_str("m_nButtons"), 0) as usize; + if button_state == 0 { + return Err(fail("live player button state unavailable")); + } + let queued_down = s2sdk::GetEntSchema2( + movement, + &Str::from_str("CPlayer_MovementServices"), + &Str::from_str("m_nQueuedButtonDownMask"), + 0, + ); + let queued_change = s2sdk::GetEntSchema2( + movement, + &Str::from_str("CPlayer_MovementServices"), + &Str::from_str("m_nQueuedButtonChangeMask"), + 0, + ); + let down = s2sdk::GetEntSchema2(button_state, &Str::from_str("CInButtonState"), &Str::from_str("m_pButtonStates"), 0); + if LivePlayer::resolve_present(player.slot) != Some(player) { + return Err(Fault::cancelled("player identity changed while reading jump input")); + } + let held = if queued_change & IN_JUMP != 0 { + queued_down & IN_JUMP != 0 + } else { + down & IN_JUMP != 0 + }; + Ok(held) +} + +fn wall_hang_world_contact(player: LivePlayer) -> Result { + const SWEEP_DISTANCE: f32 = 2.0; + const INSET: f32 = 0.5; + const DIAGONAL: f32 = std::f32::consts::FRAC_1_SQRT_2; + const DIRECTIONS: [(f32, f32); 8] = [ + (1.0, 0.0), + (DIAGONAL, DIAGONAL), + (0.0, 1.0), + (-DIAGONAL, DIAGONAL), + (-1.0, 0.0), + (-DIAGONAL, -DIAGONAL), + (0.0, -1.0), + (DIAGONAL, -DIAGONAL), + ]; + let mechanism = Mechanism::WallHang; + let fail = |reason: &str| Fault::mechanism(mechanism, reason); + if LivePlayer::resolve_present(player.slot) != Some(player) + || !s2sdk::IsValidEntHandle(player.pawn_handle) + || s2sdk::EntHandleToEntPointer(player.pawn_handle) == 0 + { + return Err(Fault::cancelled("wall-hang pawn identity changed before hull query")); + } + for (class, field) in [ + ("CBaseEntity", "m_pCollision"), + ("CCollisionProperty", "m_vecMins"), + ("CCollisionProperty", "m_vecMaxs"), + ] { + if s2sdk::GetSchemaOffset(&Str::from_str(class), &Str::from_str(field)) < 0 { + return Err(fail("live pawn collision-hull schema unavailable")); + } + } + let pawn = s2sdk::EntHandleToEntPointer(player.pawn_handle); + let collision = s2sdk::GetEntSchema2(pawn, &Str::from_str("CBaseEntity"), &Str::from_str("m_pCollision"), 0) as usize; + if collision == 0 { + return Err(fail("live pawn collision property unavailable")); + } + let entity_mins = s2sdk::GetEntSchemaVector3D2(collision, &Str::from_str("CCollisionProperty"), &Str::from_str("m_vecMins"), 0); + let entity_maxs = s2sdk::GetEntSchemaVector3D2(collision, &Str::from_str("CCollisionProperty"), &Str::from_str("m_vecMaxs"), 0); + if ![entity_mins.x, entity_mins.y, entity_mins.z, entity_maxs.x, entity_maxs.y, entity_maxs.z] + .iter() + .all(|value| value.is_finite()) + || entity_maxs.x <= entity_mins.x + || entity_maxs.y <= entity_mins.y + || entity_maxs.z - entity_mins.z < 24.0 + { + return Err(fail("live pawn collision hull is malformed")); + } + let mins = Vec3 { + x: entity_mins.x + INSET, + y: entity_mins.y + INSET, + z: entity_mins.z + INSET, + }; + let maxs = Vec3 { + x: entity_maxs.x - INSET, + y: entity_maxs.y - INSET, + z: entity_maxs.z - INSET, + }; + if maxs.x <= mins.x || maxs.y <= mins.y || maxs.z <= mins.z { + return Err(fail("live pawn collision hull is too small for the movement trace")); + } + let origin = s2sdk::GetClientAbsOrigin(player.slot); + if ![origin.x, origin.y, origin.z].iter().all(|value| value.is_finite()) { + return Err(fail("live player origin is not finite")); + } + let mut best_gap = f32::INFINITY; + for (x, y) in DIRECTIONS { + let start = origin; + let end = Vec3 { + x: origin.x + x * SWEEP_DISTANCE, + y: origin.y + y * SWEEP_DISTANCE, + z: origin.z, + }; + let mut position = Vec3::default(); + let mut fraction = f32::NAN; + let mut hit = false; + let mut hit_handle = -1; + let mut start_solid = false; + let mut normal = Vec3::default(); + if !crate::funrounds_native::TracePlayerMovementHull( + player.pawn_handle, + &start, + &end, + &mins, + &maxs, + &mut position, + &mut fraction, + &mut hit, + &mut hit_handle, + &mut start_solid, + &mut normal, + ) { + return Err(fail("native player movement-hull query failed")); + } + if !fraction.is_finite() || !(0.0..=1.0).contains(&fraction) { + return Err(fail("native movement-hull query returned a malformed fraction")); + } + if !hit || start_solid || !s2sdk::IsValidEntHandle(hit_handle) { + continue; + } + if hit_handle != s2sdk::EntIndexToEntHandle(0) || s2sdk::GetEntityClassname(hit_handle).as_str() != "worldent" { + continue; + } + let normal_length = (normal.x * normal.x + normal.y * normal.y + normal.z * normal.z).sqrt(); + if !normal_length.is_finite() || !(0.8..=1.2).contains(&normal_length) { + return Err(fail("native movement-hull query returned a malformed world normal")); + } + let gap = fraction * SWEEP_DISTANCE; + if funrounds_core::wall_hang_contact_eligible(true, true, true, true, start_solid, gap, normal.z) { + best_gap = best_gap.min(gap); + } + } + Ok(best_gap.is_finite()) +} + +fn stop_temporary_player_velocity(player: LivePlayer, mechanism: Mechanism) -> Result<(), Fault> { + if LivePlayer::resolve_present(player.slot) != Some(player) { + return Err(Fault::cancelled("player identity changed before temporary movement velocity clamp")); + } + let zero = Vec3 { x: 0.0, y: 0.0, z: 0.0 }; + s2sdk::SetEntityAbsVelocity(player.pawn_handle, &zero); + let actual = s2sdk::GetEntityAbsVelocity(player.pawn_handle); + if ![actual.x, actual.y, actual.z].iter().all(|value| value.is_finite()) || actual.x.abs() > 0.1 || actual.y.abs() > 0.1 || actual.z.abs() > 0.1 { + return Err(Fault::mechanism(mechanism, "temporary movement velocity clamp failed readback")); + } + Ok(()) +} + fn set_max_health_unverified(player: LivePlayer, max_health: i32) -> Result<(), String> { let pawn = max_health_pawn(player)?; s2sdk::SetEntSchema2( diff --git a/crates/funrounds-plugin/src/effects/equipment.rs b/crates/funrounds-plugin/src/effects/equipment.rs index 64b86b4..712dde7 100644 --- a/crates/funrounds-plugin/src/effects/equipment.rs +++ b/crates/funrounds-plugin/src/effects/equipment.rs @@ -10,7 +10,7 @@ use crate::{ s2sdk, }; pub use funrounds_core::GrenadeKind; -use funrounds_core::{Mode, PlayerTask, TeamFilter, WeaponSlot, weapon_slot}; +use funrounds_core::{Mode, PlayerTask, TeamFilter, WeaponSlot, item_classname, item_id, weapon_slot}; use plugify::Str; use std::collections::{HashMap, HashSet}; @@ -255,7 +255,7 @@ impl Refills { } Ok(Completion::default()) } - _ => Err("equipment engine action returned an unexpected result".into()), + _ => Err(Fault::global("equipment engine action returned an unexpected result")), } } @@ -362,7 +362,7 @@ fn execute_refill(refill: Refill, mut current: impl FnMut() -> bool) -> RefillRe } if s2sdk::GetClientWeapons(player.slot).iter().any(|current| *current == handle) { return result( - Outcome::Failed(crate::fault::Scope::Global), + Outcome::Failed(crate::fault::Scope::Mechanism(Mechanism::GrenadeRefill)), None, "spent item remained in inventory after removal", ); @@ -387,7 +387,7 @@ fn execute_refill(refill: Refill, mut current: impl FnMut() -> bool) -> RefillRe || returned_class.as_deref() != Some(classname) { return result( - Outcome::Failed(crate::fault::Scope::Global), + Outcome::Failed(crate::fault::Scope::Mechanism(Mechanism::GrenadeRefill)), created, &format!("GiveNamedItem returned unusable handle={replacement}"), ); @@ -409,11 +409,19 @@ fn execute_refill(refill: Refill, mut current: impl FnMut() -> bool) -> RefillRe ); } if handle.is_some_and(|handle| s2sdk::GetClientWeapons(player.slot).iter().any(|current| *current == handle)) { - return result(Outcome::Failed(crate::fault::Scope::Global), created, "spent item remained in inventory"); + return result( + Outcome::Failed(crate::fault::Scope::Mechanism(Mechanism::GrenadeRefill)), + created, + "spent item remained in inventory", + ); } let replacement_weapon = s2sdk::EntHandleToEntPointer(replacement); if replacement_weapon == 0 { - return result(Outcome::Failed(crate::fault::Scope::Global), created, "replacement entity unavailable"); + return result( + Outcome::Failed(crate::fault::Scope::Mechanism(Mechanism::GrenadeRefill)), + created, + "replacement entity unavailable", + ); } if !refill.diagnostics { return result(Outcome::Completed, created, ""); @@ -497,11 +505,14 @@ fn shared_item_classname(requested: &str) -> Option<&'static str> { } pub(crate) fn kill_loadout_candidate_matches_classname(requested: &str, classname: &str) -> bool { - shared_item_classname(requested).unwrap_or(requested) == classname + let Some(classname_for_id) = item_id(requested).and_then(item_classname) else { + return false; + }; + shared_item_classname(classname_for_id).unwrap_or(classname_for_id) == classname } pub(crate) fn kill_loadout_source_weapon(classname: &str) -> bool { - classname == "weapon_knife_t" || weapon_slot(classname).is_some() + item_id(classname).is_some_and(|id| weapon_slot(id).is_some()) } pub(crate) fn give_name_for_original(classname: &str, item_definition: u16) -> Option { @@ -655,10 +666,26 @@ impl super::Effect { .filter(|handle| s2sdk::IsValidEntHandle(*handle)) .map(|handle| (handle, s2sdk::GetEntityClassname(handle).to_string())) .collect::>(); - let mut equipment_to_give = if give_weapons { equipment.to_vec() } else { Vec::new() }; - if give_knife && !equipment_to_give.iter().any(|weapon| weapon == "weapon_knife") && (clear_weapons || !inventory_has_knife(&inventory)) { - equipment_to_give.push("weapon_knife".into()); + let mut equipment_ids = if give_weapons { equipment.to_vec() } else { Vec::new() }; + let preserve_knife = give_knife + .then(|| { + inventory + .iter() + .find(|(_, classname)| is_knife_classname(classname)) + .map(|(handle, _)| *handle) + }) + .flatten(); + if give_knife && !equipment_ids.iter().any(|item| item == "knife") && preserve_knife.is_none() { + equipment_ids.push("knife".into()); } + let mut equipment_to_give = equipment_ids + .into_iter() + .map(|item| { + item_classname(&item) + .map(str::to_owned) + .ok_or_else(|| Fault::round(format!("validated equipment item has no engine classname: {item}"))) + }) + .collect::, _>>()?; let previous_targets = if let Some(target) = target { let Some(requested) = equipment_to_give.first() else { return Err(Fault::cancelled("upgrade has no replacement weapon")); @@ -666,7 +693,7 @@ impl super::Effect { upgrade_replacement_targets(&inventory, target, team_weapon(requested, team)) .ok_or_else(|| Fault::cancelled("upgrade target is no longer a valid owned weapon"))? } else if clear_weapons { - replacement_targets(inventory.clone()) + replacement_targets(inventory.clone(), preserve_knife) } else { Vec::new() }; @@ -703,7 +730,7 @@ impl super::Effect { .iter() .any(|current| *current == original.handle) { - return Err("engine did not remove the previous loadout".into()); + return Err(Fault::round("engine did not remove the previous loadout")); } } let requests = equipment_to_give.into_iter().enumerate().collect::>(); @@ -827,7 +854,8 @@ impl super::Effect { mode.id, returned_class.as_deref().unwrap_or(""), ) - })?; + }) + .map_err(Fault::round)?; self.replacement.as_mut().expect("loadout transaction exists").last_grant = Some((handle, outcome, requested_item_matches)); if self.diagnostics && (outcome != EquipmentGrantOutcome::InInventory || (is_random_draw && returned_class.as_deref() != Some(name))) { let current_weapons = inventory @@ -922,9 +950,11 @@ fn team_filter_matches(filter: TeamFilter, team: s2sdk::CSTeam) -> bool { } fn inventory_has_knife(inventory: &[(i32, String)]) -> bool { - inventory - .iter() - .any(|(_, name)| matches!(name.as_str(), "weapon_knife" | "weapon_knife_t")) + inventory.iter().any(|(_, name)| is_knife_classname(name)) +} + +fn is_knife_classname(name: &str) -> bool { + item_id(name) == Some("knife") } fn inventory_has_item(inventory: &[(i32, String)], requested: &str, item_definition_reader: Option u16>) -> bool { @@ -937,13 +967,16 @@ fn inventory_has_item(inventory: &[(i32, String)], requested: &str, item_definit }) } -fn replacement_targets(weapons: impl IntoIterator) -> Vec<(i32, String)> { - weapons.into_iter().filter(|(_, name)| replaces_weapon(name)).collect() +fn replacement_targets(weapons: impl IntoIterator, preserve_knife: Option) -> Vec<(i32, String)> { + weapons + .into_iter() + .filter(|(handle, name)| Some(*handle) != preserve_knife && replaces_weapon(name)) + .collect() } fn upgrade_replacement_targets(weapons: &[(i32, String)], target: i32, requested: &str) -> Option> { let target = weapons.iter().find(|(handle, name)| *handle == target && upgrade_target(name))?; - let target_slot = match weapon_slot(requested) { + let target_slot = match item_id(requested).and_then(weapon_slot) { Some(slot @ (WeaponSlot::Primary | WeaponSlot::Secondary)) => Some(slot), _ => None, }; @@ -951,7 +984,7 @@ fn upgrade_replacement_targets(weapons: &[(i32, String)], target: i32, requested if let Some(target_slot) = target_slot { for weapon in weapons .iter() - .filter(|(handle, name)| *handle != target.0 && weapon_slot(name) == Some(target_slot)) + .filter(|(handle, name)| *handle != target.0 && item_id(name).and_then(weapon_slot) == Some(target_slot)) { if !removed.iter().any(|(handle, _)| *handle == weapon.0) { removed.push(weapon.clone()); @@ -966,7 +999,7 @@ fn upgrade_target(name: &str) -> bool { } fn is_loadout_firearm(name: &str) -> bool { - matches!(weapon_slot(name), Some(WeaponSlot::Primary | WeaponSlot::Secondary)) + matches!(item_id(name).and_then(weapon_slot), Some(WeaponSlot::Primary | WeaponSlot::Secondary)) } fn select_upgrade_firearm( @@ -1576,8 +1609,8 @@ mod tests { (4, "weapon_glock".to_owned()), (5, "weapon_hegrenade".to_owned()), ]; - let removed = super::replacement_targets(inventory.clone()); - assert_eq!(removed, inventory[1..]); + let removed = super::replacement_targets(inventory.clone(), Some(2)); + assert_eq!(removed, inventory[2..]); assert!( inventory .iter() diff --git a/crates/funrounds-plugin/src/effects/ghost.rs b/crates/funrounds-plugin/src/effects/ghost.rs index 45644bb..9651da0 100644 --- a/crates/funrounds-plugin/src/effects/ghost.rs +++ b/crates/funrounds-plugin/src/effects/ghost.rs @@ -18,7 +18,6 @@ use std::{ const IN_ATTACK: u64 = 1 << 0; const IN_DUCK: u64 = 1 << 2; -const IN_JUMP: u64 = 1 << 1; const IN_USE: u64 = 1 << 5; const IN_ATTACK2: u64 = 1 << 11; const IN_RELOAD: u64 = 1 << 13; @@ -867,10 +866,8 @@ fn frame(buttons: u64, flags: i32, weapon_reloading: bool, velocity: Vec3) -> Gh } else { f32::NAN }, - bunny_hop: buttons & (IN_DUCK | IN_JUMP) == (IN_DUCK | IN_JUMP) - && velocity.x.is_finite() - && velocity.y.is_finite() - && velocity.x.hypot(velocity.y) >= 1.0, + grounded: on_ground, + crouching: buttons & IN_DUCK != 0, attacking: buttons & (IN_ATTACK | IN_ATTACK2) != 0, reloading: buttons & IN_RELOAD != 0 || weapon_reloading, using: buttons & IN_USE != 0, diff --git a/crates/funrounds-plugin/src/effects/recoil.rs b/crates/funrounds-plugin/src/effects/recoil.rs index c46e9f2..af69acc 100644 --- a/crates/funrounds-plugin/src/effects/recoil.rs +++ b/crates/funrounds-plugin/src/effects/recoil.rs @@ -412,7 +412,7 @@ fn weapon_pointer(handle: i32, classname: &str) -> Result { } pub(super) fn is_firearm(classname: &str) -> bool { - classname.starts_with("weapon_") && !NON_FIREARM_WEAPONS.contains(&classname) + classname.starts_with("weapon_") && !crate::projectiles::knife_fire_event(classname) && !NON_FIREARM_WEAPONS.contains(&classname) } pub(crate) fn firearm_event(weapon: &str) -> bool { diff --git a/crates/funrounds-plugin/src/effects/view.rs b/crates/funrounds-plugin/src/effects/view.rs index dd365ee..0781100 100644 --- a/crates/funrounds-plugin/src/effects/view.rs +++ b/crates/funrounds-plugin/src/effects/view.rs @@ -14,6 +14,8 @@ const FOV_CLASS: &str = "CBasePlayerController"; const FOV_FIELD: &str = "m_iDesiredFOV"; const HUD_CLASS: &str = "CBasePlayerPawn"; const HUD_FIELD: &str = "m_iHideHUD"; +// SourceSDK HIDEHUD_ALL in CBasePlayerPawn.m_iHideHUD. +const ALL_HUD_BIT: u32 = 1 << 2; const CROSSHAIR_HUD_BIT: u32 = 1 << 8; const SECONDARY_CLASS: &str = "CBasePlayerWeapon"; const SECONDARY_FIELD: &str = "m_nNextSecondaryAttackTick"; @@ -41,6 +43,12 @@ struct CrosshairSnapshot { hidden_by_us: bool, } +#[derive(Clone, Copy)] +struct AllHudSnapshot { + originally_hidden: bool, + hidden_by_us: bool, +} + #[derive(Clone, Copy)] struct SecondaryAttackSnapshot { weapon: i32, @@ -54,6 +62,7 @@ pub(crate) struct ViewEffects { controller_handle: i32, fov: Option, retired_fov: Vec, + all_hud: Option, crosshair: Option, secondary: Option, } @@ -84,12 +93,24 @@ impl ViewEffects { .map_err(|error| Fault::mechanism(Mechanism::Crosshair, error)) }) .transpose()?; + let all_hud = mode + .hide_all_hud + .then(|| { + read_pawn_value(player, HUD_CLASS, HUD_FIELD) + .map(|flags| AllHudSnapshot { + originally_hidden: flags as u32 & ALL_HUD_BIT != 0, + hidden_by_us: false, + }) + .map_err(|error| Fault::mechanism(Mechanism::HideAllHud, error)) + }) + .transpose()?; Ok(Self { identity, round, controller_handle: player.controller_handle, fov, retired_fov: Vec::new(), + all_hud, crosshair, secondary: None, }) @@ -101,6 +122,11 @@ impl ViewEffects { snapshot.applied = Some(desired); write_controller_value(player, FOV_CLASS, FOV_FIELD, desired).map_err(|error| Fault::mechanism(Mechanism::Fov, error))?; } + if let Some(snapshot) = &mut self.all_hud + && !snapshot.hidden_by_us + { + hide_hud_bit(player, ALL_HUD_BIT, &mut snapshot.hidden_by_us).map_err(|error| Fault::mechanism(Mechanism::HideAllHud, error))?; + } if let (Some(snapshot), Some(delay)) = (&mut self.crosshair, mode.hide_crosshair_after) { snapshot.hide_at = Some(now + delay); } @@ -125,12 +151,7 @@ impl ViewEffects { if let Some(snapshot) = &mut self.crosshair && should_hide_crosshair(*snapshot, now) { - let flags = read_pawn_value(player, HUD_CLASS, HUD_FIELD).map_err(|error| Fault::mechanism(Mechanism::Crosshair, error))? as u32; - if flags & CROSSHAIR_HUD_BIT == 0 { - snapshot.hidden_by_us = true; - let hidden = crosshair_mask(flags, true) as i64; - write_pawn_value(player, HUD_CLASS, HUD_FIELD, hidden).map_err(|error| Fault::mechanism(Mechanism::Crosshair, error))?; - } + hide_hud_bit(player, CROSSHAIR_HUD_BIT, &mut snapshot.hidden_by_us).map_err(|error| Fault::mechanism(Mechanism::Crosshair, error))?; snapshot.hide_at = None; } Ok(()) @@ -203,19 +224,18 @@ impl ViewEffects { if let Err(error) = self.restore_controller_fov() { errors.push(error); } - if let Some(snapshot) = self.crosshair - && snapshot.hidden_by_us - && let Some(player) = same_pawn(self.identity.slot, self.identity, self.controller_handle) - { - match read_pawn_value(player, HUD_CLASS, HUD_FIELD) { - Ok(current) if current as u32 & CROSSHAIR_HUD_BIT != 0 => { - let restored = crosshair_mask(current as u32, snapshot.originally_hidden); - if let Err(error) = write_pawn_value(player, HUD_CLASS, HUD_FIELD, i64::from(restored)) { - errors.push(error); - } - } - Ok(_) => {} - Err(error) => errors.push(error), + if let Some(player) = same_pawn(self.identity.slot, self.identity, self.controller_handle) { + if let Some(snapshot) = &mut self.crosshair + && snapshot.hidden_by_us + && let Err(error) = restore_hud_bit(player, CROSSHAIR_HUD_BIT, snapshot.originally_hidden, &mut snapshot.hidden_by_us) + { + errors.push(error); + } + if let Some(snapshot) = &mut self.all_hud + && snapshot.hidden_by_us + && let Err(error) = restore_hud_bit(player, ALL_HUD_BIT, snapshot.originally_hidden, &mut snapshot.hidden_by_us) + { + errors.push(error); } } if let Err(error) = self.restore_secondary_attack() { @@ -322,6 +342,14 @@ pub(crate) fn fov_probe() -> Probe { } pub(crate) fn crosshair_probe() -> Probe { + hud_probe() +} + +pub(crate) fn hide_all_hud_probe() -> Probe { + hud_probe() +} + +fn hud_probe() -> Probe { let mut probe = player_schema_probe(); probe.schema(HUD_CLASS, HUD_FIELD); probe @@ -502,12 +530,35 @@ fn blocked_secondary_tick(current_tick: i32) -> i32 { current_tick.saturating_add(SECONDARY_BLOCK_TICKS) } -fn crosshair_mask(current: u32, hidden: bool) -> u32 { - if hidden { - current | CROSSHAIR_HUD_BIT - } else { - current & !CROSSHAIR_HUD_BIT +fn hud_mask(current: u32, bit: u32, hidden: bool) -> u32 { + if hidden { current | bit } else { current & !bit } +} + +fn hide_hud_bit(player: LivePlayer, bit: u32, hidden_by_us: &mut bool) -> Result<(), String> { + if *hidden_by_us { + return Ok(()); + } + let flags = read_pawn_value(player, HUD_CLASS, HUD_FIELD)? as u32; + if flags & bit != 0 { + return Ok(()); } + *hidden_by_us = true; + write_pawn_value(player, HUD_CLASS, HUD_FIELD, i64::from(hud_mask(flags, bit, true)))?; + Ok(()) +} + +fn restore_hud_bit(player: LivePlayer, bit: u32, originally_hidden: bool, hidden_by_us: &mut bool) -> Result<(), String> { + if !*hidden_by_us { + return Ok(()); + } + let current = read_pawn_value(player, HUD_CLASS, HUD_FIELD)? as u32; + if current & bit == 0 { + *hidden_by_us = false; + return Ok(()); + } + write_pawn_value(player, HUD_CLASS, HUD_FIELD, i64::from(hud_mask(current, bit, originally_hidden)))?; + *hidden_by_us = false; + Ok(()) } fn secondary_tick_to_restore(current: i32, last_written: Option, original: i32) -> Option { diff --git a/crates/funrounds-plugin/src/fault.rs b/crates/funrounds-plugin/src/fault.rs index f5d60ac..7f840dc 100644 --- a/crates/funrounds-plugin/src/fault.rs +++ b/crates/funrounds-plugin/src/fault.rs @@ -9,6 +9,7 @@ pub enum Mechanism { Ammo, TaserCharge, Bunnyhop, + Autostrafe, Friction, TimeScale, GroundAcceleration, @@ -52,6 +53,7 @@ pub enum Mechanism { ProjectileDamage, Dodgeball, ThrowingKnives, + Lifesteal, ViewPunchDecay, NoScope, Fov, @@ -62,6 +64,10 @@ pub enum Mechanism { Classic, HealthSpeed, HealthDecay, + Regeneration, + MedicalSmoke, + Trampoline, + ChickenAura, PeriodicSpeed, PeriodicGravity, WinCondition, @@ -69,10 +75,25 @@ pub enum Mechanism { C4Assignment, RandomDamage, Suicide, + DeathExplosion, Healthshot, ChickenFollowBlocking, ChickenEating, Afterburn, + DontStop, + HotFloor, + BigHead, + InfernoDamage, + TeamkillPunishment, + HideAllHud, + HeGrenadeImpulse, + LongFlash, + WallHang, + Grapple, + HeGuidance, + ExplosiveBullets, + FriendlyFireHeal, + ProximityFuse(funrounds_core::GrenadeKind), } impl Mechanism { @@ -84,6 +105,7 @@ impl Mechanism { } Self::TaserCharge => capabilities.taser_charge = false, Self::Bunnyhop => capabilities.bunnyhop = false, + Self::Autostrafe => capabilities.autostrafe = false, Self::Friction => capabilities.friction = false, Self::TimeScale => capabilities.time_scale = false, Self::GroundAcceleration => { @@ -139,6 +161,7 @@ impl Mechanism { } Self::Dodgeball => capabilities.dodgeball = false, Self::ThrowingKnives => capabilities.throwing_knives = false, + Self::Lifesteal => capabilities.lifesteal = false, Self::ViewPunchDecay => capabilities.view_punch_decay = false, Self::NoScope => capabilities.no_scope = false, Self::Fov => capabilities.fov = false, @@ -154,12 +177,41 @@ impl Mechanism { Self::Classic => capabilities.speed = false, Self::HealthSpeed => capabilities.health_speed = false, Self::HealthDecay => capabilities.health_decay = false, + Self::Regeneration => capabilities.regeneration = false, + Self::MedicalSmoke => capabilities.medical_smoke = false, + Self::Trampoline => capabilities.trampoline = false, + Self::ChickenAura => capabilities.chicken_aura = false, Self::RandomDamage => capabilities.random_damage = false, Self::Suicide => capabilities.suicide = false, + Self::DeathExplosion => capabilities.death_explosion = false, Self::Healthshot => capabilities.healthshot = false, Self::ChickenFollowBlocking => capabilities.ordinary_chickens = false, Self::ChickenEating => {} - Self::Afterburn => capabilities.afterburn = false, + Self::Afterburn => { + capabilities.afterburn = false; + capabilities.hot_floor = false; + } + Self::DontStop => capabilities.dont_stop = false, + Self::HotFloor => capabilities.hot_floor = false, + Self::BigHead => capabilities.big_head = false, + Self::InfernoDamage => capabilities.inferno_damage = false, + Self::TeamkillPunishment => capabilities.teamkill_punishment = false, + Self::HideAllHud => capabilities.hide_all_hud = false, + Self::HeGrenadeImpulse => capabilities.hegrenade_impulse = false, + Self::LongFlash => capabilities.long_flash = false, + Self::WallHang => capabilities.wall_hang = false, + Self::Grapple => capabilities.grapple = false, + Self::HeGuidance => capabilities.he_guidance = false, + Self::ExplosiveBullets => capabilities.explosive_bullets = false, + Self::FriendlyFireHeal => capabilities.friendly_fire_heal = false, + Self::ProximityFuse(kind) => match kind { + funrounds_core::GrenadeKind::He => capabilities.proximity_he = false, + funrounds_core::GrenadeKind::Flash => capabilities.proximity_flash = false, + funrounds_core::GrenadeKind::Smoke => capabilities.proximity_smoke = false, + funrounds_core::GrenadeKind::Molotov => capabilities.proximity_molotov = false, + funrounds_core::GrenadeKind::Incendiary => capabilities.proximity_incendiary = false, + funrounds_core::GrenadeKind::Decoy => {} + }, } } } @@ -167,6 +219,7 @@ impl Mechanism { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Scope { Cancelled, + Round, Mechanism(Mechanism), Global, } @@ -192,6 +245,13 @@ impl Fault { } } + pub fn round(message: impl Into) -> Self { + Self { + scope: Scope::Round, + message: message.into(), + } + } + pub fn global(message: impl Into) -> Self { Self { scope: Scope::Global, @@ -211,18 +271,6 @@ impl fmt::Display for Fault { } } -impl From for Fault { - fn from(message: String) -> Self { - Self::global(message) - } -} - -impl From<&str> for Fault { - fn from(message: &str) -> Self { - Self::global(message) - } -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Recovery { Ready, @@ -248,6 +296,11 @@ impl Faults { pub fn record(&mut self, fault: &Fault) -> bool { match fault.scope { Scope::Cancelled => return false, + Scope::Round => { + if self.recovery != Recovery::Stopped { + self.recovery = Recovery::Recovering; + } + } Scope::Mechanism(mechanism) => { mechanism.exclude(&mut self.available); if self.recovery != Recovery::Stopped { @@ -283,6 +336,43 @@ impl Faults { } } + /// Promotes wall hang after its schema-dependent native probe becomes ready. + /// A recorded runtime failure remains sticky for this recovery epoch. + pub fn enable_wall_hang(&mut self) -> bool { + if self.recovery == Recovery::Stopped || self.reasons.iter().any(|(scope, _)| *scope == Scope::Mechanism(Mechanism::WallHang)) { + return false; + } + let changed = !self.available.wall_hang; + self.available.wall_hang = true; + changed + } + + pub fn set_trampoline_available(&mut self, ready: bool) -> bool { + let available = + ready && self.recovery != Recovery::Stopped && !self.reasons.iter().any(|(scope, _)| *scope == Scope::Mechanism(Mechanism::Trampoline)); + std::mem::replace(&mut self.available.trampoline, available) != available + } + + /// Promotes grapple after its schema-dependent use-target probe and callback are ready. + pub fn enable_grapple(&mut self) -> bool { + if self.recovery == Recovery::Stopped || self.reasons.iter().any(|(scope, _)| *scope == Scope::Mechanism(Mechanism::Grapple)) { + return false; + } + let changed = !self.available.grapple; + self.available.grapple = true; + changed + } + + /// Promotes HE guidance only after its spawn observer has been attached. + pub fn enable_he_guidance(&mut self) -> bool { + if self.recovery == Recovery::Stopped || self.reasons.iter().any(|(scope, _)| *scope == Scope::Mechanism(Mechanism::HeGuidance)) { + return false; + } + let changed = !self.available.he_guidance; + self.available.he_guidance = true; + changed + } + pub fn finish_cleanup(&mut self, complete: bool) -> bool { if self.recovery != Recovery::Recovering || !complete { return false; @@ -468,8 +558,8 @@ mod tests { .replace("id = \"example\"", "id = \"feature\"") .replace("name_key = \"mode.example.name\"", "name = \"Feature\"") .replace( - "weapons = [\"weapon_famas\", \"weapon_p250\"]", - "weapons = [\"weapon_famas\", \"weapon_p250\"]\ngive_knife = \"all\"\nthrowing_knives = true", + "weapons = [\"famas\", \"p250\"]", + "weapons = [\"famas\", \"p250\"]\ngive_knife = \"all\"\nthrowing_knives = true", ); let reloaded_source = format!("{header}\n{basic_source}\n{feature_source}"); controller.queue_reload(&reloaded_source).unwrap(); diff --git a/crates/funrounds-plugin/src/funrounds_native/airmove.rs b/crates/funrounds-plugin/src/funrounds_native/airmove.rs new file mode 100644 index 0000000..70575e8 --- /dev/null +++ b/crates/funrounds-plugin/src/funrounds_native/airmove.rs @@ -0,0 +1,39 @@ +// Generated from funrounds_native.pplugin (group: airmove) +// SPDX-License-Identifier: AGPL-3.0-or-later + +#[allow(unused_imports)] +use super::aliases::*; +#[allow(unused_imports)] +use super::delegates::*; +#[allow(unused_imports)] +use super::enums::*; +#[allow(unused_imports)] +use plugify::{Arr, Mat4x4, Str, Var, Vec2, Vec3, Vec4, scope}; +#[allow(unused_imports)] +use std::sync::RwLock; + +/// Reports whether the verified AirMove entry and current pawn identity schema are available. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn HasAirMoveSupport() -> bool { + unsafe { __funrounds_native_HasAirMoveSupport.expect("HasAirMoveSupport function was not found")() } +} +pub type _HasAirMoveSupport = unsafe extern "C" fn() -> bool; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __funrounds_native_HasAirMoveSupport: Option<_HasAirMoveSupport> = None; + +/// Attaches or detaches temporary AirMove input assistance for this callback. +/// +/// # Arguments +/// * `active` - (bool) +/// * `assist` - (function) +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn SetAirMoveAssist(active: bool, assist: AirMoveAssist) -> bool { + unsafe { __funrounds_native_SetAirMoveAssist.expect("SetAirMoveAssist function was not found")(active, assist) } +} +pub type _SetAirMoveAssist = unsafe extern "C" fn(bool, AirMoveAssist) -> bool; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __funrounds_native_SetAirMoveAssist: Option<_SetAirMoveAssist> = None; diff --git a/crates/funrounds-plugin/src/funrounds_native/bighead.rs b/crates/funrounds-plugin/src/funrounds_native/bighead.rs new file mode 100644 index 0000000..2d45fac --- /dev/null +++ b/crates/funrounds-plugin/src/funrounds_native/bighead.rs @@ -0,0 +1,53 @@ +// Generated from funrounds_native.pplugin (group: bighead) +// SPDX-License-Identifier: AGPL-3.0-or-later + +#[allow(unused_imports)] +use super::aliases::*; +#[allow(unused_imports)] +use super::delegates::*; +#[allow(unused_imports)] +use super::enums::*; +#[allow(unused_imports)] +use plugify::{Arr, Mat4x4, Str, Var, Vec2, Vec3, Vec4, scope}; +#[allow(unused_imports)] +use std::sync::RwLock; + +/// Reports whether the current server build has the verified Pawn reset hook, schema field and GameRules mutator-bit contract needed to own Big Head scaling. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn HasBigHeadScaleSupport() -> bool { + unsafe { __funrounds_native_HasBigHeadScaleSupport.expect("HasBigHeadScaleSupport function was not found")() } +} +pub type _HasBigHeadScaleSupport = unsafe extern "C" fn() -> bool; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __funrounds_native_HasBigHeadScaleSupport: Option<_HasBigHeadScaleSupport> = None; + +/// On the game thread, targets a finite positive scale for one exact live player Pawn after its native reset. Returns false if the target or current build contract cannot be confirmed. +/// +/// # Arguments +/// * `pawnHandle` - (int32) +/// * `scale` - (float) +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn SetBigHeadScaleTarget(pawnHandle: i32, scale: f32) -> bool { + unsafe { __funrounds_native_SetBigHeadScaleTarget.expect("SetBigHeadScaleTarget function was not found")(pawnHandle, scale) } +} +pub type _SetBigHeadScaleTarget = unsafe extern "C" fn(i32, f32) -> bool; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __funrounds_native_SetBigHeadScaleTarget: Option<_SetBigHeadScaleTarget> = None; + +/// On the game thread, removes the exact Pawn target and restores its captured original scale only while the current Pawn still holds the owned value; map changes discard old handles without writing through them. +/// +/// # Arguments +/// * `pawnHandle` - (int32) +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn ClearBigHeadScaleTarget(pawnHandle: i32) -> bool { + unsafe { __funrounds_native_ClearBigHeadScaleTarget.expect("ClearBigHeadScaleTarget function was not found")(pawnHandle) } +} +pub type _ClearBigHeadScaleTarget = unsafe extern "C" fn(i32) -> bool; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __funrounds_native_ClearBigHeadScaleTarget: Option<_ClearBigHeadScaleTarget> = None; diff --git a/crates/funrounds-plugin/src/funrounds_native/delegates.rs b/crates/funrounds-plugin/src/funrounds_native/delegates.rs index e5c404f..e2d9f6d 100644 --- a/crates/funrounds-plugin/src/funrounds_native/delegates.rs +++ b/crates/funrounds-plugin/src/funrounds_native/delegates.rs @@ -20,10 +20,14 @@ pub type DamagePreCallback = unsafe extern "C" fn(i32, i32, i32, i32, i32, bool, #[allow(unused)] pub type EntityDamagePreCallback = unsafe extern "C" fn(i32, i32, i32, i32, f32, u32, bool) -> i32; -/// Synchronous decision for every entity sharing the selected Touch implementation. +/// Synchronous veto decision for a subscribed Touch implementation; any nonzero callback result suppresses the original call. #[allow(unused)] pub type EntityTouchPreCallback = unsafe extern "C" fn(i32, i32) -> i32; +/// Produces forward and left input for the exact airborne pawn, or returns false to keep native input. +#[allow(unused)] +pub type AirMoveAssist = unsafe extern "C" fn(i32, i32, i32, f32, f32, f32, &mut f32, &mut f32) -> bool; + /// Synchronous target observation for an exact live player pawn; target is -1 if no committed match and inUse reports the current E state. #[allow(unused)] pub type UseTargetCallback = unsafe extern "C" fn(i32, i32, bool); diff --git a/crates/funrounds-plugin/src/funrounds_native/entities.rs b/crates/funrounds-plugin/src/funrounds_native/entities.rs index 5567eee..17951f6 100644 --- a/crates/funrounds-plugin/src/funrounds_native/entities.rs +++ b/crates/funrounds-plugin/src/funrounds_native/entities.rs @@ -23,7 +23,7 @@ pub type _IsEntityTouchPreHookAvailable = unsafe extern "C" fn() -> bool; #[unsafe(no_mangle)] pub static mut __funrounds_native_IsEntityTouchPreHookAvailable: Option<_IsEntityTouchPreHookAvailable> = None; -/// Hooks the entity's current Touch implementation address; the callback sees all entities sharing it. +/// Subscribes this callback to the entity's current Touch implementation. Other callbacks may share the detour; any nonzero callback result suppresses the original Touch. /// /// # Arguments /// * `entityHandle` - (int32) @@ -38,7 +38,7 @@ pub type _HookEntityTouchPre = unsafe extern "C" fn(i32, EntityTouchPreCallback) #[unsafe(no_mangle)] pub static mut __funrounds_native_HookEntityTouchPre: Option<_HookEntityTouchPre> = None; -/// Returns true for a non-null callback with no hooks or after all its hooks detach; false for null or incomplete own-hook detachment. Other callbacks' hooks are untouched. +/// Removes only this callback from its Touch subscriptions. A detour remains while another callback uses it; false means an own final-hook detach must be retried. /// /// # Arguments /// * `callback` - (function) diff --git a/crates/funrounds-plugin/src/funrounds_native/grenades.rs b/crates/funrounds-plugin/src/funrounds_native/grenades.rs new file mode 100644 index 0000000..bc51459 --- /dev/null +++ b/crates/funrounds-plugin/src/funrounds_native/grenades.rs @@ -0,0 +1,57 @@ +// Generated from funrounds_native.pplugin (group: grenades) +// SPDX-License-Identifier: AGPL-3.0-or-later + +#[allow(unused_imports)] +use super::aliases::*; +#[allow(unused_imports)] +use super::delegates::*; +#[allow(unused_imports)] +use super::enums::*; +#[allow(unused_imports)] +use plugify::{Arr, Mat4x4, Str, Var, Vec2, Vec3, Vec4, scope}; +#[allow(unused_imports)] +use std::sync::RwLock; + +/// On the game thread, checks kind 1 smoke, 2 Molotov, or 3 incendiary independently and installs an owned pre-hook that claims natural Detonate entry for complete projectile handles. +/// +/// # Arguments +/// * `kind` - (int32) +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn HasGrenadeDetonateSupport(kind: i32) -> bool { + unsafe { __funrounds_native_HasGrenadeDetonateSupport.expect("HasGrenadeDetonateSupport function was not found")(kind) } +} +pub type _HasGrenadeDetonateSupport = unsafe extern "C" fn(i32) -> bool; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __funrounds_native_HasGrenadeDetonateSupport: Option<_HasGrenadeDetonateSupport> = None; + +/// On the game thread, checks kind 1 smoke, 2 Molotov, or 3 incendiary independently. Returns 1 when any Detonate entry claimed this exact full handle or its non-sentinel projectile has disappeared, 0 for a valid matching projectile not yet claimed, and -1 when support, kind, identity, or state resolution fails. It never changes projectile physics or calls Detonate. +/// +/// # Arguments +/// * `projectileHandle` - (int32) +/// * `kind` - (int32) +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn GetGrenadeDetonationState(projectileHandle: i32, kind: i32) -> i32 { + unsafe { __funrounds_native_GetGrenadeDetonationState.expect("GetGrenadeDetonationState function was not found")(projectileHandle, kind) } +} +pub type _GetGrenadeDetonationState = unsafe extern "C" fn(i32, i32) -> i32; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __funrounds_native_GetGrenadeDetonationState: Option<_GetGrenadeDetonationState> = None; + +/// On the game thread, requests native Detonate for an exact full handle after caller-side provenance, managed-projectile exclusion, and proximity checks. Returns 1 when submitted, 0 when natural or earlier Detonate was already claimed or the non-sentinel handle normally disappeared, and -1 on support, identity, or submission failure. +/// +/// # Arguments +/// * `projectileHandle` - (int32) +/// * `kind` - (int32) +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn DetonateGrenade(projectileHandle: i32, kind: i32) -> i32 { + unsafe { __funrounds_native_DetonateGrenade.expect("DetonateGrenade function was not found")(projectileHandle, kind) } +} +pub type _DetonateGrenade = unsafe extern "C" fn(i32, i32) -> i32; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __funrounds_native_DetonateGrenade: Option<_DetonateGrenade> = None; diff --git a/crates/funrounds-plugin/src/funrounds_native/mod.rs b/crates/funrounds-plugin/src/funrounds_native/mod.rs index e0ee383..ffacca9 100644 --- a/crates/funrounds-plugin/src/funrounds_native/mod.rs +++ b/crates/funrounds-plugin/src/funrounds_native/mod.rs @@ -3,7 +3,9 @@ // This module re-exports all generated components pub mod afterburn; +pub mod airmove; pub mod aliases; +pub mod bighead; pub mod chickeneating; pub mod chickenfollow; pub mod damage; @@ -12,17 +14,23 @@ pub mod entities; pub mod enums; pub mod ghostradar; pub mod ghostvisibility; +pub mod grenades; pub mod groundreverse; pub mod healthshot; pub mod randomspawn; pub mod suicide; pub mod thirdperson; +pub mod wallhang; #[allow(unused_imports)] pub use afterburn::*; #[allow(unused_imports)] +pub use airmove::*; +#[allow(unused_imports)] pub use aliases::*; #[allow(unused_imports)] +pub use bighead::*; +#[allow(unused_imports)] pub use chickeneating::*; #[allow(unused_imports)] pub use chickenfollow::*; @@ -39,6 +47,8 @@ pub use ghostradar::*; #[allow(unused_imports)] pub use ghostvisibility::*; #[allow(unused_imports)] +pub use grenades::*; +#[allow(unused_imports)] pub use groundreverse::*; #[allow(unused_imports)] pub use healthshot::*; @@ -48,3 +58,5 @@ pub use randomspawn::*; pub use suicide::*; #[allow(unused_imports)] pub use thirdperson::*; +#[allow(unused_imports)] +pub use wallhang::*; diff --git a/crates/funrounds-plugin/src/funrounds_native/wallhang.rs b/crates/funrounds-plugin/src/funrounds_native/wallhang.rs new file mode 100644 index 0000000..d2b0fe7 --- /dev/null +++ b/crates/funrounds-plugin/src/funrounds_native/wallhang.rs @@ -0,0 +1,75 @@ +// Generated from funrounds_native.pplugin (group: wallhang) +// SPDX-License-Identifier: AGPL-3.0-or-later + +#[allow(unused_imports)] +use super::aliases::*; +#[allow(unused_imports)] +use super::delegates::*; +#[allow(unused_imports)] +use super::enums::*; +#[allow(unused_imports)] +use plugify::{Arr, Mat4x4, Str, Var, Vec2, Vec3, Vec4, scope}; +#[allow(unused_imports)] +use std::sync::RwLock; + +/// On the game thread, checks the exact paired CS2 26445667 movement-trace ABI, server image identity, and physics-query receiver. Unsupported or mismatched server builds return false. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn HasPlayerMovementHullSupport() -> bool { + unsafe { __funrounds_native_HasPlayerMovementHullSupport.expect("HasPlayerMovementHullSupport function was not found")() } +} +pub type _HasPlayerMovementHullSupport = unsafe extern "C" fn() -> bool; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __funrounds_native_HasPlayerMovementHullSupport: Option<_HasPlayerMovementHullSupport> = None; + +/// On the game thread, traces the supplied real local hull using the pinned player-movement filter while ignoring one exact full player-pawn handle. Returns true only after finite trace outputs are validated; a successful miss returns true with outHit=false and outEntityHandle=-1. Failure returns false with deterministic miss outputs. It never passes engine pointers across this provider boundary. +/// +/// # Arguments +/// * `pawnHandle` - (int32) +/// * `start` - (vec3) +/// * `end` - (vec3) +/// * `hullMins` - (vec3) +/// * `hullMaxs` - (vec3) +/// * `outPosition` - (vec3&) +/// * `outFraction` - (float&) +/// * `outHit` - (bool&) +/// * `outEntityHandle` - (int32&) +/// * `outStartSolid` - (bool&) +/// * `outNormal` - (vec3&) +#[track_caller] +#[allow(dead_code, non_snake_case, clippy::too_many_arguments)] +pub fn TracePlayerMovementHull( + pawnHandle: i32, + start: &Vec3, + end: &Vec3, + hullMins: &Vec3, + hullMaxs: &Vec3, + outPosition: &mut Vec3, + outFraction: &mut f32, + outHit: &mut bool, + outEntityHandle: &mut i32, + outStartSolid: &mut bool, + outNormal: &mut Vec3, +) -> bool { + unsafe { + __funrounds_native_TracePlayerMovementHull.expect("TracePlayerMovementHull function was not found")( + pawnHandle, + start, + end, + hullMins, + hullMaxs, + outPosition, + outFraction, + outHit, + outEntityHandle, + outStartSolid, + outNormal, + ) + } +} +pub type _TracePlayerMovementHull = + unsafe extern "C" fn(i32, &Vec3, &Vec3, &Vec3, &Vec3, &mut Vec3, &mut f32, &mut bool, &mut i32, &mut bool, &mut Vec3) -> bool; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __funrounds_native_TracePlayerMovementHull: Option<_TracePlayerMovementHull> = None; diff --git a/crates/funrounds-plugin/src/game.rs b/crates/funrounds-plugin/src/game.rs index 001c67e..e2c8430 100644 --- a/crates/funrounds-plugin/src/game.rs +++ b/crates/funrounds-plugin/src/game.rs @@ -142,13 +142,19 @@ impl LivePlayer { return Self::resolve_handles(slot); } // IsClientAlive follows m_hPlayerPawn, while GetClientPawn/Health follow - // current m_hPawn. Only accept the latter as a live takeover pawn when its - // authoritative controller link still points to this exact slot controller. + // current m_hPawn. A post-match unspawned pawn can still have positive HP; + // takeover requires a live pawn owned by this exact slot controller. if s2sdk::GetClientHealth(slot) <= 0 { return None; } let player = Self::resolve_handles(slot)?; - (s2sdk::GetEntityClassname(player.pawn_handle).as_str() == "player" && player.pawn_controller().is_some()).then_some(player) + let class = Str::from_str("CBaseEntity"); + let field = Str::from_str("m_lifeState"); + (s2sdk::GetEntityClassname(player.pawn_handle).as_str() == "player" + && s2sdk::GetSchemaOffset(&class, &field) >= 0 + && s2sdk::GetEntSchema2(s2sdk::EntHandleToEntPointer(player.pawn_handle), &class, &field, 0) == 0 + && player.pawn_controller().is_some()) + .then_some(player) } // Death cleanup needs the current pawn identity without treating a dead player as active. @@ -208,8 +214,9 @@ pub fn bot_takeover_probe() -> Probe { __s2sdk_GetMaxClients, __s2sdk_IsClientInGame, __s2sdk_IsClientAlive, __s2sdk_GetClientHealth, __s2sdk_GetEntityClassname, __s2sdk_PlayerSlotToEntHandle, __s2sdk_GetClientPawn, __s2sdk_IsValidEntHandle, __s2sdk_EntHandleToEntPointer, __s2sdk_EntPointerToEntHandle, - __s2sdk_GetEntSchemaEnt2, __s2sdk_GetSchemaOffset, + __s2sdk_GetEntSchema2, __s2sdk_GetEntSchemaEnt2, __s2sdk_GetSchemaOffset, ); + probe.schema("CBaseEntity", "m_lifeState"); probe.schema("CBasePlayerPawn", "m_hController"); probe } diff --git a/crates/funrounds-plugin/src/i18n.rs b/crates/funrounds-plugin/src/i18n.rs index 1a4847b..627e8a3 100644 --- a/crates/funrounds-plugin/src/i18n.rs +++ b/crates/funrounds-plugin/src/i18n.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later use funrounds_core::{TextBundle, TextCatalog}; +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; /// Semantic feedback kept independent of the receiver's current language. @@ -26,12 +27,12 @@ impl Message { } } -/// Preserve the previous round's label in both supported languages so a default-language +/// Preserve the previous round's label in available languages so a default-language /// reload does not leave the global previous-round team name in the old language. #[derive(Clone, Debug)] pub(crate) struct ModeNames { - zh_cn: String, - en: String, + localized: BTreeMap, + historical: String, } impl ModeNames { pub(crate) fn capture(mode: &funrounds_core::Mode, texts: &TextBundle) -> Result { @@ -46,13 +47,15 @@ impl ModeNames { .render_default(language, mode.name_key.as_deref().expect("validated mode label"), &[]) .unwrap_or_else(|_| historical.clone()) }; - Ok(Self { - zh_cn: for_default("zh-CN"), - en: for_default("en"), - }) + let localized = texts + .external_languages() + .chain(["zh-CN", "en", texts.default_language()]) + .map(|language| (language.to_owned(), for_default(language))) + .collect(); + Ok(Self { localized, historical }) } pub(crate) fn for_default(&self, language: &str) -> &str { - if language == "en" { &self.en } else { &self.zh_cn } + self.localized.get(language).map_or(&self.historical, String::as_str) } } @@ -74,15 +77,22 @@ pub(crate) fn config_path(root: &Path) -> (PathBuf, Option) { pub(crate) fn load(directory: &Path, default: &str, strict: bool, config: Option<&funrounds_core::Config>) -> Result { let mut candidates = Vec::new(); let mut reports = Vec::new(); - for language in ["zh-CN", "en"] { - let path = directory.join(format!("{language}.toml")); + let paths = match catalog_paths(directory) { + Ok(paths) => paths, + Err(error) if strict => return Err(error), + Err(error) => { + reports.push(error); + Vec::new() + } + }; + for path in paths { + let language = path.file_stem().unwrap_or_default().to_string_lossy().into_owned(); match std::fs::read_to_string(&path) { Ok(source) => candidates.push(( - language.to_owned(), - TextCatalog::parse_for_language(&source, language).map_err(|error| format!("{}: {error}", path.display())), + language.clone(), + TextCatalog::parse_for_language(&source, &language).map_err(|error| format!("{}: {error}", path.display())), )), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => reports.push(format!("{} missing; using fallback", path.display())), - Err(error) => candidates.push((language.to_owned(), Err(format!("{}: {error}", path.display())))), + Err(error) => candidates.push((language, Err(format!("{}: {error}", path.display())))), } } let texts = if strict { @@ -100,10 +110,12 @@ pub(crate) fn load(directory: &Path, default: &str, strict: bool, config: Option reports.extend(rejected); texts }; - for language in ["zh-CN", "en"] { + let mut languages = texts.external_languages().collect::>(); + languages.sort_unstable(); + for language in languages { let missing = texts.missing_keys(language); if !missing.is_empty() { - reports.push(format!("{language}: {} missing keys use fallback: {}", missing.len(), missing.join(","))); + reports.push(format!("{language}: {} missing keys use fallback", missing.len())); } } if !reports.is_empty() { @@ -112,6 +124,29 @@ pub(crate) fn load(directory: &Path, default: &str, strict: bool, config: Option Ok(texts) } +fn catalog_paths(directory: &Path) -> Result, String> { + let entries = match std::fs::read_dir(directory) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(format!("{}: {error}", directory.display())), + }; + let mut paths = Vec::new(); + for entry in entries { + let path = entry.map_err(|error| format!("{}: {error}", directory.display()))?.path(); + if path + .extension() + .and_then(|ext| ext.to_str()) + .is_some_and(|ext| ext.eq_ignore_ascii_case("toml")) + // Keep unreadable entries as candidates: startup rejects that file, not every valid locale. + && std::fs::metadata(&path).map_or(true, |metadata| metadata.is_file()) + { + paths.push(path); + } + } + paths.sort(); + Ok(paths) +} + /// Unlike status replies, console text keeps whitespace and the original line layout. pub(crate) fn console_parts(mut message: &str) -> impl Iterator { std::iter::from_fn(move || { diff --git a/crates/funrounds-plugin/src/lib.rs b/crates/funrounds-plugin/src/lib.rs index fe54d52..1c7e633 100644 --- a/crates/funrounds-plugin/src/lib.rs +++ b/crates/funrounds-plugin/src/lib.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later mod afterburn; +mod autostrafe; mod bombs; mod capability; mod cash; @@ -28,7 +29,6 @@ mod runtime; #[allow(dead_code)] mod s2sdk; mod suicide; - mod touch; use plugify::{Arr, Str, register_plugin}; @@ -36,7 +36,7 @@ use s2sdk::{ConCommandContext, ConVarFlag, EventHookError, HookMode, ResultType} use std::error::Error; use std::io::Write; use std::panic::{AssertUnwindSafe, catch_unwind}; -use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use std::sync::{Mutex, OnceLock, TryLockError}; use std::thread::ThreadId; @@ -58,9 +58,14 @@ const EVENTS: &[&str] = &[ "bomb_planted", "bomb_begindefuse", "bomb_abortdefuse", + "bomb_defused", "bomb_exploded", "round_prestart", "item_pickup", + "player_blind", + "bullet_impact", + "smokegrenade_detonate", + "smokegrenade_expired", ]; static ACTIVE: AtomicBool = AtomicBool::new(false); static PANIC_PENDING: AtomicBool = AtomicBool::new(false); @@ -81,6 +86,10 @@ static SUICIDE_MANIFEST_CALLBACK_REGISTERED: AtomicBool = AtomicBool::new(false) static GAME_THREAD_ID: OnceLock = OnceLock::new(); static HEALTHSHOT_HOOKED: AtomicBool = AtomicBool::new(false); static USE_TARGET_HOOKED: AtomicBool = AtomicBool::new(false); +static HE_GUIDANCE_SPAWN_LISTENER_REGISTERED: AtomicBool = AtomicBool::new(false); +static HE_GUIDANCE_SPAWN_ACTIVE: AtomicBool = AtomicBool::new(false); +static HE_GUIDANCE_SPAWN_EPOCH: AtomicU64 = AtomicU64::new(0); +static HE_GUIDANCE_SPAWN_QUEUE: Mutex> = Mutex::new(Vec::new()); static RUNTIME: Mutex> = Mutex::new(None); static DISCONNECT_BRIDGE: Mutex> = Mutex::new(None); static DAMAGE_BRIDGE: Mutex> = Mutex::new(None); @@ -90,6 +99,12 @@ fn callbacks_active() -> bool { ACTIVE.load(Ordering::Acquire) && !PANIC_PENDING.load(Ordering::Acquire) } +pub(crate) fn publish_he_guidance_spawn_active(active: bool) { + if HE_GUIDANCE_SPAWN_ACTIVE.swap(active, Ordering::AcqRel) != active { + HE_GUIDANCE_SPAWN_EPOCH.fetch_add(1, Ordering::AcqRel); + } +} + fn missing_native_abi() -> Option { let mut missing = Vec::new(); macro_rules! require_import { @@ -119,7 +134,7 @@ fn missing_native_abi() -> Option { } (!missing.is_empty()).then(|| { format!( - "FunRounds requires funrounds_native 0.3-Alpha Test 2 ABI; missing imports: {}", + "FunRounds requires funrounds_native 0.4-Alpha Test 3 ABI; missing imports: {}", missing.join(", ") ) }) @@ -152,7 +167,7 @@ fn healthshot_native_available() -> bool { parameters::has_convar("healthshot_health") && parameters::has_convar("healthshot_allow_use_at_full") && funrounds_native::HasHealthshotSupport() } -fn use_target_native_available() -> bool { +fn use_target_native_imports_available() -> bool { let (support, hook, unhook) = unsafe { ( std::ptr::addr_of!(funrounds_native::__funrounds_native_HasUseTargetSupport).read(), @@ -160,7 +175,139 @@ fn use_target_native_available() -> bool { std::ptr::addr_of!(funrounds_native::__funrounds_native_UnhookUseTarget).read(), ) }; - support.is_some() && hook.is_some() && unhook.is_some() && funrounds_native::HasUseTargetSupport() + support.is_some() && hook.is_some() && unhook.is_some() +} + +fn he_guidance_spawn_listener_imports_available() -> bool { + let (register, unregister) = unsafe { + ( + std::ptr::addr_of!(s2sdk::__s2sdk_OnEntitySpawned_Register).read(), + std::ptr::addr_of!(s2sdk::__s2sdk_OnEntitySpawned_Unregister).read(), + ) + }; + register.is_some() && unregister.is_some() +} + +fn take_he_guidance_spawn_queue() -> Vec { + std::mem::take(&mut *HE_GUIDANCE_SPAWN_QUEUE.lock().unwrap_or_else(|poisoned| poisoned.into_inner())) +} + +fn invalidate_he_guidance_spawn_epoch() { + HE_GUIDANCE_SPAWN_ACTIVE.store(false, Ordering::Release); + HE_GUIDANCE_SPAWN_EPOCH.fetch_add(1, Ordering::AcqRel); + HE_GUIDANCE_SPAWN_QUEUE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear(); +} + +fn sync_he_guidance_spawn_listener() { + let requested = { + let mut guard = RUNTIME.lock().expect("FunRounds runtime poisoned"); + let Some(runtime) = guard.as_mut() else { return }; + runtime.take_he_guidance_spawn_listener_request() + }; + if !requested || HE_GUIDANCE_SPAWN_LISTENER_REGISTERED.load(Ordering::Acquire) { + return; + } + if !he_guidance_spawn_listener_imports_available() { + return; + } + HE_GUIDANCE_SPAWN_LISTENER_REGISTERED.store(true, Ordering::Release); + s2sdk::OnEntitySpawned_Register(on_he_guidance_entity_spawned); + if let Some(runtime) = RUNTIME.lock().expect("FunRounds runtime poisoned").as_mut() { + runtime.he_guidance_spawn_listener_ready(); + runtime.sync_he_guidance_spawn_epoch(); + } +} + +fn unregister_he_guidance_spawn_listener() -> Result<(), Box> { + if !HE_GUIDANCE_SPAWN_LISTENER_REGISTERED.load(Ordering::Acquire) { + invalidate_he_guidance_spawn_epoch(); + return Ok(()); + } + let unregister = unsafe { std::ptr::addr_of!(s2sdk::__s2sdk_OnEntitySpawned_Unregister).read() } + .ok_or("FunRounds: entity spawn listener unregistration import is unavailable")?; + unsafe { unregister(on_he_guidance_entity_spawned) }; + HE_GUIDANCE_SPAWN_LISTENER_REGISTERED.store(false, Ordering::Release); + invalidate_he_guidance_spawn_epoch(); + Ok(()) +} + +unsafe extern "C" fn on_he_guidance_entity_spawned(handle: i32) { + catch_unwind(AssertUnwindSafe(|| { + if !callbacks_active() || !HE_GUIDANCE_SPAWN_LISTENER_REGISTERED.load(Ordering::Acquire) || !HE_GUIDANCE_SPAWN_ACTIVE.load(Ordering::Acquire) + { + return; + } + assert_game_thread(); + let tick = s2sdk::GetGameTickCount(); + let game_time = s2sdk::GetGameTime(); + if tick >= 0 && game_time.is_finite() { + HE_GUIDANCE_SPAWN_QUEUE + .lock() + .expect("HE guidance spawn queue poisoned") + .push(runtime::proximity::SpawnObservation { + handle, + tick, + epoch: HE_GUIDANCE_SPAWN_EPOCH.load(Ordering::Acquire), + game_time, + }); + } + })) + .unwrap_or_else(|_| contain_failure("entity spawn listener callback panic contained")); +} + +// Install once when the effective configuration first needs the service. The callbacks +// remain attached until unload; Runtime gates behavior on the current config/enabled state. +fn sync_interaction_hooks() { + let (healthshot, chicken) = { + let mut guard = RUNTIME.lock().expect("FunRounds runtime poisoned"); + let Some(runtime) = guard.as_mut() else { return }; + runtime.take_interaction_hook_requests() + }; + // Native registration can re-enter engine callbacks: never hold RUNTIME here. + let healthshot_result = healthshot.then(|| { + if !healthshot_native_available() { + return false; + } + HEALTHSHOT_HOOKED.store(true, Ordering::Release); + funrounds_native::HookHealthshot(on_healthshot_can_use, on_healthshot_effect) + }); + let chicken_result = chicken.then(|| { + if !use_target_native_imports_available() { + return Some(false); + } + if !funrounds_native::HasUseTargetSupport() { + return None; + } + USE_TARGET_HOOKED.store(true, Ordering::Release); + Some(funrounds_native::HookUseTarget(on_use_target)) + }); + if healthshot_result.is_none() && chicken_result.is_none() { + return; + } + let mut guard = RUNTIME.lock().expect("FunRounds runtime poisoned"); + let Some(runtime) = guard.as_mut() else { return }; + if let Some(ready) = healthshot_result { + if ready { + runtime.healthshot_hook_ready(); + } else { + runtime.healthshot_hook_failure("native healthshot hooks or required ConVars unavailable, or registration failed"); + } + } + if let Some(None) = chicken_result { + runtime.chicken_use_hook_deferred(); + } else if let Some(Some(ready)) = chicken_result { + if ready { + runtime.chicken_use_hook_ready(); + } else { + runtime.chicken_use_hook_failure("native committed use-target selector unavailable or registration failed"); + } + } +} + +fn process_grapple_cleanup(actions: Vec) { + for action in actions { + let _ = runtime::grapple::execute(action, || true); + } } fn chicken_follow_block_native_available() -> bool { @@ -328,6 +475,7 @@ fn start() -> Result<(), Box> { || COMMANDS.load(Ordering::Acquire) != 0 || CHAT_HOOKED.load(Ordering::Acquire) || SUICIDE_MANIFEST_CALLBACK_REGISTERED.load(Ordering::Acquire) + || HE_GUIDANCE_SPAWN_LISTENER_REGISTERED.load(Ordering::Acquire) || legacy_textmsg::hooked() || TOUCH_CLEANUP_PENDING.load(Ordering::Acquire) || CHICKEN_FOLLOW_BLOCK_ACTIVE.load(Ordering::Acquire) @@ -364,14 +512,17 @@ fn update(_dt: f32) -> Result<(), Box> { let _ = disable_chicken_follow_block(true); } if ACTIVE.load(Ordering::Acquire) { + sync_interaction_hooks(); + sync_he_guidance_spawn_listener(); apply_pending_fault()?; apply_pending_bomb_explosion(); + let spawned_entities = take_he_guidance_spawn_queue(); let mut guard = RUNTIME.try_lock().map_err(|_| "FunRounds: runtime busy or poisoned")?; if let Some(runtime) = guard.as_mut() { if !runtime.on_game_thread() { return Err("FunRounds: update is not on the game thread".into()); } - let actions = runtime.update(); + let actions = runtime.update_with_spawned_entities(spawned_entities); sync_chicken_follow_blocking(runtime); drop(guard); for action in actions { @@ -381,137 +532,67 @@ fn update(_dt: f32) -> Result<(), Box> { action @ (runtime::EngineAction::Loadout(..) | runtime::EngineAction::Upgrade(..) | runtime::EngineAction::ThirdPerson(..)) => process_loadout_action(action), - runtime::EngineAction::GrantC4(task, player) => { - let deferred = if callbacks_active() { - let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - guard - .as_mut() - .filter(|runtime| runtime.on_game_thread()) - .is_some_and(|runtime| runtime.defer_pending_loadout_c4_grant(task, player)) - } else { - false - }; - if deferred { - continue; - } - let action = runtime::EngineAction::GrantC4(task, player); - let result = suicide::grant_c4(player, || engine_action_current(&action)); - if let Err(error) = result - && engine_action_current(&action) - { - equipment_fault(error); - } - } - runtime::EngineAction::RemoveC4(task, player, handles) => { - execute_valid_action(runtime::EngineAction::RemoveC4(task, player, handles.clone()), || { - runtime::remove_native_c4(player, &handles) + runtime::EngineAction::Suicide(action) => runtime::suicide::execute(action)?, + runtime::EngineAction::Teamkill(action) => process_teamkill_action(action), + runtime::EngineAction::Shockwave(action) => { + let checked = runtime::EngineAction::Shockwave(action); + execute_valid_action(checked, || { + { + let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some(runtime) = guard.as_mut() else { return Ok(()) }; + runtime.interrupt_movement_for_impulse(action.player())?; + } + let current = runtime::EngineAction::Shockwave(action); + if engine_action_current(¤t) { + runtime::proximity::execute_shockwave(action) + } else { + Ok(()) + } })?; } - runtime::EngineAction::Suicide(action) => process_suicide_action(action), - runtime::EngineAction::Bomb(bomb) => process_bomb_action(bomb), - runtime::EngineAction::ChickenSpawn { round, origin } => process_chicken_spawn(round, origin), - runtime::EngineAction::ChickenBlast { - round, - chicken, - attacker, - origin, - config, - } => process_chicken_blast(round, chicken, attacker, origin, config), - runtime::EngineAction::ChickenRemove(handle) => chicken_entities::remove(handle), - runtime::EngineAction::SuicideFeedbackRemove(handle) => suicide::remove_feedback(handle), - runtime::EngineAction::AfterburnRemove(handle) => afterburn::remove_flame(handle), - runtime::EngineAction::AfterburnIgnite { task, player } => process_afterburn_ignite(task, player), - runtime::EngineAction::ChickenEat { - task, - player, - chicken, - outcome, - } => process_chicken_eat(task, player, chicken, outcome), - runtime::EngineAction::ChickenPurchase { task, player, price, origin } => { - process_chicken_purchase(task, player, price, origin) + runtime::EngineAction::HeGuidance(action) => { + process_he_guidance_action(action)?; } - runtime::EngineAction::HealthshotUse { - task, - player, - base_health, - config, - } => { - let action = runtime::EngineAction::HealthshotUse { - task, - player, - base_health, - config, - }; - execute_valid_action(action, || { - let current = s2sdk::GetClientHealth(task.player.slot); - if let funrounds_core::HealthshotOutcome::Applied { health, .. } = - funrounds_core::use_healthshot(config, current, base_health) - { - s2sdk::SetClientHealth(task.player.slot, health); - if s2sdk::GetClientHealth(task.player.slot) != health { - return Err(fault::Fault::mechanism( - fault::Mechanism::Healthshot, - format!("healthshot health write failed for slot {}", task.player.slot), - )); - } - } - Ok(()) + runtime::EngineAction::HeGuidanceFuseRestore(action) => { + process_he_guidance_fuse_restore(action); + } + runtime::EngineAction::Bomb(bomb) => process_bomb_action(bomb), + runtime::EngineAction::Grapple(action) => { + let checked = runtime::EngineAction::Grapple(action); + execute_valid_action(checked, || { + let current = runtime::EngineAction::Grapple(action); + runtime::grapple::execute(action, || engine_action_current(¤t)) })?; } - runtime::EngineAction::HealthshotPurchase { task, player, price } => process_healthshot_purchase(task, player, price), + runtime::EngineAction::Chicken(action) => runtime::chickens::execute(action), + runtime::EngineAction::Proximity(action) => { + if engine_action_current(&runtime::EngineAction::Proximity(action)) { + execute_valid_action(runtime::EngineAction::Proximity(action), || runtime::proximity::execute(action))?; + } else if let Some(runtime) = RUNTIME.lock().unwrap_or_else(|p| p.into_inner()).as_mut() { + runtime.cancel_proximity_action(action); + } + } + runtime::EngineAction::Shooting(action) => { + let checked = runtime::EngineAction::Shooting(action.clone()); + execute_valid_action(checked, || runtime::shooting::execute(action))?; + } + runtime::EngineAction::Composed(action) => { + let checked = runtime::EngineAction::Composed(action.clone()); + execute_valid_action(checked, || runtime::execute_composed(action))?; + } + runtime::EngineAction::Afterburn(action) => runtime::afterburn::execute(action), + runtime::EngineAction::Healthshot(action) => runtime::healthshot::execute(action)?, runtime::EngineAction::Equipment(action) => process_equipment_action(action), runtime::EngineAction::Projectile(action) => process_projectile_action(action), - runtime::EngineAction::DelayedDamage(hit) => process_delayed_damage(hit), - runtime::EngineAction::Reflection(hit) => process_reflection(hit), + runtime::EngineAction::Combat(action) => runtime::combat::execute(action), runtime::EngineAction::ProjectileImpact(impact) => { execute_valid_action(runtime::EngineAction::ProjectileImpact(impact), || { apply_projectile_impact(impact); Ok(()) })? } - runtime::EngineAction::Respawn(task, player, team) => { - execute_valid_action(runtime::EngineAction::Respawn(task, player, team), || { - s2sdk::RespawnClient(task.player.slot); - Ok(()) - })? - } + runtime::EngineAction::Respawn(action) => runtime::respawn::execute(action)?, runtime::EngineAction::HostageRescue(action) => process_hostage_rescue(action), - runtime::EngineAction::RoundRespawn(task, player, team) => { - execute_valid_action(runtime::EngineAction::RoundRespawn(task, player, team), || { - s2sdk::ForceRespawnClient(task.player.slot); - Ok(()) - })? - } - runtime::EngineAction::LowHealthFinish(task, player, numeric) => { - execute_valid_action(runtime::EngineAction::LowHealthFinish(task, player, numeric), || { - let slot = task.player.slot; - let handle = player.pawn_handle; - let zero = plugify::Vec3 { x: 0.0, y: 0.0, z: 0.0 }; - let applied = if numeric { - damage::finish_self_damage(handle)? - } else { - damage::apply_native_damage( - damage::NativeDamageCall { - victim: handle, - inflictor: handle, - attacker: handle, - force: &zero, - position: &zero, - amount: 1.0, - damage_type: damage::DMG_HEADSHOT, - weapon: -1, - skip_plugin_rules: false, - }, - fault::Mechanism::NativeSelfDamage, - "native low-health finish rejected after identity validation", - )? - }; - s2sdk::PrintToServer(&Str::from_str(&format!( - "[FunRounds] low-health finish slot={slot} pawn={handle} damage={applied}" - ))); - Ok(()) - })? - } runtime::EngineAction::CenterDisplay { generation } => { execute_valid_action(runtime::EngineAction::CenterDisplay { generation }, || { let guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); @@ -529,11 +610,16 @@ fn update(_dt: f32) -> Result<(), Box> { } } } - let rescue_active = RUNTIME - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .as_ref() - .is_some_and(runtime::Runtime::hostage_rescue_touch_enabled); + let rescue_active = if let Some(runtime) = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_mut() { + if callbacks_active() { + let now = f64::from(s2sdk::GetGameTime()); + runtime.settle_regeneration(now); + runtime.update_regions(now); + } + runtime.hostage_rescue_touch_enabled() + } else { + false + }; if !rescue_active { touch::clear_rescue_zones(); } @@ -565,6 +651,50 @@ fn engine_action_current(action: &runtime::EngineAction) -> bool { .is_some_and(|runtime| runtime.on_game_thread() && runtime.action_valid(action)) } +fn he_guidance_action_current(action: runtime::proximity::GuidanceAction) -> bool { + let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some(runtime) = guard.as_mut() else { return false }; + let current = callbacks_active() && runtime.on_game_thread() && runtime.action_valid(&runtime::EngineAction::HeGuidance(action)); + if !current { + runtime.reject_he_guidance_action(action); + } + current +} + +fn process_he_guidance_action(action: runtime::proximity::GuidanceAction) -> Result<(), Box> { + if !he_guidance_action_current(action) { + return Ok(()); + } + if let Err(error) = runtime::proximity::execute_guidance(action, he_guidance_action_current, || { + let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + guard.as_mut().is_some_and(|runtime| runtime.confirm_he_guidance_fuse_pause(action)) + }) { + let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = guard.as_mut() { + runtime.handle_fault(error); + } + } + Ok(()) +} + +fn he_guidance_fuse_restore_current(action: runtime::proximity::GuidanceFuseRestoreAction) -> bool { + let guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + guard + .as_ref() + .is_some_and(|runtime| runtime.on_game_thread() && runtime.he_guidance_fuse_restore_action_valid(action)) +} + +fn process_he_guidance_fuse_restore(action: runtime::proximity::GuidanceFuseRestoreAction) { + let result = runtime::proximity::execute_guidance_fuse_restore(action, || he_guidance_fuse_restore_current(action)); + let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = guard.as_mut() { + match result { + Ok(()) => runtime.complete_he_guidance_fuse_restore(action), + Err(error) => runtime.handle_fault(error), + } + } +} + fn process_rollback_action(action: runtime::EngineAction) { let effect = { let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); @@ -672,18 +802,67 @@ unsafe extern "C" fn on_can_acquire(pawn: i32, controller: i32) -> i32 { fn suicide_action_current(action: suicide::Action) -> bool { let guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); callbacks_active() - && guard - .as_ref() - .is_some_and(|runtime| runtime.on_game_thread() && runtime.action_valid(&runtime::EngineAction::Suicide(action))) + && guard.as_ref().is_some_and(|runtime| { + runtime.on_game_thread() && runtime.action_valid(&runtime::EngineAction::Suicide(runtime::suicide::Action::SelfDestruct(action))) + }) +} + +fn process_teamkill_action(action: runtime::teamkill::Action) { + let started = { + let mut guard = RUNTIME.lock().unwrap_or_else(|p| p.into_inner()); + guard + .as_mut() + .is_some_and(|r| callbacks_active() && r.on_game_thread() && r.begin_teamkill(action)) + }; + if !started { + return; + } + let result = catch_unwind(AssertUnwindSafe(|| { + let mut errors = Vec::new(); + // Register visual lifetime before the lethal call: the resulting + // round_end must preserve this already-started short-lived feedback. + match suicide::spawn_feedback_at(action.player.pawn_handle, action.origin, suicide::EXPLOSION_PARTICLE) { + Ok(handle) => { + let tracked = { + let mut guard = RUNTIME.lock().unwrap_or_else(|p| p.into_inner()); + guard.as_mut().is_some_and(|r| r.track_suicide_feedback(handle, s2sdk::GetGameTime())) + }; + if !tracked { + suicide::remove_feedback(handle); + errors.push(fault::Fault::mechanism( + fault::Mechanism::TeamkillPunishment, + "teamkill feedback lifetime registration failed", + )); + } + } + Err(error) => errors.push(fault::Fault::mechanism(fault::Mechanism::TeamkillPunishment, error)), + } + // Particle creation can run engine callbacks; do not carry an old + // controller/life or changed FFA policy across that boundary. + if engine_action_current(&runtime::EngineAction::Teamkill(action)) + && let Err(error) = runtime::teamkill::punish(action.player) + { + errors.push(error); + } + errors + })) + .unwrap_or_else(|_| vec![fault::Fault::global("teamkill punishment panic contained")]); + let mut guard = RUNTIME.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(runtime) = guard.as_mut() { + runtime.finish_teamkill(action); + for error in result { + runtime.handle_fault(error); + } + } } fn process_suicide_action(action: suicide::Action) { { let guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); if !callbacks_active() - || !guard - .as_ref() - .is_some_and(|runtime| runtime.on_game_thread() && runtime.action_valid(&runtime::EngineAction::Suicide(action))) + || !guard.as_ref().is_some_and(|runtime| { + runtime.on_game_thread() && runtime.action_valid(&runtime::EngineAction::Suicide(runtime::suicide::Action::SelfDestruct(action))) + }) { return; } @@ -733,61 +912,12 @@ fn process_suicide_action(action: suicide::Action) { } } } - suicide::Action::Blast { .. } => { - let targets = { - let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - let Some(runtime) = guard.as_mut() else { return }; - match runtime.prepare_suicide_blast(action) { - Ok(targets) => targets, - Err(error) => { - runtime.handle_fault(error); - return; - } - } - }; - let mut feedback_errors = Vec::new(); - let mut blast_sound_source = action.player().pawn_handle; - match suicide::spawn_feedback(action.player()) { - Ok(handle) => { - let now = s2sdk::GetGameTime(); - let tracked = RUNTIME - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) - .as_mut() - .is_some_and(|runtime| runtime.track_suicide_feedback(handle, now)); - if tracked { - blast_sound_source = handle; - } else { - suicide::remove_feedback(handle); - feedback_errors.push("自爆粒子反馈无法登记清理".to_owned()); - } - } - Err(error) => feedback_errors.push(error), - } - if let Err(error) = suicide::play_explosion_sound(blast_sound_source) { - feedback_errors.push(error); - } - for (task, player, amount) in targets { - let valid = { - let guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - guard.as_ref().is_some_and(|runtime| { - runtime.suicide_target_valid(task, player) && runtime.action_valid(&runtime::EngineAction::Suicide(action)) - }) - }; - if valid && let Err(error) = suicide::hit(action.player(), player, amount, false) { - suicide_fault(error); - break; - } - } - let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - if let Some(runtime) = guard.as_mut() { - runtime.finish_suicide_blast(); - } - drop(guard); - if !feedback_errors.is_empty() { - suicide_fault(feedback_errors.join("; ")); - } - } + suicide::Action::Blast { .. } => process_player_blast( + action.player(), + s2sdk::GetEntityAbsOrigin(action.player().pawn_handle), + runtime::EngineAction::Suicide(runtime::suicide::Action::SelfDestruct(action)), + fault::Mechanism::Suicide, + ), suicide::Action::Finish { player, .. } => { let amount = { let guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); @@ -807,6 +937,96 @@ fn process_suicide_action(action: suicide::Action) { } } +fn process_player_blast(source: game::LivePlayer, origin: plugify::Vec3, action: runtime::EngineAction, mechanism: fault::Mechanism) { + let targets = { + let mut guard = RUNTIME.lock().unwrap_or_else(|p| p.into_inner()); + let Some(runtime) = guard + .as_mut() + .filter(|r| callbacks_active() && r.on_game_thread() && r.action_valid(&action)) + else { + return; + }; + if let runtime::EngineAction::Suicide(runtime::suicide::Action::SelfDestruct(c4)) = action { + runtime.prepare_suicide_finish_after_blast(c4); + } + // If native death dispatch has ended the round, preserve the recorded + // explosion at the corpse but do not touch damage or friendly fire. + if runtime.classic_round() { + match runtime.prepare_blast_targets(source, origin) { + Ok(targets) => targets, + Err(error) => { + runtime.handle_fault(if mechanism == fault::Mechanism::DeathExplosion { + fault::Fault::mechanism(mechanism, error.to_string()) + } else { + error + }); + return; + } + } + } else { + Vec::new() + } + }; + if mechanism == fault::Mechanism::DeathExplosion { + let guard = RUNTIME.lock().unwrap_or_else(|p| p.into_inner()); + if guard.as_ref().is_some_and(|runtime| runtime.diagnostics()) { + s2sdk::PrintToServer(&Str::from_str(&format!( + "[FunRounds] death_explosion=detonate slot={} pawn={} origin={},{},{} targets={}", + source.slot, + source.pawn_handle, + origin.x, + origin.y, + origin.z, + targets.len() + ))); + } + } + let mut errors = Vec::new(); + let mut sound_source = source.pawn_handle; + match suicide::spawn_feedback_at(source.pawn_handle, origin, suicide::EXPLOSION_PARTICLE) { + Ok(handle) => { + let mut guard = RUNTIME.lock().unwrap_or_else(|p| p.into_inner()); + let tracked = guard + .as_mut() + .is_some_and(|runtime| runtime.action_valid(&action) && runtime.track_suicide_feedback(handle, s2sdk::GetGameTime())); + drop(guard); + if tracked { + sound_source = handle; + } else { + suicide::remove_feedback(handle); + } + } + Err(error) => errors.push(error), + } + if engine_action_current(&action) + && let Err(error) = suicide::play_explosion_sound(sound_source) + { + errors.push(error); + } + for (task, player, amount) in targets { + if mechanism == fault::Mechanism::DeathExplosion && source.pawn_controller() != Some(source.controller_handle) { + break; + } + let valid = { + let guard = RUNTIME.lock().unwrap_or_else(|p| p.into_inner()); + guard + .as_ref() + .is_some_and(|runtime| runtime.blast_target_valid(task, player) && runtime.action_valid(&action)) + }; + if valid && let Err(error) = suicide::hit(source, player, amount, false) { + errors.push(error); + break; + } + } + let mut guard = RUNTIME.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(runtime) = guard.as_mut() { + runtime.finish_suicide_blast(); + if !errors.is_empty() && runtime.action_valid(&action) { + runtime.handle_fault(fault::Fault::mechanism(mechanism, errors.join("; "))); + } + } +} + fn suicide_fault(error: String) { let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); if let Some(runtime) = guard.as_mut() { @@ -837,10 +1057,10 @@ fn process_delayed_damage(hit: damage::DelayedDamage) { }; let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let Some(runtime) = guard.as_mut() else { return }; - if !callbacks_active() || !runtime.action_valid(&runtime::EngineAction::DelayedDamage(hit.clone())) { + if !callbacks_active() || !runtime.action_valid(&runtime::EngineAction::Combat(runtime::combat::Action::DelayedDamage(hit.clone()))) { return; } - let blocked = runtime.combat_damage(&context, &players, 1.0, true); + let blocked = runtime.combat_damage(&context, &players, 1.0, true, false); drop(guard); if blocked { return; @@ -876,11 +1096,11 @@ fn process_reflection(hit: damage::Reflection) { }; let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let Some(runtime) = guard.as_mut() else { return }; - let action = runtime::EngineAction::Reflection(hit.clone()); + let action = runtime::EngineAction::Combat(runtime::combat::Action::Reflection(hit.clone())); if !callbacks_active() || !runtime.action_valid(&action) { return; } - let blocked = runtime.combat_damage(&context, &players, 1.0, false); + let blocked = runtime.combat_damage(&context, &players, 1.0, false, false); drop(guard); if !blocked && let Err(error) = hit.execute(s2sdk::IsValidEntHandle) { let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); @@ -897,9 +1117,10 @@ fn process_bomb_action(action: bombs::Action) { runtime.cancel_bomb_action(action); return; } + let prepared = runtime.prepare_bomb_action_scales(action); drop(guard); - let result = bombs::execute(action); + let result = prepared.and_then(|()| bombs::execute(action)); let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); if let Some(runtime) = guard.as_mut() { runtime.finish_bomb_action(action, result); @@ -907,7 +1128,7 @@ fn process_bomb_action(action: bombs::Action) { } fn process_chicken_spawn(round: funrounds_core::RoundGeneration, origin: plugify::Vec3) { - let action = runtime::EngineAction::ChickenSpawn { round, origin }; + let action = runtime::EngineAction::Chicken(runtime::chickens::Action::Spawn { round, origin }); let current = RUNTIME .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) @@ -938,7 +1159,7 @@ fn process_chicken_spawn(round: funrounds_core::RoundGeneration, origin: plugify } fn chicken_purchase_action(task: funrounds_core::PlayerTask, player: game::LivePlayer, price: u32, origin: plugify::Vec3) -> runtime::EngineAction { - runtime::EngineAction::ChickenPurchase { task, player, price, origin } + runtime::EngineAction::Chicken(runtime::chickens::Action::Purchase { task, player, price, origin }) } fn chicken_buyer_identity_current(task: funrounds_core::PlayerTask, player: game::LivePlayer) -> bool { @@ -999,7 +1220,7 @@ fn healthshot_buyer_current(task: funrounds_core::PlayerTask, player: game::Live } fn process_healthshot_purchase(task: funrounds_core::PlayerTask, player: game::LivePlayer, price: u32) { - let action = runtime::EngineAction::HealthshotPurchase { task, player, price }; + let action = runtime::EngineAction::Healthshot(runtime::healthshot::Action::Purchase { task, player, price }); let result = if !engine_action_current(&action) { Err(cash::PurchaseError::Rejected("purchase.cancelled")) } else { @@ -1056,12 +1277,12 @@ fn process_afterburn_ignite(task: funrounds_core::PlayerTask, player: game::Live if !callbacks_active() { return; } - let action = runtime::EngineAction::AfterburnIgnite { task, player }; let now = f64::from(s2sdk::GetGameTime()); let Some(remaining) = (|| { let mut guard = RUNTIME.try_lock().ok()?; let runtime = guard.as_mut()?; - (runtime.on_game_thread() && runtime.action_valid(&action)) + runtime + .on_game_thread() .then(|| runtime.begin_afterburn_ignite(task, player, now)) .flatten() })() else { @@ -1122,21 +1343,21 @@ fn process_afterburn_ignite(task: funrounds_core::PlayerTask, player: game::Live } fn process_chicken_eat(task: funrounds_core::PlayerTask, player: game::LivePlayer, chicken: i32, outcome: funrounds_core::ChickenEatOutcome) { - let action = runtime::EngineAction::ChickenEat { + let action = runtime::EngineAction::Chicken(runtime::chickens::Action::Eat { task, player, chicken, outcome, - }; + }); if engine_action_current(&action) { match outcome { funrounds_core::ChickenEatOutcome::Heal { healed, .. } => { - let action = runtime::EngineAction::ChickenEat { + let action = runtime::EngineAction::Chicken(runtime::chickens::Action::Eat { task, player, chicken, outcome, - }; + }); let _ = execute_valid_action(action, || { let health = s2sdk::GetClientHealth(player.slot).saturating_add(healed); s2sdk::SetClientHealth(player.slot, health); @@ -1231,12 +1452,12 @@ fn apply_chicken_eating_damage( outcome: funrounds_core::ChickenEatOutcome, amount: i32, ) { - let action = runtime::EngineAction::ChickenEat { + let action = runtime::EngineAction::Chicken(runtime::chickens::Action::Eat { task, player, chicken, outcome, - }; + }); if !engine_action_current(&action) { return; } @@ -1293,17 +1514,17 @@ fn process_chicken_blast( origin: plugify::Vec3, config: funrounds_core::ChickenBlastConfig, ) { - let action = runtime::EngineAction::ChickenBlast { + let action = runtime::EngineAction::Chicken(runtime::chickens::Action::Blast { round, chicken, attacker, origin, config, - }; + }); if !engine_action_current(&action) { return; } - let (effect, credited_attacker) = match chicken_entities::prepare_blast(chicken, attacker, origin, config) { + let (effect, credited_attacker) = match chicken_entities::prepare_explosion(chicken, attacker, origin, config) { Ok(prepared) => prepared, Err(error) => { s2sdk::PrintToServer(&Str::from_str(&format!( @@ -1322,10 +1543,26 @@ fn process_chicken_blast( return; } if engine_action_current(&action) { + // Pure visual feedback is registered before damage can synchronously end + // the round. It shares the existing short-lived, round-end-safe lease. + match suicide::spawn_feedback_at(chicken, origin, chicken_entities::EXPLOSION_PARTICLE) { + Ok(handle) => { + let now = s2sdk::GetGameTime(); + let tracked = RUNTIME + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .as_mut() + .is_some_and(|runtime| runtime.track_suicide_feedback(handle, now)); + if !tracked { + suicide::remove_feedback(handle); + } + } + Err(error) => s2sdk::PrintToServer(&Str::from_str(&format!("[FunRounds] chicken blast particle failed: {error}"))), + } if catch_unwind(AssertUnwindSafe(|| chicken_entities::emit_blast_sound(effect, origin, config.radius))).is_err() { contain_failure("chicken blast sound callback panic contained"); } - if catch_unwind(AssertUnwindSafe(|| chicken_entities::detonate(effect, credited_attacker))).is_err() { + if catch_unwind(AssertUnwindSafe(|| chicken_entities::detonate_blast(effect, chicken, credited_attacker))).is_err() { contain_failure("chicken blast callback panic contained"); } } @@ -1406,6 +1643,9 @@ fn subscribe() -> Result<(), Box> { "[FunRounds] {event} unavailable; weapon scale pickup recovery uses inventory reconciliation" ))); continue; + } else if matches!(*event, "smokegrenade_detonate" | "smokegrenade_expired") { + s2sdk::PrintToServer(&Str::from_str(&format!("[FunRounds] {event} unavailable; medical_smoke modes excluded"))); + continue; } else if index >= 12 { s2sdk::PrintToServer(&Str::from_str(&format!("[FunRounds] {event} unavailable; special bomb modes excluded"))); continue; @@ -1492,14 +1732,29 @@ fn subscribe() -> Result<(), Box> { ], ); bomb_events.include(bot_takeover.clone()); + let grapple_bomb_use = subscribed_events( + hooks, + &[ + "bomb_beginplant", + "bomb_abortplant", + "bomb_planted", + "bomb_begindefuse", + "bomb_abortdefuse", + "bomb_defused", + ], + ) + .available(); let bomb_plant_tracking = subscribed_events(hooks, &["bomb_beginplant", "bomb_planted"]); let healthshot_support = healthshot_native_available(); - let use_target_support = use_target_native_available(); let chicken_follow_block_support = chicken_follow_block_native_available(); - let mut runtime = runtime::Runtime::new(runtime::EventCapabilities { + let runtime = runtime::Runtime::new(runtime::EventCapabilities { grenade_thrown: hooks & (1 << 6) != 0, + smoke_events: subscribed_events(hooks, &["smokegrenade_detonate", "smokegrenade_expired"]).available(), + spawn_listener_available: he_guidance_spawn_listener_imports_available(), weapon_fire: hooks & (1 << 7) != 0, + bullet_impact: subscribed_events(hooks, &["bullet_impact"]).available(), player_hurt: hooks & (1 << 8) != 0, + player_blind: subscribed_events(hooks, &["player_blind"]).available(), damage: damage_ready, chicken_damage: chicken_damage_ready, chicken_follow_block_support, @@ -1507,35 +1762,14 @@ fn subscribe() -> Result<(), Box> { bot_takeover: bot_takeover.clone(), round_prestart: subscribed_events(hooks, &["round_prestart"]).available(), bombs: bomb_events, + grapple_bomb_use, bomb_plant_tracking, moving_blast, healthshot: healthshot_support, })?; - if runtime.healthshot_configured() { - if !healthshot_support { - runtime.healthshot_hook_failure("native healthshot hooks or required ConVars unavailable"); - } else { - HEALTHSHOT_HOOKED.store(true, Ordering::Release); - if funrounds_native::HookHealthshot(on_healthshot_can_use, on_healthshot_effect) { - runtime.healthshot_hook_ready(); - } else { - runtime.healthshot_hook_failure("native healthshot hook registration failed"); - } - } - } - if runtime.chicken_use_configured() { - if use_target_support { - USE_TARGET_HOOKED.store(true, Ordering::Release); - if funrounds_native::HookUseTarget(on_use_target) { - runtime.chicken_use_hook_ready(); - } else { - runtime.chicken_use_hook_failure("native committed use-target hook registration failed"); - } - } else { - runtime.chicken_use_hook_failure("native committed use-target selector unavailable"); - } - } *RUNTIME.lock().map_err(|_| "FunRounds: runtime poisoned")? = Some(runtime); + sync_interaction_hooks(); + sync_he_guidance_spawn_listener(); { let mut guard = RUNTIME.lock().map_err(|_| "FunRounds: runtime poisoned")?; sync_chicken_follow_blocking(guard.as_mut().expect("runtime was just installed")); @@ -1587,6 +1821,10 @@ fn cleanup() -> Result<(), Box> { if let Err(error) = unregister_suicide_manifest_callback() { failed.push(error.to_string()); } + if let Err(error) = unregister_he_guidance_spawn_listener() { + invalidate_he_guidance_spawn_epoch(); + failed.push(error.to_string()); + } if !disable_chicken_follow_block(false) { failed.push("native chicken-follow detour cleanup is not confirmed".into()); } @@ -1663,7 +1901,7 @@ fn cleanup() -> Result<(), Box> { let mut shutdown_error = None; let mut shutdown_settled = false; for _ in 0..4 { - let (actions, equipment, projectiles, rollbacks, chickens, afterburns, suicide_feedback, error) = { + let (actions, equipment, projectiles, rollbacks, chickens, afterburns, suicide_feedback, grapples, guidance_fuses, error) = { let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let Some(runtime) = guard.as_mut() else { break }; let error = runtime.shutdown().err(); @@ -1675,6 +1913,8 @@ fn cleanup() -> Result<(), Box> { runtime.take_chicken_cleanup(), runtime.take_afterburn_cleanup(), runtime.take_suicide_feedback_cleanup(), + runtime.take_grapple_cleanup(), + runtime.take_he_guidance_fuse_restore_actions(), error, ) }; @@ -1686,6 +1926,8 @@ fn cleanup() -> Result<(), Box> { && chickens.is_empty() && afterburns.is_empty() && suicide_feedback.is_empty() + && grapples.is_empty() + && guidance_fuses.is_empty() { shutdown_settled = true; break; @@ -1699,6 +1941,10 @@ fn cleanup() -> Result<(), Box> { for handle in suicide_feedback { suicide::remove_feedback(handle); } + process_grapple_cleanup(grapples); + for action in guidance_fuses { + process_he_guidance_fuse_restore(action); + } for action in actions { process_bomb_action(action); } @@ -1923,6 +2169,7 @@ unsafe extern "C" fn on_use_target(pawn_handle: i32, target_handle: i32, in_use: let mut guard = RUNTIME.try_lock().expect("FunRounds runtime busy in player use-target callback"); let Some(runtime) = guard.as_mut() else { return }; assert!(runtime.on_game_thread(), "FunRounds player use-target callback is not on game thread"); + runtime.observe_grapple_target(pawn_handle, target_handle, in_use); runtime.observe_chicken_use_target(pawn_handle, target_handle, in_use); })) .unwrap_or_else(|_| contain_failure("player use-target callback panic contained")); @@ -2086,46 +2333,64 @@ unsafe extern "C" fn on_event(name: &Str, event: usize, _dont_broadcast: bool) - // CS2 has committed the winner, but mode health/armor have not been restored yet. apply_pending_bomb_explosion(); } - let (diagnostics, bomb_cleanup, chicken_cleanup, suicide_feedback_cleanup, prestart_context) = if let Ok(mut guard) = RUNTIME.try_lock() { - if let Some(runtime) = guard.as_mut() { - if !runtime.on_game_thread() { - panic!("FunRounds event is not on the game thread"); - } - runtime.event(&name, event); - sync_chicken_follow_blocking(runtime); - let prestart_context = if name == "round_prestart" { - runtime.take_prestart_context() - } else { - None - }; - let cleanup = if name == "round_prestart" { - runtime.take_bomb_actions() - } else { - Vec::new() - }; - let chicken_cleanup = if name == "round_prestart" { - runtime.take_chicken_cleanup() - } else { - Vec::new() - }; - let suicide_feedback_cleanup = if name == "round_prestart" { - runtime.take_suicide_feedback_cleanup() + let (diagnostics, bomb_cleanup, chicken_cleanup, suicide_feedback_cleanup, grapple_cleanup, prestart_context) = + if let Ok(mut guard) = RUNTIME.try_lock() { + if let Some(runtime) = guard.as_mut() { + if !runtime.on_game_thread() { + panic!("FunRounds event is not on the game thread"); + } + runtime.event(&name, event); + if matches!(name.as_str(), "round_prestart" | "round_start" | "round_end") { + invalidate_he_guidance_spawn_epoch(); + } + runtime.sync_he_guidance_spawn_epoch(); + sync_chicken_follow_blocking(runtime); + let prestart_context = if name == "round_prestart" { + runtime.take_prestart_context() + } else { + None + }; + let cleanup = if name == "round_prestart" { + runtime.take_bomb_actions() + } else { + Vec::new() + }; + let chicken_cleanup = if name == "round_prestart" { + runtime.take_chicken_cleanup() + } else { + Vec::new() + }; + let suicide_feedback_cleanup = if name == "round_prestart" { + runtime.take_suicide_feedback_cleanup() + } else { + Vec::new() + }; + let grapple_cleanup = runtime.take_grapple_cleanup(); + ( + runtime.diagnostics(), + cleanup, + chicken_cleanup, + suicide_feedback_cleanup, + grapple_cleanup, + prestart_context, + ) } else { - Vec::new() - }; - ( - runtime.diagnostics(), - cleanup, - chicken_cleanup, - suicide_feedback_cleanup, - prestart_context, - ) + (false, Vec::new(), Vec::new(), Vec::new(), Vec::new(), None) + } } else { - (false, Vec::new(), Vec::new(), Vec::new(), None) + panic!("FunRounds runtime busy or poisoned in event callback"); + }; + if name == "player_death" { + // Run the claimed self-only penalty before native death dispatch can + // end the round and cancel ordinary next-frame actions. + let penalties = { + let mut guard = RUNTIME.lock().unwrap_or_else(|p| p.into_inner()); + guard.as_mut().map(runtime::Runtime::take_teamkill_actions).unwrap_or_default() + }; + for action in penalties { + process_teamkill_action(action); } - } else { - panic!("FunRounds runtime busy or poisoned in event callback"); - }; + } // Submit old helpers before the native round reset flushes entity deletions. for handle in chicken_cleanup { chicken_entities::remove(handle); @@ -2136,8 +2401,12 @@ unsafe extern "C" fn on_event(name: &Str, event: usize, _dont_broadcast: bool) - for action in bomb_cleanup { process_bomb_action(action); } + process_grapple_cleanup(grapple_cleanup); + // Install the shared selector observer before prestart picks a mode that may + // require its capability. The runtime refuses to query until a live pawn exists. + sync_interaction_hooks(); if let Some(context) = prestart_context { - let chicken_cleanup = { + let (chicken_cleanup, grapple_cleanup) = { let mut guard = RUNTIME .try_lock() .expect("FunRounds runtime busy or poisoned after round_prestart cleanup"); @@ -2146,9 +2415,9 @@ unsafe extern "C" fn on_event(name: &Str, event: usize, _dont_broadcast: bool) - panic!("FunRounds round_prestart completion is not on the game thread"); } runtime.finish_round_prestart(context); - runtime.take_chicken_cleanup() + (runtime.take_chicken_cleanup(), runtime.take_grapple_cleanup()) } else { - Vec::new() + (Vec::new(), Vec::new()) } }; // Round selection can disable ordinary chickens after the first cleanup drain. @@ -2156,6 +2425,7 @@ unsafe extern "C" fn on_event(name: &Str, event: usize, _dont_broadcast: bool) - for handle in chicken_cleanup { chicken_entities::remove(handle); } + process_grapple_cleanup(grapple_cleanup); } if event_log_enabled(&name, diagnostics) { s2sdk::PrintToServer(&Str::from_str(&format!("[FunRounds] event: {name}"))); @@ -2178,7 +2448,7 @@ unsafe extern "C" fn on_player_death_pre(_name: &Str, event: usize, _dont_broadc } let victim = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); let attacker = s2sdk::GetEventPlayerSlot(event, &Str::from_str("attacker")); - let replay_weapon = damage::internal_damage_death_weapon(victim, attacker); + let replay_weapon = damage::internal_damage_death_weapon(victim, attacker).or_else(|| runtime::shooting::death_weapon(victim, attacker)); let matches_knife_impact = { let guard = RUNTIME.try_lock().expect("FunRounds runtime busy or poisoned in death pre hook"); let Some(runtime) = guard.as_ref() else { return }; @@ -2316,7 +2586,9 @@ fn damage_decision(mut context: damage::Damage, multiplier: &mut f32, mark_heads let mut guard = RUNTIME.try_lock().expect("FunRounds damage runtime busy or poisoned"); let Some(runtime) = guard.as_mut() else { return 0 }; assert!(runtime.on_game_thread(), "FunRounds damage callback is not on game thread"); + runtime.mark_he_guidance_detonated(context.inflictor, context.damage_type, context.skip_plugin_rules); context.weapon_class = damage::capture_weapon_class(context.weapon, context.inflictor, context.weapon_kind); + runtime::shooting::attribute_damage(&mut context); if runtime.blocks_native_bomb_damage(context.inflictor) { return 1; } @@ -2324,6 +2596,10 @@ fn damage_decision(mut context: damage::Damage, multiplier: &mut f32, mark_heads return 1; } let players = game::DamagePlayers::resolve(context.victim, context.attacker); + let native_he = runtime.classifies_native_he() && context.is_native_he(); + if native_he { + runtime.observe_he_blast(&context, players.victim); + } runtime.observe_chicken_blast_player_damage(&context, &players); let Some((projectile_scale, projectile_head)) = runtime.projectile_damage(&mut context) else { return 1; @@ -2331,6 +2607,9 @@ fn damage_decision(mut context: damage::Damage, multiplier: &mut f32, mark_heads // A physical player hit is not a miss even when a later configured rule // blocks it, defers it, or changes its amount to zero. runtime.record_native_player_hit(&context, &players); + if runtime.convert_friendly_shot(&context, &players) { + return 1; + } if runtime.chicken_blast_damage(&context) && let Some((action, is_headshot)) = chicken_blast_action(true, runtime.combat_protected(&players), runtime.headshots()) { @@ -2360,10 +2639,13 @@ fn damage_decision(mut context: damage::Damage, multiplier: &mut f32, mark_heads if action != 0 { return action; } - let Some(common) = runtime.classic_damage_scale(&context, &players) else { + let Some(common) = runtime.classic_damage_scale(&context, &players, native_he) else { return 1; }; let combined_scale = scale * common * projectile_scale; + if combined_scale == 0.0 || context.amount == 0.0 { + return 1; + } let afterburn_damage = runtime.afterburn_flame_damage(&context, &players); let mut effective_damage = afterburn_damage.unwrap_or(context.amount) * combined_scale; let mut damage_scale = if afterburn_damage.is_some() { @@ -2393,9 +2675,14 @@ fn damage_decision(mut context: damage::Damage, multiplier: &mut f32, mark_heads runtime.defer_damage(delayed_hit); return 1; } - if runtime.combat_damage(&context, &players, damage_scale, true) { + if runtime.combat_damage(&context, &players, damage_scale, true, native_he) { return 1; } + if let Some(victim) = players.victim + && let Err(error) = runtime.interrupt_movement_for_impulse(victim) + { + runtime.handle_fault(error.context("accepted damage interrupted temporary movement")); + } if random_heal > 0 && let Err(error) = runtime.queue_random_heal(&players, random_heal) { @@ -2510,7 +2797,7 @@ unsafe extern "C" fn on_command(slot: i32, context: ConCommandContext, args: &Ar let parsed = commands::Command::parse(&args).map_err(|key| runtime.text(slot, key, &[])); // A client bind has Console context; wire decisions and errors must still be visible in game. let wire_reply = slot >= 0 && args.first().is_some_and(|name| name == "fr_wire"); - let status = matches!(&parsed, Ok(commands::Command::Status)); + let line_reply = matches!(&parsed, Ok(commands::Command::Status | commands::Command::List)); let sync_touch = matches!(&parsed, Ok(commands::Command::Enable(_))); let response = parsed.and_then(|command| { if slot != -1 && !command.permits_player() { @@ -2529,8 +2816,8 @@ unsafe extern "C" fn on_command(slot: i32, context: ConCommandContext, args: &Ar } if wire_reply { i18n::send_chat(slot, &message); - } else if status { - for part in commands::status_reply_parts(&message) { + } else if line_reply { + for part in commands::line_reply_parts(&message) { s2sdk::ReplyToCommand(context, slot, &Str::from_str(part)); } } else { diff --git a/crates/funrounds-plugin/src/parameters.rs b/crates/funrounds-plugin/src/parameters.rs index 8586ecb..88a3438 100644 --- a/crates/funrounds-plugin/src/parameters.rs +++ b/crates/funrounds-plugin/src/parameters.rs @@ -47,6 +47,9 @@ fn round_settings(settings: Vec<(&'static str, String)>, purchase_prepared: bool pub fn settings(mode: &Mode) -> Vec<(&'static str, String)> { let mut settings = Vec::new(); + if let Some(damage) = mode.inferno_damage { + settings.push(("inferno_damage", damage.to_string())); + } if let Some(buy_time) = mode.buy_time { settings.push(("mp_buytime", buy_time.to_string())); } @@ -178,6 +181,7 @@ fn parameter_fault(name: &str, message: String) -> Fault { let mechanism = match name { "sv_infinite_ammo" => Mechanism::Ammo, "mp_taser_recharge_time" => Mechanism::TaserCharge, + "inferno_damage" => Mechanism::InfernoDamage, "sv_friction" => Mechanism::Friction, "host_timescale" => Mechanism::TimeScale, "sv_accelerate" => Mechanism::GroundAcceleration, @@ -236,15 +240,16 @@ fn convar_probe(names: impl IntoIterator) -> Probe { } pub fn has_convar(name: &str) -> bool { - valid_handle(s2sdk::FindConVar(&Str::from_str(name))) + let find = unsafe { std::ptr::addr_of!(s2sdk::__s2sdk_FindConVar).read() }; + find.is_some_and(|find| unsafe { valid_handle(find(&Str::from_str(name))) }) } -fn valid_handle(handle: u64) -> bool { +pub(crate) fn valid_handle(handle: u64) -> bool { // Source SDK ConVarRef stores the access index in the low 16 bits; zero is valid. handle as u16 != u16::MAX } -fn parsed_value(value: &str) -> Option { +pub(crate) fn parsed_value(value: &str) -> Option { let value = match value { "true" => 1.0, "false" => 0.0, @@ -329,6 +334,7 @@ pub fn capabilities(weapon_fire: bool, round_prestart: bool, reasons: &mut Vec bool { + KNIFE_FIRE_WEAPON_NAMES.contains(&weapon.strip_prefix("weapon_").unwrap_or(weapon)) +} macro_rules! imports_available { ($($name:ident),+ $(,)?) => {{ @@ -459,7 +488,7 @@ impl Projectiles { } Ok(()) } - _ => Err("projectile engine action returned an unexpected result".into()), + _ => Err(Fault::global("projectile engine action returned an unexpected result")), } } @@ -491,6 +520,11 @@ impl Projectiles { .collect() } + /// Includes retired knives awaiting deletion; they are never native smoke. + pub(crate) fn manages_projectile(&self, handle: i32) -> bool { + self.tracked.contains_key(&handle) || self.retired.contains(&handle) || self.removing.contains(&handle) + } + pub fn is_clean(&self) -> bool { self.tracked.is_empty() && self.retired.is_empty() @@ -779,6 +813,10 @@ impl Projectiles { let impact = self.synthetic_impact(damage)?; if impact.kind == Kind::Knife { damage.weapon_class = Some(KNIFE_WEAPON_CLASS.to_owned()); + // The collision, not the thrower's current weapon or aim, owns this hit. + damage.weapon_kind = 2; + damage.traced_head = impact.headshot; + damage.hit_group = if impact.headshot { 1 } else { 0 }; } Some(impact) } @@ -1313,7 +1351,7 @@ fn set_elasticity(handle: i32, elasticity: f32) -> Result<(), String> { Ok(()) } -fn forward(angles: Vec3) -> Vec3 { +pub(crate) fn forward(angles: Vec3) -> Vec3 { let pitch = angles.x.to_radians(); let yaw = angles.y.to_radians(); Vec3 { diff --git a/crates/funrounds-plugin/src/random_spawn.rs b/crates/funrounds-plugin/src/random_spawn.rs index d8b9087..8e6f958 100644 --- a/crates/funrounds-plugin/src/random_spawn.rs +++ b/crates/funrounds-plugin/src/random_spawn.rs @@ -48,6 +48,12 @@ fn mechanism(message: impl Into) -> Fault { Fault::mechanism(Mechanism::RandomSpawn, message) } +fn keep_engine_spawn(slot: i32) { + s2sdk::PrintToServer(&Str::from_str(&format!( + "[FunRounds] random spawn unavailable slot={slot}; keeping engine spawn and continuing loadout" + ))); +} + fn deathmatch_spawn_points() -> Result, Fault> { let classname = Str::from_str(DEATHMATCH_SPAWN); let mut start_from = -1; @@ -73,7 +79,8 @@ fn deathmatch_spawn_points() -> Result, Fault> { Ok(points) } -/// Move an eligible live player to a engine deathmatch spawn point before loadout application. +/// Move an eligible live player to an engine deathmatch spawn point before loadout application. +/// If no point is available, keep the engine spawn without cancelling the loadout. /// The caller supplies the action identity guard and must run this on the game thread. pub(crate) fn apply(player: crate::game::LivePlayer, mode: &Mode, mut is_current: impl FnMut() -> bool) -> Result<(), Fault> { let Some(filter) = mode.random_spawn.filter(|filter| *filter != TeamFilter::None) else { @@ -101,7 +108,8 @@ pub(crate) fn apply(player: crate::game::LivePlayer, mode: &Mode, mut is_current let mut rng = rand::rngs::StdRng::try_from_rng(&mut system_rng) .map_err(|error| mechanism(format!("cannot initialize spawn selection randomness: {error}")))?; let Some(start_point) = points.choose(&mut rng).copied() else { - return Err(mechanism("map has no info_deathmatch_spawn points")); + keep_engine_spawn(player.slot); + return Ok(()); }; if !is_current() { @@ -111,7 +119,11 @@ pub(crate) fn apply(player: crate::game::LivePlayer, mode: &Mode, mut is_current if !is_current() { return Err(Fault::cancelled("random spawn cancelled after native selection")); } - if selected == -1 || !s2sdk::IsValidEntHandle(selected) || s2sdk::GetEntityClassname(selected).as_str() != DEATHMATCH_SPAWN { + if selected == -1 { + keep_engine_spawn(player.slot); + return Ok(()); + } + if !s2sdk::IsValidEntHandle(selected) || s2sdk::GetEntityClassname(selected).as_str() != DEATHMATCH_SPAWN { return Err(mechanism(format!( "native selector returned no valid info_deathmatch_spawn point (handle {selected})" ))); diff --git a/crates/funrounds-plugin/src/runtime.rs b/crates/funrounds-plugin/src/runtime.rs index a967373..b948350 100644 --- a/crates/funrounds-plugin/src/runtime.rs +++ b/crates/funrounds-plugin/src/runtime.rs @@ -1,6 +1,22 @@ // Copyright (C) 2026 Mai Ooizumi // SPDX-License-Identifier: AGPL-3.0-or-later +pub(crate) mod afterburn; +pub(crate) mod chickens; +pub(crate) mod combat; +mod composed; +pub(crate) mod grapple; +pub(crate) mod healthshot; +pub(crate) mod proximity; +mod public_properties; +mod regions; +pub(crate) mod respawn; +pub(crate) mod shooting; +pub(crate) mod suicide; +pub(crate) mod teamkill; +pub(crate) use combat::RandomHealReceipt; +pub(crate) use composed::execute as execute_composed; + use crate::{ commands::Command, effects::{Effect, equipment}, @@ -14,7 +30,7 @@ use funrounds_core::{ SelfDamage, TeamDeathmatch, }; use plugify::Str; -use rand::{RngExt, SeedableRng, rngs::StdRng, seq::SliceRandom}; +use rand::{RngExt, SeedableRng, rngs::StdRng}; use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::thread::{ThreadId, current}; @@ -30,8 +46,12 @@ enum PendingAction { pub struct EventCapabilities { pub grenade_thrown: bool, + pub smoke_events: bool, + pub spawn_listener_available: bool, pub weapon_fire: bool, + pub bullet_impact: bool, pub player_hurt: bool, + pub player_blind: bool, pub damage: bool, pub chicken_damage: bool, pub chicken_follow_block_support: bool, @@ -39,6 +59,7 @@ pub struct EventCapabilities { pub bot_takeover: crate::capability::Probe, pub round_prestart: bool, pub bombs: crate::capability::Probe, + pub grapple_bomb_use: bool, pub bomb_plant_tracking: crate::capability::Probe, pub moving_blast: crate::capability::Probe, pub healthshot: bool, @@ -59,68 +80,13 @@ struct PendingTakeover { event_tick: i32, } -#[derive(Clone, Copy)] -pub(crate) struct RandomHealReceipt { - pub target: PlayerTask, - pub source: PlayerTask, - pub target_live: LivePlayer, - pub source_live: LivePlayer, - pub frame_token: u64, - pub amount: i32, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -struct NativeSelfDamageShot { - task: PlayerTask, - player: LivePlayer, - tick: i32, - weapon: FiredWeapon, - player_hit: bool, -} - #[derive(Clone, Debug, PartialEq, Eq)] -struct FiredWeapon { +pub(crate) struct FiredWeapon { handle: i32, classname: String, item_definition: u16, } -#[derive(Clone, Debug, PartialEq, Eq)] -struct PendingChickenBlastKill { - round: RoundGeneration, - victim: PlayerIdentity, - tick: i32, - damage_frame_token: Option, - source: crate::chicken_entities::KillWeaponSource, -} - -impl PendingChickenBlastKill { - fn matches(&self, round: RoundGeneration, victim: PlayerIdentity, attacker: PlayerIdentity, tick: i32, frame_token: Option) -> bool { - self.round == round - && self.victim == victim - && self.source.attacker == attacker - && self.tick == tick - && self.damage_frame_token.is_none_or(|expected| frame_token == Some(expected)) - } -} - -fn chicken_weapon_source_readback_matches( - source: &crate::chicken_entities::KillWeaponSource, - attacker: PlayerIdentity, - valid: bool, - owner: i32, - inventory: &[i32], - classname: &str, - item_definition: u16, -) -> bool { - source.attacker == attacker - && valid - && owner == attacker.pawn_handle as i32 - && inventory.contains(&source.handle) - && source.classname == classname - && source.item_definition == item_definition -} - fn tracked_upgrade_weapon(effect: &Effect, player: LivePlayer) -> Option { let inventory = s2sdk::GetClientWeapons(player.slot); let (handle, classname, item_definition) = effect.upgraded_weapon().filter(|(handle, classname, expected_item_definition)| { @@ -177,143 +143,44 @@ fn kill_weapon_target_readback_matches( && crate::effects::equipment::kill_loadout_source_weapon(classname) } -fn capture_chicken_damage_weapon_source( - damage: crate::chicken_entities::EntityDamageSource, - players: &PlayerTracker, - controllers: &HashMap, -) -> Option { - let item_definition_reader = unsafe { crate::effects::__s2sdk_GetWeaponItemDefinition }.expect("required native ABI checked at startup"); - for slot in 0..s2sdk::GetMaxClients() { - let Some(player) = LivePlayer::resolve(slot) else { continue }; - if (s2sdk::GetClientTeam(slot) as i32) < 2 - || player.pawn_handle != damage.attacker - || controllers.get(&slot) != Some(&player.controller_handle) - { - continue; - } - let Some(attacker) = players - .identity(slot) - .filter(|identity| identity.pawn_handle == player.pawn_handle as u32) - else { - continue; - }; - let inventory = s2sdk::GetClientWeapons(slot); - for handle in [damage.ability, damage.inflictor] { - if handle == -1 - || !s2sdk::IsValidEntHandle(handle) - || s2sdk::GetEntityOwner(handle) != player.pawn_handle - || !inventory.iter().any(|owned| *owned == handle) - { - continue; - } - let classname = s2sdk::GetEntityClassname(handle).to_string(); - if !classname.starts_with("weapon_") { - continue; - } - let item_definition = unsafe { item_definition_reader(handle) }; - return Some(crate::chicken_entities::KillWeaponSource { - attacker, - handle, - classname, - item_definition, - }); - } - } - None -} - -fn chicken_weapon_source_is_current( - source: &crate::chicken_entities::KillWeaponSource, - players: &PlayerTracker, - controllers: &HashMap, -) -> bool { - let Some(player) = LivePlayer::resolve(source.attacker.slot) else { - return false; - }; - if players.identity(player.slot) != Some(source.attacker) - || controllers.get(&player.slot) != Some(&player.controller_handle) - || player.pawn_handle != source.attacker.pawn_handle as i32 - { - return false; - } - let valid = s2sdk::IsValidEntHandle(source.handle); - if !valid { - return false; - } - let owner = s2sdk::GetEntityOwner(source.handle); - let inventory = s2sdk::GetClientWeapons(player.slot).iter().copied().collect::>(); - let classname = s2sdk::GetEntityClassname(source.handle).to_string(); - let item_definition_reader = unsafe { crate::effects::__s2sdk_GetWeaponItemDefinition }.expect("required native ABI checked at startup"); - let item_definition = unsafe { item_definition_reader(source.handle) }; - chicken_weapon_source_readback_matches(source, source.attacker, valid, owner, &inventory, &classname, item_definition) -} - -#[derive(Clone, Copy, Debug, PartialEq)] -struct OwnedFloat { - previous: f32, - installed: f32, -} - -#[derive(Clone, Debug)] -struct WeaponInventory { - player: LivePlayer, - identity: PlayerIdentity, - weapons: HashMap, -} - -impl NativeSelfDamageShot { - fn matches_hit(&self, task: PlayerTask, player: LivePlayer, tick: i32, damage: &crate::damage::Damage) -> bool { - self.task == task - && self.player == player - && self.tick == tick - && self.weapon.handle == damage.weapon - && damage.weapon_class.as_deref() == Some(self.weapon.classname.as_str()) - } - - fn mark_player_hit(&mut self, task: PlayerTask, player: LivePlayer, tick: i32, damage: &crate::damage::Damage) -> bool { - if !self.matches_hit(task, player, tick, damage) { - return false; - } - self.player_hit = true; - true - } -} - -fn native_self_damage_signature(damage: &crate::damage::Damage, player: LivePlayer) -> bool { - !damage.skip_plugin_rules - && damage.victim == player.pawn_handle - && damage.attacker == player.pawn_handle - && damage.inflictor == player.pawn_handle - && damage.weapon == -1 - && damage.weapon_kind == 0 - && damage.damage_type == 0 - && damage.amount.is_finite() - && damage.amount > 0.0 -} - -fn round_end_finish_valid( - enabled: bool, - phase: Phase, - task: PlayerTask, - player: LivePlayer, - current_identity: Option, - live_player: Option, -) -> bool { - enabled && phase == Phase::Idle && current_identity == Some(task.player) && live_player == Some(player) -} - -fn round_end_finish_due(tick: i32, queued_tick: i32) -> bool { - tick > queued_tick -} - fn tracks_chicken_life(phase: Phase) -> bool { matches!(phase, Phase::Preparing | Phase::Running | Phase::Warmup) } +fn mode_configured(config: &funrounds_core::Config, predicate: impl Fn(&funrounds_core::Mode) -> bool) -> bool { + config.modes.iter().chain(config.warmup.iter().map(|warmup| &warmup.mode)).any(predicate) +} + fn active_combat_phase(phase: Phase) -> bool { matches!(phase, Phase::Running | Phase::Warmup) } +fn wall_hang_capability(reasons: &mut Vec) -> bool { + let mut probe = crate::capability::Probe::default(); + crate::capability::imports!(probe; + __s2sdk_GetEntityMoveType, __s2sdk_GetClientFlags, __s2sdk_GetClientButtons, + __s2sdk_GetClientAbsOrigin, __s2sdk_GetEntityAbsVelocity, __s2sdk_SetEntityAbsVelocity, + __s2sdk_IsValidEntHandle, __s2sdk_EntHandleToEntPointer, __s2sdk_EntIndexToEntHandle, + __s2sdk_GetEntityClassname, __s2sdk_GetSchemaOffset, __s2sdk_GetEntSchema2, + __s2sdk_GetEntSchemaVector3D2, __s2sdk_GetClientGravity, __s2sdk_SetClientGravity, + ); + let native = unsafe { std::ptr::addr_of!(crate::funrounds_native::__funrounds_native_HasPlayerMovementHullSupport).read() }; + probe.require(unsafe { native.is_some_and(|support| support()) }, "native:HasPlayerMovementHullSupport"); + for (class, field) in [ + ("CBasePlayerPawn", "m_pMovementServices"), + ("CPlayer_MovementServices", "m_nQueuedButtonDownMask"), + ("CPlayer_MovementServices", "m_nQueuedButtonChangeMask"), + ("CPlayer_MovementServices", "m_nButtons"), + ("CInButtonState", "m_pButtonStates"), + ("CBaseEntity", "m_pCollision"), + ("CCollisionProperty", "m_vecMins"), + ("CCollisionProperty", "m_vecMaxs"), + ] { + probe.schema(class, field); + } + probe.record("wall_hang", reasons) +} + fn damageable_chicken(handle: i32) -> bool { const BASE_ENTITY: &str = "CBaseEntity"; @@ -329,201 +196,34 @@ fn damageable_chicken(handle: i32) -> bool { && s2sdk::GetEntSchema2(pointer, &Str::from_str(BASE_ENTITY), &Str::from_str("m_lifeState"), 0) == 0 } -fn use_button_rising_edge(states: &mut HashMap, identity: PlayerIdentity, down: bool) -> bool { - let rising = down && !states.get(&identity.slot).is_some_and(|(old, was_down)| *old == identity && *was_down); - if down { - states.insert(identity.slot, (identity, true)); - } else if states.get(&identity.slot).is_some_and(|(old, _)| *old == identity) { - states.remove(&identity.slot); - } - rising -} - -fn update_owned_minimum(properties: &mut HashMap, handle: i32, current: f32, installed: f32) -> Option { - if !current.is_finite() || !installed.is_finite() { - return None; - } - match properties.get(&handle).copied() { - Some(_) if (current - installed).abs() <= 0.0001 => None, - Some(owner) if current < installed => { - properties.insert(handle, owner); - Some(installed) - } - Some(_) => { - properties.remove(&handle); - None - } - None if current < installed => { - properties.insert( - handle, - OwnedFloat { - previous: current, - installed, - }, - ); - Some(installed) - } - None => None, - } -} - -fn owned_float_restore(owner: OwnedFloat, current: f32) -> Option { - (current.is_finite() && (current - owner.installed).abs() <= 0.0001).then_some(owner.previous) -} - -fn matches_weapon_item(classname: &str, item: &str) -> bool { - let item = item.trim().to_ascii_lowercase(); - let classname = classname.trim().to_ascii_lowercase(); - !item.is_empty() && (item == classname || format!("weapon_{item}") == classname || format!("weapon_{classname}") == item) -} - -fn player_movement_services_for_handle(handle: i32) -> Option { - if !s2sdk::IsValidEntHandle(handle) { - return None; - } - let pawn = s2sdk::EntHandleToEntPointer(handle); - if pawn == 0 || s2sdk::EntPointerToEntHandle(pawn) != handle || s2sdk::GetEntityClassname(handle).as_str() != "player" { - return None; - } - let pawn_class = Str::from_str("CBasePlayerPawn"); - let services_field = Str::from_str("m_pMovementServices"); - let movement_class = Str::from_str("CCSPlayer_MovementServices"); - let duck_field = Str::from_str("m_flDuckSpeed"); - if s2sdk::GetSchemaOffset(&pawn_class, &services_field) < 0 || s2sdk::GetSchemaOffset(&movement_class, &duck_field) < 0 { - return None; - } - let services = s2sdk::GetEntSchema2(pawn, &pawn_class, &services_field, 0) as usize; - (services != 0).then_some(services) -} - -fn duck_speed_for_handle(handle: i32) -> Option { - let services = player_movement_services_for_handle(handle)?; - let speed = s2sdk::GetEntSchemaFloat2(services, &Str::from_str("CCSPlayer_MovementServices"), &Str::from_str("m_flDuckSpeed"), 0) as f32; - speed.is_finite().then_some(speed) -} - -fn set_duck_speed_for_handle(handle: i32, value: f32) -> bool { - if !value.is_finite() { - return false; - } - let Some(services) = player_movement_services_for_handle(handle) else { - return false; - }; - s2sdk::SetEntSchemaFloat2( - services, - &Str::from_str("CCSPlayer_MovementServices"), - &Str::from_str("m_flDuckSpeed"), - f64::from(value), - true, - 0, - ); - duck_speed_for_handle(handle).is_some_and(|actual| (actual - value).abs() <= 0.0001) -} - -fn release_duck_speed(handle: i32, owner: OwnedFloat) -> bool { - if !s2sdk::IsValidEntHandle(handle) { - return true; - } - let Some(current) = duck_speed_for_handle(handle) else { return false }; - let Some(previous) = owned_float_restore(owner, current) else { - return true; - }; - set_duck_speed_for_handle(handle, previous) -} - -fn duck_speed_update_candidate(player: LivePlayer, active_player: Option, team: i32) -> Option { - if active_player != Some(player) || !matches!(team, 2 | 3) { - return None; - } - duck_speed_for_handle(player.pawn_handle) -} - -fn release_model_scale(handle: i32, owner: OwnedFloat) -> bool { - if !s2sdk::IsValidEntHandle(handle) { - return true; - } - let Some(current) = Runtime::entity_model_scale(handle) else { - return false; - }; - let Some(previous) = owned_float_restore(owner, current) else { - return true; - }; - Runtime::set_entity_model_scale(handle, previous) -} - -fn lethal_suicide_finish_amount(anchor: f32, health: i32) -> Option { - if !anchor.is_finite() || anchor <= 0.0 || health <= 0 { - return None; - } - let current_health_amount = health as f32 * 10.0; - current_health_amount.is_finite().then_some(anchor.max(current_health_amount)) -} - // Execute after releasing the runtime lock: these engine calls can fire synchronous events. pub enum EngineAction { + Composed(composed::Action), + Shooting(shooting::Action), + Proximity(proximity::Action), + Shockwave(proximity::ShockwaveAction), + HeGuidance(proximity::GuidanceAction), + HeGuidanceFuseRestore(proximity::GuidanceFuseRestoreAction), + Teamkill(teamkill::Action), Rollback(PlayerTask, LivePlayer), Loadout(PlayerTask, LivePlayer, Vec), SettleLoadout(PlayerTask, LivePlayer, i32), Upgrade(PlayerTask, LivePlayer, Option), ThirdPerson(PlayerTask, LivePlayer), - GrantC4(PlayerTask, LivePlayer), - RemoveC4(PlayerTask, LivePlayer, Vec), - Respawn(PlayerTask, LivePlayer, i32), - RoundRespawn(PlayerTask, LivePlayer, i32), - LowHealthFinish(PlayerTask, LivePlayer, bool), + Suicide(suicide::Action), + Respawn(respawn::Action), EndRound(RoundGeneration, s2sdk::CSRoundEndReason), - CenterDisplay { - generation: RoundGeneration, - }, + CenterDisplay { generation: RoundGeneration }, Projectile(crate::projectiles::Action), HostageRescue(crate::compat::hostage_rescue::ForwardAction), Bomb(crate::bombs::Action), Equipment(equipment::Action), ProjectileImpact(crate::projectiles::Impact), - Reflection(crate::damage::Reflection), - DelayedDamage(crate::damage::DelayedDamage), - Suicide(crate::suicide::Action), - ChickenSpawn { - round: RoundGeneration, - origin: plugify::Vec3, - }, - ChickenBlast { - round: RoundGeneration, - chicken: i32, - attacker: Option, - origin: plugify::Vec3, - config: funrounds_core::ChickenBlastConfig, - }, - ChickenRemove(i32), - SuicideFeedbackRemove(i32), - ChickenPurchase { - task: PlayerTask, - player: LivePlayer, - price: u32, - origin: plugify::Vec3, - }, - HealthshotUse { - task: PlayerTask, - player: LivePlayer, - base_health: i32, - config: funrounds_core::HealthshotConfig, - }, - HealthshotPurchase { - task: PlayerTask, - player: LivePlayer, - price: u32, - }, - ChickenEat { - task: PlayerTask, - player: LivePlayer, - chicken: i32, - outcome: funrounds_core::ChickenEatOutcome, - }, - AfterburnIgnite { - task: PlayerTask, - player: LivePlayer, - }, - AfterburnRemove(i32), + Combat(combat::Action), + Chicken(chickens::Action), + Healthshot(healthshot::Action), + Afterburn(afterburn::Action), + Grapple(grapple::Action), } #[derive(Clone, Debug, PartialEq, Eq)] @@ -546,11 +246,6 @@ pub struct PreparedEquipmentEffect { pub upgrade: Option, } -fn clear_chicken_purchase_state(slot: i32, pending: &mut HashMap, actions: &mut Vec) { - pending.remove(&slot); - actions.retain(|action| !matches!(action, EngineAction::ChickenPurchase { task, .. } if task.player.slot == slot)); -} - pub struct Runtime { pub controller: RoundController, config_path: PathBuf, @@ -573,12 +268,9 @@ pub struct Runtime { third_person_map_detach_pending: bool, equipment: Vec, parameters: Parameters, - healthshot_parameters: Parameters, - healthshot_hooks_ready: bool, - healthshot_override_active: bool, - healthshot_faulted: bool, - healthshot_purchases: HashMap, + healthshot: healthshot::State, ground_reverse: crate::ground_reverse::GroundReverse, + air_strafe: crate::autostrafe::AirStrafe, night_vision: crate::night_vision::NightVision, ghost: crate::effects::GhostRuntime, team_names: Parameters, @@ -591,46 +283,41 @@ pub struct Runtime { team_match: Option, periodic_movement: Option<(RoundGeneration, funrounds_core::PeriodicMovement)>, money_income: Option<(RoundGeneration, MoneyIncome, f32)>, - respawns: Vec<(PlayerTask, LivePlayer, i32, f32)>, - round_respawns: Vec<(PlayerTask, LivePlayer, i32, f32)>, - low_health_finishes: Vec, + respawning: respawn::State, bombs: crate::bombs::Bombs, projectiles: crate::projectiles::Projectiles, hostage_rescue: crate::compat::hostage_rescue::State, chickens: crate::chicken_adapter::ChickenAdapter, - chicken_entities: crate::chicken_entities::Chickens, - chicken_ready: bool, - chicken_follow_block_support: bool, - chicken_use_ready: bool, - chicken_use_buttons: HashMap, - chicken_spawn_round: Option, - pending_chicken_blast_kills: HashMap, - chicken_cleanup: Vec, - chicken_purchases: HashMap, + ordinary_chickens: chickens::State, + use_target_hook_ready: bool, + grapple_bomb_use_ready: bool, + use_target_hook_requested: bool, + use_target_probe_retry_at: f32, + grapple: grapple::State, + he_guidance_spawn_listener_available: bool, + he_guidance_spawn_listener_requested: bool, + he_guidance_spawn_listener_ready: bool, + he_guidance_probe_ready: bool, + composed: composed::State, + regions: regions::State, + shooting: shooting::State, + proximity: proximity::State, + teamkills: teamkill::State, afterburns: crate::afterburn::Afterburns, - afterburn_cleanup: Vec, impacts: Vec, chicken_impacts: Vec, - suicide_feedback: crate::suicide::FeedbackEntities, - suicide_feedback_cleanup: Vec, - combat: HashMap, - reflections: Vec, - delayed_damage: Vec, - random_heals: Vec, - native_self_damage_shots: HashMap, + combat: combat::State, suicides: crate::suicide::Suicides, - c4_assigned: bool, + death_explosives: suicide::DeathExplosions, engine_actions: Vec, equipment_in_flight: usize, settling_loadouts: Vec<(PlayerTask, i32, i32)>, prestart_context: Option<(i32, bool)>, warmup_active: bool, warmup_activation_pending: bool, + warmup_round_faulted: bool, round_transition_waiting: bool, - duck_speed: HashMap, - weapon_inventory: HashMap, - model_scales: HashMap, - model_scale_restore_pending: HashSet, + public_properties: public_properties::State, } impl Runtime { @@ -659,7 +346,11 @@ impl Runtime { } let mut capability_reasons = Vec::new(); let mut capabilities = parameters::capabilities(events.weapon_fire, events.round_prestart, &mut capability_reasons); - capabilities.healthshot = healthshot_configured && events.healthshot; + let mut autostrafe = crate::capability::Probe::default(); + autostrafe.require(crate::autostrafe::available(), "native:air_move"); + autostrafe.require(events.combat_events, "events:player_spawn/player_death"); + capabilities.autostrafe = autostrafe.record("autostrafe", &mut capability_reasons); + capabilities.healthshot = events.healthshot; if healthshot_configured && !events.healthshot { capability_reasons.push("healthshot:[native hooks or required health ConVars unavailable]".into()); } @@ -685,6 +376,17 @@ impl Runtime { ); suicide.require(unsafe { s2sdk::__s2sdk_SetEventString }.is_some(), "import:SetEventString"); capabilities.suicide = suicide.record("suicide", &mut capability_reasons); + let mut death_explosion = crate::suicide::blast_probe(); + death_explosion.require(events.damage, "hook:entity_damage"); + death_explosion.require(events.player_hurt, "event:player_hurt"); + death_explosion.require(events.combat_events, "events:player_spawn/player_death"); + death_explosion.require(crate::damage::reflection_available(), "import:TakeEntityDamageWithWeapon"); + death_explosion.require( + crate::KNIFE_DEATH_PRE_HOOKED.load(std::sync::atomic::Ordering::Acquire), + "hook:player_death_pre", + ); + death_explosion.require(unsafe { s2sdk::__s2sdk_SetEventString }.is_some(), "import:SetEventString"); + capabilities.death_explosion = death_explosion.record("death_explosion", &mut capability_reasons); let mut source_damage = crate::capability::Probe::default(); source_damage.require(events.damage, "hook:entity_damage"); capabilities.weapon_damage = source_damage.clone().record("weapon_damage", &mut capability_reasons); @@ -705,9 +407,9 @@ impl Runtime { capabilities.energy_shield = combat.clone().record("energy_shield", &mut capability_reasons); capabilities.combat_protection = combat.record("combat_protection", &mut capability_reasons); let bomb_capabilities = crate::bombs::capabilities( - events.bombs, - events.bomb_plant_tracking, - events.moving_blast, + events.bombs.clone(), + events.bomb_plant_tracking.clone(), + events.moving_blast.clone(), events.round_prestart, &mut capability_reasons, ); @@ -735,6 +437,11 @@ impl Runtime { ); push.require(events.weapon_fire, "event:weapon_fire"); capabilities.self_push = push.record("self_push", &mut capability_reasons); + capabilities.wall_hang = wall_hang_capability(&mut capability_reasons); + capabilities.grapple = false; + if config.as_ref().is_ok_and(|config| mode_configured(config, |mode| mode.grapple.is_some())) { + capability_reasons.push("grapple:[waiting for a live pawn and the shared use-target observer]".into()); + } let mut model_scale = crate::capability::Probe::default(); crate::capability::imports!(model_scale; __s2sdk_GetEntityModelScale, __s2sdk_SetEntityModelScale); model_scale.record("model_scale", &mut capability_reasons); @@ -790,6 +497,20 @@ impl Runtime { afterburn.schema("CBaseEntity", "m_hEffectEntity"); afterburn.schema("CEntityFlame", "m_hEntAttached"); capabilities.afterburn = afterburn.record("afterburn", &mut capability_reasons); + composed::probe(&events, &mut capabilities, &mut capability_reasons); + let regions = regions::probe(&events, &mut capabilities, &mut capability_reasons); + shooting::probe(&events, &mut capabilities, &mut capability_reasons); + proximity::probe(&events, &mut capabilities, &mut capability_reasons); + let he_guidance_probe_ready = capabilities.he_guidance; + capabilities.he_guidance = false; + if he_guidance_probe_ready + && config + .as_ref() + .is_ok_and(|config| mode_configured(config, |mode| mode.he_guidance.is_some())) + { + capability_reasons.push("he_guidance:[waiting for entity spawn listener registration]".into()); + } + teamkill::probe(&events, &mut capabilities, &mut capability_reasons); log(&format!( "capabilities={capabilities:?} capability_reasons={}", capability_reasons.join(";") @@ -819,12 +540,9 @@ impl Runtime { third_person_map_detach_pending: false, equipment: Vec::new(), parameters: Parameters::default(), - healthshot_parameters: Parameters::default(), - healthshot_hooks_ready: false, - healthshot_override_active: false, - healthshot_faulted: false, - healthshot_purchases: HashMap::new(), + healthshot: healthshot::State::default(), ground_reverse: crate::ground_reverse::GroundReverse::default(), + air_strafe: crate::autostrafe::AirStrafe::default(), night_vision: crate::night_vision::NightVision::default(), ghost: crate::effects::GhostRuntime::default(), team_names: Parameters::default(), @@ -837,312 +555,130 @@ impl Runtime { team_match: None, periodic_movement: None, money_income: None, - respawns: Vec::new(), - round_respawns: Vec::new(), - low_health_finishes: Vec::new(), + respawning: respawn::State::default(), bombs: crate::bombs::Bombs::default(), projectiles: crate::projectiles::Projectiles::default(), hostage_rescue: crate::compat::hostage_rescue::State::new(), chickens: crate::chicken_adapter::ChickenAdapter::default(), - chicken_entities: crate::chicken_entities::Chickens::default(), - chicken_ready, - chicken_follow_block_support: events.chicken_follow_block_support, - chicken_use_ready: false, - chicken_use_buttons: HashMap::new(), - chicken_spawn_round: None, - pending_chicken_blast_kills: HashMap::new(), - chicken_cleanup: Vec::new(), - chicken_purchases: HashMap::new(), + ordinary_chickens: chickens::State::new(chicken_ready, events.chicken_follow_block_support), + use_target_hook_ready: false, + grapple_bomb_use_ready: events.grapple_bomb_use, + use_target_hook_requested: false, + use_target_probe_retry_at: 0.0, + grapple: grapple::State::default(), + he_guidance_spawn_listener_available: events.spawn_listener_available, + he_guidance_spawn_listener_requested: false, + he_guidance_spawn_listener_ready: false, + he_guidance_probe_ready, + composed: crate::runtime::composed::State::default(), + regions, + shooting: crate::runtime::shooting::State::default(), + proximity: crate::runtime::proximity::State::default(), + teamkills: crate::runtime::teamkill::State::default(), afterburns: crate::afterburn::Afterburns::default(), - afterburn_cleanup: Vec::new(), impacts: Vec::new(), chicken_impacts: Vec::new(), - suicide_feedback: crate::suicide::FeedbackEntities::default(), - suicide_feedback_cleanup: Vec::new(), - combat: HashMap::new(), - reflections: Vec::new(), - delayed_damage: Vec::new(), - random_heals: Vec::new(), - native_self_damage_shots: HashMap::new(), + combat: combat::State::default(), suicides: crate::suicide::Suicides::default(), - c4_assigned: false, + death_explosives: suicide::DeathExplosions::default(), engine_actions: Vec::new(), equipment_in_flight: 0, settling_loadouts: Vec::new(), prestart_context: None, warmup_active: false, warmup_activation_pending: false, + warmup_round_faulted: false, round_transition_waiting: false, - duck_speed: HashMap::new(), - weapon_inventory: HashMap::new(), - model_scales: HashMap::new(), - model_scale_restore_pending: HashSet::new(), + public_properties: public_properties::State::default(), }) } - pub(crate) fn healthshot_configured(&self) -> bool { - self.controller.config().is_some_and(|config| config.healthshot.is_some()) - } - - pub(crate) fn chicken_use_configured(&self) -> bool { + fn he_guidance_configured(&self) -> bool { self.controller .config() - .is_some_and(|config| config.chicken.is_some_and(|chicken| chicken.eating.enabled)) - } - - pub(crate) fn chicken_follow_block_supported(&self) -> bool { - self.chicken_follow_block_support - } - - /// The native veto applies to every configured FunRounds chicken round, even when eating is disabled. - pub(crate) fn chicken_follow_block_desired(&self) -> bool { - self.controller.enabled() - && self.faults.recovery != Recovery::Stopped - && self.controller.config().is_some_and(|config| config.chicken.is_some()) + .is_some_and(|config| mode_configured(config, |mode| mode.he_guidance.is_some())) } - pub(crate) fn chicken_use_hook_ready(&mut self) { - self.chicken_use_ready = true; - } - - pub(crate) fn chicken_use_hook_failure(&mut self, reason: impl Into) { - self.chicken_use_ready = false; - let reason = reason.into(); - self.capability_reasons.push(format!("chicken_eating:[{reason}]")); - log(&format!("chicken eating capability unavailable: {reason}")); + pub(crate) fn take_he_guidance_spawn_listener_request(&mut self) -> bool { + let requested = self.he_guidance_configured() && self.he_guidance_spawn_listener_available && !self.he_guidance_spawn_listener_requested; + self.he_guidance_spawn_listener_requested |= requested; + requested } - pub(crate) fn observe_chicken_use_target(&mut self, pawn_handle: i32, target_handle: i32, in_use: bool) { - let Some(player) = LivePlayer::resolve_pawn_owner(pawn_handle) else { - return; - }; - if LivePlayer::resolve(player.slot) != Some(player) || self.controllers.get(&player.slot) != Some(&player.controller_handle) { - return; - } - let Some(identity) = self - .players - .identity(player.slot) - .filter(|identity| identity.pawn_handle == pawn_handle as u32) - else { + pub(crate) fn he_guidance_spawn_listener_ready(&mut self) { + self.he_guidance_spawn_listener_ready = true; + if !self.he_guidance_probe_ready || !self.faults.enable_he_guidance() { return; - }; - if !in_use { - use_button_rising_edge(&mut self.chicken_use_buttons, identity, false); - return; - } - if !self.chicken_use_ready - || !self.chicken_ready - || !self.ordinary_chickens_enabled() - || !self.controller.enabled() - || !matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) - || !s2sdk::IsValidEntHandle(target_handle) - || s2sdk::GetEntityClassname(target_handle).as_str() != "chicken" - || !self.chicken_entities.owns(target_handle, self.controller.generation()) - { - return; - } - let Some(config) = self.controller.config().and_then(|config| config.chicken) else { - return; - }; - let Some(mode) = self.controller.current_mode() else { return }; - if !config.eating.enabled_for_mode(mode.chicken_eating) { - return; - } - let Some(task) = self.combat_task(player) else { return }; - let current_health = s2sdk::GetClientHealth(player.slot); - let Some(base_health) = self.chickens.base_health(task).ok() else { - return; - }; - // A selector may report no target before finding a chicken during the same press. - // Only a valid consumable target spends this press; releases are polled independently. - if self - .chicken_use_buttons - .get(&identity.slot) - .is_some_and(|(old, down)| *old == identity && *down) - || !self.chicken_entities.mark_consumed(target_handle, task.round) - { - return; - } - let now = f64::from(s2sdk::GetGameTime()); - let outcome = match self.chickens.consume(task, current_health, base_health, now, config, &mut self.rng) { - Ok(outcome) => outcome, - Err(_) => { - self.chicken_entities.release_consumed(target_handle, task.round); - return; - } - }; - use_button_rising_edge(&mut self.chicken_use_buttons, identity, true); - self.engine_actions.push(EngineAction::ChickenEat { - task, - player, - chicken: target_handle, - outcome, - }); - } - - pub(crate) fn finish_chicken_use(&mut self, round: RoundGeneration, chicken: i32) { - self.chicken_entities.remove_chicken(chicken, round); - self.restore_model_scale(chicken); - if self.chicken_entities.is_empty() { - crate::CHICKEN_DAMAGE_ACTIVE.store(false, std::sync::atomic::Ordering::Release); } - } - - fn release_chicken_use_buttons(&mut self) { - // The native target selector is not called on every released-input frame. - // Button state 0 is current down state; transition masks must not keep the latch held. - self.chicken_use_buttons.retain(|slot, (identity, _)| { - self.players.identity(*slot) == Some(*identity) - && LivePlayer::resolve(*slot).is_some_and(|player| player.pawn_handle as u32 == identity.pawn_handle) - && s2sdk::GetClientButtons(*slot, 0) & (1 << 5) != 0 - }); - } - - pub(crate) fn healthshot_hook_ready(&mut self) { - self.healthshot_hooks_ready = true; - } - - pub(crate) fn healthshot_hook_failure(&mut self, reason: impl Into) { - self.healthshot_hooks_ready = false; - self.healthshot_faulted = true; - let reason = reason.into(); - self.faults.exclude(Mechanism::Healthshot, reason.clone()); + self.capability_reasons + .retain(|reason| !reason.starts_with("he_guidance:[waiting for entity spawn listener registration]")); self.controller.set_capabilities(self.faults.capabilities()); - self.capability_reasons.push(format!("healthshot:[{reason}]")); - log(&format!("healthshot capability disabled: {reason}")); + log("HE guidance capability became available after the entity spawn listener was registered"); } - fn healthshot_active(&self) -> bool { - self.healthshot_hooks_ready - && !self.healthshot_faulted - && self.controller.enabled() - && self.controller.config().is_some_and(|config| config.healthshot.is_some()) - && self.faults.capabilities().healthshot + pub(crate) fn sync_he_guidance_spawn_epoch(&self) { + crate::publish_he_guidance_spawn_active(self.he_guidance_active()); } - fn sync_healthshot_override(&mut self) -> Result<(), Fault> { - let wanted = self.healthshot_active(); - if healthshot_override_settled(wanted, self.healthshot_override_active, self.healthshot_parameters.is_restored()) { - return Ok(()); - } - self.healthshot_parameters.set_healthshot_override(wanted)?; - self.healthshot_override_active = wanted; - if !wanted { - self.healthshot_purchases.clear(); - self.engine_actions - .retain(|action| !matches!(action, EngineAction::HealthshotPurchase { .. })); - } - Ok(()) + fn he_guidance_active(&self) -> bool { + self.he_guidance_spawn_listener_ready + && self.classic_round() + && active_combat_phase(self.controller.phase()) + && self.faults.capabilities().he_guidance + && self.controller.current_mode().is_some_and(|mode| mode.he_guidance.is_some()) } - pub(crate) fn reject_healthshot_use(&self, pawn_handle: i32, weapon_handle: i32) -> bool { - if !self.healthshot_active() || !self.healthshot_override_active { - return false; - } - let Some(player) = LivePlayer::resolve_pawn_owner(pawn_handle) else { - return true; - }; - if LivePlayer::resolve(player.slot) != Some(player) - || !s2sdk::IsValidEntHandle(weapon_handle) - || s2sdk::GetEntityClassname(weapon_handle).as_str() != "weapon_healthshot" - || !s2sdk::GetClientWeapons(player.slot).iter().any(|handle| *handle == weapon_handle) - { - return true; - } - let Some(task) = self.combat_task(player) else { return true }; - let Some(base_health) = self.chickens.base_health(task).ok() else { - return true; - }; - let Some(config) = self.controller.config().and_then(|config| config.healthshot) else { - return false; - }; - matches!( - funrounds_core::use_healthshot(config, s2sdk::GetClientHealth(player.slot), base_health), - funrounds_core::HealthshotOutcome::NotConsumed - ) + pub(crate) fn take_interaction_hook_requests(&mut self) -> (bool, bool) { + self.bind_pending_warmup_spawns(); + let healthshot = self.take_healthshot_hook_request(); + let chicken = self.wants_use_target_hook() + && !self.use_target_hook_requested + && s2sdk::GetGameTime() >= self.use_target_probe_retry_at + && self.use_target_probe_ready(); + self.use_target_hook_requested |= chicken; + (healthshot, chicken) } - pub(crate) fn queue_healthshot_use(&mut self, pawn_handle: i32, weapon_handle: i32) { - if !self.healthshot_active() || !self.healthshot_override_active { + fn bind_pending_warmup_spawns(&mut self) { + if !self.warmup_active || self.controller.phase() != Phase::Idle || !self.grapple_configured() { return; } - let Some(player) = LivePlayer::resolve_pawn_owner(pawn_handle) else { - return; - }; - if LivePlayer::resolve(player.slot) != Some(player) - || !s2sdk::IsValidEntHandle(weapon_handle) - || s2sdk::GetEntityClassname(weapon_handle).as_str() != "weapon_healthshot" - || !s2sdk::GetClientWeapons(player.slot).iter().any(|handle| *handle == weapon_handle) - { - return; - } - let Some(task) = self.combat_task(player) else { return }; - let Some(base_health) = self.chickens.base_health(task).ok() else { - return; - }; - let Some(config) = self.controller.config().and_then(|config| config.healthshot) else { - return; - }; - if matches!( - funrounds_core::use_healthshot(config, s2sdk::GetClientHealth(player.slot), base_health), - funrounds_core::HealthshotOutcome::Applied { .. } - ) { - self.engine_actions.push(EngineAction::HealthshotUse { - task, - player, - base_health, - config, - }); - } - } - fn request_healthshot(&mut self, slot: i32) -> Result { - if !self.healthshot_active() || !self.healthshot_override_active || !active_combat_phase(self.controller.phase()) { - return Err(self.text(slot, "healthshot.unavailable", &[])); - } - let player = LivePlayer::resolve(slot).ok_or(self.text(slot, "player.alive_required", &[]))?; - if !matches!(s2sdk::GetClientTeam(slot) as i32, 2 | 3) { - return Err(self.text(slot, "healthshot.team_required", &[])); - } - if Self::owns_healthshot(player) { - return Err(self.text(slot, "healthshot.already_owned", &[])); - } - let task = self.combat_task(player).ok_or(self.text(slot, "player.life_pending", &[]))?; - if self.healthshot_purchases.contains_key(&slot) { - return Err(self.text(slot, "healthshot.pending", &[])); + for slot in 0..s2sdk::GetMaxClients() { + let Some(expected) = self.players.pending_identity(slot) else { continue }; + let Some(player) = LivePlayer::resolve(slot) else { continue }; + if !self.players.validates_connection(expected) + || self.controllers.get(&slot) != Some(&player.controller_handle) + || player.pawn_controller() != Some(player.controller_handle) + { + continue; + } + + self.players.bind_spawn(expected, player.pawn_handle as u32); } - let price = self - .controller - .config() - .ok_or(self.text(slot, "config.unavailable", &[]))? - .prices - .healthshot_cash; - self.healthshot_purchases.insert(slot, task); - self.engine_actions.push(EngineAction::HealthshotPurchase { task, player, price }); - Ok(self.text(slot, "healthshot.request", &[("price", &price.to_string())])) } - fn owns_healthshot(player: LivePlayer) -> bool { - s2sdk::GetClientWeapons(player.slot) - .iter() - .copied() - .any(|handle| s2sdk::IsValidEntHandle(handle) && s2sdk::GetEntityClassname(handle).as_str() == "weapon_healthshot") + pub(crate) fn chicken_use_hook_ready(&mut self) { + self.use_target_hook_ready = true; + self.grapple_use_hook_ready(); } - pub(crate) fn healthshot_buyer_current(&self, task: PlayerTask, player: LivePlayer) -> bool { - self.healthshot_active() - && self.healthshot_override_active - && active_combat_phase(self.controller.phase()) - && self.healthshot_purchases.get(&player.slot) == Some(&task) - && self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) - && self.controllers.get(&player.slot) == Some(&player.controller_handle) - && LivePlayer::resolve(player.slot) == Some(player) + pub(crate) fn chicken_use_hook_failure(&mut self, reason: impl Into) { + self.use_target_hook_ready = false; + let reason = reason.into(); + if self.chicken_use_configured() { + self.capability_reasons.push(format!("chicken_eating:[{reason}]")); + log(&format!("chicken eating capability unavailable: {reason}")); + } + if self.grapple_configured() { + self.grapple_use_hook_failure(reason); + } } - pub(crate) fn finish_healthshot_purchase(&mut self, task: PlayerTask) { - if self.healthshot_purchases.get(&task.player.slot) == Some(&task) { - self.healthshot_purchases.remove(&task.player.slot); - } + pub(crate) fn chicken_use_hook_deferred(&mut self) { + self.use_target_hook_requested = false; + let now = s2sdk::GetGameTime(); + self.use_target_probe_retry_at = if now.is_finite() { now + 1.0 } else { 0.0 }; } pub fn on_game_thread(&self) -> bool { @@ -1158,13 +694,6 @@ impl Runtime { self.preferences = Some(preferences); } - pub fn headshots(&self) -> Headshots { - if self.controller.phase() == Phase::Idle { - return Headshots::Normal; - } - self.controller.current_mode().map_or(Headshots::Normal, |mode| mode.headshots) - } - pub fn projectile_damage(&mut self, damage: &mut crate::damage::Damage) -> Option<(f32, bool)> { if let Some(impact) = self.projectiles.attribute_synthetic_impact(damage) { return Some((1.0, impact.headshot)); @@ -1297,6 +826,26 @@ impl Runtime { self.effects_ready && self.controller.enabled() } + fn air_strafe_active(&self) -> bool { + self.classic_enabled() && active_combat_phase(self.controller.phase()) && self.controller.current_mode().is_some_and(|mode| mode.autostrafe) + } + + pub(crate) fn air_strafe_allowed(&self, slot: i32, pawn: i32, controller: i32) -> bool { + if !self.on_game_thread() || !self.air_strafe_active() { + return false; + } + let player = LivePlayer { + slot, + controller_handle: controller, + pawn_handle: pawn, + }; + let Some(task) = self.combat_task(player) else { return false }; + !self + .effects + .get(&slot) + .is_some_and(|effect| effect.identity == task.player && effect.round == task.round && effect.temporary_movement_owner().is_some()) + } + pub fn chat_commands_enabled(&self) -> bool { self.controller.enabled() } @@ -1367,54 +916,6 @@ impl Runtime { .status(self.controller.hostage_rescue_compat_enabled(), self.classic_round()) } - pub fn classic_damage_scale(&self, damage: &crate::damage::Damage, players: &game::DamagePlayers) -> Option { - if !self.classic_round() { - return Some(1.0); - } - let damage_type = damage.damage_type; - let game::DamagePlayers { victim, attacker } = *players; - let self_damage = victim.is_some() && victim == attacker; - let mode = self.controller.current_mode()?; - let self_damage_allowed = matches!(mode.self_damage, Some(SelfDamage::Native { amount }) if amount > 0.0) - || matches!(mode.self_damage, Some(SelfDamage::MissPenalty)) - && victim.is_some_and(|player| mode65_self_damage(damage, player.pawn_handle, s2sdk::GetClientHealth(player.slot))); - let attacker_health = if !mode.health_damage { - None - } else { - attacker - .filter(|player| { - LivePlayer::resolve(player.slot) == Some(*player) - && self.controllers.get(&player.slot) == Some(&player.controller_handle) - && self.effects.get(&player.slot).is_some_and(|effect| { - Some(effect.identity) == self.players.identity(player.slot) - && effect.identity.pawn_handle == player.pawn_handle as u32 - && !effect.has_pending_loadout() - }) - }) - .map(|player| (s2sdk::GetClientHealth(player.slot), self.effects[&player.slot].attributes.health)) - }; - let suicide_scale = if players.victim.is_some_and(|victim| self.suicides.active(victim)) { - 5.0 - } else { - 1.0 - }; - let common = suicide_scale - * mode - .health_curve - .damage_scale(attacker_health, self_damage, damage_type & 32 != 0, self_damage_allowed)?; - let weapon = (damage.weapon != -1 && s2sdk::IsValidEntHandle(damage.weapon)) - .then(|| s2sdk::GetEntityClassname(damage.weapon).to_string()) - .or_else(|| damage.weapon_class.clone()); - Some( - common - * funrounds_core::weapon_damage_scale( - mode, - weapon.as_deref().map(crate::damage::weapon_scale_class), - attacker.is_some() && !self_damage && damage_type & 32 == 0, - ), - ) - } - fn combat_task(&self, player: LivePlayer) -> Option { let identity = self.players.identity(player.slot)?; (identity.pawn_handle == player.pawn_handle as u32 && self.controllers.get(&player.slot) == Some(&player.controller_handle)).then_some( @@ -1426,7 +927,9 @@ impl Runtime { } fn clear_chicken_life(&mut self, identity: PlayerIdentity) { - self.clear_pending_chicken_blast_for_life(identity); + self.clear_region_player_life(identity.slot); + self.clear_composed_life(identity); + self.ordinary_chickens.clear_pending_chicken_blast_for_life(identity); self.chickens.clear_life(PlayerTask { round: self.controller.generation(), player: identity, @@ -1437,128 +940,6 @@ impl Runtime { }); } - fn afterburn_settings(&self) -> Option { - (self.classic_enabled() && active_combat_phase(self.controller.phase()) && self.faults.capabilities().afterburn) - .then(|| self.controller.current_mode().and_then(|mode| mode.afterburn)) - .flatten() - } - - pub(crate) fn afterburn_action_valid(&self, task: PlayerTask, player: LivePlayer) -> bool { - self.afterburn_settings().is_some() - && self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) - && LivePlayer::resolve(player.slot) == Some(player) - && self.controllers.get(&player.slot) == Some(&player.controller_handle) - && self.afterburns.entries().iter().any(|(current, current_player, deadline)| { - *current == task && *current_player == player && *deadline > f64::from(s2sdk::GetGameTime()) - }) - } - - pub(crate) fn begin_afterburn_ignite(&mut self, task: PlayerTask, player: LivePlayer, now: f64) -> Option { - self.afterburn_action_valid(task, player) - .then(|| self.afterburns.begin_ignite(task, player, now)) - .flatten() - } - - pub(crate) fn afterburn_attachment_seen(&mut self, task: PlayerTask, player: LivePlayer, now: f64, attached: Option) { - let _ = self.afterburns.observe_attachment(task, player, now, attached); - self.afterburn_cleanup.extend(self.afterburns.take_removals()); - } - - pub(crate) fn record_afterburn_flame(&mut self, task: PlayerTask, player: LivePlayer, flame: i32, now: f64) -> bool { - self.afterburn_action_valid(task, player) && self.afterburns.record_flame(task, player, flame, now) - } - - pub(crate) fn afterburn_ignition_failed(&mut self, message: impl Into) { - self.handle_fault(Fault::mechanism(Mechanism::Afterburn, message)); - } - - pub(crate) fn take_afterburn_cleanup(&mut self) -> Vec { - self.afterburn_cleanup.extend(self.afterburns.take_removals()); - std::mem::take(&mut self.afterburn_cleanup) - } - - pub(crate) fn queue_afterburn_ground_tick(&mut self, damage: &crate::damage::Damage, players: &game::DamagePlayers) { - if damage.inflictor == -1 || !s2sdk::IsValidEntHandle(damage.inflictor) { - return; - } - let (Some(settings), Some(player)) = (self.afterburn_settings(), players.victim) else { - return; - }; - let Some(task) = self.combat_task(player) else { return }; - let now = f64::from(s2sdk::GetGameTime()); - if crate::afterburn::genuine_ground_burn( - damage.skip_plugin_rules, - damage.damage_type, - s2sdk::GetEntityClassname(damage.inflictor).as_str(), - ) && self.afterburns.refresh(task, player, now, settings.duration_seconds) - && self.afterburns.queue_ignite(task, player) - { - self.engine_actions.push(EngineAction::AfterburnIgnite { task, player }); - } - } - - pub(crate) fn afterburn_flame_damage(&self, damage: &crate::damage::Damage, players: &game::DamagePlayers) -> Option { - if damage.amount <= 0.0 - || !damage.amount.is_finite() - || damage.inflictor == -1 - || !s2sdk::IsValidEntHandle(damage.inflictor) - || !crate::afterburn::flame_tick_damage( - damage.skip_plugin_rules, - damage.damage_type, - s2sdk::GetEntityClassname(damage.inflictor).as_str(), - ) - { - return None; - } - let (Some(settings), Some(player)) = (self.afterburn_settings(), players.victim) else { - return None; - }; - let task = self.combat_task(player)?; - self.afterburns - .owns_flame(task, player, damage.inflictor) - .then(|| crate::afterburn::flame_attached_to(player, damage.inflictor)) - .filter(|attached| *attached) - .map(|_| settings.tick_damage(s2sdk::GetClientHealth(player.slot))) - } - - fn update_afterburns(&mut self, now: f64) { - self.afterburns.clear_round(self.controller.generation()); - let entries = self.afterburns.entries(); - for (task, player, _) in entries { - if self.afterburn_settings().is_none() - || !self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) - || LivePlayer::resolve(player.slot) != Some(player) - || self.controllers.get(&player.slot) != Some(&player.controller_handle) - { - self.afterburns.clear_life(task); - continue; - } - let attached = crate::afterburn::attached_effect(player); - if self.afterburns.observe_attachment(task, player, now, attached) { - self.engine_actions.push(EngineAction::AfterburnIgnite { task, player }); - } - } - self.afterburn_cleanup.extend(self.afterburns.take_removals()); - } - - fn update_chicken_digestion(&mut self, now: f64) { - self.chickens.retain_round(self.controller.generation()); - let Some(config) = self.controller.config().and_then(|config| config.chicken) else { - return; - }; - if !now.is_finite() || now < 0.0 { - return; - } - for slot in 0..s2sdk::GetMaxClients() { - let Some(player) = LivePlayer::resolve(slot) else { continue }; - let Some(task) = self.combat_task(player) else { continue }; - let digestion_needed = !config.eating.enabled || matches!(self.chickens.undigested(task), Ok(count) if count > 0); - if digestion_needed { - let _ = self.chickens.digest_due(task, now, config); - } - } - } - pub fn take_equipment_effect(&mut self, action: &EngineAction) -> Result, Fault> { if !self.action_valid(action) { return Ok(None); @@ -1592,6 +973,7 @@ impl Runtime { } let attributes = self .combat + .lives .get(&player.slot) .filter(|(life_task, _)| life_task == task) .map(|(_, life)| life.attributes()) @@ -1762,269 +1144,6 @@ impl Runtime { } } - pub fn combat_protected(&self, players: &game::DamagePlayers) -> bool { - players.victim.and_then(|player| self.combat_task(player)).is_some_and(|task| { - self.combat - .get(&task.player.slot) - .is_some_and(|(expected, life)| *expected == task && life.protected(s2sdk::GetGameTime())) - }) - } - - pub fn record_native_player_hit(&mut self, damage: &crate::damage::Damage, players: &game::DamagePlayers) { - // The native classifier covers bullets, buckshot and Zeus shock damage. - if matches!(damage.weapon_kind, 1 | 3) - && !damage.skip_plugin_rules - && damage.amount.is_finite() - && damage.amount > 0.0 - && let (Some(victim), Some(attacker)) = (players.victim, players.attacker) - && victim != attacker - && self.combat_task(victim).is_some() - { - self.mark_native_shot_hit(attacker, damage); - } - } - - pub fn suppress_hit_native_self_damage(&mut self, damage: &crate::damage::Damage, players: &game::DamagePlayers) -> bool { - let (Some(victim), Some(attacker)) = (players.victim, players.attacker) else { - return false; - }; - if victim != attacker - || !native_self_damage_signature(damage, victim) - || !active_combat_phase(self.controller.phase()) - || !self - .controller - .current_mode() - .is_some_and(|mode| matches!(mode.self_damage, Some(SelfDamage::Native { amount }) if amount > 0.0)) - { - return false; - } - let Some(task) = self.combat_task(victim) else { return false }; - if self.players.identity(victim.slot) != Some(task.player) || LivePlayer::resolve(victim.slot) != Some(victim) { - return false; - } - let tick = s2sdk::GetGameTickCount(); - let matches = self - .native_self_damage_shots - .get(&victim.slot) - .is_some_and(|shot| shot.task == task && shot.player == victim && shot.tick == tick); - if !matches { - return false; - } - self.native_self_damage_shots - .remove(&victim.slot) - .is_some_and(|shot| shot.player_hit && weapon_identity_is_current(victim, &shot.weapon)) - } - - fn mark_native_shot_hit(&mut self, player: LivePlayer, damage: &crate::damage::Damage) { - let Some(task) = self.combat_task(player) else { return }; - let tick = s2sdk::GetGameTickCount(); - let Some(shot) = self.native_self_damage_shots.get_mut(&player.slot) else { - return; - }; - if weapon_identity_is_current(player, &shot.weapon) { - shot.mark_player_hit(task, player, tick, damage); - } - } - - pub fn combat_damage( - &mut self, - damage: &crate::damage::Damage, - players: &game::DamagePlayers, - common_scale: f32, - allow_reflection: bool, - ) -> bool { - let Some(victim) = players.victim else { return false }; - let Some(task) = self.combat_task(victim) else { return false }; - let Some((expected, life)) = self.combat.get_mut(&victim.slot).filter(|(expected, _)| *expected == task) else { - return false; - }; - let Some(mode) = self.controller.current_mode() else { return false }; - if players.attacker.is_some_and(|attacker| s2sdk::GetClientTeam(attacker.slot) as i32 == 1) { - return true; - } - let eligible = players.attacker.is_some_and(|attacker| attacker != victim) && damage.damage_type & 32 == 0; - let allowed_self = - players.attacker == Some(victim) && self_damage_allowed(mode, damage, victim.pawn_handle, s2sdk::GetClientHealth(victim.slot)); - let knife = damage.weapon_kind == 2 - || damage - .weapon_class - .as_deref() - .map(crate::damage::weapon_scale_class) - .is_some_and(|class| matches!(class, "weapon_knife" | "weapon_knife_t")) - || damage.weapon != -1 - && s2sdk::IsValidEntHandle(damage.weapon) - && matches!(s2sdk::GetEntityClassname(damage.weapon).as_str(), "weapon_knife" | "weapon_knife_t"); - let incoming = damage.amount * common_scale; - if !incoming.is_finite() { - return true; - } - let (blocked, reflected) = funrounds_core::combat_hit(mode, life, eligible, allowed_self, knife, incoming); - let suppress_lifesteal = mode.lifesteal; - let source = *expected; - let hud = life.armor_hud(); - // Record the HP path, not the post-hit shield: the breaking hit is fully absorbed. - if numeric_self_damage_enters_health(allowed_self, blocked, incoming) && !self.low_health_finishes.contains(&task) { - self.low_health_finishes.push(task); - } - if let Some(armor) = hud - && let Err(error) = sync_shield_hud(victim, armor) - { - self.handle_fault(error); - return true; - } - if let Some(amount) = reflected.filter(|_| allow_reflection) - && let Some(attacker) = players.attacker - && let Some(target) = self.combat_task(attacker) - { - self.reflections.push(crate::damage::Reflection { - target, - source, - target_live: attacker, - source_live: victim, - inflictor: damage.inflictor, - weapon: damage.weapon, - weapon_class: damage.weapon_class.clone(), - amount, - damage_type: damage.damage_type, - tick: s2sdk::GetGameTickCount(), - suppress_lifesteal, - }); - } - blocked - } - - pub fn prepare_delayed_damage_with_heal( - &self, - damage: &crate::damage::Damage, - players: &game::DamagePlayers, - amount: f32, - headshot: bool, - random_heal: i32, - ) -> Option { - let mode = self.controller.current_mode()?; - if !active_combat_phase(self.controller.phase()) || !mode.delayed_damage { - return None; - } - let (target, source) = (players.victim?, players.attacker?); - if s2sdk::GetClientTeam(source.slot) as i32 == 1 - || !crate::damage::delayed_damage_eligible(target.slot, source.slot, damage.damage_type, amount) - { - return None; - } - let target_task = self.combat_task(target)?; - if self.controllers.get(&source.slot) != Some(&source.controller_handle) { - return None; - } - let source_task = self - .players - .damage_source_task(source.slot, self.controller.generation(), source.pawn_handle as u32)?; - let now = s2sdk::GetGameTime(); - if !now.is_finite() { - return None; - } - let mut hit = crate::damage::DelayedDamage::new( - target_task, - source_task, - target, - source, - damage, - crate::damage::DamageOutcome { amount, headshot }, - now, - ); - hit.set_random_heal(random_heal); - Some(hit) - } - - pub fn defer_damage(&mut self, hit: crate::damage::DelayedDamage) { - self.delayed_damage.push(hit); - } - - pub fn random_damage_roll( - &mut self, - damage: &crate::damage::Damage, - players: &game::DamagePlayers, - amount: f32, - ) -> Option { - let mode = self.controller.current_mode()?; - if !active_combat_phase(self.controller.phase()) || !mode.random_damage || damage.damage_type & crate::damage::DMG_FALL != 0 { - return None; - } - let (victim, attacker) = (players.victim?, players.attacker?); - if victim == attacker - || self.combat_task(victim).is_none() - || self.combat_task(attacker).is_none() - || crate::damage::current_damage_frame_token().filter(|token| *token != 0).is_none() - { - return None; - } - funrounds_core::random_damage(amount, s2sdk::GetClientHealth(victim.slot), &mut self.rng) - } - - pub fn queue_random_heal(&mut self, players: &game::DamagePlayers, amount: i32) -> Result<(), Fault> { - if amount <= 0 { - return Ok(()); - } - let (Some(target_live), Some(source_live)) = (players.victim, players.attacker) else { - return Ok(()); - }; - let (Some(target), Some(source)) = (self.combat_task(target_live), self.combat_task(source_live)) else { - return Ok(()); - }; - let Some(frame_token) = crate::damage::current_damage_frame_token().filter(|token| *token != 0) else { - return Err(Fault::mechanism( - Mechanism::RandomDamage, - "player damage frame token unavailable before random heal settlement", - )); - }; - self.random_heals.push(RandomHealReceipt { - target, - source, - target_live, - source_live, - frame_token, - amount, - }); - Ok(()) - } - - fn settle_random_heal(&mut self, victim: i32, attacker: i32, event: usize) -> Option { - if s2sdk::GetEventInt(event, &Str::from_str("dmg_health")) <= 0 { - return None; - } - let receipt = if let Some(receipt) = crate::damage::internal_random_heal_hurt(victim, attacker) { - Some(receipt) - } else { - let token = crate::damage::current_damage_frame_token().filter(|token| *token != 0)?; - let index = self - .random_heals - .iter() - .position(|receipt| receipt.target.player.slot == victim && receipt.source.player.slot == attacker && receipt.frame_token == token)?; - Some(self.random_heals.remove(index)) - }; - let receipt = receipt?; - if !self.controller.current_mode().is_some_and(|mode| mode.random_damage) - || receipt.amount <= 0 - || receipt.target.round != self.controller.generation() - || receipt.source.round != self.controller.generation() - || !self - .players - .validates_damage_source(receipt.target, self.controller.generation(), receipt.target_live.pawn_handle as u32) - || !self - .players - .validates(receipt.source, self.controller.generation(), receipt.source_live.pawn_handle as u32) - || LivePlayer::resolve_present(receipt.target_live.slot) != Some(receipt.target_live) - || LivePlayer::resolve(receipt.source_live.slot) != Some(receipt.source_live) - || crate::damage::current_damage_frame_token() != Some(receipt.frame_token) - { - return None; - } - if let Err(error) = Effect::random_damage_heal(receipt.source_live, receipt.amount) { - self.handle_fault(Fault::mechanism(Mechanism::RandomDamage, error)); - return None; - } - Some(attacker) - } - fn refresh_translucent(&mut self) { let generation = self.controller.generation(); let mut failure = None; @@ -2096,44 +1215,6 @@ impl Runtime { } } - fn refresh_combat(&mut self) { - if self.controller.current_mode().is_none() { - return; - } - let now = s2sdk::GetGameTime(); - let mut failure = None; - for (task, life) in self.combat.values_mut() { - let Some(player) = LivePlayer::resolve(task.player.slot) else { continue }; - if !self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) - || !self - .effects - .get(&player.slot) - .is_some_and(|effect| effect.identity == task.player && !effect.has_pending_loadout()) - { - continue; - } - let health = s2sdk::GetClientHealth(player.slot); - if let Some(next) = life.recharge(now, health) - && next != health - { - s2sdk::SetClientHealth(player.slot, next); - if s2sdk::GetClientHealth(player.slot) != next { - failure = Some(Fault::mechanism(Mechanism::EnergyShield, "shield health conversion write failed")); - break; - } - } - if let Some(armor) = life.armor_hud() - && let Err(error) = sync_shield_hud(player, armor) - { - failure = Some(error); - break; - } - } - if let Some(error) = failure { - self.handle_fault(error); - } - } - fn refresh_classic(&mut self, slots: Option<&[i32]>) { if !self.classic_round() || !active_combat_phase(self.controller.phase()) { return; @@ -2257,6 +1338,80 @@ impl Runtime { } } + fn wall_hang_active(&self) -> bool { + active_combat_phase(self.controller.phase()) + && self.faults.capabilities().wall_hang + && self.controller.current_mode().is_some_and(|mode| mode.wall_hang) + } + + fn refresh_movement(&mut self) { + let enabled = self.wall_hang_active(); + let movement_requested = enabled || self.grapple_mode_active(); + let generation = self.controller.generation(); + let mut failure = None; + for effect in self.effects.values_mut() { + let slot = effect.identity.slot; + if effect.has_pending_loadout() || Some(effect.identity) != self.players.identity(slot) { + continue; + } + let Some(player) = LivePlayer::resolve(slot) else { continue }; + if self.controllers.get(&slot) != Some(&player.controller_handle) || effect.identity.pawn_handle != player.pawn_handle as u32 { + continue; + } + let result = if self.suicides.active(player) && (movement_requested || effect.temporary_movement_owner().is_some()) { + effect.interrupt_temporary_movement() + } else { + effect.update_wall_hang(enabled) + }; + if let Err(error) = result + && error.scope != Scope::Cancelled + { + failure = Some(error.context(format!("wall hang slot={slot} round={generation:?}"))); + break; + } + } + if let Some(error) = failure { + self.handle_fault(error); + } + } + + fn refresh_wall_hang_capability(&mut self) { + if self.faults.capabilities().wall_hang || self.faults.recovery == Recovery::Stopped { + return; + } + let mut reasons = Vec::new(); + if !wall_hang_capability(&mut reasons) || !self.faults.enable_wall_hang() { + return; + } + self.capability_reasons.retain(|reason| !reason.starts_with("wall_hang:")); + self.controller.set_capabilities(self.faults.capabilities()); + log("wall_hang capability became available after the map movement receiver initialized"); + } + + pub(crate) fn interrupt_movement_for_impulse(&mut self, player: LivePlayer) -> Result<(), Fault> { + if let Some(identity) = self + .players + .identity(player.slot) + .filter(|identity| identity.pawn_handle == player.pawn_handle as u32) + { + self.cancel_grapple(identity, grapple::StopReason::Impulse); + } + let movement_requested = self.wall_hang_active() || self.grapple_mode_active(); + let Some(effect) = self.effects.get_mut(&player.slot).filter(|effect| { + !effect.has_pending_loadout() + && effect.identity.pawn_handle == player.pawn_handle as u32 + && Some(effect.identity) == self.players.identity(player.slot) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + && effect.round == self.controller.generation() + }) else { + return Ok(()); + }; + if effect.temporary_movement_owner().is_none() && !movement_requested { + return Ok(()); + } + effect.interrupt_temporary_movement() + } + fn send_welcomes(&mut self) { if !self.classic_enabled() { self.welcomes.clear(); @@ -2283,6 +1438,14 @@ impl Runtime { pub fn action_valid(&self, action: &EngineAction) -> bool { match action { + EngineAction::Composed(action) => self.composed_action_valid(action), + EngineAction::Shooting(action) => self.shooting_action_valid(action), + EngineAction::Proximity(action) => self.proximity_action_valid(*action), + EngineAction::HeGuidance(action) => self.he_guidance_action_valid(*action), + EngineAction::HeGuidanceFuseRestore(action) => self.he_guidance_fuse_restore_action_valid(*action), + EngineAction::Grapple(action) => self.grapple_action_valid(action), + EngineAction::Shockwave(action) => self.shockwave_action_valid(*action), + EngineAction::Teamkill(action) => self.teamkill_action_valid(*action), EngineAction::Rollback(task, player) => { self.players.identity(player.slot) == Some(task.player) && LivePlayer::resolve(player.slot) == Some(*player) @@ -2315,89 +1478,8 @@ impl Runtime { && LivePlayer::resolve(player.slot) == Some(*player) && self.controllers.get(&player.slot) == Some(&player.controller_handle) } - EngineAction::GrantC4(task, player) => { - self.classic_round() - && !self - .effects - .get(&player.slot) - .is_some_and(|effect| effect.identity == task.player && effect.round == task.round && effect.has_pending_loadout()) - && self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) - && LivePlayer::resolve(player.slot) == Some(*player) - && self.controllers.get(&player.slot) == Some(&player.controller_handle) - } - EngineAction::RemoveC4(task, player, _) => { - self.classic_round() - && self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) - && LivePlayer::resolve(player.slot) == Some(*player) - && self.controllers.get(&player.slot) == Some(&player.controller_handle) - } - EngineAction::Suicide(action) => match action { - crate::suicide::Action::Purchase { start, .. } => { - self.c4_purchase_enabled(*start) - && self - .players - .validates(action.task(), self.controller.generation(), action.player().pawn_handle as u32) - && LivePlayer::resolve(action.player().slot) == Some(action.player()) - } - crate::suicide::Action::Finish { - after_round_end: true, - task, - player, - .. - } => round_end_finish_valid( - self.classic_enabled(), - self.controller.phase(), - *task, - *player, - self.players.identity(player.slot), - LivePlayer::resolve(player.slot), - ), - _ => { - self.suicide_enabled() - && self - .players - .validates(action.task(), self.controller.generation(), action.player().pawn_handle as u32) - && LivePlayer::resolve(action.player().slot) == Some(action.player()) - } - }, - EngineAction::DelayedDamage(hit) => { - self.classic_round() - && active_combat_phase(self.controller.phase()) - && self.controller.current_mode().is_some_and(|mode| { - mode.delayed_damage - && delayed_damage_protection_valid( - mode.spawn_protection || mode.kill_protection, - hit.target, - self.combat - .get(&hit.target.player.slot) - .map(|(task, life)| (*task, life.protected(s2sdk::GetGameTime()))), - ) - }) - && hit.validates_players( - self.controller.generation(), - &self.players, - LivePlayer::resolve(hit.target.player.slot), - LivePlayer::resolve_present(hit.source.player.slot), - ) - && hit.native_handles(s2sdk::IsValidEntHandle).is_some() - } - EngineAction::Reflection(hit) => { - self.classic_round() - && self.controller.current_mode().is_some_and(|mode| mode.reflect_damage.is_some()) - && LivePlayer::resolve(hit.target.player.slot) == Some(hit.target_live) - && LivePlayer::resolve_present(hit.source.player.slot) == Some(hit.source_live) - && self - .players - .validates(hit.target, self.controller.generation(), hit.target_live.pawn_handle as u32) - && self - .players - .validates_damage_source(hit.source, self.controller.generation(), hit.source_live.pawn_handle as u32) - && self - .combat - .get(&hit.target.player.slot) - .is_some_and(|(task, life)| *task == hit.target && !life.protected(s2sdk::GetGameTime())) - && hit.native_handles(s2sdk::IsValidEntHandle).is_some() - } + EngineAction::Suicide(action) => self.suicide_action_current(action), + EngineAction::Combat(action) => self.combat_action_current(action), EngineAction::CenterDisplay { generation, .. } => { center_display_action_valid(*generation == self.controller.generation(), self.controller.phase(), self.effects_ready) } @@ -2423,62 +1505,13 @@ impl Runtime { && self.controllers.get(&action.player.slot) == Some(&action.player.controller_handle) && LivePlayer::resolve(action.player.slot) == Some(action.player) && crate::touch::owns_rescue_zone(action.trigger) - && s2sdk::GetClientTeam(action.player.slot) as i32 >= 2 - && s2sdk::GetClientTeam(action.player.slot) as i32 <= 3 + && matches!(s2sdk::GetClientTeam(action.player.slot) as i32, 2 | 3) && crate::compat::hostage_rescue::eligible_hostage(action.trigger, action.player) == Some(action.hostage) } EngineAction::Bomb(action) => self.bombs.action_valid(*action, self.controller.generation(), &self.players), - EngineAction::ChickenSpawn { round, .. } => { - self.chicken_ready - && self.ordinary_chickens_enabled() - && self.controller.generation() == *round - && matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) - } - EngineAction::ChickenBlast { round, chicken, .. } => { - self.chicken_ready - && self.ordinary_chickens_enabled() - && self.controller.generation() == *round - && matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) - && self.chicken_entities.owns(*chicken, *round) - } - EngineAction::ChickenRemove(_) => true, - EngineAction::SuicideFeedbackRemove(_) => true, - EngineAction::AfterburnIgnite { task, player } => self.afterburn_action_valid(*task, *player), - EngineAction::AfterburnRemove(_) => true, - EngineAction::ChickenPurchase { task, player, .. } => { - self.chicken_ready - && self.ordinary_chickens_enabled() - && self.classic_enabled() - && active_combat_phase(self.controller.phase()) - && self.chicken_purchases.get(&task.player.slot) == Some(task) - && self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) - && LivePlayer::resolve(player.slot) == Some(*player) - && self.controllers.get(&player.slot) == Some(&player.controller_handle) - } - EngineAction::ChickenEat { task, player, chicken, .. } => { - self.chicken_use_ready - && self.chicken_ready - && self.ordinary_chickens_enabled() - && self.controller.enabled() - && matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) - && self.controller.current_mode().is_some_and(|mode| { - self.controller - .config() - .and_then(|config| config.chicken) - .is_some_and(|config| config.eating.enabled_for_mode(mode.chicken_eating)) - }) - && self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) - && LivePlayer::resolve(player.slot) == Some(*player) - && self.controllers.get(&player.slot) == Some(&player.controller_handle) - && self.chicken_entities.owns(*chicken, task.round) - } - EngineAction::HealthshotUse { task, player, .. } => { - self.healthshot_active() - && self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) - && LivePlayer::resolve(player.slot) == Some(*player) - && self.controllers.get(&player.slot) == Some(&player.controller_handle) - } - EngineAction::HealthshotPurchase { task, player, .. } => self.healthshot_buyer_current(*task, *player) && !Self::owns_healthshot(*player), + EngineAction::Chicken(action) => self.chickens_action_current(action), + EngineAction::Afterburn(action) => self.afterburn_action_current(action), + EngineAction::Healthshot(action) => self.healthshot_action_current(action), EngineAction::Equipment(action) => { self.refills.current(*action) && match action { @@ -2500,73 +1533,13 @@ impl Runtime { } } EngineAction::ProjectileImpact(_) => true, - EngineAction::Respawn(task, player, team) => { - respawn_window_open( - self.controller.phase(), - self.team_match.as_ref().map(|game| game.remaining(s2sdk::GetGameTime())), - ) && self.players.validates_respawn(*task, self.controller.generation()) - && respawn_target_valid( - *player, - LivePlayer::resolve_present(player.slot), - *team, - s2sdk::GetClientTeam(player.slot) as i32, - LivePlayer::resolve(player.slot).is_some(), - ) - } - EngineAction::RoundRespawn(task, player, team) => { - round_respawn_target_valid( - self.controller.current_mode().is_some_and(|mode| mode.round_respawn == RoundRespawn::All), - self.controller.phase(), - *player, - LivePlayer::resolve_present(task.player.slot), - *team, - s2sdk::GetClientTeam(task.player.slot) as i32, - ) && round_respawn_task_valid(&self.players, *task, self.controller.generation(), *player) - && respawn_window_open( - self.controller.phase(), - self.team_match.as_ref().map(|game| game.remaining(s2sdk::GetGameTime())), - ) - } - EngineAction::LowHealthFinish(task, player, _) => { - self.controller.phase() != Phase::Idle - && self.controller.current_mode().is_some_and(|mode| mode.self_damage_finish_enabled()) - && self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) - && LivePlayer::resolve(player.slot) == Some(*player) - && funrounds_core::low_health_finish(s2sdk::GetClientHealth(player.slot)) - } + EngineAction::Respawn(action) => self.respawn_action_current(action), EngineAction::EndRound(round, _) => { self.controller.phase() == Phase::Running && self.controller.generation() == *round && self.team_match.is_some() } } } - pub fn defer_pending_loadout_c4_grant(&mut self, task: PlayerTask, player: LivePlayer) -> bool { - let pending = self.effects.get(&player.slot).is_some_and(|effect| { - effect.identity == task.player - && effect.round == task.round - && effect.has_pending_loadout() - && effect - .pending_loadout_confirmation() - .is_some_and(|pending| pending.team == s2sdk::GetClientTeam(player.slot) as i32) - }); - if !pending - || !self.classic_round() - || !self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) - || LivePlayer::resolve(player.slot) != Some(player) - || self.controllers.get(&player.slot) != Some(&player.controller_handle) - { - return false; - } - if !self - .engine_actions - .iter() - .any(|queued| matches!(queued, EngineAction::GrantC4(queued_task, queued_player) if *queued_task == task && *queued_player == player)) - { - self.engine_actions.push(EngineAction::GrantC4(task, player)); - } - true - } - pub fn cancel_bomb_action(&mut self, action: crate::bombs::Action) { self.bombs.action_cancelled(action); } @@ -2618,699 +1591,121 @@ impl Runtime { self.handle_fault(error); } self.restore_completed_native_bomb_scales(); - } - - pub fn prepare_carrier_disconnect(&mut self, slot: i32) -> Option { - let player = LivePlayer::resolve_present(slot)?; - // Death retires the effect life, but cleanup must still release that connection's native pawn. - self.players.connection_identity(slot)?; - if self.controllers.get(&slot) != Some(&player.controller_handle) { - return None; - } - self.bombs.prepare_carrier_disconnect(self.controller.generation(), player) - } - - pub fn take_bomb_actions(&mut self) -> Vec { - self.bombs.take_actions() - } - - pub fn take_prestart_context(&mut self) -> Option<(i32, bool)> { - self.prestart_context.take() - } - - pub fn finish_round_prestart(&mut self, (tick, warmup): (i32, bool)) { - self.bombs.refresh_prestart_retirements(); - self.bombs.finish_round_prestart_cleanup(); - if warmup && self.controller.phase() == Phase::Warmup { - self.cleanup_effects(false); - self.restore_team_names(); - self.controller.stop_warmup(); - self.round = None; - self.prestarted_round = None; - self.warmup_activation_pending = self.warmup_active; - } - self.finish_round_transition_recovery(); - if tick < 0 || warmup { - self.prestarted_round = None; - return; - } - let key = self.controller.round_key(tick as u64); - let ready_for_prestart_selection = self.effects_ready - || (self.faults.recovery == Recovery::Ready - && self.cleanup_complete_for_round_transition_without_bombs() - && self.bombs.prestart_removals_ready()); - if self.select_round(key, warmup, ready_for_prestart_selection) { - self.prestarted_round = Some(key); - if let Err(error) = self.parameters.apply_prestart_purchase(self.controller.current_mode()) { - self.handle_fault(error); - } - } - } - - fn confirm_prestarted_round_reset(&mut self) -> bool { - self.bombs.confirm_prestart_removals_after_round_reset(); - self.effects_ready = self.faults.recovery == Recovery::Ready - && self.cleanup_complete_for_round_transition_except_pending_and_prestart_parameters_and_bombs() - && self.pending_prestarted_loadouts_are_current() - && self.bombs.is_clean(); - self.effects_ready - } - - pub fn take_bomb_explosion(&mut self) -> Option { - self.bombs.take_explosion(self.controller.generation()) - } - - fn update_duck_speed(&mut self) { - if !self.controller.enabled() { - return; - } - let players = (0..s2sdk::GetMaxClients()) - .filter_map(|slot| { - let player = LivePlayer::resolve_present(slot)?; - duck_speed_update_candidate(player, LivePlayer::resolve(slot), s2sdk::GetClientTeam(slot) as i32).map(|speed| (player, speed)) - }) - .collect::>(); - let current_handles = players - .iter() - .map(|(player, _)| player.pawn_handle) - .collect::>(); - for (player, current) in players { - if let Some(value) = update_owned_minimum(&mut self.duck_speed, player.pawn_handle, current, 8.0) - && !set_duck_speed_for_handle(player.pawn_handle, value) - { - log(&format!("failed to set crouch speed for pawn {}", player.pawn_handle)); - } - } - let stale = self - .duck_speed - .keys() - .copied() - .filter(|handle| !current_handles.contains(handle)) - .collect::>(); - for handle in stale { - let Some(owner) = self.duck_speed.get(&handle).copied() else { continue }; - if release_duck_speed(handle, owner) { - self.duck_speed.remove(&handle); - } - } - } - - fn restore_duck_speed(&mut self) { - let entries = self.duck_speed.iter().map(|(handle, owner)| (*handle, *owner)).collect::>(); - for (handle, owner) in entries { - if release_duck_speed(handle, owner) { - self.duck_speed.remove(&handle); - } - } - } - - fn weapon_inventory_player_is_current(&self, player: LivePlayer) -> bool { - let live_identity_matches = self - .players - .identity(player.slot) - .is_some_and(|identity| identity.pawn_handle == player.pawn_handle as u32) - || self.weapon_inventory.get(&player.slot).is_some_and(|previous| { - previous.player == player - && self.players.validates_damage_source( - PlayerTask { - round: self.controller.generation(), - player: previous.identity, - }, - self.controller.generation(), - player.pawn_handle as u32, - ) - }); - live_identity_matches - && LivePlayer::resolve_present(player.slot) == Some(player) - && player.pawn_controller() == Some(player.controller_handle) - } - - fn weapon_services_for_inventory(&self, player: LivePlayer) -> Option { - if !self.weapon_inventory_player_is_current(player) { - return None; - } - let class = Str::from_str("CBasePlayerPawn"); - let field = Str::from_str("m_pWeaponServices"); - if s2sdk::GetSchemaOffset(&class, &field) < 0 { - return None; - } - let pawn = s2sdk::EntHandleToEntPointer(player.pawn_handle); - if pawn == 0 || s2sdk::EntPointerToEntHandle(pawn) != player.pawn_handle { - return None; - } - let services = s2sdk::GetEntSchema2(pawn, &class, &field, 0) as usize; - (services != 0 && self.weapon_inventory_player_is_current(player)).then_some(services) - } - - fn read_client_weapon_inventory(&self, player: LivePlayer) -> Option> { - let services = self.weapon_services_for_inventory(player)?; - let weapons = s2sdk::GetClientWeapons(player.slot).iter().copied().collect(); - (self.weapon_services_for_inventory(player) == Some(services)).then_some(weapons) - } - - fn refresh_weapon_inventory(&mut self) { - let mut inventories = HashMap::new(); - for slot in 0..s2sdk::GetMaxClients() { - let Some(player) = LivePlayer::resolve_present(slot) else { continue }; - if !self.weapon_inventory_player_is_current(player) { - continue; - } - let Some(weapons) = self.read_client_weapon_inventory(player) else { - // A live pawn without readable weapon services has no inventory - // observation. Keep only its matching previous snapshot so an - // unready tick cannot be mistaken for a genuine empty inventory. - if let Some(previous) = self.weapon_inventory.get(&slot).filter(|previous| previous.player == player).cloned() { - inventories.insert(slot, previous); - } - continue; - }; - let weapons = weapons - .iter() - .filter(|handle| s2sdk::IsValidEntHandle(**handle) && s2sdk::GetEntityOwner(**handle) == player.pawn_handle) - .copied() - .map(|handle| (handle, s2sdk::GetEntityClassname(handle).to_string())) - .collect(); - let identity = self - .players - .identity(player.slot) - .or_else(|| self.weapon_inventory.get(&player.slot).map(|previous| previous.identity)); - let Some(identity) = identity else { continue }; - inventories.insert(player.slot, WeaponInventory { player, identity, weapons }); - } - // CS2 has no weapon_drop game event. Reconcile complete handles against the - // preceding inventory and the engine owner, so deletion/consumption/transfer - // is never mistaken for a world drop. - let mut dropped = Vec::new(); - if self.controller.enabled() && Self::model_scale_imports_available() { - for (slot, previous) in &self.weapon_inventory { - let Some(current) = inventories.get_mut(slot).filter(|current| current.player == previous.player) else { - continue; - }; - for (handle, classname) in &previous.weapons { - if current.weapons.contains_key(handle) - || !s2sdk::IsValidEntHandle(*handle) - || s2sdk::GetEntityClassname(*handle).as_str() != classname - { - continue; - } - match s2sdk::GetEntityOwner(*handle) { - -1 => dropped.push(*handle), - owner if owner == previous.player.pawn_handle => { - // Inventory removal can precede ownership release during a callback. - current.weapons.insert(*handle, classname.clone()); - } - _ => {} - } - } - } - } - self.weapon_inventory = inventories; - self.model_scales.retain(|handle, _| s2sdk::IsValidEntHandle(*handle)); - self.model_scale_restore_pending.retain(|handle| self.model_scales.contains_key(handle)); - for handle in dropped { - self.randomize_model_scale(handle); - } - } - - fn randomize_model_scale(&mut self, handle: i32) { - if self.model_scales.contains_key(&handle) { - return; - } - let Some(previous) = Self::entity_model_scale(handle) else { return }; - let installed = self.random_model_scale(); - if Self::set_entity_model_scale(handle, installed) { - self.model_scales.insert(handle, OwnedFloat { previous, installed }); - } - } - - fn entity_model_scale(handle: i32) -> Option { - if !Self::model_scale_imports_available() || !s2sdk::IsValidEntHandle(handle) { - return None; - } - let pointer = s2sdk::EntHandleToEntPointer(handle); - if pointer == 0 || s2sdk::EntPointerToEntHandle(pointer) != handle { - return None; - } - let scale = s2sdk::GetEntityModelScale(handle); - scale.is_finite().then_some(scale) - } - - fn set_entity_model_scale(handle: i32, value: f32) -> bool { - if !Self::model_scale_imports_available() || !s2sdk::IsValidEntHandle(handle) || !value.is_finite() { - return false; - } - let pointer = s2sdk::EntHandleToEntPointer(handle); - if pointer == 0 || s2sdk::EntPointerToEntHandle(pointer) != handle { - return false; - } - s2sdk::SetEntityModelScale(handle, value); - Self::entity_model_scale(handle).is_some_and(|actual| (actual - value).abs() <= 0.0001) - } - - fn model_scale_imports_available() -> bool { - let mut probe = crate::capability::Probe::default(); - crate::capability::imports!(probe; __s2sdk_GetEntityModelScale, __s2sdk_SetEntityModelScale); - probe.available() - } - - fn random_model_scale(&mut self) -> f32 { - match self.rng.random_range(1..=5) { - 5 => self.rng.random_range(3.0..=15.0), - 4 => self.rng.random_range(0.5..=0.75), - _ => self.rng.random_range(0.75..=3.0), - } - } - - fn item_pickup(&mut self, slot: i32, event: usize) { - let Some(player) = LivePlayer::resolve_present(slot) else { return }; - let Some(weapons) = self.read_client_weapon_inventory(player) else { - return; - }; - let item = s2sdk::GetEventString(event, &Str::from_str("item")).to_string(); - for handle in weapons { - if !self.model_scales.contains_key(&handle) { - continue; - } - if !s2sdk::IsValidEntHandle(handle) - || s2sdk::GetEntityOwner(handle) != player.pawn_handle - || !matches_weapon_item(s2sdk::GetEntityClassname(handle).as_str(), &item) - { - continue; - } - self.restore_model_scale(handle); - } - } - - fn restore_picked_up_weapon_scales(&mut self) { - let picked_up = self - .model_scales - .keys() - .filter_map(|handle| { - let player_owns_it = self - .weapon_inventory - .values() - .any(|inventory| inventory.weapons.contains_key(handle) && s2sdk::GetEntityOwner(*handle) == inventory.player.pawn_handle); - player_owns_it.then_some(*handle) - }) - .collect::>(); - for handle in picked_up { - self.restore_model_scale(handle); - } - } - - fn restore_model_scale(&mut self, handle: i32) { - let Some(owner) = self.model_scales.get(&handle).copied() else { - self.model_scale_restore_pending.remove(&handle); - return; - }; - if release_model_scale(handle, owner) { - self.model_scales.remove(&handle); - self.model_scale_restore_pending.remove(&handle); - } else { - self.model_scale_restore_pending.insert(handle); - } - } - - fn restore_model_scales(&mut self) { - let entries = self.model_scales.iter().map(|(handle, owner)| (*handle, *owner)).collect::>(); - for (handle, owner) in entries { - if release_model_scale(handle, owner) { - self.model_scales.remove(&handle); - self.model_scale_restore_pending.remove(&handle); - } else { - self.model_scale_restore_pending.insert(handle); - } - } - } - - fn retry_model_scale_restores(&mut self) { - let handles = self.model_scale_restore_pending.iter().copied().collect::>(); - for handle in handles { - self.restore_model_scale(handle); - } - } - - fn restore_completed_native_bomb_scales(&mut self) { - for handle in self.bombs.take_native_model_scale_restores() { - self.restore_model_scale(handle); - } - } - - fn warmup_activation_available(&self) -> bool { - self.controller.enabled() - && self.controller.config().is_some_and(|config| { - config.warmup.as_ref().is_some_and(|warmup| { - warmup.enabled - && self - .controller - .capabilities() - .supports_warmup_with_chicken_config(&warmup.mode, config.chicken.is_some()) - }) - }) - } - - pub fn finish_bomb_explosion(&mut self, explosion: crate::bombs::Explosion, temporary: i32, result: Result<(), Fault>) { - if self.bombs.finish_explosion(explosion, temporary) - && let Err(error) = result + if let Some((bomb, chicken)) = self.bombs.take_chicken_model_scale_candidate() + && self.controller.enabled() + && let Err(error) = self.public_properties.scale_chicken_bomb(bomb, chicken, &mut self.rng) { self.handle_fault(error); } - } - - pub fn blocks_native_bomb_damage(&self, inflictor: i32) -> bool { - self.bombs.blocks_native_explosion(inflictor) - } - - pub fn take_chicken_cleanup(&mut self) -> Vec { - std::mem::take(&mut self.chicken_cleanup) - } - - pub fn finish_chicken_purchase(&mut self, task: PlayerTask) { - if self.chicken_purchases.get(&task.player.slot) == Some(&task) { - self.chicken_purchases.remove(&task.player.slot); - } - } - - fn cancel_chicken_purchase(&mut self, slot: i32) { - clear_chicken_purchase_state(slot, &mut self.chicken_purchases, &mut self.engine_actions); - } - - pub(crate) fn chicken_risk_finish_current(&self, task: PlayerTask, player: LivePlayer) -> bool { - // round_end advances the round generation and removes the chicken. The - // synchronous risk-blast continuation retains only this exact live eater. - self.classic_enabled() - && self.players.identity(player.slot) == Some(task.player) - && self.controllers.get(&player.slot) == Some(&player.controller_handle) - && LivePlayer::resolve(player.slot) == Some(player) - } - - pub fn chicken_buyer_identity_current(&self, task: PlayerTask, player: LivePlayer) -> bool { - self.on_game_thread() - && self.players.validates_connection(task.player) - && self.controllers.get(&player.slot) == Some(&player.controller_handle) - && LivePlayer::resolve_present(player.slot) == Some(player) - } - - fn ordinary_chickens_enabled(&self) -> bool { - self.controller.config().is_some_and(|config| config.chicken.is_some()) - && self.controller.current_mode().is_some_and(|mode| mode.ordinary_chickens) - } - - fn cleanup_ordinary_chickens(&mut self) { - self.chickens.clear_eating(); - self.chicken_use_buttons.clear(); - self.chicken_purchases.clear(); - self.pending_chicken_blast_kills.clear(); - self.engine_actions.retain(|action| { - !matches!( - action, - EngineAction::ChickenSpawn { .. } - | EngineAction::ChickenBlast { .. } - | EngineAction::ChickenPurchase { .. } - | EngineAction::ChickenEat { .. } - ) - }); - let chickens = self.chicken_entities.clear(); - for handle in &chickens { - self.restore_model_scale(*handle); - } - self.chicken_cleanup.extend(chickens); - self.chicken_spawn_round = None; - crate::CHICKEN_DAMAGE_ACTIVE.store(false, std::sync::atomic::Ordering::Release); - } - - fn clear_chicken_round_work(&mut self) { - self.chickens.clear_eating(); - self.chicken_use_buttons.clear(); - self.chicken_purchases.clear(); - self.pending_chicken_blast_kills.clear(); - self.engine_actions.retain(|action| { - !matches!( - action, - EngineAction::ChickenSpawn { .. } - | EngineAction::ChickenBlast { .. } - | EngineAction::ChickenPurchase { .. } - | EngineAction::ChickenEat { .. } - ) - }); - self.chicken_spawn_round = None; - } - - fn advance_chicken_round(&mut self, round: RoundGeneration) { - self.advance_chicken_round_if_alive(round, |handle| { - if !s2sdk::IsValidEntHandle(handle) || s2sdk::GetEntityClassname(handle).as_str() != "chicken" { - return false; - } - crate::chicken_entities::health(handle).is_some_and(|(health, life_state)| health > 0 && life_state == 0) - }); - } - - fn advance_chicken_round_if_alive(&mut self, round: RoundGeneration, alive: impl FnMut(i32) -> bool) { - self.pending_chicken_blast_kills.retain(|_, pending| pending.round == round); - let stale = self.chicken_entities.advance_round(round, alive); - for handle in stale { - self.restore_model_scale(handle); - self.chicken_cleanup.push(handle); - } - crate::CHICKEN_DAMAGE_ACTIVE.store(!self.chicken_entities.is_empty(), std::sync::atomic::Ordering::Release); - } - - pub fn track_chicken(&mut self, round: RoundGeneration, handle: i32) -> bool { - if !self.chicken_ready - || !self.ordinary_chickens_enabled() - || self.controller.generation() != round - || !matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) - || !self.chicken_entities.track(handle, round) - { - return false; - } - self.randomize_model_scale(handle); - crate::CHICKEN_DAMAGE_ACTIVE.store(true, std::sync::atomic::Ordering::Release); - true - } - - pub fn track_chicken_explosion(&mut self, round: RoundGeneration, handle: i32, source: i32) -> bool { - self.ordinary_chickens_enabled() - && self.controller.generation() == round - && matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) - && self.chicken_entities.track_explosion(handle, round, source) - } - - pub fn finish_chicken_explosion(&mut self, round: RoundGeneration, handle: i32) { - self.chicken_entities.remove_explosion(handle, round); - } - - pub fn chicken_blast_damage(&self, damage: &crate::damage::Damage) -> bool { - let round = self.controller.generation(); - [damage.inflictor, damage.attacker] - .into_iter() - .any(|handle| self.chicken_entities.is_chicken_explosion(handle, round)) - } - - pub(crate) fn observe_chicken_blast_player_damage(&mut self, damage: &crate::damage::Damage, players: &game::DamagePlayers) { - let Some(victim) = players.victim else { return }; - let Some(victim_identity) = self - .players - .identity(victim.slot) - .filter(|identity| identity.pawn_handle == victim.pawn_handle as u32) - else { - self.pending_chicken_blast_kills.remove(&victim.slot); - return; - }; - let round = self.controller.generation(); - if !self.classic_round() - || !active_combat_phase(self.controller.phase()) - || !self.controller.current_mode().is_some_and(|mode| mode.kill_loadout) - || !self.chicken_blast_damage(damage) - { - self.pending_chicken_blast_kills.remove(&victim.slot); - return; - } - let Some(source) = self - .chicken_entities - .blast_kill_weapon_source(&[damage.inflictor, damage.attacker, damage.weapon], round) - else { - self.pending_chicken_blast_kills.remove(&victim.slot); - return; - }; - if !chicken_weapon_source_is_current(&source, &self.players, &self.controllers) { - self.pending_chicken_blast_kills.remove(&victim.slot); - return; - } - self.pending_chicken_blast_kills.insert( - victim.slot, - PendingChickenBlastKill { - round, - victim: victim_identity, - tick: s2sdk::GetGameTickCount(), - damage_frame_token: crate::damage::current_damage_frame_token().filter(|token| *token != 0), - source, - }, - ); - } - - fn take_chicken_blast_kill_weapon(&mut self, victim_slot: i32, attacker_slot: i32) -> Option { - let pending = self.pending_chicken_blast_kills.remove(&victim_slot)?; - let victim = self.players.identity(victim_slot)?; - let attacker = self.players.identity(attacker_slot)?; - let frame = crate::damage::current_damage_frame_token().filter(|token| *token != 0); - if pending.matches(self.controller.generation(), victim, attacker, s2sdk::GetGameTickCount(), frame) - && attacker_slot == pending.source.attacker.slot - && chicken_weapon_source_is_current(&pending.source, &self.players, &self.controllers) - { - Some(pending.source) - } else { - None + } + + pub(crate) fn prepare_bomb_action_scales(&mut self, action: crate::bombs::Action) -> Result<(), Fault> { + if let Some(chicken) = action.cleanup_chicken() { + // Restore the parent while the C4 is still attached. Detaching preserves + // world scale, so restoring afterwards would leave a scaled C4 behind. + if !self.public_properties.restore_model_scale(chicken) { + return Err(Fault::global("chicken/C4 group scale restoration pending before detach")); + } } + Ok(()) } - fn clear_pending_chicken_blast_for_life(&mut self, identity: PlayerIdentity) { - self.pending_chicken_blast_kills - .retain(|slot, pending| *slot != identity.slot && pending.victim != identity && pending.source.attacker != identity); + pub fn prepare_carrier_disconnect(&mut self, slot: i32) -> Option { + let player = LivePlayer::resolve_present(slot)?; + // Death retires the effect life, but cleanup must still release that connection's native pawn. + self.players.connection_identity(slot)?; + if self.controllers.get(&slot) != Some(&player.controller_handle) { + return None; + } + self.bombs.prepare_carrier_disconnect(self.controller.generation(), player) } - fn clear_pending_chicken_blast_for_slot(&mut self, slot: i32) { - self.pending_chicken_blast_kills - .retain(|victim, pending| *victim != slot && pending.source.attacker.slot != slot); + pub fn take_bomb_actions(&mut self) -> Vec { + self.bombs.take_actions() } - pub fn chicken_damage_blocked(&mut self, damage: crate::chicken_entities::EntityDamageSource) -> bool { - let round = self.controller.generation(); - let Some(config) = self.controller.config().and_then(|config| config.chicken) else { - return false; - }; - let blocked = self.chicken_entities.damage_blocked(damage, round, config.damage_chain); - if !blocked { - let players = &self.players; - let controllers = &self.controllers; - self.chicken_entities - .record_lethal_attacker(damage, round, || capture_chicken_damage_weapon_source(damage, players, controllers)); - } - blocked + pub fn take_prestart_context(&mut self) -> Option<(i32, bool)> { + self.prestart_context.take() } - fn queue_chicken_population(&mut self) { - if !self.chicken_ready || !self.classic_enabled() || !matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) { - return; - } - if !self.ordinary_chickens_enabled() { - self.cleanup_ordinary_chickens(); - return; - } - if self.chicken_spawn_round == Some(self.controller.generation()) { - return; - } - let Some(config) = self.controller.config().and_then(|config| config.chicken) else { - return; - }; - let mut effective_players = 0_u32; - let mut positions = Vec::new(); - for slot in 0..s2sdk::GetMaxClients() { - if !s2sdk::IsClientInGame(slot) || !matches!(s2sdk::GetClientTeam(slot) as i32, 2 | 3) { - continue; - } - effective_players = effective_players.saturating_add(1); - if let Some(player) = LivePlayer::resolve(slot) { - let origin = s2sdk::GetEntityAbsOrigin(player.pawn_handle); - if origin.x.is_finite() && origin.y.is_finite() && origin.z.is_finite() { - positions.push(origin); - } - } + pub fn finish_round_prestart(&mut self, (tick, warmup): (i32, bool)) { + self.bombs.refresh_prestart_retirements(); + self.bombs.finish_round_prestart_cleanup(); + if warmup && self.controller.phase() == Phase::Warmup { + self.cleanup_effects(false); + self.restore_team_names(); + self.controller.stop_warmup(); + self.round = None; + self.prestarted_round = None; + self.warmup_activation_pending = self.warmup_active; } - if positions.is_empty() { + self.finish_round_transition_recovery(); + if tick < 0 || warmup { + self.prestarted_round = None; return; } - let round = self.controller.generation(); - let count = config.spawn.target_count(effective_players); - let owned = self.chicken_entities.owned_handles(round); - let maximum = config.spawn.maximum_population(count); - if owned.len() as u64 > u64::from(maximum) { - let excess = (owned.len() as u64 - u64::from(maximum)) as usize; - for handle in owned.into_iter().take(excess) { - if self.chicken_entities.remove_chicken(handle, round) { - self.restore_model_scale(handle); - self.chicken_cleanup.push(handle); - } + self.on_region_map_ready(); + self.refresh_wall_hang_capability(); + self.refresh_grapple_capability(); + let key = self.controller.round_key(tick as u64); + let ready_for_prestart_selection = self.effects_ready + || (self.faults.recovery == Recovery::Ready + && self.cleanup_complete_for_round_transition_without_bombs() + && self.bombs.prestart_removals_ready()); + if self.select_round(key, warmup, ready_for_prestart_selection) { + self.prestarted_round = Some(key); + if let Err(error) = self.parameters.apply_prestart_purchase(self.controller.current_mode()) { + self.handle_fault(error); } - self.chicken_spawn_round = Some(round); - crate::CHICKEN_DAMAGE_ACTIVE.store(!self.chicken_entities.is_empty(), std::sync::atomic::Ordering::Release); - log(&format!("chicken population trim round={round:?} maximum={maximum} removed={excess}")); - return; - } - let refill_threshold = config.spawn.refill_threshold(count); - if owned.len() >= refill_threshold as usize { - self.chicken_spawn_round = Some(round); - return; - } - for index in 0..count { - let player_origin = positions[index as usize % positions.len()]; - let turn = index as f32 * 2.399_963_1; - let ring = (index as usize / positions.len()) as f32; - let distance = 64.0 + ring * 24.0; - self.engine_actions.push(EngineAction::ChickenSpawn { - round, - origin: plugify::Vec3 { - x: player_origin.x + turn.cos() * distance, - y: player_origin.y + turn.sin() * distance, - z: player_origin.z + 4.0, - }, - }); } - self.chicken_spawn_round = Some(round); - log(&format!( - "chicken spawn plan round={round:?} count={count} effective_players={effective_players}" - )); } - fn poll_chickens(&mut self) -> Vec { - if !self.chicken_ready || !matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) { - return Vec::new(); - } - if !self.ordinary_chickens_enabled() { - self.cleanup_ordinary_chickens(); - return Vec::new(); - } - let round = self.controller.generation(); - let Some(config) = self.controller.config().and_then(|config| config.chicken) else { - return Vec::new(); - }; - let mut actions = Vec::new(); - for handle in self.chicken_entities.owned_handles(round) { - let Some((health, life_state)) = crate::chicken_entities::health(handle) else { - // Removal without a readable dead state is not a kill and must not blast. - self.chicken_entities.remove_chicken(handle, round); - self.restore_model_scale(handle); - continue; - }; - let attacker = self.chicken_entities.killer(handle, round); - if (health <= 0 || life_state == 2) - && let Some(origin) = crate::chicken_entities::position(handle) - && self.chicken_entities.mark_dead(handle, round) - && let Some(config) = self.chicken_entities.take_blast_config(handle, round, config.kill_blast) - { - actions.push(EngineAction::ChickenBlast { - round, - chicken: handle, - attacker, - origin, - config, - }); - } - } - if self.chicken_entities.is_empty() { - crate::CHICKEN_DAMAGE_ACTIVE.store(false, std::sync::atomic::Ordering::Release); + fn confirm_prestarted_round_reset(&mut self) -> bool { + self.bombs.confirm_prestart_removals_after_round_reset(); + self.effects_ready = self.faults.recovery == Recovery::Ready + && self.cleanup_complete_for_round_transition_except_pending_and_prestart_parameters_and_bombs() + && self.pending_prestarted_loadouts_are_current() + && self.bombs.is_clean(); + self.effects_ready + } + + pub fn take_bomb_explosion(&mut self) -> Option { + self.bombs.take_explosion(self.controller.generation()) + } + + fn restore_completed_native_bomb_scales(&mut self) { + for handle in self.bombs.take_native_model_scale_restores() { + self.public_properties.restore_model_scale(handle); } - actions } - pub fn update(&mut self) -> Vec { - if let Err(error) = self.sync_healthshot_override() { - self.healthshot_faulted = true; - let message = error.to_string(); - self.faults.exclude(Mechanism::Healthshot, message.clone()); - self.controller.set_capabilities(self.faults.capabilities()); - log(&format!("healthshot capability disabled: {message}")); + fn warmup_activation_available(&self) -> bool { + self.controller.enabled() + && self.controller.config().is_some_and(|config| { + config.warmup.as_ref().is_some_and(|warmup| { + warmup.enabled + && self + .controller + .capabilities() + .supports_warmup_with_chicken_config(&warmup.mode, config.chicken.is_some()) + }) + }) + } + + pub fn finish_bomb_explosion(&mut self, explosion: crate::bombs::Explosion, temporary: i32, result: Result<(), Fault>) { + if self.bombs.finish_explosion(explosion, temporary) + && let Err(error) = result + { + self.handle_fault(error); } + } + + pub fn blocks_native_bomb_damage(&self, inflictor: i32) -> bool { + self.bombs.blocks_native_explosion(inflictor) + } + + pub(crate) fn update_with_spawned_entities(&mut self, spawned_entities: Vec) -> Vec { + self.update_healthshot(); if let Some(failures) = self.preferences.as_mut().map(crate::preferences::Preferences::check_worker) { for (account_id, error) in failures { log(&format!( @@ -3334,50 +1729,46 @@ impl Runtime { self.handle_fault(error); } self.apply_pending_takeovers(tick); + let air_strafe = tick >= 0 && self.air_strafe_active(); + if let Err(error) = self.air_strafe.apply(air_strafe) { + self.handle_fault(error); + } self.release_chicken_use_buttons(); - self.native_self_damage_shots.retain(|slot, shot| { - shot.tick == tick && self.players.identity(*slot) == Some(shot.task.player) && LivePlayer::resolve(*slot) == Some(shot.player) - }); - let frame = crate::damage::current_damage_frame_token().filter(|token| *token != 0); - self.random_heals.retain(|receipt| Some(receipt.frame_token) == frame); - let round = self.controller.generation(); - let players = &self.players; - self.pending_chicken_blast_kills.retain(|slot, pending| { - pending.tick == tick - && pending.round == round - && players.identity(*slot) == Some(pending.victim) - && players.identity(pending.source.attacker.slot) == Some(pending.source.attacker) - }); + self.combat.expire_combat_receipts(tick, &self.players); + self.ordinary_chickens + .expire_chicken_blast_kills(tick, self.controller.generation(), &self.players); self.recover_incomplete_effects(); let warmup = game::warmup(); self.sync_warmup(warmup, tick, None); - self.update_duck_speed(); - self.refresh_weapon_inventory(); - self.restore_picked_up_weapon_scales(); - self.retry_model_scale_restores(); + self.arm_death_explosives(); + self.public_properties + .update(self.controller.enabled(), &self.players, self.controller.generation(), &mut self.rng); if self.warmup_active && self.controller.phase() == Phase::Warmup && !self.warmup_activation_pending && self.effects_ready && tick >= 0 { self.reconcile_warmup_players(tick); } let now = s2sdk::GetGameTime(); + self.update_proximity_with_spawned_entities(tick, &spawned_entities); + self.update_teamkills(); + self.settle_shooting(tick); + self.update_composed(f64::from(now), tick); self.update_afterburns(f64::from(now)); let center_display = self.send_pending_center(tick); let mut actions = self .take_afterburn_cleanup() .into_iter() - .map(EngineAction::AfterburnRemove) + .map(|handle| EngineAction::Afterburn(afterburn::Action::Remove(handle))) .collect::>(); + self.suicides.feedback.expire(now); actions.extend( - self.suicide_feedback - .take_expired(now) + self.take_suicide_feedback_cleanup() .into_iter() - .map(EngineAction::SuicideFeedbackRemove), + .map(|handle| EngineAction::Suicide(suicide::Action::RemoveFeedback(handle))), ); actions.extend( - std::mem::take(&mut self.suicide_feedback_cleanup) + self.take_chicken_cleanup() .into_iter() - .map(EngineAction::SuicideFeedbackRemove), + .map(|handle| EngineAction::Chicken(chickens::Action::Remove(handle))), ); - actions.extend(self.take_chicken_cleanup().into_iter().map(EngineAction::ChickenRemove)); actions.extend(std::mem::take(&mut self.engine_actions)); actions.extend(self.poll_chickens()); self.queue_chicken_population(); @@ -3393,6 +1784,9 @@ impl Runtime { self.refresh_classic(None); self.refresh_view(); self.refresh_periodic_movement(); + self.refresh_movement(); + self.observe_grapple_buttons(tick); + actions.extend(std::mem::take(&mut self.engine_actions)); self.update_money_income(); self.send_welcomes(); let bomb_settings = self.controller.current_mode().and_then(|mode| mode.bomb.as_ref()); @@ -3409,7 +1803,7 @@ impl Runtime { && bomb_update.is_ok() && self.controller.enabled() { - self.randomize_model_scale(handle); + self.public_properties.randomize_model_scale(handle, &mut self.rng); } if let Err(error) = bomb_update { self.handle_fault(error); @@ -3418,21 +1812,9 @@ impl Runtime { actions.extend(self.take_equipment_cleanup().into_iter().map(EngineAction::Equipment)); actions.extend(std::mem::take(&mut self.impacts).into_iter().map(EngineAction::ProjectileImpact)); actions.extend(self.bombs.take_actions().into_iter().map(EngineAction::Bomb)); - for hit in std::mem::take(&mut self.reflections) { - if tick > hit.tick { - actions.push(EngineAction::Reflection(hit)); - } else { - self.reflections.push(hit); - } - } + self.combat.collect_reflections(tick, &mut actions); self.update_chicken_digestion(f64::from(now)); - for hit in std::mem::take(&mut self.delayed_damage) { - if hit.is_due(now) { - actions.push(EngineAction::DelayedDamage(hit)); - } else { - self.delayed_damage.push(hit); - } - } + self.combat.collect_delayed_damage(now, &mut actions); if active_combat_phase(self.controller.phase()) { if self.controller.current_mode().is_some_and(|mode| mode.dodgeball) { let touches = self.projectiles.discover_decoys(now, self.controller.generation(), &self.players); @@ -3464,65 +1846,10 @@ impl Runtime { "team.finished", &[("t", &result.scores[0].to_string()), ("ct", &result.scores[1].to_string())], ); - self.respawns.clear(); - self.round_respawns.clear(); + self.respawning.clear_respawns(); actions.push(EngineAction::EndRound(self.controller.generation(), reason)); } - for (task, player, team, due) in std::mem::take(&mut self.respawns) { - if !self.players.validates_respawn(task, self.controller.generation()) - || !respawn_window_open(self.controller.phase(), self.team_match.as_ref().map(|game| game.remaining(now))) - || !respawn_target_valid( - player, - LivePlayer::resolve_present(task.player.slot), - team, - s2sdk::GetClientTeam(task.player.slot) as i32, - LivePlayer::resolve(task.player.slot).is_some(), - ) - { - continue; - } - if now < due { - self.respawns.push((task, player, team, due)); - } else { - log(&format!("respawn slot={} team={team}", task.player.slot)); - actions.push(EngineAction::Respawn(task, player, team)); - } - } - for (task, player, team, due) in std::mem::take(&mut self.round_respawns) { - let all_respawn = self.controller.current_mode().is_some_and(|mode| mode.round_respawn == RoundRespawn::All); - if !round_respawn_task_valid(&self.players, task, self.controller.generation(), player) - || !respawn_window_open(self.controller.phase(), self.team_match.as_ref().map(|game| game.remaining(now))) - || !round_respawn_target_valid( - all_respawn, - self.controller.phase(), - player, - LivePlayer::resolve_present(task.player.slot), - team, - s2sdk::GetClientTeam(task.player.slot) as i32, - ) - { - continue; - } - if now < due { - self.round_respawns.push((task, player, team, due)); - } else { - log(&format!("round respawn slot={} team={team}", task.player.slot)); - actions.push(EngineAction::RoundRespawn(task, player, team)); - } - } - for task in std::mem::take(&mut self.low_health_finishes) { - if let Some(player) = LivePlayer::resolve(task.player.slot) - && self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) - && self.controller.current_mode().is_some_and(|mode| mode.self_damage_finish_enabled()) - && funrounds_core::low_health_finish(s2sdk::GetClientHealth(player.slot)) - { - actions.push(EngineAction::LowHealthFinish( - task, - player, - self.controller.current_mode().is_some_and(|mode| mode.native_self_damage_enabled()), - )); - } - } + self.collect_respawn_actions(now, &mut actions); actions } @@ -3573,14 +1900,17 @@ impl Runtime { fn start_periodic_movement(&mut self) { self.periodic_movement = None; - if !self + let Some((speed, gravity)) = self .controller .current_mode() - .is_some_and(|mode| mode.periodic_speed || mode.periodic_gravity) - { + .map(|mode| (mode.periodic_speed.clone(), mode.periodic_gravity.clone())) + else { + return; + }; + if speed.is_none() && gravity.is_none() { return; } - match funrounds_core::PeriodicMovement::start(s2sdk::GetGameTime()) { + match funrounds_core::PeriodicMovement::start(s2sdk::GetGameTime(), speed, gravity) { Ok(movement) => self.periodic_movement = Some((self.controller.generation(), movement)), Err(error) => self.handle_fault(Fault::mechanism(Mechanism::PeriodicMovement, error)), } @@ -3614,26 +1944,23 @@ impl Runtime { self.record_fault(Fault::global(error)); } discard_map_effects(&mut self.effects, &mut self.retired_effects); - self.model_scales.clear(); - self.model_scale_restore_pending.clear(); - self.chicken_entities.discard_map_state(); - self.chicken_cleanup.clear(); + self.public_properties.discard_map_state(); + self.ordinary_chickens.discard_map_state(); self.bombs.discard_map_state(); self.projectiles.discard_map_state(); + self.clear_regions_map(); self.afterburns.discard_map_state(); + self.composed = composed::State::default(); self.night_vision.discard_map_state(); self.ghost.discard_map_state(); - self.suicide_feedback.discard_map_state(); - self.suicide_feedback_cleanup.clear(); - self.afterburn_cleanup.clear(); + self.suicides.discard_map_state(); + self.refills.discard_map_state(); self.impacts.clear(); - self.suicides.entries.clear(); - self.suicides.pending.clear(); - self.suicides.buying.clear(); self.pending_takeovers.clear(); self.players.clear(); self.controllers.clear(); + self.discard_grapple_map_state(); self.welcomes.clear(); self.preferences.as_mut().expect("preferences active").clear_sessions(); self.last_name = None; @@ -3645,6 +1972,7 @@ impl Runtime { self.prestarted_round = None; self.warmup_active = false; self.warmup_activation_pending = false; + self.warmup_round_faulted = false; } self.sync_warmup(game::warmup(), tick, spawn_slot); tick @@ -3652,6 +1980,9 @@ impl Runtime { fn sync_warmup(&mut self, state: Option, tick: i32, spawn_slot: Option) { if state != Some(true) { + if state == Some(false) { + self.warmup_round_faulted = false; + } if self.warmup_active { self.warmup_active = false; self.warmup_activation_pending = false; @@ -3674,6 +2005,30 @@ impl Runtime { return; } + if self.warmup_round_faulted { + return; + } + + if self.controller.phase() == Phase::Idle && self.controller.enabled() && self.effects_ready && tick >= 0 { + let warmup = self + .controller + .config() + .and_then(|config| config.warmup.as_ref()) + .filter(|warmup| warmup.enabled); + let wall_hang = warmup.is_some_and(|warmup| warmup.mode.wall_hang); + let grapple = warmup.is_some_and(|warmup| warmup.mode.grapple.is_some()); + let trampoline = warmup.is_some_and(|warmup| warmup.mode.trampoline); + if trampoline { + self.on_region_map_ready(); + } + if wall_hang { + self.refresh_wall_hang_capability(); + } + if grapple { + self.refresh_grapple_capability(); + } + } + if !self.warmup_active { self.warmup_active = true; self.warmup_activation_pending = true; @@ -3805,6 +2160,22 @@ impl Runtime { warmup_spawn_needed(identity, player, effect_applied, loadout_pending) } + fn bind_pending_spawn(&mut self, task: PlayerTask, player: LivePlayer) -> Option { + let identity = self.players.bind_spawn(task.player, player.pawn_handle as u32)?; + let base_health = self.chickens.base_health(task).ok(); + self.chickens.clear_life(task); + if let Some((combat_task, _)) = self.combat.lives.get_mut(&player.slot) + && *combat_task == task + { + combat_task.player = identity; + } + if let Some(base_health) = base_health { + self.chickens.observe_life(PlayerTask { player: identity, ..task }, base_health); + } + self.death_explosives.bind_candidate(task.player, identity); + Some(identity) + } + fn apply_pending(&mut self, tick: i32) -> Vec { let mut actions = Vec::new(); let pending = std::mem::take(&mut self.pending); @@ -3832,20 +2203,10 @@ impl Runtime { continue; } if task.player.pawn_handle == u32::MAX { - let Some(identity) = self.players.bind_spawn(task.player, player.pawn_handle as u32) else { + let Some(identity) = self.bind_pending_spawn(task, player) else { continue; }; - let base_health = self.chickens.base_health(task).ok(); - self.chickens.clear_life(task); - if let Some((combat_task, _)) = self.combat.get_mut(&player.slot) - && *combat_task == task - { - combat_task.player = identity; - } task.player = identity; - if let Some(base_health) = base_health { - self.chickens.observe_life(task, base_health); - } } if !self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) { self.cancel_pending(action); @@ -4008,6 +2369,9 @@ impl Runtime { if self.controller.is_new_round(key) { self.cleanup_before_new_round(key); self.finish_round_transition_recovery(); + if !warmup { + self.on_region_map_ready(); + } } self.select_round(key, warmup, self.effects_ready) } @@ -4021,14 +2385,20 @@ impl Runtime { pub fn event(&mut self, name: &str, event: usize) { let spawn_slot = (name == "player_spawn").then(|| s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid"))); self.observe_tick(Some(name), spawn_slot); + if matches!(name, "smokegrenade_detonate" | "smokegrenade_expired") { + self.on_region_event(name, event); + } if name != "item_pickup" { - self.refresh_weapon_inventory(); + self.public_properties + .refresh_inventory(self.controller.enabled(), &self.players, self.controller.generation(), &mut self.rng); } match name { "item_pickup" => { let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); - self.item_pickup(slot, event); - self.refresh_weapon_inventory(); + self.public_properties + .item_pickup(slot, event, &self.players, self.controller.generation()); + self.public_properties + .refresh_inventory(self.controller.enabled(), &self.players, self.controller.generation(), &mut self.rng); } "round_prestart" => { self.prestart_context = None; @@ -4062,6 +2432,8 @@ impl Runtime { } "bomb_exploded" => self.bombs.capture_explosion(self.controller.generation()), "bomb_beginplant" | "bomb_begindefuse" => { + let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); + self.stop_grapple_for_bomb_use(slot, name == "bomb_begindefuse"); let Some(mode) = self.controller.current_mode() else { return }; if !active_combat_phase(self.controller.phase()) { return; @@ -4085,7 +2457,7 @@ impl Runtime { } } else if let Some(task) = task { if has_bomb_timing && let Err(error) = self.bombs.begin_defuse(task, s2sdk::GetEventBool(event, &Str::from_str("haskit"))) { - self.handle_fault(error); + self.handle_fault(Fault::mechanism(Mechanism::BombTiming, error)); return; } if quick_defuse_available @@ -4100,23 +2472,32 @@ impl Runtime { } } "bomb_abortplant" => { + let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); + self.finish_grapple_bomb_use(slot); if let Err(error) = self.bombs.abort_plant() { - self.handle_fault(error); + self.handle_fault(Fault::mechanism(Mechanism::BombTiming, error)); } } "bomb_abortdefuse" => { + let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); + self.finish_grapple_bomb_use(slot); self.bombs.abort_quick_defuse(); if let Err(error) = self.bombs.abort_defuse() { - self.handle_fault(error); + self.handle_fault(Fault::mechanism(Mechanism::BombTiming, error)); } } + "bomb_defused" => { + let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); + self.finish_grapple_bomb_use(slot); + } "bomb_planted" => { + let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); + self.finish_grapple_bomb_use(slot); if active_combat_phase(self.controller.phase()) && let Some(mode) = self.controller.current_mode() { let kind = mode.bomb.as_ref().map_or(funrounds_core::BombKind::Native, |settings| settings.kind); let round = self.controller.generation(); - let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); let task = self.players.identity(slot).map(|player| PlayerTask { player, round }); let team = if slot >= 0 && s2sdk::IsClientInGame(slot) { s2sdk::GetClientTeam(slot) as i32 @@ -4266,6 +2647,7 @@ impl Runtime { if let Some(round) = self.round { let started = self.controller.freeze_end(round); if started { + self.start_death_explosives(); self.queue_c4_assignment(); self.start_money_income(); self.start_periodic_movement(); @@ -4311,6 +2693,21 @@ impl Runtime { }; let route = grenade_thrown_route(self.controller.current_mode(), kind); let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); + if kind == Some(equipment::GrenadeKind::Smoke) { + self.record_smoke_throw(slot); + } + if matches!( + kind, + Some( + equipment::GrenadeKind::He + | equipment::GrenadeKind::Molotov + | equipment::GrenadeKind::Incendiary + | equipment::GrenadeKind::Decoy + ) + ) { + self.record_regeneration_combat(slot); + } + self.observe_proximity_throw(slot, kind); if route.track_dodgeball_decoy && let Some(identity) = self.players.identity(slot) { @@ -4348,14 +2745,19 @@ impl Runtime { } } } + "bullet_impact" => self.bullet_impact(event), "weapon_fire" => { let weapon = s2sdk::GetEventString(event, &Str::from_str("weapon")).to_string(); let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); - if matches!(weapon.as_str(), "knife" | "knife_t" | "weapon_knife" | "weapon_knife_t") - && active_combat_phase(self.controller.phase()) - && self.controller.current_mode().is_some_and(|mode| mode.throwing_knives) - { - self.native_self_damage_shots.remove(&slot); + // Empty clicks use weapon_fire_on_empty, not this native event. + let firearm = crate::effects::firearm_event(&weapon); + let knife = crate::projectiles::knife_fire_event(&weapon); + if firearm || knife { + self.record_regeneration_combat(slot); + } + self.capture_shot(slot, &weapon); + if knife && active_combat_phase(self.controller.phase()) && self.controller.current_mode().is_some_and(|mode| mode.throwing_knives) { + self.combat.native_self_damage_shots.remove(&slot); if let Some(player) = self.players.identity(slot) { self.projectiles.schedule_knife( PlayerTask { @@ -4367,37 +2769,18 @@ impl Runtime { } return; } - if !crate::effects::firearm_event(&weapon) { - self.native_self_damage_shots.remove(&slot); + if !firearm { + self.combat.native_self_damage_shots.remove(&slot); return; } let Some(player) = LivePlayer::resolve(slot) else { - self.native_self_damage_shots.remove(&slot); - return; - }; - let Some(mode) = self.controller.current_mode() else { - self.native_self_damage_shots.remove(&slot); + self.combat.native_self_damage_shots.remove(&slot); return; }; + self.queue_weapon_on_fire(player, &weapon); + self.capture_native_self_damage_shot(player, &weapon); + let Some(mode) = self.controller.current_mode() else { return }; let identity = self.players.identity(slot); - if active_combat_phase(self.controller.phase()) - && matches!(mode.self_damage, Some(SelfDamage::Native { amount }) if amount > 0.0) - && let Some(task) = self.combat_task(player) - && let Some(weapon) = fired_weapon(player, &weapon) - { - self.native_self_damage_shots.insert( - slot, - NativeSelfDamageShot { - task, - player, - tick: s2sdk::GetGameTickCount(), - weapon, - player_hit: false, - }, - ); - } else { - self.native_self_damage_shots.remove(&slot); - } let knock = self .preferences .as_mut() @@ -4408,7 +2791,7 @@ impl Runtime { && matches!(self.controller.phase(), Phase::Running | Phase::Warmup) && knock.permits(s2sdk::GetClientFlags(slot)) && self.controllers.get(&slot) == Some(&player.controller_handle) - && let Some(effect) = self.effects.get(&slot).filter(|effect| { + && let Some(effect) = self.effects.get_mut(&slot).filter(|effect| { Some(effect.identity) == identity && effect.identity.pawn_handle == player.pawn_handle as u32 && !effect.has_pending_loadout() }) && let Err(error) = effect.self_push(player, &weapon) @@ -4424,9 +2807,7 @@ impl Runtime { player, round: self.controller.generation(), }; - if !self.low_health_finishes.contains(&task) { - self.low_health_finishes.push(task); - } + self.respawning.queue_finish(task); } let diagnostics = self.diagnostics(); let no_recoil = mode.no_recoil; @@ -4475,14 +2856,18 @@ impl Runtime { "player_death" => { let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); let attacker = s2sdk::GetEventPlayerSlot(event, &Str::from_str("attacker")); + let punishment = self.is_teamkill_punishment(slot); + if !punishment { + self.count_teamkill(slot, attacker); + } + self.forget_teamkill(slot); let chicken_weapon_source = self.take_chicken_blast_kill_weapon(slot, attacker); self.bombs.abandon_quick_defuse_player(slot); if let Some(identity) = self.players.identity(slot) { self.clear_chicken_life(identity); } - self.cancel_chicken_purchase(slot); - self.native_self_damage_shots.remove(&slot); - self.pending_takeovers.retain(|pending| pending.slot != slot); + self.ordinary_chickens.cancel_purchase(slot, &mut self.engine_actions); + self.combat.native_self_damage_shots.remove(&slot); self.projectiles .retire_player(slot, self.players.identity(slot).map(|player| player.pawn_handle)); if self.diagnostics() && self.controller.current_mode().is_some_and(|mode| mode.headshots == Headshots::Only) { @@ -4492,12 +2877,12 @@ impl Runtime { s2sdk::GetEventBool(event, &Str::from_str("headshot")) )); } - if active_combat_phase(self.controller.phase()) { + if !punishment && active_combat_phase(self.controller.phase()) { if self.controller.current_mode().is_some_and(|mode| mode.kill_protection) && let Some(player) = LivePlayer::resolve(attacker) && !s2sdk::IsFakeClient(attacker) && let Some(task) = self.combat_task(player) - && let Some((expected, life)) = self.combat.get_mut(&attacker) + && let Some((expected, life)) = self.combat.lives.get_mut(&attacker) && *expected == task { life.protect(s2sdk::GetGameTime()); @@ -4509,7 +2894,8 @@ impl Runtime { chicken_weapon_source, ); } - if self.controller.phase() == Phase::Running + if !punishment + && self.controller.phase() == Phase::Running && attacker >= 0 && slot >= 0 && let Some(game) = self.team_match.as_mut() @@ -4525,10 +2911,10 @@ impl Runtime { if let Err(error) = self.suicides.forget(slot) { self.record_fault(Fault::global(error)); } - self.players.death(slot); - self.round_respawns.retain(|(task, ..)| task.player.slot != slot); - self.combat.remove(&slot); - self.delayed_damage.retain(|hit| hit.target.player.slot != slot); + self.track_player_death(slot); + self.pending_takeovers.retain(|pending| pending.slot != slot); + self.respawning.cancel_round_respawn(slot); + self.combat.remove_life(slot); self.refills.cancel_player(slot); self.retire_effect(slot); self.pending.retain(|(task, _, _)| task.player.slot != slot); @@ -4538,10 +2924,26 @@ impl Runtime { self.queue_respawn(slot, respawn.delay_seconds); } } + "player_blind" => { + let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); + self.queue_long_flash(slot, event); + } "player_hurt" => { let victim = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); let attacker = s2sdk::GetEventPlayerSlot(event, &Str::from_str("attacker")); let weapon = s2sdk::GetEventString(event, &Str::from_str("weapon")).to_string(); + let health_damage = s2sdk::GetEventInt(event, &Str::from_str("dmg_health")); + let armor_damage = s2sdk::GetEventInt(event, &Str::from_str("dmg_armor")); + if (health_damage > 0 || armor_damage > 0) + && let Some(player) = LivePlayer::resolve(victim) + && self.controllers.get(&victim) == Some(&player.controller_handle) + && let Err(error) = self.interrupt_movement_for_impulse(player) + { + self.handle_fault(error.context("received damage interrupted temporary movement")); + } + if health_damage > 0 || armor_damage > 0 { + self.record_regeneration_combat(victim); + } if self.diagnostics() && self.controller.current_mode().is_some_and(|mode| { mode.lifesteal @@ -4592,36 +2994,29 @@ impl Runtime { } "player_team" => { let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); + self.death_explosives.forget(slot); + self.forget_teamkill(slot); self.bombs.abandon_quick_defuse_player(slot); if let Some(identity) = self.players.identity(slot) { self.clear_chicken_life(identity); } - self.cancel_chicken_purchase(slot); - self.native_self_damage_shots.remove(&slot); + self.ordinary_chickens.cancel_purchase(slot, &mut self.engine_actions); + self.combat.forget_player(slot); self.pending_takeovers.retain(|pending| pending.slot != slot); if let Err(error) = self.suicides.forget(slot) { self.handle_fault(Fault::global(error)); } self.players.death(slot); - self.combat.remove(&slot); - self.reflections - .retain(|hit| hit.target.player.slot != slot && hit.source.player.slot != slot); - self.delayed_damage - .retain(|hit| hit.target.player.slot != slot && hit.source.player.slot != slot); - self.random_heals - .retain(|hit| hit.target.player.slot != slot && hit.source.player.slot != slot); self.refills.cancel_player(slot); self.pending.retain(|(task, ..)| task.player.slot != slot); self.retire_effect(slot); - self.respawns.retain(|(task, _, _, _)| task.player.slot != slot); - self.round_respawns.retain(|(task, ..)| task.player.slot != slot); + self.respawning.cancel_player_respawns(slot); } _ => {} } } - pub(crate) fn handle_fault(&mut self, fault: impl Into) { - let fault = fault.into(); + pub(crate) fn handle_fault(&mut self, fault: Fault) { if fault.scope == Scope::Cancelled { log(&format!("action cancelled: {fault}")); return; @@ -4637,9 +3032,15 @@ impl Runtime { crate::legacy_textmsg::set_enabled(false); } let changed = self.faults.record(&fault); - self.prestarted_round = None; + if fault.scope != Scope::Round { + self.prestarted_round = None; + } self.controller.set_capabilities(self.faults.capabilities()); - if let Some(round) = self.round { + if fault.scope == Scope::Round { + self.warmup_round_faulted = self.warmup_active; + self.warmup_activation_pending = false; + self.controller.clear_active_round(); + } else if let Some(round) = self.round { self.controller.end_round(round); } self.effects_ready = false; @@ -4658,23 +3059,13 @@ impl Runtime { fn cleanup_complete_without_bombs(&self) -> bool { self.cleanup_complete_except_prestart_parameters_and_bombs() && self.parameters.is_restored() - // Healthshot ConVars are configuration-scoped; an in-sync active override is not unfinished round cleanup. - && healthshot_override_settled( - self.healthshot_active(), - self.healthshot_override_active, - self.healthshot_parameters.is_restored(), - ) + && self.healthshot.settled(self.healthshot_active()) } fn cleanup_complete_for_round_transition_without_bombs(&self) -> bool { self.cleanup_complete_for_round_transition_except_prestart_parameters_and_bombs() && self.parameters.is_restored() - // Healthshot ConVars are configuration-scoped; an in-sync active override is not unfinished round cleanup. - && healthshot_override_settled( - self.healthshot_active(), - self.healthshot_override_active, - self.healthshot_parameters.is_restored(), - ) + && self.healthshot.settled(self.healthshot_active()) } fn cleanup_complete_except_prestart_parameters_and_bombs(&self) -> bool { @@ -4695,21 +3086,18 @@ impl Runtime { fn cleanup_complete_except_pending_and_prestart_parameters_and_bombs_with_round_lifetime(&self, round_transition: bool) -> bool { !self.third_person_map_detach_pending + && self.grapple.is_clean() && self.ground_reverse.is_clean() + && self.air_strafe.is_clean() && self.ghost.is_clean() && self.night_vision.is_clean() - && public_property_cleanup_complete(self.controller.enabled(), self.duck_speed.is_empty(), self.model_scales.is_empty()) + && self.public_properties.cleanup_complete(self.controller.enabled()) && self.equipment_in_flight == 0 - && self.suicides.entries.is_empty() - && self.suicides.pending.is_empty() - && self.suicides.buying.is_empty() - && (self.chicken_entities.is_empty() || (round_transition && self.chicken_entities.has_only_active_chickens())) - && self.chicken_cleanup.is_empty() - && (self.suicide_feedback.is_empty() || (round_transition && self.suicide_feedback.has_only_unexpired(s2sdk::GetGameTime()))) - && self.suicide_feedback_cleanup.is_empty() + && self.suicides.cleanup_complete(round_transition, s2sdk::GetGameTime()) + && !self.has_guidance_fuse_recovery() + && self.ordinary_chickens.cleanup_complete(round_transition) + && self.composed.is_clean() && self.afterburns.is_clean() - && self.afterburn_cleanup.is_empty() - && self.suicides.ff.is_restored() && self.effects.is_empty() && self.retired_effects.is_empty() && self.team_names.is_restored() @@ -4738,7 +3126,7 @@ impl Runtime { fn finish_recovery(&mut self) { let complete = self.cleanup_complete(); if self.faults.finish_cleanup(complete) { - log("owned cleanup complete; quarantined capabilities remain excluded; waiting for a new round"); + log("owned cleanup complete; waiting for a new round with available capabilities"); } self.effects_ready = complete && self.faults.recovery == Recovery::Ready; } @@ -4748,7 +3136,7 @@ impl Runtime { && self.bombs.is_clean() && !crate::CHICKEN_FOLLOW_BLOCK_CLEANUP_PENDING.load(std::sync::atomic::Ordering::Acquire); if self.faults.finish_cleanup(complete) { - log("owned cleanup complete; quarantined capabilities remain excluded; waiting for a new round"); + log("owned cleanup complete; waiting for a new round with available capabilities"); } self.effects_ready = complete && self.faults.recovery == Recovery::Ready; } @@ -4758,8 +3146,7 @@ impl Runtime { let waiting = self.cleanup_after_round_start_wait(); self.restore_team_names(); if !self.controller.enabled() { - self.restore_duck_speed(); - self.restore_model_scales(); + self.public_properties.restore_all(); } if waiting { self.finish_round_transition_recovery(); @@ -4769,42 +3156,6 @@ impl Runtime { } } - fn lifesteal(&mut self, event: usize, attacker: i32, victim: i32) -> Option { - if self.controller.phase() == Phase::Idle || !self.controller.current_mode().is_some_and(|mode| mode.lifesteal) { - return None; - } - let player = LivePlayer::resolve(attacker); - if !lifesteal_eligible(attacker, victim, player.is_some()) { - return None; - } - let player = player.expect("eligible attacker is alive"); - if !self.effects.get(&attacker).is_some_and(|effect| { - Some(effect.identity) == self.players.identity(attacker) - && effect.identity.pawn_handle == player.pawn_handle as u32 - && !effect.has_pending_loadout() - }) || self.controllers.get(&attacker) != Some(&player.controller_handle) - { - return None; - } - let health = s2sdk::GetEventInt(event, &Str::from_str("dmg_health")); - let armor = s2sdk::GetEventInt(event, &Str::from_str("dmg_armor")); - let energy_shield = self.controller.current_mode().is_some_and(|mode| mode.energy_shield); - let effect = self.effects.get_mut(&attacker)?; - if let Err(error) = effect.lifesteal(player, health, armor, energy_shield) { - self.handle_fault(error); - return None; - } - if self.diagnostics() { - log(&format!( - "lifesteal slot={attacker} dmg_health={health} dmg_armor={armor} health={} armor={} helmet={:?}", - s2sdk::GetClientHealth(attacker), - s2sdk::GetClientArmor(attacker), - player.helmet() - )); - } - Some(attacker) - } - fn kill_loadout(&mut self, attacker: i32, victim: i32, event_weapon: &str, chicken_source: Option) { if attacker == victim || victim < 0 { return; @@ -4832,7 +3183,7 @@ impl Runtime { let tracked = tracked_upgrade_weapon(effect, player).map(|target| target.handle); let chicken_fallback = chicken_source .filter(|source| source.attacker.slot == attacker && self.players.identity(attacker) == Some(source.attacker)) - .filter(|source| chicken_weapon_source_is_current(source, &self.players, &self.controllers)) + .filter(|source| chickens::chicken_weapon_source_is_current(source, &self.players, &self.controllers)) .filter(|source| crate::effects::equipment::kill_loadout_source_weapon(&source.classname)) .map(|source| KillWeaponTarget { attacker: source.attacker, @@ -4866,24 +3217,19 @@ impl Runtime { self.players.spawn(slot, tick as u64, pawn); let identity = self.players.identity(slot).or_else(|| self.players.pending_identity(slot)); if previous != identity { + self.death_explosives.spawned(slot, identity, &self.players); if let Some(previous) = previous { self.clear_chicken_life(previous); } - self.chicken_use_buttons.remove(&slot); - self.healthshot_purchases.remove(&slot); - self.engine_actions - .retain(|action| !matches!(action, EngineAction::HealthshotPurchase { task, .. } if task.player.slot == slot)); - self.cancel_chicken_purchase(slot); - self.round_respawns.retain(|(task, ..)| task.player.slot != slot); - self.native_self_damage_shots.remove(&slot); - self.suicides.entries.remove(&slot); - self.suicides.buying.remove(&slot); - self.suicides.pending.retain(|action| action.task().player.slot != slot); + self.ordinary_chickens.forget_input(slot); + self.healthshot.cancel_purchase(slot, &mut self.engine_actions); + self.ordinary_chickens.cancel_purchase(slot, &mut self.engine_actions); + self.respawning.cancel_round_respawn(slot); + self.combat.cancel_spawn_work(slot); + self.suicides.discard_life(slot); self.refills.cancel_player(slot); self.retire_effect(slot); self.pending.retain(|(task, _, _)| task.player.slot != slot); - self.delayed_damage - .retain(|hit| hit.target.player.slot != slot && hit.source.player.slot != slot); } if apply_effects && self.controller.phase() != Phase::Idle @@ -4894,8 +3240,9 @@ impl Runtime { player: identity, round: self.controller.generation(), }; - if !self.combat.get(&slot).is_some_and(|(expected, _)| *expected == task) { + if !self.combat.lives.get(&slot).is_some_and(|(expected, _)| *expected == task) { self.combat + .lives .insert(slot, (task, funrounds_core::CombatLife::new(mode, s2sdk::GetGameTime(), &mut self.rng))); } } @@ -4912,6 +3259,7 @@ impl Runtime { // Loadout writes happen on a later tick; the engine may still report the old HP. let base_health = self .combat + .lives .get(&slot) .filter(|(expected, _)| *expected == task) .map_or_else(|| s2sdk::GetClientHealth(slot), |(_, life)| i32::from(life.attributes().health)); @@ -4970,14 +3318,17 @@ impl Runtime { }); } + fn takeover_current(&self, takeover: PendingTakeover) -> bool { + takeover.round == self.controller.generation() + && self.controllers.get(&takeover.slot) == Some(&takeover.controller_handle) + && s2sdk::PlayerSlotToEntHandle(takeover.slot) == takeover.controller_handle + && self.players.connection_identity(takeover.slot) == Some(takeover.expected) + } + fn apply_pending_takeovers(&mut self, tick: i32) { let pending = std::mem::take(&mut self.pending_takeovers); for takeover in pending { - if takeover.round != self.controller.generation() - || self.controllers.get(&takeover.slot) != Some(&takeover.controller_handle) - || s2sdk::PlayerSlotToEntHandle(takeover.slot) != takeover.controller_handle - || self.players.connection_identity(takeover.slot) != Some(takeover.expected) - { + if !self.takeover_current(takeover) { continue; } if tick <= takeover.event_tick { @@ -4994,13 +3345,13 @@ impl Runtime { let Some(identity) = self.players.takeover_identity(takeover.expected, player.pawn_handle as u32) else { continue; }; + self.cancel_grapple_player(takeover.slot); let task = PlayerTask { player: identity, round: takeover.round, }; let mut owners = self.tracked_pawn_owners(player.pawn_handle as u32); owners.sort_unstable(); - owners.dedup(); let effect_sources = owners .iter() .copied() @@ -5012,17 +3363,6 @@ impl Runtime { }) }) .collect::>(); - let combat_sources = owners - .iter() - .copied() - .filter(|slot| { - self.combat.get(slot).is_some_and(|(task, _)| { - task.round == takeover.round - && task.player.pawn_handle == player.pawn_handle as u32 - && self.players.identity(task.player.slot) == Some(task.player) - }) - }) - .collect::>(); let suicide_sources = owners .iter() .copied() @@ -5100,38 +3440,24 @@ impl Runtime { "multiple active effects own pawn={} during bot_takeover; slot={} was retired", player.pawn_handle, source ))); - if let Some(effect) = self.effects.remove(&source) { - retired.push((source, effect)); - } - } - - let combat_source = combat_sources - .iter() - .copied() - .find(|slot| *slot == takeover.slot) - .or_else(|| combat_sources.first().copied()); - let source_combat = combat_source.and_then(|source| self.combat.remove(&source)); - for source in combat_sources { - if Some(source) != combat_source { - self.combat.remove(&source); + if let Some(effect) = self.effects.remove(&source) { + retired.push((source, effect)); } } - if combat_source != Some(takeover.slot) { - self.combat.remove(&takeover.slot); - } - if let Some((old_task, life)) = source_combat - && old_task.round == takeover.round - && old_task.player.pawn_handle == identity.pawn_handle - && combat_source.is_some_and(|source| self.players.identity(source) == Some(old_task.player)) - { - self.combat.insert(takeover.slot, (task, life)); - } + + self.combat.takeover(&owners, task, &self.players); + let armed = self.death_explosives.takeover(&owners, task, &self.players); if self.players.takeover(takeover.expected, player.pawn_handle as u32) != Some(identity) { failures.push(Fault::global("player identity changed while applying bot_takeover")); } else { + if armed { + self.say(takeover.slot, "death_explosion.armed", &[]); + } self.chickens.takeover_pawn(task); self.afterburns.takeover_pawn(task, player); + self.takeover_composed(task, player); + self.takeover_trampoline(&owners, task.player); } for (slot, mut effect) in retired { match effect.restore_retired_state(&mut self.refills) { @@ -5167,7 +3493,9 @@ impl Runtime { slots.push(target); slots.sort_unstable(); slots.dedup(); - self.native_self_damage_shots.retain(|slot, _| !slots.contains(slot)); + self.takeover_teamkills(&slots, takeover_task, takeover_player); + self.takeover_shockwave_targets(&slots, takeover_task); + self.combat.cancel_actions_for(&slots); let mut pending = std::mem::take(&mut self.pending); pending.retain(|(task, _, action)| { if slots.contains(&task.player.slot) { @@ -5178,70 +3506,32 @@ impl Runtime { } }); self.pending = pending; - self.reflections - .retain(|hit| !slots.contains(&hit.target.player.slot) && !slots.contains(&hit.source.player.slot)); - self.delayed_damage - .retain(|hit| !slots.contains(&hit.target.player.slot) && !slots.contains(&hit.source.player.slot)); - self.random_heals - .retain(|receipt| !slots.contains(&receipt.target.player.slot) && !slots.contains(&receipt.source.player.slot)); self.impacts .retain(|impact| !slots.contains(&impact.task.player.slot) && !slots.contains(&impact.victim_task.player.slot)); - self.low_health_finishes.retain(|task| !slots.contains(&task.player.slot)); - self.respawns.retain(|(task, ..)| !slots.contains(&task.player.slot)); - self.round_respawns.retain(|(task, ..)| !slots.contains(&task.player.slot)); - self.chicken_purchases.retain(|slot, _| !slots.contains(slot)); + self.respawning.cancel_slots(&slots); + self.ordinary_chickens.cancel_purchases_for_slots(&slots); + self.healthshot.cancel_purchases_for_slots(&slots); self.engine_actions.retain_mut(|action| match action { + EngineAction::Composed(action) => !slots.contains(&action.task().player.slot), + EngineAction::Shooting(action) => !action.involves(&slots), + EngineAction::Proximity(action) => !action.involves(&slots), + EngineAction::HeGuidance(action) => !action.involves(&slots), + EngineAction::HeGuidanceFuseRestore(..) => true, + EngineAction::Grapple(grapple::Action::Acquire { task, .. } | grapple::Action::Pull { task, .. }) => !slots.contains(&task.player.slot), + EngineAction::Grapple(grapple::Action::RemoveBeam { .. }) => true, + EngineAction::Shockwave(action) => !action.involves(&slots), + EngineAction::Teamkill(action) => !action.involves(&slots), EngineAction::Rollback(task, _) | EngineAction::Loadout(task, _, _) | EngineAction::SettleLoadout(task, _, _) | EngineAction::Upgrade(task, _, _) - | EngineAction::ThirdPerson(task, _) - | EngineAction::GrantC4(task, _) - | EngineAction::RemoveC4(task, _, _) - | EngineAction::Respawn(task, _, _) - | EngineAction::RoundRespawn(task, _, _) - | EngineAction::LowHealthFinish(task, _, _) - | EngineAction::HealthshotUse { task, .. } - | EngineAction::HealthshotPurchase { task, .. } - | EngineAction::AfterburnIgnite { task, .. } - | EngineAction::ChickenEat { task, .. } => !slots.contains(&task.player.slot), - EngineAction::ChickenPurchase { task, .. } => !slots.contains(&task.player.slot), - EngineAction::Suicide(suicide) => { - let old = suicide.task(); - if !slots.contains(&old.player.slot) { - return true; - } - if matches!(suicide, crate::suicide::Action::Purchase { .. }) - || suicide_source != Some(old.player.slot) - || old.round != takeover_task.round - || old.player.pawn_handle != pawn - { - return false; - } - match suicide { - crate::suicide::Action::Start { task: queued, owned } => { - *queued = takeover_task; - owned.player = takeover_player; - true - } - crate::suicide::Action::Blast { - task: queued, - player: queued_player, - } - | crate::suicide::Action::Finish { - task: queued, - player: queued_player, - .. - } => { - *queued = takeover_task; - *queued_player = takeover_player; - true - } - crate::suicide::Action::Purchase { .. } => false, - } - } - EngineAction::Reflection(hit) => !slots.contains(&hit.target.player.slot) && !slots.contains(&hit.source.player.slot), - EngineAction::DelayedDamage(hit) => !slots.contains(&hit.target.player.slot) && !slots.contains(&hit.source.player.slot), + | EngineAction::ThirdPerson(task, _) => !slots.contains(&task.player.slot), + EngineAction::Chicken(action) => !action.involves(&slots), + EngineAction::Healthshot(action) => !action.involves(&slots), + EngineAction::Afterburn(action) => !action.involves(&slots), + EngineAction::Respawn(action) => !action.involves(&slots), + EngineAction::Suicide(action) => action.retain_for_takeover(&slots, suicide_source, takeover_task, takeover_player), + EngineAction::Combat(action) => !action.involves(&slots), EngineAction::ProjectileImpact(impact) => !slots.contains(&impact.task.player.slot) && !slots.contains(&impact.victim_task.player.slot), EngineAction::Projectile(action) => match action.kind { crate::projectiles::ActionKind::SpawnKnife { task, .. } => !slots.contains(&task.player.slot), @@ -5251,11 +3541,6 @@ impl Runtime { EngineAction::Equipment(equipment::Action::Refill(refill)) => !slots.contains(&refill.task.player.slot), EngineAction::Equipment(equipment::Action::Remove { .. }) | EngineAction::Bomb(_) - | EngineAction::ChickenSpawn { .. } - | EngineAction::ChickenBlast { .. } - | EngineAction::ChickenRemove(_) - | EngineAction::SuicideFeedbackRemove(_) - | EngineAction::AfterburnRemove(_) | EngineAction::EndRound(_, _) | EngineAction::CenterDisplay { .. } => true, }); @@ -5280,133 +3565,27 @@ impl Runtime { } } - fn queue_respawn(&mut self, slot: i32, delay: f32) { - if self.controller.phase() == Phase::Idle || LivePlayer::resolve(slot).is_some() { - return; - } - self.connect(slot); - let Some(player) = LivePlayer::resolve_present(slot) else { return }; - let team = s2sdk::GetClientTeam(slot) as i32; - if !matches!(team, 2 | 3) { - return; - } - let Some(task) = self.players.respawn_task(slot, self.controller.generation()) else { - return; - }; - if !self.respawns.iter().any(|(pending, ..)| *pending == task) { - self.respawns.push((task, player, team, s2sdk::GetGameTime() + delay)); - } - } - - fn queue_round_respawn(&mut self, slot: i32, tick: i32, delay: f32) { - if self.controller.phase() == Phase::Idle || !self.controller.current_mode().is_some_and(|mode| mode.round_respawn == RoundRespawn::All) { - return; - } - let team = s2sdk::GetClientTeam(slot) as i32; - if !matches!(team, 2 | 3) { - return; - } - self.connect(slot); - let Some(player) = LivePlayer::resolve_present(slot) else { return }; - if LivePlayer::resolve(slot).is_some() - && self - .players - .identity(slot) - .is_none_or(|identity| identity.pawn_handle != player.pawn_handle as u32) - { - // Register an alive player's current life without applying effects; its real spawn follows ForceRespawnClient. - self.spawn(slot, tick, false); - } - let Some(task) = round_respawn_task(&self.players, self.controller.generation(), player) else { - return; - }; - if self.controllers.get(&slot) != Some(&player.controller_handle) { - return; - } - let now = s2sdk::GetGameTime(); - if !now.is_finite() || !delay.is_finite() || delay < 0.0 { - return; - } - if !self.round_respawns.iter().any(|(pending, ..)| *pending == task) { - self.round_respawns.push((task, player, team, now + delay)); - } - } - - fn queue_c4_assignment(&mut self) { - if !active_combat_phase(self.controller.phase()) - || self.c4_assigned - || self.equipment_in_flight > 0 - || self.pending.iter().any(|(_, _, action)| *action == PendingAction::Loadout) - || !self.settling_loadouts.is_empty() - || self.effects.values().any(Effect::has_pending_loadout) - { - return; - } - let Some(count) = self.controller.current_mode().and_then(|mode| mode.c4_count) else { - return; - }; - let count = usize::from(count); - let phase = self.controller.phase(); - let mut players = Vec::new(); - let mut candidates = Vec::new(); - for slot in 0..s2sdk::GetMaxClients() { - let Some(player) = LivePlayer::resolve(slot) else { continue }; - let Some(task) = self.combat_task(player) else { continue }; - let native = s2sdk::GetClientWeapons(slot) - .iter() - .copied() - .filter(|handle| crate::suicide::real_c4(player, *handle) && !self.bombs.excludes_suicide_c4(player, *handle)) - .collect(); - players.push((task, player, native)); - if s2sdk::GetClientTeam(slot) as i32 == 2 { - candidates.push((task, player)); - } - } - if phase == Phase::Warmup && count > 0 && candidates.is_empty() { - return; - } - self.c4_assigned = true; - self.engine_actions.extend( - players - .into_iter() - .map(|(task, player, native)| EngineAction::RemoveC4(task, player, native)), - ); - candidates.shuffle(&mut self.rng); - self.engine_actions.extend( - candidates - .into_iter() - .take(count) - .map(|(task, player)| EngineAction::GrantC4(task, player)), - ); - } - fn forget_player(&mut self, slot: i32) { - self.clear_pending_chicken_blast_for_slot(slot); + self.death_explosives.forget(slot); + self.clear_region_player_life(slot); + self.forget_teamkill(slot); + self.ordinary_chickens.clear_pending_chicken_blast_for_slot(slot); if let Some(identity) = self.players.identity(slot) { + self.clear_composed_life(identity); self.afterburns.clear_life(PlayerTask { round: self.controller.generation(), player: identity, }); - self.afterburn_cleanup.extend(self.afterburns.take_removals()); } - self.cancel_chicken_purchase(slot); - self.healthshot_purchases.remove(&slot); - self.engine_actions - .retain(|action| !matches!(action, EngineAction::HealthshotPurchase { task, .. } if task.player.slot == slot)); + self.ordinary_chickens.cancel_purchase(slot, &mut self.engine_actions); + self.healthshot.cancel_purchase(slot, &mut self.engine_actions); self.chickens.clear_slot(slot); - self.chicken_use_buttons.remove(&slot); - self.native_self_damage_shots.remove(&slot); + self.ordinary_chickens.forget_input(slot); + self.combat.forget_player(slot); self.pending_takeovers.retain(|pending| pending.slot != slot); if let Err(error) = self.suicides.forget(slot) { self.record_fault(Fault::global(error)); } - self.combat.remove(&slot); - self.delayed_damage - .retain(|hit| hit.target.player.slot != slot && hit.source.player.slot != slot); - self.random_heals - .retain(|receipt| receipt.target.player.slot != slot && receipt.source.player.slot != slot); - self.reflections - .retain(|hit| hit.target.player.slot != slot && hit.source.player.slot != slot); self.refills.cancel_player(slot); self.projectiles .retire_player(slot, self.players.identity(slot).map(|player| player.pawn_handle)); @@ -5418,11 +3597,11 @@ impl Runtime { } self.welcomes.retain(|(identity, _)| identity.slot != slot); self.pending.retain(|(task, _, _)| task.player.slot != slot); - self.respawns.retain(|(task, _, _, _)| task.player.slot != slot); - self.round_respawns.retain(|(task, ..)| task.player.slot != slot); + self.respawning.cancel_player_respawns(slot); } fn retire_effect(&mut self, slot: i32) { + self.cancel_grapple_player(slot); if let Err(error) = self.night_vision.remove_player(slot) { self.record_fault(Fault::global(error)); } @@ -5431,9 +3610,9 @@ impl Runtime { } let has_pending_loadout = self.effects.get(&slot).is_some_and(Effect::has_pending_loadout); if has_pending_loadout && self.controller.current_mode().is_some_and(|mode| mode.c4_count.is_some()) { - self.c4_assigned = false; + self.suicides.c4_assigned = false; self.engine_actions - .retain(|action| !matches!(action, EngineAction::GrantC4(task, _) if task.player.slot == slot)); + .retain(|action| !matches!(action, EngineAction::Suicide(suicide::Action::GrantC4(task, _)) if task.player.slot == slot)); } let Some(effect) = self.effects.remove(&slot) else { return }; let index = self.retired_effects.len(); @@ -5479,25 +3658,33 @@ impl Runtime { } fn cleanup_effects_with_round_lifetime(&mut self, round_end: bool, round_transition: bool) { + self.cancel_all_grapples(grapple::StopReason::RoundEnded); self.settling_loadouts.clear(); if let Err(error) = self.retry_third_person_map_detach() { self.record_fault(Fault::global(error)); } - self.weapon_inventory.clear(); + self.public_properties.clear_round_inventory(); if let Err(error) = self.night_vision.cleanup_all() { self.record_fault(Fault::global(error)); } if round_transition { self.clear_chicken_round_work(); self.advance_chicken_round(self.controller.generation()); - self.suicide_feedback_cleanup - .extend(self.suicide_feedback.take_expired(s2sdk::GetGameTime())); + self.suicides.feedback.expire(s2sdk::GetGameTime()); } else { self.cleanup_ordinary_chickens(); } - self.healthshot_purchases.clear(); + self.healthshot.clear_round(); + self.clear_regions_round(); + self.cleanup_composed(); + self.shooting = shooting::State::default(); + self.stop_he_guidance_for_cleanup(); + self.teamkills = teamkill::State::default(); self.afterburns.clear_all(); - self.afterburn_cleanup.extend(self.afterburns.take_removals()); + + if let Err(error) = self.air_strafe.apply(false) { + self.record_fault(error); + } if let Err(error) = self.ground_reverse.apply(None) { self.record_fault(error); } @@ -5514,13 +3701,9 @@ impl Runtime { self.record_fault(Fault::global(error)); } if !round_transition { - self.suicide_feedback_cleanup.extend(self.suicide_feedback.take_all()); + self.suicides.feedback.clear(); } - self.native_self_damage_shots.clear(); self.combat.clear(); - self.reflections.clear(); - self.delayed_damage.clear(); - self.random_heals.clear(); self.center_display = None; self.refills.cancel_all(); self.impacts.clear(); @@ -5530,11 +3713,13 @@ impl Runtime { self.team_match = None; self.periodic_movement = None; self.money_income = None; - self.c4_assigned = false; - self.engine_actions.clear(); - self.respawns.clear(); - self.round_respawns.clear(); - self.low_health_finishes.clear(); + self.suicides.c4_assigned = false; + self.death_explosives = suicide::DeathExplosions::default(); + self.engine_actions.retain(|action| { + matches!(action, EngineAction::HeGuidanceFuseRestore(_)) + || (round_end && matches!(action, EngineAction::Suicide(suicide::Action::DeathBlast(_)))) + }); + self.respawning.clear(); let bomb_cleanup = if round_end { self.bombs.cleanup_after_round_end(self.controller.generation()) } else { @@ -5574,324 +3759,30 @@ impl Runtime { } pub fn shutdown(&mut self) -> Result<(), String> { // Native hook cleanup runs before Runtime shutdown, so a configured healthshot override is no longer wanted. - self.healthshot_hooks_ready = false; + self.healthshot.stop_hooks(); self.ground_reverse.retry_cleanup(); - self.restore_duck_speed(); - self.restore_model_scales(); + self.air_strafe.retry_cleanup(); + self.public_properties.restore_all(); self.welcomes.clear(); self.bombs.acknowledge_shutdown_removals(); self.cleanup_effects(false); self.restore_team_names(); - if let Err(error) = self.healthshot_parameters.set_healthshot_override(false) { + if let Err(error) = self.healthshot.restore() { self.record_fault(error); } - self.healthshot_override_active = false; - if self.cleanup_complete() && self.duck_speed.is_empty() && self.model_scales.is_empty() { + if self.cleanup_complete() && self.public_properties.is_restored() { Ok(()) } else { Err("owned properties or ConVars remain unrestored; snapshots retained for shutdown retry".into()) } } - pub fn track_suicide_feedback(&mut self, handle: i32, now: f32) -> bool { - (now + crate::suicide::FEEDBACK_LIFETIME).is_finite() && self.suicide_feedback.track(handle, now + crate::suicide::FEEDBACK_LIFETIME) - } - - pub fn take_suicide_feedback_cleanup(&mut self) -> Vec { - std::mem::take(&mut self.suicide_feedback_cleanup) - } - fn restore_team_names(&mut self) { if let Err(error) = self.team_names.restore() { self.record_fault(Fault::global(error)); } } - fn suicide_enabled(&self) -> bool { - self.classic_enabled() && active_combat_phase(self.controller.phase()) && self.controller.current_mode().is_some_and(|mode| mode.suicide) - } - - fn c4_purchase_enabled(&self, start: bool) -> bool { - self.classic_enabled() - && active_combat_phase(self.controller.phase()) - && self - .controller - .current_mode() - .is_some_and(|mode| if start { mode.suicide } else { mode.c4_buy }) - } - - fn qualifying_c4(&self, player: LivePlayer) -> Option { - s2sdk::GetClientWeapons(player.slot) - .iter() - .copied() - .find(|weapon| crate::suicide::real_c4(player, *weapon) && !self.bombs.excludes_suicide_c4(player, *weapon)) - } - - fn request_chicken(&mut self, slot: i32) -> Result { - if !self.chicken_ready || !self.classic_enabled() || !active_combat_phase(self.controller.phase()) || !self.ordinary_chickens_enabled() { - return Err(self.text(slot, "chicken.unavailable", &[])); - } - let player = LivePlayer::resolve(slot).ok_or(self.text(slot, "player.alive_required", &[]))?; - if !matches!(s2sdk::GetClientTeam(slot) as i32, 2 | 3) { - return Err(self.text(slot, "chicken.team_required", &[])); - } - let task = self.combat_task(player).ok_or(self.text(slot, "player.life_pending", &[]))?; - if self.chicken_purchases.contains_key(&slot) { - return Err(self.text(slot, "chicken.pending", &[])); - } - let config = self.controller.config().ok_or(self.text(slot, "config.unavailable", &[]))?; - let price = config.prices.chicken_cash; - let player_origin = s2sdk::GetEntityAbsOrigin(player.pawn_handle); - if !player_origin.x.is_finite() || !player_origin.y.is_finite() || !player_origin.z.is_finite() { - return Err(self.text(slot, "chicken.position_invalid", &[])); - } - self.chicken_purchases.insert(slot, task); - self.engine_actions.push(EngineAction::ChickenPurchase { - task, - player, - price, - origin: plugify::Vec3 { - x: player_origin.x + 64.0, - y: player_origin.y, - z: player_origin.z + 4.0, - }, - }); - Ok(self.text(slot, "chicken.request", &[("price", &price.to_string())])) - } - - fn request_suicide(&mut self, slot: i32, start: bool) -> Result { - if !self.c4_purchase_enabled(start) { - return Err(self.text(slot, "c4.unavailable", &[])); - } - let player = LivePlayer::resolve(slot).ok_or(self.text(slot, "player.alive_required", &[]))?; - let task = self.combat_task(player).ok_or(self.text(slot, "player.life_pending", &[]))?; - if self.suicides.buying.get(&slot) == Some(&task) { - return Err(self.text(slot, "c4.pending", &[])); - } - if self.suicides.active(player) { - return Err(self.text(slot, "suicide.started", &[])); - } - if let Some(c4) = self.qualifying_c4(player) { - if self.suicide_enabled() { - self.suicides.qualify(task, player, c4); - } - if start { - self.suicides.begin(slot, s2sdk::GetGameTickCount(), s2sdk::GetGameTime())?; - } - return Ok(if self.suicide_enabled() { - self.text(slot, "c4.owned_suicide", &[]) - } else { - self.text(slot, "c4.owned", &[]) - }); - } - if self.suicides.pending.iter().any(|action| action.task() == task) { - return Err(self.text(slot, "c4.pending", &[])); - } - if s2sdk::GetClientTeam(slot) as i32 != 2 { - return Err(self.text(slot, "c4.t_required", &[])); - } - let price = self.controller.config().map_or(10_000, |config| config.prices.c4_cash); - self.suicides.buying.insert(slot, task); - self.suicides - .pending - .push(crate::suicide::Action::Purchase { task, player, start, price }); - Ok(self.text(slot, "c4.request", &[("price", &price.to_string())])) - } - - fn update_suicides(&mut self, tick: i32) -> Vec { - if !self.suicide_enabled() { - let mut due = Vec::new(); - for action in std::mem::take(&mut self.suicides.pending) { - match action { - crate::suicide::Action::Purchase { .. } => due.push(EngineAction::Suicide(action)), - crate::suicide::Action::Finish { - after_round_end: true, - tick: queued, - .. - } if self.action_valid(&EngineAction::Suicide(action)) => { - if round_end_finish_due(tick, queued) { - due.push(EngineAction::Suicide(action)); - } else { - self.suicides.pending.push(action); - } - } - _ => {} - } - } - return due; - } - let now = s2sdk::GetGameTime(); - let mut failures = Vec::new(); - for slot in 0..s2sdk::GetMaxClients() { - let Some(player) = LivePlayer::resolve(slot) else { continue }; - let Some(task) = self.combat_task(player) else { continue }; - if let Some(entry) = self.suicides.entries.get(&slot) - && entry.task != task - { - // A new life may reuse the same pawn; its fresh properties are not ours. - self.suicides.entries.remove(&slot); - } - if let Some(c4) = self.qualifying_c4(player) { - self.suicides.qualify(task, player, c4); - } - let Some(entry) = self.suicides.entries.get_mut(&slot) else { continue }; - if let Some(sequence) = entry.sequence.as_mut() { - if sequence.take_due(tick, now) { - self.suicides.pending.push(crate::suicide::Action::Blast { task, player }); - } - } else if !crate::suicide::real_c4(player, entry.c4) { - self.suicides.entries.remove(&slot); - } else { - let look = crate::funrounds_native::GetLookAtWeaponButtonState(player.pawn_handle); - let edge = look == 1 && !entry.look_down; - entry.look_down = look == 1; - if edge - && s2sdk::GetClientActiveWeapon(slot) == entry.c4 - && let Err(error) = self.suicides.begin(slot, tick, now) - { - failures.push(error); - } - } - } - if let Some(error) = failures.pop() { - self.handle_fault(Fault::mechanism(Mechanism::Suicide, error)); - } - let pending = std::mem::take(&mut self.suicides.pending); - let mut due = Vec::new(); - for action in pending { - if matches!(action, crate::suicide::Action::Finish { tick: queued, .. } if tick <= queued) { - self.suicides.pending.push(action); - } else { - due.push(EngineAction::Suicide(action)); - } - } - due - } - - pub fn blocks_suicide_pickup(&self, pawn: i32, controller: i32) -> bool { - self.suicide_enabled() - && self.suicides.entries.values().any(|entry| { - entry.player.pawn_handle == pawn - && entry.player.controller_handle == controller - && entry.sequence.is_some() - && self.combat_task(entry.player) == Some(entry.task) - }) - } - - pub fn existing_suicide_c4(&self, player: LivePlayer) -> Option { - self.qualifying_c4(player) - } - - pub fn suicide_buyer_current(&self, action: crate::suicide::Action) -> bool { - self.on_game_thread() - && self.players.validates_connection(action.task().player) - && self.controllers.get(&action.player().slot) == Some(&action.player().controller_handle) - } - - pub fn finish_suicide_purchase(&mut self, action: crate::suicide::Action, result: Result) { - let crate::suicide::Action::Purchase { task, player, start, .. } = action else { - return; - }; - if self.suicides.buying.get(&player.slot) == Some(&task) { - self.suicides.buying.remove(&player.slot); - } - if !self.action_valid(&EngineAction::Suicide(action)) { - return; - } - let message = match result { - Ok(c4) => { - if self.suicide_enabled() { - self.suicides.qualify(task, player, c4); - } - if start && let Err(error) = self.suicides.begin(player.slot, s2sdk::GetGameTickCount(), s2sdk::GetGameTime()) { - self.handle_fault(Fault::mechanism(Mechanism::Suicide, error)); - } - crate::i18n::Message::new(if start { - "c4.purchased_start" - } else if self.suicide_enabled() { - "c4.purchased_inspect" - } else { - "c4.purchased" - }) - } - Err(error) => self.purchase_error(player.slot, error), - }; - crate::i18n::send_chat(player.slot, &self.message(player.slot, message)); - } - - pub fn prepare_suicide_blast(&mut self, action: crate::suicide::Action) -> Result, Fault> { - let source = action.player(); - let origin = s2sdk::GetEntityAbsOrigin(source.pawn_handle); - let tick = s2sdk::GetGameTickCount(); - let self_amount = s2sdk::GetClientHealth(source.slot) as f32 * 10.0; - self.suicides.pending.push(crate::suicide::Action::Finish { - task: action.task(), - player: source, - amount: self_amount, - tick, - after_round_end: false, - }); - let mut targets = Vec::new(); - for slot in 0..s2sdk::GetMaxClients() { - let Some(player) = LivePlayer::resolve(slot).filter(|player| *player != source) else { - continue; - }; - let Some(task) = self.combat_task(player) else { continue }; - let position = s2sdk::GetEntityAbsOrigin(player.pawn_handle); - let distance = ((origin.x - position.x).powi(2) + (origin.y - position.y).powi(2) + (origin.z - position.z).powi(2)).sqrt(); - let amount = funrounds_core::suicide_blast_damage(s2sdk::GetClientHealth(slot), distance); - if amount <= 0.0 { - continue; - } - if let Some(sequence) = self.suicides.entries.get_mut(&slot).and_then(|entry| entry.sequence.as_mut()) { - sequence.chain_next_tick(tick); - continue; - } - targets.push((task, player, amount)); - } - for name in [ - "mp_friendlyfire", - "ff_damage_reduction_bullets", - "ff_damage_reduction_grenade", - "ff_damage_reduction_other", - ] { - self.suicides.ff.set_number(name, 1.0)?; - } - Ok(targets) - } - - pub fn prepare_suicide_finish(&self, action: crate::suicide::Action) -> Option { - let crate::suicide::Action::Finish { player, amount, .. } = action else { - return None; - }; - if !self.action_valid(&EngineAction::Suicide(action)) { - return None; - } - lethal_suicide_finish_amount(amount, s2sdk::GetClientHealth(player.slot)) - } - - pub fn suicide_target_valid(&self, task: PlayerTask, player: LivePlayer) -> bool { - self.suicide_enabled() && self.combat_task(player) == Some(task) && LivePlayer::resolve(player.slot) == Some(player) - } - - fn suicide_hurt(&mut self, event: usize, victim: i32, attacker: i32) { - if !crate::damage::internal_suicide_hurt(victim, attacker) { - return; - } - let Some(player) = LivePlayer::resolve_present(victim) else { return }; - let Some(task) = self.combat_task(player) else { return }; - if let Some((expected, life)) = self.combat.get_mut(&victim).filter(|(expected, _)| *expected == task) { - let _ = expected; - life.lose_native_armor(s2sdk::GetEventInt(event, &Str::from_str("dmg_armor"))); - } - } - - pub fn finish_suicide_blast(&mut self) { - if let Err(error) = self.suicides.ff.restore() { - self.handle_fault(Fault::global(error)); - } - } - pub(crate) fn text(&self, slot: i32, key: &'static str, args: &[(&str, &str)]) -> String { self.texts .render(&crate::i18n::language(slot, &self.texts), key, args) @@ -5977,7 +3868,7 @@ impl Runtime { ); let (hostage_rescue_available, hostage_rescue_reason) = self.hostage_rescue_status(); let details = format!( - "config={}\ncapabilities={:?}\nexcluded={}\ncapability_reasons={}\nhostage_rescue_compat_enabled={}\nhostage_rescue_compat_available={}\nhostage_rescue_compat_reason={}", + "config={}\ncapabilities={:?}\nexcluded={}\ncapability_reasons={}\nhostage_rescue_compat_enabled={}\nhostage_rescue_compat_available={}\nhostage_rescue_compat_reason={}\nhostage_rescue_compat_owner={}", self.config_path.display(), self.controller.capabilities(), self.controller @@ -6000,6 +3891,7 @@ impl Runtime { self.controller.hostage_rescue_compat_enabled(), hostage_rescue_available, hostage_rescue_reason, + "funrounds", ); Ok(format_status( &summary, @@ -6048,19 +3940,18 @@ impl Runtime { } if !enabled { self.ground_reverse.retry_cleanup(); + self.air_strafe.retry_cleanup(); self.cleanup_effects(false); self.restore_team_names(); self.welcomes.clear(); self.hostage_rescue.clear_attempts(); } if enabled && !was_enabled { - self.restore_duck_speed(); - self.restore_model_scales(); + self.public_properties.restore_all(); } self.controller.set_enabled(enabled); if !enabled { - self.restore_duck_speed(); - self.restore_model_scales(); + self.public_properties.restore_all(); self.finish_recovery(); } Ok(self.text(slot, "command.enabled", &[("enabled", &enabled.to_string())])) @@ -6098,6 +3989,7 @@ impl Runtime { } if let Some(shield) = self .combat + .lives .get(&slot) .and_then(|(task, life)| (Some(task.player) == self.players.identity(slot)).then(|| life.shield()).flatten()) { @@ -6149,16 +4041,6 @@ impl Runtime { } } -fn sync_shield_hud(player: LivePlayer, armor: i32) -> Result<(), Fault> { - if s2sdk::GetClientArmor(player.slot) != armor { - s2sdk::SetClientArmor(player.slot, armor); - if s2sdk::GetClientArmor(player.slot) != armor { - return Err(Fault::mechanism(Mechanism::EnergyShield, "shield armor HUD write failed")); - } - } - Ok(()) -} - fn event_weapon_snapshot(player: LivePlayer, attacker: PlayerIdentity, event_weapon: &str) -> Option { if LivePlayer::resolve(player.slot) != Some(player) { return None; @@ -6247,7 +4129,11 @@ fn weapon_identity_is_current(player: LivePlayer, weapon: &FiredWeapon) -> bool fn format_status(summary: &str, faults: &Faults, cleanup_pending: bool, details: &str) -> String { format!( "{summary} recovery={:?} cleanup_pending={cleanup_pending}\nfaults={}\n{details}", - faults.recovery, + if cleanup_pending && faults.recovery == Recovery::Ready { + Recovery::Recovering + } else { + faults.recovery + }, faults.reasons(), ) } @@ -6257,66 +4143,6 @@ fn read_config(path: &std::path::Path) -> Result { Config::parse(&source).map_err(|error| format!("{}: {error}", path.display())) } -pub(crate) fn remove_native_c4(player: LivePlayer, handles: &[i32]) -> Result<(), Fault> { - if LivePlayer::resolve(player.slot) != Some(player) { - return Err(Fault::cancelled("player identity changed before native C4 cleanup")); - } - for handle in handles.iter().copied() { - if !s2sdk::IsValidEntHandle(handle) || s2sdk::GetEntityClassname(handle).as_str() != "weapon_c4" { - continue; - } - if s2sdk::GetEntityOwner(handle) != player.pawn_handle { - return Err(Fault::cancelled("native C4 ownership changed before cleanup")); - } - s2sdk::RemoveWeapon(player.slot, handle); - if LivePlayer::resolve(player.slot) != Some(player) { - return Err(Fault::cancelled("player identity changed during native C4 cleanup")); - } - if s2sdk::GetClientWeapons(player.slot).iter().any(|current| *current == handle) { - return Err(Fault::mechanism(Mechanism::NoC4, "engine retained the native C4 after removal")); - } - if s2sdk::IsValidEntHandle(handle) { - if s2sdk::GetEntityClassname(handle).as_str() != "weapon_c4" - || !matches!(s2sdk::GetEntityOwner(handle), owner if owner == -1 || owner == player.pawn_handle) - { - return Err(Fault::cancelled("native C4 ownership changed during cleanup")); - } - s2sdk::RemoveEntity(handle); - if !crate::game::engine_removal_acknowledged(handle) { - return Err(Fault::mechanism(Mechanism::C4Assignment, "native C4 entity survived cleanup")); - } - } - } - Ok(()) -} - -fn mode65_self_damage(damage: &crate::damage::Damage, pawn: i32, health: i32) -> bool { - let damage_type = damage.damage_type; - let native_self = damage.inflictor == pawn; - // mp_weapon_self_inflict_amount uses pawn-attributed DMG_GENERIC, not DMG_BULLET. - native_self && (damage_type == 0 || damage_type == 0x0200_0000 && health <= 1 && damage.amount == 1.0) - || damage.weapon_kind == 1 && damage_type & crate::damage::DMG_BULLET != 0 -} - -fn self_damage_allowed(mode: &funrounds_core::Mode, damage: &crate::damage::Damage, pawn: i32, health: i32) -> bool { - if damage.damage_type & 32 != 0 { - return false; - } - match mode.self_damage { - Some(SelfDamage::MissPenalty) => mode65_self_damage(damage, pawn, health), - Some(SelfDamage::Native { amount }) => amount > 0.0, - None => false, - } -} - -fn numeric_self_damage_enters_health(allowed_self: bool, blocked: bool, incoming: f32) -> bool { - allowed_self && !blocked && incoming.is_finite() && incoming > 0.0 -} - -fn delayed_damage_protection_valid(protection_enabled: bool, target: PlayerTask, current: Option<(PlayerTask, bool)>) -> bool { - !protection_enabled || current.is_some_and(|(task, protected)| task == target && !protected) -} - fn observe_lifecycle_tick(last: &mut Option, tick: i32, event: Option<&str>) -> bool { // Damage callbacks can rewind ticks; round boundaries can precede the first new-map frame. if event.is_some_and(|name| !matches!(name, "round_prestart" | "round_start")) { @@ -6348,14 +4174,6 @@ fn round_selection_waits(game_warmup: bool, effects_ready_after_cleanup: bool) - game_warmup || !effects_ready_after_cleanup } -fn healthshot_override_settled(wanted: bool, active: bool, parameters_restored: bool) -> bool { - wanted == active && (wanted || parameters_restored) -} - -fn public_property_cleanup_complete(enabled: bool, duck_speed_empty: bool, model_scales_empty: bool) -> bool { - enabled || (duck_speed_empty && model_scales_empty) -} - fn warmup_reactivation_needed(state: Option, warmup_active: bool, phase: Phase, activation_pending: bool, activation_available: bool) -> bool { state == Some(true) && warmup_active && phase != Phase::Warmup && !activation_pending && activation_available } @@ -6376,10 +4194,6 @@ fn log(message: &str) { s2sdk::PrintToServer(&Str::from_str(&format!("[FunRounds] {message}"))); } -fn respawn_target_valid(expected: LivePlayer, current: Option, team: i32, current_team: i32, alive: bool) -> bool { - current == Some(expected) && matches!(team, 2 | 3) && current_team == team && !alive -} - fn random_kill_loadout_start(mode: &funrounds_core::Mode, rng: &mut impl rand::Rng) -> Vec { // Resample the same configured equipment categories at each life, not just at round start. mode.select_equipment(rng) @@ -6392,44 +4206,6 @@ fn warmup_spawn_needed(identity: Option, player: LivePlayer, eff identity.is_none_or(|identity| identity.pawn_handle != player.pawn_handle as u32) || !(effect_applied || loadout_pending) } -fn round_respawn_task(players: &PlayerTracker, round: RoundGeneration, player: LivePlayer) -> Option { - if let Some(identity) = players - .identity(player.slot) - .filter(|identity| identity.pawn_handle == player.pawn_handle as u32) - { - return Some(PlayerTask { player: identity, round }); - } - players.respawn_task(player.slot, round) -} - -fn round_respawn_task_valid(players: &PlayerTracker, task: PlayerTask, round: RoundGeneration, player: LivePlayer) -> bool { - task.player.slot == player.slot - && if task.player.pawn_handle == u32::MAX { - players.validates_respawn(task, round) - } else { - players.validates(task, round, player.pawn_handle as u32) - } -} - -fn round_respawn_target_valid( - all_respawn: bool, - phase: Phase, - expected: LivePlayer, - current: Option, - team: i32, - current_team: i32, -) -> bool { - all_respawn && phase != Phase::Idle && current == Some(expected) && matches!(team, 2 | 3) && current_team == team -} - -fn lifesteal_eligible(attacker: i32, victim: i32, attacker_alive: bool) -> bool { - attacker >= 0 && victim >= 0 && attacker != victim && attacker_alive -} - -fn respawn_window_open(phase: Phase, remaining: Option) -> bool { - phase == Phase::Preparing || phase == Phase::Warmup || (phase == Phase::Running && remaining.is_none_or(|seconds| seconds > 0.0)) -} - fn center_display_due(current: bool, phase: Phase, tick: i32, scheduled: i32) -> bool { current && phase != Phase::Idle && tick > scheduled } @@ -6475,7 +4251,7 @@ mod tests { false, &details, ); - let parts = crate::commands::status_reply_parts(&status).collect::>(); + let parts = crate::commands::line_reply_parts(&status).collect::>(); assert!(parts[0].ends_with("recovery=Stopped cleanup_pending=false")); assert_eq!(parts[1], "faults=Global:[created action failed after cancellation]"); assert!(parts[2].starts_with("capabilities=")); @@ -6513,43 +4289,6 @@ mod tests { assert_eq!(super::separate_console_output("[FunRounds] mode".into()), "\n[FunRounds] mode"); } - #[test] - fn miss_penalty_respects_native_self_damage_and_final_health_point() { - let mut mode = funrounds_core::Config::parse(include_str!("../../../config/funrounds.example.toml")) - .unwrap() - .modes - .remove(0); - mode.self_damage = Some(funrounds_core::SelfDamage::MissPenalty); - let mut damage = crate::damage::Damage { - victim: 42, - attacker: 42, - inflictor: 42, - weapon_kind: 0, - hit_group: -1, - traced_head: false, - amount: 36.0, - damage_type: 0, - weapon: -1, - weapon_class: None, - skip_plugin_rules: false, - }; - assert!(super::self_damage_allowed(&mode, &damage, 42, 200)); - assert!(!super::self_damage_allowed(&mode, &damage, 43, 200)); - for damage_type in [8, 64, 256, 0x0200_0000] { - damage.damage_type = damage_type; - assert!(!super::self_damage_allowed(&mode, &damage, 42, 200)); - } - damage.amount = 1.0; - assert!(super::self_damage_allowed(&mode, &damage, 42, 1)); - assert!(!super::self_damage_allowed(&mode, &damage, 42, 2)); - damage.damage_type = 0; - assert!(super::self_damage_allowed(&mode, &damage, 42, 1)); - damage.damage_type = 2; - assert!(!super::self_damage_allowed(&mode, &damage, 42, 200)); - damage.weapon_kind = 1; - assert!(super::self_damage_allowed(&mode, &damage, 42, 200)); - } - #[test] fn localized_team_info_distinguishes_waiting_and_running_clocks() { let texts = funrounds_core::TextBundle::embedded("zh-CN").unwrap(); @@ -6621,58 +4360,6 @@ mod tests { } } - #[test] - fn lifesteal_excludes_self_world_and_dead_attackers() { - assert!(super::lifesteal_eligible(1, 2, true)); - assert!(!super::lifesteal_eligible(1, 1, true)); - assert!(!super::lifesteal_eligible(-1, 2, true)); - assert!(!super::lifesteal_eligible(1, -1, true)); - assert!(!super::lifesteal_eligible(1, 2, false)); - } - - #[test] - fn team_respawn_works_during_freeze_without_starting_the_score_timer() { - use funrounds_core::Phase; - assert!(super::respawn_window_open(Phase::Preparing, None)); - assert!(super::respawn_window_open(Phase::Running, Some(3.0))); - assert!(!super::respawn_window_open(Phase::Running, Some(0.0))); - assert!(super::respawn_window_open(Phase::Running, None)); - assert!(!super::respawn_window_open(Phase::Idle, Some(30.0))); - } - - #[test] - fn respawn_rejects_changed_handles_team_and_external_resurrection() { - let player = crate::game::LivePlayer { - slot: 1, - controller_handle: 0x4001, - pawn_handle: 0x4002, - }; - assert!(super::respawn_target_valid(player, Some(player), 2, 2, false)); - assert!(!super::respawn_target_valid(player, Some(player), 2, 3, false)); - assert!(!super::respawn_target_valid(player, Some(player), 2, 2, true)); - assert!(!super::respawn_target_valid(player, None, 2, 2, false)); - assert!(!super::respawn_target_valid( - player, - Some(crate::game::LivePlayer { - pawn_handle: 0x8002, - ..player - }), - 2, - 2, - false - )); - assert!(!super::respawn_target_valid( - player, - Some(crate::game::LivePlayer { - controller_handle: 0x8001, - ..player - }), - 2, - 2, - false - )); - } - #[test] fn map_change_discards_active_and_retired_entity_snapshots() { let mut effects = HashMap::from([(1, "active")]); diff --git a/crates/funrounds-plugin/src/runtime/afterburn.rs b/crates/funrounds-plugin/src/runtime/afterburn.rs new file mode 100644 index 0000000..1b04339 --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/afterburn.rs @@ -0,0 +1,162 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::{EngineAction, Runtime, active_combat_phase}; +use crate::process_afterburn_ignite; +use crate::{ + fault::{Fault, Mechanism}, + game::{self, LivePlayer}, + s2sdk, +}; +use funrounds_core::PlayerTask; + +impl Runtime { + pub(super) fn managed_burn_enabled(&self) -> bool { + self.classic_enabled() + && active_combat_phase(self.controller.phase()) + && self.faults.capabilities().afterburn + && self + .controller + .current_mode() + .is_some_and(|mode| mode.afterburn.is_some() || mode.hot_floor.is_some()) + } + + pub(super) fn afterburn_settings(&self) -> Option { + (self.classic_enabled() && active_combat_phase(self.controller.phase()) && self.faults.capabilities().afterburn) + .then(|| self.controller.current_mode().and_then(|mode| mode.afterburn)) + .flatten() + } + + pub(crate) fn afterburn_action_valid(&self, task: PlayerTask, player: LivePlayer) -> bool { + self.managed_burn_enabled() + && self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) + && LivePlayer::resolve(player.slot) == Some(player) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + && self.afterburns.is_active(task, player, f64::from(s2sdk::GetGameTime())) + } + + pub(crate) fn begin_afterburn_ignite(&mut self, task: PlayerTask, player: LivePlayer, now: f64) -> Option { + self.afterburn_action_valid(task, player) + .then(|| self.afterburns.begin_ignite(task, player, now)) + .flatten() + } + + pub(crate) fn afterburn_attachment_seen(&mut self, task: PlayerTask, player: LivePlayer, now: f64, attached: Option) { + let _ = self.afterburns.observe_attachment(task, player, now, attached); + } + + pub(crate) fn record_afterburn_flame(&mut self, task: PlayerTask, player: LivePlayer, flame: i32, now: f64) -> bool { + if !self.afterburn_action_valid(task, player) || !self.afterburns.record_flame(task, player, flame, now) { + return false; + } + if self.afterburns.hot_floor_active(task, player, now) { + self.record_regeneration_combat_for(task, now); + } + true + } + + pub(crate) fn afterburn_ignition_failed(&mut self, message: impl Into) { + self.handle_fault(Fault::mechanism(Mechanism::Afterburn, message)); + } + + pub(crate) fn take_afterburn_cleanup(&mut self) -> Vec { + self.afterburns.take_removals() + } + + pub(crate) fn queue_afterburn_ground_tick(&mut self, damage: &crate::damage::Damage, players: &game::DamagePlayers) { + if damage.inflictor == -1 || !s2sdk::IsValidEntHandle(damage.inflictor) { + return; + } + let (Some(settings), Some(player)) = (self.afterburn_settings(), players.victim) else { + return; + }; + let Some(task) = self.combat_task(player) else { return }; + let now = f64::from(s2sdk::GetGameTime()); + if crate::afterburn::genuine_ground_burn( + damage.skip_plugin_rules, + damage.damage_type, + s2sdk::GetEntityClassname(damage.inflictor).as_str(), + ) && self.afterburns.refresh_source(task, player, now, settings, false) + && self.afterburns.queue_ignite(task, player) + { + self.engine_actions.push(EngineAction::Afterburn(Action::Ignite { task, player })); + } + } + + pub(crate) fn afterburn_flame_damage(&self, damage: &crate::damage::Damage, players: &game::DamagePlayers) -> Option { + if damage.amount <= 0.0 + || !damage.amount.is_finite() + || damage.inflictor == -1 + || !s2sdk::IsValidEntHandle(damage.inflictor) + || !crate::afterburn::flame_tick_damage( + damage.skip_plugin_rules, + damage.damage_type, + s2sdk::GetEntityClassname(damage.inflictor).as_str(), + ) + { + return None; + } + let player = players.victim?; + if !self.managed_burn_enabled() { + return None; + } + let task = self.combat_task(player)?; + self.afterburns + .owns_flame(task, player, damage.inflictor) + .then(|| crate::afterburn::flame_attached_to(player, damage.inflictor)) + .filter(|attached| *attached) + .and_then(|_| { + self.afterburns + .tick_damage(task, player, f64::from(s2sdk::GetGameTime()), s2sdk::GetClientHealth(player.slot)) + }) + } + + pub(super) fn update_afterburns(&mut self, now: f64) { + self.afterburns.clear_round(self.controller.generation()); + let entries = self.afterburns.entries(); + for (task, player, _) in entries { + if !self.managed_burn_enabled() + || !self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) + || LivePlayer::resolve(player.slot) != Some(player) + || self.controllers.get(&player.slot) != Some(&player.controller_handle) + { + self.afterburns.clear_life(task); + continue; + } + let attached = crate::afterburn::attached_effect(player); + if self.afterburns.observe_attachment(task, player, now, attached) { + self.engine_actions.push(EngineAction::Afterburn(Action::Ignite { task, player })); + } + } + } +} + +pub enum Action { + Ignite { task: PlayerTask, player: LivePlayer }, + Remove(i32), +} + +impl Action { + pub(super) fn involves(&self, slots: &[i32]) -> bool { + match self { + Self::Ignite { task, .. } => slots.contains(&task.player.slot), + Self::Remove(_) => false, + } + } +} + +impl Runtime { + pub(super) fn afterburn_action_current(&self, action: &Action) -> bool { + match action { + Action::Ignite { task, player } => self.afterburn_action_valid(*task, *player), + Action::Remove(_) => true, + } + } +} + +pub(crate) fn execute(action: Action) { + match action { + Action::Remove(handle) => crate::afterburn::remove_flame(handle), + Action::Ignite { task, player } => process_afterburn_ignite(task, player), + } +} diff --git a/crates/funrounds-plugin/src/runtime/chickens.rs b/crates/funrounds-plugin/src/runtime/chickens.rs new file mode 100644 index 0000000..2af7e7f --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/chickens.rs @@ -0,0 +1,814 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::{EngineAction, Runtime, active_combat_phase, log}; +use crate::{ + fault::{Fault, Recovery}, + game::{self, LivePlayer}, + s2sdk, +}; +use crate::{process_chicken_blast, process_chicken_eat, process_chicken_purchase, process_chicken_spawn}; +use funrounds_core::{Phase, PlayerIdentity, PlayerTask, PlayerTracker, RoundGeneration}; +use plugify::Str; +use std::collections::HashMap; + +#[derive(Clone, Debug, PartialEq, Eq)] +struct PendingChickenBlastKill { + round: RoundGeneration, + victim: PlayerIdentity, + tick: i32, + damage_frame_token: Option, + source: crate::chicken_entities::KillWeaponSource, +} + +impl PendingChickenBlastKill { + fn matches(&self, round: RoundGeneration, victim: PlayerIdentity, attacker: PlayerIdentity, tick: i32, frame_token: Option) -> bool { + self.round == round + && self.victim == victim + && self.source.attacker == attacker + && self.tick == tick + && self.damage_frame_token.is_none_or(|expected| frame_token == Some(expected)) + } +} + +fn chicken_weapon_source_readback_matches( + source: &crate::chicken_entities::KillWeaponSource, + owner: i32, + inventory: &[i32], + classname: &str, + item_definition: u16, +) -> bool { + owner == source.attacker.pawn_handle as i32 + && inventory.contains(&source.handle) + && source.classname == classname + && source.item_definition == item_definition +} + +fn capture_chicken_damage_weapon_source( + damage: crate::chicken_entities::EntityDamageSource, + players: &PlayerTracker, + controllers: &HashMap, +) -> Option { + let item_definition_reader = unsafe { crate::effects::__s2sdk_GetWeaponItemDefinition }.expect("required native ABI checked at startup"); + for slot in 0..s2sdk::GetMaxClients() { + let Some(player) = LivePlayer::resolve(slot) else { continue }; + if (s2sdk::GetClientTeam(slot) as i32) < 2 + || player.pawn_handle != damage.attacker + || controllers.get(&slot) != Some(&player.controller_handle) + { + continue; + } + let Some(attacker) = players + .identity(slot) + .filter(|identity| identity.pawn_handle == player.pawn_handle as u32) + else { + continue; + }; + let inventory = s2sdk::GetClientWeapons(slot); + for handle in [damage.ability, damage.inflictor] { + if handle == -1 + || !s2sdk::IsValidEntHandle(handle) + || s2sdk::GetEntityOwner(handle) != player.pawn_handle + || !inventory.iter().any(|owned| *owned == handle) + { + continue; + } + let classname = s2sdk::GetEntityClassname(handle).to_string(); + if !classname.starts_with("weapon_") { + continue; + } + let item_definition = unsafe { item_definition_reader(handle) }; + return Some(crate::chicken_entities::KillWeaponSource { + attacker, + handle, + classname, + item_definition, + }); + } + } + None +} + +pub(super) fn chicken_weapon_source_is_current( + source: &crate::chicken_entities::KillWeaponSource, + players: &PlayerTracker, + controllers: &HashMap, +) -> bool { + let Some(player) = LivePlayer::resolve(source.attacker.slot) else { + return false; + }; + if players.identity(player.slot) != Some(source.attacker) + || controllers.get(&player.slot) != Some(&player.controller_handle) + || player.pawn_handle != source.attacker.pawn_handle as i32 + { + return false; + } + if !s2sdk::IsValidEntHandle(source.handle) { + return false; + } + let owner = s2sdk::GetEntityOwner(source.handle); + let inventory = s2sdk::GetClientWeapons(player.slot).iter().copied().collect::>(); + let classname = s2sdk::GetEntityClassname(source.handle).to_string(); + let item_definition_reader = unsafe { crate::effects::__s2sdk_GetWeaponItemDefinition }.expect("required native ABI checked at startup"); + let item_definition = unsafe { item_definition_reader(source.handle) }; + chicken_weapon_source_readback_matches(source, owner, &inventory, &classname, item_definition) +} + +fn use_button_rising_edge(states: &mut HashMap, identity: PlayerIdentity, down: bool) -> bool { + let rising = down && !states.get(&identity.slot).is_some_and(|(old, was_down)| *old == identity && *was_down); + if down { + states.insert(identity.slot, (identity, true)); + } else if states.get(&identity.slot).is_some_and(|(old, _)| *old == identity) { + states.remove(&identity.slot); + } + rising +} + +#[derive(Default)] +pub(super) struct State { + pub(super) entities: crate::chicken_entities::Chickens, + pub(super) ready: bool, + follow_block_support: bool, + pub(super) use_buttons: HashMap, + pub(super) spawn_round: Option, + blast_kills: HashMap, + pub(super) cleanup: Vec, + pub(super) purchases: HashMap, +} + +impl State { + pub(super) fn new(ready: bool, follow_block_support: bool) -> Self { + Self { + ready, + follow_block_support, + ..Self::default() + } + } + + pub(super) fn cancel_purchase(&mut self, slot: i32, actions: &mut Vec) { + self.purchases.remove(&slot); + actions.retain(|action| !matches!(action, EngineAction::Chicken(Action::Purchase { task, .. }) if task.player.slot == slot)); + } + + pub(super) fn cancel_purchases_for_slots(&mut self, slots: &[i32]) { + self.purchases.retain(|slot, _| !slots.contains(slot)); + } + + pub(super) fn forget_input(&mut self, slot: i32) { + self.use_buttons.remove(&slot); + } + + pub(super) fn discard_map_state(&mut self) { + self.entities.discard_map_state(); + self.cleanup.clear(); + } + + fn finish_purchase(&mut self, task: PlayerTask) { + if self.purchases.get(&task.player.slot) == Some(&task) { + self.purchases.remove(&task.player.slot); + } + } + + fn clear_round_work(&mut self, actions: &mut Vec) { + self.use_buttons.clear(); + self.purchases.clear(); + self.blast_kills.clear(); + actions.retain(|action| { + !matches!( + action, + EngineAction::Chicken(Action::Spawn { .. } | Action::Blast { .. } | Action::Purchase { .. } | Action::Eat { .. }) + ) + }); + self.spawn_round = None; + } + + pub(super) fn clear_pending_chicken_blast_for_life(&mut self, identity: PlayerIdentity) { + self.blast_kills + .retain(|slot, pending| *slot != identity.slot && pending.victim != identity && pending.source.attacker != identity); + } + + pub(super) fn clear_pending_chicken_blast_for_slot(&mut self, slot: i32) { + self.blast_kills + .retain(|victim, pending| *victim != slot && pending.source.attacker.slot != slot); + } + + pub(super) fn expire_chicken_blast_kills(&mut self, tick: i32, round: RoundGeneration, players: &funrounds_core::PlayerTracker) { + self.blast_kills.retain(|slot, pending| { + pending.tick == tick + && pending.round == round + && players.identity(*slot) == Some(pending.victim) + && players.identity(pending.source.attacker.slot) == Some(pending.source.attacker) + }); + } + + pub(super) fn cleanup_complete(&self, round_transition: bool) -> bool { + (self.entities.is_empty() || (round_transition && self.entities.has_only_active_chickens())) && self.cleanup.is_empty() + } +} + +impl Runtime { + pub(crate) fn chicken_use_configured(&self) -> bool { + self.controller + .config() + .is_some_and(|config| config.chicken.is_some_and(|chicken| chicken.eating.enabled)) + } + + pub(crate) fn chicken_follow_block_supported(&self) -> bool { + self.ordinary_chickens.follow_block_support + } + + /// Following belongs to ordinary chicken ecology, independently from E eating. + pub(crate) fn chicken_follow_block_desired(&self) -> bool { + self.controller.enabled() && self.faults.recovery != Recovery::Stopped && self.ordinary_chickens_enabled() + } + + pub(crate) fn observe_chicken_use_target(&mut self, pawn_handle: i32, target_handle: i32, in_use: bool) { + let Some(player) = LivePlayer::resolve_pawn_owner(pawn_handle) else { + return; + }; + if self.controllers.get(&player.slot) != Some(&player.controller_handle) { + return; + } + let Some(identity) = self + .players + .identity(player.slot) + .filter(|identity| identity.pawn_handle == pawn_handle as u32) + else { + return; + }; + if !in_use { + use_button_rising_edge(&mut self.ordinary_chickens.use_buttons, identity, false); + return; + } + self.discover_ordinary_chicken(target_handle); + if !self.use_target_hook_ready + || !self.ordinary_chickens.ready + || !self.ordinary_chickens_enabled() + || !self.controller.enabled() + || !matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) + || !s2sdk::IsValidEntHandle(target_handle) + || s2sdk::GetEntityClassname(target_handle).as_str() != "chicken" + || !self.ordinary_chickens.entities.contains(target_handle, self.controller.generation()) + { + return; + } + let Some(config) = self.controller.config().and_then(|config| config.chicken) else { + return; + }; + let Some(mode) = self.controller.current_mode() else { return }; + if !config.eating.enabled_for_mode(mode.chicken_eating) { + return; + } + let Some(task) = self.combat_task(player) else { return }; + let current_health = s2sdk::GetClientHealth(player.slot); + let Some(base_health) = self.chickens.base_health(task).ok() else { + return; + }; + // A selector may report no target before finding a chicken during the same press. + // Only a valid consumable target spends this press; releases are polled independently. + if self + .ordinary_chickens + .use_buttons + .get(&identity.slot) + .is_some_and(|(old, down)| *old == identity && *down) + || !self.ordinary_chickens.entities.mark_consumed(target_handle, task.round) + { + return; + } + let now = f64::from(s2sdk::GetGameTime()); + let outcome = match self.chickens.consume(task, current_health, base_health, now, config, &mut self.rng) { + Ok(outcome) => outcome, + Err(_) => { + self.ordinary_chickens.entities.release_consumed(target_handle, task.round); + return; + } + }; + use_button_rising_edge(&mut self.ordinary_chickens.use_buttons, identity, true); + self.mark_chicken_target_claimed(identity, s2sdk::GetGameTickCount(), target_handle); + self.engine_actions.push(EngineAction::Chicken(Action::Eat { + task, + player, + chicken: target_handle, + outcome, + })); + } + + pub(crate) fn finish_chicken_use(&mut self, round: RoundGeneration, chicken: i32) { + self.ordinary_chickens.entities.remove_chicken(chicken, round); + self.public_properties.restore_model_scale(chicken); + } + + pub(super) fn release_chicken_use_buttons(&mut self) { + // The native target selector is not called on every released-input frame. + // Button state 0 is current down state; transition masks must not keep the latch held. + self.ordinary_chickens.use_buttons.retain(|slot, (identity, _)| { + self.players.identity(*slot) == Some(*identity) + && LivePlayer::resolve(*slot).is_some_and(|player| player.pawn_handle as u32 == identity.pawn_handle) + && s2sdk::GetClientButtons(*slot, 0) & (1 << 5) != 0 + }); + } + + pub(super) fn update_chicken_digestion(&mut self, now: f64) { + self.chickens.retain_round(self.controller.generation()); + let Some(config) = self.controller.config().and_then(|config| config.chicken) else { + return; + }; + if !now.is_finite() || now < 0.0 { + return; + } + for slot in 0..s2sdk::GetMaxClients() { + let Some(player) = LivePlayer::resolve(slot) else { continue }; + let Some(task) = self.combat_task(player) else { continue }; + let digestion_needed = !config.eating.enabled || matches!(self.chickens.undigested(task), Ok(count) if count > 0); + if digestion_needed { + let _ = self.chickens.digest_due(task, now, config); + } + } + } + + pub fn take_chicken_cleanup(&mut self) -> Vec { + std::mem::take(&mut self.ordinary_chickens.cleanup) + } + + pub fn finish_chicken_purchase(&mut self, task: PlayerTask) { + self.ordinary_chickens.finish_purchase(task); + } + + pub(crate) fn chicken_risk_finish_current(&self, task: PlayerTask, player: LivePlayer) -> bool { + // round_end advances the round generation and removes the chicken. The + // synchronous risk-blast continuation retains only this exact live eater. + self.classic_enabled() + && self.players.identity(player.slot) == Some(task.player) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + && LivePlayer::resolve(player.slot) == Some(player) + } + + pub fn chicken_buyer_identity_current(&self, task: PlayerTask, player: LivePlayer) -> bool { + self.on_game_thread() + && self.players.validates_connection(task.player) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + && LivePlayer::resolve_present(player.slot) == Some(player) + } + + pub(super) fn ordinary_chickens_enabled(&self) -> bool { + self.controller.config().is_some_and(|config| config.chicken.is_some()) + && self.controller.current_mode().is_some_and(|mode| mode.ordinary_chickens) + } + + pub(super) fn cleanup_ordinary_chickens(&mut self) { + self.clear_chicken_round_work(); + let registered = self.ordinary_chickens.entities.registered_handles(); + let chickens = self.ordinary_chickens.entities.clear(); + for handle in ®istered { + self.public_properties.restore_model_scale(*handle); + } + self.ordinary_chickens.cleanup.extend(chickens); + if self.public_properties.has_pending_restores() { + self.effects_ready = false; + } + crate::CHICKEN_DAMAGE_ACTIVE.store(false, std::sync::atomic::Ordering::Release); + } + + pub(super) fn clear_chicken_round_work(&mut self) { + self.chickens.clear_eating(); + self.ordinary_chickens.clear_round_work(&mut self.engine_actions); + } + + pub(super) fn advance_chicken_round(&mut self, round: RoundGeneration) { + self.advance_chicken_round_if_alive(round, |handle| { + if !s2sdk::IsValidEntHandle(handle) || s2sdk::GetEntityClassname(handle).as_str() != "chicken" { + return false; + } + crate::chicken_entities::health(handle).is_some_and(|(health, life_state)| health > 0 && life_state == 0) + }); + } + + pub(super) fn advance_chicken_round_if_alive(&mut self, round: RoundGeneration, alive: impl FnMut(i32) -> bool) { + self.ordinary_chickens.blast_kills.retain(|_, pending| pending.round == round); + let registered = self.ordinary_chickens.entities.registered_handles(); + let stale = self.ordinary_chickens.entities.advance_round(round, alive); + for handle in registered { + if !self.ordinary_chickens.entities.contains(handle, round) { + self.public_properties.restore_model_scale(handle); + } + } + self.ordinary_chickens.cleanup.extend(stale); + crate::CHICKEN_DAMAGE_ACTIVE.store( + self.ordinary_chickens.ready && self.controller.enabled() && self.ordinary_chickens_enabled(), + std::sync::atomic::Ordering::Release, + ); + } + + pub fn track_chicken(&mut self, round: RoundGeneration, handle: i32) -> bool { + if !self.ordinary_chickens.ready + || !self.ordinary_chickens_enabled() + || self.controller.generation() != round + || !matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) + || !self.ordinary_chickens.entities.track(handle, round) + { + return false; + } + self.public_properties.randomize_model_scale(handle, &mut self.rng); + crate::CHICKEN_DAMAGE_ACTIVE.store(true, std::sync::atomic::Ordering::Release); + true + } + + fn discover_ordinary_chickens(&mut self) { + if !self.ordinary_chickens.ready || !self.controller.enabled() || !self.ordinary_chickens_enabled() { + return; + } + crate::CHICKEN_DAMAGE_ACTIVE.store(true, std::sync::atomic::Ordering::Release); + let mut handle = -1; + loop { + let previous = handle; + handle = s2sdk::FindEntityByClassname(handle, &Str::from_str("chicken")); + if handle == -1 { + break; + } + if handle == previous || !s2sdk::IsValidEntHandle(handle) { + self.handle_fault(Fault::global("chicken enumeration returned a repeated or invalid handle")); + break; + } + self.discover_ordinary_chicken(handle); + } + } + + fn discover_ordinary_chicken(&mut self, handle: i32) { + if !self.ordinary_chickens.ready + || !self.controller.enabled() + || !self.ordinary_chickens_enabled() + || !matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) + || self.bombs.is_carrier_chicken(handle) + || !s2sdk::IsValidEntHandle(handle) + || s2sdk::GetEntityClassname(handle).as_str() != "chicken" + { + return; + } + if self.ordinary_chickens.entities.discover(handle, self.controller.generation()) { + self.public_properties.randomize_model_scale(handle, &mut self.rng); + crate::CHICKEN_DAMAGE_ACTIVE.store(true, std::sync::atomic::Ordering::Release); + } + } + + pub fn track_chicken_explosion(&mut self, round: RoundGeneration, handle: i32, source: i32) -> bool { + self.ordinary_chickens_enabled() + && self.controller.generation() == round + && matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) + && self.ordinary_chickens.entities.track_explosion(handle, round, source) + } + + pub fn finish_chicken_explosion(&mut self, round: RoundGeneration, handle: i32) { + self.ordinary_chickens.entities.remove_explosion(handle, round); + } + + pub fn chicken_blast_damage(&self, damage: &crate::damage::Damage) -> bool { + let round = self.controller.generation(); + [damage.inflictor, damage.attacker] + .into_iter() + .any(|handle| self.ordinary_chickens.entities.is_chicken_explosion(handle, round)) + } + + pub(crate) fn observe_chicken_blast_player_damage(&mut self, damage: &crate::damage::Damage, players: &game::DamagePlayers) { + let Some(victim) = players.victim else { return }; + let Some(victim_identity) = self + .players + .identity(victim.slot) + .filter(|identity| identity.pawn_handle == victim.pawn_handle as u32) + else { + self.ordinary_chickens.blast_kills.remove(&victim.slot); + return; + }; + let round = self.controller.generation(); + if !self.classic_round() + || !active_combat_phase(self.controller.phase()) + || !self.controller.current_mode().is_some_and(|mode| mode.kill_loadout) + || !self.chicken_blast_damage(damage) + { + self.ordinary_chickens.blast_kills.remove(&victim.slot); + return; + } + let Some(source) = self + .ordinary_chickens + .entities + .blast_kill_weapon_source(&[damage.inflictor, damage.attacker, damage.weapon], round) + else { + self.ordinary_chickens.blast_kills.remove(&victim.slot); + return; + }; + if !chicken_weapon_source_is_current(&source, &self.players, &self.controllers) { + self.ordinary_chickens.blast_kills.remove(&victim.slot); + return; + } + self.ordinary_chickens.blast_kills.insert( + victim.slot, + PendingChickenBlastKill { + round, + victim: victim_identity, + tick: s2sdk::GetGameTickCount(), + damage_frame_token: crate::damage::current_damage_frame_token().filter(|token| *token != 0), + source, + }, + ); + } + + pub(super) fn take_chicken_blast_kill_weapon( + &mut self, + victim_slot: i32, + attacker_slot: i32, + ) -> Option { + let pending = self.ordinary_chickens.blast_kills.remove(&victim_slot)?; + let victim = self.players.identity(victim_slot)?; + let attacker = self.players.identity(attacker_slot)?; + let frame = crate::damage::current_damage_frame_token().filter(|token| *token != 0); + if pending.matches(self.controller.generation(), victim, attacker, s2sdk::GetGameTickCount(), frame) + && chicken_weapon_source_is_current(&pending.source, &self.players, &self.controllers) + { + Some(pending.source) + } else { + None + } + } + + pub fn chicken_damage_blocked(&mut self, damage: crate::chicken_entities::EntityDamageSource) -> bool { + self.discover_ordinary_chicken(damage.victim); + let round = self.controller.generation(); + let Some(config) = self.controller.config().and_then(|config| config.chicken) else { + return false; + }; + let blocked = self.ordinary_chickens.entities.damage_blocked(damage, round, config.damage_chain); + if !blocked { + let players = &self.players; + let controllers = &self.controllers; + self.ordinary_chickens + .entities + .record_lethal_attacker(damage, round, || capture_chicken_damage_weapon_source(damage, players, controllers)); + } + blocked + } + + pub(super) fn queue_chicken_population(&mut self) { + if !self.ordinary_chickens.ready + || !self.classic_enabled() + || !matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) + { + return; + } + if !self.ordinary_chickens_enabled() { + self.cleanup_ordinary_chickens(); + return; + } + if self.ordinary_chickens.spawn_round == Some(self.controller.generation()) { + return; + } + let Some(config) = self.controller.config().and_then(|config| config.chicken) else { + return; + }; + let mut effective_players = 0_u32; + let mut positions = Vec::new(); + for slot in 0..s2sdk::GetMaxClients() { + if !s2sdk::IsClientInGame(slot) || !matches!(s2sdk::GetClientTeam(slot) as i32, 2 | 3) { + continue; + } + effective_players = effective_players.saturating_add(1); + if let Some(player) = LivePlayer::resolve(slot) { + let origin = s2sdk::GetEntityAbsOrigin(player.pawn_handle); + if origin.x.is_finite() && origin.y.is_finite() && origin.z.is_finite() { + positions.push(origin); + } + } + } + if positions.is_empty() { + return; + } + let round = self.controller.generation(); + self.discover_ordinary_chickens(); + let count = config.spawn.target_count(effective_players); + let population = self.ordinary_chickens.entities.active_handles(round).len(); + let owned = self.ordinary_chickens.entities.owned_handles(round); + let maximum = config.spawn.maximum_population(count); + if population as u64 > u64::from(maximum) { + let excess = ((population as u64 - u64::from(maximum)) as usize).min(owned.len()); + for handle in owned.into_iter().take(excess) { + if self.ordinary_chickens.entities.remove_chicken(handle, round) { + self.public_properties.restore_model_scale(handle); + self.ordinary_chickens.cleanup.push(handle); + } + } + self.ordinary_chickens.spawn_round = Some(round); + crate::CHICKEN_DAMAGE_ACTIVE.store( + self.ordinary_chickens.ready && self.controller.enabled() && self.ordinary_chickens_enabled(), + std::sync::atomic::Ordering::Release, + ); + log(&format!("chicken population trim round={round:?} maximum={maximum} removed={excess}")); + return; + } + let refill_threshold = config.spawn.refill_threshold(count); + if population >= refill_threshold as usize { + self.ordinary_chickens.spawn_round = Some(round); + return; + } + for index in 0..count { + let player_origin = positions[index as usize % positions.len()]; + let turn = index as f32 * 2.399_963_1; + let ring = (index as usize / positions.len()) as f32; + let distance = 64.0 + ring * 24.0; + self.engine_actions.push(EngineAction::Chicken(Action::Spawn { + round, + origin: plugify::Vec3 { + x: player_origin.x + turn.cos() * distance, + y: player_origin.y + turn.sin() * distance, + z: player_origin.z + 4.0, + }, + })); + } + self.ordinary_chickens.spawn_round = Some(round); + log(&format!( + "chicken spawn plan round={round:?} count={count} effective_players={effective_players}" + )); + } + + pub(super) fn poll_chickens(&mut self) -> Vec { + if !self.ordinary_chickens.ready || !matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) { + return Vec::new(); + } + if !self.ordinary_chickens_enabled() { + self.cleanup_ordinary_chickens(); + return Vec::new(); + } + self.discover_ordinary_chickens(); + let round = self.controller.generation(); + let Some(config) = self.controller.config().and_then(|config| config.chicken) else { + return Vec::new(); + }; + let mut actions = Vec::new(); + for handle in self.ordinary_chickens.entities.active_handles(round) { + let Some((health, life_state)) = crate::chicken_entities::health(handle) else { + // Removal without a readable dead state is not a kill and must not blast. + self.ordinary_chickens.entities.remove_chicken(handle, round); + self.public_properties.restore_model_scale(handle); + continue; + }; + let attacker = self.ordinary_chickens.entities.killer(handle, round); + if (health <= 0 || life_state == 2) + && let Some(origin) = crate::chicken_entities::position(handle) + && self.ordinary_chickens.entities.mark_dead(handle, round) + && let Some(config) = self.ordinary_chickens.entities.take_blast_config(handle, round, config.kill_blast) + { + actions.push(EngineAction::Chicken(Action::Blast { + round, + chicken: handle, + attacker, + origin, + config, + })); + } + } + + actions + } + + pub(super) fn request_chicken(&mut self, slot: i32) -> Result { + if !self.ordinary_chickens.ready + || !self.classic_enabled() + || !active_combat_phase(self.controller.phase()) + || !self.ordinary_chickens_enabled() + { + return Err(self.text(slot, "chicken.unavailable", &[])); + } + let player = LivePlayer::resolve(slot).ok_or(self.text(slot, "player.alive_required", &[]))?; + if !matches!(s2sdk::GetClientTeam(slot) as i32, 2 | 3) { + return Err(self.text(slot, "chicken.team_required", &[])); + } + let task = self.combat_task(player).ok_or(self.text(slot, "player.life_pending", &[]))?; + if self.ordinary_chickens.purchases.contains_key(&slot) { + return Err(self.text(slot, "chicken.pending", &[])); + } + let config = self.controller.config().ok_or(self.text(slot, "config.unavailable", &[]))?; + let price = config.prices.chicken_cash; + let player_origin = s2sdk::GetEntityAbsOrigin(player.pawn_handle); + if !player_origin.x.is_finite() || !player_origin.y.is_finite() || !player_origin.z.is_finite() { + return Err(self.text(slot, "chicken.position_invalid", &[])); + } + self.ordinary_chickens.purchases.insert(slot, task); + self.engine_actions.push(EngineAction::Chicken(Action::Purchase { + task, + player, + price, + origin: plugify::Vec3 { + x: player_origin.x + 64.0, + y: player_origin.y, + z: player_origin.z + 4.0, + }, + })); + Ok(self.text(slot, "chicken.request", &[("price", &price.to_string())])) + } + + pub(super) fn chicken_spawn_current(&self, round: RoundGeneration) -> bool { + self.ordinary_chickens.ready + && self.ordinary_chickens_enabled() + && self.controller.generation() == round + && matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) + } + + pub(super) fn chicken_blast_current(&self, round: RoundGeneration, chicken: i32) -> bool { + self.chicken_spawn_current(round) && self.ordinary_chickens.entities.contains(chicken, round) + } + + pub(super) fn chicken_purchase_current(&self, task: PlayerTask, player: LivePlayer) -> bool { + self.ordinary_chickens.ready + && self.ordinary_chickens_enabled() + && self.classic_enabled() + && active_combat_phase(self.controller.phase()) + && self.ordinary_chickens.purchases.get(&task.player.slot) == Some(&task) + && self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) + && LivePlayer::resolve(player.slot) == Some(player) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + } + + pub(super) fn chicken_eat_current(&self, task: PlayerTask, player: LivePlayer, chicken: i32) -> bool { + self.use_target_hook_ready + && self.ordinary_chickens.ready + && self.ordinary_chickens_enabled() + && self.controller.enabled() + && matches!(self.controller.phase(), Phase::Preparing | Phase::Running | Phase::Warmup) + && self.controller.current_mode().is_some_and(|mode| { + self.controller + .config() + .and_then(|config| config.chicken) + .is_some_and(|config| config.eating.enabled_for_mode(mode.chicken_eating)) + }) + && self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) + && LivePlayer::resolve(player.slot) == Some(player) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + && self.ordinary_chickens.entities.contains(chicken, task.round) + } +} + +pub enum Action { + Spawn { + round: RoundGeneration, + origin: plugify::Vec3, + }, + Blast { + round: RoundGeneration, + chicken: i32, + attacker: Option, + origin: plugify::Vec3, + config: funrounds_core::ChickenBlastConfig, + }, + Remove(i32), + Purchase { + task: PlayerTask, + player: LivePlayer, + price: u32, + origin: plugify::Vec3, + }, + Eat { + task: PlayerTask, + player: LivePlayer, + chicken: i32, + outcome: funrounds_core::ChickenEatOutcome, + }, +} + +impl Action { + pub(super) fn involves(&self, slots: &[i32]) -> bool { + match self { + Self::Purchase { task, .. } | Self::Eat { task, .. } => slots.contains(&task.player.slot), + Self::Spawn { .. } | Self::Blast { .. } | Self::Remove(_) => false, + } + } +} + +impl Runtime { + pub(super) fn chickens_action_current(&self, action: &Action) -> bool { + match action { + Action::Spawn { round, .. } => self.chicken_spawn_current(*round), + Action::Blast { round, chicken, .. } => self.chicken_blast_current(*round, *chicken), + Action::Remove(_) => true, + Action::Purchase { task, player, .. } => self.chicken_purchase_current(*task, *player), + Action::Eat { task, player, chicken, .. } => self.chicken_eat_current(*task, *player, *chicken), + } + } +} + +pub(crate) fn execute(action: Action) { + match action { + Action::Spawn { round, origin } => process_chicken_spawn(round, origin), + Action::Blast { + round, + chicken, + attacker, + origin, + config, + } => process_chicken_blast(round, chicken, attacker, origin, config), + Action::Remove(handle) => crate::chicken_entities::remove(handle), + Action::Eat { + task, + player, + chicken, + outcome, + } => process_chicken_eat(task, player, chicken, outcome), + Action::Purchase { task, player, price, origin } => process_chicken_purchase(task, player, price, origin), + } +} diff --git a/crates/funrounds-plugin/src/runtime/combat.rs b/crates/funrounds-plugin/src/runtime/combat.rs new file mode 100644 index 0000000..051fbcb --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/combat.rs @@ -0,0 +1,773 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::{ + Effect, EngineAction, Fault, FiredWeapon, LivePlayer, Mechanism, Phase, PlayerTask, Runtime, SelfDamage, Str, active_combat_phase, log, s2sdk, + weapon_identity_is_current, +}; +use crate::game; +use crate::{process_delayed_damage, process_reflection}; +use funrounds_core::Headshots; +use std::collections::HashMap; + +#[derive(Default)] +pub(super) struct State { + pub(super) lives: HashMap, + pub(super) reflections: Vec, + pub(super) delayed_damage: Vec, + pub(super) random_heals: Vec, + pub(super) native_self_damage_shots: HashMap, +} + +impl State { + pub(super) fn takeover(&mut self, owners: &[i32], task: PlayerTask, players: &funrounds_core::PlayerTracker) { + let sources = owners + .iter() + .copied() + .filter(|slot| { + self.lives.get(slot).is_some_and(|(previous, _)| { + previous.round == task.round + && previous.player.pawn_handle == task.player.pawn_handle + && players.identity(*slot) == Some(previous.player) + }) + }) + .collect::>(); + let source = sources + .iter() + .copied() + .find(|slot| *slot == task.player.slot) + .or_else(|| sources.first().copied()); + let life = source.and_then(|slot| self.lives.remove(&slot)).map(|(_, life)| life); + for slot in sources { + if Some(slot) != source { + self.lives.remove(&slot); + } + } + if source != Some(task.player.slot) { + self.lives.remove(&task.player.slot); + } + if let Some(life) = life { + self.lives.insert(task.player.slot, (task, life)); + } + } + + pub(super) fn remove_life(&mut self, slot: i32) { + self.lives.remove(&slot); + // A dead attacker still owns damage already dealt to another player. + self.delayed_damage.retain(|hit| hit.target.player.slot != slot); + } + + pub(super) fn cancel_spawn_work(&mut self, slot: i32) { + self.native_self_damage_shots.remove(&slot); + self.delayed_damage + .retain(|hit| hit.target.player.slot != slot && hit.source.player.slot != slot); + } + + pub(super) fn cancel_actions_for(&mut self, slots: &[i32]) { + self.native_self_damage_shots.retain(|slot, _| !slots.contains(slot)); + self.reflections + .retain(|hit| !slots.contains(&hit.target.player.slot) && !slots.contains(&hit.source.player.slot)); + self.delayed_damage + .retain(|hit| !slots.contains(&hit.target.player.slot) && !slots.contains(&hit.source.player.slot)); + self.random_heals + .retain(|receipt| !slots.contains(&receipt.target.player.slot) && !slots.contains(&receipt.source.player.slot)); + } + + pub(super) fn forget_player(&mut self, slot: i32) { + self.lives.remove(&slot); + self.cancel_actions_for(&[slot]); + } + + pub(super) fn clear(&mut self) { + self.lives.clear(); + self.reflections.clear(); + self.delayed_damage.clear(); + self.random_heals.clear(); + self.native_self_damage_shots.clear(); + } + + pub(super) fn expire_combat_receipts(&mut self, tick: i32, players: &funrounds_core::PlayerTracker) { + self.native_self_damage_shots.retain(|slot, shot| { + shot.tick == tick && players.identity(*slot) == Some(shot.task.player) && LivePlayer::resolve(*slot) == Some(shot.player) + }); + let frame = crate::damage::current_damage_frame_token().filter(|token| *token != 0); + self.random_heals.retain(|receipt| Some(receipt.frame_token) == frame); + } + + fn take_native_player_hit(&mut self, task: PlayerTask, victim: LivePlayer, tick: i32) -> bool { + let matches = self + .native_self_damage_shots + .get(&victim.slot) + .is_some_and(|shot| shot.task == task && shot.player == victim && shot.tick == tick); + if !matches { + return false; + } + self.native_self_damage_shots + .remove(&victim.slot) + .is_some_and(|shot| shot.player_hit && weapon_identity_is_current(victim, &shot.weapon)) + } + + fn mark_native_shot_hit(&mut self, task: PlayerTask, player: LivePlayer, tick: i32, damage: &crate::damage::Damage) { + let Some(shot) = self.native_self_damage_shots.get_mut(&player.slot) else { + return; + }; + if weapon_identity_is_current(player, &shot.weapon) { + shot.mark_player_hit(task, player, tick, damage); + } + } + + pub(super) fn collect_reflections(&mut self, tick: i32, actions: &mut Vec) { + actions.extend( + self.reflections + .extract_if(.., |hit| tick > hit.tick) + .map(|hit| EngineAction::Combat(Action::Reflection(hit))), + ); + } + + pub(super) fn collect_delayed_damage(&mut self, now: f32, actions: &mut Vec) { + actions.extend( + self.delayed_damage + .extract_if(.., |hit| hit.is_due(now)) + .map(|hit| EngineAction::Combat(Action::DelayedDamage(hit))), + ); + } +} + +#[derive(Clone, Copy)] +pub(crate) struct RandomHealReceipt { + pub target: PlayerTask, + pub source: PlayerTask, + pub target_live: LivePlayer, + pub source_live: LivePlayer, + pub frame_token: u64, + pub amount: i32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct NativeSelfDamageShot { + pub(super) task: PlayerTask, + pub(super) player: LivePlayer, + pub(super) tick: i32, + pub(super) weapon: FiredWeapon, + pub(super) player_hit: bool, +} + +impl NativeSelfDamageShot { + fn matches_hit(&self, task: PlayerTask, player: LivePlayer, tick: i32, damage: &crate::damage::Damage) -> bool { + self.task == task + && self.player == player + && self.tick == tick + && self.weapon.handle == damage.weapon + && damage.weapon_class.as_deref() == Some(self.weapon.classname.as_str()) + } + + fn mark_player_hit(&mut self, task: PlayerTask, player: LivePlayer, tick: i32, damage: &crate::damage::Damage) -> bool { + if !self.matches_hit(task, player, tick, damage) { + return false; + } + self.player_hit = true; + true + } +} + +fn native_self_damage_signature(damage: &crate::damage::Damage, player: LivePlayer) -> bool { + !damage.skip_plugin_rules + && damage.victim == player.pawn_handle + && damage.attacker == player.pawn_handle + && damage.inflictor == player.pawn_handle + && damage.weapon == -1 + && damage.weapon_kind == 0 + && damage.damage_type == 0 + && damage.amount.is_finite() + && damage.amount > 0.0 +} + +fn sync_shield_hud(player: LivePlayer, armor: i32) -> Result<(), Fault> { + if s2sdk::GetClientArmor(player.slot) != armor { + s2sdk::SetClientArmor(player.slot, armor); + if s2sdk::GetClientArmor(player.slot) != armor { + return Err(Fault::mechanism(Mechanism::EnergyShield, "shield armor HUD write failed")); + } + } + Ok(()) +} + +fn mode65_self_damage(damage: &crate::damage::Damage, pawn: i32, health: i32) -> bool { + let damage_type = damage.damage_type; + let native_self = damage.inflictor == pawn; + // mp_weapon_self_inflict_amount uses pawn-attributed DMG_GENERIC, not DMG_BULLET. + native_self && (damage_type == 0 || damage_type == 0x0200_0000 && health <= 1 && damage.amount == 1.0) + || damage.weapon_kind == 1 && damage_type & crate::damage::DMG_BULLET != 0 +} + +fn self_damage_allowed(mode: &funrounds_core::Mode, damage: &crate::damage::Damage, pawn: i32, health: i32) -> bool { + if damage.damage_type & 32 != 0 { + return false; + } + match mode.self_damage { + Some(SelfDamage::MissPenalty) => mode65_self_damage(damage, pawn, health), + Some(SelfDamage::Native { amount }) => amount > 0.0, + None => false, + } +} + +fn numeric_self_damage_enters_health(allowed_self: bool, blocked: bool, incoming: f32) -> bool { + allowed_self && !blocked && incoming.is_finite() && incoming > 0.0 +} + +fn delayed_damage_protection_valid(protection_enabled: bool, target: PlayerTask, current: Option<(PlayerTask, bool)>) -> bool { + !protection_enabled || current.is_some_and(|(task, protected)| task == target && !protected) +} + +fn lifesteal_eligible(attacker: i32, victim: i32, attacker_alive: bool) -> bool { + attacker >= 0 && victim >= 0 && attacker != victim && attacker_alive +} + +impl Runtime { + pub(super) fn capture_native_self_damage_shot(&mut self, player: LivePlayer, weapon: &str) { + if active_combat_phase(self.controller.phase()) + && self + .controller + .current_mode() + .is_some_and(|mode| matches!(mode.self_damage, Some(SelfDamage::Native { amount }) if amount > 0.0)) + && let Some(task) = self.combat_task(player) + && let Some(weapon) = super::fired_weapon(player, weapon) + { + self.combat.native_self_damage_shots.insert( + player.slot, + NativeSelfDamageShot { + task, + player, + tick: s2sdk::GetGameTickCount(), + weapon, + player_hit: false, + }, + ); + } else { + self.combat.native_self_damage_shots.remove(&player.slot); + } + } + + pub fn headshots(&self) -> Headshots { + if self.controller.phase() == Phase::Idle { + return Headshots::Normal; + } + self.controller.current_mode().map_or(Headshots::Normal, |mode| mode.headshots) + } + + pub(crate) fn classifies_native_he(&self) -> bool { + self.classic_round() + && self + .controller + .current_mode() + .is_some_and(|mode| mode.hegrenade_impulse.is_some() || !mode.weapon_damage.is_empty()) + } + + pub fn classic_damage_scale(&self, damage: &crate::damage::Damage, players: &game::DamagePlayers, native_he: bool) -> Option { + if !self.classic_round() { + return Some(1.0); + } + let damage_type = damage.damage_type; + let game::DamagePlayers { victim, attacker } = *players; + let self_damage = victim.is_some() && victim == attacker; + let mode = self.controller.current_mode()?; + let he_multiplier = native_he.then(|| mode.weapon_damage.configured("hegrenade")).flatten(); + let self_damage_allowed = he_multiplier.is_some() + || matches!(mode.self_damage, Some(SelfDamage::Native { amount }) if amount > 0.0) + || matches!(mode.self_damage, Some(SelfDamage::MissPenalty)) + && victim.is_some_and(|player| mode65_self_damage(damage, player.pawn_handle, s2sdk::GetClientHealth(player.slot))); + let attacker_health = if !mode.health_damage { + None + } else { + attacker + .filter(|player| { + LivePlayer::resolve(player.slot) == Some(*player) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + && self.effects.get(&player.slot).is_some_and(|effect| { + Some(effect.identity) == self.players.identity(player.slot) + && effect.identity.pawn_handle == player.pawn_handle as u32 + && !effect.has_pending_loadout() + }) + }) + .map(|player| (s2sdk::GetClientHealth(player.slot), self.effects[&player.slot].attributes.health)) + }; + let suicide_scale = if players.victim.is_some_and(|victim| self.suicides.active(victim)) { + 5.0 + } else { + 1.0 + }; + let common = if victim.is_some() && attacker.is_some() && !self_damage && damage_type & 32 == 0 { + mode.damage_multiplier + } else { + 1.0 + } * suicide_scale + * mode + .health_curve + .damage_scale(attacker_health, self_damage, damage_type & 32 != 0, self_damage_allowed)?; + if native_he { + return Some(common * he_multiplier.unwrap_or(1.0)); + } + if mode.weapon_damage.is_empty() || attacker.is_none() || self_damage || damage_type & crate::damage::DMG_FALL != 0 { + return Some(common); + } + let weapon = (damage.weapon != -1 && s2sdk::IsValidEntHandle(damage.weapon)) + .then(|| { + let class = s2sdk::GetEntityClassname(damage.weapon); + if !class.as_str().starts_with("weapon_") { + return class.to_string(); + } + let definition = unsafe { crate::effects::__s2sdk_GetWeaponItemDefinition }.expect("required native ABI checked at startup"); + crate::effects::equipment::give_name_for_original(class.as_str(), unsafe { definition(damage.weapon) }) + .unwrap_or_else(|| class.to_string()) + }) + .or_else(|| damage.weapon_class.clone()); + Some( + common + * funrounds_core::weapon_damage_scale( + mode, + weapon.as_deref().map(crate::damage::weapon_scale_id).filter(|id| *id != "hegrenade"), + true, + ), + ) + } + + pub fn combat_protected(&self, players: &game::DamagePlayers) -> bool { + players.victim.and_then(|player| self.combat_task(player)).is_some_and(|task| { + self.combat + .lives + .get(&task.player.slot) + .is_some_and(|(expected, life)| *expected == task && life.protected(s2sdk::GetGameTime())) + }) + } + + pub fn record_native_player_hit(&mut self, damage: &crate::damage::Damage, players: &game::DamagePlayers) { + // The native classifier covers bullets, buckshot and Zeus shock damage. + if matches!(damage.weapon_kind, 1 | 3) + && !damage.skip_plugin_rules + && damage.amount.is_finite() + && damage.amount > 0.0 + && let (Some(victim), Some(attacker)) = (players.victim, players.attacker) + && victim != attacker + && self.combat_task(victim).is_some() + { + self.mark_native_shot_hit(attacker, damage); + } + } + + pub fn suppress_hit_native_self_damage(&mut self, damage: &crate::damage::Damage, players: &game::DamagePlayers) -> bool { + let (Some(victim), Some(attacker)) = (players.victim, players.attacker) else { + return false; + }; + if victim != attacker + || !native_self_damage_signature(damage, victim) + || !active_combat_phase(self.controller.phase()) + || !self + .controller + .current_mode() + .is_some_and(|mode| matches!(mode.self_damage, Some(SelfDamage::Native { amount }) if amount > 0.0)) + { + return false; + } + let Some(task) = self.combat_task(victim) else { return false }; + if LivePlayer::resolve(victim.slot) != Some(victim) { + return false; + } + let tick = s2sdk::GetGameTickCount(); + self.combat.take_native_player_hit(task, victim, tick) + } + + pub(super) fn mark_native_shot_hit(&mut self, player: LivePlayer, damage: &crate::damage::Damage) { + let Some(task) = self.combat_task(player) else { return }; + self.combat.mark_native_shot_hit(task, player, s2sdk::GetGameTickCount(), damage); + } + + pub fn combat_damage( + &mut self, + damage: &crate::damage::Damage, + players: &game::DamagePlayers, + common_scale: f32, + allow_reflection: bool, + native_he: bool, + ) -> bool { + let Some(victim) = players.victim else { return false }; + let Some(task) = self.combat_task(victim) else { return false }; + let Some((expected, life)) = self.combat.lives.get_mut(&victim.slot).filter(|(expected, _)| *expected == task) else { + return false; + }; + let Some(mode) = self.controller.current_mode() else { return false }; + if players.attacker.is_some_and(|attacker| s2sdk::GetClientTeam(attacker.slot) as i32 == 1) { + return true; + } + let eligible = players.attacker.is_some_and(|attacker| attacker != victim) && damage.damage_type & 32 == 0; + let allowed_self = + players.attacker == Some(victim) && self_damage_allowed(mode, damage, victim.pawn_handle, s2sdk::GetClientHealth(victim.slot)); + let he_self = native_he && players.attacker == Some(victim) && mode.weapon_damage.configured("hegrenade").is_some(); + let knife = damage.weapon_kind == 2 + || damage.weapon_class.as_deref().is_some_and(crate::projectiles::knife_fire_event) + || damage.weapon != -1 + && s2sdk::IsValidEntHandle(damage.weapon) + && matches!(s2sdk::GetEntityClassname(damage.weapon).as_str(), "weapon_knife" | "weapon_knife_t"); + let incoming = damage.amount * common_scale; + if !incoming.is_finite() { + return true; + } + let (blocked, reflected) = funrounds_core::combat_hit(mode, life, eligible, allowed_self || he_self, knife, incoming); + let suppress_lifesteal = mode.lifesteal; + let source = *expected; + let hud = life.armor_hud(); + // Record the HP path, not the post-hit shield: the breaking hit is fully absorbed. + if numeric_self_damage_enters_health(allowed_self && !he_self, blocked, incoming) { + self.respawning.queue_finish(task); + } + if let Some(armor) = hud + && let Err(error) = sync_shield_hud(victim, armor) + { + self.handle_fault(error); + return true; + } + if let Some(amount) = reflected.filter(|_| allow_reflection) + && let Some(attacker) = players.attacker + && let Some(target) = self.combat_task(attacker) + { + self.combat.reflections.push(crate::damage::Reflection { + target, + source, + target_live: attacker, + source_live: victim, + inflictor: damage.inflictor, + weapon: damage.weapon, + weapon_class: damage.weapon_class.clone(), + amount, + damage_type: damage.damage_type, + tick: s2sdk::GetGameTickCount(), + suppress_lifesteal, + }); + } + blocked + } + + pub fn prepare_delayed_damage_with_heal( + &self, + damage: &crate::damage::Damage, + players: &game::DamagePlayers, + amount: f32, + headshot: bool, + random_heal: i32, + ) -> Option { + let mode = self.controller.current_mode()?; + if !active_combat_phase(self.controller.phase()) || !mode.delayed_damage { + return None; + } + let (target, source) = (players.victim?, players.attacker?); + if s2sdk::GetClientTeam(source.slot) as i32 == 1 + || !crate::damage::delayed_damage_eligible(target.slot, source.slot, damage.damage_type, amount) + { + return None; + } + let target_task = self.combat_task(target)?; + if self.controllers.get(&source.slot) != Some(&source.controller_handle) { + return None; + } + let source_task = self + .players + .damage_source_task(source.slot, self.controller.generation(), source.pawn_handle as u32)?; + let now = s2sdk::GetGameTime(); + if !now.is_finite() { + return None; + } + let mut hit = crate::damage::DelayedDamage::new( + target_task, + source_task, + target, + source, + damage, + crate::damage::DamageOutcome { amount, headshot }, + now, + ); + hit.set_random_heal(random_heal); + Some(hit) + } + + pub fn defer_damage(&mut self, hit: crate::damage::DelayedDamage) { + self.combat.delayed_damage.push(hit); + } + + pub fn random_damage_roll( + &mut self, + damage: &crate::damage::Damage, + players: &game::DamagePlayers, + amount: f32, + ) -> Option { + let mode = self.controller.current_mode()?; + if !active_combat_phase(self.controller.phase()) || !mode.random_damage || damage.damage_type & crate::damage::DMG_FALL != 0 { + return None; + } + let (victim, attacker) = (players.victim?, players.attacker?); + if victim == attacker + || self.combat_task(victim).is_none() + || self.combat_task(attacker).is_none() + || crate::damage::current_damage_frame_token().filter(|token| *token != 0).is_none() + { + return None; + } + funrounds_core::random_damage(amount, s2sdk::GetClientHealth(victim.slot), &mut self.rng) + } + + pub fn queue_random_heal(&mut self, players: &game::DamagePlayers, amount: i32) -> Result<(), Fault> { + if amount <= 0 { + return Ok(()); + } + let (Some(target_live), Some(source_live)) = (players.victim, players.attacker) else { + return Ok(()); + }; + let (Some(target), Some(source)) = (self.combat_task(target_live), self.combat_task(source_live)) else { + return Ok(()); + }; + let Some(frame_token) = crate::damage::current_damage_frame_token().filter(|token| *token != 0) else { + return Err(Fault::mechanism( + Mechanism::RandomDamage, + "player damage frame token unavailable before random heal settlement", + )); + }; + self.combat.random_heals.push(RandomHealReceipt { + target, + source, + target_live, + source_live, + frame_token, + amount, + }); + Ok(()) + } + + pub(super) fn settle_random_heal(&mut self, victim: i32, attacker: i32, event: usize) -> Option { + if s2sdk::GetEventInt(event, &Str::from_str("dmg_health")) <= 0 { + return None; + } + let receipt = if let Some(receipt) = crate::damage::internal_random_heal_hurt(victim, attacker) { + Some(receipt) + } else { + let token = crate::damage::current_damage_frame_token().filter(|token| *token != 0)?; + let index = + self.combat.random_heals.iter().position(|receipt| { + receipt.target.player.slot == victim && receipt.source.player.slot == attacker && receipt.frame_token == token + })?; + Some(self.combat.random_heals.remove(index)) + }; + let receipt = receipt?; + if !self.controller.current_mode().is_some_and(|mode| mode.random_damage) + || receipt.amount <= 0 + || !self + .players + .validates_damage_source(receipt.target, self.controller.generation(), receipt.target_live.pawn_handle as u32) + || !self + .players + .validates(receipt.source, self.controller.generation(), receipt.source_live.pawn_handle as u32) + || LivePlayer::resolve_present(receipt.target_live.slot) != Some(receipt.target_live) + || LivePlayer::resolve(receipt.source_live.slot) != Some(receipt.source_live) + || crate::damage::current_damage_frame_token() != Some(receipt.frame_token) + { + return None; + } + if let Err(error) = Effect::random_damage_heal(receipt.source_live, receipt.amount) { + self.handle_fault(Fault::mechanism(Mechanism::RandomDamage, error)); + return None; + } + Some(attacker) + } + + pub(super) fn refresh_combat(&mut self) { + if self.controller.current_mode().is_none() { + return; + } + let now = s2sdk::GetGameTime(); + let mut failure = None; + for (task, life) in self.combat.lives.values_mut() { + let Some(player) = LivePlayer::resolve(task.player.slot) else { continue }; + if !self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) + || !self + .effects + .get(&player.slot) + .is_some_and(|effect| effect.identity == task.player && !effect.has_pending_loadout()) + { + continue; + } + let health = s2sdk::GetClientHealth(player.slot); + if let Some(next) = life.recharge(now, health) + && next != health + { + s2sdk::SetClientHealth(player.slot, next); + if s2sdk::GetClientHealth(player.slot) != next { + failure = Some(Fault::mechanism(Mechanism::EnergyShield, "shield health conversion write failed")); + break; + } + } + if let Some(armor) = life.armor_hud() + && let Err(error) = sync_shield_hud(player, armor) + { + failure = Some(error); + break; + } + } + if let Some(error) = failure { + self.handle_fault(error); + } + } + + pub(super) fn lifesteal(&mut self, event: usize, attacker: i32, victim: i32) -> Option { + if self.controller.phase() == Phase::Idle || !self.controller.current_mode().is_some_and(|mode| mode.lifesteal) { + return None; + } + let player = LivePlayer::resolve(attacker); + if !lifesteal_eligible(attacker, victim, player.is_some()) { + return None; + } + let player = player.expect("eligible attacker is alive"); + if !self.effects.get(&attacker).is_some_and(|effect| { + Some(effect.identity) == self.players.identity(attacker) + && effect.identity.pawn_handle == player.pawn_handle as u32 + && !effect.has_pending_loadout() + }) || self.controllers.get(&attacker) != Some(&player.controller_handle) + { + return None; + } + let health = s2sdk::GetEventInt(event, &Str::from_str("dmg_health")); + let armor = s2sdk::GetEventInt(event, &Str::from_str("dmg_armor")); + let energy_shield = self.controller.current_mode().is_some_and(|mode| mode.energy_shield); + let effect = self.effects.get_mut(&attacker)?; + if let Err(error) = effect.lifesteal(player, health, armor, energy_shield) { + self.handle_fault(Fault::mechanism(Mechanism::Lifesteal, error)); + return None; + } + if self.diagnostics() { + log(&format!( + "lifesteal slot={attacker} dmg_health={health} dmg_armor={armor} health={} armor={} helmet={:?}", + s2sdk::GetClientHealth(attacker), + s2sdk::GetClientArmor(attacker), + player.helmet() + )); + } + Some(attacker) + } + + pub(super) fn delayed_damage_current(&self, hit: &crate::damage::DelayedDamage) -> bool { + self.classic_round() + && active_combat_phase(self.controller.phase()) + && self.controller.current_mode().is_some_and(|mode| { + mode.delayed_damage + && delayed_damage_protection_valid( + mode.spawn_protection || mode.kill_protection, + hit.target, + self.combat + .lives + .get(&hit.target.player.slot) + .map(|(task, life)| (*task, life.protected(s2sdk::GetGameTime()))), + ) + }) + && hit.validates_players( + self.controller.generation(), + &self.players, + LivePlayer::resolve(hit.target.player.slot), + LivePlayer::resolve_present(hit.source.player.slot), + ) + && hit.native_handles(s2sdk::IsValidEntHandle).is_some() + } + + pub(super) fn reflection_current(&self, hit: &crate::damage::Reflection) -> bool { + self.classic_round() + && self.controller.current_mode().is_some_and(|mode| mode.reflect_damage.is_some()) + && LivePlayer::resolve(hit.target.player.slot) == Some(hit.target_live) + && LivePlayer::resolve_present(hit.source.player.slot) == Some(hit.source_live) + && self + .players + .validates(hit.target, self.controller.generation(), hit.target_live.pawn_handle as u32) + && self + .players + .validates_damage_source(hit.source, self.controller.generation(), hit.source_live.pawn_handle as u32) + && self + .combat + .lives + .get(&hit.target.player.slot) + .is_some_and(|(task, life)| *task == hit.target && !life.protected(s2sdk::GetGameTime())) + && hit.native_handles(s2sdk::IsValidEntHandle).is_some() + } +} + +pub enum Action { + Reflection(crate::damage::Reflection), + DelayedDamage(crate::damage::DelayedDamage), +} + +impl Action { + pub(super) fn involves(&self, slots: &[i32]) -> bool { + match self { + Self::Reflection(hit) => slots.contains(&hit.target.player.slot) || slots.contains(&hit.source.player.slot), + Self::DelayedDamage(hit) => slots.contains(&hit.target.player.slot) || slots.contains(&hit.source.player.slot), + } + } +} + +impl Runtime { + pub(super) fn combat_action_current(&self, action: &Action) -> bool { + match action { + Action::DelayedDamage(hit) => self.delayed_damage_current(hit), + Action::Reflection(hit) => self.reflection_current(hit), + } + } +} + +pub(crate) fn execute(action: Action) { + match action { + Action::DelayedDamage(hit) => process_delayed_damage(hit), + Action::Reflection(hit) => process_reflection(hit), + } +} + +#[cfg(test)] +mod tests { + #[test] + fn miss_penalty_respects_native_self_damage_and_final_health_point() { + let mut mode = funrounds_core::Config::parse(include_str!("../../../../config/funrounds.example.toml")) + .unwrap() + .modes + .remove(0); + mode.self_damage = Some(funrounds_core::SelfDamage::MissPenalty); + let mut damage = crate::damage::Damage { + victim: 42, + attacker: 42, + inflictor: 42, + weapon_kind: 0, + hit_group: -1, + traced_head: false, + amount: 36.0, + damage_type: 0, + weapon: -1, + weapon_class: None, + skip_plugin_rules: false, + }; + assert!(super::self_damage_allowed(&mode, &damage, 42, 200)); + assert!(!super::self_damage_allowed(&mode, &damage, 43, 200)); + for damage_type in [8, 64, 256, 0x0200_0000] { + damage.damage_type = damage_type; + assert!(!super::self_damage_allowed(&mode, &damage, 42, 200)); + } + damage.amount = 1.0; + assert!(super::self_damage_allowed(&mode, &damage, 42, 1)); + assert!(!super::self_damage_allowed(&mode, &damage, 42, 2)); + damage.damage_type = 0; + assert!(super::self_damage_allowed(&mode, &damage, 42, 1)); + damage.damage_type = 2; + assert!(!super::self_damage_allowed(&mode, &damage, 42, 200)); + damage.weapon_kind = 1; + assert!(super::self_damage_allowed(&mode, &damage, 42, 200)); + } + + #[test] + fn lifesteal_excludes_self_world_and_dead_attackers() { + assert!(super::lifesteal_eligible(1, 2, true)); + assert!(!super::lifesteal_eligible(1, 1, true)); + assert!(!super::lifesteal_eligible(-1, 2, true)); + assert!(!super::lifesteal_eligible(1, -1, true)); + assert!(!super::lifesteal_eligible(1, 2, false)); + } +} diff --git a/crates/funrounds-plugin/src/runtime/composed.rs b/crates/funrounds-plugin/src/runtime/composed.rs new file mode 100644 index 0000000..bf0fda0 --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/composed.rs @@ -0,0 +1,735 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::*; +use rand::prelude::IndexedRandom; + +#[derive(Clone)] +pub enum Action { + Penalty { + task: PlayerTask, + player: LivePlayer, + amount: f32, + burn: bool, + }, + Weapon { + task: PlayerTask, + player: LivePlayer, + fired: FiredWeapon, + switch_to: Option, + }, +} + +impl Action { + pub fn task(&self) -> PlayerTask { + match self { + Self::Penalty { task, .. } | Self::Weapon { task, .. } => *task, + } + } + + fn player(&self) -> LivePlayer { + match self { + Self::Penalty { player, .. } | Self::Weapon { player, .. } => *player, + } + } +} + +#[derive(Clone, Copy)] +struct Life { + task: PlayerTask, + last_combat: f64, + regeneration_at: f64, + breath_pending: bool, + aura_at: f64, + stopped_since: f64, + stopped_tick: f64, + grounded_since: f64, + grounded_tick: f64, + weapon_ready: f64, +} + +impl Life { + fn new(task: PlayerTask, now: f64) -> Self { + Self { + task, + last_combat: now, + regeneration_at: now, + breath_pending: true, + aura_at: now, + stopped_since: now, + stopped_tick: now, + grounded_since: now, + grounded_tick: now, + weapon_ready: now, + } + } +} + +#[derive(Clone, Copy)] +struct Flash { + task: PlayerTask, + player: LivePlayer, + tick: i32, + pending_until: f64, + native_until: f64, + native_duration: f64, + installed: Option<(f64, f64)>, + partial_write: bool, +} + +#[derive(Default)] +pub(super) struct State { + lives: HashMap, + weapons: Vec<(i32, Action)>, + flashes: HashMap, + heads: HashMap, + head_round: Option, + head_scales: HashMap, +} + +impl State { + pub fn is_clean(&self) -> bool { + self.heads.is_empty() && self.flashes.is_empty() && self.weapons.is_empty() + } +} + +pub(super) fn probe(events: &EventCapabilities, caps: &mut funrounds_core::Capabilities, reasons: &mut Vec) { + let mut health = crate::capability::Probe::default(); + crate::capability::imports!(health; __s2sdk_GetGameTime, __s2sdk_GetClientHealth, __s2sdk_SetClientHealth); + health.require(events.combat_events, "events:player_lifecycle"); + let mut regeneration = health.clone(); + regeneration.require( + events.player_hurt && events.weapon_fire && events.grenade_thrown, + "events:player_hurt/weapon_fire/grenade_thrown", + ); + crate::capability::imports!(regeneration; __s2sdk_EmitSoundToClient); + caps.regeneration = regeneration.record("regeneration", reasons); + let mut aura = health; + crate::capability::imports!(aura; __s2sdk_GetEntityAbsOrigin, __s2sdk_GetClientAbsOrigin); + aura.require(crate::chicken_entities::available(), "ordinary_chicken_identity"); + caps.chicken_aura = aura.record("chicken_aura", reasons); + let mut movement = crate::capability::Probe::default(); + crate::capability::imports!(movement; __s2sdk_GetClientAbsVelocity, __s2sdk_GetClientFlags, __s2sdk_GetGameTime); + movement.require(events.damage && events.combat_events, "hooks:damage/lifecycle"); + movement.require(crate::damage::reflection_available(), "native:TakeEntityDamageWithWeapon"); + caps.dont_stop = movement.clone().record("dont_stop", reasons); + movement.require(caps.afterburn, "managed_afterburn"); + caps.hot_floor = movement.record("hot_floor", reasons); + let mut weapon = crate::capability::Probe::default(); + crate::capability::imports!(weapon; __s2sdk_DropWeapon, __s2sdk_SwitchWeapon, __s2sdk_GetClientWeapons, + __s2sdk_GetClientActiveWeapon, __s2sdk_GetEntityOwner, __s2sdk_GetEntityClassname); + weapon.require(events.weapon_fire && events.combat_events, "events:weapon_fire/lifecycle"); + caps.weapon_on_fire = weapon.record("weapon_on_fire", reasons); + let mut flash = crate::capability::Probe::default(); + crate::capability::imports!(flash; __s2sdk_GetEntSchemaFloat2, __s2sdk_SetEntSchemaFloat2, __s2sdk_GetGameTime, __s2sdk_GetEventFloat); + flash.require(events.player_blind && events.combat_events, "events:player_blind/lifecycle"); + flash.schema("CCSPlayerPawn", "m_blindUntilTime"); + flash.schema("CCSPlayerPawn", "m_flFlashDuration"); + caps.long_flash = flash.record("long_flash", reasons); + let mut head = crate::capability::Probe::default(); + crate::capability::imports!(head; __s2sdk_GetClientKills, __s2sdk_GetClientDeaths); + head.require( + unsafe { crate::funrounds_native::__funrounds_native_HasBigHeadScaleSupport }.is_some_and(|query| unsafe { query() }), + "native:BigHeadScaleSupport", + ); + head.require( + unsafe { crate::funrounds_native::__funrounds_native_SetBigHeadScaleTarget }.is_some() + && unsafe { crate::funrounds_native::__funrounds_native_ClearBigHeadScaleTarget }.is_some(), + "native:BigHeadScaleTarget", + ); + caps.big_head = head.record("big_head", reasons); +} + +fn read_flash(player: LivePlayer, field: &str) -> f64 { + s2sdk::GetEntSchemaFloat2( + s2sdk::EntHandleToEntPointer(player.pawn_handle), + &Str::from_str("CCSPlayerPawn"), + &Str::from_str(field), + 0, + ) +} + +fn write_flash(player: LivePlayer, field: &str, value: f64) -> bool { + s2sdk::SetEntSchemaFloat2( + s2sdk::EntHandleToEntPointer(player.pawn_handle), + &Str::from_str("CCSPlayerPawn"), + &Str::from_str(field), + value, + true, + 0, + ); + read_flash(player, field) == f64::from(value as f32) +} + +fn restore_flash(flash: &mut Flash) -> bool { + if LivePlayer::resolve_present(flash.player.slot) != Some(flash.player) { + return true; + } + let Some((until, duration)) = flash.installed else { + return true; + }; + if !flash.partial_write && (read_flash(flash.player, "m_blindUntilTime") != until || read_flash(flash.player, "m_flFlashDuration") != duration) { + return true; + } + flash.partial_write = true; + let until_ok = read_flash(flash.player, "m_blindUntilTime") != until || write_flash(flash.player, "m_blindUntilTime", flash.native_until); + let duration_ok = + read_flash(flash.player, "m_flFlashDuration") != duration || write_flash(flash.player, "m_flFlashDuration", flash.native_duration); + until_ok && duration_ok +} + +impl Runtime { + fn composed_active(&self) -> bool { + self.classic_enabled() && self.effects_ready && active_combat_phase(self.controller.phase()) + } + + pub(super) fn composed_action_valid(&self, action: &Action) -> bool { + let player = action.player(); + self.composed_active() + && self.combat_task(player) == Some(action.task()) + && LivePlayer::resolve(player.slot) == Some(player) + && match action { + Action::Penalty { .. } => !self.combat_protected(&game::DamagePlayers { + victim: Some(player), + attacker: None, + }), + Action::Weapon { fired, switch_to, .. } => { + weapon_identity_is_current(player, fired) && switch_to.is_none_or(|handle| inventory_weapon(player, handle)) + } + } + } + + pub(super) fn record_regeneration_combat(&mut self, slot: i32) { + if !self.classic_enabled() || self.controller.current_mode().is_none_or(|mode| mode.regeneration.is_none()) { + return; + } + let Some(player) = LivePlayer::resolve(slot) else { return }; + let Some(task) = self.combat_task(player) else { return }; + self.record_regeneration_combat_for(task, f64::from(s2sdk::GetGameTime())); + } + + pub(super) fn record_regeneration_combat_for(&mut self, task: PlayerTask, now: f64) { + if self.controller.current_mode().is_none_or(|mode| mode.regeneration.is_none()) { + return; + } + let life = self.composed.lives.entry(task.player.slot).or_insert_with(|| Life::new(task, now)); + if life.task != task { + *life = Life::new(task, now); + } + life.last_combat = now; + life.regeneration_at = now; + life.breath_pending = true; + } + + pub(super) fn queue_weapon_on_fire(&mut self, player: LivePlayer, event_weapon: &str) { + if !self.composed_active() { + return; + } + let Some(settings) = self.controller.current_mode().and_then(|mode| mode.weapon_on_fire) else { + return; + }; + let Some(task) = self.combat_task(player) else { return }; + let Some(fired) = fired_weapon(player, event_weapon) else { return }; + let now = f64::from(s2sdk::GetGameTime()); + let life = self.composed.lives.entry(player.slot).or_insert_with(|| Life::new(task, now)); + if life.task != task { + *life = Life::new(task, now); + } + if now < life.weapon_ready || self.rng.random::() >= settings.chance { + return; + } + let switch_to = if self + .rng + .random_range(0..u64::from(settings.switch_weight) + u64::from(settings.drop_weight)) + < u64::from(settings.switch_weight) + { + let targets: Vec<_> = s2sdk::GetClientWeapons(player.slot) + .iter() + .copied() + .filter(|handle| *handle != fired.handle && inventory_weapon(player, *handle)) + .collect(); + let Some(target) = targets.choose(&mut self.rng) else { return }; + Some(*target) + } else { + None + }; + life.weapon_ready = now + f64::from(settings.cooldown_seconds); + self.composed.weapons.push(( + s2sdk::GetGameTickCount(), + Action::Weapon { + task, + player, + fired, + switch_to, + }, + )); + } + + pub(super) fn queue_long_flash(&mut self, slot: i32, event: usize) { + if !self.composed_active() || self.controller.current_mode().is_none_or(|mode| mode.long_flash.is_none()) { + return; + } + let Some(player) = LivePlayer::resolve(slot) else { return }; + let Some(task) = self.combat_task(player) else { return }; + let duration = f64::from(s2sdk::GetEventFloat(event, &Str::from_str("blind_duration"))); + let now = f64::from(s2sdk::GetGameTime()); + let current_until = read_flash(player, "m_blindUntilTime"); + let current_duration = read_flash(player, "m_flFlashDuration"); + let settings = self.controller.current_mode().and_then(|mode| mode.long_flash).expect("checked setting"); + let Some(pending_until) = funrounds_core::extended_flash_deadline( + now, + now + duration, + current_until, + settings.duration_multiplier, + settings.duration_cap_seconds, + ) else { + return; + }; + let previous = self.composed.flashes.get(&slot).copied().filter(|flash| flash.task == task); + let pending_until = previous.map_or(pending_until, |previous| previous.pending_until.max(pending_until)); + let mut native_until = current_until; + let mut native_duration = current_duration; + let mut installed = None; + if let Some(previous) = previous + && let Some((until, owned_duration)) = previous.installed + { + if current_until == until { + native_until = previous.native_until.max(now + duration); + } + if current_duration == owned_duration { + native_duration = previous.native_duration.max(duration); + } + installed = previous.installed; + } + self.composed.flashes.insert( + slot, + Flash { + task, + player, + native_until, + native_duration, + pending_until, + tick: s2sdk::GetGameTickCount(), + installed, + partial_write: false, + }, + ); + } + + pub(super) fn update_composed(&mut self, now: f64, tick: i32) { + self.update_big_heads(); + if !self.composed_active() { + // Hurt events can create a life during freeze. Keep their healing delay, + // but never carry frozen time into a movement penalty at freeze_end. + for life in self.composed.lives.values_mut() { + life.stopped_since = now; + life.stopped_tick = now; + life.grounded_since = now; + life.grounded_tick = now; + } + return; + } + let Some(mode) = self.controller.current_mode() else { return }; + let pending = std::mem::take(&mut self.composed.weapons); + for (queued, action) in pending { + if tick > queued { + self.engine_actions.push(EngineAction::Composed(action)); + } else { + self.composed.weapons.push((queued, action)); + } + } + let mut flashes = std::mem::take(&mut self.composed.flashes).into_iter(); + while let Some((slot, mut flash)) = flashes.next() { + if self.combat_task(flash.player) != Some(flash.task) || LivePlayer::resolve(slot) != Some(flash.player) { + if !restore_flash(&mut flash) { + self.composed.flashes.insert(slot, flash); + } + continue; + } + if flash.pending_until > 0.0 && tick > flash.tick { + let current = read_flash(flash.player, "m_blindUntilTime"); + let target = flash.pending_until; + flash.pending_until = 0.0; + if target > current { + let duration = read_flash(flash.player, "m_flFlashDuration") + target - current; + let until = f64::from(target as f32); + let duration = f64::from(duration as f32); + let previous_installed = flash.installed; + flash.installed = Some((until, duration)); + flash.partial_write = true; + if !write_flash(flash.player, "m_blindUntilTime", until) || !write_flash(flash.player, "m_flFlashDuration", duration) { + // A failed extension can leave either field at our + // previous installed value; keep that ownership too. + if let Some((previous_until, previous_duration)) = previous_installed { + flash.installed = Some(( + if read_flash(flash.player, "m_blindUntilTime") == previous_until { + previous_until + } else { + until + }, + if read_flash(flash.player, "m_flFlashDuration") == previous_duration { + previous_duration + } else { + duration + }, + )); + } + self.composed.flashes.insert(slot, flash); + self.composed.flashes.extend(flashes); + self.handle_fault(Fault::mechanism(Mechanism::LongFlash, "long_flash schema write/readback failed")); + return; + } + flash.partial_write = false; + } + } + if flash.pending_until > 0.0 || flash.installed.is_some_and(|(until, _)| until > now) { + self.composed.flashes.insert(slot, flash); + } + } + let chicken_positions: Vec<_> = if mode.chicken_aura.is_some() { + self.ordinary_chickens + .entities + .active_handles(self.controller.generation()) + .into_iter() + .filter(|handle| crate::chicken_entities::health(*handle).is_some_and(|(health, state)| health > 0 && state == 0)) + .filter_map(crate::chicken_entities::position) + .collect() + } else { + Vec::new() + }; + for slot in 0..s2sdk::GetMaxClients() { + let Some(player) = LivePlayer::resolve(slot) else { continue }; + let Some(task) = self.combat_task(player) else { continue }; + let Some((expected, combat)) = self.combat.lives.get(&slot).filter(|(expected, _)| *expected == task) else { + continue; + }; + let base = i32::from(combat.attributes().health); + let protected = combat.protected(now as f32); + let task = *expected; + if self.effects.get(&slot).is_none_or(|effect| effect.has_pending_loadout()) { + continue; + } + let life = self.composed.lives.entry(slot).or_insert_with(|| Life::new(task, now)); + if life.task != task { + *life = Life::new(task, now); + } + if let Some(settings) = mode.chicken_aura + && now >= life.aura_at + { + life.aura_at = now + f64::from(settings.interval_seconds); + let position = s2sdk::GetClientAbsOrigin(slot); + if chicken_positions.iter().any(|chicken| { + (chicken.x - position.x).powi(2) + (chicken.y - position.y).powi(2) + (chicken.z - position.z).powi(2) <= settings.radius.powi(2) + }) && let Err(error) = heal(slot, base, settings.heal, mode.healing_cap_base_multiple, Mechanism::ChickenAura) + { + self.handle_fault(error); + return; + } + } + if let Some(settings) = mode.dont_stop { + let velocity = s2sdk::GetClientAbsVelocity(slot); + if protected + || !matches!(self.controller.phase(), Phase::Running | Phase::Warmup) + || velocity.x.hypot(velocity.y) >= settings.minimum_horizontal_speed + { + life.stopped_since = now; + life.stopped_tick = now; + } else if now >= life.stopped_since + f64::from(settings.grace_seconds) && now >= life.stopped_tick { + life.stopped_tick = now + f64::from(settings.damage_interval_seconds); + self.engine_actions.push(EngineAction::Composed(Action::Penalty { + task, + player, + amount: settings.damage as f32, + burn: false, + })); + } + } + if let Some(settings) = mode.hot_floor { + if protected || !matches!(self.controller.phase(), Phase::Running | Phase::Warmup) || s2sdk::GetClientFlags(slot) & 1 == 0 { + life.grounded_since = now; + life.grounded_tick = now; + } else { + let elapsed = now - life.grounded_since; + if elapsed >= f64::from(settings.grounded_seconds) && now >= life.grounded_tick { + life.grounded_tick = now + f64::from(settings.damage_interval_seconds); + self.engine_actions.push(EngineAction::Composed(Action::Penalty { + task, + player, + amount: settings.damage as f32, + burn: true, + })); + } + if elapsed >= f64::from(settings.ignite_after_seconds) { + self.afterburns.refresh_source( + task, + player, + now, + funrounds_core::AfterburnSettings { + duration_seconds: settings.burn_duration_seconds, + damage_fraction: settings.burn_damage_fraction, + minimum_damage: settings.burn_minimum_damage, + }, + true, + ); + if self.afterburns.queue_ignite(task, player) { + self.engine_actions + .push(EngineAction::Afterburn(super::afterburn::Action::Ignite { task, player })); + } + } + } + } + } + self.composed + .lives + .retain(|slot, life| self.players.identity(*slot) == Some(life.task.player)); + } + + pub(crate) fn settle_regeneration(&mut self, now: f64) { + if !self.composed_active() { + return; + } + let Some(mode) = self.controller.current_mode() else { return }; + let Some(settings) = mode.regeneration else { return }; + let cap = mode.healing_cap_base_multiple; + // Native penalty and delayed damage actions dispatch hurt synchronously. + // Check the latest combat time only after those actions have settled. + for (&slot, life) in &mut self.composed.lives { + if now < life.last_combat + f64::from(settings.delay_seconds) || now < life.regeneration_at { + continue; + } + let Some(player) = LivePlayer::resolve(slot) else { continue }; + let Some((expected, combat)) = self.combat.lives.get(&slot) else { + continue; + }; + if *expected != life.task + || !self.players.validates(life.task, self.controller.generation(), player.pawn_handle as u32) + || self.controllers.get(&slot) != Some(&player.controller_handle) + || self.effects.get(&slot).is_none_or(|effect| effect.has_pending_loadout()) + { + continue; + } + life.regeneration_at = now + f64::from(settings.interval_seconds); + match heal(slot, i32::from(combat.attributes().health), settings.heal, cap, Mechanism::Regeneration) { + Ok(true) if life.breath_pending => { + life.breath_pending = false; + // Short native gasp; the looping Hostage.Breath track is reserved for Ghost. + s2sdk::EmitSoundToClient( + player.pawn_handle, + &plugify::Arr::from(vec![slot]), + &Str::from_str("Hostage.Pain"), + 0.6, + 100.0, + ); + } + Ok(_) => {} + Err(error) => { + self.handle_fault(error); + return; + } + } + } + } + + pub(super) fn update_big_heads(&mut self) { + if !self.classic_enabled() || self.controller.phase() == Phase::Idle { + return; + } + let Some(mode) = self.controller.current_mode() else { return }; + if mode.big_head.is_some() + && !unsafe { crate::funrounds_native::__funrounds_native_HasBigHeadScaleSupport }.is_some_and(|query| unsafe { query() }) + { + self.handle_fault(Fault::mechanism(Mechanism::BigHead, "native Big Head support or owned state lost")); + return; + } + if self.composed.head_round != Some(self.controller.generation()) { + self.composed.head_round = Some(self.controller.generation()); + self.composed.head_scales.clear(); + if let Some(settings) = mode.big_head { + for slot in 0..s2sdk::GetMaxClients() { + if s2sdk::IsClientInGame(slot) { + self.composed.head_scales.insert( + s2sdk::PlayerSlotToEntHandle(slot), + funrounds_core::big_head_scale( + s2sdk::GetClientKills(slot).max(0) as u32, + s2sdk::GetClientDeaths(slot).max(0) as u32, + settings.min_scale, + settings.max_scale, + ), + ); + } + } + } + } + for slot in 0..s2sdk::GetMaxClients() { + let Some(player) = LivePlayer::resolve(slot) else { continue }; + if self.combat_task(player).is_none() { + continue; + } + if let Some(settings) = mode.big_head { + // A respawn or takeover reuses this round's controller snapshot; no mid-round K/D resampling. + let scale = self.composed.heads.get(&player.pawn_handle).copied().unwrap_or_else(|| { + *self.composed.head_scales.entry(player.controller_handle).or_insert_with(|| { + funrounds_core::big_head_scale( + s2sdk::GetClientKills(slot).max(0) as u32, + s2sdk::GetClientDeaths(slot).max(0) as u32, + settings.min_scale, + settings.max_scale, + ) + }) + }); + if self.composed.heads.get(&player.pawn_handle) != Some(&scale) { + self.composed.heads.insert(player.pawn_handle, scale); + if !unsafe { crate::funrounds_native::__funrounds_native_SetBigHeadScaleTarget } + .is_some_and(|set| unsafe { set(player.pawn_handle, scale) }) + { + self.handle_fault(Fault::mechanism(Mechanism::BigHead, "Big Head target registration failed")); + return; + } + } + } + } + } + + pub(super) fn clear_composed_life(&mut self, identity: PlayerIdentity) { + if self.composed.lives.get(&identity.slot).is_some_and(|life| life.task.player == identity) { + self.composed.lives.remove(&identity.slot); + } + self.composed.weapons.retain(|(_, action)| action.task().player != identity); + if let Some(mut flash) = self.composed.flashes.remove(&identity.slot) + && (flash.task.player != identity || !restore_flash(&mut flash)) + { + self.composed.flashes.insert(identity.slot, flash); + if flash.task.player == identity { + self.record_fault(Fault::mechanism(Mechanism::LongFlash, "long_flash life restoration pending")); + } + } + let handle = identity.pawn_handle as i32; + if self.composed.heads.contains_key(&handle) { + if unsafe { crate::funrounds_native::__funrounds_native_ClearBigHeadScaleTarget }.is_some_and(|clear| unsafe { clear(handle) }) { + self.composed.heads.remove(&handle); + } else { + self.record_fault(Fault::mechanism(Mechanism::BigHead, "Big Head life restoration pending")); + } + } + } + + pub(super) fn takeover_composed(&mut self, task: PlayerTask, player: LivePlayer) { + if let Some(slot) = self + .composed + .lives + .iter() + .find_map(|(slot, life)| (life.task.round == task.round && life.task.player.pawn_handle == task.player.pawn_handle).then_some(*slot)) + && let Some(mut life) = self.composed.lives.remove(&slot) + { + life.task = task; + self.composed.lives.insert(player.slot, life); + } + if let Some(slot) = self + .composed + .flashes + .iter() + .find_map(|(slot, flash)| (flash.task.round == task.round && flash.player.pawn_handle == player.pawn_handle).then_some(*slot)) + && let Some(mut flash) = self.composed.flashes.remove(&slot) + && flash.installed.is_some() + { + flash.task = task; + flash.player = player; + flash.pending_until = 0.0; + self.composed.flashes.insert(player.slot, flash); + } + } + + pub(super) fn cleanup_composed(&mut self) { + self.composed.lives.clear(); + self.composed.weapons.clear(); + for (slot, mut flash) in std::mem::take(&mut self.composed.flashes) { + if !restore_flash(&mut flash) { + self.composed.flashes.insert(slot, flash); + } + } + let clear = unsafe { crate::funrounds_native::__funrounds_native_ClearBigHeadScaleTarget }; + self.composed + .heads + .retain(|handle, _| !clear.is_some_and(|clear| unsafe { clear(*handle) })); + if !self.composed.flashes.is_empty() { + self.record_fault(Fault::mechanism(Mechanism::LongFlash, "long_flash restoration pending")); + } + if !self.composed.heads.is_empty() { + self.record_fault(Fault::mechanism(Mechanism::BigHead, "Big Head restoration pending")); + } + } +} + +fn inventory_weapon(player: LivePlayer, handle: i32) -> bool { + s2sdk::IsValidEntHandle(handle) + && s2sdk::GetEntityOwner(handle) == player.pawn_handle + && s2sdk::GetClientWeapons(player.slot).iter().any(|current| *current == handle) + && { + let class = s2sdk::GetEntityClassname(handle); + class.as_str().starts_with("weapon_") + } +} + +pub(super) fn heal(slot: i32, base: i32, amount: funrounds_core::HealingAmount, cap: f32, mechanism: Mechanism) -> Result { + if let Some(amount) = amount.amount(base) + && let Some(target) = funrounds_core::healing_target(base, s2sdk::GetClientHealth(slot), amount, cap) + { + s2sdk::SetClientHealth(slot, target); + if s2sdk::GetClientHealth(slot) != target { + return Err(Fault::mechanism(mechanism, "shared healing write/readback failed")); + } + return Ok(true); + } + Ok(false) +} + +pub(crate) fn execute(action: Action) -> Result<(), Fault> { + match action { + Action::Weapon { + player, fired, switch_to, .. + } => { + if let Some(target) = switch_to { + s2sdk::SwitchWeapon(player.slot, target); + } else { + let zero = plugify::Vec3 { x: 0.0, y: 0.0, z: 0.0 }; + s2sdk::DropWeapon(player.slot, fired.handle, &zero, &zero); + } + } + Action::Penalty { player, amount, burn, .. } => { + let zero = plugify::Vec3 { x: 0.0, y: 0.0, z: 0.0 }; + crate::damage::with_internal_damage_context( + crate::damage::InternalDamageContext { + victim: player.pawn_handle, + attacker: player.pawn_handle, + inflictor: player.pawn_handle, + weapon: -1, + victim_slot: player.slot, + attacker_slot: player.slot, + headshot: false, + check_protection: true, + suppress_lifesteal: true, + random_heal: None, + death_weapon: Some(if burn { "hot_floor" } else { "dont_stop" }.into()), + }, + || { + crate::damage::apply_native_damage( + crate::damage::NativeDamageCall { + victim: player.pawn_handle, + attacker: player.pawn_handle, + inflictor: player.pawn_handle, + force: &zero, + position: &zero, + amount, + damage_type: if burn { crate::damage::DMG_BURN } else { 0 }, + weapon: -1, + skip_plugin_rules: true, + }, + if burn { Mechanism::HotFloor } else { Mechanism::DontStop }, + "movement penalty native damage rejected", + ) + }, + )?; + } + } + Ok(()) +} diff --git a/crates/funrounds-plugin/src/runtime/grapple.rs b/crates/funrounds-plugin/src/runtime/grapple.rs new file mode 100644 index 0000000..1fca57d --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/grapple.rs @@ -0,0 +1,1027 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::*; +use plugify::{Vec3, Vec4}; +use std::collections::{HashMap, VecDeque}; + +const IN_JUMP: u64 = 1 << 1; +const IN_USE: u64 = 1 << 5; +const TRACE_MASK: i32 = 798737; +const GRAPPLE_GRAVITY: f32 = 0.001; +const BEAM_WIDTH: f64 = 3.0; +const BEAM_COLOR: Vec4 = Vec4 { + x: 255.0, + y: 60.0, + z: 60.0, + w: 255.0, +}; +const WORLD_CLASS: &str = "worldent"; +const BEAM_CLASS: &str = "beam"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Input { + identity: PlayerIdentity, + sampled_down: bool, + armed: bool, + attempt_consumed: bool, + native_target_won: bool, +} + +impl Input { + fn new(identity: PlayerIdentity, down: bool) -> Self { + Self { + identity, + sampled_down: down, + armed: !down, + attempt_consumed: down, + native_target_won: false, + } + } + + fn sample(&mut self, down: bool) { + if !down { + self.sampled_down = false; + self.armed = true; + self.attempt_consumed = false; + self.native_target_won = false; + } else if !self.sampled_down { + self.sampled_down = true; + self.attempt_consumed = !self.armed; + } + } + + fn can_attempt(&self) -> bool { + self.sampled_down && self.armed && !self.attempt_consumed && !self.native_target_won + } +} + +#[derive(Clone, Copy)] +struct Observation { + identity: PlayerIdentity, + tick: i32, + target: i32, + in_use: bool, + target_valid: bool, + chicken_claimed: bool, +} + +impl Observation { + fn new(identity: PlayerIdentity, tick: i32, target: i32, in_use: bool) -> Self { + Self { + identity, + tick, + target, + in_use, + // UseTarget's native callback is invoked only after it has checked + // IsValid, round-tripped the complete handle, and committed the + // selected target. Preserve that callback-time winner even if the + // entity is removed before this tick's observations are drained. + target_valid: in_use && target != -1, + chicken_claimed: false, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SelectorDecision { + NativeTarget, + Empty, +} + +#[derive(Default)] +struct SelectorBatch { + native_target: bool, + empty_target: bool, +} + +impl SelectorBatch { + fn observe(&mut self, observation: Observation) { + if !observation.in_use { + return; + } + if observation.chicken_claimed || observation.target_valid { + self.native_target = true; + } else if observation.target == -1 { + self.empty_target = true; + } + } + + fn decision(&self) -> Option { + if self.native_target { + Some(SelectorDecision::NativeTarget) + } else if self.empty_target { + Some(SelectorDecision::Empty) + } else { + None + } + } +} + +struct Active { + task: PlayerTask, + player: LivePlayer, + anchor: Vec3, + settings: funrounds_core::GrappleSettings, + beam: Option, +} + +#[derive(Default)] +pub(super) struct State { + input: HashMap, + observations: VecDeque, + active: HashMap, + retired_beams: HashMap, + bomb_use: HashMap, +} + +#[derive(Clone, Copy)] +pub(crate) enum Action { + Acquire { + task: PlayerTask, + player: LivePlayer, + settings: funrounds_core::GrappleSettings, + }, + Pull { + task: PlayerTask, + player: LivePlayer, + anchor: Vec3, + beam: i32, + settings: funrounds_core::GrappleSettings, + }, + RemoveBeam { + handle: i32, + }, +} + +impl State { + fn sample(&mut self, identity: PlayerIdentity, down: bool) { + let state = self.input.entry(identity.slot).or_insert_with(|| Input::new(identity, down)); + if state.identity != identity { + *state = Input::new(identity, down); + } else { + state.sample(down); + } + } + + fn queue_observation(&mut self, observation: Observation) { + if observation.in_use && (observation.target_valid || observation.chicken_claimed) { + self.confirm_native_target(observation.identity); + } + self.observations.push_back(observation); + } + + fn take_closed_tick_observations(&mut self, tick: i32) -> Vec { + let mut closed = Vec::new(); + while self.observations.front().is_some_and(|observation| observation.tick < tick) { + closed.push(self.observations.pop_front().expect("front observation exists")); + } + closed + } + + fn consume_attempt(&mut self, identity: PlayerIdentity) -> bool { + let Some(input) = self + .input + .get_mut(&identity.slot) + .filter(|input| input.identity == identity && input.can_attempt()) + else { + return false; + }; + input.attempt_consumed = true; + true + } + + fn win_native_target(&mut self, identity: PlayerIdentity) { + if let Some(input) = self + .input + .get_mut(&identity.slot) + .filter(|input| input.identity == identity && input.sampled_down) + { + input.attempt_consumed = true; + input.native_target_won = true; + } + } + + fn confirm_native_target(&mut self, identity: PlayerIdentity) { + let input = self.input.entry(identity.slot).or_insert_with(|| Input::new(identity, false)); + if input.identity != identity { + *input = Input::new(identity, false); + } + input.attempt_consumed = true; + input.native_target_won = true; + } + + fn input_allows_action(&self, identity: PlayerIdentity) -> bool { + self.input + .get(&identity.slot) + .is_some_and(|input| input.identity == identity && input.sampled_down && !input.native_target_won) + } + + fn begin_bomb_use(&mut self, identity: PlayerIdentity) { + self.bomb_use.insert(identity.slot, identity); + self.confirm_native_target(identity); + } + + fn end_bomb_use(&mut self, identity: PlayerIdentity) { + if self.bomb_use.get(&identity.slot) == Some(&identity) { + self.bomb_use.remove(&identity.slot); + } + } + + fn native_bomb_use(&self, identity: PlayerIdentity) -> bool { + self.bomb_use.get(&identity.slot) == Some(&identity) + } + + fn retire_beam(&mut self, handle: i32) { + if handle != -1 { + self.retired_beams.entry(handle).or_insert(false); + } + } + + fn take_beam_cleanup_actions(&mut self) -> Vec { + self.retired_beams.keys().copied().map(|handle| Action::RemoveBeam { handle }).collect() + } + + fn beam_cleanup_complete(&mut self, handle: i32, complete: bool) { + if complete { + self.retired_beams.remove(&handle); + } else if let Some(requested) = self.retired_beams.get_mut(&handle) { + *requested = true; + } + } + + pub(super) fn is_clean(&self) -> bool { + self.active.is_empty() && self.retired_beams.is_empty() && self.observations.is_empty() && self.bomb_use.is_empty() + } + + fn claim_chicken_target(&mut self, identity: PlayerIdentity, tick: i32, target: i32) { + let matched = if let Some(observation) = + self.observations.iter_mut().rev().find(|observation| { + observation.identity == identity && observation.tick == tick && observation.target == target && observation.in_use + }) { + observation.chicken_claimed = true; + true + } else { + let mut observation = Observation::new(identity, tick, target, true); + observation.chicken_claimed = true; + self.queue_observation(observation); + false + }; + if matched { + self.win_native_target(identity); + } + } +} + +pub(super) fn capability_probe(reasons: &mut Vec) -> bool { + let mut probe = crate::capability::Probe::default(); + crate::capability::imports!(probe; + __s2sdk_GetClientButtons, __s2sdk_GetGameTickCount, __s2sdk_GetClientEyePosition, __s2sdk_GetClientEyeAngles, + __s2sdk_TraceLine, __s2sdk_IsValidEntHandle, __s2sdk_EntHandleToEntPointer, __s2sdk_EntIndexToEntHandle, + __s2sdk_GetEntityClassname, __s2sdk_GetEntityMoveType, __s2sdk_GetEntityAbsOrigin, __s2sdk_GetEntityAbsVelocity, + __s2sdk_SetEntityAbsVelocity, __s2sdk_GetClientGravity, __s2sdk_SetClientGravity, + __s2sdk_GetSchemaOffset, __s2sdk_CreateEntityByName, __s2sdk_DispatchSpawn, __s2sdk_TeleportEntity, + __s2sdk_RemoveEntity, __s2sdk_SetEntSchemaFloat2, __s2sdk_GetEntSchemaFloat2, + __s2sdk_SetEntSchemaVector3D2, __s2sdk_GetEntSchemaVector3D2, __s2sdk_SetEntSchemaColor, + __s2sdk_GetEntSchemaColor, + ); + probe.require( + unsafe { crate::funrounds_native::__funrounds_native_HasUseTargetSupport }.is_some(), + "native:HasUseTargetSupport", + ); + probe.require( + unsafe { crate::funrounds_native::__funrounds_native_HookUseTarget }.is_some(), + "native:HookUseTarget", + ); + probe.require( + unsafe { crate::funrounds_native::__funrounds_native_UnhookUseTarget }.is_some(), + "native:UnhookUseTarget", + ); + probe.schema("CBeam", "m_vecEndPos"); + probe.schema("CBeam", "m_fWidth"); + probe.schema("CBaseModelEntity", "m_clrRender"); + probe.record("grapple", reasons) +} + +fn finite_vec(value: Vec3) -> bool { + value.x.is_finite() && value.y.is_finite() && value.z.is_finite() +} + +fn vector_near(actual: Vec3, expected: Vec3, tolerance: f32) -> bool { + finite_vec(actual) + && finite_vec(expected) + && (actual.x - expected.x).abs() <= tolerance + && (actual.y - expected.y).abs() <= tolerance + && (actual.z - expected.z).abs() <= tolerance +} + +fn color_near(actual: Vec4, expected: Vec4, tolerance: f32) -> bool { + (actual.x - expected.x).abs() <= tolerance + && (actual.y - expected.y).abs() <= tolerance + && (actual.z - expected.z).abs() <= tolerance + && (actual.w - expected.w).abs() <= tolerance +} + +fn beam_pointer(handle: i32) -> Option { + if !s2sdk::IsValidEntHandle(handle) { + return None; + } + let pointer = s2sdk::EntHandleToEntPointer(handle); + (pointer != 0).then_some(pointer) +} + +fn trace_world_anchor(player: LivePlayer, settings: funrounds_core::GrappleSettings) -> Option { + let start = s2sdk::GetClientEyePosition(player.slot); + let angles = s2sdk::GetClientEyeAngles(player.slot); + if !finite_vec(start) || !finite_vec(angles) { + return None; + } + let pitch = angles.x.to_radians(); + let yaw = angles.y.to_radians(); + let forward = Vec3 { + x: pitch.cos() * yaw.cos(), + y: pitch.cos() * yaw.sin(), + z: -pitch.sin(), + }; + let end = Vec3 { + x: start.x + forward.x * settings.max_distance, + y: start.y + forward.y * settings.max_distance, + z: start.z + forward.z * settings.max_distance, + }; + let mut hit_position = Vec3::default(); + let mut fraction = 1.0; + let mut hit = false; + let mut hit_handle = -1; + let mut start_solid = false; + let traced = s2sdk::TraceLine( + &start, + &end, + TRACE_MASK, + player.pawn_handle, + &mut hit_position, + &mut fraction, + &mut hit, + &mut hit_handle, + &mut start_solid, + ); + let world = s2sdk::EntIndexToEntHandle(0); + (traced + && hit + && !start_solid + && fraction.is_finite() + && (0.0..1.0).contains(&fraction) + && finite_vec(hit_position) + && hit_handle == world + && beam_pointer(hit_handle).is_some() + && s2sdk::GetEntityClassname(hit_handle).as_str() == WORLD_CLASS) + .then_some(hit_position) +} + +fn create_beam(player: LivePlayer, anchor: Vec3) -> Result)> { + let start = s2sdk::GetClientEyePosition(player.slot); + if !finite_vec(start) { + return Err(("player eye position is not finite".into(), None)); + } + let handle = s2sdk::CreateEntityByName(&Str::from_str(BEAM_CLASS)); + if beam_pointer(handle).is_none() { + return Err(("beam entity creation returned no full entity handle".into(), None)); + } + let result = (|| { + if s2sdk::GetEntityClassname(handle).as_str() != BEAM_CLASS { + return Err("created beam handle resolved to another entity class".into()); + } + let pointer = beam_pointer(handle).ok_or_else(|| "created beam handle became invalid before setup".to_owned())?; + let end_class = Str::from_str("CBeam"); + let end_field = Str::from_str("m_vecEndPos"); + let width_class = Str::from_str("CBeam"); + let width_field = Str::from_str("m_fWidth"); + let color_class = Str::from_str("CBaseModelEntity"); + let color_field = Str::from_str("m_clrRender"); + let zero = Vec3::default(); + s2sdk::SetEntSchemaFloat2(pointer, &width_class, &width_field, BEAM_WIDTH, true, 0); + s2sdk::SetEntSchemaColor(handle, &color_class, &color_field, &BEAM_COLOR, true, 0); + s2sdk::SetEntSchemaVector3D2(pointer, &end_class, &end_field, &anchor, true, 0); + s2sdk::TeleportEntity(handle, &start, &zero, &zero); + if beam_pointer(handle).is_none() || LivePlayer::resolve(player.slot) != Some(player) { + return Err("player or beam identity changed before beam spawn".into()); + } + s2sdk::DispatchSpawn(handle); + let pointer = beam_pointer(handle).ok_or_else(|| "beam disappeared during spawn".to_owned())?; + if s2sdk::GetEntityClassname(handle).as_str() != BEAM_CLASS { + return Err("spawned entity no longer resolves to beam".into()); + } + let origin = s2sdk::GetEntityAbsOrigin(handle); + let end = s2sdk::GetEntSchemaVector3D2(pointer, &end_class, &end_field, 0); + let width = s2sdk::GetEntSchemaFloat2(pointer, &width_class, &width_field, 0) as f32; + let color = s2sdk::GetEntSchemaColor(handle, &color_class, &color_field, 0); + if !vector_near(origin, start, 0.25) + || !vector_near(end, anchor, 0.25) + || (width - BEAM_WIDTH as f32).abs() > 0.01 + || !color_near(color, BEAM_COLOR, 1.0) + { + return Err("beam setup readback did not match endpoint, width, or color".into()); + } + Ok(()) + })(); + if let Err(error) = result { + if beam_pointer(handle).is_some() { + s2sdk::RemoveEntity(handle); + } + return Err((error, beam_pointer(handle).is_some().then_some(handle))); + } + Ok(handle) +} + +fn update_beam(handle: i32, start: Vec3, anchor: Vec3) -> Result<(), String> { + if s2sdk::GetEntityClassname(handle).as_str() != BEAM_CLASS { + return Err("owned beam handle or classname was lost".into()); + } + let pointer = beam_pointer(handle).ok_or_else(|| "owned beam handle no longer resolves".to_owned())?; + let class = Str::from_str("CBeam"); + let end_field = Str::from_str("m_vecEndPos"); + let zero = Vec3::default(); + s2sdk::TeleportEntity(handle, &start, &zero, &zero); + s2sdk::SetEntSchemaVector3D2(pointer, &class, &end_field, &anchor, true, 0); + let origin = s2sdk::GetEntityAbsOrigin(handle); + let endpoint = s2sdk::GetEntSchemaVector3D2(pointer, &class, &end_field, 0); + if !vector_near(origin, start, 0.25) || !vector_near(endpoint, anchor, 0.25) { + return Err("beam endpoint update failed readback".into()); + } + Ok(()) +} + +fn remove_beam(handle: i32) -> bool { + if beam_pointer(handle).is_none() { + return true; + } + s2sdk::RemoveEntity(handle); + beam_pointer(handle).is_none() +} + +impl Runtime { + pub(super) fn refresh_grapple_capability(&mut self) { + if self.faults.capabilities().grapple || self.faults.recovery == Recovery::Stopped || !self.use_target_hook_ready { + return; + } + self.grapple_use_hook_ready(); + } + + pub(super) fn grapple_configured(&self) -> bool { + self.controller + .config() + .is_some_and(|config| mode_configured(config, |mode| mode.grapple.is_some())) + } + + pub(super) fn use_target_probe_ready(&self) -> bool { + (0..s2sdk::GetMaxClients()).any(|slot| { + LivePlayer::resolve(slot).is_some_and(|player| { + self.players + .identity(slot) + .is_some_and(|identity| identity.pawn_handle == player.pawn_handle as u32) + && self.controllers.get(&slot) == Some(&player.controller_handle) + }) + }) + } + + pub(super) fn grapple_use_hook_ready(&mut self) { + if !self.grapple_configured() { + return; + } + if !self.grapple_bomb_use_ready { + self.grapple_use_hook_failure("required C4 plant/defuse lifecycle events unavailable"); + return; + } + self.capability_reasons.retain(|reason| !reason.starts_with("grapple:")); + if !capability_probe(&mut self.capability_reasons) || !self.faults.enable_grapple() { + return; + } + self.capability_reasons.retain(|reason| !reason.starts_with("grapple:")); + self.controller.set_capabilities(self.faults.capabilities()); + log("grapple capability is ready after the live use-target observer was installed"); + } + + pub(super) fn grapple_use_hook_failure(&mut self, reason: impl Into) { + let reason = reason.into(); + let first = self.faults.exclude(Mechanism::Grapple, reason.clone()); + if first { + self.capability_reasons.push(format!("grapple:[{reason}]")); + } + self.controller.set_capabilities(self.faults.capabilities()); + if first { + log(&format!("grapple capability unavailable: {reason}")); + } + } + + pub(super) fn wants_use_target_hook(&self) -> bool { + self.chicken_use_configured() || self.grapple_configured() + } + + pub(super) fn grapple_mode_active(&self) -> bool { + self.controller.enabled() + && active_combat_phase(self.controller.phase()) + && self.faults.capabilities().grapple + && self.controller.current_mode().is_some_and(|mode| mode.grapple.is_some()) + } + + pub(super) fn observe_grapple_buttons(&mut self, tick: i32) { + let mode = self.controller.current_mode().cloned(); + let enabled = self.grapple_mode_active() && self.use_target_hook_ready; + if !enabled && self.grapple.active.is_empty() { + self.grapple.input.clear(); + self.grapple.observations.clear(); + return; + } + let mut live = HashSet::new(); + for slot in 0..s2sdk::GetMaxClients() { + let Some(player) = LivePlayer::resolve(slot) else { continue }; + let Some(identity) = self + .players + .identity(slot) + .filter(|identity| identity.pawn_handle == player.pawn_handle as u32) + else { + continue; + }; + if self.controllers.get(&slot) != Some(&player.controller_handle) || player.pawn_controller() != Some(player.controller_handle) { + continue; + } + if !enabled && !self.grapple.active.contains_key(&slot) { + continue; + } + live.insert(slot); + let buttons = s2sdk::GetClientButtons(slot, 0); + if let Some(effect) = self.effects.get_mut(&slot).filter(|effect| effect.identity == identity) { + effect.observe_movement_buttons(buttons); + } + self.grapple.sample(identity, buttons & IN_USE != 0); + } + self.grapple + .input + .retain(|slot, input| live.contains(slot) || self.players.identity(*slot) == Some(input.identity)); + + let mut batches: Vec<(PlayerIdentity, i32, SelectorBatch)> = Vec::new(); + for observation in self.grapple.take_closed_tick_observations(tick) { + let Some(player) = LivePlayer::resolve(observation.identity.slot) else { + continue; + }; + if player.pawn_handle as u32 != observation.identity.pawn_handle + || self.players.identity(observation.identity.slot) != Some(observation.identity) + || self.controllers.get(&player.slot) != Some(&player.controller_handle) + { + continue; + } + let batch = if let Some(batch) = batches + .iter_mut() + .find(|(identity, tick, _)| *identity == observation.identity && *tick == observation.tick) + { + batch + } else { + batches.push((observation.identity, observation.tick, SelectorBatch::default())); + batches.last_mut().expect("batch was just inserted") + }; + batch.2.observe(observation); + } + for (identity, _, batch) in batches { + let decision = batch.decision(); + match decision { + Some(SelectorDecision::NativeTarget) => { + self.grapple.win_native_target(identity); + self.cancel_grapple(identity, StopReason::NativeTarget); + } + Some(SelectorDecision::Empty) if enabled => { + if let Some(settings) = mode.as_ref().and_then(|mode| mode.grapple) { + let task = PlayerTask { + player: identity, + round: self.controller.generation(), + }; + let Some(player) = LivePlayer::resolve(identity.slot) else { continue }; + let not_suicide = !self.suicides.active(player); + if not_suicide && self.grapple.consume_attempt(identity) && !self.grapple.active.contains_key(&identity.slot) { + self.engine_actions + .push(EngineAction::Grapple(Action::Acquire { task, player, settings })); + } + } + } + Some(SelectorDecision::Empty) | None => {} + } + } + + for slot in 0..s2sdk::GetMaxClients() { + let Some(active) = self.grapple.active.get(&slot) else { continue }; + let identity = active.task.player; + let Some(player) = LivePlayer::resolve(slot) else { + self.cancel_grapple(identity, StopReason::LifeEnded); + continue; + }; + let invalid = identity != self.players.identity(slot).unwrap_or(identity) + || player != active.player + || self.controllers.get(&slot) != Some(&player.controller_handle) + || self.controller.generation() != active.task.round + || self.suicides.active(player) + || s2sdk::GetEntityMoveType(player.pawn_handle) != s2sdk::MoveType::Walk + || self + .effects + .get(&slot) + .is_none_or(|effect| effect.temporary_movement_owner() != Some(crate::effects::TemporaryMovementOwner::Grapple)); + let buttons = s2sdk::GetClientButtons(slot, 0); + if invalid || buttons & IN_USE == 0 { + self.cancel_grapple( + identity, + if invalid { + StopReason::MovementInvalidated + } else { + StopReason::InputReleased + }, + ); + continue; + } + if let Some(active) = self.grapple.active.get(&slot) + && let Some(beam) = active.beam + { + self.engine_actions.push(EngineAction::Grapple(Action::Pull { + task: active.task, + player: active.player, + anchor: active.anchor, + beam, + settings: active.settings, + })); + } + } + + for handle in self.grapple.retired_beams.keys().copied() { + self.engine_actions.push(EngineAction::Grapple(Action::RemoveBeam { handle })); + } + } + + pub(crate) fn observe_grapple_target(&mut self, pawn_handle: i32, target_handle: i32, in_use: bool) { + if !self.grapple_configured() && self.grapple.active.is_empty() { + return; + } + let Some(identity) = self + .controllers + .keys() + .find_map(|slot| self.players.identity(*slot).filter(|identity| identity.pawn_handle == pawn_handle as u32)) + else { + return; + }; + let observation = Observation::new(identity, s2sdk::GetGameTickCount(), target_handle, in_use); + self.grapple.queue_observation(observation); + } + + pub(super) fn mark_chicken_target_claimed(&mut self, identity: PlayerIdentity, tick: i32, target: i32) { + if self.grapple_configured() || !self.grapple.active.is_empty() { + self.grapple.claim_chicken_target(identity, tick, target); + } + } + + pub(super) fn cancel_grapple(&mut self, identity: PlayerIdentity, reason: StopReason) { + let Some(active) = self + .grapple + .active + .get(&identity.slot) + .filter(|active| active.task.player.pawn_handle == identity.pawn_handle) + else { + return; + }; + let task = active.task; + if let Some(beam) = active.beam { + self.grapple.retire_beam(beam); + } + self.grapple.active.remove(&identity.slot); + let wait = match reason { + StopReason::InputReleased => IN_USE, + StopReason::NativeTarget + | StopReason::Defusing + | StopReason::Planting + | StopReason::MovementInvalidated + | StopReason::Impulse + | StopReason::LifeEnded + | StopReason::RoundEnded => IN_USE | IN_JUMP, + }; + if let Some(effect) = self + .effects + .get_mut(&identity.slot) + .filter(|effect| effect.identity == task.player && effect.round == task.round) + && let Err(error) = effect.stop_temporary_movement(wait) + { + self.handle_fault(error.context(format!("grapple release slot={}", identity.slot))); + } + if self.diagnostics() { + log(&format!( + "grapple=stopped slot={} pawn={} reason={reason:?}", + identity.slot, identity.pawn_handle + )); + } + } + + pub(super) fn cancel_grapple_player(&mut self, slot: i32) { + if let Some(active) = self.grapple.active.get(&slot) { + self.cancel_grapple(active.task.player, StopReason::LifeEnded); + } + self.grapple.input.remove(&slot); + self.grapple.observations.retain(|observation| observation.identity.slot != slot); + self.grapple.bomb_use.remove(&slot); + } + + pub(super) fn cancel_all_grapples(&mut self, reason: StopReason) { + let identities = self.grapple.active.values().map(|active| active.task.player).collect::>(); + for identity in identities { + self.cancel_grapple(identity, reason); + } + self.grapple.input.clear(); + self.grapple.observations.clear(); + self.grapple.bomb_use.clear(); + } + + pub(crate) fn take_grapple_cleanup(&mut self) -> Vec { + self.grapple.take_beam_cleanup_actions() + } + + pub(super) fn grapple_beam_cleanup_complete(&mut self, handle: i32, complete: bool) { + self.grapple.beam_cleanup_complete(handle, complete); + } + + pub(super) fn retain_grapple_beam(&mut self, handle: i32) { + self.grapple.retire_beam(handle); + } + + pub(super) fn grapple_action_valid(&self, action: &Action) -> bool { + match action { + Action::Acquire { task, player, .. } => { + self.grapple_run_valid(*task, *player) + && self.grapple.input_allows_action(task.player) + && self + .grapple + .input + .get(&task.player.slot) + .is_some_and(|input| input.identity == task.player && input.attempt_consumed && !input.native_target_won) + && !self.grapple.active.contains_key(&player.slot) + } + Action::Pull { task, player, beam, .. } => self.grapple.active.get(&player.slot).is_some_and(|active| { + active.task == *task + && active.player == *player + && active.beam == Some(*beam) + && self.grapple.input_allows_action(task.player) + && self.grapple_run_valid(*task, *player) + }), + Action::RemoveBeam { handle } => self.grapple.retired_beams.contains_key(handle), + } + } + + fn grapple_run_valid(&self, task: PlayerTask, player: LivePlayer) -> bool { + self.grapple_mode_active() + && self.use_target_hook_ready + && self.controller.generation() == task.round + && self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) + && LivePlayer::resolve(player.slot) == Some(player) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + && !self.grapple.native_bomb_use(task.player) + && self + .effects + .get(&player.slot) + .is_some_and(|effect| effect.identity == task.player && effect.round == task.round && !effect.movement_waits_for_release(IN_USE)) + && !self.suicides.active(player) + && s2sdk::GetClientButtons(player.slot, 0) & IN_USE != 0 + } + + pub(super) fn start_grapple( + &mut self, + task: PlayerTask, + player: LivePlayer, + anchor: Vec3, + settings: funrounds_core::GrappleSettings, + ) -> Result<(), Fault> { + if !self.grapple_run_valid(task, player) || self.grapple.active.contains_key(&player.slot) { + return Err(Fault::cancelled("grapple attempt changed before anchor acquisition")); + } + if s2sdk::GetEntityMoveType(player.pawn_handle) != s2sdk::MoveType::Walk { + return Err(Fault::cancelled("grapple pawn left WALK movement before anchor acquisition")); + } + let Some(effect) = self + .effects + .get_mut(&player.slot) + .filter(|effect| effect.identity == task.player && effect.round == task.round) + else { + return Err(Fault::cancelled("grapple player effect is not current")); + }; + effect.acquire_temporary_movement(crate::effects::TemporaryMovementOwner::Grapple, GRAPPLE_GRAVITY)?; + self.grapple.active.insert( + player.slot, + Active { + task, + player, + anchor, + settings, + beam: None, + }, + ); + Ok(()) + } + + pub(super) fn attach_grapple_beam(&mut self, task: PlayerTask, player: LivePlayer, handle: i32) -> bool { + if self + .grapple + .active + .get(&player.slot) + .is_some_and(|active| active.task == task && active.player == player) + { + self.grapple.active.get_mut(&player.slot).expect("active grapple exists").beam = Some(handle); + true + } else { + self.grapple.retire_beam(handle); + false + } + } + + pub(super) fn fail_grapple(&mut self, task: PlayerTask, player: LivePlayer, reason: String) { + let current = self + .grapple + .active + .get(&player.slot) + .is_some_and(|active| active.task == task && active.player == player); + if !current { + return; + } + self.cancel_grapple(task.player, StopReason::MovementInvalidated); + self.handle_fault(Fault::mechanism(Mechanism::Grapple, reason).context(format!("slot={} pawn={}", player.slot, player.pawn_handle))); + } + + pub(super) fn grapple_pending_beam_current(&self, task: PlayerTask, player: LivePlayer) -> bool { + self.grapple + .active + .get(&player.slot) + .is_some_and(|active| active.task == task && active.player == player && active.beam.is_none() && self.grapple_run_valid(task, player)) + } + + pub(super) fn stop_grapple_for_bomb_use(&mut self, slot: i32, defusing: bool) { + if self.grapple_mode_active() + && let Some(identity) = self.players.identity(slot) + { + let down = s2sdk::GetClientButtons(slot, 0) & IN_USE != 0; + self.grapple.sample(identity, down); + self.grapple.begin_bomb_use(identity); + } + if let Some(active) = self.grapple.active.get(&slot) { + self.cancel_grapple(active.task.player, if defusing { StopReason::Defusing } else { StopReason::Planting }); + } + } + + pub(super) fn finish_grapple_bomb_use(&mut self, slot: i32) { + if let Some(identity) = self.players.identity(slot) { + self.grapple.end_bomb_use(identity); + } + } + + pub(super) fn discard_grapple_map_state(&mut self) { + self.grapple = State::default(); + } +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum StopReason { + InputReleased, + NativeTarget, + Defusing, + Planting, + MovementInvalidated, + Impulse, + LifeEnded, + RoundEnded, +} + +pub(crate) fn execute(action: Action, still_current: impl Fn() -> bool) -> Result<(), Fault> { + match action { + Action::Acquire { task, player, settings } => { + if !still_current() { + return Ok(()); + } + let Some(anchor) = trace_world_anchor(player, settings) else { + return Ok(()); + }; + if !still_current() { + return Ok(()); + } + { + let mut guard = crate::RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some(runtime) = guard.as_mut().filter(|runtime| runtime.on_game_thread()) else { + return Ok(()); + }; + if let Err(error) = runtime.start_grapple(task, player, anchor, settings) { + return if error.scope == Scope::Cancelled { Ok(()) } else { Err(error) }; + } + } + let pending_current = { + let guard = crate::RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + guard.as_ref().is_some_and(|runtime| runtime.grapple_pending_beam_current(task, player)) + }; + if !pending_current { + let mut guard = crate::RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = guard.as_mut() { + runtime.fail_grapple(task, player, "grapple input or owner changed after anchor lock".into()); + } + return Ok(()); + } + match create_beam(player, anchor) { + Ok(handle) => { + let mut guard = crate::RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = guard.as_mut() { + if runtime.attach_grapple_beam(task, player, handle) && runtime.diagnostics() { + log(&format!( + "grapple=latched slot={} pawn={} beam={handle} anchor={anchor:?}", + player.slot, player.pawn_handle + )); + } + } else { + let _ = remove_beam(handle); + } + } + Err((error, leaked_handle)) => { + let mut guard = crate::RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = guard.as_mut() { + if let Some(handle) = leaked_handle { + runtime.retain_grapple_beam(handle); + } + runtime.fail_grapple(task, player, format!("visible beam setup failed: {error}")); + } + } + } + Ok(()) + } + Action::Pull { + task, + player, + anchor, + beam, + settings, + } => { + if !still_current() { + return Ok(()); + } + let gravity = s2sdk::GetClientGravity(player.slot); + if !gravity.is_finite() || (gravity - GRAPPLE_GRAVITY).abs() > 0.0001 { + let mut guard = crate::RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = guard.as_mut() { + runtime.cancel_grapple(task.player, StopReason::MovementInvalidated); + } + return Ok(()); + } + let start = s2sdk::GetClientEyePosition(player.slot); + if !finite_vec(start) { + let mut guard = crate::RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = guard.as_mut() { + runtime.fail_grapple(task, player, "grapple eye position became non-finite".into()); + } + return Ok(()); + } + if let Err(error) = update_beam(beam, start, anchor) { + let mut guard = crate::RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = guard.as_mut() { + runtime.fail_grapple(task, player, format!("visible beam update failed: {error}")); + } + return Ok(()); + } + if !still_current() { + return Ok(()); + } + let origin = s2sdk::GetEntityAbsOrigin(player.pawn_handle); + let delta = Vec3 { + x: anchor.x - origin.x, + y: anchor.y - origin.y, + z: anchor.z - origin.z, + }; + let distance_squared = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z; + if !distance_squared.is_finite() || distance_squared < 0.0 { + let mut guard = crate::RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = guard.as_mut() { + runtime.fail_grapple(task, player, "grapple pull distance became non-finite".into()); + } + return Ok(()); + } + let distance = distance_squared.sqrt(); + let speed = settings.max_speed.min(distance * settings.pull_gain); + let velocity = if distance > 0.0 { + Vec3 { + x: delta.x * speed / distance, + y: delta.y * speed / distance, + z: delta.z * speed / distance, + } + } else { + Vec3::default() + }; + if !finite_vec(velocity) { + return Err(Fault::mechanism(Mechanism::Grapple, "grapple pull velocity became non-finite")); + } + if still_current() { + s2sdk::SetEntityAbsVelocity(player.pawn_handle, &velocity); + } + Ok(()) + } + Action::RemoveBeam { handle } => { + let complete = remove_beam(handle); + let mut guard = crate::RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(runtime) = guard.as_mut() { + runtime.grapple_beam_cleanup_complete(handle, complete); + } + Ok(()) + } + } +} diff --git a/crates/funrounds-plugin/src/runtime/healthshot.rs b/crates/funrounds-plugin/src/runtime/healthshot.rs new file mode 100644 index 0000000..b969d3d --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/healthshot.rs @@ -0,0 +1,299 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::{EngineAction, Runtime, active_combat_phase, log}; +use crate::{execute_valid_action, fault, process_healthshot_purchase}; +use crate::{ + fault::{Fault, Mechanism}, + game::LivePlayer, + parameters::Parameters, + s2sdk, +}; +use funrounds_core::PlayerTask; +use std::collections::HashMap; + +#[derive(Default)] +pub(super) struct State { + parameters: Parameters, + hooks_requested: bool, + hooks_ready: bool, + override_active: bool, + faulted: bool, + purchases: HashMap, +} + +impl State { + pub(super) fn cancel_purchase(&mut self, slot: i32, actions: &mut Vec) { + self.purchases.remove(&slot); + actions.retain(|action| !matches!(action, EngineAction::Healthshot(Action::Purchase { task, .. }) if task.player.slot == slot)); + } + + pub(super) fn cancel_purchases_for_slots(&mut self, slots: &[i32]) { + self.purchases.retain(|slot, _| !slots.contains(slot)); + } + + fn finish_purchase(&mut self, task: PlayerTask) { + if self.purchases.get(&task.player.slot) == Some(&task) { + self.purchases.remove(&task.player.slot); + } + } + + pub(super) fn clear_round(&mut self) { + self.purchases.clear(); + } + + pub(super) fn stop_hooks(&mut self) { + self.hooks_ready = false; + } + + pub(super) fn restore(&mut self) -> Result<(), Fault> { + let result = self.parameters.set_healthshot_override(false); + self.override_active = false; + result + } + + pub(super) fn settled(&self, wanted: bool) -> bool { + // The ConVar lease lasts across rounds; only an unwanted lease must be fully restored. + override_settled(wanted, self.override_active, self.parameters.is_restored()) + } +} + +fn override_settled(wanted: bool, active: bool, parameters_restored: bool) -> bool { + wanted == active && (wanted || parameters_restored) +} + +impl Runtime { + pub(super) fn take_healthshot_hook_request(&mut self) -> bool { + let requested = self.healthshot_configured() && !self.healthshot.hooks_requested; + self.healthshot.hooks_requested |= requested; + requested + } + + fn healthshot_configured(&self) -> bool { + self.controller.config().is_some_and(|config| config.healthshot.is_some()) + } + + pub(crate) fn healthshot_hook_ready(&mut self) { + self.healthshot.hooks_ready = true; + } + + pub(crate) fn healthshot_hook_failure(&mut self, reason: impl Into) { + self.healthshot.hooks_ready = false; + self.healthshot.faulted = true; + let reason = reason.into(); + self.faults.exclude(Mechanism::Healthshot, reason.clone()); + // Healthshot is an optional global service, not a round-selection requirement. + // Do not clear an unrelated active round when lazy registration fails. + self.capability_reasons.push(format!("healthshot:[{reason}]")); + log(&format!("healthshot capability disabled: {reason}")); + } + + pub(super) fn healthshot_active(&self) -> bool { + self.healthshot.hooks_ready + && !self.healthshot.faulted + && self.controller.enabled() + && self.healthshot_configured() + && self.faults.capabilities().healthshot + } + + pub(super) fn sync_healthshot_override(&mut self) -> Result<(), Fault> { + let wanted = self.healthshot_active(); + if self.healthshot.settled(wanted) { + return Ok(()); + } + self.healthshot.parameters.set_healthshot_override(wanted)?; + self.healthshot.override_active = wanted; + if !wanted { + self.healthshot.purchases.clear(); + self.engine_actions + .retain(|action| !matches!(action, EngineAction::Healthshot(Action::Purchase { .. }))); + } + Ok(()) + } + + pub(crate) fn reject_healthshot_use(&self, pawn_handle: i32, weapon_handle: i32) -> bool { + if !self.healthshot_active() || !self.healthshot.override_active { + return false; + } + let Some(player) = LivePlayer::resolve_pawn_owner(pawn_handle) else { + return true; + }; + if !s2sdk::IsValidEntHandle(weapon_handle) + || s2sdk::GetEntityClassname(weapon_handle).as_str() != "weapon_healthshot" + || !s2sdk::GetClientWeapons(player.slot).iter().any(|handle| *handle == weapon_handle) + { + return true; + } + let Some(task) = self.combat_task(player) else { return true }; + let Some(base_health) = self.chickens.base_health(task).ok() else { + return true; + }; + let Some(config) = self.controller.config().and_then(|config| config.healthshot) else { + return false; + }; + matches!( + funrounds_core::use_healthshot(config, s2sdk::GetClientHealth(player.slot), base_health), + funrounds_core::HealthshotOutcome::NotConsumed + ) + } + + pub(crate) fn queue_healthshot_use(&mut self, pawn_handle: i32, weapon_handle: i32) { + if !self.healthshot_active() || !self.healthshot.override_active { + return; + } + let Some(player) = LivePlayer::resolve_pawn_owner(pawn_handle) else { + return; + }; + if !s2sdk::IsValidEntHandle(weapon_handle) + || s2sdk::GetEntityClassname(weapon_handle).as_str() != "weapon_healthshot" + || !s2sdk::GetClientWeapons(player.slot).iter().any(|handle| *handle == weapon_handle) + { + return; + } + let Some(task) = self.combat_task(player) else { return }; + let Some(base_health) = self.chickens.base_health(task).ok() else { + return; + }; + let Some(config) = self.controller.config().and_then(|config| config.healthshot) else { + return; + }; + if matches!( + funrounds_core::use_healthshot(config, s2sdk::GetClientHealth(player.slot), base_health), + funrounds_core::HealthshotOutcome::Applied { .. } + ) { + self.engine_actions.push(EngineAction::Healthshot(Action::Use { + task, + player, + base_health, + config, + })); + } + } + + pub(super) fn request_healthshot(&mut self, slot: i32) -> Result { + if !self.healthshot_active() || !self.healthshot.override_active || !active_combat_phase(self.controller.phase()) { + return Err(self.text(slot, "healthshot.unavailable", &[])); + } + let player = LivePlayer::resolve(slot).ok_or(self.text(slot, "player.alive_required", &[]))?; + if !matches!(s2sdk::GetClientTeam(slot) as i32, 2 | 3) { + return Err(self.text(slot, "healthshot.team_required", &[])); + } + if Self::owns_healthshot(player) { + return Err(self.text(slot, "healthshot.already_owned", &[])); + } + let task = self.combat_task(player).ok_or(self.text(slot, "player.life_pending", &[]))?; + if self.healthshot.purchases.contains_key(&slot) { + return Err(self.text(slot, "healthshot.pending", &[])); + } + let price = self + .controller + .config() + .ok_or(self.text(slot, "config.unavailable", &[]))? + .prices + .healthshot_cash; + self.healthshot.purchases.insert(slot, task); + self.engine_actions + .push(EngineAction::Healthshot(Action::Purchase { task, player, price })); + Ok(self.text(slot, "healthshot.request", &[("price", &price.to_string())])) + } + + pub(super) fn owns_healthshot(player: LivePlayer) -> bool { + s2sdk::GetClientWeapons(player.slot) + .iter() + .copied() + .any(|handle| s2sdk::IsValidEntHandle(handle) && s2sdk::GetEntityClassname(handle).as_str() == "weapon_healthshot") + } + + pub(crate) fn healthshot_buyer_current(&self, task: PlayerTask, player: LivePlayer) -> bool { + self.healthshot_active() + && self.healthshot.override_active + && active_combat_phase(self.controller.phase()) + && self.healthshot.purchases.get(&player.slot) == Some(&task) + && self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + && LivePlayer::resolve(player.slot) == Some(player) + } + + pub(crate) fn finish_healthshot_purchase(&mut self, task: PlayerTask) { + self.healthshot.finish_purchase(task); + } + + pub(super) fn update_healthshot(&mut self) { + if let Err(error) = self.sync_healthshot_override() { + self.healthshot.faulted = true; + let message = error.to_string(); + // Healthshot is not a round-selection dependency; leave the active round intact. + self.faults.exclude(Mechanism::Healthshot, message.clone()); + log(&format!("healthshot capability disabled: {message}")); + } + } +} + +pub enum Action { + Use { + task: PlayerTask, + player: LivePlayer, + base_health: i32, + config: funrounds_core::HealthshotConfig, + }, + Purchase { + task: PlayerTask, + player: LivePlayer, + price: u32, + }, +} + +impl Action { + pub(super) fn involves(&self, slots: &[i32]) -> bool { + match self { + Self::Use { task, .. } | Self::Purchase { task, .. } => slots.contains(&task.player.slot), + } + } +} + +impl Runtime { + pub(super) fn healthshot_action_current(&self, action: &Action) -> bool { + match action { + Action::Use { task, player, .. } => { + self.healthshot_active() + && self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) + && LivePlayer::resolve(player.slot) == Some(*player) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + } + Action::Purchase { task, player, .. } => self.healthshot_buyer_current(*task, *player) && !Self::owns_healthshot(*player), + } + } +} + +pub(crate) fn execute(action: Action) -> Result<(), Box> { + match action { + Action::Use { + task, + player, + base_health, + config, + } => { + let action = EngineAction::Healthshot(Action::Use { + task, + player, + base_health, + config, + }); + execute_valid_action(action, || { + let current = s2sdk::GetClientHealth(task.player.slot); + if let funrounds_core::HealthshotOutcome::Applied { health, .. } = funrounds_core::use_healthshot(config, current, base_health) { + s2sdk::SetClientHealth(task.player.slot, health); + if s2sdk::GetClientHealth(task.player.slot) != health { + return Err(fault::Fault::mechanism( + fault::Mechanism::Healthshot, + format!("healthshot health write failed for slot {}", task.player.slot), + )); + } + } + Ok(()) + })?; + } + Action::Purchase { task, player, price } => process_healthshot_purchase(task, player, price), + } + Ok(()) +} diff --git a/crates/funrounds-plugin/src/runtime/proximity.rs b/crates/funrounds-plugin/src/runtime/proximity.rs new file mode 100644 index 0000000..8c3907a --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/proximity.rs @@ -0,0 +1,1636 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::*; +use funrounds_core::GrenadeKind; +use plugify::Vec3; +use std::cmp::Ordering; + +const PROJECTILE_CLASS: &str = "CBaseCSGrenadeProjectile"; +const TRACE_MASK: i32 = 798785; +const GUIDANCE_FUSE_HOLD_GRACE_SECONDS: f64 = 0.5; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Source { + task: PlayerTask, + player: LivePlayer, + kind: GrenadeKind, + tick: i32, + team: i32, +} +#[derive(Clone, Copy, Debug, PartialEq)] +struct GuidanceSpawn { + handle: i32, + tick: i32, + epoch: u64, + game_time: f32, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct GuidanceThrow { + source: Source, + epoch: u64, +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct SpawnObservation { + pub(crate) handle: i32, + pub(crate) tick: i32, + pub(crate) epoch: u64, + pub(crate) game_time: f32, +} +impl From for GuidanceSpawn { + fn from(observation: SpawnObservation) -> Self { + Self { + handle: observation.handle, + tick: observation.tick, + epoch: observation.epoch, + game_time: observation.game_time, + } + } +} +#[derive(Clone, Copy, Debug, PartialEq)] +struct GuidanceFusePause { + native_deadline: f64, + held_deadline: f64, + remaining_seconds: f64, + confirmed: bool, +} +#[derive(Clone, Copy, Debug, PartialEq)] +struct Guidance { + target: LivePlayer, + target_task: PlayerTask, + spawned_at: f32, + last_game_time: f32, + force_retarget: bool, +} +#[derive(Clone, Copy)] +struct WaitingTarget { + player: LivePlayer, + task: PlayerTask, + started_at: f32, +} +#[derive(Clone)] +struct Grenade { + source: Source, + waiting: Option, + claimed: bool, + guidance: Option, + guidance_fuse: Option, +} + +fn merge_proximity_grenade(grenades: &mut HashMap, handle: i32, source: Source) -> bool { + match grenades.entry(handle) { + std::collections::hash_map::Entry::Vacant(entry) => { + entry.insert(Grenade { + source, + waiting: None, + claimed: false, + guidance: None, + guidance_fuse: None, + }); + true + } + std::collections::hash_map::Entry::Occupied(entry) => { + let existing = entry.get(); + if existing.source.task != source.task || existing.source.player != source.player || existing.source.kind != source.kind { + return false; + } + true + } + } +} + +fn merge_guidance_association( + grenades: &mut HashMap, + handle: i32, + source: Source, + selected: Option<(LivePlayer, PlayerTask)>, + spawned_at: f32, + game_time: f32, +) -> bool { + let entry = grenades.entry(handle).or_insert_with(|| Grenade { + source, + waiting: None, + claimed: false, + guidance: None, + guidance_fuse: None, + }); + if entry.source.task != source.task || entry.source.player != source.player || entry.source.kind != GrenadeKind::He { + return false; + } + if !entry.claimed { + entry.guidance = selected.map(|(target, target_task)| Guidance { + target, + target_task, + spawned_at, + last_game_time: game_time, + force_retarget: false, + }); + } + true +} + +fn relinquish_stale_proximity_ownership(grenade: &mut Grenade) -> Option { + let fuse_pause = grenade.guidance_fuse?; + grenade.guidance = None; + Some(fuse_pause) +} + +fn guidance_fuse_pause(native_deadline: f64, now: f64, remaining_guidance_seconds: f64) -> Option { + if !native_deadline.is_finite() + || !now.is_finite() + || !remaining_guidance_seconds.is_finite() + || native_deadline <= now + || remaining_guidance_seconds <= 0.0 + { + return None; + } + let remaining_seconds = native_deadline - now; + let held_deadline = f64::from((now + remaining_seconds + remaining_guidance_seconds + GUIDANCE_FUSE_HOLD_GRACE_SECONDS) as f32); + (remaining_seconds.is_finite() && remaining_seconds > 0.0 && held_deadline.is_finite() && held_deadline > native_deadline).then_some( + GuidanceFusePause { + native_deadline, + held_deadline, + remaining_seconds, + confirmed: false, + }, + ) +} + +fn same_fuse_deadline(actual: f64, expected: f64) -> bool { + actual.is_finite() && expected.is_finite() && actual == expected +} + +fn guidance_deadline_owned(fuse_pause: GuidanceFusePause, deadline: f64, now: f64, pause_fuse: bool) -> bool { + deadline.is_finite() + && deadline > now + && if fuse_pause.confirmed { + !pause_fuse && same_fuse_deadline(deadline, fuse_pause.held_deadline) + } else { + pause_fuse && same_fuse_deadline(deadline, fuse_pause.native_deadline) + } +} + +fn remaining_guidance_budget(spawned_at: f32, now: f32, max_guidance_seconds: f32) -> Option { + if !spawned_at.is_finite() || !now.is_finite() || !max_guidance_seconds.is_finite() || max_guidance_seconds <= 0.0 { + return None; + } + let elapsed = f64::from(now) - f64::from(spawned_at); + let remaining = f64::from(max_guidance_seconds) - elapsed; + (elapsed >= 0.0 && remaining.is_finite() && remaining > 0.0).then_some(remaining) +} + +fn retarget_guidance(guidance: &mut Guidance, target: LivePlayer, target_task: PlayerTask) { + guidance.target = target; + guidance.target_task = target_task; +} + +fn request_guidance_retarget(grenades: &mut HashMap, action: GuidanceAction) -> bool { + if let Some(grenade) = grenades.get_mut(&action.handle) + && grenade.source == action.source + && grenade.guidance.is_some_and(|guidance| { + guidance.target == action.target && guidance.target_task == action.target_task && guidance.last_game_time == action.game_time + }) + { + grenade.guidance.as_mut().expect("matched guidance").force_retarget = true; + return true; + } + false +} +#[derive(Default)] +pub(super) struct State { + round: Option, + known: HashSet, + recent: HashMap, + pending: Vec, + guidance_spawns: Vec, + guidance_throws: Vec, + grenades: HashMap, + impulse_hits: HashMap>, +} + +#[derive(Clone, Copy)] +pub(crate) struct Action { + source: Source, + handle: i32, + target: LivePlayer, + target_task: PlayerTask, + radius: f32, +} + +#[derive(Clone, Copy)] +pub(crate) struct GuidanceAction { + source: Source, + handle: i32, + target: LivePlayer, + target_task: PlayerTask, + settings: funrounds_core::HeGuidanceSettings, + delta_seconds: f32, + game_time: f32, + fuse_pause: GuidanceFusePause, + pause_fuse: bool, +} +impl GuidanceAction { + pub(super) fn involves(self, slots: &[i32]) -> bool { + slots.contains(&self.source.player.slot) || slots.contains(&self.target.slot) + } +} +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct GuidanceFuseRestoreAction { + source: Source, + handle: i32, + fuse_pause: GuidanceFusePause, +} +impl Action { + pub(super) fn involves(self, slots: &[i32]) -> bool { + slots.contains(&self.source.player.slot) || slots.contains(&self.target.slot) + } +} + +pub(super) fn probe(events: &EventCapabilities, caps: &mut funrounds_core::Capabilities, reasons: &mut Vec) { + let mut common = crate::capability::Probe::default(); + common.require(events.grenade_thrown && events.combat_events, "events:grenade_thrown/lifecycle"); + crate::capability::imports!(common; __s2sdk_GetFirstActiveEntity, __s2sdk_GetNextActiveEntity, __s2sdk_IsValidEntHandle, + __s2sdk_GetEntityClassname, __s2sdk_EntHandleToEntPointer, __s2sdk_GetEntSchemaEnt2, __s2sdk_GetEntityAbsOrigin, + __s2sdk_GetClientAbsOrigin, __s2sdk_GetClientEyePosition, __s2sdk_TraceLine, __s2sdk_GetClientTeam, + __s2sdk_FindConVar, __s2sdk_GetConVarValue, __s2sdk_GetGameTickCount, __s2sdk_GetGameTime); + common.require( + super::shooting::teammates_are_friendly().is_ok(), + "convar:mp_teammates_are_enemies (readable boolean)", + ); + common.schema("CBaseGrenade", "m_hThrower"); + let mut deadline = common.clone(); + crate::capability::imports!(deadline; __s2sdk_GetEntSchemaFloat2, __s2sdk_SetEntSchemaFloat2); + deadline.schema(PROJECTILE_CLASS, "m_flDetonateTime"); + let mut impulse = crate::capability::Probe::default(); + impulse.require(events.combat_events && events.damage, "hooks:damage/lifecycle"); + crate::capability::imports!(impulse; __s2sdk_IsValidEntHandle, __s2sdk_GetEntityClassname, + __s2sdk_GetEntityAbsOrigin, __s2sdk_GetEntityAbsVelocity, __s2sdk_SetEntityAbsVelocity); + caps.hegrenade_impulse = impulse.record("hegrenade_impulse", reasons); + caps.proximity_he = deadline.clone().record("proximity_he", reasons); + let mut flash = deadline; + crate::capability::imports!(flash; __s2sdk_GetClientEyeAngles); + caps.proximity_flash = flash.record("proximity_flash", reasons); + + let mut guidance = crate::capability::Probe::default(); + guidance.require(events.grenade_thrown && events.combat_events, "events:grenade_thrown/lifecycle"); + guidance.require(events.spawn_listener_available, "event_listener:OnEntitySpawned"); + crate::capability::imports!(guidance; + __s2sdk_IsClientInGame, __s2sdk_IsClientAlive, __s2sdk_GetClientHealth, __s2sdk_GetMaxClients, + __s2sdk_IsValidEntHandle, __s2sdk_GetEntityClassname, __s2sdk_EntHandleToEntPointer, + __s2sdk_GetEntSchemaEnt2, __s2sdk_GetEntityAbsOrigin, __s2sdk_GetClientAbsOrigin, + __s2sdk_GetClientEyePosition, __s2sdk_TraceLine, __s2sdk_GetClientTeam, __s2sdk_GetGameTickCount, + __s2sdk_GetGameTime, __s2sdk_FindConVar, __s2sdk_GetConVarValue, __s2sdk_PlayerSlotToEntHandle, + __s2sdk_GetClientPawn, __s2sdk_EntPointerToEntHandle, + __s2sdk_GetEntSchema2, __s2sdk_GetEntSchemaFloat2, __s2sdk_GetEntityAbsVelocity, __s2sdk_SetEntityAbsVelocity, + ); + guidance.require( + super::shooting::teammates_are_friendly().is_ok(), + "convar:mp_teammates_are_enemies (readable boolean)", + ); + guidance.schema("CBaseGrenade", "m_hThrower"); + guidance.schema("CBasePlayerPawn", "m_hController"); + guidance.schema(PROJECTILE_CLASS, "m_flDetonateTime"); + caps.he_guidance = guidance.record("he_guidance", reasons); + for (kind, capability, name) in [ + (1, &mut caps.proximity_smoke, "proximity_smoke"), + (2, &mut caps.proximity_molotov, "proximity_molotov"), + (3, &mut caps.proximity_incendiary, "proximity_incendiary"), + ] { + let mut probe = common.clone(); + probe.require( + unsafe { crate::funrounds_native::__funrounds_native_HasGrenadeDetonateSupport }.is_some_and(|query| unsafe { query(kind) }), + "native:typed_grenade_detonation", + ); + if kind == 1 { + probe.require( + unsafe { crate::funrounds_native::__funrounds_native_DetonateGrenade }.is_some(), + "native:DetonateGrenade", + ); + } else { + probe.require( + unsafe { crate::funrounds_native::__funrounds_native_GetGrenadeDetonationState }.is_some(), + "native:GetGrenadeDetonationState", + ); + crate::capability::imports!(probe; __s2sdk_GetEntityAbsVelocity, __s2sdk_SetEntityAbsVelocity); + } + *capability = probe.record(name, reasons); + } +} + +fn classname(kind: GrenadeKind) -> &'static str { + match kind { + GrenadeKind::He => "hegrenade_projectile", + GrenadeKind::Flash => "flashbang_projectile", + GrenadeKind::Smoke => "smokegrenade_projectile", + GrenadeKind::Molotov | GrenadeKind::Incendiary => "molotov_projectile", + GrenadeKind::Decoy => "decoy_projectile", + } +} + +fn native_kind(kind: GrenadeKind) -> Option { + match kind { + GrenadeKind::Smoke => Some(1), + GrenadeKind::Molotov => Some(2), + GrenadeKind::Incendiary => Some(3), + _ => None, + } +} + +fn thrower(handle: i32) -> i32 { + s2sdk::GetEntSchemaEnt2( + s2sdk::EntHandleToEntPointer(handle), + &Str::from_str("CBaseGrenade"), + &Str::from_str("m_hThrower"), + 0, + ) +} + +fn all_projectiles() -> Vec { + [ + "hegrenade_projectile", + "flashbang_projectile", + "smokegrenade_projectile", + "molotov_projectile", + ] + .into_iter() + .flat_map(game::entity_handles) + .collect() +} + +fn guidance_tick_pair(throw_tick: i32, spawn_tick: i32) -> bool { + throw_tick.abs_diff(spawn_tick) <= 1 +} + +#[derive(Default)] +struct GuidanceResolution { + pairs: Vec<(usize, usize)>, + discard_throws: HashSet, + discard_spawns: HashSet, + ambiguous_components: Vec<(usize, usize)>, +} + +fn resolve_guidance_candidates( + candidates: &[(usize, usize)], + throws: &[GuidanceThrow], + spawns: &[GuidanceSpawn], + current_tick: i32, +) -> GuidanceResolution { + let mut throw_edges = HashMap::>::new(); + let mut spawn_edges = HashMap::>::new(); + for &(throw_index, spawn_index) in candidates { + throw_edges.entry(throw_index).or_default().push(spawn_index); + spawn_edges.entry(spawn_index).or_default().push(throw_index); + } + + let mut resolution = GuidanceResolution::default(); + let mut visited_throws = HashSet::new(); + let mut visited_spawns = HashSet::new(); + for &first_throw in throw_edges.keys() { + if !visited_throws.insert(first_throw) { + continue; + } + let mut component_throws = vec![first_throw]; + let mut component_spawns = Vec::new(); + let mut pending_throws = vec![first_throw]; + while let Some(throw_index) = pending_throws.pop() { + for &spawn_index in throw_edges.get(&throw_index).into_iter().flatten() { + if visited_spawns.insert(spawn_index) { + component_spawns.push(spawn_index); + for &neighbor_throw in spawn_edges.get(&spawn_index).into_iter().flatten() { + if visited_throws.insert(neighbor_throw) { + component_throws.push(neighbor_throw); + pending_throws.push(neighbor_throw); + } + } + } + } + } + + let closed = component_throws + .iter() + .all(|index| current_tick > throws[*index].source.tick.saturating_add(1)) + && component_spawns.iter().all(|index| current_tick > spawns[*index].tick.saturating_add(1)); + if !closed { + continue; + } + if let ([throw_index], [spawn_index]) = (component_throws.as_slice(), component_spawns.as_slice()) { + resolution.pairs.push((*throw_index, *spawn_index)); + } else { + resolution.discard_throws.extend(component_throws.iter().copied()); + resolution.discard_spawns.extend(component_spawns.iter().copied()); + resolution.ambiguous_components.push((component_throws.len(), component_spawns.len())); + } + } + + for (index, throw) in throws.iter().enumerate() { + if !throw_edges.contains_key(&index) && current_tick > throw.source.tick.saturating_add(1) { + resolution.discard_throws.insert(index); + } + } + for (index, spawn) in spawns.iter().enumerate() { + if !spawn_edges.contains_key(&index) && current_tick > spawn.tick.saturating_add(1) { + resolution.discard_spawns.insert(index); + } + } + resolution +} + +fn guidance_candidate_pairs( + throws: &[GuidanceThrow], + spawns: &[GuidanceSpawn], + owners: &HashMap, + round: RoundGeneration, + epoch: u64, +) -> Vec<(usize, usize)> { + let mut candidates = Vec::new(); + for (throw_index, source) in throws.iter().enumerate() { + for (spawn_index, spawn) in spawns.iter().enumerate() { + if source.source.kind == GrenadeKind::He + && source.epoch == epoch + && source.source.task.round == round + && spawn.epoch == epoch + && guidance_tick_pair(source.source.tick, spawn.tick) + && owners.get(&spawn_index) == Some(&source.source.player.pawn_handle) + { + candidates.push((throw_index, spawn_index)); + } + } + } + candidates +} + +fn guidance_target_order(left: (f64, i32, i32), right: (f64, i32, i32)) -> Ordering { + left.0 + .total_cmp(&right.0) + .then_with(|| left.1.cmp(&right.1)) + .then_with(|| left.2.cmp(&right.2)) +} + +fn grenade_detonate_deadline(handle: i32) -> f64 { + let pointer = s2sdk::EntHandleToEntPointer(handle); + s2sdk::GetEntSchemaFloat2(pointer, &Str::from_str(PROJECTILE_CLASS), &Str::from_str("m_flDetonateTime"), 0) +} + +fn set_grenade_detonate_deadline(handle: i32, deadline: f64) { + let pointer = s2sdk::EntHandleToEntPointer(handle); + s2sdk::SetEntSchemaFloat2( + pointer, + &Str::from_str(PROJECTILE_CLASS), + &Str::from_str("m_flDetonateTime"), + deadline, + true, + 0, + ); +} + +fn he_damage_is_detonation(damage_type: u32, skip_plugin_rules: bool) -> bool { + !skip_plugin_rules && damage_type & crate::damage::DMG_BLAST != 0 +} + +impl Runtime { + fn proximity_active(&self) -> bool { + self.classic_round() + && active_combat_phase(self.controller.phase()) + && self.controller.current_mode().is_some_and(|m| m.proximity_fuse.is_some()) + } + + fn proximity_source_current(&self, source: Source) -> bool { + self.proximity_active() + && s2sdk::GetClientTeam(source.player.slot) as i32 == source.team + && self.controllers.get(&source.player.slot) == Some(&source.player.controller_handle) + && LivePlayer::resolve_present(source.player.slot) == Some(source.player) + && self + .players + .validates_damage_source(source.task, self.controller.generation(), source.player.pawn_handle as u32) + && source.player.pawn_controller().is_some() + } + + fn guidance_source_current(&self, source: Source) -> bool { + source.kind == GrenadeKind::He + && self.he_guidance_active() + && s2sdk::GetClientTeam(source.player.slot) as i32 == source.team + && self.controllers.get(&source.player.slot) == Some(&source.player.controller_handle) + && LivePlayer::resolve(source.player.slot) == Some(source.player) + && self.combat_task(source.player) == Some(source.task) + && self + .players + .validates(source.task, self.controller.generation(), source.player.pawn_handle as u32) + && source.player.pawn_controller().is_some() + } + + pub(super) fn observe_proximity_throw(&mut self, slot: i32, kind: Option) { + self.sync_he_guidance_spawn_epoch(); + let guidance_enabled = self.he_guidance_active(); + let proximity_enabled = self.proximity_active(); + let old_path_kind = kind.filter(|kind| { + proximity_enabled + && self + .controller + .current_mode() + .is_some_and(|mode| mode.proximity_fuse.as_ref().is_some_and(|settings| settings.grenades.contains(kind))) + }); + let guidance_he = guidance_enabled && kind == Some(GrenadeKind::He); + let Some(kind) = old_path_kind.or_else(|| guidance_he.then_some(GrenadeKind::He)) else { + return; + }; + let Some(player) = LivePlayer::resolve(slot) else { return }; + let Some(task) = self.combat_task(player) else { return }; + let tick = s2sdk::GetGameTickCount(); + if tick < 0 { + return; + } + let source = Source { + task, + player, + kind, + tick, + team: s2sdk::GetClientTeam(slot) as i32, + }; + if old_path_kind.is_some() && !self.match_proximity_throw(source) { + self.proximity.pending.push(source); + } + if guidance_he { + self.proximity.guidance_throws.push(GuidanceThrow { + source, + epoch: crate::HE_GUIDANCE_SPAWN_EPOCH.load(std::sync::atomic::Ordering::Acquire), + }); + } + } + + fn match_proximity_throw(&mut self, source: Source) -> bool { + let candidates: Vec<_> = game::entity_handles(classname(source.kind)) + .into_iter() + .filter(|handle| { + (!self.proximity.known.contains(handle) + || self + .proximity + .recent + .get(handle) + .is_some_and(|(task, tick)| *task == source.task && source.tick >= *tick && source.tick <= tick.saturating_add(1))) + && !self.projectiles.manages_projectile(*handle) + && thrower(*handle) == source.player.pawn_handle + }) + .collect(); + if let [handle] = candidates.as_slice() { + self.proximity.known.insert(*handle); + self.proximity.recent.remove(handle); + if !merge_proximity_grenade(&mut self.proximity.grenades, *handle, source) { + log(&format!( + "proximity association conflicts with existing projectile owner: handle={handle} slot={}", + source.player.slot + )); + } + true + } else { + // Multiple unclaimed projectiles cannot be attributed to one real + // throw. Never choose an arbitrary entity or infer its grenade kind. + if candidates.len() > 1 { + self.proximity.known.extend(candidates); + self.handle_fault(Fault::mechanism( + Mechanism::ProximityFuse(source.kind), + "ambiguous projectile source; native grenades left unchanged", + )); + } + false + } + } + + fn queue_guidance_fuse_restore(&mut self, handle: i32, source: Source, fuse_pause: GuidanceFusePause) { + let action = GuidanceFuseRestoreAction { source, handle, fuse_pause }; + if !self + .engine_actions + .iter() + .any(|queued| matches!(queued, EngineAction::HeGuidanceFuseRestore(existing) if *existing == action)) + { + self.engine_actions.push(EngineAction::HeGuidanceFuseRestore(action)); + } + } + + fn stop_grenade_guidance(&mut self, handle: i32) { + let Some((source, fuse_pause)) = self.proximity.grenades.get_mut(&handle).map(|grenade| { + grenade.guidance = None; + (grenade.source, grenade.guidance_fuse) + }) else { + return; + }; + if let Some(fuse_pause) = fuse_pause { + self.queue_guidance_fuse_restore(handle, source, fuse_pause); + } + } + + fn stop_all_guidance(&mut self) { + self.proximity.guidance_throws.clear(); + self.proximity.guidance_spawns.clear(); + let handles = self.proximity.grenades.keys().copied().collect::>(); + for handle in handles { + self.stop_grenade_guidance(handle); + } + } + + fn reset_proximity_preserving_fuse_recovery(&mut self) { + self.stop_all_guidance(); + self.proximity.pending.clear(); + self.proximity.known.clear(); + self.proximity.recent.clear(); + self.proximity.guidance_throws.clear(); + self.proximity.guidance_spawns.clear(); + self.proximity.round = None; + self.proximity.grenades.retain(|_, grenade| grenade.guidance_fuse.is_some()); + } + + pub(super) fn stop_he_guidance_for_cleanup(&mut self) { + self.proximity.impulse_hits.clear(); + self.reset_proximity_preserving_fuse_recovery(); + } + + pub(super) fn has_guidance_fuse_recovery(&self) -> bool { + self.proximity.grenades.values().any(|grenade| grenade.guidance_fuse.is_some()) + } + + pub(super) fn update_proximity_with_spawned_entities(&mut self, tick: i32, spawned_entities: &[SpawnObservation]) { + self.sync_he_guidance_spawn_epoch(); + self.proximity.impulse_hits.retain(|handle, _| s2sdk::IsValidEntHandle(*handle)); + let proximity_active = self.proximity_active(); + let guidance_active = self.he_guidance_active(); + let guidance_epoch = crate::HE_GUIDANCE_SPAWN_EPOCH.load(std::sync::atomic::Ordering::Acquire); + if !proximity_active && !guidance_active { + self.reset_proximity_preserving_fuse_recovery(); + return; + } + let round = self.controller.generation(); + let new_round = self.proximity.round != Some(round); + if new_round { + let stale_handles = self + .proximity + .grenades + .iter() + .filter_map(|(handle, grenade)| (grenade.source.task.round != round).then_some(*handle)) + .collect::>(); + for handle in stale_handles { + self.stop_grenade_guidance(handle); + } + self.proximity.round = Some(round); + self.proximity + .grenades + .retain(|_, grenade| grenade.source.task.round == round || grenade.guidance_fuse.is_some()); + self.proximity.pending.retain(|source| source.task.round == round); + self.proximity + .guidance_throws + .retain(|throw| throw.source.task.round == round && throw.epoch == guidance_epoch); + self.proximity.guidance_spawns.clear(); + self.proximity.known.clear(); + self.proximity.recent.clear(); + } + if guidance_active { + for spawn in spawned_entities.iter().filter(|spawn| spawn.epoch == guidance_epoch && spawn.tick >= 0) { + if !self + .proximity + .guidance_spawns + .iter() + .any(|existing| existing.handle == spawn.handle && existing.epoch == spawn.epoch) + { + self.proximity.guidance_spawns.push((*spawn).into()); + } + } + self.proximity.guidance_spawns.retain(|spawn| { + spawn.epoch == guidance_epoch + && s2sdk::IsValidEntHandle(spawn.handle) + && !self.projectiles.manages_projectile(spawn.handle) + && s2sdk::GetEntityClassname(spawn.handle).as_str() == "hegrenade_projectile" + }); + let throws = std::mem::take(&mut self.proximity.guidance_throws); + self.proximity.guidance_throws = throws + .into_iter() + .filter(|throw| throw.epoch == guidance_epoch && self.guidance_source_current(throw.source)) + .collect(); + if let Err(error) = self.associate_he_guidance_throws(tick) { + self.handle_fault(error); + return; + } + } else { + self.proximity.guidance_spawns.clear(); + self.proximity.guidance_throws.clear(); + self.stop_all_guidance(); + } + + if !proximity_active { + self.proximity.pending.clear(); + self.proximity.known.clear(); + self.proximity.recent.clear(); + } else { + for source in std::mem::take(&mut self.proximity.pending) { + if self.proximity_source_current(source) + && tick >= source.tick + && tick <= source.tick.saturating_add(1) + && !self.match_proximity_throw(source) + && tick == source.tick + { + self.proximity.pending.push(source); + } + } + self.proximity.known.retain(|handle| s2sdk::IsValidEntHandle(*handle)); + self.proximity + .recent + .retain(|handle, (_, seen)| s2sdk::IsValidEntHandle(*handle) && tick >= *seen && tick <= seen.saturating_add(1)); + for handle in all_projectiles() { + if self.proximity.known.insert(handle) && !new_round && !self.projectiles.manages_projectile(handle) { + let owner = thrower(handle); + if let Some(task) = (0..s2sdk::GetMaxClients()).find_map(|slot| { + let player = LivePlayer::resolve(slot)?; + (player.pawn_handle == owner).then(|| self.combat_task(player)).flatten() + }) { + self.proximity.recent.insert(handle, (task, tick)); + } + } + } + let settings = self.controller.current_mode().and_then(|m| m.proximity_fuse.clone()); + let now = settings.as_ref().map_or(0.0, |_| s2sdk::GetGameTime()); + let mut team_relation_fault = None; + for (handle, mut grenade) in std::mem::take(&mut self.proximity.grenades) { + if !s2sdk::IsValidEntHandle(handle) + || self.projectiles.manages_projectile(handle) + || s2sdk::GetEntityClassname(handle).as_str() != classname(grenade.source.kind) + { + continue; + } + let proximity_current = self.proximity_source_current(grenade.source) && thrower(handle) == grenade.source.player.pawn_handle; + if !proximity_current { + if let Some(fuse_pause) = relinquish_stale_proximity_ownership(&mut grenade) { + // The proximity manager no longer owns this source, but it + // must not drop a deadline lease still owned by HE guidance. + self.queue_guidance_fuse_restore(handle, grenade.source, fuse_pause); + self.proximity.grenades.insert(handle, grenade); + } + continue; + } + let Some(settings) = settings + .as_ref() + .filter(|settings| proximity_current && settings.grenades.contains(&grenade.source.kind)) + else { + self.proximity.grenades.insert(handle, grenade); + continue; + }; + if !grenade.claimed { + // A delayed fuse uses the game's clock and one target identity. + // If that player ceases to qualify, discard the timer before + // selecting any other currently eligible enemy. + if settings.delay_seconds > 0.0 && !now.is_finite() { + grenade.waiting = None; + self.proximity.grenades.insert(handle, grenade); + continue; + } + grenade.waiting = grenade.waiting.filter(|waiting| { + if self.combat_task(waiting.player) != Some(waiting.task) || LivePlayer::resolve(waiting.player.slot) != Some(waiting.player) + { + return false; + } + match qualifies(grenade.source.player, waiting.player, grenade.source.kind, handle, settings.radius) { + Ok(qualifies) => qualifies, + Err(error) => { + team_relation_fault.get_or_insert((Mechanism::ProximityFuse(grenade.source.kind), error)); + false + } + } + }); + if grenade.waiting.is_none() { + grenade.waiting = (0..s2sdk::GetMaxClients()).find_map(|slot| { + let player = LivePlayer::resolve(slot)?; + let task = self.combat_task(player)?; + match qualifies(grenade.source.player, player, grenade.source.kind, handle, settings.radius) { + Ok(true) => Some(WaitingTarget { + player, + task, + started_at: now, + }), + Ok(false) => None, + Err(error) => { + team_relation_fault.get_or_insert((Mechanism::ProximityFuse(grenade.source.kind), error)); + None + } + } + }); + } + if let Some(waiting) = grenade.waiting + && elapsed(now, waiting.started_at, settings.delay_seconds) + { + let action = Action { + source: grenade.source, + handle, + target: waiting.player, + target_task: waiting.task, + radius: settings.radius, + }; + grenade.claimed = true; + self.engine_actions.push(EngineAction::Proximity(action)); + } + } + self.proximity.grenades.insert(handle, grenade); + } + if let Some((mechanism, error)) = team_relation_fault { + self.handle_fault(Fault::mechanism(mechanism, error)); + return; + } + } + if guidance_active { + self.update_he_guidance(); + } + } + + fn associate_he_guidance_throws(&mut self, tick: i32) -> Result<(), Fault> { + let round = self.controller.generation(); + let epoch = crate::HE_GUIDANCE_SPAWN_EPOCH.load(std::sync::atomic::Ordering::Acquire); + let throws = self.proximity.guidance_throws.clone(); + let spawns = self.proximity.guidance_spawns.clone(); + let owners = spawns + .iter() + .enumerate() + .map(|(index, spawn)| (index, thrower(spawn.handle))) + .collect::>(); + let candidates = guidance_candidate_pairs(&throws, &spawns, &owners, round, epoch); + let resolution = resolve_guidance_candidates(&candidates, &throws, &spawns, tick); + let now = s2sdk::GetGameTime(); + let settings = self.controller.current_mode().and_then(|mode| mode.he_guidance); + let mut discard_throws = resolution.discard_throws; + let mut discard_spawns = resolution.discard_spawns; + for (throw_count, spawn_count) in resolution.ambiguous_components { + log(&format!( + "HE guidance association ambiguous; native trajectory retained: throws={throw_count} projectiles={spawn_count}" + )); + } + for (throw_index, spawn_index) in resolution.pairs { + let source = throws[throw_index].source; + let spawn = spawns[spawn_index]; + let handle = spawn.handle; + discard_throws.insert(throw_index); + discard_spawns.insert(spawn_index); + if !now.is_finite() || !spawn.game_time.is_finite() || now < spawn.game_time || settings.is_none() { + continue; + } + let settings = settings.expect("checked above"); + let selected = self + .select_he_guidance_target(source, handle, settings) + .map_err(|error| Fault::mechanism(Mechanism::HeGuidance, error))?; + if !merge_guidance_association(&mut self.proximity.grenades, handle, source, selected, spawn.game_time, now) { + log(&format!( + "HE guidance association conflicts with existing projectile owner: handle={handle} slot={}", + source.player.slot + )); + } else if selected.is_none() { + log(&format!( + "HE guidance found no eligible target at spawn; native fuse retained: handle={handle} slot={}", + source.player.slot + )); + } + } + + for (index, throw) in throws.iter().enumerate() { + if discard_throws.contains(&index) + && !candidates.iter().any(|(throw_index, _)| *throw_index == index) + && self.guidance_source_current(throw.source) + { + log(&format!( + "HE guidance source has no matching projectile; native trajectory retained: slot={} pawn={} tick={}", + throw.source.player.slot, throw.source.player.pawn_handle, throw.source.tick + )); + } + } + self.proximity.guidance_throws = throws + .into_iter() + .enumerate() + .filter_map(|(index, source)| { + (!discard_throws.contains(&index) && source.epoch == epoch && self.guidance_source_current(source.source)).then_some(source) + }) + .collect(); + self.proximity.guidance_spawns = spawns + .into_iter() + .enumerate() + .filter_map(|(index, spawn)| { + (!discard_spawns.contains(&index) && spawn.epoch == epoch && s2sdk::IsValidEntHandle(spawn.handle)).then_some(spawn) + }) + .collect(); + Ok(()) + } + + fn select_he_guidance_target( + &self, + source: Source, + handle: i32, + settings: funrounds_core::HeGuidanceSettings, + ) -> Result, &'static str> { + let origin = s2sdk::GetEntityAbsOrigin(handle); + if ![origin.x, origin.y, origin.z].iter().all(|value| value.is_finite()) { + return Ok(None); + } + let mut nearest: Option<(f64, LivePlayer, PlayerTask)> = None; + for slot in 0..s2sdk::GetMaxClients() { + let Some(target) = LivePlayer::resolve(slot) else { continue }; + let Some(task) = self.combat_task(target) else { continue }; + if !qualifies(source.player, target, GrenadeKind::He, handle, settings.range)? { + continue; + } + let feet = s2sdk::GetClientAbsOrigin(slot); + let eyes = s2sdk::GetClientEyePosition(slot); + let center = Vec3 { + x: feet.x + (eyes.x - feet.x) * 0.5, + y: feet.y + (eyes.y - feet.y) * 0.5, + z: feet.z + (eyes.z - feet.z) * 0.5, + }; + let distance_squared = + f64::from(origin.x - center.x).powi(2) + f64::from(origin.y - center.y).powi(2) + f64::from(origin.z - center.z).powi(2); + if distance_squared.is_finite() + && nearest.is_none_or(|(distance, player, _)| { + guidance_target_order( + (distance_squared, target.slot, target.pawn_handle), + (distance, player.slot, player.pawn_handle), + ) + .is_lt() + }) + { + nearest = Some((distance_squared, target, task)); + } + } + Ok(nearest.map(|(_, player, task)| (player, task))) + } + + fn update_he_guidance(&mut self) { + let Some(settings) = self.controller.current_mode().and_then(|mode| mode.he_guidance) else { + self.stop_all_guidance(); + return; + }; + let now = s2sdk::GetGameTime(); + if !now.is_finite() { + return; + } + let handles = self.proximity.grenades.keys().copied().collect::>(); + for handle in handles { + let Some(grenade) = self.proximity.grenades.get(&handle).cloned() else { + continue; + }; + let Some(mut guidance) = grenade.guidance else { continue }; + let projectile_valid = s2sdk::IsValidEntHandle(handle) + && !self.projectiles.manages_projectile(handle) + && s2sdk::GetEntityClassname(handle).as_str() == "hegrenade_projectile" + && thrower(handle) == grenade.source.player.pawn_handle; + if !self.guidance_source_current(grenade.source) || !projectile_valid || grenade.claimed { + self.stop_grenade_guidance(handle); + continue; + } + + let Some(remaining_budget) = remaining_guidance_budget(guidance.spawned_at, now, settings.max_guidance_seconds) else { + self.stop_grenade_guidance(handle); + continue; + }; + + let target_valid = if !guidance.force_retarget + && self.combat_task(guidance.target) == Some(guidance.target_task) + && LivePlayer::resolve(guidance.target.slot) == Some(guidance.target) + { + match qualifies(grenade.source.player, guidance.target, GrenadeKind::He, handle, settings.range) { + Ok(valid) => valid, + Err(error) => { + self.handle_fault(Fault::mechanism(Mechanism::HeGuidance, error)); + return; + } + } + } else { + false + }; + if !target_valid { + let selected = match self.select_he_guidance_target(grenade.source, handle, settings) { + Ok(selected) => selected, + Err(error) => { + self.handle_fault(Fault::mechanism(Mechanism::HeGuidance, error)); + return; + } + }; + let Some((target, target_task)) = selected else { + self.stop_grenade_guidance(handle); + continue; + }; + retarget_guidance(&mut guidance, target, target_task); + guidance.force_retarget = false; + } + + let delta = now - guidance.last_game_time; + if !delta.is_finite() || delta < 0.0 { + self.stop_grenade_guidance(handle); + continue; + } + + let deadline = grenade_detonate_deadline(handle); + let (fuse_pause, pause_fuse) = if let Some(fuse_pause) = grenade.guidance_fuse { + let pause_fuse = !fuse_pause.confirmed; + if !guidance_deadline_owned(fuse_pause, deadline, f64::from(now), pause_fuse) { + // A near-miss, native detonation, or another owner changed the + // deadline. Its earlier/current value wins; never write over it. + if let Some(entry) = self.proximity.grenades.get_mut(&handle) { + entry.guidance = None; + entry.guidance_fuse = None; + } + continue; + } + (fuse_pause, pause_fuse) + } else { + if !deadline.is_finite() { + self.handle_fault(Fault::mechanism(Mechanism::HeGuidance, "native HE fuse deadline is unavailable")); + self.stop_grenade_guidance(handle); + continue; + } + if deadline <= f64::from(now) { + self.stop_grenade_guidance(handle); + continue; + } + let Some(fuse_pause) = guidance_fuse_pause(deadline, f64::from(now), remaining_budget) else { + self.handle_fault(Fault::mechanism( + Mechanism::HeGuidance, + "HE guidance fuse hold deadline cannot be represented", + )); + self.stop_grenade_guidance(handle); + continue; + }; + (fuse_pause, true) + }; + + guidance.last_game_time = now; + if let Some(entry) = self.proximity.grenades.get_mut(&handle) { + entry.guidance = Some(guidance); + entry.guidance_fuse = Some(fuse_pause); + } + self.engine_actions.push(EngineAction::HeGuidance(GuidanceAction { + source: grenade.source, + handle, + target: guidance.target, + target_task: guidance.target_task, + settings, + delta_seconds: delta, + game_time: now, + fuse_pause, + pause_fuse, + })); + } + } + + pub(crate) fn cancel_proximity_action(&mut self, action: Action) { + if let Some(grenade) = self.proximity.grenades.get_mut(&action.handle) + && grenade.source.task == action.source.task + && grenade.source.kind == action.source.kind + { + grenade.claimed = false; + grenade.waiting = None; + } + } + + pub(super) fn proximity_action_valid(&self, action: Action) -> bool { + self.proximity_active() + && self.proximity_source_current(action.source) + && self.combat_task(action.target) == Some(action.target_task) + && LivePlayer::resolve(action.target.slot) == Some(action.target) + && s2sdk::IsValidEntHandle(action.handle) + && !self.projectiles.manages_projectile(action.handle) + && thrower(action.handle) == action.source.player.pawn_handle + && s2sdk::GetEntityClassname(action.handle).as_str() == classname(action.source.kind) + && qualifies(action.source.player, action.target, action.source.kind, action.handle, action.radius).is_ok_and(|qualifies| qualifies) + } + + pub(crate) fn mark_he_guidance_detonated(&mut self, inflictor: i32, damage_type: u32, skip_plugin_rules: bool) { + if !he_damage_is_detonation(damage_type, skip_plugin_rules) { + return; + } + if let Some(grenade) = self.proximity.grenades.get_mut(&inflictor) + && grenade.source.kind == GrenadeKind::He + { + grenade.guidance = None; + // The native detonation already owns this entity. Do not restore a + // held fuse after its real blast has started. + grenade.guidance_fuse = None; + } + } + + pub(crate) fn reject_he_guidance_action(&mut self, action: GuidanceAction) { + let matches = self.proximity.grenades.get(&action.handle).is_some_and(|grenade| { + grenade.source == action.source + && grenade.guidance_fuse == Some(action.fuse_pause) + && grenade.guidance.is_some_and(|guidance| { + guidance.target == action.target && guidance.target_task == action.target_task && guidance.last_game_time == action.game_time + }) + }); + if !matches { + return; + } + if self.he_guidance_action_base_valid(action) && !self.he_guidance_target_valid(action) { + request_guidance_retarget(&mut self.proximity.grenades, action); + } else { + self.stop_grenade_guidance(action.handle); + } + } + + fn he_guidance_action_base_valid(&self, action: GuidanceAction) -> bool { + let now = s2sdk::GetGameTime(); + self.he_guidance_active() + && self.on_game_thread() + && action.source.kind == GrenadeKind::He + && action.delta_seconds.is_finite() + && action.delta_seconds >= 0.0 + && action.game_time.is_finite() + && self.controller.current_mode().and_then(|mode| mode.he_guidance) == Some(action.settings) + && now.is_finite() + && self.guidance_source_current(action.source) + && s2sdk::IsValidEntHandle(action.handle) + && !self.projectiles.manages_projectile(action.handle) + && s2sdk::GetEntityClassname(action.handle).as_str() == "hegrenade_projectile" + && thrower(action.handle) == action.source.player.pawn_handle + && self.proximity.grenades.get(&action.handle).is_some_and(|grenade| { + !grenade.claimed + && grenade.source == action.source + && grenade.guidance_fuse == Some(action.fuse_pause) + && grenade.guidance.is_some_and(|guidance| { + !guidance.force_retarget + && guidance.target == action.target + && guidance.target_task == action.target_task + && guidance.last_game_time == action.game_time + && remaining_guidance_budget(guidance.spawned_at, now, action.settings.max_guidance_seconds).is_some() + }) + }) + && { + let deadline = grenade_detonate_deadline(action.handle); + guidance_deadline_owned(action.fuse_pause, deadline, f64::from(now), action.pause_fuse) + } + } + + fn he_guidance_target_valid(&self, action: GuidanceAction) -> bool { + self.combat_task(action.target) == Some(action.target_task) + && LivePlayer::resolve(action.target.slot) == Some(action.target) + && qualifies(action.source.player, action.target, GrenadeKind::He, action.handle, action.settings.range).is_ok_and(|qualifies| qualifies) + } + + pub(super) fn he_guidance_action_valid(&self, action: GuidanceAction) -> bool { + self.he_guidance_action_base_valid(action) && self.he_guidance_target_valid(action) + } + + pub(crate) fn confirm_he_guidance_fuse_pause(&mut self, action: GuidanceAction) -> bool { + if !action.pause_fuse + || action.fuse_pause.confirmed + || !self.on_game_thread() + || !s2sdk::IsValidEntHandle(action.handle) + || s2sdk::GetEntityClassname(action.handle).as_str() != "hegrenade_projectile" + || thrower(action.handle) != action.source.player.pawn_handle + || !same_fuse_deadline(grenade_detonate_deadline(action.handle), action.fuse_pause.held_deadline) + { + return false; + } + let Some(grenade) = self.proximity.grenades.get_mut(&action.handle) else { + return false; + }; + if grenade.source != action.source + || grenade.guidance_fuse != Some(action.fuse_pause) + || !grenade.guidance.is_some_and(|guidance| { + guidance.target == action.target && guidance.target_task == action.target_task && guidance.last_game_time == action.game_time + }) + { + return false; + } + grenade.guidance_fuse.as_mut().expect("matched fuse snapshot").confirmed = true; + true + } + + pub(crate) fn he_guidance_fuse_restore_action_valid(&self, action: GuidanceFuseRestoreAction) -> bool { + self.on_game_thread() + && self.proximity.grenades.get(&action.handle).is_some_and(|grenade| { + grenade.source == action.source && grenade.guidance.is_none() && grenade.guidance_fuse == Some(action.fuse_pause) + }) + && s2sdk::IsValidEntHandle(action.handle) + && !self.projectiles.manages_projectile(action.handle) + && s2sdk::GetEntityClassname(action.handle).as_str() == "hegrenade_projectile" + && thrower(action.handle) == action.source.player.pawn_handle + } + + pub(crate) fn complete_he_guidance_fuse_restore(&mut self, action: GuidanceFuseRestoreAction) { + let may_discard_grenade = !self.proximity_active(); + let remove = self.proximity.grenades.get_mut(&action.handle).is_some_and(|grenade| { + if grenade.source != action.source || grenade.guidance_fuse != Some(action.fuse_pause) { + return false; + } + grenade.guidance_fuse = None; + grenade.guidance.is_none() && may_discard_grenade + }); + if remove { + self.proximity.grenades.remove(&action.handle); + } + } + + pub(crate) fn take_he_guidance_fuse_restore_actions(&mut self) -> Vec { + let mut actions = Vec::new(); + self.engine_actions.retain(|action| { + if let EngineAction::HeGuidanceFuseRestore(action) = action { + actions.push(*action); + false + } else { + true + } + }); + actions + } +} + +#[derive(Clone, Copy)] +pub(crate) struct ShockwaveAction { + task: PlayerTask, + player: LivePlayer, + delta: Vec3, +} +impl ShockwaveAction { + pub(super) fn involves(self, slots: &[i32]) -> bool { + slots.contains(&self.player.slot) + } + + pub(crate) fn player(self) -> LivePlayer { + self.player + } +} + +impl Runtime { + fn he_impulse_strength(&self) -> Option { + if !self.classic_round() || !active_combat_phase(self.controller.phase()) { + return None; + } + self.controller.current_mode()?.hegrenade_impulse.map(|settings| settings.impulse) + } + + pub(crate) fn observe_he_blast(&mut self, damage: &crate::damage::Damage, victim: Option) { + if damage.damage_type & crate::damage::DMG_BLAST == 0 || damage.amount <= 0.0 { + return; + } + let Some(impulse) = self.he_impulse_strength().filter(|strength| *strength > 0.0) else { + return; + }; + let Some(player) = victim.filter(|player| LivePlayer::resolve(player.slot) == Some(*player)) else { + return; + }; + let Some(task) = self.combat_task(player) else { return }; + let victims = self.proximity.impulse_hits.entry(damage.inflictor).or_default(); + if victims.contains(&task.player) { + return; + } + victims.push(task.player); + let origin = s2sdk::GetEntityAbsOrigin(damage.inflictor); + let mut center = s2sdk::GetEntityAbsOrigin(player.pawn_handle); + center.z += 36.0; + if let Some(delta) = funrounds_core::shockwave_impulse([origin.x, origin.y, origin.z], [center.x, center.y, center.z], impulse) { + self.engine_actions.push(EngineAction::Shockwave(ShockwaveAction { + task, + player, + delta: Vec3 { + x: delta[0], + y: delta[1], + z: delta[2], + }, + })); + } else { + log(&format!( + "HE shockwave has no finite direction: projectile={} victim={}", + damage.inflictor, player.pawn_handle + )); + } + } + + pub(super) fn takeover_shockwave_targets(&mut self, owners: &[i32], task: PlayerTask) { + for victims in self.proximity.impulse_hits.values_mut() { + for victim in victims { + if owners.contains(&victim.slot) && victim.pawn_handle == task.player.pawn_handle { + *victim = task.player; + } + } + } + } + + pub(super) fn shockwave_action_valid(&self, action: ShockwaveAction) -> bool { + self.he_impulse_strength().is_some() + && self.combat_task(action.player) == Some(action.task) + && LivePlayer::resolve(action.player.slot) == Some(action.player) + && action.player.pawn_controller().is_some() + } +} + +pub(crate) fn execute_shockwave(action: ShockwaveAction) -> Result<(), Fault> { + let before = s2sdk::GetEntityAbsVelocity(action.player.pawn_handle); + let after = Vec3 { + x: before.x + action.delta.x, + y: before.y + action.delta.y, + z: before.z + action.delta.z, + }; + if ![before.x, before.y, before.z, after.x, after.y, after.z].iter().all(|v| v.is_finite()) { + return Err(Fault::mechanism(Mechanism::HeGrenadeImpulse, "HE shockwave velocity unavailable")); + } + s2sdk::SetEntityAbsVelocity(action.player.pawn_handle, &after); + if s2sdk::IsValidEntHandle(action.player.pawn_handle) { + let actual = s2sdk::GetEntityAbsVelocity(action.player.pawn_handle); + if ![(actual.x, after.x), (actual.y, after.y), (actual.z, after.z)] + .iter() + .all(|(a, b)| a.is_finite() && (a - b).abs() <= 0.1) + { + return Err(Fault::mechanism( + Mechanism::HeGrenadeImpulse, + "HE shockwave velocity write/readback failed", + )); + } + } + Ok(()) +} + +pub(crate) fn execute_guidance( + mut action: GuidanceAction, + current: impl Fn(GuidanceAction) -> bool, + confirm_fuse_pause: impl FnOnce() -> bool, +) -> Result<(), Fault> { + let fault = |reason| Fault::mechanism(Mechanism::HeGuidance, reason); + if !current(action) { + return Ok(()); + } + if !s2sdk::IsValidEntHandle(action.handle) + || s2sdk::GetEntityClassname(action.handle).as_str() != "hegrenade_projectile" + || thrower(action.handle) != action.source.player.pawn_handle + || !action.delta_seconds.is_finite() + || action.delta_seconds < 0.0 + { + return Err(Fault::cancelled("HE guidance projectile or action changed before execution")); + } + let deadline = grenade_detonate_deadline(action.handle); + let now = s2sdk::GetGameTime(); + if !now.is_finite() { + return Err(fault("HE guidance game time is unavailable before fuse ownership check")); + } + if action.pause_fuse && !action.fuse_pause.confirmed && guidance_deadline_owned(action.fuse_pause, deadline, f64::from(now), action.pause_fuse) { + if !current(action) + || !s2sdk::IsValidEntHandle(action.handle) + || s2sdk::GetEntityClassname(action.handle).as_str() != "hegrenade_projectile" + || thrower(action.handle) != action.source.player.pawn_handle + || !same_fuse_deadline(grenade_detonate_deadline(action.handle), action.fuse_pause.native_deadline) + { + return Ok(()); + } + set_grenade_detonate_deadline(action.handle, action.fuse_pause.held_deadline); + let actual_deadline = grenade_detonate_deadline(action.handle); + if !s2sdk::IsValidEntHandle(action.handle) + || s2sdk::GetEntityClassname(action.handle).as_str() != "hegrenade_projectile" + || thrower(action.handle) != action.source.player.pawn_handle + || !same_fuse_deadline(actual_deadline, action.fuse_pause.held_deadline) + { + return Err(fault("HE guidance native fuse pause write/readback failed")); + } + if !confirm_fuse_pause() { + return Err(fault("HE guidance fuse pause lost runtime ownership before confirmation")); + } + action.fuse_pause.confirmed = true; + action.pause_fuse = false; + } else if !guidance_deadline_owned(action.fuse_pause, deadline, f64::from(now), action.pause_fuse) { + return Err(fault("HE guidance native fuse deadline changed before pause")); + } + if !current(action) || action.delta_seconds == 0.0 { + return Ok(()); + } + let velocity = s2sdk::GetEntityAbsVelocity(action.handle); + let origin = s2sdk::GetEntityAbsOrigin(action.handle); + let feet = s2sdk::GetClientAbsOrigin(action.target.slot); + let eyes = s2sdk::GetClientEyePosition(action.target.slot); + let target = Vec3 { + x: feet.x + (eyes.x - feet.x) * 0.5, + y: feet.y + (eyes.y - feet.y) * 0.5, + z: feet.z + (eyes.z - feet.z) * 0.5, + }; + let direction = [target.x - origin.x, target.y - origin.y, target.z - origin.z]; + let velocity = [velocity.x, velocity.y, velocity.z]; + if velocity.iter().chain(direction.iter()).any(|value| !value.is_finite()) { + return Err(fault("HE guidance projectile velocity or target direction is unavailable")); + } + let desired = funrounds_core::turn_projectile_velocity(velocity, direction, action.delta_seconds, action.settings) + .ok_or_else(|| fault("HE guidance velocity calculation rejected current motion"))?; + let output = Vec3 { + x: desired[0], + y: desired[1], + z: desired[2], + }; + if !current(action) { + return Ok(()); + } + s2sdk::SetEntityAbsVelocity(action.handle, &output); + if !s2sdk::IsValidEntHandle(action.handle) + || s2sdk::GetEntityClassname(action.handle).as_str() != "hegrenade_projectile" + || thrower(action.handle) != action.source.player.pawn_handle + { + return Err(fault("HE guidance projectile identity changed after velocity write")); + } + let actual = s2sdk::GetEntityAbsVelocity(action.handle); + if ![(actual.x, output.x), (actual.y, output.y), (actual.z, output.z)] + .iter() + .all(|(actual, expected)| actual.is_finite() && (actual - expected).abs() <= 0.1) + { + return Err(fault("HE guidance velocity write/readback failed")); + } + Ok(()) +} + +pub(crate) fn execute_guidance_fuse_restore(action: GuidanceFuseRestoreAction, current: impl Fn() -> bool) -> Result<(), Fault> { + let fault = |reason| Fault::mechanism(Mechanism::HeGuidance, reason); + if !current() { + return Ok(()); + } + if !s2sdk::IsValidEntHandle(action.handle) + || s2sdk::GetEntityClassname(action.handle).as_str() != "hegrenade_projectile" + || thrower(action.handle) != action.source.player.pawn_handle + { + return Ok(()); + } + let now = s2sdk::GetGameTime(); + if !now.is_finite() { + return Err(fault("HE guidance fuse restore has no finite game time")); + } + let deadline = grenade_detonate_deadline(action.handle); + // Trust the live deadline, not confirmation bookkeeping: a setter may have + // landed even when its immediate readback failed. Only our held value is + // ours to restore; native or any other value belongs to another outcome. + if same_fuse_deadline(deadline, action.fuse_pause.native_deadline) + || !same_fuse_deadline(deadline, action.fuse_pause.held_deadline) + || action.fuse_pause.held_deadline <= f64::from(now) + { + return Ok(()); + } + let resume_deadline = f64::from((f64::from(now) + action.fuse_pause.remaining_seconds) as f32); + if !resume_deadline.is_finite() || resume_deadline <= f64::from(now) { + return Err(fault("HE guidance fuse remaining time cannot be represented")); + } + if !current() + || !s2sdk::IsValidEntHandle(action.handle) + || s2sdk::GetEntityClassname(action.handle).as_str() != "hegrenade_projectile" + || thrower(action.handle) != action.source.player.pawn_handle + || !same_fuse_deadline(grenade_detonate_deadline(action.handle), action.fuse_pause.held_deadline) + { + return Ok(()); + } + set_grenade_detonate_deadline(action.handle, resume_deadline); + let actual = grenade_detonate_deadline(action.handle); + if !s2sdk::IsValidEntHandle(action.handle) + || s2sdk::GetEntityClassname(action.handle).as_str() != "hegrenade_projectile" + || thrower(action.handle) != action.source.player.pawn_handle + || !same_fuse_deadline(actual, resume_deadline) + { + return Err(fault("HE guidance native fuse restore write/readback failed")); + } + Ok(()) +} + +fn clear_line(start: Vec3, end: Vec3, ignore: i32, target: Option) -> bool { + let mut position = Vec3 { + x: f32::NAN, + y: f32::NAN, + z: f32::NAN, + }; + let mut fraction = f64::NAN; + let mut hit = true; + let mut entity = -1; + let mut solid = false; + let _ = s2sdk::TraceLine( + &start, + &end, + TRACE_MASK, + ignore, + &mut position, + &mut fraction, + &mut hit, + &mut entity, + &mut solid, + ); + fraction.is_finite() + && (0.0..=1.0).contains(&fraction) + && [position.x, position.y, position.z].iter().all(|v| v.is_finite()) + && !solid + && (target.is_some_and(|target| hit && target == entity) || !hit && fraction >= 0.999) +} + +fn qualifies(source: LivePlayer, target: LivePlayer, kind: GrenadeKind, handle: i32, radius: f32) -> Result { + let source_team = s2sdk::GetClientTeam(source.slot) as i32; + if source == target || !matches!(source_team, 2 | 3) { + return Ok(false); + } + if s2sdk::GetClientTeam(target.slot) as i32 == source_team && super::shooting::teammates_are_friendly()? { + return Ok(false); + } + let origin = s2sdk::GetEntityAbsOrigin(handle); + let feet = s2sdk::GetClientAbsOrigin(target.slot); + let eyes = s2sdk::GetClientEyePosition(target.slot); + let body = Vec3 { + x: feet.x + (eyes.x - feet.x) * 0.5, + y: feet.y + (eyes.y - feet.y) * 0.5, + z: feet.z + (eyes.z - feet.z) * 0.5, + }; + let distance = f64::from(origin.x - body.x).powi(2) + f64::from(origin.y - body.y).powi(2) + f64::from(origin.z - body.z).powi(2); + if !distance.is_finite() || distance > f64::from(radius).powi(2) { + return Ok(false); + } + if needs_facing(kind) { + // Flash proximity is only useful while the target faces the flash and + // its eyes have a clear path to the projectile. + Ok(faces_point(eyes, s2sdk::GetClientEyeAngles(target.slot), origin) && clear_line(eyes, origin, target.pawn_handle, Some(handle))) + } else { + Ok(clear_line(origin, body, handle, Some(target.pawn_handle))) + } +} + +fn elapsed(now: f32, started_at: f32, delay_seconds: f32) -> bool { + delay_seconds == 0.0 || now.is_finite() && started_at.is_finite() && f64::from(now) - f64::from(started_at) >= f64::from(delay_seconds) +} + +fn needs_facing(kind: GrenadeKind) -> bool { + kind == GrenadeKind::Flash +} + +fn faces_point(eyes: Vec3, angles: Vec3, point: Vec3) -> bool { + if ![eyes.x, eyes.y, eyes.z, angles.x, angles.y, angles.z, point.x, point.y, point.z] + .iter() + .all(|value| value.is_finite()) + { + return false; + } + let forward = crate::projectiles::forward(angles); + let toward_point = [ + f64::from(point.x) - f64::from(eyes.x), + f64::from(point.y) - f64::from(eyes.y), + f64::from(point.z) - f64::from(eyes.z), + ]; + let dot = f64::from(forward.x) * toward_point[0] + f64::from(forward.y) * toward_point[1] + f64::from(forward.z) * toward_point[2]; + dot.is_finite() && dot > 0.0 +} + +pub(crate) fn execute(action: Action) -> Result<(), Fault> { + if matches!(action.source.kind, GrenadeKind::Molotov | GrenadeKind::Incendiary) { + return descend(action.handle, action.source.kind); + } + if let Some(kind) = native_kind(action.source.kind) { + let Some(request) = (unsafe { crate::funrounds_native::__funrounds_native_DetonateGrenade }) else { + return Err(Fault::mechanism( + Mechanism::ProximityFuse(action.source.kind), + "native grenade detonation unavailable", + )); + }; + if !matches!(unsafe { request(action.handle, kind) }, 0 | 1) { + return Err(Fault::mechanism( + Mechanism::ProximityFuse(action.source.kind), + "native grenade detonation rejected", + )); + } + } else { + let pointer = s2sdk::EntHandleToEntPointer(action.handle); + let now = f64::from(s2sdk::GetGameTime()); + let previous = s2sdk::GetEntSchemaFloat2(pointer, &Str::from_str(PROJECTILE_CLASS), &Str::from_str("m_flDetonateTime"), 0); + // Do not revive or delay an already due natural detonation. + if previous.is_finite() && previous > now { + s2sdk::SetEntSchemaFloat2( + pointer, + &Str::from_str(PROJECTILE_CLASS), + &Str::from_str("m_flDetonateTime"), + now, + true, + 0, + ); + if s2sdk::IsValidEntHandle(action.handle) + && s2sdk::GetEntSchemaFloat2(pointer, &Str::from_str(PROJECTILE_CLASS), &Str::from_str("m_flDetonateTime"), 0) != now + { + return Err(Fault::mechanism( + Mechanism::ProximityFuse(action.source.kind), + "grenade deadline write/readback failed", + )); + } + } + } + Ok(()) +} +// One velocity impulse: keep horizontal travel, original fuse and collision +// handling. A committed impulse is not a property lease to restore on disable. +fn descend(handle: i32, kind: GrenadeKind) -> Result<(), Fault> { + let fault = |reason| Fault::mechanism(Mechanism::ProximityFuse(kind), reason); + let query = + unsafe { crate::funrounds_native::__funrounds_native_GetGrenadeDetonationState }.ok_or_else(|| fault("native grenade state unavailable"))?; + match unsafe { query(handle, native_kind(kind).expect("fire grenade kind")) } { + 1 => return Ok(()), // Natural collision/detonation already owns this entity. + 0 => {} + _ => return Err(fault("native grenade state rejected")), + } + let previous = s2sdk::GetEntityAbsVelocity(handle); + if ![previous.x, previous.y, previous.z].iter().all(|value| value.is_finite()) { + return Err(fault("grenade velocity read failed")); + } + let desired = Vec3 { + z: previous.z.min(-1200.0), + ..previous + }; + s2sdk::SetEntityAbsVelocity(handle, &desired); + if s2sdk::IsValidEntHandle(handle) { + let actual = s2sdk::GetEntityAbsVelocity(handle); + if ![(actual.x, desired.x), (actual.y, desired.y), (actual.z, desired.z)] + .iter() + .all(|(actual, desired)| actual.is_finite() && (actual - desired).abs() <= 0.1) + { + return Err(fault("grenade descent write/readback failed")); + } + } + Ok(()) +} diff --git a/crates/funrounds-plugin/src/runtime/public_properties.rs b/crates/funrounds-plugin/src/runtime/public_properties.rs new file mode 100644 index 0000000..0d6f5ca --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/public_properties.rs @@ -0,0 +1,474 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::log; +use crate::{ + fault::{Fault, Mechanism}, + game::LivePlayer, + s2sdk, +}; +use funrounds_core::{PlayerIdentity, PlayerTask, PlayerTracker, RoundGeneration}; +use plugify::Str; +use rand::RngExt; +use std::collections::{HashMap, HashSet}; + +#[derive(Clone, Copy, Debug, PartialEq)] +struct OwnedFloat { + previous: f32, + installed: f32, +} + +#[derive(Debug)] +struct WeaponInventory { + player: LivePlayer, + identity: PlayerIdentity, + weapons: HashMap, +} + +#[derive(Default)] +pub(super) struct State { + duck_speed: HashMap, + weapon_inventory: HashMap, + model_scales: HashMap, + model_scale_restore_pending: HashSet, +} + +impl State { + pub(super) fn update(&mut self, enabled: bool, players: &PlayerTracker, round: RoundGeneration, rng: &mut impl rand::Rng) { + if enabled { + self.update_duck_speed(); + } + self.refresh_inventory(enabled, players, round, rng); + self.restore_picked_up_weapon_scales(); + self.retry_model_scale_restores(); + } + + pub(super) fn clear_round_inventory(&mut self) { + self.weapon_inventory.clear(); + } + + pub(super) fn discard_map_state(&mut self) { + // A new map can reuse complete handles; old snapshots must never restore its entities. + self.duck_speed.clear(); + self.weapon_inventory.clear(); + self.model_scales.clear(); + self.model_scale_restore_pending.clear(); + } + + pub(super) fn restore_all(&mut self) { + self.restore_duck_speed(); + self.restore_model_scales(); + } + + pub(super) fn is_restored(&self) -> bool { + self.duck_speed.is_empty() && self.model_scales.is_empty() + } + + pub(super) fn has_pending_restores(&self) -> bool { + !self.model_scale_restore_pending.is_empty() + } + + pub(super) fn cleanup_complete(&self, enabled: bool) -> bool { + (enabled || self.is_restored()) && !self.has_pending_restores() + } + + fn update_duck_speed(&mut self) { + let players = (0..s2sdk::GetMaxClients()) + .filter_map(|slot| { + let player = LivePlayer::resolve_present(slot)?; + duck_speed_update_candidate(player, LivePlayer::resolve(slot), s2sdk::GetClientTeam(slot) as i32).map(|speed| (player, speed)) + }) + .collect::>(); + let current_handles = players + .iter() + .map(|(player, _)| player.pawn_handle) + .collect::>(); + for (player, current) in players { + if let Some(value) = update_owned_minimum(&mut self.duck_speed, player.pawn_handle, current, 8.0) + && !set_duck_speed_for_handle(player.pawn_handle, value) + { + log(&format!("failed to set crouch speed for pawn {}", player.pawn_handle)); + } + } + let stale = self + .duck_speed + .keys() + .copied() + .filter(|handle| !current_handles.contains(handle)) + .collect::>(); + for handle in stale { + let Some(owner) = self.duck_speed.get(&handle).copied() else { continue }; + if release_duck_speed(handle, owner) { + self.duck_speed.remove(&handle); + } + } + } + + fn restore_duck_speed(&mut self) { + let entries = self.duck_speed.iter().map(|(handle, owner)| (*handle, *owner)).collect::>(); + for (handle, owner) in entries { + if release_duck_speed(handle, owner) { + self.duck_speed.remove(&handle); + } + } + } + + fn weapon_inventory_player_is_current(&self, player: LivePlayer, players: &PlayerTracker, round: RoundGeneration) -> bool { + let live_identity_matches = players + .identity(player.slot) + .is_some_and(|identity| identity.pawn_handle == player.pawn_handle as u32) + || self.weapon_inventory.get(&player.slot).is_some_and(|previous| { + previous.player == player + && players.validates_damage_source( + PlayerTask { + round, + player: previous.identity, + }, + round, + player.pawn_handle as u32, + ) + }); + live_identity_matches && player.pawn_controller() == Some(player.controller_handle) + } + + // Both callers validate the complete player identity before these read-only + // game-thread calls. An unavailable service is not an empty inventory. + fn read_client_weapon_inventory(player: LivePlayer) -> Option> { + let class = Str::from_str("CBasePlayerPawn"); + let field = Str::from_str("m_pWeaponServices"); + if s2sdk::GetSchemaOffset(&class, &field) < 0 { + return None; + } + let pawn = s2sdk::EntHandleToEntPointer(player.pawn_handle); + let services = s2sdk::GetEntSchema2(pawn, &class, &field, 0) as usize; + (services != 0).then(|| s2sdk::GetClientWeapons(player.slot).iter().copied().collect()) + } + + pub(super) fn refresh_inventory(&mut self, enabled: bool, players: &PlayerTracker, round: RoundGeneration, rng: &mut impl rand::Rng) { + let scale_drops = enabled && Self::model_scale_imports_available(); + if !scale_drops && self.model_scales.is_empty() && self.model_scale_restore_pending.is_empty() { + self.weapon_inventory.clear(); + return; + } + let max_clients = s2sdk::GetMaxClients(); + self.weapon_inventory.retain(|slot, _| (0..max_clients).contains(slot)); + let mut dropped = Vec::new(); + for slot in 0..max_clients { + let Some(player) = LivePlayer::resolve_present(slot).filter(|player| self.weapon_inventory_player_is_current(*player, players, round)) + else { + self.weapon_inventory.remove(&slot); + continue; + }; + let Some(mut weapons) = Self::read_client_weapon_inventory(player) else { + // An unreadable service is not an empty inventory. Keep only the + // matching life's observation until a ready scan can confirm a drop. + if self.weapon_inventory.get(&slot).is_some_and(|previous| previous.player != player) { + self.weapon_inventory.remove(&slot); + } + continue; + }; + weapons.retain(|handle| s2sdk::IsValidEntHandle(*handle) && s2sdk::GetEntityOwner(*handle) == player.pawn_handle); + let identity = players + .identity(slot) + .or_else(|| self.weapon_inventory.get(&slot).map(|previous| previous.identity)); + let Some(identity) = identity else { continue }; + let inventory = self.weapon_inventory.entry(slot).or_insert_with(|| WeaponInventory { + player, + identity, + weapons: HashMap::new(), + }); + if inventory.player != player { + inventory.weapons.clear(); + } + inventory.player = player; + inventory.identity = identity; + // CS2 has no weapon_drop event. Keep classnames for the lifetime of + // each observed full handle, and recheck identity and owner on removal. + inventory.weapons.retain(|handle, classname| { + if weapons.contains(handle) { + return true; + } + if !scale_drops || !s2sdk::IsValidEntHandle(*handle) || s2sdk::GetEntityClassname(*handle).as_str() != classname { + return false; + } + match s2sdk::GetEntityOwner(*handle) { + -1 => { + dropped.push(*handle); + false + } + // Inventory removal can precede ownership release in a callback. + owner if owner == player.pawn_handle => true, + _ => false, + } + }); + for handle in weapons { + inventory + .weapons + .entry(handle) + .or_insert_with(|| s2sdk::GetEntityClassname(handle).to_string()); + } + } + self.model_scales.retain(|handle, _| s2sdk::IsValidEntHandle(*handle)); + self.model_scale_restore_pending.retain(|handle| self.model_scales.contains_key(handle)); + for handle in dropped { + self.randomize_model_scale(handle, rng); + } + } + + pub(super) fn randomize_model_scale(&mut self, handle: i32, rng: &mut impl rand::Rng) { + if self.model_scales.contains_key(&handle) { + return; + } + let Some(previous) = Self::entity_model_scale(handle) else { return }; + let installed = Self::random_model_scale(rng); + if Self::set_entity_model_scale(handle, installed) { + self.model_scales.insert(handle, OwnedFloat { previous, installed }); + } + } + + pub(super) fn scale_chicken_bomb(&mut self, bomb: i32, chicken: i32, rng: &mut impl rand::Rng) -> Result<(), Fault> { + if self.model_scales.contains_key(&chicken) || !s2sdk::IsValidEntHandle(bomb) || s2sdk::GetEntityParent(bomb) != chicken { + return Ok(()); + } + let (Some(previous), Some(child_local)) = (Self::entity_model_scale(chicken), Self::entity_model_scale(bomb)) else { + return Ok(()); + }; + // SetParent preserves the C4's world scale via its local scale. The engine + // propagates the parent's multiplier to both the child and its local offset. + // Only the parent is written: two writes would square the group multiplier. + let installed = previous * Self::random_model_scale(rng); + self.model_scales.insert(chicken, OwnedFloat { previous, installed }); + if !Self::set_entity_model_scale(chicken, installed) + || !s2sdk::IsValidEntHandle(bomb) + || s2sdk::GetEntityParent(bomb) != chicken + || Self::entity_model_scale(bomb).is_none_or(|actual| (actual - child_local).abs() > 0.0001) + { + self.restore_model_scale(chicken); + return Err(Fault::mechanism(Mechanism::ChickenBomb, "chicken/C4 group model scale readback failed")); + } + Ok(()) + } + + fn entity_model_scale(handle: i32) -> Option { + if !Self::model_scale_imports_available() || !s2sdk::IsValidEntHandle(handle) { + return None; + } + let pointer = s2sdk::EntHandleToEntPointer(handle); + if pointer == 0 || s2sdk::EntPointerToEntHandle(pointer) != handle { + return None; + } + let scale = s2sdk::GetEntityModelScale(handle); + scale.is_finite().then_some(scale) + } + + fn set_entity_model_scale(handle: i32, value: f32) -> bool { + if !Self::model_scale_imports_available() || !s2sdk::IsValidEntHandle(handle) || !value.is_finite() { + return false; + } + let pointer = s2sdk::EntHandleToEntPointer(handle); + if pointer == 0 || s2sdk::EntPointerToEntHandle(pointer) != handle { + return false; + } + s2sdk::SetEntityModelScale(handle, value); + Self::entity_model_scale(handle).is_some_and(|actual| (actual - value).abs() <= 0.0001) + } + + fn model_scale_imports_available() -> bool { + let mut probe = crate::capability::Probe::default(); + crate::capability::imports!(probe; __s2sdk_GetEntityModelScale, __s2sdk_SetEntityModelScale); + probe.available() + } + + fn random_model_scale(rng: &mut impl rand::Rng) -> f32 { + match rng.random_range(1..=5) { + 5 => rng.random_range(3.0..=15.0), + 4 => rng.random_range(0.5..=0.75), + _ => rng.random_range(0.75..=3.0), + } + } + + pub(super) fn item_pickup(&mut self, slot: i32, event: usize, players: &PlayerTracker, round: RoundGeneration) { + let Some(player) = LivePlayer::resolve_present(slot).filter(|player| self.weapon_inventory_player_is_current(*player, players, round)) else { + return; + }; + let Some(weapons) = Self::read_client_weapon_inventory(player) else { + return; + }; + let item = s2sdk::GetEventString(event, &Str::from_str("item")).to_string(); + for handle in weapons { + if !self.model_scales.contains_key(&handle) { + continue; + } + if !s2sdk::IsValidEntHandle(handle) + || s2sdk::GetEntityOwner(handle) != player.pawn_handle + || !matches_weapon_item(s2sdk::GetEntityClassname(handle).as_str(), &item) + { + continue; + } + self.restore_model_scale(handle); + } + } + + fn restore_picked_up_weapon_scales(&mut self) { + let picked_up = self + .model_scales + .keys() + .filter_map(|handle| { + let player_owns_it = self + .weapon_inventory + .values() + .any(|inventory| inventory.weapons.contains_key(handle) && s2sdk::GetEntityOwner(*handle) == inventory.player.pawn_handle); + player_owns_it.then_some(*handle) + }) + .collect::>(); + for handle in picked_up { + self.restore_model_scale(handle); + } + } + + pub(super) fn restore_model_scale(&mut self, handle: i32) -> bool { + let Some(owner) = self.model_scales.get(&handle).copied() else { + self.model_scale_restore_pending.remove(&handle); + return true; + }; + if release_model_scale(handle, owner) { + self.model_scales.remove(&handle); + self.model_scale_restore_pending.remove(&handle); + true + } else { + self.model_scale_restore_pending.insert(handle); + false + } + } + + fn restore_model_scales(&mut self) { + let entries = self.model_scales.iter().map(|(handle, owner)| (*handle, *owner)).collect::>(); + for (handle, owner) in entries { + if release_model_scale(handle, owner) { + self.model_scales.remove(&handle); + self.model_scale_restore_pending.remove(&handle); + } else { + self.model_scale_restore_pending.insert(handle); + } + } + } + + pub(super) fn retry_model_scale_restores(&mut self) { + let handles = self.model_scale_restore_pending.iter().copied().collect::>(); + for handle in handles { + self.restore_model_scale(handle); + } + } +} + +fn update_owned_minimum(properties: &mut HashMap, handle: i32, current: f32, installed: f32) -> Option { + if !current.is_finite() || !installed.is_finite() { + return None; + } + match properties.get(&handle).copied() { + Some(_) if (current - installed).abs() <= 0.0001 => None, + Some(owner) if current < installed => { + properties.insert(handle, owner); + Some(installed) + } + Some(_) => { + properties.remove(&handle); + None + } + None if current < installed => { + properties.insert( + handle, + OwnedFloat { + previous: current, + installed, + }, + ); + Some(installed) + } + None => None, + } +} + +fn owned_float_restore(owner: OwnedFloat, current: f32) -> Option { + (current.is_finite() && (current - owner.installed).abs() <= 0.0001).then_some(owner.previous) +} + +fn matches_weapon_item(classname: &str, item: &str) -> bool { + let item = item.trim().to_ascii_lowercase(); + let classname = classname.trim().to_ascii_lowercase(); + !item.is_empty() && (item == classname || format!("weapon_{item}") == classname || format!("weapon_{classname}") == item) +} + +fn player_movement_services_for_handle(handle: i32) -> Option { + if !s2sdk::IsValidEntHandle(handle) { + return None; + } + let pawn = s2sdk::EntHandleToEntPointer(handle); + if pawn == 0 || s2sdk::EntPointerToEntHandle(pawn) != handle || s2sdk::GetEntityClassname(handle).as_str() != "player" { + return None; + } + let pawn_class = Str::from_str("CBasePlayerPawn"); + let services_field = Str::from_str("m_pMovementServices"); + let movement_class = Str::from_str("CCSPlayer_MovementServices"); + let duck_field = Str::from_str("m_flDuckSpeed"); + if s2sdk::GetSchemaOffset(&pawn_class, &services_field) < 0 || s2sdk::GetSchemaOffset(&movement_class, &duck_field) < 0 { + return None; + } + let services = s2sdk::GetEntSchema2(pawn, &pawn_class, &services_field, 0) as usize; + (services != 0).then_some(services) +} + +fn duck_speed_for_handle(handle: i32) -> Option { + let services = player_movement_services_for_handle(handle)?; + let speed = s2sdk::GetEntSchemaFloat2(services, &Str::from_str("CCSPlayer_MovementServices"), &Str::from_str("m_flDuckSpeed"), 0) as f32; + speed.is_finite().then_some(speed) +} + +fn set_duck_speed_for_handle(handle: i32, value: f32) -> bool { + if !value.is_finite() { + return false; + } + let Some(services) = player_movement_services_for_handle(handle) else { + return false; + }; + s2sdk::SetEntSchemaFloat2( + services, + &Str::from_str("CCSPlayer_MovementServices"), + &Str::from_str("m_flDuckSpeed"), + f64::from(value), + true, + 0, + ); + duck_speed_for_handle(handle).is_some_and(|actual| (actual - value).abs() <= 0.0001) +} + +fn release_duck_speed(handle: i32, owner: OwnedFloat) -> bool { + if !s2sdk::IsValidEntHandle(handle) { + return true; + } + let Some(current) = duck_speed_for_handle(handle) else { return false }; + let Some(previous) = owned_float_restore(owner, current) else { + return true; + }; + set_duck_speed_for_handle(handle, previous) +} + +fn duck_speed_update_candidate(player: LivePlayer, active_player: Option, team: i32) -> Option { + if active_player != Some(player) || !matches!(team, 2 | 3) { + return None; + } + duck_speed_for_handle(player.pawn_handle) +} + +fn release_model_scale(handle: i32, owner: OwnedFloat) -> bool { + if !s2sdk::IsValidEntHandle(handle) { + return true; + } + let Some(current) = State::entity_model_scale(handle) else { + return false; + }; + let Some(previous) = owned_float_restore(owner, current) else { + return true; + }; + State::set_entity_model_scale(handle, previous) +} diff --git a/crates/funrounds-plugin/src/runtime/regions.rs b/crates/funrounds-plugin/src/runtime/regions.rs new file mode 100644 index 0000000..b946794 --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/regions.rs @@ -0,0 +1,719 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::*; +use funrounds_core::regions::{ + MEDICAL_SMOKE_HEAL, MEDICAL_SMOKE_INTERVAL_SECONDS, MEDICAL_SMOKE_RADIUS, Position, TrampolineLatch, TrampolineRegion, fixed_trampoline_region, + medical_smoke_team, +}; +use plugify::{Str, Vec3}; +use std::collections::{HashMap, HashSet}; + +const SMOKE_PROJECTILE: &str = "smokegrenade_projectile"; +const GRENADE_CLASS: &str = "CBaseGrenade"; +const THROWER_FIELD: &str = "m_hThrower"; +const ON_GROUND: i32 = 1; + +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct Prerequisites { + trampoline: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct SmokeThrow { + player: PlayerIdentity, + team: Option, + round: RoundGeneration, + tick: i32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct SmokeProjectile { + handle: i32, + thrower: i32, + tick: i32, + round: RoundGeneration, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct SmokeReceipt { + team: i32, + round: RoundGeneration, +} + +#[derive(Clone, Copy)] +struct SmokeDetonation { + handle: i32, + entity_index: i32, + origin: Position, + round: RoundGeneration, + tick: i32, + time: f64, +} + +impl SmokeDetonation { + fn can_wait_for_receipt(self, tick: i32, round: RoundGeneration) -> bool { + // At most one tick separates the observations; both adjacent-tick + // windows must close before the pair can be accepted. + self.round == round && tick <= self.tick.saturating_add(3) + } +} + +#[derive(Clone, Copy)] +struct SmokeCloud { + handle: i32, + entity_index: i32, + team: i32, + origin: Position, + round: RoundGeneration, +} + +#[derive(Default)] +pub(super) struct State { + prerequisites: Prerequisites, + smoke_active: bool, + pending_throws: Vec, + smoke_projectiles: Vec, + smoke_receipts: HashMap, + pending_detonations: HashMap, + observed_smokes: HashSet, + smokes: HashMap, + next_smoke_pulse: Option, + map_name: Option, + trampoline_region: Option, + trampoline_latches: HashMap, +} + +impl State { + fn begin_smoke_activation(&mut self, existing: impl IntoIterator) { + self.smoke_active = true; + self.pending_throws.clear(); + self.smoke_projectiles.clear(); + self.smoke_receipts.clear(); + self.pending_detonations.clear(); + self.smokes.clear(); + self.next_smoke_pulse = None; + self.observed_smokes = existing.into_iter().collect(); + } + + fn disable_smoke(&mut self) { + self.smoke_active = false; + self.pending_throws.clear(); + self.smoke_projectiles.clear(); + self.smoke_receipts.clear(); + self.pending_detonations.clear(); + self.observed_smokes.clear(); + self.smokes.clear(); + self.next_smoke_pulse = None; + } + + fn observe_smoke_throw(&mut self, throw: SmokeThrow) { + self.pending_throws.push(throw); + } + + fn observe_smoke_projectile(&mut self, projectile: SmokeProjectile) { + if !self.observed_smokes.insert(projectile.handle) { + return; + } + self.smoke_projectiles.push(projectile); + } + + /// Pair by thrower handle and the adjacent engine tick window. Ambiguous many-to-many pairs are discarded. + fn resolve_smoke_projectiles(&mut self, tick: i32, round: RoundGeneration) { + let mut throws_by_projectile = vec![Vec::new(); self.smoke_projectiles.len()]; + let mut projectiles_by_throw = vec![Vec::new(); self.pending_throws.len()]; + for (throw_index, throw) in self.pending_throws.iter().enumerate() { + for (projectile_index, projectile) in self.smoke_projectiles.iter().enumerate() { + if throw.round == round + && projectile.round == round + && projectile.thrower == throw.player.pawn_handle as i32 + && throw.tick.abs_diff(projectile.tick) <= 1 + { + projectiles_by_throw[throw_index].push(projectile_index); + throws_by_projectile[projectile_index].push(throw_index); + } + } + } + + let mut resolved_throws = HashSet::new(); + let mut resolved_projectiles = HashSet::new(); + for (throw_index, projectile_indexes) in projectiles_by_throw.iter().enumerate() { + if projectile_indexes.len() > 1 || projectile_indexes.iter().any(|index| throws_by_projectile[*index].len() > 1) { + // Do not let an ambiguous association become a match as older + // candidates independently age out of the window. + resolved_throws.insert(throw_index); + resolved_projectiles.extend(projectile_indexes.iter().copied()); + continue; + } + let [projectile_index] = projectile_indexes.as_slice() else { continue }; + let throw = self.pending_throws[throw_index]; + let projectile = self.smoke_projectiles[*projectile_index]; + if tick <= throw.tick.saturating_add(1) || tick <= projectile.tick.saturating_add(1) { + continue; + } + let detonation = self.pending_detonations.remove(&projectile.handle); + if let Some(team) = throw.team { + if let Some(detonation) = detonation { + if detonation.can_wait_for_receipt(tick, round) { + self.open_smoke_cloud(detonation, team); + } + } else { + self.smoke_receipts.insert(projectile.handle, SmokeReceipt { team, round: throw.round }); + } + } + resolved_throws.insert(throw_index); + resolved_projectiles.insert(*projectile_index); + } + + self.pending_throws = self + .pending_throws + .drain(..) + .enumerate() + .filter_map(|(index, throw)| { + (!resolved_throws.contains(&index) + && throw.round == round + // A projectile can arrive one tick after its throw and needs + // its own adjacent tick to leave the association window. + && tick <= throw.tick.saturating_add(2)) + .then_some(throw) + }) + .collect(); + self.smoke_projectiles = self + .smoke_projectiles + .drain(..) + .enumerate() + .filter_map(|(index, projectile)| { + (!resolved_projectiles.contains(&index) && projectile.round == round && tick <= projectile.tick.saturating_add(2)) + .then_some(projectile) + }) + .collect(); + self.pending_detonations + .retain(|_, detonation| detonation.can_wait_for_receipt(tick, round)); + } + + fn observe_smoke_detonation(&mut self, detonation: SmokeDetonation) -> bool { + let handle = detonation.handle; + if self.smokes.contains_key(&handle) { + return false; + } + if let Some(team) = self.take_smoke_receipt(handle, detonation.round) { + self.open_smoke_cloud(detonation, team); + return true; + } + // Keep the first native event, not a borrowed event pointer. Only a + // same-round receipt for the exact full handle can turn it into a cloud. + self.pending_detonations.entry(handle).or_insert(detonation); + false + } + + fn open_smoke_cloud(&mut self, detonation: SmokeDetonation, team: i32) { + self.smokes.insert( + detonation.handle, + SmokeCloud { + handle: detonation.handle, + entity_index: detonation.entity_index, + team, + origin: detonation.origin, + round: detonation.round, + }, + ); + self.next_smoke_pulse.get_or_insert(detonation.time + MEDICAL_SMOKE_INTERVAL_SECONDS); + } + + fn take_smoke_receipt(&mut self, handle: i32, round: RoundGeneration) -> Option { + let receipt = self.smoke_receipts.remove(&handle)?; + (receipt.round == round).then_some(receipt.team) + } + + fn forget_player_latch(&mut self, slot: i32) { + self.trampoline_latches.remove(&slot); + } +} + +pub(super) fn probe(events: &EventCapabilities, capabilities: &mut funrounds_core::Capabilities, reasons: &mut Vec) -> State { + let mut smoke = crate::capability::Probe::default(); + crate::capability::imports!(smoke; + __s2sdk_GetGameTime, __s2sdk_GetGameTickCount, __s2sdk_GetFirstActiveEntity, __s2sdk_GetNextActiveEntity, + __s2sdk_GetMaxClients, __s2sdk_IsClientInGame, __s2sdk_IsClientAlive, + __s2sdk_GetClientTeam, __s2sdk_GetClientAbsOrigin, __s2sdk_GetClientHealth, __s2sdk_SetClientHealth, + __s2sdk_PlayerSlotToEntHandle, __s2sdk_GetEventPlayerSlot, __s2sdk_GetEventString, + __s2sdk_GetEventInt, __s2sdk_GetEventFloat, __s2sdk_EntIndexToEntHandle, + __s2sdk_IsValidEntHandle, __s2sdk_EntHandleToEntPointer, __s2sdk_EntPointerToEntHandle, + __s2sdk_GetEntityClassname, __s2sdk_GetEntSchemaEnt2, __s2sdk_FindConVar, __s2sdk_GetConVarValue, + ); + smoke.require(events.grenade_thrown, "event:grenade_thrown"); + smoke.require(events.smoke_events, "events:smokegrenade_detonate/smokegrenade_expired"); + smoke.require(events.combat_events, "events:player_spawn/player_death"); + smoke.require( + shooting::teammates_are_friendly().is_ok(), + "convar:mp_teammates_are_enemies (readable boolean)", + ); + smoke.schema(GRENADE_CLASS, THROWER_FIELD); + capabilities.medical_smoke = smoke.record("medical_smoke", reasons); + + let mut trampoline = crate::capability::Probe::default(); + crate::capability::imports!(trampoline; + __s2sdk_GetCurrentMap, __s2sdk_GetGameTickCount, __s2sdk_GetMaxClients, + __s2sdk_GetClientAbsOrigin, __s2sdk_GetClientAbsVelocity, __s2sdk_SetClientAbsVelocity, + __s2sdk_GetClientFlags, + ); + trampoline.require(events.round_prestart, "event:round_prestart"); + trampoline.require(events.combat_events, "events:player_spawn/player_death"); + let trampoline_ready = trampoline.record("trampoline", reasons); + capabilities.trampoline = false; + if trampoline_ready { + reasons.push("trampoline:[waiting for map readiness]".into()); + } + + State { + prerequisites: Prerequisites { + trampoline: trampoline_ready, + }, + ..State::default() + } +} + +impl Runtime { + fn medical_smoke_enabled(&self) -> bool { + self.classic_enabled() + && self.effects_ready + && active_combat_phase(self.controller.phase()) + && self.faults.capabilities().medical_smoke + && self + .controller + .current_mode() + .is_some_and(|mode| mode.medical_smoke && mode.teammates_as_enemies != Some(true)) + } + + fn trampoline_enabled(&self) -> bool { + self.classic_enabled() + && self.effects_ready + && active_combat_phase(self.controller.phase()) + && self.faults.capabilities().trampoline + && self.controller.current_mode().is_some_and(|mode| mode.trampoline) + && self.regions.trampoline_region.is_some() + } + + fn sync_smoke_tracking(&mut self, enabled: bool) { + match (enabled, self.regions.smoke_active) { + (true, false) => { + let existing = game::entity_handles(SMOKE_PROJECTILE) + .into_iter() + .filter(|handle| complete_entity(*handle)) + .collect::>(); + self.regions.begin_smoke_activation(existing); + } + (false, true) => self.regions.disable_smoke(), + _ => {} + } + } + + fn scan_smoke_projectiles(&mut self, tick: i32) { + if tick < 0 || !self.regions.smoke_active { + return; + } + let round = self.controller.generation(); + self.regions.observed_smokes.retain(|handle| complete_entity(*handle)); + self.regions.smoke_receipts.retain(|handle, _| complete_entity(*handle)); + self.regions + .smoke_projectiles + .retain(|projectile| projectile.round == round && is_smoke_projectile(projectile.handle)); + + // Discovery needs the active entity list only while a throw is awaiting + // attribution. Existing candidates can be checked by full handle. + if !self.regions.pending_throws.is_empty() { + for projectile in &mut self.regions.smoke_projectiles { + let pointer = s2sdk::EntHandleToEntPointer(projectile.handle); + projectile.thrower = s2sdk::GetEntSchemaEnt2(pointer, &Str::from_str(GRENADE_CLASS), &Str::from_str(THROWER_FIELD), 0); + } + for handle in game::entity_handles(SMOKE_PROJECTILE) { + if self.regions.observed_smokes.contains(&handle) || !complete_entity(handle) { + continue; + } + let pointer = s2sdk::EntHandleToEntPointer(handle); + let thrower = s2sdk::GetEntSchemaEnt2(pointer, &Str::from_str(GRENADE_CLASS), &Str::from_str(THROWER_FIELD), 0); + self.regions.observe_smoke_projectile(SmokeProjectile { + handle, + thrower, + tick, + round, + }); + } + } + self.regions.pending_detonations.retain(|handle, _| is_smoke_projectile(*handle)); + self.regions.resolve_smoke_projectiles(tick, round); + } + + /// Read the event while its borrowed engine pointer is valid; only owned identities and values persist. + pub(super) fn on_region_event(&mut self, name: &str, event: usize) { + match name { + "smokegrenade_detonate" => self.start_smoke(event), + "smokegrenade_expired" => self.expire_smoke(event), + _ => {} + } + } + + pub(super) fn record_smoke_throw(&mut self, slot: i32) { + let enabled = self.medical_smoke_enabled(); + self.sync_smoke_tracking(enabled); + if !enabled { + return; + } + let friendly = match shooting::teammates_are_friendly() { + Ok(friendly) => friendly, + Err(error) => { + self.handle_fault(Fault::mechanism(Mechanism::MedicalSmoke, error)); + return; + } + }; + let Some(player) = LivePlayer::resolve(slot).filter(|player| player.pawn_controller() == Some(player.controller_handle)) else { + return; + }; + let Some(task) = self.combat_task(player) else { return }; + // Consume native throws even when they cannot heal, so their older + // projectiles are not rediscovered after the friendly-fire policy changes. + let team = medical_smoke_team(s2sdk::GetClientTeam(slot) as i32, !friendly); + let tick = s2sdk::GetGameTickCount(); + if tick < 0 { + return; + } + self.regions.observe_smoke_throw(SmokeThrow { + player: task.player, + team, + round: task.round, + tick, + }); + self.scan_smoke_projectiles(tick); + } + + fn start_smoke(&mut self, event: usize) { + let enabled = self.medical_smoke_enabled(); + self.sync_smoke_tracking(enabled); + if !enabled { + return; + } + let entity_index = s2sdk::GetEventInt(event, &Str::from_str("entityid")); + let handle = s2sdk::EntIndexToEntHandle(entity_index); + if !is_smoke_projectile(handle) { + return; + } + let origin = Position { + x: s2sdk::GetEventFloat(event, &Str::from_str("x")), + y: s2sdk::GetEventFloat(event, &Str::from_str("y")), + z: s2sdk::GetEventFloat(event, &Str::from_str("z")), + }; + if !origin.is_finite() { + return; + } + let now = f64::from(s2sdk::GetGameTime()); + if !now.is_finite() { + self.handle_fault(Fault::mechanism( + Mechanism::MedicalSmoke, + "game time is not finite when a smoke cloud starts", + )); + return; + } + let tick = s2sdk::GetGameTickCount(); + if tick < 0 { + return; + } + let matched = self.regions.observe_smoke_detonation(SmokeDetonation { + handle, + entity_index, + origin, + round: self.controller.generation(), + tick, + time: now, + }); + if self.diagnostics() { + log(&format!("medical_smoke=detonate tick={tick} handle={handle} matched={matched}")); + } + } + + fn expire_smoke(&mut self, event: usize) { + let entity_index = s2sdk::GetEventInt(event, &Str::from_str("entityid")); + let event_handle = s2sdk::EntIndexToEntHandle(entity_index); + let mut expired = self + .regions + .smokes + .iter() + .filter_map(|(handle, smoke)| { + (smoke.entity_index == entity_index && (event_handle == *handle || !complete_entity(*handle))).then_some(*handle) + }) + .collect::>(); + expired.extend( + self.regions + .observed_smokes + .iter() + .copied() + .filter(|handle| event_handle == *handle || !complete_entity(*handle)), + ); + expired.extend( + self.regions + .smoke_receipts + .keys() + .copied() + .filter(|handle| event_handle == *handle || !complete_entity(*handle)), + ); + self.regions + .pending_detonations + .retain(|handle, _| event_handle != *handle && complete_entity(*handle)); + for handle in expired { + self.regions.smokes.remove(&handle); + self.regions.smoke_receipts.remove(&handle); + self.regions.smoke_projectiles.retain(|projectile| projectile.handle != handle); + } + self.regions.observed_smokes.retain(|handle| complete_entity(*handle)); + // The native expiry event can arrive before deletion. Never rediscover + // that same full handle as a new projectile during another throw. + if is_smoke_projectile(event_handle) { + self.regions.observed_smokes.insert(event_handle); + } + if self.regions.smokes.is_empty() { + self.regions.next_smoke_pulse = None; + } + } + + /// Called from round prestart/start only when the map-query imports passed the startup probe. + pub(super) fn on_region_map_ready(&mut self) { + let Some(map_name) = map_name_when_ready( + self.regions.prerequisites, + || s2sdk::GetGameTickCount(), + || s2sdk::GetCurrentMap().to_string(), + ) else { + return; + }; + let region = fixed_trampoline_region(&map_name); + if self.regions.map_name.as_deref() != Some(map_name.as_str()) { + self.clear_regions_round(); + } + self.regions.map_name = Some(map_name); + self.regions.trampoline_region = region; + self.refresh_trampoline_availability(); + } + + fn refresh_trampoline_availability(&mut self) { + let ready = self.regions.prerequisites.trampoline && self.regions.trampoline_region.is_some(); + if self.faults.set_trampoline_available(ready) { + self.controller.set_capabilities(self.faults.capabilities()); + } + } + + pub(crate) fn update_regions(&mut self, now: f64) { + let smoke_enabled = self.medical_smoke_enabled(); + self.sync_smoke_tracking(smoke_enabled); + if smoke_enabled + && (!self.regions.pending_throws.is_empty() || !self.regions.smoke_projectiles.is_empty() || !self.regions.pending_detonations.is_empty()) + { + self.scan_smoke_projectiles(s2sdk::GetGameTickCount()); + } + if self.regions.smokes.is_empty() { + self.regions.next_smoke_pulse = None; + } else { + let generation = self.controller.generation(); + self.regions + .smokes + .retain(|_, smoke| smoke.round == generation && complete_entity(smoke.handle)); + if self.regions.smokes.is_empty() { + self.regions.next_smoke_pulse = None; + } else if !now.is_finite() { + self.regions.smokes.clear(); + self.regions.next_smoke_pulse = None; + self.handle_fault(Fault::mechanism(Mechanism::MedicalSmoke, "game time is not finite during smoke healing")); + } else { + let due = *self.regions.next_smoke_pulse.get_or_insert(now + MEDICAL_SMOKE_INTERVAL_SECONDS); + if now >= due { + self.regions.next_smoke_pulse = Some(now + MEDICAL_SMOKE_INTERVAL_SECONDS); + self.heal_smoke_recipients(); + } + } + } + + if !self.trampoline_enabled() { + self.regions.trampoline_latches.clear(); + return; + } + self.update_trampoline_players(); + } + + fn heal_smoke_recipients(&mut self) { + let Some(healing_cap) = self.controller.current_mode().map(|mode| mode.healing_cap_base_multiple) else { + return; + }; + match shooting::teammates_are_friendly() { + Ok(true) => {} + Ok(false) => return, + Err(error) => { + self.handle_fault(Fault::mechanism(Mechanism::MedicalSmoke, error)); + return; + } + } + let smokes = self.regions.smokes.values().copied().collect::>(); + for slot in 0..s2sdk::GetMaxClients() { + let Some(player) = LivePlayer::resolve(slot) else { continue }; + let team = s2sdk::GetClientTeam(slot) as i32; + let position = position(s2sdk::GetClientAbsOrigin(slot)); + if !position.is_finite() { + continue; + } + if !smokes + .iter() + .any(|smoke| smoke.team == team && position.within_sphere(smoke.origin, MEDICAL_SMOKE_RADIUS)) + { + continue; + } + let Some(task) = self.combat_task(player) else { continue }; + let Some(base) = self + .combat + .lives + .get(&slot) + .filter(|(expected, _)| *expected == task) + .map(|(_, life)| i32::from(life.attributes().health)) + else { + continue; + }; + if self.effects.get(&slot).is_none_or(|effect| effect.has_pending_loadout()) { + continue; + } + if let Err(error) = super::composed::heal( + slot, + base, + funrounds_core::HealingAmount::Fixed(MEDICAL_SMOKE_HEAL), + healing_cap, + Mechanism::MedicalSmoke, + ) { + self.handle_fault(error); + self.regions.smokes.clear(); + self.regions.next_smoke_pulse = None; + return; + } + } + } + + fn update_trampoline_players(&mut self) { + let Some(region) = self.regions.trampoline_region else { return }; + for slot in 0..s2sdk::GetMaxClients() { + let Some(player) = LivePlayer::resolve(slot) else { + self.regions.trampoline_latches.remove(&slot); + continue; + }; + let Some(task) = self.combat_task(player) else { + self.regions.trampoline_latches.remove(&slot); + continue; + }; + if self.effects.get(&slot).is_none_or(|effect| effect.has_pending_loadout()) { + continue; + } + let position = position(s2sdk::GetClientAbsOrigin(slot)); + let grounded = s2sdk::GetClientFlags(slot) & ON_GROUND != 0; + let step = self + .regions + .trampoline_latches + .entry(slot) + .or_default() + .observe(task.player, position, grounded, region); + if step.triggered { + self.launch_trampoline(player, task.player); + } + } + } + + fn launch_trampoline(&mut self, player: LivePlayer, identity: PlayerIdentity) { + if let Err(error) = self.interrupt_movement_for_impulse(player) { + self.handle_fault(error.context("trampoline movement interruption")); + return; + } + if LivePlayer::resolve(player.slot) != Some(player) || self.players.identity(player.slot) != Some(identity) || !self.trampoline_enabled() { + return; + } + let before = s2sdk::GetClientAbsVelocity(player.slot); + if !finite_velocity(before) { + self.handle_fault(Fault::mechanism(Mechanism::Trampoline, "grounded player velocity is not finite")); + return; + } + let requested = Vec3 { + x: before.x, + y: before.y, + z: funrounds_core::regions::TRAMPOLINE_LAUNCH_Z, + }; + s2sdk::SetClientAbsVelocity(player.slot, &requested); + if LivePlayer::resolve(player.slot) != Some(player) || self.players.identity(player.slot) != Some(identity) { + return; + } + let actual = s2sdk::GetClientAbsVelocity(player.slot); + if !velocity_matches(actual, requested) { + self.handle_fault(Fault::mechanism(Mechanism::Trampoline, "vertical launch velocity write/readback failed")); + return; + } + self.say(player.slot, "trampoline.launched", &[]); + } + + pub(super) fn clear_regions_round(&mut self) { + self.regions.disable_smoke(); + self.regions.trampoline_latches.clear(); + } + + pub(super) fn clear_regions_map(&mut self) { + self.clear_regions_round(); + self.regions.map_name = None; + self.regions.trampoline_region = None; + self.refresh_trampoline_availability(); + } + + pub(super) fn clear_region_player_life(&mut self, slot: i32) { + self.regions.forget_player_latch(slot); + } + + pub(super) fn takeover_trampoline(&mut self, previous_owners: &[i32], identity: PlayerIdentity) { + let mut transferred = None; + for slot in previous_owners { + if let Some(mut latch) = self.regions.trampoline_latches.remove(slot) + && latch.rebind(identity) + { + transferred = Some(latch); + } + } + self.regions.trampoline_latches.remove(&identity.slot); + if let Some(latch) = transferred { + self.regions.trampoline_latches.insert(identity.slot, latch); + } + } +} + +fn map_name_when_ready(prerequisites: Prerequisites, tick_count: impl FnOnce() -> i32, current_map: impl FnOnce() -> String) -> Option { + if !prerequisites.trampoline || tick_count() < 0 { + return None; + } + Some(current_map()) +} + +fn is_smoke_projectile(handle: i32) -> bool { + complete_entity(handle) && s2sdk::GetEntityClassname(handle).as_str() == SMOKE_PROJECTILE +} + +fn complete_entity(handle: i32) -> bool { + if !s2sdk::IsValidEntHandle(handle) { + return false; + } + let pointer = s2sdk::EntHandleToEntPointer(handle); + pointer != 0 && s2sdk::EntPointerToEntHandle(pointer) == handle +} + +fn finite_velocity(velocity: Vec3) -> bool { + velocity.x.is_finite() && velocity.y.is_finite() && velocity.z.is_finite() +} + +fn velocity_matches(actual: Vec3, requested: Vec3) -> bool { + finite_velocity(actual) + && [(actual.x, requested.x), (actual.y, requested.y), (actual.z, requested.z)] + .iter() + .all(|(actual, requested)| (actual - requested).abs() <= 0.1) +} + +fn position(value: Vec3) -> Position { + Position { + x: value.x, + y: value.y, + z: value.z, + } +} diff --git a/crates/funrounds-plugin/src/runtime/respawn.rs b/crates/funrounds-plugin/src/runtime/respawn.rs new file mode 100644 index 0000000..9a2fa66 --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/respawn.rs @@ -0,0 +1,324 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::{EngineAction, Runtime, Str, log}; +use crate::{damage, execute_valid_action, fault}; +use crate::{game::LivePlayer, s2sdk}; +use funrounds_core::{Phase, PlayerTask, PlayerTracker, RoundGeneration, RoundRespawn}; + +#[derive(Default)] +pub(super) struct State { + pub(super) dead: Vec<(PlayerTask, LivePlayer, i32, f32)>, + pub(super) round: Vec<(PlayerTask, LivePlayer, i32, f32)>, + pub(super) finishes: Vec, +} + +impl State { + pub(super) fn queue_finish(&mut self, task: PlayerTask) { + if !self.finishes.contains(&task) { + self.finishes.push(task); + } + } + + pub(super) fn cancel_round_respawn(&mut self, slot: i32) { + self.round.retain(|(task, ..)| task.player.slot != slot); + } + + pub(super) fn cancel_player_respawns(&mut self, slot: i32) { + self.dead.retain(|(task, ..)| task.player.slot != slot); + self.cancel_round_respawn(slot); + } + + pub(super) fn cancel_slots(&mut self, slots: &[i32]) { + self.dead.retain(|(task, ..)| !slots.contains(&task.player.slot)); + self.round.retain(|(task, ..)| !slots.contains(&task.player.slot)); + self.finishes.retain(|task| !slots.contains(&task.player.slot)); + } + + pub(super) fn clear_respawns(&mut self) { + self.dead.clear(); + self.round.clear(); + } + + pub(super) fn clear(&mut self) { + self.clear_respawns(); + self.finishes.clear(); + } +} + +impl Runtime { + pub(super) fn queue_respawn(&mut self, slot: i32, delay: f32) { + if self.controller.phase() == Phase::Idle || LivePlayer::resolve(slot).is_some() { + return; + } + self.connect(slot); + let Some(player) = LivePlayer::resolve_present(slot) else { return }; + let team = s2sdk::GetClientTeam(slot) as i32; + if !matches!(team, 2 | 3) { + return; + } + let Some(task) = self.players.respawn_task(slot, self.controller.generation()) else { + return; + }; + if !self.respawning.dead.iter().any(|(pending, ..)| *pending == task) { + self.respawning.dead.push((task, player, team, s2sdk::GetGameTime() + delay)); + } + } + + pub(super) fn queue_round_respawn(&mut self, slot: i32, tick: i32, delay: f32) { + if self.controller.phase() == Phase::Idle || !self.controller.current_mode().is_some_and(|mode| mode.round_respawn == RoundRespawn::All) { + return; + } + let team = s2sdk::GetClientTeam(slot) as i32; + if !matches!(team, 2 | 3) { + return; + } + self.connect(slot); + let Some(player) = LivePlayer::resolve_present(slot) else { return }; + if LivePlayer::resolve(slot).is_some() + && self + .players + .identity(slot) + .is_none_or(|identity| identity.pawn_handle != player.pawn_handle as u32) + { + // Register an alive player's current life without applying effects; its real spawn follows ForceRespawnClient. + self.spawn(slot, tick, false); + } + let Some(task) = round_respawn_task(&self.players, self.controller.generation(), player) else { + return; + }; + if self.controllers.get(&slot) != Some(&player.controller_handle) { + return; + } + let now = s2sdk::GetGameTime(); + if !now.is_finite() || !delay.is_finite() || delay < 0.0 { + return; + } + if !self.respawning.round.iter().any(|(pending, ..)| *pending == task) { + self.respawning.round.push((task, player, team, now + delay)); + } + } + + pub(super) fn respawn_current(&self, task: PlayerTask, player: LivePlayer, team: i32, now: f32) -> bool { + respawn_window_open(self.controller.phase(), self.team_match.as_ref().map(|game| game.remaining(now))) + && self.players.validates_respawn(task, self.controller.generation()) + && respawn_target_valid( + player, + LivePlayer::resolve_present(player.slot), + team, + s2sdk::GetClientTeam(player.slot) as i32, + LivePlayer::resolve(player.slot).is_some(), + ) + } + + pub(super) fn round_respawn_current(&self, task: PlayerTask, player: LivePlayer, team: i32, now: f32) -> bool { + round_respawn_task_valid(&self.players, task, self.controller.generation(), player) + && respawn_window_open(self.controller.phase(), self.team_match.as_ref().map(|game| game.remaining(now))) + && round_respawn_target_valid( + self.controller.current_mode().is_some_and(|mode| mode.round_respawn == RoundRespawn::All), + self.controller.phase(), + player, + LivePlayer::resolve_present(task.player.slot), + team, + s2sdk::GetClientTeam(task.player.slot) as i32, + ) + } + + pub(super) fn low_health_finish_current(&self, task: PlayerTask, player: LivePlayer) -> bool { + self.controller.phase() != Phase::Idle + && self.controller.current_mode().is_some_and(|mode| mode.self_damage_finish_enabled()) + && self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) + && LivePlayer::resolve(player.slot) == Some(player) + && funrounds_core::low_health_finish(s2sdk::GetClientHealth(player.slot)) + } + + pub(super) fn collect_respawn_actions(&mut self, now: f32, actions: &mut Vec) { + for (task, player, team, due) in std::mem::take(&mut self.respawning.dead) { + if !self.respawn_current(task, player, team, now) { + continue; + } + if now < due { + self.respawning.dead.push((task, player, team, due)); + } else { + log(&format!("respawn slot={} team={team}", task.player.slot)); + actions.push(EngineAction::Respawn(Action::Player(task, player, team))); + } + } + for (task, player, team, due) in std::mem::take(&mut self.respawning.round) { + if !self.round_respawn_current(task, player, team, now) { + continue; + } + if now < due { + self.respawning.round.push((task, player, team, due)); + } else { + log(&format!("round respawn slot={} team={team}", task.player.slot)); + actions.push(EngineAction::Respawn(Action::RoundStart(task, player, team))); + } + } + for task in std::mem::take(&mut self.respawning.finishes) { + if let Some(player) = LivePlayer::resolve(task.player.slot) + && self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) + && self.controller.current_mode().is_some_and(|mode| mode.self_damage_finish_enabled()) + && funrounds_core::low_health_finish(s2sdk::GetClientHealth(player.slot)) + { + actions.push(EngineAction::Respawn(Action::LowHealthFinish( + task, + player, + self.controller.current_mode().is_some_and(|mode| mode.native_self_damage_enabled()), + ))); + } + } + } +} + +fn respawn_target_valid(expected: LivePlayer, current: Option, team: i32, current_team: i32, alive: bool) -> bool { + current == Some(expected) && matches!(team, 2 | 3) && current_team == team && !alive +} + +fn round_respawn_task(players: &PlayerTracker, round: RoundGeneration, player: LivePlayer) -> Option { + if let Some(identity) = players + .identity(player.slot) + .filter(|identity| identity.pawn_handle == player.pawn_handle as u32) + { + return Some(PlayerTask { player: identity, round }); + } + players.respawn_task(player.slot, round) +} + +fn round_respawn_task_valid(players: &PlayerTracker, task: PlayerTask, round: RoundGeneration, player: LivePlayer) -> bool { + task.player.slot == player.slot + && if task.player.pawn_handle == u32::MAX { + players.validates_respawn(task, round) + } else { + players.validates(task, round, player.pawn_handle as u32) + } +} + +fn round_respawn_target_valid( + all_respawn: bool, + phase: Phase, + expected: LivePlayer, + current: Option, + team: i32, + current_team: i32, +) -> bool { + all_respawn && phase != Phase::Idle && current == Some(expected) && matches!(team, 2 | 3) && current_team == team +} + +fn respawn_window_open(phase: Phase, remaining: Option) -> bool { + phase == Phase::Preparing || phase == Phase::Warmup || (phase == Phase::Running && remaining.is_none_or(|seconds| seconds > 0.0)) +} + +pub enum Action { + Player(PlayerTask, LivePlayer, i32), + RoundStart(PlayerTask, LivePlayer, i32), + LowHealthFinish(PlayerTask, LivePlayer, bool), +} + +impl Action { + pub(super) fn involves(&self, slots: &[i32]) -> bool { + match self { + Self::Player(task, ..) | Self::RoundStart(task, ..) | Self::LowHealthFinish(task, ..) => slots.contains(&task.player.slot), + } + } +} + +impl Runtime { + pub(super) fn respawn_action_current(&self, action: &Action) -> bool { + match action { + Action::Player(task, player, team) => self.respawn_current(*task, *player, *team, s2sdk::GetGameTime()), + Action::RoundStart(task, player, team) => self.round_respawn_current(*task, *player, *team, s2sdk::GetGameTime()), + Action::LowHealthFinish(task, player, _) => self.low_health_finish_current(*task, *player), + } + } +} + +pub(crate) fn execute(action: Action) -> Result<(), Box> { + match action { + Action::Player(task, player, team) => execute_valid_action(EngineAction::Respawn(Action::Player(task, player, team)), || { + s2sdk::RespawnClient(task.player.slot); + Ok(()) + })?, + Action::RoundStart(task, player, team) => execute_valid_action(EngineAction::Respawn(Action::RoundStart(task, player, team)), || { + s2sdk::ForceRespawnClient(task.player.slot); + Ok(()) + })?, + Action::LowHealthFinish(task, player, numeric) => { + execute_valid_action(EngineAction::Respawn(Action::LowHealthFinish(task, player, numeric)), || { + let slot = task.player.slot; + let handle = player.pawn_handle; + let zero = plugify::Vec3 { x: 0.0, y: 0.0, z: 0.0 }; + let applied = if numeric { + damage::finish_self_damage(handle)? + } else { + damage::apply_native_damage( + damage::NativeDamageCall { + victim: handle, + inflictor: handle, + attacker: handle, + force: &zero, + position: &zero, + amount: 1.0, + damage_type: damage::DMG_HEADSHOT, + weapon: -1, + skip_plugin_rules: false, + }, + fault::Mechanism::NativeSelfDamage, + "native low-health finish rejected after identity validation", + )? + }; + s2sdk::PrintToServer(&Str::from_str(&format!( + "[FunRounds] low-health finish slot={slot} pawn={handle} damage={applied}" + ))); + Ok(()) + })? + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + #[test] + fn team_respawn_works_during_freeze_without_starting_the_score_timer() { + use funrounds_core::Phase; + assert!(super::respawn_window_open(Phase::Preparing, None)); + assert!(super::respawn_window_open(Phase::Running, Some(3.0))); + assert!(!super::respawn_window_open(Phase::Running, Some(0.0))); + assert!(super::respawn_window_open(Phase::Running, None)); + assert!(!super::respawn_window_open(Phase::Idle, Some(30.0))); + } + + #[test] + fn respawn_rejects_changed_handles_team_and_external_resurrection() { + let player = crate::game::LivePlayer { + slot: 1, + controller_handle: 0x4001, + pawn_handle: 0x4002, + }; + assert!(super::respawn_target_valid(player, Some(player), 2, 2, false)); + assert!(!super::respawn_target_valid(player, Some(player), 2, 3, false)); + assert!(!super::respawn_target_valid(player, Some(player), 2, 2, true)); + assert!(!super::respawn_target_valid(player, None, 2, 2, false)); + assert!(!super::respawn_target_valid( + player, + Some(crate::game::LivePlayer { + pawn_handle: 0x8002, + ..player + }), + 2, + 2, + false + )); + assert!(!super::respawn_target_valid( + player, + Some(crate::game::LivePlayer { + controller_handle: 0x8001, + ..player + }), + 2, + 2, + false + )); + } +} diff --git a/crates/funrounds-plugin/src/runtime/shooting.rs b/crates/funrounds-plugin/src/runtime/shooting.rs new file mode 100644 index 0000000..0459bc3 --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/shooting.rs @@ -0,0 +1,409 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::*; + +#[derive(Clone)] +pub(crate) struct Shot { + task: PlayerTask, + player: LivePlayer, + weapon: FiredWeapon, + weapon_name: String, + tick: i32, + serial: u64, +} + +#[derive(Clone)] +pub(crate) enum Action { + Blast { + shot: Shot, + origin: plugify::Vec3, + config: funrounds_core::ChickenBlastConfig, + }, + Heal { + shot: Shot, + target: PlayerTask, + player: LivePlayer, + amount: i32, + base: i32, + }, +} + +impl Action { + pub(super) fn involves(&self, slots: &[i32]) -> bool { + match self { + Self::Blast { shot, .. } => slots.contains(&shot.player.slot), + Self::Heal { shot, player, .. } => slots.contains(&shot.player.slot) || slots.contains(&player.slot), + } + } +} + +struct Heal { + shot: Shot, + target: PlayerTask, + player: LivePlayer, + damage: f64, + settings: funrounds_core::FriendlyFireHealSettings, +} + +#[derive(Default)] +pub(super) struct State { + serial: u64, + shots: HashMap, + cooldowns: HashMap, + heals: Vec, +} + +pub(super) fn probe(events: &EventCapabilities, caps: &mut funrounds_core::Capabilities, reasons: &mut Vec) { + let mut source = crate::capability::Probe::default(); + source.require(events.weapon_fire && events.combat_events, "events:weapon_fire/lifecycle"); + crate::capability::imports!(source; __s2sdk_GetGameTickCount, __s2sdk_GetGameTime, __s2sdk_GetClientActiveWeapon, + __s2sdk_GetEntityOwner, __s2sdk_GetEntityClassname, __s2sdk_IsValidEntHandle); + source.require( + unsafe { crate::effects::__s2sdk_GetWeaponItemDefinition }.is_some(), + "GetWeaponItemDefinition", + ); + let mut heal = source.clone(); + heal.require(events.damage, "native:player_damage_pre"); + crate::capability::imports!(heal; __s2sdk_GetClientTeam, __s2sdk_FindConVar, __s2sdk_GetConVarValue, + __s2sdk_GetClientHealth, __s2sdk_SetClientHealth); + heal.require(teammates_are_friendly().is_ok(), "convar:mp_teammates_are_enemies (readable boolean)"); + caps.friendly_fire_heal = heal.record("friendly_fire_heal", reasons); + let mut blast = source; + blast.require(events.bullet_impact, "event:bullet_impact"); + blast.require( + crate::KNIFE_DEATH_PRE_HOOKED.load(std::sync::atomic::Ordering::Acquire), + "event:player_death_pre", + ); + blast.require(events.damage && crate::damage::damage_frame_token_available(), "native:damage/frame"); + blast.require(crate::chicken_entities::available(), "env_explosion/feedback"); + crate::capability::imports!(blast; __s2sdk_GetEventFloat, __s2sdk_SetEventString, __s2sdk_AcceptEntityInput); + caps.explosive_bullets = blast.record("explosive_bullets", reasons); + caps.damage_multiplier = events.damage; +} + +impl Runtime { + fn shooting_active(&self) -> bool { + self.classic_enabled() && self.classic_round() && active_combat_phase(self.controller.phase()) + } + + fn shot_current(&self, shot: &Shot) -> bool { + self.shooting_active() && self.combat_task(shot.player) == Some(shot.task) && LivePlayer::resolve(shot.player.slot) == Some(shot.player) + } + + pub(super) fn capture_shot(&mut self, slot: i32, event_weapon: &str) { + self.shooting.shots.remove(&slot); + let Some(player) = LivePlayer::resolve(slot) else { return }; + if !self.shooting_active() + || self + .controller + .current_mode() + .is_none_or(|m| m.explosive_bullets.is_none() && m.friendly_fire_heal.is_none()) + { + return; + } + let Some(task) = self.combat_task(player) else { return }; + let Some(weapon) = fired_weapon(player, event_weapon) else { return }; + let weapon_name = + crate::effects::equipment::give_name_for_original(&weapon.classname, weapon.item_definition).expect("verified firearm definition"); + self.shooting.serial = self.shooting.serial.wrapping_add(1); + self.shooting.shots.insert( + player.slot, + Shot { + task, + player, + weapon, + weapon_name, + tick: s2sdk::GetGameTickCount(), + serial: self.shooting.serial, + }, + ); + } + + pub(super) fn bullet_impact(&mut self, event: usize) { + let slot = s2sdk::GetEventPlayerSlot(event, &Str::from_str("userid")); + let Some(shot) = self.shooting.shots.get(&slot).cloned() else { return }; + // Impacts are synchronous with the matching weapon_fire batch. Never + // carry a recent shot into a later tick or resolve a replacement weapon. + if shot.tick != s2sdk::GetGameTickCount() || !self.shot_current(&shot) { + return; + } + let Some(settings) = self.controller.current_mode().and_then(|m| m.explosive_bullets) else { + return; + }; + let now = f64::from(s2sdk::GetGameTime()); + if self + .shooting + .cooldowns + .get(&slot) + .is_some_and(|(task, ready)| *task == shot.task && now < *ready) + { + return; + } + let origin = plugify::Vec3 { + x: s2sdk::GetEventFloat(event, &Str::from_str("x")), + y: s2sdk::GetEventFloat(event, &Str::from_str("y")), + z: s2sdk::GetEventFloat(event, &Str::from_str("z")), + }; + if ![origin.x, origin.y, origin.z].iter().all(|v| v.is_finite()) { + return; + } + let config = funrounds_core::ChickenBlastConfig { + damage: f32::from(settings.damage.sample(&mut self.rng)), + radius: f32::from(settings.radius.sample(&mut self.rng)), + }; + self.engine_actions.push(EngineAction::Shooting(Action::Blast { + shot: shot.clone(), + origin, + config, + })); + self.shooting + .cooldowns + .insert(slot, (shot.task, now + f64::from(settings.cooldown_seconds))); + } + + pub(crate) fn convert_friendly_shot(&mut self, damage: &crate::damage::Damage, players: &game::DamagePlayers) -> bool { + if !self.shooting_active() + || damage.skip_plugin_rules + || damage.weapon_kind != 1 + || damage.damage_type & (crate::damage::DMG_BULLET | 0x1000000) == 0 + || damage.damage_type & (crate::damage::DMG_BLAST | crate::damage::DMG_BURN | crate::damage::DMG_SLASH) != 0 + || !damage.amount.is_finite() + || damage.amount <= 0.0 + { + return false; + } + let Some(settings) = self.controller.current_mode().and_then(|m| m.friendly_fire_heal) else { + return false; + }; + let (Some(attacker), Some(victim)) = (players.attacker, players.victim) else { + return false; + }; + match friendly(attacker, victim) { + Ok(true) => {} + Ok(false) => return false, + Err(error) => { + self.handle_fault(Fault::mechanism(Mechanism::FriendlyFireHeal, error)); + return false; + } + } + let Some(shot) = self.shooting.shots.get(&attacker.slot).cloned() else { + return false; + }; + if !self.shot_current(&shot) + || shot.tick != s2sdk::GetGameTickCount() + || damage.weapon != shot.weapon.handle + || damage.inflictor != attacker.pawn_handle + { + return false; + } + let Some(target) = self.combat_task(victim) else { return false }; + if let Some(heal) = self + .shooting + .heals + .iter_mut() + .find(|h| h.shot.serial == shot.serial && h.shot.task == shot.task && h.target == target) + { + heal.damage += f64::from(damage.amount); + } else { + self.shooting.heals.push(Heal { + shot, + target, + player: victim, + damage: f64::from(damage.amount), + settings, + }); + } + true + } + + pub(super) fn settle_shooting(&mut self, tick: i32) { + for heal in std::mem::take(&mut self.shooting.heals) { + if tick == heal.shot.tick { + self.shooting.heals.push(heal); + continue; + } + if tick <= heal.shot.tick + || !self.shot_current(&heal.shot) + || self.combat_task(heal.player) != Some(heal.target) + || LivePlayer::resolve(heal.player.slot) != Some(heal.player) + { + continue; + } + let is_friendly = match friendly(heal.shot.player, heal.player) { + Ok(is_friendly) => is_friendly, + Err(error) => { + self.handle_fault(Fault::mechanism(Mechanism::FriendlyFireHeal, error)); + return; + } + }; + if is_friendly + && let Some(effect) = self + .effects + .get(&heal.player.slot) + .filter(|e| e.identity == heal.target.player && !e.has_pending_loadout()) + { + self.engine_actions.push(EngineAction::Shooting(Action::Heal { + amount: heal.settings.healing(heal.damage), + base: i32::from(effect.attributes.health), + shot: heal.shot, + target: heal.target, + player: heal.player, + })); + } + } + self.shooting.shots.retain(|_, shot| shot.tick == tick); + } + + pub(super) fn shooting_action_valid(&self, action: &Action) -> bool { + match action { + Action::Blast { shot, .. } => self.shot_current(shot) && self.controller.current_mode().is_some_and(|m| m.explosive_bullets.is_some()), + Action::Heal { shot, target, player, .. } => { + self.shot_current(shot) + && self.combat_task(*player) == Some(*target) + && LivePlayer::resolve(player.slot) == Some(*player) + && friendly(shot.player, *player).is_ok_and(|friendly| friendly) + && self.controller.current_mode().is_some_and(|m| m.friendly_fire_heal.is_some()) + } + } + } +} + +pub(super) fn teammates_are_friendly() -> Result { + let find = unsafe { std::ptr::addr_of!(s2sdk::__s2sdk_FindConVar).read() }.ok_or("FindConVar import unavailable")?; + let handle = unsafe { find(&Str::from_str("mp_teammates_are_enemies")) }; + if !crate::parameters::valid_handle(handle) { + return Err("mp_teammates_are_enemies is unavailable"); + } + let get = unsafe { std::ptr::addr_of!(s2sdk::__s2sdk_GetConVarValue).read() }.ok_or("GetConVarValue import unavailable")?; + let value = unsafe { get(handle) }.to_string(); + match crate::parameters::parsed_value(&value) { + Some(0.0) => Ok(true), + Some(1.0) => Ok(false), + _ => Err("mp_teammates_are_enemies has an invalid boolean value"), + } +} + +fn friendly(attacker: LivePlayer, victim: LivePlayer) -> Result { + let team = s2sdk::GetClientTeam(attacker.slot) as i32; + if attacker == victim || !matches!(team, 2 | 3) || s2sdk::GetClientTeam(victim.slot) as i32 != team { + return Ok(false); + } + teammates_are_friendly() +} + +pub(crate) fn execute(action: Action) -> Result<(), Fault> { + match action { + Action::Heal { player, amount, base, .. } => super::composed::heal( + player.slot, + base, + funrounds_core::HealingAmount::Fixed(amount), + 1.0, + Mechanism::FriendlyFireHeal, + ) + .map(|_| ()), + Action::Blast { shot, origin, config } => { + let (effect, _) = crate::chicken_entities::prepare_explosion(shot.player.pawn_handle, Some(shot.player.pawn_handle), origin, config) + .map_err(|e| Fault::mechanism(Mechanism::ExplosiveBullets, e))?; + // Each explosion uses its own inflictor; it never enters chicken exceptions. + let pointer = s2sdk::EntHandleToEntPointer(effect); + s2sdk::SetEntSchemaEnt2(pointer, &Str::from_str("CEnvExplosion"), &Str::from_str("m_hInflictor"), effect, false, 0); + if s2sdk::GetEntSchemaEnt2(pointer, &Str::from_str("CEnvExplosion"), &Str::from_str("m_hInflictor"), 0) != effect { + crate::chicken_entities::remove(effect); + return Err(Fault::mechanism(Mechanism::ExplosiveBullets, "explosion inflictor readback failed")); + } + let _entity = BlastEntity(effect); + let _scope = BlastScope::enter(effect, shot.clone()); + let action = EngineAction::Shooting(Action::Blast { + shot: shot.clone(), + origin, + config, + }); + if !crate::engine_action_current(&action) { + return Ok(()); + } + let feedback = crate::suicide::spawn_feedback_at(shot.player.pawn_handle, origin, crate::chicken_entities::EXPLOSION_PARTICLE) + .map_err(|e| Fault::mechanism(Mechanism::ExplosiveBullets, e))?; + let tracked = crate::RUNTIME + .lock() + .unwrap_or_else(|p| p.into_inner()) + .as_mut() + .is_some_and(|runtime| runtime.track_suicide_feedback(feedback, s2sdk::GetGameTime())); + if !tracked { + crate::suicide::remove_feedback(feedback); + return Ok(()); + } + crate::chicken_entities::emit_blast_sound(effect, origin, config.radius); + crate::chicken_entities::detonate(effect, shot.player.pawn_handle); + Ok(()) + } + } +} + +struct BlastContext { + effect: i32, + shot: Shot, + receipt: Option<(i32, u64)>, +} +thread_local! { static BLAST: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } +struct BlastScope(Option); +impl BlastScope { + fn enter(effect: i32, shot: Shot) -> Self { + Self(BLAST.with(|b| b.replace(Some(BlastContext { effect, shot, receipt: None })))) + } +} +impl Drop for BlastScope { + fn drop(&mut self) { + BLAST.with(|b| b.replace(self.0.take())); + } +} + +pub(crate) fn attribute_damage(damage: &mut crate::damage::Damage) { + BLAST.with(|b| { + let mut b = b.borrow_mut(); + let Some(source) = b + .as_mut() + .filter(|b| damage.inflictor == b.effect && damage.attacker == b.shot.player.pawn_handle) + else { + return; + }; + damage.weapon_class = Some(source.shot.weapon_name.clone()); + let weapon = &source.shot.weapon; + damage.weapon = if s2sdk::IsValidEntHandle(weapon.handle) + && s2sdk::GetEntityClassname(weapon.handle).as_str() == weapon.classname + && unsafe { crate::effects::__s2sdk_GetWeaponItemDefinition }.is_some_and(|read| unsafe { read(weapon.handle) } == weapon.item_definition) + { + weapon.handle + } else { + -1 + }; + source.receipt = crate::damage::current_damage_frame_token() + .filter(|t| *t != 0) + .map(|t| (damage.victim, t)); + }); +} + +pub(crate) fn death_weapon(victim: i32, attacker: i32) -> Option { + BLAST.with(|b| { + let b = b.borrow(); + let source = b.as_ref()?; + let token = crate::damage::current_damage_frame_token()?; + (attacker == source.shot.player.slot && source.receipt == Some((s2sdk::EntPointerToEntHandle(s2sdk::GetClientPawn(victim)), token))).then( + || { + source + .shot + .weapon_name + .strip_prefix("weapon_") + .unwrap_or(&source.shot.weapon_name) + .to_owned() + }, + ) + }) +} + +struct BlastEntity(i32); +impl Drop for BlastEntity { + fn drop(&mut self) { + crate::chicken_entities::remove(self.0); + } +} diff --git a/crates/funrounds-plugin/src/runtime/suicide.rs b/crates/funrounds-plugin/src/runtime/suicide.rs new file mode 100644 index 0000000..ea09b84 --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/suicide.rs @@ -0,0 +1,810 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::{ + Effect, EngineAction, Fault, LivePlayer, Mechanism, PendingAction, Phase, PlayerIdentity, PlayerTask, Runtime, Str, active_combat_phase, s2sdk, +}; +use crate::{RUNTIME, callbacks_active, engine_action_current, equipment_fault, execute_valid_action, process_suicide_action}; +use funrounds_core::{PlayerTracker, RoundKey}; +use plugify::Vec3; +use rand::seq::SliceRandom; +use std::collections::HashMap; + +#[derive(Default)] +pub(super) struct DeathExplosions { + pub(super) armed: HashMap, + candidates: Option>, +} + +struct DeathCandidate { + life: PlayerIdentity, + team: i32, + round_respawn: bool, +} + +impl DeathExplosions { + pub(super) fn takeover(&mut self, owners: &[i32], task: PlayerTask, players: &PlayerTracker) -> bool { + if let Some(candidates) = &mut self.candidates { + candidates.retain_mut(|candidate| { + if owners.contains(&candidate.life.slot) + && candidate.life.pawn_handle == task.player.pawn_handle + && players.identity(candidate.life.slot) == Some(candidate.life) + { + candidate.life = task.player; + candidate.round_respawn = false; + return true; + } + candidate.life.slot != task.player.slot + }); + } + let mut moved = false; + for &slot in owners { + if self.armed.remove(&slot).is_some_and(|old| { + old.round == task.round && old.player.pawn_handle == task.player.pawn_handle && players.identity(slot) == Some(old.player) + }) { + moved = true; + } + } + self.armed.remove(&task.player.slot); + if moved { + self.armed.insert(task.player.slot, task); + } + moved + } + + pub(super) fn forget(&mut self, slot: i32) { + self.armed.remove(&slot); + if let Some(candidates) = &mut self.candidates { + candidates.retain(|candidate| candidate.life.slot != slot); + } + } + + pub(super) fn spawned(&mut self, slot: i32, life: Option, players: &PlayerTracker) { + self.armed.remove(&slot); + if let Some(candidates) = &mut self.candidates { + candidates.retain_mut(|candidate| { + if candidate.life.slot != slot { + return true; + } + if let Some(life) = life + && candidate.round_respawn + && players.validates_connection(candidate.life) + { + candidate.life = life; + candidate.round_respawn = false; + return true; + } + false + }); + } + } + + pub(super) fn bind_candidate(&mut self, pending: PlayerIdentity, bound: PlayerIdentity) { + if let Some(candidates) = &mut self.candidates + && let Some(candidate) = candidates.iter_mut().find(|candidate| candidate.life == pending) + { + candidate.life = bound; + } + } +} + +#[derive(Clone, Copy, Debug)] +pub struct DeathBlast { + victim: PlayerIdentity, + pub player: LivePlayer, + pub origin: Vec3, + round_key: RoundKey, +} + +fn round_end_finish_valid( + enabled: bool, + phase: Phase, + task: PlayerTask, + player: LivePlayer, + current_identity: Option, + live_player: Option, +) -> bool { + enabled && phase == Phase::Idle && current_identity == Some(task.player) && live_player == Some(player) +} + +fn round_end_finish_due(tick: i32, queued_tick: i32) -> bool { + tick > queued_tick +} + +fn lethal_suicide_finish_amount(anchor: f32, health: i32) -> Option { + if !anchor.is_finite() || anchor <= 0.0 || health <= 0 { + return None; + } + let current_health_amount = health as f32 * 10.0; + current_health_amount.is_finite().then_some(anchor.max(current_health_amount)) +} + +pub(crate) fn remove_native_c4(player: LivePlayer, handles: &[i32]) -> Result<(), Fault> { + if LivePlayer::resolve(player.slot) != Some(player) { + return Err(Fault::cancelled("player identity changed before native C4 cleanup")); + } + for handle in handles.iter().copied() { + if !s2sdk::IsValidEntHandle(handle) || s2sdk::GetEntityClassname(handle).as_str() != "weapon_c4" { + continue; + } + if s2sdk::GetEntityOwner(handle) != player.pawn_handle { + return Err(Fault::cancelled("native C4 ownership changed before cleanup")); + } + s2sdk::RemoveWeapon(player.slot, handle); + if LivePlayer::resolve(player.slot) != Some(player) { + return Err(Fault::cancelled("player identity changed during native C4 cleanup")); + } + if s2sdk::GetClientWeapons(player.slot).iter().any(|current| *current == handle) { + return Err(Fault::mechanism(Mechanism::NoC4, "engine retained the native C4 after removal")); + } + if s2sdk::IsValidEntHandle(handle) { + if s2sdk::GetEntityClassname(handle).as_str() != "weapon_c4" + || !matches!(s2sdk::GetEntityOwner(handle), owner if owner == -1 || owner == player.pawn_handle) + { + return Err(Fault::cancelled("native C4 ownership changed during cleanup")); + } + s2sdk::RemoveEntity(handle); + if !crate::game::engine_removal_acknowledged(handle) { + return Err(Fault::mechanism(Mechanism::C4Assignment, "native C4 entity survived cleanup")); + } + } + } + Ok(()) +} + +impl Runtime { + pub fn defer_pending_loadout_c4_grant(&mut self, task: PlayerTask, player: LivePlayer) -> bool { + let pending = self.effects.get(&player.slot).is_some_and(|effect| { + effect.identity == task.player + && effect.round == task.round + && effect.has_pending_loadout() + && effect + .pending_loadout_confirmation() + .is_some_and(|pending| pending.team == s2sdk::GetClientTeam(player.slot) as i32) + }); + if !pending + || !self.classic_round() + || !self.players.validates(task, self.controller.generation(), player.pawn_handle as u32) + || LivePlayer::resolve(player.slot) != Some(player) + || self.controllers.get(&player.slot) != Some(&player.controller_handle) + { + return false; + } + if !self + .engine_actions + .iter() + .any(|queued| matches!(queued, EngineAction::Suicide(Action::GrantC4(queued_task, queued_player)) if *queued_task == task && *queued_player == player)) + { + self.engine_actions.push(EngineAction::Suicide(Action::GrantC4(task, player))); + } + true + } + + pub(super) fn queue_c4_assignment(&mut self) { + if !active_combat_phase(self.controller.phase()) + || self.suicides.c4_assigned + || self.equipment_in_flight > 0 + || self.pending.iter().any(|(_, _, action)| *action == PendingAction::Loadout) + || !self.settling_loadouts.is_empty() + || self.effects.values().any(Effect::has_pending_loadout) + { + return; + } + let Some(count) = self.controller.current_mode().and_then(|mode| mode.c4_count) else { + return; + }; + let count = usize::from(count); + let phase = self.controller.phase(); + let mut players = Vec::new(); + let mut candidates = Vec::new(); + for slot in 0..s2sdk::GetMaxClients() { + let Some(player) = LivePlayer::resolve(slot) else { continue }; + let Some(task) = self.combat_task(player) else { continue }; + let native = s2sdk::GetClientWeapons(slot) + .iter() + .copied() + .filter(|handle| crate::suicide::real_c4(player, *handle) && !self.bombs.excludes_suicide_c4(player, *handle)) + .collect(); + players.push((task, player, native)); + if s2sdk::GetClientTeam(slot) as i32 == 2 { + candidates.push((task, player)); + } + } + if phase == Phase::Warmup && count > 0 && candidates.is_empty() { + return; + } + self.suicides.c4_assigned = true; + self.engine_actions.extend( + players + .into_iter() + .map(|(task, player, native)| EngineAction::Suicide(Action::RemoveC4(task, player, native))), + ); + candidates.shuffle(&mut self.rng); + self.engine_actions.extend( + candidates + .into_iter() + .take(count) + .map(|(task, player)| EngineAction::Suicide(Action::GrantC4(task, player))), + ); + } + + pub fn track_suicide_feedback(&mut self, handle: i32, now: f32) -> bool { + self.suicides.feedback.track(handle, now + crate::suicide::FEEDBACK_LIFETIME) + } + + pub fn take_suicide_feedback_cleanup(&mut self) -> Vec { + self.suicides.feedback.take_removals() + } + + pub(super) fn suicide_enabled(&self) -> bool { + self.classic_enabled() && active_combat_phase(self.controller.phase()) && self.controller.current_mode().is_some_and(|mode| mode.suicide) + } + + pub(super) fn c4_purchase_enabled(&self, start: bool) -> bool { + self.classic_enabled() + && active_combat_phase(self.controller.phase()) + && self + .controller + .current_mode() + .is_some_and(|mode| if start { mode.suicide } else { mode.c4_buy }) + } + + pub(super) fn qualifying_c4(&self, player: LivePlayer) -> Option { + s2sdk::GetClientWeapons(player.slot) + .iter() + .copied() + .find(|weapon| crate::suicide::real_c4(player, *weapon) && !self.bombs.excludes_suicide_c4(player, *weapon)) + } + + pub(super) fn request_suicide(&mut self, slot: i32, start: bool) -> Result { + if !self.c4_purchase_enabled(start) { + return Err(self.text(slot, "c4.unavailable", &[])); + } + let player = LivePlayer::resolve(slot).ok_or(self.text(slot, "player.alive_required", &[]))?; + let task = self.combat_task(player).ok_or(self.text(slot, "player.life_pending", &[]))?; + if self.suicides.buying.get(&slot) == Some(&task) { + return Err(self.text(slot, "c4.pending", &[])); + } + if self.suicides.active(player) { + return Err(self.text(slot, "suicide.started", &[])); + } + if let Some(c4) = self.qualifying_c4(player) { + if self.suicide_enabled() { + self.suicides.qualify(task, player, c4); + } + if start { + self.suicides.begin(slot, s2sdk::GetGameTickCount(), s2sdk::GetGameTime())?; + } + return Ok(if self.suicide_enabled() { + self.text(slot, "c4.owned_suicide", &[]) + } else { + self.text(slot, "c4.owned", &[]) + }); + } + if self.suicides.pending.iter().any(|action| action.task() == task) { + return Err(self.text(slot, "c4.pending", &[])); + } + if s2sdk::GetClientTeam(slot) as i32 != 2 { + return Err(self.text(slot, "c4.t_required", &[])); + } + let price = self.controller.config().map_or(10_000, |config| config.prices.c4_cash); + self.suicides.buying.insert(slot, task); + self.suicides + .pending + .push(crate::suicide::Action::Purchase { task, player, start, price }); + Ok(self.text(slot, "c4.request", &[("price", &price.to_string())])) + } + + pub(super) fn update_suicides(&mut self, tick: i32) -> Vec { + if !self.suicide_enabled() { + let mut due = Vec::new(); + for action in std::mem::take(&mut self.suicides.pending) { + match action { + crate::suicide::Action::Purchase { .. } => due.push(EngineAction::Suicide(Action::SelfDestruct(action))), + crate::suicide::Action::Finish { + after_round_end: true, + tick: queued, + .. + } if self.action_valid(&EngineAction::Suicide(Action::SelfDestruct(action))) => { + if round_end_finish_due(tick, queued) { + due.push(EngineAction::Suicide(Action::SelfDestruct(action))); + } else { + self.suicides.pending.push(action); + } + } + _ => {} + } + } + return due; + } + let now = s2sdk::GetGameTime(); + let mut failure = None; + for slot in 0..s2sdk::GetMaxClients() { + let Some(player) = LivePlayer::resolve(slot) else { continue }; + let Some(task) = self.combat_task(player) else { continue }; + if let Some(entry) = self.suicides.entries.get(&slot) + && entry.task != task + { + // A new life may reuse the same pawn; its fresh properties are not ours. + self.suicides.entries.remove(&slot); + } + if let Some(c4) = self.qualifying_c4(player) { + self.suicides.qualify(task, player, c4); + } + let Some(entry) = self.suicides.entries.get_mut(&slot) else { continue }; + if let Some(sequence) = entry.sequence.as_mut() { + if sequence.take_due(tick, now) { + self.suicides.pending.push(crate::suicide::Action::Blast { task, player }); + } + } else if !crate::suicide::real_c4(player, entry.c4) { + self.suicides.entries.remove(&slot); + } else { + let look = crate::funrounds_native::GetLookAtWeaponButtonState(player.pawn_handle); + let edge = look == 1 && !entry.look_down; + entry.look_down = look == 1; + if edge + && s2sdk::GetClientActiveWeapon(slot) == entry.c4 + && let Err(error) = self.suicides.begin(slot, tick, now) + { + failure = Some(error); + break; + } + } + } + if let Some(error) = failure { + self.handle_fault(Fault::mechanism(Mechanism::Suicide, error)); + } + self.suicides + .take_due_actions(tick) + .map(|action| EngineAction::Suicide(Action::SelfDestruct(action))) + .collect() + } + + pub fn blocks_suicide_pickup(&self, pawn: i32, controller: i32) -> bool { + self.suicide_enabled() + && self.suicides.entries.values().any(|entry| { + entry.player.pawn_handle == pawn + && entry.player.controller_handle == controller + && entry.sequence.is_some() + && self.combat_task(entry.player) == Some(entry.task) + }) + } + + pub fn existing_suicide_c4(&self, player: LivePlayer) -> Option { + self.qualifying_c4(player) + } + + pub fn suicide_buyer_current(&self, action: crate::suicide::Action) -> bool { + self.on_game_thread() + && self.players.validates_connection(action.task().player) + && self.controllers.get(&action.player().slot) == Some(&action.player().controller_handle) + } + + pub fn finish_suicide_purchase(&mut self, action: crate::suicide::Action, result: Result) { + let crate::suicide::Action::Purchase { task, player, start, .. } = action else { + return; + }; + if self.suicides.buying.get(&player.slot) == Some(&task) { + self.suicides.buying.remove(&player.slot); + } + if !self.action_valid(&EngineAction::Suicide(Action::SelfDestruct(action))) { + return; + } + let message = match result { + Ok(c4) => { + if self.suicide_enabled() { + self.suicides.qualify(task, player, c4); + } + if start && let Err(error) = self.suicides.begin(player.slot, s2sdk::GetGameTickCount(), s2sdk::GetGameTime()) { + self.handle_fault(Fault::mechanism(Mechanism::Suicide, error)); + } + crate::i18n::Message::new(if start { + "c4.purchased_start" + } else if self.suicide_enabled() { + "c4.purchased_inspect" + } else { + "c4.purchased" + }) + } + Err(error) => self.purchase_error(player.slot, error), + }; + crate::i18n::send_chat(player.slot, &self.message(player.slot, message)); + } + + pub(super) fn start_death_explosives(&mut self) { + if !self.controller.current_mode().is_some_and(|mode| mode.death_explosion.enabled()) { + return; + } + // Fix the roster at freeze end, even if a round-start respawn delays the draw. + self.death_explosives.candidates = Some( + (0..s2sdk::GetMaxClients()) + .filter(|&slot| s2sdk::IsClientInGame(slot)) + .filter_map(|slot| { + let team = s2sdk::GetClientTeam(slot) as i32; + if !matches!(team, 2 | 3) { + return None; + } + let round_respawn = self.respawning.round.iter().any(|(task, ..)| task.player.slot == slot); + let life = if round_respawn { + self.players.connection_identity(slot) + } else { + self.players.identity(slot).or_else(|| self.players.pending_identity(slot)) + }?; + Some(DeathCandidate { life, team, round_respawn }) + }) + .collect(), + ); + self.arm_death_explosives(); + } + + pub(super) fn arm_death_explosives(&mut self) { + // With zero freeze time the existing round-start respawns may still be + // queued. Sample the new lives after those actions have run. + if !self.classic_enabled() || !self.respawning.round.is_empty() { + return; + } + let Some(mut candidates) = self.death_explosives.candidates.take() else { + return; + }; + let Some(quota) = self + .controller + .current_mode() + .map(|mode| mode.death_explosion) + .filter(|quota| quota.enabled()) + else { + return; + }; + let mut awaiting_pawn = false; + let mut eligible = Vec::new(); + let round = self.controller.generation(); + for candidate in &mut candidates { + let slot = candidate.life.slot; + if (if candidate.team == 2 { quota.t } else { quota.ct }) == 0 + || !s2sdk::IsClientInGame(slot) + || s2sdk::GetClientTeam(slot) as i32 != candidate.team + { + continue; + } + let player = LivePlayer::resolve(slot).filter(|player| { + self.controllers.get(&slot) == Some(&player.controller_handle) && player.pawn_controller() == Some(player.controller_handle) + }); + if self.players.pending_identity(slot) == Some(candidate.life) { + let Some(player) = player else { + awaiting_pawn = true; + continue; + }; + let pending = PlayerTask { + player: candidate.life, + round, + }; + let Some(bound) = self.bind_pending_spawn(pending, player) else { + continue; + }; + candidate.life = bound; + // The loadout and other queued work still belong to this same life. + for (task, ..) in &mut self.pending { + if *task == pending { + task.player = bound; + } + } + } + if let Some(task) = player.and_then(|player| self.combat_task(player)) + && task.player == candidate.life + && !eligible.contains(&(candidate.team, task)) + { + eligible.push((candidate.team, task)); + } + } + if awaiting_pawn { + self.death_explosives.candidates = Some(candidates); + return; + } + for (team, count) in [(2, quota.t), (3, quota.ct)] { + let mut eligible = eligible + .iter() + .filter_map(|(candidate_team, task)| (*candidate_team == team).then_some(*task)) + .collect::>(); + eligible.shuffle(&mut self.rng); + for task in eligible.into_iter().take(usize::from(count)) { + self.death_explosives.armed.insert(task.player.slot, task); + self.say(task.player.slot, "death_explosion.armed", &[]); + if self.diagnostics() { + super::log(&format!( + "death_explosion=armed slot={} pawn={} team={team}", + task.player.slot, task.player.pawn_handle + )); + } + } + } + } + + pub(super) fn track_player_death(&mut self, slot: i32) { + let nominated = if self.death_explosives.armed.is_empty() || self.controller.phase() != Phase::Running { + None + } else { + LivePlayer::resolve_present(slot).filter(|player| self.claim_death_nomination(*player)) + }; + self.death_explosives.forget(slot); + self.players.death(slot); + if let (Some(player), Some(round_key), Some(victim)) = (nominated, self.round, self.players.connection_identity(slot)) { + self.engine_actions.push(EngineAction::Suicide(Action::DeathBlast(DeathBlast { + victim, + player, + origin: s2sdk::GetEntityAbsOrigin(player.pawn_handle), + round_key, + }))); + } + } + + fn claim_death_nomination(&mut self, player: LivePlayer) -> bool { + let Some(controller) = player.pawn_controller().filter(|controller| *controller == player.controller_handle) else { + return false; + }; + if self + .combat_task(player) + .is_some_and(|task| self.death_explosives.armed.get(&player.slot) == Some(&task)) + { + return true; + } + // The native death event may precede the next game-thread takeover update. + // Claim from the old owner without adopting a dead pawn or moving live effects. + let Some(takeover) = self + .pending_takeovers + .iter() + .find(|pending| pending.slot == player.slot && pending.controller_handle == controller && self.takeover_current(**pending)) + else { + return false; + }; + let Some(owner) = self.death_explosives.armed.iter().find_map(|(&slot, old)| { + (old.round == takeover.round && old.player.pawn_handle == player.pawn_handle as u32 && self.players.identity(slot) == Some(old.player)) + .then_some(slot) + }) else { + return false; + }; + self.death_explosives.armed.remove(&owner); + true + } + + fn death_blast_current(&self, blast: DeathBlast) -> bool { + self.classic_enabled() + && self.round == Some(blast.round_key) + && matches!(self.controller.phase(), Phase::Running | Phase::Idle) + && self.controllers.get(&blast.player.slot) == Some(&blast.player.controller_handle) + && self.players.connection_identity(blast.player.slot) == Some(blast.victim) + && LivePlayer::resolve_present(blast.player.slot) == Some(blast.player) + } + + pub fn prepare_suicide_finish_after_blast(&mut self, action: crate::suicide::Action) { + let source = action.player(); + let tick = s2sdk::GetGameTickCount(); + let self_amount = s2sdk::GetClientHealth(source.slot) as f32 * 10.0; + self.suicides.pending.push(crate::suicide::Action::Finish { + task: action.task(), + player: source, + amount: self_amount, + tick, + after_round_end: false, + }); + } + + pub fn prepare_blast_targets(&mut self, source: LivePlayer, origin: Vec3) -> Result, Fault> { + let tick = s2sdk::GetGameTickCount(); + let mut targets = Vec::new(); + for slot in 0..s2sdk::GetMaxClients() { + let Some(player) = LivePlayer::resolve(slot).filter(|player| *player != source) else { + continue; + }; + let Some(task) = self.combat_task(player) else { continue }; + let position = s2sdk::GetEntityAbsOrigin(player.pawn_handle); + let distance = ((origin.x - position.x).powi(2) + (origin.y - position.y).powi(2) + (origin.z - position.z).powi(2)).sqrt(); + let amount = funrounds_core::suicide_blast_damage(s2sdk::GetClientHealth(slot), distance); + if amount <= 0.0 { + continue; + } + if let Some(sequence) = self.suicides.entries.get_mut(&slot).and_then(|entry| entry.sequence.as_mut()) { + sequence.chain_next_tick(tick); + continue; + } + targets.push((task, player, amount)); + } + if targets.is_empty() { + return Ok(targets); + } + for name in [ + "mp_friendlyfire", + "ff_damage_reduction_bullets", + "ff_damage_reduction_grenade", + "ff_damage_reduction_other", + ] { + self.suicides.ff.set_number(name, 1.0)?; + } + Ok(targets) + } + + pub fn prepare_suicide_finish(&self, action: crate::suicide::Action) -> Option { + let crate::suicide::Action::Finish { player, amount, .. } = action else { + return None; + }; + if !self.action_valid(&EngineAction::Suicide(Action::SelfDestruct(action))) { + return None; + } + lethal_suicide_finish_amount(amount, s2sdk::GetClientHealth(player.slot)) + } + + pub fn blast_target_valid(&self, task: PlayerTask, player: LivePlayer) -> bool { + active_combat_phase(self.controller.phase()) && self.combat_task(player) == Some(task) && LivePlayer::resolve(player.slot) == Some(player) + } + + pub(super) fn suicide_hurt(&mut self, event: usize, victim: i32, attacker: i32) { + if !crate::damage::internal_suicide_hurt(victim, attacker) { + return; + } + let Some(player) = LivePlayer::resolve_present(victim) else { return }; + let Some(task) = self.combat_task(player) else { return }; + if let Some((_, life)) = self.combat.lives.get_mut(&victim).filter(|(expected, _)| *expected == task) { + life.lose_native_armor(s2sdk::GetEventInt(event, &Str::from_str("dmg_armor"))); + } + } + + pub fn finish_suicide_blast(&mut self) { + if let Err(error) = self.suicides.ff.restore() { + self.handle_fault(Fault::global(error)); + } + } + + pub(super) fn self_destruct_action_current(&self, action: &crate::suicide::Action) -> bool { + match action { + crate::suicide::Action::Purchase { start, .. } => { + self.c4_purchase_enabled(*start) + && self + .players + .validates(action.task(), self.controller.generation(), action.player().pawn_handle as u32) + && LivePlayer::resolve(action.player().slot) == Some(action.player()) + } + crate::suicide::Action::Finish { + after_round_end: true, + task, + player, + .. + } => round_end_finish_valid( + self.classic_enabled(), + self.controller.phase(), + *task, + *player, + self.players.identity(player.slot), + LivePlayer::resolve(player.slot), + ), + _ => { + self.suicide_enabled() + && self + .players + .validates(action.task(), self.controller.generation(), action.player().pawn_handle as u32) + && LivePlayer::resolve(action.player().slot) == Some(action.player()) + } + } + } +} + +pub enum Action { + GrantC4(PlayerTask, LivePlayer), + RemoveC4(PlayerTask, LivePlayer, Vec), + SelfDestruct(crate::suicide::Action), + DeathBlast(DeathBlast), + RemoveFeedback(i32), +} + +impl Action { + pub(super) fn retain_for_takeover( + &mut self, + slots: &[i32], + suicide_source: Option, + takeover_task: PlayerTask, + takeover_player: LivePlayer, + ) -> bool { + match self { + Self::GrantC4(task, _) | Self::RemoveC4(task, ..) => !slots.contains(&task.player.slot), + Self::DeathBlast(blast) => !slots.contains(&blast.player.slot), + Self::RemoveFeedback(_) => true, + Self::SelfDestruct(suicide) => { + let old = suicide.task(); + if !slots.contains(&old.player.slot) { + return true; + } + if matches!(suicide, crate::suicide::Action::Purchase { .. }) + || suicide_source != Some(old.player.slot) + || old.round != takeover_task.round + || old.player.pawn_handle != takeover_task.player.pawn_handle + { + return false; + } + match suicide { + crate::suicide::Action::Start { task: queued, owned } => { + *queued = takeover_task; + owned.player = takeover_player; + true + } + crate::suicide::Action::Blast { + task: queued, + player: queued_player, + } + | crate::suicide::Action::Finish { + task: queued, + player: queued_player, + .. + } => { + *queued = takeover_task; + *queued_player = takeover_player; + true + } + crate::suicide::Action::Purchase { .. } => false, + } + } + } + } +} + +impl Runtime { + pub(super) fn suicide_action_current(&self, action: &Action) -> bool { + match action { + Action::GrantC4(task, player) => { + self.classic_round() + && !self + .effects + .get(&player.slot) + .is_some_and(|effect| effect.identity == task.player && effect.round == task.round && effect.has_pending_loadout()) + && self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) + && LivePlayer::resolve(player.slot) == Some(*player) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + } + Action::RemoveC4(task, player, _) => { + self.classic_round() + && self.players.validates(*task, self.controller.generation(), player.pawn_handle as u32) + && LivePlayer::resolve(player.slot) == Some(*player) + && self.controllers.get(&player.slot) == Some(&player.controller_handle) + } + Action::SelfDestruct(action) => self.self_destruct_action_current(action), + Action::DeathBlast(blast) => self.death_blast_current(*blast), + Action::RemoveFeedback(_) => true, + } + } +} + +pub(crate) fn execute(action: Action) -> Result<(), Box> { + match action { + Action::GrantC4(task, player) => { + let deferred = if callbacks_active() { + let mut guard = RUNTIME.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + guard + .as_mut() + .filter(|runtime| runtime.on_game_thread()) + .is_some_and(|runtime| runtime.defer_pending_loadout_c4_grant(task, player)) + } else { + false + }; + if deferred { + return Ok(()); + } + let action = EngineAction::Suicide(Action::GrantC4(task, player)); + let result = crate::suicide::grant_c4(player, || engine_action_current(&action)); + if let Err(error) = result + && engine_action_current(&action) + { + equipment_fault(error); + } + } + Action::RemoveC4(task, player, handles) => { + execute_valid_action(EngineAction::Suicide(Action::RemoveC4(task, player, handles.clone())), || { + remove_native_c4(player, &handles) + })?; + } + Action::SelfDestruct(action) => process_suicide_action(action), + Action::DeathBlast(blast) => crate::process_player_blast( + blast.player, + blast.origin, + EngineAction::Suicide(Action::DeathBlast(blast)), + Mechanism::DeathExplosion, + ), + Action::RemoveFeedback(handle) => crate::suicide::remove_feedback(handle), + } + Ok(()) +} diff --git a/crates/funrounds-plugin/src/runtime/teamkill.rs b/crates/funrounds-plugin/src/runtime/teamkill.rs new file mode 100644 index 0000000..2da130a --- /dev/null +++ b/crates/funrounds-plugin/src/runtime/teamkill.rs @@ -0,0 +1,246 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +use super::*; +use funrounds_core::TeamkillCounter; +use plugify::Vec3; + +#[derive(Default)] +pub(super) struct State { + entries: HashMap, + executing: Option, +} +struct Entry { + task: PlayerTask, + team: i32, + counter: TeamkillCounter, + pending: bool, +} +#[derive(Clone, Copy)] +pub(crate) struct Action { + pub player: LivePlayer, + pub origin: Vec3, + task: PlayerTask, + team: i32, +} +impl Action { + pub(super) fn involves(self, slots: &[i32]) -> bool { + slots.contains(&self.player.slot) + } +} + +pub(super) fn probe(events: &EventCapabilities, caps: &mut funrounds_core::Capabilities, reasons: &mut Vec) { + let mut probe = crate::suicide::resource_probe(); + probe.require(events.combat_events && events.damage, "events:combat/damage/lifecycle"); + probe.require(crate::damage::damage_frame_token_available(), "native:damage_frame"); + probe.require(crate::damage::reflection_available(), "native:TakeEntityDamageWithWeapon"); + crate::capability::imports!(probe; __s2sdk_GetClientTeam, __s2sdk_GetClientHealth, __s2sdk_GetClientArmor, + __s2sdk_GetEntityAbsOrigin, __s2sdk_FindConVar, __s2sdk_GetConVarValue, __s2sdk_CreateEntityByName, + __s2sdk_DispatchSpawn2, __s2sdk_AcceptEntityInput, __s2sdk_TeleportEntity, __s2sdk_RemoveEntity); + probe.require( + shooting::teammates_are_friendly().is_ok(), + "convar:mp_teammates_are_enemies (readable boolean)", + ); + caps.teamkill_punishment = probe.record("teamkill_punishment", reasons); +} + +impl Runtime { + pub(super) fn update_teamkills(&mut self) { + if !self.classic_round() || !active_combat_phase(self.controller.phase()) { + self.teamkills.entries.clear(); + return; + } + let entries = std::mem::take(&mut self.teamkills.entries); + self.teamkills.entries = entries + .into_iter() + .filter(|(slot, entry)| { + self.players + .validates(entry.task, self.controller.generation(), entry.task.player.pawn_handle) + && LivePlayer::resolve(*slot).is_some_and(|p| p.pawn_handle as u32 == entry.task.player.pawn_handle) + && s2sdk::GetClientTeam(*slot) as i32 == entry.team + }) + .collect(); + } + + pub(super) fn is_teamkill_punishment(&self, slot: i32) -> bool { + self.teamkills + .executing + .is_some_and(|task| task.player.slot == slot && self.players.identity(slot) == Some(task.player)) + } + + pub(super) fn count_teamkill(&mut self, victim: i32, attacker: i32) { + if !self.classic_round() || !active_combat_phase(self.controller.phase()) || victim == attacker { + return; + } + let Some(limit) = self.controller.current_mode().and_then(|mode| mode.teamkill_limit) else { + return; + }; + let Some(player) = LivePlayer::resolve(attacker) else { return }; + if player.pawn_controller().is_none() { + return; + } + let Some(task) = self.combat_task(player) else { return }; + let team = s2sdk::GetClientTeam(attacker) as i32; + if !matches!(team, 2 | 3) || s2sdk::GetClientTeam(victim) as i32 != team { + return; + } + match shooting::teammates_are_friendly() { + Ok(true) => {} + Ok(false) => return, + Err(error) => { + self.handle_fault(Fault::mechanism(Mechanism::TeamkillPunishment, error)); + return; + } + } + let Some(victim_identity) = self.players.identity(victim) else { return }; + let entry = self.teamkills.entries.entry(attacker).or_insert_with(|| Entry { + task, + team, + counter: TeamkillCounter::default(), + pending: false, + }); + if entry.task != task || entry.team != team { + *entry = Entry { + task, + team, + counter: TeamkillCounter::default(), + pending: false, + }; + } + if !entry.pending && entry.counter.record(victim_identity, limit) { + entry.pending = true; + self.engine_actions.push(EngineAction::Teamkill(Action { + player, + task, + team, + origin: s2sdk::GetEntityAbsOrigin(player.pawn_handle), + })); + } + } + + pub(crate) fn teamkill_action_valid(&self, action: Action) -> bool { + self.teamkill_action_valid_inner(action).is_ok_and(|valid| valid) + } + + fn teamkill_action_valid_inner(&self, action: Action) -> Result { + if !self.classic_round() || !active_combat_phase(self.controller.phase()) { + return Ok(false); + } + if !self.controller.current_mode().is_some_and(|mode| mode.teamkill_limit.is_some()) + || self.combat_task(action.player) != Some(action.task) + || LivePlayer::resolve(action.player.slot) != Some(action.player) + || action.player.pawn_controller().is_none() + || s2sdk::GetClientTeam(action.player.slot) as i32 != action.team + || !self + .teamkills + .entries + .get(&action.player.slot) + .is_some_and(|entry| entry.task == action.task && entry.pending) + { + return Ok(false); + } + shooting::teammates_are_friendly() + } + + pub(crate) fn take_teamkill_actions(&mut self) -> Vec { + let mut actions = Vec::new(); + self.engine_actions.retain(|action| { + if let EngineAction::Teamkill(action) = action { + actions.push(*action); + false + } else { + true + } + }); + actions + } + + pub(crate) fn begin_teamkill(&mut self, action: Action) -> bool { + match self.teamkill_action_valid_inner(action) { + Ok(true) => {} + Ok(false) => return false, + Err(error) => { + self.handle_fault(Fault::mechanism(Mechanism::TeamkillPunishment, error)); + return false; + } + } + self.teamkills.executing = Some(action.task); + true + } + pub(crate) fn finish_teamkill(&mut self, action: Action) { + if self.teamkills.executing == Some(action.task) { + self.teamkills.executing = None; + } + if let Some(entry) = self.teamkills.entries.get_mut(&action.player.slot).filter(|e| e.task == action.task) { + entry.pending = false; + } + } + pub(super) fn forget_teamkill(&mut self, slot: i32) { + self.teamkills.entries.remove(&slot); + } + + pub(super) fn takeover_teamkills(&mut self, owners: &[i32], task: PlayerTask, player: LivePlayer) { + let mut transferred = None; + for slot in owners.iter().copied().chain(std::iter::once(player.slot)) { + if let Some(entry) = self.teamkills.entries.remove(&slot) + && entry.task.round == task.round + && entry.task.player.pawn_handle == task.player.pawn_handle + && entry.team == s2sdk::GetClientTeam(player.slot) as i32 + { + transferred = Some(Entry { + task, + pending: false, + ..entry + }); + } + } + if let Some(entry) = transferred { + self.teamkills.entries.insert(player.slot, entry); + } + } +} + +pub(crate) fn punish(player: LivePlayer) -> Result<(), Fault> { + let health = s2sdk::GetClientHealth(player.slot).max(1) as f32; + let armor = s2sdk::GetClientArmor(player.slot).max(0) as f32; + let zero = Vec3 { x: 0.0, y: 0.0, z: 0.0 }; + crate::damage::with_internal_damage_context( + crate::damage::InternalDamageContext { + victim: player.pawn_handle, + attacker: player.pawn_handle, + inflictor: player.pawn_handle, + weapon: -1, + victim_slot: player.slot, + attacker_slot: player.slot, + headshot: false, + check_protection: false, + suppress_lifesteal: true, + random_heal: None, + death_weapon: None, + }, + || { + crate::damage::apply_native_damage( + crate::damage::NativeDamageCall { + victim: player.pawn_handle, + attacker: player.pawn_handle, + inflictor: player.pawn_handle, + force: &zero, + position: &zero, + amount: (health + armor + 1.0) * 10.0, + damage_type: crate::damage::DMG_HEADSHOT, + weapon: -1, + skip_plugin_rules: true, + }, + Mechanism::TeamkillPunishment, + "teamkill punishment damage rejected", + ) + }, + )?; + if LivePlayer::resolve(player.slot) == Some(player) { + return Err(Fault::mechanism( + Mechanism::TeamkillPunishment, + "teamkill offender survived native punishment", + )); + } + Ok(()) +} diff --git a/crates/funrounds-plugin/src/s2sdk/clients.rs b/crates/funrounds-plugin/src/s2sdk/clients.rs index 04fb579..29a741e 100644 --- a/crates/funrounds-plugin/src/s2sdk/clients.rs +++ b/crates/funrounds-plugin/src/s2sdk/clients.rs @@ -584,3 +584,52 @@ pub type _GetClientLanguageCode = unsafe extern "C" fn(i32) -> Str; #[allow(dead_code, non_upper_case_globals)] #[unsafe(no_mangle)] pub static mut __s2sdk_GetClientLanguageCode: Option<_GetClientLanguageCode> = None; + +/// Retrieves the number of kills for a client. +/// +/// # Arguments +/// * `playerSlot` - (int32): The index of the player's slot. +/// +/// # Returns - (int32): +/// The number of kills the client has, or 0 if the player slot is invalid. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn GetClientKills(playerSlot: i32) -> i32 { + unsafe { __s2sdk_GetClientKills.expect("GetClientKills function was not found")(playerSlot) } +} +pub type _GetClientKills = unsafe extern "C" fn(i32) -> i32; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_GetClientKills: Option<_GetClientKills> = None; + +/// Retrieves the number of deaths for a client. +/// +/// # Arguments +/// * `playerSlot` - (int32): The index of the player's slot. +/// +/// # Returns - (int32): +/// The number of deaths the client has, or 0 if the player slot is invalid. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn GetClientDeaths(playerSlot: i32) -> i32 { + unsafe { __s2sdk_GetClientDeaths.expect("GetClientDeaths function was not found")(playerSlot) } +} +pub type _GetClientDeaths = unsafe extern "C" fn(i32) -> i32; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_GetClientDeaths: Option<_GetClientDeaths> = None; + +/// Changes the player's team. +/// +/// # Arguments +/// * `playerSlot` - (int32): The index of the player's slot. +/// * `team` - (int32): The team index to change the client to. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn ChangeClientTeam(playerSlot: i32, team: CSTeam) { + unsafe { __s2sdk_ChangeClientTeam.expect("ChangeClientTeam function was not found")(playerSlot, team) } +} +pub type _ChangeClientTeam = unsafe extern "C" fn(i32, CSTeam); +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_ChangeClientTeam: Option<_ChangeClientTeam> = None; diff --git a/crates/funrounds-plugin/src/s2sdk/commands.rs b/crates/funrounds-plugin/src/s2sdk/commands.rs index 342c3de..8edc475 100644 --- a/crates/funrounds-plugin/src/s2sdk/commands.rs +++ b/crates/funrounds-plugin/src/s2sdk/commands.rs @@ -122,3 +122,18 @@ pub type _AddCommandListener = unsafe extern "C" fn(&Str, ConCommandCallback, Ho #[allow(dead_code, non_upper_case_globals)] #[unsafe(no_mangle)] pub static mut __s2sdk_AddCommandListener: Option<_AddCommandListener> = None; + +/// Executes a client command on the server without network communication. +/// +/// # Arguments +/// * `playerSlot` - (int32): The index of the client. +/// * `command` - (string): The command to be executed by the client. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn FakeClientCommand(playerSlot: i32, command: &Str) { + unsafe { __s2sdk_FakeClientCommand.expect("FakeClientCommand function was not found")(playerSlot, command) } +} +pub type _FakeClientCommand = unsafe extern "C" fn(i32, &Str); +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_FakeClientCommand: Option<_FakeClientCommand> = None; diff --git a/crates/funrounds-plugin/src/s2sdk/cvars.rs b/crates/funrounds-plugin/src/s2sdk/cvars.rs index 6429304..dc04e4d 100644 --- a/crates/funrounds-plugin/src/s2sdk/cvars.rs +++ b/crates/funrounds-plugin/src/s2sdk/cvars.rs @@ -78,3 +78,38 @@ pub type _SetConVarValue = unsafe extern "C" fn(u64, &Str, bool, bool); #[allow(dead_code, non_upper_case_globals)] #[unsafe(no_mangle)] pub static mut __s2sdk_SetConVarValue: Option<_SetConVarValue> = None; + +/// Creates a new boolean console variable. +/// +/// # Arguments +/// * `name` - (string): The name of the console variable. +/// * `defaultValue` - (bool): The default value for the console variable. +/// * `description` - (string): A brief description of the console variable. +/// * `flags` - (int64): Flags that define the behavior of the console variable. +/// * `hasMin` - (bool): Indicates if a minimum value is provided. +/// * `min` - (bool): The minimum value if hasMin is true. +/// * `hasMax` - (bool): Indicates if a maximum value is provided. +/// * `max` - (bool): The maximum value if hasMax is true. +/// +/// # Returns - (uint64): +/// A handle to the created console variable data. +#[track_caller] +#[allow(dead_code, non_snake_case, clippy::too_many_arguments)] +pub fn CreateConVarBool( + name: &Str, + defaultValue: bool, + description: &Str, + flags: ConVarFlag, + hasMin: bool, + min: bool, + hasMax: bool, + max: bool, +) -> u64 { + unsafe { + __s2sdk_CreateConVarBool.expect("CreateConVarBool function was not found")(name, defaultValue, description, flags, hasMin, min, hasMax, max) + } +} +pub type _CreateConVarBool = unsafe extern "C" fn(&Str, bool, &Str, ConVarFlag, bool, bool, bool, bool) -> u64; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_CreateConVarBool: Option<_CreateConVarBool> = None; diff --git a/crates/funrounds-plugin/src/s2sdk/delegates.rs b/crates/funrounds-plugin/src/s2sdk/delegates.rs index fe2796c..332bb72 100644 --- a/crates/funrounds-plugin/src/s2sdk/delegates.rs +++ b/crates/funrounds-plugin/src/s2sdk/delegates.rs @@ -27,3 +27,7 @@ pub type OnBuildGameSessionManifestCallback = unsafe extern "C" fn(); /// Called on every map end. #[allow(unused)] pub type OnMapEndCallback = unsafe extern "C" fn(); + +/// Called when an entity is spawned. +#[allow(unused)] +pub type OnEntitySpawnedCallback = unsafe extern "C" fn(i32); diff --git a/crates/funrounds-plugin/src/s2sdk/engine.rs b/crates/funrounds-plugin/src/s2sdk/engine.rs index 01f8217..b329a07 100644 --- a/crates/funrounds-plugin/src/s2sdk/engine.rs +++ b/crates/funrounds-plugin/src/s2sdk/engine.rs @@ -118,3 +118,31 @@ pub type _QueryInterface = unsafe extern "C" fn(&Str, &Str) -> usize; #[allow(dead_code, non_upper_case_globals)] #[unsafe(no_mangle)] pub static mut __s2sdk_QueryInterface: Option<_QueryInterface> = None; + +/// Returns the current map name. +/// +/// # Returns - (string): +/// A reference to a string where the current map name will be stored. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn GetCurrentMap() -> Str { + unsafe { __s2sdk_GetCurrentMap.expect("GetCurrentMap function was not found")() } +} +pub type _GetCurrentMap = unsafe extern "C" fn() -> Str; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_GetCurrentMap: Option<_GetCurrentMap> = None; + +/// Returns the path of the game's directory. +/// +/// # Returns - (string): +/// A reference to a string where the game directory path will be stored. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn GetGameDirectory() -> Str { + unsafe { __s2sdk_GetGameDirectory.expect("GetGameDirectory function was not found")() } +} +pub type _GetGameDirectory = unsafe extern "C" fn() -> Str; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_GetGameDirectory: Option<_GetGameDirectory> = None; diff --git a/crates/funrounds-plugin/src/s2sdk/events.rs b/crates/funrounds-plugin/src/s2sdk/events.rs index c40e345..037e2d6 100644 --- a/crates/funrounds-plugin/src/s2sdk/events.rs +++ b/crates/funrounds-plugin/src/s2sdk/events.rs @@ -137,3 +137,21 @@ pub type _SetEventString = unsafe extern "C" fn(usize, &Str, &Str); #[allow(dead_code, non_upper_case_globals)] #[unsafe(no_mangle)] pub static mut __s2sdk_SetEventString: Option<_SetEventString> = None; + +/// Retrieves the float value of a game event's key. +/// +/// # Arguments +/// * `event` - (ptr64): A pointer to the IGameEvent object containing event data. +/// * `key` - (string): The key for which to retrieve the float value. +/// +/// # Returns - (float): +/// The float value associated with the key. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn GetEventFloat(event: usize, key: &Str) -> f32 { + unsafe { __s2sdk_GetEventFloat.expect("GetEventFloat function was not found")(event, key) } +} +pub type _GetEventFloat = unsafe extern "C" fn(usize, &Str) -> f32; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_GetEventFloat: Option<_GetEventFloat> = None; diff --git a/crates/funrounds-plugin/src/s2sdk/listeners.rs b/crates/funrounds-plugin/src/s2sdk/listeners.rs index 33cf0a9..ebf6913 100644 --- a/crates/funrounds-plugin/src/s2sdk/listeners.rs +++ b/crates/funrounds-plugin/src/s2sdk/listeners.rs @@ -68,3 +68,31 @@ pub type _OnMapEnd_Unregister = unsafe extern "C" fn(OnMapEndCallback); #[allow(dead_code, non_upper_case_globals)] #[unsafe(no_mangle)] pub static mut __s2sdk_OnMapEnd_Unregister: Option<_OnMapEnd_Unregister> = None; + +/// Register callback to event. +/// +/// # Arguments +/// * `callback` - (function): Function callback. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn OnEntitySpawned_Register(callback: OnEntitySpawnedCallback) { + unsafe { __s2sdk_OnEntitySpawned_Register.expect("OnEntitySpawned_Register function was not found")(callback) } +} +pub type _OnEntitySpawned_Register = unsafe extern "C" fn(OnEntitySpawnedCallback); +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_OnEntitySpawned_Register: Option<_OnEntitySpawned_Register> = None; + +/// Unregister callback to event. +/// +/// # Arguments +/// * `callback` - (function): Function callback. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn OnEntitySpawned_Unregister(callback: OnEntitySpawnedCallback) { + unsafe { __s2sdk_OnEntitySpawned_Unregister.expect("OnEntitySpawned_Unregister function was not found")(callback) } +} +pub type _OnEntitySpawned_Unregister = unsafe extern "C" fn(OnEntitySpawnedCallback); +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_OnEntitySpawned_Unregister: Option<_OnEntitySpawned_Unregister> = None; diff --git a/crates/funrounds-plugin/src/s2sdk/mod.rs b/crates/funrounds-plugin/src/s2sdk/mod.rs index 6f1ed44..f6cca48 100644 --- a/crates/funrounds-plugin/src/s2sdk/mod.rs +++ b/crates/funrounds-plugin/src/s2sdk/mod.rs @@ -18,6 +18,7 @@ pub mod listeners; pub mod models; pub mod protobuf; pub mod schema; +pub mod trace; pub mod transmit; #[allow(unused_imports)] @@ -53,4 +54,6 @@ pub use protobuf::*; #[allow(unused_imports)] pub use schema::*; #[allow(unused_imports)] +pub use trace::*; +#[allow(unused_imports)] pub use transmit::*; diff --git a/crates/funrounds-plugin/src/s2sdk/schema.rs b/crates/funrounds-plugin/src/s2sdk/schema.rs index 85e1534..6354762 100644 --- a/crates/funrounds-plugin/src/s2sdk/schema.rs +++ b/crates/funrounds-plugin/src/s2sdk/schema.rs @@ -212,3 +212,44 @@ pub type _NetworkStateChanged = unsafe extern "C" fn(i32, &Str, &Str); #[allow(dead_code, non_upper_case_globals)] #[unsafe(no_mangle)] pub static mut __s2sdk_NetworkStateChanged: Option<_NetworkStateChanged> = None; + +/// Retrieves a color value from an entity's schema. +/// +/// # Arguments +/// * `entityHandle` - (int32): The handle of the entity from which the value is to be retrieved. +/// * `className` - (string): The name of the class. +/// * `memberName` - (string): The name of the schema member. +/// * `element` - (int32): Element # (starting from 0) if schema is an array. +/// +/// # Returns - (vec4): +/// A color value at the given schema offset. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn GetEntSchemaColor(entityHandle: i32, className: &Str, memberName: &Str, element: i32) -> Vec4 { + unsafe { __s2sdk_GetEntSchemaColor.expect("GetEntSchemaColor function was not found")(entityHandle, className, memberName, element) } +} +pub type _GetEntSchemaColor = unsafe extern "C" fn(i32, &Str, &Str, i32) -> Vec4; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_GetEntSchemaColor: Option<_GetEntSchemaColor> = None; + +/// Sets a color value in an entity's schema. +/// +/// # Arguments +/// * `entityHandle` - (int32): The handle of the entity from which the value is to be retrieved. +/// * `className` - (string): The name of the class. +/// * `memberName` - (string): The name of the schema member. +/// * `value` - (vec4): The color value to set. +/// * `changeState` - (bool): If true, change will be sent over the network. +/// * `element` - (int32): Element # (starting from 0) if schema is an array. +#[track_caller] +#[allow(dead_code, non_snake_case)] +pub fn SetEntSchemaColor(entityHandle: i32, className: &Str, memberName: &Str, value: &Vec4, changeState: bool, element: i32) { + unsafe { + __s2sdk_SetEntSchemaColor.expect("SetEntSchemaColor function was not found")(entityHandle, className, memberName, value, changeState, element) + } +} +pub type _SetEntSchemaColor = unsafe extern "C" fn(i32, &Str, &Str, &Vec4, bool, i32); +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_SetEntSchemaColor: Option<_SetEntSchemaColor> = None; diff --git a/crates/funrounds-plugin/src/s2sdk/trace.rs b/crates/funrounds-plugin/src/s2sdk/trace.rs new file mode 100644 index 0000000..9ea83d9 --- /dev/null +++ b/crates/funrounds-plugin/src/s2sdk/trace.rs @@ -0,0 +1,60 @@ +// Generated from s2sdk.pplugin (group: trace) +// SPDX-License-Identifier: AGPL-3.0-or-later + +#[allow(unused_imports)] +use super::aliases::*; +#[allow(unused_imports)] +use super::delegates::*; +#[allow(unused_imports)] +use super::enums::*; +#[allow(unused_imports)] +use plugify::{Arr, Mat4x4, Str, Var, Vec2, Vec3, Vec4, scope}; +#[allow(unused_imports)] +use std::sync::RwLock; + +/// Performs a line trace between two points. +/// +/// # Arguments +/// * `startPos` - (vec3): Trace start position +/// * `endPos` - (vec3): Trace end position +/// * `mask` - (int32): Trace mask +/// * `ignoreHandle` - (int32): Entity handle to ignore during trace +/// * `outPos` - (vec3&): Output: position of impact +/// * `outFraction` - (double&): Output: fraction of trace completed +/// * `outHit` - (bool&): Output: whether a hit occurred +/// * `outEntHit` - (int32&): Output: handle of entity hit +/// * `outStartSolid` - (bool&): Output: whether trace started inside solid +/// +/// # Returns - (bool): +/// True if trace hit something, false otherwise +#[track_caller] +#[allow(dead_code, non_snake_case, clippy::too_many_arguments)] +pub fn TraceLine( + startPos: &Vec3, + endPos: &Vec3, + mask: i32, + ignoreHandle: i32, + outPos: &mut Vec3, + outFraction: &mut f64, + outHit: &mut bool, + outEntHit: &mut i32, + outStartSolid: &mut bool, +) -> bool { + unsafe { + __s2sdk_TraceLine.expect("TraceLine function was not found")( + startPos, + endPos, + mask, + ignoreHandle, + outPos, + outFraction, + outHit, + outEntHit, + outStartSolid, + ) + } +} +pub type _TraceLine = unsafe extern "C" fn(&Vec3, &Vec3, i32, i32, &mut Vec3, &mut f64, &mut bool, &mut i32, &mut bool) -> bool; +#[allow(dead_code, non_upper_case_globals)] +#[unsafe(no_mangle)] +pub static mut __s2sdk_TraceLine: Option<_TraceLine> = None; diff --git a/crates/funrounds-plugin/src/suicide.rs b/crates/funrounds-plugin/src/suicide.rs index 728cfe7..99e5562 100644 --- a/crates/funrounds-plugin/src/suicide.rs +++ b/crates/funrounds-plugin/src/suicide.rs @@ -21,7 +21,7 @@ pub fn c4_probe(purchase: bool) -> Probe { let mut probe = Probe::default(); imports!(probe; __s2sdk_GetClientWeapons, __s2sdk_GetClientActiveWeapon, __s2sdk_GetEntityOwner, __s2sdk_IsValidEntHandle, - __s2sdk_GetEntityClassname, __s2sdk_IsValidEntHandle, __s2sdk_GiveNamedItem, + __s2sdk_GetEntityClassname, __s2sdk_GiveNamedItem, __s2sdk_RemoveWeapon, __s2sdk_RemoveEntity, __s2sdk_SelectWeapon, ); if purchase { @@ -40,19 +40,14 @@ pub(crate) fn resource_probe() -> Probe { } pub fn probe(hook_ready: bool) -> Probe { - let mut probe = Probe::default(); - probe.include(resource_probe()); + let mut probe = blast_probe(); probe.require(hook_ready, "hook:CanAcquire"); imports!(probe; __s2sdk_GetClientWeapons, __s2sdk_GetClientActiveWeapon, __s2sdk_GetEntityOwner, __s2sdk_GiveNamedItem, __s2sdk_RemoveWeapon, __s2sdk_RemoveEntity, __s2sdk_SelectWeapon, __s2sdk_DropWeapon, __s2sdk_GetClientSpeed, __s2sdk_SetClientSpeed, __s2sdk_GetEntSchema2, __s2sdk_SetEntSchema2, __s2sdk_GetEntSchemaFloat2, - __s2sdk_SetEntSchemaFloat2, __s2sdk_GetEntityAbsOrigin, - ); - imports!(probe; - __s2sdk_CreateEntityByName, __s2sdk_DispatchSpawn2, __s2sdk_AcceptEntityInput, __s2sdk_TeleportEntity, - __s2sdk_EmitSoundToClient, __s2sdk_GetMaxClients, __s2sdk_IsClientInGame, __s2sdk_GetClientTeam, + __s2sdk_SetEntSchemaFloat2, ); for (class, field) in [ ("CCSPlayerController", "m_pInGameMoneyServices"), @@ -62,6 +57,16 @@ pub fn probe(hook_ready: bool) -> Probe { ] { probe.schema(class, field); } + probe +} + +pub(crate) fn blast_probe() -> Probe { + let mut probe = resource_probe(); + imports!(probe; + __s2sdk_GetEntityAbsOrigin, __s2sdk_RemoveEntity, + __s2sdk_CreateEntityByName, __s2sdk_DispatchSpawn2, __s2sdk_AcceptEntityInput, __s2sdk_TeleportEntity, + __s2sdk_EmitSoundToClient, __s2sdk_GetMaxClients, __s2sdk_IsClientInGame, __s2sdk_GetClientTeam, + ); for name in [ "mp_friendlyfire", "ff_damage_reduction_bullets", @@ -292,9 +297,33 @@ pub struct Suicides { pub pending: Vec, pub buying: HashMap, pub ff: crate::parameters::Parameters, + pub(crate) feedback: FeedbackEntities, + pub(crate) c4_assigned: bool, } impl Suicides { + pub(crate) fn discard_life(&mut self, slot: i32) { + self.entries.remove(&slot); + self.buying.remove(&slot); + self.pending.retain(|action| action.task().player.slot != slot); + } + + pub(crate) fn discard_map_state(&mut self) { + self.entries.clear(); + self.pending.clear(); + self.buying.clear(); + self.feedback.discard_map_state(); + self.c4_assigned = false; + } + + pub(crate) fn cleanup_complete(&self, round_transition: bool, now: f32) -> bool { + self.entries.is_empty() + && self.pending.is_empty() + && self.buying.is_empty() + && self.ff.is_restored() + && self.feedback.cleanup_complete(round_transition, now) + } + pub fn qualify(&mut self, task: PlayerTask, player: LivePlayer, c4: i32) { if self .entries @@ -508,6 +537,13 @@ impl Suicides { self.cleanup_entries() } + pub(crate) fn take_due_actions(&mut self, tick: i32) -> impl Iterator + '_ { + self.pending.extract_if( + .., + move |action| !matches!(action, Action::Finish { tick: queued, .. } if tick <= *queued), + ) + } + pub fn cancel_round_end_finishes(&mut self) { self.pending .retain(|action| !matches!(action, Action::Finish { after_round_end: true, .. })); @@ -566,37 +602,36 @@ pub fn hit(source: LivePlayer, target: LivePlayer, amount: f32, force: bool) -> result.map(|_| ()).map_err(|error| error.to_string()) } -pub fn spawn_feedback(player: LivePlayer) -> Result { - if !s2sdk::IsValidEntHandle(player.pawn_handle) { - return Err("自爆反馈玩家实体失效".into()); +pub(crate) fn spawn_feedback_at(source: i32, origin: Vec3, particle: &str) -> Result { + if !s2sdk::IsValidEntHandle(source) { + return Err("爆炸反馈来源实体失效".into()); } let effect = s2sdk::CreateEntityByName(&Str::from_str("info_particle_system")); if !s2sdk::IsValidEntHandle(effect) { - return Err("自爆粒子反馈创建失败".into()); + return Err("爆炸粒子反馈创建失败".into()); } - let origin = s2sdk::GetEntityAbsOrigin(player.pawn_handle); let result = (|| { let keys = plugify::Arr::from(vec!["effect_name".to_owned()]); - let values = plugify::Arr::from(vec![plugify::Any::from(EXPLOSION_PARTICLE)]); + let values = plugify::Arr::from(vec![plugify::Any::from(particle)]); s2sdk::DispatchSpawn2(effect, &keys, &values); if !s2sdk::IsValidEntHandle(effect) { - return Err("自爆粒子实体在生成时消失".into()); + return Err("爆炸粒子实体在生成时消失".into()); } s2sdk::TeleportEntity(effect, &origin, &ZERO, &ZERO); if !s2sdk::IsValidEntHandle(effect) || !same_position(s2sdk::GetEntityAbsOrigin(effect), origin) { - return Err("自爆粒子爆点定位失败".into()); + return Err("爆炸粒子爆点定位失败".into()); } s2sdk::AcceptEntityInput( effect, &Str::from_str("Start"), - player.pawn_handle, - player.pawn_handle, + source, + source, &plugify::Var::default(), s2sdk::FieldType::Auto, 0, ); if !s2sdk::IsValidEntHandle(effect) { - return Err("自爆粒子实体在启动时消失".into()); + return Err("爆炸粒子实体在启动时消失".into()); } Ok(effect) })(); @@ -607,7 +642,9 @@ pub fn spawn_feedback(player: LivePlayer) -> Result { } pub fn precache_feedback_resource() { - s2sdk::Precache(&Str::from_str(EXPLOSION_PARTICLE)); + for particle in [EXPLOSION_PARTICLE, crate::chicken_entities::EXPLOSION_PARTICLE] { + s2sdk::Precache(&Str::from_str(particle)); + } } pub fn play_start_sound(player: LivePlayer) -> Result<(), String> { @@ -649,6 +686,7 @@ fn same_position(left: Vec3, right: Vec3) -> bool { #[derive(Default)] pub struct FeedbackEntities { active: HashMap, + removals: Vec, } impl FeedbackEntities { @@ -660,28 +698,35 @@ impl FeedbackEntities { true } - pub fn take_expired(&mut self, now: f32) -> Vec { + pub fn expire(&mut self, now: f32) { if !now.is_finite() { - return Vec::new(); + return; } - let mut expired = Vec::new(); self.active.retain(|handle, expires_at| { if *expires_at <= now { - expired.push(*handle); + self.removals.push(*handle); false } else { true } }); - expired } - pub fn take_all(&mut self) -> Vec { - self.active.drain().map(|(handle, _)| handle).collect() + pub fn clear(&mut self) { + self.removals.extend(self.active.drain().map(|(handle, _)| handle)); + } + + pub fn take_removals(&mut self) -> Vec { + std::mem::take(&mut self.removals) } pub fn discard_map_state(&mut self) { self.active.clear(); + self.removals.clear(); + } + + pub fn cleanup_complete(&self, round_transition: bool, now: f32) -> bool { + self.removals.is_empty() && (self.is_empty() || (round_transition && self.has_only_unexpired(now))) } pub fn is_empty(&self) -> bool { diff --git a/native/funrounds-native/CMakeLists.txt b/native/funrounds-native/CMakeLists.txt index 9ab6015..a78c56c 100644 --- a/native/funrounds-native/CMakeLists.txt +++ b/native/funrounds-native/CMakeLists.txt @@ -97,12 +97,14 @@ set(FUNROUNDS_S2SDK_INCLUDE_DIRS add_library(funrounds-native SHARED src/plugin.cpp src/engine.cpp + src/bighead.cpp src/burn.cpp src/damage.cpp src/touch.cpp src/suicide.cpp src/collision.cpp src/ground_reverse.cpp + src/airmove.cpp src/third_person.cpp src/ghost_visibility.cpp src/ghost_radar.cpp @@ -110,6 +112,8 @@ add_library(funrounds-native SHARED src/ghost_radar_state.cpp src/interactions.cpp src/random_spawn.cpp + src/standard_grenade.cpp + src/movement_trace.cpp "${FUNROUNDS_PLUGIFY_INCLUDE_DIR}/polyhook/polyhook.cpp" "${FUNROUNDS_S2SDK_GENERATED_INCLUDE_DIR}/s2sdk/s2sdk.cpp" ) @@ -134,7 +138,7 @@ target_include_directories(funrounds-native PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/exports" ) target_include_directories(funrounds-native SYSTEM PRIVATE ${FUNROUNDS_S2SDK_INCLUDE_DIRS}) -target_link_libraries(funrounds-native PRIVATE sourcesdk "${FUNROUNDS_PROTOBUF_TARGET}") +target_link_libraries(funrounds-native PRIVATE sourcesdk "${FUNROUNDS_PROTOBUF_TARGET}" ${CMAKE_DL_LIBS}) target_compile_definitions(funrounds-native PRIVATE PLUGIFY_IS_DEBUG=$ PLUGIFY_IS_RELEASE=$ diff --git a/native/funrounds-native/funrounds-native.pplugin b/native/funrounds-native/funrounds-native.pplugin index de90937..f057ead 100644 --- a/native/funrounds-native/funrounds-native.pplugin +++ b/native/funrounds-native/funrounds-native.pplugin @@ -1,8 +1,8 @@ { "$schema": "https://raw.githubusercontent.com/untrustedmodders/plugify/refs/tags/v3.1.0/schemas/plugin.schema.json", - "version": "0.3.0-alpha.test.2", + "version": "0.4.0-alpha.test.3", "name": "funrounds_native", - "description": "Native Source 2 damage, pickup, touch, collision, chicken-use, suicide-input, ground-reverse, bot-visibility, ghost-radar and passive sound-message hooks for FunRounds", + "description": "Native Source 2 damage, pickup, touch, collision, chicken-use, suicide-input, Big Head scaling, ground-reverse, bot-visibility, ghost-radar and passive sound-message hooks for FunRounds", "author": "Mai Ooizumi", "website": "https://github.com/Mai-Ooizumi", "license": "AGPL-3.0-or-later", @@ -12,7 +12,7 @@ "dependencies": [ { "name": "s2sdk", - "constraints": "=3.0.6" + "constraints": "=3.3.1" }, { "name": "polyhook", @@ -20,6 +20,34 @@ } ], "methods": [ + { + "name": "HasPlayerMovementHullSupport", + "funcName": "HasPlayerMovementHullSupport", + "group": "WallHang", + "description": "On the game thread, checks the exact paired CS2 26445667 movement-trace ABI, server image identity, and physics-query receiver. Unsupported or mismatched server builds return false.", + "paramTypes": [], + "retType": { "type": "bool" } + }, + { + "name": "TracePlayerMovementHull", + "funcName": "TracePlayerMovementHull", + "group": "WallHang", + "description": "On the game thread, traces the supplied real local hull using the pinned player-movement filter while ignoring one exact full player-pawn handle. Returns true only after finite trace outputs are validated; a successful miss returns true with outHit=false and outEntityHandle=-1. Failure returns false with deterministic miss outputs. It never passes engine pointers across this provider boundary.", + "paramTypes": [ + { "name": "pawnHandle", "type": "int32", "ref": false }, + { "name": "start", "type": "vec3", "ref": false }, + { "name": "end", "type": "vec3", "ref": false }, + { "name": "hullMins", "type": "vec3", "ref": false }, + { "name": "hullMaxs", "type": "vec3", "ref": false }, + { "name": "outPosition", "type": "vec3", "ref": true }, + { "name": "outFraction", "type": "float", "ref": true }, + { "name": "outHit", "type": "bool", "ref": true }, + { "name": "outEntityHandle", "type": "int32", "ref": true }, + { "name": "outStartSolid", "type": "bool", "ref": true }, + { "name": "outNormal", "type": "vec3", "ref": true } + ], + "retType": { "type": "bool" } + }, { "name": "HasPlayerRandomSpawnPointSupport", "funcName": "HasPlayerRandomSpawnPointSupport", @@ -50,66 +78,56 @@ } }, { - "name": "HasThirdPersonEyeSupport", - "funcName": "HasThirdPersonEyeSupport", - "group": "ThirdPerson", + "name": "HasThirdPersonEyeSupport", "funcName": "HasThirdPersonEyeSupport", "group": "ThirdPerson", "description": "On the game thread, checks the optional pawn eye camera-branch Hook ABI and schema. Does not change any view.", - "paramTypes": [], - "retType": { - "type": "bool" - } + "paramTypes": [], "retType": { "type": "bool" } }, { - "name": "RegisterThirdPersonEyeTarget", - "funcName": "RegisterThirdPersonEyeTarget", - "group": "ThirdPerson", + "name": "RegisterThirdPersonEyeTarget", "funcName": "RegisterThirdPersonEyeTarget", "group": "ThirdPerson", "description": "On the game thread, registers one exact pawn/camera pair before assigning its view. Only a live own-camera path uses the original pawn eye branch.", - "paramTypes": [ - { - "name": "pawn", - "type": "int32", - "ref": false - }, - { - "name": "camera", - "type": "int32", - "ref": false - } - ], - "retType": { - "type": "bool" - } + "paramTypes": [{ "name": "pawn", "type": "int32", "ref": false }, { "name": "camera", "type": "int32", "ref": false }], + "retType": { "type": "bool" } }, { - "name": "UnregisterThirdPersonEyeTarget", - "funcName": "UnregisterThirdPersonEyeTarget", - "group": "ThirdPerson", + "name": "UnregisterThirdPersonEyeTarget", "funcName": "UnregisterThirdPersonEyeTarget", "group": "ThirdPerson", "description": "On the game thread, removes an exact pair only after its pawn view no longer references the owned camera. A failed detach remains retryable.", + "paramTypes": [{ "name": "pawn", "type": "int32", "ref": false }, { "name": "camera", "type": "int32", "ref": false }], + "retType": { "type": "bool" } + }, + { + "name": "ResetThirdPersonEyeTargets", "funcName": "ResetThirdPersonEyeTargets", "group": "ThirdPerson", + "description": "Map transition only: drops all old-map target identities and detaches the eye Hook without resolving or modifying reused entity handles.", + "paramTypes": [], "retType": { "type": "bool" } + }, + { + "name": "HasGrenadeDetonateSupport", + "funcName": "HasGrenadeDetonateSupport", + "group": "Grenades", + "description": "On the game thread, checks kind 1 smoke, 2 Molotov, or 3 incendiary independently and installs an owned pre-hook that claims natural Detonate entry for complete projectile handles.", + "paramTypes": [{ "name": "kind", "type": "int32" }], + "retType": { "type": "bool" } + }, + { + "name": "GetGrenadeDetonationState", + "funcName": "GetGrenadeDetonationState", + "group": "Grenades", + "description": "On the game thread, checks kind 1 smoke, 2 Molotov, or 3 incendiary independently. Returns 1 when any Detonate entry claimed this exact full handle or its non-sentinel projectile has disappeared, 0 for a valid matching projectile not yet claimed, and -1 when support, kind, identity, or state resolution fails. It never changes projectile physics or calls Detonate.", "paramTypes": [ - { - "name": "pawn", - "type": "int32", - "ref": false - }, - { - "name": "camera", - "type": "int32", - "ref": false - } + { "name": "projectileHandle", "type": "int32" }, + { "name": "kind", "type": "int32" } ], - "retType": { - "type": "bool" - } + "retType": { "type": "int32" } }, { - "name": "ResetThirdPersonEyeTargets", - "funcName": "ResetThirdPersonEyeTargets", - "group": "ThirdPerson", - "description": "Map transition only: drops all old-map target identities and detaches the eye Hook without resolving or modifying reused entity handles.", - "paramTypes": [], - "retType": { - "type": "bool" - } + "name": "DetonateGrenade", + "funcName": "DetonateGrenade", + "group": "Grenades", + "description": "On the game thread, requests native Detonate for an exact full handle after caller-side provenance, managed-projectile exclusion, and proximity checks. Returns 1 when submitted, 0 when natural or earlier Detonate was already claimed or the non-sentinel handle normally disappeared, and -1 on support, identity, or submission failure.", + "paramTypes": [ + { "name": "projectileHandle", "type": "int32" }, + { "name": "kind", "type": "int32" } + ], + "retType": { "type": "int32" } }, { "name": "TryIgnitePlayer", @@ -117,16 +135,8 @@ "group": "Afterburn", "description": "On the game thread, attempts native mode-14 ignition for one exact current live player pawn without replacing a valid attached effect. Returns the new attached entityflame full handle for exact caller-owned lifecycle cleanup, or -1 when validation or readback fails.", "paramTypes": [ - { - "name": "pawnHandle", - "type": "int32", - "ref": false - }, - { - "name": "duration", - "type": "float", - "ref": false - } + { "name": "pawnHandle", "type": "int32", "ref": false }, + { "name": "duration", "type": "float", "ref": false } ], "retType": { "type": "int32", @@ -139,9 +149,7 @@ "group": "Suicide", "description": "Reports whether the optional CanAcquire hook and inspect-button schema are available.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "GetLookAtWeaponButtonState", @@ -149,15 +157,9 @@ "group": "Suicide", "description": "Returns live IN_LOOK_AT_WEAPON state for an exact pawn handle, or -1 when unavailable.", "paramTypes": [ - { - "name": "pawnHandle", - "type": "int32", - "ref": false - } + { "name": "pawnHandle", "type": "int32", "ref": false } ], - "retType": { - "type": "int32" - } + "retType": { "type": "int32" } }, { "name": "HookPlayerCanAcquire", @@ -165,16 +167,9 @@ "group": "Suicide", "description": "Hooks pickup acquisition decisions so only active suicide bombers are denied weapon pickups.", "paramTypes": [ - { - "name": "callback", - "type": "function", - "prototype": "PlayerCanAcquireCallback", - "ref": false - } + { "name": "callback", "type": "function", "prototype": "PlayerCanAcquireCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "UnhookPlayerCanAcquire", @@ -182,16 +177,9 @@ "group": "Suicide", "description": "Removes the optional CanAcquire detour and callback.", "paramTypes": [ - { - "name": "callback", - "type": "function", - "prototype": "PlayerCanAcquireCallback", - "ref": false - } + { "name": "callback", "type": "function", "prototype": "PlayerCanAcquireCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HasPlayerTakeDamagePre", @@ -199,9 +187,7 @@ "group": "Damage", "description": "Reports whether the current native damage-hook prerequisites are available.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HookPlayerTakeDamagePre", @@ -209,16 +195,9 @@ "group": "Damage", "description": "Installs the exclusive synchronous player damage policy callback.", "paramTypes": [ - { - "name": "callback", - "type": "function", - "prototype": "DamagePreCallback", - "ref": false - } + { "name": "callback", "type": "function", "prototype": "DamagePreCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "UnhookPlayerTakeDamagePre", @@ -226,16 +205,9 @@ "group": "Damage", "description": "Revokes the player damage callback and removes its detour.", "paramTypes": [ - { - "name": "callback", - "type": "function", - "prototype": "DamagePreCallback", - "ref": false - } + { "name": "callback", "type": "function", "prototype": "DamagePreCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HasEntityTakeDamagePre", @@ -243,9 +215,7 @@ "group": "Damage", "description": "Reports whether the shared non-player damage callback prerequisites are available without player-only headshot tracing.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HookEntityTakeDamagePre", @@ -253,16 +223,9 @@ "group": "Damage", "description": "Subscribes one synchronous non-player entity damage callback to the shared TakeDamageOld detour; nonzero suppresses native damage.", "paramTypes": [ - { - "name": "callback", - "type": "function", - "prototype": "EntityDamagePreCallback", - "ref": false - } + { "name": "callback", "type": "function", "prototype": "EntityDamagePreCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "UnhookEntityTakeDamagePre", @@ -270,16 +233,9 @@ "group": "Damage", "description": "Revokes this entity damage callback and removes the shared detour only when no damage callbacks remain. Returns true when this callback is absent or revoked; other callbacks are untouched.", "paramTypes": [ - { - "name": "callback", - "type": "function", - "prototype": "EntityDamagePreCallback", - "ref": false - } + { "name": "callback", "type": "function", "prototype": "EntityDamagePreCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "GetCurrentDamageFrameToken", @@ -287,9 +243,7 @@ "group": "Damage", "description": "Returns the current nested damage-call token, or zero outside a damage call.", "paramTypes": [], - "retType": { - "type": "uint64" - } + "retType": { "type": "uint64" } }, { "name": "TakeEntityDamageWithWeapon", @@ -297,51 +251,15 @@ "group": "Damage", "description": "Applies native damage with an exact ability weapon handle and optional callback-specific rule bypass; returns -1 on execution failure, otherwise the actual non-negative health lost (0 is valid).", "paramTypes": [ - { - "name": "victimHandle", - "type": "int32", - "ref": false - }, - { - "name": "inflictorHandle", - "type": "int32", - "ref": false - }, - { - "name": "attackerHandle", - "type": "int32", - "ref": false - }, - { - "name": "force", - "type": "vec3", - "ref": false - }, - { - "name": "position", - "type": "vec3", - "ref": false - }, - { - "name": "amount", - "type": "float", - "ref": false - }, - { - "name": "damageType", - "type": "int32", - "ref": false - }, - { - "name": "weaponHandle", - "type": "int32", - "ref": false - }, - { - "name": "skipPluginRules", - "type": "bool", - "ref": false - } + { "name": "victimHandle", "type": "int32", "ref": false }, + { "name": "inflictorHandle", "type": "int32", "ref": false }, + { "name": "attackerHandle", "type": "int32", "ref": false }, + { "name": "force", "type": "vec3", "ref": false }, + { "name": "position", "type": "vec3", "ref": false }, + { "name": "amount", "type": "float", "ref": false }, + { "name": "damageType", "type": "int32", "ref": false }, + { "name": "weaponHandle", "type": "int32", "ref": false }, + { "name": "skipPluginRules", "type": "bool", "ref": false } ], "retType": { "type": "int32", @@ -354,48 +272,57 @@ "group": "Entities", "description": "Reports whether the Touch vtable offset is available in the native gamedata.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HookEntityTouchPre", "funcName": "HookEntityTouchPre", "group": "Entities", - "description": "Hooks the entity's current Touch implementation address; the callback sees all entities sharing it.", + "description": "Subscribes this callback to the entity's current Touch implementation. Other callbacks may share the detour; any nonzero callback result suppresses the original Touch.", "paramTypes": [ - { - "name": "entityHandle", - "type": "int32", - "ref": false - }, - { - "name": "callback", - "type": "function", - "prototype": "EntityTouchPreCallback", - "ref": false - } + { "name": "entityHandle", "type": "int32", "ref": false }, + { "name": "callback", "type": "function", "prototype": "EntityTouchPreCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "UnhookEntityTouchPre", "funcName": "UnhookEntityTouchPre", "group": "Entities", - "description": "Returns true for a non-null callback with no hooks or after all its hooks detach; false for null or incomplete own-hook detachment. Other callbacks' hooks are untouched.", + "description": "Removes only this callback from its Touch subscriptions. A detour remains while another callback uses it; false means an own final-hook detach must be retried.", "paramTypes": [ - { - "name": "callback", - "type": "function", - "prototype": "EntityTouchPreCallback", - "ref": false - } + { "name": "callback", "type": "function", "prototype": "EntityTouchPreCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } + }, + { + "name": "HasBigHeadScaleSupport", + "funcName": "HasBigHeadScaleSupport", + "group": "BigHead", + "description": "Reports whether the current server build has the verified Pawn reset hook, schema field and GameRules mutator-bit contract needed to own Big Head scaling.", + "paramTypes": [], + "retType": { "type": "bool" } + }, + { + "name": "SetBigHeadScaleTarget", + "funcName": "SetBigHeadScaleTarget", + "group": "BigHead", + "description": "On the game thread, targets a finite positive scale for one exact live player Pawn after its native reset. Returns false if the target or current build contract cannot be confirmed.", + "paramTypes": [ + { "name": "pawnHandle", "type": "int32", "ref": false }, + { "name": "scale", "type": "float", "ref": false } + ], + "retType": { "type": "bool" } + }, + { + "name": "ClearBigHeadScaleTarget", + "funcName": "ClearBigHeadScaleTarget", + "group": "BigHead", + "description": "On the game thread, removes the exact Pawn target and restores its captured original scale only while the current Pawn still holds the owned value; map changes discard old handles without writing through them.", + "paramTypes": [ + { "name": "pawnHandle", "type": "int32", "ref": false } + ], + "retType": { "type": "bool" } }, { "name": "SetEntityDefaultCollisionGroup", @@ -403,15 +330,28 @@ "group": "Entities", "description": "Sets both collision-group fields to the standard default and notifies collision rules.", "paramTypes": [ - { - "name": "entityHandle", - "type": "int32", - "ref": false - } + { "name": "entityHandle", "type": "int32", "ref": false } ], - "retType": { - "type": "void" - } + "retType": { "type": "void" } + }, + { + "name": "HasAirMoveSupport", + "funcName": "HasAirMoveSupport", + "group": "AirMove", + "description": "Reports whether the verified AirMove entry and current pawn identity schema are available.", + "paramTypes": [], + "retType": { "type": "bool" } + }, + { + "name": "SetAirMoveAssist", + "funcName": "SetAirMoveAssist", + "group": "AirMove", + "description": "Attaches or detaches temporary AirMove input assistance for this callback.", + "paramTypes": [ + { "name": "active", "type": "bool", "ref": false }, + { "name": "assist", "type": "function", "prototype": "AirMoveAssist", "ref": false } + ], + "retType": { "type": "bool" } }, { "name": "HasGroundReverseSupport", @@ -419,9 +359,7 @@ "group": "GroundReverse", "description": "Reports whether the platform ground-reverse callsite and current-controller identity schema are available.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "SetGroundReverseActive", @@ -429,20 +367,10 @@ "group": "GroundReverse", "description": "Enables ground-reversed human movement and normal BOT movement with the configured local ground acceleration; false detaches the hook.", "paramTypes": [ - { - "name": "active", - "type": "bool", - "ref": false - }, - { - "name": "acceleration", - "type": "float", - "ref": false - } + { "name": "active", "type": "bool", "ref": false }, + { "name": "acceleration", "type": "float", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HasGhostVisibilitySupport", @@ -450,9 +378,7 @@ "group": "GhostVisibility", "description": "Installs the resident CCSBot visibility hook and reports whether its current-platform signature is available.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "SetGhostVisibilityTargets", @@ -460,15 +386,9 @@ "group": "GhostVisibility", "description": "Atomically replaces the exact full pawn-handle set hidden from BOT visibility; an empty set clears the filter.", "paramTypes": [ - { - "name": "pawnHandles", - "type": "int32[]", - "ref": false - } + { "name": "pawnHandles", "type": "int32[]", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HasGhostRadarSupport", @@ -476,9 +396,7 @@ "group": "GhostRadar", "description": "On the game thread, reports whether both the per-recipient radar update filter and spotted-state filter are ready.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HasGhostPassiveSoundMessageSupport", @@ -486,9 +404,7 @@ "group": "GhostVisibility", "description": "On the game thread, reports whether the per-recipient filter for the complete paired passive movement sound-event family is ready for fully hidden Ghost pawn handles. It filters client sound messages only; Hostage.Breath and active combat sounds remain visible.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HasGhostPassiveNoiseSupport", @@ -496,9 +412,7 @@ "group": "GhostVisibility", "description": "On the game thread, reports whether the scoped CCSBotManager::OnPlayerFootstep/per-BOT noise filter is ready. It suppresses only footsteps from exact fully hidden Ghost pawns to the exact connected enemy BOT controller; other noise, fall damage, teammates, and combat stay native.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "SetGhostRadarTargets", @@ -506,20 +420,10 @@ "group": "GhostRadar", "description": "On the game thread, publishes full pawn handles and parallel 64-bit masks of living enemy recipients whose radar updates must be hidden. Empty parallel arrays clear the snapshot.", "paramTypes": [ - { - "name": "fullPawnHandles", - "type": "int32[]", - "ref": false - }, - { - "name": "enemyRecipientMasks", - "type": "uint64[]", - "ref": false - } + { "name": "fullPawnHandles", "type": "int32[]", "ref": false }, + { "name": "enemyRecipientMasks", "type": "uint64[]", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HasUseTargetSupport", @@ -527,9 +431,7 @@ "group": "ChickenEating", "description": "Reports whether the exact committed player-use target callback is available on this platform.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HookUseTarget", @@ -537,16 +439,9 @@ "group": "ChickenEating", "description": "Observes the exact outer use-selector result and committed target for a live player pawn.", "paramTypes": [ - { - "name": "callback", - "type": "function", - "prototype": "UseTargetCallback", - "ref": false - } + { "name": "callback", "type": "function", "prototype": "UseTargetCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "UnhookUseTarget", @@ -554,16 +449,9 @@ "group": "ChickenEating", "description": "Removes only this callback from the committed use-target observation hook.", "paramTypes": [ - { - "name": "callback", - "type": "function", - "prototype": "UseTargetCallback", - "ref": false - } + { "name": "callback", "type": "function", "prototype": "UseTargetCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HasChickenFollowBlockSupport", @@ -571,9 +459,7 @@ "group": "ChickenFollow", "description": "Reports whether the exact CChickenChickenUse callback detour is available on this platform.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "SetChickenFollowBlocking", @@ -581,15 +467,9 @@ "group": "ChickenFollow", "description": "On the game thread, enables the native chicken-follow veto or disables it and removes only this provider's detour. Returns false while setup or owned-hook cleanup remains incomplete.", "paramTypes": [ - { - "name": "active", - "type": "bool", - "ref": false - } + { "name": "active", "type": "bool", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HasHealthshotSupport", @@ -597,9 +477,7 @@ "group": "Healthshot", "description": "Reports whether the healthshot eligibility and successful-effect hooks resolve on this platform.", "paramTypes": [], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "HookHealthshot", @@ -607,22 +485,10 @@ "group": "Healthshot", "description": "Blocks only the custom B-relative cap decision before consumption and reports successful native effects afterward.", "paramTypes": [ - { - "name": "canUse", - "type": "function", - "prototype": "HealthshotCanUseCallback", - "ref": false - }, - { - "name": "effect", - "type": "function", - "prototype": "HealthshotEffectCallback", - "ref": false - } + { "name": "canUse", "type": "function", "prototype": "HealthshotCanUseCallback", "ref": false }, + { "name": "effect", "type": "function", "prototype": "HealthshotEffectCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } }, { "name": "UnhookHealthshot", @@ -630,216 +496,114 @@ "group": "Healthshot", "description": "Removes only the two healthshot callbacks owned by this provider consumer.", "paramTypes": [ - { - "name": "canUse", - "type": "function", - "prototype": "HealthshotCanUseCallback", - "ref": false - }, - { - "name": "effect", - "type": "function", - "prototype": "HealthshotEffectCallback", - "ref": false - } + { "name": "canUse", "type": "function", "prototype": "HealthshotCanUseCallback", "ref": false }, + { "name": "effect", "type": "function", "prototype": "HealthshotEffectCallback", "ref": false } ], - "retType": { - "type": "bool" - } + "retType": { "type": "bool" } } ], "prototypes": [ + { + "name": "AirMoveAssist", + "funcName": "AirMoveAssist", + "description": "Produces forward and left input for the exact airborne pawn, or returns false to keep native input.", + "paramTypes": [ + { "name": "slot", "type": "int32" }, + { "name": "pawn", "type": "int32" }, + { "name": "controller", "type": "int32" }, + { "name": "yaw", "type": "float" }, + { "name": "vx", "type": "float" }, + { "name": "vy", "type": "float" }, + { "name": "forward", "type": "float", "ref": true }, + { "name": "left", "type": "float", "ref": true } + ], + "retType": { "type": "bool" } + }, { "name": "PlayerCanAcquireCallback", "funcName": "PlayerCanAcquireCallback", "description": "Synchronous pickup decision for exact player pawn and controller handles.", "paramTypes": [ - { - "name": "pawnHandle", - "type": "int32" - }, - { - "name": "controllerHandle", - "type": "int32" - } + { "name": "pawnHandle", "type": "int32" }, + { "name": "controllerHandle", "type": "int32" } ], - "retType": { - "type": "int32" - } + "retType": { "type": "int32" } }, { "name": "DamagePreCallback", "funcName": "DamagePreCallback", "description": "Synchronous player damage decision with native damage type, exact weapon handle, and per-call rule scope.", "paramTypes": [ - { - "name": "victimHandle", - "type": "int32" - }, - { - "name": "attackerHandle", - "type": "int32" - }, - { - "name": "inflictorHandle", - "type": "int32" - }, - { - "name": "weaponKind", - "type": "int32" - }, - { - "name": "hitGroup", - "type": "int32" - }, - { - "name": "tracedHead", - "type": "bool" - }, - { - "name": "damage", - "type": "float" - }, - { - "name": "damageType", - "type": "uint32" - }, - { - "name": "multiplier", - "type": "float", - "ref": true - }, - { - "name": "markHeadshot", - "type": "bool", - "ref": true - }, - { - "name": "weaponHandle", - "type": "int32" - }, - { - "name": "skipPluginRules", - "type": "bool" - } + { "name": "victimHandle", "type": "int32" }, + { "name": "attackerHandle", "type": "int32" }, + { "name": "inflictorHandle", "type": "int32" }, + { "name": "weaponKind", "type": "int32" }, + { "name": "hitGroup", "type": "int32" }, + { "name": "tracedHead", "type": "bool" }, + { "name": "damage", "type": "float" }, + { "name": "damageType", "type": "uint32" }, + { "name": "multiplier", "type": "float", "ref": true }, + { "name": "markHeadshot", "type": "bool", "ref": true }, + { "name": "weaponHandle", "type": "int32" }, + { "name": "skipPluginRules", "type": "bool" } ], - "retType": { - "type": "int32" - } + "retType": { "type": "int32" } }, { "name": "EntityDamagePreCallback", "funcName": "EntityDamagePreCallback", "description": "Synchronous raw non-player entity damage decision with exact victim/source handles, damage type, and per-call rule scope; return zero to allow or nonzero to suppress.", "paramTypes": [ - { - "name": "victimHandle", - "type": "int32" - }, - { - "name": "attackerHandle", - "type": "int32" - }, - { - "name": "inflictorHandle", - "type": "int32" - }, - { - "name": "abilityHandle", - "type": "int32" - }, - { - "name": "damage", - "type": "float" - }, - { - "name": "damageType", - "type": "uint32" - }, - { - "name": "skipPluginRules", - "type": "bool" - } + { "name": "victimHandle", "type": "int32" }, + { "name": "attackerHandle", "type": "int32" }, + { "name": "inflictorHandle", "type": "int32" }, + { "name": "abilityHandle", "type": "int32" }, + { "name": "damage", "type": "float" }, + { "name": "damageType", "type": "uint32" }, + { "name": "skipPluginRules", "type": "bool" } ], - "retType": { - "type": "int32" - } + "retType": { "type": "int32" } }, { "name": "EntityTouchPreCallback", "funcName": "EntityTouchPreCallback", - "description": "Synchronous decision for every entity sharing the selected Touch implementation.", + "description": "Synchronous veto decision for a subscribed Touch implementation; any nonzero callback result suppresses the original call.", "paramTypes": [ - { - "name": "entityHandle", - "type": "int32" - }, - { - "name": "otherHandle", - "type": "int32" - } + { "name": "entityHandle", "type": "int32" }, + { "name": "otherHandle", "type": "int32" } ], - "retType": { - "type": "int32" - } + "retType": { "type": "int32" } }, { "name": "UseTargetCallback", "funcName": "UseTargetCallback", "description": "Synchronous target observation for an exact live player pawn; target is -1 if no committed match and inUse reports the current E state.", "paramTypes": [ - { - "name": "pawnHandle", - "type": "int32" - }, - { - "name": "targetHandle", - "type": "int32" - }, - { - "name": "inUse", - "type": "bool" - } + { "name": "pawnHandle", "type": "int32" }, + { "name": "targetHandle", "type": "int32" }, + { "name": "inUse", "type": "bool" } ], - "retType": { - "type": "void" - } + "retType": { "type": "void" } }, { "name": "HealthshotCanUseCallback", "funcName": "HealthshotCanUseCallback", "description": "Returns nonzero only to veto custom healthshot use for the exact player life and healthshot inventory entity.", "paramTypes": [ - { - "name": "pawnHandle", - "type": "int32" - }, - { - "name": "weaponHandle", - "type": "int32" - } + { "name": "pawnHandle", "type": "int32" }, + { "name": "weaponHandle", "type": "int32" } ], - "retType": { - "type": "int32" - } + "retType": { "type": "int32" } }, { "name": "HealthshotEffectCallback", "funcName": "HealthshotEffectCallback", "description": "Reports the completed native healthshot effect for exact pawn and inventory-weapon handles.", "paramTypes": [ - { - "name": "pawnHandle", - "type": "int32" - }, - { - "name": "weaponHandle", - "type": "int32" - } + { "name": "pawnHandle", "type": "int32" }, + { "name": "weaponHandle", "type": "int32" } ], - "retType": { - "type": "void" - } + "retType": { "type": "void" } } ] } diff --git a/native/funrounds-native/gamedata/funrounds-native.jsonc b/native/funrounds-native/gamedata/funrounds-native.jsonc index 5ab5ef3..e1266f8 100644 --- a/native/funrounds-native/gamedata/funrounds-native.jsonc +++ b/native/funrounds-native/gamedata/funrounds-native.jsonc @@ -2,6 +2,12 @@ "$schema": "https://raw.githubusercontent.com/untrustedmodders/plugify-plugin-s2sdk/refs/tags/v3.0.0/assets/gamedata.schema.json", "csgo": { "Signatures": { + // Current CS2 BuildID 26445667 only. Native additionally validates PE timestamp/image size or the Linux ELF BuildID, helper RVA/prologue, and receiver slot/value before calling. + "FunRounds::PlayerMovementTraceShape": { + "library": "server", + "win64": "48 89 54 24 10 48 89 4C 24 08 55 53 56 57 41 54 41 56 41 57 48 8D AC 24 F0 DB FF FF", + "linuxsteamrt64": "55 48 8D 05 ?? ?? ?? ?? 48 89 E5 41 57 49 89 F7 41 56 48 8D 35 ?? ?? ?? ?? 49 89 CE" + }, // Internal spawn validator, independently inspected on both 2000938 binaries. // This bypasses only the caller's Deathmatch-mode gate, not point validation. "FunRounds::SelectSpawnSpot": { @@ -31,6 +37,33 @@ "win64": "44 89 44 24 ? 48 89 54 24 ? 48 89 4C 24 ? 55 53 56 57 41 54 41 55 41 56 41 57 48 8B EC", "linuxsteamrt64": "55 48 89 E5 41 57 41 56 49 89 F6 41 55 41 54 49 89 CC 53 48 89 FB 48 83 EC ? 4C 8B 6F 38" }, + // Exact entry prefixes verified in CS2 BuildID 26445667 (2000942). + // The layout anchors below must all resolve relative to this entry and its AngleVectors call. + "FunRounds::AirMove": { + "library": "server", + "win64": "48 8B C4 55 53 56 57 41 56 48 8D 68 C8 48 81 EC 10 01 00 00 0F 29 70 C8 4C 8D 05 01 1A E4 00 0F 29 78 B8 48 8B DA 44 0F 29 40 A8 48 8B F9", + "linuxsteamrt64": "55 48 8D 15 3A 5D 32 FF 48 89 E5 41 57 41 56 4C 8D BD 68 FF FF FF 41 55 4C 8D B5 78 FF FF FF 41 54 49 89 FC 53 48 89 F3 48 81 EC A8 00 00 00" + }, + "FunRounds::AirMove::AnglesCall": { + "library": "server", + "win64": "48 8D 4B 14 4C 8D 4C 24 60 4C 8D 44 24 30 48 8D 54 24 40 E8 ?? ?? ?? ??", + "linuxsteamrt64": "48 8D 4D 84 4C 89 F2 4C 89 FE 48 8D 7B 14 E8 ?? ?? ?? ??" + }, + "FunRounds::AirMove::InputLoads": { + "library": "server", + "win64": "F3 0F 10 43 30 41 0F 28 C9 F3 0F 10 74 24 40 F3 44 0F 10 7B 2C F3 0F 11 45 40", + "linuxsteamrt64": "F3 0F 7E 43 2C F3 0F 11 65 80 F3 0F 16 CA F3 0F 10 1D ?? ?? ?? ?? F3 0F 12 F0 F3 0F 16 F8" + }, + "FunRounds::AirMove::VelocityLoads": { + "library": "server", + "win64": "F3 0F 10 43 38 F3 0F 5C C2 F3 0F 11 43 38 F3 0F 10 43 3C F3 0F 5C C1 F3 0F 11 43 3C", + "linuxsteamrt64": "F3 0F 7E 53 38 F3 0F 16 CA 0F 28 C2 F3 0F 59 C2 F3 0F 59 C9 F3 0F 58 C1 66 0F EF C9" + }, + "FunRounds::AirMove::AngleVectors": { + "library": "server", + "win64": "48 8B C4 48 89 58 08 48 89 70 10 57 48 83 EC 70 F3 0F 10 01 49 8B F8 0F 29 70 E8 4C 8D 40 A8 F3 0F 10 71 04 48 8B DA 0F 29 78 D8 48 8D 50 B8 F3 0F 10 3D 29 E9 35 00", + "linuxsteamrt64": "55 48 89 E5 41 55 49 89 F5 41 54 48 8D 45 C0 49 89 D4 53 48 8D 75 D0 48 89 CB 48 83 EC 38 F3 0F 10 05 ?? ?? ?? ?? F3 0F 59 07 F3 0F 10 77 08 F3 0F 10 4F 04" + }, "FunRounds::GroundReverseAccelerationCallsite": { "library": "server", "win64": "F3 0F 11 44 24 20 E8 ? ? ? ? 44 89 6F 40 4C 8D 67 38", @@ -74,10 +107,31 @@ "CChickenChickenUse": { "library": "server", "win64": "48 8B 01 FF A0 E0 09 00 00", - "linuxsteamrt64": "55 48 89 E5 41 56 41 55 41 54 53 48 8B 1E 48 85 DB 0F 84 ?? ?? ?? ?? 48 8B 03 49 89 FC 49 89 F5 48 89 DF FF 90 50 05 00 00" + "linuxsteamrt64": "55 48 89 E5 41 55 41 54 53 48 83 EC 08 48 8B 1E 48 85 DB 0F 84 ?? ?? ?? ?? 48 8B 03 49 89 FC 48 89 DF FF 90 50 05 00 00 84 C0" + }, + // Current BuildID 26334290 reset routines read and restore + // CCSPlayerPawn::m_flBigHeadScale after the native mutator reset. + // The paired Windows and Linux server binaries were checked in IDA. + "FunRounds::BigHeadScaleReset": { + "library": "server", + "win64": "48 8B C4 57 48 81 EC 70 01 00 00 83 B9 F0 0F 00 00 00 48 8B F9 0F 85 4A 02 00 00 48 89 58 08 48 89 70 18 E8 ? ? ? ? 48 8B D8 48 85 C0 74 10 48 8B C8 E8 ? ? ? ? 48 8B CB E8 ? ? ? ? F3 0F 10 87 AC 15 00 00 0F 2E 05 ? ? ? ? 7A", + "linuxsteamrt64": "55 48 89 E5 41 57 41 56 41 55 41 54 53 48 89 FB 48 81 EC 68 01 00 00 E8 ? ? ? ? 48 85 C0 74 13 49 89 C4 48 89 C7 E8 ? ? ? ? 4C 89 E7 E8 ? ? ? ? F3 0F 10 0D ? ? ? ? 0F 2E 8B 74" } }, "Offsets": { + // FromEntry offsets tie the body signatures to AirMove. Operand offsets + // are relative to the corresponding signature, not CMoveData. Equal + // operand offsets identify a packed pair (second float follows the first). + "FunRounds::AirMove::AnglesCallFromEntry": { "win64": 93, "linuxsteamrt64": 52 }, + "FunRounds::AirMove::InputLoadsFromEntry": { "win64": 279, "linuxsteamrt64": 137 }, + "FunRounds::AirMove::VelocityLoadsFromEntry": { "win64": 1062, "linuxsteamrt64": 632 }, + "FunRounds::AirMove::AnglesBaseDisp8": { "win64": 3, "linuxsteamrt64": 13 }, + "FunRounds::AirMove::AngleVectorsRel32": { "win64": 20, "linuxsteamrt64": 15 }, + "FunRounds::AirMove::YawDisp8": { "win64": 35, "linuxsteamrt64": 51 }, + "FunRounds::AirMove::ForwardDisp8": { "win64": 20, "linuxsteamrt64": 4 }, + "FunRounds::AirMove::LeftDisp8": { "win64": 4, "linuxsteamrt64": 4 }, + "FunRounds::AirMove::VelocityXDisp8": { "win64": 4, "linuxsteamrt64": 4 }, + "FunRounds::AirMove::VelocityYDisp8": { "win64": 18, "linuxsteamrt64": 4 }, "CBaseEntity::Touch": { "win64": 151, "linuxsteamrt64": 150 @@ -90,13 +144,32 @@ "win64": 188, "linuxsteamrt64": 187 }, + // Player Ignite call shape is ABI-specific and validated by burn.cpp; keep the slot paired with gamedata. + "CBaseEntity::IgnitePawn": { + "win64": 266, + "linuxsteamrt64": 267 + }, // CPlayer_UseServices committed full target handle, same observed build. "UseServicesLastTargetHandle": { "win64": 72, "linuxsteamrt64": 72 + }, + // Runtime-verified against the pinned CS2 2000940 server on Windows and + // Linux: the engine exposes this shared Detonate wrapper for each type. + "CSGrenadeProjectileBase::Detonate": { + "win64": 309, + "linuxsteamrt64": 310 } }, "VTables": { + "CSmokeGrenadeProjectile": { + "library": "server", + "table": "CSmokeGrenadeProjectile" + }, + "CMolotovProjectile": { + "library": "server", + "table": "CMolotovProjectile" + }, // Shared CServerSideClientBase::SendNetMessage hook; the binary vtable is in engine2. "CServerSideClient": { "library": "engine2", diff --git a/native/funrounds-native/src/airmove.cpp b/native/funrounds-native/src/airmove.cpp new file mode 100644 index 0000000..e7f1bdd --- /dev/null +++ b/native/funrounds-native/src/airmove.cpp @@ -0,0 +1,282 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#include "airmove.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "engine.hpp" +#include "entity_handle.hpp" + +namespace funrounds::native::detail { +namespace { + +constexpr char kAirMove[] = "FunRounds::AirMove"; +constexpr std::uint64_t kDirections = (1ULL << 3) | (1ULL << 4) | (1ULL << 9) | (1ULL << 10); +using Assist = bool (*)(std::int32_t, std::int32_t, std::int32_t, float, float, float, float&, float&); +using Phase = polyhook::CallbackType; +using Result = polyhook::ResultType; + +struct MoveLayout { + std::size_t yaw{}, forward{}, left{}, vx{}, vy{}; +}; + +struct AirMoveState { + void* address{}; + polyhook::HookHandle hook{}; + MoveLayout layout{}; + SchemaField movementOwner{}; + SchemaField pawnController{}; + SchemaField pawnLifeState{}; + SchemaField pawnHealth{}; + Assist assist{}; + std::thread::id gameThread{}; +} g_state; + +struct Edit { + std::byte* move{}; + float forward{}, left{}, writtenForward{}, writtenLeft{}; + unsigned nested{}; +}; +thread_local Edit g_edit; + +template +T Read(const std::byte* object, std::size_t offset) noexcept { + T value; + std::memcpy(&value, object + offset, sizeof(value)); + return value; +} + +void WriteMoveAxis(std::byte* move, std::size_t offset, float value) noexcept { + std::memcpy(move + offset, &value, sizeof(value)); +} + +bool ResolveMoveLayout(const std::byte* entry, MoveLayout& layout) { + const auto config = GameConfig(); + const auto body = [&](const char* signature, const char* fromEntry) -> const std::byte* { + auto* site = static_cast(s2sdk::GetGameConfigSignature(config, signature)); + const auto relative = s2sdk::GetGameConfigOffset(config, fromEntry); + if (!site || relative <= 0 || + reinterpret_cast(site) - reinterpret_cast(entry) != static_cast(relative)) { + return nullptr; + } + return site; + }; + const auto* call = body("FunRounds::AirMove::AnglesCall", "FunRounds::AirMove::AnglesCallFromEntry"); + const auto* input = body("FunRounds::AirMove::InputLoads", "FunRounds::AirMove::InputLoadsFromEntry"); + const auto* velocity = body("FunRounds::AirMove::VelocityLoads", "FunRounds::AirMove::VelocityLoadsFromEntry"); + const auto* angles = static_cast(s2sdk::GetGameConfigSignature(config, "FunRounds::AirMove::AngleVectors")); + if (!call || !input || !velocity || !angles) return false; + + // Gamedata provides the locations of operands inside the short signatures. + // Keep operand reads bounded; a missing key is reported by S2SDK as -1. + constexpr int maxOperandOffset = 63; + const auto operand = [&](const char* key) { + const auto offset = s2sdk::GetGameConfigOffset(config, key); + return offset >= 0 && offset <= maxOperandOffset ? offset : -1; + }; + const auto rel32 = operand("FunRounds::AirMove::AngleVectorsRel32"); + const auto base = operand("FunRounds::AirMove::AnglesBaseDisp8"); + const auto yaw = operand("FunRounds::AirMove::YawDisp8"); + const auto forward = operand("FunRounds::AirMove::ForwardDisp8"); + const auto left = operand("FunRounds::AirMove::LeftDisp8"); + const auto vx = operand("FunRounds::AirMove::VelocityXDisp8"); + const auto vy = operand("FunRounds::AirMove::VelocityYDisp8"); + if (rel32 < 0 || base < 0 || yaw < 0 || forward < 0 || left < 0 || vx < 0 || vy < 0) return false; + + const auto* relativeCall = call + rel32; + const auto destination = reinterpret_cast(relativeCall + sizeof(std::int32_t)) + Read(relativeCall, 0); + if (destination != reinterpret_cast(angles)) return false; + + const auto displacement = [](const std::byte* site, int index) -> std::size_t { + return Read(site, static_cast(index)); + }; + // A packed load uses the same operand for both halves of the float pair. + layout = { + displacement(call, base) + displacement(angles, yaw), + displacement(input, forward), + displacement(input, left) + (left == forward ? sizeof(float) : 0), + displacement(velocity, vx), + displacement(velocity, vy) + (vy == vx ? sizeof(float) : 0), + }; + const std::array offsets{layout.yaw, layout.forward, layout.left, layout.vx, layout.vy}; + for (std::size_t i = 0; i < offsets.size(); ++i) { + if (offsets[i] == 0 || offsets[i] > 127 || offsets[i] % alignof(float) != 0) return false; + for (std::size_t j = 0; j < i; ++j) { + if (offsets[i] == offsets[j]) return false; + } + } + return true; +} + +bool ResolveAirMove() { + if (g_state.address) { + return true; + } + if (!__polyhook_HookDetour || !__polyhook_FindDetour || !__polyhook_UnhookDetour || + !__polyhook_AddCallback || !__polyhook_RemoveCallback || !__polyhook_IsCallbackRegistered || + !__polyhook_AreCallbacksRegistered || !__polyhook_GetArgumentPointer || + !__s2sdk_GetGameConfigSignature || !__s2sdk_GetGameConfigOffset || !__s2sdk_GetClientPawn || !__s2sdk_GetMaxClients || + !__s2sdk_PlayerSlotToEntHandle || !__s2sdk_IsClientInGame || + !__s2sdk_GetClientFlags || !__s2sdk_GetClientButtons || !__s2sdk_GetEntityMoveType || + !EnsureEngine() || + !ResolvePlayerPawnComponentChain(g_state.movementOwner) || + !ResolveSchemaField("CBasePlayerPawn", "m_hController", sizeof(std::uint32_t), g_state.pawnController) || + !ResolveSchemaField("CBaseEntity", "m_lifeState", sizeof(std::uint8_t), g_state.pawnLifeState) || + !ResolveSchemaField("CBaseEntity", "m_iHealth", sizeof(std::int32_t), g_state.pawnHealth)) { + return false; + } + auto* entry = static_cast(s2sdk::GetGameConfigSignature(GameConfig(), kAirMove)); + if (!entry || !ResolveMoveLayout(entry, g_state.layout)) { + return false; + } + g_state.address = entry; + return true; +} + +Result AirMove(polyhook::HookHandle, polyhook::ParametersHandle args, std::int32_t, + polyhook::ReturnHandle, Phase phase) noexcept { + if (std::this_thread::get_id() != g_state.gameThread) { + return Result::Ignored; + } + if (phase == Phase::Post) { + if (g_edit.nested) { + --g_edit.nested; + } else if (auto* move = g_edit.move) { + // Only undo our own writes. A cooperating hook may have replaced either axis. + if (Read(move, g_state.layout.forward) == g_edit.writtenForward) WriteMoveAxis(move, g_state.layout.forward, g_edit.forward); + if (Read(move, g_state.layout.left) == g_edit.writtenLeft) WriteMoveAxis(move, g_state.layout.left, g_edit.left); + g_edit = {}; + } + return Result::Ignored; + } + if (g_edit.move) { + ++g_edit.nested; + return Result::Ignored; + } + + try { + if (!g_state.assist) return Result::Ignored; + auto* move = static_cast(polyhook::GetArgument(args, 1)); + auto* services = static_cast(polyhook::GetArgument(args, 0)); + if (!services || !move) return Result::Ignored; + const float oldForward = Read(move, g_state.layout.forward); + const float oldLeft = Read(move, g_state.layout.left); + if (!(std::abs(oldForward) <= .001F && std::abs(oldLeft) <= .001F)) return Result::Ignored; + auto* chain = reinterpret_cast(services + g_state.movementOwner.offset); + auto* pawn = reinterpret_cast(chain->GetObject()); + if (!pawn) return Result::Ignored; + const auto controllerHandle = ToApiHandle(Read(pawn, g_state.pawnController.offset)); + const auto pawnHandle = HandleFromEntity(pawn); + auto* controller = static_cast(EntityFromHandle(controllerHandle)); + if (!controller || pawnHandle == -1) return Result::Ignored; + const auto slot = controller->GetRefEHandle().GetEntryIndex() - 1; + if (slot < 0 || slot >= s2sdk::GetMaxClients() || !s2sdk::IsClientInGame(slot) || + s2sdk::PlayerSlotToEntHandle(slot) != controllerHandle || s2sdk::GetClientPawn(slot) != pawn) { + return Result::Ignored; + } + // IsClientAlive follows the slot's original pawn, not the pawn being driven after BOT takeover. + if (Read(pawn, g_state.pawnLifeState.offset) != 0 || + Read(pawn, g_state.pawnHealth.offset) <= 0 || (s2sdk::GetClientFlags(slot) & 1) != 0 || + s2sdk::GetEntityMoveType(pawnHandle) != s2sdk::MoveType::Walk || + (s2sdk::GetClientButtons(slot, 0) & kDirections) != 0) { + return Result::Ignored; + } + + float forward{}, left{}; + if (g_state.assist(slot, pawnHandle, controllerHandle, + Read(move, g_state.layout.yaw), + Read(move, g_state.layout.vx), + Read(move, g_state.layout.vy), forward, left)) { + g_edit = {move, oldForward, oldLeft, forward, left, 0}; + WriteMoveAxis(move, g_state.layout.forward, forward); + WriteMoveAxis(move, g_state.layout.left, left); + } + } catch (...) { + // A failed read leaves the native movement command untouched. + } + return Result::Ignored; +} + +bool RemoveAirMove() { + g_state.assist = nullptr; + if (!g_state.hook) return true; + if (g_edit.move) return false; + const auto hook = polyhook::FindDetour(g_state.address); + if (hook && hook != g_state.hook) return false; + if (hook) { + for (const auto phase : {Phase::Pre, Phase::Post}) { + if (polyhook::IsCallbackRegistered(hook, phase, AirMove)) { + (void)polyhook::RemoveCallback(hook, phase, AirMove); + if (polyhook::IsCallbackRegistered(hook, phase, AirMove)) return false; + } + } + if (!polyhook::AreCallbacksRegistered(hook) && + !polyhook::UnhookDetour(g_state.address) && polyhook::FindDetour(g_state.address) == hook) { + return false; + } + } + g_state.hook = nullptr; + return true; +} + +bool SetAirMove(bool active, Assist assist) { + if (!active) { + return (!g_state.assist || g_state.assist == assist) && RemoveAirMove(); + } + if (!assist || !ResolveAirMove()) return false; + if (g_state.hook) return g_state.assist == assist; + if (polyhook::FindDetour(g_state.address)) return false; + using T = polyhook::DataType; + g_state.hook = polyhook::HookDetour(g_state.address, T::Void, {T::Pointer, T::Pointer}, -1, kAirMove); + if (!g_state.hook) return false; + g_state.gameThread = std::this_thread::get_id(); + if (!polyhook::AddCallback(g_state.hook, Phase::Post, AirMove) || + !polyhook::AddCallback(g_state.hook, Phase::Pre, AirMove)) { + (void)RemoveAirMove(); + return false; + } + g_state.assist = assist; + return true; +} + +} // namespace + +bool ShutdownAirMove() noexcept { + try { + if (!RemoveAirMove()) return false; + g_state = {}; + return true; + } catch (...) { + return false; + } +} + +} // namespace funrounds::native::detail + +extern "C" PLUGIN_API bool HasAirMoveSupport() noexcept { + try { + return funrounds::native::detail::ResolveAirMove(); + } catch (...) { + return false; + } +} + +extern "C" PLUGIN_API bool SetAirMoveAssist(bool active, funrounds::native::detail::Assist assist) noexcept { + try { + return funrounds::native::detail::SetAirMove(active, assist); + } catch (...) { + return false; + } +} diff --git a/native/funrounds-native/src/airmove.hpp b/native/funrounds-native/src/airmove.hpp new file mode 100644 index 0000000..c071f16 --- /dev/null +++ b/native/funrounds-native/src/airmove.hpp @@ -0,0 +1,8 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#pragma once + +namespace funrounds::native::detail { +bool ShutdownAirMove() noexcept; +} diff --git a/native/funrounds-native/src/bighead.cpp b/native/funrounds-native/src/bighead.cpp new file mode 100644 index 0000000..4132c3e --- /dev/null +++ b/native/funrounds-native/src/bighead.cpp @@ -0,0 +1,656 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#include "bighead.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "bighead_policy.hpp" +#include "engine.hpp" + +namespace funrounds::native::detail { +namespace { + +constexpr char kResetSignature[] = "FunRounds::BigHeadScaleReset"; +constexpr char kResetHookName[] = "FunRounds::BigHeadScaleReset"; +constexpr char kPawnClass[] = "CCSPlayerPawn"; +constexpr char kScaleField[] = "m_flBigHeadScale"; +constexpr char kRulesClass[] = "CCSGameRules"; +constexpr char kMutatorsField[] = "m_nActiveMutators"; +constexpr std::int32_t kInvalidHandle = -1; + +struct BigHeadLayout { + SchemaField scale{}; + SchemaField mutators{}; + bool ready{}; +}; + +struct RulesIdentity { + void* rules{}; +}; + +struct BigHeadTarget { + std::int32_t pawnHandle{kInvalidHandle}; + void* pawn{}; + float originalScale{}; + float lastScale{}; +}; + +struct ResetHook { + void* address{}; + polyhook::HookHandle handle{}; + bool attempted{}; +}; + +BigHeadLayout g_layout; +std::vector g_targets; +ResetHook g_resetHook; +RulesIdentity g_rules; +bighead::MutatorBitLease g_mutatorLease{}; +bool g_hasRules{}; +bool g_hasMutatorLease{}; +bool g_mapEndRegistered{}; +bool g_faulted{}; +bool g_faultLogged{}; + +polyhook::ResultType BigHeadResetPost(polyhook::HookHandle, + polyhook::ParametersHandle, + std::int32_t, + polyhook::ReturnHandle, + polyhook::CallbackType) noexcept; +void BigHeadMapEndCallback() noexcept; + +bool RequiredImportsAvailable() noexcept { + return __polyhook_HookDetour != nullptr && __polyhook_FindDetour != nullptr && + __polyhook_AddCallback != nullptr && __polyhook_IsCallbackRegistered != nullptr && + __polyhook_RemoveCallback != nullptr && __polyhook_AreCallbacksRegistered != nullptr && + __polyhook_UnhookDetour != nullptr && __polyhook_GetArgumentPointer != nullptr && + __s2sdk_GetGameRules != nullptr && __s2sdk_GetGameConfigSignature != nullptr && + __s2sdk_OnMapEnd_Register != nullptr && __s2sdk_OnMapEnd_Unregister != nullptr && + __s2sdk_EntHandleToEntPointer != nullptr && __s2sdk_EntPointerToEntHandle != nullptr && + __s2sdk_IsValidEntHandle != nullptr && __s2sdk_IsEntityPlayerPawn != nullptr && + __s2sdk_GetEntSchemaFloat2 != nullptr && __s2sdk_SetEntSchemaFloat2 != nullptr && + __s2sdk_GetEntSchema2 != nullptr && __s2sdk_SetEntSchema2 != nullptr; +} + +void LatchBigHeadFailure(const char* message) noexcept { + g_faulted = true; + if (g_faultLogged) { + return; + } + g_faultLogged = true; + try { + if (plg::Log != nullptr) { + plg::Log(message, plg::Severity::Error, plg::source_location::current()); + } + } catch (...) { + } +} + +bool ResolveBigHeadLayout() noexcept { + if (g_layout.ready) { + return true; + } + + SchemaField scale{}; + SchemaField mutators{}; + if (!ResolveSchemaField(kPawnClass, kScaleField, sizeof(float), scale) || scale.offset < 0 || + !ResolveSchemaField(kRulesClass, kMutatorsField, sizeof(std::int32_t), mutators) || + mutators.offset < 0) { + return false; + } + + g_layout = {scale, mutators, true}; + return true; +} + +void* CurrentRules() noexcept { + try { + return s2sdk::GetGameRules(); + } catch (...) { + return nullptr; + } +} + +bool SameRules(const RulesIdentity& identity) noexcept { + return identity.rules != nullptr && CurrentRules() == identity.rules; +} + +std::uint32_t ReadMutators(void* rules) { + const auto mask = s2sdk::GetEntSchema2(rules, kRulesClass, kMutatorsField, 0); + return static_cast(static_cast(mask)); +} + +void WriteMutators(void* rules, std::uint32_t mask) { + const auto signedMask = std::bit_cast(mask); + s2sdk::SetEntSchema2(rules, + kRulesClass, + kMutatorsField, + static_cast(signedMask), + true, + 0); +} + +float ReadScale(void* pawn) { + return static_cast(s2sdk::GetEntSchemaFloat2(pawn, kPawnClass, kScaleField, 0)); +} + +void WriteScale(void* pawn, float scale) { + s2sdk::SetEntSchemaFloat2(pawn, kPawnClass, kScaleField, static_cast(scale), true, 0); +} + +bool CurrentPawn(std::int32_t pawnHandle, void*& pawn) noexcept { + try { + if (pawnHandle == kInvalidHandle || !s2sdk::IsValidEntHandle(pawnHandle) || !IsPlayerPawn(pawnHandle)) { + return false; + } + pawn = EntityFromHandle(pawnHandle); + return pawn != nullptr && HandleFromEntity(pawn) == pawnHandle; + } catch (...) { + pawn = nullptr; + return false; + } +} + +bool RegisterMapEndCallback() noexcept { + if (g_mapEndRegistered) { + return true; + } + try { + s2sdk::OnMapEnd_Register(BigHeadMapEndCallback); + g_mapEndRegistered = true; + return true; + } catch (...) { + return false; + } +} + +bool UnregisterMapEndCallback() noexcept { + if (!g_mapEndRegistered) { + return true; + } + try { + s2sdk::OnMapEnd_Unregister(BigHeadMapEndCallback); + g_mapEndRegistered = false; + return true; + } catch (...) { + LatchBigHeadFailure("Big Head map-end callback cleanup failed; native recovery remains pending"); + return false; + } +} + +void ForgetTargetsForMapChange() noexcept { + // Entity handles can be recycled on the next map. Never resolve or restore + // a Pawn snapshot after crossing this boundary. + g_targets.clear(); + g_rules = {}; + g_mutatorLease = {}; + g_hasRules = false; + g_hasMutatorLease = false; +} + +bool RestoreMutatorBit() noexcept { + if (!g_hasRules || !g_hasMutatorLease || !g_mutatorLease.owned) { + g_rules = {}; + g_mutatorLease = {}; + g_hasRules = false; + g_hasMutatorLease = false; + return true; + } + + if (!SameRules(g_rules)) { + // The old rules object is gone or a new map already owns the global. + ForgetTargetsForMapChange(); + return true; + } + + try { + const auto current = ReadMutators(g_rules.rules); + const auto restored = bighead::RestoreOwnedMutatorBit(current, g_mutatorLease); + if (restored != current) { + WriteMutators(g_rules.rules, restored); + if (ReadMutators(g_rules.rules) != restored) { + LatchBigHeadFailure("Big Head mutator bit restore was not confirmed"); + return false; + } + } + g_rules = {}; + g_mutatorLease = {}; + g_hasRules = false; + g_hasMutatorLease = false; + return true; + } catch (...) { + LatchBigHeadFailure("Big Head mutator bit restore failed; native recovery remains pending"); + return false; + } +} + +bool EnsureRulesBit() noexcept { + void* const rules = CurrentRules(); + if (rules == nullptr) { + return false; + } + + if (g_hasRules && !SameRules(g_rules)) { + ForgetTargetsForMapChange(); + } + + try { + auto current = ReadMutators(rules); + if (!g_hasMutatorLease) { + g_rules = {rules}; + g_hasRules = true; + g_mutatorLease = bighead::BeginMutatorBitLease(current); + g_hasMutatorLease = true; + } + + if ((current & bighead::kBigHeadMutatorBit) == 0) { + if (!g_mutatorLease.owned) { + return false; + } + const auto enabled = bighead::EnableOwnedMutatorBit(current, g_mutatorLease); + WriteMutators(rules, enabled); + current = ReadMutators(rules); + if ((current & bighead::kBigHeadMutatorBit) == 0) { + return false; + } + } + return true; + } catch (...) { + return false; + } +} + +bool DetachResetHook() noexcept { + try { + if (g_resetHook.address == nullptr) { + return g_resetHook.handle == nullptr; + } + + const auto current = polyhook::FindDetour(g_resetHook.address); + if (current == nullptr) { + g_resetHook = {}; + return true; + } + if (current != g_resetHook.handle) { + LatchBigHeadFailure("Big Head reset detour identity changed; native recovery remains pending"); + return false; + } + + if (polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Post, BigHeadResetPost)) { + (void)polyhook::RemoveCallback(current, polyhook::CallbackType::Post, BigHeadResetPost); + if (polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Post, BigHeadResetPost)) { + LatchBigHeadFailure("Big Head reset callback removal failed; native recovery remains pending"); + return false; + } + } + + // PolyHook handles are process-wide. Leave another plugin's callback + // and detour alone after removing this provider's subscription. + if (polyhook::AreCallbacksRegistered(current)) { + g_resetHook = {}; + return true; + } + + (void)polyhook::UnhookDetour(g_resetHook.address); + if (polyhook::FindDetour(g_resetHook.address) != nullptr) { + LatchBigHeadFailure("Big Head reset detour removal failed; native recovery remains pending"); + return false; + } + g_resetHook = {}; + return true; + } catch (...) { + LatchBigHeadFailure("Big Head reset detour cleanup failed; native recovery remains pending"); + return false; + } +} + +bool EnsureResetHook() noexcept { + try { + void* const address = s2sdk::GetGameConfigSignature(GameConfig(), kResetSignature); + if (address == nullptr) { + return false; + } + if (g_resetHook.address != nullptr && g_resetHook.address != address && !DetachResetHook()) { + return false; + } + + auto handle = polyhook::FindDetour(address); + if (g_resetHook.handle != nullptr && handle != nullptr && handle != g_resetHook.handle) { + return false; + } + if (handle != nullptr && g_resetHook.handle == nullptr) { + // A pre-existing detour may have been created with HookDetour2's + // mid-hook ABI, which cannot provide the Pawn* parameter needed by + // this post-reset callback. Join only a detour this typed provider + // created and can identify. + return false; + } + if (handle == nullptr) { + g_resetHook.address = address; + g_resetHook.attempted = true; + const plg::vector arguments{polyhook::DataType::Pointer}; + handle = polyhook::HookDetour(address, + polyhook::DataType::Void, + arguments, + -1, + kResetHookName); + g_resetHook.handle = handle; + if (handle == nullptr) { + handle = polyhook::FindDetour(address); + if (handle != nullptr) { + g_resetHook.handle = handle; + } else { + g_resetHook = {}; + LatchBigHeadFailure("Big Head reset detour could not be installed"); + return false; + } + } + } else { + g_resetHook.address = address; + g_resetHook.handle = handle; + } + + if (!polyhook::IsCallbackRegistered(handle, polyhook::CallbackType::Post, BigHeadResetPost)) { + (void)polyhook::AddCallback(handle, polyhook::CallbackType::Post, BigHeadResetPost); + } + if (!polyhook::IsCallbackRegistered(handle, polyhook::CallbackType::Post, BigHeadResetPost)) { + (void)DetachResetHook(); + LatchBigHeadFailure("Big Head reset callback could not be installed"); + return false; + } + return true; + } catch (...) { + (void)DetachResetHook(); + LatchBigHeadFailure("Big Head reset hook initialization failed"); + return false; + } +} + +bool CleanupWhenEmpty() noexcept { + if (!g_targets.empty()) { + return true; + } + const bool bitClean = RestoreMutatorBit(); + const bool hookClean = DetachResetHook(); + // Keep the map-end recovery path until the GameRules lease is restored or + // the map boundary invalidates that lease. Unregistering here would leave + // a retained rules pointer vulnerable to address reuse on the next map. + const bool callbackClean = bitClean && UnregisterMapEndCallback(); + const bool clean = bitClean && hookClean && callbackClean; + if (clean) { + g_faulted = false; + g_faultLogged = false; + } + return clean; +} + +bool BigHeadSupportAvailable() noexcept { + if (g_faulted || !RequiredImportsAvailable() || !EnsureEngine() || !ResolveBigHeadLayout()) { + return false; + } + try { + void* const address = s2sdk::GetGameConfigSignature(GameConfig(), kResetSignature); + if (address == nullptr) { + return false; + } + const auto current = polyhook::FindDetour(address); + if (current != nullptr && (g_resetHook.address != address || g_resetHook.handle != current)) { + return false; + } + if (g_hasRules && g_hasMutatorLease && SameRules(g_rules) && !g_mutatorLease.owned && + (ReadMutators(g_rules.rules) & bighead::kBigHeadMutatorBit) == 0) { + LatchBigHeadFailure("Big Head mutator bit owned by another system was cleared"); + return false; + } + return true; + } catch (...) { + if (!g_targets.empty() || g_hasMutatorLease) { + LatchBigHeadFailure("Big Head support check failed while native state was active"); + } + return false; + } +} + +bool ClearTarget(std::int32_t pawnHandle) noexcept { + const auto found = std::find_if(g_targets.begin(), g_targets.end(), [pawnHandle](const auto& target) { + return target.pawnHandle == pawnHandle; + }); + if (found == g_targets.end()) { + return CleanupWhenEmpty(); + } + + try { + void* pawn = nullptr; + if (CurrentPawn(found->pawnHandle, pawn) && pawn == found->pawn) { + const float current = ReadScale(pawn); + if (bighead::StillOwnsScale(current, found->lastScale) && + !bighead::StillOwnsScale(current, found->originalScale)) { + WriteScale(pawn, found->originalScale); + if (!bighead::StillOwnsScale(ReadScale(pawn), found->originalScale)) { + LatchBigHeadFailure("Big Head scale restore was not confirmed; native recovery remains pending"); + return false; + } + } + } + g_targets.erase(found); + return CleanupWhenEmpty(); + } catch (...) { + LatchBigHeadFailure("Big Head scale restore failed; native recovery remains pending"); + return false; + } +} + +bool WriteTargetScale(BigHeadTarget& target, float scale) noexcept { + const float previousLast = target.lastScale; + try { + target.lastScale = scale; + WriteScale(target.pawn, scale); + const float observed = ReadScale(target.pawn); + if (bighead::StillOwnsScale(observed, scale)) { + target.lastScale = observed; + return true; + } + if (bighead::StillOwnsScale(observed, previousLast)) { + target.lastScale = previousLast; + } + return false; + } catch (...) { + try { + const float observed = ReadScale(target.pawn); + if (bighead::StillOwnsScale(observed, previousLast)) { + target.lastScale = previousLast; + } else if (bighead::StillOwnsScale(observed, scale)) { + target.lastScale = scale; + } + } catch (...) { + } + return false; + } +} + +bool SetTarget(std::int32_t pawnHandle, float scale) noexcept { + if (g_faulted || !bighead::IsValidScale(scale) || !RequiredImportsAvailable() || !EnsureEngine() || + !ResolveBigHeadLayout()) { + return false; + } + + void* pawn = nullptr; + if (!CurrentPawn(pawnHandle, pawn)) { + return false; + } + if (!RegisterMapEndCallback()) { + LatchBigHeadFailure("Big Head map-end recovery callback could not be registered"); + (void)CleanupWhenEmpty(); + return false; + } + if (!EnsureResetHook()) { + LatchBigHeadFailure("Big Head reset hook is unavailable"); + if (g_targets.empty()) { + (void)CleanupWhenEmpty(); + } + return false; + } + + if (!EnsureRulesBit()) { + LatchBigHeadFailure("Big Head mutator bit is unavailable or no longer owned"); + if (g_targets.empty()) { + (void)CleanupWhenEmpty(); + } + return false; + } + + try { + auto found = std::find_if(g_targets.begin(), g_targets.end(), [pawnHandle](const auto& target) { + return target.pawnHandle == pawnHandle; + }); + const float current = ReadScale(pawn); + bool inserted = false; + if (found == g_targets.end()) { + g_targets.push_back({pawnHandle, pawn, current, current}); + found = std::prev(g_targets.end()); + inserted = true; + } else if (found->pawn != pawn) { + // A serial-bearing handle must resolve to the same object. Treat a + // mismatch as a new identity only after relinquishing the old lease. + g_targets.erase(found); + g_targets.push_back({pawnHandle, pawn, current, current}); + found = std::prev(g_targets.end()); + inserted = true; + } else if (!bighead::StillOwnsScale(current, found->lastScale)) { + // A later explicit set rebases restoration onto the external value + // that currently owns the field instead of restoring a stale lease. + found->originalScale = current; + found->lastScale = current; + } + + if (WriteTargetScale(*found, scale)) { + return true; + } + LatchBigHeadFailure("Big Head scale write was not confirmed"); + if (inserted) { + void* currentPawn = nullptr; + if (!CurrentPawn(pawnHandle, currentPawn) || currentPawn != pawn || + !bighead::StillOwnsScale(ReadScale(pawn), found->lastScale)) { + g_targets.erase(found); + } + } + if (g_targets.empty()) { + (void)CleanupWhenEmpty(); + } + return false; + } catch (...) { + LatchBigHeadFailure("Big Head target registration failed; native recovery remains pending"); + if (g_targets.empty()) { + (void)CleanupWhenEmpty(); + } + return false; + } +} + +void BigHeadMapEndCallback() noexcept { + // Map end is the safe invalidation boundary for the old rules and Pawn + // identities. Do not write through GameRules here: an engine may already + // have reused that address for the next map. + ForgetTargetsForMapChange(); + if (!DetachResetHook()) { + LatchBigHeadFailure("Big Head map-end reset hook removal failed"); + return; + } + // The old map's leases are now discarded and its reset hook is detached; + // a prior map-scoped failure no longer blocks the next map. + g_faulted = false; + g_faultLogged = false; +} + +polyhook::ResultType BigHeadResetPost(polyhook::HookHandle, + polyhook::ParametersHandle parameters, + std::int32_t, + polyhook::ReturnHandle, + polyhook::CallbackType type) noexcept { + if (g_faulted || type != polyhook::CallbackType::Post || parameters == nullptr || g_targets.empty()) { + return polyhook::ResultType::Ignored; + } + + try { + void* const pawn = polyhook::GetArgumentPointer(parameters, 0); + if (pawn == nullptr) { + return polyhook::ResultType::Ignored; + } + const auto pawnHandle = HandleFromEntity(pawn); + void* currentPawn = nullptr; + if (!CurrentPawn(pawnHandle, currentPawn) || currentPawn != pawn) { + return polyhook::ResultType::Ignored; + } + + const auto found = std::find_if(g_targets.begin(), g_targets.end(), [pawnHandle](const auto& target) { + return target.pawnHandle == pawnHandle; + }); + if (found == g_targets.end() || found->pawn != pawn) { + return polyhook::ResultType::Ignored; + } + if (!SameRules(g_rules)) { + ForgetTargetsForMapChange(); + return polyhook::ResultType::Ignored; + } + + if (!EnsureRulesBit()) { + LatchBigHeadFailure("Big Head post-reset mutator bit is unavailable or no longer owned"); + return polyhook::ResultType::Ignored; + } + if (!WriteTargetScale(*found, found->lastScale)) { + LatchBigHeadFailure("Big Head post-reset scale write was not confirmed"); + } + } catch (...) { + LatchBigHeadFailure("Big Head post-reset recovery failed; native recovery remains pending"); + } + return polyhook::ResultType::Ignored; +} + +} // namespace + +bool ShutdownBigHead() noexcept { + try { + while (!g_targets.empty()) { + const auto pawnHandle = g_targets.front().pawnHandle; + const auto before = g_targets.size(); + if (!ClearTarget(pawnHandle) || g_targets.size() == before) { + return false; + } + } + + const bool bitClean = RestoreMutatorBit(); + const bool hookClean = DetachResetHook(); + const bool callbackClean = bitClean && UnregisterMapEndCallback(); + if (!bitClean || !hookClean || !callbackClean) { + return false; + } + g_layout = {}; + return true; + } catch (...) { + return false; + } +} + +} // namespace funrounds::native::detail + +extern "C" PLUGIN_API bool HasBigHeadScaleSupport() { + return funrounds::native::detail::BigHeadSupportAvailable(); +} + +extern "C" PLUGIN_API bool SetBigHeadScaleTarget(std::int32_t pawnHandle, float scale) { + return funrounds::native::detail::SetTarget(pawnHandle, scale); +} + +extern "C" PLUGIN_API bool ClearBigHeadScaleTarget(std::int32_t pawnHandle) { + return funrounds::native::detail::ClearTarget(pawnHandle); +} diff --git a/native/funrounds-native/src/bighead.hpp b/native/funrounds-native/src/bighead.hpp new file mode 100644 index 0000000..a8493fb --- /dev/null +++ b/native/funrounds-native/src/bighead.hpp @@ -0,0 +1,10 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#pragma once + +namespace funrounds::native::detail { + +bool ShutdownBigHead() noexcept; + +} // namespace funrounds::native::detail diff --git a/native/funrounds-native/src/bighead_policy.hpp b/native/funrounds-native/src/bighead_policy.hpp new file mode 100644 index 0000000..6500f3d --- /dev/null +++ b/native/funrounds-native/src/bighead_policy.hpp @@ -0,0 +1,43 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#pragma once + +#include +#include +#include + +namespace funrounds::native::bighead { + +constexpr std::uint32_t kBigHeadMutatorBit = 1U; + +struct MutatorBitLease { + bool originallySet{}; + bool owned{}; +}; + +constexpr MutatorBitLease BeginMutatorBitLease(std::uint32_t current) noexcept { + const bool originallySet = (current & kBigHeadMutatorBit) != 0; + return {originallySet, !originallySet}; +} + +constexpr std::uint32_t EnableOwnedMutatorBit(std::uint32_t current, MutatorBitLease lease) noexcept { + return lease.owned ? current | kBigHeadMutatorBit : current; +} + +constexpr std::uint32_t RestoreOwnedMutatorBit(std::uint32_t current, MutatorBitLease lease) noexcept { + if (!lease.owned || lease.originallySet || (current & kBigHeadMutatorBit) == 0) { + return current; + } + return current & ~kBigHeadMutatorBit; +} + +inline bool IsValidScale(float scale) noexcept { + return std::isfinite(scale) && scale > 0.0F; +} + +inline bool StillOwnsScale(float current, float lastWritten) noexcept { + return std::bit_cast(current) == std::bit_cast(lastWritten); +} + +} // namespace funrounds::native::bighead diff --git a/native/funrounds-native/src/burn.cpp b/native/funrounds-native/src/burn.cpp index 8ec919f..2055b60 100644 --- a/native/funrounds-native/src/burn.cpp +++ b/native/funrounds-native/src/burn.cpp @@ -26,12 +26,15 @@ constexpr char kEntityClass[] = "CBaseEntity"; constexpr char kPlayerPawnClass[] = "CBasePlayerPawn"; constexpr char kEntityFlameClass[] = "CEntityFlame"; constexpr std::string_view kEntityFlameName = "entityflame"; +constexpr char kIgniteVtableSlot[] = "CBaseEntity::IgnitePawn"; +constexpr std::int32_t kMaximumIgniteVtableSlot = 4095; + +std::int32_t g_igniteVtableSlot{-1}; +bool g_igniteSchemaReady{}; #if defined(_WIN32) -constexpr std::size_t kIgniteVtableSlot = 266; -extern "C" void FunRoundsInvokeIgnite(void* pawn, float duration, std::int32_t mode); +extern "C" void FunRoundsInvokeIgnite(void* pawn, float duration, std::int32_t mode, std::size_t slot); #elif defined(__linux__) && defined(__x86_64__) -constexpr std::size_t kIgniteVtableSlot = 267; #else #error "Player ignition is supported only on Windows x64 and Linux x64" #endif @@ -42,11 +45,35 @@ bool RequiredImportsAvailable() noexcept { __s2sdk_GetEntSchema2 != nullptr && __s2sdk_GetEntSchemaEnt2 != nullptr && __s2sdk_GetEntityClassname != nullptr && __s2sdk_GetMaxClients != nullptr && __s2sdk_IsClientInGame != nullptr && __s2sdk_PlayerSlotToEntHandle != nullptr && - __s2sdk_GetClientPawn != nullptr && __s2sdk_IsClientAlive != nullptr && - __s2sdk_RemoveEntity != nullptr; + __s2sdk_GetClientPawn != nullptr && __s2sdk_RemoveEntity != nullptr && + __s2sdk_GetGameConfigOffset != nullptr; +} + +bool ResolveIgniteVtableSlot() noexcept { + if (g_igniteVtableSlot >= 0) { + return true; + } + if (!funrounds::native::detail::EnsureEngine() || !__s2sdk_GetGameConfigOffset) { + return false; + } + + try { + const auto slot = s2sdk::GetGameConfigOffset(funrounds::native::detail::GameConfig(), kIgniteVtableSlot); + if (slot < 0 || slot > kMaximumIgniteVtableSlot) { + return false; + } + g_igniteVtableSlot = slot; + return true; + } catch (...) { + return false; + } } bool HasRequiredSchema() { + if (g_igniteSchemaReady) { + return true; + } + using funrounds::native::detail::SchemaField; using funrounds::native::detail::ServerSchema; @@ -82,9 +109,10 @@ bool HasRequiredSchema() { return false; }; - return hasField(kEntityClass, "m_iHealth") && hasField(kEntityClass, "m_lifeState") && + g_igniteSchemaReady = hasField(kEntityClass, "m_iHealth") && hasField(kEntityClass, "m_lifeState") && isHandleField(kEntityClass, "m_hEffectEntity") && isHandleField(kPlayerPawnClass, "m_hController") && isHandleField(kEntityFlameClass, "m_hEntAttached"); + return g_igniteSchemaReady; } bool IsEntityClass(std::int32_t handle, std::string_view expected) { @@ -119,7 +147,7 @@ bool IsCurrentLivePlayerPawn(std::int32_t pawnHandle, const auto maxClients = s2sdk::GetMaxClients(); for (std::int32_t slot = 0; slot < maxClients; ++slot) { if (s2sdk::IsClientInGame(slot) && s2sdk::PlayerSlotToEntHandle(slot) == controllerHandle && - s2sdk::GetClientPawn(slot) == expectedPawn && s2sdk::IsClientAlive(slot)) { + s2sdk::GetClientPawn(slot) == expectedPawn) { return true; } } @@ -155,22 +183,23 @@ void RemoveExactNewFlame(void* pawn, std::int32_t pawnHandle, std::int32_t effec void InvokeIgnite(void* pawn, float duration) { auto** const vtable = *reinterpret_cast(pawn); - if (vtable == nullptr || vtable[kIgniteVtableSlot] == nullptr) { + if (vtable == nullptr || g_igniteVtableSlot < 0 || vtable[g_igniteVtableSlot] == nullptr) { return; } #if defined(_WIN32) - FunRoundsInvokeIgnite(pawn, duration, kIgniteMode); + FunRoundsInvokeIgnite(pawn, duration, kIgniteMode, static_cast(g_igniteVtableSlot)); #else using IgniteMethod = void (*)(void*, std::int32_t, void*, __m128, float, double, float); constexpr double kEngineIgniteSentinel = 1.4044474254567505e306; - const auto method = reinterpret_cast(vtable[kIgniteVtableSlot]); + const auto method = reinterpret_cast(vtable[g_igniteVtableSlot]); method(pawn, kIgniteMode, nullptr, _mm_set_ss(duration), 0.0F, kEngineIgniteSentinel, std::numeric_limits::max()); #endif } std::int32_t TryIgnitePlayerImpl(std::int32_t pawnHandle, float duration) { - if (!RequiredImportsAvailable() || !HasRequiredSchema() || !std::isfinite(duration) || duration <= 0.0F || + if (!RequiredImportsAvailable() || !HasRequiredSchema() || !ResolveIgniteVtableSlot() || + !std::isfinite(duration) || duration <= 0.0F || pawnHandle == kInvalidHandle || !s2sdk::IsValidEntHandle(pawnHandle) || !s2sdk::IsEntityPlayerPawn(pawnHandle)) { return kInvalidHandle; @@ -220,6 +249,11 @@ std::int32_t TryIgnitePlayerImpl(std::int32_t pawnHandle, float duration) { } // namespace +void funrounds::native::detail::ResetBurnMetadata() noexcept { + g_igniteSchemaReady = false; + g_igniteVtableSlot = -1; +} + extern "C" PLUGIN_API std::int32_t TryIgnitePlayer(std::int32_t pawnHandle, float duration) { try { return TryIgnitePlayerImpl(pawnHandle, duration); diff --git a/native/funrounds-native/src/burn.hpp b/native/funrounds-native/src/burn.hpp index f94b012..2bc3e62 100644 --- a/native/funrounds-native/src/burn.hpp +++ b/native/funrounds-native/src/burn.hpp @@ -7,6 +7,10 @@ #include +namespace funrounds::native::detail { +void ResetBurnMetadata() noexcept; +} + // Ignites one exact live player pawn for `duration` seconds and returns the // newly attached entityflame full handle. Returns -1 when validation or the // engine effect check fails. This is a game-thread-only engine operation. diff --git a/native/funrounds-native/src/burn_ignite_win.asm b/native/funrounds-native/src/burn_ignite_win.asm index 6d77019..11e13c2 100644 --- a/native/funrounds-native/src/burn_ignite_win.asm +++ b/native/funrounds-native/src/burn_ignite_win.asm @@ -11,10 +11,10 @@ FunRoundsInvokeIgnite PROC FRAME .allocstack 48h .endprolog - ; Reviewed Win64 CBaseModelEntity::Ignite call shape: slot 266, mode in R8D. + ; Gamedata-provided vtable slot arrives in R9; mode remains in R8D. mov r10, rcx mov r11, qword ptr [r10] - mov rax, qword ptr [r11+850h] + mov rax, qword ptr [r11+r9*8] ; Win64 shadow space plus four engine stack arguments. mov qword ptr [rsp+20h], 0 diff --git a/native/funrounds-native/src/collision.cpp b/native/funrounds-native/src/collision.cpp index dc729dc..045ccd2 100644 --- a/native/funrounds-native/src/collision.cpp +++ b/native/funrounds-native/src/collision.cpp @@ -10,10 +10,40 @@ #include #include +#include "collision.hpp" #include "engine.hpp" +namespace funrounds::native::detail { namespace { +struct CollisionSchema { + SchemaField entityCollision{}; + SchemaField collisionAttribute{}; + SchemaField attributeGroup{}; + SchemaField collisionGroup{}; + bool ready{}; +}; + +CollisionSchema g_collisionSchema; + +bool ResolveCollisionSchema() noexcept { + if (g_collisionSchema.ready) { + return true; + } + + CollisionSchema resolved{}; + if (!ResolveSchemaField("CBaseEntity", "m_pCollision", sizeof(void*), resolved.entityCollision) || + !ResolveSchemaField("CCollisionProperty", "m_collisionAttribute", 0, resolved.collisionAttribute) || + !ResolveSchemaField("VPhysicsCollisionAttribute_t", "m_nCollisionGroup", sizeof(std::uint8_t), resolved.attributeGroup) || + !ResolveSchemaField("CCollisionProperty", "m_CollisionGroup", sizeof(std::uint8_t), resolved.collisionGroup)) { + return false; + } + + resolved.ready = true; + g_collisionSchema = resolved; + return true; +} + template void WriteField(void* destination, std::int32_t offset, const T& value) noexcept { std::memcpy(static_cast(destination) + offset, &value, sizeof(value)); @@ -21,6 +51,12 @@ void WriteField(void* destination, std::int32_t offset, const T& value) noexcept } // namespace +void ResetCollisionSchema() noexcept { + g_collisionSchema = {}; +} + +} // namespace funrounds::native::detail + extern "C" PLUGIN_API void SetEntityDefaultCollisionGroup(std::int32_t entityHandle) { try { using namespace funrounds::native::detail; @@ -32,14 +68,7 @@ extern "C" PLUGIN_API void SetEntityDefaultCollisionGroup(std::int32_t entityHan return; } - SchemaField collisionPointer{}; - SchemaField collisionAttribute{}; - SchemaField attributeGroup{}; - SchemaField collisionGroup{}; - if (!ResolveSchemaField("CBaseEntity", "m_pCollision", sizeof(void*), collisionPointer) || - !ResolveSchemaField("CCollisionProperty", "m_collisionAttribute", 0, collisionAttribute) || - !ResolveSchemaField("VPhysicsCollisionAttribute_t", "m_nCollisionGroup", sizeof(std::uint8_t), attributeGroup) || - !ResolveSchemaField("CCollisionProperty", "m_CollisionGroup", sizeof(std::uint8_t), collisionGroup)) { + if (!ResolveCollisionSchema()) { return; } @@ -53,16 +82,16 @@ extern "C" PLUGIN_API void SetEntityDefaultCollisionGroup(std::int32_t entityHan } void* property = nullptr; - std::memcpy(&property, static_cast(entity) + collisionPointer.offset, sizeof(property)); + std::memcpy(&property, static_cast(entity) + g_collisionSchema.entityCollision.offset, sizeof(property)); if (!property) { return; } constexpr auto defaultGroup = static_cast(COLLISION_GROUP_DEFAULT); - WriteField(static_cast(property) + collisionAttribute.offset, - attributeGroup.offset, + WriteField(static_cast(property) + g_collisionSchema.collisionAttribute.offset, + g_collisionSchema.attributeGroup.offset, defaultGroup); - WriteField(property, collisionGroup.offset, defaultGroup); + WriteField(property, g_collisionSchema.collisionGroup.offset, defaultGroup); reinterpret_cast(vtable[methodOffset])(entity); } catch (...) { } diff --git a/native/funrounds-native/src/collision.hpp b/native/funrounds-native/src/collision.hpp new file mode 100644 index 0000000..f471fc2 --- /dev/null +++ b/native/funrounds-native/src/collision.hpp @@ -0,0 +1,10 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#pragma once + +namespace funrounds::native::detail { + +void ResetCollisionSchema() noexcept; + +} // namespace funrounds::native::detail diff --git a/native/funrounds-native/src/damage.cpp b/native/funrounds-native/src/damage.cpp index d2a7d4e..1dfc094 100644 --- a/native/funrounds-native/src/damage.cpp +++ b/native/funrounds-native/src/damage.cpp @@ -1163,6 +1163,7 @@ bool ShutdownDamage() noexcept { const bool detached = DetachDamageHook(); if (detached) { ClearDamageSubscriptions(); + g_damage = {}; } return detached; } catch (...) { diff --git a/native/funrounds-native/src/engine.cpp b/native/funrounds-native/src/engine.cpp index c520b17..9904735 100644 --- a/native/funrounds-native/src/engine.cpp +++ b/native/funrounds-native/src/engine.cpp @@ -5,6 +5,9 @@ #include +#include +#include + namespace funrounds::native::detail { namespace { @@ -112,6 +115,53 @@ bool ResolveSchemaField(const char* className, return false; } +bool ResolvePlayerPawnComponentChain(SchemaField& result) noexcept { + auto* schema = ServerSchema(); + if (!schema) { + return false; + } + auto* componentClass = schema->FindDeclaredClass("CPlayerPawnComponent").Get(); + if (!componentClass || componentClass->m_nSize < 0 || + (componentClass->m_nFieldCount != 0 && !componentClass->m_pFields)) { + return false; + } + + for (std::uint16_t index = 0; index < componentClass->m_nFieldCount; ++index) { + const auto& candidate = componentClass->m_pFields[index]; + if (!candidate.m_pszName || std::strcmp(candidate.m_pszName, "__m_pChainEntity") != 0) { + continue; + } + if (!candidate.m_pType || candidate.m_pType->m_eTypeCategory != SCHEMA_TYPE_DECLARED_CLASS || + candidate.m_nSingleInheritanceOffset < 0) { + return false; + } + + const auto* declared = static_cast(candidate.m_pType); + const auto* chainClass = declared->m_pClassInfo; + if (!chainClass || !chainClass->m_pszName || + std::strcmp(chainClass->m_pszName, "CNetworkVarChainer") != 0 || + chainClass->m_nSize != static_cast(sizeof(CNetworkVarChainer))) { + return false; + } + + int fieldSize = 0; + std::uint8_t alignment = 0; + if (!candidate.m_pType->GetSizeAndAlignment(fieldSize, alignment) || + fieldSize != static_cast(sizeof(CNetworkVarChainer))) { + return false; + } + + const auto offset = static_cast(candidate.m_nSingleInheritanceOffset); + const auto objectSize = static_cast(componentClass->m_nSize); + if (offset > objectSize || sizeof(CNetworkVarChainer) > objectSize - offset) { + return false; + } + result = {candidate.m_nSingleInheritanceOffset, sizeof(CNetworkVarChainer)}; + return true; + } + return false; +} + void* EntityFromHandle(std::int32_t handle) noexcept { if (handle == -1 || !__s2sdk_EntHandleToEntPointer) { return nullptr; diff --git a/native/funrounds-native/src/engine.hpp b/native/funrounds-native/src/engine.hpp index 4dd6773..a51c610 100644 --- a/native/funrounds-native/src/engine.hpp +++ b/native/funrounds-native/src/engine.hpp @@ -23,6 +23,7 @@ void ShutdownEngine() noexcept; s2sdk::ConfigId GameConfig() noexcept; ISchemaSystemTypeScope* ServerSchema() noexcept; bool ResolveSchemaField(const char* className, const char* fieldName, std::size_t expectedSize, SchemaField& field) noexcept; +bool ResolvePlayerPawnComponentChain(SchemaField& field) noexcept; void* EntityFromHandle(std::int32_t handle) noexcept; std::int32_t HandleFromEntity(void* entity) noexcept; diff --git a/native/funrounds-native/src/ghost_radar.cpp b/native/funrounds-native/src/ghost_radar.cpp index 56df527..9c9ea93 100644 --- a/native/funrounds-native/src/ghost_radar.cpp +++ b/native/funrounds-native/src/ghost_radar.cpp @@ -97,14 +97,12 @@ class RepeatedSpottedUpdates final { return {&update, fields_.entityIndex}; } - void DeleteSubrange(int index, int count) { - for (int removed = 0; removed < count; ++removed) { - const int last = size() - 1; - for (int current = index; current < last; ++current) { - reflection_->SwapElements(&message_, fields_.updates, current, current + 1); - } - reflection_->RemoveLast(&message_, fields_.updates); - } + void Swap(int left, int right) { + reflection_->SwapElements(&message_, fields_.updates, left, right); + } + + void RemoveLast() { + reflection_->RemoveLast(&message_, fields_.updates); } private: diff --git a/native/funrounds-native/src/ghost_radar_policy.hpp b/native/funrounds-native/src/ghost_radar_policy.hpp index db561bf..36940a7 100644 --- a/native/funrounds-native/src/ghost_radar_policy.hpp +++ b/native/funrounds-native/src/ghost_radar_policy.hpp @@ -30,6 +30,21 @@ struct SpottedState { std::uint64_t spottedByMask{}; }; +inline constexpr std::uint8_t kSpottedByMaskLowWordChanged = 1U << 0; +inline constexpr std::uint8_t kSpottedByMaskHighWordChanged = 1U << 1; + +inline std::uint8_t ChangedSpottedByMaskWords(std::uint64_t before, std::uint64_t after) noexcept { + const std::uint64_t changed = before ^ after; + std::uint8_t changedWords = 0; + if (static_cast(changed) != 0) { + changedWords = static_cast(changedWords | kSpottedByMaskLowWordChanged); + } + if (static_cast(changed >> 32) != 0) { + changedWords = static_cast(changedWords | kSpottedByMaskHighWordChanged); + } + return changedWords; +} + template class NestedInvocationStack final { public: @@ -212,13 +227,21 @@ template std::size_t FilterEntityUpdates(RepeatedUpdates& updates, std::int32_t recipientSlot, const std::vector& sortedTargets) { + const int count = updates.size(); + int write = 0; std::size_t removed = 0; - for (int index = updates.size(); index > 0;) { - --index; - if (ShouldFilterEntityUpdate(updates.Get(index).entity_idx(), recipientSlot, sortedTargets)) { - updates.DeleteSubrange(index, 1); + for (int read = 0; read < count; ++read) { + if (ShouldFilterEntityUpdate(updates.Get(read).entity_idx(), recipientSlot, sortedTargets)) { ++removed; + continue; } + if (write != read) { + updates.Swap(write, read); + } + ++write; + } + while (updates.size() > write) { + updates.RemoveLast(); } return removed; } diff --git a/native/funrounds-native/src/ghost_radar_state.cpp b/native/funrounds-native/src/ghost_radar_state.cpp index eb5ae20..2ff7e02 100644 --- a/native/funrounds-native/src/ghost_radar_state.cpp +++ b/native/funrounds-native/src/ghost_radar_state.cpp @@ -76,8 +76,8 @@ void GhostRadarMapEndCallback() noexcept; bool RequiredImportsAvailable() noexcept { return __polyhook_FindVirtual2 != nullptr && __polyhook_AddCallback != nullptr && __polyhook_IsCallbackRegistered != nullptr && __polyhook_RemoveCallback != nullptr && - __s2sdk_QueryInterface != nullptr && __s2sdk_NetworkStateChanged != nullptr && - __s2sdk_OnMapEnd_Register != nullptr && __s2sdk_OnMapEnd_Unregister != nullptr && + __s2sdk_QueryInterface != nullptr && __s2sdk_OnMapEnd_Register != nullptr && + __s2sdk_OnMapEnd_Unregister != nullptr && __s2sdk_EntHandleToEntPointer != nullptr && __s2sdk_EntPointerToEntHandle != nullptr && __s2sdk_IsEntityPlayerPawn != nullptr; } @@ -167,10 +167,24 @@ void WriteSpottedByMask(void* pawn, std::uint64_t value) noexcept { } } -void MarkSpottedStateChanged(std::int32_t pawnHandle) noexcept { - try { - s2sdk::NetworkStateChanged(pawnHandle, kPawnClass, kSpottedStateField); - } catch (...) { +void MarkSpottedStateChanged(void* pawn, + bool spottedChanged, + std::uint8_t spottedByMaskChangedWords) noexcept { + if (pawn == nullptr) { + return; + } + + auto* const entity = reinterpret_cast(pawn); + if (spottedChanged) { + entity->NetworkStateChanged(NetworkStateChanged_t(static_cast(g_layout.spottedOffset))); + } + if ((spottedByMaskChangedWords & ghost_radar::kSpottedByMaskLowWordChanged) != 0) { + entity->NetworkStateChanged(NetworkStateChanged_t(static_cast(g_layout.spottedByMaskOffset))); + } + if ((spottedByMaskChangedWords & ghost_radar::kSpottedByMaskHighWordChanged) != 0) { + entity->NetworkStateChanged(NetworkStateChanged_t( + static_cast(g_layout.spottedByMaskOffset) + + static_cast(sizeof(std::uint32_t)))); } } @@ -224,24 +238,28 @@ void RestoreOwnedSpottedStates() noexcept { continue; } - bool changed = false; + bool spottedChanged = false; bool* const spotted = SpottedField(pawn); if (owned.ownsSpotted && spotted != nullptr && *spotted == owned.filteredSpotted && *spotted != owned.originalSpotted) { *spotted = owned.originalSpotted; - changed = true; + spottedChanged = true; } + bool spottedByMaskChanged = false; + std::uint8_t spottedByMaskChangedWords = 0; const std::uint64_t spottedByMask = ReadSpottedByMask(pawn); if (owned.ownsSpottedByMask && spottedByMask == owned.filteredSpottedByMask && spottedByMask != owned.originalSpottedByMask) { WriteSpottedByMask(pawn, owned.originalSpottedByMask); - changed = true; + spottedByMaskChanged = true; + spottedByMaskChangedWords = ghost_radar::ChangedSpottedByMaskWords( + spottedByMask, owned.originalSpottedByMask); } - if (changed) { - MarkSpottedStateChanged(owned.pawnHandle); - } + MarkSpottedStateChanged(pawn, + spottedChanged, + spottedByMaskChanged ? spottedByMaskChangedWords : 0); } g_ownedStates.clear(); } @@ -286,6 +304,8 @@ void ApplySpottedStateFilter() { continue; } + const std::uint8_t spottedByMaskChangedWords = ghost_radar::ChangedSpottedByMaskWords( + originalMask, filtered.spottedByMask); if (owned.ownsSpotted) { *spotted = filtered.spotted; } @@ -293,7 +313,9 @@ void ApplySpottedStateFilter() { WriteSpottedByMask(pawn, filtered.spottedByMask); } nextOwned.push_back(owned); - MarkSpottedStateChanged(pawnHandle); + MarkSpottedStateChanged(pawn, + owned.ownsSpotted, + owned.ownsSpottedByMask ? spottedByMaskChangedWords : 0); } g_ownedStates = std::move(nextOwned); } @@ -420,7 +442,7 @@ bool ShutdownGhostRadarStateFilter() noexcept { g_hooks.preWorldUpdateHook = nullptr; g_hooks.gameFrameHook = nullptr; g_hooks.server = nullptr; - g_hooks.ready.store(false, std::memory_order_release); + g_layout = {}; return true; } diff --git a/native/funrounds-native/src/ground_reverse.cpp b/native/funrounds-native/src/ground_reverse.cpp index 3dde6fb..f19fd5f 100644 --- a/native/funrounds-native/src/ground_reverse.cpp +++ b/native/funrounds-native/src/ground_reverse.cpp @@ -11,6 +11,8 @@ #include #include #include +#include +#include #include "engine.hpp" #include "entity_handle.hpp" @@ -22,7 +24,6 @@ namespace { constexpr char kCallsiteSignature[] = "FunRounds::GroundReverseAccelerationCallsite"; constexpr char kHookName[] = "FunRounds::GroundReverseAccelerationCallsite"; constexpr std::int32_t kInvalidHandle = -1; -constexpr std::int32_t kMovementPawnOffset = 56; constexpr float kDefaultAcceleration = 5.5F; #if defined(_WIN32) @@ -37,6 +38,7 @@ struct GroundReverseState { void* address{}; polyhook::HookHandle hook{}; SchemaField pawnController{}; + SchemaField movementOwnerChain{}; bool schemaReady{}; bool enabled{}; float acceleration{kDefaultAcceleration}; @@ -71,7 +73,8 @@ bool ResolveGroundIdentitySchema() noexcept { if (g_state.schemaReady) { return true; } - if (!ResolveSchemaField("CBasePlayerPawn", "m_hController", sizeof(std::uint32_t), g_state.pawnController)) { + if (!ResolveSchemaField("CBasePlayerPawn", "m_hController", sizeof(std::uint32_t), g_state.pawnController) || + !ResolvePlayerPawnComponentChain(g_state.movementOwnerChain)) { return false; } g_state.schemaReady = true; @@ -95,7 +98,9 @@ bool ResolveCurrentControl(void* movement, return false; } - void* pawn = ReadField(movement, kMovementPawnOffset); + auto* const movementOwner = reinterpret_cast( + static_cast(movement) + g_state.movementOwnerChain.offset); + void* pawn = movementOwner->GetObject(); pawnHandle = HandleFromEntity(pawn); if (!pawn || pawnHandle == kInvalidHandle || !IsPlayerPawn(pawnHandle) || HandleFromEntity(pawn) != pawnHandle || EntityFromHandle(pawnHandle) != pawn) { @@ -110,42 +115,29 @@ bool ResolveCurrentControl(void* movement, return false; } - std::int32_t matchedSlots = 0; - std::int32_t matchingSlot = -1; - void* matchingPawn = nullptr; - bool matchingClientInGame = false; - bool matchingFakeClient = false; const auto maxClients = s2sdk::GetMaxClients(); if (maxClients <= 0) { return false; } - for (std::int32_t slot = 0; slot < maxClients; ++slot) { - if (!s2sdk::IsClientInGame(slot) || s2sdk::PlayerSlotToEntHandle(slot) != currentControllerHandle) { - continue; - } - void* const slotPawn = s2sdk::GetClientPawn(slot); - if (!slotPawn || slotPawn != pawn || HandleFromEntity(slotPawn) != pawnHandle) { - continue; - } - ++matchedSlots; - matchingSlot = slot; - matchingPawn = slotPawn; - matchingClientInGame = true; - matchingFakeClient = s2sdk::IsFakeClient(slot); + const auto controllerRefHandle = static_cast(controller)->GetRefEHandle(); + const std::int32_t slot = controllerRefHandle.GetEntryIndex() - 1; + if (controllerRefHandle.ToInt() != ToNativeHandle(currentControllerHandle) || slot < 0 || slot >= maxClients || + !s2sdk::IsClientInGame(slot) || s2sdk::PlayerSlotToEntHandle(slot) != currentControllerHandle) { + return false; } - - if (matchingSlot == -1) { + void* const slotPawn = s2sdk::GetClientPawn(slot); + if (slotPawn != pawn || HandleFromEntity(slotPawn) != pawnHandle) { return false; } const GroundControlIdentity identity{ .pawnHandle = pawnHandle, .currentControllerHandle = currentControllerHandle, - .slotControllerHandle = s2sdk::PlayerSlotToEntHandle(matchingSlot), + .slotControllerHandle = currentControllerHandle, .pawn = pawn, - .slotPawn = matchingPawn, - .exactSlotMatches = matchedSlots, - .clientInGame = matchingClientInGame, - .fakeClient = matchingFakeClient, + .slotPawn = slotPawn, + .exactSlotMatches = 1, + .clientInGame = true, + .fakeClient = s2sdk::IsFakeClient(slot), }; source = ClassifyGroundControlSource(identity); return source != GroundControlSource::Unresolved; @@ -266,7 +258,11 @@ bool SetGroundReverseActive(bool active, float acceleration) noexcept { } bool ShutdownGroundReverse() noexcept { - return RemoveGroundHook(); + if (!RemoveGroundHook()) { + return false; + } + g_state = {}; + return true; } namespace { diff --git a/native/funrounds-native/src/interactions.cpp b/native/funrounds-native/src/interactions.cpp index 8756f68..a0e6d38 100644 --- a/native/funrounds-native/src/interactions.cpp +++ b/native/funrounds-native/src/interactions.cpp @@ -4,6 +4,7 @@ #include "interactions.hpp" #include +#include #include #include #include @@ -115,7 +116,8 @@ polyhook::ResultType ChickenFollowUsePre(polyhook::HookHandle, bool HookImportsAvailable() noexcept { return __polyhook_HookDetour && __polyhook_FindDetour && __polyhook_AddCallback && - __polyhook_IsCallbackRegistered && __polyhook_RemoveCallback && __polyhook_UnhookDetour && + __polyhook_IsCallbackRegistered && __polyhook_AreCallbacksRegistered && + __polyhook_RemoveCallback && __polyhook_UnhookDetour && __polyhook_GetArgumentPointer && __polyhook_GetArgumentFloat && __polyhook_GetArgumentInt32 && __polyhook_GetReturnPointer && __polyhook_SetReturnBool && __s2sdk_GetGameConfigSignature && __s2sdk_GetGameConfigOffset && __s2sdk_GetSchemaOffset && __s2sdk_GetEntSchema2 && __s2sdk_GetEntSchemaEnt2 && @@ -130,7 +132,16 @@ bool ChickenFollowImportsAvailable() noexcept { return HookImportsAvailable(); } -bool ResolveUseTargetMetadata() noexcept { +bool ResolvePawnControllerSchema(std::int32_t& offset) noexcept { + offset = -1; + if (!EnsureEngine() || !__s2sdk_GetSchemaOffset) { + return false; + } + offset = s2sdk::GetSchemaOffset(plg::string("CBasePlayerPawn"), plg::string("m_hController")); + return offset >= 0; +} + +bool ResolveUseTargetMetadata(std::int32_t& pawnControllerOffset) noexcept { if (!EnsureEngine() || !__s2sdk_GetGameConfigOffset || !__s2sdk_GetSchemaOffset || !__s2sdk_GetEntSchema2) { return false; } @@ -140,13 +151,15 @@ bool ResolveUseTargetMetadata() noexcept { if (g_useTarget.committedTargetOffset < 0) { return false; } - if (g_useTarget.schemaCount == 0) { - for (std::size_t index = 0; index < kPawnClasses.size(); ++index) { - const auto className = kPawnClasses[index]; - const auto offset = s2sdk::GetSchemaOffset(plg::string(className), plg::string("m_pUseServices")); - if (offset >= 0) { - g_useTarget.schemaClassIndices[g_useTarget.schemaCount++] = index; - } + if (!ResolvePawnControllerSchema(pawnControllerOffset)) { + return false; + } + g_useTarget.schemaCount = 0; + for (std::size_t index = 0; index < kPawnClasses.size(); ++index) { + const auto className = kPawnClasses[index]; + const auto offset = s2sdk::GetSchemaOffset(plg::string(className), plg::string("m_pUseServices")); + if (offset >= 0) { + g_useTarget.schemaClassIndices[g_useTarget.schemaCount++] = index; } } return g_useTarget.schemaCount != 0; @@ -159,13 +172,12 @@ void* Signature(std::string_view name) noexcept { return s2sdk::GetGameConfigSignature(GameConfig(), plg::string(name)); } -bool SlotOwnsPawn(std::int32_t slot, void* pawn) noexcept { +bool SlotOwnsPawn(std::int32_t slot, void* pawn, std::int32_t pawnControllerOffset) noexcept { if (!pawn || !s2sdk::IsClientInGame(slot) || s2sdk::GetClientPawn(slot) != pawn) { return false; } const auto controller = s2sdk::PlayerSlotToEntHandle(slot); - if (!s2sdk::IsValidEntHandle(controller) || - s2sdk::GetSchemaOffset(plg::string("CBasePlayerPawn"), plg::string("m_hController")) < 0) { + if (!s2sdk::IsValidEntHandle(controller) || pawnControllerOffset < 0) { return false; } // A stale BOT slot may retain m_hPawn after takeover. The pawn's reverse link is authoritative. @@ -173,7 +185,8 @@ bool SlotOwnsPawn(std::int32_t slot, void* pawn) noexcept { } bool ResolveUseServiceOwner(void* services, std::int32_t& pawnHandle, std::int32_t& slot) noexcept { - if (!services || !ResolveUseTargetMetadata()) { + std::int32_t pawnControllerOffset{-1}; + if (!services || !ResolveUseTargetMetadata(pawnControllerOffset)) { return false; } std::size_t matches = 0; @@ -188,7 +201,7 @@ bool ResolveUseServiceOwner(void* services, std::int32_t& pawnHandle, std::int32 void* const pawn = s2sdk::GetClientPawn(candidateSlot); const auto candidateHandle = HandleFromEntity(pawn); if (!pawn || candidateHandle == kInvalidHandle || !IsPlayerPawn(candidateHandle) || - EntityFromHandle(candidateHandle) != pawn || !SlotOwnsPawn(candidateSlot, pawn)) { + EntityFromHandle(candidateHandle) != pawn || !SlotOwnsPawn(candidateSlot, pawn, pawnControllerOffset)) { continue; } bool serviceMatches = false; @@ -207,7 +220,7 @@ bool ResolveUseServiceOwner(void* services, std::int32_t& pawnHandle, std::int32 slot = candidateSlot; } } - return matches == 1 && SlotOwnsPawn(slot, EntityFromHandle(pawnHandle)); + return matches == 1 && SlotOwnsPawn(slot, EntityFromHandle(pawnHandle), pawnControllerOffset); } bool UseButtonDown(std::int32_t slot) noexcept { @@ -236,6 +249,10 @@ bool ResolveHealthshotOwner(void* weapon, void* pawn, std::int32_t& pawnHandle, if (resolvedPawn == kInvalidHandle || !IsPlayerPawn(resolvedPawn) || EntityFromHandle(resolvedPawn) != pawn) { return false; } + std::int32_t pawnControllerOffset{-1}; + if (!ResolvePawnControllerSchema(pawnControllerOffset)) { + return false; + } std::size_t ownerMatches = 0; std::int32_t matchedSlot = -1; std::int32_t matchedWeapon = kInvalidHandle; @@ -244,7 +261,7 @@ bool ResolveHealthshotOwner(void* weapon, void* pawn, std::int32_t& pawnHandle, return false; } for (std::int32_t candidateSlot = 0; candidateSlot < maximum; ++candidateSlot) { - if (!SlotOwnsPawn(candidateSlot, pawn)) { + if (!SlotOwnsPawn(candidateSlot, pawn, pawnControllerOffset)) { continue; } std::size_t weaponMatches = 0; @@ -264,7 +281,7 @@ bool ResolveHealthshotOwner(void* weapon, void* pawn, std::int32_t& pawnHandle, } } if (ownerMatches != 1 || matchedSlot < 0 || matchedWeapon == kInvalidHandle || - !SlotOwnsPawn(matchedSlot, pawn) || HandleFromEntity(pawn) != resolvedPawn) { + !SlotOwnsPawn(matchedSlot, pawn, pawnControllerOffset) || HandleFromEntity(pawn) != resolvedPawn) { return false; } pawnHandle = resolvedPawn; @@ -294,6 +311,11 @@ bool RemoveUseTargetHook() noexcept { if (polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Post, UseTargetPost)) { return false; } + g_useTarget.callbackInstalled = false; + } + if (polyhook::AreCallbacksRegistered(current)) { + g_useTarget = {}; + return true; } if (!polyhook::UnhookDetour(g_useTarget.address) && polyhook::FindDetour(g_useTarget.address)) { return false; @@ -336,6 +358,11 @@ bool RemoveHealthshotHooks() noexcept { } } installed = false; + if (polyhook::AreCallbacksRegistered(current)) { + hook = nullptr; + address = nullptr; + return true; + } if (!polyhook::UnhookDetour(address) && polyhook::FindDetour(address)) { return false; } @@ -357,7 +384,14 @@ bool RemoveHealthshotHooks() noexcept { polyhook::CallbackType::Post, HealthshotEffectPost, g_healthshot.effectCallbackInstalled) && clean; if (clean) { - g_healthshot = {}; + if (!g_healthshot.canUseHook && !g_healthshot.effectHook) { + g_healthshot = {}; + } else { + g_healthshot.canUseCallback = nullptr; + g_healthshot.effectCallback = nullptr; + g_healthshot.canUseOwner = nullptr; + g_healthshot.effectOwner = nullptr; + } } return clean; } @@ -398,6 +432,10 @@ bool RemoveChickenFollowUseHook() noexcept { } g_chickenFollowUse.callbackInstalled = false; } + if (polyhook::AreCallbacksRegistered(current)) { + g_chickenFollowUse = {}; + return true; + } if (!polyhook::UnhookDetour(g_chickenFollowUse.address) && polyhook::FindDetour(g_chickenFollowUse.address)) { return false; @@ -412,33 +450,39 @@ bool RemoveChickenFollowUseHook() noexcept { } } -bool InstallChickenFollowUseHook() { - if (!ChickenFollowImportsAvailable()) { - return false; - } - const auto address = Signature(kChickenFollowUseSignature); +bool InstallChickenFollowUseHookAt(void* address) { if (!address || (g_chickenFollowUse.address && g_chickenFollowUse.address != address)) { return false; } if (g_chickenFollowUse.hook) { - if (polyhook::FindDetour(address) != g_chickenFollowUse.hook || - !polyhook::IsCallbackRegistered(g_chickenFollowUse.hook, polyhook::CallbackType::Pre, - ChickenFollowUsePre)) { + if (polyhook::FindDetour(address) != g_chickenFollowUse.hook) { return false; } + if (!polyhook::IsCallbackRegistered(g_chickenFollowUse.hook, polyhook::CallbackType::Pre, + ChickenFollowUsePre)) { + (void)polyhook::AddCallback(g_chickenFollowUse.hook, polyhook::CallbackType::Pre, + ChickenFollowUsePre); + g_chickenFollowUse.callbackInstalled = polyhook::IsCallbackRegistered( + g_chickenFollowUse.hook, polyhook::CallbackType::Pre, ChickenFollowUsePre); + if (!g_chickenFollowUse.callbackInstalled) { + return false; + } + } else { + g_chickenFollowUse.callbackInstalled = true; + } g_chickenFollowUse.active = true; return true; } - if (polyhook::FindDetour(address)) { - return false; - } - // Preserve the full CChickenChickenUse ABI: (this, const EntityUseInput_t*) -> void. const std::array arguments{polyhook::DataType::Pointer, polyhook::DataType::Pointer}; g_chickenFollowUse.address = address; - g_chickenFollowUse.hook = polyhook::HookDetour( - address, polyhook::DataType::Void, plg::vector(arguments.begin(), arguments.end()), -1, - plg::string(kChickenFollowUseHookName)); + g_chickenFollowUse.hook = polyhook::FindDetour(address); + if (!g_chickenFollowUse.hook) { + g_chickenFollowUse.hook = polyhook::HookDetour( + address, polyhook::DataType::Void, + plg::vector(arguments.begin(), arguments.end()), -1, + plg::string(kChickenFollowUseHookName)); + } if (!g_chickenFollowUse.hook) { (void)RemoveChickenFollowUseHook(); return false; @@ -459,8 +503,16 @@ bool InstallChickenFollowUseHook() { } } +bool InstallChickenFollowUseHook() { + if (!ChickenFollowImportsAvailable()) { + return false; + } + return InstallChickenFollowUseHookAt(Signature(kChickenFollowUseSignature)); +} + bool InstallUseTargetHook(UseTargetCallback callback) { - if (!callback || !HookImportsAvailable() || !ResolveUseTargetMetadata()) { + std::int32_t pawnControllerOffset{-1}; + if (!callback || !HookImportsAvailable() || !ResolveUseTargetMetadata(pawnControllerOffset)) { return false; } const auto address = Signature(kUseTargetSignature); @@ -468,21 +520,30 @@ bool InstallUseTargetHook(UseTargetCallback callback) { return false; } if (g_useTarget.hook) { - if (g_useTarget.owner != callback || polyhook::FindDetour(address) != g_useTarget.hook || - !polyhook::IsCallbackRegistered(g_useTarget.hook, polyhook::CallbackType::Post, UseTargetPost)) { + if (g_useTarget.owner != callback || polyhook::FindDetour(address) != g_useTarget.hook) { return false; } + if (!polyhook::IsCallbackRegistered(g_useTarget.hook, polyhook::CallbackType::Post, UseTargetPost)) { + (void)polyhook::AddCallback(g_useTarget.hook, polyhook::CallbackType::Post, UseTargetPost); + g_useTarget.callbackInstalled = polyhook::IsCallbackRegistered( + g_useTarget.hook, polyhook::CallbackType::Post, UseTargetPost); + if (!g_useTarget.callbackInstalled) { + return false; + } + } else { + g_useTarget.callbackInstalled = true; + } g_useTarget.callback = callback; return true; } - if (polyhook::FindDetour(address)) { - return false; - } const std::array arguments{polyhook::DataType::Pointer, polyhook::DataType::Float}; g_useTarget.address = address; - g_useTarget.hook = polyhook::HookDetour(address, polyhook::DataType::Pointer, - plg::vector(arguments.begin(), arguments.end()), -1, - plg::string(kUseTargetHookName)); + g_useTarget.hook = polyhook::FindDetour(address); + if (!g_useTarget.hook) { + g_useTarget.hook = polyhook::HookDetour(address, polyhook::DataType::Pointer, + plg::vector(arguments.begin(), arguments.end()), -1, + plg::string(kUseTargetHookName)); + } if (!g_useTarget.hook) { (void)RemoveUseTargetHook(); return false; @@ -515,33 +576,35 @@ bool InstallHealthshotHooks(HealthshotCanUseCallback canUse, HealthshotEffectCal (g_healthshot.effectAddress && g_healthshot.effectAddress != effectAddress)) { return false; } - if (g_healthshot.canUseHook || g_healthshot.effectHook) { - if (g_healthshot.canUseOwner != canUse || g_healthshot.effectOwner != effect || - polyhook::FindDetour(canUseAddress) != g_healthshot.canUseHook || - polyhook::FindDetour(effectAddress) != g_healthshot.effectHook || - !polyhook::IsCallbackRegistered(g_healthshot.canUseHook, polyhook::CallbackType::Pre, HealthshotCanUsePre) || - !polyhook::IsCallbackRegistered(g_healthshot.effectHook, polyhook::CallbackType::Post, HealthshotEffectPost)) { - return false; - } - g_healthshot.canUseCallback = canUse; - g_healthshot.effectCallback = effect; - return true; - } - if (polyhook::FindDetour(canUseAddress) || polyhook::FindDetour(effectAddress)) { + if ((g_healthshot.canUseOwner && g_healthshot.canUseOwner != canUse) || + (g_healthshot.effectOwner && g_healthshot.effectOwner != effect)) { return false; } const std::array canUseArguments{polyhook::DataType::Pointer, polyhook::DataType::Pointer}; g_healthshot.canUseAddress = canUseAddress; - g_healthshot.canUseHook = polyhook::HookDetour(canUseAddress, polyhook::DataType::Bool, - plg::vector(canUseArguments.begin(), canUseArguments.end()), -1, - plg::string(kHealthshotCanUseHookName)); + if (g_healthshot.canUseHook) { + if (polyhook::FindDetour(canUseAddress) != g_healthshot.canUseHook) { + return false; + } + } else { + g_healthshot.canUseHook = polyhook::FindDetour(canUseAddress); + if (!g_healthshot.canUseHook) { + g_healthshot.canUseHook = polyhook::HookDetour(canUseAddress, polyhook::DataType::Bool, + plg::vector(canUseArguments.begin(), canUseArguments.end()), -1, + plg::string(kHealthshotCanUseHookName)); + } + } if (!g_healthshot.canUseHook) { (void)RemoveHealthshotHooks(); return false; } try { - (void)polyhook::AddCallback(g_healthshot.canUseHook, polyhook::CallbackType::Pre, HealthshotCanUsePre); + if (!polyhook::IsCallbackRegistered(g_healthshot.canUseHook, + polyhook::CallbackType::Pre, HealthshotCanUsePre)) { + (void)polyhook::AddCallback(g_healthshot.canUseHook, polyhook::CallbackType::Pre, + HealthshotCanUsePre); + } g_healthshot.canUseCallbackInstalled = polyhook::IsCallbackRegistered( g_healthshot.canUseHook, polyhook::CallbackType::Pre, HealthshotCanUsePre); if (!g_healthshot.canUseCallbackInstalled) { @@ -558,14 +621,28 @@ bool InstallHealthshotHooks(HealthshotCanUseCallback canUse, HealthshotEffectCal #error "Healthshot interaction hook supports Windows x64 and Linux x64 only" #endif g_healthshot.effectAddress = effectAddress; - g_healthshot.effectHook = polyhook::HookDetour(effectAddress, polyhook::DataType::Void, - plg::vector(effectArguments.begin(), effectArguments.end()), -1, - plg::string(kHealthshotEffectHookName)); + if (g_healthshot.effectHook) { + if (polyhook::FindDetour(effectAddress) != g_healthshot.effectHook) { + (void)RemoveHealthshotHooks(); + return false; + } + } else { + g_healthshot.effectHook = polyhook::FindDetour(effectAddress); + if (!g_healthshot.effectHook) { + g_healthshot.effectHook = polyhook::HookDetour(effectAddress, polyhook::DataType::Void, + plg::vector(effectArguments.begin(), effectArguments.end()), -1, + plg::string(kHealthshotEffectHookName)); + } + } if (!g_healthshot.effectHook) { (void)RemoveHealthshotHooks(); return false; } - (void)polyhook::AddCallback(g_healthshot.effectHook, polyhook::CallbackType::Post, HealthshotEffectPost); + if (!polyhook::IsCallbackRegistered(g_healthshot.effectHook, + polyhook::CallbackType::Post, HealthshotEffectPost)) { + (void)polyhook::AddCallback(g_healthshot.effectHook, polyhook::CallbackType::Post, + HealthshotEffectPost); + } g_healthshot.effectCallbackInstalled = polyhook::IsCallbackRegistered( g_healthshot.effectHook, polyhook::CallbackType::Post, HealthshotEffectPost); if (!g_healthshot.effectCallbackInstalled) { @@ -689,11 +766,14 @@ polyhook::ResultType ChickenFollowUsePre(polyhook::HookHandle, } } + } // namespace + bool HasUseTargetSupport() noexcept { try { - return HookImportsAvailable() && ResolveUseTargetMetadata() && Signature(kUseTargetSignature); + std::int32_t pawnControllerOffset{-1}; + return HookImportsAvailable() && ResolveUseTargetMetadata(pawnControllerOffset) && Signature(kUseTargetSignature); } catch (...) { return false; } diff --git a/native/funrounds-native/src/interactions.hpp b/native/funrounds-native/src/interactions.hpp index 9e2b183..4356e65 100644 --- a/native/funrounds-native/src/interactions.hpp +++ b/native/funrounds-native/src/interactions.hpp @@ -22,6 +22,7 @@ bool UnhookHealthshot(HealthshotCanUseCallback canUse, HealthshotEffectCallback bool HasChickenFollowBlockSupport() noexcept; bool SetChickenFollowBlocking(bool active) noexcept; + bool ShutdownInteractions() noexcept; } // namespace funrounds::native::detail diff --git a/native/funrounds-native/src/linux_image.hpp b/native/funrounds-native/src/linux_image.hpp new file mode 100644 index 0000000..4449315 --- /dev/null +++ b/native/funrounds-native/src/linux_image.hpp @@ -0,0 +1,36 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#pragma once + +#include +#include +#include + +namespace funrounds::native::detail { + +inline constexpr std::uint32_t kPtLoad = 1; + +template +bool ComputeMappedImageEnd(const ProgramHeader* headers, + std::size_t count, + std::uint64_t& imageEnd) noexcept { + imageEnd = 0; + for (std::size_t index = 0; index < count; ++index) { + const ProgramHeader& header = headers[index]; + if (header.p_type != kPtLoad) { + continue; + } + if (header.p_memsz < header.p_filesz || + header.p_vaddr > std::numeric_limits::max() - header.p_memsz) { + return false; + } + const std::uint64_t end = header.p_vaddr + header.p_memsz; + if (end > imageEnd) { + imageEnd = end; + } + } + return imageEnd != 0; +} + +} // namespace funrounds::native::detail diff --git a/native/funrounds-native/src/movement_trace.cpp b/native/funrounds-native/src/movement_trace.cpp new file mode 100644 index 0000000..04dc05f --- /dev/null +++ b/native/funrounds-native/src/movement_trace.cpp @@ -0,0 +1,420 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#include "movement_trace.hpp" + +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#elif defined(__linux__) +#include +#include +#else +#error "Player movement hull tracing is supported on Windows x64 and Linux x64 only" +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include "engine.hpp" +#include "entity_handle.hpp" +#if defined(__linux__) +#include "linux_image.hpp" +#endif + +namespace funrounds::native::detail { +namespace { + +constexpr char kSignature[] = "FunRounds::PlayerMovementTraceShape"; +constexpr std::int32_t kInvalidHandle = -1; +constexpr std::uint64_t kPlayersolidMask = 798737; + +constexpr std::uintptr_t kWindowsTraceShapeRva = 0xC2F3C0; +constexpr std::uintptr_t kWindowsReceiverSlotRva = 0x1E1E260; +constexpr std::uintptr_t kWindowsReceiverRva = 0x218AE50; +constexpr std::uint32_t kWindowsPeTimestamp = 0x6AEBC501; +constexpr std::uint32_t kWindowsImageSize = 0x257C000; +constexpr std::uintptr_t kLinuxTraceShapeRva = 0x173B540; +constexpr std::uintptr_t kLinuxReceiverSlotRva = 0x27A47F0; +constexpr std::uintptr_t kLinuxReceiverRva = 0x29DAA00; +constexpr unsigned char kLinuxBuildId[] = { + 0x5E, 0xA0, 0xE4, 0x82, 0xB4, 0x6E, 0xB7, 0x1C, 0x4F, 0x96, + 0x15, 0xC4, 0x8B, 0x34, 0xDD, 0xC3, 0x6F, 0x55, 0xCA, 0x40, +}; + +using TraceShapeFn = bool (*)(void*, const Ray_t&, const Vector&, const Vector&, CTraceFilter*, CGameTrace*); + +struct TraceSchema { + SchemaField pawnCollision{}; + SchemaField pawnOwner{}; + SchemaField collisionAttributes{}; + SchemaField interactsAs{}; + SchemaField interactsExclude{}; + bool ready{}; +}; + +struct Query { + TraceShapeFn call{}; + void* receiver{}; + + explicit operator bool() const noexcept { + return call != nullptr && receiver != nullptr; + } +}; + +struct QueryAddresses { + TraceShapeFn call{}; + void** receiverSlot{}; + void* expectedReceiver{}; + + explicit operator bool() const noexcept { + return call != nullptr && receiverSlot != nullptr && expectedReceiver != nullptr; + } +}; + +TraceSchema g_traceSchema; +QueryAddresses g_queryAddresses; + +static_assert(sizeof(Ray_t) == 0x30); +static_assert(offsetof(Ray_t, m_eType) == 0x28); +static_assert(sizeof(CGameTrace) == 0xC0); +static_assert(offsetof(CGameTrace, m_pEnt) == 0x08); +static_assert(offsetof(CGameTrace, m_vStartPos) == 0x78); +static_assert(offsetof(CGameTrace, m_vEndPos) == 0x84); +static_assert(offsetof(CGameTrace, m_vHitNormal) == 0x90); +static_assert(offsetof(CGameTrace, m_flFraction) == 0xAC); +static_assert(offsetof(CGameTrace, m_eRayType) == 0xBA); +static_assert(offsetof(CGameTrace, m_bStartInSolid) == 0xBB); +static_assert(offsetof(CTraceFilter, m_nInteractsWith) == 0x08); +#if defined(_WIN32) +static_assert(sizeof(CTraceFilter) == 0x48); +static_assert(offsetof(CTraceFilter, m_bIterateEntities) == 0x40); +#else +// Itanium reuses RnQueryAttr_t tail padding; this is the observed Linux layout. +static_assert(sizeof(CTraceFilter) == 0x40); +static_assert(offsetof(CTraceFilter, m_bIterateEntities) == 0x3A); +#endif +static_assert(MASK_PLAYERSOLID == kPlayersolidMask); + +bool Finite(const Vector& value) noexcept { + return std::isfinite(value.x) && std::isfinite(value.y) && std::isfinite(value.z); +} + +bool WithinImage(std::uintptr_t base, std::size_t imageSize, std::uintptr_t rva, std::size_t length) noexcept { + return rva <= imageSize && length <= imageSize - rva && base <= std::numeric_limits::max() - rva; +} + +#if defined(_WIN32) +bool CurrentImageBase(void* function, std::uintptr_t& base, std::size_t& imageSize) noexcept { + MEMORY_BASIC_INFORMATION memory{}; + if (!function || VirtualQuery(function, &memory, sizeof(memory)) != sizeof(memory) || + memory.Type != MEM_IMAGE || !memory.AllocationBase) { + return false; + } + + base = reinterpret_cast(memory.AllocationBase); + const auto* dos = reinterpret_cast(base); + if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew <= 0 || dos->e_lfanew > 0x1000) { + return false; + } + + const auto* nt = reinterpret_cast(base + static_cast(dos->e_lfanew)); + if (nt->Signature != IMAGE_NT_SIGNATURE || nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64 || + nt->FileHeader.TimeDateStamp != kWindowsPeTimestamp || nt->OptionalHeader.SizeOfImage != kWindowsImageSize) { + return false; + } + + imageSize = nt->OptionalHeader.SizeOfImage; + return true; +} +#else +bool MatchesLinuxBuildId(std::uintptr_t base, std::size_t& imageSize) noexcept { + const auto* elf = reinterpret_cast(base); + if (std::memcmp(elf->e_ident, ELFMAG, SELFMAG) != 0 || elf->e_ident[EI_CLASS] != ELFCLASS64 || + elf->e_ident[EI_DATA] != ELFDATA2LSB || elf->e_machine != EM_X86_64 || + elf->e_phentsize != sizeof(Elf64_Phdr) || elf->e_phnum == 0 || elf->e_phnum > 64 || + elf->e_phoff > 0x10000) { + return false; + } + + const auto* headers = reinterpret_cast(base + elf->e_phoff); + std::uint64_t mappedEnd{}; + // ELF may list PT_NOTE before PT_LOAD, so resolve the full image end first. + if (!ComputeMappedImageEnd(headers, elf->e_phnum, mappedEnd)) { + return false; + } + + for (std::uint16_t index = 0; index < elf->e_phnum; ++index) { + const Elf64_Phdr& header = headers[index]; + if (header.p_type != PT_NOTE || header.p_memsz < sizeof(Elf64_Nhdr) || header.p_memsz > 0x10000 || + base > std::numeric_limits::max() - header.p_vaddr) { + continue; + } + + const auto* cursor = reinterpret_cast(base + header.p_vaddr); + const auto* const limit = cursor + header.p_memsz; + while (static_cast(limit - cursor) >= sizeof(Elf64_Nhdr)) { + const auto* note = reinterpret_cast(cursor); + const std::size_t nameSize = (static_cast(note->n_namesz) + 3U) & ~std::size_t{3U}; + const std::size_t descSize = (static_cast(note->n_descsz) + 3U) & ~std::size_t{3U}; + cursor += sizeof(Elf64_Nhdr); + if (nameSize > static_cast(limit - cursor) || + descSize > static_cast(limit - cursor) - nameSize) { + break; + } + if (note->n_type == NT_GNU_BUILD_ID && note->n_namesz == 4 && note->n_descsz == sizeof(kLinuxBuildId) && + std::memcmp(cursor, "GNU", 4) == 0 && + std::memcmp(cursor + nameSize, kLinuxBuildId, sizeof(kLinuxBuildId)) == 0) { + imageSize = static_cast(mappedEnd); + return true; + } + cursor += nameSize + descSize; + } + } + return false; +} + +bool CurrentImageBase(void* function, std::uintptr_t& base, std::size_t& imageSize) noexcept { + Dl_info info{}; + if (!function || dladdr(function, &info) == 0 || !info.dli_fbase) { + return false; + } + + base = reinterpret_cast(info.dli_fbase); + if (!MatchesLinuxBuildId(base, imageSize)) { + return false; + } + return true; +} +#endif + +Query ResolveQuery() noexcept { + if (!g_queryAddresses) { + if (!__s2sdk_GetGameConfigSignature || !EnsureEngine()) { + return {}; + } + + try { + void* const signature = s2sdk::GetGameConfigSignature(GameConfig(), kSignature); + if (!signature) { + return {}; + } + + std::uintptr_t base{}; + std::size_t imageSize{}; + if (!CurrentImageBase(signature, base, imageSize)) { + return {}; + } + +#if defined(_WIN32) + constexpr std::uintptr_t functionRva = kWindowsTraceShapeRva; + constexpr std::uintptr_t receiverSlotRva = kWindowsReceiverSlotRva; + constexpr std::uintptr_t receiverRva = kWindowsReceiverRva; +#else + constexpr std::uintptr_t functionRva = kLinuxTraceShapeRva; + constexpr std::uintptr_t receiverSlotRva = kLinuxReceiverSlotRva; + constexpr std::uintptr_t receiverRva = kLinuxReceiverRva; +#endif + + const auto signatureAddress = reinterpret_cast(signature); + if (!WithinImage(base, imageSize, functionRva, 1) || signatureAddress != base + functionRva || + !WithinImage(base, imageSize, receiverSlotRva, sizeof(void*)) || + !WithinImage(base, imageSize, receiverRva, sizeof(void*))) { + return {}; + } + + g_queryAddresses = { + reinterpret_cast(signature), + reinterpret_cast(base + receiverSlotRva), + reinterpret_cast(base + receiverRva), + }; + } catch (...) { + return {}; + } + } + + const QueryAddresses addresses = g_queryAddresses; + // Cache only stable addresses; the receiver slot and its first field remain + // live values and must pass these checks on every use. + void* const receiver = *addresses.receiverSlot; + if (receiver != addresses.expectedReceiver || !*reinterpret_cast(receiver)) { + return {}; + } + return {addresses.call, receiver}; +} + +bool ResolveTraceSchema() noexcept { + if (g_traceSchema.ready) { + return true; + } + + TraceSchema resolved{}; + if (!ResolveSchemaField("CBaseEntity", "m_pCollision", sizeof(void*), resolved.pawnCollision) || + !ResolveSchemaField("CBaseEntity", "m_hOwnerEntity", sizeof(std::uint32_t), resolved.pawnOwner) || + !ResolveSchemaField("CCollisionProperty", "m_collisionAttribute", 0, resolved.collisionAttributes) || + !ResolveSchemaField("VPhysicsCollisionAttribute_t", "m_nInteractsAs", sizeof(std::uint64_t), resolved.interactsAs) || + !ResolveSchemaField("VPhysicsCollisionAttribute_t", "m_nInteractsExclude", sizeof(std::uint64_t), resolved.interactsExclude)) { + return false; + } + + g_traceSchema = resolved; + g_traceSchema.ready = true; + return true; +} + +template +T ReadField(const void* entity, std::int32_t offset) noexcept { + T value{}; + if (entity && offset >= 0) { + std::memcpy(&value, static_cast(entity) + offset, sizeof(T)); + } + return value; +} + +void InitializeMiss(const Vector& end, + Vector& outPosition, + float& outFraction, + bool& outHit, + std::int32_t& outEntityHandle, + bool& outStartSolid, + Vector& outNormal) noexcept { + outPosition = end; + outFraction = 1.0F; + outHit = false; + outEntityHandle = kInvalidHandle; + outStartSolid = false; + outNormal.Init(0.0F, 0.0F, 0.0F); +} + +bool TracePlayerMovementHullImpl(std::int32_t pawnHandle, + const Vector& start, + const Vector& end, + const Vector& hullMins, + const Vector& hullMaxs, + Vector& outPosition, + float& outFraction, + bool& outHit, + std::int32_t& outEntityHandle, + bool& outStartSolid, + Vector& outNormal) { + InitializeMiss(end, outPosition, outFraction, outHit, outEntityHandle, outStartSolid, outNormal); + + if (pawnHandle == kInvalidHandle || !Finite(start) || !Finite(end) || !Finite(hullMins) || !Finite(hullMaxs) || + hullMins.x > hullMaxs.x || hullMins.y > hullMaxs.y || hullMins.z > hullMaxs.z || + !__s2sdk_EntPointerToEntHandle || !__s2sdk_EntHandleToEntPointer || !IsPlayerPawn(pawnHandle)) { + return false; + } + + void* const pawn = EntityFromHandle(pawnHandle); + if (!pawn || HandleFromEntity(pawn) != pawnHandle || EntityFromHandle(pawnHandle) != pawn) { + return false; + } + if (!ResolveTraceSchema()) { + return false; + } + + void* const collision = ReadField(pawn, g_traceSchema.pawnCollision.offset); + if (!collision) { + return false; + } + const auto collisionAttributes = static_cast(collision) + g_traceSchema.collisionAttributes.offset; + const auto interactsAs = ReadField(collisionAttributes, g_traceSchema.interactsAs.offset); + const auto interactsExclude = ReadField(collisionAttributes, g_traceSchema.interactsExclude.offset); + const auto ownerHandle = ToApiHandle(ReadField(pawn, g_traceSchema.pawnOwner.offset)); + void* owner = ownerHandle == kInvalidHandle ? nullptr : EntityFromHandle(ownerHandle); + if (owner && HandleFromEntity(owner) != ownerHandle) { + owner = nullptr; + } + + const Query query = ResolveQuery(); + if (!query) { + return false; + } + + Ray_t ray(hullMins, hullMaxs); + CTraceFilter filter(kPlayersolidMask, COLLISION_GROUP_PLAYER_MOVEMENT, false); + auto* const pawnEntity = static_cast(pawn); + filter.SetPassEntity1(pawnEntity); + filter.SetPassEntityOwner1(static_cast(owner)); + filter.m_nInteractsAs = interactsAs; + filter.m_nInteractsExclude = interactsExclude; + filter.m_bHitSolidRequiresGenerateContacts = true; + + CGameTrace trace{}; + (void)query.call(query.receiver, ray, start, end, &filter, &trace); + if (!Finite(trace.m_vEndPos) || !Finite(trace.m_vHitNormal) || !std::isfinite(trace.m_flFraction) || + trace.m_flFraction < 0.0F || trace.m_flFraction > 1.0F) { + return false; + } + + outPosition = trace.m_vEndPos; + outFraction = trace.m_flFraction; + outHit = trace.DidHit(); + outStartSolid = trace.m_bStartInSolid; + outNormal = trace.m_vHitNormal; + if (outHit) { + if (!trace.m_pEnt) { + InitializeMiss(end, outPosition, outFraction, outHit, outEntityHandle, outStartSolid, outNormal); + return false; + } + const std::int32_t hitHandle = HandleFromEntity(trace.m_pEnt); + void* const resolved = hitHandle == kInvalidHandle ? nullptr : EntityFromHandle(hitHandle); + if (resolved == trace.m_pEnt && HandleFromEntity(resolved) == hitHandle) { + outEntityHandle = hitHandle; + } else { + InitializeMiss(end, outPosition, outFraction, outHit, outEntityHandle, outStartSolid, outNormal); + return false; + } + } + + return true; +} + +} // namespace + +void ResetMovementTraceMetadata() noexcept { + g_traceSchema = {}; + g_queryAddresses = {}; +} + +} // namespace funrounds::native::detail + +extern "C" PLUGIN_API bool HasPlayerMovementHullSupport() { + try { + return static_cast(funrounds::native::detail::ResolveQuery()); + } catch (...) { + return false; + } +} + +extern "C" PLUGIN_API bool TracePlayerMovementHull(std::int32_t pawnHandle, + const Vector& start, + const Vector& end, + const Vector& hullMins, + const Vector& hullMaxs, + Vector& outPosition, + float& outFraction, + bool& outHit, + std::int32_t& outEntityHandle, + bool& outStartSolid, + Vector& outNormal) { + try { + return funrounds::native::detail::TracePlayerMovementHullImpl(pawnHandle, start, end, hullMins, hullMaxs, + outPosition, outFraction, outHit, + outEntityHandle, outStartSolid, outNormal); + } catch (...) { + funrounds::native::detail::InitializeMiss(end, outPosition, outFraction, outHit, outEntityHandle, + outStartSolid, outNormal); + return false; + } +} diff --git a/native/funrounds-native/src/movement_trace.hpp b/native/funrounds-native/src/movement_trace.hpp new file mode 100644 index 0000000..2a1954d --- /dev/null +++ b/native/funrounds-native/src/movement_trace.hpp @@ -0,0 +1,31 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#pragma once + +#include + +#include + +#include + +namespace funrounds::native::detail { +void ResetMovementTraceMetadata() noexcept; +} + +// Both methods are game-thread-only. The query accepts a complete player pawn +// handle and the pawn's real local collision bounds. A true return means a +// finite query completed; `outHit == false` is a successful miss. +extern "C" PLUGIN_API bool HasPlayerMovementHullSupport(); + +extern "C" PLUGIN_API bool TracePlayerMovementHull(std::int32_t pawnHandle, + const Vector& start, + const Vector& end, + const Vector& hullMins, + const Vector& hullMaxs, + Vector& outPosition, + float& outFraction, + bool& outHit, + std::int32_t& outEntityHandle, + bool& outStartSolid, + Vector& outNormal); diff --git a/native/funrounds-native/src/plugin.cpp b/native/funrounds-native/src/plugin.cpp index d53e26c..1af905b 100644 --- a/native/funrounds-native/src/plugin.cpp +++ b/native/funrounds-native/src/plugin.cpp @@ -5,13 +5,19 @@ #include +#include "airmove.hpp" +#include "burn.hpp" +#include "collision.hpp" #include "damage.hpp" #include "engine.hpp" +#include "bighead.hpp" #include "ghost_radar.hpp" #include "ghost_visibility.hpp" #include "ground_reverse.hpp" #include "interactions.hpp" +#include "movement_trace.hpp" #include "suicide.hpp" +#include "standard_grenade.hpp" #include "touch.hpp" #include "third_person.hpp" @@ -62,8 +68,11 @@ class FunRoundsNativePlugin final : public plg::Plugin { plg::PluginResult OnPluginEnd() override { try { const bool damageClean = funrounds::native::detail::ShutdownDamage(); + const bool bigHeadClean = funrounds::native::detail::ShutdownBigHead(); const bool suicideClean = funrounds::native::detail::ShutdownSuicide(); + const bool standardGrenadesClean = funrounds::native::detail::ShutdownStandardGrenades(); const bool touchClean = funrounds::native::detail::ShutdownTouch(); + const bool airMoveClean = funrounds::native::detail::ShutdownAirMove(); const bool groundReverseClean = funrounds::native::detail::ShutdownGroundReverse(); const bool ghostRadarClean = funrounds::native::detail::ShutdownGhostRadar(); const bool ghostVisibilityClean = funrounds::native::detail::ShutdownGhostVisibility(); @@ -74,11 +83,14 @@ class FunRoundsNativePlugin final : public plg::Plugin { #else constexpr bool probeClean = true; #endif - if (!damageClean || !suicideClean || !touchClean || !groundReverseClean || !ghostRadarClean || + if (!damageClean || !bigHeadClean || !suicideClean || !standardGrenadesClean || !touchClean || !airMoveClean || !groundReverseClean || !ghostRadarClean || !ghostVisibilityClean || !interactionsClean || !thirdPersonClean || !probeClean) { return plg::PluginResult{"Native hook cleanup could not be verified"}; } + funrounds::native::detail::ResetBurnMetadata(); + funrounds::native::detail::ResetCollisionSchema(); + funrounds::native::detail::ResetMovementTraceMetadata(); funrounds::native::detail::ShutdownEngine(); return {}; } catch (...) { diff --git a/native/funrounds-native/src/standard_grenade.cpp b/native/funrounds-native/src/standard_grenade.cpp new file mode 100644 index 0000000..368556e --- /dev/null +++ b/native/funrounds-native/src/standard_grenade.cpp @@ -0,0 +1,412 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#include "standard_grenade.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "engine.hpp" +#include "standard_grenade_policy.hpp" + +namespace funrounds::native::detail { +namespace { + +struct PendingDetonation { + std::int32_t handle{-1}; + void* entity{}; +}; + +struct DetonateHook { + void* address{}; + polyhook::HookHandle handle{}; + bool attempted{}; +}; + +std::vector g_pending; +DetonateHook g_smokeHook; +DetonateHook g_molotovHook; +bool g_mapEndRegistered{}; +bool g_smokeFailureLogged{}; +bool g_fireFailureLogged{}; + +polyhook::ResultType DetonateEntry(polyhook::HookHandle, + polyhook::ParametersHandle parameters, + std::int32_t, + polyhook::ReturnHandle, + polyhook::CallbackType type) noexcept; + +const char* MissingRequiredImport() noexcept { + if (!__s2sdk_GetGameConfigVTable) return "missing S2SDK GetGameConfigVTable import"; + if (!__s2sdk_GetGameConfigOffset) return "missing S2SDK GetGameConfigOffset import"; + if (!__s2sdk_IsValidEntHandle) return "missing S2SDK IsValidEntHandle import"; + if (!__s2sdk_EntHandleToEntPointer) return "missing S2SDK EntHandleToEntPointer import"; + if (!__s2sdk_EntPointerToEntHandle) return "missing S2SDK EntPointerToEntHandle import"; + if (!__s2sdk_GetEntityClassname) return "missing S2SDK GetEntityClassname import"; + if (!__s2sdk_OnMapEnd_Register) return "missing S2SDK OnMapEnd_Register import"; + if (!__s2sdk_OnMapEnd_Unregister) return "missing S2SDK OnMapEnd_Unregister import"; + if (!__polyhook_HookDetour) return "missing PolyHook HookDetour import"; + if (!__polyhook_FindDetour) return "missing PolyHook FindDetour import"; + if (!__polyhook_AddCallback) return "missing PolyHook AddCallback import"; + if (!__polyhook_IsCallbackRegistered) return "missing PolyHook IsCallbackRegistered import"; + if (!__polyhook_RemoveCallback) return "missing PolyHook RemoveCallback import"; + if (!__polyhook_AreCallbacksRegistered) return "missing PolyHook AreCallbacksRegistered import"; + if (!__polyhook_UnhookDetour) return "missing PolyHook UnhookDetour import"; + if (!__polyhook_GetArgumentPointer) return "missing PolyHook GetArgumentPointer import"; + return nullptr; +} + +void LogSupportFailure(funrounds::native::grenade::Kind kind, const char* reason) noexcept { + bool& logged = kind == funrounds::native::grenade::Kind::Smoke ? g_smokeFailureLogged : g_fireFailureLogged; + if (logged) return; + logged = true; + try { + if (plg::Log != nullptr) { + std::string message = kind == funrounds::native::grenade::Kind::Smoke + ? "Standard smoke Detonate unavailable: " + : "Standard Molotov/incendiary Detonate unavailable: "; + message += reason; + plg::Log(plg::string(message), plg::Severity::Error, plg::source_location::current()); + } + } catch (...) { + } +} + +void ForgetPendingOnMapEnd() noexcept { + g_pending.clear(); +} + +bool RegisterMapEndCallback() noexcept { + if (g_mapEndRegistered) return true; + try { + s2sdk::OnMapEnd_Register(ForgetPendingOnMapEnd); + g_mapEndRegistered = true; + return true; + } catch (...) { + return false; + } +} + +bool UnregisterMapEndCallback() noexcept { + if (!g_mapEndRegistered) return true; + try { + s2sdk::OnMapEnd_Unregister(ForgetPendingOnMapEnd); + g_mapEndRegistered = false; + return true; + } catch (...) { + return false; + } +} + +std::int32_t DetonateSlot() noexcept { + try { + const auto slot = s2sdk::GetGameConfigOffset(GameConfig(), "CSGrenadeProjectileBase::Detonate"); + return slot >= 0 && slot < 4096 ? slot : -1; + } catch (...) { + return -1; + } +} + +void* ProjectileDetonate(funrounds::native::grenade::Kind kind) noexcept { + try { + const auto name = funrounds::native::grenade::VTableName(kind); + if (name.empty()) return nullptr; + auto* const table = static_cast(s2sdk::GetGameConfigVTable(GameConfig(), std::string(name))); + const auto slot = DetonateSlot(); + if (!table || slot < 0) return nullptr; + return table[slot]; + } catch (...) { + return nullptr; + } +} + +DetonateHook& HookFor(funrounds::native::grenade::Kind kind) noexcept { + return kind == funrounds::native::grenade::Kind::Smoke ? g_smokeHook : g_molotovHook; +} + +bool CurrentProjectile(std::int32_t handle, + funrounds::native::grenade::Kind kind, + void*& entity) noexcept { + entity = nullptr; + try { + if (handle == -1 || !s2sdk::IsValidEntHandle(handle)) return false; + entity = EntityFromHandle(handle); + if (!entity || HandleFromEntity(entity) != handle || + reinterpret_cast(entity)->GetRefEHandle().ToInt() != static_cast(handle)) { + entity = nullptr; + return false; + } + const auto classname = s2sdk::GetEntityClassname(handle); + if (std::string_view(classname.c_str()) != funrounds::native::grenade::ProjectileClass(kind)) { + entity = nullptr; + return false; + } + return true; + } catch (...) { + entity = nullptr; + return false; + } +} + +bool IsKnownGrenadeProjectile(std::int32_t handle, void* entity) { + if (handle == -1 || !entity || !s2sdk::IsValidEntHandle(handle) || EntityFromHandle(handle) != entity || + HandleFromEntity(entity) != handle || + reinterpret_cast(entity)->GetRefEHandle().ToInt() != static_cast(handle)) { + return false; + } + const auto classname = s2sdk::GetEntityClassname(handle); + const std::string_view value(classname.c_str()); + return value == funrounds::native::grenade::ProjectileClass(funrounds::native::grenade::Kind::Smoke) || + value == funrounds::native::grenade::ProjectileClass(funrounds::native::grenade::Kind::Molotov); +} + +void RetireStalePending() noexcept { + std::erase_if(g_pending, [](const PendingDetonation& pending) { + try { + return pending.handle == -1 || !s2sdk::IsValidEntHandle(pending.handle) || + EntityFromHandle(pending.handle) != pending.entity || HandleFromEntity(pending.entity) != pending.handle || + reinterpret_cast(pending.entity)->GetRefEHandle().ToInt() != static_cast(pending.handle); + } catch (...) { + return true; + } + }); +} + +bool IsPending(std::int32_t handle) noexcept { + return std::any_of(g_pending.begin(), g_pending.end(), [handle](const PendingDetonation& item) { + return item.handle == handle; + }); +} + +bool IsPending(std::int32_t handle, void* entity) noexcept { + return std::any_of(g_pending.begin(), g_pending.end(), [handle, entity](const PendingDetonation& item) { + return item.handle == handle && item.entity == entity; + }); +} + +bool RemoveHook(DetonateHook& state) noexcept; + +bool ClaimDetonation(std::int32_t handle, void* entity) noexcept { + RetireStalePending(); + if (IsPending(handle)) return false; + try { + g_pending.push_back({handle, entity}); + return true; + } catch (...) { + return false; + } +} + +bool InstallDetonateHook(funrounds::native::grenade::Kind kind, void* address) noexcept { + auto& state = HookFor(kind); + auto& other = kind == funrounds::native::grenade::Kind::Smoke ? g_molotovHook : g_smokeHook; + if (!address) return false; + try { + if (other.address == address) { + const auto current = polyhook::FindDetour(address); + if (!other.handle && other.attempted) other.handle = current; + return current && other.handle == current && + polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Pre, DetonateEntry); + } + if (state.address) { + const auto current = polyhook::FindDetour(state.address); + if (!state.handle && state.attempted) state.handle = current; + return current && state.handle == current && + polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Pre, DetonateEntry); + } + if (polyhook::FindDetour(address)) return false; + + const plg::vector arguments{polyhook::DataType::Pointer}; + state.address = address; + state.attempted = true; + state.handle = polyhook::HookDetour(address, + polyhook::DataType::Void, + arguments, + -1, + plg::string(kind == funrounds::native::grenade::Kind::Smoke + ? "FunRounds::SmokeGrenadeProjectile::Detonate" + : "FunRounds::MolotovProjectile::Detonate")); + if (!state.handle) { + (void)RemoveHook(state); + return false; + } + (void)polyhook::AddCallback(state.handle, polyhook::CallbackType::Pre, DetonateEntry); + if (!polyhook::IsCallbackRegistered(state.handle, polyhook::CallbackType::Pre, DetonateEntry)) { + (void)RemoveHook(state); + return false; + } + return true; + } catch (...) { + (void)RemoveHook(state); + return false; + } +} + +bool RemoveHook(DetonateHook& state) noexcept { + try { + if (!state.address) return !state.handle; + const auto current = polyhook::FindDetour(state.address); + if (!current) { + state = {}; + return true; + } + if (!state.handle && state.attempted) state.handle = current; + if (!state.handle || current != state.handle) return false; + if (polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Pre, DetonateEntry)) { + (void)polyhook::RemoveCallback(current, polyhook::CallbackType::Pre, DetonateEntry); + if (polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Pre, DetonateEntry)) return false; + } + if (polyhook::AreCallbacksRegistered(current)) { + state = {}; + return true; + } + (void)polyhook::UnhookDetour(state.address); + if (polyhook::FindDetour(state.address)) return false; + state = {}; + return true; + } catch (...) { + return false; + } +} + +polyhook::ResultType DetonateEntry(polyhook::HookHandle, + polyhook::ParametersHandle parameters, + std::int32_t, + polyhook::ReturnHandle, + polyhook::CallbackType type) noexcept { + if (type != polyhook::CallbackType::Pre || !parameters) return polyhook::ResultType::Ignored; + try { + auto* const entity = polyhook::GetArgument(parameters, 0); + if (!entity) return polyhook::ResultType::Ignored; + const auto handle = HandleFromEntity(entity); + if (!IsKnownGrenadeProjectile(handle, entity)) return polyhook::ResultType::Ignored; + + // This pre-entry claim catches natural fuse/collision paths as well as our + // direct request. For smoke it is set before the asynchronous volume build + // can emit smokegrenade_detonate or set m_bDidSmokeEffect. + (void)ClaimDetonation(handle, entity); + } catch (...) { + } + return polyhook::ResultType::Ignored; +} + +} // namespace + +bool HasGrenadeDetonateSupport(std::int32_t value) noexcept { + if (!funrounds::native::grenade::ValidKind(value)) return false; + const auto kind = static_cast(value); + const auto fail = [kind](const char* reason) noexcept { + LogSupportFailure(kind, reason); + return false; + }; + + try { + if (const auto* missing = MissingRequiredImport()) return fail(missing); + if (!EnsureEngine()) return fail("engine schema or native gamedata is not ready"); + if (!RegisterMapEndCallback()) return fail("map-end claim cleanup callback could not be registered"); + void* const detonate = ProjectileDetonate(kind); + if (!detonate) return fail("configured projectile vtable or Detonate offset did not resolve"); + if (!InstallDetonateHook(kind, detonate)) return fail("Detonate entry hook is unavailable or not owned"); + return true; + } catch (...) { + return fail("support probe threw while resolving the configured native entry"); + } +} + +std::int32_t GetGrenadeDetonationState(std::int32_t projectileHandle, std::int32_t value) noexcept { + using funrounds::native::grenade::StateResult; + using funrounds::native::grenade::StateValue; + if (!funrounds::native::grenade::ValidKind(value) || projectileHandle == -1) { + return StateValue(StateResult::Failed); + } + const auto kind = static_cast(value); + try { + if (!HasGrenadeDetonateSupport(value)) return StateValue(StateResult::Failed); + if (!s2sdk::IsValidEntHandle(projectileHandle)) return StateValue(StateResult::StartedOrGone); + + // Validate the live full handle and its concrete projectile class before + // consulting the shared natural/direct Detonate-entry claim set. + void* entity{}; + if (!CurrentProjectile(projectileHandle, kind, entity)) { + return StateValue(s2sdk::IsValidEntHandle(projectileHandle) + ? StateResult::Failed + : StateResult::StartedOrGone); + } + return StateValue(IsPending(projectileHandle, entity) ? StateResult::StartedOrGone + : StateResult::NotStarted); + } catch (...) { + return StateValue(StateResult::Failed); + } +} + +std::int32_t DetonateGrenade(std::int32_t projectileHandle, std::int32_t value) noexcept { + using funrounds::native::grenade::RequestResult; + using funrounds::native::grenade::ResultValue; + if (!funrounds::native::grenade::ValidKind(value)) return ResultValue(RequestResult::Failed); + const auto kind = static_cast(value); + try { + if (!HasGrenadeDetonateSupport(value)) return ResultValue(RequestResult::Failed); + if (projectileHandle == -1) return ResultValue(RequestResult::Failed); + // A non-sentinel full handle can become invalid between the adapter's + // last read and this request when a natural fuse/collision wins the race. + if (!s2sdk::IsValidEntHandle(projectileHandle)) return ResultValue(RequestResult::AlreadyStartedOrGone); + RetireStalePending(); + void* const detonate = ProjectileDetonate(kind); + void* entity{}; + if (!detonate) return ResultValue(RequestResult::Failed); + if (IsPending(projectileHandle)) return ResultValue(RequestResult::AlreadyStartedOrGone); + if (!CurrentProjectile(projectileHandle, kind, entity)) { + return ResultValue(s2sdk::IsValidEntHandle(projectileHandle) + ? RequestResult::Failed + : RequestResult::AlreadyStartedOrGone); + } + + // Claim before dispatch so a second request in this frame cannot race the + // entry callback. The hook also claims natural engine entry points. + if (!ClaimDetonation(projectileHandle, entity)) { + return ResultValue(IsPending(projectileHandle) ? RequestResult::AlreadyStartedOrGone + : RequestResult::Failed); + } + using Detonate = void (*)(void*); + reinterpret_cast(detonate)(entity); + return ResultValue(RequestResult::Submitted); + } catch (...) { + // Preserve the claim if dispatch began: retrying an ambiguous native call + // could run the engine's effects twice. + return ResultValue(RequestResult::Failed); + } +} + +bool ShutdownStandardGrenades() noexcept { + // Remove the observers before discarding claims; a failed detach retains both + // the hook identity and the pending handles for a later cleanup retry. + const bool smokeClean = RemoveHook(g_smokeHook); + const bool molotovClean = RemoveHook(g_molotovHook); + if (!smokeClean || !molotovClean) return false; + if (!UnregisterMapEndCallback()) return false; + g_pending.clear(); + return true; +} + +} // namespace funrounds::native::detail + +extern "C" PLUGIN_API bool HasGrenadeDetonateSupport(std::int32_t kind) { + return funrounds::native::detail::HasGrenadeDetonateSupport(kind); +} + +extern "C" PLUGIN_API std::int32_t GetGrenadeDetonationState(std::int32_t projectileHandle, std::int32_t kind) { + return funrounds::native::detail::GetGrenadeDetonationState(projectileHandle, kind); +} + +extern "C" PLUGIN_API std::int32_t DetonateGrenade(std::int32_t projectileHandle, std::int32_t kind) { + return funrounds::native::detail::DetonateGrenade(projectileHandle, kind); +} diff --git a/native/funrounds-native/src/standard_grenade.hpp b/native/funrounds-native/src/standard_grenade.hpp new file mode 100644 index 0000000..525bd40 --- /dev/null +++ b/native/funrounds-native/src/standard_grenade.hpp @@ -0,0 +1,15 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#pragma once + +#include + +namespace funrounds::native::detail { + +bool HasGrenadeDetonateSupport(std::int32_t kind) noexcept; +std::int32_t GetGrenadeDetonationState(std::int32_t projectileHandle, std::int32_t kind) noexcept; +std::int32_t DetonateGrenade(std::int32_t projectileHandle, std::int32_t kind) noexcept; +bool ShutdownStandardGrenades() noexcept; + +} // namespace funrounds::native::detail diff --git a/native/funrounds-native/src/standard_grenade_policy.hpp b/native/funrounds-native/src/standard_grenade_policy.hpp new file mode 100644 index 0000000..2b53dc0 --- /dev/null +++ b/native/funrounds-native/src/standard_grenade_policy.hpp @@ -0,0 +1,61 @@ +// Copyright (C) 2026 Mai Ooizumi +// SPDX-License-Identifier: AGPL-3.0-or-later + +#pragma once + +#include +#include + +namespace funrounds::native::grenade { + +enum class Kind : std::int32_t { + Smoke = 1, + Molotov = 2, + Incendiary = 3, +}; + +enum class RequestResult : std::int32_t { + Failed = -1, + AlreadyStartedOrGone = 0, + Submitted = 1, +}; + +enum class StateResult : std::int32_t { + Failed = -1, + NotStarted = 0, + StartedOrGone = 1, +}; + +constexpr std::int32_t ResultValue(RequestResult value) noexcept { + return static_cast(value); +} + +constexpr std::int32_t StateValue(StateResult value) noexcept { + return static_cast(value); +} + +constexpr bool ValidKind(std::int32_t value) noexcept { + return value == static_cast(Kind::Smoke) || + value == static_cast(Kind::Molotov) || + value == static_cast(Kind::Incendiary); +} + +constexpr std::string_view ProjectileClass(Kind kind) noexcept { + switch (kind) { + case Kind::Smoke: return "smokegrenade_projectile"; + case Kind::Molotov: + case Kind::Incendiary: return "molotov_projectile"; + } + return {}; +} + +constexpr std::string_view VTableName(Kind kind) noexcept { + switch (kind) { + case Kind::Smoke: return "CSmokeGrenadeProjectile"; + case Kind::Molotov: + case Kind::Incendiary: return "CMolotovProjectile"; + } + return {}; +} + +} // namespace funrounds::native::grenade diff --git a/native/funrounds-native/src/suicide.cpp b/native/funrounds-native/src/suicide.cpp index db2b3d8..6213966 100644 --- a/native/funrounds-native/src/suicide.cpp +++ b/native/funrounds-native/src/suicide.cpp @@ -59,53 +59,6 @@ void* CanAcquireAddress() noexcept { return s2sdk::GetGameConfigSignature(GameConfig(), kCanAcquireSignature); } -bool ResolveItemServicesChain() noexcept { - auto* schema = ServerSchema(); - if (!schema) { - return false; - } - auto* componentClass = schema->FindDeclaredClass("CPlayerPawnComponent").Get(); - if (!componentClass || componentClass->m_nSize < 0 || - (componentClass->m_nFieldCount != 0 && !componentClass->m_pFields)) { - return false; - } - - for (std::uint16_t index = 0; index < componentClass->m_nFieldCount; ++index) { - const auto& field = componentClass->m_pFields[index]; - if (!field.m_pszName || std::strcmp(field.m_pszName, "__m_pChainEntity") != 0) { - continue; - } - if (!field.m_pType || field.m_pType->m_eTypeCategory != SCHEMA_TYPE_DECLARED_CLASS || - field.m_nSingleInheritanceOffset < 0) { - return false; - } - - const auto* declared = static_cast(field.m_pType); - const auto* chainClass = declared->m_pClassInfo; - if (!chainClass || !chainClass->m_pszName || - std::strcmp(chainClass->m_pszName, "CNetworkVarChainer") != 0 || - chainClass->m_nSize != static_cast(sizeof(CNetworkVarChainer))) { - return false; - } - - int fieldSize = 0; - std::uint8_t alignment = 0; - if (!field.m_pType->GetSizeAndAlignment(fieldSize, alignment) || - fieldSize != static_cast(sizeof(CNetworkVarChainer))) { - return false; - } - - const auto offset = static_cast(field.m_nSingleInheritanceOffset); - const auto objectSize = static_cast(componentClass->m_nSize); - if (offset > objectSize || sizeof(CNetworkVarChainer) > objectSize - offset) { - return false; - } - g_schema.itemServicesChain = {field.m_nSingleInheritanceOffset, sizeof(CNetworkVarChainer)}; - return true; - } - return false; -} - bool HasInspectSchema() noexcept { if (g_schema.ready) { return true; @@ -115,7 +68,7 @@ bool HasInspectSchema() noexcept { !ResolveSchemaField("CPlayer_MovementServices", "m_nButtons", 0, g_schema.movementButtons) || !ResolveSchemaField("CInButtonState", "m_pButtonStates", sizeof(std::uint64_t[3]), g_schema.buttonStates) || !ResolveSchemaField("CBaseEntity", "m_lifeState", sizeof(std::uint8_t), g_schema.lifeState) || - !ResolveItemServicesChain() || + !ResolvePlayerPawnComponentChain(g_schema.itemServicesChain) || !ResolveSchemaField("CBasePlayerPawn", "m_hController", sizeof(std::uint32_t), g_schema.pawnController)) { return false; } @@ -160,7 +113,7 @@ std::int32_t PawnForItemServices(void* services) noexcept { return pawn && IsPlayerPawn(handle) && HandleFromEntity(pawn) == handle ? handle : -1; } -bool RemoveHook() noexcept { +bool RemoveHook(bool unhookIfEmpty = true) noexcept { g_hook.callback = nullptr; if (!g_hook.address) { g_hook = {}; @@ -181,6 +134,14 @@ bool RemoveHook() noexcept { if (polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Pre, CanAcquirePre)) { return false; } + if (polyhook::AreCallbacksRegistered(current)) { + g_hook = {}; + return true; + } + if (!unhookIfEmpty) { + g_hook = {}; + return true; + } (void)polyhook::UnhookDetour(g_hook.address); if (polyhook::FindDetour(g_hook.address)) { return false; @@ -234,7 +195,8 @@ bool HasSuicideSupport() { const auto address = CanAcquireAddress(); const bool inspectSchemaReady = HasInspectSchema(); const bool polyhookReady = __polyhook_HookDetour && __polyhook_FindDetour && __polyhook_AddCallback && - __polyhook_IsCallbackRegistered && __polyhook_RemoveCallback && + __polyhook_IsCallbackRegistered && __polyhook_AreCallbacksRegistered && + __polyhook_RemoveCallback && __polyhook_UnhookDetour; return address && inspectSchemaReady && polyhookReady; } @@ -255,68 +217,78 @@ std::int32_t LookAtWeaponButtonState(std::int32_t pawnHandle) { return (buttons & kLookAtWeaponButton) != 0 ? 1 : 0; } -bool HookPlayerCanAcquire(PlayerCanAcquireCallback callback) { - if (!callback) { - return false; - } - if (!HasSuicideSupport()) { +bool InstallCanAcquireHookAt(void* address, PlayerCanAcquireCallback callback) { + if (!callback || !address) { return false; } if (g_hook.owner && g_hook.owner != callback) { return false; } - const auto address = CanAcquireAddress(); - if (!address || (g_hook.address && g_hook.address != address)) { + if (g_hook.address && g_hook.address != address) { return false; } if (g_hook.address) { - if (polyhook::FindDetour(address) != g_hook.handle) { - return false; - } - try { - if (!polyhook::IsCallbackRegistered(g_hook.handle, polyhook::CallbackType::Pre, CanAcquirePre)) { - (void)polyhook::AddCallback(g_hook.handle, polyhook::CallbackType::Pre, CanAcquirePre); - } - if (!polyhook::IsCallbackRegistered(g_hook.handle, polyhook::CallbackType::Pre, CanAcquirePre)) { + const auto current = polyhook::FindDetour(address); + if (!current) { + g_hook = {}; + } else if (current != g_hook.handle) { + // This address has a known typed ABI, so a replacement detour at + // the same entry point can be joined through its current handle. + g_hook = {}; + } else { + try { + if (!polyhook::IsCallbackRegistered(g_hook.handle, polyhook::CallbackType::Pre, CanAcquirePre)) { + (void)polyhook::AddCallback(g_hook.handle, polyhook::CallbackType::Pre, CanAcquirePre); + } + if (!polyhook::IsCallbackRegistered(g_hook.handle, polyhook::CallbackType::Pre, CanAcquirePre)) { + return false; + } + g_hook.owner = callback; + g_hook.callback = callback; + return true; + } catch (...) { return false; } - g_hook.owner = callback; - g_hook.callback = callback; - return true; - } catch (...) { - return false; } } - if (polyhook::FindDetour(address)) { - return false; - } - constexpr std::array argumentKinds{polyhook::DataType::Pointer, polyhook::DataType::Pointer, polyhook::DataType::Int32, polyhook::DataType::Pointer}; const plg::vector argumentTypes(argumentKinds.begin(), argumentKinds.end()); - const auto hook = polyhook::HookDetour(address, polyhook::DataType::Int8, - argumentTypes, -1, - kCanAcquireHookName); + auto hook = polyhook::FindDetour(address); + const bool createdDetour = hook == nullptr; + if (!hook) { + hook = polyhook::HookDetour(address, polyhook::DataType::Int8, + argumentTypes, -1, + kCanAcquireHookName); + } if (!hook) { return false; } - g_hook = {address, hook, callback, nullptr}; + g_hook = {address, hook, nullptr, nullptr}; try { (void)polyhook::AddCallback(hook, polyhook::CallbackType::Pre, CanAcquirePre); if (!polyhook::IsCallbackRegistered(hook, polyhook::CallbackType::Pre, CanAcquirePre)) { - (void)RemoveHook(); + (void)RemoveHook(createdDetour); return false; } + g_hook.owner = callback; g_hook.callback = callback; return true; } catch (...) { - (void)RemoveHook(); + (void)RemoveHook(createdDetour); return false; } } +bool HookPlayerCanAcquire(PlayerCanAcquireCallback callback) { + if (!callback || !HasSuicideSupport()) { + return false; + } + return InstallCanAcquireHookAt(CanAcquireAddress(), callback); +} + bool UnhookPlayerCanAcquire(PlayerCanAcquireCallback callback) { if (!callback || callback != g_hook.owner) { return false; @@ -325,7 +297,11 @@ bool UnhookPlayerCanAcquire(PlayerCanAcquireCallback callback) { } bool ShutdownSuicide() noexcept { - return RemoveHook(); + if (!RemoveHook()) { + return false; + } + g_schema = {}; + return true; } } // namespace funrounds::native::detail diff --git a/native/funrounds-native/src/third_person.cpp b/native/funrounds-native/src/third_person.cpp index fa524fb..3ef5aca 100644 --- a/native/funrounds-native/src/third_person.cpp +++ b/native/funrounds-native/src/third_person.cpp @@ -43,7 +43,8 @@ T Read(const void* object, SchemaField field) noexcept { bool ImportsAvailable() noexcept { return __polyhook_HookDetour2 && __polyhook_FindDetour && __polyhook_AddCallback && - __polyhook_RemoveCallback && __polyhook_IsCallbackRegistered && __polyhook_UnhookDetour && + __polyhook_RemoveCallback && __polyhook_IsCallbackRegistered && + __polyhook_AreCallbacksRegistered && __polyhook_UnhookDetour && __polyhook_GetRegisterPointer && __polyhook_SetRegisterPointer && __s2sdk_GetGameConfigSignature && __s2sdk_GetEntityClassname; } @@ -151,6 +152,11 @@ bool RemoveHook() noexcept { return false; } } + if (polyhook::AreCallbacksRegistered(current)) { + // Keep only the known HookDetour2 handle so this module can reattach + // its callback later; no callback into this module remains registered. + return true; + } (void)polyhook::UnhookDetour(g_hook.address); if (polyhook::FindDetour(g_hook.address)) { return false; @@ -162,12 +168,39 @@ bool RemoveHook() noexcept { } } -bool InstallHook(const Snapshot& schema) { +bool RefreshKnownHookRecord() noexcept { + try { + if (!g_hook.address) { + return !g_hook.hook; + } + const auto current = polyhook::FindDetour(g_hook.address); + if (!current) { + g_hook = {}; + return true; + } + return g_hook.hook && current == g_hook.hook; + } catch (...) { + return false; + } +} + +bool AttachEyeCallback(polyhook::HookHandle hook) { + if (!polyhook::IsCallbackRegistered(hook, polyhook::CallbackType::Pre, EyePre)) { + (void)polyhook::AddCallback(hook, polyhook::CallbackType::Pre, EyePre); + } + return polyhook::IsCallbackRegistered(hook, polyhook::CallbackType::Pre, EyePre); +} + +bool InstallHookAt(void* address) { + if (!address || !RefreshKnownHookRecord()) { + return false; + } if (g_hook.address) { - return g_hook.hook && polyhook::FindDetour(g_hook.address) == g_hook.hook && - polyhook::IsCallbackRegistered(g_hook.hook, polyhook::CallbackType::Pre, EyePre); + if (g_hook.address != address) { + return false; + } + return AttachEyeCallback(g_hook.hook); } - void* const address = BranchAddress(schema); if (!address || polyhook::FindDetour(address)) { return false; } @@ -177,16 +210,27 @@ bool InstallHook(const Snapshot& schema) { (void)RemoveHook(); return false; } - (void)polyhook::AddCallback(g_hook.hook, polyhook::CallbackType::Pre, EyePre); - return polyhook::IsCallbackRegistered(g_hook.hook, polyhook::CallbackType::Pre, EyePre); + return AttachEyeCallback(g_hook.hook); +} + +bool InstallHook(const Snapshot& schema) { + if (!RefreshKnownHookRecord()) { + return false; + } + if (g_hook.address) { + return AttachEyeCallback(g_hook.hook); + } + return InstallHookAt(BranchAddress(schema)); } } // namespace bool HasThirdPersonEyeSupport() noexcept { try { Snapshot schema; - return ImportsAvailable() && ResolveSchema(schema) && - (g_hook.address ? (g_hook.hook && polyhook::FindDetour(g_hook.address) == g_hook.hook) : BranchAddress(schema) != nullptr); + if (!ImportsAvailable() || !ResolveSchema(schema) || !RefreshKnownHookRecord()) { + return false; + } + return g_hook.address || BranchAddress(schema) != nullptr; } catch (...) { return false; } @@ -271,6 +315,7 @@ bool ShutdownThirdPersonEye() noexcept { return false; } } + } // namespace funrounds::native::detail extern "C" PLUGIN_API bool HasThirdPersonEyeSupport() { diff --git a/native/funrounds-native/src/touch.cpp b/native/funrounds-native/src/touch.cpp index 58c0dda..3f98787 100644 --- a/native/funrounds-native/src/touch.cpp +++ b/native/funrounds-native/src/touch.cpp @@ -5,7 +5,9 @@ #include #include +#include #include +#include #include #include @@ -17,15 +19,18 @@ namespace funrounds::native::detail { namespace { +using TouchCallbacks = std::vector; +using TouchCallbackSnapshot = std::shared_ptr; +using TouchCallbackSlot = std::atomic; + struct TouchHook { void* address; polyhook::HookHandle handle; bool callbackRegistered; + std::shared_ptr callbacks; }; std::vector g_hooks; -EntityTouchPreCallback g_owner = nullptr; -EntityTouchPreCallback g_callback = nullptr; #if defined(FUNROUNDS_NATIVE_LIFECYCLE_PROBE) bool g_probeFailNextTouchAdd = false; bool g_probeFailNextTouchRemove = false; @@ -41,7 +46,7 @@ std::int32_t TouchForeignProbeCallback(std::int32_t, std::int32_t) { } #endif -polyhook::ResultType TouchPre(polyhook::HookHandle, +polyhook::ResultType TouchPre(polyhook::HookHandle hook, polyhook::ParametersHandle params, std::int32_t, polyhook::ReturnHandle, @@ -50,11 +55,6 @@ polyhook::ResultType TouchPre(polyhook::HookHandle, return polyhook::ResultType::Ignored; } - const auto callback = g_callback; - if (!callback) { - return polyhook::ResultType::Ignored; - } - try { auto* entity = polyhook::GetArgument(params, 0); auto* other = polyhook::GetArgument(params, 1); @@ -71,14 +71,32 @@ polyhook::ResultType TouchPre(polyhook::HookHandle, otherHandle = -1; } - return callback(entityHandle, otherHandle) == 0 ? polyhook::ResultType::Ignored - : polyhook::ResultType::Supercede; + const auto record = std::find_if(g_hooks.begin(), g_hooks.end(), [hook](const auto& item) { + return item.handle == hook; + }); + if (record == g_hooks.end()) { + return polyhook::ResultType::Ignored; + } + const auto callbacks = record->callbacks->load(std::memory_order_acquire); + if (!callbacks || callbacks->empty()) { + return polyhook::ResultType::Ignored; + } + + bool suppressOriginal = false; + for (const auto callback : *callbacks) { + try { + suppressOriginal = callback(entityHandle, otherHandle) != 0 || suppressOriginal; + } catch (...) { + // One consumer cannot prevent the other Touch consumers from running. + } + } + return suppressOriginal ? polyhook::ResultType::Supercede : polyhook::ResultType::Ignored; } catch (...) { return polyhook::ResultType::Ignored; } } -bool RemoveHook(TouchHook& record) noexcept { +bool RemoveHook(TouchHook& record, bool unhookIfEmpty = true) noexcept { try { auto current = polyhook::FindDetour(record.address); if (!current) { @@ -96,6 +114,10 @@ bool RemoveHook(TouchHook& record) noexcept { } #endif + const auto callbacks = record.callbacks ? record.callbacks->load(std::memory_order_acquire) : nullptr; + if (callbacks && !callbacks->empty()) { + return false; + } if (polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Pre, TouchPre)) { (void)polyhook::RemoveCallback(current, polyhook::CallbackType::Pre, TouchPre); } @@ -104,6 +126,18 @@ bool RemoveHook(TouchHook& record) noexcept { } record.callbackRegistered = false; + // PolyHook handles are shared by all plugin consumers in the process. + // The native provider may detach only after its callback was the last + // callback registered on this implementation. + if (polyhook::AreCallbacksRegistered(current)) { + record.handle = nullptr; + return true; + } + if (!unhookIfEmpty) { + record.handle = nullptr; + return true; + } + (void)polyhook::UnhookDetour(record.address); if (polyhook::FindDetour(record.address)) { return false; @@ -116,9 +150,11 @@ bool RemoveHook(TouchHook& record) noexcept { } bool DetachAll() noexcept { - g_callback = nullptr; bool detached = true; for (auto it = g_hooks.begin(); it != g_hooks.end();) { + if (it->callbacks) { + it->callbacks->store({}, std::memory_order_release); + } if (RemoveHook(*it)) { it = g_hooks.erase(it); } else { @@ -126,12 +162,49 @@ bool DetachAll() noexcept { ++it; } } - if (g_hooks.empty()) { - g_owner = nullptr; - } return detached; } +bool HasCallback(const TouchHook& hook, EntityTouchPreCallback callback) noexcept { + const auto callbacks = hook.callbacks ? hook.callbacks->load(std::memory_order_acquire) : nullptr; + return callbacks && std::find(callbacks->begin(), callbacks->end(), callback) != callbacks->end(); +} + +bool AddCallback(TouchHook& hook, EntityTouchPreCallback callback) { + if (!hook.callbacks) { + return false; + } + auto callbacks = hook.callbacks->load(std::memory_order_acquire); + if (callbacks && std::find(callbacks->begin(), callbacks->end(), callback) != callbacks->end()) { + return true; + } + auto updated = std::make_shared>(); + if (callbacks) { + *updated = *callbacks; + } + updated->push_back(callback); + hook.callbacks->store(TouchCallbackSnapshot(std::move(updated)), std::memory_order_release); + return true; +} + +void RemoveCallback(TouchHook& hook, EntityTouchPreCallback callback) { + if (!hook.callbacks) { + return; + } + const auto callbacks = hook.callbacks->load(std::memory_order_acquire); + if (!callbacks || std::find(callbacks->begin(), callbacks->end(), callback) == callbacks->end()) { + return; + } + auto updated = std::make_shared>(); + updated->reserve(callbacks->size() - 1); + for (const auto current : *callbacks) { + if (current != callback) { + updated->push_back(current); + } + } + hook.callbacks->store(TouchCallbackSnapshot(std::move(updated)), std::memory_order_release); +} + bool AddTouchCallback(polyhook::HookHandle hook) { #if defined(FUNROUNDS_NATIVE_LIFECYCLE_PROBE) if (g_probeFailNextTouchAdd) { @@ -177,10 +250,8 @@ bool IsTouchAvailable() { bool HookTouch(std::int32_t entityHandle, EntityTouchPreCallback callback) { if (!callback || !__polyhook_HookDetour || !__polyhook_FindDetour || !__polyhook_AddCallback || !__polyhook_IsCallbackRegistered || - !__polyhook_RemoveCallback || !__polyhook_UnhookDetour) { - return false; - } - if (g_owner && g_owner != callback) { + !__polyhook_RemoveCallback || !__polyhook_UnhookDetour || + !__polyhook_AreCallbacksRegistered) { return false; } void* implementation = nullptr; @@ -195,35 +266,52 @@ bool HookTouch(std::int32_t entityHandle, EntityTouchPreCallback callback) { if (existing->handle != polyhook::FindDetour(implementation)) { return false; } - if (existing->callbackRegistered && - polyhook::IsCallbackRegistered(existing->handle, polyhook::CallbackType::Pre, TouchPre)) { - g_callback = callback; - return true; + const bool alreadySubscribed = HasCallback(*existing, callback); + if (!alreadySubscribed) { + AddCallback(*existing, callback); + } + if (!existing->callbackRegistered || + !polyhook::IsCallbackRegistered(existing->handle, polyhook::CallbackType::Pre, TouchPre)) { + try { + (void)AddTouchCallback(existing->handle); + existing->callbackRegistered = + polyhook::IsCallbackRegistered(existing->handle, polyhook::CallbackType::Pre, TouchPre); + } catch (...) { + existing->callbackRegistered = + polyhook::IsCallbackRegistered(existing->handle, polyhook::CallbackType::Pre, TouchPre); + } } + if (!existing->callbackRegistered && !alreadySubscribed) { + RemoveCallback(*existing, callback); + } + return existing->callbackRegistered; + } + + if (const auto current = polyhook::FindDetour(implementation); current != nullptr) { + // This entry has a known typed ABI. A borrowed empty detour remains + // the creator's cleanup responsibility until our callback is live. + g_hooks.reserve(g_hooks.size() + 1); + auto callbacks = std::make_shared>(1, callback); + g_hooks.push_back({implementation, current, false, + std::make_shared(TouchCallbackSnapshot(std::move(callbacks)))}); + auto& record = g_hooks.back(); try { - (void)AddTouchCallback(existing->handle); - existing->callbackRegistered = - polyhook::IsCallbackRegistered(existing->handle, polyhook::CallbackType::Pre, TouchPre); + (void)AddTouchCallback(current); + record.callbackRegistered = + polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Pre, TouchPre); } catch (...) { - existing->callbackRegistered = false; - } - if (existing->callbackRegistered) { - g_callback = callback; - return true; + record.callbackRegistered = + polyhook::IsCallbackRegistered(current, polyhook::CallbackType::Pre, TouchPre); } - - if (RemoveHook(*existing)) { - g_hooks.erase(existing); - if (g_hooks.empty()) { - g_owner = nullptr; - g_callback = nullptr; + if (!record.callbackRegistered) { + record.callbacks->store({}, std::memory_order_release); + if (RemoveHook(record, false)) { + g_hooks.pop_back(); } + return false; } - return false; - } - if (polyhook::FindDetour(implementation)) { - return false; + return true; } g_hooks.reserve(g_hooks.size() + 1); @@ -238,8 +326,9 @@ bool HookTouch(std::int32_t entityHandle, EntityTouchPreCallback callback) { return false; } - g_owner = callback; - g_hooks.push_back({implementation, hook, false}); + g_hooks.push_back({implementation, hook, false, + std::make_shared( + std::make_shared>(1, callback))}); auto& record = g_hooks.back(); try { (void)AddTouchCallback(hook); @@ -248,17 +337,12 @@ bool HookTouch(std::int32_t entityHandle, EntityTouchPreCallback callback) { record.callbackRegistered = false; } if (!record.callbackRegistered) { + record.callbacks->store({}, std::memory_order_release); if (RemoveHook(record)) { g_hooks.pop_back(); - if (g_hooks.empty()) { - g_owner = nullptr; - g_callback = nullptr; - } } return false; } - - g_callback = callback; return true; } @@ -332,10 +416,22 @@ bool UnhookTouch(EntityTouchPreCallback callback) { if (!callback) { return false; } - if (callback != g_owner) { - return true; + bool detached = true; + for (auto it = g_hooks.begin(); it != g_hooks.end();) { + RemoveCallback(*it, callback); + const auto callbacks = it->callbacks ? it->callbacks->load(std::memory_order_acquire) : nullptr; + if (callbacks && !callbacks->empty()) { + ++it; + continue; + } + if (RemoveHook(*it)) { + it = g_hooks.erase(it); + } else { + detached = false; + ++it; + } } - return DetachAll(); + return detached; } bool ShutdownTouch() noexcept { diff --git a/native/funrounds-native/src/touch.hpp b/native/funrounds-native/src/touch.hpp index 51880c1..eb9bffc 100644 --- a/native/funrounds-native/src/touch.hpp +++ b/native/funrounds-native/src/touch.hpp @@ -11,8 +11,9 @@ using EntityTouchPreCallback = std::int32_t (*)(std::int32_t entityHandle, std:: bool IsTouchAvailable(); bool HookTouch(std::int32_t entityHandle, EntityTouchPreCallback callback); -// Returns false for null callbacks or when one of the callback's retained -// Touch hooks cannot be detached. A callback that owns no hooks succeeds. +// Removes only this callback's subscriptions. Other callbacks keep their shared +// detours alive; false means one of this callback's final-hook detachments must +// be retried. bool UnhookTouch(EntityTouchPreCallback callback); bool ShutdownTouch() noexcept; #if defined(FUNROUNDS_NATIVE_LIFECYCLE_PROBE) diff --git a/packaging/funrounds.pplugin b/packaging/funrounds.pplugin index 0ae01ee..4131d1a 100644 --- a/packaging/funrounds.pplugin +++ b/packaging/funrounds.pplugin @@ -1,5 +1,5 @@ { - "version": "0.3.0-alpha.test.2", + "version": "0.4.0-alpha.test.3", "name": "funrounds", "description": "Configurable special rounds for Counter-Strike 2", "author": "Mai Ooizumi", @@ -10,11 +10,11 @@ "dependencies": [ { "name": "s2sdk", - "constraints": "=3.0.6" + "constraints": "=3.3.1" }, { "name": "funrounds_native", - "constraints": "=0.3.0-alpha.test.2" + "constraints": "=0.4.0-alpha.test.3" } ], "methods": [] diff --git a/scripts/build-native.py b/scripts/build-native.py index 889e6f7..a364ed3 100644 --- a/scripts/build-native.py +++ b/scripts/build-native.py @@ -17,8 +17,8 @@ S2SDK_URL = "https://github.com/Mai-Ooizumi/plugify-plugin-s2sdk.git" # funrounds branch; pin the patched provider used by both plugins and the bundle. -S2SDK_COMMIT = "dfa3a3e8e88a70872b66d379490d3228a48f6d81" -S2SDK_VERSION = "3.0.6" +S2SDK_COMMIT = "2fca1d177ddca1c265ee585457ad160752e9111c" +S2SDK_VERSION = "3.3.1" SOURCESDK_URL = "https://github.com/Wend4r/sourcesdk.git" SOURCESDK_COMMIT = "f3de33c58595c628c12b4ffaba76dfcd49b8763f" diff --git a/scripts/tests/test_build_native.py b/scripts/tests/test_build_native.py index 8074e48..1b847bf 100644 --- a/scripts/tests/test_build_native.py +++ b/scripts/tests/test_build_native.py @@ -80,7 +80,7 @@ def fake_run(command): def test_generates_pinned_s2sdk_import_manifest(self): sdk = self.root / "sdk" sdk.mkdir() - (sdk / "version.txt").write_text("3.0.6\n", encoding="utf-8") + (sdk / "version.txt").write_text("3.3.1\n", encoding="utf-8") (sdk / "plugify-plugin-s2sdk.pplugin.in").write_text( '{"version":"${S2SDK_VERSION}","name":"${S2SDK_PACKAGE}"}', encoding="utf-8" ) @@ -96,7 +96,7 @@ def fake_run(command): build_native.generate_s2sdk_imports(sdk, generated_include) rendered = json.loads((self.root / "generated/plugify-plugin-s2sdk.pplugin").read_text("utf-8")) - self.assertEqual(rendered, {"version": "3.0.6", "name": "s2sdk"}) + self.assertEqual(rendered, {"version": "3.3.1", "name": "s2sdk"}) self.assertEqual(commands[0][1:7], ["-manifest", str(self.root / "generated/plugify-plugin-s2sdk.pplugin"), "-output", str(generated_include), "-lang", "cpp"]) self.assertIn("-overwrite", commands[0]) self.assertTrue((generated_include / "external/plugify/include/s2sdk/s2sdk.cpp").is_file()) @@ -173,7 +173,9 @@ def test_builds_and_stages_patched_s2sdk_on_both_platforms(self): self.assertEqual(len(list((output / "s2sdk/licenses").glob("*.txt"))), 5) source = json.loads((output / "s2sdk/source.json").read_text("utf-8")) self.assertEqual(source["repository"], "https://github.com/Mai-Ooizumi/plugify-plugin-s2sdk.git") - self.assertEqual(source["commit"], "dfa3a3e8e88a70872b66d379490d3228a48f6d81") + self.assertEqual(source["commit"], "2fca1d177ddca1c265ee585457ad160752e9111c") + binding = json.loads((ROOT / "bindings/s2sdk.pplugin").read_text("utf-8")) + self.assertEqual(source["version"], binding["version"]) if __name__ == "__main__": diff --git a/scripts/tests/test_ci.py b/scripts/tests/test_ci.py index 515f1c6..3535dda 100644 --- a/scripts/tests/test_ci.py +++ b/scripts/tests/test_ci.py @@ -41,12 +41,12 @@ def make_repo(self, version="1.2.3"): for name in ("funrounds-core", "funrounds-plugin") )) self.write("crates/funrounds-core/src/lib.rs", f'pub const VERSION: &str = "{version}";\n') - main = {"version": version, "dependencies": [{"name": "s2sdk", "constraints": "=3.0.6"}, + main = {"version": version, "dependencies": [{"name": "s2sdk", "constraints": "=3.3.1"}, {"name": "funrounds_native", "constraints": f"={version}"}]} - native = {"version": version, "dependencies": [{"name": "s2sdk", "constraints": "=3.0.6"}]} + native = {"version": version, "dependencies": [{"name": "s2sdk", "constraints": "=3.3.1"}]} self.write("packaging/funrounds.pplugin", json.dumps(main)) self.write("native/funrounds-native/funrounds-native.pplugin", json.dumps(native)) - self.write("bindings/s2sdk.pplugin", '{"version":"3.0.6","dependencies":[{"name":"configs","constraints":">=2.1.0"}]}') + self.write("bindings/s2sdk.pplugin", '{"version":"3.3.1","dependencies":[{"name":"configs","constraints":">=2.1.2"}]}') self.write("native/funrounds-native/gamedata/funrounds-native.jsonc", '{}') self.write("config/funrounds.example.toml", '# Generic example\n') for language in ("zh-CN", "en"): @@ -61,7 +61,7 @@ def assets(self, version="1.2.3"): (output / f"funrounds-{version}-{platform}.zip").write_bytes(b"archive") return output - def sdk_fixture(self, platform, version="3.0.6"): + def sdk_fixture(self, platform, version="3.3.1"): name = "plugify-plugin-s2sdk.dll" if platform == "windows-x64" else "libplugify-plugin-s2sdk.so" self.write(f"native-output/s2sdk/bin/{name}", "patched SDK") self.write("native-output/s2sdk/plugify-plugin-s2sdk.pplugin", json.dumps({"name": "s2sdk", "version": version})) @@ -199,7 +199,7 @@ def test_release_stages_draft_then_publishes_exact_sha(self, run, api, changed): self.assertIn("--draft", create) self.assertIn("b" * 40, create) self.assertIn("Includes patched S2SDK", create[create.index("--notes") + 1]) - self.assertIn("configs >=2.1.0", create[create.index("--notes") + 1]) + self.assertIn("configs >=2.1.2", create[create.index("--notes") + 1]) self.assertIn("--draft=false", publish) self.assertIn("--prerelease=false", publish)