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 { /// /// 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 /// — writing directly (replicated to clients /// by the stock LocalTransform default variant; no hand-written [GhostField]). Ordered /// [UpdateAfter(PredictedSimulationSystemGroup)] (the predicted group is OrderFirst, so UpdateBefore is ignored) so a contact appended this /// tick is drained the following tick by (which runs inside the predicted /// group on the server). No Simulate 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 /// ; server fixed-step SystemAPI.Time.DeltaTime is correct here (not the /// rollback loop). Structural-free: the only deferred op is appending to the player's DamageEvent buffer. /// [BurstCompile] [WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)] [UpdateInGroup(typeof(SimulationSystemGroup))] [UpdateAfter(typeof(PredictedSimulationSystemGroup))] public partial struct EnemyAISystem : ISystem { [BurstCompile] public void OnCreate(ref SystemState state) { state.RequireForUpdate(); state.RequireForUpdate(state.GetEntityQuery(ComponentType.ReadOnly())); } [BurstCompile] public void OnUpdate(ref SystemState state) { // Snapshot living player targets once this tick (stable query order). var playerEntities = new NativeList(Allocator.Temp); var playerPositions = new NativeList(Allocator.Temp); var playerRegions = new NativeList(Allocator.Temp); foreach (var (xform, health, region, entity) in SystemAPI.Query, RefRO, RefRO>() .WithAll() .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(Allocator.Temp); var structurePositions = new NativeList(Allocator.Temp); var structureRegions = new NativeList(Allocator.Temp); // Structures were deleted with the shell (2026-08-07 audit purge), so the raze-target snapshot is // empty. The lists stay so the aggro selection below keeps one code path; drop them when the // LANTERN buildables land and give enemies something to attack again. foreach (var (sx, sh, sr, se) in SystemAPI.Query, RefRO, RefRO>() .WithAll() .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(Allocator.Temp); var decoyPositions = new NativeList(Allocator.Temp); foreach (var (dx, dh, de) in SystemAPI.Query, RefRO>() .WithAll().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().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(out var tcfg) ? tcfg : TuningConfig.Defaults(); float structAggro = math.max(0f, tune.StructureAggroWeight); var ecb = new EntityCommandBuffer(Allocator.Temp); bool havePhysics = SystemAPI.TryGetSingleton(out var physics); uint envMask = SystemAPI.TryGetSingleton(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>() .WithAll().WithNone().WithNone()) depenXform.ValueRW.Position = EnemyMoveUtil.Depenetrate(in physics, depenXform.ValueRO.Position, SweepRadius, envFilter); } foreach (var (xform, stats, cooldown, knockback, windup, region) in SystemAPI.Query, RefRO, RefRW, RefRW, RefRW, RefRO>() .WithAll().WithNone().WithNone()) { 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 / Spitter / IsLunging passes DELETED 2026-08-07 (audit purge). // ChargerAuthoring, SpitterAuthoring and SwarmerAuthoring were attached to ZERO prefabs, so // LungeState / SpitterState / SwarmerTag were never baked and these three passes could not match a // single chunk at runtime — ~272 lines of Bursted code plus 734 lines of green tests certifying an // escalation curve that always resolved to Grunt. Recover from git if the lunge/spit behaviours are // wanted; the LANTERN bestiary reintroduces variety through the CreatureKit path instead. // --- 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(Allocator.Temp); var sepPos = new NativeList(Allocator.Temp); var sepRad = new NativeList(Allocator.Temp); var sepMov = new NativeList(Allocator.Temp); foreach (var (sxf, shr, se) in SystemAPI.Query, RefRO>() .WithAll().WithNone().WithEntityAccess()) { bool movable = true; if (movable && SystemAPI.HasComponent(se)) { var k = SystemAPI.GetComponent(se); if (k.UntilTick != 0 && new NetworkTick(k.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(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, RefRO, RefRW, RefRO>() .WithAll().WithNone().WithNone().WithEntityAccess()) { float3 npos = nxform.ValueRO.Position; byte nRegion = nregion.ValueRO.Region; bool committed = false; if (SystemAPI.HasComponent(nent)) { var k = SystemAPI.GetComponent(nent); committed |= k.UntilTick != 0 && new NetworkTick(k.UntilTick).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(coverHit.Entity); } if (!blockedByCover) { nav.ValueRW.NudgeUntilTick = TickUtil.NonZero(now + NudgeBurstTicks); st = 0u; } } nav.ValueRW.StuckTicks = st; } } 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); } }