Author SHA1 Message Date
N0VAN0M4LY 470fc3746d chore(docs):update readme 2026-12-05 20:06:00 +08:00
N0VAN0M4LY f86ab99c17 feat(mods): compose shared tech tree insertions
Accept manifest declarations for inserting vehicles into an existing research link. Compose shared links in mod load order after ordinary overlays and write matching shop and economy prerequisites. Validate anchors, rank order, and cycles, and document the manifest field.

Verified type checks, a 2.61.0.64 build with shared, folded, and cross-column insertions, load-order and disable readback, and the local server health endpoint. In-game acceptance remains pending.
2026-12-05 18:36:50 +08:00
N0VAN0M4LY 0843fde6ff fix(ground-ai): respect mounted gun traverse limits
Read the selected gun mount limits from the vehicle data and constrain its aiming commands. Send out-of-traverse aim requests to the chassis driver and require alignment before firing.

Verified type checks, executable patch checks and builds on 2.61.0.37 and 2.61.0.64, and guarded daScript initialization on 2.61.0.64. In-battle acceptance remains pending.
2026-12-05 18:36:19 +08:00
N0VAN0M4LY 39a77c04cb fix(tools): register decrypt-clog command in wtotools cli
log_commands defined decrypt-clog but the cli entry point never registered it, so the command was rejected as an invalid choice. Verified by decrypting a lab .clog through python -m wtotools.cli.
2026-12-05 17:07:17 +08:00
N0VAN0M4LY f932ef096f docs(repo): clarify single-player offline scope and no-multiplayer policy 2026-12-05 11:43:23 +08:00
N0VAN0M4LY d40623cd47 fix(battle): correct LocalMP capture and hit feedback
Credit completed zone captures to the units counted by the mission engine and send the local capture fact through the existing settlement flow. Filter hit markers and shell-change hints using the actual attacker and active view.

TypeScript checks and the MSVC build passed. Verified exe, Quirrel, and native patches on 2.61.0.37, 2.61.0.58, 2.61.0.60, and 2.61.0.64. Rebuilt the .58 and .64 copies and verified local service health on .58. In-game verification is pending.
2026-12-05 10:24:14 +08:00
38 changed files with 981 additions and 235 deletions

No files matched your search

+8 -4
View File
@@ -8,6 +8,8 @@
WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线项目。本地服务器模拟 Gaijin 的线上服务,客户端的所有请求都发到本机。客户端照常登录、读取档案、进入机库、提交玩家操作,游戏规则、存档和对局结算都在本地服务器上完成,对手和队友全部是 AI。 WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线项目。本地服务器模拟 Gaijin 的线上服务,客户端的所有请求都发到本机。客户端照常登录、读取档案、进入机库、提交玩家操作,游戏规则、存档和对局结算都在本地服务器上完成,对手和队友全部是 AI。
> **项目定位**:WTOffline 是为了方便玩家离线游玩的**单机**《战争雷霆》项目。为保持项目边界清晰、避免争议,项目组**不会提供也不会制作包括局域网联机在内的任何形式联机功能**。
仓库只包含源码和补丁定义,不包含任何游戏文件。构建时从玩家本机的原版安装读取文件,生成一份独立的游戏副本。 仓库只包含源码和补丁定义,不包含任何游戏文件。构建时从玩家本机的原版安装读取文件,生成一份独立的游戏副本。
## 状态 ## 状态
@@ -41,7 +43,7 @@ WTOffline 是《战争雷霆》(War Thunder)Windows 客户端的单机离线
| 战后 | 结算页、战斗历史、个人统计、战斗奖章、加成道具与合同结算、修理费与自动修理 | | 战后 | 结算页、战斗历史、个人统计、战斗奖章、加成道具与合同结算、修理费与自动修理 |
| 回放 | 录制与回放,回放中切换到 AI 视角 | | 回放 | 录制与回放,回放中切换到 AI 视角 |
尚未实现:全真模式、自定义战斗、单人任务与动态战役、世界大战、战令、成就进度和称号获取、排行榜。好友、组队等多人社交功能不适用,只保证界面不报错。 尚未实现:全真模式、自定义战斗、单人任务与动态战役、世界大战、战令、成就进度和称号获取、排行榜。本项目仅面向单人离线游玩,不制作包括局域网联机在内的任何联机功能;好友、组队等多人社交功能不适用,只保证界面不报错。
AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不足。 AI 的驾驶、寻路和战术使用游戏自带的 AI,目前仍有明显不足。
@@ -261,7 +263,7 @@ tools/ wtotools,补丁检查工具(Python)
## 声明 ## 声明
本项目是同人爱好项目,与 Gaijin Entertainment 没有任何关联,也未获其认可。War Thunder 及相关名称和素材归其各自所有者所有。仓库不分发任何游戏文件,使用者需要自行拥有合法的游戏客户端。 本项目是面向单人离线游玩的非商业同人爱好项目,项目组不会主动制作包括局域网联机在内的任何联机功能。本项目与 Gaijin Entertainment 没有任何关联,也未获其认可。War Thunder 及相关名称和素材归其各自所有者所有。仓库不分发任何游戏文件,使用者需要自行拥有合法的游戏客户端。
--- ---
@@ -273,6 +275,8 @@ tools/ wtotools,补丁检查工具(Python)
WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI. WTOffline is a single-player offline project for the Windows client of War Thunder. A local server emulates Gaijin's online services, and the client sends all of its requests to the local machine. The client logs in, loads its profile, enters the hangar, and submits player actions as usual. Game rules, saves, and battle settlement run on the local server, and all allies and opponents are AI.
> **Project scope**: WTOffline is a **single-player offline** War Thunder project built to make offline play convenient for players. The project team **will not develop or provided any kind of multiplayer or networking features, including LAN multiplayer**.
The repository contains source code and patch definitions only. It does not contain any game files. The build reads files from the player's own installation and produces a separate game copy. The repository contains source code and patch definitions only. It does not contain any game files. The build reads files from the player's own installation and produces a separate game copy.
## Status ## Status
@@ -306,7 +310,7 @@ Join the [WTOffline Discord server](https://discord.gg/P566xWNpEs) for general d
| After battle | Debriefing, battle history, personal statistics, battle awards, booster and contract settlement, repair costs and auto-repair | | After battle | Debriefing, battle history, personal statistics, battle awards, booster and contract settlement, repair costs and auto-repair |
| Replays | Recording and playback, switching to AI vehicles during playback | | Replays | Recording and playback, switching to AI vehicles during playback |
Not yet implemented: Simulator modes, custom battles, single missions and dynamic campaigns, World War, the battle pass, achievement progress and title unlocks, leaderboards. Social multiplayer features such as friends and squads do not apply; the interface is only kept from breaking. Not yet implemented: Simulator modes, custom battles, single missions and dynamic campaigns, World War, the battle pass, achievement progress and title unlocks, leaderboards. This project is strictly for single-player offline play and will not develop any multiplayer features (including LAN multiplayer); social multiplayer features such as friends and squads do not apply and are only kept from breaking the interface.
AI driving, pathfinding, and tactics come from the game's built-in AI and still have clear shortcomings. AI driving, pathfinding, and tactics come from the game's built-in AI and still have clear shortcomings.
@@ -526,4 +530,4 @@ This project is released under the [GNU Affero General Public License v3.0](LICE
## Disclaimer ## Disclaimer
This is a non-commercial fan project. It is not affiliated with or endorsed by Gaijin Entertainment. War Thunder and related names and assets belong to their respective owners. The repository does not distribute any game files; you need your own legitimate copy of the game client. This is a non-commercial fan project built strictly for single-player offline play; the project team will not actively develop any multiplayer features, including LAN multiplayer. It is not affiliated with or endorsed by Gaijin Entertainment. War Thunder and related names and assets belong to their respective owners. The repository does not distribute any game files; you need your own legitimate copy of the game client.
+13 -2
View File
@@ -29,6 +29,7 @@ let public WTO_DENY_MUZZLE_HARD = 8
let public WTO_DENY_ARC_HARD = 9 let public WTO_DENY_ARC_HARD = 9
let public WTO_DENY_FRIENDLY = 10 let public WTO_DENY_FRIENDLY = 10
let public WTO_DENY_MULTI_GUN = 11 let public WTO_DENY_MULTI_GUN = 11
let public WTO_DENY_TRAVERSE = 12
[safe_when_uninitialized] [safe_when_uninitialized]
struct public WtoShellProfile struct public WtoShellProfile
@@ -76,9 +77,21 @@ struct public WtoPerceiveState
expScore : float[8] expScore : float[8]
expGoodLosSec : float[8] expGoodLosSec : float[8]
[safe_when_uninitialized]
struct public WtoGunTraverse
known : bool = false
yaw : float2 = float2(0.0, 0.0)
pitch : float2 = float2(1.0, 0.0)
hasPitchTable : bool = false
pitchSector : float4 = float4(1.0, 0.0, 1.0, 0.0)
[safe_when_uninitialized] [safe_when_uninitialized]
struct public WtoFireState struct public WtoFireState
turretNo : int = -1 turretNo : int = -1
traverseTurretNo : int = -1
traverse : WtoGunTraverse = WtoGunTraverse()
hullAimTarget : EntityId = INVALID_ENTITY_ID
hullAimDir : float3 = float3(0.0, 0.0, 0.0)
gunReady : bool = false gunReady : bool = false
reloading : bool = false reloading : bool = false
gunDamaged : bool = false gunDamaged : bool = false
@@ -89,8 +102,6 @@ struct public WtoFireState
activeCaliberM : float = 0.09 activeCaliberM : float = 0.09
pitchBlocked : bool = false pitchBlocked : bool = false
pitchClampSec : float = 0.0 pitchClampSec : float = 0.0
cmdYawDeg : float = 0.0
cmdPitchDeg : float = 0.0
curYawDeg : float = 0.0 curYawDeg : float = 0.0
curPitchDeg : float = 0.0 curPitchDeg : float = 0.0
prevPitchDeg : float = 0.0 prevPitchDeg : float = 0.0
+21 -9
View File
@@ -70,6 +70,15 @@ def private wto_check_echo_watchdog(unitMissionName : string; var actor : Vehicl
st.deadEchoSec = 0.0 st.deadEchoSec = 0.0
return true return true
def public wto_pivot_drive_mode(spec : WtoVehicleSpec const&; frontClearM, rearClearM : float; preferNeutral : bool) : int
let openFront = frontClearM >= spec.halfLen + 3.5
let neutralTurn = spec.canPivot && frontClearM >= spec.halfLen + 1.2 && rearClearM >= spec.halfLen + 1.0
if neutralTurn && (preferNeutral || !openFront)
return WTO_DRIVE_PIVOT
if openFront
return WTO_DRIVE_CRUISE
return rearClearM >= spec.halfLen + WTO_AI_TERRAIN_MARGIN_M ? WTO_DRIVE_REVERSE : WTO_DRIVE_HALT
[never_inline] [never_inline]
def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&; def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSpec const&;
fwd, left : float3; vFwd, omega : float; fwd, left : float3; vFwd, omega : float;
@@ -82,15 +91,18 @@ def private wto_compute_pivot_axes(cmd : WtoDriveCmd const&; spec : WtoVehicleSp
outBrk = 1.0 outBrk = 1.0
outStr = turnSign * WTO_AI_NAV_STEER_SIGN outStr = turnSign * WTO_AI_NAV_STEER_SIGN
return return
let openFront = cmd.frontClearM >= spec.halfLen + 3.5 let mode = wto_pivot_drive_mode(spec, cmd.frontClearM, cmd.rearClearM, cmd.speedMps <= 0.0)
if openFront if mode == WTO_DRIVE_PIVOT
let response = errRad / (WTO_AI_NAV_PIVOT_ANGLE_DEG * WTO_DEG_TO_RAD)
outStr = clamp(response - omega * 0.35, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN
return
if mode == WTO_DRIVE_CRUISE
// Two-beat turn micro: launch straight to 2nd gear before applying full steering. // Two-beat turn micro: launch straight to 2nd gear before applying full steering.
outThr = 1.0 outThr = 1.0
outStr = abs(vFwd) < WTO_AI_SM_TURN_LAUNCH_MPS ? 0.0 : (turnSign * WTO_AI_NAV_STEER_SIGN) outStr = abs(vFwd) < WTO_AI_SM_TURN_LAUNCH_MPS ? 0.0 : (turnSign * WTO_AI_NAV_STEER_SIGN)
return return
if spec.canPivot && cmd.frontClearM >= spec.halfLen + 1.2 && cmd.rearClearM >= spec.halfLen + 1.0 if mode == WTO_DRIVE_HALT
outThr = 0.0 outBrk = 1.0
outStr = clamp(turnSign - omega * 0.35, -1.0, 1.0) * WTO_AI_NAV_STEER_SIGN
return return
// Tight front obstacle: execute clean 3-point reverse turn instead of ramming the wall. // Tight front obstacle: execute clean 3-point reverse turn instead of ramming the wall.
outThr = vFwd > -WTO_AI_SM_TURN_LAUNCH_MPS ? -1.0 : -0.6 outThr = vFwd > -WTO_AI_SM_TURN_LAUNCH_MPS ? -1.0 : -0.6
@@ -177,7 +189,7 @@ def private wto_ensure_phys_owner(gm : IGroundModel const?; var actor : VehicleP
return false return false
if !st.routeBOwned if !st.routeBOwned
slot.spec.isTracked = actor.phys.trackWidth > 0.01 slot.spec.isTracked = actor.phys.trackWidth > 0.01
slot.spec.canPivot = slot.spec.isTracked && actor.phys.haveSeparateBrakes slot.spec.canPivot = slot.spec.canPivot && slot.spec.isTracked && actor.phys.haveSeparateBrakes
st.routeBOwned = true st.routeBOwned = true
return st.routeBOwned return st.routeBOwned
@@ -191,12 +203,12 @@ def private wto_apply_drive_cmd(var actor : VehiclePhysActor&; fwd, left, veloci
var str = 0.0 var str = 0.0
var brk = 0.0 var brk = 0.0
var hand = 0.0 var hand = 0.0
if cmd.mode == WTO_DRIVE_HALT || cmd.speedMps <= 0.05 if cmd.mode == WTO_DRIVE_PIVOT
wto_compute_pivot_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk)
elif cmd.mode == WTO_DRIVE_HALT || cmd.speedMps <= 0.05
thr = abs(vFwd) > 0.35 ? (vFwd > 0.0 ? -1.0 : 1.0) : 0.0 thr = abs(vFwd) > 0.35 ? (vFwd > 0.0 ? -1.0 : 1.0) : 0.0
brk = 1.0 brk = 1.0
hand = abs(vFwd) > 0.35 ? 0.0 : 1.0 hand = abs(vFwd) > 0.35 ? 0.0 : 1.0
elif cmd.mode == WTO_DRIVE_PIVOT
wto_compute_pivot_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk)
elif cmd.mode == WTO_DRIVE_REVERSE elif cmd.mode == WTO_DRIVE_REVERSE
wto_compute_reverse_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk, hand) wto_compute_reverse_axes(cmd, slot.spec, fwd, left, vFwd, st.omegaYawRad, thr, str, brk, hand)
else else
+34 -84
View File
@@ -22,31 +22,7 @@ require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_estimate_common require %appGame.wtoai.wto_ai_estimate_common
require %appGame.wtoai.wto_ai_fire_gate_common require %appGame.wtoai.wto_ai_fire_gate_common
require %appGame.wtoai.wto_ai_traverse_common
[never_inline]
def private wto_world_to_hull_deg(worldDir, hullFwd, hullUp, hullLeft : float3;
var outYawDeg, outPitchDeg : float&)
let len = length(worldDir)
if len < 1.0e-5
outYawDeg = 0.0
outPitchDeg = 0.0
return
let d = worldDir / len
let f = dot(d, hullFwd)
let u = dot(d, hullUp)
let l = dot(d, hullLeft)
let horiz = sqrt(f * f + l * l)
outYawDeg = horiz > 1.0e-5 ? (-atan2(l, f) * WTO_RAD_TO_DEG) : 0.0
outPitchDeg = clamp(atan2(u, max(1.0e-5, horiz)) * WTO_RAD_TO_DEG, -24.0, 65.0)
[never_inline]
def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3
let yr = yawDeg * WTO_DEG_TO_RAD
let pr = pitchDeg * WTO_DEG_TO_RAD
let cp = cos(pr)
let dir = hullFwd * (cp * cos(yr)) - hullLeft * (cp * sin(yr)) + hullUp * sin(pr)
let l = length(dir)
return l > 1.0e-5 ? (dir / l) : hullFwd
[never_inline] [never_inline]
def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&) def private wto_sync_active_shell(gun : WTGun const?; spec : WtoVehicleSpec const&; var fc : WtoFireState&)
@@ -111,18 +87,23 @@ def private wto_select_next_shell(var gun : WTGun?; spec : WtoVehicleSpec const&
[never_inline] [never_inline]
def private wto_inspect_primary_weapon(var unit : Unit?; now : float; def private wto_inspect_primary_weapon(var unit : Unit?; now : float;
spec : WtoVehicleSpec const&; wantSoftShell : bool; spec : WtoVehicleSpec const&; wantSoftShell : bool;
var fc : WtoFireState&) var fc : WtoFireState&) : int
let previousTurret = fc.turretNo
fc.turretNo = -1 fc.turretNo = -1
fc.gunReady = false fc.gunReady = false
fc.reloading = false fc.reloading = false
fc.gunDamaged = false fc.gunDamaged = false
if unit == null || unit.weap == null if unit == null || unit.weap == null
return return -1
var selected = -1
var nextIndex = 0
var anyGun = false var anyGun = false
var anyAlive = false var anyAlive = false
var anyReserve = false var anyReserve = false
var totalLoaded = 0 var totalLoaded = 0
foreach_primary_gun(unit.weap.Weapons) <| $(var weapon) foreach_primary_gun(unit.weap.Weapons) <| $(var weapon)
let index = nextIndex
nextIndex++
if weapon == null || weapon.isDummyGun if weapon == null || weapon.isDummyGun
return return
var gun = as_gun(weapon) var gun = as_gun(weapon)
@@ -131,7 +112,8 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float;
anyGun = true anyGun = true
anyAlive = true anyAlive = true
anyReserve = true anyReserve = true
if fc.turretNo < 0 if selected < 0
selected = index
fc.turretNo = weapon.turretNo fc.turretNo = weapon.turretNo
fc.gunReady = true fc.gunReady = true
totalLoaded += weapon.countBullets totalLoaded += weapon.countBullets
@@ -140,8 +122,11 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float;
if gun.isInoperable if gun.isInoperable
return return
anyAlive = true anyAlive = true
if fc.turretNo < 0 if selected < 0
selected = index
fc.turretNo = weapon.turretNo fc.turretNo = weapon.turretNo
if fc.turretNo != previousTurret
fc.loadedBulletIdx = -1
wto_select_next_shell(gun, spec, wantSoftShell) wto_select_next_shell(gun, spec, wantSoftShell)
wto_sync_active_shell(gun, spec, fc) wto_sync_active_shell(gun, spec, fc)
if gun.isReadyToShoot if gun.isReadyToShoot
@@ -158,6 +143,7 @@ def private wto_inspect_primary_weapon(var unit : Unit?; now : float;
elif (now - fc.pendingShotAt) > 0.35 elif (now - fc.pendingShotAt) > 0.35
fc.pendingShotConfirm = false fc.pendingShotConfirm = false
fc.prevLoadedAmmo = totalLoaded fc.prevLoadedAmmo = totalLoaded
return selected
[never_inline] [never_inline]
def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBotSlot&; def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBotSlot&;
@@ -178,63 +164,24 @@ def private wto_solve_ballistic_aim(muzzlePos, myVel : float3; var slot : WtoBot
return rawDist return rawDist
[never_inline] [never_inline]
def private wto_sample_turret_muzzle(unit : Unit const?; turretNo : int; def private wto_sample_muzzle(unit : Unit const?; primaryIndex : int;
var outPos, outDir : float3&) : bool var outPos, outDir : float3&) : bool
if unit == null || unit.weap == null if unit == null || unit.weap == null || primaryIndex < 0
return false return false
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret var sampled = false
if (turretNo >= 0 && tIdx != turretNo) || (turretNo < 0 && int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY)) get_weapons_by_trigger_group(unit.weap.Weapons, WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY) <| $(weapons : array<Weapon const? const> const#)
continue if primaryIndex >= length(weapons)
let weapon = get_weapon(unit.weap.Weapons, int(turret.triggerNo), int(turret.weaponIndex)) return
assume weapon = weapons[primaryIndex]
if weapon == null if weapon == null
continue return
var gunTm : float3x4 var gunTm : float3x4
weapon_calcShootTm(weapon, unit.unitTm, gunTm) weapon_calcShootTm(weapon, unit.unitTm, gunTm)
if length_sq(gunTm[0]) > 0.25 if length_sq(gunTm[0]) > 0.25
outPos = gunTm[3] outPos = gunTm[3]
outDir = normalize(gunTm[0]) outDir = normalize(gunTm[0])
return true sampled = true
return false return sampled
[never_inline]
def private wto_drive_turret_and_sample_barrel(var unit : Unit?; dt : float;
wishYawDeg, wishPitchDeg : float;
var slot : WtoBotSlot&;
var outMuzzlePos, outLiveDir : float3&)
assume fc = slot.fire
let dtStep = clamp(dt, 0.005, 0.12)
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret
if (fc.turretNo >= 0 && tIdx != fc.turretNo) || (fc.turretNo < 0 && int(turret.triggerGroupNo) != int(WeaponTriggerGroups.TRIGGER_GROUP_PRIMARY))
continue
fc.curYawDeg = turret.currentState.yaw
fc.curPitchDeg = turret.currentState.pitch
if !fc.servoInit
fc.cmdYawDeg = fc.curYawDeg
fc.cmdPitchDeg = fc.curPitchDeg
fc.prevPitchDeg = fc.curPitchDeg
fc.servoInit = true
let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep
fc.prevPitchDeg = fc.curPitchDeg
if slot.perceive.hasClearLos && wishPitchDeg < fc.curPitchDeg - 2.3 && pitchSpd < 0.8
fc.pitchClampSec = min(2.0, fc.pitchClampSec + dtStep)
fc.pitchBlocked = fc.pitchClampSec >= 0.75
else
fc.pitchClampSec = max(0.0, fc.pitchClampSec - dtStep * 2.5)
if fc.pitchClampSec <= 0.05
fc.pitchBlocked = false
let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep
let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep
let yawDelta = clamp(wto_wrap_deg(wishYawDeg - fc.curYawDeg), -maxYawStep, maxYawStep)
let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep)
fc.cmdYawDeg = wto_wrap_deg(fc.curYawDeg + yawDelta)
fc.cmdPitchDeg = clamp(fc.curPitchDeg + pitchDelta, slot.spec.minPitchDeg - 2.0, slot.spec.maxPitchDeg + 2.0)
turret.yawLim = fc.cmdYawDeg
turret.pitchLim = fc.cmdPitchDeg
break
var uPos = unit.pos
updateWeaponAnims(*unit.weap, dtStep, 1.0, uPos)
if !wto_sample_turret_muzzle(unit, fc.turretNo, outMuzzlePos, outLiveDir)
outLiveDir = wto_hull_deg_to_world(fc.curYawDeg, fc.curPitchDeg, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2])
def private wto_clear_aim_tracking(var fc : WtoFireState&) def private wto_clear_aim_tracking(var fc : WtoFireState&)
fc.aimTargetEid = INVALID_ENTITY_ID fc.aimTargetEid = INVALID_ENTITY_ID
@@ -244,12 +191,13 @@ def private wto_clear_aim_tracking(var fc : WtoFireState&)
fc.lastDenyReason = WTO_DENY_NO_TARGET fc.lastDenyReason = WTO_DENY_NO_TARGET
[never_inline] [never_inline]
def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?; className : string;
now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&) now, dt : float; var slot : WtoBotSlot&; var fireBudget : int&)
if !WTO_AI_LAYER_FIRE_CONTROL || unit == null || unit.weap == null if !WTO_AI_LAYER_FIRE_CONTROL || unit == null || unit.weap == null
return return
// SPAA vs aircraft only delegates to stock air-target fire control (never ground targets). // SPAA vs aircraft only delegates to stock air-target fire control (never ground targets).
if slot.tactics.spaaYieldAir if slot.tactics.spaaYieldAir
wto_set_hull_aim(unit, false, 0.0, unit.unitTm[0], slot)
wto_clear_aim_tracking(slot.fire) wto_clear_aim_tracking(slot.fire)
var gm = as_gm(unit) var gm = as_gm(unit)
if gm != null if gm != null
@@ -263,10 +211,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?;
let tgtIdx = wto_world_find_unit(world, slot.perceive.targetEid) let tgtIdx = wto_world_find_unit(world, slot.perceive.targetEid)
if tgtIdx >= 0 if tgtIdx >= 0
wantSoftShell = world.units[tgtIdx].isLightTag || world.units[tgtIdx].halfWid < 1.35 wantSoftShell = world.units[tgtIdx].isLightTag || world.units[tgtIdx].halfWid < 1.35
wto_inspect_primary_weapon(unit, now, slot.spec, wantSoftShell, slot.fire) let primaryIndex = wto_inspect_primary_weapon(unit, now, slot.spec, wantSoftShell, slot.fire)
var muzzlePos = unit.pos + float3(0.0, 1.95, 0.0) var muzzlePos = unit.pos + float3(0.0, 1.95, 0.0)
var liveBarrelDir = unit.unitTm[0] var liveBarrelDir = unit.unitTm[0]
let _preSample = wto_sample_turret_muzzle(unit, slot.fire.turretNo, muzzlePos, liveBarrelDir) let _preSample = wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir)
let hFwd = unit.unitTm[0] let hFwd = unit.unitTm[0]
var wishWorldDir = hFwd var wishWorldDir = hFwd
@@ -287,8 +235,10 @@ def public wto_fire_update(world : WtoWorldSnap const&; var unit : Unit?;
var wishYaw = 0.0 var wishYaw = 0.0
var wishPitch = 0.0 var wishPitch = 0.0
wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch) wto_world_to_hull_deg(wishWorldDir, hFwd, unit.unitTm[1], unit.unitTm[2], wishYaw, wishPitch)
wto_drive_turret_and_sample_barrel(unit, dt, wishYaw, wishPitch, slot, muzzlePos, liveBarrelDir) wto_drive_mounted_gun(unit, className, dt, wishYaw, wishPitch, slot)
if !engageValid || distToTgt > WTO_AI_FC_MAX_RANGE_M let canEngage = engageValid && distToTgt <= WTO_AI_FC_MAX_RANGE_M && wto_sample_muzzle(unit, primaryIndex, muzzlePos, liveBarrelDir)
wto_set_hull_aim(unit, canEngage, wishYaw, liveBarrelDir, slot)
if !canEngage
wto_clear_aim_tracking(slot.fire) wto_clear_aim_tracking(slot.fire)
return return
let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos)) let distXZ = sqrt(wto_xz_dist_sq(unit.pos, slot.perceive.knownPos))
+5 -2
View File
@@ -186,12 +186,15 @@ def public wto_fire_gate_try_shoot(world : WtoWorldSnap const&; var unit : Unit?
let speedOk = measuredSpeed <= speedLimit let speedOk = measuredSpeed <= speedLimit
let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M
let allowErrDeg = clamp(atan2(WTO_AI_FC_CLOSE_HIT_RADIUS_M, max(distXZ, 6.0)) * WTO_RAD_TO_DEG, WTO_AI_FC_BASE_ALIGN_DEG, 2.4) let allowErrDeg = clamp(atan2(WTO_AI_FC_CLOSE_HIT_RADIUS_M, max(distXZ, 6.0)) * WTO_RAD_TO_DEG, WTO_AI_FC_BASE_ALIGN_DEG, 2.4)
wto_gate_track_aim(now, liveDir - wishDir, slot.perceive.targetEid, aimErrDeg <= allowErrDeg && speedOk, close, fc) let withinTraverse = fc.hullAimTarget == INVALID_ENTITY_ID
wto_gate_track_aim(now, liveDir - wishDir, slot.perceive.targetEid, withinTraverse && aimErrDeg <= allowErrDeg && speedOk, close, fc)
let minCadence = slot.spec.isAutocannonBelt ? 0.12 : 0.65 let minCadence = slot.spec.isAutocannonBelt ? 0.12 : 0.65
let reqHold = close ? WTO_AI_FC_CLOSE_SETTLE_HOLD_SEC : WTO_AI_FC_SETTLE_HOLD_SEC let reqHold = close ? WTO_AI_FC_CLOSE_SETTLE_HOLD_SEC : WTO_AI_FC_SETTLE_HOLD_SEC
var deny = WTO_DENY_OK var deny = WTO_DENY_OK
if !fc.gunReady || (now - fc.lastShotAt) < minCadence if !withinTraverse
deny = WTO_DENY_TRAVERSE
elif !fc.gunReady || (now - fc.lastShotAt) < minCadence
deny = WTO_DENY_NOT_READY deny = WTO_DENY_NOT_READY
elif !speedOk elif !speedOk
deny = WTO_DENY_SPEED deny = WTO_DENY_SPEED
+16 -11
View File
@@ -12,6 +12,7 @@ require math
require %appGame.wtoai.wto_ai_config_common require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_drive_common
require %appGame.wtoai.wto_ai_terrain_common require %appGame.wtoai.wto_ai_terrain_common
require %appGame.wtoai.wto_ai_world_common require %appGame.wtoai.wto_ai_world_common
require %appGame.wtoai.wto_ai_crowd_common require %appGame.wtoai.wto_ai_crowd_common
@@ -155,16 +156,17 @@ def private wto_set_drive_cmd(var cmd : WtoDriveCmd&; mode : int; targetPos, des
cmd.rearClearM = rearClr cmd.rearClearM = rearClr
[never_inline] [never_inline]
def private wto_handle_stationary_engage(myPos, hullFwd : float3; var slot : WtoBotSlot&) def private wto_try_hull_aim(myPos, hullFwd : float3; var slot : WtoBotSlot&) : bool
// Casemate / limited-traverse TDs rotate hull ONLY while target is outside 78% of gun arc. let state = slot.tactics.state
if slot.spec.isLimitedTraverse && !!slot.perceive.targetEid if state != WTO_STATE_MARCH && state != WTO_STATE_RUN_AND_GUN && state != WTO_STATE_PREAIM && state != WTO_STATE_SHORT_HALT
let toTgt = wto_xz_normalize(slot.perceive.knownPos - myPos, hullFwd) return false
let angDeg = acos(clamp(dot(toTgt, hullFwd), -1.0, 1.0)) * WTO_RAD_TO_DEG if !slot.fire.hullAimTarget || slot.fire.hullAimTarget != slot.perceive.targetEid || slot.tactics.immobilized
if angDeg > slot.spec.yawLimitDeg * 0.78 return false
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos + toTgt * 18.0, toTgt, 2.0, slot.nav.frontClearM, slot.nav.rearClearM) if wto_pivot_drive_mode(slot.spec, slot.nav.frontClearM, slot.nav.rearClearM, true) == WTO_DRIVE_HALT
return return false
// Turreted tanks (and aligned TDs) hold chassis completely still so barrel settles cleanly! let direction = wto_xz_normalize(slot.fire.hullAimDir, hullFwd)
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_PIVOT, myPos, direction, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
return true
[never_inline] [never_inline]
def private wto_check_stuck_watchdog(var world : WtoWorldSnap&; now : float; def private wto_check_stuck_watchdog(var world : WtoWorldSnap&; now : float;
@@ -230,9 +232,12 @@ def public wto_nav_update(var world : WtoWorldSnap&; now : float;
else else
wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM) wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
return return
if wto_try_hull_aim(myPos, hullFwd, slot)
slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
return
if slot.tactics.state == WTO_STATE_SHORT_HALT || slot.tactics.state == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05 if slot.tactics.state == WTO_STATE_SHORT_HALT || slot.tactics.state == WTO_STATE_COVER_RELOAD || slot.tactics.desiredSpeedMps <= 0.05
slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC slot.nav.stuckCheckAt = now + WTO_AI_NAV_STUCK_WINDOW_SEC
wto_handle_stationary_engage(myPos, hullFwd, slot) wto_set_drive_cmd(slot.driveCmd, WTO_DRIVE_HALT, myPos, hullFwd, 0.0, slot.nav.frontClearM, slot.nav.rearClearM)
return return
if wto_try_reverse_drive(world, now, myPos, hullFwd, slot) if wto_try_reverse_drive(world, now, myPos, hullFwd, slot)
return return
+1 -1
View File
@@ -268,10 +268,10 @@ def wto_ai_pipeline_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref :
if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL if WTO_AI_LAYER_TACTICS || WTO_AI_LAYER_FIRE_CONTROL
wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot) wto_perceive_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], slot)
wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd) wto_tactics_update(g_world, now, WTO_AI_TACTICS_TICK_SEC, unit.pos, unit.unitTm[0], unit.isBurn, repair_system_remaining_repair_time, slot, g_crowd)
wto_fire_update(g_world, unit, unit__className, now, act.dt, slot, g_fire_budget)
if now >= slot.nextNavAt if now >= slot.nextNavAt
slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC slot.nextNavAt = now + WTO_AI_NAV_TICK_SEC
wto_nav_update(g_world, now, unit.pos, unit.unitTm[0], slot) wto_nav_update(g_world, now, unit.pos, unit.unitTm[0], slot)
wto_fire_update(g_world, unit, now, act.dt, slot, g_fire_budget)
[es(tag=server, after=wto_ai_pipeline_es)] [es(tag=server, after=wto_ai_pipeline_es)]
def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&; def wto_ai_phys_tick_es(act : UpdateStageInfoAct; eid : EntityId; var unit__ref : UnitRef&;
+10 -42
View File
@@ -1,6 +1,6 @@
// Authoritative per-vehicle specification loader: reads unit & weapon DataBlocks once per // Authoritative per-vehicle specification loader: reads unit & weapon DataBlocks once per
// spawned bot (`gamedata/units/<className>.blk`) to extract exact role, gun stabilizer, // spawned bot (`gamedata/units/<className>.blk`) to extract role, gun stabilizer,
// traverse limits, turret slew rates, shell muzzle velocity, and reverse speed capability. // turret slew rates, shell muzzle velocity, and chassis capabilities.
options indenting = 2 options indenting = 2
options no_global_heap = true options no_global_heap = true
module wto_ai_specs_common shared module wto_ai_specs_common shared
@@ -19,6 +19,7 @@ require %game.utils.utils_common
require %appGame.wtoai.wto_ai_math_common require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_combat_types_common require %appGame.wtoai.wto_ai_combat_types_common
require %appGame.wtoai.wto_ai_types_common require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_traverse_common
[never_inline] [never_inline]
def private wto_parse_role_strings(unitType : string; expClass : string; isLightTag : bool) : int def private wto_parse_role_strings(unitType : string; expClass : string; isLightTag : bool) : int
@@ -32,40 +33,6 @@ def private wto_parse_role_strings(unitType : string; expClass : string; isLight
return WTO_ROLE_LIGHT return WTO_ROLE_LIGHT
return WTO_ROLE_MEDIUM return WTO_ROLE_MEDIUM
[never_inline]
def private wto_parse_turret_limits(turretBlk : DataBlock const?; var spec : WtoVehicleSpec&)
if turretBlk == null
return
let lim1 = *turretBlk |> datablock_getPoint4("lim1", float4(0.0, 0.0, 0.0, 0.0))
let lim2 = *turretBlk |> datablock_getPoint4("lim2", float4(0.0, 0.0, 0.0, 0.0))
var maxAbsYaw = 0.0
var minPitch = 0.0
var maxPitch = 0.0
if abs(lim1.x) > 0.1 || abs(lim1.y) > 0.1
maxAbsYaw = max(maxAbsYaw, max(abs(lim1.x), abs(lim1.y)))
minPitch = min(minPitch, lim1.z)
maxPitch = max(maxPitch, lim1.w)
if abs(lim2.x) > 0.1 || abs(lim2.y) > 0.1
maxAbsYaw = max(maxAbsYaw, max(abs(lim2.x), abs(lim2.y)))
minPitch = min(minPitch, lim2.z)
maxPitch = max(maxPitch, lim2.w)
let limitsBlk = *turretBlk |> datablock_get_block_by_name("limits")
if limitsBlk != null
let yawRange = *limitsBlk |> datablock_getPoint2("yaw", float2(0.0, 0.0))
let pitchRange = *limitsBlk |> datablock_getPoint2("pitch", float2(0.0, 0.0))
if abs(yawRange.x) > 0.1 || abs(yawRange.y) > 0.1
maxAbsYaw = max(maxAbsYaw, max(abs(yawRange.x), abs(yawRange.y)))
if pitchRange.x < -0.1 || pitchRange.y > 0.1
minPitch = min(minPitch, pitchRange.x)
maxPitch = max(maxPitch, pitchRange.y)
if maxAbsYaw > 0.5
spec.yawLimitDeg = clamp(maxAbsYaw, 4.0, 180.0)
spec.isLimitedTraverse = spec.yawLimitDeg < 75.0
if minPitch < -0.5
spec.minPitchDeg = clamp(minPitch, -25.0, -2.0)
if maxPitch > 1.0
spec.maxPitchDeg = clamp(maxPitch, 8.0, 88.0)
[never_inline] [never_inline]
def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicleSpec&; isDefault : bool) def private wto_record_shell_block(bBlk : DataBlock const&; var spec : WtoVehicleSpec&; isDefault : bool)
let spd = bBlk |> datablock_getReal("speed", 0.0) let spd = bBlk |> datablock_getReal("speed", 0.0)
@@ -122,7 +89,7 @@ def private wto_parse_weapon_blk(weapBlkPath : string; var spec : WtoVehicleSpec
def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec : WtoVehicleSpec&) : bool def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec : WtoVehicleSpec&) : bool
if empty(className) if empty(className)
return false return false
let relPath = find(className, "/") >= 0 ? ("gamedata/units/" + className + ".blk") : ("gamedata/units/tankModels/" + className + ".blk") let relPath = wto_unit_model_path(className)
var loaded = false var loaded = false
datablock_load_cached(relPath, DataBlockReadFlag.ROBUST) <| $(mBlk) datablock_load_cached(relPath, DataBlockReadFlag.ROBUST) <| $(mBlk)
if mBlk.paramCount == 0u && mBlk.blockCount == 0u if mBlk.paramCount == 0u && mBlk.blockCount == 0u
@@ -137,6 +104,11 @@ def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec :
spec.vMaxFwd = clamp(fwdKmh / 3.6, 4.0, 28.0) spec.vMaxFwd = clamp(fwdKmh / 3.6, 4.0, 28.0)
if revKmh > 1.0 if revKmh > 1.0
spec.vMaxRev = clamp(revKmh / 3.6, 1.0, 16.0) spec.vMaxRev = clamp(revKmh / 3.6, 1.0, 16.0)
let physBlk = mBlk |> datablock_get_block_by_name("VehiclePhys")
if physBlk != null
let mechanics = *physBlk |> datablock_get_block_by_name("mechanics")
if mechanics != null
spec.canPivot = (*mechanics |> datablock_getReal("neutralGearRatio", 0.0)) > 0.0
let commonBlk = mBlk |> datablock_get_block_by_name("commonWeapons") let commonBlk = mBlk |> datablock_get_block_by_name("commonWeapons")
if commonBlk == null if commonBlk == null
return return
@@ -156,7 +128,6 @@ def private wto_parse_unit_blk(className : string; isLightTag : bool; var spec :
let stabBlk = weapBlk |> datablock_get_block_by_name("gunStabilizer") let stabBlk = weapBlk |> datablock_get_block_by_name("gunStabilizer")
if stabBlk != null if stabBlk != null
spec.hasVertStab = *stabBlk |> datablock_getBool("hasVertical", false) spec.hasVertStab = *stabBlk |> datablock_getBool("hasVertical", false)
wto_parse_turret_limits(weapBlk |> datablock_get_block_by_name("turret"), spec)
wto_parse_weapon_blk(wPath, spec) wto_parse_weapon_blk(wPath, spec)
return loaded return loaded
@@ -182,11 +153,8 @@ def private wto_apply_runtime_fallbacks(unit : Unit const?; gm : IGroundModel co
elif as_gun(weapon) != null elif as_gun(weapon) != null
gunCount++ gunCount++
spec.isPureLauncher = gunCount == 0 && launcherCount > 0 spec.isPureLauncher = gunCount == 0 && launcherCount > 0
if length(unit.weap.turret) == 0 && gunCount > 0
spec.isLimitedTraverse = true
spec.yawLimitDeg = min(spec.yawLimitDeg, 12.0)
if !blkLoaded if !blkLoaded
if spec.isLimitedTraverse if length(unit.weap.turret) == 0 && gunCount > 0
spec.role = WTO_ROLE_TD spec.role = WTO_ROLE_TD
elif isLightTag elif isLightTag
spec.role = WTO_ROLE_LIGHT spec.role = WTO_ROLE_LIGHT
+1 -2
View File
@@ -139,8 +139,7 @@ def private wto_sm_handle_combat(world : WtoWorldSnap const&; now : float;
let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M let close = distXZ <= WTO_AI_FC_CLOSE_RANGE_M
let urgentPush = slot.order.urgency == WTO_URGENCY_HIGH || distGoal > 130.0 let urgentPush = slot.order.urgency == WTO_URGENCY_HIGH || distGoal > 130.0
let canHalt = now >= tac.shortHaltCooldownUntil && !tac.repositionActive && wto_sm_stop_range_allowed(distXZ, slot) let canHalt = now >= tac.shortHaltCooldownUntil && !tac.repositionActive && wto_sm_stop_range_allowed(distXZ, slot)
let aimReady = (fc.gunReady && fc.aimTargetEid == slot.perceive.targetEid && let aimReady = (fc.gunReady && fc.aimTargetEid == slot.perceive.targetEid && fc.lastAimErrDeg <= WTO_AI_SM_PREAIM_DEG)
(fc.lastAimErrDeg <= WTO_AI_SM_PREAIM_DEG || slot.spec.isLimitedTraverse))
if marchSpd > 0.0 && (close || (distXZ <= WTO_AI_FC_MID_RANGE_M && urgentPush)) if marchSpd > 0.0 && (close || (distXZ <= WTO_AI_FC_MID_RANGE_M && urgentPush))
if wto_sm_waited_for_moving_shot(now, aimReady, slot) && canHalt if wto_sm_waited_for_moving_shot(now, aimReady, slot) && canHalt
wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "moving_shot_halt", distXZ, slot) wto_sm_set_state(now, WTO_STATE_SHORT_HALT, myPos, 0.0, "moving_shot_halt", distXZ, slot)
+202
View File
@@ -0,0 +1,202 @@
// Mechanical angles of the selected ground weapon, read from the original mount definition.
options indenting = 2
options no_global_heap = true
module wto_ai_traverse_common shared
require ecs
require app
require math
require strings
require DagorMath
require DagorDataBlock
require Unit
require Weapon
require %game.utils.utils_common
require %appGame.wtoai.wto_ai_config_common
require %appGame.wtoai.wto_ai_math_common
require %appGame.wtoai.wto_ai_types_common
require %appGame.wtoai.wto_ai_combat_types_common
// The engine's weapon trigger parser maps "gunnerN" to N + 0x13.
let private WTO_FIRST_GUNNER_TRIGGER = int(0x13)
def public wto_unit_model_path(className : string) : string
return find(className, "/") >= 0 ? ("gamedata/units/" + className + ".blk") : ("gamedata/units/tankModels/" + className + ".blk")
def private wto_valid_angle_range(angles : float2) : bool
return wto_is_finite(angles.x) && wto_is_finite(angles.y) && angles.x <= angles.y
[never_inline]
def private wto_read_gunner_mount(className : string; triggerNo, weaponIndex : int;
readMount : block<(mount : DataBlock) : void>)
if empty(className) || triggerNo < WTO_FIRST_GUNNER_TRIGGER || weaponIndex < 0
return
let trigger = "gunner{triggerNo - WTO_FIRST_GUNNER_TRIGGER}"
datablock_load_cached(wto_unit_model_path(className), DataBlockReadFlag.ROBUST) <| $(unitBlk)
let common = unitBlk |> datablock_get_block_by_name("commonWeapons")
if common == null
return
var index = 0
datablock_for_each_block(*common, "Weapon") <| $(mount)
if (mount |> datablock_getStr("trigger", "")) != trigger
return
if index == weaponIndex && (mount |> datablock_getStr("triggerGroup", "primary")) == "primary"
invoke(readMount, mount)
index++
[never_inline]
def private wto_load_gun_traverse(className : string; triggerNo, weaponIndex : int; var traverse : WtoGunTraverse&)
traverse = WtoGunTraverse()
wto_read_gunner_mount(className, triggerNo, weaponIndex) <| $(mount)
let limits = mount |> datablock_get_block_by_name("limits")
if limits == null
return
let yaw = *limits |> datablock_getPoint2("yaw", float2(1.0, 0.0))
if !wto_valid_angle_range(yaw) || abs(yaw.x) > 360.0 || abs(yaw.y) > 360.0
return
traverse.known = true
traverse.yaw = yaw
let pitch = *limits |> datablock_getPoint2("pitch", float2(1.0, 0.0))
if wto_valid_angle_range(pitch)
traverse.pitch = pitch
let sectors = mount |> datablock_get_block_by_name("limitsTable")
traverse.hasPitchTable = sectors != null && sectors.paramCount > 0u
def private wto_full_gun_traverse(yaw : float2) : bool
return yaw.y - yaw.x >= 360.0
def private wto_yaw_in_mount_coordinates(yaw : float; arc : float2) : float
let center = (arc.x + arc.y) * 0.5
return center + wto_wrap_deg(yaw - center)
[never_inline]
def private wto_gun_pitch_at_yaw(className : string; triggerNo, weaponIndex : int; yaw : float;
var traverse : WtoGunTraverse&) : float2
if !traverse.hasPitchTable
return traverse.pitch
if yaw >= traverse.pitchSector.x && yaw < traverse.pitchSector.y
return float2(traverse.pitchSector.z, traverse.pitchSector.w)
var sector = float4(traverse.yaw.x, traverse.yaw.y, traverse.pitch.x, traverse.pitch.y)
wto_read_gunner_mount(className, triggerNo, weaponIndex) <| $(mount)
let sectors = mount |> datablock_get_block_by_name("limitsTable")
if sectors == null
return
// A DataBlock can repeat a parameter name. Read each sector by its original index.
for index in 0u..sectors.paramCount
if (*sectors |> datablock_getParamType(index)) != int(DataBlockParamType.TYPE_POINT4)
continue
let entry = *sectors |> datablock_getPoint4(int(index))
if !wto_valid_angle_range(float2(entry.x, entry.y)) || !wto_valid_angle_range(float2(entry.z, entry.w))
continue
if yaw < entry.x
sector.y = min(sector.y, entry.x)
elif yaw > entry.y
sector.x = max(sector.x, entry.y)
else
sector = entry
break
traverse.pitchSector = sector
return float2(sector.z, sector.w)
[never_inline]
def public wto_world_to_hull_deg(worldDir, hullFwd, hullUp, hullLeft : float3;
var outYawDeg, outPitchDeg : float&)
let len = length(worldDir)
if !wto_is_finite3(worldDir) || len < 1.0e-5
outYawDeg = 0.0
outPitchDeg = 0.0
return
let d = worldDir / len
let f = dot(d, hullFwd)
let u = dot(d, hullUp)
let l = dot(d, hullLeft)
let horiz = sqrt(f * f + l * l)
outYawDeg = horiz > 1.0e-5 ? (-atan2(l, f) * WTO_RAD_TO_DEG) : 0.0
outPitchDeg = atan2(u, max(1.0e-5, horiz)) * WTO_RAD_TO_DEG
[never_inline]
def private wto_hull_deg_to_world(yawDeg, pitchDeg : float; hullFwd, hullUp, hullLeft : float3) : float3
let yr = yawDeg * WTO_DEG_TO_RAD
let pr = pitchDeg * WTO_DEG_TO_RAD
let cp = cos(pr)
let dir = hullFwd * (cp * cos(yr)) - hullLeft * (cp * sin(yr)) + hullUp * sin(pr)
let l = length(dir)
return l > 1.0e-5 ? (dir / l) : hullFwd
def private wto_step_mounted_yaw(current, desired, step : float; arc : float2) : float
if wto_full_gun_traverse(arc)
return wto_wrap_deg(current + clamp(wto_wrap_deg(desired - current), -step, step))
let clampedCurrent = clamp(wto_yaw_in_mount_coordinates(current, arc), arc.x, arc.y)
let clampedTarget = clamp(wto_yaw_in_mount_coordinates(desired, arc), arc.x, arc.y)
return clamp(clampedCurrent + clamp(clampedTarget - clampedCurrent, -step, step), arc.x, arc.y)
def private wto_track_blocked_pitch(wishPitchDeg, dtStep : float; var slot : WtoBotSlot&)
assume fc = slot.fire
let pitchSpd = abs(fc.curPitchDeg - fc.prevPitchDeg) / dtStep
fc.prevPitchDeg = fc.curPitchDeg
if slot.perceive.hasClearLos && wishPitchDeg < fc.curPitchDeg - 2.3 && pitchSpd < 0.8
fc.pitchClampSec = min(2.0, fc.pitchClampSec + dtStep)
fc.pitchBlocked = fc.pitchClampSec >= 0.75
else
fc.pitchClampSec = max(0.0, fc.pitchClampSec - dtStep * 2.5)
if fc.pitchClampSec <= 0.05
fc.pitchBlocked = false
[never_inline]
def public wto_drive_mounted_gun(var unit : Unit?; className : string; dt : float;
wishYawDeg, wishPitchDeg : float; var slot : WtoBotSlot&)
assume fc = slot.fire
let dtStep = clamp(dt, 0.005, 0.12)
if fc.traverseTurretNo != fc.turretNo
fc.traverseTurretNo = fc.turretNo
fc.traverse = WtoGunTraverse()
fc.servoInit = false
fc.pitchBlocked = false
fc.pitchClampSec = 0.0
for tIdx, turret in iter_range(unit.weap.turret), unit.weap.turret
if tIdx != fc.turretNo
continue
let triggerNo = int(turret.triggerNo)
let weaponIndex = int(turret.weaponIndex)
if !fc.servoInit
wto_load_gun_traverse(className, triggerNo, weaponIndex, fc.traverse)
fc.prevPitchDeg = turret.currentState.pitch
fc.servoInit = true
fc.curYawDeg = turret.currentState.yaw
fc.curPitchDeg = turret.currentState.pitch
if !fc.traverse.known
return
wto_track_blocked_pitch(wishPitchDeg, dtStep, slot)
let yaw = fc.traverse.yaw
let maxYawStep = max(24.0, slot.spec.turretYawSpd * 1.1) * dtStep
let cmdYaw = wto_step_mounted_yaw(fc.curYawDeg, wishYawDeg, maxYawStep, yaw)
let maxPitchStep = max(10.0, slot.spec.turretPitchSpd * 1.1) * dtStep
let pitch = wto_gun_pitch_at_yaw(className, triggerNo, weaponIndex, cmdYaw, fc.traverse)
turret.yawLim = cmdYaw
if pitch.x <= pitch.y
let pitchDelta = clamp(wishPitchDeg - fc.curPitchDeg, -maxPitchStep, maxPitchStep)
turret.pitchLim = clamp(fc.curPitchDeg + pitchDelta, pitch.x, pitch.y)
break
if fc.traverse.known
var uPos = unit.pos
updateWeaponAnims(*unit.weap, dtStep, 1.0, uPos)
def public wto_set_hull_aim(unit : Unit const?; active : bool; wishYaw : float; liveBarrelDir : float3;
var slot : WtoBotSlot&)
assume fc = slot.fire
var target = INVALID_ENTITY_ID
if active
var arc = fc.traverse.yaw
if !fc.traverse.known
var fixedYaw, pitch : float
wto_world_to_hull_deg(liveBarrelDir, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2], fixedYaw, pitch)
arc = float2(fixedYaw, fixedYaw)
let aimYaw = wto_yaw_in_mount_coordinates(wishYaw, arc)
let tolerance = arc.x == arc.y ? WTO_AI_FC_BASE_ALIGN_DEG : 0.0
if !wto_full_gun_traverse(arc) && (aimYaw < arc.x - tolerance || aimYaw > arc.y + tolerance)
target = slot.perceive.targetEid
let yawToTurn = wto_wrap_deg(wishYaw - (arc.x + arc.y) * 0.5)
fc.hullAimDir = wto_hull_deg_to_world(yawToTurn, 0.0, unit.unitTm[0], unit.unitTm[1], unit.unitTm[2])
if target != fc.hullAimTarget
slot.nextNavAt = 0.0
fc.hullAimTarget = target
-4
View File
@@ -45,10 +45,6 @@ struct public WtoVehicleSpec
ready : bool = false ready : bool = false
role : int = 0 role : int = 0
hasVertStab : bool = false hasVertStab : bool = false
isLimitedTraverse : bool = false
yawLimitDeg : float = 180.0
minPitchDeg : float = -8.0
maxPitchDeg : float = 22.0
turretYawSpd : float = 24.0 turretYawSpd : float = 24.0
turretPitchSpd : float = 8.0 turretPitchSpd : float = 8.0
muzzleSpeedMps : float = 880.0 muzzleSpeedMps : float = 880.0
+1
View File
@@ -141,6 +141,7 @@ Manifest parsing enforces **strict whitelist validation**: typos or unknown keys
| `conflicts` | No | `string[]` | Mutually incompatible mod IDs; enabling both raises a **blocking error** | | `conflicts` | No | `string[]` | Mutually incompatible mod IDs; enabling both raises a **blocking error** |
| `load_after` | No | `string[]` | Optional mods this mod should load after (lower in the list = higher priority); does not require them to be enabled, and participates in order hints & **Auto-Sort** | | `load_after` | No | `string[]` | Optional mods this mod should load after (lower in the list = higher priority); does not require them to be enabled, and participates in order hints & **Auto-Sort** |
| `load_before` | No | `string[]` | Optional mods this mod should load before; also participates in order hints & **Auto-Sort** | | `load_before` | No | `string[]` | Optional mods this mod should load before; also participates in order hints & **Auto-Sort** |
| `tech_tree_insertions` | No | `{ vehicle: string, after: string, before: string }[]` | Inserts vehicles into an existing research link in mod load order. [Example](02-client-packs-and-blk.md#63-inserting-vehicles-into-the-same-research-link) |
| `server` | No | `{ entry?: string, tuning?: string }` | Explicit relative paths (no `..`) overriding default auto-detection of `server/index.{ts,mjs,js}` and `server/tuning` | | `server` | No | `{ entry?: string, tuning?: string }` | Explicit relative paths (no `..`) overriding default auto-detection of `server/index.{ts,mjs,js}` and `server/tuning` |
--- ---
+15 -1
View File
@@ -328,7 +328,7 @@ Keep three rules in mind when writing `shop.blk.patch.blk` (or `.patch.jsonc`):
2. **Collapsible folder groups (`*_group`)**: when multiple variants share one tech-tree folder, `range` contains a child block ending in `_group` (e.g. `us_sherman_group`) whose children are the grouped vehicles; the folder's display label comes from `shop/group/<group_name>` in `units.csv`; 2. **Collapsible folder groups (`*_group`)**: when multiple variants share one tech-tree folder, `range` contains a child block ending in `_group` (e.g. `us_sherman_group`) whose children are the grouped vehicles; the folder's display label comes from `shop/group/<group_name>` in `units.csv`;
3. **Why is the prerequisite arrow field named `reqAir` even on tanks and ships?** 3. **Why is the prerequisite arrow field named `reqAir` even on tanks and ships?**
War Thunder began life as an aviation-only game (*World of Planes*), so `air` / `aircraft` remained the universal internal noun for any unit. Consequently, **`reqAir` defines the research prerequisite vehicle across tanks, helicopters, aircraft, and ships alike**! War Thunder began life as an aviation-only game (*World of Planes*), so `air` / `aircraft` remained the universal internal noun for any unit. Consequently, **`reqAir` defines the research prerequisite vehicle across tanks, helicopters, aircraft, and ships alike**!
- Setting `reqAir:t="us_m2a4"` in `wpcost.blk` requires owning `us_m2a4` before researching the unit; - With `reqAir:t="us_m2a4"` in `wpcost.blk`, completing research on `us_m2a4` unlocks research on this vehicle. Buying this vehicle requires owning `us_m2a4`.
- Inside a `range` column in `shop.blk`: consecutive vehicles with no `reqAir` property automatically connect with vertical arrows; `reqAir:t="us_m2a4"` draws an explicit arrow from `us_m2a4`; and **`reqAir:t=""` (empty string) explicitly breaks the arrow from the vehicle above it** (used at mid-column gaps and throughout the right-hand premium/pack columns). - Inside a `range` column in `shop.blk`: consecutive vehicles with no `reqAir` property automatically connect with vertical arrows; `reqAir:t="us_m2a4"` draws an explicit arrow from `us_m2a4`; and **`reqAir:t=""` (empty string) explicitly breaks the arrow from the vehicle above it** (used at mid-column gaps and throughout the right-hand premium/pack columns).
### 6.2 All 4 `lang/units.csv` Keys & Incremental CSV Merging ### 6.2 All 4 `lang/units.csv` Keys & Incremental CSV Merging
@@ -357,6 +357,20 @@ Example `client/packs/lang.vromfs.bin/lang/units.csv.patch.csv`:
--- ---
### 6.3 Inserting Vehicles into the Same Research Link
Supply the vehicle definition and its `wpcost.blk` entry, then declare the research link in `mod.jsonc`. In 2.61.0.64, the F-15C MSIP II follows the F-15A.
```jsonc
"tech_tree_insertions": [
{ "vehicle": "my_fighter", "after": "f_15a", "before": "f_15c_msip2" }
]
```
- `vehicle` is the mod vehicle ID. `after` and `before` are the existing predecessor and successor IDs. The builder checks that `before` requires `after` in `wpcost.blk` after the ordinary overlays. When migrating a manual insertion, remove the successor's manual `reqAir` edits so the builder can handle the link.
- Use regular vehicles from the same nation and branch, with ranks in nondecreasing order. The builder creates a shop entry or reuses one already declared on the same page. An insertion between members of a folder goes inside that folder. An insertion across columns goes in the successor's column.
- Multiple mods targeting the same link compose `A → X → Y → B` in the launcher's top-to-bottom order. Reordering or toggling mods rebuilds the chain from stock and the current selection. A missing anchor, a changed link, or a cycle produces a build error naming the mod and vehicles.
## 7. Patching Root `config.blk` (`client/config-blk.patch.blk` / `.jsonc`) ## 7. Patching Root `config.blk` (`client/config-blk.patch.blk` / `.jsonc`)
If your mod needs to adjust the client root `config.blk` (for example enabling sound mods via `sound{ enable_mod:b=yes }` or setting a custom hangar `hangarBlk:t="..."`), place a BLK patch at `client/config-blk.patch.blk` (recommended; `client/config-blk.patch.jsonc` is also supported): If your mod needs to adjust the client root `config.blk` (for example enabling sound mods via `sound{ enable_mod:b=yes }` or setting a custom hangar `hangarBlk:t="..."`), place a BLK patch at `client/config-blk.patch.blk` (recommended; `client/config-blk.patch.jsonc` is also supported):
+1
View File
@@ -141,6 +141,7 @@ console.log(formatBlkText(decodeBlk(getFile(ar, 'config/wpcost.blk'), { names: a
| `conflicts` | 否 | `string[]` | 已知互斥模组 ID 列表;同时启用时作为**阻塞错误**阻止启动 | | `conflicts` | 否 | `string[]` | 已知互斥模组 ID 列表;同时启用时作为**阻塞错误**阻止启动 |
| `load_after` | 否 | `string[]` | 建议排在这些可选模组 ID 之后(越靠下越晚加载、优先级越高);不强制要求对方启用,若同时启用则参与顺序提示与「按依赖自动排序」 | | `load_after` | 否 | `string[]` | 建议排在这些可选模组 ID 之后(越靠下越晚加载、优先级越高);不强制要求对方启用,若同时启用则参与顺序提示与「按依赖自动排序」 |
| `load_before` | 否 | `string[]` | 建议排在这些可选模组 ID 之前;同样参与顺序提示与「按依赖自动排序」 | | `load_before` | 否 | `string[]` | 建议排在这些可选模组 ID 之前;同样参与顺序提示与「按依赖自动排序」 |
| `tech_tree_insertions` | 否 | `{ vehicle: string, after: string, before: string }[]` | 按加载顺序把新载具插进指定的研发关系。 [写法](02-client-packs-and-blk.md#63-多个模组插入同一段研发线) |
| `server` | 否 | `{ entry?: string, tuning?: string }` | 显式覆盖服务端入口文件(相对路径,不得含 `..`)和 `tuning` 目录路径(默认自动探测 `server/index.{ts,mjs,js}` 与 `server/tuning`) | | `server` | 否 | `{ entry?: string, tuning?: string }` | 显式覆盖服务端入口文件(相对路径,不得含 `..`)和 `tuning` 目录路径(默认自动探测 `server/index.{ts,mjs,js}` 与 `server/tuning`) |
--- ---
+15 -1
View File
@@ -328,7 +328,7 @@ country_usa (或 country_germany / country_ussr / country_britain / country_japa
2. **折叠文件夹(`*_group`)**:当同一格折叠了多辆同系载具时,`range` 下会放一个以 `_group` 结尾的子块(例如 `us_sherman_group`),里面再嵌套各辆具体载具子块,折叠封面标题来自 `units.csv` 的 `shop/group/<组名>`; 2. **折叠文件夹(`*_group`)**:当同一格折叠了多辆同系载具时,`range` 下会放一个以 `_group` 结尾的子块(例如 `us_sherman_group`),里面再嵌套各辆具体载具子块,折叠封面标题来自 `units.csv` 的 `shop/group/<组名>`;
3. **为什么坦克和军舰的前置研发箭头也叫 `reqAir`?** 3. **为什么坦克和军舰的前置研发箭头也叫 `reqAir`?**
因为《战争雷霆》最早立项时是纯空战游戏(*World of Planes*),所有载具在底层代码里都沿用了 `air` / `aircraft` 命名,因此**无论是坦克、直升机还是战列舰,指定“上一辆前置研发载具”的字段一律叫 `reqAir`**! 因为《战争雷霆》最早立项时是纯空战游戏(*World of Planes*),所有载具在底层代码里都沿用了 `air` / `aircraft` 命名,因此**无论是坦克、直升机还是战列舰,指定“上一辆前置研发载具”的字段一律叫 `reqAir`**!
- 在 `wpcost.blk` 中设置 `reqAir:t="us_m2a4"`:声明玩家必须先拥有 `us_m2a4` 才能研发本车; - 在 `wpcost.blk` 中设置 `reqAir:t="us_m2a4"`:研发完 `us_m2a4` 才能研发本车,购买本车前须拥有 `us_m2a4`;
- 在 `shop.blk` 的同一 `range` 列中:连续排列且未写 `reqAir` 的两辆车默认自动画纵向实线箭头;写 `reqAir:t="us_m2a4"` 会显式从 `us_m2a4` 连出箭头;而写 **`reqAir:t=""`(空字符串)则会显式断开与上方载具的箭头连接**(科技树断线处以及右侧金币/礼包列里的车都用 `reqAir:t=""`)。 - 在 `shop.blk` 的同一 `range` 列中:连续排列且未写 `reqAir` 的两辆车默认自动画纵向实线箭头;写 `reqAir:t="us_m2a4"` 会显式从 `us_m2a4` 连出箭头;而写 **`reqAir:t=""`(空字符串)则会显式断开与上方载具的箭头连接**(科技树断线处以及右侧金币/礼包列里的车都用 `reqAir:t=""`)。
### 6.2 `lang/units.csv` 的 4 个载具译名后缀与 CSV 增量合并 ### 6.2 `lang/units.csv` 的 4 个载具译名后缀与 CSV 增量合并
@@ -357,6 +357,20 @@ CSV 补丁文件写法示例(`client/packs/lang.vromfs.bin/lang/units.csv.patc
--- ---
### 6.3 多个模组插入同一段研发线
给新载具准备好游戏定义和 `wpcost.blk` 条目,在 `mod.jsonc` 加上要插入的研发关系。例如 2.61.0.64 中,F-15C MSIP II 的前置是 F-15A。
```jsonc
"tech_tree_insertions": [
{ "vehicle": "my_fighter", "after": "f_15a", "before": "f_15c_msip2" }
]
```
- `vehicle` 是模组载具 ID。`after`、`before` 是已有的前置和后继 ID。构建器在普通补丁叠加后核对 `before` 的 `reqAir` 是否指向 `after`。从手工接线迁移时,把后继载具对 `reqAir` 的手工覆写删掉,让构建器处理这条关系。
- 锚点和新载具须为同一国家、同一兵种的常规载具,沿线大等级按顺序递增或相等。构建器可以创建 `shop.blk` 格子,也会复用你已经在同一页声明的格子。插入折叠组内的两个成员之间时,新车进入该组。跨列时,新车在后继载具所在列。
- 多个模组声明同一段时,按启动器列表从上到下接成 `A → X → Y → B`。重新排序或调整启用项后,下次构建会从原版和当前模组重新接线。找不到锚点、原连接被改写或组合成循环时,构建错误会指出模组和载具。
## 7. 修改游戏根目录 `config.blk`(`client/config-blk.patch.blk` / `.jsonc`) ## 7. 修改游戏根目录 `config.blk`(`client/config-blk.patch.blk` / `.jsonc`)
如果模组需要调整游戏根目录的 `config.blk`(例如开启音效模组开关 `sound{ enable_mod:b=yes }` 或指定自定义机库 `hangarBlk:t="..."`),放一份 BLK 补丁到 `client/config-blk.patch.blk`(推荐,同样兼容 `client/config-blk.patch.jsonc`)即可: 如果模组需要调整游戏根目录的 `config.blk`(例如开启音效模组开关 `sound{ enable_mod:b=yes }` 或指定自定义机库 `hangarBlk:t="..."`),放一份 BLK 补丁到 `client/config-blk.patch.blk`(推荐,同样兼容 `client/config-blk.patch.jsonc`)即可:
+1 -1
View File
@@ -23,7 +23,7 @@ New-Item -ItemType Directory -Force $obj | Out-Null
$sources = @( $sources = @(
"$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c", "$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c",
"$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c", "$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c",
"$src\local_mp_damage_notifications.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_zones.c", "$src\local_mp_air_ai_sync.c", "$src\local_mp_damage_notifications.c", "$src\local_mp_hit_feedback.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_zones.c", "$src\local_mp_captures.c", "$src\local_mp_air_ai_sync.c",
"$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c" "$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c"
) | ForEach-Object { '"' + (Resolve-Path $_) + '"' } ) | ForEach-Object { '"' + (Resolve-Path $_) + '"' }
+21 -7
View File
@@ -58,7 +58,13 @@ const char *local_mp_unit_exp_class(const uint8_t *unit)
return (exp_class != NULL && exp_class[0] != '\0') ? exp_class : NULL; return (exp_class != NULL && exp_class[0] != '\0') ? exp_class : NULL;
} }
void local_mp_report_award_event(const LocalMpAwardEvent *ev) static const char *bare_unit_name(const char *unit_name)
{
const char *slash = strrchr(unit_name, '/');
return (slash != NULL && slash[1] != '\0') ? slash + 1 : unit_name;
}
static void report_award_event(const LocalMpAwardEvent *ev, const char *source_unit)
{ {
__declspec(align(16)) uint8_t blk[LMP_BLK_SIZE]; __declspec(align(16)) uint8_t blk[LMP_BLK_SIZE];
uint8_t *gsd = g_game_save_data ? *g_game_save_data : NULL; uint8_t *gsd = g_game_save_data ? *g_game_save_data : NULL;
@@ -72,6 +78,8 @@ void local_mp_report_award_event(const LocalMpAwardEvent *ev)
fn_blk_set_str(blk, "expClass", victim_class ? victim_class : ""); fn_blk_set_str(blk, "expClass", victim_class ? victim_class : "");
fn_blk_set_str(blk, "victim", victim_name ? victim_name : ""); fn_blk_set_str(blk, "victim", victim_name ? victim_name : "");
fn_blk_set_str(blk, "messageModifier", ev->modifier ? ev->modifier : ""); fn_blk_set_str(blk, "messageModifier", ev->modifier ? ev->modifier : "");
if (source_unit != NULL)
fn_blk_set_str(blk, "unit", bare_unit_name(source_unit));
blk_set_int(blk, "messageCode", (int32_t)ev->exp_event); blk_set_int(blk, "messageCode", (int32_t)ev->exp_event);
blk_set_int(blk, "victimIsPlayer", ev->victim_is_player ? 1 : 0); blk_set_int(blk, "victimIsPlayer", ev->victim_is_player ? 1 : 0);
blk_set_int(blk, "friendly", ev->friendly ? 1 : 0); blk_set_int(blk, "friendly", ev->friendly ? 1 : 0);
@@ -80,6 +88,17 @@ void local_mp_report_award_event(const LocalMpAwardEvent *ev)
fn_blk_dtor(blk); fn_blk_dtor(blk);
} }
void local_mp_report_award_event(const LocalMpAwardEvent *ev)
{
report_award_event(ev, NULL);
}
void local_mp_report_capture(const char *unit_name)
{
const LocalMpAwardEvent award = { LMP_EXP_EVENT_CAPTURE_ZONE, NULL, 0, 0, NULL, 0 };
report_award_event(&award, unit_name);
}
/* The fact behind the award killStreak_bomber_nuclear_success, which online the battle server /* The fact behind the award killStreak_bomber_nuclear_success, which online the battle server
* judges itself; the event carries no fields. */ * judges itself; the event carries no fields. */
void local_mp_report_nuclear_strike(void) void local_mp_report_nuclear_strike(void)
@@ -114,16 +133,11 @@ void local_mp_report_backup_spawn(const char *unit_name, int32_t slot_id, const
{ {
__declspec(align(16)) uint8_t blk[LMP_BLK_SIZE]; __declspec(align(16)) uint8_t blk[LMP_BLK_SIZE];
uint8_t *gsd = g_game_save_data ? *g_game_save_data : NULL; uint8_t *gsd = g_game_save_data ? *g_game_save_data : NULL;
const char *slash;
if (gsd == NULL || fn_hud_notify_script == NULL || unit_name == NULL) if (gsd == NULL || fn_hud_notify_script == NULL || unit_name == NULL)
return; return;
slash = strrchr(unit_name, '/');
if (slash != NULL && slash[1] != '\0')
unit_name = slash + 1;
memset(blk, 0, sizeof(blk)); memset(blk, 0, sizeof(blk));
fn_blk_ctor(blk); fn_blk_ctor(blk);
fn_blk_set_str(blk, "unit", unit_name); fn_blk_set_str(blk, "unit", bare_unit_name(unit_name));
fn_blk_set_str(blk, "backup", backup); fn_blk_set_str(blk, "backup", backup);
blk_set_int(blk, "slot", slot_id); blk_set_int(blk, "slot", slot_id);
fn_hud_notify_script(gsd + LMP_GSD_OFF_HUD_QUEUE, "wtoLocalMpBackupSpawn", blk); fn_hud_notify_script(gsd + LMP_GSD_OFF_HUD_QUEUE, "wtoLocalMpBackupSpawn", blk);
+108
View File
@@ -0,0 +1,108 @@
/* Credit completed captures using the mission engine's own unit eligibility checks. */
#include "hook_config.h"
#include "local_mp_internal.h"
#include "local_mp_offsets.h"
#include <intrin.h>
#include <windows.h>
typedef void (__fastcall *SetZoneOwnerFn)(uint8_t *zone, int32_t team);
typedef float (__fastcall *TeamCapturePowerFn)(int32_t team, uint8_t *zone, int32_t *count);
typedef float (__fastcall *UnitCapturePowerFn)(uint8_t *zone, const uint8_t *unit);
typedef struct CaptureAward {
uint8_t *player;
const char *unit_name;
float power;
float score;
} CaptureAward;
typedef struct CaptureScan {
const uint8_t *zone;
int32_t team;
CaptureAward awards[UINT8_MAX + 1];
} CaptureScan;
static __declspec(thread) CaptureScan *active_scan;
static SetZoneOwnerFn original_set_owner;
static UnitCapturePowerFn original_unit_power;
static uintptr_t cta_end;
static float __fastcall hook_unit_power(uint8_t *zone, const uint8_t *unit)
{
float power = original_unit_power(zone, unit);
CaptureScan *scan = active_scan;
if (scan == NULL || scan->zone != zone || unit == NULL || !(power > 0.0f))
return power;
uint8_t *player = *(uint8_t *const *)(unit + LMP_UNIT_OFF_MPLAYER);
if (player == NULL || player[LMP_MP_OFF_TEAM] != scan->team)
return power;
CaptureAward *award = &scan->awards[player[LMP_MP_OFF_PID]];
if (power > award->power) {
award->player = player;
award->unit_name = local_mp_unit_name(unit);
award->power = power;
award->score = local_mp_event_score("capture", unit, 1);
}
return power;
}
static int is_capture_completion(uintptr_t return_address)
{
return return_address == (uintptr_t)g_lmp.capture_complete_call + LMP_REL32_CALL_SIZE ||
(return_address >= (uintptr_t)g_lmp.capture_cta_logic && return_address < cta_end);
}
static void credit_capture(const CaptureAward *award)
{
uint8_t *player = award->player;
local_mp_inc_mplayer_stat(player, LMP_MP_OFF_CAPTURE_ZONE);
local_mp_add_personal_score(player, award->score, LMP_EXP_EVENT_CAPTURE_ZONE);
local_mp_mark_mplayer_dirty(player);
if (local_mp_is_local_mplayer(player))
local_mp_report_capture(award->unit_name);
}
static void __fastcall hook_set_owner(uint8_t *zone, int32_t team)
{
if (!local_mp_is_host() || !is_capture_completion((uintptr_t)_ReturnAddress()) ||
(team != 1 && team != 2) || zone[g_lmp.capture_owner] == team) {
original_set_owner(zone, team);
return;
}
/* Run the same side's eligibility walk immediately before the ownership commit. A player
can have several eligible units in that walk, so credit their strongest one once. */
CaptureScan scan = { .zone = zone, .team = team };
CaptureScan *previous = active_scan;
int32_t count = 0;
active_scan = &scan;
((TeamCapturePowerFn)g_lmp.capture_team_power)(team, zone, &count);
active_scan = previous;
original_set_owner(zone, team);
if (zone[g_lmp.capture_owner] != team)
return;
for (size_t pid = 0; pid < sizeof(scan.awards) / sizeof(scan.awards[0]); ++pid) {
if (scan.awards[pid].player != NULL)
credit_capture(&scan.awards[pid]);
}
}
int install_local_mp_capture_hooks(void)
{
DWORD64 base;
const RUNTIME_FUNCTION *cta = RtlLookupFunctionEntry((DWORD64)g_lmp.capture_cta_logic, &base, NULL);
if (cta == NULL || g_lmp.capture_complete_set_owner != g_lmp.capture_set_owner) {
log_line("local_mp: local_mp_captures skipped: inconsistent ownership call sites");
return 0;
}
cta_end = (uintptr_t)(base + cta->EndAddress);
const LocalMpHookSpec hooks[] = {
{ "capture_set_owner", g_lmp.capture_set_owner, (void *)&hook_set_owner, (void **)&original_set_owner },
{ "capture_unit_power", g_lmp.capture_unit_power, (void *)&hook_unit_power, (void **)&original_unit_power },
};
return local_mp_queue_hooks("local_mp_captures", hooks, sizeof(hooks) / sizeof(hooks[0]));
}
+2
View File
@@ -139,10 +139,12 @@ static const LocalMpModule MODULES[] = {
{ "local_mp_scores", install_local_mp_score_reader }, { "local_mp_scores", install_local_mp_score_reader },
{ "local_mp_kills", install_local_mp_kill_hooks }, { "local_mp_kills", install_local_mp_kill_hooks },
{ "local_mp_events", install_local_mp_event_hooks }, { "local_mp_events", install_local_mp_event_hooks },
{ "local_mp_captures", install_local_mp_capture_hooks },
{ "local_mp_zones", install_local_mp_zone_hooks }, { "local_mp_zones", install_local_mp_zone_hooks },
{ "local_mp_nuke", install_local_mp_nuke_hooks }, { "local_mp_nuke", install_local_mp_nuke_hooks },
{ "local_mp_support", install_local_mp_support_hooks }, { "local_mp_support", install_local_mp_support_hooks },
{ "local_mp_damage_notifications", install_local_mp_damage_notification_hooks }, { "local_mp_damage_notifications", install_local_mp_damage_notification_hooks },
{ "local_mp_hit_feedback", install_local_mp_hit_feedback_hooks },
{ "local_mp_air_events", install_local_mp_air_event_hooks }, { "local_mp_air_events", install_local_mp_air_event_hooks },
{ "local_mp_ground_ai", install_local_mp_ground_ai_hooks }, { "local_mp_ground_ai", install_local_mp_ground_ai_hooks },
{ "local_mp_air_ai_sync", install_local_mp_air_ai_sync_hooks }, { "local_mp_air_ai_sync", install_local_mp_air_ai_sync_hooks },
@@ -56,6 +56,7 @@ static int suppressed_avionics_logged;
static int suppressed_optic_logged; static int suppressed_optic_logged;
static int suppressed_parts_logged; static int suppressed_parts_logged;
static int suppressed_enemy_mpi_logged; static int suppressed_enemy_mpi_logged;
static int damage_hooks_queued;
static const uint8_t *local_mplayer(void) static const uint8_t *local_mplayer(void)
{ {
@@ -99,17 +100,29 @@ static const uint8_t *watched_unit(const uint8_t *mplayer)
} }
/* The owner check also covers projectiles fired before switching to a support vehicle. */ /* The owner check also covers projectiles fired before switching to a support vehicle. */
static int is_local_enemy_hit(const uint8_t *attacker, const uint8_t *victim) int local_mp_is_view_hit(const uint8_t *attacker, const uint8_t *victim)
{ {
const uint8_t *mplayer = local_mplayer(); const uint8_t *mplayer = local_mplayer();
if (attacker == NULL || attacker == victim || mplayer == NULL) if (attacker == NULL || attacker == victim || mplayer == NULL)
return 0; return 0;
if (victim[LMP_UNIT_OFF_ARMY] != 0 && victim[LMP_UNIT_OFF_ARMY] == attacker[LMP_UNIT_OFF_ARMY])
const uint8_t *owner = owning_mplayer(attacker);
if (owner != NULL && owner == owning_mplayer(victim))
return 0; return 0;
return owning_mplayer(attacker) == mplayer || attacker == controlled_unit(mplayer) return owner == mplayer || attacker == controlled_unit(mplayer)
|| attacker == watched_unit(mplayer); || attacker == watched_unit(mplayer);
} }
int local_mp_has_enemy_hit_feedback(void)
{
return active_hit_victim != NULL;
}
int local_mp_damage_notifications_ready(void)
{
return damage_hooks_queued;
}
static uint8_t __fastcall hook_barrel_damage(void *damage, const uint8_t *impact) static uint8_t __fastcall hook_barrel_damage(void *damage, const uint8_t *impact)
{ {
/* The stock handler resolves the reference before it emits the notice and tags it in bit 0. */ /* The stock handler resolves the reference before it emits the notice and tags it in bit 0. */
@@ -202,7 +215,9 @@ static uint64_t __fastcall hook_unit_on_event(void *unit, const uint8_t *event,
if (unit != NULL && event != NULL && local_mp_is_host() if (unit != NULL && event != NULL && local_mp_is_host()
&& *(const uint16_t *)(event + g_lmp.mpi_msg_id_off) == LMP_MPI_MSG_HIT_FEEDBACK) { && *(const uint16_t *)(event + g_lmp.mpi_msg_id_off) == LMP_MPI_MSG_HIT_FEEDBACK) {
const uint8_t *attacker = *(const uint8_t *const *)(event + g_lmp.hit_event_offender); const uint8_t *attacker = *(const uint8_t *const *)(event + g_lmp.hit_event_offender);
if (is_local_enemy_hit(attacker, unit)) const uint8_t *victim = unit;
if (local_mp_is_view_hit(attacker, victim) &&
(victim[LMP_UNIT_OFF_ARMY] == 0 || victim[LMP_UNIT_OFF_ARMY] != attacker[LMP_UNIT_OFF_ARMY]))
active_hit_victim = unit; active_hit_victim = unit;
} }
result = original_unit_on_event(unit, event, arg3, arg4); result = original_unit_on_event(unit, event, arg3, arg4);
@@ -288,5 +303,6 @@ int install_local_mp_damage_notification_hooks(void)
log_line("local_mp: local_mp_damage_notifications skipped: barrel and breech deliver addresses differ"); log_line("local_mp: local_mp_damage_notifications skipped: barrel and breech deliver addresses differ");
return 0; return 0;
} }
return local_mp_queue_hooks("local_mp_damage_notifications", hooks, sizeof(hooks) / sizeof(hooks[0])); damage_hooks_queued = local_mp_queue_hooks("local_mp_damage_notifications", hooks, sizeof(hooks) / sizeof(hooks[0]));
return damage_hooks_queued;
} }
+1 -25
View File
@@ -1,6 +1,6 @@
/* /*
* LocalMP non-fatal combat event dispatchers: deduplicated assists across air/ground/naval, * LocalMP non-fatal combat event dispatchers: deduplicated assists across air/ground/naval,
* zone captures, hit results, severe damage, and naval damage awards. * hit results, severe damage, and naval damage awards.
* *
* `IGroundModel::onBecameDead` calls both `IGroundModel::awardAssists` (`0x465540`) and * `IGroundModel::onBecameDead` calls both `IGroundModel::awardAssists` (`0x465540`) and
* `Unit::awardAssists` (`0xe5b200` -> `dispatchAssist` `0x35beb0`); deduplicating `(victim, mp)` * `Unit::awardAssists` (`0xe5b200` -> `dispatchAssist` `0x35beb0`); deduplicating `(victim, mp)`
@@ -27,7 +27,6 @@ typedef struct AssistDedupRecord {
typedef void (__fastcall *IGroundAwardAssistsFn)(uint8_t *victim); typedef void (__fastcall *IGroundAwardAssistsFn)(uint8_t *victim);
typedef void (__fastcall *DispatchAssistFn)(int64_t uid, uint8_t *victim, uint8_t *offender, float share, int32_t extra); typedef void (__fastcall *DispatchAssistFn)(int64_t uid, uint8_t *victim, uint8_t *offender, float share, int32_t extra);
typedef void (__fastcall *DispatchCaptureZoneFn)(int64_t uid, uint8_t *capturer_unit);
typedef void (__fastcall *DispatchHitFn)( typedef void (__fastcall *DispatchHitFn)(
int64_t uid, uint8_t *victim, uint8_t *offender, float dmg, uint8_t repeat_flush, uint8_t effective_hit, uint8_t extra); int64_t uid, uint8_t *victim, uint8_t *offender, float dmg, uint8_t repeat_flush, uint8_t effective_hit, uint8_t extra);
typedef void (__fastcall *DispatchSevereDamageFn)(int64_t uid, uint8_t *victim, uint8_t *offender); typedef void (__fastcall *DispatchSevereDamageFn)(int64_t uid, uint8_t *victim, uint8_t *offender);
@@ -35,7 +34,6 @@ typedef void (__fastcall *DispatchNavalDamageFn)(int64_t uid, uint8_t *victim, u
static IGroundAwardAssistsFn orig_iground_award_assists; static IGroundAwardAssistsFn orig_iground_award_assists;
static DispatchAssistFn orig_dispatch_assist; static DispatchAssistFn orig_dispatch_assist;
static DispatchCaptureZoneFn orig_dispatch_capture_zone;
static DispatchHitFn orig_dispatch_hit; static DispatchHitFn orig_dispatch_hit;
static DispatchSevereDamageFn orig_dispatch_severe_damage; static DispatchSevereDamageFn orig_dispatch_severe_damage;
static DispatchNavalDamageFn orig_dispatch_naval_damage; static DispatchNavalDamageFn orig_dispatch_naval_damage;
@@ -135,27 +133,6 @@ static void __fastcall hook_dispatch_assist(int64_t uid, uint8_t *victim, uint8_
orig_dispatch_assist(uid, victim, offender, share, extra); orig_dispatch_assist(uid, victim, offender, share, extra);
} }
static void __fastcall hook_dispatch_capture_zone(int64_t uid, uint8_t *capturer_unit)
{
if (local_mp_is_host()) {
uint8_t *mp = local_mp_find_mplayer(uid, 0xffu);
if (mp == NULL && capturer_unit != NULL)
mp = *(uint8_t **)(capturer_unit + LMP_UNIT_OFF_MPLAYER);
if (mp != NULL) {
const uint8_t *own_unit = capturer_unit != NULL ? capturer_unit
: (g_lmp_get_unit_by_eid ? (const uint8_t *)g_lmp_get_unit_by_eid(*(uint32_t *)(mp + LMP_MP_OFF_UNIT_EID)) : NULL);
local_mp_inc_mplayer_stat(mp, LMP_MP_OFF_CAPTURE_ZONE);
local_mp_add_mplayer_score(mp, local_mp_event_score("capture", own_unit, 1), LMP_EXP_EVENT_CAPTURE_ZONE);
local_mp_mark_mplayer_dirty(mp);
if (local_mp_is_local_mplayer(mp)) {
LocalMpAwardEvent award = { LMP_EXP_EVENT_CAPTURE_ZONE, NULL, 0, 0, NULL, 0 };
local_mp_report_award_event(&award);
}
}
}
orig_dispatch_capture_zone(uid, capturer_unit);
}
/* /*
* Unit::flushOffenderHitAward passes a repeat marker and an effective-hit flag. Its stock * Unit::flushOffenderHitAward passes a repeat marker and an effective-hit flag. Its stock
* single-player path (.58 0xffd369) selects HIT / INEFFECTIVE_HIT from that same flag. The * single-player path (.58 0xffd369) selects HIT / INEFFECTIVE_HIT from that same flag. The
@@ -240,7 +217,6 @@ int install_local_mp_event_hooks(void)
const LocalMpHookSpec hooks[] = { const LocalMpHookSpec hooks[] = {
{ "iground_award_assists", g_lmp.iground_award_assists, (void *)&hook_iground_award_assists, (void **)&orig_iground_award_assists }, { "iground_award_assists", g_lmp.iground_award_assists, (void *)&hook_iground_award_assists, (void **)&orig_iground_award_assists },
{ "dispatch_assist", g_lmp.dispatch_assist, (void *)&hook_dispatch_assist, (void **)&orig_dispatch_assist }, { "dispatch_assist", g_lmp.dispatch_assist, (void *)&hook_dispatch_assist, (void **)&orig_dispatch_assist },
{ "dispatch_capture_zone", g_lmp.dispatch_capture_zone, (void *)&hook_dispatch_capture_zone, (void **)&orig_dispatch_capture_zone },
{ "dispatch_hit", g_lmp.dispatch_hit, (void *)&hook_dispatch_hit, (void **)&orig_dispatch_hit }, { "dispatch_hit", g_lmp.dispatch_hit, (void *)&hook_dispatch_hit, (void **)&orig_dispatch_hit },
{ "dispatch_severe_damage", g_lmp.dispatch_severe_damage, (void *)&hook_dispatch_severe_damage, (void **)&orig_dispatch_severe_damage }, { "dispatch_severe_damage", g_lmp.dispatch_severe_damage, (void *)&hook_dispatch_severe_damage, (void **)&orig_dispatch_severe_damage },
{ "dispatch_naval_damage", g_lmp.dispatch_naval_damage, (void *)&hook_dispatch_naval_damage, (void **)&orig_dispatch_naval_damage }, { "dispatch_naval_damage", g_lmp.dispatch_naval_damage, (void *)&hook_dispatch_naval_damage, (void **)&orig_dispatch_naval_damage },
@@ -0,0 +1,63 @@
/* Validate recipient ownership at the two outgoing hit-feedback dispatch points. */
#include "local_mp_internal.h"
#include "local_mp_offsets.h"
#include <intrin.h>
typedef void (__fastcall *SendScriptNetEventFn)(void *manager, uint8_t broadcast, uint32_t destination,
const void *event, const char *event_name, const void *recipient_args, const void *recipient_filter);
typedef void (__fastcall *NotifyHudScriptFn)(void *hud, int32_t event_id, const void *data);
/* The CmdShowHitMark unicast constructor writes 0x0001001c6c52bfea followed by its victim EID.
* The stock sender handles event destruction when its flags require it. This event is plain data. */
typedef struct HitMarkEvent {
uint32_t type;
uint16_t size;
uint16_t flags;
uint32_t victim;
} HitMarkEvent;
enum { HIT_MARK_EVENT_TYPE = 0x6c52bfea, HIT_MARK_EVENT_SIZE = 0x1c, ECS_EVENT_UNICAST = 1 };
enum { HUD_HINT_CHANGE_SHELL_TYPE = 0xc5 };
static SendScriptNetEventFn original_send_script_event;
static NotifyHudScriptFn original_notify_hud_script;
static int should_drop_hit_mark(uint8_t broadcast, uint32_t destination, const HitMarkEvent *event)
{
if (event == NULL || event->type != HIT_MARK_EVENT_TYPE || event->size != HIT_MARK_EVENT_SIZE ||
event->flags != ECS_EVENT_UNICAST || broadcast || !local_mp_is_host())
return 0;
const uint8_t *attacker = g_lmp_get_unit_by_eid(destination);
const uint8_t *victim = g_lmp_get_unit_by_eid(event->victim);
return !local_mp_is_view_hit(attacker, victim);
}
static void __fastcall hook_send_script_event(void *manager, uint8_t broadcast, uint32_t destination,
const void *event, const char *event_name, const void *recipient_args, const void *recipient_filter)
{
if (!should_drop_hit_mark(broadcast, destination, event))
original_send_script_event(manager, broadcast, destination, event, event_name, recipient_args, recipient_filter);
}
static void __fastcall hook_notify_hud_script(void *hud, int32_t event_id, const void *data)
{
if (event_id == HUD_HINT_CHANGE_SHELL_TYPE &&
(uintptr_t)_ReturnAddress() == (uintptr_t)g_lmp.hit_shell_hint_call + LMP_REL32_CALL_SIZE &&
local_mp_is_host() && !local_mp_has_enemy_hit_feedback())
return;
original_notify_hud_script(hud, event_id, data);
}
int install_local_mp_hit_feedback_hooks(void)
{
if (!local_mp_damage_notifications_ready())
return 0;
const LocalMpHookSpec hooks[] = {
{ "send_script_net_event", g_lmp.hit_mark_send, (void *)&hook_send_script_event, (void **)&original_send_script_event },
{ "notify_shell_hint", g_lmp.hit_shell_hint_notify, (void *)&hook_notify_hud_script, (void **)&original_notify_hud_script },
};
return local_mp_queue_hooks("local_mp_hit_feedback", hooks, sizeof(hooks) / sizeof(hooks[0]));
}
+6
View File
@@ -62,6 +62,7 @@ void local_mp_players_queue_spawn(int32_t slot_id, int32_t spare_type, int32_t b
/* Local player events sent to the GUI scripts (local_mp_awards.c). */ /* Local player events sent to the GUI scripts (local_mp_awards.c). */
void local_mp_report_award_event(const LocalMpAwardEvent *ev); void local_mp_report_award_event(const LocalMpAwardEvent *ev);
void local_mp_report_capture(const char *unit_name);
void local_mp_report_nuclear_strike(void); void local_mp_report_nuclear_strike(void);
void local_mp_report_airfield_spawn(const char *unit_name, int32_t base_id); void local_mp_report_airfield_spawn(const char *unit_name, int32_t base_id);
void local_mp_report_backup_spawn(const char *unit_name, int32_t slot_id, const char *backup); void local_mp_report_backup_spawn(const char *unit_name, int32_t slot_id, const char *backup);
@@ -103,10 +104,15 @@ int install_local_mp_action_hooks(void);
int install_local_mp_award_hooks(void); int install_local_mp_award_hooks(void);
int install_local_mp_kill_hooks(void); int install_local_mp_kill_hooks(void);
int install_local_mp_event_hooks(void); int install_local_mp_event_hooks(void);
int install_local_mp_capture_hooks(void);
int install_local_mp_score_reader(void); int install_local_mp_score_reader(void);
int install_local_mp_nuke_hooks(void); int install_local_mp_nuke_hooks(void);
int install_local_mp_support_hooks(void); int install_local_mp_support_hooks(void);
int install_local_mp_damage_notification_hooks(void); int install_local_mp_damage_notification_hooks(void);
int install_local_mp_hit_feedback_hooks(void);
int local_mp_damage_notifications_ready(void);
int local_mp_is_view_hit(const uint8_t *attacker, const uint8_t *victim);
int local_mp_has_enemy_hit_feedback(void);
int install_local_mp_zone_hooks(void); int install_local_mp_zone_hooks(void);
void local_mp_zones_reset(void); void local_mp_zones_reset(void);
int install_local_mp_air_event_hooks(void); int install_local_mp_air_event_hooks(void);
+2
View File
@@ -15,6 +15,8 @@
#include "local_mp_values.h" #include "local_mp_values.h"
#define LMP_REL32_CALL_SIZE (1 + sizeof(int32_t)) /* x64 E8 + signed displacement */
#define LMP_GUI_STATE_PILOT_CONTROL 2 #define LMP_GUI_STATE_PILOT_CONTROL 2
#define LMP_GUI_STATE_CA_SELECT 6 #define LMP_GUI_STATE_CA_SELECT 6
#define LMP_GUI_STATE_CA_READY 8 #define LMP_GUI_STATE_CA_READY 8
+13 -1
View File
@@ -37,10 +37,12 @@ typedef struct LmpValueSpec {
#define SCORES "local_mp_scores" #define SCORES "local_mp_scores"
#define KILLS "local_mp_kills" #define KILLS "local_mp_kills"
#define EVENTS "local_mp_events" #define EVENTS "local_mp_events"
#define CAPTURES "local_mp_captures"
#define ZONES "local_mp_zones" #define ZONES "local_mp_zones"
#define NUKE "local_mp_nuke" #define NUKE "local_mp_nuke"
#define SUPPORT "local_mp_support" #define SUPPORT "local_mp_support"
#define DAMAGE_NOTICES "local_mp_damage_notifications" #define DAMAGE_NOTICES "local_mp_damage_notifications"
#define HIT_FEEDBACK "local_mp_hit_feedback"
#define AIR_EVENTS "local_mp_air_events" #define AIR_EVENTS "local_mp_air_events"
#define GROUND_AI "local_mp_ground_ai" #define GROUND_AI "local_mp_ground_ai"
#define AIR_AI_SYNC "local_mp_air_ai_sync" #define AIR_AI_SYNC "local_mp_air_ai_sync"
@@ -138,10 +140,16 @@ static const LmpValueSpec SPECS[] = {
O(KILLS, "stat_award_damage.field", mp_award_damage), O(KILLS, "stat_air_severe.field", mp_air_severe_dmg), O(KILLS, "stat_award_damage.field", mp_award_damage), O(KILLS, "stat_air_severe.field", mp_air_severe_dmg),
O(KILLS, "stat_ship_severe.field", mp_ship_severe_dmg), O(KILLS, "stat_ship_severe.field", mp_ship_severe_dmg),
A(EVENTS, "dispatch_assist", dispatch_assist), A(EVENTS, "caller_capture_zone.call", dispatch_capture_zone), A(EVENTS, "dispatch_assist", dispatch_assist),
A(EVENTS, "caller_hit_crit.call", dispatch_hit), A(EVENTS, "caller_severe_damage.call", dispatch_severe_damage), A(EVENTS, "caller_hit_crit.call", dispatch_hit), A(EVENTS, "caller_severe_damage.call", dispatch_severe_damage),
A(EVENTS, "caller_naval_damage.call", dispatch_naval_damage), O(EVENTS, "offender_assist.assist_sent", offender_assist_sent), A(EVENTS, "caller_naval_damage.call", dispatch_naval_damage), O(EVENTS, "offender_assist.assist_sent", offender_assist_sent),
A(CAPTURES, "capture_cta_logic", capture_cta_logic),
A(CAPTURES, "capture_set_owner", capture_set_owner), O(CAPTURES, "capture_set_owner.owner", capture_owner),
A(CAPTURES, "capture_complete_call", capture_complete_call),
A(CAPTURES, "capture_complete_call.set_owner", capture_complete_set_owner),
A(CAPTURES, "capture_team_power", capture_team_power), A(CAPTURES, "capture_unit_power_call.function", capture_unit_power),
A(NUKE, "shell_launch", shell_launch), A(NUKE, "shell_explode", shell_explode), A(NUKE, "cta_logic_action", cta_logic_action), A(NUKE, "shell_launch", shell_launch), A(NUKE, "shell_explode", shell_explode), A(NUKE, "cta_logic_action", cta_logic_action),
O(NUKE, "shell_instant_win.record", shell_launch_record), O(NUKE, "shell_instant_win.instant_win", shell_rec_instant_win), O(NUKE, "shell_instant_win.record", shell_launch_record), O(NUKE, "shell_instant_win.instant_win", shell_rec_instant_win),
O(NUKE, "mission_vars_data.data", mission_vars_data), O(NUKE, "mission_vars_walk.count", mission_vars_count), O(NUKE, "mission_vars_data.data", mission_vars_data), O(NUKE, "mission_vars_walk.count", mission_vars_count),
@@ -172,6 +180,10 @@ static const LmpValueSpec SPECS[] = {
O(DAMAGE_NOTICES, "enemy_part_damage_mpi.msg_id", enemy_part_dmg_mpi_id), O(DAMAGE_NOTICES, "enemy_part_damage_mpi.msg_id", enemy_part_dmg_mpi_id),
O(DAMAGE_NOTICES, "enemy_part_hit_mpi.msg_id", enemy_part_hit_mpi_id), O(DAMAGE_NOTICES, "enemy_part_hit_mpi.msg_id", enemy_part_hit_mpi_id),
A(HIT_FEEDBACK, "hit_mark_send.send", hit_mark_send),
A(HIT_FEEDBACK, "hit_shell_hint_call", hit_shell_hint_call),
A(HIT_FEEDBACK, "hit_shell_hint_call.notify", hit_shell_hint_notify),
O(AIR_EVENTS, "mission_mode_name.mode_name", mis_mode_name), O(AIR_EVENTS, "mission_mode_name.mode_name", mis_mode_name),
A(AIR_EVENTS, "prepare_local_mission", prepare_local_mission), A(AIR_EVENTS, "prepare_local_mission", prepare_local_mission),
A(AIR_EVENTS, "prepare_local_mission_clear.use_kill_streaks", use_kill_streaks), A(AIR_EVENTS, "prepare_local_mission_clear.use_kill_streaks", use_kill_streaks),
+9 -1
View File
@@ -61,9 +61,14 @@ typedef struct LmpValues {
size_t mp_award_damage, mp_air_severe_dmg, mp_ship_severe_dmg; size_t mp_award_damage, mp_air_severe_dmg, mp_ship_severe_dmg;
/* local_mp_events */ /* local_mp_events */
uint8_t *dispatch_assist, *dispatch_capture_zone, *dispatch_hit, *dispatch_severe_damage, *dispatch_naval_damage; uint8_t *dispatch_assist, *dispatch_hit, *dispatch_severe_damage, *dispatch_naval_damage;
size_t offender_assist_sent; size_t offender_assist_sent;
/* local_mp_captures */
uint8_t *capture_cta_logic, *capture_set_owner, *capture_complete_call, *capture_complete_set_owner;
uint8_t *capture_team_power, *capture_unit_power;
size_t capture_owner;
/* local_mp_nuke */ /* local_mp_nuke */
uint8_t *shell_launch, *shell_explode, *cta_logic_action; uint8_t *shell_launch, *shell_explode, *cta_logic_action;
size_t shell_launch_record, shell_rec_instant_win, mission_vars_data, mission_vars_count, mission_var_stride; size_t shell_launch_record, shell_rec_instant_win, mission_vars_data, mission_vars_count, mission_var_stride;
@@ -82,6 +87,9 @@ typedef struct LmpValues {
size_t barrel_unit_ref, breech_unit, barrel_notice_id, breech_notice_id, avionics_unit, hit_event_offender; size_t barrel_unit_ref, breech_unit, barrel_notice_id, breech_notice_id, avionics_unit, hit_event_offender;
size_t mpi_msg_id_off, enemy_part_dmg_mpi_id, enemy_part_hit_mpi_id; size_t mpi_msg_id_off, enemy_part_dmg_mpi_id, enemy_part_hit_mpi_id;
/* local_mp_hit_feedback */
uint8_t *hit_mark_send, *hit_shell_hint_call, *hit_shell_hint_notify;
/* local_mp_zones */ /* local_mp_zones */
uint8_t *apply_zone_damage; uint8_t *apply_zone_damage;
size_t zone_health, zone_max_health, zone_team, zone_flags, zone_airfield_mask; size_t zone_health, zone_max_health, zone_team, zone_flags, zone_airfield_mask;
+3 -1
View File
@@ -109,7 +109,8 @@ export function inspectModContent(rootDir: string, manifest: ModManifest): ModCo
: undefined; : undefined;
const badges = computeRiskBadges({ const badges = computeRiskBadges({
hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0 || configBlkPatch !== undefined, hasData: serverTuningFiles.length > 0 || packOperations.length > 0 || hasClientAddon || clientFiles.length > 0
|| configBlkPatch !== undefined || !!manifest.techTreeInsertions?.length,
hasGui: guiPatchDirs.length > 0, hasGui: guiPatchDirs.length > 0,
hasScript: serverEntry !== undefined, hasScript: serverEntry !== undefined,
hasExe: exePatchDirs.length > 0, hasExe: exePatchDirs.length > 0,
@@ -270,6 +271,7 @@ export function touchedClientPacks(mods: readonly DiscoveredMod[]): ModdableClie
const set = new Set<ModdableClientPack>(); const set = new Set<ModdableClientPack>();
for (const mod of mods) { for (const mod of mods) {
for (const op of mod.content.packOperations) set.add(op.pack); for (const op of mod.content.packOperations) set.add(op.pack);
if (mod.manifest.techTreeInsertions?.length) set.add('char.vromfs.bin');
if (mod.content.guiPatchDirs.length > 0) set.add('gui.vromfs.bin'); if (mod.content.guiPatchDirs.length > 0) set.add('gui.vromfs.bin');
if (mod.content.hasClientAddon) set.add('aces.vromfs.bin'); if (mod.content.hasClientAddon) set.add('aces.vromfs.bin');
} }
+1
View File
@@ -22,6 +22,7 @@ export {
type ModPreset, type ModPreset,
type ModRiskBadge, type ModRiskBadge,
type ModServerConfig, type ModServerConfig,
type ModTechTreeInsertion,
type ModdableClientPack, type ModdableClientPack,
type PackFileAction, type PackFileAction,
type ResolvedModLoadOrder, type ResolvedModLoadOrder,
+25 -1
View File
@@ -4,7 +4,7 @@
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { join } from 'node:path'; import { join } from 'node:path';
import { parseJsonc } from '@wto/jsonc'; import { parseJsonc } from '@wto/jsonc';
import { MOD_FORMAT_VERSION, type LocalizedText, type ModManifest, type ModServerConfig } from './types.ts'; import { MOD_FORMAT_VERSION, type LocalizedText, type ModManifest, type ModServerConfig, type ModTechTreeInsertion } from './types.ts';
export const MOD_MANIFEST_FILE = 'mod.jsonc'; export const MOD_MANIFEST_FILE = 'mod.jsonc';
@@ -22,9 +22,11 @@ const ALLOWED_ROOT_KEYS = new Set([
'conflicts', 'conflicts',
'load_after', 'load_after',
'load_before', 'load_before',
'tech_tree_insertions',
'server', 'server',
]); ]);
const ALLOWED_SERVER_KEYS = new Set(['entry', 'tuning']); const ALLOWED_SERVER_KEYS = new Set(['entry', 'tuning']);
const TECH_TREE_INSERTION_KEYS = new Set(['vehicle', 'after', 'before']);
export class ModManifestError extends Error { export class ModManifestError extends Error {
override name = 'ModManifestError'; override name = 'ModManifestError';
@@ -62,6 +64,7 @@ export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModMa
const conflicts = optionalIdList(obj.conflicts, `${where} "conflicts"`, id); const conflicts = optionalIdList(obj.conflicts, `${where} "conflicts"`, id);
const loadAfter = optionalIdList(obj.load_after, `${where} "load_after"`, id); const loadAfter = optionalIdList(obj.load_after, `${where} "load_after"`, id);
const loadBefore = optionalIdList(obj.load_before, `${where} "load_before"`, id); const loadBefore = optionalIdList(obj.load_before, `${where} "load_before"`, id);
const techTreeInsertions = parseTechTreeInsertions(obj.tech_tree_insertions, `${where} "tech_tree_insertions"`);
const server = obj.server === undefined ? undefined : parseServerConfig(obj.server, `${where} "server"`); const server = obj.server === undefined ? undefined : parseServerConfig(obj.server, `${where} "server"`);
return { return {
@@ -77,10 +80,31 @@ export function parseModManifest(raw: unknown, where = MOD_MANIFEST_FILE): ModMa
conflicts, conflicts,
loadAfter, loadAfter,
loadBefore, loadBefore,
...(techTreeInsertions.length > 0 ? { techTreeInsertions } : {}),
...(server !== undefined ? { server } : {}), ...(server !== undefined ? { server } : {}),
}; };
} }
function parseTechTreeInsertions(raw: unknown, where: string): ModTechTreeInsertion[] {
if (raw === undefined) return [];
if (!Array.isArray(raw)) throw new ModManifestError(`${where}: expected an array`);
const seen = new Set<string>();
return raw.map((item, index) => {
const location = `${where}[${index}]`;
const value = expectObject(item, location);
rejectUnknownKeys(value, TECH_TREE_INSERTION_KEYS, location);
const vehicle = expectString(value.vehicle, `${location}.vehicle`);
const after = expectString(value.after, `${location}.after`);
const before = expectString(value.before, `${location}.before`);
if (new Set([vehicle, after, before]).size !== 3) {
throw new ModManifestError(`${location}: vehicle, after, and before must be different vehicles`);
}
if (seen.has(vehicle)) throw new ModManifestError(`${location}: duplicate insertion for "${vehicle}"`);
seen.add(vehicle);
return { vehicle, after, before };
});
}
function parseServerConfig(raw: unknown, where: string): ModServerConfig { function parseServerConfig(raw: unknown, where: string): ModServerConfig {
const obj = expectObject(raw, where); const obj = expectObject(raw, where);
rejectUnknownKeys(obj, ALLOWED_SERVER_KEYS, where); rejectUnknownKeys(obj, ALLOWED_SERVER_KEYS, where);
+7
View File
@@ -33,6 +33,12 @@ export interface ModServerConfig {
readonly tuning?: string; readonly tuning?: string;
} }
export interface ModTechTreeInsertion {
readonly vehicle: string;
readonly after: string;
readonly before: string;
}
export interface ModManifest { export interface ModManifest {
readonly format: 1; readonly format: 1;
readonly id: string; readonly id: string;
@@ -46,6 +52,7 @@ export interface ModManifest {
readonly conflicts: readonly string[]; readonly conflicts: readonly string[];
readonly loadAfter: readonly string[]; readonly loadAfter: readonly string[];
readonly loadBefore: readonly string[]; readonly loadBefore: readonly string[];
readonly techTreeInsertions?: readonly ModTechTreeInsertion[];
readonly server?: ModServerConfig; readonly server?: ModServerConfig;
} }
@@ -226,6 +226,9 @@ export function computeModsBuildFingerprint(
hash.update(`port=${port};salt=${extraSalt}\n`); hash.update(`port=${port};salt=${extraSalt}\n`);
for (const mod of mods) { for (const mod of mods) {
hash.update(`mod=${mod.manifest.id}@${mod.manifest.version}\n`); hash.update(`mod=${mod.manifest.id}@${mod.manifest.version}\n`);
if (mod.manifest.techTreeInsertions?.length) {
hash.update(`tech_tree_insertions=${JSON.stringify(mod.manifest.techTreeInsertions)}\n`);
}
const filesToStamp = [ const filesToStamp = [
...mod.content.packOperations.map((op) => op.sourceRelativePath), ...mod.content.packOperations.map((op) => op.sourceRelativePath),
...mod.content.guiPatchDirs, ...mod.content.guiPatchDirs,
+21 -6
View File
@@ -4,7 +4,7 @@
*/ */
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import { join } from 'node:path'; import { join } from 'node:path';
import { decodeBlk, encodeBlk, isBinaryBlk, parseBlkText, parseSharedNameMap } from '@wto/blk'; import { decodeBlk, encodeBlk, isBinaryBlk, parseBlkText, parseSharedNameMap, type SharedNameContext } from '@wto/blk';
import { import {
applyBlkPatch, applyBlkPatch,
applyBlkTextPatch, applyBlkTextPatch,
@@ -18,6 +18,8 @@ import {
type ModdableClientPack, type ModdableClientPack,
} from '@wto/mods'; } from '@wto/mods';
import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs'; import { getFile, NAME_MAP_PATH, putFile, readArchive, writeArchive, type Archive } from '@wto/vromfs';
import { composeTechTreeInsertions, VEHICLE_ECONOMY_PATH } from '../tech-tree/compose-insertions.ts';
import { SHOP_PATH } from '../tech-tree/reveal-hidden-vehicles.ts';
export interface PackOverlayReport { export interface PackOverlayReport {
readonly pack: ModdableClientPack; readonly pack: ModdableClientPack;
@@ -35,7 +37,10 @@ export function applyModPackOverlays(
ops: mod.content.packOperations.filter((op) => op.pack === packName), ops: mod.content.packOperations.filter((op) => op.pack === packName),
})) }))
.filter((entry) => entry.ops.length > 0); .filter((entry) => entry.ops.length > 0);
const totalOps = relevantMods.reduce((sum, entry) => sum + entry.ops.length, 0); const insertions = packName === 'char.vromfs.bin'
? mods.flatMap(({ manifest }) => (manifest.techTreeInsertions ?? []).map((entry) => ({ ...entry, modId: manifest.id })))
: [];
const totalOps = relevantMods.reduce((sum, entry) => sum + entry.ops.length, insertions.length);
if (totalOps === 0) { if (totalOps === 0) {
return { pack: basePack, report: { pack: packName, operationsApplied: 0 } }; return { pack: basePack, report: { pack: packName, operationsApplied: 0 } };
} }
@@ -74,10 +79,7 @@ export function applyModPackOverlays(
if (!resolvedPath) { if (!resolvedPath) {
throw new Error(`${where}: target BLK "${op.targetPath}" not found in ${packName}`); throw new Error(`${where}: target BLK "${op.targetPath}" not found in ${packName}`);
} }
const raw = getFile(archive, resolvedPath); const root = readOverlayBlk(archive, resolvedPath, { names, dictionary });
const root = isBinaryBlk(raw)
? decodeBlk(raw, { names, dictionary })
: parseBlkText(Buffer.from(raw).toString('utf8'));
const patchText = readFileSync(sourcePath, 'utf8'); const patchText = readFileSync(sourcePath, 'utf8');
if (op.sourceRelativePath.toLowerCase().endsWith('.patch.blk')) { if (op.sourceRelativePath.toLowerCase().endsWith('.patch.blk')) {
applyBlkTextPatch(root, patchText, { applyBlkTextPatch(root, patchText, {
@@ -123,12 +125,25 @@ export function applyModPackOverlays(
} }
} }
if (insertions.length > 0) {
const shop = readOverlayBlk(archive, SHOP_PATH, { names, dictionary });
const economy = readOverlayBlk(archive, VEHICLE_ECONOMY_PATH, { names, dictionary });
composeTechTreeInsertions(shop, economy, insertions);
putFile(archive, SHOP_PATH, encodeBlk(shop));
putFile(archive, VEHICLE_ECONOMY_PATH, encodeBlk(economy));
}
return { return {
pack: writeArchive(archive), pack: writeArchive(archive),
report: { pack: packName, operationsApplied: totalOps }, report: { pack: packName, operationsApplied: totalOps },
}; };
} }
function readOverlayBlk(archive: Archive, path: string, shared: SharedNameContext) {
const raw = getFile(archive, path);
return isBinaryBlk(raw) ? decodeBlk(raw, shared) : parseBlkText(Buffer.from(raw).toString('utf8'));
}
function createArchiveIncludeResolver(params: { function createArchiveIncludeResolver(params: {
readonly archive: Archive; readonly archive: Archive;
readonly names: readonly string[]; readonly names: readonly string[];
@@ -0,0 +1,221 @@
/** Compose opt-in research links after the normal BLK overlays have supplied the vehicles. */
import { emptyBlock, findParam, setParam, type BlkBlock } from '@wto/blk';
import type { ModTechTreeInsertion } from '@wto/mods';
export const VEHICLE_ECONOMY_PATH = 'config/wpcost.blk';
export interface RequestedTechTreeInsertion extends ModTechTreeInsertion {
readonly modId: string;
}
interface ShopPosition {
readonly entry: BlkBlock;
readonly page: BlkBlock;
readonly country: string;
readonly column: BlkBlock;
readonly group?: BlkBlock;
}
interface InsertionPlan {
readonly destination: BlkBlock;
readonly anchor: BlkBlock;
readonly successor: ShopPosition;
readonly updateGroupLink: boolean;
readonly entries: readonly { entry: BlkBlock; from: ShopPosition | undefined; rank: number; previous: string }[];
readonly lastVehicle: string;
}
export function composeTechTreeInsertions(
shop: BlkBlock,
economy: BlkBlock,
requests: readonly RequestedTechTreeInsertion[],
): void {
const catalog = indexByName(economy.blocks);
const positions = indexShop(shop);
const owners = new Map<string, string>();
const bySuccessor = new Map<string, RequestedTechTreeInsertion[]>();
for (const request of requests) {
const owner = owners.get(request.vehicle);
if (owner !== undefined) throw invalid(request, `"${request.vehicle}" is already inserted by mod "${owner}"`);
owners.set(request.vehicle, request.modId);
addToIndex(bySuccessor, request.before, request);
}
const links = new Map<string, { previous: string; request: RequestedTechTreeInsertion }>();
const plans: InsertionPlan[] = [];
for (const group of bySuccessor.values()) {
const first = group[0]!;
for (const request of group) {
if (owners.has(request.after) || owners.has(request.before)) {
throw invalid(request, 'insertion anchors must belong to the existing line');
}
if (request.after !== first.after) throw invalid(request, `mod "${first.modId}" names a different predecessor of "${request.before}"`);
}
const plan = planInsertion(catalog, positions, group);
for (const [index, entry] of plan.entries.entries()) {
links.set(entry.entry.name, { previous: entry.previous, request: group[index]! });
}
links.set(first.before, { previous: plan.lastVehicle, request: first });
plans.push(plan);
}
validateAcyclicLinks(catalog, links);
for (const [name, { previous, request }] of links) {
setParam(requireOne(catalog, name, VEHICLE_ECONOMY_PATH, request), 'reqAir', { type: 'string', value: previous });
}
for (const plan of plans) applyPlacement(plan);
}
function planInsertion(
catalog: ReadonlyMap<string, BlkBlock[]>,
positions: ReadonlyMap<string, ShopPosition[]>,
requests: readonly RequestedTechTreeInsertion[],
): InsertionPlan {
const first = requests[0]!;
const predecessor = requireOne(positions, first.after, 'config/shop.blk', first);
const successor = requireOne(positions, first.before, 'config/shop.blk', first);
if (predecessor.page !== successor.page) throw invalid(first, 'the two anchors must belong to the same country and branch');
const after = requireOne(catalog, first.after, VEHICLE_ECONOMY_PATH, first);
const before = requireOne(catalog, first.before, VEHICLE_ECONOMY_PATH, first);
const declaredPredecessor = textParam(before, 'reqAir');
if (declaredPredecessor !== first.after) {
throw invalid(first, `"${first.before}" requires ${declaredPredecessor ? `"${declaredPredecessor}"` : 'no vehicle'} in ${VEHICLE_ECONOMY_PATH}`);
}
const withinGroup = successor.group !== undefined && predecessor.group === successor.group;
const anchor = withinGroup ? successor.entry : successor.group ?? successor.entry;
if (successor.group && !withinGroup && successor.group.blocks[0] !== successor.entry) {
throw invalid(first, 'the link enters a non-leading variant of another folder');
}
validateShopPredecessor(anchor, first);
const maxRank = researchRank(before, successor, successor.country, first);
let lastRank = researchRank(after, predecessor, successor.country, first);
let lastVehicle = first.after;
const entries = requests.map((request) => {
const source = requireOne(catalog, request.vehicle, VEHICLE_ECONOMY_PATH, request);
const from = optionalOne(positions, request.vehicle, 'config/shop.blk', request);
if (from && from.page !== successor.page) throw invalid(request, `"${request.vehicle}" is placed in a different country or branch`);
if (from?.group && (!withinGroup || from.group !== successor.group)) {
throw invalid(request, `"${request.vehicle}" is already inside a different folder`);
}
const rank = researchRank(source, from, successor.country, request);
if (rank < lastRank || rank > maxRank) {
throw invalid(request, `rank ${rank} must be between ${lastRank} and ${maxRank} in mod load order`);
}
const entry = { entry: from?.entry ?? emptyBlock(request.vehicle), from, rank, previous: lastVehicle };
lastRank = rank;
lastVehicle = request.vehicle;
return entry;
});
return { destination: withinGroup ? successor.group! : successor.column, anchor, successor, updateGroupLink: anchor !== successor.entry, entries, lastVehicle };
}
function validateShopPredecessor(anchor: BlkBlock, request: RequestedTechTreeInsertion): void {
for (const key of ['reqAir', 'futureReqAir']) {
const value = findParam(anchor, key)?.value;
if (value !== undefined && (value.type !== 'string' || value.value !== request.after)) {
throw invalid(request, `"${anchor.name}" has a different ${key} in config/shop.blk`);
}
}
}
function applyPlacement(plan: InsertionPlan): void {
for (const item of plan.entries) {
if (item.from) {
const parent = item.from.group ?? item.from.column;
parent.blocks.splice(parent.blocks.indexOf(item.entry), 1);
}
setParam(item.entry, 'rank', { type: 'int', value: item.rank });
setPrerequisite(item.entry, item.previous);
}
plan.destination.blocks.splice(plan.destination.blocks.indexOf(plan.anchor), 0, ...plan.entries.map(({ entry }) => entry));
setPrerequisite(plan.successor.entry, plan.lastVehicle);
if (plan.updateGroupLink) setPrerequisite(plan.anchor, plan.lastVehicle);
}
function setPrerequisite(block: BlkBlock, previous: string): void {
setParam(block, 'reqAir', { type: 'string', value: previous });
if (findParam(block, 'futureReqAir')) setParam(block, 'futureReqAir', { type: 'string', value: previous });
}
function researchRank(entry: BlkBlock, position: ShopPosition | undefined, country: string, request: RequestedTechTreeInsertion): number {
const rank = findParam(entry, 'rank')?.value;
const gold = findParam(entry, 'costGold')?.value;
if (textParam(entry, 'country') !== country || rank?.type !== 'int' || rank.value < 1) {
throw invalid(request, `"${entry.name}" must have a valid rank in ${country} in ${VEHICLE_ECONOMY_PATH}`);
}
if (textParam(entry, 'gift') !== undefined || textParam(entry, 'event') !== undefined || textParam(entry, 'researchType') === 'clanVehicle'
|| findParam(entry, 'premPackAir')?.value.value === true || (gold?.type === 'int' && gold.value > 0)
|| (position && findParam(position.entry, 'showOnlyWhenBought')?.value.value === true)) {
throw invalid(request, `"${entry.name}" must be a regular vehicle in the research line`);
}
return rank.value;
}
function validateAcyclicLinks(
catalog: ReadonlyMap<string, BlkBlock[]>,
links: ReadonlyMap<string, { previous: string; request: RequestedTechTreeInsertion }>,
): void {
const checked = new Set<string>();
for (const [vehicle, { request }] of links) {
const path = new Set<string>();
let name: string | undefined = vehicle;
while (name !== undefined && !checked.has(name)) {
if (path.has(name)) throw invalid(request, `research prerequisites form a cycle at "${name}"`);
path.add(name);
const existing: BlkBlock | undefined = catalog.get(name)?.[0];
name = links.get(name)?.previous ?? (existing ? textParam(existing, 'reqAir') : undefined);
}
for (const visited of path) checked.add(visited);
}
}
function indexShop(shop: BlkBlock): Map<string, ShopPosition[]> {
const positions = new Map<string, ShopPosition[]>();
for (const country of shop.blocks) {
for (const page of country.blocks) {
for (const column of page.blocks) {
for (const entry of column.blocks) {
addToIndex(positions, entry.name, { entry, page, country: country.name, column });
for (const variant of entry.blocks) {
addToIndex(positions, variant.name, { entry: variant, page, country: country.name, column, group: entry });
}
}
}
}
}
return positions;
}
function indexByName(blocks: readonly BlkBlock[]): Map<string, BlkBlock[]> {
const entries = new Map<string, BlkBlock[]>();
for (const block of blocks) addToIndex(entries, block.name, block);
return entries;
}
function addToIndex<T>(index: Map<string, T[]>, key: string, entry: T): void {
const list = index.get(key);
if (list) list.push(entry);
else index.set(key, [entry]);
}
function requireOne<T>(index: ReadonlyMap<string, T[]>, name: string, where: string, request: RequestedTechTreeInsertion): T {
const entry = optionalOne(index, name, where, request);
if (entry === undefined) throw invalid(request, `"${name}" is missing from ${where}`);
return entry;
}
function optionalOne<T>(index: ReadonlyMap<string, T[]>, name: string, where: string, request: RequestedTechTreeInsertion): T | undefined {
const entries = index.get(name);
if (entries && entries.length > 1) throw invalid(request, `"${name}" is ambiguous in ${where}`);
return entries?.[0];
}
function textParam(block: BlkBlock, name: string): string | undefined {
const value = findParam(block, name)?.value;
return value?.type === 'string' ? value.value : undefined;
}
function invalid(request: RequestedTechTreeInsertion, reason: string): Error {
return new Error(`mod "${request.modId}" tech_tree_insertions (${request.after} -> ${request.vehicle} -> ${request.before}): ${reason}`);
}
@@ -82,7 +82,9 @@ function wtoOnLocalMpExpEvent(ev) {
if (battle == null) if (battle == null)
return return
let wtoMission = require("mission") let wtoMission = require("mission")
let unit = ndbTryRead(["wto", "battleLog", "openLife"])?.unit ?? require("unit").get_player_unit_name() let sourceUnit = ev?.unit ?? ""
let unit = battle?.awards?.vehicles?[sourceUnit] != null ? sourceUnit
: ndbTryRead(["wto", "battleLog", "openLife"])?.unit ?? require("unit").get_player_unit_name()
let entry = { let entry = {
time = wtoMission.get_mission_time() time = wtoMission.get_mission_time()
unit unit
+65
View File
@@ -0,0 +1,65 @@
// Award capture credit to players whose units contribute to a completed LocalMP capture.
// Only the mission engine knows when a zone changes owner and which units it counted.
// Without this module, the scoreboard and settlement miss completed captures.
{
"module": "local_mp_captures",
"features": ["K-Kill, assist and capture scoring"],
"requires": ["local_mp_core", "local_mp_kills", "local_mp_scores", "local_mp_awards"],
"sites": {
// cta_logic_action contains the zone-update timing diagnostic and the inline airfield completion path.
"capture_cta_logic": {
"variants": [{
"written_for": "2.61.0.37",
"locate": { "method": "string_ref", "string": "update_capture_zones", "target": "function" }
}]
},
// CaptureZone::setArmy. Read the old owner before the native replicated setter runs.
// 2.61.0.37: 0x11b7f70; 2.61.0.60: 0x11bcba0.
"capture_set_owner": {
"variants": [{
"written_for": "2.61.0.37",
"locate": {
"method": "signature",
"pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec 28 01 00 00 0f 29 b4 24 10 01 00 00 0f b6 71 ?? 89 54 24 2c 39 f2 0f 84 ?? ?? ?? ?? 49 89 cd",
"captures": { "owner": { "offset": 30, "type": "u8" } }
}
}]
},
// The setArmy call made when the ordinary progress helper reaches the capturing team's limit.
// 2.61.0.37: 0x11c2095; 2.61.0.60: 0x11c7605.
"capture_complete_call": {
"variants": [{
"written_for": "2.61.0.37",
"locate": {
"method": "signature",
"pattern": "e8 ?? ?? ?? ?? 48 8b 0d ?? ?? ?? ?? 48 8b 05 ?? ?? ?? ?? 48 85 c0 74 ?? 80 3d ?? ?? ?? ?? 00 75 ?? 80 3d ?? ?? ?? ?? 00 75 ?? 48 8d 50 70",
"captures": { "set_owner": { "offset": 1, "type": "rel32" } }
}
}]
},
// sumCapturePower(army, zone, &count) walks eligible mission units for one team.
// 2.61.0.37: 0x11b90a0; 2.61.0.60: 0x11bdd30.
"capture_team_power": {
"variants": [{
"written_for": "2.61.0.37",
"locate": {
"method": "signature",
"pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 81 ec b8 00 00 00 0f 29 b4 24 a0 00 00 00 48 89 d7 89 4c 24 3c 4c 89 44 24 40 41 c7 00 00 00 00 00 48 b8 32 00 00 00 ff ff ff ff"
}
}]
},
// sumCapturePower calls this helper after accepting a unit and increments its count.
// 2.61.0.37: 0x11b9214 -> 0x11b8f10; 2.61.0.60: 0x11bdea4 -> 0x11bdba0.
"capture_unit_power_call": {
"variants": [{
"written_for": "2.61.0.37",
"locate": {
"method": "within",
"in": "capture_team_power",
"pattern": "ff 00 48 89 f9 48 89 ea e8 ?? ?? ?? ?? f3 0f 58 f0",
"captures": { "function": { "offset": 9, "type": "rel32" } }
}
}]
}
}
}
+2 -21
View File
@@ -1,6 +1,6 @@
// Combat events on the LocalMP host (native/wto-net/src/local_mp_events.c): assists, captures, // Combat events on the LocalMP host (native/wto-net/src/local_mp_events.c): assists,
// effective and ineffective hits, and severe damage, reported as award facts. // effective and ineffective hits, and severe damage, reported as award facts.
// Without it: assists, captures and damage events score nothing in LocalMP battles. // Without it: assists and damage events score nothing in LocalMP battles.
{ {
"module": "local_mp_events", "module": "local_mp_events",
"features": [ "features": [
@@ -26,25 +26,6 @@
} }
] ]
}, },
// A caller of the capture zone dispatch; captures the callee.
// 2.61.0.37: 0x3db0e0
"caller_capture_zone": {
"variants": [
{
"written_for": "2.61.0.37",
"locate": {
"method": "signature",
"pattern": "41 57 41 56 41 55 41 54 56 57 55 53 48 83 ec 38 44 0f b7 72 02 44 8b 7a 04 4c 8b 62 08 4c 8b 6a 18 49 8d 85 88 06 00 00 48 89 44 24 30 49 8d 85 50 06 00 00 48 89 44 24 28 eb ?? 48 8b 90 08 0e 00 00 89 d1 83 e1 01 0b 0d ?? ?? ?? ?? 3b 88 14 0e 00 00 0f 85 ?? ?? ?? ?? 48 83 e2 fe 48 8b 82 98 0f 00 00 48 8b 88 b8 00 00 00 e8 ?? ?? ?? ??",
"captures": {
"call": {
"offset": 108,
"type": "rel32"
}
}
}
}
]
},
// Flushes effective / ineffective hits. The site key also identifies this capture in version records. // Flushes effective / ineffective hits. The site key also identifies this capture in version records.
// 2.61.0.37: 0xff85ea // 2.61.0.37: 0xff85ea
"caller_hit_crit": { "caller_hit_crit": {
@@ -0,0 +1,38 @@
// Keep outgoing hit markers and shell advice tied to the firing unit on a LocalMP host.
// The local daScript send path bypasses the recipient filter. The native shell hint has its own dispatch.
// Without this module, impacts by other units can reach the local attack feedback paths.
{
"module": "local_mp_hit_feedback",
"features": ["K-Player damage notices"],
"requires": ["local_mp_core", "local_mp_damage_notifications"],
"sites": {
// CmdShowHitMark unicast wrapper calls the common daScript network event sender. The inline
// damage script and the interpreted wrapper use that same sender.
// 2.61.0.37: 0x1eaa106 -> 0x50a06e0; 2.61.0.60: 0x1eb79b6 -> 0x50b13c0.
"hit_mark_send": {
"variants": [{
"written_for": "2.61.0.37",
"locate": {
"method": "string_ref",
"string": "CmdShowHitMark",
"lea_at": 0,
"pattern": "48 8d 15 ?? ?? ?? ?? 66 48 0f 6e ca 66 0f 7f 8c 24 f0 00 00 00 66 0f 7f 84 24 00 01 00 00 41 0f 10 01 4c 8d 4c 24 70 4c 89 4c 24 40 4c 8d 4c 24 40 4c 89 4c 24 50 4c 8d 0d ?? ?? ?? ?? 4c 89 4c 24 48 c6 44 24 68 01 0f 11 44 24 58 48 8b 89 30 03 00 00 4c 8d 4c 24 48 4c 89 4c 24 30 4c 8d 4c 24 58 4c 89 4c 24 28 48 89 54 24 20 31 d2 49 89 c1 e8 ?? ?? ?? ??",
"captures": { "send": { "offset": 114, "type": "rel32" } }
}
}]
},
// The shell-change hint's call in Unit::onEvent, just before it queues enemy damage parts.
// 2.61.0.37: 0x1045fbe -> 0x183bcc0; 2.61.0.60: 0x104a8e4 -> 0x1844c30.
"hit_shell_hint_call": {
"variants": [{
"written_for": "2.61.0.37",
"locate": {
"method": "within",
"in": "unit_on_event",
"pattern": "e8 ?? ?? ?? ?? 48 8b 0d ?? ?? ?? ?? 4c 8d b4 24 00 01 00 00 4c 89 ea 4d 89 f0 e8 ?? ?? ?? ??",
"captures": { "notify": { "offset": 1, "type": "rel32" } }
}
}]
}
}
}
+2 -2
View File
@@ -6,7 +6,7 @@ from __future__ import annotations
import argparse import argparse
from . import exe_commands, gui_commands from . import exe_commands, gui_commands, log_commands
def main(argv: list[str] | None = None) -> int: def main(argv: list[str] | None = None) -> int:
@@ -16,7 +16,7 @@ def main(argv: list[str] | None = None) -> int:
formatter_class=argparse.RawDescriptionHelpFormatter, formatter_class=argparse.RawDescriptionHelpFormatter,
) )
commands = parser.add_subparsers(dest="command", required=True) commands = parser.add_subparsers(dest="command", required=True)
for group in (exe_commands, gui_commands): for group in (exe_commands, gui_commands, log_commands):
group.register(commands) group.register(commands)
args = parser.parse_args(argv) args = parser.parse_args(argv)
return args.handler(args) return args.handler(args)