diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index b974463f..6bc72c86 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -145,6 +145,15 @@ public static void AI_TraceLOS(in Vector3 absStart, in Vector3 absEnd, BaseEntit Util.TraceLine(absStart, absEnd, Mask.BlockLOSAndNPCs, ref traceFilter, out tr); } + public static void AI_TraceLOS(in Vector3 absStart, in Vector3 absEnd, BaseEntity? looker, out Trace tr, scoped ref IF filter) where IF : struct, ITraceFilter { + if (ai_LOS_mode.GetBool()) { + Util.TraceLine(absStart, absEnd, Mask.BlockLOS, looker, CollisionGroup.None, out tr); + return; + } + + Util.TraceLine(absStart, absEnd, Mask.BlockLOSAndNPCs, ref filter, out tr); + } + public static bool AI_DoLoadSchedules(Func baseLoad, Action initCustomSchedules, ref AI_SchedLoadStatus loadStatus) { baseLoad(); @@ -4337,7 +4346,49 @@ public bool ValidateNavGoal() { return true; } - public virtual bool IsCoverPosition(in Vector3 threat, in Vector3 position) => throw new NotImplementedException(); + public virtual bool IsCoverPosition(in Vector3 threat, in Vector3 position) { + BaseEntity? passEntity = null; + + BaseEntity? enemy = GetEnemy(); + if (enemy != null) { + bool threatPosIsEnemy = (threat - enemy.EyePosition()).LengthSquared() < 0.1f; + if (threatPosIsEnemy) { + BaseCombatCharacter? ccEnemy = enemy.MyCombatCharacterPointer(); + if (ccEnemy != null && ccEnemy.IsInAVehicle()) + passEntity = ccEnemy.GetVehicleEntity(); + + passEntity ??= enemy; + } + } + + TraceFilterLOS filter = new(passEntity, Source.CollisionGroup.None, this); + AI_TraceLOS(threat, position, this, out Trace tr, ref filter); + + if (tr.Fraction != 1.0f && hl2_episodic.GetBool()) { + if (tr.Ent is BaseEntity hitEntity && hitEntity.Classname == Classname) + return false; + } + + return tr.Fraction != 1.0f; + } + + public virtual bool IsValidCover(in Vector3 coverLocation, AI_Hint? hint) { + string? hintGroup = GetHintGroup(); + if (!string.IsNullOrEmpty(hintGroup)) { + if (hint == null || hint.GetGroup() != hintGroup) + return false; + } + + Vector3 startPos = coverLocation; + startPos.Z -= GetHullMins().Z; + Vector3 endPos = startPos; + endPos.Z += 0.01f; + Util.TraceEntity(this, coverLocation, endPos, Mask.NPCSolid, out Trace tr); + if (tr.StartSolid) + return false; + + return true; + } public bool ShouldMoveWait() => MoveWaitFinished > gpGlobals.CurTime; @@ -6141,7 +6192,113 @@ public virtual int SelectAlertSchedule() { return SCHED_ALERT_STAND; } - public virtual int SelectCombatSchedule() => throw new NotImplementedException(); + public virtual void FearSound() { } + + public virtual bool UseAttackSquadSlots() => false; + + public int SelectCombatSchedule() { + if (ForcedInteractionPartner.Get() != null) + return SelectInteractionSchedule(); + + int sched = SelectFlinchSchedule(); + if (sched != SCHED_NONE) + return sched; + + if (HasCondition((int)SCOND_t.COND_NEW_ENEMY) && gpGlobals.CurTime - GetEnemies().FirstTimeSeen(GetEnemy()) < 2.0) + return SCHED_WAKE_ANGRY; + + if (HasCondition((int)SCOND_t.COND_ENEMY_DEAD)) { + SetEnemy(null); + + if (ChooseEnemy()) { + ClearCondition((int)SCOND_t.COND_ENEMY_DEAD); + return SelectSchedule(); + } + + SetState(NPCState.Alert); + return SelectSchedule(); + } + + if (IRelationType(GetEnemy()) == Disposition.FR) { + if (HasCondition((int)SCOND_t.COND_SEE_ENEMY) || + HasCondition((int)SCOND_t.COND_LIGHT_DAMAGE) || + HasCondition((int)SCOND_t.COND_HEAVY_DAMAGE)) { + FearSound(); + return SCHED_RUN_FROM_ENEMY; + } + + AI_EnemyInfo? memory = GetEnemies().Find(GetEnemy()); + if ((memory != null && memory.Unforgettable) || (GetEnemyLastTimeSeen() > (gpGlobals.CurTime - 5.0))) { + if (FInAimCone(GetEnemy()!.EyePosition())) + return SCHED_COMBAT_STAND; + + return SCHED_FEAR_FACE; + } + } + + if (HasCondition((int)SCOND_t.COND_LOW_PRIMARY_AMMO) || HasCondition((int)SCOND_t.COND_NO_PRIMARY_AMMO)) + return SCHED_HIDE_AND_RELOAD; + + if (!HasCondition((int)SCOND_t.COND_SEE_ENEMY)) { + if (!HasCondition((int)SCOND_t.COND_ENEMY_OCCLUDED)) + return SCHED_COMBAT_FACE; + + if (GetActiveWeapon() != null || (CapabilitiesGet() & (Capability.InnateRangeAttack1 | Capability.InnateRangeAttack2)) != 0) + return SCHED_ESTABLISH_LINE_OF_FIRE; + else if ((CapabilitiesGet() & (Capability.InnateMeleeAttack1 | Capability.InnateMeleeAttack2)) != 0) + return SCHED_CHASE_ENEMY; + else + return SCHED_TAKE_COVER_FROM_ENEMY; + } + + if (HasCondition((int)SCOND_t.COND_TOO_CLOSE_TO_ATTACK)) + return SCHED_BACK_AWAY_FROM_ENEMY; + + if (HasCondition((int)SCOND_t.COND_WEAPON_PLAYER_IN_SPREAD) || + HasCondition((int)SCOND_t.COND_WEAPON_BLOCKED_BY_FRIEND) || + HasCondition((int)SCOND_t.COND_WEAPON_SIGHT_OCCLUDED)) { + return SCHED_ESTABLISH_LINE_OF_FIRE; + } + + if (GetShotRegulator().IsInRestInterval()) { + if (HasCondition((int)SCOND_t.COND_CAN_RANGE_ATTACK1)) + return SCHED_COMBAT_FACE; + } + + if (HasCondition((int)SCOND_t.COND_CAN_RANGE_ATTACK1)) { + if (!UseAttackSquadSlots() || OccupyStrategySlotRange(SquadSlot.Attack1, SquadSlot.Attack2)) + return SCHED_RANGE_ATTACK1; + return SCHED_COMBAT_FACE; + } + + if (HasCondition((int)SCOND_t.COND_CAN_RANGE_ATTACK2)) + return SCHED_RANGE_ATTACK2; + + if (HasCondition((int)SCOND_t.COND_CAN_MELEE_ATTACK1)) + return SCHED_MELEE_ATTACK1; + + if (HasCondition((int)SCOND_t.COND_CAN_MELEE_ATTACK2)) + return SCHED_MELEE_ATTACK2; + + if (HasCondition((int)SCOND_t.COND_NOT_FACING_ATTACK)) + return SCHED_COMBAT_FACE; + + if (!HasCondition((int)SCOND_t.COND_CAN_RANGE_ATTACK1) && !HasCondition((int)SCOND_t.COND_CAN_MELEE_ATTACK1)) { + if (GetActiveWeapon() != null) + return SCHED_MOVE_TO_WEAPON_RANGE; + + if (HasCondition((int)SCOND_t.COND_TOO_FAR_TO_ATTACK) && (CapabilitiesGet() & (Capability.InnateRangeAttack1 | Capability.InnateRangeAttack2)) != 0) + return SCHED_MOVE_TO_WEAPON_RANGE; + + if ((CapabilitiesGet() & (Capability.InnateMeleeAttack1 | Capability.InnateMeleeAttack2)) != 0) + return SCHED_CHASE_ENEMY; + else + return SCHED_TAKE_COVER_FROM_ENEMY; + } + + DevWarning(2, "No suitable combat schedule!\n"); + return SCHED_FAIL; + } public virtual int SelectDeadSchedule() { if (BecomeRagdollOnClient(vec3_origin)) { @@ -6606,7 +6763,216 @@ public virtual void GatherEnemyConditions(BaseEntity enemy) { } } - public virtual void GatherAttackConditions(BaseEntity target, float dist) => throw new NotImplementedException(); + public void GatherAttackConditions(BaseEntity target, float dist) { + Vector3 vecLOS = target.GetAbsOrigin() - GetAbsOrigin(); + vecLOS.Z = 0; + MathLib.VectorNormalize(ref vecLOS); + + Vector3 bodyDir = BodyDirection2D(); + float dot = Vector3.Dot(vecLOS, bodyDir); + + Capability capability = CapabilitiesGet(); + + ClearAttackConditions(); + Vector3 targetPos = target.EyePosition(); + bool weaponHasLOS = CurrentWeaponLOSCondition(targetPos, true); + + if (!weaponHasLOS) { + ClearAttackConditions(); + targetPos = target.BodyTarget(GetAbsOrigin(), true); + weaponHasLOS = CurrentWeaponLOSCondition(targetPos, true); + } + else + SetCondition((int)SCOND_t.COND_WEAPON_HAS_LOS); + + BaseCombatWeapon? weapon = GetActiveWeapon(); + bool weaponIsReady = weapon != null && !IsWeaponStateChanging(); + int condition; + + if ((capability & Capability.WeaponRangeAttack1) != 0 && weaponIsReady) { + condition = (int)weapon!.WeaponRangeAttack1Condition(dot, dist); + + if (condition == (int)SCOND_t.COND_NOT_FACING_ATTACK && FInAimCone(targetPos)) + DevMsg("Warning: COND_NOT_FACING_ATTACK set but FInAimCone is true\n"); + + if (condition != (int)SCOND_t.COND_CAN_RANGE_ATTACK1 || weaponHasLOS) + SetCondition(condition); + } + else if ((capability & Capability.InnateRangeAttack1) != 0) { + condition = RangeAttack1Conditions(dot, dist); + if (condition != (int)SCOND_t.COND_CAN_RANGE_ATTACK1 || weaponHasLOS) + SetCondition(condition); + } + + if ((capability & Capability.WeaponRangeAttack2) != 0 && weaponIsReady && (weapon!.CapabilitiesGet() & Capability.WeaponRangeAttack2) != 0) { + condition = (int)weapon.WeaponRangeAttack2Condition(dot, dist); + if (condition != (int)SCOND_t.COND_CAN_RANGE_ATTACK2 || weaponHasLOS) + SetCondition(condition); + } + else if ((capability & Capability.InnateRangeAttack2) != 0) { + condition = RangeAttack2Conditions(dot, dist); + if (condition != (int)SCOND_t.COND_CAN_RANGE_ATTACK2 || weaponHasLOS) + SetCondition(condition); + } + + if ((capability & Capability.WeaponMeleeAttack1) != 0 && weaponIsReady) + SetCondition((int)weapon!.WeaponMeleeAttack1Condition(dot, dist)); + else if ((capability & Capability.InnateMeleeAttack1) != 0) + SetCondition(MeleeAttack1Conditions(dot, dist)); + + if ((capability & Capability.WeaponMeleeAttack2) != 0 && weaponIsReady) + SetCondition((int)weapon!.WeaponMeleeAttack2Condition(dot, dist)); + else if ((capability & Capability.InnateMeleeAttack2) != 0) + SetCondition(MeleeAttack2Conditions(dot, dist)); + + if (HasCondition((int)SCOND_t.COND_CAN_RANGE_ATTACK2) || + HasCondition((int)SCOND_t.COND_CAN_RANGE_ATTACK1) || + HasCondition((int)SCOND_t.COND_CAN_MELEE_ATTACK2) || + HasCondition((int)SCOND_t.COND_CAN_MELEE_ATTACK1)) { + ClearCondition((int)SCOND_t.COND_TOO_CLOSE_TO_ATTACK); + ClearCondition((int)SCOND_t.COND_TOO_FAR_TO_ATTACK); + ClearCondition((int)SCOND_t.COND_WEAPON_BLOCKED_BY_FRIEND); + } + } + + public virtual int RangeAttack1Conditions(float dot, float dist) { + if (dist < 64) + return (int)SCOND_t.COND_TOO_CLOSE_TO_ATTACK; + else if (dist > 784) + return (int)SCOND_t.COND_TOO_FAR_TO_ATTACK; + else if (dot < 0.5) + return (int)SCOND_t.COND_NOT_FACING_ATTACK; + + return (int)SCOND_t.COND_CAN_RANGE_ATTACK1; + } + + public virtual int RangeAttack2Conditions(float dot, float dist) { + if (dist < 64) + return (int)SCOND_t.COND_TOO_CLOSE_TO_ATTACK; + else if (dist > 512) + return (int)SCOND_t.COND_TOO_FAR_TO_ATTACK; + else if (dot < 0.5) + return (int)SCOND_t.COND_NOT_FACING_ATTACK; + + return (int)SCOND_t.COND_CAN_RANGE_ATTACK2; + } + + public virtual int MeleeAttack1Conditions(float dot, float dist) { + if (dist > 64) + return (int)SCOND_t.COND_TOO_FAR_TO_ATTACK; + else if (dot < 0.7) + return 0; + else if (GetEnemy() == null) + return 0; + + if ((GetEnemy()!.GetFlags() & EntityFlags.OnGround) != 0) + return (int)SCOND_t.COND_CAN_MELEE_ATTACK1; + + return 0; + } + + public virtual int MeleeAttack2Conditions(float dot, float dist) { + if (dist > 64) + return (int)SCOND_t.COND_TOO_FAR_TO_ATTACK; + else if (dot < 0.7) + return 0; + + return (int)SCOND_t.COND_CAN_MELEE_ATTACK2; + } + + public bool IsWeaponStateChanging() => DesiredWeaponState == DesiredWeaponState.Changing || DesiredWeaponState == DesiredWeaponState.ChangingDestroy; + + public virtual bool CurrentWeaponLOSCondition(in Vector3 targetPos, bool setConditions) => WeaponLOSCondition(GetAbsOrigin(), targetPos, setConditions); + + public virtual bool WeaponLOSCondition(in Vector3 ownerPos, in Vector3 targetPos, bool setConditions) { + bool haveLOS = true; + + if (GetActiveWeapon() != null) + haveLOS = GetActiveWeapon()!.WeaponLOSCondition(ownerPos, targetPos, setConditions); + else if ((CapabilitiesGet() & Capability.InnateRangeAttack1) != 0) + haveLOS = InnateWeaponLOSCondition(ownerPos, targetPos, setConditions); + else { + if (setConditions) + SetCondition((int)SCOND_t.COND_NO_WEAPON); + haveLOS = false; + } + + if ((CapabilitiesGet() & (Capability.NoHitPlayer | Capability.NoHitSquadmates)) != 0) { + float spread = 0.92f; + if (GetActiveWeapon() != null) { + Vector3 vSpread = GetAttackSpread(GetActiveWeapon()); + if (vSpread.X > VECTOR_CONE_15DEGREES.X) + spread = MathF.Cos(MathF.Asin(vSpread.X)); + else + spread = 0.99145f; + } + + if ((CapabilitiesGet() & Capability.NoHitPlayer) != 0) { + if (PlayerInSpread(ownerPos, targetPos, spread, 8 * 12)) { + if (setConditions) + SetCondition((int)SCOND_t.COND_WEAPON_PLAYER_IN_SPREAD); + haveLOS = false; + } + } + + if (haveLOS) { + if ((CapabilitiesGet() & Capability.NoHitSquadmates) != 0 && Squad != null && GetEnemy() != null) { + if (IsSquadmateInSpread(ownerPos, targetPos, spread, 8 * 12)) { + SetCondition((int)SCOND_t.COND_WEAPON_BLOCKED_BY_FRIEND); + haveLOS = false; + } + } + } + } + + return haveLOS; + } + + public virtual bool InnateWeaponLOSCondition(in Vector3 ownerPos, in Vector3 targetPos, bool setConditions) { + Vector3 barrelPos = ownerPos + GetViewOffset(); + Util.TraceLine(barrelPos, targetPos, Mask.Shot, this, Source.CollisionGroup.None, out Trace tr); + + if (tr.Fraction == 1.0f) + return true; + + BaseEntity? hitEntity = tr.Ent; + + if (GetEnemy() != null) { + BaseCombatCharacter? ccEnemy = GetEnemy()!.MyCombatCharacterPointer(); + if (ccEnemy != null && ccEnemy.IsInAVehicle()) { + BaseEntity? vehicleEnt = ccEnemy.GetVehicleEntity(); + if (hitEntity == vehicleEnt || hitEntity?.GetOwnerEntity() == vehicleEnt) + return true; + } + } + + if (hitEntity == GetEnemy()) + return true; + else if (hitEntity != null && hitEntity.MyCombatCharacterPointer() != null) { + if (IRelationType(hitEntity) == Disposition.HT) + return true; + else if (setConditions) + SetCondition((int)SCOND_t.COND_WEAPON_BLOCKED_BY_FRIEND); + } + else if (setConditions) { + SetCondition((int)SCOND_t.COND_WEAPON_SIGHT_OCCLUDED); + SetEnemyOccluder(tr.Ent); + } + + return false; + } + + public virtual bool PlayerInSpread(in Vector3 sourcePos, in Vector3 targetPos, float spread, float maxDistOffCenter, bool ignoreHatedPlayers = true) { + for (int i = 1; i <= gpGlobals.MaxClients; i++) { + BasePlayer? player = Util.PlayerByIndex(i); + + if (player != null && (!ignoreHatedPlayers || IRelationType(player) != Disposition.HT)) { + if (PointInSpread(player, sourcePos, targetPos, player.WorldSpaceCenter(), spread, maxDistOffCenter)) + return true; + } + } + return false; + } public virtual bool FCanCheckAttacks() { if (GetNavType() == Navigation.Climb || GetNavType() == Navigation.Jump) @@ -7861,7 +8227,25 @@ public override Activity NPC_TranslateActivity(Activity newActivity) { public AI_Hint? GetHintNode() => HintNode.Get(); public virtual Activity GetReloadActivity(AI_Hint? hint) => throw new NotImplementedException(); - public virtual Activity GetCoverActivity(AI_Hint? hint) => throw new NotImplementedException(); + public virtual Activity GetCoverActivity(AI_Hint? hint) { + Activity coverActivity = Activity.ACT_INVALID; + + if (hint != null) { + switch (hint.HintType()) { + case Hint.TacticalCoverMed: + coverActivity = Activity.ACT_COVER_MED; + break; + case Hint.TacticalCoverLow: + coverActivity = Activity.ACT_COVER_LOW; + break; + } + } + + if (coverActivity == Activity.ACT_INVALID) + coverActivity = Activity.ACT_COVER; + + return coverActivity; + } static readonly List sUniqueActivities = []; diff --git a/Game.Server/AI_FollowBehavior.cs b/Game.Server/AI_FollowBehavior.cs index e6c91635..ab793725 100644 --- a/Game.Server/AI_FollowBehavior.cs +++ b/Game.Server/AI_FollowBehavior.cs @@ -2,6 +2,8 @@ using Game.Shared; +using Source; + namespace Game.Server; public static class AI_FollowBehaviorGlobals @@ -43,11 +45,38 @@ public class AI_FollowManager public class AI_FollowBehavior : AI_Behavior_AI_BaseNPC_100000 { - public AI_FollowBehavior() { } + public AI_FollowBehavior() { + FollowDelay.Set(1.0f, 3.0f); + } public override string GetName() => "Follow"; - public override bool CanSelectSchedule() => throw new NotImplementedException(); + public BaseEntity? GetFollowTarget() => FollowTarget.Get(); + + public override bool CanSelectSchedule() { + if (!GetOuter()!.IsInterruptable()) + return false; + + if (!ShouldFollow()) + return false; + + return true; + } + + protected virtual bool ShouldFollow() { + if (GetFollowTarget() == null) + return false; + + if ((GetFollowTarget()!.GetFlags() & EntityFlags.NoTarget) != 0) + return false; + + if (FollowNavFailed && FollowDelay.IsRunning() && !FollowDelay.Expired()) + return false; + + FollowNavFailed = false; + + return true; + } public override void GatherConditions() => throw new NotImplementedException(); @@ -67,4 +96,7 @@ protected override void Precache() { protected AI_FollowManagerInfoHandle_t FollowManagerInfo; protected AI_FollowParams Params = new(); + + bool FollowNavFailed; + readonly RandStopwatch FollowDelay = new(); } diff --git a/Game.Server/AI_Squad.cs b/Game.Server/AI_Squad.cs index 386aec70..c838e1f1 100644 --- a/Game.Server/AI_Squad.cs +++ b/Game.Server/AI_Squad.cs @@ -29,6 +29,7 @@ public class AI_Squad public bool FOkToMakeSound(SentencePriority soundPriority) => throw new NotImplementedException(); public void JustMadeSound(SentencePriority soundPriority, TimeUnit_t time) => throw new NotImplementedException(); public bool IsLeader(AI_BaseNPC npc) => throw new NotImplementedException(); + public AI_BaseNPC? GetLeader() => throw new NotImplementedException(); public void SquadRemember(AI_MemoryFlags memory) => throw new NotImplementedException(); public void BroadcastInteraction(AI_Interaction interactionType, object? data, BaseCombatCharacter? sender) => throw new NotImplementedException(); public AI_BaseNPC? GetFirstMember(out int iter) => throw new NotImplementedException(); diff --git a/Game.Server/AI_TacticalServices.cs b/Game.Server/AI_TacticalServices.cs index fc8586b4..34d8ce44 100644 --- a/Game.Server/AI_TacticalServices.cs +++ b/Game.Server/AI_TacticalServices.cs @@ -15,7 +15,122 @@ public void Init(AI_Network? network) { Assert(Pathfinder != null); } - public bool FindCoverPos(in Vector3 threatPos, in Vector3 threatEyePos, float minDist, float maxDist, out Vector3 result) => throw new NotImplementedException(); + public bool FindCoverPos(in Vector3 threatPos, in Vector3 threatEyePos, float minDist, float maxDist, out Vector3 result) + => FindCoverPos(GetLocalOrigin(), threatPos, threatEyePos, minDist, maxDist, out result); + + public bool FindCoverPos(in Vector3 nearPos, in Vector3 threatPos, in Vector3 threatEyePos, float minDist, float maxDist, out Vector3 result) { + int node = FindCoverNode(nearPos, threatPos, threatEyePos, minDist, maxDist); + + if (node == NO_NODE) { + result = default; + return false; + } + + result = GetNodePos(node); + return true; + } + + static int SearchRandomizer; + static readonly PriorityQueue NodeList = new(); + + public int FindCoverNode(in Vector3 threatPos, in Vector3 threatEyePos, float minDist, float maxDist) + => FindCoverNode(GetLocalOrigin(), threatPos, threatEyePos, minDist, maxDist); + + public int FindCoverNode(in Vector3 nearPos, in Vector3 threatPos, in Vector3 threatEyePos, float minDist, float maxDist) { + if (!AI_NetworkManager.NetworksLoaded()) + return NO_NODE; + + AI_BaseNPC outer = GetOuter()!; + int myNode = Pathfinder!.NearestNodeToPoint(nearPos); + + if (myNode == NO_NODE) { + Vector3 pos = outer.GetAbsOrigin(); + DevWarning(2, $"FindCover() - {outer.GetClassname()} has no nearest node! (Check near {pos.X} {pos.Y} {pos.Z})\n"); + return NO_NODE; + } + + if (maxDist == 0) + maxDist = 784; + + if (minDist > 0.5f * maxDist) + minDist = 0.5f * maxDist; + + int numNodes = Network!.NumNodes(); + PriorityQueue list = NodeList; + list.Clear(); + Span wasVisited = stackalloc bool[numNodes]; + + list.Enqueue(myNode, 0); + wasVisited[myNode] = true; + float minDistSqr = minDist * minDist; + float maxDistSqr = maxDist * maxDist; + + while (list.Count > 0) { + int nodeIndex = list.Dequeue(); + + AI_Node node = Network.GetNode(nodeIndex)!; + Vector3 nodeOrigin = node.GetPosition(GetHullType()); + + float dist = (nearPos - nodeOrigin).LengthSquared(); + if (dist >= minDistSqr && dist < maxDistSqr) { + Activity coverActivity = outer.GetCoverActivity(node.GetHint()); + Vector3 eyePos = nodeOrigin + outer.EyeOffset(coverActivity); + + if (outer.IsValidCover(nodeOrigin, node.GetHint())) { + if (outer.IsCoverPosition(threatEyePos, eyePos)) { + node.Lock(1.0); + + AI_Hint? hint = node.GetHint(); + if (hint != null && (hint.HintType() == Hint.TacticalCoverMed || hint.HintType() == Hint.TacticalCoverLow)) { + if (outer.GetHintNode() != null) { + outer.GetHintNode()!.Unlock(outer.GetHintDelay(outer.GetHintNode()!.HintType())); + outer.SetHintNode(null); + } + + outer.SetHintNode(hint); + } + + SearchRandomizer = nodeIndex; + return nodeIndex; + } + } + } + + int numLinks = node.NumLinks(); + for (int link = 0; link < numLinks; link++) { + int index = (link + SearchRandomizer) % numLinks; + ref AI_Link nodeLink = ref node.GetLinkByIndex(index); + + if (!Pathfinder.IsLinkUsable(ref nodeLink, myNode)) + continue; + + int newID = nodeLink.DestNodeID(nodeIndex); + + if (!wasVisited[newID]) { + AI_Node newNode = Network.GetNode(newID)!; + if (newNode.NodeType != NodeType.Climb && !newNode.IsLocked()) { + nodeOrigin = newNode.GetPosition(GetHullType()); + dist = (nearPos - nodeOrigin).LengthSquared(); + + // Use the distance to the threat as a heuristic so the NPC does not run towards it + float threatDist = (threatPos - nodeOrigin).LengthSquared(); + + if (dist < threatDist * 1.5f) + list.Enqueue(newID, dist); + } + wasVisited[newID] = true; + } + } + } + + outer.ClearHintNode(); + return NO_NODE; + } + + public Vector3 GetNodePos(int node) => Network!.GetNode(node)!.GetPosition(GetHullType()); + + Vector3 GetLocalOrigin() => GetOuter()!.GetLocalOrigin(); + AI_HullType GetHullType() => GetOuter()!.GetHullType(); public AI_Network? Network; public AI_Pathfinder? Pathfinder; diff --git a/Game.Server/BaseCombatWeapon.cs b/Game.Server/BaseCombatWeapon.cs index 2f2a2502..82b37999 100644 --- a/Game.Server/BaseCombatWeapon.cs +++ b/Game.Server/BaseCombatWeapon.cs @@ -197,6 +197,59 @@ public override void HandleAnimEvent(ref AnimEvent animEvent) { public virtual void Operator_ForceNPCFire(BaseCombatCharacter op, bool secondary) { } + public virtual bool WeaponLOSCondition(in Vector3 ownerPos, in Vector3 targetPos, bool setConditions) { + AI_BaseNPC npcOwner = GetOwner()!.MyNPCPointer()!; + + Vector3 relativeShootPosition = npcOwner.Weapon_ShootPosition() - npcOwner.GetAbsOrigin(); + Vector3 barrelPos = ownerPos + relativeShootPosition; + + WeaponLOSFilter traceFilter = new(GetOwner(), npcOwner.GetEnemy(), Source.CollisionGroup.BreakableGlass); + Util.TraceLine(barrelPos, targetPos, Mask.Shot, ref traceFilter, out Trace tr); + + if (tr.Fraction == 1.0f) { + if (ai_debug_shoot_positions.GetBool()) + DebugOverlay.Line(barrelPos, targetPos, 0, 255, 0, false, 1.0f); + + return true; + } + + BaseEntity? hitEnt = tr.Ent; + + BasePlayer? enemyPlayer = ToBasePlayer(npcOwner.GetEnemy()); + if (enemyPlayer != null && enemyPlayer.IsInAVehicle()) { + BaseEntity? vehicleEnt = enemyPlayer.GetVehicle()!.GetVehicleEnt(); + if (hitEnt == vehicleEnt || hitEnt?.GetOwnerEntity() == vehicleEnt) + return true; + } + + if (hitEnt == npcOwner.GetEnemy()) { + if (ai_debug_shoot_positions.GetBool()) + DebugOverlay.Line(barrelPos, targetPos, 0, 255, 0, false, 1.0f); + + return true; + } + + IServerVehicle? vehicle = hitEnt?.GetServerVehicle(); + BaseCombatCharacter? bcc = vehicle != null ? vehicle.GetPassenger() : ToBaseCombatCharacter(hitEnt); + + if (bcc != null) { + if (npcOwner.IRelationType(bcc) == Disposition.HT) + return true; + + if (setConditions) + npcOwner.SetCondition((int)SCOND_t.COND_WEAPON_BLOCKED_BY_FRIEND); + } + else if (setConditions) { + npcOwner.SetCondition((int)SCOND_t.COND_WEAPON_SIGHT_OCCLUDED); + npcOwner.SetEnemyOccluder(hitEnt); + + if (ai_debug_shoot_positions.GetBool()) + DebugOverlay.Line(tr.StartPos, tr.EndPos, 255, 0, 0, false, 1.0f); + } + + return false; + } + public virtual SCOND_t WeaponRangeAttack1Condition(float dot, float dist) { if (UsesPrimaryAmmo() && !HasPrimaryAmmo()) return SCOND_t.COND_NO_PRIMARY_AMMO; @@ -314,3 +367,28 @@ public void CheckRespawn() { public override bool IsBaseCombatWeapon() => true; } + +public struct WeaponLOSFilter : ITraceFilter +{ + TraceFilterSkipTwoEntities SkipTwo; + readonly BaseEntity? Vehicle; + + public WeaponLOSFilter(IHandleEntity? handleEntity, IHandleEntity? handleEntity2, CollisionGroup collisionGroup) { + SkipTwo = new(handleEntity, handleEntity2, collisionGroup); + Vehicle = (handleEntity as BaseEntity)?.MyCombatCharacterPointer()?.GetVehicleEntity(); + } + + public bool ShouldHitEntity(IHandleEntity handleEntity, Contents contentsMask) { + BaseEntity? entity = EntityFromEntityHandle(handleEntity); + + if (entity != null && entity.GetCollisionGroup() == CollisionGroup.Weapon) + return false; + + if (Vehicle != null && entity == Vehicle) + return false; + + // todo: let the trace pass through breakable glass once func_breakable materials are ported + + return SkipTwo.ShouldHitEntity(handleEntity, contentsMask); + } +} diff --git a/Game.Server/NPC_MetroPolice.cs b/Game.Server/NPC_MetroPolice.cs index 06153f7f..792c6381 100644 --- a/Game.Server/NPC_MetroPolice.cs +++ b/Game.Server/NPC_MetroPolice.cs @@ -39,6 +39,7 @@ public class NPC_MetroPolice : AI_BaseActor const float METROPOLICE_SQUAD_STITCH_MAX_INTERVAL = 1.2f; const float RECENT_DAMAGE_INTERVAL = 3.0f; + const float RECENT_DAMAGE_THRESHOLD = 0.2f; const int METROPOLICE_MAX_WARNINGS = 3; @@ -224,6 +225,9 @@ public class NPC_MetroPolice : AI_BaseActor int RecentDamage; TimeUnit_t RecentDamageTime; + SquadSlot LastShootSlot = SquadSlot.None; + readonly RandSimTimer TimeYieldShootSlot = new(); + public NPC_MetroPolice() => LoadSchedules(); public override AI_ClassScheduleIdSpace GetClassScheduleIdSpace() => gm_ClassScheduleIdSpace; @@ -900,6 +904,8 @@ public override void Spawn() { weapon.AddEffects(EntityEffects.NoDraw); } + TimeYieldShootSlot.Set(2, 6); + GetEnemies().SetFreeKnowledgeDuration(6.0f); ShouldActivateBaton = false; @@ -1389,7 +1395,191 @@ public override bool OnObstructionPreSteer(ref AILocalMoveGoal moveGoal, float d return base.OnObstructionPreSteer(ref moveGoal, distClear, ref result); } - int SelectCombatSchedule() => throw new NotImplementedException(); + void AnnounceEnemyType(BaseEntity? enemy) { + if (enemy == null || Squad == null) + return; + + if (!PlayerIsCriminal()) + return; + + if (HasSpawnFlags(SF.ArrestEnemy)) + return; + + if (Squad.IsLeader(this) || (Squad.GetLeader() != null && Squad.GetLeader()!.GetEnemy() != GetEnemy())) { + string sentenceName = "METROPOLICE_MONST"; + switch (enemy.Classify()) { + case Class_T.Player: + sentenceName = enemy is BasePlayer player && player.IsInAVehicle() ? "METROPOLICE_MONST_PLAYER_VEHICLE" : "METROPOLICE_MONST_PLAYER"; + break; + + case Class_T.PlayerAlly: + case Class_T.CitizenRebel: + case Class_T.CitizenPassive: + case Class_T.Vortigaunt: + sentenceName = "METROPOLICE_MONST_CITIZENS"; + break; + + case Class_T.PlayerAllyVital: + sentenceName = "METROPOLICE_MONST_CHARACTER"; + break; + + case Class_T.Antlion: + sentenceName = "METROPOLICE_MONST_BUGS"; + break; + + case Class_T.Zombie: + sentenceName = "METROPOLICE_MONST_ZOMBIES"; + break; + + case Class_T.Headcrab: + case Class_T.Barnacle: + sentenceName = "METROPOLICE_MONST_PARASITES"; + break; + } + + Sentences.Speak(sentenceName, SentencePriority.High); + } + else { + if (Squad.GetLeader() != null && FOkToMakeSound(SentencePriority.Medium)) + JustMadeSound(SentencePriority.Medium); + } + } + + int SelectRangeAttackSchedule() { + if (HasSpawnFlags(SF.AlwaysStitch)) { + int sched = SelectMoveToLedgeSchedule(); + if (sched != SCHED_NONE) + return sched; + } + + if (TryToEnterPistolSlot(SquadSlot.Attack1) || TryToEnterPistolSlot(SquadSlot.Attack2)) + return SCHED_RANGE_ATTACK1; + + LastShootSlot = SquadSlot.None; + + if (CanDeployManhack() && OccupyStrategySlot(SQUAD_SLOT_POLICE_DEPLOY_MANHACK)) + return SCHED_METROPOLICE_DEPLOY_MANHACK; + + return SCHED_METROPOLICE_ADVANCE; + } + + int SelectScheduleArrestEnemy() { + if (!HasSpawnFlags(SF.ArrestEnemy) || !IsInSquad()) + return SCHED_NONE; + + if (!HasCondition((int)SCOND_t.COND_SEE_ENEMY)) + return SCHED_NONE; + + if (!WeaponDrawn) + return SCHED_METROPOLICE_DRAW_PISTOL; + + if (OccupyStrategySlot(SQUAD_SLOT_POLICE_ARREST_ENEMY)) + return SCHED_METROPOLICE_WARN_AND_ARREST_ENEMY; + + return SCHED_METROPOLICE_ARREST_ENEMY; + } + + int SelectScheduleNewEnemy() { + int sched = SelectScheduleArrestEnemy(); + if (sched != SCHED_NONE) + return sched; + + if (HasCondition((int)SCOND_t.COND_NEW_ENEMY)) { + NextLedgeCheckTime = gpGlobals.CurTime; + + if (CanDeployManhack() && OccupyStrategySlot(SQUAD_SLOT_POLICE_DEPLOY_MANHACK)) + return SCHED_METROPOLICE_DEPLOY_MANHACK; + } + + if (!WeaponDrawn) + return SCHED_METROPOLICE_DRAW_PISTOL; + + if (HasBaton() && BatonActive() == false && IsCurSchedule(SCHED_METROPOLICE_ACTIVATE_BATON) == false) { + SetTarget(GetEnemy()); + SetBatonState(true); + BatonDebounceTime = gpGlobals.CurTime + random.RandomFloat(2.5f, 4.0f); + return SCHED_METROPOLICE_ACTIVATE_BATON; + } + + return SCHED_NONE; + } + + int SelectScheduleNoDirectEnemy() { + if (CanDeployManhack() && OccupyStrategySlot(SQUAD_SLOT_POLICE_DEPLOY_MANHACK)) + return SCHED_METROPOLICE_DEPLOY_MANHACK; + + if (BlockingProp.Get() != null && HasBaton()) { + SetTarget(BlockingProp.Get()); + BlockingProp.Set(null); + return SCHED_METROPOLICE_SMASH_PROP; + } + + return SCHED_METROPOLICE_CHASE_ENEMY; + } + + new int SelectCombatSchedule() { + if (HasCondition((int)SCOND_t.COND_NEW_ENEMY)) + AnnounceEnemyType(GetEnemy()); + + int result = SelectScheduleNewEnemy(); + if (result != SCHED_NONE) + return result; + + if (!WeaponDrawn) + return SCHED_METROPOLICE_DRAW_PISTOL; + + if (!HasBaton() && ((float)RecentDamage / (float)GetMaxHealth()) > RECENT_DAMAGE_THRESHOLD) { + RecentDamage = 0; + RecentDamageTime = 0; + Sentences.Speak("METROPOLICE_COVER_HEAVY_DAMAGE", SentencePriority.Medium, SentenceCriteria.Normal); + + return SCHED_TAKE_COVER_FROM_ENEMY; + } + + if (HasCondition((int)SCOND_t.COND_CAN_RANGE_ATTACK1)) { + if (!GetShotRegulator().IsInRestInterval()) + return SelectRangeAttackSchedule(); + else + return SCHED_METROPOLICE_ADVANCE; + } + + if (HasCondition((int)SCOND_t.COND_CAN_MELEE_ATTACK1)) { + if (BatonSwingTimer.Expired()) { + ChasePlayerTime = 0; + BatonSwingTimer.Set(1.0f, 1.75f); + return SCHED_MELEE_ATTACK1; + } + else + return SCHED_COMBAT_FACE; + } + + if (HasCondition((int)SCOND_t.COND_TOO_CLOSE_TO_ATTACK)) + return SCHED_BACK_AWAY_FROM_ENEMY; + + if (HasCondition((int)SCOND_t.COND_LOW_PRIMARY_AMMO) || HasCondition((int)SCOND_t.COND_NO_PRIMARY_AMMO)) { + AnnounceOutOfAmmo(); + return SCHED_HIDE_AND_RELOAD; + } + + if (HasCondition((int)SCOND_t.COND_WEAPON_SIGHT_OCCLUDED) && !HasBaton()) { + BaseEntity? blocker = GetEnemyOccluder(); + if (blocker != null && blocker.GetHealth() > 0 && OccupyStrategySlotRange(SQUAD_SLOT_POLICE_ATTACK_OCCLUDER1, SQUAD_SLOT_POLICE_ATTACK_OCCLUDER2)) { + Sentences.Speak("METROPOLICE_SHOOT_COVER"); + return SCHED_SHOOT_ENEMY_COVER; + } + } + + if (HasCondition((int)SCOND_t.COND_ENEMY_OCCLUDED)) { + if (GetEnemy() != null && (GetEnemy()!.GetFlags() & EntityFlags.NoTarget) == 0) + return SCHED_ESTABLISH_LINE_OF_FIRE; + } + + result = SelectScheduleNoDirectEnemy(); + if (result != SCHED_NONE) + return result; + + return SCHED_NONE; + } int SelectAirboatCombatSchedule() => throw new NotImplementedException(); @@ -1399,7 +1589,17 @@ public override bool OnObstructionPreSteer(ref AILocalMoveGoal moveGoal, float d bool ShouldAttemptToStitch() => throw new NotImplementedException(); - bool TryToEnterPistolSlot(SquadSlot squadSlot) => throw new NotImplementedException(); + bool TryToEnterPistolSlot(SquadSlot squadSlot) { + if ((LastShootSlot != squadSlot || !TimeYieldShootSlot.Expired()) && OccupyStrategySlot(squadSlot)) { + if (LastShootSlot != squadSlot) { + TimeYieldShootSlot.Reset(); + LastShootSlot = squadSlot; + } + return true; + } + + return false; + } bool IsEnemyInAnAirboat() { if (GetEnemy() == null || !GetEnemy()!.IsPlayer()) diff --git a/Game.Server/SimTimer.cs b/Game.Server/SimTimer.cs index c178ba42..ce0a5894 100644 --- a/Game.Server/SimTimer.cs +++ b/Game.Server/SimTimer.cs @@ -67,6 +67,41 @@ public void Reset(float interval = -1.0f) { ]); } +public class RandSimTimer : SimpleSimTimer +{ + public RandSimTimer(float minInterval = 0.0f, float maxInterval = 0.0f, bool startExpired = true) { + Set(minInterval, maxInterval, startExpired); + } + + public void Set(float minInterval, float maxInterval = 0.0f, bool startExpired = true) { + MinInterval = minInterval; + MaxInterval = maxInterval; + + if (startExpired) + Next = -1; + else + Reset(); + } + + public void Reset() { + if (MaxInterval == 0) + Next = gpGlobals.CurTime + MinInterval; + else + Next = gpGlobals.CurTime + RandomFloat(MinInterval, MaxInterval); + } + + public float GetMinInterval() => MinInterval; + public float GetMaxInterval() => MaxInterval; + + float MinInterval; + float MaxInterval; + + public static readonly new DataMap DataDesc = new(typeof(RandSimTimer), SimpleSimTimer.DataDesc, [ + DEFINE.FIELD(nameof(MinInterval), FieldType.Float), + DEFINE.FIELD(nameof(MaxInterval), FieldType.Float), + ]); +} + public class StopwatchBase : SimpleSimTimer { public StopwatchBase() { diff --git a/Game.Shared/BaseEntityShared.cs b/Game.Shared/BaseEntityShared.cs index d1d0f082..581ea3b9 100644 --- a/Game.Shared/BaseEntityShared.cs +++ b/Game.Shared/BaseEntityShared.cs @@ -67,6 +67,7 @@ public static class BaseEntityConstants #endif public static readonly ConVar ai_shot_bias_min = new("ai_shot_bias_min", "-1.0", FCvar.Replicated); public static readonly ConVar ai_shot_bias_max = new("ai_shot_bias_max", "1.0", FCvar.Replicated); + public static readonly ConVar ai_debug_shoot_positions = new("ai_debug_shoot_positions", "0", FCvar.Replicated | FCvar.Cheat); public const int NUM_PARENTATTACHMENT_BITS = 8; // < gmod increased 6 . 8 public const int VPHYSICS_MAX_OBJECT_LIST_COUNT = 1024;