Files
Project-M/Assets/_Project/Scripts/Server/Combat/EnemyAISystem.cs
T
kronic 2710d680b4 Sandbox target dummy: planted EnemyTag ghost + DevSandbox respawn spawner
GymSub bakes no WaveDirector (why sandbox enemies never spawned); the
sandbox's combat target is now a TargetDummyTag'd enemy ghost all five
EnemyAISystem passes exclude (planted; knockback stamps inert), spawned
at player+3m with 400 HP by an editor-only scene-gated server system,
dying through the normal Dying path and respawning 1.5s after the corpse.
EnemyTag-reuse audited: sandbox-only by design (cleared-checks would
count it elsewhere).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 00:13:47 -07:00

695 lines
42 KiB
C#

using ProjectM.Simulation;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
using Unity.Physics;
using Unity.Transforms;
namespace ProjectM.Server
{
/// <summary>
/// Server-authoritative Husk AI: each tick every Husk seeks the nearest LIVING player and strikes on
/// contact. Husks are OWNERLESS INTERPOLATED ghosts (not predicted), so this runs SERVER-ONLY in the plain
/// <see cref="SimulationSystemGroup"/> — writing <see cref="LocalTransform"/> directly (replicated to clients
/// by the stock LocalTransform default variant; no hand-written <c>[GhostField]</c>). Ordered
/// <c>[UpdateAfter(PredictedSimulationSystemGroup)]</c> (the predicted group is OrderFirst, so UpdateBefore is ignored) so a contact <see cref="DamageEvent"/> appended this
/// tick is drained the following tick by <see cref="HealthApplyDamageSystem"/> (which runs inside the predicted
/// group on the server). No <c>Simulate</c> filter: interpolated ghosts are not predicted and the server has
/// no rollback, so every Husk advances exactly once per tick. Movement/attack math is the pure, deterministic
/// <see cref="EnemyAIMath"/>; server fixed-step <c>SystemAPI.Time.DeltaTime</c> is correct here (not the
/// rollback loop). Structural-free: the only deferred op is appending to the player's DamageEvent buffer.
/// </summary>
[BurstCompile]
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(PredictedSimulationSystemGroup))]
public partial struct EnemyAISystem : ISystem
{
EntityQuery m_EnemyProjectiles;
[BurstCompile]
public void OnCreate(ref SystemState state)
{
state.RequireForUpdate<NetworkTime>();
state.RequireForUpdate(state.GetEntityQuery(ComponentType.ReadOnly<EnemyTag>()));
m_EnemyProjectiles = state.GetEntityQuery(ComponentType.ReadOnly<EnemyProjectile>());
}
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
// Snapshot living player targets once this tick (stable query order).
var playerEntities = new NativeList<Entity>(Allocator.Temp);
var playerPositions = new NativeList<float3>(Allocator.Temp);
var playerRegions = new NativeList<byte>(Allocator.Temp);
foreach (var (xform, health, region, entity) in
SystemAPI.Query<RefRO<LocalTransform>, RefRO<Health>, RefRO<RegionTag>>()
.WithAll<PlayerTag>()
.WithEntityAccess())
{
if (health.ValueRO.Current <= 0f)
continue; // don't chase or strike a corpse
playerEntities.Add(entity);
playerPositions.Add(xform.ValueRO.Position);
playerRegions.Add(region.ValueRO.Region);
}
// EB-1 fortress aggro: also snapshot live structures (Turret/Wall/Pylon AND the Fabricator all carry
// Health since the DR-032 parity fix; the query keys on it). Snapshot ABOVE the early-return so Husks keep razing
// the base even with every player dead/away (the locked 'push for structures' fork).
var structureEntities = new NativeList<Entity>(Allocator.Temp);
var structurePositions = new NativeList<float3>(Allocator.Temp);
var structureRegions = new NativeList<byte>(Allocator.Temp);
foreach (var (sx, sh, sr, se) in
SystemAPI.Query<RefRO<LocalTransform>, RefRO<Health>, RefRO<RegionTag>>()
.WithAll<PlacedStructure>()
.WithEntityAccess())
{
if (sh.ValueRO.Current <= 0f)
continue; // skip a structure already at 0 (pending destroy this tick)
structureEntities.Add(se);
structurePositions.Add(sx.ValueRO.Position);
structureRegions.Add(sr.ValueRO.Region);
}
// LANTERN decoy-wisp aggro: a decoy draws Husks like a fake target. Region-agnostic gather (gym).
var decoyEntities = new NativeList<Entity>(Allocator.Temp);
var decoyPositions = new NativeList<float3>(Allocator.Temp);
foreach (var (dx, dh, de) in
SystemAPI.Query<RefRO<LocalTransform>, RefRO<Health>>()
.WithAll<DecoyTag>().WithEntityAccess())
{
if (dh.ValueRO.Current <= 0f) continue; // a spent decoy is being despawned; don't aggro a corpse
decoyEntities.Add(de);
decoyPositions.Add(dx.ValueRO.Position);
}
if (playerEntities.Length == 0 && structureEntities.Length == 0 && decoyEntities.Length == 0)
{
playerEntities.Dispose();
playerPositions.Dispose();
playerRegions.Dispose();
structureEntities.Dispose();
structurePositions.Dispose();
structureRegions.Dispose();
decoyEntities.Dispose();
decoyPositions.Dispose();
return;
}
float dt = SystemAPI.Time.DeltaTime;
var serverTick = SystemAPI.GetSingleton<NetworkTime>().ServerTick;
uint now = serverTick.TickIndexForValidTick;
float decoyAggroSq = 30f * 30f; // LANTERN decoy-wisp aggro radius (world units, squared)
// Live feel knobs (MC-0): one read, guarded at use. Server-only — clients never simulate enemies.
var tune = SystemAPI.TryGetSingleton<TuningConfig>(out var tcfg) ? tcfg : TuningConfig.Defaults();
float structAggro = math.max(0f, tune.StructureAggroWeight);
var ecb = new EntityCommandBuffer(Allocator.Temp);
bool havePhysics = SystemAPI.TryGetSingleton<PhysicsWorldSingleton>(out var physics);
uint envMask = SystemAPI.TryGetSingleton<WorldCollisionConfig>(out var worldCol) ? worldCol.EnvironmentMask : 0u;
uint sweepMask = envMask | worldCol.StructureMask; // DR-042 C5: also collide enemies against player-built walls
var envFilter = new CollisionFilter { BelongsTo = ~0u, CollidesWith = sweepMask, GroupIndex = 0 };
bool sweep = havePhysics && sweepMask != 0u;
const float SweepRadius = 0.5f; // collide-and-slide sphere radius for Husk movement
// Anti-stuck (1/2): DEPENETRATE every living enemy out of any env/cover it overlaps BEFORE seeking, so a
// Husk spawned inside or shoved into a cover rock isn't frozen by a zero-fraction sweep (the sweep cannot
// move a mover that STARTS already penetrating). One point-distance query per living enemy (<=~15/room).
// Boss excluded (BossAISystem owns it at a larger radius).
if (sweep)
{
foreach (var depenXform in SystemAPI.Query<RefRW<LocalTransform>>()
.WithAll<EnemyTag>().WithNone<Dying, BossState>().WithNone<TargetDummyTag>())
depenXform.ValueRW.Position = EnemyMoveUtil.Depenetrate(in physics, depenXform.ValueRO.Position, SweepRadius, envFilter);
}
foreach (var (xform, stats, cooldown, knockback, windup, region) in
SystemAPI.Query<RefRW<LocalTransform>, RefRO<EnemyStats>, RefRW<EnemyAttackCooldown>,
RefRW<KnockbackState>, RefRW<AttackWindup>, RefRO<RegionTag>>()
.WithAll<EnemyTag>().WithNone<LungeState, SpitterState, Dying>().WithNone<TargetDummyTag>())
{
float3 pos = xform.ValueRO.Position;
byte huskRegion = region.ValueRO.Region;
// Knockback overrides seek/strike for its window — EnemyAISystem stays the SOLE writer of Position.
var kb = knockback.ValueRO;
if (kb.UntilTick != 0)
{
var kbTick = new NetworkTick(kb.UntilTick);
if (kbTick.IsValid && kbTick.IsNewerThan(serverTick))
{
float3 kpos = pos + new float3(kb.Dir.x, 0f, kb.Dir.y) * (kb.Speed * dt);
kpos.y = pos.y;
if (sweep)
kpos = SweptMove(in physics, pos, kpos, SweepRadius, envFilter);
xform.ValueRW.Position = kpos;
if (kb.Speed >= tune.StaggerKnockbackSpeed)
windup.ValueRW.WindUpUntilTick = 0; // B2 poise: only a HEAVY hit interrupts; a light hit nudges while the wind-up keeps counting
continue; // recoiling: skip seek + strike this tick
}
knockback.ValueRW.UntilTick = 0; // window elapsed
}
// EB-1 fortress aggro: nearest of players (weight 1) + structures (StructureAggroWeight) — a wall/
// turret is the preferred target unless a player is in the way (closer after weighting).
EnemyAIMath.PickWeightedNearest(pos, playerPositions, playerRegions, structurePositions, structureRegions, huskRegion, structAggro, out bool tgtIsStruct, out int tgtIdx);
// Decoy aggro (LANTERN): a decoy-wisp within range is the PREFERRED target -- overrides player/structure/core.
int decoyIdx = -1;
float decoyBestSq = decoyAggroSq;
for (int di = 0; di < decoyPositions.Length; di++)
{
float dsq = math.distancesq(pos.xz, decoyPositions[di].xz);
if (dsq <= decoyBestSq) { decoyBestSq = dsq; decoyIdx = di; }
}
Entity targetEntity;
float3 targetPos;
if (decoyIdx >= 0)
{
targetEntity = decoyEntities[decoyIdx];
targetPos = decoyPositions[decoyIdx];
}
else
{
if (tgtIdx < 0)
continue; // no decoy, no player/structure -> nothing to seek
targetEntity = tgtIsStruct ? structureEntities[tgtIdx] : playerEntities[tgtIdx];
targetPos = tgtIsStruct ? structurePositions[tgtIdx] : playerPositions[tgtIdx];
}
// Seek: stop just inside strike range so the Husk holds position to attack.
float stopDistance = stats.ValueRO.AttackRange * 0.9f;
float3 vel = EnemyAIMath.SeekVelocity(pos, targetPos, stats.ValueRO.MoveSpeed, stopDistance);
float3 newPos = pos + vel * dt;
newPos.y = pos.y; // hold the movement plane
if (sweep)
newPos = SweptMove(in physics, pos, newPos, SweepRadius, envFilter);
xform.ValueRW.Position = newPos;
// Face the target (planar) for presentation.
float3 toTarget = targetPos - pos;
toTarget.y = 0f;
if (math.lengthsq(toTarget) > 1e-6f)
xform.ValueRW.Rotation = quaternion.LookRotationSafe(math.normalize(toTarget), math.up());
// Two-phase strike with a telegraph wind-up: commit a wind-up when first in-range + cooldown-ready,
// then strike when it elapses. WindUpUntilTick is a [GhostField] so the client can cue the ~0.3s
// tell; leaving range mid-windup cancels it. Tuning.AttackWindupTicks = 0/1 -> near-instant (legacy).
bool inRange = EnemyAIMath.InAttackRange(pos, targetPos, stats.ValueRO.AttackRange);
uint windRaw = windup.ValueRO.WindUpUntilTick;
if (windRaw != 0)
{
// B1 commitment: once inside the final ~30% of the wind-up the strike is COMMITTED — leaving
// range no longer cancels it (a last-instant step-back won't save you; dash i-frames or an early
// exit will). A committed swing the player dodged out of WHIFFS at elapse (still burns cooldown)
// -> the punish window, mirroring the Charger. Grunts (speed < player) can now actually land on a
// lingering player instead of being trivially kited (readable-but-fair).
var windTick = new NetworkTick(windRaw);
bool elapsed = !(windTick.IsValid && windTick.IsNewerThan(serverTick));
int remain = windTick.IsValid ? windTick.TicksSince(serverTick) : 0;
uint gTotal = (uint)math.max(1f, tune.GruntWindupTicks);
bool committed = remain > 0 && remain <= (int)(gTotal * 0.3f);
if (!elapsed)
{
if (!inRange && !committed)
windup.ValueRW.WindUpUntilTick = 0; // left range early -> cancel the wind-up
}
else
{
if (inRange && targetEntity != Entity.Null) ecb.AppendToBuffer(targetEntity, new DamageEvent
{
Amount = stats.ValueRO.AttackDamage,
SourceNetworkId = -1, // environment / Husk, not a player
SourceTick = TickUtil.NonZero(now),
});
uint cooldownTicks = (uint)math.max(1, stats.ValueRO.AttackCooldownTicks);
cooldown.ValueRW.NextAttackTick = TickUtil.NonZero(now + cooldownTicks);
windup.ValueRW.WindUpUntilTick = 0;
}
}
else if (inRange)
{
uint nextRaw = cooldown.ValueRO.NextAttackTick;
bool ready = true;
if (nextRaw != 0)
{
var nextTick = new NetworkTick(nextRaw);
if (nextTick.IsValid && nextTick.IsNewerThan(serverTick))
ready = false;
}
if (ready)
{
uint windupTicks = (uint)math.max(1f, tune.GruntWindupTicks);
windup.ValueRW.WindUpUntilTick = TickUtil.NonZero(now + windupTicks);
}
}
}
// --- Charger pass: a Husk variant baked with LungeState commits to a punishable fixed-direction lunge.
// Component-presence is the discriminator; the Grunt pass above excludes these via .WithNone<LungeState>().
// Charger feel knobs — live-tunable via TuningConfig (MC-0), guarded at the read site. Server-only
// (clients never simulate Chargers); the >=1-tick floor avoids a degenerate instant/no-travel lunge.
float ChargerLungeSpeed = math.max(0f, tune.ChargerLungeSpeed); // units/s while lunging
uint ChargerLungeDurationTicks = (uint)math.max(1f, tune.ChargerLungeDurationTicks); // committed travel
uint ChargerWindupTicks = (uint)math.max(1f, tune.ChargerWindupTicks); // readable telegraph lead
uint ChargerWhiffStaggerTicks = (uint)math.max(1f, tune.ChargerWhiffStaggerTicks); // punish window
uint chargerWhiffsThisTick = 0;
foreach (var (xform, stats, cooldown, knockback, windup, lunge, region) in
SystemAPI.Query<RefRW<LocalTransform>, RefRO<EnemyStats>, RefRW<EnemyAttackCooldown>,
RefRW<KnockbackState>, RefRW<AttackWindup>, RefRW<LungeState>, RefRO<RegionTag>>()
.WithAll<EnemyTag>().WithNone<SpitterState, BossState, Dying>())
{
float3 pos = xform.ValueRO.Position;
byte cHuskRegion = region.ValueRO.Region;
// 1. Knockback wins (and cancels any in-flight lunge so Position keeps a single writer).
var kb = knockback.ValueRO;
if (kb.UntilTick != 0)
{
var kbTick = new NetworkTick(kb.UntilTick);
if (kbTick.IsValid && kbTick.IsNewerThan(serverTick))
{
float3 kpos = pos + new float3(kb.Dir.x, 0f, kb.Dir.y) * (kb.Speed * dt);
kpos.y = pos.y;
if (sweep) kpos = SweptMove(in physics, pos, kpos, SweepRadius, envFilter);
xform.ValueRW.Position = kpos;
if (kb.Speed >= tune.StaggerKnockbackSpeed)
{
windup.ValueRW.WindUpUntilTick = 0; // B2 poise: only a HEAVY hit breaks the windup / committed lunge
lunge.ValueRW.UntilTick = 0;
}
continue;
}
knockback.ValueRW.UntilTick = 0;
}
// EB-1 fortress aggro: same weighted target selection as the Grunt pass (shared helper).
EnemyAIMath.PickWeightedNearest(pos, playerPositions, playerRegions, structurePositions, structureRegions, cHuskRegion, structAggro, out bool cIsStruct, out int cIdx);
if (cIdx < 0)
continue;
Entity cTargetEntity = cIsStruct ? structureEntities[cIdx] : playerEntities[cIdx];
float3 cTargetPos = cIsStruct ? structurePositions[cIdx] : playerPositions[cIdx];
// 2. Lunge active: travel the locked direction; damage on contact, or stagger on a wall-stop whiff.
var lg = lunge.ValueRO;
if (lg.UntilTick != 0)
{
var lgTick = new NetworkTick(lg.UntilTick);
if (lgTick.IsValid && lgTick.IsNewerThan(serverTick))
{
float3 intended = pos + new float3(lg.Dir.x, 0f, lg.Dir.y) * (lg.Speed * dt);
intended.y = pos.y;
float3 moved = sweep ? SweptMove(in physics, pos, intended, SweepRadius, envFilter) : intended;
xform.ValueRW.Position = moved;
if (math.lengthsq(lg.Dir) > 1e-6f)
xform.ValueRW.Rotation = quaternion.LookRotationSafe(new float3(lg.Dir.x, 0f, lg.Dir.y), math.up());
if (EnemyAIMath.InAttackRange(moved, cTargetPos, stats.ValueRO.AttackRange))
{
if (cTargetEntity != Entity.Null) ecb.AppendToBuffer(cTargetEntity, new DamageEvent
{
Amount = stats.ValueRO.AttackDamage,
SourceNetworkId = -1,
SourceTick = TickUtil.NonZero(now),
});
uint cdTicks = (uint)math.max(1, stats.ValueRO.AttackCooldownTicks);
cooldown.ValueRW.NextAttackTick = TickUtil.NonZero(now + cdTicks);
lunge.ValueRW.UntilTick = 0; // landed -> end the lunge
}
else
{
float intendedDist = math.distance(pos.xz, intended.xz);
float actualDist = math.distance(pos.xz, moved.xz);
if (intendedDist > 1e-4f && actualDist < intendedDist * 0.5f)
{
cooldown.ValueRW.NextAttackTick = TickUtil.NonZero(now + ChargerWhiffStaggerTicks);
lunge.ValueRW.UntilTick = 0; // wall-stop whiff -> stagger (the punish window)
chargerWhiffsThisTick++;
lunge.ValueRW.StaggerUntilTick = TickUtil.NonZero(now + ChargerWhiffStaggerTicks); // scoreable punish window
}
}
continue; // committed this tick
}
// Timer elapsed without landing -> overshoot whiff -> stagger, then seek this tick.
cooldown.ValueRW.NextAttackTick = TickUtil.NonZero(now + ChargerWhiffStaggerTicks);
lunge.ValueRW.UntilTick = 0;
chargerWhiffsThisTick++;
lunge.ValueRW.StaggerUntilTick = TickUtil.NonZero(now + ChargerWhiffStaggerTicks); // scoreable punish window
}
// 3. Seek + face (shared shape with the Grunt path). B3: a whiffed Charger is ROOTED during its
// stagger punish window so the advertised punish reads (the player sees it stop). Facing still tracks.
bool cStaggered = lunge.ValueRO.StaggerUntilTick != 0u
&& new NetworkTick(lunge.ValueRO.StaggerUntilTick).IsNewerThan(serverTick);
if (!cStaggered)
{
float cStop = stats.ValueRO.AttackRange * 0.9f;
float3 cvel = EnemyAIMath.SeekVelocity(pos, cTargetPos, stats.ValueRO.MoveSpeed, cStop);
float3 cNewPos = pos + cvel * dt; cNewPos.y = pos.y;
if (sweep) cNewPos = SweptMove(in physics, pos, cNewPos, SweepRadius, envFilter);
xform.ValueRW.Position = cNewPos;
}
float3 cToTarget = cTargetPos - pos; cToTarget.y = 0f;
if (math.lengthsq(cToTarget) > 1e-6f)
xform.ValueRW.Rotation = quaternion.LookRotationSafe(math.normalize(cToTarget), math.up());
// 4. Commit: a wind-up elapses -> LOCK the lunge direction + fire. NO cancel-on-leave-range — the
// whole point is the commit lands even if the player dodged out of range (the punishable tell).
uint cWindRaw = windup.ValueRO.WindUpUntilTick;
if (cWindRaw != 0)
{
var cWindTick = new NetworkTick(cWindRaw);
if (!(cWindTick.IsValid && cWindTick.IsNewerThan(serverTick)))
{
float3 toT = cTargetPos - pos; toT.y = 0f;
float2 ldir = math.lengthsq(toT) > 1e-6f ? math.normalize(toT.xz) : new float2(0f, 1f);
lunge.ValueRW.Dir = ldir;
lunge.ValueRW.Speed = ChargerLungeSpeed;
lunge.ValueRW.UntilTick = TickUtil.NonZero(now + ChargerLungeDurationTicks);
windup.ValueRW.WindUpUntilTick = 0;
}
}
else
{
bool cInRange = EnemyAIMath.InAttackRange(pos, cTargetPos, stats.ValueRO.AttackRange);
if (cInRange)
{
bool cReady = cooldown.ValueRO.NextAttackTick == 0
|| !new NetworkTick(cooldown.ValueRO.NextAttackTick).IsNewerThan(serverTick);
if (cReady)
windup.ValueRW.WindUpUntilTick = TickUtil.NonZero(now + ChargerWindupTicks);
}
}
}
// --- Spitter pass: a Husk variant baked with SpitterState holds a RANGED range-band and fires a
// telegraphed, dodgeable spit. Partitioned .WithAll<SpitterState>().WithNone<LungeState>() (and the Grunt
// pass excludes SpitterState) so a Spitter is moved by EXACTLY this pass — the sole-Position-writer rule.
bool haveSpit = SystemAPI.TryGetSingleton<SpitterProjectilePrefab>(out var spitCfg) && spitCfg.Prefab != Entity.Null;
int liveSpits = m_EnemyProjectiles.CalculateEntityCount();
LocalTransform spitBakedLt = default;
EnemyProjectile spitBakedProj = default;
if (haveSpit)
{
spitBakedLt = state.EntityManager.GetComponentData<LocalTransform>(spitCfg.Prefab);
spitBakedProj = state.EntityManager.GetComponentData<EnemyProjectile>(spitCfg.Prefab);
}
foreach (var (xform, stats, knockback, windup, spitter, region) in
SystemAPI.Query<RefRW<LocalTransform>, RefRO<EnemyStats>, RefRW<KnockbackState>,
RefRW<AttackWindup>, RefRW<SpitterState>, RefRO<RegionTag>>()
.WithAll<EnemyTag, SpitterState>().WithNone<LungeState, Dying>().WithNone<TargetDummyTag>())
{
float3 pos = xform.ValueRO.Position;
byte sRegion = region.ValueRO.Region;
// 1. Knockback overrides everything (sole Position writer preserved).
var kb = knockback.ValueRO;
if (kb.UntilTick != 0)
{
var kbTick = new NetworkTick(kb.UntilTick);
if (kbTick.IsValid && kbTick.IsNewerThan(serverTick))
{
float3 kpos = pos + new float3(kb.Dir.x, 0f, kb.Dir.y) * (kb.Speed * dt);
kpos.y = pos.y;
if (sweep) kpos = SweptMove(in physics, pos, kpos, SweepRadius, envFilter);
xform.ValueRW.Position = kpos;
if (kb.Speed >= tune.StaggerKnockbackSpeed)
windup.ValueRW.WindUpUntilTick = 0; // B2 poise: light hits nudge, only heavy interrupts
continue;
}
knockback.ValueRW.UntilTick = 0;
}
// 2. Target (region-scoped shared helper); no target -> idle.
EnemyAIMath.PickWeightedNearest(pos, playerPositions, playerRegions, structurePositions, structureRegions, sRegion, structAggro, out bool sIsStruct, out int sIdx);
if (sIdx < 0)
continue;
Entity sTargetEntity = sIsStruct ? structureEntities[sIdx] : playerEntities[sIdx];
float3 sTargetPos = sIsStruct ? structurePositions[sIdx] : playerPositions[sIdx];
// 3. Range-band movement: advance if too far, retreat if too close, hold in-band. Face the target.
var sp = spitter.ValueRO;
// Once the player has closed inside CorneredRange the Spitter STANDS (no flee) + point-blanks — so a
// melee player who commits can actually catch it (fixes the endless-kite complaint; the spit is dash-dodgeable).
bool sCorneredMove = math.distance(pos.xz, sTargetPos.xz) <= sp.CorneredRange;
float3 bandVel = sCorneredMove ? float3.zero
: EnemyAIMath.BandVelocity(pos, sTargetPos, stats.ValueRO.MoveSpeed, sp.PreferredRange, sp.RangeTolerance);
float3 sNewPos = pos + bandVel * dt; sNewPos.y = pos.y;
if (sweep) sNewPos = SweptMove(in physics, pos, sNewPos, SweepRadius, envFilter);
xform.ValueRW.Position = sNewPos;
float3 sToTarget = sTargetPos - pos; sToTarget.y = 0f;
if (math.lengthsq(sToTarget) > 1e-6f)
xform.ValueRW.Rotation = quaternion.LookRotationSafe(math.normalize(sToTarget), math.up());
// 4. Telegraphed shot: commit a wind-up (the dodge window) when the shot gate is ready; on elapse,
// spawn a spit toward the target. A cornered Spitter still fires (point-blank) — no safe corner.
uint sWindRaw = windup.ValueRO.WindUpUntilTick;
if (sWindRaw != 0)
{
var sWindTick = new NetworkTick(sWindRaw);
if (!(sWindTick.IsValid && sWindTick.IsNewerThan(serverTick)))
{
float2 dir2 = math.lengthsq(sToTarget) > 1e-6f ? math.normalize(sToTarget.xz) : new float2(0f, 1f);
if (haveSpit && liveSpits < math.max(1, spitCfg.MaxLiveProjectiles))
{
float3 spawnPos = pos + new float3(dir2.x, 0f, dir2.y) * 0.8f;
spawnPos.y = pos.y;
var spit = ecb.Instantiate(spitCfg.Prefab);
ecb.SetComponent(spit, spitBakedLt.WithPosition(spawnPos)); // preserve baked [GhostField] Scale
ecb.SetComponent(spit, new EnemyProjectile
{
Direction = dir2,
Speed = sp.ProjectileSpeed,
Damage = stats.ValueRO.AttackDamage,
Range = spitBakedProj.Range,
DistanceTravelled = 0f,
LastStep = 0f,
Region = sRegion,
});
ecb.AddComponent(spit, new RegionTag { Region = sRegion }); // relevancy (the spit prefab bakes none)
liveSpits++;
uint shotCd = (uint)math.max(1, stats.ValueRO.AttackCooldownTicks);
spitter.ValueRW.NextShotTick = TickUtil.NonZero(now + shotCd);
}
else
{
// Over the concurrent cap (or no prefab wired): soft-fail — short retry, no full cooldown burn.
spitter.ValueRW.NextShotTick = TickUtil.NonZero(now + 8u);
}
windup.ValueRW.WindUpUntilTick = 0;
}
}
else
{
bool sReady = sp.NextShotTick == 0 || !new NetworkTick(sp.NextShotTick).IsNewerThan(serverTick);
// In-band gate (DR-041): telegraph + fire ONLY when holding the preferred band, OR when the target has
// closed inside CorneredRange (point-blank, no retreat room). While ADVANCING from too far OR
// RETREATING from a too-close target it must NOT fire — that IS the hold-range "reposition" question.
float sDist = math.length(sToTarget);
bool sInBand = math.abs(sDist - sp.PreferredRange) <= sp.RangeTolerance;
bool sCornered = sDist <= sp.CorneredRange;
if (sReady && (sInBand || sCornered))
{
uint wTicks = (uint)math.max(1, sp.WindupTicks);
windup.ValueRW.WindUpUntilTick = TickUtil.NonZero(now + wTicks);
}
}
}
// Slice 1 (Feature D): derive the replicated IsLunging cue ONCE per tick from the end-of-tick LungeState
// (single point, idempotent — mirrors PlayerDeathStateSystem deriving Dead from Health). .WithPresent so a
// Charger whose bit is currently DISABLED is still visited (Entities default-excludes disabled enableables).
foreach (var (lunge, isLunging) in
SystemAPI.Query<RefRO<LungeState>, EnabledRefRW<IsLunging>>()
.WithAll<EnemyTag>().WithPresent<IsLunging>().WithNone<Dying>().WithNone<TargetDummyTag>())
{
isLunging.ValueRW = lunge.ValueRO.UntilTick != 0u; // lunging iff a committed lunge is live this tick
}
// --- Phase 1 B1: SEPARATION (soft-collision) so hordes stop interpenetrating. Lives INSIDE
// EnemyAISystem (the sole enemy-Position writer; BossAISystem runs after and re-owns the boss).
// Pairwise among LIVING enemies (MaxAlive <= ~14 + boss -> O(n^2) is trivial); an enemy mid-knockback
// or mid-lunge keeps its committed motion (immovable this tick) but still pushes neighbours away, and
// the BOSS is never pushed (knockback-immune identity). Enemies also yield a SMALL personal radius
// around each player (below melee range so grunts can still strike - review B1-1). Displacement goes
// through the same swept move so separation cannot shove anything through walls.
{
var sepEnt = new NativeList<Entity>(Allocator.Temp);
var sepPos = new NativeList<float3>(Allocator.Temp);
var sepRad = new NativeList<float>(Allocator.Temp);
var sepMov = new NativeList<bool>(Allocator.Temp);
foreach (var (sxf, shr, se) in SystemAPI.Query<RefRO<LocalTransform>, RefRO<HitRadius>>()
.WithAll<EnemyTag>().WithNone<Dying>().WithEntityAccess())
{
bool movable = !SystemAPI.HasComponent<BossState>(se);
if (movable && SystemAPI.HasComponent<KnockbackState>(se))
{
var k = SystemAPI.GetComponent<KnockbackState>(se);
if (k.UntilTick != 0 && new NetworkTick(k.UntilTick).IsNewerThan(serverTick)) movable = false;
}
if (movable && SystemAPI.HasComponent<LungeState>(se))
{
var l = SystemAPI.GetComponent<LungeState>(se);
if (l.UntilTick != 0 && new NetworkTick(l.UntilTick).IsNewerThan(serverTick)) movable = false;
}
sepEnt.Add(se); sepPos.Add(sxf.ValueRO.Position); sepRad.Add(shr.ValueRO.Value); sepMov.Add(movable);
}
float sepMaxStep = math.max(0f, tune.SeparationMaxSpeed) * dt;
for (int i = 0; i < sepEnt.Length && sepMaxStep > 0f; i++)
{
if (!sepMov[i]) continue;
float3 pi = sepPos[i];
float2 push = float2.zero;
for (int j = 0; j < sepEnt.Length; j++)
{
if (j == i) continue;
float2 d = pi.xz - sepPos[j].xz;
float want = (sepRad[i] + sepRad[j]) * 0.9f;
float distSq = math.lengthsq(d);
if (want <= 0f || distSq >= want * want) continue;
float dist = math.sqrt(distSq);
// Exact stacks de-overlap deterministically by index (golden angle), never randomly.
float2 dir = dist > 1e-4f ? d / dist : new float2(math.sin(i * 2.399963f), math.cos(i * 2.399963f));
push += dir * (want - dist) * 0.5f;
}
for (int pj = 0; pj < playerPositions.Length; pj++)
{
float2 d = pi.xz - playerPositions[pj].xz;
float want = sepRad[i] + 0.35f; // small: never blocks strike range or the Spitter cornered-hold
float distSq = math.lengthsq(d);
if (distSq >= want * want) continue;
float dist = math.sqrt(distSq);
float2 dir = dist > 1e-4f ? d / dist : new float2(1f, 0f);
push += dir * (want - dist);
}
if (math.lengthsq(push) < 1e-8f) continue;
float pushLen = math.length(push);
if (pushLen > sepMaxStep) push *= sepMaxStep / pushLen;
float3 sepTarget = pi + new float3(push.x, 0f, push.y);
sepTarget.y = pi.y;
if (sweep) sepTarget = SweptMove(in physics, pi, sepTarget, SweepRadius, envFilter);
var sepXf = SystemAPI.GetComponentRW<LocalTransform>(sepEnt[i]);
sepXf.ValueRW.Position = sepTarget;
}
sepEnt.Dispose(); sepPos.Dispose(); sepRad.Dispose(); sepMov.Dispose();
}
// Anti-stuck (2/2): the GUARANTEED backstop. An enemy that WANTS to close on its target (outside attack
// range, not knocked/lunging/staggered) but hasn't gained ground on it for StuckUnstickTicks is phase-
// nudged toward the nearest target (collide-and-slide bypassed) until it escapes -> a room can never
// soft-lock on one Husk wedged in geometry the reactive slide can't solve. Progress is measured as
// distance CLOSED toward the target (not raw displacement) so the separation jiggle can't mask a stuck
// Husk. Server-only; EnemyNavState is not replicated. Spitters hold at range by design (excluded); the
// boss is driven by BossAISystem (excluded).
{
const float StuckMinProgressPerTick = 0.02f;
const uint StuckUnstickTicks = 90u; // ~1.5s of no ground gained before the nudge triggers
const uint NudgeBurstTicks = 45u; // ~0.75s of phasing toward the target per trigger
const float UnstickNudgeSpeed = 4.5f; // units/s while phase-nudging out of geometry
float nudgeStep = UnstickNudgeSpeed * dt;
foreach (var (nxform, nstats, nav, nregion, nent) in
SystemAPI.Query<RefRW<LocalTransform>, RefRO<EnemyStats>, RefRW<EnemyNavState>, RefRO<RegionTag>>()
.WithAll<EnemyTag>().WithNone<SpitterState, BossState, Dying>().WithNone<TargetDummyTag>().WithEntityAccess())
{
float3 npos = nxform.ValueRO.Position;
byte nRegion = nregion.ValueRO.Region;
bool committed = false;
if (SystemAPI.HasComponent<KnockbackState>(nent))
{
var k = SystemAPI.GetComponent<KnockbackState>(nent);
committed |= k.UntilTick != 0 && new NetworkTick(k.UntilTick).IsNewerThan(serverTick);
}
if (SystemAPI.HasComponent<LungeState>(nent))
{
var l = SystemAPI.GetComponent<LungeState>(nent);
committed |= (l.UntilTick != 0 && new NetworkTick(l.UntilTick).IsNewerThan(serverTick))
|| (l.StaggerUntilTick != 0 && new NetworkTick(l.StaggerUntilTick).IsNewerThan(serverTick));
}
EnemyAIMath.PickWeightedNearest(npos, playerPositions, playerRegions, structurePositions, structureRegions, nRegion, structAggro, out bool nIsStruct, out int nIdx);
bool hasTarget = nIdx >= 0;
float3 nTarget = nIdx < 0 ? npos : (nIsStruct ? structurePositions[nIdx] : playerPositions[nIdx]);
bool wantsToClose = hasTarget && !committed
&& math.distance(npos.xz, nTarget.xz) > nstats.ValueRO.AttackRange * 1.15f;
bool nudging = nav.ValueRO.NudgeUntilTick != 0 && new NetworkTick(nav.ValueRO.NudgeUntilTick).IsNewerThan(serverTick);
if (nudging)
{
if (wantsToClose)
{
float3 toT = nTarget - npos; toT.y = 0f;
float l2 = math.lengthsq(toT);
if (l2 > 1e-6f)
{
float3 step = math.normalize(toT) * math.min(nudgeStep, math.sqrt(l2));
float3 np = npos + step; np.y = npos.y;
nxform.ValueRW.Position = np;
nav.ValueRW.LastPos = np;
continue;
}
}
nav.ValueRW.NudgeUntilTick = 0; // reached range / lost target -> stop nudging
}
if (!wantsToClose)
{
nav.ValueRW.StuckTicks = 0u;
nav.ValueRW.LastPos = npos;
continue;
}
float progressToward = math.distance(nav.ValueRO.LastPos.xz, nTarget.xz) - math.distance(npos.xz, nTarget.xz);
uint st = progressToward < StuckMinProgressPerTick ? nav.ValueRO.StuckTicks + 1u : 0u;
nav.ValueRW.LastPos = npos;
if (st >= StuckUnstickTicks)
{
// COVER-AWARE (destructible-cover review wf_e14dd739-069 HIGH): if what blocks this enemy
// is a LIVE cover GHOST (BlightClutter carrier), do NOT phase-nudge — cover must genuinely
// hold until the player breaks it. No soft-lock is possible: the blocker is destructible,
// and the counter stays primed so any OTHER wedge (static geometry) still nudges next check.
bool blockedByCover = false;
if (havePhysics)
{
float3 toTgt = nTarget - npos; toTgt.y = 0f;
float tl = math.length(toTgt);
if (tl > 1e-4f && physics.CollisionWorld.SphereCast(
npos, 0.35f, toTgt / tl, math.min(1.8f, tl), out var coverHit, envFilter))
blockedByCover = SystemAPI.HasComponent<BlightClutter>(coverHit.Entity);
}
if (!blockedByCover)
{
nav.ValueRW.NudgeUntilTick = TickUtil.NonZero(now + NudgeBurstTicks);
st = 0u;
}
}
nav.ValueRW.StuckTicks = st;
}
}
if (chargerWhiffsThisTick != 0 && SystemAPI.HasSingleton<DevTelemetry>())
SystemAPI.GetSingletonRW<DevTelemetry>().ValueRW.ChargerWhiffWindowsOpened += chargerWhiffsThisTick;
ecb.Playback(state.EntityManager);
ecb.Dispose();
playerEntities.Dispose();
playerPositions.Dispose();
playerRegions.Dispose();
structureEntities.Dispose();
structurePositions.Dispose();
structureRegions.Dispose();
decoyEntities.Dispose();
decoyPositions.Dispose();
}
// Swept collide-and-slide for server-authoritative enemy movement — delegates to the shared
// EnemyMoveUtil.SweptMove (extracted so BossAISystem reuses ONE collide-and-slide impl; a fix reaches both).
// Kept as a private wrapper so this file's many call sites read unchanged.
static float3 SweptMove(in PhysicsWorldSingleton physics, float3 from, float3 to, float radius, CollisionFilter filter)
=> EnemyMoveUtil.SweptMove(in physics, from, to, radius, filter);
}
}