From 4a1658db93fe09afa503a138d7943b9f176739ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 13:58:41 +0300 Subject: [PATCH 01/73] Port AI node graph nodes, links and network --- Game.Server/AI_Hull.cs | 3 ++ Game.Server/AI_Link.cs | 24 +++++++++ Game.Server/AI_Network.cs | 84 ++++++++++++++++++++++++++++- Game.Server/AI_Node.cs | 109 ++++++++++++++++++++++++++++++++++++-- 4 files changed, 216 insertions(+), 4 deletions(-) create mode 100644 Game.Server/AI_Link.cs diff --git a/Game.Server/AI_Hull.cs b/Game.Server/AI_Hull.cs index 30f0970ab..38c44026c 100644 --- a/Game.Server/AI_Hull.cs +++ b/Game.Server/AI_Hull.cs @@ -1,7 +1,10 @@ using System.Numerics; +using System.Runtime.CompilerServices; namespace Game.Server; +[InlineArray((int)AI_HullType.NumHulls)] public struct InlineArrayNumHulls { public T item; } + // analog of Hull_t public enum AI_HullType { diff --git a/Game.Server/AI_Link.cs b/Game.Server/AI_Link.cs new file mode 100644 index 000000000..78b99901f --- /dev/null +++ b/Game.Server/AI_Link.cs @@ -0,0 +1,24 @@ +namespace Game.Server; + +[Flags] +public enum LinkInfo : byte +{ + StaleSuggested = 0x01, + Off = 0x02, +} + +public struct AI_Link +{ + public AI_Link() { } + + public short SrcID = -1; + public short DestID = -1; + + public readonly int DestNodeID(int srcID) => srcID == SrcID ? DestID : SrcID; + + public InlineArrayNumHulls AcceptedMoveTypes; + + public LinkInfo LinkInfo; + + public TimeUnit_t TimeStaleExpires; +} diff --git a/Game.Server/AI_Network.cs b/Game.Server/AI_Network.cs index 39418f434..55d52d3dd 100644 --- a/Game.Server/AI_Network.cs +++ b/Game.Server/AI_Network.cs @@ -1,5 +1,8 @@ global using static Game.Server.AI_NetworkGlobals; +using System.Numerics; +using System.Runtime.InteropServices; + namespace Game.Server; public static class AI_NetworkGlobals @@ -9,5 +12,84 @@ public static class AI_NetworkGlobals public class AI_Network { - public AI_Node? GetNode(int id, bool asserted = true) => throw new NotImplementedException(); + public const int AI_MAX_NODE_LINKS = 30; + public const int MAX_NODES = 1500; + + public AI_Node AddNode(Vector3 origin, float yaw) { + if (AINode == null || AINode[0] == null) + AINode = new AI_Node?[MAX_NODES]; + + if (NodeCount >= MAX_NODES) { + DevMsg("ERROR: too many nodes in map, deleting last node.\n"); + NodeCount--; + } + + AINode[NodeCount] = new AI_Node(this, NodeCount, origin, yaw); + + NodeCount++; + + return AINode[NodeCount - 1]!; + } + + public const short NO_LINK = -1; + + public short CreateLink(int srcID, int destID) { + AI_Node? srcNode = g_pBigAINet!.GetNode(srcID); + AI_Node? destNode = g_pBigAINet.GetNode(destID); + + Assert(srcNode != null && destNode != null && srcNode != destNode); + + if (srcNode == null || destNode == null) { + DevMsg("Attempted to create link to node that doesn't exist\n"); + return NO_LINK; + } + + if (srcNode == destNode) { + DevMsg("Attempted to link a node to itself\n"); + return NO_LINK; + } + + if (srcNode.NumLinks() == AI_MAX_NODE_LINKS) { + DevMsg($"Node {srcID} has too many links\n"); + return NO_LINK; + } + + if (destNode.NumLinks() == AI_MAX_NODE_LINKS) { + DevMsg($"Node {destID} has too many links\n"); + return NO_LINK; + } + + short link = (short)AILinks.Count; + AILinks.Add(new() { + SrcID = (short)srcID, + DestID = (short)destID + }); + + srcNode.AddLink(link); + destNode.AddLink(link); + + return link; + } + + public ref AI_Link GetLink(short link) => ref CollectionsMarshal.AsSpan(AILinks)[link]; + + public int NumNodes() => NodeCount; + + static int GetNodeWarningCount; + public AI_Node? GetNode(int id, bool asserted = true) { + if (id >= 0 && id < NodeCount) + return AINode![id]; + + if (asserted) { + if (++GetNodeWarningCount < 10) + AssertMsg(false, $"Node ({id}) out of range ({NodeCount} total)\n"); + } + return null; + } + + public AI_Node?[]? AccessNodes() => AINode; + + internal int NodeCount; + internal AI_Node?[]? AINode; + internal readonly List AILinks = []; } diff --git a/Game.Server/AI_Node.cs b/Game.Server/AI_Node.cs index 4c2120f34..59da3ef17 100644 --- a/Game.Server/AI_Node.cs +++ b/Game.Server/AI_Node.cs @@ -1,7 +1,110 @@ +using System.Numerics; +using System.Runtime.CompilerServices; + namespace Game.Server; -public class AI_Node +public enum AI_ZoneIds +{ + Unknown = 0, + Solo = 1, + Universal = 3, + FirstZone = 4, +} + +public enum NodeType +{ + Any, + Deleted, + Ground, + Air, + Climb, + Water, +} + +[Flags] +public enum NodeInfoBits : uint +{ + ClimbBottom = 1 << 0, + ClimbOn = 1 << 1, + ClimbOffForward = 1 << 2, + ClimbOffLeft = 1 << 3, + ClimbOffRight = 1 << 4, + + ClimbExit = ClimbOffForward | ClimbOffLeft | ClimbOffRight, + + DontDrop = 1 << 14, + + WCNeedRebuild = 0x10000000, + WCChanged = 0x20000000, + + WontFitHull = 0x40000000, + Fallen = 0x80000000, +} + +public class AI_Node(AI_Network network, int id, Vector3 origin, float yaw) { - public bool IsLocked() => throw new NotImplementedException(); - public void Unlock() => throw new NotImplementedException(); + public const int NODE_ENT_FLAGS_SHIFT = 5; + + public int NumLinks() => Links.Count; + public ref AI_Link GetLink(int destNodeId) { + for (int link = 0; link < NumLinks(); link++) { + ref AI_Link nodeLink = ref GetLinkByIndex(link); + if (nodeLink.DestNodeID(ID) == destNodeId) + return ref nodeLink; + } + + return ref Unsafe.NullRef(); + } + public ref AI_Link GetLinkByIndex(int i) => ref Network.GetLink(Links[i]); + + public bool IsLocked() => NextUseTime > gpGlobals.CurTime; + public void Lock(TimeUnit_t duration) => NextUseTime = gpGlobals.CurTime + duration; + public void Unlock() => NextUseTime = gpGlobals.CurTime; + + public int GetZone() => Zone; + public void SetZone(int zone) => Zone = zone; + + public int GetId() => ID; + + public ref readonly Vector3 GetOrigin() => ref Origin; + public float GetYaw() => Yaw; + + public void AddLink(short newLink) { + if (NumLinks() == AI_Network.AI_MAX_NODE_LINKS) { + DevMsg($"Node {ID} has too many links\n"); + return; + } + +#if DEBUG + for (int link = 0; link < NumLinks(); link++) { + if (Links[link] == newLink) { + AssertMsg(false, "Link added to node multiple times!"); + return; + } + } + + ref AI_Link added = ref Network.GetLink(newLink); + AssertMsg(added.DestID == ID || added.SrcID == ID, "Added link to node that doesn't reference the node"); +#endif + + Links.Add(newLink); + } + + readonly AI_Network Network = network; + + public int ID = id; + public Vector3 Origin = origin; + + public readonly float[] VOffset = new float[(int)AI_HullType.NumHulls]; + public float Yaw = yaw; + + public NodeType NodeType = NodeType.Ground; + + public NodeInfoBits NodeInfo; + + public int Zone = (int)AI_ZoneIds.Unknown; + public readonly List Links = new(4); + + public TimeUnit_t NextUseTime; + public int FirstShuffledLink; } From 5bd245ed53b1e739f7d823804ed9c947c8ee5649 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:05:27 +0300 Subject: [PATCH 02/73] Load the AI node graph from the map's .ain file --- Game.Server/AI_NetworkManager.cs | 138 +++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) diff --git a/Game.Server/AI_NetworkManager.cs b/Game.Server/AI_NetworkManager.cs index 1687bcbe1..ba1857d0e 100644 --- a/Game.Server/AI_NetworkManager.cs +++ b/Game.Server/AI_NetworkManager.cs @@ -2,6 +2,11 @@ using Game.Shared; +using Source.Common.Commands; +using Source.Common.Utilities; + +using System.Numerics; + namespace Game.Server; public static class AI_NetworkManagerGlobals @@ -9,17 +14,150 @@ public static class AI_NetworkManagerGlobals public static AI_NetworkManager? g_pAINetworkManager; } +public class AI_NetworkEditTools +{ + public int[]? NodeIndexTable; +} + [LinkEntityToClass("ai_network")] public class AI_NetworkManager : PointEntity { + const int AINET_VERSION_NUMBER = 37; + + static readonly ConVar g_ai_norebuildgraph = new("ai_norebuildgraph", "0"); + public static void InitializeAINetworks() { g_pAINetworkManager = (AI_NetworkManager)CreateEntityByName("ai_network")!; + g_pBigAINet = g_pAINetworkManager.GetNetwork(); + g_pAINetworkManager.LoadNetworkGraph(); + } + + public void LoadNetworkGraph() { + if (!g_pGameRules.FAllowNPCs()) { + DevMsg("Not loading AI due to games rules\n"); + return; + } + + string nrpFilename = $"maps/graphs/{gpGlobals.MapName}.ain"; + + long fileSize = filesystem.Size(nrpFilename, "GAME"); + byte[]? data = fileSize > 0 ? new byte[fileSize] : null; + if (data == null || !filesystem.ReadFile(nrpFilename, "GAME", data, 0)) { + DevWarning(2, $"Couldn't read {nrpFilename}!\n"); + return; + } + + UtlBuffer buf = new(data, UtlBuffer.BufferFlags.ReadOnly); + + if (buf.GetChar() == 'V' && buf.GetChar() == 'e' && buf.GetChar() == 'r') { + DevMsg($"AI node graph {nrpFilename} is out of date\n"); + return; + } + + buf.SeekGet(SeekOrigin.Begin, 0); + + int version = buf.GetInt(); + + if (version != AINET_VERSION_NUMBER) { + DevMsg($"AI node graph {nrpFilename} is out of date\n"); + return; + } + + int mapversion = buf.GetInt(); + + if (mapversion != gpGlobals.MapVersion && !g_ai_norebuildgraph.GetBool()) { + DevMsg($"AI node graph {nrpFilename} is out of date (map version changed)\n"); + return; + } + + int numNodes = buf.GetInt(); + + if (numNodes > AI_Network.MAX_NODES || numNodes < 0) { + Error($"AI node graph {nrpFilename} is corrupt\n"); + Assert(false); + return; + } + + int node; + for (node = 0; node < numNodes; node++) { + Vector3 origin; + float yaw; + origin.X = buf.GetFloat(); + origin.Y = buf.GetFloat(); + origin.Z = buf.GetFloat(); + yaw = buf.GetFloat(); + + AI_Node newNode = Network.AddNode(origin, yaw); + + for (int hull = 0; hull < newNode.VOffset.Length; hull++) + newNode.VOffset[hull] = buf.GetFloat(); + newNode.NodeType = (NodeType)buf.GetUnsignedChar(); + + newNode.NodeInfo = (NodeInfoBits)buf.GetUnsignedShort(); + newNode.Zone = buf.GetShort(); + } + + int totalNumLinks = buf.GetInt(); + + Span moveTypes = stackalloc byte[(int)AI_HullType.NumHulls]; + for (int link = 0; link < totalNumLinks; link++) { + int srcID, destID; + + srcID = buf.GetShort(); + destID = buf.GetShort(); + + short newLink = Network.CreateLink(srcID, destID); + + buf.Get(moveTypes); + if (newLink != AI_Network.NO_LINK) { + ref AI_Link loadedLink = ref Network.GetLink(newLink); + for (int hull = 0; hull < moveTypes.Length; hull++) + loadedLink.AcceptedMoveTypes[hull] = (Capability)moveTypes[hull]; + } + } + + GetEditOps().NodeIndexTable = new int[Math.Max(Network.NumNodes(), 1)]; + + for (node = 0; node < Network.NumNodes(); node++) + GetEditOps().NodeIndexTable![node] = buf.GetInt(); + + HashSet usedIds = []; + HashSet reportedIds = []; + + bool printedHeader = false; + + for (node = 0; node < Network.NumNodes(); node++) { + int editorId = GetEditOps().NodeIndexTable![node]; + if (editorId != NO_NODE) { + if (usedIds.Contains(editorId)) { + if (!printedHeader) { + Warning("** Duplicate Hammer Node IDs: "); + printedHeader = true; + } + + if (reportedIds.Add(editorId)) + DevMsg($"{editorId}, "); + } + else + usedIds.Add(editorId); + } + } + + if (printedHeader) + DevMsg("\n** Should run \"Check For Problems\" on the VMF then verify dynamic links\n"); + + gm_fNetworksLoaded = true; } public static bool NetworksLoaded() => gm_fNetworksLoaded; public bool IsInitialized() => Initalized; + public AI_NetworkEditTools GetEditOps() => EditOps; + public AI_Network GetNetwork() => Network; + static bool gm_fNetworksLoaded = true; + readonly AI_Network Network = new(); + readonly AI_NetworkEditTools EditOps = new(); bool Initalized = true; } From 06949cff9c603e0ca559e3d5f87ec7b7c7a20630 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 14:14:56 +0300 Subject: [PATCH 03/73] Refactor the loading, avoid copying the entire data, make it testable --- Game.Server/AI_NetworkManager.cs | 68 +++++++++++++++++--------------- 1 file changed, 36 insertions(+), 32 deletions(-) diff --git a/Game.Server/AI_NetworkManager.cs b/Game.Server/AI_NetworkManager.cs index ba1857d0e..ee5893ca6 100644 --- a/Game.Server/AI_NetworkManager.cs +++ b/Game.Server/AI_NetworkManager.cs @@ -3,9 +3,10 @@ using Game.Shared; using Source.Common.Commands; -using Source.Common.Utilities; +using Source.Common.Filesystem; using System.Numerics; +using System.Text; namespace Game.Server; @@ -40,37 +41,42 @@ public void LoadNetworkGraph() { string nrpFilename = $"maps/graphs/{gpGlobals.MapName}.ain"; - long fileSize = filesystem.Size(nrpFilename, "GAME"); - byte[]? data = fileSize > 0 ? new byte[fileSize] : null; - if (data == null || !filesystem.ReadFile(nrpFilename, "GAME", data, 0)) { + using IFileHandle? handle = filesystem.Open(nrpFilename, FileOpenOptions.Read | FileOpenOptions.Binary, "GAME"); + if (handle == null) { DevWarning(2, $"Couldn't read {nrpFilename}!\n"); return; } - UtlBuffer buf = new(data, UtlBuffer.BufferFlags.ReadOnly); + LoadNetworkGraph(handle.Stream, nrpFilename, gpGlobals.MapVersion); + } - if (buf.GetChar() == 'V' && buf.GetChar() == 'e' && buf.GetChar() == 'r') { - DevMsg($"AI node graph {nrpFilename} is out of date\n"); - return; - } + public void LoadNetworkGraph(Stream stream, ReadOnlySpan nrpFilename, int currentMapVersion) { + using BinaryReader reader = new(stream, Encoding.ASCII, true); - buf.SeekGet(SeekOrigin.Begin, 0); + try { + LoadNetworkGraph(reader, nrpFilename, currentMapVersion); + } + catch (EndOfStreamException) { + Warning($"AI node graph {nrpFilename} is truncated\n"); + } + } - int version = buf.GetInt(); + void LoadNetworkGraph(BinaryReader reader, ReadOnlySpan nrpFilename, int currentMapVersion) { + int version = reader.ReadInt32(); if (version != AINET_VERSION_NUMBER) { DevMsg($"AI node graph {nrpFilename} is out of date\n"); return; } - int mapversion = buf.GetInt(); + int mapversion = reader.ReadInt32(); - if (mapversion != gpGlobals.MapVersion && !g_ai_norebuildgraph.GetBool()) { + if (mapversion != currentMapVersion && !g_ai_norebuildgraph.GetBool()) { DevMsg($"AI node graph {nrpFilename} is out of date (map version changed)\n"); return; } - int numNodes = buf.GetInt(); + int numNodes = reader.ReadInt32(); if (numNodes > AI_Network.MAX_NODES || numNodes < 0) { Error($"AI node graph {nrpFilename} is corrupt\n"); @@ -82,44 +88,42 @@ public void LoadNetworkGraph() { for (node = 0; node < numNodes; node++) { Vector3 origin; float yaw; - origin.X = buf.GetFloat(); - origin.Y = buf.GetFloat(); - origin.Z = buf.GetFloat(); - yaw = buf.GetFloat(); + origin.X = reader.ReadSingle(); + origin.Y = reader.ReadSingle(); + origin.Z = reader.ReadSingle(); + yaw = reader.ReadSingle(); AI_Node newNode = Network.AddNode(origin, yaw); for (int hull = 0; hull < newNode.VOffset.Length; hull++) - newNode.VOffset[hull] = buf.GetFloat(); - newNode.NodeType = (NodeType)buf.GetUnsignedChar(); + newNode.VOffset[hull] = reader.ReadSingle(); + newNode.NodeType = (NodeType)reader.ReadByte(); - newNode.NodeInfo = (NodeInfoBits)buf.GetUnsignedShort(); - newNode.Zone = buf.GetShort(); + newNode.NodeInfo = (NodeInfoBits)reader.ReadUInt16(); + newNode.Zone = reader.ReadInt16(); } - int totalNumLinks = buf.GetInt(); + int totalNumLinks = reader.ReadInt32(); - Span moveTypes = stackalloc byte[(int)AI_HullType.NumHulls]; for (int link = 0; link < totalNumLinks; link++) { int srcID, destID; - srcID = buf.GetShort(); - destID = buf.GetShort(); + srcID = reader.ReadInt16(); + destID = reader.ReadInt16(); short newLink = Network.CreateLink(srcID, destID); - buf.Get(moveTypes); - if (newLink != AI_Network.NO_LINK) { - ref AI_Link loadedLink = ref Network.GetLink(newLink); - for (int hull = 0; hull < moveTypes.Length; hull++) - loadedLink.AcceptedMoveTypes[hull] = (Capability)moveTypes[hull]; + for (int hull = 0; hull < (int)AI_HullType.NumHulls; hull++) { + Capability moveTypes = (Capability)reader.ReadByte(); + if (newLink != AI_Network.NO_LINK) + Network.GetLink(newLink).AcceptedMoveTypes[hull] = moveTypes; } } GetEditOps().NodeIndexTable = new int[Math.Max(Network.NumNodes(), 1)]; for (node = 0; node < Network.NumNodes(); node++) - GetEditOps().NodeIndexTable![node] = buf.GetInt(); + GetEditOps().NodeIndexTable![node] = reader.ReadInt32(); HashSet usedIds = []; HashSet reportedIds = []; From 2f9474c1f3e3e7f2a0cb6373dba60601059da5ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:43:18 +0300 Subject: [PATCH 04/73] Replace schedule text parsing with typed schedule definitions --- Game.Server/AI_BaseNPC.cs | 177 +-- Game.Server/AI_Default.cs | 2638 +++++++++++++++++------------------- Game.Server/AI_Schedule.cs | 312 +---- Game.Server/AI_Task.cs | 21 + 4 files changed, 1290 insertions(+), 1858 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 83b0f1115..50a4d8d62 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -2468,182 +2468,7 @@ public static void InitSchedulingTables() { InitDefaultActivitySR(); } - public static bool LoadDefaultSchedules() { - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_IDLE_STAND, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_IDLE_WALK, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_IDLE_WANDER, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_WAKE_ANGRY, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_ALERT_FACE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_ALERT_FACE_BESTSOUND, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_ALERT_REACT_TO_COMBAT_SOUND, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_ALERT_SCAN, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_ALERT_STAND, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_ALERT_WALK, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_INVESTIGATE_SOUND, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_COMBAT_FACE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_COMBAT_SWEEP, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_COMBAT_WALK, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_FEAR_FACE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_COMBAT_STAND, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_CHASE_ENEMY, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_CHASE_ENEMY_FAILED, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_VICTORY_DANCE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_TARGET_FACE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_TARGET_CHASE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SMALL_FLINCH, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_BIG_FLINCH, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_BACK_AWAY_FROM_ENEMY, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_MOVE_AWAY_FROM_ENEMY, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_BACK_AWAY_FROM_SAVE_POSITION, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_TAKE_COVER_FROM_ENEMY, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_TAKE_COVER_FROM_BEST_SOUND, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_FLEE_FROM_BEST_SOUND, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_TAKE_COVER_FROM_ORIGIN, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_FAIL_TAKE_COVER, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_RUN_FROM_ENEMY, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_RUN_FROM_ENEMY_FALLBACK, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_MOVE_TO_WEAPON_RANGE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_ESTABLISH_LINE_OF_FIRE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SHOOT_ENEMY_COVER, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_PRE_FAIL_ESTABLISH_LINE_OF_FIRE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_FAIL_ESTABLISH_LINE_OF_FIRE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_COWER, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_MELEE_ATTACK1, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_MELEE_ATTACK2, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_RANGE_ATTACK1, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_RANGE_ATTACK2, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SPECIAL_ATTACK1, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SPECIAL_ATTACK2, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_STANDOFF, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_ARM_WEAPON, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_DISARM_WEAPON, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_HIDE_AND_RELOAD, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_RELOAD, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_AMBUSH, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_DIE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_DIE_RAGDOLL, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_WAIT_FOR_SCRIPT, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SCRIPTED_WALK, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SCRIPTED_RUN, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SCRIPTED_CUSTOM_MOVE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SCRIPTED_WAIT, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SCRIPTED_FACE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SCENE_GENERIC, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_NEW_WEAPON, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_NEW_WEAPON_CHEAT, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SWITCH_TO_PENDING_WEAPON, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_GET_HEALTHKIT, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_MOVE_AWAY, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_MOVE_AWAY_FAIL, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_MOVE_AWAY_END, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_WAIT_FOR_SPEAK_FINISH, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_FORCED_GO, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_FORCED_GO_RUN, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_PATROL_WALK, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_COMBAT_PATROL, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_PATROL_RUN, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_RUN_RANDOM, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_FAIL, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_FAIL_NOSTOP, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_FALL_TO_GROUND, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_DROPSHIP_DUSTOFF, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_FLINCH_PHYSICS, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_RUN_FROM_ENEMY_MOB, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_DUCK_DODGE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_NPC_FREEZE, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_INTERACTION_MOVE_TO_PARTNER, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_INTERACTION_WAIT_FOR_PARTNER, ClassScheduleIdSpace)) - return false; - if (!g_AI_SchedulesManager.LoadSchedulesFromBuffer("CAI_BaseNPC", g_pszSCHED_SLEEP, ClassScheduleIdSpace)) - return false; - - return true; - } + public static bool LoadDefaultSchedules() => g_AI_SchedulesManager.DefineSchedules("CAI_BaseNPC", ClassScheduleIdSpace, DefaultSchedules); public NPCState GetState() => NPCState; diff --git a/Game.Server/AI_Default.cs b/Game.Server/AI_Default.cs index 65654f287..614f1201f 100644 --- a/Game.Server/AI_Default.cs +++ b/Game.Server/AI_Default.cs @@ -2,6 +2,8 @@ using Game.Shared; +using static Game.Server.SCOND_t; + namespace Game.Server; public static class AI_DefaultGlobals @@ -96,1433 +98,1215 @@ public static class AI_DefaultGlobals public const int SCHED_SLEEP = 87; public const int LAST_SHARED_SCHEDULE = 88; - public const string g_pszSCHED_FAIL = - "\n Schedule" + - "\n SCHED_FAIL" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FAIL_NOSTOP" + - " TASK_STOP_MOVING 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_WAIT 1" + - " TASK_WAIT_PVS 0" + - "" + - " Interrupts" + - " COND_CAN_RANGE_ATTACK1 " + - " COND_CAN_RANGE_ATTACK2 " + - " COND_CAN_MELEE_ATTACK1 " + - " COND_CAN_MELEE_ATTACK2" + - " COND_GIVE_WAY" + - "\n"; - - public const string g_pszSCHED_FAIL_NOSTOP = - "\n Schedule" + - "\n SCHED_FAIL_NOSTOP" + - " Tasks" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_WAIT 1" + - " TASK_WAIT_PVS 0" + - "" + - " Interrupts" + - " COND_CAN_RANGE_ATTACK1 " + - " COND_CAN_RANGE_ATTACK2 " + - " COND_CAN_MELEE_ATTACK1 " + - " COND_CAN_MELEE_ATTACK2" + - " COND_GIVE_WAY" + - "\n"; - - public const string g_pszSCHED_IDLE_STAND = - "\n Schedule" + - "\n SCHED_IDLE_STAND" + - " Tasks" + - " TASK_STOP_MOVING 1" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_WAIT 5" + - " TASK_WAIT_PVS 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_SEE_FEAR" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_SMELL" + - " COND_PROVOKED" + - " COND_GIVE_WAY" + - " COND_HEAR_PLAYER" + - " COND_HEAR_DANGER" + - " COND_HEAR_COMBAT" + - " COND_HEAR_BULLET_IMPACT" + - " COND_IDLE_INTERRUPT" + - "\n"; - - public const string g_pszSCHED_WAIT_FOR_SCRIPT = - "\n Schedule" + - "\n SCHED_WAIT_FOR_SCRIPT" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_WAIT_INDEFINITE 0" + - "" + - " Interrupts" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - "\n"; - - public const string g_pszSCHED_IDLE_WALK = - "\n Schedule" + - "\n SCHED_IDLE_WALK" + - " Tasks" + - " TASK_WALK_PATH 9999" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_WAIT_PVS 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_SEE_ENEMY" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_SMELL" + - " COND_PROVOKED" + - " COND_HEAR_COMBAT" + - " COND_HEAR_BULLET_IMPACT" + - "\n"; - - public const string g_pszSCHED_NEW_WEAPON = - "\n Schedule" + - "\n SCHED_NEW_WEAPON" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_TOLERANCE_DISTANCE 5" + - " TASK_GET_PATH_TO_TARGET_WEAPON 0" + - " TASK_WEAPON_RUN_PATH 0" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_TARGET 0" + - " TASK_WEAPON_PICKUP 0" + - " TASK_WAIT 1" + - "" + - " Interrupts" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_NEW_WEAPON_CHEAT = - "\n Schedule" + - "\n SCHED_NEW_WEAPON_CHEAT" + - " Tasks" + - " TASK_WEAPON_CREATE 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_SWITCH_TO_PENDING_WEAPON = - "\n Schedule" + - "\n SCHED_SWITCH_TO_PENDING_WEAPON" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_PLAY_SEQUENCE ACTIVITY:ACT_DROP_WEAPON" + - " TASK_CREATE_PENDING_WEAPON 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_GET_HEALTHKIT = - "\n Schedule" + - "\n SCHED_GET_HEALTHKIT" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_TOLERANCE_DISTANCE 5" + - " TASK_GET_PATH_TO_TARGET_WEAPON 0" + - " TASK_ITEM_RUN_PATH 0" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_TARGET 0" + - " TASK_ITEM_PICKUP 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_RANGE_ATTACK1 = - "\n Schedule" + - "\n SCHED_RANGE_ATTACK1" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_ENEMY 0" + - " TASK_ANNOUNCE_ATTACK 1" + - " TASK_RANGE_ATTACK1 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_ENEMY_OCCLUDED" + - " COND_NO_PRIMARY_AMMO" + - " COND_HEAR_DANGER" + - " COND_WEAPON_BLOCKED_BY_FRIEND" + - " COND_WEAPON_SIGHT_OCCLUDED" + - "\n"; - - public const string g_pszSCHED_RANGE_ATTACK2 = - "\n Schedule" + - "\n SCHED_RANGE_ATTACK2" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_ENEMY 0" + - " TASK_ANNOUNCE_ATTACK 2" + - " TASK_RANGE_ATTACK2 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_ENEMY_OCCLUDED" + - " COND_NO_SECONDARY_AMMO" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_AMBUSH = - "\n Schedule" + - "\n SCHED_AMBUSH" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_WAIT_INDEFINITE 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_PROVOKED" + - "\n"; - - public const string g_pszSCHED_WAKE_ANGRY = - "\n Schedule" + - "\n SCHED_WAKE_ANGRY" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE " + - " TASK_SOUND_WAKE 0" + - " TASK_FACE_IDEAL 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE " + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_ALERT_FACE = - "\n Schedule" + - "\n SCHED_ALERT_FACE" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_IDEAL 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_SEE_FEAR" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_PROVOKED" + - "\n"; - - public const string g_pszSCHED_ALERT_FACE_BESTSOUND = - "\n Schedule" + - "\n SCHED_ALERT_FACE_BESTSOUND" + - " Tasks" + - " TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION 0" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_SAVEPOSITION 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_WAIT 1.5" + - " TASK_FACE_REASONABLE 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_SEE_FEAR" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_PROVOKED" + - "\n"; - - public const string g_pszSCHED_ALERT_REACT_TO_COMBAT_SOUND = - "\n Schedule" + - "\n SCHED_ALERT_REACT_TO_COMBAT_SOUND" + - " Tasks" + - " TASK_SET_SCHEDULE SCHEDULE:SCHED_ALERT_FACE_BESTSOUND" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_ALERT_SCAN = - "\n Schedule" + - "\n SCHED_ALERT_SCAN" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_WAIT 0.5" + - " TASK_TURN_LEFT 180" + - " TASK_WAIT 0.5" + - " TASK_TURN_LEFT 180" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - "\n"; - - public const string g_pszSCHED_ALERT_STAND = - "\n Schedule" + - "\n SCHED_ALERT_STAND" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_REASONABLE 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_WAIT 20" + - " TASK_SUGGEST_STATE STATE:IDLE" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_SEE_ENEMY" + - " COND_SEE_FEAR" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_PROVOKED" + - " COND_SMELL" + - " COND_HEAR_COMBAT" + - " COND_HEAR_WORLD" + - " COND_HEAR_PLAYER" + - " COND_HEAR_DANGER" + - " COND_HEAR_BULLET_IMPACT" + - " COND_IDLE_INTERRUPT" + - " COND_GIVE_WAY" + - "\n"; - - public const string g_pszSCHED_ALERT_WALK = - "\n Schedule" + - "\n SCHED_ALERT_WALK" + - " Tasks" + - " TASK_WALK_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_WAIT_PVS 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_SEE_ENEMY" + - " COND_SEE_FEAR" + - " COND_ENEMY_DEAD" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_HEAR_DANGER" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_MELEE_ATTACK2" + - "\n"; - - public const string g_pszSCHED_INVESTIGATE_SOUND = - "\n Schedule" + - "\n SCHED_INVESTIGATE_SOUND" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_STORE_LASTPOSITION 0" + - " TASK_GET_PATH_TO_BESTSOUND 0" + - " TASK_FACE_IDEAL 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_STOP_MOVING 0" + - " TASK_WAIT 5" + - " TASK_GET_PATH_TO_LASTPOSITION 0" + - " TASK_WALK_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_STOP_MOVING 0" + - " TASK_CLEAR_LASTPOSITION 0" + - " TASK_FACE_REASONABLE 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_SEE_FEAR" + - " COND_SEE_ENEMY" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_COMBAT_STAND = - "\n Schedule" + - "\n SCHED_COMBAT_STAND" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_WAIT_INDEFINITE 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_SEE_ENEMY" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_MELEE_ATTACK2" + - " COND_IDLE_INTERRUPT" + - "\n"; - - public const string g_pszSCHED_COMBAT_WALK = - "\n Schedule" + - "\n SCHED_COMBAT_WALK" + - " Tasks" + - " TASK_WALK_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_WAIT_PVS 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_HEAR_DANGER" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_MELEE_ATTACK2" + - "\n"; - - public const string g_pszSCHED_COMBAT_FACE = - "\n Schedule" + - "\n SCHED_COMBAT_FACE" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_FACE_ENEMY 0" + - "" + - " Interrupts" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_MELEE_ATTACK2" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - "\n"; - - public const string g_pszSCHED_COMBAT_SWEEP = - "\n Schedule" + - "\n SCHED_COMBAT_SWEEP" + - " Tasks" + - " TASK_TURN_LEFT 45" + - " TASK_WAIT 2" + - " TASK_TURN_RIGHT 45" + - " TASK_WAIT 2" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_SEE_ENEMY" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_HEAR_DANGER" + - " COND_HEAR_WORLD" + - "\n"; - - public const string g_pszSCHED_STANDOFF = - "\n Schedule" + - "\n SCHED_STANDOFF" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_WAIT_FACE_ENEMY 2" + - "" + - " Interrupts" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_MELEE_ATTACK2" + - " COND_ENEMY_DEAD" + - " COND_NEW_ENEMY" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_ARM_WEAPON = - "\n Schedule" + - "\n SCHED_ARM_WEAPON" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_IDEAL 0" + - " TASK_PLAY_SEQUENCE ACTIVITY:ACT_ARM" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_DISARM_WEAPON = - "\n Schedule" + - "\n SCHED_DISARM_WEAPON" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_IDEAL 0" + - " TASK_PLAY_SEQUENCE ACTIVITY:ACT_DISARM" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_HIDE_AND_RELOAD = - "\n Schedule" + - "\n SCHED_HIDE_AND_RELOAD" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_RELOAD" + - " TASK_FIND_COVER_FROM_ENEMY 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_REMEMBER MEMORY:INCOVER" + - " TASK_FACE_ENEMY 0" + - " TASK_SET_SCHEDULE SCHEDULE:SCHED_RELOAD" + - "" + - " Interrupts" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_RELOAD = - "\n Schedule" + - "\n SCHED_RELOAD" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_RELOAD 0" + - "" + - " Interrupts" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_MELEE_ATTACK1 = - "\n Schedule" + - "\n SCHED_MELEE_ATTACK1" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_ENEMY 0" + - " TASK_ANNOUNCE_ATTACK 1" + - " TASK_MELEE_ATTACK1 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_ENEMY_OCCLUDED" + - "\n"; - - public const string g_pszSCHED_MELEE_ATTACK2 = - "\n Schedule" + - "\n SCHED_MELEE_ATTACK2" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_ENEMY 0" + - " TASK_ANNOUNCE_ATTACK 2" + - " TASK_MELEE_ATTACK2 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_ENEMY_OCCLUDED" + - "\n"; - - public const string g_pszSCHED_SPECIAL_ATTACK1 = - "\n Schedule" + - "\n SCHED_SPECIAL_ATTACK1" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_ENEMY 0" + - " TASK_SPECIAL_ATTACK1 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_ENEMY_OCCLUDED" + - " COND_NO_PRIMARY_AMMO" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_SPECIAL_ATTACK2 = - "\n Schedule" + - "\n SCHED_SPECIAL_ATTACK2" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_ENEMY 0" + - " TASK_SPECIAL_ATTACK2 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_ENEMY_OCCLUDED" + - " COND_NO_SECONDARY_AMMO" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_CHASE_ENEMY = - "\n Schedule" + - "\n SCHED_CHASE_ENEMY" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY_FAILED" + - " TASK_GET_CHASE_PATH_TO_ENEMY 300" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_FACE_ENEMY 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_ENEMY_UNREACHABLE" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK2" + - " COND_TOO_CLOSE_TO_ATTACK" + - " COND_TASK_FAILED" + - " COND_LOST_ENEMY" + - " COND_BETTER_WEAPON_AVAILABLE" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_TARGET_FACE = - "\n Schedule" + - "\n SCHED_TARGET_FACE" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_FACE_TARGET 0" + - "" + - " Interrupts" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_MELEE_ATTACK2" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - "\n"; - - public const string g_pszSCHED_TARGET_CHASE = - "\n Schedule" + - "\n SCHED_TARGET_CHASE" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_GET_PATH_TO_TARGET 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_ENEMY_UNREACHABLE" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK2" + - " COND_TOO_CLOSE_TO_ATTACK" + - " COND_TASK_FAILED" + - " COND_LOST_ENEMY" + - " COND_BETTER_WEAPON_AVAILABLE" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_CHASE_ENEMY_FAILED = - "\n Schedule" + - "\n SCHED_CHASE_ENEMY_FAILED" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_WAIT 0.2" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_STANDOFF" + - " TASK_FIND_COVER_FROM_ENEMY 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_REMEMBER MEMORY:INCOVER" + - " TASK_FACE_ENEMY 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_WAIT 1" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK2" + - " COND_HEAR_DANGER" + - " COND_BETTER_WEAPON_AVAILABLE" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - "\n"; - - public const string g_pszSCHED_BACK_AWAY_FROM_SAVE_POSITION = - "\n Schedule" + - "\n SCHED_BACK_AWAY_FROM_SAVE_POSITION" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FIND_BACKAWAY_FROM_SAVEPOSITION 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_BACK_AWAY_FROM_ENEMY = - "\n Schedule" + - "\n SCHED_BACK_AWAY_FROM_ENEMY" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION 0" + - " TASK_FIND_BACKAWAY_FROM_SAVEPOSITION 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_MELEE_ATTACK2" + - "\n"; - - public const string g_pszSCHED_SMALL_FLINCH = - "\n Schedule" + - "\n SCHED_SMALL_FLINCH" + - " Tasks" + - " TASK_REMEMBER MEMORY:FLINCHED " + - " TASK_STOP_MOVING 0" + - " TASK_SMALL_FLINCH 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_BIG_FLINCH = - "\n Schedule" + - "\n SCHED_BIG_FLINCH" + - " Tasks" + - " TASK_REMEMBER MEMORY:FLINCHED " + - " TASK_STOP_MOVING 0" + - " TASK_BIG_FLINCH 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_NPC_FREEZE = - "\n Schedule" + - "\n SCHED_NPC_FREEZE" + - " Tasks" + - " TASK_FREEZE 0" + - " Interrupts" + - " COND_NPC_UNFREEZE" + - "\n"; - - public const string g_pszSCHED_DIE = - "\n Schedule" + - "\n SCHED_DIE" + - " Tasks" + - " TASK_STOP_MOVING 0 " + - " TASK_SOUND_DIE 0 " + - " TASK_DIE 0 " + - "" + - " Interrupts" + - " COND_NO_CUSTOM_INTERRUPTS" + - "\n"; - - public const string g_pszSCHED_DIE_RAGDOLL = - "\n Schedule" + - "\n SCHED_DIE_RAGDOLL" + - " Tasks" + - " TASK_STOP_MOVING 0 " + - " TASK_SOUND_DIE 0 " + - "" + - " Interrupts" + - " COND_NO_CUSTOM_INTERRUPTS" + - "\n"; - - public const string g_pszSCHED_VICTORY_DANCE = - "\n Schedule" + - "\n SCHED_VICTORY_DANCE" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_PLAY_SEQUENCE ACTIVITY:ACT_VICTORY_DANCE" + - " TASK_WAIT 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_SCRIPTED_WALK = - "\n Schedule" + - "\n SCHED_SCRIPTED_WALK" + - " Tasks" + - " TASK_PRE_SCRIPT 0" + - " TASK_SET_TOLERANCE_DISTANCE 2" + - " TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY 0" + - " TASK_SCRIPT_WALK_TO_TARGET 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_PLANT_ON_SCRIPT 0" + - " TASK_FACE_SCRIPT 0" + - " TASK_ENABLE_SCRIPT 0" + - " TASK_WAIT_FOR_SCRIPT 0" + - " TASK_PLAY_SCRIPT 0" + - " TASK_PLAY_SCRIPT_POST_IDLE 0" + - "" + - " Interrupts" + - " COND_LIGHT_DAMAGE " + - " COND_HEAVY_DAMAGE" + - "\n"; - - public const string g_pszSCHED_SCRIPTED_RUN = - "\n Schedule" + - "\n SCHED_SCRIPTED_RUN" + - " Tasks" + - " TASK_PRE_SCRIPT 0" + - " TASK_SET_TOLERANCE_DISTANCE 2" + - " TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY 0" + - " TASK_SCRIPT_RUN_TO_TARGET 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_PLANT_ON_SCRIPT 0" + - " TASK_FACE_SCRIPT 0" + - " TASK_ENABLE_SCRIPT 0" + - " TASK_WAIT_FOR_SCRIPT 0" + - " TASK_PLAY_SCRIPT 0" + - " TASK_PLAY_SCRIPT_POST_IDLE 0" + - "" + - " Interrupts" + - " COND_LIGHT_DAMAGE " + - " COND_HEAVY_DAMAGE" + - "\n"; - - public const string g_pszSCHED_SCRIPTED_CUSTOM_MOVE = - "\n Schedule" + - "\n SCHED_SCRIPTED_CUSTOM_MOVE" + - " Tasks" + - " TASK_PRE_SCRIPT 0" + - " TASK_SET_TOLERANCE_DISTANCE 2" + - " TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY 0" + - " TASK_SCRIPT_CUSTOM_MOVE_TO_TARGET 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_PLANT_ON_SCRIPT 0" + - " TASK_FACE_SCRIPT 0" + - " TASK_ENABLE_SCRIPT 0" + - " TASK_WAIT_FOR_SCRIPT 0" + - " TASK_PLAY_SCRIPT 0" + - " TASK_PLAY_SCRIPT_POST_IDLE 0" + - "" + - " Interrupts" + - " COND_LIGHT_DAMAGE " + - " COND_HEAVY_DAMAGE" + - "\n"; - - public const string g_pszSCHED_SCRIPTED_WAIT = - "\n Schedule" + - "\n SCHED_SCRIPTED_WAIT" + - " Tasks" + - " TASK_PRE_SCRIPT 0" + - " TASK_STOP_MOVING 0" + - " TASK_ENABLE_SCRIPT 0" + - " TASK_WAIT_FOR_SCRIPT 0" + - " TASK_PLAY_SCRIPT 0" + - " TASK_PLAY_SCRIPT_POST_IDLE 0" + - "" + - " Interrupts" + - " COND_LIGHT_DAMAGE " + - " COND_HEAVY_DAMAGE" + - "\n"; - - public const string g_pszSCHED_SCRIPTED_FACE = - "\n Schedule" + - "\n SCHED_SCRIPTED_FACE" + - " Tasks" + - " TASK_PRE_SCRIPT 0" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_SCRIPT 0" + - " TASK_ENABLE_SCRIPT 0" + - " TASK_WAIT_FOR_SCRIPT 0" + - " TASK_PLAY_SCRIPT 0" + - " TASK_PLAY_SCRIPT_POST_IDLE 0" + - "" + - " Interrupts" + - " COND_LIGHT_DAMAGE " + - " COND_HEAVY_DAMAGE" + - "\n"; - - public const string g_pszSCHED_SCENE_GENERIC = - "\n Schedule" + - "\n SCHED_SCENE_GENERIC" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_SCENE_GENERIC" + - " TASK_STOP_MOVING 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_PLAY_SCENE 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_STOP_MOVING 0" + - " TASK_SET_SCHEDULE SCHEDULE:SCHED_SCENE_GENERIC" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_COWER = - "\n Schedule" + - "\n SCHED_COWER" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_PLAY_SEQUENCE ACTIVITY:ACT_COWER" + - " TASK_WAIT_UNTIL_NO_DANGER_SOUND 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_TAKE_COVER_FROM_ORIGIN = - "\n Schedule" + - "\n SCHED_TAKE_COVER_FROM_ORIGIN" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FAIL_TAKE_COVER" + - " TASK_STOP_MOVING 0" + - " TASK_FIND_COVER_FROM_ORIGIN 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_REMEMBER MEMORY:INCOVER" + - " TASK_TURN_LEFT 179" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - "\n"; - - public const string g_pszSCHED_TAKE_COVER_FROM_BEST_SOUND = - "\n Schedule" + - "\n SCHED_TAKE_COVER_FROM_BEST_SOUND" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FLEE_FROM_BEST_SOUND" + - " TASK_STOP_MOVING 0" + - " TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION 0" + - " TASK_FIND_COVER_FROM_BEST_SOUND 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_REMEMBER MEMORY:INCOVER" + - " TASK_FACE_SAVEPOSITION 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - "\n"; - - public const string g_pszSCHED_FLEE_FROM_BEST_SOUND = - "\n Schedule" + - "\n SCHED_FLEE_FROM_BEST_SOUND" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COWER" + - " TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION 0" + - " TASK_GET_PATH_AWAY_FROM_BEST_SOUND 600" + - " TASK_RUN_PATH_FLEE 100" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_SAVEPOSITION 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - "\n"; - - public const string g_pszSCHED_TAKE_COVER_FROM_ENEMY = - "\n Schedule" + - "\n SCHED_TAKE_COVER_FROM_ENEMY" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_FAIL_TAKE_COVER" + - " TASK_STOP_MOVING 0" + - " TASK_WAIT 0.2" + - " TASK_FIND_COVER_FROM_ENEMY 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_REMEMBER MEMORY:INCOVER" + - " TASK_FACE_ENEMY 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_WAIT 1" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_FAIL_TAKE_COVER = - "\n Schedule" + - "\n SCHED_FAIL_TAKE_COVER" + - " Tasks " + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - "\n"; - - public const string g_pszSCHED_RUN_FROM_ENEMY = - "\n Schedule" + - "\n SCHED_RUN_FROM_ENEMY" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_RUN_FROM_ENEMY_FALLBACK" + - " TASK_STOP_MOVING 0" + - " TASK_FIND_COVER_FROM_ENEMY 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - "\n"; - - public const string g_pszSCHED_RUN_FROM_ENEMY_FALLBACK = - "\n Schedule" + - "\n SCHED_RUN_FROM_ENEMY_FALLBACK" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_RUN_RANDOM" + - " TASK_STOP_MOVING 0" + - " TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION 0" + - " TASK_FIND_BACKAWAY_FROM_SAVEPOSITION 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - "\n"; - - public const string g_pszSCHED_RUN_FROM_ENEMY_MOB = - "\n Schedule" + - "\n SCHED_RUN_FROM_ENEMY_MOB" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_RUN_RANDOM" + - " TASK_STOP_MOVING 0" + - " TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION 0" + - " TASK_FIND_BACKAWAY_FROM_SAVEPOSITION 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_FEAR_FACE = - "\n Schedule" + - "\n SCHED_FEAR_FACE" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - " TASK_FACE_ENEMY 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_SEE_ENEMY" + - "\n"; - - public const string g_pszSCHED_FORCED_GO = - "\n Schedule" + - "\n SCHED_FORCED_GO" + - " Tasks" + - " TASK_SET_TOLERANCE_DISTANCE 48" + - " TASK_SET_ROUTE_SEARCH_TIME 3" + - " TASK_GET_PATH_TO_LASTPOSITION 0" + - " TASK_WALK_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_FORCED_GO_RUN = - "\n Schedule" + - "\n SCHED_FORCED_GO_RUN" + - " Tasks" + - " TASK_SET_TOLERANCE_DISTANCE 48" + - " TASK_SET_ROUTE_SEARCH_TIME 3" + - " TASK_GET_PATH_TO_LASTPOSITION 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_MOVE_TO_WEAPON_RANGE = - "\n Schedule" + - "\n SCHED_MOVE_TO_WEAPON_RANGE" + - " Tasks " + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_CHASE_ENEMY" + - " TASK_GET_PATH_TO_RANGE_ENEMY_LKP_LOS 0" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_SET_SCHEDULE SCHEDULE:SCHED_COMBAT_FACE" + - "" + - " Interrupts " + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LOST_ENEMY" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK2" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_ESTABLISH_LINE_OF_FIRE = - "\n Schedule" + - "\n SCHED_ESTABLISH_LINE_OF_FIRE" + - " Tasks " + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK" + - " TASK_GET_PATH_TO_ENEMY_LOS 0" + - " TASK_SPEAK_SENTENCE 1" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_SET_SCHEDULE SCHEDULE:SCHED_COMBAT_FACE" + - "" + - " Interrupts " + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LOST_ENEMY" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK2" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_SHOOT_ENEMY_COVER = - "\n Schedule" + - "\n SCHED_SHOOT_ENEMY_COVER" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_ENEMY 0" + - " TASK_WAIT 0.5" + - " TASK_RANGE_ATTACK1 0" + - "" + - " Interrupts" + - " COND_ENEMY_DEAD" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_NO_PRIMARY_AMMO" + - " COND_HEAR_DANGER" + - " COND_WEAPON_BLOCKED_BY_FRIEND" + - "\n"; - - public const string g_pszSCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK = - "\n Schedule" + - "\n SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_PRE_FAIL_ESTABLISH_LINE_OF_FIRE" + - " TASK_GET_CHASE_PATH_TO_ENEMY 300" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_FACE_ENEMY 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_ENEMY_UNREACHABLE" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK2" + - " COND_TOO_CLOSE_TO_ATTACK" + - " COND_TASK_FAILED" + - " COND_LOST_ENEMY" + - " COND_BETTER_WEAPON_AVAILABLE" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_PRE_FAIL_ESTABLISH_LINE_OF_FIRE = - "\n Schedule" + - "\n SCHED_PRE_FAIL_ESTABLISH_LINE_OF_FIRE" + - " Tasks" + - " TASK_FACE_ENEMY 0" + - " TASK_FACE_REASONABLE 0" + - " TASK_IGNORE_OLD_ENEMIES 0" + - " TASK_SET_SCHEDULE SCHEDULE:SCHED_FAIL_ESTABLISH_LINE_OF_FIRE" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK2" + - "\n"; - - public const string g_pszSCHED_FAIL_ESTABLISH_LINE_OF_FIRE = - "\n Schedule" + - "\n SCHED_FAIL_ESTABLISH_LINE_OF_FIRE" + - " Tasks " + - "" + - " TASK_SET_ACTIVITY ACTIVITY:ACT_IDLE" + - "" + - " Interrupts " + - " COND_NEW_ENEMY" + - " COND_ENEMY_DEAD" + - " COND_LOST_ENEMY" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK2" + - " COND_HEAR_DANGER" + - "\n"; - - public const string g_pszSCHED_PATROL_RUN = - "\n Schedule" + - "\n SCHED_PATROL_RUN" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_COMBAT_FACE" + - " TASK_SET_ROUTE_SEARCH_TIME 5" + - " TASK_GET_PATH_TO_RANDOM_NODE 200" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - " COND_CAN_RANGE_ATTACK1 " + - " COND_CAN_RANGE_ATTACK2 " + - " COND_CAN_MELEE_ATTACK1 " + - " COND_CAN_MELEE_ATTACK2" + - " COND_GIVE_WAY" + - " COND_NEW_ENEMY" + - " COND_SEE_ENEMY" + - " COND_SEE_FEAR" + - " COND_HEAR_COMBAT" + - " COND_HEAR_DANGER" + - " COND_HEAR_PLAYER" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_SMELL" + - " COND_PROVOKED" + - "\n"; - - public const string g_pszSCHED_IDLE_WANDER = - "\n Schedule" + - "\n SCHED_IDLE_WANDER" + - " Tasks" + - " TASK_SET_ROUTE_SEARCH_TIME 5" + - " TASK_GET_PATH_TO_RANDOM_NODE 200" + - " TASK_WALK_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_WAIT_PVS 0" + - "" + - " Interrupts" + - " COND_GIVE_WAY" + - " COND_HEAR_COMBAT" + - " COND_HEAR_DANGER" + - " COND_NEW_ENEMY" + - " COND_SEE_ENEMY" + - " COND_SEE_FEAR" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_IDLE_INTERRUPT" + - "\n"; - - public const string g_pszSCHED_PATROL_WALK = - "\n Schedule" + - "\n SCHED_PATROL_WALK" + - " Tasks" + - " TASK_SET_ROUTE_SEARCH_TIME 5" + - " TASK_GET_PATH_TO_RANDOM_NODE 200" + - " TASK_WALK_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - " COND_CAN_RANGE_ATTACK1 " + - " COND_CAN_RANGE_ATTACK2 " + - " COND_CAN_MELEE_ATTACK1 " + - " COND_CAN_MELEE_ATTACK2" + - " COND_GIVE_WAY" + - " COND_HEAR_COMBAT" + - " COND_HEAR_DANGER" + - " COND_HEAR_PLAYER" + - " COND_NEW_ENEMY" + - " COND_SEE_ENEMY" + - " COND_SEE_FEAR" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_SMELL" + - " COND_PROVOKED" + - "\n"; - - public const string g_pszSCHED_COMBAT_PATROL = - "\n Schedule" + - "\n SCHED_COMBAT_PATROL" + - " Tasks" + - " TASK_SET_ROUTE_SEARCH_TIME 5" + - " TASK_GET_PATH_TO_RANDOM_NODE 200" + - " TASK_WALK_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - " COND_CAN_RANGE_ATTACK1 " + - " COND_CAN_RANGE_ATTACK2 " + - " COND_CAN_MELEE_ATTACK1 " + - " COND_CAN_MELEE_ATTACK2" + - " COND_GIVE_WAY" + - " COND_HEAR_DANGER" + - " COND_NEW_ENEMY" + - "\n"; - - public const string g_pszSCHED_RUN_RANDOM = - "\n Schedule" + - "\n SCHED_RUN_RANDOM" + - " Tasks" + - " TASK_SET_ROUTE_SEARCH_TIME 1" + - " TASK_GET_PATH_TO_RANDOM_NODE 500" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_FALL_TO_GROUND = - "\n Schedule" + - "\n SCHED_FALL_TO_GROUND" + - " Tasks" + - " TASK_FALL_TO_GROUND 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_DROPSHIP_DUSTOFF = - "\n Schedule" + - "\n SCHED_DROPSHIP_DUSTOFF" + - " Tasks" + - " TASK_WALK_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_WAIT_PVS 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_FLINCH_PHYSICS = - "\n Schedule" + - "\n SCHED_FLINCH_PHYSICS" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_PLAY_SEQUENCE ACTIVITY:ACT_FLINCH_PHYSICS" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_MOVE_AWAY_FROM_ENEMY = - "\n Schedule" + - "\n SCHED_MOVE_AWAY_FROM_ENEMY" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_MOVE_AWAY_FAIL" + - " TASK_FACE_ENEMY 0" + - " TASK_MOVE_AWAY_PATH 120" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_SET_SCHEDULE SCHEDULE:SCHED_MOVE_AWAY_END" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_CAN_RANGE_ATTACK1" + - " COND_CAN_RANGE_ATTACK2" + - " COND_CAN_MELEE_ATTACK1" + - " COND_CAN_MELEE_ATTACK2" + - "\n"; - - public const string g_pszSCHED_MOVE_AWAY = - "\n Schedule" + - "\n SCHED_MOVE_AWAY" + - " Tasks" + - " TASK_SET_FAIL_SCHEDULE SCHEDULE:SCHED_MOVE_AWAY_FAIL" + - " TASK_MOVE_AWAY_PATH 120" + - " TASK_RUN_PATH 0" + - " TASK_WAIT_FOR_MOVEMENT 0" + - " TASK_SET_SCHEDULE SCHEDULE:SCHED_MOVE_AWAY_END" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_MOVE_AWAY_FAIL = - "\n Schedule" + - "\n SCHED_MOVE_AWAY_FAIL" + - " Tasks" + - " TASK_STOP_MOVING 0" + - "" + - " Interrupts" + - "\n"; - - public const string g_pszSCHED_MOVE_AWAY_END = - "\n Schedule" + - "\n SCHED_MOVE_AWAY_END" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_FACE_REASONABLE 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_SEE_ENEMY" + - " COND_SEE_FEAR" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_PROVOKED" + - " COND_SMELL" + - " COND_HEAR_COMBAT" + - " COND_HEAR_WORLD" + - " COND_HEAR_PLAYER" + - " COND_HEAR_DANGER" + - " COND_HEAR_BULLET_IMPACT" + - " COND_IDLE_INTERRUPT" + - "\n"; - - public const string g_pszSCHED_WAIT_FOR_SPEAK_FINISH = - "\n Schedule" + - "\n SCHED_WAIT_FOR_SPEAK_FINISH" + - " Tasks" + - " TASK_WAIT_FOR_SPEAK_FINISH 0" + - "" + - " Interrupts" + - " COND_NEW_ENEMY" + - " COND_SEE_FEAR" + - " COND_LIGHT_DAMAGE" + - " COND_HEAVY_DAMAGE" + - " COND_SMELL" + - " COND_PROVOKED" + - " COND_GIVE_WAY" + - " COND_HEAR_DANGER" + - " COND_HEAR_COMBAT" + - " COND_HEAR_BULLET_IMPACT" + - "\n"; - - public const string g_pszSCHED_DUCK_DODGE = - "\n Schedule" + - "\n SCHED_DUCK_DODGE" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_PLAY_SEQUENCE ACTIVITY:ACT_DUCK_DODGE" + - " TASK_DEFER_DODGE 30" + - "" + - " Interrupts" + - "" + - "\n"; - - public const string g_pszSCHED_INTERACTION_MOVE_TO_PARTNER = - "\n Schedule" + - "\n SCHED_INTERACTION_MOVE_TO_PARTNER" + - " Tasks" + - " TASK_GET_PATH_TO_INTERACTION_PARTNER 0" + - " TASK_FACE_TARGET 0" + - " TASK_WAIT 1" + - "" + - " Interrupts" + - " COND_NO_CUSTOM_INTERRUPTS" + - "\n"; - - public const string g_pszSCHED_INTERACTION_WAIT_FOR_PARTNER = - "\n Schedule" + - "\n SCHED_INTERACTION_WAIT_FOR_PARTNER" + - " Tasks" + - " TASK_FACE_TARGET 0" + - " TASK_WAIT 1" + - "" + - " Interrupts" + - " COND_NO_CUSTOM_INTERRUPTS" + - "\n"; - - public const string g_pszSCHED_SLEEP = - "\n Schedule" + - "\n SCHED_SLEEP" + - " Tasks" + - " TASK_STOP_MOVING 0" + - " TASK_WAIT 0.2" + - "" + - " Interrupts" + - "" + - "\n"; + public static readonly AI_ScheduleDef[] DefaultSchedules = [ + new(SCHED_IDLE_STAND, + [ + (TASK_STOP_MOVING, 1), + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + (TASK_WAIT, 5), + TASK_WAIT_PVS, + ], + [ + COND_NEW_ENEMY, + COND_SEE_FEAR, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_SMELL, + COND_PROVOKED, + COND_GIVE_WAY, + COND_HEAR_PLAYER, + COND_HEAR_DANGER, + COND_HEAR_COMBAT, + COND_HEAR_BULLET_IMPACT, + COND_IDLE_INTERRUPT, + ]), + + new(SCHED_IDLE_WALK, + [ + (TASK_WALK_PATH, 9999), + TASK_WAIT_FOR_MOVEMENT, + TASK_WAIT_PVS, + ], + [ + COND_NEW_ENEMY, + COND_SEE_ENEMY, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_SMELL, + COND_PROVOKED, + COND_HEAR_COMBAT, + COND_HEAR_BULLET_IMPACT, + ]), + + new(SCHED_IDLE_WANDER, + [ + (TASK_SET_ROUTE_SEARCH_TIME, 5), + (TASK_GET_PATH_TO_RANDOM_NODE, 200), + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_WAIT_PVS, + ], + [ + COND_GIVE_WAY, + COND_HEAR_COMBAT, + COND_HEAR_DANGER, + COND_NEW_ENEMY, + COND_SEE_ENEMY, + COND_SEE_FEAR, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_IDLE_INTERRUPT, + ]), + + new(SCHED_WAKE_ANGRY, + [ + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + TASK_SOUND_WAKE, + TASK_FACE_IDEAL, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + ]), + + new(SCHED_ALERT_FACE, + [ + TASK_STOP_MOVING, + TASK_FACE_IDEAL, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + ], + [ + COND_NEW_ENEMY, + COND_SEE_FEAR, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_PROVOKED, + ]), + + new(SCHED_ALERT_FACE_BESTSOUND, + [ + TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION, + TASK_STOP_MOVING, + TASK_FACE_SAVEPOSITION, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + (TASK_WAIT, 1.5f), + TASK_FACE_REASONABLE, + ], + [ + COND_NEW_ENEMY, + COND_SEE_FEAR, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_PROVOKED, + ]), + + new(SCHED_ALERT_REACT_TO_COMBAT_SOUND, + [ + (TASK_SET_SCHEDULE, SCHED_ALERT_FACE_BESTSOUND), + ]), + + new(SCHED_ALERT_SCAN, + [ + TASK_STOP_MOVING, + (TASK_WAIT, 0.5f), + (TASK_TURN_LEFT, 180), + (TASK_WAIT, 0.5f), + (TASK_TURN_LEFT, 180), + ], + [ + COND_NEW_ENEMY, + ]), + + new(SCHED_ALERT_STAND, + [ + TASK_STOP_MOVING, + TASK_FACE_REASONABLE, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + (TASK_WAIT, 20), + (TASK_SUGGEST_STATE, NPCState.Idle), + ], + [ + COND_NEW_ENEMY, + COND_SEE_ENEMY, + COND_SEE_FEAR, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_PROVOKED, + COND_SMELL, + COND_HEAR_COMBAT, + COND_HEAR_WORLD, + COND_HEAR_PLAYER, + COND_HEAR_DANGER, + COND_HEAR_BULLET_IMPACT, + COND_IDLE_INTERRUPT, + COND_GIVE_WAY, + ]), + + new(SCHED_ALERT_WALK, + [ + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_WAIT_PVS, + ], + [ + COND_NEW_ENEMY, + COND_SEE_ENEMY, + COND_SEE_FEAR, + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_HEAR_DANGER, + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + ]), + + new(SCHED_INVESTIGATE_SOUND, + [ + TASK_STOP_MOVING, + TASK_STORE_LASTPOSITION, + TASK_GET_PATH_TO_BESTSOUND, + TASK_FACE_IDEAL, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + (TASK_WAIT, 5), + TASK_GET_PATH_TO_LASTPOSITION, + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + TASK_CLEAR_LASTPOSITION, + TASK_FACE_REASONABLE, + ], + [ + COND_NEW_ENEMY, + COND_SEE_FEAR, + COND_SEE_ENEMY, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_HEAR_DANGER, + ]), + + new(SCHED_COMBAT_FACE, + [ + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + TASK_FACE_ENEMY, + ], + [ + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + ]), + + new(SCHED_COMBAT_SWEEP, + [ + (TASK_TURN_LEFT, 45), + (TASK_WAIT, 2), + (TASK_TURN_RIGHT, 45), + (TASK_WAIT, 2), + ], + [ + COND_NEW_ENEMY, + COND_SEE_ENEMY, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_HEAR_DANGER, + COND_HEAR_WORLD, + ]), + + new(SCHED_COMBAT_WALK, + [ + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_WAIT_PVS, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_HEAR_DANGER, + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + ]), + + new(SCHED_FEAR_FACE, + [ + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + TASK_FACE_ENEMY, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_SEE_ENEMY, + ]), + + new(SCHED_COMBAT_STAND, + [ + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + TASK_WAIT_INDEFINITE, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_SEE_ENEMY, + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_IDLE_INTERRUPT, + ]), + + new(SCHED_CHASE_ENEMY, + [ + TASK_STOP_MOVING, + (TASK_SET_FAIL_SCHEDULE, SCHED_CHASE_ENEMY_FAILED), + (TASK_GET_CHASE_PATH_TO_ENEMY, 300), + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_FACE_ENEMY, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_ENEMY_UNREACHABLE, + COND_CAN_RANGE_ATTACK1, + COND_CAN_MELEE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK2, + COND_TOO_CLOSE_TO_ATTACK, + COND_TASK_FAILED, + COND_LOST_ENEMY, + COND_BETTER_WEAPON_AVAILABLE, + COND_HEAR_DANGER, + ]), + + new(SCHED_CHASE_ENEMY_FAILED, + [ + TASK_STOP_MOVING, + (TASK_WAIT, 0.2f), + (TASK_SET_FAIL_SCHEDULE, SCHED_STANDOFF), + TASK_FIND_COVER_FROM_ENEMY, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_REMEMBER, AI_MemoryFlags.Incover), + TASK_FACE_ENEMY, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + (TASK_WAIT, 1), + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_CAN_RANGE_ATTACK1, + COND_CAN_MELEE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK2, + COND_HEAR_DANGER, + COND_BETTER_WEAPON_AVAILABLE, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + ]), + + new(SCHED_VICTORY_DANCE, + [ + TASK_STOP_MOVING, + (TASK_PLAY_SEQUENCE, Activity.ACT_VICTORY_DANCE), + TASK_WAIT, + ]), + + new(SCHED_TARGET_FACE, + [ + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + TASK_FACE_TARGET, + ], + [ + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + ]), + + new(SCHED_TARGET_CHASE, + [ + TASK_STOP_MOVING, + TASK_GET_PATH_TO_TARGET, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_ENEMY_UNREACHABLE, + COND_CAN_RANGE_ATTACK1, + COND_CAN_MELEE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK2, + COND_TOO_CLOSE_TO_ATTACK, + COND_TASK_FAILED, + COND_LOST_ENEMY, + COND_BETTER_WEAPON_AVAILABLE, + COND_HEAR_DANGER, + ]), + + new(SCHED_SMALL_FLINCH, + [ + (TASK_REMEMBER, AI_MemoryFlags.Flinched), + TASK_STOP_MOVING, + TASK_SMALL_FLINCH, + ]), + + new(SCHED_BIG_FLINCH, + [ + (TASK_REMEMBER, AI_MemoryFlags.Flinched), + TASK_STOP_MOVING, + TASK_BIG_FLINCH, + ]), + + new(SCHED_BACK_AWAY_FROM_ENEMY, + [ + TASK_STOP_MOVING, + TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION, + TASK_FIND_BACKAWAY_FROM_SAVEPOSITION, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ], + [ + COND_NEW_ENEMY, + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + ]), + + new(SCHED_MOVE_AWAY_FROM_ENEMY, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_MOVE_AWAY_FAIL), + TASK_FACE_ENEMY, + (TASK_MOVE_AWAY_PATH, 120), + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_SET_SCHEDULE, SCHED_MOVE_AWAY_END), + ], + [ + COND_NEW_ENEMY, + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + ]), + + new(SCHED_BACK_AWAY_FROM_SAVE_POSITION, + [ + TASK_STOP_MOVING, + TASK_FIND_BACKAWAY_FROM_SAVEPOSITION, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ]), + + new(SCHED_TAKE_COVER_FROM_ENEMY, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_FAIL_TAKE_COVER), + TASK_STOP_MOVING, + (TASK_WAIT, 0.2f), + TASK_FIND_COVER_FROM_ENEMY, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_REMEMBER, AI_MemoryFlags.Incover), + TASK_FACE_ENEMY, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + (TASK_WAIT, 1), + ], + [ + COND_NEW_ENEMY, + COND_HEAR_DANGER, + ]), + + new(SCHED_TAKE_COVER_FROM_BEST_SOUND, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_FLEE_FROM_BEST_SOUND), + TASK_STOP_MOVING, + TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION, + TASK_FIND_COVER_FROM_BEST_SOUND, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_REMEMBER, AI_MemoryFlags.Incover), + TASK_FACE_SAVEPOSITION, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + ], + [ + COND_NEW_ENEMY, + ]), + + new(SCHED_FLEE_FROM_BEST_SOUND, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_COWER), + TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION, + (TASK_GET_PATH_AWAY_FROM_BEST_SOUND, 600), + (TASK_RUN_PATH_FLEE, 100), + TASK_STOP_MOVING, + TASK_FACE_SAVEPOSITION, + ], + [ + COND_NEW_ENEMY, + ]), + + new(SCHED_TAKE_COVER_FROM_ORIGIN, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_FAIL_TAKE_COVER), + TASK_STOP_MOVING, + TASK_FIND_COVER_FROM_ORIGIN, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_REMEMBER, AI_MemoryFlags.Incover), + (TASK_TURN_LEFT, 179), + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + ], + [ + COND_NEW_ENEMY, + ]), + + new(SCHED_FAIL_TAKE_COVER, + [ + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + ], + [ + COND_NEW_ENEMY, + ]), + + new(SCHED_RUN_FROM_ENEMY, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_RUN_FROM_ENEMY_FALLBACK), + TASK_STOP_MOVING, + TASK_FIND_COVER_FROM_ENEMY, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + ]), + + new(SCHED_RUN_FROM_ENEMY_FALLBACK, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_RUN_RANDOM), + TASK_STOP_MOVING, + TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION, + TASK_FIND_BACKAWAY_FROM_SAVEPOSITION, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + ]), + + new(SCHED_MOVE_TO_WEAPON_RANGE, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_CHASE_ENEMY), + TASK_GET_PATH_TO_RANGE_ENEMY_LKP_LOS, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_SET_SCHEDULE, SCHED_COMBAT_FACE), + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LOST_ENEMY, + COND_CAN_RANGE_ATTACK1, + COND_CAN_MELEE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK2, + COND_HEAR_DANGER, + ]), + + new(SCHED_ESTABLISH_LINE_OF_FIRE, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK), + TASK_GET_PATH_TO_ENEMY_LOS, + (TASK_SPEAK_SENTENCE, 1), + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_SET_SCHEDULE, SCHED_COMBAT_FACE), + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LOST_ENEMY, + COND_CAN_RANGE_ATTACK1, + COND_CAN_MELEE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK2, + COND_HEAR_DANGER, + ]), + + new(SCHED_SHOOT_ENEMY_COVER, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_WAIT, 0.5f), + TASK_RANGE_ATTACK1, + ], + [ + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_NO_PRIMARY_AMMO, + COND_HEAR_DANGER, + COND_WEAPON_BLOCKED_BY_FRIEND, + ]), + + new(SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK, + [ + TASK_STOP_MOVING, + (TASK_SET_FAIL_SCHEDULE, SCHED_PRE_FAIL_ESTABLISH_LINE_OF_FIRE), + (TASK_GET_CHASE_PATH_TO_ENEMY, 300), + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_FACE_ENEMY, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_ENEMY_UNREACHABLE, + COND_CAN_RANGE_ATTACK1, + COND_CAN_MELEE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK2, + COND_TOO_CLOSE_TO_ATTACK, + COND_TASK_FAILED, + COND_LOST_ENEMY, + COND_BETTER_WEAPON_AVAILABLE, + COND_HEAR_DANGER, + ]), + + new(SCHED_PRE_FAIL_ESTABLISH_LINE_OF_FIRE, + [ + TASK_FACE_ENEMY, + TASK_FACE_REASONABLE, + TASK_IGNORE_OLD_ENEMIES, + (TASK_SET_SCHEDULE, SCHED_FAIL_ESTABLISH_LINE_OF_FIRE), + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_CAN_RANGE_ATTACK1, + COND_CAN_MELEE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK2, + ]), + + new(SCHED_FAIL_ESTABLISH_LINE_OF_FIRE, + [ + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LOST_ENEMY, + COND_CAN_RANGE_ATTACK1, + COND_CAN_MELEE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK2, + COND_HEAR_DANGER, + ]), + + new(SCHED_COWER, + [ + TASK_STOP_MOVING, + (TASK_PLAY_SEQUENCE, Activity.ACT_COWER), + TASK_WAIT_UNTIL_NO_DANGER_SOUND, + ]), + + new(SCHED_MELEE_ATTACK1, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + TASK_MELEE_ATTACK1, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_ENEMY_OCCLUDED, + ]), + + new(SCHED_MELEE_ATTACK2, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 2), + TASK_MELEE_ATTACK2, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_ENEMY_OCCLUDED, + ]), + + new(SCHED_RANGE_ATTACK1, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + TASK_RANGE_ATTACK1, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_ENEMY_OCCLUDED, + COND_NO_PRIMARY_AMMO, + COND_HEAR_DANGER, + COND_WEAPON_BLOCKED_BY_FRIEND, + COND_WEAPON_SIGHT_OCCLUDED, + ]), + + new(SCHED_RANGE_ATTACK2, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 2), + TASK_RANGE_ATTACK2, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_ENEMY_OCCLUDED, + COND_NO_SECONDARY_AMMO, + COND_HEAR_DANGER, + ]), + + new(SCHED_SPECIAL_ATTACK1, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + TASK_SPECIAL_ATTACK1, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_ENEMY_OCCLUDED, + COND_NO_PRIMARY_AMMO, + COND_HEAR_DANGER, + ]), + + new(SCHED_SPECIAL_ATTACK2, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + TASK_SPECIAL_ATTACK2, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_ENEMY_OCCLUDED, + COND_NO_SECONDARY_AMMO, + COND_HEAR_DANGER, + ]), + + new(SCHED_STANDOFF, + [ + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + (TASK_WAIT_FACE_ENEMY, 2), + ], + [ + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_ENEMY_DEAD, + COND_NEW_ENEMY, + COND_HEAR_DANGER, + ]), + + new(SCHED_ARM_WEAPON, + [ + TASK_STOP_MOVING, + TASK_FACE_IDEAL, + (TASK_PLAY_SEQUENCE, Activity.ACT_ARM), + ]), + + new(SCHED_DISARM_WEAPON, + [ + TASK_STOP_MOVING, + TASK_FACE_IDEAL, + (TASK_PLAY_SEQUENCE, Activity.ACT_DISARM), + ]), + + new(SCHED_HIDE_AND_RELOAD, + [ + TASK_STOP_MOVING, + (TASK_SET_FAIL_SCHEDULE, SCHED_RELOAD), + TASK_FIND_COVER_FROM_ENEMY, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_REMEMBER, AI_MemoryFlags.Incover), + TASK_FACE_ENEMY, + (TASK_SET_SCHEDULE, SCHED_RELOAD), + ], + [ + COND_HEAR_DANGER, + ]), + + new(SCHED_RELOAD, + [ + TASK_STOP_MOVING, + TASK_RELOAD, + ], + [ + COND_HEAR_DANGER, + ]), + + new(SCHED_AMBUSH, + [ + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + TASK_WAIT_INDEFINITE, + ], + [ + COND_NEW_ENEMY, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_PROVOKED, + ]), + + new(SCHED_DIE, + [ + TASK_STOP_MOVING, + TASK_SOUND_DIE, + TASK_DIE, + ], + [ + COND_NO_CUSTOM_INTERRUPTS, + ]), + + new(SCHED_DIE_RAGDOLL, + [ + TASK_STOP_MOVING, + TASK_SOUND_DIE, + ], + [ + COND_NO_CUSTOM_INTERRUPTS, + ]), + + new(SCHED_WAIT_FOR_SCRIPT, + [ + TASK_STOP_MOVING, + TASK_WAIT_INDEFINITE, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + ]), + + new(SCHED_SCRIPTED_WALK, + [ + TASK_PRE_SCRIPT, + (TASK_SET_TOLERANCE_DISTANCE, 2), + TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY, + TASK_SCRIPT_WALK_TO_TARGET, + TASK_WAIT_FOR_MOVEMENT, + TASK_PLANT_ON_SCRIPT, + TASK_FACE_SCRIPT, + TASK_ENABLE_SCRIPT, + TASK_WAIT_FOR_SCRIPT, + TASK_PLAY_SCRIPT, + TASK_PLAY_SCRIPT_POST_IDLE, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + ]), + + new(SCHED_SCRIPTED_RUN, + [ + TASK_PRE_SCRIPT, + (TASK_SET_TOLERANCE_DISTANCE, 2), + TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY, + TASK_SCRIPT_RUN_TO_TARGET, + TASK_WAIT_FOR_MOVEMENT, + TASK_PLANT_ON_SCRIPT, + TASK_FACE_SCRIPT, + TASK_ENABLE_SCRIPT, + TASK_WAIT_FOR_SCRIPT, + TASK_PLAY_SCRIPT, + TASK_PLAY_SCRIPT_POST_IDLE, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + ]), + + new(SCHED_SCRIPTED_CUSTOM_MOVE, + [ + TASK_PRE_SCRIPT, + (TASK_SET_TOLERANCE_DISTANCE, 2), + TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY, + TASK_SCRIPT_CUSTOM_MOVE_TO_TARGET, + TASK_WAIT_FOR_MOVEMENT, + TASK_PLANT_ON_SCRIPT, + TASK_FACE_SCRIPT, + TASK_ENABLE_SCRIPT, + TASK_WAIT_FOR_SCRIPT, + TASK_PLAY_SCRIPT, + TASK_PLAY_SCRIPT_POST_IDLE, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + ]), + + new(SCHED_SCRIPTED_WAIT, + [ + TASK_PRE_SCRIPT, + TASK_STOP_MOVING, + TASK_ENABLE_SCRIPT, + TASK_WAIT_FOR_SCRIPT, + TASK_PLAY_SCRIPT, + TASK_PLAY_SCRIPT_POST_IDLE, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + ]), + + new(SCHED_SCRIPTED_FACE, + [ + TASK_PRE_SCRIPT, + TASK_STOP_MOVING, + TASK_FACE_SCRIPT, + TASK_ENABLE_SCRIPT, + TASK_WAIT_FOR_SCRIPT, + TASK_PLAY_SCRIPT, + TASK_PLAY_SCRIPT_POST_IDLE, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + ]), + + new(SCHED_SCENE_GENERIC, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_SCENE_GENERIC), + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + TASK_PLAY_SCENE, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + (TASK_SET_SCHEDULE, SCHED_SCENE_GENERIC), + ]), + + new(SCHED_NEW_WEAPON, + [ + TASK_STOP_MOVING, + (TASK_SET_TOLERANCE_DISTANCE, 5), + TASK_GET_PATH_TO_TARGET_WEAPON, + TASK_WEAPON_RUN_PATH, + TASK_STOP_MOVING, + TASK_FACE_TARGET, + TASK_WEAPON_PICKUP, + (TASK_WAIT, 1), + ], + [ + COND_HEAR_DANGER, + ]), + + new(SCHED_NEW_WEAPON_CHEAT, + [ + TASK_WEAPON_CREATE, + ]), + + new(SCHED_SWITCH_TO_PENDING_WEAPON, + [ + TASK_STOP_MOVING, + (TASK_PLAY_SEQUENCE, Activity.ACT_DROP_WEAPON), + TASK_CREATE_PENDING_WEAPON, + ]), + + new(SCHED_GET_HEALTHKIT, + [ + TASK_STOP_MOVING, + (TASK_SET_TOLERANCE_DISTANCE, 5), + TASK_GET_PATH_TO_TARGET_WEAPON, + TASK_ITEM_RUN_PATH, + TASK_STOP_MOVING, + TASK_FACE_TARGET, + TASK_ITEM_PICKUP, + ]), + + new(SCHED_MOVE_AWAY, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_MOVE_AWAY_FAIL), + (TASK_MOVE_AWAY_PATH, 120), + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_SET_SCHEDULE, SCHED_MOVE_AWAY_END), + ]), + + new(SCHED_MOVE_AWAY_FAIL, + [ + TASK_STOP_MOVING, + ]), + + new(SCHED_MOVE_AWAY_END, + [ + TASK_STOP_MOVING, + TASK_FACE_REASONABLE, + ], + [ + COND_NEW_ENEMY, + COND_SEE_ENEMY, + COND_SEE_FEAR, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_PROVOKED, + COND_SMELL, + COND_HEAR_COMBAT, + COND_HEAR_WORLD, + COND_HEAR_PLAYER, + COND_HEAR_DANGER, + COND_HEAR_BULLET_IMPACT, + COND_IDLE_INTERRUPT, + ]), + + new(SCHED_WAIT_FOR_SPEAK_FINISH, + [ + TASK_WAIT_FOR_SPEAK_FINISH, + ], + [ + COND_NEW_ENEMY, + COND_SEE_FEAR, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_SMELL, + COND_PROVOKED, + COND_GIVE_WAY, + COND_HEAR_DANGER, + COND_HEAR_COMBAT, + COND_HEAR_BULLET_IMPACT, + ]), + + new(SCHED_FORCED_GO, + [ + (TASK_SET_TOLERANCE_DISTANCE, 48), + (TASK_SET_ROUTE_SEARCH_TIME, 3), + TASK_GET_PATH_TO_LASTPOSITION, + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + ]), + + new(SCHED_FORCED_GO_RUN, + [ + (TASK_SET_TOLERANCE_DISTANCE, 48), + (TASK_SET_ROUTE_SEARCH_TIME, 3), + TASK_GET_PATH_TO_LASTPOSITION, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ]), + + new(SCHED_PATROL_WALK, + [ + (TASK_SET_ROUTE_SEARCH_TIME, 5), + (TASK_GET_PATH_TO_RANDOM_NODE, 200), + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + ], + [ + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_GIVE_WAY, + COND_HEAR_COMBAT, + COND_HEAR_DANGER, + COND_HEAR_PLAYER, + COND_NEW_ENEMY, + COND_SEE_ENEMY, + COND_SEE_FEAR, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_SMELL, + COND_PROVOKED, + ]), + + new(SCHED_COMBAT_PATROL, + [ + (TASK_SET_ROUTE_SEARCH_TIME, 5), + (TASK_GET_PATH_TO_RANDOM_NODE, 200), + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + ], + [ + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_GIVE_WAY, + COND_HEAR_DANGER, + COND_NEW_ENEMY, + ]), + + new(SCHED_PATROL_RUN, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_COMBAT_FACE), + (TASK_SET_ROUTE_SEARCH_TIME, 5), + (TASK_GET_PATH_TO_RANDOM_NODE, 200), + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ], + [ + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_GIVE_WAY, + COND_NEW_ENEMY, + COND_SEE_ENEMY, + COND_SEE_FEAR, + COND_HEAR_COMBAT, + COND_HEAR_DANGER, + COND_HEAR_PLAYER, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_SMELL, + COND_PROVOKED, + ]), + + new(SCHED_RUN_RANDOM, + [ + (TASK_SET_ROUTE_SEARCH_TIME, 1), + (TASK_GET_PATH_TO_RANDOM_NODE, 500), + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ]), + + new(SCHED_FAIL, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_FAIL_NOSTOP), + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + (TASK_WAIT, 1), + TASK_WAIT_PVS, + ], + [ + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_GIVE_WAY, + ]), + + new(SCHED_FAIL_NOSTOP, + [ + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + (TASK_WAIT, 1), + TASK_WAIT_PVS, + ], + [ + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_GIVE_WAY, + ]), + + new(SCHED_FALL_TO_GROUND, + [ + TASK_FALL_TO_GROUND, + ]), + + new(SCHED_DROPSHIP_DUSTOFF, + [ + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_WAIT_PVS, + ]), + + new(SCHED_FLINCH_PHYSICS, + [ + TASK_STOP_MOVING, + (TASK_PLAY_SEQUENCE, Activity.ACT_FLINCH_PHYSICS), + ]), + + new(SCHED_RUN_FROM_ENEMY_MOB, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_RUN_RANDOM), + TASK_STOP_MOVING, + TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION, + TASK_FIND_BACKAWAY_FROM_SAVEPOSITION, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ], + [ + COND_HEAR_DANGER, + ]), + + new(SCHED_DUCK_DODGE, + [ + TASK_STOP_MOVING, + (TASK_PLAY_SEQUENCE, Activity.ACT_DUCK_DODGE), + (TASK_DEFER_DODGE, 30), + ]), + + new(SCHED_NPC_FREEZE, + [ + TASK_FREEZE, + ], + [ + COND_NPC_UNFREEZE, + ]), + + new(SCHED_INTERACTION_MOVE_TO_PARTNER, + [ + TASK_GET_PATH_TO_INTERACTION_PARTNER, + TASK_FACE_TARGET, + (TASK_WAIT, 1), + ], + [ + COND_NO_CUSTOM_INTERRUPTS, + ]), + + new(SCHED_INTERACTION_WAIT_FOR_PARTNER, + [ + TASK_FACE_TARGET, + (TASK_WAIT, 1), + ], + [ + COND_NO_CUSTOM_INTERRUPTS, + ]), + + new(SCHED_SLEEP, + [ + TASK_STOP_MOVING, + (TASK_WAIT, 0.2f), + ]), + ]; } public class AI_SystemHook(ReadOnlySpan name) : AutoGameSystem(name) diff --git a/Game.Server/AI_Schedule.cs b/Game.Server/AI_Schedule.cs index e37e9b9af..2deade91e 100644 --- a/Game.Server/AI_Schedule.cs +++ b/Game.Server/AI_Schedule.cs @@ -73,282 +73,74 @@ AI_Schedule CreateSchedule(ReadOnlySpan name, int scheduleID) { return sched; } - static NPCState GetStateID(ReadOnlySpan stateName) { - if (stricmp(stateName, "NONE") == 0) return NPCState.None; - else if (stricmp(stateName, "IDLE") == 0) return NPCState.Idle; - else if (stricmp(stateName, "COMBAT") == 0) return NPCState.Combat; - else if (stricmp(stateName, "PRONE") == 0) return NPCState.Prone; - else if (stricmp(stateName, "ALERT") == 0) return NPCState.Alert; - else if (stricmp(stateName, "SCRIPT") == 0) return NPCState.Script; - else if (stricmp(stateName, "PLAYDEAD") == 0) return NPCState.PlayDead; - else if (stricmp(stateName, "DEAD") == 0) return NPCState.Dead; - else return NPCState.Invalid; - } - - static AI_MemoryFlags GetMemoryID(ReadOnlySpan stateName) { - if (stricmp(stateName, "PROVOKED") == 0) return AI_MemoryFlags.Provoked; - else if (stricmp(stateName, "INCOVER") == 0) return AI_MemoryFlags.Incover; - else if (stricmp(stateName, "SUSPICIOUS") == 0) return AI_MemoryFlags.Suspicious; - else if (stricmp(stateName, "PATH_FAILED") == 0) return AI_MemoryFlags.PathFailed; - else if (stricmp(stateName, "FLINCHED") == 0) return AI_MemoryFlags.Flinched; - else if (stricmp(stateName, "TOURGUIDE") == 0) return AI_MemoryFlags.TourGuide; - else if (stricmp(stateName, "LOCKED_HINT") == 0) return AI_MemoryFlags.LockedHint; - else if (stricmp(stateName, "TURNING") == 0) return AI_MemoryFlags.Turning; - else if (stricmp(stateName, "TURNHACK") == 0) return AI_MemoryFlags.TurnHack; - else if (stricmp(stateName, "CUSTOM4") == 0) return AI_MemoryFlags.Custom4; - else if (stricmp(stateName, "CUSTOM3") == 0) return AI_MemoryFlags.Custom3; - else if (stricmp(stateName, "CUSTOM2") == 0) return AI_MemoryFlags.Custom2; - else if (stricmp(stateName, "CUSTOM1") == 0) return AI_MemoryFlags.Custom1; - else return (AI_MemoryFlags)(-1); - } - - static PathType GetPathID(ReadOnlySpan token) { - if (stricmp(token, "TRAVEL") == 0) return PathType.Travel; - else if (stricmp(token, "LOS") == 0) return PathType.LOS; - else if (stricmp(token, "COVER") == 0) return PathType.Cover; - - return PathType.None; - } - - static ScheduleGoalType GetGoalID(ReadOnlySpan token) { - if (stricmp(token, "ENEMY") == 0) return ScheduleGoalType.Enemy; - else if (stricmp(token, "ENEMY_LKP") == 0) return ScheduleGoalType.EnemyLKP; - else if (stricmp(token, "TARGET") == 0) return ScheduleGoalType.Target; - else if (stricmp(token, "SAVED_POSITION") == 0) return ScheduleGoalType.SavedPosition; + public bool DefineSchedules(ReadOnlySpan prefix, AI_ClassScheduleIdSpace idSpace, ReadOnlySpan schedules) { + for (int i = 0; i < schedules.Length; i++) { + if (!DefineSchedule(prefix, idSpace, schedules[i])) + return false; + } - return ScheduleGoalType.None; + return true; } - static ReadOnlySpan Token(ReadOnlySpan buffer) => buffer.SliceNullTerminatedString(); - - public bool LoadSchedulesFromBuffer(ReadOnlySpan prefix, ReadOnlySpan startFile, AI_ClassScheduleIdSpace? idSpace) { - Span token = stackalloc char[1024]; - Span saveToken = stackalloc char[1024]; - ReadOnlySpan file = engine.ParseFile(startFile, token); - - while (stricmp("Schedule", Token(token)) == 0) { - file = engine.ParseFile(file, token); + bool DefineSchedule(ReadOnlySpan prefix, AI_ClassScheduleIdSpace idSpace, in AI_ScheduleDef schedule) { + int scheduleLocalID = schedule.Schedule; + int scheduleID = idSpace.ScheduleLocalToGlobal(scheduleLocalID); + string? name = scheduleID != -1 ? AI_BaseNPC.GetSchedulingSymbols().ScheduleIdToSymbol(scheduleID) : null; + if (name == null) { + DevMsg($"ERROR: LoadSchd ({prefix}): Unknown schedule type ({scheduleLocalID})\n"); + return true; + } - if (GetScheduleByName(Token(token)) != null) { - DevMsg($"ERROR: file contains a schedule ({Token(token)}) that has already been defined!\n"); - DevMsg(" Aborting schedule load.\n"); - Assert(false); - return false; - } + if (GetScheduleByName(name) != null) { + DevMsg($"ERROR: file contains a schedule ({name}) that has already been defined!\n"); + DevMsg(" Aborting schedule load.\n"); + Assert(false); + return false; + } - int scheduleID = AI_BaseNPC.GetScheduleID(Token(token)); - if (scheduleID == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): Unknown schedule type ({Token(token)})\n"); - break; - } + AI_Schedule newSchedule = CreateSchedule(name, scheduleID); - AI_Schedule newSchedule = CreateSchedule(Token(token), scheduleID); + AI_TaskDef[] tasks = schedule.Tasks; + Task_t[] taskList = new Task_t[tasks.Length]; - file = engine.ParseFile(file, token); - if (stricmp(Token(token), "Tasks") != 0) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Malformed AI Schedule. Expecting 'Tasks' keyword.\n"); + for (int i = 0; i < tasks.Length; i++) { + if (idSpace.TaskLocalToGlobal(tasks[i].Task) == -1) { + DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown task {tasks[i].Task}!\n"); Assert(false); return false; } - Span tempTask = stackalloc Task_t[50]; - int taskNum = 0; - - file = engine.ParseFile(file, token); - while (Token(token).Length > 0 && stricmp("Interrupts", Token(token)) != 0) { - int taskID = AI_BaseNPC.GetTaskID(Token(token)); - tempTask[taskNum].Task = (idSpace != null) ? idSpace.TaskGlobalToLocal(taskID) : AI_RemapFromGlobal(taskID); + taskList[i].Task = tasks[i].Task; + taskList[i].TaskData = tasks[i].Data; - if (tempTask[taskNum].Task == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown task {Token(token)}!\n"); + if (tasks[i].ActivityName != null) { + taskList[i].TaskData = AI_BaseNPC.GetActivityID(tasks[i].ActivityName); + if (taskList[i].TaskData == -1) { + DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown activity {tasks[i].ActivityName}!\n"); Assert(false); return false; } - - Assert(AI_IdIsLocal(tempTask[taskNum].Task)); - - file = engine.ParseFile(file, token); - - if (stricmp("Activity", Token(token)) == 0) { - file = engine.ParseFile(file, token); - if (stricmp(Token(token), ":") != 0) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Malformed AI Schedule. Expecting ':' after type 'ACTIVITY.\n"); - Assert(false); - return false; - } - - file = engine.ParseFile(file, token); - tempTask[taskNum].TaskData = AI_BaseNPC.GetActivityID(Token(token)); - if (tempTask[taskNum].TaskData == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown activity {Token(token)}!\n"); - Assert(false); - return false; - } - } - else if (stricmp("Task", Token(token)) == 0) { - file = engine.ParseFile(file, token); - if (stricmp(Token(token), ":") != 0) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Malformed AI Schedule. Expecting ':' after type 'ACTIVITY.\n"); - Assert(false); - return false; - } - - file = engine.ParseFile(file, token); - - int dataTaskID = AI_BaseNPC.GetTaskID(Token(token)); - tempTask[taskNum].TaskData = (idSpace != null) ? idSpace.TaskGlobalToLocal(dataTaskID) : AI_RemapFromGlobal(dataTaskID); - - if (tempTask[taskNum].TaskData == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown task {Token(token)}!\n"); - Assert(false); - return false; - } - } - else if (stricmp("Schedule", Token(token)) == 0) { - file = engine.ParseFile(file, token); - if (stricmp(Token(token), ":") != 0) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Malformed AI Schedule. Expecting ':' after type 'ACTIVITY.\n"); - Assert(false); - return false; - } - - file = engine.ParseFile(file, token); - - int schedID = AI_BaseNPC.GetScheduleID(Token(token)); - tempTask[taskNum].TaskData = (idSpace != null) ? idSpace.ScheduleGlobalToLocal(schedID) : AI_RemapFromGlobal(schedID); - - if (tempTask[taskNum].TaskData == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown shedule {Token(token)}!\n"); - Assert(false); - return false; - } - } - else if (stricmp("State", Token(token)) == 0) { - file = engine.ParseFile(file, token); - if (stricmp(Token(token), ":") != 0) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Malformed AI Schedule. Expecting ':' after type 'STATE.\n"); - Assert(false); - return false; - } - - file = engine.ParseFile(file, token); - tempTask[taskNum].TaskData = (int)GetStateID(Token(token)); - if (tempTask[taskNum].TaskData == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown shedule {Token(token)}!\n"); - Assert(false); - return false; - } - } - else if (stricmp("Memory", Token(token)) == 0) { - file = engine.ParseFile(file, token); - if (stricmp(Token(token), ":") != 0) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Malformed AI Schedule. Expecting ':' after type 'STATE.\n"); - Assert(false); - return false; - } - - file = engine.ParseFile(file, token); - tempTask[taskNum].TaskData = (int)GetMemoryID(Token(token)); - if (tempTask[taskNum].TaskData == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown shedule {Token(token)}!\n"); - Assert(false); - return false; - } - } - else if (stricmp("Path", Token(token)) == 0) { - file = engine.ParseFile(file, token); - if (stricmp(Token(token), ":") != 0) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Malformed AI Schedule. Expecting ':' after type 'PATH.\n"); - Assert(false); - return false; - } - - file = engine.ParseFile(file, token); - tempTask[taskNum].TaskData = (int)GetPathID(Token(token)); - if (tempTask[taskNum].TaskData == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown path type {Token(token)}!\n"); - Assert(false); - return false; - } - } - else if (stricmp("Goal", Token(token)) == 0) { - file = engine.ParseFile(file, token); - if (stricmp(Token(token), ":") != 0) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Malformed AI Schedule. Expecting ':' after type 'GOAL.\n"); - Assert(false); - return false; - } - - file = engine.ParseFile(file, token); - tempTask[taskNum].TaskData = (int)GetGoalID(Token(token)); - if (tempTask[taskNum].TaskData == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown goal type {Token(token)}!\n"); - Assert(false); - return false; - } - } - else if (stricmp("HintFlags", Token(token)) == 0) { - file = engine.ParseFile(file, token); - if (stricmp(Token(token), ":") != 0) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Malformed AI Schedule. Expecting ':' after type 'HINTFLAG'\n"); - Assert(false); - return false; - } - - file = engine.ParseFile(file, token); - tempTask[taskNum].TaskData = (int)AI_HintManager.GetFlags(Token(token)); - if (tempTask[taskNum].TaskData == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Unknown hint flag type {Token(token)}!\n"); - Assert(false); - return false; - } - } - else if (stricmp("Interrupts", Token(token)) == 0 || strnicmp("TASK_", Token(token), 5) == 0) { - Warning($"ERROR: LoadSchd ({prefix}): ({newSchedule.GetName()}) Bad syntax at task #{taskNum} (wasn't expecting {Token(token)})\n"); - Assert(false); - return false; - } - else - tempTask[taskNum].TaskData = (float)atof(Token(token)); - taskNum++; - - Token(token).CopyTo(saveToken); - saveToken[Token(token).Length] = '\0'; - file = engine.ParseFile(file, token); - - if (stricmp(Token(token), ":") == 0) { - DevMsg($"ERROR: LoadSchd ({prefix}): Schedule ({newSchedule.GetName()}),\n Task ({taskID}), has a malformed AI Task Argument = ({Token(saveToken)})\n"); - Assert(false); - return false; - } - } - - newSchedule.NumTasksValue = taskNum; - newSchedule.TaskList = new Task_t[taskNum]; - for (int i = 0; i < taskNum; i++) { - newSchedule.TaskList[i].Task = tempTask[i].Task; - newSchedule.TaskList[i].TaskData = tempTask[i].TaskData; - - Assert(AI_IdIsLocal(newSchedule.TaskList[i].Task)); } + } - file = engine.ParseFile(file, token); - while (Token(token).Length > 0 && stricmp("Schedule", Token(token)) != 0) { - int condID = AI_BaseNPC.GetConditionID(Token(token)); + newSchedule.NumTasksValue = taskList.Length; + newSchedule.TaskList = taskList; - if (condID == -1) { - DevMsg($"ERROR: LoadSchd ({prefix}): Schedule ({newSchedule.GetName()}), Unknown condition {Token(token)}!\n"); - Assert(false); - } - else { - int interrupt = AI_RemapFromGlobal(condID); - Assert(AI_IdIsGlobal(condID) && interrupt >= 0 && interrupt < MAX_CONDITIONS); - newSchedule.InterruptMask.Set(interrupt); - } + AI_ScheduleCondition[] interrupts = schedule.Interrupts ?? []; + for (int i = 0; i < interrupts.Length; i++) { + int condID = idSpace.ConditionLocalToGlobal(interrupts[i].Condition); - file = engine.ParseFile(file, token); + if (condID == -1) { + DevMsg($"ERROR: LoadSchd ({prefix}): Schedule ({newSchedule.GetName()}), Unknown condition {interrupts[i].Condition}!\n"); + Assert(false); + } + else { + int interrupt = AI_RemapFromGlobal(condID); + Assert(AI_IdIsGlobal(condID) && interrupt >= 0 && interrupt < MAX_CONDITIONS); + newSchedule.InterruptMask.Set(interrupt); } } + return true; } @@ -382,6 +174,16 @@ public void DeleteAllSchedules() { } } +public readonly struct AI_ScheduleCondition(int condition) +{ + public readonly int Condition = condition; + + public static implicit operator AI_ScheduleCondition(int condition) => new(condition); + public static implicit operator AI_ScheduleCondition(SCOND_t condition) => new((int)condition); +} + +public readonly record struct AI_ScheduleDef(int Schedule, AI_TaskDef[] Tasks, AI_ScheduleCondition[]? Interrupts = null); + public class AI_Schedule { public int GetId() => ScheduleID; diff --git a/Game.Server/AI_Task.cs b/Game.Server/AI_Task.cs index 543a530ce..d26091f54 100644 --- a/Game.Server/AI_Task.cs +++ b/Game.Server/AI_Task.cs @@ -1,5 +1,7 @@ global using static Game.Server.AI_TaskGlobals; +using Game.Shared; + namespace Game.Server; // keeping these as const ints for now since the scripts refer to them by these names @@ -260,3 +262,22 @@ public struct Task_t public int Task; public float TaskData; } + +public readonly struct AI_TaskDef(int task, float data, string? activityName = null) +{ + public readonly int Task = task; + public readonly float Data = data; + public readonly string? ActivityName = activityName; + + public static implicit operator AI_TaskDef(int task) => new(task, 0); + public static implicit operator AI_TaskDef((int Task, int Data) task) => new(task.Task, task.Data); + public static implicit operator AI_TaskDef((int Task, float Data) task) => new(task.Task, task.Data); + public static implicit operator AI_TaskDef((int Task, Activity Data) task) => new(task.Task, (int)task.Data); + public static implicit operator AI_TaskDef((int Task, string ActivityName) task) => new(task.Task, 0, task.ActivityName); + public static implicit operator AI_TaskDef((int Task, NPCState Data) task) => new(task.Task, (int)task.Data); + public static implicit operator AI_TaskDef((int Task, AI_MemoryFlags Data) task) => new(task.Task, (int)task.Data); + public static implicit operator AI_TaskDef((int Task, PathType Data) task) => new(task.Task, (int)task.Data); + public static implicit operator AI_TaskDef((int Task, ScheduleGoalType Data) task) => new(task.Task, (int)task.Data); + public static implicit operator AI_TaskDef((int Task, AI_HintNodeFlags Data) task) => new(task.Task, (int)task.Data); + public static implicit operator AI_TaskDef((int Task, DamageType Data) task) => new(task.Task, (int)task.Data); +} From 5e0be2f49dabd3662b63e709477354062b99d45d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:19:57 +0300 Subject: [PATCH 05/73] Initialize the AI network manager through DelayedInit like the SDK --- Game.Server/AI_Default.cs | 1 + Game.Server/AI_NetworkManager.cs | 44 ++++++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/Game.Server/AI_Default.cs b/Game.Server/AI_Default.cs index 614f1201f..850f4e08f 100644 --- a/Game.Server/AI_Default.cs +++ b/Game.Server/AI_Default.cs @@ -1320,6 +1320,7 @@ public override void LevelInitPreEntity() { } public override void LevelShutdownPostEntity() { + AI_NetworkManager.DeleteAllAINetworks(); g_AI_SchedulesManager.DeleteAllSchedules(); g_AI_SchedulesManager.DestroyStringRegistries(); } diff --git a/Game.Server/AI_NetworkManager.cs b/Game.Server/AI_NetworkManager.cs index ee5893ca6..c2b4ecb77 100644 --- a/Game.Server/AI_NetworkManager.cs +++ b/Game.Server/AI_NetworkManager.cs @@ -28,9 +28,16 @@ public class AI_NetworkManager : PointEntity static readonly ConVar g_ai_norebuildgraph = new("ai_norebuildgraph", "0"); public static void InitializeAINetworks() { - g_pAINetworkManager = (AI_NetworkManager)CreateEntityByName("ai_network")!; - g_pBigAINet = g_pAINetworkManager.GetNetwork(); - g_pAINetworkManager.LoadNetworkGraph(); + AI_NetworkManager network = (AI_NetworkManager)CreateEntityByName("ai_network")!; + g_pAINetworkManager = network; + network.AddEFlags(EFL.KeepOnRecreateEntities); + g_pBigAINet = network.GetNetwork(); + network.SetName("BigNet"); + network.Spawn(); + network.LoadNetworkGraph(); + + network.SetThink(network.DelayedInit); + network.SetNextThink(gpGlobals.CurTime); } public void LoadNetworkGraph() { @@ -153,15 +160,42 @@ void LoadNetworkGraph(BinaryReader reader, ReadOnlySpan nrpFilename, int c gm_fNetworksLoaded = true; } + public static void DeleteAllAINetworks() { + gm_fNetworksLoaded = false; + g_pBigAINet = null; + } + + public override void Spawn() { + SetSolid(Source.SolidType.None); + SetMoveType(Source.MoveType.None); + } + + void DelayedInit() { + if (!g_pGameRules.FAllowNPCs()) { + SetThink(null); + return; + } + + if (!g_ai_norebuildgraph.GetBool() && !NetworksLoaded()) { + SetThink(null); + return; + } + + Initalized = true; + + if (g_AI_Manager.NumAIs() != 0 && g_pBigAINet!.NumNodes() == 0) + DevMsg("WARNING: Level contains NPCs but has no path nodes\n"); + } + public static bool NetworksLoaded() => gm_fNetworksLoaded; public bool IsInitialized() => Initalized; public AI_NetworkEditTools GetEditOps() => EditOps; public AI_Network GetNetwork() => Network; - static bool gm_fNetworksLoaded = true; + static bool gm_fNetworksLoaded; readonly AI_Network Network = new(); readonly AI_NetworkEditTools EditOps = new(); - bool Initalized = true; + bool Initalized; } From aa967a0988f2dcf7e0f2ec71169a91cc5e6d6f25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:26:38 +0300 Subject: [PATCH 06/73] Port node entity spawning for loaded AI graphs --- Game.Server/AI_InitUtils.cs | 101 +++++++++++++++++++++++++++++-- Game.Server/AI_NetworkManager.cs | 3 + Game.Server/EntityList.cs | 2 +- 3 files changed, 100 insertions(+), 6 deletions(-) diff --git a/Game.Server/AI_InitUtils.cs b/Game.Server/AI_InitUtils.cs index 08a753bb5..9c18c2a26 100644 --- a/Game.Server/AI_InitUtils.cs +++ b/Game.Server/AI_InitUtils.cs @@ -1,17 +1,108 @@ -using Game.Shared; +using Game.Shared; -using System; -using System.Collections.Generic; -using System.Text; +using Source; +using Source.Common; + +using System.Numerics; namespace Game.Server; +public enum HintIgnoreFacing +{ + No, + Yes, + Default, +} + +public class HintNodeData +{ + public static readonly DataMap DataDesc = new(typeof(HintNodeData), [ + DEFINE.FIELD(nameof(EntityName), FieldType.String), + DEFINE.KEYFIELD(nameof(HintType), FieldType.Short, "hinttype"), + DEFINE.KEYFIELD(nameof(Group), FieldType.String, "Group"), + DEFINE.KEYFIELD(nameof(Disabled), FieldType.Integer, "StartHintDisabled"), + DEFINE.FIELD(nameof(NodeID), FieldType.Integer), + DEFINE.KEYFIELD(nameof(ActivityName), FieldType.String, "hintactivity"), + DEFINE.KEYFIELD(nameof(TargetWCNodeID), FieldType.Integer, "TargetNode"), + DEFINE.KEYFIELD(nameof(WCNodeID), FieldType.Integer, "nodeid"), + DEFINE.KEYFIELD(nameof(IgnoreFacing), FieldType.Integer, "IgnoreFacing"), + DEFINE.KEYFIELD(nameof(MinState), FieldType.Integer, "MinimumState"), + DEFINE.KEYFIELD(nameof(MaxState), FieldType.Integer, "MaximumState"), + ]); + + public string? EntityName; + public Vector3 Position; + public short HintType; + public int NodeID; + public string? Group; + public int Disabled; + public string? ActivityName; + public int TargetWCNodeID; + public HintIgnoreFacing IgnoreFacing; + public NPCState MinState; + public NPCState MaxState; + + public int WCNodeID; +} + [LinkEntityToClass("info_hint")] [LinkEntityToClass("info_node")] [LinkEntityToClass("info_node_hint")] [LinkEntityToClass("info_node_air")] [LinkEntityToClass("info_node_air_hint")] [LinkEntityToClass("info_node_climb")] -public class NodeEnt : ServerOnlyPointEntity { +public class NodeEnt : ServerOnlyPointEntity +{ + public static readonly new DataMap DataDesc = new(typeof(NodeEnt), BaseEntity.DataDesc, [ + DEFINE.EMBEDDED(nameof(NodeData)), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public static int NodeCount; + + public HintNodeData NodeData = new(); + + public override void Spawn() { + NodeData.EntityName = GetEntityName(); + NodeData.Position = GetAbsOrigin(); + NodeData.NodeID = NO_NODE; + if (NodeData.MinState == NPCState.None) + NodeData.MinState = NPCState.Idle; + if (NodeData.MaxState == NPCState.None) + NodeData.MaxState = NPCState.Combat; + + if (FClassnameIs(this, "info_hint")) { + if (NodeData.HintType == 0) + Warning($"info_hint (HammerID: {NodeData.WCNodeID}, position ({NodeData.Position.X:0.00}, {NodeData.Position.Y:0.00}, {NodeData.Position.Z:0.00})) with no hint type.\n"); + Util.RemoveImmediate(this); + return; + } + + if (AI_NetworkManager.NetworksLoaded()) { + NodeCount++; + Util.RemoveImmediate(this); + return; + } + else + NodeCount++; + + AI_Node newNode = g_pBigAINet!.AddNode(GetAbsOrigin(), GetAbsAngles().Y); + + AI_NetworkEditTools editOps = g_pAINetworkManager!.GetEditOps(); + if (editOps.NodeIndexTable != null) + editOps.NodeIndexTable[newNode.GetId()] = NodeData.WCNodeID; + if (editOps.NextWCIndex <= NodeData.WCNodeID) + editOps.NextWCIndex = NodeData.WCNodeID + 1; + + if (FClassnameIs(this, "info_node_air") || FClassnameIs(this, "info_node_air_hint")) + newNode.NodeType = NodeType.Air; + else if (FClassnameIs(this, "info_node_climb")) + newNode.NodeType = NodeType.Climb; + else + newNode.NodeType = NodeType.Ground; + + newNode.NodeInfo = (NodeInfoBits)(SpawnFlags << AI_Node.NODE_ENT_FLAGS_SHIFT); + Util.RemoveImmediate(this); + } } diff --git a/Game.Server/AI_NetworkManager.cs b/Game.Server/AI_NetworkManager.cs index c2b4ecb77..3bcb0682b 100644 --- a/Game.Server/AI_NetworkManager.cs +++ b/Game.Server/AI_NetworkManager.cs @@ -18,6 +18,7 @@ public static class AI_NetworkManagerGlobals public class AI_NetworkEditTools { public int[]? NodeIndexTable; + public int NextWCIndex; } [LinkEntityToClass("ai_network")] @@ -36,6 +37,8 @@ public static void InitializeAINetworks() { network.Spawn(); network.LoadNetworkGraph(); + NodeEnt.NodeCount = 0; + network.SetThink(network.DelayedInit); network.SetNextThink(gpGlobals.CurTime); } diff --git a/Game.Server/EntityList.cs b/Game.Server/EntityList.cs index af66b19c4..043bd7432 100644 --- a/Game.Server/EntityList.cs +++ b/Game.Server/EntityList.cs @@ -724,7 +724,7 @@ public override void FrameUpdatePostEntityThink() { engine.AllowImmediateEdictReuse(); // Reset node counter used during load - // NodeEnt.m_nNodeCount = 0; todo + NodeEnt.NodeCount = 0; RespawnEntitiesFilter filter = new(); MapEntity_ParseAllEntities(engine.GetMapEntitiesString(), filter, true); From db85c107b806b65d4ed056ea0b04bebcc214ad47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:32:57 +0300 Subject: [PATCH 07/73] Port AI dynamic links and link controllers --- Game.Server/AI_DynamicLink.cs | 374 +++++++++++++++++++++++++++++++ Game.Server/AI_Link.cs | 2 + Game.Server/AI_NetworkManager.cs | 84 ++++++- Game.Server/AI_Node.cs | 5 + 4 files changed, 463 insertions(+), 2 deletions(-) create mode 100644 Game.Server/AI_DynamicLink.cs diff --git a/Game.Server/AI_DynamicLink.cs b/Game.Server/AI_DynamicLink.cs new file mode 100644 index 000000000..2a6b2386b --- /dev/null +++ b/Game.Server/AI_DynamicLink.cs @@ -0,0 +1,374 @@ +using Game.Shared; + +using Source; +using Source.Common; + +using System.Numerics; +using System.Runtime.CompilerServices; + +namespace Game.Server; + +public enum DynamicLinkState +{ + Off = 0, + On = 1, +} + +[LinkEntityToClass("info_node_link_controller")] +public class AI_DynamicLinkController : ServerOnlyEntity +{ + public static readonly new DataMap DataDesc = new(typeof(AI_DynamicLinkController), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(LinkState), FieldType.Integer, "initialstate"), + DEFINE.KEYFIELD(nameof(AllowUse), FieldType.String, "AllowUse"), + DEFINE.KEYFIELD(nameof(InvertAllow), FieldType.Boolean, "InvertAllow"), + DEFINE.KEYFIELD(nameof(UseAirLinkRadius), FieldType.Boolean, "useairlinkradius"), + + DEFINE.INPUTFUNC(FieldType.Void, "TurnOn", nameof(InputTurnOn), (INPUTFUNCPTR)((self, data) => ((AI_DynamicLinkController)self).InputTurnOn(data))), + DEFINE.INPUTFUNC(FieldType.Void, "TurnOff", nameof(InputTurnOff), (INPUTFUNCPTR)((self, data) => ((AI_DynamicLinkController)self).InputTurnOff(data))), + DEFINE.INPUTFUNC(FieldType.String, "SetAllowed", nameof(InputSetAllowed), (INPUTFUNCPTR)((self, data) => ((AI_DynamicLinkController)self).InputSetAllowed(data))), + DEFINE.INPUTFUNC(FieldType.Boolean, "SetInvert", nameof(InputSetInvert), (INPUTFUNCPTR)((self, data) => ((AI_DynamicLinkController)self).InputSetInvert(data))), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public void GenerateLinksFromVolume() { + Assert(ControlledLinks.Count == 0); + + int nodeCount = g_pBigAINet!.NumNodes(); + AI_Node?[] nodes = g_pBigAINet.AccessNodes()!; + + float minDistCareSq; + if (UseAirLinkRadius) + minDistCareSq = (AI_Node.MAX_AIR_NODE_LINK_DIST + 0.1f) * (AI_Node.MAX_AIR_NODE_LINK_DIST + 0.1f); + else + minDistCareSq = (AI_Node.MAX_NODE_LINK_DIST + 0.1f) * (AI_Node.MAX_NODE_LINK_DIST + 0.1f); + + Vector3 origin = WorldSpaceCenter(); + CollisionProp().WorldSpaceAABB(out Vector3 absMins, out Vector3 absMaxs); + absMins -= new Vector3(1, 1, 1); + absMaxs += new Vector3(1, 1, 1); + + for (int i = 0; i < nodeCount; i++) { + AI_Node node = nodes[i]!; + ref readonly Vector3 nodeOrigin = ref node.GetOrigin(); + if (Vector3.DistanceSquared(origin, nodeOrigin) < minDistCareSq) { + int linkCount = node.NumLinks(); + for (int j = 0; j < linkCount; j++) { + int linkDest = node.GetLinkByIndex(j).DestNodeID(i); + if (linkDest > i) { + ref readonly Vector3 originOther = ref nodes[linkDest]!.GetOrigin(); + if (Vector3.DistanceSquared(origin, originOther) < minDistCareSq) { + Vector3 delta = originOther - nodeOrigin; + Vector3 invDelta = new(delta.X != 0 ? 1.0f / delta.X : float.MaxValue, delta.Y != 0 ? 1.0f / delta.Y : float.MaxValue, delta.Z != 0 ? 1.0f / delta.Z : float.MaxValue); + if (CollisionUtils.IsBoxIntersectingRay(absMins, absMaxs, nodeOrigin, delta, invDelta)) { + AI_DynamicLink link = (AI_DynamicLink)CreateEntityByName("info_node_link")!; + link.SrcID = i; + link.DestID = linkDest; + link.SrcEditID = g_pAINetworkManager!.GetEditOps().GetWCIdFromNodeId(link.SrcID); + link.DestEditID = g_pAINetworkManager.GetEditOps().GetWCIdFromNodeId(link.DestID); + link.LinkState = LinkState; + link.AllowUse = AllowUse; + link.InvertAllow = InvertAllow; + link.FixedUpIds = true; + link.NotSaved = true; + + link.Spawn(); + ControlledLinks.Add(new(link.GetRefEHandle())); + } + } + } + } + } + } + } + + public void InputTurnOn(InputData inputdata) { + for (int i = 0; i < ControlledLinks.Count; i++) { + if (ControlledLinks[i].Get() == null) { + ControlledLinks.RemoveAt(i); + if (i >= ControlledLinks.Count) + break; + } + ControlledLinks[i].Get()!.InputTurnOn(inputdata); + } + + LinkState = DynamicLinkState.On; + } + + public void InputTurnOff(InputData inputdata) { + for (int i = 0; i < ControlledLinks.Count; i++) { + if (ControlledLinks[i].Get() == null) { + ControlledLinks.RemoveAt(i); + if (i >= ControlledLinks.Count) + break; + } + ControlledLinks[i].Get()!.InputTurnOff(inputdata); + } + + LinkState = DynamicLinkState.Off; + } + + public void InputSetAllowed(InputData inputdata) { + AllowUse = inputdata.Value.StringID(); + for (int i = 0; i < ControlledLinks.Count; i++) { + if (ControlledLinks[i].Get() == null) { + ControlledLinks.RemoveAt(i); + if (i >= ControlledLinks.Count) + break; + } + ControlledLinks[i].Get()!.AllowUse = AllowUse; + } + } + + public void InputSetInvert(InputData inputdata) { + InvertAllow = inputdata.Value.Bool(); + for (int i = 0; i < ControlledLinks.Count; i++) { + if (ControlledLinks[i].Get() == null) { + ControlledLinks.RemoveAt(i); + if (i >= ControlledLinks.Count) + break; + } + ControlledLinks[i].Get()!.InvertAllow = InvertAllow; + } + } + + public readonly List> ControlledLinks = []; + public DynamicLinkState LinkState; + public string? AllowUse; + public bool InvertAllow; + public bool UseAirLinkRadius; +} + +[LinkEntityToClass("info_node_link")] +public class AI_DynamicLink : ServerOnlyEntity +{ + public static readonly new DataMap DataDesc = new(typeof(AI_DynamicLink), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(LinkState), FieldType.Integer, "initialstate"), + DEFINE.KEYFIELD(nameof(SrcEditID), FieldType.Integer, "startnode"), + DEFINE.KEYFIELD(nameof(DestEditID), FieldType.Integer, "endnode"), + DEFINE.KEYFIELD(nameof(LinkType), FieldType.Integer, "linktype"), + DEFINE.FIELD(nameof(InvertAllow), FieldType.Boolean), + DEFINE.KEYFIELD(nameof(AllowUse), FieldType.String, "AllowUse"), + + DEFINE.INPUTFUNC(FieldType.Void, "TurnOn", nameof(InputTurnOn), (INPUTFUNCPTR)((self, data) => ((AI_DynamicLink)self).InputTurnOn(data))), + DEFINE.INPUTFUNC(FieldType.Void, "TurnOff", nameof(InputTurnOff), (INPUTFUNCPTR)((self, data) => ((AI_DynamicLink)self).InputTurnOff(data))), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public static AI_DynamicLink? AllDynamicLinks; + public static bool gm_bInitialized; + + public AI_DynamicLink() { + NextDynamicLink = AllDynamicLinks; + AllDynamicLinks = this; + } + + public override void UpdateOnRemove() { + AI_DynamicLink? dynamicLink = AllDynamicLinks; + if (dynamicLink == this) + AllDynamicLinks = dynamicLink.NextDynamicLink; + else { + while (dynamicLink != null) { + if (dynamicLink.NextDynamicLink == this) { + dynamicLink.NextDynamicLink = dynamicLink.NextDynamicLink.NextDynamicLink; + break; + } + dynamicLink = dynamicLink.NextDynamicLink; + } + } + + base.UpdateOnRemove(); + } + + public static void GenerateControllerLinks() { + AI_DynamicLinkController? controller = null; + while ((controller = gEntList.NextEntByClass(controller)) != null) + controller.GenerateLinksFromVolume(); + } + + public static void InitDynamicLinks() { + if (g_pAINetworkManager!.GetEditOps().NodeIndexTable == null) { + Warning("ERROR: Trying initialize links with no WC ID table!\n"); + return; + } + + if (gm_bInitialized) + return; + + gm_bInitialized = true; + + bool updateZones = false; + + GenerateControllerLinks(); + + AI_DynamicLink? dynamicLink = AllDynamicLinks; + + while (dynamicLink != null) { + if (!dynamicLink.FixedUpIds) { + int srcID = g_pAINetworkManager.GetEditOps().GetNodeIdFromWCId(dynamicLink.SrcEditID); + if (srcID == -1) { + DevMsg($"ERROR: Dynamic link source WC node {dynamicLink.SrcEditID} not found\n"); + srcID = NO_NODE; + } + + int destID = g_pAINetworkManager.GetEditOps().GetNodeIdFromWCId(dynamicLink.DestEditID); + if (destID == -1) { + DevMsg($"ERROR: Dynamic link dest WC node {dynamicLink.DestEditID} not found\n"); + destID = NO_NODE; + } + + dynamicLink.SrcID = srcID; + dynamicLink.DestID = destID; + dynamicLink.FixedUpIds = true; + } + + if (dynamicLink.SrcID != NO_NODE && dynamicLink.DestID != NO_NODE) { + AI_HullBits hullBits = (AI_HullBits)dynamicLink.SpawnFlags & AI_HullBits.HullBitsMask; + if (hullBits != 0) { + short link = dynamicLink.FindLink(); + if (link == AI_Network.NO_LINK) { + AI_Node? node1 = g_pBigAINet!.GetNode(dynamicLink.SrcID); + AI_Node? node2 = g_pBigAINet.GetNode(dynamicLink.DestID); + + if (node1 != null && node2 != null) { + link = g_pBigAINet.CreateLink(dynamicLink.SrcID, dynamicLink.DestID); + if (link == AI_Network.NO_LINK) + DevMsg($"Failed to create dynamic link ({dynamicLink.SrcEditID} <--> {dynamicLink.DestEditID})\n"); + } + } + + if (link != AI_Network.NO_LINK) { + updateZones = true; + + ref AI_Link networkLink = ref g_pBigAINet!.GetLink(link); + for (int i = 0; i < (int)AI_HullType.NumHulls; i++) { + if (((int)hullBits & (1 << i)) != 0) + networkLink.AcceptedMoveTypes[i] = dynamicLink.LinkType; + } + } + } + + dynamicLink.SetLinkState(); + + dynamicLink = dynamicLink.NextDynamicLink; + } + else { + AI_DynamicLink badDynamicLink = dynamicLink; + + dynamicLink = dynamicLink.NextDynamicLink; + + Util.RemoveImmediate(badDynamicLink); + } + } + + if (updateZones) + g_AINetworkBuilder.InitZones(g_pBigAINet!); + } + + public static void ResetDynamicLinks() { + AI_DynamicLink? dynamicLink = AllDynamicLinks; + + while (dynamicLink != null) { + dynamicLink.SetLinkState(); + dynamicLink = dynamicLink.NextDynamicLink; + } + } + + public bool IsLinkValid() { + AI_Node node = g_pBigAINet!.GetNode(SrcID)!; + return !Unsafe.IsNullRef(ref node.GetLink(DestID)); + } + + public void InputTurnOn(InputData inputdata) { + if (LinkState == DynamicLinkState.Off) { + LinkState = DynamicLinkState.On; + SetLinkState(); + } + } + + public void InputTurnOff(InputData inputdata) { + if (LinkState == DynamicLinkState.On) { + LinkState = DynamicLinkState.Off; + SetLinkState(); + } + } + + public short FindLink() { + AI_Node? srcNode = g_pBigAINet!.GetNode(SrcID, false); + if (srcNode != null) { + int linkCount = srcNode.NumLinks(); + for (int i = 0; i < linkCount; i++) { + ref AI_Link link = ref srcNode.GetLinkByIndex(i); + + if ((link.SrcID == SrcID && link.DestID == DestID) || + (link.SrcID == DestID && link.DestID == SrcID)) { + return srcNode.Links[i]; + } + } + } + return AI_Network.NO_LINK; + } + + public override EntityCapabilities ObjectCaps() { + EntityCapabilities caps = base.ObjectCaps(); + + if (NotSaved) + caps |= EntityCapabilities.DontSave; + + return caps; + } + + public void SetLinkState() { + if (!gm_bInitialized) + return; + + if (SrcID == NO_NODE || DestID == NO_NODE) { + Vector3 pos = GetAbsOrigin(); + DevWarning($"ERROR: Dynamic link at {pos.X} {pos.Y} {pos.Z} pointing to invalid node ID!!\n"); + return; + } + + AI_Node? srcNode = g_pBigAINet!.GetNode(SrcID, false); + if (srcNode != null) { + short link = FindLink(); + if (link != AI_Network.NO_LINK) { + ref AI_Link networkLink = ref g_pBigAINet.GetLink(link); + networkLink.DynamicLink = this; + if (LinkState == DynamicLinkState.Off) + networkLink.LinkInfo |= LinkInfo.Off; + else + networkLink.LinkInfo &= ~LinkInfo.Off; + } + else + DevMsg($"Dynamic Link Error: ({GetDebugName()}) unable to form between nodes {SrcID} and {DestID}\n"); + } + } + + public static AI_DynamicLink? GetDynamicLink(int srcID, int dstID) { + AI_DynamicLink? dynamicLink = AllDynamicLinks; + + while (dynamicLink != null) { + if ((srcID == dynamicLink.SrcID && dstID == dynamicLink.DestID) || + (srcID == dynamicLink.DestID && dstID == dynamicLink.SrcID)) { + return dynamicLink; + } + + dynamicLink = dynamicLink.NextDynamicLink; + } + return null; + } + + public AI_DynamicLink? NextDynamicLink; + + public int SrcEditID; + public int DestEditID; + + public int SrcID = NO_NODE; + public int DestID = NO_NODE; + public DynamicLinkState LinkState = DynamicLinkState.Off; + public string? AllowUse; + public bool InvertAllow; + + public bool FixedUpIds; + public bool NotSaved; + public Capability LinkType = Capability.MoveGround; +} diff --git a/Game.Server/AI_Link.cs b/Game.Server/AI_Link.cs index 78b99901f..ca4ba997a 100644 --- a/Game.Server/AI_Link.cs +++ b/Game.Server/AI_Link.cs @@ -21,4 +21,6 @@ public AI_Link() { } public LinkInfo LinkInfo; public TimeUnit_t TimeStaleExpires; + + public AI_DynamicLink? DynamicLink; } diff --git a/Game.Server/AI_NetworkManager.cs b/Game.Server/AI_NetworkManager.cs index 3bcb0682b..458bfb078 100644 --- a/Game.Server/AI_NetworkManager.cs +++ b/Game.Server/AI_NetworkManager.cs @@ -13,12 +13,83 @@ namespace Game.Server; public static class AI_NetworkManagerGlobals { public static AI_NetworkManager? g_pAINetworkManager; + public static readonly AI_NetworkBuilder g_AINetworkBuilder = new(); } -public class AI_NetworkEditTools +public class AI_NetworkBuilder +{ + void FloodFillZone(AI_Node?[] nodes, AI_Node node, int zone) { + node.SetZone(zone); + + for (int link = 0; link < node.NumLinks(); link++) { + ref AI_Link nodeLink = ref node.GetLinkByIndex(link); + AI_Node linkedNode = (nodeLink.DestID == node.GetId()) ? nodes[nodeLink.SrcID]! : nodes[nodeLink.DestID]!; + if (linkedNode.GetZone() == (int)AI_ZoneIds.Unknown) + FloodFillZone(nodes, linkedNode, zone); + + Assert(linkedNode.GetZone() == node.GetZone() && node.GetZone() == zone); + } + } + + public void InitZones(AI_Network network) { + int nodeCount = network.NumNodes(); + AI_Node?[]? nodes = network.AccessNodes(); + + if (nodeCount == 0) + return; + + int i; + + for (i = 0; i < nodeCount; i++) + nodes![i]!.SetZone((int)AI_ZoneIds.Unknown); + + for (i = 0; i < nodeCount; i++) { + if (nodes![i]!.NumLinks() == 0) + nodes[i]!.SetZone((int)AI_ZoneIds.Solo); + } + + int curZone = (int)AI_ZoneIds.FirstZone; + + for (i = 0; i < nodeCount; i++) { + if (nodes![i]!.GetZone() == (int)AI_ZoneIds.Unknown) { + FloodFillZone(nodes, nodes[i]!, curZone); + curZone++; + } + } + } +} + +public class AI_NetworkEditTools(AI_Network network) { public int[]? NodeIndexTable; public int NextWCIndex; + + public int GetNodeIdFromWCId(int wcId) { + if (wcId == -1) + return -1; + + if (NodeIndexTable == null) { + DevMsg("ERROR: Trying to get WC ID with no table!\n"); + return -1; + } + + if (network.NumNodes() == 0) { + DevMsg("ERROR: Trying to get WC ID with no network!\n"); + return -1; + } + + for (int i = 0; i < network.NumNodes(); i++) { + if (NodeIndexTable[i] == wcId) + return i; + } + return -1; + } + + public int GetWCIdFromNodeId(int nodeId) { + if (nodeId == -1 || nodeId >= network.NumNodes()) + return -1; + return NodeIndexTable![nodeId]; + } } [LinkEntityToClass("ai_network")] @@ -28,6 +99,11 @@ public class AI_NetworkManager : PointEntity static readonly ConVar g_ai_norebuildgraph = new("ai_norebuildgraph", "0"); + public AI_NetworkManager() { + EditOps = new(Network); + AI_DynamicLink.gm_bInitialized = false; + } + public static void InitializeAINetworks() { AI_NetworkManager network = (AI_NetworkManager)CreateEntityByName("ai_network")!; g_pAINetworkManager = network; @@ -161,9 +237,11 @@ void LoadNetworkGraph(BinaryReader reader, ReadOnlySpan nrpFilename, int c DevMsg("\n** Should run \"Check For Problems\" on the VMF then verify dynamic links\n"); gm_fNetworksLoaded = true; + AI_DynamicLink.gm_bInitialized = false; } public static void DeleteAllAINetworks() { + AI_DynamicLink.gm_bInitialized = false; gm_fNetworksLoaded = false; g_pBigAINet = null; } @@ -184,6 +262,8 @@ void DelayedInit() { return; } + AI_DynamicLink.InitDynamicLinks(); + Initalized = true; if (g_AI_Manager.NumAIs() != 0 && g_pBigAINet!.NumNodes() == 0) @@ -199,6 +279,6 @@ void DelayedInit() { static bool gm_fNetworksLoaded; readonly AI_Network Network = new(); - readonly AI_NetworkEditTools EditOps = new(); + readonly AI_NetworkEditTools EditOps; bool Initalized; } diff --git a/Game.Server/AI_Node.cs b/Game.Server/AI_Node.cs index 59da3ef17..27da1cac1 100644 --- a/Game.Server/AI_Node.cs +++ b/Game.Server/AI_Node.cs @@ -45,6 +45,11 @@ public class AI_Node(AI_Network network, int id, Vector3 origin, float yaw) { public const int NODE_ENT_FLAGS_SHIFT = 5; + public const float MAX_NODE_LINK_DIST = 60 * 12; + public const float MAX_NODE_LINK_DIST_SQ = MAX_NODE_LINK_DIST * MAX_NODE_LINK_DIST; + public const float MAX_AIR_NODE_LINK_DIST = 120 * 12; + public const float MAX_AIR_NODE_LINK_DIST_SQ = MAX_AIR_NODE_LINK_DIST * MAX_AIR_NODE_LINK_DIST; + public int NumLinks() => Links.Count; public ref AI_Link GetLink(int destNodeId) { for (int link = 0; link < NumLinks(); link++) { From 847356d1a3e9e725ecb406257c9ca0d7f36c826a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:35:21 +0300 Subject: [PATCH 08/73] Port AI node per-hull positions and hint slot --- Game.Server/AI_Node.cs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/Game.Server/AI_Node.cs b/Game.Server/AI_Node.cs index 27da1cac1..e3551cebf 100644 --- a/Game.Server/AI_Node.cs +++ b/Game.Server/AI_Node.cs @@ -1,3 +1,5 @@ +using Source.Common.Mathematics; + using System.Numerics; using System.Runtime.CompilerServices; @@ -44,12 +46,16 @@ public enum NodeInfoBits : uint public class AI_Node(AI_Network network, int id, Vector3 origin, float yaw) { public const int NODE_ENT_FLAGS_SHIFT = 5; + public const float NODE_CLIMB_OFFSET = 8; public const float MAX_NODE_LINK_DIST = 60 * 12; public const float MAX_NODE_LINK_DIST_SQ = MAX_NODE_LINK_DIST * MAX_NODE_LINK_DIST; public const float MAX_AIR_NODE_LINK_DIST = 120 * 12; public const float MAX_AIR_NODE_LINK_DIST_SQ = MAX_AIR_NODE_LINK_DIST * MAX_AIR_NODE_LINK_DIST; + public AI_Hint? GetHint() => Hint; + public void SetHint(AI_Hint? hint) => Hint = hint; + public int NumLinks() => Links.Count; public ref AI_Link GetLink(int destNodeId) { for (int link = 0; link < NumLinks(); link++) { @@ -71,6 +77,34 @@ public ref AI_Link GetLink(int destNodeId) { public int GetId() => ID; + public Vector3 GetPosition(AI_HullType hull) { + if (NodeType == NodeType.Climb) { + float shift = (0.5f * NAI_Hull.Length(hull)) + NODE_CLIMB_OFFSET; + + Vector3 offsetDir = new(MathF.Cos(MathLib.DEG2RAD(Yaw)), MathF.Sin(MathLib.DEG2RAD(Yaw)), 0); + + Vector3 origin; + if ((NodeInfo & NodeInfoBits.ClimbOffForward) != 0) + origin = Origin + (shift * offsetDir); + else if ((NodeInfo & NodeInfoBits.ClimbOffLeft) != 0) { + Vector3 leftDir = Vector3.Cross(offsetDir, Vector3.UnitZ); + origin = Origin - (2 * shift * leftDir) - (shift * offsetDir); + } + else if ((NodeInfo & NodeInfoBits.ClimbOffRight) != 0) { + Vector3 leftDir = Vector3.Cross(offsetDir, Vector3.UnitZ); + origin = Origin + (2 * shift * leftDir) - (shift * offsetDir); + } + else + origin = Origin - (shift * offsetDir); + + return new(origin.X, origin.Y, origin.Z + VOffset[(int)hull]); + } + else if (NodeType == NodeType.Ground) + return new(Origin.X, Origin.Y, Origin.Z + VOffset[(int)hull]); + else + return Origin; + } + public ref readonly Vector3 GetOrigin() => ref Origin; public float GetYaw() => Yaw; @@ -111,5 +145,6 @@ public void AddLink(short newLink) { public readonly List Links = new(4); public TimeUnit_t NextUseTime; + public AI_Hint? Hint; public int FirstShuffledLink; } From 4a70081778e549d8562977ef594451ed87a322dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:37:48 +0300 Subject: [PATCH 09/73] Port NPC step height and stand-on checks --- Game.Server/AI_BaseNPC.cs | 15 +++++++++++++++ Game.Server/AI_Navigator.cs | 13 +++++++++++++ Game.Server/AI_Route.cs | 2 ++ 3 files changed, 30 insertions(+) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 50a4d8d62..f2cf72ab4 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -2814,6 +2814,21 @@ public virtual bool QuerySeeEntity(BaseEntity entity, bool onlyHateOrFearIfNPC = public ref readonly Vector3 GetHullMins() => ref NAI_Hull.Mins(GetHullType()); public ref readonly Vector3 GetHullMaxs() => ref NAI_Hull.Maxs(GetHullType()); + public virtual float StepHeight() => 18.0f; + public float GetStepDownMultiplier() => Navigator!.GetStepDownMultiplier(); + + public override bool CanStandOn(BaseEntity? surface) { + if (!surface!.IsAIWalkable()) + return false; + + AI_Navigator navigator = GetNavigator()!; + + if (navigator.IsGoalActive() && surface == navigator.GetGoalTarget()) + return false; + + return base.CanStandOn(surface); + } + public virtual Vector3 GetCrouchEyeOffset() => new(0, 0, 40); public override bool IsMoving() => GetNavigator()!.IsGoalSet(); diff --git a/Game.Server/AI_Navigator.cs b/Game.Server/AI_Navigator.cs index b10250e70..4765a426a 100644 --- a/Game.Server/AI_Navigator.cs +++ b/Game.Server/AI_Navigator.cs @@ -76,6 +76,19 @@ public bool ClearGoal() { public bool IsGoalActive() => GetPath() != null && !GetPath().IsEmpty(); + public BaseEntity? GetGoalTarget() => GetPath().GetTarget(); + + public float GetStepDownMultiplier() { + BaseEntity? bigStepGroundEnt = BigStepGroundEnt.Get(); + if (bigStepGroundEnt != null) { + if (!bigStepGroundEnt.IsPlayer()) + return 2.6f; + else + return 10.0f; + } + return 1.0f; + } + public float GetIdealSpeed() => throw new NotImplementedException(); public virtual float CalcYawSpeed() { diff --git a/Game.Server/AI_Route.cs b/Game.Server/AI_Route.cs index 1603fbb58..0f1cdcdb5 100644 --- a/Game.Server/AI_Route.cs +++ b/Game.Server/AI_Route.cs @@ -48,6 +48,8 @@ public Activity GetArrivalActivity() { public NavGoalType GoalType() => GoalTypeValue; + public BaseEntity? GetTarget() => Target.Get(); + public void Clear() { Waypoints.RemoveAll(); From f0206296a17f5e4dd4cdf6937cdb14c37a37ca60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:39:56 +0300 Subject: [PATCH 10/73] Port CAI_MoveProbe::CheckStandPosition --- Game.Server/AI_MoveProbe.cs | 67 +++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/Game.Server/AI_MoveProbe.cs b/Game.Server/AI_MoveProbe.cs index 8d721ae9c..eb004b40d 100644 --- a/Game.Server/AI_MoveProbe.cs +++ b/Game.Server/AI_MoveProbe.cs @@ -4,6 +4,7 @@ using Source; using Source.Common; +using Source.Common.Commands; using Source.Common.Formats.BSP; using System.Numerics; @@ -13,6 +14,8 @@ namespace Game.Server; public static class AI_MoveProbeGlobals { public static float MOVE_HEIGHT_EPSILON = 0.0625f; + + public static readonly ConVar ai_strong_optimizations_no_checkstand = new("ai_strong_optimizations_no_checkstand", "0"); } public class AI_MoveProbe : AI_Component @@ -90,6 +93,70 @@ public bool FloorPoint(in Vector3 start, Mask collisionMask, float startZ, float return true; } + public bool CheckStandPosition(in Vector3 start, Mask collisionMask) { + if ((GetOuter()!.CapabilitiesGet() & Capability.SkipNavGroundCheck) != 0) + return true; + + if (ai_strong_optimizations_no_checkstand.GetBool()) + return true; + + Vector3 contactMin, contactMax; + + Vector3 vecUp = new(start.X, start.Y, start.Z + 0.1f); + Vector3 vecDown = new(start.X, start.Y, start.Z - StepHeight() * GetOuter()!.GetStepDownMultiplier()); + + Vector3 hullMins = GetOuter()!.WorldAlignMins(); + Vector3 hullMaxs = GetOuter()!.WorldAlignMaxs(); + + if (hullMaxs == vec3_origin && hullMins == hullMaxs) { + hullMins = GetOuter()!.GetHullMins(); + hullMaxs = GetOuter()!.GetHullMaxs(); + } + + contactMin.X = hullMins.X * 0.75f + hullMaxs.X * 0.25f; + contactMax.X = hullMins.X * 0.25f + hullMaxs.X * 0.75f; + contactMin.Y = hullMins.Y * 0.75f + hullMaxs.Y * 0.25f; + contactMax.Y = hullMins.Y * 0.25f + hullMaxs.Y * 0.75f; + contactMin.Z = hullMins.Z; + contactMax.Z = hullMins.Z; + + Trace trace1, trace2; + + if (!GetOuter()!.IsFlaggedEfficient()) { + Vector3 hullBottomCenter = new(0, 0, hullMins.Z); + + TraceHull(vecUp, vecDown, contactMin, hullBottomCenter, collisionMask, out trace1); + if (trace1.Fraction != 1.0f && CanStandOn(trace1.Ent)) { + TraceHull(vecUp, vecDown, hullBottomCenter, contactMax, collisionMask, out trace2); + if (trace2.Fraction != 1.0f && (trace1.Ent == trace2.Ent || CanStandOn(trace2.Ent))) + return true; + } + + Vector3 testMin = new(contactMin.X, 0, hullMins.Z); + Vector3 testMax = new(0, contactMax.Y, hullMins.Z); + + TraceHull(vecUp, vecDown, testMin, testMax, collisionMask, out trace1); + if (trace1.Fraction != 1.0f && CanStandOn(trace1.Ent)) { + testMin = new(0, contactMin.Y, hullMins.Z); + testMax = new(contactMax.X, 0, hullMins.Z); + TraceHull(vecUp, vecDown, testMin, testMax, collisionMask, out trace2); + if (trace2.Fraction != 1.0f && (trace1.Ent == trace2.Ent || CanStandOn(trace2.Ent))) + return true; + } + } + else { + TraceHull(vecUp, vecDown, contactMin, contactMax, collisionMask, out trace1); + if (trace1.Fraction != 1.0f && CanStandOn(trace1.Ent)) + return true; + } + + return false; + } + + public bool CanStandOn(BaseEntity? surface) => GetOuter()!.CanStandOn(surface); + + public float StepHeight() => GetOuter()!.StepHeight(); + public void ClearBlockingEntity() => LastBlockingEnt.Set(null); public BaseEntity? GetBlockingEntity() => LastBlockingEnt.Get(); From 7308d7c9a4479c4778eb76ea2cad19ec0c88ee35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:42:13 +0300 Subject: [PATCH 11/73] Port navigator CanFitAtNode and CanFitAtPosition --- Game.Server/AI_Navigator.cs | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Game.Server/AI_Navigator.cs b/Game.Server/AI_Navigator.cs index 4765a426a..68570f3e4 100644 --- a/Game.Server/AI_Navigator.cs +++ b/Game.Server/AI_Navigator.cs @@ -2,6 +2,10 @@ using Game.Shared; +using Source; +using Source.Common; +using Source.Common.Formats.BSP; + using System.Numerics; namespace Game.Server; @@ -78,6 +82,47 @@ public bool ClearGoal() { public BaseEntity? GetGoalTarget() => GetPath().GetTarget(); + public bool CanFitAtNode(int nodeNum, Mask collisionMask = Mask.NPCSolidBrushOnly) { + if (GetNetwork() == null) { + DevMsg("CanFitAtNode() called with no network!\n"); + return false; + } + + AI_Node testNode = GetNetwork()!.GetNode(nodeNum)!; + Vector3 startPos = testNode.GetPosition(GetOuter()!.GetHullType()); + + if (testNode.NodeType == NodeType.Ground) { + if (!GetMoveProbe()!.CheckStandPosition(startPos, collisionMask)) + return false; + } + + if (testNode.NodeType == NodeType.Climb && + (testNode.NodeInfo & (NodeInfoBits.ClimbBottom | NodeInfoBits.ClimbExit)) != 0) { + if (!GetMoveProbe()!.CheckStandPosition(startPos, collisionMask)) + return false; + } + + if (!CanFitAtPosition(startPos, collisionMask)) { + startPos.Z += GetOuter()!.StepHeight(); + if (!CanFitAtPosition(startPos, collisionMask)) + return false; + } + + return true; + } + + public bool CanFitAtPosition(in Vector3 startPos, Mask collisionMask, bool ignoreTransients = false, bool allowPlayerAvoid = true) { + TraceFilterNav traceFilter = new(GetOuter()!, ignoreTransients, GetOuter(), CollisionGroup.None, allowPlayerAvoid); + + Vector3 endPos = startPos; + endPos.Z += 0.01f; + Util.TraceHull(startPos, endPos, GetOuter()!.GetHullMins(), GetOuter()!.GetHullMaxs(), collisionMask, ref traceFilter, out Trace tr); + + if (tr.StartSolid) + return false; + return true; + } + public float GetStepDownMultiplier() { BaseEntity? bigStepGroundEnt = BigStepGroundEnt.Get(); if (bigStepGroundEnt != null) { From d857afbe7ccea8871c391c98104094f3bb227273 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:44:31 +0300 Subject: [PATCH 12/73] Port NPC unusable node check and hint groups --- Game.Server/AI_BaseNPC.cs | 17 +++++++++++++++++ Game.Server/AI_Hint.cs | 1 + 2 files changed, 18 insertions(+) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index f2cf72ab4..5fadf0577 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -282,6 +282,8 @@ public static ReadOnlySpan GetActivityName(Activity actID) { public static readonly new DataMap DataDesc = new(typeof(AI_BaseNPC), BaseEntity.DataDesc, [ DEFINE.KEYFIELD(nameof(SpawnEquipment), FieldType.String, "additionalequipment"), + DEFINE.KEYFIELD(nameof(HintGroup), FieldType.String, "hintgroup"), + DEFINE.KEYFIELD(nameof(HintGroupNavLimiting), FieldType.Boolean, "hintlimiting"), ]); public override DataMap? GetDataDescMap() => DataDesc; @@ -2829,6 +2831,21 @@ public override bool CanStandOn(BaseEntity? surface) { return base.CanStandOn(surface); } + public virtual bool IsUnusableNode(int nodeID, AI_Hint? hint) { + if (HintGroupNavLimiting && !string.IsNullOrEmpty(HintGroup)) { + if (hint == null || hint.GetGroup() != GetHintGroup()) + return true; + } + return false; + } + + public string? GetHintGroup() => HintGroup; + + public virtual Vector3 GetNodeViewOffset() => GetViewOffset(); + + public string? HintGroup; + public bool HintGroupNavLimiting; + public virtual Vector3 GetCrouchEyeOffset() => new(0, 0, 40); public override bool IsMoving() => GetNavigator()!.IsGoalSet(); diff --git a/Game.Server/AI_Hint.cs b/Game.Server/AI_Hint.cs index ff7916823..1c2c060b6 100644 --- a/Game.Server/AI_Hint.cs +++ b/Game.Server/AI_Hint.cs @@ -3,6 +3,7 @@ namespace Game.Server; public class AI_Hint : ServerOnlyEntity { public short HintType() => throw new NotImplementedException(); + public string? GetGroup() => throw new NotImplementedException(); public void Unlock(float delay) => throw new NotImplementedException(); } From eaa32a8660389ce608082c8d1e929eb3adc77fe3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:46:52 +0300 Subject: [PATCH 13/73] Port AI network NearestNodeToPoint and node cache --- Game.Server/AI_Network.cs | 277 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 277 insertions(+) diff --git a/Game.Server/AI_Network.cs b/Game.Server/AI_Network.cs index 55d52d3dd..d1517e66e 100644 --- a/Game.Server/AI_Network.cs +++ b/Game.Server/AI_Network.cs @@ -1,5 +1,12 @@ global using static Game.Server.AI_NetworkGlobals; +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Formats.BSP; + using System.Numerics; using System.Runtime.InteropServices; @@ -8,12 +15,282 @@ namespace Game.Server; public static class AI_NetworkGlobals { public static AI_Network? g_pBigAINet; + + public static readonly ConVar ai_no_node_cache = new("ai_no_node_cache", "0"); +} + +public interface INearestNodeFilter +{ + bool IsValid(AI_Node node); + bool ShouldContinue(); +} + +public record struct AI_NearNode(int NodeIndex, float Dist); + +readonly struct NodeFilter(AI_BaseNPC? npc, Vector3 pos) +{ + readonly Capability Capabilities = npc?.CapabilitiesGet() ?? 0; + + public bool NodeIsValid(AI_Node node) { + if (node.NodeType == NodeType.Deleted) + return false; + + if (npc == null) + return true; + + if (npc.GetNavType() == Navigation.Fly && node.NodeType != NodeType.Air) + return false; + + if ((node.NodeType == NodeType.Air && (Capabilities & Capability.MoveFly) == 0) || + (node.NodeType == NodeType.Ground && (Capabilities & Capability.MoveGround) == 0)) + return false; + + if (npc.IsUnusableNode(node.GetId(), node.GetHint())) + return false; + + return true; + } + + public float NodeDistanceSqr(AI_Node node) { + if (npc != null) + return (node.GetPosition(npc.GetHullType()) - pos).LengthSquared(); + else + return (node.GetOrigin() - pos).LengthSquared(); + } } public class AI_Network { public const int AI_MAX_NODE_LINKS = 30; public const int MAX_NODES = 1500; + public const int NOT_CACHED = -2; + + const int MAX_NEAR_NODES = 10; + const int NEARNODE_CACHE_SIZE = 32; + const int NEARNODE_CACHE_LIFE = 10; + + struct NearNodeCache + { + public Vector3 TestPosition; + public TimeUnit_t Expiration; + public int Node; + public AI_HullType Hull; + } + + public AI_Network() { + NearestCacheNext = NEARNODE_CACHE_SIZE - 1; + for (int node = 0; node < NEARNODE_CACHE_SIZE; node++) { + NearestCache[node].Hull = AI_HullType.None; + NearestCache[node].Expiration = 1.175494351e-38f; + } + } + + int ListNodesInBox(Span list, in Vector3 mins, in Vector3 maxs, in NodeFilter filter) { + int count = 0; + + for (int node = 0; node < NodeCount; node++) { + AI_Node aiNode = AINode![node]!; + ref readonly Vector3 origin = ref aiNode.GetOrigin(); + if (origin.X < mins.X || origin.X > maxs.X || + origin.Y < mins.Y || origin.Y > maxs.Y || + origin.Z < mins.Z || origin.Z > maxs.Z) + continue; + + if (!filter.NodeIsValid(aiNode)) + continue; + + float dist = filter.NodeDistanceSqr(aiNode); + + if (count == list.Length) { + if (dist >= list[count - 1].Dist) + continue; + count--; + } + + int insert = count; + while (insert > 0 && list[insert - 1].Dist > dist) { + list[insert] = list[insert - 1]; + insert--; + } + list[insert] = new(node, dist); + count++; + } + + return count; + } + + public int NearestNodeToPoint(AI_BaseNPC? npc, in Vector3 origin, bool checkVisibility = true, INearestNodeFilter? filter = null) { + if (NodeCount == 0) + return NO_NODE; + + int cachedNode = GetCachedNearestNode(origin, npc, out int cachePos); + if (cachedNode != NO_NODE) { + if (checkVisibility) { + Vector3 testLoc = (npc != null) ? + AINode![cachedNode]!.GetPosition(npc.GetHullType()) + npc.GetViewOffset() : + AINode![cachedNode]!.GetOrigin(); + + if (!IsVisible(npc, origin, testLoc)) + cachedNode = NO_NODE; + } + + if (cachedNode != NO_NODE && (filter == null || filter.IsValid(AINode![cachedNode]!))) { + NearestCache[cachePos].Expiration = gpGlobals.CurTime + NEARNODE_CACHE_LIFE; + return cachedNode; + } + } + + NodeFilter nodeFilter = new(npc, origin); + + Span list = stackalloc AI_NearNode[MAX_NEAR_NODES]; + + Vector3 ext = new(AI_Node.MAX_NODE_LINK_DIST, AI_Node.MAX_NODE_LINK_DIST, AI_Node.MAX_NODE_LINK_DIST); + if (npc != null && (npc.CapabilitiesGet() & Capability.MoveFly) != 0) + ext = new(AI_Node.MAX_AIR_NODE_LINK_DIST, AI_Node.MAX_AIR_NODE_LINK_DIST, AI_Node.MAX_AIR_NODE_LINK_DIST); + + int count = ListNodesInBox(list, origin - ext, origin + ext, nodeFilter); + + for (int i = 0; i < count; i++) { + int smallest = list[i].NodeIndex; + + if (smallest == cachedNode) + continue; + + if (npc != null && !npc.GetNavigator()!.CanFitAtNode(smallest)) + continue; + + if (checkVisibility) { + Vector3 testLoc = (npc != null) ? + AINode![smallest]!.GetPosition(npc.GetHullType()) + npc.GetNodeViewOffset() : + AINode![smallest]!.GetOrigin(); + + Vector3 visOrigin = origin + new Vector3(0, 0, 1); + + if (!IsVisible(npc, visOrigin, testLoc)) + continue; + } + + if (filter != null) { + if (!filter.IsValid(AINode![smallest]!)) { + if (!filter.ShouldContinue()) + break; + continue; + } + } + + SetCachedNearestNode(origin, smallest, (npc != null) ? npc.GetHullType() : AI_HullType.None); + + return smallest; + } + + SetCachedNearestNode(origin, NO_NODE, (npc != null) ? npc.GetHullType() : AI_HullType.None); + + return NO_NODE; + } + + static bool IsVisible(AI_BaseNPC? npc, in Vector3 start, in Vector3 end) { + Trace tr; + if (npc != null) { + TraceFilterNav traceFilter = new(npc, true, npc, CollisionGroup.None); + Util.TraceLine(start, end, Mask.NPCSolidBrushOnly, ref traceFilter, out tr); + } + else + Util.TraceLine(start, end, Mask.NPCSolidBrushOnly, null, CollisionGroup.None, out tr); + + return tr.Fraction == 1.0f; + } + + public int NearestNodeToPoint(in Vector3 position, bool checkVisibility = true) => NearestNodeToPoint(null, position, checkVisibility); + + int GetCachedNode(in Vector3 checkPos, AI_HullType hull, out int cachePos) { + if (ai_no_node_cache.GetBool()) { + cachePos = -1; + return NOT_CACHED; + } + + int newest = NearestCacheNext + 1; + for (int i = 0; i < NEARNODE_CACHE_SIZE; i++) { + int current = (newest + i) % NEARNODE_CACHE_SIZE; + if (NearestCache[current].Hull == hull && NearestCache[current].Expiration > gpGlobals.CurTime) { + if ((NearestCache[current].TestPosition - checkPos).LengthSquared() < 24.0f * 24.0f) { + cachePos = current; + return NearestCache[current].Node; + } + } + } + + cachePos = -1; + return NOT_CACHED; + } + + int GetCachedNearestNode(in Vector3 checkPos, AI_BaseNPC? npc, out int cachePos) { + if (npc != null) { + NodeFilter filter = new(npc, checkPos); + + int nodeID = GetCachedNode(checkPos, npc.GetHullType(), out cachePos); + if (nodeID >= 0) { + if (filter.NodeIsValid(AINode![nodeID]!) && npc.GetNavigator()!.CanFitAtNode(nodeID)) + return nodeID; + } + } + else + cachePos = -1; + return NO_NODE; + } + + void SetCachedNearestNode(in Vector3 checkPos, int nodeID, AI_HullType hull) { + if (ai_no_node_cache.GetBool()) + return; + + NearestCache[NearestCacheNext].TestPosition = checkPos; + NearestCache[NearestCacheNext].Node = nodeID; + NearestCache[NearestCacheNext].Hull = hull; + NearestCache[NearestCacheNext].Expiration = gpGlobals.CurTime + NEARNODE_CACHE_LIFE; + + NearestCacheNext--; + if (NearestCacheNext < 0) + NearestCacheNext = NEARNODE_CACHE_SIZE - 1; + } + + public Vector3 GetNodePosition(AI_HullType hull, int nodeID) { + if (AINode == null) { + Assert(false); + return vec3_origin; + } + + if ((nodeID < 0) || (nodeID > NodeCount)) { + Assert(false); + return vec3_origin; + } + + return AINode[nodeID]!.GetPosition(hull); + } + + public Vector3 GetNodePosition(BaseCombatCharacter? npc, int nodeID) { + if (npc == null) { + Assert(false); + return vec3_origin; + } + + return GetNodePosition(npc.GetHullType(), nodeID); + } + + public float GetNodeYaw(int nodeID) { + if (AINode == null) { + Assert(false); + return 0.0f; + } + + if ((nodeID < 0) || (nodeID > NodeCount)) { + Assert(false); + return 0.0f; + } + + return AINode[nodeID]!.GetYaw(); + } + + readonly NearNodeCache[] NearestCache = new NearNodeCache[NEARNODE_CACHE_SIZE]; + int NearestCacheNext; public AI_Node AddNode(Vector3 origin, float yaw) { if (AINode == null || AINode[0] == null) From 5b2bf1b5385d215a16de2c6d1acf7bc86b6217a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:53:38 +0300 Subject: [PATCH 14/73] Port AI move result types and route distance helpers --- Game.Server/AI_MoveTypes.cs | 77 +++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Game.Server/AI_MoveTypes.cs diff --git a/Game.Server/AI_MoveTypes.cs b/Game.Server/AI_MoveTypes.cs new file mode 100644 index 000000000..63071787f --- /dev/null +++ b/Game.Server/AI_MoveTypes.cs @@ -0,0 +1,77 @@ +global using static Game.Server.AI_MoveTypesGlobals; + +using System.Numerics; + +namespace Game.Server; + +public enum AIMoveResult +{ + BlockedEntity = -1, + BlockedWorld = -2, + BlockedNPC = -3, + Illegal = -4, + + Ok = 0, + + ChangeType, +} + +public enum StepGroundTest +{ + DontCheckGround = 0, + OnValidGround, + OnInvalidGround, +} + +public struct AIMoveTrace +{ + public AIMoveResult Status; + public Vector3 EndPosition; + public Vector3 HitNormal; + public BaseEntity? Obstruction; + public float TotalDist; + public float DistObstructed; + public Vector3 JumpVelocity; + public float StepUpDistance; +} + +public static class AI_MoveTypesGlobals +{ + public static bool IsMoveBlocked(AIMoveResult moveResult) => moveResult < AIMoveResult.Ok; + public static bool IsMoveBlocked(in AIMoveTrace moveTrace) => moveTrace.Status < AIMoveResult.Ok; + + public static AIMoveResult AIComputeBlockerMoveResult(BaseEntity blocker) { + if (blocker.MyNPCPointer() != null) + return AIMoveResult.BlockedNPC; + else if (blocker.EntIndex() == 0) + return AIMoveResult.BlockedWorld; + return AIMoveResult.BlockedEntity; + } + + public static float ComputePathDistance(Navigation navType, in Vector3 start, in Vector3 end) { + if (navType == Navigation.Ground) { + Vector2 delta = new(end.X - start.X, end.Y - start.Y); + return delta.Length(); + } + else + return (end - start).Length(); + } + + public static Vector3 ComputePathVector(Navigation navType, in Vector3 start, in Vector3 end) { + if (navType == Navigation.Ground) + return new(end.X - start.X, end.Y - start.Y, 0.0f); + else + return end - start; + } + + public static float ComputePathDirection(Navigation navType, in Vector3 start, in Vector3 end, out Vector3 direction) { + direction = end - start; + if (navType == Navigation.Ground) + direction.Z = 0.0f; + + float length = direction.Length(); + if (length != 0.0f) + direction /= length; + return length; + } +} From b49b0d29a870a52562f7fb29956fff9956943b57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 16:58:14 +0300 Subject: [PATCH 15/73] Port nav ignore and NPC jump legality helpers --- Game.Server/AI_BaseNPC.cs | 27 +++++++++++++++++++++++++++ Game.Server/BaseEntity.cs | 8 ++++++++ 2 files changed, 35 insertions(+) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 5fadf0577..7bac3343a 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -2818,6 +2818,33 @@ public virtual bool QuerySeeEntity(BaseEntity entity, bool onlyHateOrFearIfNPC = public virtual float StepHeight() => 18.0f; public float GetStepDownMultiplier() => Navigator!.GetStepDownMultiplier(); + public virtual float GetMaxJumpSpeed() => 350.0f; + public virtual float GetJumpGravity() => 1.0f; + + public float GetHullHeight() => NAI_Hull.Height(GetHullType()); + + public bool IsJumpLegal(in Vector3 startPos, in Vector3 apex, in Vector3 endPos, float maxUp, float maxDown, float maxDist) { + if ((endPos.Z - startPos.Z) > maxUp + 0.1f) + return false; + if ((startPos.Z - endPos.Z) > maxDown + 0.1f) + return false; + + if ((apex.Z - startPos.Z) > maxUp * 1.25f) + return false; + + float dist = (startPos - endPos).Length(); + if (dist > maxDist + 0.1f) + return false; + return true; + } + + public virtual bool IsJumpLegal(in Vector3 startPos, in Vector3 apex, in Vector3 endPos) { + const float MAX_JUMP_RISE = 80.0f; + const float MAX_JUMP_DISTANCE = 250.0f; + const float MAX_JUMP_DROP = 192.0f; + + return IsJumpLegal(startPos, apex, endPos, MAX_JUMP_RISE, MAX_JUMP_DROP, MAX_JUMP_DISTANCE); + } public override bool CanStandOn(BaseEntity? surface) { if (!surface!.IsAIWalkable()) diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 0c851bc3c..26684de8b 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -3248,6 +3248,14 @@ public virtual void GetVectors(out Vector3 forward, out Vector3 right, out Vecto public TimeUnit_t NavIgnoreUntilTime; + public void SetNavIgnore(float duration = float.MaxValue) { + TimeUnit_t navIgnoreUntilTime = (duration == float.MaxValue) ? float.MaxValue : gpGlobals.CurTime + duration; + if (navIgnoreUntilTime > NavIgnoreUntilTime) + NavIgnoreUntilTime = navIgnoreUntilTime; + } + + public void ClearNavIgnore() => NavIgnoreUntilTime = 0; + public bool IsNavIgnored() => gpGlobals.CurTime <= NavIgnoreUntilTime; public BasePlayer? AI_GetClosestPlayer() { From a4deea89f1031b7b0f6366704e0a5af6f3c095ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:06:41 +0300 Subject: [PATCH 16/73] Fix StopwatchBase Expired ignoring running state --- Game.Server/SimTimer.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Game.Server/SimTimer.cs b/Game.Server/SimTimer.cs index 0f392f165..ed6f7ac9a 100644 --- a/Game.Server/SimTimer.cs +++ b/Game.Server/SimTimer.cs @@ -75,6 +75,8 @@ public StopwatchBase() { public void Stop() => IsRunning = false; + public new bool Expired() => IsRunning && base.Expired(); + protected bool IsRunning; public static readonly new DataMap DataDesc = new(typeof(StopwatchBase), SimpleSimTimer.DataDesc, [ From b71a5805c94eb4541824bb44c80d1cc647fafac0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:13:27 +0300 Subject: [PATCH 17/73] Fix FVisible missing ai_ignoreplayers check for NPCs --- Game.Server/BaseEntity.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 26684de8b..eabeb63c9 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -3202,6 +3202,9 @@ public virtual bool FVisible(BaseEntity entity, Mask traceMask = Mask.BlockLOS) if ((entity.GetFlags() & EntityFlags.NoTarget) != 0) return false; + if (IsNPC() && entity.IsPlayer() && AI_BaseNPCGlobals.g_IgnorePlayers.GetBool()) + return false; + Vector3 vecLookerOrigin = EyePosition(); Vector3 vecTargetOrigin = entity.EyePosition(); From 3ff10d5158c5217391bbba558dda072508b31f99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:21:52 +0300 Subject: [PATCH 18/73] Fix GetStoppedActivity ignoring arrival activity --- Game.Server/AI_BaseNPC.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 7bac3343a..d671f9161 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -3519,7 +3519,16 @@ public virtual void OnScheduleChange() { public bool IsActivityFinished() => IsSequenceFinished() && (GetSequence() == IdealSequence); - public Activity GetStoppedActivity() => Activity.ACT_IDLE; + public Activity GetStoppedActivity() { + if (GetNavigator()!.IsGoalActive()) { + Activity activity = GetNavigator()!.GetArrivalActivity(); + + if (activity > Activity.ACT_RESET) + return activity; + } + + return Activity.ACT_IDLE; + } public void MaintainActivity() { if (LifeState == (int)Source.LifeState.Dead) From c122f931b815f873f15876856a5e7719b4b76868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:28:09 +0300 Subject: [PATCH 19/73] Fix unregistered AI_BaseNPC hearing and lost-enemy outputs --- Game.Server/AI_BaseNPC.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index d671f9161..5a52e3862 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -284,6 +284,12 @@ public static ReadOnlySpan GetActivityName(Activity actID) { DEFINE.KEYFIELD(nameof(SpawnEquipment), FieldType.String, "additionalequipment"), DEFINE.KEYFIELD(nameof(HintGroup), FieldType.String, "hintgroup"), DEFINE.KEYFIELD(nameof(HintGroupNavLimiting), FieldType.Boolean, "hintlimiting"), + + DEFINE.OUTPUT(nameof(OnHearWorld), "OnHearWorld", eventFuncs), + DEFINE.OUTPUT(nameof(OnHearPlayer), "OnHearPlayer", eventFuncs), + DEFINE.OUTPUT(nameof(OnHearCombat), "OnHearCombat", eventFuncs), + DEFINE.OUTPUT(nameof(OnLostEnemy), "OnLostEnemy", eventFuncs), + DEFINE.OUTPUT(nameof(OnLostPlayer), "OnLostPlayer", eventFuncs), ]); public override DataMap? GetDataDescMap() => DataDesc; From 3a2c009e3c3256226029175cdec5e1b92a2dafe9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:33:47 +0300 Subject: [PATCH 20/73] Port studio movement data and sequence velocity queries --- Source.Common/BoneSetup.cs | 118 ++++++++++++++++++++++++++++++++++++- Source.Common/Studio.cs | 28 +++++++++ 2 files changed, 145 insertions(+), 1 deletion(-) diff --git a/Source.Common/BoneSetup.cs b/Source.Common/BoneSetup.cs index b03709b81..9cb878f64 100644 --- a/Source.Common/BoneSetup.cs +++ b/Source.Common/BoneSetup.cs @@ -1648,9 +1648,125 @@ private static bool Studio_AnimPosition(MStudioAnimDesc anim, float cycle, out V float flFrame = cycle * (anim.NumFrames - 1); for (int i = 0; i < anim.NumMovements; i++) { - // todo + MStudioMovement pmove = anim.Movement(i); + + if (pmove.EndFrame >= flFrame) { + float f = (flFrame - prevframe) / (pmove.EndFrame - prevframe); + + float d = pmove.V0 * f + 0.5f * (pmove.V1 - pmove.V0) * f * f; + + vecPos = vecPos + d * pmove.Vector; + vecAngle.Y = vecAngle.Y * (1 - f) + pmove.Angle * f; + if (iLoops != 0) { + MStudioMovement lastMove = anim.Movement(anim.NumMovements - 1); + vecPos = vecPos + iLoops * lastMove.Position; + vecAngle.Y = vecAngle.Y + iLoops * lastMove.Angle; + } + return true; + } + else { + prevframe = pmove.EndFrame; + vecPos = pmove.Position; + vecAngle.Y = pmove.Angle; + } } return false; } + + private static bool Studio_AnimVelocity(MStudioAnimDesc anim, float cycle, out Vector3 vecVelocity) { + float prevframe = 0; + vecVelocity = default; + + float flFrame = cycle * (anim.NumFrames - 1); + flFrame = flFrame - (int)(flFrame / (anim.NumFrames - 1)); + + for (int i = 0; i < anim.NumMovements; i++) { + MStudioMovement pmove = anim.Movement(i); + + if (pmove.EndFrame >= flFrame) { + float f = (flFrame - prevframe) / (pmove.EndFrame - prevframe); + + float vel = pmove.V0 * (1 - f) + pmove.V1 * f; + vel = vel * anim.FPS / (pmove.EndFrame - prevframe); + + vecVelocity = pmove.Vector * vel; + return true; + } + else + prevframe = pmove.EndFrame; + } + return false; + } + + private static float Studio_FindAnimDistance(MStudioAnimDesc anim, float dist) { + float prevframe = 0; + + if (dist <= 0) + return 0.0f; + + for (int i = 0; i < anim.NumMovements; i++) { + MStudioMovement pmove = anim.Movement(i); + + float move = (pmove.V0 + pmove.V1) * 0.5f; + + if (move >= dist) { + if (MathLib.SolveQuadratic(0.5f * (pmove.V1 - pmove.V0), pmove.V0, -dist, out float root1, out _)) { + float cpf = 1.0f / (anim.NumFrames - 1); + + return (prevframe + root1 * (pmove.EndFrame - prevframe)) * cpf; + } + return 0.0f; + } + else { + dist -= move; + prevframe = pmove.EndFrame; + } + } + return 1.0f; + } + + public static bool Studio_SeqVelocity(StudioHdr studioHdr, int sequence, float cycle, ReadOnlySpan poseParameter, out Vector3 vecVelocity) { + MStudioAnimDesc[] panim = ArrayPool.Shared.Rent(4); + Span weight = stackalloc float[4]; + + MStudioSeqDesc seqdesc = studioHdr.Seqdesc(sequence); + Studio_SeqAnims(studioHdr, seqdesc, sequence, poseParameter, panim, weight); + + vecVelocity = default; + + bool found = false; + + for (int i = 0; i < 4; i++) { + if (weight[i] != 0) { + if (Studio_AnimVelocity(panim[i], cycle, out Vector3 localVelocity)) { + vecVelocity = vecVelocity + localVelocity * weight[i]; + found = true; + } + } + } + + ArrayPool.Shared.Return(panim, true); + return found; + } + + public static float Studio_FindSeqDistance(StudioHdr studioHdr, int sequence, ReadOnlySpan poseParameter, float dist) { + MStudioAnimDesc[] panim = ArrayPool.Shared.Rent(4); + Span weight = stackalloc float[4]; + + MStudioSeqDesc seqdesc = studioHdr.Seqdesc(sequence); + Studio_SeqAnims(studioHdr, seqdesc, sequence, poseParameter, panim, weight); + + float cycle = 0; + + for (int i = 0; i < 4; i++) { + if (weight[i] != 0) { + float localCycle = Studio_FindAnimDistance(panim[i], dist); + cycle = cycle + localCycle * weight[i]; + } + } + + ArrayPool.Shared.Return(panim, true); + return cycle; + } } diff --git a/Source.Common/Studio.cs b/Source.Common/Studio.cs index 672b85267..2a87b152f 100644 --- a/Source.Common/Studio.cs +++ b/Source.Common/Studio.cs @@ -1171,6 +1171,32 @@ public class MStudioAnimSections public int AnimIndex; } +public class MStudioMovement +{ + public const int SIZEOF = 44; + public static MStudioMovement FACTORY(object caller, Memory data) => new(data); + + public int EndFrame; + public int MotionFlags; + public float V0; + public float V1; + public float Angle; + public Vector3 Vector; + public Vector3 Position; + + public MStudioMovement(Memory data) { + SpanBinaryReader br = new(data.Span); + + br.Read(out EndFrame); + br.Read(out MotionFlags); + br.Read(out V0); + br.Read(out V1); + br.Read(out Angle); + br.Read(out Vector); + br.Read(out Position); + } +} + public class MStudioAnimDesc { public const int SIZEOF = 100; // Static offset from MSVC stats (mstudiobone_t size 100, alignment 4) @@ -1191,6 +1217,8 @@ public class MStudioAnimDesc public int NumMovements; public int MovementIndex; + MStudioMovement[]? movements; + public MStudioMovement Movement(int i) => Studio.ProduceArrayIdx(this, ref movements, NumMovements, MovementIndex, i, MStudioMovement.SIZEOF, Data, MStudioMovement.FACTORY); // UNUSED 6 INTEGERS From 5636f28038048c051fdf0239184f59560a999bda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:37:22 +0300 Subject: [PATCH 21/73] Port quadratic solver and infinite ray sphere intersection --- Source.Common/CollisionUtils.cs | 25 ++++++++++++++++++++ Source.Common/Mathematics/MathLib.cs | 35 ++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/Source.Common/CollisionUtils.cs b/Source.Common/CollisionUtils.cs index c0e19d36d..2f7e4a46b 100644 --- a/Source.Common/CollisionUtils.cs +++ b/Source.Common/CollisionUtils.cs @@ -9,6 +9,31 @@ namespace Source.Common; public static class CollisionUtils { + public static bool IntersectInfiniteRayWithSphere(in Vector3 rayOrigin, in Vector3 rayDelta, in Vector3 sphereCenter, float radius, out float t1, out float t2) { + Vector3 sphereToRay = rayOrigin - sphereCenter; + + float a = Vector3.Dot(rayDelta, rayDelta); + + if (a == 0.0f) { + t1 = t2 = 0.0f; + return sphereToRay.LengthSquared() <= radius * radius; + } + + float b = 2 * Vector3.Dot(sphereToRay, rayDelta); + float c = Vector3.Dot(sphereToRay, sphereToRay) - radius * radius; + float discrim = b * b - 4 * a * c; + if (discrim < 0.0f) { + t1 = t2 = 0.0f; + return false; + } + + discrim = MathF.Sqrt(discrim); + float oo2a = 0.5f / a; + t1 = (-b - discrim) * oo2a; + t2 = (-b + discrim) * oo2a; + return true; + } + public static bool IsSphereIntersectingCone(in Vector3 sphereCenter, float sphereRadius, in Vector3 coneOrigin, in Vector3 coneNormal, float coneSine, float coneCosine) { Vector3 backCenter = coneOrigin - (sphereRadius / coneSine) * coneNormal; Vector3 delta = sphereCenter - backCenter; diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index c6dfb2a2f..cac36b599 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -674,6 +674,32 @@ public static float Lerp(float percent, float start, float end) { public static float Lerp(float f1, float f2, float i1, float i2, float x) { return f1 + (f2 - f1) * (x - i1) / (i2 - i1); } + public static bool SolveQuadratic(float a, float b, float c, out float root1, out float root2) { + if (a == 0) { + if (b != 0) { + root1 = root2 = -c / b; + return true; + } + if (c == 0) { + root1 = root2 = 0; + return true; + } + root1 = root2 = 0; + return false; + } + + float tmp = b * b - 4.0f * a * c; + + if (tmp < 0) { + root1 = root2 = 0; + return false; + } + + tmp = MathF.Sqrt(tmp); + root1 = (-b + tmp) / (2.0f * a); + root2 = (-b - tmp) / (2.0f * a); + return true; + } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Fmod(double x, double y) { return x - y * Math.Truncate(x / y); @@ -2143,6 +2169,15 @@ public static Vector3 RandomVector(float minVal, float maxVal) { return random; } [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Vector2DNormalize(ref Vector2 v) { + float l = v.Length(); + if (l != 0.0f) + v /= l; + else + v.X = v.Y = 0.0f; + return l; + } + public static float VectorNormalize(ref Vector3 vec) { float radius = MathF.Sqrt(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z); From c6cf9147ca605bae37c87998bff31d7f4be81a5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:42:09 +0300 Subject: [PATCH 22/73] Port entity movement and collision helpers used by AI --- Game.Server/BaseAnimating.cs | 82 ++++++++++++++++++++++++++++++++ Game.Server/BaseEntity.cs | 18 +++++++ Game.Server/PhysicsMain.cs | 2 +- Game.Server/Util.cs | 7 +++ Game.Shared/Animation.cs | 2 + Game.Shared/CollisionProperty.cs | 15 ++++++ Game.Shared/UtilShared.cs | 13 +++++ 7 files changed, 138 insertions(+), 1 deletion(-) diff --git a/Game.Server/BaseAnimating.cs b/Game.Server/BaseAnimating.cs index 67ba4ea85..52fa5c83f 100644 --- a/Game.Server/BaseAnimating.cs +++ b/Game.Server/BaseAnimating.cs @@ -799,6 +799,20 @@ public virtual void SetSequence(int sequence) { public int SelectWeightedSequence(Activity activity) { return Animation.SelectWeightedSequence(GetModelPtr(), activity, GetSequence()); } + public int SelectWeightedSequence(Activity activity, int curSequence) { + Assert(activity != Activity.ACT_INVALID); + Assert(GetModelPtr() != null); + return Animation.SelectWeightedSequence(GetModelPtr(), activity, curSequence); + } + public string GetSequenceName(int sequence) { + if (sequence == -1) + return "Not Found!"; + + if (GetModelPtr() == null) + return "No model!"; + + return Animation.GetSequenceName(GetModelPtr(), sequence); + } public int SelectHeaviestSequence(Activity activity) { Assert(GetModelPtr() != null); return Animation.SelectHeaviestSequence(GetModelPtr(), activity); @@ -897,6 +911,74 @@ public float GetSequenceGroundSpeed(StudioHdr? studioHdr, int sequence) { else return 0; } + public float GetSequenceMoveYaw(int sequence) { + Assert(GetModelPtr() != null); + Animation.GetSequenceLinearMotion(GetModelPtr(), sequence, GetPoseParameterArray(), out Vector3 vecReturn); + + if (vecReturn.Length() > 0) + return Util.VecToYaw(vecReturn); + + return Animation.NOMOTION; + } + public void GetSequenceLinearMotion(int sequence, out Vector3 vec) { + Assert(GetModelPtr() != null); + Animation.GetSequenceLinearMotion(GetModelPtr(), sequence, GetPoseParameterArray(), out vec); + } + public virtual float GetIdealSpeed() => GroundSpeed; + public virtual float GetIdealAccel() => GetIdealSpeed() + 50; + public bool HasPoseParameter(int sequence, ReadOnlySpan name) { + int parameter = LookupPoseParameter(name); + if (parameter == -1) + return false; + + return HasPoseParameter(sequence, parameter); + } + public bool HasPoseParameter(int sequence, int parameter) { + StudioHdr? studioHdr = GetModelPtr(); + + if (studioHdr == null) + return false; + + if (!studioHdr.SequencesAvailable()) + return false; + + if (sequence < 0 || sequence >= studioHdr.GetNumSeq()) + return false; + + MStudioSeqDesc seqdesc = studioHdr.Seqdesc(sequence); + if (studioHdr.GetSharedPoseParameter(sequence, seqdesc.ParamIndex[0]) == parameter || + studioHdr.GetSharedPoseParameter(sequence, seqdesc.ParamIndex[1]) == parameter) + return true; + return false; + } + public float GetInstantaneousVelocity(float interval = 0.0f) { + StudioHdr? studioHdr = GetModelPtr(); + if (studioHdr == null) + return 0; + + float nextCycle = (float)(GetCycle() + interval * GetSequenceCycleRate(GetSequence()) * PlaybackRate); + + BoneSetup.Studio_SeqVelocity(studioHdr, GetSequence(), nextCycle, GetPoseParameterArray(), out Vector3 vecVelocity); + vecVelocity *= (float)PlaybackRate; + + return vecVelocity.Length(); + } + public float GetEntryVelocity(int sequence) { + StudioHdr? studioHdr = GetModelPtr(); + if (studioHdr == null) + return 0; + + BoneSetup.Studio_SeqVelocity(studioHdr, sequence, 0.0f, GetPoseParameterArray(), out Vector3 vecVelocity); + + return vecVelocity.Length(); + } + public float GetMovementFrame(float dist) { + StudioHdr? studioHdr = GetModelPtr(); + if (studioHdr == null) + return 0; + + return BoneSetup.Studio_FindSeqDistance(studioHdr, GetSequence(), GetPoseParameterArray(), dist); + } public void ResetSequenceInfo() { if (GetSequence() == -1) // This shouldn't happen. Setting m_nSequence blindly is a horrible coding practice. diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index eabeb63c9..19867f72e 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -1186,6 +1186,24 @@ public virtual void OnEntityEvent(EntityEvent ev, T? data) { } } + public bool AddStepDiscontinuity(TimeUnit_t time, in Vector3 origin, in QAngle angles) { + if ((GetMoveType() != Source.MoveType.Step) || !HasDataObjectType(DataObjectType.StepSimulation)) + return false; + + ref StepSimulationData step = ref GetDataObject(DataObjectType.StepSimulation); + + if (Unsafe.IsNullRef(ref step)) { + Assert(false); + return false; + } + + step.Discontinuity.TickCount = TIME_TO_TICKS(time); + step.Discontinuity.Origin = origin; + MathLib.AngleQuaternion(angles, out step.Discontinuity.Rotation); + + return true; + } + public void TransformStepData_ParentToWorld(BaseEntity? parent) { // Fix up our step simulation points to be in the proper local space ref StepSimulationData step = ref GetDataObject(DataObjectType.StepSimulation); diff --git a/Game.Server/PhysicsMain.cs b/Game.Server/PhysicsMain.cs index 350b992c1..efb345d6f 100644 --- a/Game.Server/PhysicsMain.cs +++ b/Game.Server/PhysicsMain.cs @@ -126,7 +126,7 @@ private void PhysicsAddHalfGravity(double timestep) { PhysicsCheckVelocity(); } - private void PhysicsStepRecheckGround() { + public void PhysicsStepRecheckGround() { Mask mask = PhysicsSolidMaskForEntity(); Vector3 mins, maxs, point = default; int x, y; diff --git a/Game.Server/Util.cs b/Game.Server/Util.cs index aec4e78d3..ba8947014 100644 --- a/Game.Server/Util.cs +++ b/Game.Server/Util.cs @@ -334,6 +334,13 @@ public static void SetMinMaxSize(BaseEntity ent, in Vector3 mins, in Vector3 max ent.SetCollisionBounds(mins, maxs); } + public static float DistApprox2D(in Vector3 vec1, in Vector3 vec2) { + float dx = vec1.X - vec2.X; + float dy = vec1.Y - vec2.Y; + + return MathF.Abs(dx) + MathF.Abs(dy); + } + public static BasePlayer? GetLocalPlayer() { if (gpGlobals.MaxClients > 1) { if (developer.GetBool()) { diff --git a/Game.Shared/Animation.cs b/Game.Shared/Animation.cs index 834d85b6d..d0af2ba1f 100644 --- a/Game.Shared/Animation.cs +++ b/Game.Shared/Animation.cs @@ -16,6 +16,8 @@ namespace Game.Shared; public static class Animation { + public const float NOMOTION = 99999; + static Animation(){ StudioHdr.SetActivityForSequence += SetActivityForSequence; } diff --git a/Game.Shared/CollisionProperty.cs b/Game.Shared/CollisionProperty.cs index 9c8f63c99..ae53ff1d9 100644 --- a/Game.Shared/CollisionProperty.cs +++ b/Game.Shared/CollisionProperty.cs @@ -679,6 +679,21 @@ public Vector3 CollisionToWorldSpace(in Vector3 input) { //----------------------------------------------------------------------------- // Transforms a point in world space to OBB space //----------------------------------------------------------------------------- + public Vector3 NormalizedToCollisionSpace(in Vector3 input) { + return new(MathLib.Lerp(input.X, Mins.X, Maxs.X), + MathLib.Lerp(input.Y, Mins.Y, Maxs.Y), + MathLib.Lerp(input.Z, Mins.Z, Maxs.Z)); + } + + public Vector3 NormalizedToWorldSpace(in Vector3 input) => CollisionToWorldSpace(NormalizedToCollisionSpace(input)); + + public bool IsPointInBounds(in Vector3 worldPt) { + Vector3 localSpace = WorldToCollisionSpace(worldPt); + return (localSpace.X >= Mins.X && localSpace.X <= Maxs.X) && + (localSpace.Y >= Mins.Y && localSpace.Y <= Maxs.Y) && + (localSpace.Z >= Mins.Z && localSpace.Z <= Maxs.Z); + } + public Vector3 WorldToCollisionSpace(in Vector3 input) { Vector3 result; if (!IsBoundsDefinedInEntitySpace() || (GetCollisionAngles() == vec3_angle)) diff --git a/Game.Shared/UtilShared.cs b/Game.Shared/UtilShared.cs index bc943e5db..ccffb9e88 100644 --- a/Game.Shared/UtilShared.cs +++ b/Game.Shared/UtilShared.cs @@ -403,6 +403,19 @@ public static void TraceLine(in Vector3 absStart, in Vector3 absEnd, Mask ma // todo: visualize } + public static void TraceModel(in Vector3 vecStart, in Vector3 vecEnd, in Vector3 hullMin, in Vector3 hullMax, BaseEntity? entModel, CollisionGroup collisionGroup, out Trace ptr) { + if (entModel != null && entModel.ShouldCollide(collisionGroup, unchecked((Contents)Mask.All))) { + Ray ray = default; + ray.Init(vecStart, vecEnd, hullMin, hullMax); + ptr = default; + enginetrace.ClipRayToEntity(ray, Mask.All, entModel, ref ptr); + } + else { + ptr = default; + ptr.Fraction = 1.0f; + } + } + public static void TraceHull(in Vector3 vecAbsStart, in Vector3 vecAbsEnd, in Vector3 hullMin, in Vector3 hullMax, Mask mask, IHandleEntity? ignore, CollisionGroup collisionGroup, out Trace ptr) { Ray ray = default; ray.Init(vecAbsStart, vecAbsEnd, hullMin, hullMax); From e5b8581fad19c7b33fadfd15af8030e60b12a2cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:46:51 +0300 Subject: [PATCH 23/73] Port move probe move limits and local move goal types --- Game.Server/AI_MoveProbe.cs | 687 ++++++++++++++++++++++++++++++++++++ Game.Server/AI_MoveTypes.cs | 47 +++ 2 files changed, 734 insertions(+) diff --git a/Game.Server/AI_MoveProbe.cs b/Game.Server/AI_MoveProbe.cs index eb004b40d..3a12373b0 100644 --- a/Game.Server/AI_MoveProbe.cs +++ b/Game.Server/AI_MoveProbe.cs @@ -6,6 +6,7 @@ using Source.Common; using Source.Common.Commands; using Source.Common.Formats.BSP; +using Source.Common.Mathematics; using System.Numerics; @@ -16,15 +17,701 @@ public static class AI_MoveProbeGlobals public static float MOVE_HEIGHT_EPSILON = 0.0625f; public static readonly ConVar ai_strong_optimizations_no_checkstand = new("ai_strong_optimizations_no_checkstand", "0"); + public static readonly ConVar ai_moveprobe_debug = new("ai_moveprobe_debug", "0"); + public static readonly ConVar ai_moveprobe_jump_debug = new("ai_moveprobe_jump_debug", "0"); + + public static bool g_bAIDebugStep = false; +} + +[Flags] +public enum AI_TestGroundMoveFlags +{ + Default = 0, + IgnoreFloor = 0x01, + IgnoreInitialStandPos = 0x02, + TwoD = 0x04, + DrawResults = 0x08, +} + +[Flags] +public enum AI_MoveLimitFlags +{ + Default = 0, + TwoD = 0x01, + DrawResults = 0x02, + IgnoreTransients = 0x04, + QuickReject = 0x08, } public class AI_MoveProbe : AI_Component { + const float LOCAL_STEP_SIZE = 16.0f; + + struct CheckStepArgs + { + public Vector3 Start; + public Vector3 StepDir; + public float StepSize; + public float StepHeight; + public float StepDownMultiplier; + public float MinStepLanding; + public Mask CollisionMask; + public StepGroundTest GroundTest; + } + + struct CheckStepResult + { + public Vector3 EndPoint; + public Vector3 HitNormal; + public bool StartSolid; + public BaseEntity? Blocker; + } + public AI_MoveProbe(AI_BaseNPC? outer) : base(outer) { IgnoreTransientEntities = false; TraceListData = null; } + public void TraceLine(in Vector3 start, in Vector3 end, Mask mask, bool useCollisionGroup, out Trace result) { + CollisionGroup collisionGroup = useCollisionGroup ? GetOuter()!.GetCollisionGroup() : CollisionGroup.None; + + TraceFilterNav traceFilter = new(GetOuter()!, IgnoreTransientEntities, GetOuter(), collisionGroup); + + Util.TraceLine(start, end, mask, ref traceFilter, out result); + } + + bool CheckStep(in CheckStepArgs args, out CheckStepResult result) { + Mask collisionMask = args.CollisionMask; + Vector3 end = args.Start + args.StepSize * args.StepDir; + + result.EndPoint = args.Start; + result.StartSolid = false; + result.HitNormal = vec3_origin; + result.Blocker = null; + + Vector3 stepStart = new(args.Start.X, args.Start.Y, args.Start.Z + MOVE_HEIGHT_EPSILON); + Vector3 stepEnd = new(end.X, end.Y, args.Start.Z + MOVE_HEIGHT_EPSILON); + + if (g_bAIDebugStep) { + DebugOverlay.Line(stepStart, stepEnd, 255, 255, 255, true, 5); + DebugOverlay.Cross3D(stepEnd, 32, 255, 255, 255, true, 5); + } + + TraceHull(stepStart, stepEnd, collisionMask, out Trace trace); + + if (trace.StartSolid || (trace.Fraction < 1)) { + Trace stepTrace; + + if (!trace.StartSolid) { + if (g_bAIDebugStep) + DebugOverlay.Box(trace.EndPos, GetOuter()!.WorldAlignMins(), GetOuter()!.WorldAlignMaxs(), 64, 64, 64, 0, 5); + + stepStart = trace.EndPos; + + Vector3 stepUp = stepStart; + stepUp.Z += args.StepHeight; + TraceHull(stepStart, stepUp, collisionMask, out stepTrace); + + if (g_bAIDebugStep) + DebugOverlay.Box(stepTrace.EndPos, GetOuter()!.WorldAlignMins(), GetOuter()!.WorldAlignMaxs(), 96, 96, 96, 0, 5); + + stepStart = stepTrace.EndPos; + } + else + stepStart.Z += args.StepHeight; + + stepEnd.Z = stepStart.Z; + + TraceHull(stepStart, stepEnd, collisionMask, out stepTrace); + bool rejectStep = false; + + if (stepTrace.StartSolid || stepTrace.Fraction <= 0.01f) { + if (trace.StartSolid) { + result.StartSolid = true; + result.Blocker = trace.Ent; + result.HitNormal = trace.Plane.Normal; + return false; + } + + rejectStep = true; + } + else { + if (g_bAIDebugStep) + DebugOverlay.Box(stepTrace.EndPos, GetOuter()!.WorldAlignMins(), GetOuter()!.WorldAlignMaxs(), 128, 128, 128, 0, 5); + + float landingDistSq = new Vector2(stepEnd.X - stepStart.X, stepEnd.Y - stepStart.Y).LengthSquared(); + float requiredLandingDistSq = args.MinStepLanding * args.MinStepLanding; + if (landingDistSq < requiredLandingDistSq) { + Vector3 stepEndWithLanding = stepStart + args.MinStepLanding * args.StepDir; + TraceHull(stepStart, stepEndWithLanding, collisionMask, out Trace landingTrace); + if (landingTrace.Fraction < 1) { + if (g_bAIDebugStep) + DebugOverlay.Box(landingTrace.EndPos, GetOuter()!.WorldAlignMins() + new Vector3(0, 0, 0.1f), GetOuter()!.WorldAlignMaxs() + new Vector3(0, 0, 0.1f), 255, 0, 0, 0, 5); + + rejectStep = true; + if (landingTrace.Ent != null) + result.Blocker = landingTrace.Ent; + } + } + else if (new Vector2(stepTrace.EndPos.X - stepStart.X, stepTrace.EndPos.Y - stepStart.Y).LengthSquared() < requiredLandingDistSq) { + if (g_bAIDebugStep) + DebugOverlay.Box(stepTrace.EndPos, GetOuter()!.WorldAlignMins() + new Vector3(0, 0, 0.1f), GetOuter()!.WorldAlignMaxs() + new Vector3(0, 0, 0.1f), 255, 0, 0, 0, 5); + + rejectStep = true; + } + } + + if (!rejectStep) + trace = stepTrace; + + if (trace.Fraction < 1.0f) { + if (result.Blocker == null) + result.Blocker = trace.Ent; + result.HitNormal = trace.Plane.Normal; + } + + stepEnd = trace.EndPos; + } + + stepStart = stepEnd; + stepEnd.Z = args.Start.Z - args.StepHeight * args.StepDownMultiplier - MOVE_HEIGHT_EPSILON; + + TraceHull(stepStart, stepEnd, collisionMask, out trace); + + if (trace.Fraction == 1.0f) { + if (g_bAIDebugStep) + DebugOverlay.Box(trace.EndPos, GetOuter()!.WorldAlignMins(), GetOuter()!.WorldAlignMaxs(), 255, 0, 0, 0, 5); + + Assert(result.EndPoint == args.Start); + if (GetOuter()!.GetGroundEntity() != null) + result.Blocker = GetOuter()!.GetGroundEntity(); + else + result.Blocker = BaseEntity.GetContainingEntity(engine.PEntityOfEntIndex(0)); + return false; + } + + if (g_bAIDebugStep) + DebugOverlay.Box(trace.EndPos, GetOuter()!.WorldAlignMins(), GetOuter()!.WorldAlignMaxs(), 160, 160, 160, 0, 5); + + BaseEntity? floor = trace.Ent; + if (floor != GetOuter()!.GetGroundEntity() && !CanStandOn(floor)) { + if (g_bAIDebugStep) + DebugOverlay.Cross3D(trace.EndPos, 32, 255, 0, 0, true, 5); + + Assert(result.EndPoint == args.Start); + result.Blocker = floor; + return false; + } + + if (trace.EndPos.Z - args.Start.Z > args.StepHeight * 0.5f && + ((floor!.IsWorld() && trace.HitBox > 0) || floor is PhysicsProp)) { + if (MathF.Abs(Vector3.Dot(trace.Plane.Normal, new Vector3(1, 0, 0))) > .4f) { + Assert(result.EndPoint == args.Start); + result.Blocker = floor; + + if (g_bAIDebugStep) + DebugOverlay.Cross3D(trace.EndPos, 32, 0, 0, 255, true, 5); + return false; + } + } + + if (args.GroundTest != StepGroundTest.DontCheckGround) { + bool isFloorFlat = CheckStandPosition(trace.EndPos, collisionMask); + if (args.GroundTest != StepGroundTest.OnInvalidGround && !isFloorFlat) { + result.Blocker = floor; + + if (g_bAIDebugStep) + DebugOverlay.Cross3D(trace.EndPos, 32, 255, 0, 255, true, 5); + return false; + } + } + + result.EndPoint = trace.EndPos; + result.EndPoint.Z += MOVE_HEIGHT_EPSILON; + + if (g_bAIDebugStep) + DebugOverlay.Cross3D(trace.EndPos, 32, 0, 255, 0, true, 5); + + return result.Blocker == null; + } + + public bool TestGroundMove(in Vector3 actualStart, in Vector3 desiredEnd, Mask collisionMask, AI_TestGroundMoveFlags flags, out AIMoveTrace moveTrace) + => TestGroundMove(actualStart, desiredEnd, collisionMask, 100, flags, out moveTrace); + + public bool TestGroundMove(in Vector3 actualStart, in Vector3 desiredEnd, Mask collisionMask, float pctToCheckStandPositions, AI_TestGroundMoveFlags flags, out AIMoveTrace moveTrace) { + moveTrace = default; + moveTrace.DistObstructed = 0.0f; + moveTrace.Obstruction = null; + moveTrace.HitNormal = vec3_origin; + moveTrace.Status = AIMoveResult.Ok; + moveTrace.EndPosition = actualStart; + moveTrace.StepUpDistance = 0; + + moveTrace.TotalDist = ComputePathDirection(Navigation.Ground, actualStart, desiredEnd, out Vector3 moveDir); + if (moveTrace.TotalDist == 0.0f) + return true; + + StepGroundTest groundTest; + if ((flags & AI_TestGroundMoveFlags.IgnoreFloor) != 0 || pctToCheckStandPositions < 0.001f) { + groundTest = StepGroundTest.DontCheckGround; + pctToCheckStandPositions = 0; + } + else { + if (pctToCheckStandPositions > 99.999f) + pctToCheckStandPositions = 100; + + if ((flags & AI_TestGroundMoveFlags.IgnoreInitialStandPos) != 0 || CheckStandPosition(actualStart, collisionMask)) + groundTest = StepGroundTest.OnValidGround; + else + groundTest = StepGroundTest.OnInvalidGround; + } + + if ((flags & AI_TestGroundMoveFlags.DrawResults) != 0 && !CheckStandPosition(actualStart, collisionMask)) + DebugOverlay.Cross3D(actualStart, 16, 128, 0, 0, true, 2.0f); + + float distClear = 0; + int i; + + CheckStepArgs checkStepArgs; + CheckStepResult checkStepResult; + + checkStepArgs.Start = actualStart; + checkStepArgs.StepDir = moveDir; + checkStepArgs.StepSize = 0; + checkStepArgs.StepHeight = StepHeight(); + checkStepArgs.StepDownMultiplier = GetOuter()!.GetStepDownMultiplier(); + checkStepArgs.MinStepLanding = GetOuter()!.GetHullWidth() * 0.3333333f; + checkStepArgs.CollisionMask = collisionMask; + checkStepArgs.GroundTest = groundTest; + + checkStepResult.EndPoint = actualStart; + checkStepResult.HitNormal = vec3_origin; + checkStepResult.Blocker = null; + checkStepResult.StartSolid = false; + + float distStartToIgnoreGround = (pctToCheckStandPositions == 100) ? moveTrace.TotalDist : moveTrace.TotalDist * (pctToCheckStandPositions * 0.01f); + Vector3 localOrigin = GetOuter()!.GetLocalOrigin(); + bool tryNavIgnore = (new Vector2(actualStart.X - localOrigin.X, actualStart.Y - localOrigin.Y).LengthSquared() < 0.1f && MathF.Abs(actualStart.Z - localOrigin.Z) < checkStepArgs.StepHeight * 0.5f); + + List ignoredEntities = []; + + for (; ; ) { + float stepSize = Math.Min(LOCAL_STEP_SIZE, moveTrace.TotalDist - distClear); + if (stepSize < 0.001f) + break; + + checkStepArgs.StepSize = stepSize; + if (distClear - distStartToIgnoreGround > 0.001f) + checkStepArgs.GroundTest = StepGroundTest.DontCheckGround; + + for (i = 0; i < 16; i++) { + CheckStep(checkStepArgs, out checkStepResult); + + if (!tryNavIgnore || checkStepResult.Blocker == null || !checkStepResult.StartSolid) + break; + + if (checkStepResult.Blocker.GetMoveType() != Source.MoveType.VPhysics && !checkStepResult.Blocker.IsNPC()) + break; + + if (actualStart != checkStepArgs.Start) { + tryNavIgnore = false; + break; + } + + if (checkStepResult.Blocker.GetMoveType() == Source.MoveType.VPhysics) { + Vector3 moveDirection = desiredEnd - actualStart; + MathLib.VectorNormalize(ref moveDirection); + + Vector3 obstacleDir = checkStepResult.Blocker.WorldSpaceCenter() - GetOuter()!.WorldSpaceCenter(); + MathLib.VectorNormalize(ref obstacleDir); + + if (Vector3.Dot(moveDirection, obstacleDir) >= 0) + break; + } + + if ((flags & AI_TestGroundMoveFlags.DrawResults) != 0 && checkStepResult.StartSolid && checkStepResult.Blocker.IsNPC()) { + DebugOverlay.EntityBounds(GetOuter()!, 0, 0, 255, 0, .5f); + DebugOverlay.EntityBounds(checkStepResult.Blocker, 255, 0, 0, 0, .5f); + } + + ignoredEntities.Add(checkStepResult.Blocker); + checkStepResult.Blocker.SetNavIgnore(); + } + + if ((flags & AI_TestGroundMoveFlags.DrawResults) != 0) { + if (!CheckStandPosition(checkStepResult.EndPoint, collisionMask)) { + DebugOverlay.Box(checkStepResult.EndPoint, GetOuter()!.WorldAlignMins(), GetOuter()!.WorldAlignMaxs(), 255, 0, 0, 0, 0.1f); + DebugOverlay.Cross3D(checkStepResult.EndPoint, 16, 255, 0, 0, true, 0.1f); + } + else { + DebugOverlay.Box(checkStepResult.EndPoint, GetOuter()!.WorldAlignMins(), GetOuter()!.WorldAlignMaxs(), 0, 255, 0, 0, 0.1f); + DebugOverlay.Cross3D(checkStepResult.EndPoint, 16, 0, 255, 0, true, 0.1f); + } + } + + if (checkStepResult.Blocker != null) { + distClear += new Vector2(checkStepResult.EndPoint.X - checkStepArgs.Start.X, checkStepResult.EndPoint.Y - checkStepArgs.Start.Y).Length(); + break; + } + + float dz = checkStepResult.EndPoint.Z - checkStepArgs.Start.Z; + if (dz < 0) + dz = 0; + + moveTrace.StepUpDistance += dz; + distClear += stepSize; + checkStepArgs.Start = checkStepResult.EndPoint; + } + + for (i = 0; i < ignoredEntities.Count; i++) + ignoredEntities[i].ClearNavIgnore(); + + moveTrace.EndPosition = checkStepResult.EndPoint; + + if (checkStepResult.Blocker != null) { + moveTrace.Obstruction = checkStepResult.Blocker; + moveTrace.HitNormal = checkStepResult.HitNormal; + moveTrace.Status = AIComputeBlockerMoveResult(checkStepResult.Blocker); + moveTrace.DistObstructed = moveTrace.TotalDist - distClear; + + if ((flags & AI_TestGroundMoveFlags.DrawResults) != 0) + DebugOverlay.Box(checkStepResult.EndPoint, GetOuter()!.WorldAlignMins(), GetOuter()!.WorldAlignMaxs(), 255, 0, 0, 0, 0.5f); + + return false; + } + + if ((flags & AI_TestGroundMoveFlags.TwoD) == 0) { + float threshold = Math.Max(0.5f * GetOuter()!.GetHullHeight(), StepHeight() + 0.1f); + if (MathF.Abs(moveTrace.EndPosition.Z - desiredEnd.Z) > threshold) { + moveTrace.Obstruction = BaseEntity.GetContainingEntity(engine.PEntityOfEntIndex(0)); + moveTrace.HitNormal = vec3_origin; + moveTrace.Status = AIMoveResult.BlockedWorld; + moveTrace.DistObstructed = ComputePathDistance(Navigation.Ground, moveTrace.EndPosition, desiredEnd); + return false; + } + } + + return true; + } + + void GroundMoveLimit(in Vector3 start, in Vector3 end, Mask collisionMask, BaseEntity? target, AI_TestGroundMoveFlags testGroundMoveFlags, float pctToCheckStandPositions, ref AIMoveTrace trace) { + Assert(!IsMoveBlocked(trace)); + + Vector3 desiredEnd; + + trace.TotalDist = ComputePathDistance(Navigation.Ground, start, end); + + if (!IterativeFloorPoint(start, collisionMask, out Vector3 actualStart)) { + trace.DistObstructed = trace.TotalDist; + trace.Obstruction = BaseEntity.GetContainingEntity(engine.PEntityOfEntIndex(0)); + trace.HitNormal = vec3_origin; + trace.Status = AIMoveResult.BlockedWorld; + trace.EndPosition = start; + return; + } + + if ((testGroundMoveFlags & AI_TestGroundMoveFlags.TwoD) == 0) + IterativeFloorPoint(end, collisionMask, out desiredEnd); + else + desiredEnd = end; + + TestGroundMove(actualStart, desiredEnd, collisionMask, pctToCheckStandPositions, testGroundMoveFlags, out trace); + + bool vehicleMatchesObstruction = false; + + if (target != null) { + if (target is BaseCombatCharacter ccTarget && ccTarget.IsInAVehicle()) { + BaseEntity? vehicleEnt = ccTarget.GetVehicleEntity(); + if (vehicleEnt == trace.Obstruction) + vehicleMatchesObstruction = true; + } + } + + if ((target != null && (target == trace.Obstruction)) || vehicleMatchesObstruction) { + trace.DistObstructed = 0.0f; + trace.Obstruction = null; + trace.HitNormal = vec3_origin; + trace.Status = AIMoveResult.Ok; + } + } + + void FlyMoveLimit(in Vector3 start, in Vector3 end, Mask collisionMask, BaseEntity? target, ref AIMoveTrace moveTrace) { + Assert(!IsMoveBlocked(moveTrace)); + + TraceHull(start, end, collisionMask, out Trace tr); + + if (tr.Fraction < 1) { + BaseEntity? blocker = tr.Ent; + if (blocker != null) { + if (target == blocker) { + moveTrace.EndPosition = tr.EndPos; + return; + } + + moveTrace.Obstruction = blocker; + moveTrace.HitNormal = vec3_origin; + moveTrace.Status = AIComputeBlockerMoveResult(blocker); + } + moveTrace.DistObstructed = ComputePathDistance(Navigation.Fly, tr.EndPos, end); + moveTrace.EndPosition = tr.EndPos; + return; + } + + moveTrace.EndPosition = end; + } + + void JumpMoveLimit(in Vector3 start, in Vector3 end, Mask collisionMask, BaseEntity? target, ref AIMoveTrace moveTrace) { + moveTrace.JumpVelocity = Vector3.Zero; + + float dist = ComputePathDistance(Navigation.Jump, start, end); + + if (!IsJumpLegal(start, end, end)) { + moveTrace.Status = AIMoveResult.Illegal; + moveTrace.DistObstructed = dist; + return; + } + + IterativeFloorPoint(start, collisionMask, out Vector3 from); + + IterativeFloorPoint(end, collisionMask, StepHeight() * 0.5f, out Vector3 to); + if (!CheckStandPosition(to, collisionMask)) { + moveTrace.Status = AIMoveResult.Illegal; + moveTrace.DistObstructed = dist; + return; + } + + if (from == to) { + moveTrace.Status = AIMoveResult.Illegal; + moveTrace.DistObstructed = dist; + return; + } + + if (new Vector2(from.X - to.X, from.Y - to.Y).Length() == 0.0f) { + moveTrace.Status = AIMoveResult.Illegal; + moveTrace.DistObstructed = dist; + return; + } + + float maxHorzVel = GetOuter()!.GetMaxJumpSpeed(); + + Vector3 gravity = new(0, 0, GetCurrentGravity() * GetOuter()!.GetJumpGravity()); + + if (gravity.Z < 0.01f) { + moveTrace.Status = AIMoveResult.Illegal; + moveTrace.DistObstructed = dist; + return; + } + + BaseEntity? obstruction = null; + AIMoveResult status = AIMoveResult.Illegal; + float distObstructed = dist; + + float minSuccessfulJumpHeight = 1024.0f; + float minJumpHeight = 0.0f; + float minJumpStep = 1024.0f; + + Vector3 rawJumpVel = CalcJumpLaunchVelocity(from, to, gravity.Z, ref minJumpHeight, maxHorzVel, out Vector3 apex); + float baselineJumpHeight = minJumpHeight; + + do { + rawJumpVel = CalcJumpLaunchVelocity(from, to, gravity.Z, ref minJumpHeight, maxHorzVel, out apex); + + if (!IsJumpLegal(from, apex, to)) { + minJumpStep = minJumpStep / 2.0f; + minJumpHeight = minJumpHeight - minJumpStep; + } + else { + float jumpTime = new Vector2(from.X - to.X, from.Y - to.Y).Length() / new Vector2(rawJumpVel.X, rawJumpVel.Y).Length(); + float timeStep = jumpTime / 10.0f; + + Vector3 test = from; + bool madeIt = true; + + for (float time = 0; time < jumpTime - 0.01f; time += timeStep) { + Vector3 nextPos = test + (rawJumpVel - 0.5f * gravity * timeStep) * timeStep; + + TraceHull(test, nextPos, collisionMask, out Trace trace); + + if (trace.StartSolid || trace.Fraction < 0.99f) { + obstruction = trace.Ent; + status = AIComputeBlockerMoveResult(obstruction!); + distObstructed = ComputePathDistance(Navigation.Jump, test, to); + + if (trace.Plane.Normal.Z < 0.0f) { + minJumpStep = minJumpStep / 2.0f; + minJumpHeight = minJumpHeight - minJumpStep; + } + else { + minJumpStep = minJumpStep / 2.0f; + minJumpHeight += minJumpStep; + } + + if (ai_moveprobe_jump_debug.GetBool()) + DebugOverlay.Line(test, nextPos, 255, 0, 0, true, 2.0f); + + madeIt = false; + break; + } + else { + if (ai_moveprobe_jump_debug.GetBool()) + DebugOverlay.Line(test, nextPos, 0, 255, 0, true, 2.0f); + } + + rawJumpVel = rawJumpVel - gravity * timeStep; + test = nextPos; + } + + if (madeIt) { + minSuccessfulJumpHeight = minJumpHeight; + minJumpStep = minJumpStep / 2.0f; + minJumpHeight -= minJumpStep; + } + } + } + while (minJumpHeight > baselineJumpHeight && minJumpHeight <= 1024.0f && minJumpStep >= 16.0f); + + if (minSuccessfulJumpHeight != 1024.0f) + moveTrace.JumpVelocity = CalcJumpLaunchVelocity(from, to, gravity.Z, ref minSuccessfulJumpHeight, maxHorzVel, out apex); + else { + moveTrace.Obstruction = obstruction; + moveTrace.HitNormal = vec3_origin; + moveTrace.Status = status; + moveTrace.DistObstructed = distObstructed; + } + } + + void ClimbMoveLimit(in Vector3 start, in Vector3 end, BaseEntity? target, ref AIMoveTrace moveTrace) { + TraceHull(start, end, Mask.NPCSolid, out Trace tr); + + if (tr.Fraction < 1.0f) { + BaseEntity? entity = tr.Ent; + if (entity == target) + return; + else { + moveTrace.Obstruction = entity; + moveTrace.HitNormal = vec3_origin; + moveTrace.Status = AIComputeBlockerMoveResult(entity!); + + float dist = (1.0f - tr.Fraction) * ComputePathDistance(Navigation.Climb, start, end); + if (dist <= 0.001f) + dist = 0.001f; + moveTrace.DistObstructed = dist; + return; + } + } + } + + public bool MoveLimit(Navigation navType, in Vector3 start, in Vector3 end, Mask collisionMask, BaseEntity? target, out AIMoveTrace trace) + => MoveLimit(navType, start, end, collisionMask, target, 100.0f, AI_MoveLimitFlags.Default, out trace); + + public bool MoveLimit(Navigation navType, in Vector3 start, in Vector3 end, Mask collisionMask, BaseEntity? target, float pctToCheckStandPositions, out AIMoveTrace trace) + => MoveLimit(navType, start, end, collisionMask, target, pctToCheckStandPositions, AI_MoveLimitFlags.Default, out trace); + + public bool MoveLimit(Navigation navType, in Vector3 start, in Vector3 end, Mask collisionMask, BaseEntity? target, float pctToCheckStandPositions, AI_MoveLimitFlags flags, out AIMoveTrace trace) { + trace = default; + trace.TotalDist = ComputePathDistance(navType, start, end); + trace.DistObstructed = 0.0f; + trace.Obstruction = null; + trace.HitNormal = vec3_origin; + trace.Status = AIMoveResult.Ok; + trace.EndPosition = start; + + switch (navType) { + case Navigation.Ground: { + AI_TestGroundMoveFlags testGroundMoveFlags = AI_TestGroundMoveFlags.Default; + if ((flags & AI_MoveLimitFlags.TwoD) != 0) + testGroundMoveFlags |= AI_TestGroundMoveFlags.TwoD; + if ((flags & AI_MoveLimitFlags.DrawResults) != 0) + testGroundMoveFlags |= AI_TestGroundMoveFlags.DrawResults; + if (ai_moveprobe_debug.GetBool() && (GetOuter()!.DebugOverlays & DebugOverlayBits.NPCSelected) != 0) + testGroundMoveFlags |= AI_TestGroundMoveFlags.DrawResults; + + if ((flags & AI_MoveLimitFlags.IgnoreTransients) != 0) + IgnoreTransientEntities = true; + + bool doIt = true; + if ((flags & AI_MoveLimitFlags.QuickReject) != 0) { + Assert(start == GetOuter()!.GetLocalOrigin()); + TraceLine(GetOuter()!.EyePosition(), end, collisionMask, true, out Trace tr); + doIt = tr.Fraction > 0.99f; + } + + if (doIt) + GroundMoveLimit(start, end, collisionMask, target, testGroundMoveFlags, pctToCheckStandPositions, ref trace); + else { + trace.Obstruction = BaseEntity.GetContainingEntity(engine.PEntityOfEntIndex(0)); + trace.HitNormal = vec3_origin; + trace.Status = AIMoveResult.BlockedWorld; + trace.DistObstructed = ComputePathDistance(Navigation.Ground, start, end); + } + + IgnoreTransientEntities = false; + + break; + } + + case Navigation.Fly: + FlyMoveLimit(start, end, collisionMask, target, ref trace); + break; + + case Navigation.Jump: + JumpMoveLimit(start, end, collisionMask, target, ref trace); + break; + + case Navigation.Climb: + ClimbMoveLimit(start, end, target, ref trace); + break; + + default: + trace.Status = AIMoveResult.Illegal; + trace.DistObstructed = ComputePathDistance(navType, start, end); + break; + } + + if (IsMoveBlocked(trace.Status) && trace.Obstruction != null && !trace.Obstruction.IsWorld()) + LastBlockingEnt.Set(trace.Obstruction); + + return !IsMoveBlocked(trace.Status); + } + + public Vector3 CalcJumpLaunchVelocity(in Vector3 startPos, in Vector3 endPos, float gravity, ref float minHeight, float maxHorzVelocity, out Vector3 apex) { + float stepHeight = endPos.Z - startPos.Z; + + Vector3 targetDir2D = endPos - startPos; + targetDir2D.Z = 0; + float distance = targetDir2D.Length(); + if (distance != 0.0f) + targetDir2D /= distance; + + Assert(maxHorzVelocity > 0); + + float minHorzTime = distance / maxHorzVelocity; + float minHorzHeight = 0.5f * gravity * (minHorzTime * 0.5f) * (minHorzTime * 0.5f); + + minHeight = Math.Max(minHeight, minHorzHeight); + minHeight = Math.Max(minHeight, stepHeight); + + float t0 = MathF.Sqrt((2.0f * minHeight) / gravity); + float t1 = MathF.Sqrt((2.0f * MathF.Abs(minHeight - stepHeight)) / gravity); + + float velHorz = distance / (t0 + t1); + + Vector3 jumpVel = targetDir2D * velHorz; + + jumpVel.Z = MathF.Sqrt(2.0f * gravity * minHeight); + + apex = startPos + targetDir2D * velHorz * t0 + new Vector3(0, 0, minHeight); + + return jumpVel; + } + + bool IterativeFloorPoint(in Vector3 start, Mask collisionMask, out Vector3 result) => IterativeFloorPoint(start, collisionMask, 0, out result); + + bool IterativeFloorPoint(in Vector3 start, Mask collisionMask, float addedStep, out Vector3 result) + => FloorPoint(start, collisionMask, StepHeight() * GetOuter()!.GetStepDownMultiplier() + addedStep, -(12 * 60), out result); + + bool IsJumpLegal(in Vector3 startPos, in Vector3 apex, in Vector3 endPos) => GetOuter()!.IsJumpLegal(startPos, apex, endPos); + public bool ShouldBrushBeIgnored(BaseEntity entity) { if (entity.Classname == g_iszFuncBrushClassname) { FuncBrush funcBrush = (FuncBrush)entity; diff --git a/Game.Server/AI_MoveTypes.cs b/Game.Server/AI_MoveTypes.cs index 63071787f..eb9d18a51 100644 --- a/Game.Server/AI_MoveTypes.cs +++ b/Game.Server/AI_MoveTypes.cs @@ -35,6 +35,53 @@ public struct AIMoveTrace public float StepUpDistance; } +[Flags] +public enum AILocalMoveGoalFlags +{ + None, + TargetIsGoal = 0x01, + ConsumeInterval = 0x02, + TargetIsTransition = 0x04, + NoSteer = 0x08, + NoAvoidancePaths = 0x10, +} + +public struct AILocalMoveGoal +{ + public Vector3 Target; + + public Vector3 Dir; + public Vector3 Facing; + public float Speed; + + public float MaxDist; + + public float CurExpectedDist; + + public Navigation NavType; + public BaseEntity? MoveTarget; + + public AILocalMoveGoalFlags Flags; + + public AI_Path? Path; + + public bool HasTraced; + public AIMoveTrace DirectTrace; + public AIMoveTrace ThinkTrace; +} + +public enum AIMotorMoveResult +{ + Failed, + Success, + + PartialHitNPC, + PartialHitWorld, + PartialHitTarget, + + NumResults +} + public static class AI_MoveTypesGlobals { public static bool IsMoveBlocked(AIMoveResult moveResult) => moveResult < AIMoveResult.Ok; From 00e16f580570cfa8ed4f0db85f8ab39ddf7ae247 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:51:34 +0300 Subject: [PATCH 24/73] Port AI path and waypoint list --- Game.Server/AI_Route.cs | 323 ++++++++++++++++++++++++++++++++++++- Game.Server/AI_Waypoint.cs | 77 +++++++++ 2 files changed, 396 insertions(+), 4 deletions(-) diff --git a/Game.Server/AI_Route.cs b/Game.Server/AI_Route.cs index 0f1cdcdb5..028684e58 100644 --- a/Game.Server/AI_Route.cs +++ b/Game.Server/AI_Route.cs @@ -1,6 +1,7 @@ using Game.Shared; using Source.Common; +using Source.Common.Mathematics; using System.Numerics; @@ -27,9 +28,36 @@ public AI_Path() { WaypointTolerance = DEF_WAYPOINT_TOLERANCE; } + public void SetWaypoints(AI_Waypoint? route, bool setGoalFromLast = false) { + Waypoints.Set(route); + + AI_Waypoint? last = Waypoints.GetLast(); + if (last != null) { + last.PathDistGoal = -1; + if (setGoalFromLast) { + GoalPosSet = false; + last.ModifyFlags(WaypointFlags.ToGoal, true); + SetGoalPosition(last.GetPos()); + } + } + } + + public void PrependWaypoints(AI_Waypoint waypoints) { + Waypoints.PrependWaypoints(waypoints); + AI_Waypoint last = Waypoints.GetLast()!; + last.PathDistGoal = -1; + } + + public void PrependWaypoint(in Vector3 newPoint, Navigation navType, WaypointFlags waypointFlags) { + Waypoints.PrependWaypoint(newPoint, navType, waypointFlags); + AI_Waypoint last = Waypoints.GetLast()!; + last.PathDistGoal = -1; + } + public bool IsEmpty() => Waypoints.IsEmpty(); public AI_Waypoint? GetCurWaypoint() => Waypoints.GetFirst(); + public AI_Waypoint? GetGoalWaypoint() => Waypoints.GetLast(); public Vector3 CurWaypointPos() { if (GetCurWaypoint() != null) @@ -38,18 +66,286 @@ public Vector3 CurWaypointPos() { return gm_InvalidWaypoint.GetPos(); } + public Vector3 NextWaypointPos() { + if (GetCurWaypoint() != null && GetCurWaypoint()!.GetNext() != null) + return GetCurWaypoint()!.GetNext()!.GetPos(); + AssertMsg(false, "Invalid call to NextWaypointPos()"); + return gm_InvalidWaypoint.GetPos(); + } + + public float CurWaypointYaw() => GetCurWaypoint()!.Yaw; + + public WaypointFlags CurWaypointFlags() { + if (GetCurWaypoint() == null) + return 0; + else + return GetCurWaypoint()!.Flags(); + } + + public Navigation CurWaypointNavType() { + if (GetCurWaypoint() == null) + return Navigation.None; + else + return GetCurWaypoint()!.NavType(); + } + + public float GetPathLength() { + AI_Waypoint? last = Waypoints.GetLast(); + if (last != null && last.PathDistGoal == -1) + ComputeRouteGoalDistances(last); + AI_Waypoint? current = GetCurWaypoint(); + return current != null ? current.PathDistGoal : 0; + } + + public float GetPathDistanceToGoal(in Vector3 startPos) { + AI_Waypoint? current = GetCurWaypoint(); + if (current != null) + return GetPathLength() + ComputePathDistance(current.NavType(), startPos, current.GetPos()); + return 0; + } + + public TimeUnit_t GetStartTime() => RouteStartTime; + + public void SetGoalTolerance(float tolerance) => GoalTolerance = tolerance; + public float GetGoalTolerance() => GoalTolerance; + + public void SetWaypointTolerance(float tolerance) => WaypointTolerance = tolerance; + public float GetWaypointTolerance() => WaypointTolerance; + public Activity GetMovementActivity() => ActivityValue; + public Activity SetMovementActivity(Activity activity) { + Assert(activity != Activity.ACT_RESET && activity != Activity.ACT_INVALID); + + Sequence = (int)Activity.ACT_INVALID; + return ActivityValue = activity; + } + + public int GetMovementSequence() => Sequence; + public int SetMovementSequence(int sequence) => Sequence = sequence; + public Activity GetArrivalActivity() { if (!Waypoints.IsEmpty()) return ArrivalActivity; return Activity.ACT_INVALID; } - public NavGoalType GoalType() => GoalTypeValue; + public void SetArrivalActivity(Activity activity) { + ArrivalActivity = activity; + ArrivalSequence = (int)Activity.ACT_INVALID; + } + + public int GetArrivalSequence() { + if (!Waypoints.IsEmpty()) + return ArrivalSequence; + return (int)Activity.ACT_INVALID; + } + + public void SetArrivalSequence(int sequence) => ArrivalSequence = sequence; + + public void SetGoalDirection(in Vector3 goalDirection) { + GoalDirectionTarget.Set(null); + GoalDirection = goalDirection; + MathLib.VectorNormalize(ref GoalDirection); + } + + public void SetGoalDirection(BaseEntity? target) { + GoalDirectionTarget.Set(target); + + if (target != null) { + AI_Waypoint? last = Waypoints.GetLast(); + if (last != null) { + GoalDirection = target.GetAbsOrigin() - last.VecLocation; + MathLib.VectorNormalize(ref GoalDirection); + } + } + } + + public Vector3 GetGoalDirection(in Vector3 startPos) { + BaseEntity? goalDirectionTarget = GoalDirectionTarget.Get(); + if (goalDirectionTarget != null) { + AI_Waypoint? last = Waypoints.GetLast(); + if (last != null) { + AI_Waypoint? prev = last.GetPrev(); + if (prev != null) { + Vector3 goalDirection = goalDirectionTarget.GetAbsOrigin() - prev.VecLocation; + MathLib.VectorNormalize(ref goalDirection); + return goalDirection; + } + else { + Vector3 goalDirection = goalDirectionTarget.GetAbsOrigin() - startPos; + MathLib.VectorNormalize(ref goalDirection); + return goalDirection; + } + } + } + else if (GoalDirection == vec3_origin) { + AI_Waypoint? last = Waypoints.GetLast(); + if (last != null) { + AI_Waypoint? prev = last.GetPrev(); + if (prev != null) { + Vector3 goalDirection = last.VecLocation - prev.VecLocation; + MathLib.VectorNormalize(ref goalDirection); + return goalDirection; + } + else { + Vector3 goalDirection = last.VecLocation - startPos; + MathLib.VectorNormalize(ref goalDirection); + return goalDirection; + } + } + } + + return GoalDirection; + } + + public void SetGoalSpeed(float speed) => GoalSpeed = speed; + + public void SetGoalSpeed(BaseEntity? target) => GoalSpeedTarget.Set(target); + + public float GetGoalSpeed(in Vector3 startPos) { + BaseEntity? goalSpeedTarget = GoalSpeedTarget.Get(); + if (goalSpeedTarget != null) { + Vector3 goalDirection = GetGoalDirection(startPos); + Vector3 targetVelocity = goalSpeedTarget.GetSmoothedVelocity(); + float dot = Vector3.Dot(goalDirection, targetVelocity); + dot = Math.Max(0.0f, dot); + if (GoalSpeed > 0.0) + return dot + GoalSpeed; + return dot; + } + return GoalSpeed; + } + + public void SetGoalStoppingDistance(float distance) => GoalStoppingDistance = distance; + + public float GetGoalStoppingDistance() => GoalStoppingDistance; + public void SetTarget(BaseEntity? target) => Target.Set(target); + public void ClearTarget() { + Target.Set(null); + TargetOffset = vec3_origin; + } + public void SetTargetOffset(in Vector3 offset) => TargetOffset = offset; public BaseEntity? GetTarget() => Target.Get(); + public void SetGoalType(NavGoalType goalType) { +#if DEBUG + if (GoalTypeValue != Server.NavGoalType.None && goalType != Server.NavGoalType.None) + DevMsg("GetCurWaypoint Goal Type Set Twice!\n"); +#endif + + if (GoalTypeValue != Server.NavGoalType.None) { + RouteStartTime = gpGlobals.CurTime; + GoalTypeSet = true; + } + else + GoalTypeSet = false; + + GoalTypeValue = goalType; + } + + public void SetGoalPosition(in Vector3 goalPos) { +#if DEBUG + if (GoalPosSet) + DevMsg("GetCurWaypoint Goal Position Set Twice!\n"); +#endif + + GoalPosSet = true; + GoalPos = goalPos + TargetOffset; + } + + public void SetLastNodeAsGoal(bool reset = false) { +#if DEBUG + if (!reset && GoalPosSet) + DevMsg("GetCurWaypoint Goal Position Set Twice!\n"); +#endif + + if (GetCurWaypoint() != null) { + AI_Waypoint? waypoint = GetCurWaypoint(); + + while (waypoint != null) { + if (waypoint.GetNext() == null) { + GoalPos = waypoint.GetPos(); + GoalPosSet = true; + waypoint.ModifyFlags(WaypointFlags.ToGoal, true); + return; + } + waypoint = waypoint.GetNext(); + } + } + } + + public void ResetGoalPosition(in Vector3 goalPos) { + GoalPosSet = true; + GoalPos = goalPos + TargetOffset; + } + + public Vector3 BaseGoalPosition() { +#if DEBUG + if (!GoalPosSet) + DevMsg("GetCurWaypoint Goal Position Never Set!\n"); +#endif + + return GoalPos - TargetOffset; + } + + public ref readonly Vector3 ActualGoalPosition() { +#if DEBUG + if (!GoalPosSet) + DevMsg("GetCurWaypoint Goal Position Never Set!\n"); +#endif + + return ref GoalPos; + } + + public NavGoalType GoalType() => GoalTypeValue; + + public void SetGoalFlags(AI_NavGoalFlags flags) => GoalFlagsValue = flags; + public AI_NavGoalFlags GoalFlags() => GoalFlagsValue; + + public void Advance() { + if (CurWaypointIsGoal()) + return; + + if (GetCurWaypoint()!.GetNext() != null) { + AI_Waypoint next = GetCurWaypoint()!.GetNext()!; + + if ((GetCurWaypoint()!.Flags() & WaypointFlags.ToNode) != 0) + LastNodeReached = GetCurWaypoint()!.NodeID; + + GetCurWaypoint()!.Delete(); + SetWaypoints(next); + + return; + } + else { + DevMsg("!!ERROR!! Force end of route with no goal!\n"); + GetCurWaypoint()!.ModifyFlags(WaypointFlags.ToGoal, true); + } + } + + public bool CurWaypointIsGoal() { + if (GetCurWaypoint() == null) + return false; + + if ((GetCurWaypoint()!.Flags() & WaypointFlags.ToGoal) != 0) { +#if DEBUG + if (GetCurWaypoint()!.GetNext() != null) + DevMsg("!!ERROR!! Goal is not last waypoint!\n"); + if ((GetCurWaypoint()!.GetPos() - GoalPos).Length() > 0.1) + DevMsg("!!ERROR!! Last waypoint isn't in goal position!\n"); +#endif + return true; + } +#if DEBUG + if (GetCurWaypoint()!.GetNext() == null) + DevMsg("!!ERROR!! GetCurWaypoint has no goal!\n"); +#endif + + return false; + } + public void Clear() { Waypoints.RemoveAll(); @@ -79,6 +375,25 @@ public void Clear() { GoalStoppingDistance = 0.0f; } + public int GetLastNodeReached() => LastNodeReached; + public void ClearWaypoints() { + Waypoints.RemoveAll(); + LastNodeReached = NO_NODE; + } + + static void ComputeRouteGoalDistances(AI_Waypoint goalWaypoint) { + AI_Waypoint curWaypoint = goalWaypoint; + curWaypoint.PathDistGoal = 0; + while (curWaypoint.GetPrev() != null) { + AI_Waypoint prev = curWaypoint.GetPrev()!; + + float waypointDist = ComputePathDistance(curWaypoint.NavType(), prev.GetPos(), curWaypoint.GetPos()); + prev.PathDistGoal = curWaypoint.PathDistGoal + waypointDist; + + curWaypoint = prev; + } + } + readonly AI_WaypointList Waypoints = new(); float GoalTolerance; @@ -99,9 +414,9 @@ public void Clear() { bool GoalTypeSet; NavGoalType GoalTypeValue; - uint GoalFlagsValue; + AI_NavGoalFlags GoalFlagsValue; - float RouteStartTime; + TimeUnit_t RouteStartTime; Vector3 GoalDirection; EHANDLE GoalDirectionTarget = new(); @@ -111,5 +426,5 @@ public void Clear() { float GoalStoppingDistance; - static readonly AI_Waypoint gm_InvalidWaypoint = new(); + static readonly AI_Waypoint gm_InvalidWaypoint = new(vec3_origin, 0, Navigation.None, 0, 0); } diff --git a/Game.Server/AI_Waypoint.cs b/Game.Server/AI_Waypoint.cs index a3f3951a0..f1854a162 100644 --- a/Game.Server/AI_Waypoint.cs +++ b/Game.Server/AI_Waypoint.cs @@ -17,6 +17,30 @@ public static void DeleteAll(AI_Waypoint? waypointList) { prevWaypoint.Delete(); } } + + public static void AddWaypointLists(AI_Waypoint oldRoute, AI_Waypoint? addRoute) { + AI_Waypoint waypoint = oldRoute; + + while (waypoint.GetNext() != null) + waypoint = waypoint.GetNext()!; + + waypoint.ModifyFlags(WaypointFlags.ToGoal, false); + + if (addRoute != null && + waypoint.NodeID != NO_NODE && + waypoint.NodeID == addRoute.NodeID) { + AI_Waypoint? next = addRoute.GetNext(); + addRoute.Delete(); + waypoint.SetNext(next); + } + else + waypoint.SetNext(addRoute); + + while (waypoint.GetNext() != null) + waypoint = waypoint.GetNext()!; + + waypoint.ModifyFlags(WaypointFlags.ToGoal, true); + } } [Flags] @@ -39,6 +63,16 @@ public AI_Waypoint() { PathDistGoal = -1; } + public AI_Waypoint(in Vector3 initPosition, float initYaw, Navigation initNavType, WaypointFlags initWaypointFlags, int initNodeID) { + VecLocation = initPosition; + Yaw = initYaw; + WPType = initNavType; + WaypointFlags = initWaypointFlags; + NodeID = initNodeID; + + PathDistGoal = -1; + } + public void Delete() { AssertValid(); if (Next != null) { @@ -61,6 +95,29 @@ public void AssertValid() { public WaypointFlags Flags() => WaypointFlags; public Navigation NavType() => WPType; + public void ModifyFlags(WaypointFlags flags, bool enable) { + if (enable) + WaypointFlags |= flags; + else + WaypointFlags &= ~flags; + } + + public bool IsReducible() => Next != null && WPType == Next.WPType && (WaypointFlags & (WaypointFlags.ToGoal | WaypointFlags.ToPathCorner | WaypointFlags.DontSimplify)) == 0; + + public void SetNext(AI_Waypoint? p) { + if (Next != null) + Next.Prev = null; + + Next = p; + + if (Next != null) { + if (Next.Prev != null) + Next.Prev.Next = null; + + Next.Prev = this; + } + } + public AI_Waypoint? GetNext() => Next; public AI_Waypoint? GetPrev() => Prev; @@ -98,6 +155,26 @@ public AI_WaypointList(AI_Waypoint? firstWaypoint) { public AI_Waypoint? GetFirst() => FirstWaypoint; + public AI_Waypoint? GetLast() { + AI_Waypoint? p = GetFirst(); + if (p == null) + return null; + while (p.GetNext() != null) + p = p.GetNext()!; + + return p; + } + + public void Set(AI_Waypoint? route) => FirstWaypoint = route; + + public void PrependWaypoints(AI_Waypoint waypoints) { + AddWaypointLists(waypoints, GetFirst()); + Set(waypoints); + } + + public void PrependWaypoint(in Vector3 newPoint, Navigation navType, WaypointFlags waypointFlags, float yaw = 0) => + PrependWaypoints(new AI_Waypoint(newPoint, yaw, navType, waypointFlags, NO_NODE)); + public void RemoveAll() { DeleteAll(FirstWaypoint); FirstWaypoint = null; From b253f227cce92445e1b1dc31d1431c8274519dbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:55:18 +0300 Subject: [PATCH 25/73] Port node link shuffling, floor height and hint types --- Game.Server/AI_BaseNPC.cs | 2 +- Game.Server/AI_Hint.cs | 78 ++++++++++++++++++++++++++++++++++++++- Game.Server/AI_Network.cs | 40 ++++++++++++++++++++ Game.Server/AI_Node.cs | 39 ++++++++++++++++++++ 4 files changed, 157 insertions(+), 2 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 5a52e3862..66edaca3f 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -3517,7 +3517,7 @@ public virtual void OnScheduleChange() { } } - public virtual float GetHintDelay(short hintType) => 0; + public virtual float GetHintDelay(Hint hintType) => 0; public Activity GetIdealActivity() => IdealActivity; diff --git a/Game.Server/AI_Hint.cs b/Game.Server/AI_Hint.cs index 1c2c060b6..a1099ba4c 100644 --- a/Game.Server/AI_Hint.cs +++ b/Game.Server/AI_Hint.cs @@ -1,9 +1,85 @@ namespace Game.Server; +public enum Hint : short +{ + Any = -1, + None = 0, + NotUsedWorldDoor, + WorldWindow, + NotUsedWorldButton, + NotUsedWorldMachinery, + NotUsedWorldLedge, + NotUsedWorldLightSource, + NotUsedWorldHeatSource, + NotUsedWorldBlinkingLight, + NotUsedWorldBrightColors, + NotUsedWorldHumanBlood, + NotUsedWorldAlienBlood, + + WorldWorkPosition, + WorldVisuallyInteresting, + WorldVisuallyInterestingDontAim, + WorldInhibitCombineMines, + WorldVisuallyInterestingStealth, + + TacticalCoverMed = 100, + TacticalCoverLow, + TacticalSpawn, + TacticalPinch, + NotUsedTacticalGuard, + TacticalEnemyDisadvantaged, + NotUsedHealthKit, + + NotUsedUrbanStreetcorner = 200, + NotUsedUrbanStreetlamp, + NotUsedUrbanDarkSpot, + NotUsedUrbanPoster, + NotUsedUrbanShelter, + + NotUsedAssassinSecluded = 300, + NotUsedAssassinRafters, + NotUsedAssassinGround, + NotUsedAssassinMonkeybars, + + AntlionBurrowPoint = 400, + AntlionThumperFleePoint, + + HeadcrabBurrowPoint = 450, + HeadcrabExitPodPoint, + + NotUsedRollerPatrolPoint = 500, + NotUsedRollerCleanupPoint, + + NotUsedPstormRockSpawn = 600, + + CrowFlytoPoint = 700, + + BugPatrolPoint = 800, + + FollowWaitPoint = 900, + JumpOverride = 901, + PlayerSquadTransitonPoint = 902, + NpcExitPoint = 903, + StriderNode = 904, + + PlayerAllyMoveAwayDest = 950, + PlayerAllyFearDest, + + HL1WorldMachinery = 1000, + HL1WorldBlinkingLight, + HL1WorldHumanBlood, + HL1WorldAlienBlood, + + CStrikeHostageEscape = 1100, +} + public class AI_Hint : ServerOnlyEntity { - public short HintType() => throw new NotImplementedException(); + public const int SF_ALLOW_JUMP_UP = 65536; + + public Hint HintType() => throw new NotImplementedException(); public string? GetGroup() => throw new NotImplementedException(); + public int GetTargetNode() => throw new NotImplementedException(); public void Unlock(float delay) => throw new NotImplementedException(); } diff --git a/Game.Server/AI_Network.cs b/Game.Server/AI_Network.cs index d1517e66e..da57af02e 100644 --- a/Game.Server/AI_Network.cs +++ b/Game.Server/AI_Network.cs @@ -85,6 +85,18 @@ public AI_Network() { } } + public static int FindBSSmallest(ReadOnlySpan bitString, ReadOnlySpan floatArray, int arraySize) { + int winIndex = -1; + float winSize = float.MaxValue; + for (int i = 0; i < arraySize; i++) { + if (bitString[i] && (floatArray[i] < winSize)) { + winIndex = i; + winSize = floatArray[i]; + } + } + return winIndex; + } + int ListNodesInBox(Span list, in Vector3 mins, in Vector3 maxs, in NodeFilter filter) { int count = 0; @@ -350,6 +362,34 @@ public short CreateLink(int srcID, int destID) { public ref AI_Link GetLink(short link) => ref CollectionsMarshal.AsSpan(AILinks)[link]; + public bool IsConnected(int srcID, int destID) { + if (srcID > NodeCount || destID > NodeCount) { + DevMsg("IsConnected called with invalid node IDs!\n"); + return false; + } + + if (srcID == destID) + return true; + + int srcZone = AINode![srcID]!.GetZone(); + int destZone = AINode[destID]!.GetZone(); + + if (srcZone == (int)AI_ZoneIds.Solo || destZone == (int)AI_ZoneIds.Solo) + return false; + + if (srcZone == (int)AI_ZoneIds.Universal || destZone == (int)AI_ZoneIds.Universal) + return true; + +#if DEBUG + if (srcZone == (int)AI_ZoneIds.Unknown || destZone == (int)AI_ZoneIds.Unknown) { + DevMsg("Warning: Node found in unknown zone\n"); + return true; + } +#endif + + return srcZone == destZone; + } + public int NumNodes() => NodeCount; static int GetNodeWarningCount; diff --git a/Game.Server/AI_Node.cs b/Game.Server/AI_Node.cs index e3551cebf..4857323f5 100644 --- a/Game.Server/AI_Node.cs +++ b/Game.Server/AI_Node.cs @@ -1,3 +1,10 @@ +global using static Game.Server.AI_NodeGlobals; + +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Formats.BSP; using Source.Common.Mathematics; using System.Numerics; @@ -5,6 +12,25 @@ namespace Game.Server; +public static class AI_NodeGlobals +{ + public static float GetFloorZ(in Vector3 origin, float maxDrop) { + Util.TraceLine(origin, origin - new Vector3(0, 0, maxDrop), Mask.NPCSolidBrushOnly, null, CollisionGroup.None, out Trace tr); + + Util.TraceLine(origin, origin - new Vector3(0, 0, maxDrop), Mask.NPCSolid, null, CollisionGroup.None, out Trace trEnt); + + if (trEnt.Fraction < tr.Fraction) { + BaseEntity? e = trEnt.Ent; + if (e != null && (e.GetFlags() & EntityFlags.WorldBrush) != 0) + tr.EndPos = trEnt.EndPos; + } + + return tr.EndPos.Z; + } + + public static float GetFloorZ(in Vector3 origin) => GetFloorZ(origin, 384); +} + public enum AI_ZoneIds { Unknown = 0, @@ -68,6 +94,19 @@ public ref AI_Link GetLink(int destNodeId) { } public ref AI_Link GetLinkByIndex(int i) => ref Network.GetLink(Links[i]); + public void ShuffleLinks() { + FirstShuffledLink++; + if (FirstShuffledLink >= NumLinks()) + FirstShuffledLink = 0; + } + + public ref AI_Link GetShuffledLink(int num) { + int linkID = FirstShuffledLink + num; + if (linkID >= NumLinks()) + linkID -= NumLinks(); + return ref GetLinkByIndex(linkID); + } + public bool IsLocked() => NextUseTime > gpGlobals.CurTime; public void Lock(TimeUnit_t duration) => NextUseTime = gpGlobals.CurTime + duration; public void Unlock() => NextUseTime = gpGlobals.CurTime; From b7aa2dea0b566eb65a7322c04429a1616ee7d720 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:00:43 +0300 Subject: [PATCH 26/73] Port AI pathfinder --- Game.Server/AI_Pathfinder.cs | 1131 ++++++++++++++++++++++++++++++++++ 1 file changed, 1131 insertions(+) diff --git a/Game.Server/AI_Pathfinder.cs b/Game.Server/AI_Pathfinder.cs index 27cded016..b61f879fb 100644 --- a/Game.Server/AI_Pathfinder.cs +++ b/Game.Server/AI_Pathfinder.cs @@ -1,7 +1,61 @@ +global using static Game.Server.AI_PathfinderGlobals; + +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Formats.BSP; +using Source.Common.Mathematics; + +using System.Numerics; + namespace Game.Server; +[Flags] +public enum RouteBuildFlags +{ + Ground = 0x00000001, + Jump = 0x00000002, + Fly = 0x00000004, + Climb = 0x00000008, + GiveWay = 0x00000010, + Triang = 0x00000020, + IgnoreNPCs = 0x00000040, + CollideNPCs = 0x00000080, + GetClose = 0x00000100, +} + +public static class AI_PathfinderGlobals +{ + public static readonly float[] MAX_LOCAL_NAV_DIST_GROUND = [50 * 12, 25 * 12]; + public static readonly float[] MAX_LOCAL_NAV_DIST_FLY = [750 * 12, 750 * 12]; + + public static readonly ConVar ai_no_local_paths = new("ai_no_local_paths", "0"); + + public static Navigation MoveBitsToNavType(Capability bits) { + switch (bits) { + case Capability.MoveGround: + return Navigation.Ground; + case Capability.MoveFly: + return Navigation.Fly; + case Capability.MoveClimb: + return Navigation.Climb; + case Capability.MoveJump: + return Navigation.Jump; + default: + Assert(false); + return Navigation.None; + } + } +} + public class AI_Pathfinder : AI_Component { + const int MAX_NODE_TRIES = 4; + const int MAX_TRIANGULATIONS = 2; + const float MAX_TRIAGULATION_DIST = 32 * 12; + public AI_Pathfinder(AI_BaseNPC? outer) : base(outer) { Network = null; } @@ -11,5 +65,1082 @@ public void Init(AI_Network? network) { Network = network; } + AI_HullType GetHullType() => GetOuter()!.GetHullType(); + Capability CapabilitiesGet() => GetOuter()!.CapabilitiesGet(); + + bool UseStrongOptimizations() { + if (!AIStrongOpt()) + return false; + + if (GetOuter()!.Classify() == Class_T.PlayerAllyVital) + return false; + + return true; + } + + Navigation ComputeWaypointType(AI_Node?[] nodes, int parentID, int destID) { + Navigation navType = Navigation.None; + + AI_Node node = nodes[parentID]!; + for (int link = 0; link < node.NumLinks(); link++) { + ref AI_Link nodeLink = ref node.GetLinkByIndex(link); + if (nodeLink.DestNodeID(parentID) == destID) { + Capability linkMoveTypeBits = nodeLink.AcceptedMoveTypes[(int)GetHullType()]; + Capability moveTypeBits = linkMoveTypeBits & CapabilitiesGet(); + if (moveTypeBits == 0 && linkMoveTypeBits == Capability.MoveJump) { + Assert(node.GetHint() != null && node.GetHint()!.HintType() == Hint.JumpOverride); + nodes[destID]!.Lock(0.3); + moveTypeBits = linkMoveTypeBits; + } + Navigation linkType = MoveBitsToNavType(moveTypeBits); + + Assert(navType == Navigation.None || navType == linkType); + navType = linkType; + break; + } + } + + if (navType == Navigation.None) { + node = nodes[destID]!; + for (int link = 0; link < node.NumLinks(); link++) { + ref AI_Link nodeLink = ref node.GetLinkByIndex(link); + if (nodeLink.DestNodeID(parentID) == destID) { + Capability npcMoveBits = CapabilitiesGet(); + Capability nodeMoveBits = nodeLink.AcceptedMoveTypes[(int)GetHullType()]; + Capability moveTypeBits = npcMoveBits & nodeMoveBits; + Navigation linkType = MoveBitsToNavType(moveTypeBits); + + Assert(navType == Navigation.None || navType == linkType); + navType = linkType; + + DevMsg("Note: Strange link found between nodes in AI node graph\n"); + break; + } + } + } + + AssertMsg(navType != Navigation.None, "Pathfinder appears to have output a path with consecutive nodes thate are not actually connected\n"); + + return navType; + } + + AI_Waypoint? MakeRouteFromParents(ReadOnlySpan parentArray, int endID) { + AI_Waypoint? oldWaypoint = null; + int currentID = endID; + + AI_Node?[] aiNode = GetNetwork()!.AccessNodes()!; + + while (currentID != NO_NODE) { + int prevID = parentArray[currentID]; + + int destID; + if (prevID != NO_NODE) + destID = prevID; + else { + if (oldWaypoint == null) + return null; + destID = oldWaypoint.NodeID; + } + + Navigation waypointType = ComputeWaypointType(aiNode, currentID, destID); + + Assert(waypointType != Navigation.None); + + AI_Waypoint newWaypoint = new(aiNode[currentID]!.GetPosition(GetHullType()), + aiNode[currentID]!.GetYaw(), waypointType, WaypointFlags.ToNode, currentID); + + newWaypoint.SetNext(oldWaypoint); + oldWaypoint = newWaypoint; + + currentID = prevID; + } + + return oldWaypoint; + } + + bool IsLinkStillStale(Capability moveType, ref AI_Link nodeLink) { + if (IgnoreStaleLinks) + return false; + + if ((nodeLink.LinkInfo & LinkInfo.StaleSuggested) == 0) + return false; + + if (gpGlobals.CurTime < nodeLink.TimeStaleExpires) + return true; + + if (gpGlobals.CurTime == LastStaleLinkCheckTime) + return true; + else + LastStaleLinkCheckTime = gpGlobals.CurTime; + + if (CheckStaleRoute(GetNetwork()!.GetNode(nodeLink.SrcID)!.GetPosition(GetHullType()), + GetNetwork()!.GetNode(nodeLink.DestID)!.GetPosition(GetHullType()), moveType)) { + nodeLink.LinkInfo &= ~LinkInfo.StaleSuggested; + return false; + } + + nodeLink.TimeStaleExpires = gpGlobals.CurTime + 1.0; + + return true; + } + + public int NearestNodeToNPC() => GetNetwork()!.NearestNodeToPoint(GetOuter(), GetOuter()!.GetAbsOrigin()); + + public int NearestNodeToPoint(in Vector3 origin) => GetNetwork()!.NearestNodeToPoint(GetOuter(), origin); + + public AI_Waypoint? FindBestPath(int startID, int endID) { + if (GetNetwork()!.NumNodes() == 0) + return null; + + int nodes = GetNetwork()!.NumNodes(); + AI_Node?[] aiNode = GetNetwork()!.AccessNodes()!; + AI_HullType hull = GetHullType(); + + Span openBS = stackalloc bool[nodes]; + Span closeBS = stackalloc bool[nodes]; + + Span nodeG = stackalloc float[nodes]; + Span nodeH = stackalloc float[nodes]; + Span nodeF = stackalloc float[nodes]; + Span nodeP = stackalloc int[nodes]; + + for (int node = 0; node < nodes; node++) { + nodeG[node] = float.MaxValue; + nodeP[node] = -1; + } + + nodeG[startID] = 0; + + nodeH[startID] = 0.1f * (aiNode[startID]!.GetPosition(hull) - aiNode[endID]!.GetPosition(hull)).Length(); + nodeF[startID] = nodeG[startID] + nodeH[startID]; + + openBS[startID] = true; + closeBS[startID] = true; + + while (openBS.Contains(true)) { + int smallestID = AI_Network.FindBSSmallest(openBS, nodeF, nodes); + + openBS[smallestID] = false; + + AI_Node smallestNode = aiNode[smallestID]!; + + if (GetOuter()!.IsUnusableNode(smallestID, smallestNode.GetHint())) + continue; + + if (smallestID == endID) + return MakeRouteFromParents(nodeP, endID); + + for (int link = 0; link < smallestNode.NumLinks(); link++) { + ref AI_Link nodeLink = ref smallestNode.GetLinkByIndex(link); + + if (!IsLinkUsable(ref nodeLink, smallestID)) + continue; + + Capability moveType = nodeLink.AcceptedMoveTypes[(int)hull] & CapabilitiesGet(); + int testID = nodeLink.DestNodeID(smallestID); + + Vector3 r1 = smallestNode.GetPosition(hull); + Vector3 r2 = aiNode[testID]!.GetPosition(hull); + float dist = GetOuter()!.GetNavigator()!.MovementCost(moveType, r1, r2); + + if (dist == float.MaxValue) + continue; + + float newG = nodeG[smallestID] + dist; + + if (!closeBS[testID] || (newG < nodeG[testID])) { + nodeP[testID] = smallestID; + nodeG[testID] = newG; + nodeH[testID] = (aiNode[testID]!.GetPosition(hull) - aiNode[endID]!.GetPosition(hull)).Length(); + nodeF[testID] = nodeG[testID] + nodeH[testID]; + + closeBS[testID] = true; + openBS[testID] = true; + } + } + } + + return null; + } + + public AI_Waypoint? FindShortRandomPath(int startID, float minPathLength, in Vector3 directionIn = default) { + Span neighbor = stackalloc int[AI_Network.AI_MAX_NODE_LINKS]; + Span staleNeighbor = stackalloc int[AI_Network.AI_MAX_NODE_LINKS]; + int numNeighbors = 1; + int numStaleNeighbors = 0; + int neighborID = NO_NODE; + + int nodes = GetNetwork()!.NumNodes(); + AI_Node?[]? aiNode = GetNetwork()!.AccessNodes(); + + if (nodes == 0) + return null; + + GetOuter()?.Remember(AI_MemoryFlags.TaskExpensive); + + Span nodeParent = stackalloc int[nodes]; + Span closeBS = stackalloc bool[nodes]; + Vector3 direction = directionIn; + + if (aiNode![startID]!.NumLinks() == 0) + return null; + + nodeParent[startID] = NO_NODE; + neighbor[0] = startID; + + float pathLength = 0; + int searchCount = 0; + while ((pathLength < minPathLength) || + (neighborID != NO_NODE && aiNode[neighborID]!.NodeType == NodeType.Climb)) { + searchCount++; + + if (neighborID != NO_NODE && + numNeighbors == 0 && + numStaleNeighbors == 0) { + if (aiNode[neighborID]!.NodeType == NodeType.Climb) + return null; + else + return MakeRouteFromParents(nodeParent, neighborID); + } + + int lastID = neighborID; + + if (direction != vec3_origin) { + float bestDot = -1; + Vector3 lastPos; + + if (lastID == NO_NODE) + lastPos = GetOuter()!.GetLocalOrigin(); + else + lastPos = aiNode[lastID]!.GetOrigin(); + + if (numNeighbors == 0) + neighborID = staleNeighbor[random.RandomInt(0, numStaleNeighbors - 1)]; + else { + for (int i = 0; i < numNeighbors; i++) { + Vector3 nodeDir = lastPos - aiNode[neighbor[i]]!.GetOrigin(); + MathLib.VectorNormalize(ref nodeDir); + float dotPr = Vector3.Dot(direction, nodeDir); + if (dotPr > bestDot) { + bestDot = dotPr; + neighborID = neighbor[i]; + } + } + } + + if (neighborID != NO_NODE) { + direction = lastPos - aiNode[neighborID]!.GetOrigin(); + MathLib.VectorNormalize(ref direction); + } + } + else if (numNeighbors != 0) + neighborID = neighbor[random.RandomInt(0, numNeighbors - 1)]; + else + neighborID = staleNeighbor[random.RandomInt(0, numStaleNeighbors - 1)]; + + if (neighborID < 0) + return null; + + nodeParent[neighborID] = lastID; + closeBS[neighborID] = true; + + if (lastID != NO_NODE) + pathLength += (aiNode[lastID]!.GetOrigin() - aiNode[neighborID]!.GetOrigin()).Length(); + + if ((pathLength >= minPathLength || searchCount > 20) && + aiNode[neighborID]!.NodeType != NodeType.Climb) + return MakeRouteFromParents(nodeParent, neighborID); + + numNeighbors = 0; + numStaleNeighbors = 0; + + AI_Node neighborNode = aiNode[neighborID]!; + neighborNode.ShuffleLinks(); + for (int link = 0; link < neighborNode.NumLinks(); link++) { + if (numStaleNeighbors == staleNeighbor.Length) { + AssertMsg(false, "Array overflow"); + return null; + } + if (numNeighbors == staleNeighbor.Length) { + AssertMsg(false, "Array overflow"); + return null; + } + + ref AI_Link nodeLink = ref neighborNode.GetShuffledLink(link); + int testID = nodeLink.DestNodeID(neighborID); + + if (closeBS[testID]) + continue; + + if (testID == lastID) + continue; + + if (!IsLinkUsable(ref nodeLink, neighborID)) + continue; + + if (aiNode[testID]!.IsLocked()) { + staleNeighbor[numStaleNeighbors] = testID; + numStaleNeighbors++; + } + else { + neighbor[numNeighbors] = testID; + numNeighbors++; + } + } + } + + return MakeRouteFromParents(nodeParent, neighborID); + } + + public bool IsLinkUsable(ref AI_Link link, int startID) { + if ((link.LinkInfo & LinkInfo.Off) != 0) { + AI_DynamicLink? dynamicLink = link.DynamicLink; + + if (dynamicLink == null || string.IsNullOrEmpty(dynamicLink.AllowUse)) + return false; + + string allowUse = dynamicLink.AllowUse; + if (dynamicLink.InvertAllow) { + if (GetOuter()!.NameMatches(allowUse) || GetOuter()!.ClassMatches(allowUse)) + return false; + } + else { + if (!GetOuter()!.NameMatches(allowUse) && !GetOuter()!.ClassMatches(allowUse)) + return false; + } + } + + int endID = link.DestNodeID(startID); + + Capability linkMoveTypes = link.AcceptedMoveTypes[(int)GetHullType()]; + Capability moveType = linkMoveTypes & CapabilitiesGet(); + + AI_Node startNode = GetNetwork()!.GetNode(startID)!; + AI_Node endNode = GetNetwork()!.GetNode(endID)!; + + if ((linkMoveTypes & Capability.MoveJump) != 0 && moveType == 0) { + AI_Hint? startHint = startNode.GetHint(); + AI_Hint? endHint = endNode.GetHint(); + if (startHint != null && endHint != null) { + if (startHint.HintType() == Hint.JumpOverride && + endHint.HintType() == Hint.JumpOverride && + (((startHint.SpawnFlags | endHint.SpawnFlags) & AI_Hint.SF_ALLOW_JUMP_UP) != 0 || startHint.GetAbsOrigin().Z > endHint.GetAbsOrigin().Z)) { + if (!startNode.IsLocked()) { + if (startHint.GetTargetNode() == -1 || startHint.GetTargetNode() == endID) + moveType = Capability.MoveJump; + } + } + } + } + + if (moveType == 0) + return false; + + if (GetOuter()!.IsUnusableNode(endID, endNode.GetHint())) + return false; + + if (moveType == Capability.MoveJump) { + if (!GetOuter()!.IsJumpLegal(startNode.GetPosition(GetHullType()), + endNode.GetPosition(GetHullType()), + endNode.GetPosition(GetHullType()))) + return false; + } + + if ((link.LinkInfo & LinkInfo.StaleSuggested) != 0) { + if (IsLinkStillStale(moveType, ref link)) + return false; + } + return true; + } + + static RouteBuildFlags NPCBuildFlags(AI_BaseNPC npc, in Vector3 origin) { + if (npc.GetLocalOrigin() == origin && npc.GetNavType() == Navigation.Climb) + return RouteBuildFlags.Climb; + else if ((npc.CapabilitiesGet() & Capability.MoveFly) != 0) + return RouteBuildFlags.Fly | RouteBuildFlags.GiveWay; + else if ((npc.CapabilitiesGet() & Capability.MoveGround) != 0) { + RouteBuildFlags buildFlags = RouteBuildFlags.Ground | RouteBuildFlags.GiveWay; + if ((npc.CapabilitiesGet() & Capability.MoveJump) != 0) + buildFlags |= RouteBuildFlags.Jump; + + return buildFlags; + } + return 0; + } + + AI_Waypoint CreateNodeWaypoint(AI_HullType hullType, int nodeID, WaypointFlags nodeFlags = 0) { + AI_Node node = GetNetwork()!.GetNode(nodeID)!; + + Navigation navType = node.NodeType switch { + NodeType.Climb => Navigation.Climb, + NodeType.Air => Navigation.Fly, + _ => Navigation.Ground, + }; + + return new AI_Waypoint(node.GetPosition(hullType), node.GetYaw(), navType, WaypointFlags.ToNode | nodeFlags, nodeID); + } + + AI_Waypoint? RouteToNode(in Vector3 origin, RouteBuildFlags buildFlags, int nodeID, float goalTolerance) { + buildFlags |= NPCBuildFlags(GetOuter()!, origin); + buildFlags &= ~RouteBuildFlags.GetClose; + + Vector3 nodePosition = GetNetwork()!.GetNode(nodeID)!.GetPosition(GetHullType()); + if (origin == nodePosition) + return CreateNodeWaypoint(GetHullType(), nodeID, WaypointFlags.ToGoal); + + AI_Waypoint? result = BuildLocalRoute(origin, nodePosition, null, WaypointFlags.ToNode, nodeID, buildFlags, goalTolerance); + if (result != null) + result.NodeID = nodeID; + return result; + } + + AI_Waypoint? RouteFromNode(in Vector3 origin, RouteBuildFlags buildFlags, int nodeID, float goalTolerance) { + buildFlags |= NPCBuildFlags(GetOuter()!, origin); + buildFlags |= RouteBuildFlags.GetClose; + + AI_Node node = GetNetwork()!.GetNode(nodeID)!; + Vector3 nodePosition = node.GetPosition(GetHullType()); + + if (origin == nodePosition) + return CreateNodeWaypoint(GetHullType(), nodeID, WaypointFlags.ToGoal); + + AI_Waypoint? result = BuildLocalRoute(nodePosition, origin, null, WaypointFlags.ToGoal, NO_NODE, buildFlags, goalTolerance); + + if (result == null && + node.NodeType == NodeType.Climb && + (origin - nodePosition).Length2DSqr() < 32.0f * 32.0f && + GetOuter()!.GetMoveProbe()!.CheckStandPosition(nodePosition, Mask.NPCSolidBrushOnly)) + result = new AI_Waypoint(origin, 0, Navigation.Ground, WaypointFlags.ToGoal, nodeID); + + return result; + } + + AI_Waypoint? BuildSimpleRoute(Navigation navType, in Vector3 start, in Vector3 end, BaseEntity? target, WaypointFlags endFlags, int nodeID, NodeType nodeTargetType, float yaw) { + Assert(navType == Navigation.Jump || navType == Navigation.Climb); + if ((nodeID == NO_NODE) || (GetNetwork()!.GetNode(nodeID)!.NodeType == nodeTargetType)) { + GetOuter()!.GetMoveProbe()!.MoveLimit(navType, start, end, Mask.NPCSolid, target, out AIMoveTrace moveTrace); + + if (!IsMoveBlocked(moveTrace)) + return new AI_Waypoint(end, yaw, navType, endFlags, nodeID); + } + return null; + } + + AI_Waypoint? BuildComplexRoute(Navigation navType, in Vector3 start, in Vector3 end, BaseEntity? target, WaypointFlags endFlags, int nodeID, + RouteBuildFlags buildFlags, float yaw, float goalTolerance, float maxLocalNavDistance) { + float totalDist = ComputePathDistance(navType, start, end); + if (totalDist < 0.0625f) + return new AI_Waypoint(end, yaw, navType, endFlags, nodeID); + + Mask collideFlags = (buildFlags & RouteBuildFlags.IgnoreNPCs) != 0 ? Mask.NPCSolidBrushOnly : Mask.NPCSolid; + + bool checkGround = (GetOuter()!.CapabilitiesGet() & Capability.SkipNavGroundCheck) == 0; + + if (totalDist <= maxLocalNavDistance) { + GetOuter()!.GetMoveProbe()!.MoveLimit(navType, start, end, collideFlags, target, checkGround ? 100 : 0, out AIMoveTrace moveTrace); + + if (!IsMoveBlocked(moveTrace)) + return new AI_Waypoint(end, yaw, navType, endFlags, nodeID); + + if ((buildFlags & RouteBuildFlags.GetClose) != 0 && + (endFlags & WaypointFlags.ToGoal) != 0 && + moveTrace.DistObstructed <= goalTolerance) + return new AI_Waypoint(end, yaw, navType, endFlags, nodeID); + + if ((buildFlags & RouteBuildFlags.Triang) != 0) { + if (!UseStrongOptimizations() || (GetOuter()!.GetState() == NPCState.Script || GetOuter()!.IsCurSchedule(SCHED_SCENE_GENERIC, false))) { + AI_Waypoint? triangRoute = BuildTriangulationRoute(start, end, target, + endFlags, nodeID, yaw, totalDist - moveTrace.DistObstructed, navType); + + if (triangRoute != null) + return triangRoute; + } + } + + if (moveTrace.Status == AIMoveResult.BlockedNPC && (buildFlags & RouteBuildFlags.GiveWay) != 0) { + GetOuter()!.GetMoveProbe()!.MoveLimit(navType, start, end, Mask.NPCSolidBrushOnly, target, checkGround ? 100 : 0, out AIMoveTrace moveTrace2); + + if (!IsMoveBlocked(moveTrace2)) { + if (CanGiveWay(start, end, moveTrace.Obstruction!)) + return new AI_Waypoint(end, yaw, navType, endFlags, nodeID); + } + } + } + return null; + } + + AI_Waypoint? BuildJumpRoute(in Vector3 start, in Vector3 end, BaseEntity? target, WaypointFlags endFlags, int nodeID, RouteBuildFlags buildFlags, float yaw) + => BuildSimpleRoute(Navigation.Jump, start, end, target, endFlags, nodeID, NodeType.Ground, yaw); + + AI_Waypoint? BuildClimbRoute(in Vector3 start, in Vector3 end, BaseEntity? target, WaypointFlags endFlags, int nodeID, RouteBuildFlags buildFlags, float yaw) + => BuildSimpleRoute(Navigation.Climb, start, end, target, endFlags, nodeID, NodeType.Climb, yaw); + + AI_Waypoint? BuildGroundRoute(in Vector3 start, in Vector3 end, BaseEntity? target, WaypointFlags endFlags, int nodeID, RouteBuildFlags buildFlags, float yaw, float goalTolerance) + => BuildComplexRoute(Navigation.Ground, start, end, target, endFlags, nodeID, buildFlags, yaw, goalTolerance, MAX_LOCAL_NAV_DIST_GROUND[UseStrongOptimizations() ? 1 : 0]); + + AI_Waypoint? BuildFlyRoute(in Vector3 start, in Vector3 end, BaseEntity? target, WaypointFlags endFlags, int nodeID, RouteBuildFlags buildFlags, float yaw, float goalTolerance) + => BuildComplexRoute(Navigation.Fly, start, end, target, endFlags, nodeID, buildFlags, yaw, goalTolerance, MAX_LOCAL_NAV_DIST_FLY[UseStrongOptimizations() ? 1 : 0]); + + bool CanGiveWay(in Vector3 start, in Vector3 end, BaseEntity blocker) { + AI_BaseNPC? npcBlocker = blocker.MyNPCPointer(); + if (npcBlocker != null && npcBlocker.Edict() != null) { + Disposition dispBlockerToMe = npcBlocker.IRelationType(GetOuter()); + if (dispBlockerToMe == Disposition.LI || dispBlockerToMe == Disposition.NU) + return true; + + return false; + } + return false; + } + + public virtual AI_Waypoint? BuildTriangulationRoute(in Vector3 start, in Vector3 end, BaseEntity? target, WaypointFlags endFlags, int nodeID, + float yaw, float distToBlocker, Navigation navType) { + if (!Triangulate(navType, start, end, distToBlocker, target, out Vector3 apex)) + return null; + + AI_Waypoint waypoint2 = new(end, yaw, navType, endFlags, nodeID); + + AI_Waypoint waypoint1 = new(apex, 0, navType, WaypointFlags.ToDetour, NO_NODE); + waypoint1.SetNext(waypoint2); + + return waypoint1; + } + + static int GetNextPoint(int lastNode, int direction, int numNodes) { + int nextNode = lastNode + direction; + if (nextNode > (numNodes - 1)) + nextNode = 0; + else if (nextNode < 0) + nextNode = numNodes - 1; + + return nextNode; + } + + AI_Waypoint? BuildRouteThroughPoints(ReadOnlySpan points, int numPoints, int direction, int startIndex, int endIndex, Navigation navType, BaseEntity? target) { + AI_MoveProbe moveProbe = GetOuter()!.GetMoveProbe()!; + + AI_Waypoint? firstRoute = null; + AI_Waypoint? headRoute = null; + + int curIndex = startIndex; + int nextIndex; + + moveProbe.MoveLimit(navType, GetOuter()!.GetAbsOrigin(), points[startIndex], Mask.NPCSolid, target, out AIMoveTrace endTrace); + if (IsMoveBlocked(endTrace)) + return null; + + int runAwayCount = 0; + while (runAwayCount++ < numPoints) { + nextIndex = GetNextPoint(curIndex, direction, numPoints); + + moveProbe.MoveLimit(navType, points[curIndex], points[nextIndex], Mask.NPCSolid, target, out endTrace); + if (IsMoveBlocked(endTrace)) { + if (headRoute != null) + DeleteAll(headRoute); + + return null; + } + + if (headRoute == null) + firstRoute = headRoute = new AI_Waypoint(points[curIndex], 0.0f, navType, WaypointFlags.ToDetour, NO_NODE); + else { + AI_Waypoint newNode = new(points[curIndex], 0.0f, navType, WaypointFlags.ToDetour | WaypointFlags.DontSimplify, NO_NODE); + headRoute.SetNext(newNode); + headRoute = newNode; + } + + if (nextIndex == endIndex) { + AI_Waypoint newNode = new(points[endIndex], 0.0f, navType, WaypointFlags.ToDetour, NO_NODE); + headRoute.SetNext(newNode); + headRoute = newNode; + break; + } + + curIndex = nextIndex; + } + + return firstRoute; + } + + static int ClosestPointToPosition(in Vector3 position, ReadOnlySpan points, int numPoints) { + int bestNode = -1; + float bestDistSqr = float.MaxValue; + float distSqr; + for (int i = 0; i < numPoints; i++) { + distSqr = (points[i] - position).LengthSquared(); + if (distSqr < bestDistSqr) { + bestDistSqr = distSqr; + bestNode = i; + } + } + + return bestNode; + } + + static int ShortestDirectionThroughPoints(in Vector3 start, int startPoint, int endPoint, ReadOnlySpan points, int numPoints) { + const int clockwise = 1; + const int counterClockwise = -1; + + int curPoint = startPoint; + int nextPoint = GetNextPoint(startPoint, 1, numPoints); + + float startDistSqr = (start - points[startPoint]).LengthSquared(); + float distanceSqr = startDistSqr; + + for (int i = 0; i < numPoints; i++) { + distanceSqr += (points[curPoint] - points[nextPoint]).LengthSquared(); + + if (nextPoint == endPoint) + break; + + nextPoint = GetNextPoint(nextPoint, 1, numPoints); + } + + float bestDistanceSqr = distanceSqr; + + distanceSqr = startDistSqr; + + curPoint = startPoint; + nextPoint = GetNextPoint(startPoint, -1, numPoints); + + for (int i = 0; i < numPoints; i++) { + distanceSqr += (points[curPoint] - points[nextPoint]).LengthSquared(); + + if (distanceSqr > bestDistanceSqr) + break; + + if (nextPoint == endPoint) + return counterClockwise; + + nextPoint = GetNextPoint(nextPoint, -1, numPoints); + } + + return clockwise; + } + + public virtual AI_Waypoint? BuildOBBAvoidanceRoute(in Vector3 start, in Vector3 end, BaseEntity obstruction, BaseEntity? target, Navigation navType) { + if (obstruction.CollisionProp().IsPointInBounds(end)) + return null; + + Vector3 size = obstruction.CollisionProp().OBBSize(); + float width = GetOuter()!.GetHullWidth() * 0.5f; + + float widthPercX = width / size.X; + float widthPercY = width / size.Y; + + Span points = [ + obstruction.CollisionProp().NormalizedToWorldSpace(new(-widthPercX, 1 + widthPercY, 0.25f)), + obstruction.CollisionProp().NormalizedToWorldSpace(new(1 + widthPercX, 1 + widthPercY, 0.25f)), + obstruction.CollisionProp().NormalizedToWorldSpace(new(1 + widthPercX, -widthPercY, 0.25f)), + obstruction.CollisionProp().NormalizedToWorldSpace(new(-widthPercX, -widthPercY, 0.25f)), + ]; + + int startPoint = ClosestPointToPosition(start, points, points.Length); + int endPoint = ClosestPointToPosition(end, points, points.Length); + + if (startPoint == endPoint) + return null; + + int direction = ShortestDirectionThroughPoints(start, startPoint, endPoint, points, points.Length); + + AI_Waypoint? route = BuildRouteThroughPoints(points, points.Length, direction, startPoint, endPoint, navType, target); + if (route == null) { + route = BuildRouteThroughPoints(points, points.Length, -direction, startPoint, endPoint, navType, target); + if (route == null) + return null; + } + + return route; + } + + public virtual AI_Waypoint? BuildLocalRoute(in Vector3 start, in Vector3 end, BaseEntity? target, WaypointFlags endFlags, int nodeID, RouteBuildFlags buildFlags, float goalTolerance) { + float yaw; + if (nodeID != NO_NODE) + yaw = GetNetwork()!.GetNode(nodeID)!.GetYaw(); + else + yaw = 0; + + if ((buildFlags & RouteBuildFlags.Ground) != 0) { + AI_Waypoint? groundRoute = BuildGroundRoute(start, end, target, endFlags, nodeID, buildFlags, yaw, goalTolerance); + + if (groundRoute != null) + return groundRoute; + } + + if ((buildFlags & RouteBuildFlags.Fly) != 0) { + AI_Waypoint? flyRoute = BuildFlyRoute(start, end, target, endFlags, nodeID, buildFlags, yaw, goalTolerance); + + if (flyRoute != null) + return flyRoute; + } + + if ((buildFlags & RouteBuildFlags.Jump) != 0 && (CapabilitiesGet() & Capability.MoveJump) != 0) { + AI_Waypoint? jumpRoute = BuildJumpRoute(start, end, target, endFlags, nodeID, buildFlags, yaw); + + if (jumpRoute != null) + return jumpRoute; + } + + if ((buildFlags & RouteBuildFlags.Climb) != 0 && (CapabilitiesGet() & Capability.MoveClimb) != 0) { + AI_Waypoint? climbRoute = BuildClimbRoute(start, end, target, endFlags, nodeID, buildFlags, yaw); + + if (climbRoute != null) + return climbRoute; + } + + return null; + } + + public AI_Waypoint? BuildRoute(in Vector3 start, in Vector3 end, BaseEntity? target, float goalTolerance, Navigation curNavType = Navigation.None, bool localSucceedOnWithinTolerance = false) { + RouteBuildFlags buildFlags = 0; + bool tryLocal = !ai_no_local_paths.GetBool(); + + if (curNavType == Navigation.Climb) { + buildFlags = RouteBuildFlags.Climb; + tryLocal = false; + } + else if ((CapabilitiesGet() & Capability.MoveFly) != 0 || (CapabilitiesGet() & Capability.MoveSwim) != 0) + buildFlags = RouteBuildFlags.Fly | RouteBuildFlags.GiveWay | RouteBuildFlags.Triang; + else if ((CapabilitiesGet() & Capability.MoveGround) != 0) { + buildFlags = RouteBuildFlags.Ground | RouteBuildFlags.GiveWay | RouteBuildFlags.Triang; + if ((CapabilitiesGet() & Capability.MoveJump) != 0) + buildFlags |= RouteBuildFlags.Jump; + } + + if (localSucceedOnWithinTolerance) + buildFlags |= RouteBuildFlags.GetClose; + + AI_Waypoint? result = null; + + if (tryLocal && CanUseLocalNavigation()) + result = BuildLocalRoute(start, end, target, WaypointFlags.ToGoal, NO_NODE, buildFlags, goalTolerance); + + if (result == null) + result = BuildNodeRoute(start, end, buildFlags, goalTolerance); + + IgnoreStaleLinks = false; + + return result; + } + + public void UnlockRouteNodes(AI_Waypoint? path) { + AI_Node? node; + while (path != null) { + if (path.NodeID != NO_NODE && (node = GetNetwork()!.GetNode(path.NodeID)) != null && node.IsLocked()) + node.Unlock(); + path = path.GetNext(); + } + } + + public void SetIgnoreBadLinks() => IgnoreStaleLinks = true; + + public virtual AI_Waypoint? BuildRadialRoute(in Vector3 startPos, in Vector3 centerPos, in Vector3 goalPos, float radius, float arc, float stepDist, bool clockwise, float goalTolerance, bool airRoute) { + GetOuter()?.Remember(AI_MemoryFlags.TaskExpensive); + + float angleStep = 2.0f * MathF.Atan((0.5f * stepDist) / radius); + + if (clockwise) { + arc *= -1; + angleStep *= -1; + } + + Vector3 startDir = startPos - centerPos; + MathLib.VectorNormalize(ref startDir); + + float startAngle = MathLib.DEG2RAD(Util.VecToYaw(startDir)); + float endAngle = startAngle + MathLib.DEG2RAD(arc); + + startAngle += angleStep; + + AI_Waypoint? headRoute = null; + AI_Waypoint? nextRoute; + Vector3 lastPos = startPos; + RouteBuildFlags routeBits = airRoute ? RouteBuildFlags.Fly : RouteBuildFlags.Ground; + float curAngle = startAngle; + Vector3 nextPos; + + Assert((clockwise && curAngle > endAngle) || (!clockwise && curAngle < endAngle)); + + while (true) { + if ((clockwise && curAngle <= endAngle) || (!clockwise && curAngle >= endAngle)) + break; + + nextPos = centerPos; + nextPos.X += radius * MathF.Cos(curAngle); + nextPos.Y += radius * MathF.Sin(curAngle); + + nextRoute = BuildLocalRoute(lastPos, nextPos, null, 0, NO_NODE, routeBits, goalTolerance); + + if (nextRoute == null) + return null; + + nextRoute.ModifyFlags(WaypointFlags.DontSimplify, true); + + if (headRoute != null) + AddWaypointLists(headRoute, nextRoute); + else + headRoute = nextRoute; + + lastPos = nextPos; + + curAngle += angleStep; + } + + if (headRoute == null) + return null; + + AI_Waypoint? lastRoute = BuildLocalRoute(lastPos, goalPos, null, 0, NO_NODE, airRoute ? RouteBuildFlags.Fly : RouteBuildFlags.Ground, goalTolerance); + if (lastRoute == null) + return null; + + lastRoute.ModifyFlags(WaypointFlags.DontSimplify, false); + lastRoute.ModifyFlags(WaypointFlags.ToGoal, true); + + AddWaypointLists(headRoute, lastRoute); + + return headRoute; + } + + bool CheckStaleNavTypeRoute(Navigation navType, in Vector3 start, in Vector3 end) { + GetOuter()!.GetMoveProbe()!.MoveLimit(navType, start, end, Mask.NPCSolid, null, 100, AI_MoveLimitFlags.IgnoreTransients, out AIMoveTrace moveTrace); + + if (!IsMoveBlocked(moveTrace)) + return true; + + Vector3 delta = end - start; + float totalDist = delta.Length(); + + if (Triangulate(navType, start, end, totalDist - moveTrace.DistObstructed, null, out _)) + return true; + + if (moveTrace.Obstruction != null && moveTrace.Obstruction.MyNPCPointer() != null) { + GetOuter()!.GetMoveProbe()!.MoveLimit(navType, start, end, Mask.NPCSolidBrushOnly, null, out moveTrace); + + if (!IsMoveBlocked(moveTrace)) + return true; + } + + return false; + } + + bool CheckStaleRoute(in Vector3 start, in Vector3 end, Capability moveTypes) { + if ((moveTypes & Capability.MoveGround) != 0) { + if (CheckStaleNavTypeRoute(Navigation.Ground, start, end)) + return true; + } + + if ((moveTypes & Capability.MoveFly) != 0) { + if (CheckStaleNavTypeRoute(Navigation.Fly, start, end)) + return true; + } + + if ((moveTypes & Capability.MoveJump) != 0) { + GetOuter()!.GetMoveProbe()!.MoveLimit(Navigation.Jump, start, end, Mask.NPCSolid, null, out AIMoveTrace moveTrace); + if (!IsMoveBlocked(moveTrace)) + return true; + else { + GetOuter()!.GetMoveProbe()!.MoveLimit(Navigation.Jump, end, start, Mask.NPCSolid, null, out moveTrace); + if (!IsMoveBlocked(moveTrace)) + return true; + } + } + + if ((moveTypes & Capability.MoveClimb) != 0) { + GetOuter()!.GetMoveProbe()!.MoveLimit(Navigation.Climb, start, end, Mask.NPCSolid, null, out AIMoveTrace moveTrace); + if (!IsMoveBlocked(moveTrace)) + return true; + } + + return false; + } + + sealed class PathfindNearestNodeFilter(AI_Pathfinder pathfinder, Vector3 goal, bool toNode, RouteBuildFlags buildFlags, float goalTolerance) : INearestNodeFilter + { + int Tries; + readonly Capability MoveTypes = (Capability)(buildFlags & (RouteBuildFlags.Ground | RouteBuildFlags.Fly | RouteBuildFlags.Jump | RouteBuildFlags.Climb)); + + public AI_Waypoint? Route; + + public bool IsValid(AI_Node node) { + int staleLinks = 0; + if (!pathfinder.IgnoreStaleLinks) { + int hull = (int)pathfinder.GetOuter()!.GetHullType(); + for (int i = 0; i < node.NumLinks(); i++) { + ref AI_Link link = ref node.GetLinkByIndex(i); + if ((link.LinkInfo & (LinkInfo.StaleSuggested | LinkInfo.Off)) != 0) + staleLinks++; + else if ((link.AcceptedMoveTypes[hull] & MoveTypes) == 0) + staleLinks++; + } + } + + if (staleLinks != 0 && staleLinks == node.NumLinks()) + return false; + + RouteBuildFlags routeFlags = (Tries < MAX_TRIANGULATIONS) ? (RouteBuildFlags.IgnoreNPCs | RouteBuildFlags.Triang) : RouteBuildFlags.IgnoreNPCs; + + if (toNode) + Route = pathfinder.RouteToNode(goal, routeFlags, node.GetId(), goalTolerance); + else + Route = pathfinder.RouteFromNode(goal, routeFlags, node.GetId(), goalTolerance); + + Tries++; + + return Route != null; + } + + public bool ShouldContinue() => Route == null && Tries < MAX_NODE_TRIES; + } + + AI_Waypoint? BuildNearestNodeRoute(in Vector3 goal, bool toNode, RouteBuildFlags buildFlags, float goalTolerance, out int nearestNode) { + PathfindNearestNodeFilter filter = new(this, goal, toNode, buildFlags, goalTolerance); + nearestNode = GetNetwork()!.NearestNodeToPoint(GetOuter(), goal, true, filter); + + return filter.Route; + } + + public virtual AI_Waypoint? BuildNodeRoute(in Vector3 start, in Vector3 end, RouteBuildFlags buildFlags, float goalTolerance) { + if (GetNetwork()!.NumNodes() == 0) + return null; + + AI_Waypoint? srcRoute = BuildNearestNodeRoute(start, true, buildFlags, goalTolerance, out int srcID); + if (srcRoute == null) + return null; + + AI_Waypoint? destRoute = BuildNearestNodeRoute(end, false, buildFlags, goalTolerance, out int destID); + if (destRoute == null) { + DeleteAll(srcRoute); + return null; + } + + if (destID == srcID) { + AddWaypointLists(srcRoute, destRoute); + return srcRoute; + } + + if (!GetNetwork()!.IsConnected(srcID, destID)) + return null; + + AI_Waypoint? path = FindBestPath(srcID, destID); + + if (path == null) { + DeleteAll(srcRoute); + DeleteAll(destRoute); + return null; + } + + AddWaypointLists(srcRoute, path); + AddWaypointLists(srcRoute, destRoute); + + return srcRoute; + } + + bool TestTriangulationRoute(Navigation navType, in Vector3 start, in Vector3 apex, in Vector3 end, BaseEntity? targetEnt, out AIMoveTrace startTrace) { + AI_MoveProbe moveProbe = GetOuter()!.GetMoveProbe()!; + + bool pathClear = false; + + if (moveProbe.MoveLimit(navType, start, apex, Mask.NPCSolid, targetEnt, out startTrace)) { + if (moveProbe.MoveLimit(navType, apex, end, Mask.NPCSolid, targetEnt, out _)) + pathClear = true; + } + + return pathClear; + } + + public bool Triangulate(Navigation navType, in Vector3 start, in Vector3 endIn, float distToBlocker, BaseEntity? targetEnt, out Vector3 apex) { + apex = default; + + if (GetOuter()!.IsFlaggedEfficient()) + return false; + + Vector3 forward = endIn - start; + float totalDist = MathLib.VectorNormalize(ref forward); + + Vector3 end; + + if (navType != Navigation.Fly && totalDist > MAX_TRIAGULATION_DIST) { + end = forward * MAX_TRIAGULATION_DIST; + totalDist = MAX_TRIAGULATION_DIST; + if (!GetOuter()!.GetMoveProbe()!.MoveLimit(navType, end, endIn, Mask.NPCSolid, targetEnt, out _)) + return false; + } + else + end = endIn; + + Vector3 up, perpendicular; + if (1.0f - MathF.Abs(forward.Z) > 1e-3f) { + up = new(0, 0, 1); + perpendicular = Vector3.Cross(forward, up); + } + else { + up = new(0, 1, 0); + perpendicular = new(1, 0, 0); + } + + float sizeX = 0.5f * NAI_Hull.Length(GetHullType()); + float sizeZ = 0.5f * NAI_Hull.Height(GetHullType()); + + float apexDist = distToBlocker + sizeX; + if (apexDist > totalDist) + apexDist = totalDist; + + Span delta = stackalloc Vector3[2]; + Span apexes = stackalloc Vector3[4]; + Span apexDists = stackalloc float[4]; + + int numToTest = 2; + delta[0] = perpendicular * sizeX; + + Vector3 center = start + apexDist * forward; + apexes[0] = center - delta[0]; + apexes[1] = center + delta[0]; + delta[0] *= 2.0f; + apexDists[0] = apexDists[1] = apexDist; + + if (navType == Navigation.Fly) { + delta[1] = up * (3.0f * sizeZ); + apexes[2] = center - delta[1]; + apexes[3] = center + delta[1]; + apexDists[2] = apexDists[3] = apexDist; + numToTest = 4; + } + + for (int i = 0; i < 2; ++i) { + for (int j = numToTest; --j >= 0;) { + if (TestTriangulationRoute(navType, start, apexes[j], end, targetEnt, out AIMoveTrace moveTrace)) { + apex = apexes[j]; + return true; + } + + if (IsMoveBlocked(moveTrace)) { + Vector3 startToObstruction = moveTrace.EndPosition - start; + float distToObstruction = Vector3.Dot(startToObstruction, forward); + + float newApexDist = apexDists[j]; + if (apexDists[j] > distToObstruction) + newApexDist = distToObstruction; + + apexes[j] += (newApexDist - apexDists[j]) * forward; + apexDists[j] = newApexDist; + } + + if ((j & 0x1) != 0) + apexes[j] += delta[j >> 1]; + else + apexes[j] -= delta[j >> 1]; + } + } + + return false; + } + + protected virtual bool CanUseLocalNavigation() => true; + + AI_Network? GetNetwork() => Network; + + TimeUnit_t LastStaleLinkCheckTime; + bool IgnoreStaleLinks; + public AI_Network? Network; } From b9ea79079874c2cf87c7a3eb82b654a8980e9eb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:05:12 +0300 Subject: [PATCH 27/73] Port AI move solver and plane solver --- Game.Server/AI_MoveSolver.cs | 264 +++++++++++++++ Game.Server/AI_PlaneSolver.cs | 583 +++++++++++++++++++++++++++++++++- 2 files changed, 846 insertions(+), 1 deletion(-) create mode 100644 Game.Server/AI_MoveSolver.cs diff --git a/Game.Server/AI_MoveSolver.cs b/Game.Server/AI_MoveSolver.cs new file mode 100644 index 000000000..be7bfde3d --- /dev/null +++ b/Game.Server/AI_MoveSolver.cs @@ -0,0 +1,264 @@ +global using static Game.Server.AI_MoveSolverGlobals; + +using Game.Shared; + +using System.Runtime.InteropServices; + +namespace Game.Server; + +public enum AI_MoveSuggType +{ + Move, + + AvoidDanger, + AvoidObject, + AvoidNPC, + AvoidWorld, + + NoKnowledge, + OscillationDeterrance, + + Invalid +} + +[Flags] +public enum AI_MoveSuggestionFlags +{ + FavorLeft = 0x01, + FavorRight = 0x02 +} + +public static class AI_MoveSolverGlobals +{ + public static float NormalizeAngle(float angle) { + if (angle < 0.0f) + angle += 360.0f; + else if (angle >= 360.0f) + angle -= 360.0f; + return angle; + } +} + +public struct AI_Arc +{ + public void Set(float newCenter, float newSpan) { + Center = NormalizeAngle(newCenter); + Span = NormalizeAngle(newSpan); + } + + public void SetByLimits(float yawRight, float yawLeft) { + Span = yawLeft - yawRight; + + if (Span < 0) + Span += 360; + + Center = yawRight + Span * 0.5f; + + if (Center >= 360) + Center -= 360; + } + + public float Center; + public float Span; +} + +public struct AI_MoveSuggestion +{ + public AI_MoveSuggestion() { + Type = AI_MoveSuggType.Invalid; + Weight = 0; + Flags = 0; + } + + public AI_MoveSuggestion(AI_MoveSuggType newType, float newWeight, float newDir, float newSpan, BaseEntity? entity = null) => Set(newType, newWeight, newDir, newSpan, entity); + + public AI_MoveSuggestion(AI_MoveSuggType newType, float newWeight, in AI_Arc arc, BaseEntity? entity = null) => Set(newType, newWeight, arc.Center, arc.Span, entity); + + public void Set(AI_MoveSuggType newType, float newWeight, float newDir, float newSpan, BaseEntity? entity = null) { + Type = newType; + Weight = newWeight; + ObstacleEntity.Set(entity); + Flags = 0; + + Arc.Set(newDir, newSpan); + } + + public void Set(AI_MoveSuggType newType, float newWeight, in AI_Arc arc, BaseEntity? entity = null) => Set(newType, newWeight, arc.Center, arc.Span, entity); + + public AI_MoveSuggType Type; + public float Weight; + public AI_Arc Arc; + public EHANDLE ObstacleEntity = new(); + public AI_MoveSuggestionFlags Flags; +} + +public struct AI_MoveSolution +{ + public float Dir; +} + +public class AI_MoveSolver +{ + const int REGS_RESERVE = 8; + const float AIMS_EPS = 0.01f; + + const int NUM_SOLUTIONS = 120; + const int SOLUTION_ANG = 360 / NUM_SOLUTIONS; + + readonly record struct AI_MoveSuggWeights(float Min, float Max); + + static readonly AI_MoveSuggWeights[] g_AI_MoveSuggWeights = [ + new(0.20f, 1.00f), + new(-0.00f, -0.25f), + new(-0.00f, -0.25f), + new(-0.00f, -0.25f), + new(-0.00f, -0.25f), + new(-1.00f, -1.00f), + new(-0.60f, -0.60f), + new(0.00f, 0.00f), + ]; + + struct Solution + { + public float Bias; + public float HighBias; + public int HighSuggestion; + } + + static float V_round(float f) => (int)(f + 0.5f); + + public void AddRegulation(in AI_MoveSuggestion suggestion) => Regulations.Add(suggestion); + + public void AddRegulations(ReadOnlySpan suggestions) { + for (int i = 0; i < suggestions.Length; ++i) + Regulations.Add(suggestions[i]); + } + + public bool HaveRegulations() => Regulations.Count > 0; + public void ClearRegulations() => Regulations.Clear(); + + public bool Solve(in AI_MoveSuggestion suggestion, out AI_MoveSolution result) => Solve(new ReadOnlySpan(in suggestion), out result); + + public bool Solve(ReadOnlySpan suggestionsIn, out AI_MoveSolution result) { + result = default; + + if (suggestionsIn.Length == 0) + return false; + + if (suggestionsIn.Length == 1 && Regulations.Count == 0 && suggestionsIn[0].Type == AI_MoveSuggType.Move) { + result.Dir = suggestionsIn[0].Arc.Center; + return true; + } + + int count = Regulations.Count + suggestionsIn.Length; + Span suggestions = count <= 32 ? stackalloc AI_MoveSuggestion[count] : new AI_MoveSuggestion[count]; + suggestionsIn.CopyTo(suggestions); + CollectionsMarshal.AsSpan(Regulations).CopyTo(suggestions[suggestionsIn.Length..]); + + Span solutions = stackalloc Solution[NUM_SOLUTIONS]; + for (int i = 0; i < NUM_SOLUTIONS; ++i) + solutions[i].HighSuggestion = -1; + + Assert(suggestions.Length >= 1); + NormalizeSuggestions(suggestions); + + for (int suggestion = 0; suggestion < suggestions.Length; ++suggestion) { + ref AI_MoveSuggestion current = ref suggestions[suggestion]; + + float halfSpan = current.Arc.Span * 0.5f; + int center = (int)V_round((halfSpan * NUM_SOLUTIONS) / 360); + int left = (int)((current.Arc.Span * NUM_SOLUTIONS) / 360); + + float angRight = current.Arc.Center - halfSpan; + + if (angRight < 0.0f) + angRight += 360; + + int baseIndex = (int)((angRight * NUM_SOLUTIONS) / 360); + + const float positiveDegradePer180 = 0.05f; + const float positiveDegrade = positiveDegradePer180 / (NUM_SOLUTIONS * 0.5f); + + for (int i = 0; i < left + 1; ++i) { + float bias = 0.0f; + + if (current.Weight > 0) { + int offset = center - i; + float degrade = Math.Abs(offset) * positiveDegrade; + + if (((current.Flags & AI_MoveSuggestionFlags.FavorLeft) != 0 && i > center) || + ((current.Flags & AI_MoveSuggestionFlags.FavorRight) != 0 && i < center)) + degrade *= 0.9f; + + bias = current.Weight - (current.Weight * degrade); + } + else + bias = current.Weight; + + int curSolution = (baseIndex + i) % NUM_SOLUTIONS; + + solutions[curSolution].Bias += bias; + if (bias > solutions[curSolution].HighBias) { + solutions[curSolution].HighBias = bias; + solutions[curSolution].HighSuggestion = suggestion; + } + } + } + + int best = -1; + float biasBest = 0; + + for (int i = 0; i < NUM_SOLUTIONS; ++i) { + if (solutions[i].Bias > biasBest) { + best = i; + biasBest = solutions[i].Bias; + } + } + + if (best == -1) + return false; + + float resultDir = best * SOLUTION_ANG; + + float suggestionCenter = suggestions[solutions[best].HighSuggestion].Arc.Center; + + if (suggestionCenter > resultDir && suggestionCenter <= resultDir + SOLUTION_ANG) + resultDir = suggestionCenter; + + result.Dir = resultDir; + + return true; + } + + static void NormalizeSuggestions(Span suggestions) { + for (int i = 0; i < suggestions.Length; i++) { + ref AI_MoveSuggestion suggestion = ref suggestions[i]; + float min = g_AI_MoveSuggWeights[(int)suggestion.Type].Min; + float max = g_AI_MoveSuggWeights[(int)suggestion.Type].Max; + + Assert(suggestion.Weight >= -AIMS_EPS && suggestion.Weight <= 1.0f + AIMS_EPS); + + if (suggestion.Weight < AIMS_EPS) + suggestion.Weight = 0.0f; + else + suggestion.Weight = ((max - min) * suggestion.Weight) + min; + + while (suggestion.Arc.Center < 0) + suggestion.Arc.Center += 360; + + while (suggestion.Arc.Center >= 360) + suggestion.Arc.Center -= 360; + } + } + + public bool HaveRegulationForObstacle(BaseEntity? entity) { + for (int i = 0; i < Regulations.Count; ++i) { + if (Regulations[i].ObstacleEntity.Get() != null && + entity == Regulations[i].ObstacleEntity.Get()) + return true; + } + return false; + } + + readonly List Regulations = new(REGS_RESERVE); +} diff --git a/Game.Server/AI_PlaneSolver.cs b/Game.Server/AI_PlaneSolver.cs index fb8e357f2..d8fc973e5 100644 --- a/Game.Server/AI_PlaneSolver.cs +++ b/Game.Server/AI_PlaneSolver.cs @@ -1,10 +1,39 @@ +using Game.Shared; + +using Source.Common.Formats.BSP; +using Source.Common.Mathematics; + using System.Numerics; namespace Game.Server; +public enum AI_SuggestorResult +{ + None, + Ok, + Fail +} + public class AI_PlaneSolver { static readonly float[] PLANE_SOLVER_THINK_FREQUENCY = [0.0f, 0.2f]; + static readonly float[] MAX_PROBE_DIST = [10.0f * 12.0f, 8.0f * 12.0f]; + + const float DEGREES_POSITIVE_ARC = 270; + const float DEGREES_POSITIVE_ARC_CLOSE_OBSTRUCTION = 340; + const int NUM_PROBES = 5; + + const float MIN_ZDIR_TO_RADIUS = 0.1f; + + struct CircleObstacles(in Vector3 center, float radius, BaseEntity? entity, AI_MoveSuggType type) + { + public Vector3 Center = center; + public float Radius = radius; + public AI_MoveSuggType Type = type; + public EHANDLE Entity = entity?.GetRefEHandle() ?? new EHANDLE(); + } + + static float Sq(float f) => f * f; public AI_PlaneSolver(AI_BaseNPC npc) { Npc = npc; @@ -17,6 +46,553 @@ public AI_PlaneSolver(AI_BaseNPC npc) { RefreshSamplesTimer = new(PLANE_SOLVER_THINK_FREQUENCY[AIStrongOpt() ? 1 : 0] - 0.05f); } + AI_BaseNPC GetNpc() => Npc; + AI_Motor GetMotor() => Npc.GetMotor()!; + ref readonly Vector3 GetLocalOrigin() => ref Npc.GetLocalOrigin(); + + static float GetLookaheadTime() => 1.0f; + + bool MoveLimit(Navigation navType, in Vector3 target, bool ignoreTransients, bool checkStep, Mask contents, out AIMoveTrace moveTrace) { + AI_MoveLimitFlags flags = (navType == Navigation.Ground) ? AI_MoveLimitFlags.TwoD : AI_MoveLimitFlags.Default; + + if (ignoreTransients) + flags |= AI_MoveLimitFlags.IgnoreTransients; + + AI_MoveProbe probe = Npc.GetMoveProbe()!; + return probe.MoveLimit(navType, GetLocalOrigin(), target, contents, + Npc.GetNavTargetEntity(), checkStep ? 100 : 0, + flags, + out moveTrace); + } + + bool MoveLimit(Navigation navType, in Vector3 target, bool ignoreTransients, bool checkStep, out AIMoveTrace moveTrace) + => MoveLimit(navType, target, ignoreTransients, checkStep, Mask.NPCSolid, out moveTrace); + + bool DetectUnsolvable(in AILocalMoveGoal goal) { + float curDistance = new Vector2(goal.Target.X - GetLocalOrigin().X, goal.Target.Y - GetLocalOrigin().Y).Length(); + if (PrevTarget != goal.Target) { + TimeLastProgress = gpGlobals.CurTime; + ClosestHaveBeenToCurrent = curDistance; + CannotSolveCurrent = false; + } + else { + if (CannotSolveCurrent) + return true; + + if (ClosestHaveBeenToCurrent - curDistance > 0) { + TimeLastProgress = gpGlobals.CurTime; + ClosestHaveBeenToCurrent = curDistance; + } + else { + if (gpGlobals.CurTime - TimeLastProgress > 0.75) { + CannotSolveCurrent = true; + return true; + } + } + } + return false; + } + + float AdjustRegulationWeight(BaseEntity entity, float weight) { + AI_BaseNPC? blocker = entity.MyNPCPointer(); + if (blocker != null) { + ref readonly Vector3 ownerVel = ref GetNpc().GetMotor()!.GetCurVel(); + ref readonly Vector3 blockerVel = ref blocker.GetMotor()!.GetCurVel(); + + Vector2 velOwnerNorm = new(ownerVel.X, ownerVel.Y); + Vector2 velBlockerNorm = new(blockerVel.X, blockerVel.Y); + + float speedOwner = MathLib.Vector2DNormalize(ref velOwnerNorm); + float speedBlocker = MathLib.Vector2DNormalize(ref velBlockerNorm); + + float dot = Vector2.Dot(velOwnerNorm, velBlockerNorm); + + if (speedBlocker > 0) { + if (dot > 0 && speedBlocker >= speedOwner * 0.9) { + if (dot > 0.86) + weight = 0; + else if (dot > 0.7) + weight *= Sq(weight); + else + weight *= weight; + } + } + } + + return weight; + } + + float CalculateRegulationWeight(in AIMoveTrace moveTrace, float pctBlocked) { + float weight; + + if (pctBlocked > 0.9) + weight = 1; + else if (pctBlocked < 0.1) + weight = 0; + else { + weight = Sq((pctBlocked - 0.1f) / 0.8f); + weight = AdjustRegulationWeight(moveTrace.Obstruction!, weight); + } + + return weight; + } + + void GenerateSuggestionFromTrace(in AILocalMoveGoal goal, in AIMoveTrace moveTrace, float probeDist, float arcCenter, float arcSpan, int probeOffset) { + AI_MoveSuggestion suggestion = new(); + AI_MoveSuggType type; + + switch (moveTrace.Status) { + case AIMoveResult.BlockedEntity: type = AI_MoveSuggType.AvoidObject; break; + case AIMoveResult.BlockedWorld: type = AI_MoveSuggType.AvoidWorld; break; + case AIMoveResult.BlockedNPC: type = AI_MoveSuggType.AvoidNPC; break; + case AIMoveResult.Illegal: type = AI_MoveSuggType.AvoidDanger; break; + default: type = AI_MoveSuggType.NoKnowledge; AssertMsg(false, "Unexpected mode status"); break; + } + + if (goal.MoveTarget != null && goal.MoveTarget == moveTrace.Obstruction) { + suggestion.Set(type, 0, + arcCenter, arcSpan, + moveTrace.Obstruction); + + Solver.AddRegulation(suggestion); + + return; + } + + float clearDist = probeDist - moveTrace.DistObstructed; + float pctBlocked = 1.0f - (clearDist / probeDist); + + float weight = CalculateRegulationWeight(moveTrace, pctBlocked); + + if (weight < 0.001) + return; + + if (pctBlocked < 0.5) + arcSpan *= pctBlocked * 2.0f; + + Vector3 vecToEnd = moveTrace.EndPosition - GetLocalOrigin(); + Vector3 crossProduct; + bool favorLeft = false, favorRight = false; + + if (moveTrace.Status == AIMoveResult.BlockedNPC) { + Vector3 vecToOther = moveTrace.Obstruction!.GetLocalOrigin() - GetLocalOrigin(); + + crossProduct = Vector3.Cross(vecToEnd, vecToOther); + + favorLeft = crossProduct.Z < 0; + favorRight = crossProduct.Z > 0; + } + else if (moveTrace.HitNormal != vec3_origin) { + crossProduct = Vector3.Cross(vecToEnd, moveTrace.HitNormal); + favorLeft = crossProduct.Z > 0; + favorRight = crossProduct.Z < 0; + } + + float thirdSpan = arcSpan / 3.0f; + float favoredWeight = weight * pctBlocked; + + suggestion.Set(type, weight, + arcCenter, thirdSpan, + moveTrace.Obstruction); + + Solver.AddRegulation(suggestion); + + suggestion.Set(type, favorRight ? favoredWeight : weight, + arcCenter - thirdSpan, thirdSpan, + moveTrace.Obstruction); + + Solver.AddRegulation(suggestion); + + suggestion.Set(type, favorLeft ? favoredWeight : weight, + arcCenter + thirdSpan, thirdSpan, + moveTrace.Obstruction); + + Solver.AddRegulation(suggestion); + } + + static void CalcYawsFromOffset(float yawScanCenter, float spanPerProbe, int probeOffset, out float yawTest, out float yawCenter) { + if (probeOffset != 0) { + float sign = (probeOffset > 0) ? 1 : -1; + + yawCenter = yawScanCenter + probeOffset * spanPerProbe; + if (yawCenter < 0) + yawCenter += 360; + else if (yawCenter >= 360) + yawCenter -= 360; + + yawTest = yawCenter - (sign * spanPerProbe * 0.5f); + if (yawTest < 0) + yawTest += 360; + else if (yawTest >= 360) + yawTest -= 360; + } + else + yawCenter = yawTest = yawScanCenter; + } + + void GenerateObstacleNpcs(in AILocalMoveGoal goal, float probeDist) { + List ais = g_AI_Manager.AccessAIs(); + Npc.CollisionProp().WorldSpaceSurroundingBounds(out Vector3 minsSelf, out Vector3 maxsSelf); + float radiusSelf = new Vector2(minsSelf.X - maxsSelf.X, minsSelf.Y - maxsSelf.Y).Length() * 0.5f; + + Vector3 mins, maxs; + + for (int i = 0; i < g_AI_Manager.NumAIs(); i++) { + AI_BaseNPC ai = ais[i]; + if (ai != Npc && ai.IsAlive() && (goal.Path == null || ai != goal.Path.GetTarget())) { + ai.CollisionProp().WorldSpaceSurroundingBounds(out mins, out maxs); + if (mins.Z < maxsSelf.Z + 12.0 && maxs.Z > minsSelf.Z - 12.0) { + float radius = new Vector2(mins.X - maxs.X, mins.Y - maxs.Y).Length() * 0.5f; + float distance = new Vector2(ai.GetAbsOrigin().X - Npc.GetAbsOrigin().X, ai.GetAbsOrigin().Y - Npc.GetAbsOrigin().Y).Length(); + if (distance - radius < radiusSelf + probeDist) + AddObstacle(ai.WorldSpaceCenter(), radius, ai, AI_MoveSuggType.AvoidNPC); + } + } + } + + for (int i = 1; i <= gpGlobals.MaxClients; i++) { + BasePlayer? player = Util.PlayerByIndex(i); + if (player == null) + continue; + + player.CollisionProp().WorldSpaceSurroundingBounds(out mins, out maxs); + if (mins.Z < maxsSelf.Z + 12.0 && maxs.Z > minsSelf.Z - 12.0) { + float radius = new Vector2(mins.X - maxs.X, mins.Y - maxs.Y).Length(); + float distance = new Vector2(player.GetAbsOrigin().X - Npc.GetAbsOrigin().X, player.GetAbsOrigin().Y - Npc.GetAbsOrigin().Y).Length(); + if (distance - radius < radiusSelf + probeDist) + AddObstacle(player.WorldSpaceCenter(), radius, player, AI_MoveSuggType.AvoidNPC); + } + } + } + + AI_SuggestorResult GenerateObstacleSuggestion(in AILocalMoveGoal goal, float yawScanCenter, float probeDist, float spanPerProbe, int probeOffset) { + CalcYawsFromOffset(yawScanCenter, spanPerProbe, probeOffset, out float yawTest, out float arcCenter); + + Vector3 probeDir = Util.YawToVector(yawTest); + float requiredMovement = goal.Speed * GetMotor().GetMoveInterval(); + + AIMoveTrace moveTrace = default; + bool traceClear = true; + if (probeDist > requiredMovement) { + if (!MoveLimit(goal.NavType, GetLocalOrigin() + probeDir * requiredMovement, true, true, out moveTrace)) { + traceClear = false; + moveTrace.DistObstructed = (probeDist - requiredMovement) + moveTrace.DistObstructed; + } + } + + if (traceClear) + traceClear = MoveLimit(goal.NavType, GetLocalOrigin() + probeDir * probeDist, true, false, out moveTrace); + + if (!traceClear) { + GenerateSuggestionFromTrace(goal, moveTrace, probeDist, arcCenter, spanPerProbe, probeOffset); + return AI_SuggestorResult.Ok; + } + + return AI_SuggestorResult.None; + } + + AI_SuggestorResult GenerateObstacleSuggestions(in AILocalMoveGoal goal, in AIMoveTrace directTrace, float distClear, float probeDist, float degreesToProbe, int nProbes) { + Assert(nProbes % 2 == 1); + + AI_SuggestorResult seekResult = AI_SuggestorResult.None; + bool newTarget = !SolvedPrev || PrevTarget != goal.Target; + + if (newTarget) + RefreshSamplesTimer.Force(); + + if (PLANE_SOLVER_THINK_FREQUENCY[AIStrongOpt() ? 1 : 0] == 0.0 || RefreshSamplesTimer.Expired()) { + Solver.ClearRegulations(); + + GenerateObstacleNpcs(goal, probeDist); + + if (GenerateCircleObstacleSuggestions(goal, probeDist)) + seekResult = AI_SuggestorResult.Ok; + + float spanPerProbe = degreesToProbe / nProbes; + int nSideProbes = (nProbes - 1) / 2; + float yawGoalDir = Util.VecToYaw(goal.Dir); + + int i; + + if (MathF.Abs(probeDist - (distClear + directTrace.DistObstructed)) < 0.1 && + directTrace.Status != AIMoveResult.BlockedNPC) { + if (directTrace.Status != AIMoveResult.Ok) { + seekResult = AI_SuggestorResult.Ok; + GenerateSuggestionFromTrace(goal, directTrace, probeDist, yawGoalDir, spanPerProbe, 0); + } + } + else if (GenerateObstacleSuggestion(goal, yawGoalDir, probeDist, spanPerProbe, 0) == AI_SuggestorResult.Ok) + seekResult = AI_SuggestorResult.Ok; + + bool foundClear = false; + + for (i = 1; i <= nSideProbes; i++) { + if (!foundClear) { + AI_SuggestorResult curSeekResult = GenerateObstacleSuggestion(goal, yawGoalDir, probeDist, spanPerProbe, i); + if (curSeekResult == AI_SuggestorResult.Ok) + seekResult = AI_SuggestorResult.Ok; + else + foundClear = true; + } + else { + CalcYawsFromOffset(yawGoalDir, spanPerProbe, i, out _, out float arcCenter); + Solver.AddRegulation(new AI_MoveSuggestion(AI_MoveSuggType.NoKnowledge, 1, arcCenter, spanPerProbe)); + } + } + + foundClear = false; + + for (i = -1; i >= -nSideProbes; i--) { + if (!foundClear) { + AI_SuggestorResult curSeekResult = GenerateObstacleSuggestion(goal, yawGoalDir, probeDist, spanPerProbe, i); + if (curSeekResult == AI_SuggestorResult.Ok) + seekResult = AI_SuggestorResult.Ok; + else + foundClear = true; + } + else { + CalcYawsFromOffset(yawGoalDir, spanPerProbe, i, out _, out float arcCenter); + Solver.AddRegulation(new AI_MoveSuggestion(AI_MoveSuggType.NoKnowledge, 1, arcCenter, spanPerProbe)); + } + } + + if (seekResult == AI_SuggestorResult.Ok) { + float arcCenter = yawGoalDir - 180; + if (arcCenter < 0) + arcCenter += 360; + + Solver.AddRegulation(new AI_MoveSuggestion(AI_MoveSuggType.NoKnowledge, 1, arcCenter, 360 - degreesToProbe)); + } + + RefreshSamplesTimer.Reset(PLANE_SOLVER_THINK_FREQUENCY[AIStrongOpt() ? 1 : 0]); + } + else if (Solver.HaveRegulations()) + seekResult = AI_SuggestorResult.Ok; + + return seekResult; + } + + void AdjustSolutionForFliers(in AILocalMoveGoal goal, float solutionYaw, ref Vector3 solution) { + Assert(solution.Z == 0.0f); + + Vector3 vecDelta = goal.Target - GetLocalOrigin(); + Vector3 vecDir = vecDelta; + MathLib.VectorNormalize(ref vecDir); + float radius = MathF.Sqrt(vecDir.X * vecDir.X + vecDir.Y * vecDir.Y); + solution *= radius; + solution.Z = vecDir.Z; + + float upAmount; + if (vecDir.Z >= -radius * MIN_ZDIR_TO_RADIUS) + upAmount = 1.0f; + else if ((vecDir.Z <= -radius) || (MathF.Abs(vecDir.Z) < 1e-3f)) + upAmount = 0.0f; + else { + upAmount = (-radius / vecDir.Z) - 1.0f; + upAmount *= MIN_ZDIR_TO_RADIUS; + Assert((upAmount >= 0.0f) && (upAmount <= 1.0f)); + } + + solution.Z += upAmount * 5.0f; + + MathLib.VectorNormalize(ref solution); + } + + static AI_MoveSuggestionFlags ComputeTurnBiasFlags(in AILocalMoveGoal goal, in AIMoveTrace directTrace) { + if (directTrace.Status == AIMoveResult.BlockedWorld) + return 0; + + if (directTrace.Status == AIMoveResult.BlockedNPC) + return AI_MoveSuggestionFlags.FavorLeft; + + return 0; + } + + bool RunMoveSolver(in AILocalMoveGoal goal, in AIMoveTrace directTrace, float degreesPositiveArc, bool deterOscillation, out Vector3 result) { + result = default; + + if (Solver.HaveRegulations()) { + bool newTarget = !SolvedPrev || PrevTarget != goal.Target; + + Span moveSuggestions = [new(), new()]; + int nSuggestions = 1; + + moveSuggestions[0].Set(AI_MoveSuggType.Move, 1, Util.VecToYaw(goal.Dir), degreesPositiveArc); + moveSuggestions[0].Flags |= ComputeTurnBiasFlags(goal, directTrace); + + if (deterOscillation && !newTarget) + moveSuggestions[nSuggestions++].Set(AI_MoveSuggType.OscillationDeterrance, 1, PrevSolution - 180, 180); + + if (Solver.Solve(moveSuggestions[..nSuggestions], out AI_MoveSolution solution)) { + result = Util.YawToVector(solution.Dir); + + if (goal.NavType == Navigation.Fly) + AdjustSolutionForFliers(goal, solution.Dir, ref result); + + if (!newTarget) { + float delta = solution.Dir - PrevSolution; + if (delta < 0) + delta += 360; + if (delta > 165 && delta < 195) + return false; + } + + PrevSolution = solution.Dir; + PrevSolutionVector = result; + + Vector3 curVelocity = Npc.GetSmoothedVelocity(); + if (curVelocity != vec3_origin) { + MathLib.VectorNormalize(ref curVelocity); + if (!newTarget) + result = curVelocity * 0.1f + PrevSolutionVector * 0.1f + result * 0.8f; + else + result = curVelocity * 0.2f + result * 0.8f; + } + + return true; + } + } + else { + if (goal.NavType != Navigation.Fly) + result = goal.Dir; + else { + result = goal.Target - GetLocalOrigin(); + MathLib.VectorNormalize(ref result); + } + return true; + } + + return false; + } + + public float CalcProbeDist(float speed) { + float result = GetLookaheadTime() * speed; + if (result < Npc.GetHullWidth()) + return Npc.GetHullWidth(); + if (result > MAX_PROBE_DIST[AIStrongOpt() ? 1 : 0]) + return MAX_PROBE_DIST[AIStrongOpt() ? 1 : 0]; + return result; + } + + public void AddObstacle(in Vector3 center, float radius, BaseEntity? entity = null, AI_MoveSuggType type = AI_MoveSuggType.AvoidObject) + => Obstacles.Add(new CircleObstacles(center, radius, entity, type)); + + public bool HaveObstacles() => Obstacles.Count != 0; + + bool GenerateCircleObstacleSuggestions(in AILocalMoveGoal moveGoal, float probeDist) { + bool result = false; + Vector3 npcLoc = Npc.WorldSpaceCenter(); + + Npc.CollisionProp().WorldSpaceSurroundingBounds(out Vector3 mins, out Vector3 maxs); + float radiusNpc = new Vector2(mins.X - maxs.X, mins.Y - maxs.Y).Length() * 0.5f; + + for (int i = 0; i < Obstacles.Count; i++) { + CircleObstacles obstacle = Obstacles[i]; + BaseEntity? obstacleEntity = obstacle.Entity.Get(); + + float zDistTooFar; + if (obstacleEntity != null && obstacleEntity.CollisionProp() != null) { + if (obstacleEntity == moveGoal.MoveTarget && (obstacleEntity.IsNPC() || obstacleEntity.IsPlayer())) + continue; + + obstacleEntity.CollisionProp().WorldSpaceSurroundingBounds(out mins, out maxs); + zDistTooFar = (maxs.Z - mins.Z) * 0.5f + GetNpc().GetHullHeight() * 0.5f; + } + else + zDistTooFar = GetNpc().GetHullHeight(); + + if (MathF.Abs(obstacle.Center.Z - npcLoc.Z) > zDistTooFar) + continue; + + Vector3 vecToNpc = npcLoc - obstacle.Center; + vecToNpc.Z = 0; + float distToObstacleSq = Sq(vecToNpc.X) + Sq(vecToNpc.Y); + float radius = obstacle.Radius + radiusNpc; + + if (distToObstacleSq > 0.001 && distToObstacleSq < Sq(radius + probeDist)) { + Vector3 vecToObstacle = vecToNpc * -1; + float distToObstacle = MathLib.VectorNormalize(ref vecToObstacle); + float weight; + float arc; + float radiusSq = Sq(radius); + + float dot = Vector3.Dot(vecToObstacle, moveGoal.Dir); + + if (dot < 0.0f && distToObstacleSq > radiusSq) + continue; + + if (radiusSq < distToObstacleSq) { + Vector3 vecTangent; + float distToTangent = MathF.Sqrt(distToObstacleSq - radiusSq); + + float oneOverDistToObstacleSq = 1 / distToObstacleSq; + + vecTangent.X = (-distToTangent * vecToNpc.X + radius * vecToNpc.Y) * oneOverDistToObstacleSq; + vecTangent.Y = (-distToTangent * vecToNpc.Y - radius * vecToNpc.X) * oneOverDistToObstacleSq; + vecTangent.Z = 0; + + float cosHalfArc = Vector3.Dot(vecToObstacle, vecTangent); + arc = MathLib.RAD2DEG(MathF.Acos(cosHalfArc)) * 2.0f; + weight = 1.0f - (distToObstacle - radius) / probeDist; + if (weight > 0.75) + arc += (arc * 0.5f) * (weight - 0.75f) / 0.25f; + + Assert(weight >= 0.0 && weight <= 1.0); + } + else { + arc = 210; + weight = 1.0f; + } + + if (obstacleEntity != null) + weight = AdjustRegulationWeight(obstacleEntity, weight); + + AI_MoveSuggestion suggestion = new(obstacle.Type, weight, Util.VecToYaw(vecToObstacle), arc); + Solver.AddRegulation(suggestion); + result = true; + } + } + + Obstacles.Clear(); + return result; + } + + public bool Solve(in AILocalMoveGoal goal, float distClear, out Vector3 solution) { + bool solved = false; + solution = default; + + if (goal.Speed == 0) + return false; + + if (DetectUnsolvable(goal)) + return false; + + bool veryClose = distClear < 1.0; + float degreesPositiveArc = !veryClose ? DEGREES_POSITIVE_ARC : DEGREES_POSITIVE_ARC_CLOSE_OBSTRUCTION; + float probeDist = CalcProbeDist(goal.Speed); + + if ((goal.Flags & (AILocalMoveGoalFlags.TargetIsTransition | AILocalMoveGoalFlags.TargetIsGoal)) != 0) + probeDist = Math.Min(goal.MaxDist, probeDist); + + if (GenerateObstacleSuggestions(goal, goal.DirectTrace, distClear, probeDist, degreesPositiveArc, NUM_PROBES) != AI_SuggestorResult.Fail) { + if (RunMoveSolver(goal, goal.DirectTrace, degreesPositiveArc, !veryClose, out solution)) { + float requiredMovement = goal.Speed * GetMotor().GetMoveInterval(); + + MoveLimit(goal.NavType, GetLocalOrigin() + solution * requiredMovement, false, true, out AIMoveTrace moveTrace); + + if (!IsMoveBlocked(moveTrace)) + solved = true; + else + solved = false; + } + } + + SolvedPrev = solved && goal.Speed != 0; + PrevTarget = goal.Target; + + return solved; + } + public void Reset() { RefreshSamplesTimer.Force(); @@ -33,11 +609,16 @@ public void Reset() { Vector3 PrevTarget; bool SolvedPrev; float PrevSolution; + Vector3 PrevSolutionVector; float ClosestHaveBeenToCurrent; - float TimeLastProgress; + TimeUnit_t TimeLastProgress; bool CannotSolveCurrent; readonly SimTimer RefreshSamplesTimer; + + readonly List Obstacles = []; + + readonly AI_MoveSolver Solver = new(); } From 8e60b860954c144e3ea8a7c8fe8afd599f86b02c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:09:57 +0300 Subject: [PATCH 28/73] Port AI local navigator and movement sink --- Game.Server/AI_LocalNavigator.cs | 270 +++++++++++++++++++++++++++++++ Game.Server/IAI_MovementSink.cs | 12 +- 2 files changed, 281 insertions(+), 1 deletion(-) diff --git a/Game.Server/AI_LocalNavigator.cs b/Game.Server/AI_LocalNavigator.cs index 9cba806a7..cfec20cc5 100644 --- a/Game.Server/AI_LocalNavigator.cs +++ b/Game.Server/AI_LocalNavigator.cs @@ -1,12 +1,30 @@ +global using static Game.Server.AI_LocalNavigatorGlobals; + +using Game.Shared; + +using Source.Common.Commands; +using Source.Common.Formats.BSP; +using Source.Common.Mathematics; + +using System.Numerics; + namespace Game.Server; +public static class AI_LocalNavigatorGlobals +{ + public static readonly ConVar ai_no_steer = new("ai_no_steer", "0"); +} + public class AI_LocalNavigator : AI_Component, IAI_MovementSink { + static readonly float[] TIME_DELAY_FULL_DIRECT_PROBE = [0.25f, 0.35f]; + public AI_LocalNavigator(AI_BaseNPC? outer) : base(outer) { MoveProbe = null; PlaneSolver = new AI_PlaneSolver(outer!); LastWasClear = false; + LastMoveGoal = default; } public void Init(IAI_MovementSink? movementServices) { @@ -21,15 +39,267 @@ public virtual float CalcYawSpeed() { return -1.0f; } + public virtual bool OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) + => Proxied != null && Proxied.OnCalcBaseMove(ref moveGoal, distClear, ref result); + + public virtual bool OnObstructionPreSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) + => Proxied != null && Proxied.OnObstructionPreSteer(ref moveGoal, distClear, ref result); + + public virtual bool OnFailedSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) + => Proxied != null && Proxied.OnFailedSteer(ref moveGoal, distClear, ref result); + + public virtual bool OnFailedLocalNavigation(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) + => Proxied != null && Proxied.OnFailedLocalNavigation(ref moveGoal, distClear, ref result); + + public virtual bool OnInsufficientStopDist(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) + => Proxied != null && Proxied.OnInsufficientStopDist(ref moveGoal, distClear, ref result); + + public virtual bool OnMoveBlocked(ref AIMoveResult result) + => Proxied != null && Proxied.OnMoveBlocked(ref result); + + public virtual bool OnMoveStalled(in AILocalMoveGoal move) + => Proxied != null && Proxied.OnMoveStalled(move); + + public virtual bool OnMoveExecuteFailed(in AILocalMoveGoal move, in AIMoveTrace trace, AIMotorMoveResult motorResult, ref AIMoveResult result) + => Proxied != null && Proxied.OnMoveExecuteFailed(move, trace, motorResult, ref result); + public void ResetMoveCalculations() { FullDirectTimer.Force(); PlaneSolver.Reset(); } + public void AddObstacle(in Vector3 pos, float radius, AI_MoveSuggType type = AI_MoveSuggType.AvoidObject) => PlaneSolver.AddObstacle(pos, radius, null, type); + + public bool HaveObstacles() => PlaneSolver.HaveObstacles(); + + protected AI_MoveProbe? GetMoveProbe() => MoveProbe; + + protected bool MoveCalcDirect(ref AILocalMoveGoal moveGoal, bool onlyCurThink, ref float distClearOut, ref AIMoveResult result) { + bool retVal = false; + + if (moveGoal.Speed != 0) { + AI_Motor motor = GetOuter()!.GetMotor()!; + float minCheckDist = motor.MinCheckDist(); + float probeDist = PlaneSolver.CalcProbeDist(moveGoal.Speed); + float checkDist = Math.Max(minCheckDist, probeDist); + float checkStepDist = Math.Max(16.0f, probeDist * 0.5f); + + if ((moveGoal.Flags & (AILocalMoveGoalFlags.TargetIsTransition | AILocalMoveGoalFlags.TargetIsGoal)) != 0) + checkDist = Math.Min(checkDist, moveGoal.MaxDist); + + if (checkDist <= 0.0) { + result = AIMoveResult.Ok; + return true; + } + + float moveThisInterval = motor.CalcIntervalMove(); + bool expectingArrival = moveThisInterval >= checkDist; + + if (!FullDirectTimer.Expired()) { + if (!LastWasClear || + (!MathLib.VectorsAreEqual(moveGoal.Target, LastMoveGoal.Target, 0.1f) || + !MathLib.VectorsAreEqual(moveGoal.Dir, LastMoveGoal.Dir, 0.1f)) || + expectingArrival) + FullDirectTimer.Force(); + } + + if (onlyCurThink) + FullDirectTimer.Set(TIME_DELAY_FULL_DIRECT_PROBE[AIStrongOpt() ? 1 : 0]); + + bool traceClear = true; + Vector3 testPos; + ref readonly Vector3 localOrigin = ref GetOuter()!.GetLocalOrigin(); + + if (!expectingArrival) { + testPos = localOrigin + moveGoal.Dir * moveThisInterval; + traceClear = GetMoveProbe()!.MoveLimit(moveGoal.NavType, localOrigin, testPos, + Mask.NPCSolid, moveGoal.MoveTarget, + 100.0f, + (moveGoal.NavType == Navigation.Ground) ? AI_MoveLimitFlags.TwoD : AI_MoveLimitFlags.Default, + out moveGoal.DirectTrace); + + if (!traceClear) + moveGoal.DirectTrace.DistObstructed = (checkDist - moveThisInterval) + moveGoal.DirectTrace.DistObstructed; + + moveGoal.ThinkTrace = moveGoal.DirectTrace; + } + + if (traceClear) { + if (FullDirectTimer.Expired()) { + testPos = localOrigin + moveGoal.Dir * checkDist; + float checkStepPct = (checkStepDist / checkDist) * 100.0f; + if (checkStepPct > 100.0) + checkStepPct = 100.0f; + + traceClear = GetMoveProbe()!.MoveLimit(moveGoal.NavType, localOrigin, testPos, + Mask.NPCSolid, moveGoal.MoveTarget, + checkStepPct, + (moveGoal.NavType == Navigation.Ground) ? AI_MoveLimitFlags.TwoD : AI_MoveLimitFlags.Default, + out moveGoal.DirectTrace); + if (expectingArrival) + moveGoal.ThinkTrace = moveGoal.DirectTrace; + } + } + + moveGoal.HasTraced = true; + + float distClear = checkDist - moveGoal.DirectTrace.DistObstructed; + if (distClear < 0.001) + distClear = 0; + + if (traceClear) { + result = AIMoveResult.Ok; + retVal = true; + LastWasClear = true; + } + else if ((moveGoal.Flags & (AILocalMoveGoalFlags.TargetIsTransition | AILocalMoveGoalFlags.TargetIsGoal)) != 0 && + moveGoal.MaxDist < distClear) { + result = AIMoveResult.Ok; + retVal = true; + LastWasClear = true; + } + else { + distClearOut = distClear; + LastWasClear = false; + } + } + else { + result = AIMoveResult.Illegal; + retVal = true; + } + + LastMoveGoal = moveGoal; + if (retVal && FullDirectTimer.Expired()) + FullDirectTimer.Set(TIME_DELAY_FULL_DIRECT_PROBE[AIStrongOpt() ? 1 : 0]); + + return retVal; + } + + protected bool MoveCalcSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if ((moveGoal.Flags & AILocalMoveGoalFlags.NoSteer) != 0) + return false; + + if (ai_no_steer.GetBool()) + return false; + + if (GetOuter()!.IsFlaggedEfficient()) + return false; + + if (PlaneSolver.Solve(moveGoal, distClear, out Vector3 moveSolution)) { + if (moveSolution != moveGoal.Dir) { + float dot = moveSolution.X * moveGoal.Dir.X + moveSolution.Y * moveGoal.Dir.Y; + + const float COS_HALF_30 = 0.966f; + if (dot > COS_HALF_30) { + float probeDist = PlaneSolver.CalcProbeDist(moveGoal.Speed); + if (moveGoal.MaxDist < probeDist * 0.33333 && distClear > probeDist * 0.6666) { + result = AIMoveResult.Ok; + return true; + } + } + + moveGoal.Facing = moveGoal.Dir = moveSolution; + } + result = AIMoveResult.Ok; + return true; + } + + return false; + } + + protected static bool MoveCalcStop(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if (distClear < moveGoal.MaxDist) { + if (distClear < 0.1) + result = AIMoveResult.Illegal; + else { + moveGoal.MaxDist = distClear; + result = AIMoveResult.Ok; + } + + return true; + } + result = AIMoveResult.Ok; + return true; + } + + protected AIMoveResult MoveCalcRaw(ref AILocalMoveGoal moveGoal, bool onlyCurThink) { + AIMoveResult result = AIMoveResult.Ok; + float distClear = 0; + + bool directClear = MoveCalcDirect(ref moveGoal, onlyCurThink, ref distClear, ref result); + if (OnCalcBaseMove(ref moveGoal, distClear, ref result)) + return result; + + bool shouldSteer = (moveGoal.Flags & AILocalMoveGoalFlags.NoSteer) == 0 && (!directClear || HaveObstacles()); + + if (directClear && !shouldSteer) + return result; + + if (shouldSteer) { + if (!directClear) { + if (OnObstructionPreSteer(ref moveGoal, distClear, ref result)) + return result; + } + + if (MoveCalcSteer(ref moveGoal, distClear, ref result)) + return result; + } + + if (OnFailedSteer(ref moveGoal, distClear, ref result)) + return result; + + if (OnFailedLocalNavigation(ref moveGoal, distClear, ref result)) + return result; + + if (distClear < GetOuter()!.GetMotor()!.MinStoppingDist()) { + if (OnInsufficientStopDist(ref moveGoal, distClear, ref result)) + return result; + + if (MoveCalcStop(ref moveGoal, distClear, ref result)) + return result; + } + + if (distClear > moveGoal.CurExpectedDist) + return AIMoveResult.Ok; + + return IsMoveBlocked(moveGoal.DirectTrace.Status) ? moveGoal.DirectTrace.Status : AIMoveResult.Illegal; + } + + public AIMoveResult MoveCalc(ref AILocalMoveGoal moveGoal, bool previouslyValidated = false) { + bool onlyCurThink = previouslyValidated && !HaveObstacles(); + + AIMoveResult result = MoveCalcRaw(ref moveGoal, onlyCurThink); + + if (moveGoal.CurExpectedDist > moveGoal.MaxDist) + moveGoal.CurExpectedDist = moveGoal.MaxDist; + + if (result == AIMoveResult.Ok) { + float interval = GetOuter()!.GetMotor()!.GetMoveInterval(); + float currentYaw = Util.AngleMod(GetOuter()!.GetLocalAngles().Y); + float goalYaw; + float deltaYaw; + float speed; + float clampedYaw; + + goalYaw = Util.VecToYaw(moveGoal.Facing); + deltaYaw = MathF.Abs(Util.AngleDiff(goalYaw, currentYaw)); + if (deltaYaw > 15) { + speed = deltaYaw * 4.0f; + clampedYaw = AI_Motor.AI_ClampYaw(speed, currentYaw, goalYaw, interval); + + if (clampedYaw != goalYaw) + moveGoal.Facing = Util.YawToVector(clampedYaw); + } + } + + return result; + } + public AI_MoveProbe? MoveProbe; public IAI_MovementSink? Proxied; bool LastWasClear; + AILocalMoveGoal LastMoveGoal; readonly SimpleSimTimer FullDirectTimer = new(); readonly AI_PlaneSolver PlaneSolver; } diff --git a/Game.Server/IAI_MovementSink.cs b/Game.Server/IAI_MovementSink.cs index 5a9812c4a..db40d4e3b 100644 --- a/Game.Server/IAI_MovementSink.cs +++ b/Game.Server/IAI_MovementSink.cs @@ -2,5 +2,15 @@ namespace Game.Server; public interface IAI_MovementSink { - float CalcYawSpeed(); + float CalcYawSpeed() => -1.0f; + + bool OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => false; + bool OnObstructionPreSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => false; + bool OnFailedSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => false; + bool OnFailedLocalNavigation(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => false; + bool OnInsufficientStopDist(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => false; + bool OnMoveBlocked(ref AIMoveResult result) => false; + + bool OnMoveStalled(in AILocalMoveGoal move) => false; + bool OnMoveExecuteFailed(in AILocalMoveGoal move, in AIMoveTrace trace, AIMotorMoveResult motorResult, ref AIMoveResult result) => false; } From c23c3ef1921da65e64f778be9323fdd3388aca18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:14:26 +0300 Subject: [PATCH 29/73] Port AI motor --- Game.Server/AI_BlendedMotor.cs | 2 +- Game.Server/AI_Motor.cs | 442 ++++++++++++++++++++++++++++++++- 2 files changed, 435 insertions(+), 9 deletions(-) diff --git a/Game.Server/AI_BlendedMotor.cs b/Game.Server/AI_BlendedMotor.cs index f86d02021..05189a351 100644 --- a/Game.Server/AI_BlendedMotor.cs +++ b/Game.Server/AI_BlendedMotor.cs @@ -45,7 +45,7 @@ public override void ResetMoveCalculations() { ScriptTurn.Clear(); } - public float OverrideMaxYawSpeed(Activity activity) { + public override float OverrideMaxYawSpeed(Activity activity) { if (IsYawLocked()) return 0.0f; diff --git a/Game.Server/AI_Motor.cs b/Game.Server/AI_Motor.cs index 66b91d184..7bb72a31f 100644 --- a/Game.Server/AI_Motor.cs +++ b/Game.Server/AI_Motor.cs @@ -1,4 +1,9 @@ +using Game.Shared; + +using Source; +using Source.Common.Formats.BSP; using Source.Common.Mathematics; +using Source.Common.Physics; using System.Numerics; @@ -7,8 +12,11 @@ namespace Game.Server; public class AI_Motor : AI_Component, IAI_MovementSink { public AI_Motor(AI_BaseNPC? outer) : base(outer) { + MoveInterval = 0; + IdealYaw = 0; YawSpeed = 0; + Velocity = new(0, 0, 0); MoveProbe = null; YawLocked = false; } @@ -25,10 +33,346 @@ public virtual float CalcYawSpeed() { return -1.0f; } + public virtual bool OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) + => Proxied != null && Proxied.OnCalcBaseMove(ref moveGoal, distClear, ref result); + + public virtual bool OnObstructionPreSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) + => Proxied != null && Proxied.OnObstructionPreSteer(ref moveGoal, distClear, ref result); + + public virtual bool OnFailedSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) + => Proxied != null && Proxied.OnFailedSteer(ref moveGoal, distClear, ref result); + + public virtual bool OnFailedLocalNavigation(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) + => Proxied != null && Proxied.OnFailedLocalNavigation(ref moveGoal, distClear, ref result); + + public virtual bool OnInsufficientStopDist(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) + => Proxied != null && Proxied.OnInsufficientStopDist(ref moveGoal, distClear, ref result); + + public virtual bool OnMoveBlocked(ref AIMoveResult result) + => Proxied != null && Proxied.OnMoveBlocked(ref result); + + public virtual bool OnMoveStalled(in AILocalMoveGoal move) + => Proxied != null && Proxied.OnMoveStalled(move); + + public virtual bool OnMoveExecuteFailed(in AILocalMoveGoal move, in AIMoveTrace trace, AIMotorMoveResult motorResult, ref AIMoveResult result) + => Proxied != null && Proxied.OnMoveExecuteFailed(move, trace, motorResult, ref result); + public const float AI_CALC_YAW_SPEED = -1; public const float AI_KEEP_YAW_SPEED = -2; + public float GetMoveInterval() => MoveInterval; + public float SetMoveInterval(float interval) => MoveInterval = interval; + + public AIMotorMoveResult MoveGroundStep(in Vector3 newPos, BaseEntity? moveTarget = null, float yaw = -1, bool asFarAsCan = true, bool testZ = true) + => MoveGroundStep(newPos, moveTarget, yaw, asFarAsCan, testZ, out _); + + public AIMotorMoveResult MoveGroundStep(in Vector3 newPos, BaseEntity? moveTarget, float yaw, bool asFarAsCan, bool testZ, out AIMoveTrace traceResult) { + AI_TestGroundMoveFlags testFlags = AI_TestGroundMoveFlags.IgnoreFloor; + + if (!testZ) + testFlags |= AI_TestGroundMoveFlags.TwoD; + + GetMoveProbe()!.TestGroundMove(GetOuter()!.GetLocalOrigin(), newPos, Mask.NPCSolid, testFlags, out AIMoveTrace moveTrace); + traceResult = moveTrace; + + bool hitTarget = moveTrace.Obstruction != null && moveTarget == moveTrace.Obstruction; + + bool isBlocked = IsMoveBlocked(moveTrace.Status); + if (!isBlocked || asFarAsCan || hitTarget) { + Util.SetOrigin(GetOuter()!, moveTrace.EndPosition, true); + + if ((GetOuter()!.GetFlags() & EntityFlags.OnGround) != 0) + GetOuter()!.PhysicsStepRecheckGround(); + + if (moveTrace.StepUpDistance > 0.1f) { + float height = Math.Clamp(moveTrace.StepUpDistance, 0.0f, StepHeight()); + IPhysicsObject? physicsObject = GetOuter()!.VPhysicsGetObject(); + if (physicsObject != null) { + IPhysicsShadowController? shadow = physicsObject.GetShadowController(); + shadow?.StepUp(height); + } + } + if (yaw != -1) { + QAngle angles = GetOuter()!.GetLocalAngles(); + angles.Y = yaw; + GetOuter()!.SetLocalAngles(angles); + } + if (hitTarget) + return AIMotorMoveResult.PartialHitTarget; + + if (!isBlocked) + return AIMotorMoveResult.Success; + + if (moveTrace.Status == AIMoveResult.BlockedNPC) + return AIMotorMoveResult.PartialHitNPC; + + return AIMotorMoveResult.PartialHitWorld; + } + return AIMotorMoveResult.Failed; + } + + public virtual void MoveClimbStart(in Vector3 climbDest, in Vector3 climbDir, float climbDist, float yaw) { + if (MathF.Abs(climbDir.Z) < .1) + GetOuter()!.SetActivity(GetNavigator()!.GetMovementActivity()); + else + GetOuter()!.SetActivity((climbDir.Z > -0.01) ? Activity.ACT_CLIMB_UP : Activity.ACT_CLIMB_DOWN); + + DismountSequence = SelectWeightedSequence(Activity.ACT_CLIMB_DISMOUNT); + if (DismountSequence != (int)Activity.ACT_INVALID) + GetOuter()!.GetSequenceLinearMotion(DismountSequence, out Dismount); + else + Dismount = default; + + GetOuter()!.AddFlag(EntityFlags.Fly); + GetOuter()!.SetSolid(SolidType.BBox); + GetOuter()!.SetGravity(0.0f); + GetOuter()!.SetGroundEntity(null); + } + + public virtual AIMoveResult MoveClimbExecute(in Vector3 climbDest, in Vector3 climbDir, float climbDist, float yaw, int climbNodesLeft) { + if (MathF.Abs(climbDir.Z) > .1) { + if (GetOuter()!.GetActivity() != Activity.ACT_CLIMB_DISMOUNT) { + Activity desiredActivity = (climbDir.Z > -0.01) ? Activity.ACT_CLIMB_UP : Activity.ACT_CLIMB_DOWN; + if (GetOuter()!.GetActivity() != desiredActivity) + GetOuter()!.SetActivity(desiredActivity); + } + + if (GetOuter()!.GetActivity() != Activity.ACT_CLIMB_UP && GetOuter()!.GetActivity() != Activity.ACT_CLIMB_DOWN && GetOuter()!.GetActivity() != Activity.ACT_CLIMB_DISMOUNT) { + DevMsg("Climber not in a climb activity!\n"); + return AIMoveResult.Illegal; + } + + if (DismountSequence != (int)Activity.ACT_INVALID) { + if (GetOuter()!.GetActivity() == Activity.ACT_CLIMB_UP) { + if (climbNodesLeft <= 2 && climbDist < MathF.Abs(Dismount.Z)) { + GetOuter()!.SetActivity(Activity.ACT_CLIMB_DISMOUNT); + GetOuter()!.SetCycle(GetOuter()!.GetMovementFrame(Dismount.Z - climbDist)); + } + } + } + } + + float climbSpeed = GetOuter()!.GetInstantaneousVelocity(); + + if (DismountSequence != (int)Activity.ACT_INVALID) + climbSpeed = Math.Max(climbSpeed, 30.0f); + else + climbSpeed = 100.0f; + + SetSmoothedVelocity(climbDir * climbSpeed); + + if (climbDist < climbSpeed * GetMoveInterval()) { + if (climbDist <= 1e-2) + climbDist = 0; + + float climbTime = climbDist / climbSpeed; + + SetMoveInterval(GetMoveInterval() - climbTime); + GetOuter()!.SetLocalOrigin(climbDest); + + return AIMoveResult.ChangeType; + } + else + SetMoveInterval(0); + + SetIdealYawAndUpdate(yaw); + + return AIMoveResult.Ok; + } + + public virtual void MoveClimbStop() { + if (GetNavigator()!.GetMovementActivity() > Activity.ACT_RESET) + GetOuter()!.SetActivity(GetNavigator()!.GetMovementActivity()); + else + GetOuter()!.SetActivity(Activity.ACT_IDLE); + + GetOuter()!.RemoveFlag(EntityFlags.Fly); + SetSmoothedVelocity(vec3_origin); + GetOuter()!.SetGravity(1.0f); + } + + public virtual void MoveJumpStart(in Vector3 velocity) { + SetSmoothedVelocity(velocity); + GetOuter()!.SetGravity(GetOuter()!.GetJumpGravity()); + GetOuter()!.SetGroundEntity(null); + + GetOuter()!.SetActivity(Activity.ACT_JUMP); + + SetIdealYawAndUpdate(velocity); + } + + public virtual AIMoveResult MoveJumpExecute() { + UpdateYaw(); + + if (GetOuter()!.GetActivity() == Activity.ACT_JUMP && GetOuter()!.IsActivityFinished()) + GetOuter()!.SetActivity(Activity.ACT_GLIDE); + + SetMoveInterval(0); + + return AIMoveResult.Ok; + } + + public virtual AIMoveResult MoveJumpStop() { + SetSmoothedVelocity(new(0, 0, 0)); + + if (GetOuter()!.GetActivity() == Activity.ACT_GLIDE) { + float time = GetOuter()!.GetGroundChangeTime(); + GetOuter()!.AddStepDiscontinuity(time, GetOuter()!.GetAbsOrigin(), GetOuter()!.GetAbsAngles()); + + if (SelectWeightedSequence(Activity.ACT_LAND) == (int)Activity.ACT_INVALID) + return AIMoveResult.ChangeType; + + GetOuter()!.SetActivity(Activity.ACT_LAND); + } + if (GetOuter()!.GetActivity() != Activity.ACT_LAND || GetOuter()!.IsActivityFinished()) + return AIMoveResult.ChangeType; + + SetMoveInterval(0); + + GetOuter()!.SetGravity(1.0f); + + return AIMoveResult.Ok; + } + + public float GetIdealSpeed() => GetOuter()!.GetIdealSpeed(); + public float GetIdealAccel() => GetOuter()!.GetIdealAccel(); + public float GetCurSpeed() => Velocity.Length(); + public ref readonly Vector3 GetCurVel() => ref Velocity; + + public virtual float OverrideMaxYawSpeed(Activity activity) => -1; + public bool IsDeceleratingToGoal() => false; + + public virtual float MinStoppingDist(float minResult = 10.0f) { + float decelRate = GetIdealAccel(); + + if (decelRate > 0.0) { + float t = GetCurSpeed() / decelRate; + float dist = GetCurSpeed() * t - 0.5f * decelRate * t * t; + + if (dist > minResult) + return dist; + return minResult; + } + return minResult; + } + + protected float IdealVelocity() => GetIdealSpeed() * (float)GetOuter()!.GetPlaybackRate(); + + public virtual void ResetMoveCalculations() { } + + public virtual void MoveStart() { } + + public virtual void MoveStop() { + Velocity = default; + GetOuter()!.GetLocalNavigator()!.ResetMoveCalculations(); + } + + public virtual void MovePaused() { } + + public float CalcIntervalMove() => 0.5f * (GetCurSpeed() + GetIdealSpeed()) * GetMoveInterval(); + + protected virtual AIMotorMoveResult MoveGroundExecute(in AILocalMoveGoal move, out AIMoveTrace traceResult) { + MoveFacing(move); + + return MoveGroundExecuteWalk(move, GetIdealSpeed(), CalcIntervalMove(), out traceResult); + } + + protected AIMotorMoveResult MoveGroundExecuteWalk(in AILocalMoveGoal move, float speed, float dist, out AIMoveTrace traceResult) { + traceResult = default; + bool reachingLocalGoal = dist > move.MaxDist; + + if (reachingLocalGoal) { + if ((move.Flags & AILocalMoveGoalFlags.ConsumeInterval) == 0) + SetMoveInterval(GetMoveInterval() * (1 - move.MaxDist / dist)); + else + SetMoveInterval(0); + dist = move.MaxDist; + } + else + SetMoveInterval(0); + + SetMoveVel(move.Dir * speed); + + AIMotorMoveResult result = AIMotorMoveResult.Success; + if (dist > 0.0) { + Vector3 vecFrom = GetOuter()!.GetLocalOrigin(); + Vector3 vecTo = vecFrom + move.Dir * dist; + + result = MoveGroundStep(vecTo, move.MoveTarget, -1, true, reachingLocalGoal, out traceResult); + + if (result == AIMotorMoveResult.Failed) + MoveStop(); + } + else if (!OnMoveStalled(move)) + result = AIMotorMoveResult.Failed; + + return result; + } + + protected virtual AIMotorMoveResult MoveFlyExecute(in AILocalMoveGoal move, out AIMoveTrace traceResult) { + MoveFacing(move); + + float newSpeed = GetIdealSpeed(); + SetMoveVel(move.Dir * newSpeed); + + float total = 0.5f * (GetCurSpeed() + newSpeed) * GetMoveInterval(); + + float distance = move.MaxDist; + + if (total > distance) { + SetMoveInterval(GetMoveInterval() * (1 - distance / total)); + total = distance; + } + else + SetMoveInterval(0); + + Vector3 vecStart = GetOuter()!.GetLocalOrigin(); + Vector3 vecEnd = vecStart + total * move.Dir; + + GetMoveProbe()!.MoveLimit(Navigation.Fly, vecStart, vecEnd, Mask.NPCSolid, null, out AIMoveTrace moveTrace); + traceResult = moveTrace; + + if (MathF.Abs(moveTrace.DistObstructed - total) <= 1e-1) { + if (move.MoveTarget != null && (moveTrace.Obstruction == move.MoveTarget)) + return AIMotorMoveResult.PartialHitTarget; + + return AIMotorMoveResult.Failed; + } + + Util.SetOrigin(GetOuter()!, moveTrace.EndPosition, true); + + return IsMoveBlocked(moveTrace.Status) ? AIMotorMoveResult.PartialHitWorld : AIMotorMoveResult.Success; + } + + protected virtual void MoveFacing(in AILocalMoveGoal move) { + if (GetOuter()!.OverrideMoveFacing(move, GetMoveInterval())) + return; + + float moveYaw = Util.VecToYaw(move.Dir); + + int sequence = GetOuter()!.GetSequence(); + float sequenceMoveYaw = GetOuter()!.GetSequenceMoveYaw(sequence); + if (sequenceMoveYaw == Animation.NOMOTION) + sequenceMoveYaw = 0; + + if (!GetOuter()!.HasPoseParameter(sequence, GetOuter()!.LookupPoseMoveYaw())) + SetIdealYawAndUpdate(Util.AngleMod(moveYaw - sequenceMoveYaw)); + else { + float influence = GetFacingDirection(out Vector3 dir); + dir = move.Facing * (1 - influence) + dir * influence; + MathLib.VectorNormalize(ref dir); + + float idealYaw = Util.AngleMod(Util.VecToYaw(dir)); + + SetIdealYawAndUpdate(idealYaw); + + float diff = Util.AngleDiff(moveYaw, GetOuter()!.GetLocalAngles().Y); + GetOuter()!.SetPoseParameter(GetOuter()!.LookupPoseMoveYaw(), diff); + } + } + public void SetIdealYaw(float idealYaw) => IdealYaw = idealYaw; + public void SetIdealYaw(in Vector3 facing) => SetIdealYaw(Util.VecToYaw(facing)); public void SetIdealYawAndUpdate(float idealYaw, float yawSpeed = AI_CALC_YAW_SPEED) { SetIdealYaw(idealYaw); @@ -39,15 +383,48 @@ public void SetIdealYawAndUpdate(float idealYaw, float yawSpeed = AI_CALC_YAW_SP UpdateYaw(-1); } + public void SetIdealYawAndUpdate(in Vector3 facing, float yawSpeed = AI_CALC_YAW_SPEED) => SetIdealYawAndUpdate(Util.VecToYaw(facing), yawSpeed); + + public void SetIdealYawToTargetAndUpdate(in Vector3 target, float yawSpeed = AI_CALC_YAW_SPEED) => SetIdealYawAndUpdate(GetOuter()!.CalcIdealYaw(target), yawSpeed); + public virtual void AddFacingTarget(BaseEntity? target, float importance, float duration, float ramp = 0.0f) => FacingQueue.Add(target, importance, duration, ramp); public virtual void AddFacingTarget(in Vector3 position, float importance, float duration, float ramp = 0.0f) => FacingQueue.Add(position, importance, duration, ramp); public virtual void AddFacingTarget(BaseEntity? target, in Vector3 position, float importance, float duration, float ramp = 0.0f) => FacingQueue.Add(target, position, importance, duration, ramp); + public virtual float GetFacingDirection(out Vector3 vecDir) { + float totalInterest = 0.0f; + vecDir = new(0, 0, 0); + + int i; + + for (i = 0; i < FacingQueue.Count;) { + if (!FacingQueue[i].IsActive()) + FacingQueue.RemoveAt(i); + else + i++; + } + + for (i = 0; i < FacingQueue.Count; i++) { + float interest = FacingQueue[i].Interest(); + Vector3 tmp = FacingQueue[i].GetPosition() - GetOuter()!.GetAbsOrigin(); + + MathLib.VectorNormalize(ref tmp); + + vecDir = vecDir * (1 - interest) + tmp * interest; + + totalInterest = 1 - (1 - totalInterest) * (1 - interest); + + MathLib.VectorNormalize(ref vecDir); + } + + return totalInterest; + } + + public void SnapYaw() => UpdateYaw(360); + public void SetYawSpeed(float yawSpeed) => YawSpeed = yawSpeed; public float GetYawSpeed() => YawSpeed; - public virtual void ResetMoveCalculations() { } - public virtual void RecalculateYawSpeed() { SetYawSpeed(CalcYawSpeed()); } @@ -136,22 +513,71 @@ public void SetIdealYawToTarget(in Vector3 target, float noise = 0.0f, float off public virtual void MaintainTurnActivity() { } public virtual bool AddTurnGesture(float yd) => false; - public virtual void MoveStop() { - Velocity = default; - GetOuter()!.GetLocalNavigator()!.ResetMoveCalculations(); + public AIMoveResult MoveNormalExecute(in AILocalMoveGoal move) { + AIMotorMoveResult motorResult; + AIMoveTrace moveTrace; + + if (move.NavType == Navigation.Ground) + motorResult = MoveGroundExecute(move, out moveTrace); + else { + Assert(move.NavType == Navigation.Fly); + motorResult = MoveFlyExecute(move, out moveTrace); + } + + AIMoveResult result = MoveResults[(int)motorResult]; + + if (result != AIMoveResult.Ok) { + OnMoveExecuteFailed(move, moveTrace, motorResult, ref result); + SetMoveInterval(0); + } + + return result; } - public virtual void MoveClimbStop() => throw new NotImplementedException(); + static readonly AIMoveResult[] MoveResults = [ + AIMoveResult.Illegal, + AIMoveResult.Ok, + AIMoveResult.BlockedNPC, + AIMoveResult.BlockedWorld, + AIMoveResult.BlockedWorld, + ]; + + public virtual float MinCheckDist() { + float moveDist = GetMoveInterval() * GetIdealSpeed(); + float minDist = Math.Max(MinStoppingDist(), moveDist); + if (minDist < GetOuter()!.GetHullWidth()) + minDist = GetOuter()!.GetHullWidth(); + return minDist; + } - public Vector3 Velocity; + public AI_Navigator? GetNavigator() => GetOuter()!.GetNavigator(); + public int SelectWeightedSequence(Activity activity) => GetOuter()!.SelectWeightedSequence(activity); + public float GetSequenceGroundSpeed(int sequence) => (float)GetOuter()!.GetSequenceGroundSpeed(sequence); + + protected AI_MoveProbe? GetMoveProbe() => MoveProbe; + protected void SetSmoothedVelocity(in Vector3 velocity) => GetOuter()!.SetAbsVelocity(velocity); + protected Vector3 GetSmoothedVelocity() => GetOuter()!.GetSmoothedVelocity(); + protected float StepHeight() => GetOuter()!.StepHeight(); + protected void SetMoveVel(in Vector3 velocity) => Velocity = velocity; public bool IsYawLocked() => YawLocked; public void SetYawLocked(bool state) => YawLocked = state; + public float MoveInterval; + public float IdealYaw; public float YawSpeed; + + public Vector3 Velocity; + public Vector3 AngularVelocity; + + public int DismountSequence; + public Vector3 Dismount; + + public readonly AI_InterestTarget FacingQueue = new(); + public AI_MoveProbe? MoveProbe; public IAI_MovementSink? Proxied; + public bool YawLocked; - public readonly AI_InterestTarget FacingQueue = new(); } From 26df81121f51a4320c24b366fe26b96178a7bf0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:19:48 +0300 Subject: [PATCH 30/73] Port AI navigator --- Game.Server/AI_Navigator.cs | 2631 +++++++++++++++++++++++++++++++++-- 1 file changed, 2534 insertions(+), 97 deletions(-) diff --git a/Game.Server/AI_Navigator.cs b/Game.Server/AI_Navigator.cs index 68570f3e4..c87302fb7 100644 --- a/Game.Server/AI_Navigator.cs +++ b/Game.Server/AI_Navigator.cs @@ -4,7 +4,10 @@ using Source; using Source.Common; +using Source.Common.Commands; using Source.Common.Formats.BSP; +using Source.Common.Mathematics; +using Source.Common.Physics; using System.Numerics; @@ -12,75 +15,2049 @@ namespace Game.Server; public static class AI_NavigatorGlobals { + public const float AIN_DEF_TOLERANCE = -1.0f; + public const float AIN_HULL_TOLERANCE = -2.0f; public const Activity AIN_DEF_ACTIVITY = Activity.ACT_INVALID; + public const int AIN_NO_NODE = -1; + public static readonly Vector3 AIN_NO_DEST = new(float.MaxValue, float.MaxValue, float.MaxValue); + + public static readonly ConVar ai_vehicle_avoidance = new("ai_vehicle_avoidance", "1", FCvar.Cheat); + public static readonly ConVar ai_navigator_generate_spikes = new("ai_navigator_generate_spikes", "0"); + public static readonly ConVar ai_navigator_generate_spikes_strength = new("ai_navigator_generate_spikes_strength", "8"); + public static readonly ConVar ai_use_clipped_paths = new("ai_use_clipped_paths", "1"); +} + +[Flags] +public enum AI_NavGoalFlags +{ + Default = 0, + YawToDest = 0x01, + UpdateTargetPos = 0x02, + NoPathcornerPathfinding = 0x04, +} + +[Flags] +public enum AI_NavSetGoalFlags +{ + ClearPreviousState = 0x01, + ClearTarget = 0x02, + DiscardIfFail = 0x04, + NoPathTaskFail = 0x08, +} + +public enum AI_NpcBlockHandling +{ + Block, + Avoid, + Ignore, +} + +public enum AI_NavPathProgress +{ + NoChange, + Advanced, + Complete, + Blocked, +} + +public struct AI_NavGoal +{ + public AI_NavGoal() : this(NavGoalType.Invalid) { } + + public AI_NavGoal(NavGoalType type, Activity activity = AIN_DEF_ACTIVITY, float tolerance = AIN_DEF_TOLERANCE, + AI_NavGoalFlags flags = AI_NavGoalFlags.Default, BaseEntity? target = null, bool defTarget = true) + : this(type, AIN_NO_DEST, AIN_NO_NODE, activity, tolerance, flags, target, defTarget) { } + + public AI_NavGoal(in Vector3 dest, Activity activity = AIN_DEF_ACTIVITY, float tolerance = AIN_DEF_TOLERANCE, + AI_NavGoalFlags flags = AI_NavGoalFlags.Default, BaseEntity? target = null, bool defTarget = true) + : this(NavGoalType.Location, dest, AIN_NO_NODE, activity, tolerance, flags, target, defTarget) { } + + public AI_NavGoal(NavGoalType type, in Vector3 dest, Activity activity = AIN_DEF_ACTIVITY, float tolerance = AIN_DEF_TOLERANCE, + AI_NavGoalFlags flags = AI_NavGoalFlags.Default, BaseEntity? target = null, bool defTarget = true) + : this(type, dest, AIN_NO_NODE, activity, tolerance, flags, target, defTarget) { } + + public AI_NavGoal(int destNode, Activity activity = AIN_DEF_ACTIVITY, float tolerance = AIN_DEF_TOLERANCE, + AI_NavGoalFlags flags = AI_NavGoalFlags.Default, BaseEntity? target = null, bool defTarget = true) + : this(NavGoalType.Location, AIN_NO_DEST, destNode, activity, tolerance, flags, target, defTarget) { } + + public AI_NavGoal(NavGoalType type, int destNode, Activity activity = AIN_DEF_ACTIVITY, float tolerance = AIN_DEF_TOLERANCE, + AI_NavGoalFlags flags = AI_NavGoalFlags.Default, BaseEntity? target = null, bool defTarget = true) + : this(type, AIN_NO_DEST, destNode, activity, tolerance, flags, target, defTarget) { } + + AI_NavGoal(NavGoalType type, in Vector3 dest, int destNode, Activity activity, float tolerance, AI_NavGoalFlags flags, BaseEntity? target, bool defTarget) { + Type = type; + Dest = dest; + DestNode = destNode; + Activity = activity; + Tolerance = tolerance; + MaxInitialSimplificationDist = -1; + Flags = flags; + Target = target; + DefTarget = defTarget && target == null; + ArrivalActivity = AIN_DEF_ACTIVITY; + ArrivalSequence = (int)Activity.ACT_INVALID; + } + + public NavGoalType Type; + + public Vector3 Dest; + public int DestNode; + + public Activity Activity; + + public Activity ArrivalActivity; + public int ArrivalSequence; + + public float Tolerance; + + public float MaxInitialSimplificationDist; + + public AI_NavGoalFlags Flags; + + public BaseEntity? Target; + public bool DefTarget; +} + +public struct AI_ProgressFlyPathParams(Mask collisionMask, float strictPointTolerance = 32.0f, float blockTolerance = 0.0f, + float waypointTolerance = 100, float goalTolerance = 12, AI_NpcBlockHandling blockHandling = AI_NpcBlockHandling.Block) +{ + public void SetCurrent(BaseEntity? newTarget, bool newTrySimplify = true) { + Target = newTarget; + TrySimplify = newTrySimplify; + } + + public Mask CollisionMask = collisionMask; + public float StrictPointTolerance = strictPointTolerance; + public float BlockTolerance = blockTolerance; + public float WaypointTolerance = waypointTolerance; + public float GoalTolerance = goalTolerance; + public AI_NpcBlockHandling BlockHandling = blockHandling; + + public BaseEntity? Target = null; + public bool TrySimplify = true; +} + +class AI_NavInHintGroupFilter(string? group = null) : INearestNodeFilter +{ + public bool IsValid(AI_Node node) { + if (node.GetHint() == null) + return false; + + if (node.GetHint()!.GetGroup() != Group) + return false; + + return true; + } + + public bool ShouldContinue() => true; + + public string? Group = group; } -public class AI_Navigator : AI_Component, IAI_MovementSink -{ - public AI_Navigator(AI_BaseNPC? outer) : base(outer) { - Path = new AI_Path(); - AINetwork = null; - NotOnNetwork = false; - NextSimplifyTime = 0; +public class AI_Navigator : AI_Component, IAI_MovementSink +{ + const float NAV_STOP_MOVING_TOLERANCE = 6; + + const float MIN_ANGLE_COS_SIMPLIFY = 0.766f; + + static readonly float[] ROUTE_SIMPLIFY_TIME_DELAY = [0.5f, 1.0f]; + static readonly float[] NO_PVS_ROUTE_SIMPLIFY_TIME_DELAY = [1.0f, 2.0f]; + static readonly float[] QUICK_SIMPLIFY_TIME_DELAY = [float.MinValue, 0.3f]; + + const float FLY_ROUTE_SIMPLIFY_TIME_DELAY = 0.3f; + const float FLY_ROUTE_SIMPLIFY_LOOK_DIST = 12.0f * 12.0f; + + static long g_iFrameLastSimplified; + + struct SimplifyForwardScanParams(float scanDist, float radius, float increment, int maxSamples) + { + public float ScanDist = scanDist; + public float Radius = radius; + public float Increment = increment; + public int MaxSamples = maxSamples; + } + + static SimplifyForwardScanParams fullScanParams = new(32 * 12, 12 * 12, 3 * 12, 4); + + static readonly SimplifyForwardScanParams[] quickScanParams = [ + new((12.0f * 12.0f) - 0.1f, 12 * 12, 0.5f * 12, 1), + new((6.0f * 12.0f) - 0.1f, 8 * 12, 1.0f * 12, 1), + ]; + + public AI_Navigator(AI_BaseNPC? outer) : base(outer) { + Path = new AI_Path(); + AINetwork = null; + NotOnNetwork = false; + NextSimplifyTime = 0; + + LastSuccessfulSimplifyTime = -1; + + ClippedWaypoints = new AI_WaypointList(); + TimeClipped = -1; + + ValidateActivitySpeed = true; + CalledStartMove = false; + + NavType = Navigation.Ground; + NavComplete = false; + LastNavFailed = false; + + PeerWaitMoveTimer.Set(0.25f); + PeerWaitClearTimer.Set(3.0f); + NextSidestepTimer.Set(5.0f); + + PosBeginFailedSteer = vec3_invalid; + TimeBeginFailedSteer = float.MaxValue; + + TimeLastAvoidanceTriangulate = -1; + + NoPathcornerPathfinds = false; + LocalSucceedOnWithinTolerance = false; + + RememberStaleNodes = true; + + Motor = null; + MoveProbe = null; + LocalNavigator = null; + + NavFailCounter = 0; + LastNavFailTime = -1; + } + + public virtual void Init(AI_Network? network) { + Motor = GetOuter()!.GetMotor(); + MoveProbe = GetOuter()!.GetMoveProbe(); + LocalNavigator = GetOuter()!.GetLocalNavigator(); + AINetwork = network; + } + + public void SetPathcornerPathfinding(bool newVal) => NoPathcornerPathfinds = !newVal; + public void SetRememberStaleNodes(bool newVal) => RememberStaleNodes = newVal; + public void SetValidateActivitySpeed(bool validateActivitySpeed) => ValidateActivitySpeed = validateActivitySpeed; + public void SetLocalSucceedOnWithinTolerance(bool newVal) => LocalSucceedOnWithinTolerance = newVal; + + static bool ActivityIsLocomotive(Activity activity) => activity > Activity.ACT_IDLE; + + protected AI_Pathfinder? GetPathfinder() => GetOuter()!.GetPathfinder(); + + protected BaseEntity? GetNavTargetEntity() { + if (GetGoalType() == NavGoalType.Enemy || GetGoalType() == NavGoalType.TargetEnt) + return GetOuter()!.GetNavTargetEntity(); + return GetPath().GetTarget(); + } + + protected void TaskMovementComplete() => GetOuter()!.TaskMovementComplete(); + protected float MaxYawSpeed() => GetOuter()!.MaxYawSpeed(); + protected void SetSpeed(float speed) => GetOuter()!.Speed = speed; + + AI_HullType GetHullType() => GetOuter()!.GetHullType(); + float GetHullWidth() => GetOuter()!.GetHullWidth(); + ref readonly Vector3 GetLocalOrigin() => ref GetOuter()!.GetLocalOrigin(); + ref readonly Vector3 GetAbsOrigin() => ref GetOuter()!.GetAbsOrigin(); + Capability CapabilitiesGet() => GetOuter()!.CapabilitiesGet(); + void SetActivity(Activity activity) => GetOuter()!.SetActivity(activity); + Activity GetActivity() => GetOuter()!.GetActivity(); + bool HasMemory(AI_MemoryFlags memory) => GetOuter()!.HasMemory(memory); + void Remember(AI_MemoryFlags memory) => GetOuter()!.Remember(memory); + void Forget(AI_MemoryFlags memory) => GetOuter()!.Forget(memory); + void TaskComplete() => GetOuter()!.TaskComplete(); + void TaskFail(AI_TaskFailureCode code) => GetOuter()!.TaskFail(code); + + bool FindPath(in AI_NavGoal goal, AI_NavSetGoalFlags flags) { + AI_Path path = GetPath(); + + GetOuter()?.Remember(AI_MemoryFlags.TaskExpensive); + + if ((flags & AI_NavSetGoalFlags.ClearPreviousState) != 0) + path.Clear(); + else if ((flags & AI_NavSetGoalFlags.ClearTarget) != 0) + path.ClearTarget(); + + if (goal.Activity != AIN_DEF_ACTIVITY) + path.SetMovementActivity(goal.Activity); + else if (path.GetMovementActivity() == Activity.ACT_INVALID) + path.SetMovementActivity((GetOuter()!.GetState() == NPCState.Combat) ? Activity.ACT_RUN : Activity.ACT_WALK); + + if (goal.Tolerance == AIN_HULL_TOLERANCE) + path.SetGoalTolerance(GetHullWidth()); + else if (goal.Tolerance != AIN_DEF_TOLERANCE) + path.SetGoalTolerance(goal.Tolerance); + else if (path.GetGoalTolerance() == 0) + path.SetGoalTolerance(GetOuter()!.GetDefaultNavGoalTolerance()); + + path.SetWaypointTolerance(GetHullWidth() * 0.5f); + + path.SetGoalType(NavGoalType.None); + path.SetGoalType(goal.Type); + path.SetGoalFlags(goal.Flags); + + BaseEntity? pathTarget = goal.Target; + bool pathTargetIsDef = goal.DefTarget; + if ((goal.Type == NavGoalType.TargetEnt) || (goal.Type == NavGoalType.Enemy)) { + if (goal.Type == NavGoalType.TargetEnt) + pathTarget = GetOuter()!.GetTarget(); + else + pathTarget = GetOuter()!.GetEnemy(); + pathTargetIsDef = false; + + Assert(goal.DefTarget || goal.Target == pathTarget); + + if (goal.Dest != AIN_NO_DEST) + path.SetTargetOffset(goal.Dest); + } + else { + if (goal.Dest != AIN_NO_DEST) + path.ResetGoalPosition(goal.Dest); + else if (goal.DestNode != AIN_NO_NODE) + path.ResetGoalPosition(GetNodePos(goal.DestNode)); + } + + if (pathTarget != null && !pathTargetIsDef) + path.SetTarget(pathTarget); + + path.ClearWaypoints(); + bool result = FindPath((flags & AI_NavSetGoalFlags.NoPathTaskFail) == 0); + + if (result == false) { + if ((flags & AI_NavSetGoalFlags.DiscardIfFail) != 0) + path.Clear(); + else + path.SetGoalType(NavGoalType.None); + } + else { + if (goal.ArrivalActivity != AIN_DEF_ACTIVITY && goal.ArrivalActivity > Activity.ACT_RESET) + path.SetArrivalActivity(goal.ArrivalActivity); + else if (goal.ArrivalSequence != -1) + path.SetArrivalSequence(goal.ArrivalSequence); + + if (goal.Type == NavGoalType.Enemy) { + path.SetGoalDirection(pathTarget); + path.SetGoalSpeed(pathTarget); + } + else + path.SetGoalDirection(path.ActualGoalPosition() - GetAbsOrigin()); + } + + return result; + } + + public virtual bool SetGoal(in AI_NavGoal goal, AI_NavSetGoalFlags flags = 0) { + AI_Path path = GetPath(); + + OnNewGoal(); + + if ((flags & AI_NavSetGoalFlags.ClearPreviousState) != 0) + ClearPath(); + + if (GetOuter()!.IsCurTaskContinuousMove()) + flags |= AI_NavSetGoalFlags.NoPathTaskFail; + + bool result = FindPath(goal, flags); + + if (result == false) { + if ((flags & AI_NavSetGoalFlags.DiscardIfFail) != 0) + ClearPath(); + } + else { + if ((goal.Flags & AI_NavGoalFlags.YawToDest) != 0) + GetMotor()!.SetIdealYawToTarget(path.ActualGoalPosition()); + + SimplifyPath(true, goal.MaxInitialSimplificationDist); + } + + return result; + } + + public virtual bool SetGoalTarget(BaseEntity? entity, in Vector3 offset) { + OnNewGoal(); + AI_Path path = GetPath(); + path.SetTargetOffset(offset); + path.SetTarget(entity); + path.ClearWaypoints(); + return FindPath(!GetOuter()!.IsCurTaskContinuousMove()); + } + + public bool SetRadialGoal(in Vector3 destination, in Vector3 center, float radius, float arc, float stepDist, bool clockwise, bool airRoute = false) { + OnNewGoal(); + GetPath().SetGoalType(NavGoalType.Location); + + GetPath().SetWaypoints(GetPathfinder()!.BuildRadialRoute(GetLocalOrigin(), center, destination, radius, arc, stepDist, clockwise, GetPath().GetGoalTolerance(), airRoute), true); + GetPath().SetGoalTolerance(GetOuter()!.GetDefaultNavGoalTolerance()); + + return IsGoalActive(); + } + + public bool SetRandomGoal(in Vector3 from, float minPathLength, in Vector3 dir = default) { + OnNewGoal(); + if (GetNetwork()!.NumNodes() <= 0) + return false; + + INearestNodeFilter? filter = null; + AI_NavInHintGroupFilter hintFilter = new(); + if (GetOuter()!.GetHintGroup() != null) { + hintFilter.Group = GetOuter()!.GetHintGroup(); + filter = hintFilter; + } + + int fromNodeID = GetNetwork()!.NearestNodeToPoint(GetOuter(), from, true, filter); + + if (fromNodeID == NO_NODE) + return false; + + AI_Waypoint? route = GetPathfinder()!.FindShortRandomPath(fromNodeID, minPathLength, dir); + + if (route == null) + return false; + + GetPath().SetGoalType(NavGoalType.Location); + GetPath().SetWaypoints(route); + GetPath().SetLastNodeAsGoal(); + GetPath().SetGoalTolerance(GetOuter()!.GetDefaultNavGoalTolerance()); + + SimplifyPath(true); + + return true; + } + + public bool SetRandomGoal(float minPathLength, in Vector3 dir = default) => SetRandomGoal(GetLocalOrigin(), minPathLength, dir); + + public bool SetDirectGoal(in Vector3 goalPos, Navigation navType = Navigation.Ground) { + OnNewGoal(); + ClearPath(); + GetPath().SetGoalType(NavGoalType.Location); + GetPath().SetWaypoints(new AI_Waypoint(goalPos, 0, navType, WaypointFlags.ToGoal, NO_NODE)); + GetPath().SetGoalTolerance(GetOuter()!.GetDefaultNavGoalTolerance()); + GetPath().SetGoalPosition(goalPos); + return true; + } + + static bool SetWanderGoalByRandomVector(AI_Navigator nav, float minRadius, float maxRadius, int numTries) { + while (--numTries >= 0) { + float dist = random.RandomFloat(minRadius, maxRadius); + Vector3 dir = Util.YawToVector(random.RandomFloat(0, 359.99f)); + + if (nav.SetVectorGoal(dir, dist, minRadius)) + return true; + } + + return false; + } + + public bool SetWanderGoal(float minRadius, float maxRadius) { + if (GetOuter()!.GetHintGroup() == null) + return SetWanderGoalByRandomVector(this, minRadius, maxRadius, 5) || SetRandomGoal(1); + else + return SetRandomGoal(1) || SetWanderGoalByRandomVector(this, minRadius, maxRadius, 5); + } + + static void CalculateDeflection(in Vector3 start, in Vector3 dir, in Vector3 normal, out Vector3 result) { + Vector3 temp = Vector3.Cross(dir, normal); + result = Vector3.Cross(normal, temp); + MathLib.VectorNormalize(ref result); + } + + public bool SetVectorGoal(in Vector3 dir, float targetDist, float minDist = 0, bool shouldDeflect = false) { + if (FindVectorGoal(out Vector3 result, dir, targetDist, minDist, shouldDeflect)) + return SetGoal(new AI_NavGoal(result)); + + return false; + } + + public bool SetVectorGoalFromTarget(in Vector3 goalPos, float minDist = 0, bool shouldDeflect = false) { + float dist = ComputePathDirection(GetNavType(), GetLocalOrigin(), goalPos, out Vector3 dir); + return SetVectorGoal(dir, dist, minDist, shouldDeflect); + } + + public bool FindVectorGoal(out Vector3 result, in Vector3 dir, float targetDist, float minDist = 0, bool shouldDeflect = false) { + float distAchieved; + + GetOuter()?.Remember(AI_MemoryFlags.TaskExpensive); + + Vector3 testLoc = GetLocalOrigin() + (dir * targetDist); + GetMoveProbe()!.MoveLimit(GetNavType(), GetLocalOrigin(), testLoc, Mask.NPCSolid, null, out AIMoveTrace moveTrace); + + if (moveTrace.Status != AIMoveResult.Ok) { + distAchieved = targetDist - moveTrace.DistObstructed; + if (shouldDeflect && moveTrace.HitNormal != vec3_origin) { + Vector3 normal = moveTrace.HitNormal; + if (GetNavType() == Navigation.Ground) + normal.Z = 0; + + CalculateDeflection(moveTrace.EndPosition, dir, normal, out Vector3 deflect); + + testLoc = moveTrace.EndPosition + (deflect * (targetDist - distAchieved)); + + Vector3 temp = moveTrace.EndPosition; + GetMoveProbe()!.MoveLimit(GetNavType(), temp, testLoc, Mask.NPCSolid, null, out moveTrace); + + distAchieved += (targetDist - distAchieved) - moveTrace.DistObstructed; + } + + if (distAchieved < minDist + 0.01) { + result = default; + return false; + } + } + + result = moveTrace.EndPosition; + return true; + } + + public bool PrependLocalAvoidance(float distObstacle, in AIMoveTrace directTrace) { + if (AIStrongOpt()) + return false; + + if (GetOuter()!.IsFlaggedEfficient()) + return false; + + if (TimeLastAvoidanceTriangulate >= gpGlobals.CurTime) + return false; + + TimeLastAvoidanceTriangulate = gpGlobals.CurTime; + + AI_Waypoint? avoidanceRoute = null; + + Vector3 start = GetLocalOrigin(); + + if (distObstacle < GetHullWidth() * 0.5) { + Vector3 testBackaway = GetCurWaypointPos() - GetLocalOrigin(); + MathLib.VectorNormalize(ref testBackaway); + testBackaway *= -GetHullWidth(); + testBackaway += GetLocalOrigin(); + + AI_MoveLimitFlags backawayFlags = (GetNavType() == Navigation.Ground) ? AI_MoveLimitFlags.TwoD : AI_MoveLimitFlags.Default; + + if (GetMoveProbe()!.MoveLimit(GetNavType(), GetLocalOrigin(), testBackaway, + Mask.NPCSolid, GetNavTargetEntity(), + 100.0f, + backawayFlags, out AIMoveTrace backawayTrace)) { + start = backawayTrace.EndPosition; + avoidanceRoute = new AI_Waypoint(start, 0, GetNavType(), WaypointFlags.ToDetour, NO_NODE); + } + } + + AI_Waypoint? triangulation = GetPathfinder()!.BuildTriangulationRoute( + start, + GetCurWaypointPos(), + GetNavTargetEntity(), + WaypointFlags.ToDetour, + NO_NODE, + 0.0f, + distObstacle, + GetNavType()); + + if (triangulation == null) { + avoidanceRoute?.Delete(); + return false; + } + + if (avoidanceRoute != null) + avoidanceRoute.SetNext(triangulation); + else + avoidanceRoute = triangulation; + + float moveThisInterval = GetMotor()!.CalcIntervalMove(); + Vector3 dir = avoidanceRoute.GetPos() - GetLocalOrigin(); + float dist = MathLib.VectorNormalize(ref dir); + Vector3 testPos; + if (dist > moveThisInterval) { + dist = moveThisInterval; + testPos = GetLocalOrigin() + dir * dist; + } + else + testPos = avoidanceRoute.GetPos(); + + AI_MoveLimitFlags flags = (GetNavType() == Navigation.Ground) ? AI_MoveLimitFlags.TwoD : AI_MoveLimitFlags.Default; + + if (!GetMoveProbe()!.MoveLimit(GetNavType(), GetLocalOrigin(), testPos, + Mask.NPCSolid, GetNavTargetEntity(), + 100.0f, + flags, out _)) { + DeleteAll(avoidanceRoute); + return false; + } + + GetPath().PrependWaypoints(avoidanceRoute); + return true; + } + + public void PrependWaypoint(in Vector3 newPoint, Navigation navType, WaypointFlags waypointFlags = 0) => GetPath().PrependWaypoint(newPoint, navType, waypointFlags); + + public Vector3 GetGoalPos() => GetPath().BaseGoalPosition(); + + public BaseEntity? GetGoalTarget() => GetPath().GetTarget(); + + public float GetGoalTolerance() => GetPath().GetGoalTolerance(); + + public void SetGoalTolerance(float tolerance) => GetPath().SetGoalTolerance(tolerance); + + public bool RefindPathToGoal(bool signalTaskStatus = true, bool dontIgnoreBadLinks = false) => FindPath(signalTaskStatus, dontIgnoreBadLinks); + + public bool UpdateGoalPos(in Vector3 goalPos) { + if (GetNavType() == Navigation.Jump) { + DevMsg("Updating goal pos while jumping!\n"); + Assert(false); + return false; + } + + Assert((GetPath().GoalType() != NavGoalType.Enemy) && (GetPath().GoalType() != NavGoalType.TargetEnt)); + + GetPath().ResetGoalPosition(goalPos); + if (FindPath(!GetOuter()!.IsCurTaskContinuousMove())) { + SimplifyPath(true); + return true; + } + return false; + } + + public Activity SetMovementActivity(Activity activity) => GetPath().SetMovementActivity(activity); + + public void StopMoving(bool immediate = true) { + if (IsGoalSet()) { + if (immediate || !SetGoalFromStoppingPath()) + OnNavComplete(); + } + else + ClearGoal(); + } + + public bool ClearGoal() { + ClearPath(); + OnNewGoal(); + return true; + } + + public int GetMovementSequence() { + int sequence = GetPath().GetMovementSequence(); + if (sequence == (int)Activity.ACT_INVALID) { + Activity activity = GetPath().GetMovementActivity(); + Assert(activity != Activity.ACT_INVALID); + + sequence = GetOuter()!.SelectWeightedSequence(GetOuter()!.TranslateActivity(activity)); + if (sequence == (int)Activity.ACT_INVALID) { + if (activity == Activity.ACT_SCRIPT_CUSTOM_MOVE) + sequence = GetOuter()!.GetScriptCustomMoveSequence(); + else + sequence = GetOuter()!.SelectWeightedSequence(GetOuter()!.TranslateActivity(Activity.ACT_WALK)); + } + Assert(sequence != (int)Activity.ACT_INVALID); + GetPath().SetMovementSequence(sequence); + } + return sequence; + } + + public void SetMovementSequence(int sequence) => GetPath().SetMovementSequence(sequence); + + public Activity GetMovementActivity() => GetPath().GetMovementActivity(); + + public void SetArrivalActivity(Activity activity) => GetPath().SetArrivalActivity(activity); + + public int GetArrivalSequence(int curSequence) { + int sequence = GetPath().GetArrivalSequence(); + if (sequence == (int)Activity.ACT_INVALID) { + Activity activity = GetOuter()!.GetStoppedActivity(); + + Assert(activity != Activity.ACT_INVALID); + if (activity == Activity.ACT_INVALID) + activity = Activity.ACT_IDLE; + + sequence = GetOuter()!.SelectWeightedSequence(GetOuter()!.TranslateActivity(activity), curSequence); + + if (sequence == (int)Activity.ACT_INVALID) + sequence = GetOuter()!.SelectWeightedSequence(GetOuter()!.TranslateActivity(Activity.ACT_IDLE), curSequence); + Assert(sequence != (int)Activity.ACT_INVALID); + GetPath().SetArrivalSequence(sequence); + } + return sequence; + } + + public void SetArrivalSequence(int sequence) { + GetPath().SetArrivalActivity(Activity.ACT_INVALID); + GetPath().SetArrivalSequence(sequence); + } + + public Activity GetArrivalActivity() => GetPath().GetArrivalActivity(); + + public void SetArrivalDirection(in Vector3 goalDirection) => GetPath().SetGoalDirection(goalDirection); + + public void SetArrivalDirection(in QAngle goalAngle) { + MathLib.AngleVectors(goalAngle, out Vector3 goalDirection); + GetPath().SetGoalDirection(goalDirection); + } + + public void SetArrivalDirection(BaseEntity? target) => GetPath().SetGoalDirection(target); + + public Vector3 GetArrivalDirection() => GetPath().GetGoalDirection(GetAbsOrigin()); + + public void SetArrivalSpeed(float speed) => GetPath().SetGoalSpeed(speed); + + public float GetArrivalSpeed() { + float speed = GetPath().GetGoalSpeed(GetAbsOrigin()); + + if (speed >= 0.0) + return speed; + + int sequence = GetArrivalSequence((int)Activity.ACT_INVALID); + + if (sequence != (int)Activity.ACT_INVALID) { + speed = GetOuter()!.GetEntryVelocity(sequence); + SetArrivalSpeed(speed); + } + else + speed = 0.0f; + + return speed; + } + + public void SetArrivalDistance(float distance) => GetPath().SetGoalStoppingDistance(distance); + + public float GetArrivalDistance() => GetPath().GetGoalStoppingDistance(); + + public Vector3 GetCurWaypointPos() => GetPath().CurWaypointPos(); + + public WaypointFlags GetCurWaypointFlags() => GetPath().CurWaypointFlags(); + + public NavGoalType GetGoalType() => GetPath().GoalType(); + + public AI_NavGoalFlags GetGoalFlags() => GetPath().GoalFlags(); + + public bool CurWaypointIsGoal() => GetPath().CurWaypointIsGoal(); + + public bool IsGoalSet() => GetPath().GoalType() != NavGoalType.None; + + public bool IsGoalActive() => GetPath() != null && !GetPath().IsEmpty(); + + public bool GetPointAlongPath(out Vector3 result, float distance, bool reducibleOnly = false) { + result = default; + if (GetPath().GetCurWaypoint() == null) + return false; + + AI_Waypoint curWaypoint = GetPath().GetCurWaypoint()!; + AI_Waypoint endPoint = curWaypoint; + float distRemaining = distance; + float distToNext; + Vector3 posPrev = GetLocalOrigin(); + + while (endPoint.GetNext() != null) { + distToNext = ComputePathDistance(GetNavType(), posPrev, endPoint.GetPos()); + + if (distToNext > distRemaining) + break; + + distRemaining -= distToNext; + posPrev = endPoint.GetPos(); + if (reducibleOnly && !endPoint.IsReducible()) + break; + endPoint = endPoint.GetNext()!; + } + + float distToEnd = ComputePathDistance(GetNavType(), posPrev, endPoint.GetPos()); + if (distToEnd - distRemaining < 0.1) + result = endPoint.GetPos(); + else { + result = endPoint.GetPos() - posPrev; + MathLib.VectorNormalize(ref result); + result *= distRemaining; + result += posPrev; + } + + return true; + } + + public float GetPathDistanceToGoal() => GetPath().GetPathDistanceToGoal(GetAbsOrigin()); + + public float GetPathTimeToGoal() { + if (GetOuter()!.GroundSpeed != 0) + return GetPathDistanceToGoal() / GetOuter()!.GroundSpeed; + return 0; + } + + public int GetNearestNode() => GetPathfinder()!.NearestNodeToNPC(); + + public Vector3 GetNodePos(int node) => GetNetwork()!.GetNode(node)!.GetPosition(GetHullType()); + + public virtual void OnScheduleChange() { } + + public virtual void OnClearPath() { } + + public virtual void OnNewGoal() { + ResetCalculations(); + NavComplete = true; + } + + public virtual void OnNavComplete() { + ResetCalculations(); + TaskMovementComplete(); + NavComplete = true; + } + + void OnNavFailed(bool movement = false) { + if (movement) + GetOuter()!.OnMovementFailed(); + + ResetCalculations(); + NavComplete = true; + LastNavFailed = true; + } + + void OnNavFailed(AI_TaskFailureCode code, bool movement = false) { + if (GetOuter()!.ShouldFailNav(movement)) { + OnNavFailed(movement); + SetActivity(GetOuter()!.GetStoppedActivity()); + TaskFail(code); + } + else { + NavFailCounter++; + LastNavFailTime = gpGlobals.CurTime; + if (GetOuter()!.ShouldBruteForceFailedNav()) { + if (movement) { + TimeBeginFailedSteer = float.MaxValue; + + BaseEntity? blocker = GetBlockingEntity(); + if (blocker != null && !blocker.IsWorld() && !blocker.IsPlayer() && !BaseEntity.FClassnameIs(blocker, "func_tracktrain")) { + if (NPCPhysics_CreateSolver(GetOuter()!, blocker, true, 10.0f) != null) + ClearNavFailCounter(); + } + + if (GetNavFailCounter() > 0) { + if (TeleportAlongPath()) + ClearNavFailCounter(); + } + } + else { + BaseEntity? blocker = GetMoveProbe()!.GetBlockingEntity(); + if (blocker != null) { + if (NPCPhysics_CreateSolver(GetOuter()!, blocker, true, 10.0f) != null) + ClearNavFailCounter(); + } + } + } + } + } + + public int GetNavFailCounter() => NavFailCounter; + + public void ClearNavFailCounter() => NavFailCounter = 0; + + public TimeUnit_t GetLastNavFailTime() => LastNavFailTime; + + public bool TeleportAlongPath() { + while (GetPath().GetCurWaypoint() != null) { + Vector3 start = GetPath().CurWaypointPos(); + AdvancePath(); + + GetOuter()!.GetMoveProbe()!.FloorPoint(start, Mask.NPCSolid, GetOuter()!.StepHeight(), -64, out Vector3 testPoint); + + if (CanFitAtPosition(testPoint, Mask.NPCSolid, false, false)) { + if (GetOuter()!.GetMoveProbe()!.CheckStandPosition(testPoint, Mask.NPCSolid)) { + GetOuter()!.Teleport(testPoint, null, null); + GetOuter()!.SetGroundEntity(null); + GetOuter()!.PhysicsTouchTriggers(testPoint); + return true; + } + } + + if (CurWaypointIsGoal()) + break; + } + return false; + } + + public void ResetCalculations() { + PeerWaitingOn.Set(null); + PeerWaitMoveTimer.Force(); + PeerWaitClearTimer.Force(); + + BigStepGroundEnt.Set(null); + + NextSidestepTimer.Force(); + + CalledStartMove = false; + + PosBeginFailedSteer = vec3_invalid; + TimeBeginFailedSteer = float.MaxValue; + + LastSuccessfulSimplifyTime = -1; + + GetLocalNavigator()!.ResetMoveCalculations(); + GetMotor()!.ResetMoveCalculations(); + GetMoveProbe()!.ClearBlockingEntity(); + + NavFailCounter = 0; + LastNavFailTime = -1; + } + + public void SetNavType(Navigation navType) => NavType = navType; + + public bool IsInterruptable() => NavType != Navigation.Climb && NavType != Navigation.Jump; + + protected virtual AIMoveResult MoveClimb() { + Vector3 climbDest = GetPath().CurWaypointPos(); + Vector3 climbDir = climbDest - GetLocalOrigin(); + float climbDist = MathLib.VectorNormalize(ref climbDir); + + if (GetNavType() != Navigation.Climb) + GetMotor()!.MoveClimbStart(climbDest, climbDir, climbDist, GetPath().CurWaypointYaw()); + + SetNavType(Navigation.Climb); + + if (climbDist > 0.01 && + !GetMoveProbe()!.MoveLimit(Navigation.Climb, GetLocalOrigin(), GetLocalOrigin() + (climbDir * Math.Min(0.1f, climbDist - 0.005f)), Mask.NPCSolid, GetNavTargetEntity(), out AIMoveTrace moveTrace)) { + AI_BaseNPC? other = moveTrace.Obstruction?.MyNPCPointer(); + if (other != null) { + bool abort = false; + + if (!other.IsMoving()) + abort = true; + else if (other.GetNavType() == Navigation.Climb && climbDir.Z <= 0.01) { + Vector3 otherClimbDest = other.GetNavigator()!.GetPath().CurWaypointPos(); + Vector3 otherClimbDir = otherClimbDest - other.GetLocalOrigin(); + MathLib.VectorNormalize(ref otherClimbDir); + + if (Vector3.Dot(otherClimbDir, climbDir) < 0) { + abort = true; + if (other.GetNavigator()!.GetStoppingPath(ClippedWaypoints)) { + TimeClipped = gpGlobals.CurTime; + SetNavType(Navigation.Ground); + GetOuter()!.SetGravity(1.0f); + if (RefindPathToGoal(false)) + abort = false; + GetOuter()!.SetGravity(0.0f); + SetNavType(Navigation.Climb); + } + } + } + + if (abort) { + GetMotor()!.MoveClimbStop(); + SetNavType(Navigation.Ground); + return AIMoveResult.BlockedNPC; + } + } + } + + int climbNodesLeft = 0; + AI_Waypoint? waypoint = GetPath().GetCurWaypoint(); + while (waypoint != null && waypoint.NavType() == Navigation.Climb) { + ++climbNodesLeft; + waypoint = waypoint.GetNext(); + } + + AIMoveResult result = GetMotor()!.MoveClimbExecute(climbDest, climbDir, climbDist, GetPath().CurWaypointYaw(), climbNodesLeft); + + if (result == AIMoveResult.ChangeType) { + if (GetPath().GetCurWaypoint()!.GetNext() != null) + AdvancePath(); + else + OnNavComplete(); + + if (GetPath().GetCurWaypoint() == null || GetPath().GetCurWaypoint()!.GetNext() == null || !(GetPath().CurWaypointNavType() == Navigation.Climb)) { + GetMotor()!.MoveClimbStop(); + SetNavType(Navigation.Ground); + } + } + else if (result != AIMoveResult.Ok) { + GetMotor()!.MoveClimbStop(); + SetNavType(Navigation.Ground); + return result; + } + + return result; + } + + protected virtual AIMoveResult MoveJump() { + if ((GetNavType() != Navigation.Jump) && (GetOuter()!.GetFlags() & EntityFlags.OnGround) != 0) { + GetMoveProbe()!.MoveLimit(Navigation.Jump, GetLocalOrigin(), GetPath().CurWaypointPos(), + Mask.NPCSolid, GetNavTargetEntity(), out AIMoveTrace moveTrace); + if (IsMoveBlocked(moveTrace)) + return moveTrace.Status; + + SetNavType(Navigation.Jump); + + GetMotor()!.MoveJumpStart(moveTrace.JumpVelocity); + } + else if (GetNavType() == Navigation.Jump && (GetOuter()!.GetFlags() & EntityFlags.OnGround) != 0) { + AIMoveResult result = GetMotor()!.MoveJumpStop(); + + if (result == AIMoveResult.ChangeType) { + SetNavType(Navigation.Ground); + + if (CurWaypointIsGoal()) { + OnNavComplete(); + return AIMoveResult.Ok; + } + else { + AdvancePath(); + return AIMoveResult.ChangeType; + } + } + return AIMoveResult.Ok; + } + else + GetMotor()!.MoveJumpExecute(); + + return AIMoveResult.Ok; + } + + protected virtual void MoveCalcBaseGoal(ref AILocalMoveGoal moveGoal) { + moveGoal.NavType = GetNavType(); + moveGoal.Target = GetPath().CurWaypointPos(); + moveGoal.MaxDist = ComputePathDirection(GetNavType(), GetLocalOrigin(), moveGoal.Target, out moveGoal.Dir); + moveGoal.Facing = moveGoal.Dir; + moveGoal.Speed = GetMotor()!.GetSequenceGroundSpeed(GetMovementSequence()); + moveGoal.CurExpectedDist = moveGoal.Speed * GetMotor()!.GetMoveInterval(); + moveGoal.MoveTarget = GetNavTargetEntity(); + + if (moveGoal.CurExpectedDist > moveGoal.MaxDist) + moveGoal.CurExpectedDist = moveGoal.MaxDist; + + if (GetPath().CurWaypointIsGoal()) + moveGoal.Flags |= AILocalMoveGoalFlags.TargetIsGoal; + else { + AI_Waypoint curWaypoint = GetPath().GetCurWaypoint()!; + if (curWaypoint.GetNext() != null && curWaypoint.GetNext()!.NavType() != curWaypoint.NavType()) + moveGoal.Flags |= AILocalMoveGoalFlags.TargetIsTransition; + } + + Task_t? curTask = GetOuter()!.GetTask(); + if (curTask != null && curTask.Value.Task == TASK_STOP_MOVING) + moveGoal.Flags |= AILocalMoveGoalFlags.NoSteer | AILocalMoveGoalFlags.NoAvoidancePaths; + + moveGoal.Path = GetPath(); + } + + public virtual bool OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if (GetOuter()!.OnCalcBaseMove(ref moveGoal, distClear, ref result)) + return true; + + return false; + } + + public virtual bool OnObstructionPreSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + bool targetIsGoal = (moveGoal.Flags & AILocalMoveGoalFlags.TargetIsGoal) != 0; + bool shouldAttemptHit = false; + bool shouldAdvancePath = false; + float tolerance = 0; + + if (targetIsGoal) { + shouldAttemptHit = true; + tolerance = GetPath().GetGoalTolerance(); + } + else if ((moveGoal.Flags & AILocalMoveGoalFlags.TargetIsTransition) == 0) { + shouldAttemptHit = true; + shouldAdvancePath = true; + tolerance = GetPath().GetWaypointTolerance(); + + if (moveGoal.MaxDist < 4 * 12 && moveGoal.MaxDist - distClear < tolerance) + tolerance = moveGoal.MaxDist + 1; + } + + if (shouldAttemptHit) { + if (distClear > moveGoal.MaxDist) { + result = AIMoveResult.Ok; + return true; + } + + if (moveGoal.MaxDist < tolerance) { + if (!targetIsGoal || + (moveGoal.DirectTrace.Status != AIMoveResult.BlockedNPC) || + (!((AI_BaseNPC)moveGoal.DirectTrace.Obstruction!).IsMoving())) { + moveGoal.MaxDist = distClear; + result = AIMoveResult.Ok; + + if (shouldAdvancePath) + AdvancePath(); + else if (distClear < 0.025) + result = moveGoal.DirectTrace.Status; + return true; + } + } + } + +#if HL2_EPISODIC + if (ai_vehicle_avoidance.GetBool() && moveGoal.DirectTrace.Obstruction != null && moveGoal.DirectTrace.Obstruction.GetServerVehicle() != null) { + AI_Waypoint? obb = GetPathfinder()!.BuildOBBAvoidanceRoute(GetOuter()!.GetAbsOrigin(), + GetGoalPos(), + moveGoal.DirectTrace.Obstruction, + GetNavTargetEntity(), + GetNavType()); + + if (obb != null) { + GetPath().PrependWaypoints(obb); + return true; + } + } +#endif + + if (GetOuter()!.OnObstructionPreSteer(ref moveGoal, distClear, ref result)) + return true; + + if (BigStepGroundEnt.Get() == null && + moveGoal.DirectTrace.Obstruction != null && + distClear < GetHullWidth() && + moveGoal.DirectTrace.Obstruction == GetOuter()!.GetGroundEntity() && + (moveGoal.DirectTrace.Obstruction.IsPlayer() || + moveGoal.DirectTrace.Obstruction is PhysicsProp)) { + BigStepGroundEnt.Set(moveGoal.DirectTrace.Obstruction); + result = AIMoveResult.ChangeType; + return true; + } + + return false; + } + + public virtual bool OnInsufficientStopDist(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if (GetOuter()!.OnInsufficientStopDist(ref moveGoal, distClear, ref result)) + return true; + + if (!IsMovingOutOfWay(moveGoal, distClear)) { + float goalDist = ComputePathDistance(GetNavType(), GetAbsOrigin(), GetPath().ActualGoalPosition()); + + if (goalDist < GetGoalTolerance() + 0.01) { + moveGoal.MaxDist = distClear; + moveGoal.Flags |= AILocalMoveGoalFlags.ConsumeInterval; + OnNavComplete(); + result = AIMoveResult.Ok; + return true; + } + + if (NextSidestepTimer.Expired()) { + NextSidestepTimer.Reset(); + + CalculateDeflection(GetLocalOrigin(), moveGoal.Dir, moveGoal.DirectTrace.HitNormal, out Vector3 deflection); + + for (int i = 1; i > -2; i -= 2) { + Vector3 testLoc = GetLocalOrigin() + (deflection * GetHullWidth() * 2.0f) * i; + GetMoveProbe()!.MoveLimit(GetNavType(), GetLocalOrigin(), testLoc, Mask.NPCSolid, null, out AIMoveTrace moveTrace); + if (moveTrace.Status == AIMoveResult.Ok) { + Vector3 newWaypoint = moveTrace.EndPosition; + GetMoveProbe()!.MoveLimit(GetNavType(), newWaypoint, moveGoal.Target, Mask.NPCSolidBrushOnly, null, out moveTrace); + if (moveTrace.Status == AIMoveResult.Ok) { + PrependWaypoint(newWaypoint, GetNavType(), WaypointFlags.ToDetour); + result = AIMoveResult.ChangeType; + return true; + } + } + } + } + + if (distClear < 1.0) { + result = moveGoal.DirectTrace.Status; + moveGoal.MaxDist = 0; + return true; + } + return false; + } + + result = AIMoveResult.Ok; + moveGoal.MaxDist = distClear; + moveGoal.Flags |= AILocalMoveGoalFlags.ConsumeInterval; + return true; + } + + public virtual bool OnFailedSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if (GetOuter()!.OnFailedSteer(ref moveGoal, distClear, ref result)) + return true; + + if ((moveGoal.Flags & AILocalMoveGoalFlags.TargetIsGoal) != 0) { + if (distClear >= GetPathDistToGoal()) { + result = AIMoveResult.Ok; + return true; + } + + if (distClear > moveGoal.MaxDist - GetPath().GetGoalTolerance()) { + Assert(CurWaypointIsGoal() && MathF.Abs(moveGoal.MaxDist - GetPathDistToCurWaypoint()) < 0.01); + + if (moveGoal.MaxDist > distClear) + moveGoal.MaxDist = distClear; + + if (distClear < 0.125) + OnNavComplete(); + + moveGoal.Flags |= AILocalMoveGoalFlags.ConsumeInterval; + result = AIMoveResult.Ok; + + return true; + } + } + + if ((moveGoal.Flags & AILocalMoveGoalFlags.TargetIsTransition) == 0) { + float distToWaypoint = GetPathDistToCurWaypoint(); + float halfHull = GetHullWidth() * 0.5f; + + if (distToWaypoint < halfHull) { + if (distClear > distToWaypoint + halfHull) { + result = AIMoveResult.Ok; + return true; + } + } + } + + if (moveGoal.DirectTrace.Status == AIMoveResult.BlockedNPC && moveGoal.DirectTrace.HitNormal != vec3_origin) { + CalculateDeflection(GetLocalOrigin(), moveGoal.Dir, moveGoal.DirectTrace.HitNormal, out Vector3 deflection); + + if (moveGoal.Dir.X * deflection.X + moveGoal.Dir.Y * deflection.Y > 0.7) { + Vector3 testLoc = GetLocalOrigin() + (deflection * moveGoal.CurExpectedDist); + GetMoveProbe()!.MoveLimit(GetNavType(), GetLocalOrigin(), testLoc, Mask.NPCSolid, null, out AIMoveTrace moveTrace); + if (moveTrace.Status == AIMoveResult.Ok) { + moveGoal.Dir = deflection; + moveGoal.MaxDist = moveGoal.CurExpectedDist; + result = AIMoveResult.Ok; + return true; + } + } + } + + const float MOVE_TOLERANCE = 12.0f; + const float TIME_TOLERANCE = 1.0f; + + if (PosBeginFailedSteer == vec3_invalid || (PosBeginFailedSteer - GetAbsOrigin()).LengthSquared() > MOVE_TOLERANCE * MOVE_TOLERANCE) { + PosBeginFailedSteer = GetAbsOrigin(); + TimeBeginFailedSteer = gpGlobals.CurTime; + } + else if (GetNavType() == Navigation.Ground && + gpGlobals.CurTime - TimeBeginFailedSteer > TIME_TOLERANCE && + GetOuter()!.GroundSpeed * TIME_TOLERANCE > MOVE_TOLERANCE) { + result = AIMoveResult.Illegal; + return true; + } + + if ((moveGoal.Flags & AILocalMoveGoalFlags.NoAvoidancePaths) == 0 && distClear < moveGoal.MaxDist) { + if (PrependLocalAvoidance(distClear, moveGoal.DirectTrace)) { + result = AIMoveResult.ChangeType; + return true; + } + } + + return false; + } + + public virtual bool OnFailedLocalNavigation(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if (GetOuter()!.OnFailedLocalNavigation(ref moveGoal, distClear, ref result)) + return true; + + if (DelayNavigationFailure(moveGoal.DirectTrace)) { + result = AIMoveResult.Ok; + moveGoal.MaxDist = distClear; + moveGoal.Flags |= AILocalMoveGoalFlags.ConsumeInterval; + return true; + } + + return false; + } + + bool DelayNavigationFailure(in AIMoveTrace trace) { + AI_BaseNPC? blocker = trace.Obstruction?.MyNPCPointer(); + Assert(PeerMoveWait == false || blocker == PeerWaitingOn.Get()); + + if (!PeerMoveWait || blocker != PeerWaitingOn.Get()) { + if (blocker != null) { + if (PeerWaitingOn.Get() != blocker || PeerWaitClearTimer.Expired()) { + PeerMoveWait = true; + PeerWaitingOn.Set(blocker); + PeerWaitMoveTimer.Reset(); + PeerWaitClearTimer.Reset(); + + if (blocker.GetGroundEntity() == GetOuter()) { + blocker.GetMoveProbe()!.TraceHull(blocker.GetAbsOrigin(), + blocker.GetAbsOrigin() + new Vector3(0, 0, 2.0f), + Mask.NPCSolid, + out Trace bumpTrace); + if (bumpTrace.Fraction == 1.0) + Util.SetOrigin(blocker, bumpTrace.EndPos, true); + } + } + else if (PeerWaitingOn.Get() == blocker && !PeerWaitMoveTimer.Expired()) + PeerMoveWait = true; + } + } + + return PeerMoveWait; + } + + protected virtual bool MoveUpdateWaypoint(ref AIMoveResult result) { + AI_Waypoint curWaypoint = GetPath().GetCurWaypoint()!; + float waypointDist = ComputePathDistance(GetNavType(), GetLocalOrigin(), curWaypoint.GetPos()); + bool isGoal = CurWaypointIsGoal(); + float tolerance = Physics.npc_vphysics.GetBool() ? 0.25f : 0.0625f; + + if (waypointDist <= tolerance) { + if (isGoal) { + OnNavComplete(); + result = AIMoveResult.Ok; + } + else { + AdvancePath(); + result = AIMoveResult.ChangeType; + } + return true; + } + + return false; + } + + public virtual bool OnMoveStalled(in AILocalMoveGoal move) { + SetActivity(GetOuter()!.GetStoppedActivity()); + return true; + } + + public virtual bool OnMoveExecuteFailed(in AILocalMoveGoal move, in AIMoveTrace trace, AIMotorMoveResult motorResult, ref AIMoveResult result) { + if (GetOuter()!.OnMoveExecuteFailed(move, trace, motorResult, ref result)) + return true; + + if (BigStepGroundEnt.Get() == null && + trace.Obstruction != null && + trace.TotalDist - trace.DistObstructed < GetHullWidth() && + trace.Obstruction == GetOuter()!.GetGroundEntity() && + (trace.Obstruction.IsPlayer() || + trace.Obstruction is PhysicsProp)) { + BigStepGroundEnt.Set(trace.Obstruction); + result = AIMoveResult.ChangeType; + return true; + } + + if (motorResult == AIMotorMoveResult.PartialHitTarget) { + OnNavComplete(); + result = AIMoveResult.Ok; + } + else if (motorResult == AIMotorMoveResult.PartialHitNPC && DelayNavigationFailure(trace)) + result = AIMoveResult.Ok; + + return true; + } + + public virtual bool OnMoveBlocked(ref AIMoveResult result) { + if (result == AIMoveResult.BlockedNPC && + GetPath().GetCurWaypoint() != null && + (GetPath().GetCurWaypoint()!.Flags() & WaypointFlags.ToDoor) != 0) { + if (GetPath().GetCurWaypoint()!.Data.Get() is BasePropDoor door) { + GetOuter()!.OpenPropDoorBegin(door); + result = AIMoveResult.Ok; + return true; + } + } + + if (GetOuter()!.OnMoveBlocked(ref result)) + return true; + + float waypointDist; + + if (!GetPath().CurWaypointIsGoal() && GetPath().GetCurWaypoint()!.IsReducible()) { + waypointDist = ComputePathDistance(GetNavType(), GetLocalOrigin(), GetCurWaypointPos()); + if (waypointDist < GetHullWidth()) { + AdvancePath(); + result = AIMoveResult.ChangeType; + } + } + + SetActivity(GetOuter()!.GetStoppedActivity()); + + const float EPS = 0.1f; + + waypointDist = ComputePathDistance(GetNavType(), GetLocalOrigin(), GetPath().ActualGoalPosition()); + + if (waypointDist < GetGoalTolerance() + EPS) { + OnNavComplete(); + result = AIMoveResult.Ok; + return true; + } + + return false; + } + + protected virtual AIMoveResult MoveEnact(in AILocalMoveGoal baseMove) { + AIMoveResult result; + AILocalMoveGoal move = baseMove; + + result = GetLocalNavigator()!.MoveCalc(ref move, LastSuccessfulSimplifyTime == gpGlobals.CurTime); + + if (result != AIMoveResult.Ok) + LastBlockingEnt.Set(move.DirectTrace.Obstruction); + else { + LastBlockingEnt.Set(null); + GetMoveProbe()!.ClearBlockingEntity(); + } + + if (result == AIMoveResult.Ok && !NavComplete) { + Assert(GetPath().GetCurWaypoint() != null); + result = GetMotor()!.MoveNormalExecute(move); + } + else if (result != AIMoveResult.ChangeType) + GetMotor()!.MoveStop(); + + if (IsMoveBlocked(result)) + OnMoveBlocked(ref result); + + return result; + } + + protected virtual AIMoveResult MoveNormal() { + if (!PreMove()) + return AIMoveResult.Illegal; + + AIMoveResult result = AIMoveResult.Illegal; + + if (MoveUpdateWaypoint(ref result)) + return result; + + float preMoveSpeed = GetIdealSpeed(); + Activity preMoveActivity = GetActivity(); + int preMoveSequence = GetOuter()!.GetSequence(); + Vector3 start = GetAbsOrigin(); + + SetActivity(GetMovementActivity()); + + if (ValidateActivitySpeed && GetIdealSpeed() <= 0.0f) { + if (GetActivity() == Activity.ACT_TRANSITION) + return AIMoveResult.Ok; + DevMsg($"{GetOuter()!.GetClassname()} moving with speed <= 0 ({GetOuter()!.GetSequenceName(GetOuter()!.GetSequence())})\n"); + } + + AILocalMoveGoal move = default; + + MoveCalcBaseGoal(ref move); + + result = MoveEnact(move); + + if (result == AIMoveResult.Ok && preMoveSpeed < 0.01) { + if ((GetAbsOrigin() - start).Length() < 0.01) { + GetOuter()!.SetSequence(preMoveSequence); + SetActivity(preMoveActivity); + } + } + + return result; + } + + bool PreMove() { + Navigation goalType = GetPath().CurWaypointNavType(); + Navigation curType = GetNavType(); + + PeerMoveWait = false; + + if (goalType == Navigation.Ground && curType != Navigation.Ground) { + DevMsg($"Warning: {GetOuter()!.GetClassname()}({GetOuter()!.GetEntityName()}) appears to have wrong nav type in CAI_Navigator::MoveGround()\n"); + switch (curType) { + case Navigation.Climb: + GetMotor()!.MoveClimbStop(); + break; + + case Navigation.Jump: + GetMotor()!.MoveJumpStop(); + break; + } + + SetNavType(Navigation.Ground); + } + else if (goalType == Navigation.Fly && curType != Navigation.Fly) { + AssertMsg(false, "GetNavType() == NAV_FLY"); + return false; + } + + Assert(GetMotor()!.GetMoveInterval() > 0); + + SimplifyPath(); + + return true; + } + + bool IsMovingOutOfWay(in AILocalMoveGoal moveGoal, float distClear) { + AI_BaseNPC? blocker = moveGoal.DirectTrace.Obstruction?.MyNPCPointer(); + + if (blocker == null) + return false; + + if (blocker.IsMoving()) { + if (distClear > moveGoal.CurExpectedDist * 0.75) + return true; + + ref readonly Vector3 blockerVel = ref blocker.GetMotor()!.GetCurVel(); + Vector2 velBlockerNorm = new(blockerVel.X, blockerVel.Y); + + MathLib.Vector2DNormalize(ref velBlockerNorm); + + float dot = moveGoal.Dir.X * velBlockerNorm.X + moveGoal.Dir.Y * velBlockerNorm.Y; + + if (dot > -0.25) + return true; + } + + return false; + } + + enum AINavResult + { + Ok, + NoGoal, + NoRoute, + Blocked, + Illegal + } + + static readonly AI_TaskFailureCode[] NavResultFailures = [ + AI_TaskFailureCode.NoTaskFailure, + AI_TaskFailureCode.NoRouteGoal, + AI_TaskFailureCode.NoRoute, + AI_TaskFailureCode.NoRouteBlocked, + AI_TaskFailureCode.NoRouteIllegal + ]; + + public virtual bool Move(float interval = 0.1f) { + if (interval > 1.0) + interval = 1.0f; + + if (!GetOuter()!.OverrideMove(interval)) { + bool hasGoal = GetGoalType() != NavGoalType.None; + bool isTurning = HasMemory(AI_MemoryFlags.Turning); + if (hasGoal) { + if (isTurning) { + if (gpGlobals.CurTime - GetPath().GetStartTime() > 5) { + Forget(AI_MemoryFlags.Turning); + isTurning = false; + } + } + + if (ActivityIsLocomotive(PreviousMoveActivity) && !ActivityIsLocomotive(GetMovementActivity())) + SetMovementActivity(GetOuter()!.TranslateActivity(PreviousMoveActivity)); + } + else { + PreviousMoveActivity = Activity.ACT_RESET; + PreviousArrivalActivity = Activity.ACT_RESET; + } + + bool shouldMove = hasGoal && ActivityIsLocomotive(GetMovementActivity()); + if (shouldMove) { + AINavResult result = AINavResult.Ok; + + GetMotor()!.SetMoveInterval(interval); + + if (GetPath().GoalType() == NavGoalType.None) { + DevWarning("Move requested with no route!\n"); + result = AINavResult.NoGoal; + } + else if (GetPath().GetCurWaypoint() == null) { + DevWarning("Move goal with no route!\n"); + GetPath().Clear(); + result = AINavResult.NoRoute; + } + + if (result == AINavResult.Ok) { + if (GetOuter()!.ShouldMoveWait()) { + GetMotor()!.MovePaused(); + return false; + } + + int loopCount = 0; + + bool moved = false; + AIMoveResult moveResult = AIMoveResult.ChangeType; + NavComplete = false; + + while (moveResult >= AIMoveResult.Ok && !NavComplete) { + if (GetMotor()!.GetMoveInterval() <= 0) { + moveResult = AIMoveResult.Ok; + break; + } + + if (!CalledStartMove) { + GetMotor()!.MoveStart(); + CalledStartMove = true; + } + + if (BigStepGroundEnt.Get() != null && BigStepGroundEnt.Get() != GetOuter()!.GetGroundEntity()) + BigStepGroundEnt.Set(null); + + switch (GetPath().CurWaypointNavType()) { + case Navigation.Climb: + moveResult = MoveClimb(); + break; + + case Navigation.Jump: + moveResult = MoveJump(); + break; + + case Navigation.Ground: + case Navigation.Fly: + moveResult = MoveNormal(); + break; + + default: + DevMsg("Bogus route move type!"); + moveResult = AIMoveResult.Illegal; + break; + } + + if (moveResult == AIMoveResult.Ok) + moved = true; + + ++loopCount; + if (loopCount > 16) { + DevMsg($"ERROR: {GetOuter()!.GetDebugName()} navigation not terminating. Possibly bad cyclical solving?\n"); + moveResult = AIMoveResult.Illegal; + + switch (GetPath().CurWaypointNavType()) { + case Navigation.Ground: + case Navigation.Fly: + OnMoveBlocked(ref moveResult); + break; + } + break; + } + } + + if (IsMoveBlocked(moveResult)) { + bool recovered = false; + if (moveResult != AIMoveResult.BlockedNPC || GetNavType() == Navigation.Climb || GetNavType() == Navigation.Jump || GetPath().CurWaypointNavType() == Navigation.Jump) { + if (MarkCurWaypointFailedLink()) { + AI_Waypoint? savedWaypoints = GetPath().GetCurWaypoint(); + if (savedWaypoints != null) { + GetPath().SetWaypoints(null); + if (RefindPathToGoal(false, true)) { + DeleteAll(savedWaypoints); + recovered = true; + } + else + GetPath().SetWaypoints(savedWaypoints); + } + } + } + + if (!recovered) + OnNavFailed((moveResult == AIMoveResult.Illegal) ? AI_TaskFailureCode.NoRouteIllegal : AI_TaskFailureCode.NoRouteBlocked, true); + } + return moved; + } + + OnNavFailed(NavResultFailures[(int)result], false); + } + else { + if (GetNavType() == Navigation.Climb) { + GetMotor()!.MoveClimbStop(); + SetNavType(Navigation.Ground); + } + GetMotor()!.MoveStop(); + AssertMsg(GetOuter()!.TaskIsRunning() || GetOuter()!.TaskIsComplete(), "Schedule stalled!!\n"); + } + return false; + } + + return true; + } + + public float GetIdealSpeed() => GetOuter()!.GetIdealSpeed(); + + public virtual float CalcYawSpeed() { + float npcYaw = GetOuter()!.CalcYawSpeed(); + if (npcYaw >= 0.0f) + return npcYaw; + + float maxYaw = MaxYawSpeed(); + + if (IsGoalSet() && GetIdealSpeed() != 0.0) { + if (GetPath().GetCurWaypoint() == null) + return maxYaw; + + if (GetIdealSpeed() > 0) { + float waypointDist = (GetPath().CurWaypointPos() - GetLocalOrigin()).Length(); + + if (waypointDist < 100) { + float scale = 1 + (0.01f * (100 - waypointDist)); + return maxYaw * scale; + } + } + } + return maxYaw; + } + + public float GetStepDownMultiplier() { + BaseEntity? bigStepGroundEnt = BigStepGroundEnt.Get(); + if (bigStepGroundEnt != null) { + if (!bigStepGroundEnt.IsPlayer()) + return 2.6f; + else + return 10.0f; + } + return 1.0f; + } + + public void SetAllowBigStep(BaseEntity? entToStepOff) { + if (entToStepOff == null || !entToStepOff.IsWorld()) + BigStepGroundEnt.Set(entToStepOff); + } + + public void AdvancePath() { + AI_Waypoint curWaypoint = GetPath().GetCurWaypoint()!; + bool passingPathcorner = (curWaypoint.Flags() & WaypointFlags.ToPathCorner) != 0; + + if (passingPathcorner) { + Assert(curWaypoint.GetNext() == null || (curWaypoint.GetNext()!.Flags() & (WaypointFlags.ToPathCorner | WaypointFlags.ToGoal)) == (WaypointFlags.ToPathCorner | WaypointFlags.ToGoal)); + BaseEntity? entity = curWaypoint.PathCorner.Get(); + if (entity != null) { + Variant_t emptyVariant = default; + entity.AcceptInput("InPass", GetOuter(), entity, emptyVariant, 0); + } + } + + if (GetPath().CurWaypointIsGoal()) + return; + + if ((curWaypoint.Flags() & WaypointFlags.ToDoor) != 0) { + if (curWaypoint.Data.Get() is BasePropDoor door) + GetOuter()!.OpenPropDoorBegin(door); + else + DevMsg($"{GetOuter()!.GetDebugName()} trying to open a door that has been deleted!\n"); + } + + GetPath().Advance(); + + if (passingPathcorner) { + AI_Waypoint? newWaypoint = GetPath().GetCurWaypoint(); + + if (newWaypoint != null) { + Assert((newWaypoint.Flags() & (WaypointFlags.ToPathCorner | WaypointFlags.ToGoal)) == (WaypointFlags.ToPathCorner | WaypointFlags.ToGoal)); + + GetOuter()!.SetGoalEnt(newWaypoint.PathCorner.Get()); + DoFindPathToPathcorner(newWaypoint.PathCorner.Get()); + } + } + } + + bool ShouldAttemptSimplifyTo(in Vector3 pos) { + if (ForcedSimplify) + return true; + + Vector3 vecToPos = pos - GetLocalOrigin(); + vecToPos.Z = 0; + MathLib.VectorNormalize(ref vecToPos); + + Vector3 vecCurrentDirectionOfMovement = GetCurWaypointPos() - GetLocalOrigin(); + vecCurrentDirectionOfMovement.Z = 0; + MathLib.VectorNormalize(ref vecCurrentDirectionOfMovement); + + float dot = vecCurrentDirectionOfMovement.X * vecToPos.X + vecCurrentDirectionOfMovement.Y * vecToPos.Y; + + return ForcedSimplify || dot > MIN_ANGLE_COS_SIMPLIFY; + } + + bool ShouldSimplifyTo(bool passedDetour, in Vector3 pos) { + AI_MoveLimitFlags flags = AI_MoveLimitFlags.QuickReject; + + if (!passedDetour) + flags |= AI_MoveLimitFlags.IgnoreTransients; + + GetMoveProbe()!.MoveLimit(GetNavType(), + GetLocalOrigin(), pos, Mask.NPCSolid, + GetPath().GetTarget(), 100, flags, out AIMoveTrace moveTrace); + + return !IsMoveBlocked(moveTrace); + } + + void SimplifyPathInsertSimplification(AI_Waypoint segmentStart, in Vector3 point) { + if (point != segmentStart.GetPos()) { + AI_Waypoint? nextWaypoint = segmentStart.GetNext(); + Assert(nextWaypoint != null); + Assert(segmentStart.NavType() == nextWaypoint!.NavType()); + + AI_Waypoint newWaypoint = new(point, 0, segmentStart.NavType(), 0, NO_NODE); + + while (GetPath().GetCurWaypoint() != nextWaypoint) { + Assert(GetPath().GetCurWaypoint()!.IsReducible()); + GetPath().Advance(); + } + newWaypoint.SetNext(nextWaypoint); + GetPath().SetWaypoints(newWaypoint); + } + else { + while (GetPath().GetCurWaypoint() != segmentStart) { + Assert(GetPath().GetCurWaypoint()!.IsReducible()); + GetPath().Advance(); + } + } + } + + bool SimplifyPathForwardScan(in SimplifyForwardScanParams parms, AI_Waypoint curWaypoint, in Vector3 curPoint, float distRemaining, bool skipTest, bool passedDetour, ref int testCount) { + AI_Waypoint? nextWaypoint = curWaypoint.GetNext(); + + if (!passedDetour) + passedDetour = (curWaypoint.Flags() & WaypointFlags.ToDetour) != 0; + + if (distRemaining > 0) { + if (curWaypoint.IsReducible()) { + AI_Waypoint recursionWaypoint; + Vector3 nextPoint; + + float distToNext = ComputePathDistance(GetNavType(), curPoint, nextWaypoint!.GetPos()); + if (distToNext < parms.Increment * 1.10) { + nextPoint = nextWaypoint.GetPos(); + distRemaining -= distToNext; + recursionWaypoint = nextWaypoint; + } + else { + Vector3 offset = nextWaypoint.GetPos() - curWaypoint.GetPos(); + MathLib.VectorNormalize(ref offset); + offset *= parms.Increment; + nextPoint = curPoint + offset; + distRemaining -= parms.Increment; + recursionWaypoint = curWaypoint; + } + + bool skipTestNext = ComputePathDistance(GetNavType(), GetLocalOrigin(), nextPoint) > parms.Radius + 0.1; + + if (SimplifyPathForwardScan(parms, recursionWaypoint, nextPoint, distRemaining, skipTestNext, passedDetour, ref testCount)) + return true; + } + } + + if (!skipTest && testCount < parms.MaxSamples && ShouldAttemptSimplifyTo(curPoint)) { + testCount++; + + if (ShouldSimplifyTo(passedDetour, curPoint)) { + SimplifyPathInsertSimplification(curWaypoint, curPoint); + return true; + } + } + + return false; + } + + bool SimplifyPathForwardScan(in SimplifyForwardScanParams parms) { + AI_Waypoint curWaypoint = GetPath().GetCurWaypoint()!; + float distRemaining = parms.ScanDist - GetPathDistToCurWaypoint(); + int testCount = 0; + + if (distRemaining < 0.1) + return false; + + if (SimplifyPathForwardScan(parms, curWaypoint, curWaypoint.GetPos(), distRemaining, true, false, ref testCount)) + return true; + + return false; + } + + bool SimplifyPathForward(float maxDist = -1) { + AI_Waypoint curWaypoint = GetPath().GetCurWaypoint()!; + AI_Waypoint? nextWaypoint = curWaypoint.GetNext(); + + if (nextWaypoint == null) + return false; + + SimplifyForwardScanParams scanParams = fullScanParams; + if (maxDist > fullScanParams.Radius) { + float ratio = maxDist / fullScanParams.Radius; + + fullScanParams.Radius = maxDist; + fullScanParams.ScanDist *= ratio; + fullScanParams.Increment *= ratio; + } + + if (SimplifyPathForwardScan(scanParams)) + return true; + + if (ShouldAttemptSimplifyTo(nextWaypoint.GetPos()) && + ComputePathDistance(GetNavType(), GetLocalOrigin(), nextWaypoint.GetPos()) < scanParams.ScanDist && + ShouldSimplifyTo((curWaypoint.Flags() & WaypointFlags.ToDetour) != 0, nextWaypoint.GetPos())) { + curWaypoint.Delete(); + GetPath().SetWaypoints(nextWaypoint); + return true; + } + + return false; + } + + bool SimplifyPathBacktrack() { + AI_Waypoint curWaypoint = GetPath().GetCurWaypoint()!; + AI_Waypoint? nextWaypoint = curWaypoint.GetNext(); + + if (curWaypoint.GetNext() != null && + (nextWaypoint!.Flags() & WaypointFlags.ToNode) != 0 && + (nextWaypoint.NavType() == Navigation.Ground) && + (curWaypoint.NavType() == Navigation.Ground) && + (curWaypoint.Flags() & WaypointFlags.ToNode) != 0) { + + Vector3 firstToMe = GetLocalOrigin() - curWaypoint.GetPos(); + Vector3 firstToNext = nextWaypoint.GetPos() - curWaypoint.GetPos(); + MathLib.VectorNormalize(ref firstToNext); + firstToMe.Z = 0; + firstToNext.Z = 0; + float firstDist = firstToMe.Length(); + float firstProj = Vector3.Dot(firstToMe, firstToNext); + float goalTolerance = GetPath().GetGoalTolerance(); + if (firstProj > 0.5 * firstDist) { + Vector3 targetPos = curWaypoint.GetPos() + (firstProj * firstToNext); + + RouteBuildFlags buildFlags = 0; + if ((CapabilitiesGet() & Capability.MoveGround) != 0) + buildFlags |= RouteBuildFlags.Ground; + if ((CapabilitiesGet() & Capability.MoveJump) != 0) + buildFlags |= RouteBuildFlags.Jump; + + AI_Waypoint? route1 = GetPathfinder()!.BuildLocalRoute(GetLocalOrigin(), targetPos, GetPath().GetTarget(), WaypointFlags.ToDetour, NO_NODE, buildFlags, goalTolerance); + if (route1 == null) + return false; + + AI_Waypoint? route2 = GetPathfinder()!.BuildLocalRoute(targetPos, nextWaypoint.GetPos(), GetPath().GetTarget(), WaypointFlags.ToDetour, NO_NODE, buildFlags, goalTolerance); + if (route2 == null) { + DeleteAll(route1); + return false; + } + + AddWaypointLists(route1, route2); + + AddWaypointLists(route1, nextWaypoint.GetNext()); - LastSuccessfulSimplifyTime = -1; + AI_Waypoint freeMe = curWaypoint.GetNext()!; + curWaypoint.Delete(); + freeMe.Delete(); - ClippedWaypoints = new AI_WaypointList(); - TimeClipped = -1; + GetPath().SetWaypoints(route1); + return true; + } + } + return false; + } - ValidateActivitySpeed = true; - CalledStartMove = false; + bool SimplifyPathQuick() { + if (SimplifyPathForwardScan(quickScanParams[AIStrongOpt() ? 1 : 0])) + return true; - NavType = Navigation.Ground; - NavComplete = false; - LastNavFailed = false; + return false; + } - PeerWaitMoveTimer.Set(0.25f); - PeerWaitClearTimer.Set(3.0f); - NextSidestepTimer.Set(5.0f); + public virtual bool SimplifyPath(bool firstForPath = false, float scanDist = -1) { + bool inPVS = GetOuter()!.HasCondition((int)SCOND_t.COND_IN_PVS); + bool retVal = false; - PosBeginFailedSteer = vec3_invalid; - TimeBeginFailedSteer = float.MaxValue; + Navigation navType = GetOuter()!.GetNavType(); + if (navType == Navigation.Ground || navType == Navigation.Fly) { + AI_Waypoint? curWaypoint = GetPath().GetCurWaypoint(); + if (curWaypoint == null || !curWaypoint.IsReducible()) + return false; - TimeLastAvoidanceTriangulate = -1; + bool fullSimplify; - NoPathcornerPathfinds = false; - LocalSucceedOnWithinTolerance = false; + fullSimplify = NextSimplifyTime <= gpGlobals.CurTime; - RememberStaleNodes = true; + if (firstForPath && !fullSimplify) + fullSimplify = inPVS; - Motor = null; - MoveProbe = null; - LocalNavigator = null; + if (AIStrongOpt() && fullSimplify) { + if (g_iFrameLastSimplified != gpGlobals.FrameCount) + g_iFrameLastSimplified = gpGlobals.FrameCount; + else + fullSimplify = false; + } - NavFailCounter = 0; - LastNavFailTime = -1; + ForcedSimplify = firstForPath; + + if (fullSimplify) { + float simplifyDelay = inPVS ? ROUTE_SIMPLIFY_TIME_DELAY[AIStrongOpt() ? 1 : 0] : NO_PVS_ROUTE_SIMPLIFY_TIME_DELAY[AIStrongOpt() ? 1 : 0]; + + if (GetOuter()!.GetMoveEfficiency() > AI_MoveEfficiency.Normal) + simplifyDelay *= 2; + + NextSimplifyTime = gpGlobals.CurTime + simplifyDelay; + + if (SimplifyPathForward(scanDist)) + retVal = true; + else if (SimplifyPathBacktrack()) + retVal = true; + else if (SimplifyPathQuick()) + retVal = true; + } + else if (firstForPath || (inPVS && GetOuter()!.GetMoveEfficiency() == AI_MoveEfficiency.Normal)) { + if (!AIStrongOpt() || gpGlobals.CurTime - LastSuccessfulSimplifyTime > QUICK_SIMPLIFY_TIME_DELAY[AIStrongOpt() ? 1 : 0]) { + if (SimplifyPathQuick()) + retVal = true; + } + } + } + + if (retVal) + LastSuccessfulSimplifyTime = gpGlobals.CurTime; + + return retVal; } - public void SetValidateActivitySpeed(bool validateActivitySpeed) => ValidateActivitySpeed = validateActivitySpeed; + public AI_NavPathProgress ProgressFlyPath(in AI_ProgressFlyPathParams parms) { + if (IsGoalActive()) { + float waypointDist = (GetCurWaypointPos() - GetLocalOrigin()).Length(); - public virtual void Init(AI_Network? network) { - Motor = GetOuter()!.GetMotor(); - MoveProbe = GetOuter()!.GetMoveProbe(); - LocalNavigator = GetOuter()!.GetLocalNavigator(); - AINetwork = network; + if (CurWaypointIsGoal()) { + float tolerance = Math.Max(parms.GoalTolerance, GetPath().GetGoalTolerance()); + if (waypointDist <= tolerance) + return AI_NavPathProgress.Complete; + } + else { + bool isStrictWaypoint = (GetPath().CurWaypointFlags() & (WaypointFlags.ToPathCorner | WaypointFlags.DontSimplify)) != 0; + float tolerance = isStrictWaypoint ? parms.StrictPointTolerance : parms.WaypointTolerance; + if (waypointDist <= tolerance) { + Util.TraceLine(GetAbsOrigin(), GetPath().GetCurWaypoint()!.GetNext()!.GetPos(), Mask.NPCSolid, GetOuter(), CollisionGroup.None, out Trace tr); + if (tr.Fraction == 1.0f) { + AdvancePath(); + return AI_NavPathProgress.Advanced; + } + } + + if (SimplifyFlyPath(parms)) + return AI_NavPathProgress.Advanced; + } + } + + return AI_NavPathProgress.NoChange; } - public bool ClearGoal() { - ClearPath(); - OnNewGoal(); - return true; + public void SimplifyFlyPath(Mask collisionMask, BaseEntity? target, float strictPointTolerance = 32.0f, float blockTolerance = 0.0f, AI_NpcBlockHandling blockHandling = AI_NpcBlockHandling.Block) { + AI_ProgressFlyPathParams parms = new(collisionMask, strictPointTolerance, blockTolerance, 0, 0, blockHandling); + parms.SetCurrent(target); + SimplifyFlyPath(parms); } - public Activity GetMovementActivity() => GetPath().GetMovementActivity(); + public bool SimplifyFlyPath(in AI_ProgressFlyPathParams parms) { + if (GetPath().GetCurWaypoint() == null) + return false; - public Activity GetArrivalActivity() => GetPath().GetArrivalActivity(); + if (NextSimplifyTime > gpGlobals.CurTime) + return false; - public bool IsGoalSet() => GetPath().GoalType() != NavGoalType.None; + NextSimplifyTime = gpGlobals.CurTime + FLY_ROUTE_SIMPLIFY_TIME_DELAY; - public bool IsGoalActive() => GetPath() != null && !GetPath().IsEmpty(); + if (parms.TrySimplify && SimplifyPathForward(FLY_ROUTE_SIMPLIFY_LOOK_DIST)) + return true; - public BaseEntity? GetGoalTarget() => GetPath().GetTarget(); + bool isStrictWaypoint = !parms.TrySimplify || (GetPath().CurWaypointFlags() & (WaypointFlags.ToPathCorner | WaypointFlags.DontSimplify)) != 0; + + Vector3 dir = GetCurWaypointPos() - GetLocalOrigin(); + float length = MathLib.VectorNormalize(ref dir); + + if (!isStrictWaypoint || length < parms.StrictPointTolerance) { + if (GetPath().CurWaypointIsGoal()) + return false; + + GetMoveProbe()!.MoveLimit(Navigation.Fly, GetLocalOrigin(), GetPath().NextWaypointPos(), + parms.CollisionMask, parms.Target, out AIMoveTrace moveTrace); + + if (moveTrace.DistObstructed - parms.BlockTolerance < 0.01 || + ((parms.BlockHandling == AI_NpcBlockHandling.Ignore) && (moveTrace.Status == AIMoveResult.BlockedNPC))) { + AdvancePath(); + return true; + } + else if (moveTrace.Obstruction != null && parms.BlockHandling == AI_NpcBlockHandling.Avoid) + PrependLocalAvoidance(parms.BlockTolerance - moveTrace.DistObstructed, moveTrace); + } + + return false; + } + + public float MovementCost(Capability moveType, in Vector3 start, in Vector3 end) { + float cost = (start - end).Length(); + + if (moveType == Capability.MoveJump || moveType == Capability.MoveClimb) + cost *= 2.0f; + + GetOuter()!.MovementCost(moveType, start, end, ref cost); + + return cost; + } public bool CanFitAtNode(int nodeNum, Mask collisionMask = Mask.NPCSolidBrushOnly) { if (GetNetwork() == null) { @@ -123,71 +2100,376 @@ public bool CanFitAtPosition(in Vector3 startPos, Mask collisionMask, bool ignor return true; } - public float GetStepDownMultiplier() { - BaseEntity? bigStepGroundEnt = BigStepGroundEnt.Get(); - if (bigStepGroundEnt != null) { - if (!bigStepGroundEnt.IsPlayer()) - return 2.6f; + public bool IsOnNetwork() => !NotOnNetwork; + + public void SetMaxRouteRebuildTime(float time) => TimePathRebuildMax = time; + + public float GetPathDistToCurWaypoint() { + return GetPath().GetCurWaypoint() != null ? + ComputePathDistance(GetNavType(), GetLocalOrigin(), GetPath().CurWaypointPos()) : + 0; + } + + public float BuildAndGetPathDistToGoal() { + if (GetPath() == null) + return -1; + + GetPath().GetPathLength(); + + if (GetPath().GetCurWaypoint() != null && (GetPath().GetCurWaypoint()!.PathDistGoal >= 0)) + return GetPathDistToGoal(); + + return -1; + } + + public float GetPathDistToGoal() { + return GetPath().GetCurWaypoint() != null ? + (GetPathDistToCurWaypoint() + GetPath().GetCurWaypoint()!.PathDistGoal) : + 0; + } + + bool FindPath(bool signalTaskStatus = true, bool dontIgnoreBadLinks = false) { + if (ai_navigator_generate_spikes.GetBool()) { + uint largeCount = (uint)(int.MaxValue >> ai_navigator_generate_spikes_strength.GetInt()); + while (largeCount-- != 0) { } + } + + bool retrying = HasMemory(AI_MemoryFlags.PathFailed) && TimePathRebuildMax != 0; + if (retrying) { + if (TimePathRebuildFail < gpGlobals.CurTime) { + if (signalTaskStatus) + OnNavFailed(AI_TaskFailureCode.NoRoute); + else + OnNavFailed(); + return false; + } + else if (TimePathRebuildNext > gpGlobals.CurTime) + return false; + } + + bool findResult = DoFindPath(); + + if (!dontIgnoreBadLinks && !findResult && GetOuter()!.IsNavigationUrgent()) { + GetPathfinder()!.SetIgnoreBadLinks(); + findResult = DoFindPath(); + } + + if (findResult) { + Forget(AI_MemoryFlags.PathFailed); + + if (signalTaskStatus) + TaskComplete(); + return true; + } + + if (TimePathRebuildMax == 0) { + if (signalTaskStatus) + OnNavFailed(AI_TaskFailureCode.NoRoute); else - return 10.0f; + OnNavFailed(); + return false; + } + else { + if (!retrying) { + Remember(AI_MemoryFlags.PathFailed); + TimePathRebuildFail = gpGlobals.CurTime + TimePathRebuildMax; + } + TimePathRebuildNext = gpGlobals.CurTime + TimePathRebuildDelay; + return false; } - return 1.0f; } - public float GetIdealSpeed() => throw new NotImplementedException(); + bool MarkCurWaypointFailedLink() { + if (!RememberStaleNodes) + return false; - public virtual float CalcYawSpeed() { - float npcYaw = GetOuter()!.CalcYawSpeed(); - if (npcYaw >= 0.0f) - return npcYaw; + if (GetPath() == null || GetPath().GetCurWaypoint() == null) + return false; - float maxYaw = GetOuter()!.MaxYawSpeed(); + bool didMark = false; + + int startID = GetPath().GetLastNodeReached(); + int endID = GetPath().GetCurWaypoint()!.NodeID; + + if (endID != NO_NODE) { + bool blockAll = false; + + BaseEntity? lastBlockingEnt = LastBlockingEnt.Get(); + IPhysicsObject? blockingPhysObj = lastBlockingEnt?.VPhysicsGetObject(); + if (lastBlockingEnt != null && + !lastBlockingEnt.IsPlayer() && !lastBlockingEnt.IsNPC() && + lastBlockingEnt.GetMoveType() == Source.MoveType.VPhysics && + blockingPhysObj != null && + (!blockingPhysObj.IsMoveable() || + blockingPhysObj.GetMass() > 200)) { + CollisionProperty collisionProp = lastBlockingEnt.CollisionProp(); + bool foundLarge = false; + bool foundSmall = false; + Vector3 vecSize = collisionProp.OBBMaxs() - collisionProp.OBBMins(); + for (int i = 0; i < 3; i++) { + if (vecSize[i] > 40) + foundLarge = true; + + if (vecSize[i] < 30) { + foundSmall = true; + break; + } + } - if (IsGoalSet() && GetIdealSpeed() != 0.0) { - if (GetPath().GetCurWaypoint() == null) - return maxYaw; + if (foundLarge && !foundSmall) { + Vector3 startPos = GetNetwork()!.GetNode(endID)!.GetPosition(GetHullType()); + Vector3 endPos = startPos; + endPos.Z += 0.01f; - if (GetIdealSpeed() > 0) { - float waypointDist = (GetPath().CurWaypointPos() - GetOuter()!.GetLocalOrigin()).Length(); + Util.TraceModel(startPos, endPos, GetOuter()!.GetHullMins(), GetOuter()!.GetHullMaxs(), lastBlockingEnt, CollisionGroup.None, out Trace tr); - if (waypointDist < 100) { - float scale = 1 + (0.01f * (100 - waypointDist)); - return maxYaw * scale; + if (tr.StartSolid) + blockAll = true; + } + } + + if (blockAll) { + AI_Node destNode = GetNetwork()!.GetNode(endID)!; + for (int i = 0; i < destNode.NumLinks(); i++) { + ref AI_Link link = ref destNode.GetLinkByIndex(i); + link.LinkInfo |= LinkInfo.StaleSuggested; + link.TimeStaleExpires = gpGlobals.CurTime + 4.0; + didMark = true; + } + } + else if (startID != NO_NODE) { + AI_Node node = GetNetwork()!.GetNode(startID)!; + ref AI_Link link = ref node.GetLink(endID); + if (!System.Runtime.CompilerServices.Unsafe.IsNullRef(ref link)) { + link.LinkInfo |= LinkInfo.StaleSuggested; + link.TimeStaleExpires = gpGlobals.CurTime + 4.0; + didMark = true; } } } - return maxYaw; + + return didMark; } - public virtual void OnClearPath() { } + protected virtual bool DoFindPathToPos() { + AI_Path path = GetPath(); + AI_Pathfinder pathfinder = GetPathfinder()!; + Vector3 actualGoalPos = path.ActualGoalPosition(); + BaseEntity? target = path.GetTarget(); + float tolerance = path.GetGoalTolerance(); + Vector3 origin; + + if (gpGlobals.CurTime - TimeClipped > 0.11 || LastNavFailed) + ClippedWaypoints.RemoveAll(); + + if (ClippedWaypoints.IsEmpty()) + origin = GetLocalOrigin(); + else { + AI_Waypoint lastClipped = ClippedWaypoints.GetLast()!; + origin = lastClipped.GetPos(); + } - public virtual void OnNewGoal() { - ResetCalculations(); - NavComplete = true; + LastNavFailed = false; + + path.ClearWaypoints(); + + AI_Waypoint? firstWaypoint = pathfinder.BuildRoute(origin, actualGoalPos, target, tolerance, GetNavType(), LocalSucceedOnWithinTolerance); + + if (firstWaypoint == null) + return false; + + path.SetWaypoints(firstWaypoint); + + if (!ClippedWaypoints.IsEmpty()) { + AI_Waypoint firstClipped = ClippedWaypoints.GetFirst()!; + ClippedWaypoints.Set(null); + firstClipped.ModifyFlags(WaypointFlags.DontSimplify, true); + path.PrependWaypoints(firstClipped); + firstWaypoint = firstClipped; + } + + if (firstWaypoint.IsReducible() && firstWaypoint.GetNext() != null && firstWaypoint.GetNext()!.NavType() == GetNavType() && + ShouldOptimizeInitialPathSegment(firstWaypoint)) { + const float EPS = 0.1f; + MathLib.CalcClosestPointOnLineSegment(origin, + firstWaypoint.GetPos(), firstWaypoint.GetNext()!.GetPos(), + out Vector3 closest, out _); + if ((firstWaypoint.GetPos() - closest).Length() > EPS && + (origin - closest).Length() < GetHullWidth() * 0.5) + path.Advance(); + } + + return true; } - public void ResetCalculations() { - PeerWaitingOn.Set(null); - PeerWaitMoveTimer.Force(); - PeerWaitClearTimer.Force(); + protected virtual bool ShouldOptimizeInitialPathSegment(AI_Waypoint waypoint) => true; - BigStepGroundEnt.Set(null); + public BaseEntity? GetNextPathcorner(BaseEntity? pathCorner) { + BaseEntity? nextPathCorner = null; - NextSidestepTimer.Force(); + Assert(pathCorner != null); + if (pathCorner != null) { + nextPathCorner = pathCorner.GetNextTarget(); - CalledStartMove = false; + if (nextPathCorner == null && pathCorner is AI_Hint hint) { + int targetNode = hint.GetTargetNode(); + if (targetNode != NO_NODE) { + AI_Node testNode = GetNetwork()!.GetNode(targetNode)!; + nextPathCorner = testNode.GetHint(); + } + } + } - PosBeginFailedSteer = vec3_invalid; - TimeBeginFailedSteer = float.MaxValue; + return nextPathCorner; + } - LastSuccessfulSimplifyTime = -1; + bool DoFindPathToPathcorner(BaseEntity? pathCorner) { + bool returnCode = false; + Assert(GetPath().GoalType() == NavGoalType.PathCorner); + + if (pathCorner != null) { + if ((GetGoalFlags() & AI_NavGoalFlags.NoPathcornerPathfinding) != 0 || NoPathcornerPathfinds) { + if (pathCorner.Speed != 0) + SetSpeed(pathCorner.Speed); + + GetPath().ClearWaypoints(); + + AI_Waypoint route = new(pathCorner.GetLocalOrigin(), 0, GetNavType(), WaypointFlags.ToPathCorner, NO_NODE); + route.PathCorner.Set(pathCorner); + AI_Waypoint last = route; + pathCorner = GetNextPathcorner(pathCorner); + if (pathCorner != null) { + last = new AI_Waypoint(pathCorner.GetLocalOrigin(), 0, GetNavType(), WaypointFlags.ToPathCorner, NO_NODE); + last.PathCorner.Set(pathCorner); + route.SetNext(last); + } + last.ModifyFlags(WaypointFlags.ToGoal, true); + GetPath().SetWaypoints(route, true); + returnCode = true; + } + else { + Vector3 initPos = pathCorner.GetLocalOrigin(); - GetLocalNavigator()!.ResetMoveCalculations(); - GetMotor()!.ResetMoveCalculations(); - GetMoveProbe()!.ClearBlockingEntity(); + GetOuter()!.TranslateNavGoal(pathCorner, ref initPos); - NavFailCounter = 0; - LastNavFailTime = -1; + GetPath().ResetGoalPosition(initPos); + + float tolerance = GetPath().GetGoalTolerance(); + float outerTolerance = GetOuter()!.GetDefaultNavGoalTolerance(); + if (outerTolerance > tolerance) { + GetPath().SetGoalTolerance(outerTolerance); + tolerance = outerTolerance; + } + + if (returnCode = DoFindPathToPos()) { + if (pathCorner.Speed != 0) + SetSpeed(pathCorner.Speed); + + AI_Waypoint lastWaypoint = GetPath().GetGoalWaypoint()!; + Assert(lastWaypoint != null); + + lastWaypoint.ModifyFlags(WaypointFlags.ToPathCorner, true); + lastWaypoint.PathCorner.Set(pathCorner); + + pathCorner = GetNextPathcorner(pathCorner); + if (pathCorner != null) { + lastWaypoint.ModifyFlags(WaypointFlags.ToGoal, false); + AI_Waypoint curWaypoint = new(pathCorner.GetLocalOrigin(), 0, GetNavType(), WaypointFlags.ToPathCorner | WaypointFlags.ToGoal, NO_NODE); + Vector3 waypointPos = curWaypoint.GetPos(); + GetOuter()!.TranslateNavGoal(pathCorner, ref waypointPos); + curWaypoint.SetPos(waypointPos); + GetPath().SetGoalTolerance(tolerance); + curWaypoint.PathCorner.Set(pathCorner); + lastWaypoint.SetNext(curWaypoint); + GetPath().ResetGoalPosition(curWaypoint.GetPos()); + } + } + } + } + return returnCode; + } + + bool DoFindPath() { + GetPath().ClearWaypoints(); + + bool returnCode; + + returnCode = false; + + switch (GetPath().GoalType()) { + case NavGoalType.PathCorner: + returnCode = DoFindPathToPathcorner(GetOuter()!.GetGoalEnt()); + break; + + case NavGoalType.Enemy: { + BaseEntity? enemy = GetPath().GetTarget(); + if (enemy != null) { + Assert(enemy == GetOuter()!.GetEnemy()); + + Vector3 newPos = GetOuter()!.GetEnemyLKP(); + + float tolerance = GetPath().GetGoalTolerance(); + float outerTolerance = GetOuter()!.GetDefaultNavGoalTolerance(); + if (outerTolerance > tolerance) { + GetPath().SetGoalTolerance(outerTolerance); + tolerance = outerTolerance; + } + + GetOuter()!.TranslateNavGoal(enemy, ref newPos); + + GetPath().ResetGoalPosition(newPos); + GetPath().SetGoalTolerance(tolerance); + + returnCode = DoFindPathToPos(); + } + } + break; + + case NavGoalType.Location: + case NavGoalType.Flank: + case NavGoalType.Cover: + returnCode = DoFindPathToPos(); + break; + + case NavGoalType.LocationNearestNode: { + int myNodeID; + int destNodeID; + + returnCode = false; + + myNodeID = GetPathfinder()!.NearestNodeToNPC(); + if (myNodeID != NO_NODE) { + destNodeID = GetPathfinder()!.NearestNodeToPoint(GetPath().ActualGoalPosition()); + if (destNodeID != NO_NODE) { + AI_Waypoint? route = GetPathfinder()!.FindBestPath(myNodeID, destNodeID); + + if (route != null) { + GetPath().SetWaypoints(route); + GetPath().SetLastNodeAsGoal(true); + returnCode = true; + } + } + } + } + break; + + case NavGoalType.TargetEnt: { + BaseEntity? target = GetPath().GetTarget(); + + if (target != null) { + Assert(target == GetOuter()!.GetTarget()); + + Vector3 initPos = target.GetAbsOrigin(); + GetOuter()!.TranslateNavGoal(target, ref initPos); + + GetPath().ResetGoalPosition(initPos); + returnCode = DoFindPathToPos(); + } + } + break; + } + + return returnCode; } public void ClearPath() { @@ -198,7 +2480,7 @@ public void ClearPath() { TimePathRebuildNext = 0; TimePathRebuildDelay = 0; - GetOuter()!.Forget(AI_MemoryFlags.PathFailed); + Forget(AI_MemoryFlags.PathFailed); AI_Waypoint? waypoint = GetPath().GetCurWaypoint(); @@ -226,11 +2508,163 @@ public void ClearPath() { GetPath().Clear(); } - public void SaveStoppingPath() => throw new NotImplementedException(); + protected virtual bool GetStoppingPath(AI_WaypointList clippedWaypoints) { + clippedWaypoints.RemoveAll(); + + AI_Waypoint? curWaypoint = GetPath().GetCurWaypoint(); + if (curWaypoint != null) { + bool mustCompleteCurrent = curWaypoint.NavType() == Navigation.Climb || curWaypoint.NavType() == Navigation.Jump; + float distRemaining = GetMotor()!.MinStoppingDist(0); + + if (mustCompleteCurrent) { + float distToCurrent = ComputePathDistance(curWaypoint.NavType(), GetLocalOrigin(), curWaypoint.GetPos()); + if (curWaypoint.NavType() == Navigation.Climb) { + if (curWaypoint.GetNext() != null && curWaypoint.GetNext()!.NavType() == Navigation.Climb) + distToCurrent += ComputePathDistance(Navigation.Climb, curWaypoint.GetPos(), curWaypoint.GetNext()!.GetPos()); + distToCurrent += GetHullWidth() * 2.0f; + } + + if (distToCurrent > distRemaining) + distRemaining = distToCurrent; + } + + if (mustCompleteCurrent || distRemaining > 0.1) { + Vector3 posPrev = GetLocalOrigin(); + AI_Waypoint? nextPoint = curWaypoint; + AI_Waypoint? savedWaypoints = null; + AI_Waypoint? lastSavedWaypoint = null; + AI_Waypoint newWaypoint; + + while (distRemaining > 0.01 && nextPoint != null) { + if ((nextPoint.NavType() == Navigation.Climb || nextPoint.NavType() == Navigation.Jump) && + !mustCompleteCurrent) + break; + + if (nextPoint.NavType() != Navigation.Climb || nextPoint.GetNext() == null || nextPoint.GetNext()!.NavType() != Navigation.Climb) + mustCompleteCurrent = false; + + float distToNext = ComputePathDistance(nextPoint.NavType(), posPrev, nextPoint.GetPos()); + + if (distToNext <= distRemaining + 0.01) { + newWaypoint = new AI_Waypoint(nextPoint.GetPos(), nextPoint.Yaw, nextPoint.NavType(), nextPoint.Flags(), nextPoint.NodeID); + newWaypoint.PathCorner = nextPoint.PathCorner; + newWaypoint.Data = nextPoint.Data; + + if ((newWaypoint.Flags() & WaypointFlags.ToPathCorner) != 0) { + newWaypoint.ModifyFlags(WaypointFlags.ToPathCorner, false); + newWaypoint.PathCorner.Set(null); + } + + newWaypoint.ModifyFlags(WaypointFlags.ToGoal | WaypointFlags.ToNode, false); + newWaypoint.NodeID = NO_NODE; + + if (lastSavedWaypoint != null) + lastSavedWaypoint.SetNext(newWaypoint); + else + savedWaypoints = newWaypoint; + lastSavedWaypoint = newWaypoint; + + posPrev = nextPoint.GetPos(); + + nextPoint = nextPoint.GetNext(); + distRemaining -= distToNext; + } + else { + Assert(!(nextPoint.NavType() == Navigation.Climb || nextPoint.NavType() == Navigation.Jump)); + Vector3 remainder = nextPoint.GetPos() - posPrev; + MathLib.VectorNormalize(ref remainder); + float yaw = Util.VecToYaw(remainder); + remainder *= distRemaining; + remainder += posPrev; + + if (GetMoveProbe()!.MoveLimit(nextPoint.NavType(), posPrev, remainder, Mask.NPCSolid, null, 100, AI_MoveLimitFlags.Default | AI_MoveLimitFlags.TwoD, out AIMoveTrace trace)) { + newWaypoint = new AI_Waypoint(trace.EndPosition, yaw, nextPoint.NavType(), WaypointFlags.ToGoal, 0); + + if (lastSavedWaypoint != null) + lastSavedWaypoint.SetNext(newWaypoint); + else + savedWaypoints = newWaypoint; + } + + distRemaining = 0; + } + } + + if (savedWaypoints != null) { + clippedWaypoints.Set(savedWaypoints); + return true; + } + } + } + return false; + } + + public void IgnoreStoppingPath() { + if (ClippedWaypoints != null && ClippedWaypoints.GetFirst() != null) { + AI_Waypoint waypoint = ClippedWaypoints.GetFirst()!; + + if (waypoint.NavType() != Navigation.Jump && waypoint.NavType() != Navigation.Climb) + ClippedWaypoints.RemoveAll(); + } + } + + void SaveStoppingPath() { + TimeClipped = -1; + + ClippedWaypoints.RemoveAll(); + AI_Waypoint? curWaypoint = GetPath().GetCurWaypoint(); + if (curWaypoint != null) { + if ((curWaypoint.NavType() == Navigation.Climb || curWaypoint.NavType() == Navigation.Jump) || ai_use_clipped_paths.GetBool()) { + if (GetStoppingPath(ClippedWaypoints)) + TimeClipped = gpGlobals.CurTime; + } + } + } + + public bool SetGoalFromStoppingPath() { + if (ClippedWaypoints != null && ClippedWaypoints.IsEmpty()) + SaveStoppingPath(); + if (ClippedWaypoints != null && !ClippedWaypoints.IsEmpty()) { + if (PreviousMoveActivity <= Activity.ACT_RESET && GetMovementActivity() <= Activity.ACT_RESET) { + ClippedWaypoints.RemoveAll(); + DevWarning(2, $"{GetOuter()!.GetDebugName()} has a stopping path and no valid. Movement activity: {GetMovementActivity()} (prev {PreviousMoveActivity})\n"); + return false; + } + + if (ClippedWaypoints.GetFirst()!.NavType() == Navigation.Climb || ClippedWaypoints.GetFirst()!.NavType() == Navigation.Jump) { + Task_t? curTask = GetOuter()!.GetTask(); + if (curTask != null && curTask.Value.Task == TASK_STOP_MOVING) { + ClippedWaypoints.RemoveAll(); + return false; + } + } + + if (!GetPath().IsEmpty()) + GetPath().ClearWaypoints(); + GetPath().SetWaypoints(ClippedWaypoints.GetFirst(), true); + ClippedWaypoints.Set(null); + GetPath().SetGoalType(NavGoalType.None); + GetPath().SetGoalType(NavGoalType.Location); + GetPath().SetGoalTolerance(NAV_STOP_MOVING_TOLERANCE); + Assert(GetPath().GetCurWaypoint() != null); + + Assert(PreviousMoveActivity != Activity.ACT_INVALID); + + if (PreviousMoveActivity != Activity.ACT_RESET) + GetPath().SetMovementActivity(PreviousMoveActivity); + if (PreviousArrivalActivity != Activity.ACT_RESET) + GetPath().SetArrivalActivity(PreviousArrivalActivity); + return true; + } + return false; + } + + public BaseEntity? GetBlockingEntity() => LastBlockingEnt.Get(); public AI_Path GetPath() => Path; public AI_Network? GetNetwork() => AINetwork; + public void SetNetwork(AI_Network? network) => AINetwork = network; public AI_Motor? GetMotor() => Motor; public AI_MoveProbe? GetMoveProbe() => MoveProbe; @@ -251,25 +2685,29 @@ public void ClearPath() { readonly AI_Path Path; readonly AI_WaypointList ClippedWaypoints; - float TimeClipped; + TimeUnit_t TimeClipped; Activity PreviousMoveActivity; Activity PreviousArrivalActivity; bool CalledStartMove; bool NotOnNetwork; - float NextSimplifyTime; - float LastSuccessfulSimplifyTime; + TimeUnit_t NextSimplifyTime; + bool ForcedSimplify; + TimeUnit_t LastSuccessfulSimplifyTime; + + TimeUnit_t TimeLastAvoidanceTriangulate; float TimePathRebuildMax; float TimePathRebuildDelay; - float TimePathRebuildFail; - float TimePathRebuildNext; + TimeUnit_t TimePathRebuildFail; + TimeUnit_t TimePathRebuildNext; + bool RememberStaleNodes; bool NoPathcornerPathfinds; bool LocalSucceedOnWithinTolerance; - bool RememberStaleNodes; + bool PeerMoveWait; EHANDLE PeerWaitingOn = new(); readonly SimTimer PeerWaitMoveTimer = new(); readonly SimTimer PeerWaitClearTimer = new(); @@ -277,12 +2715,11 @@ public void ClearPath() { readonly SimTimer NextSidestepTimer = new(); EHANDLE BigStepGroundEnt = new(); + EHANDLE LastBlockingEnt = new(); Vector3 PosBeginFailedSteer; - float TimeBeginFailedSteer; - - float TimeLastAvoidanceTriangulate; + TimeUnit_t TimeBeginFailedSteer; int NavFailCounter; - float LastNavFailTime; + TimeUnit_t LastNavFailTime; } From 45f23a983a01ac0f9b07e0018ccf1c03226f0f8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:24:15 +0300 Subject: [PATCH 31/73] Port NPC navigation hooks and movement tasks --- Game.Server/AI_BaseNPC.cs | 464 +++++++++++++++++++++++++++++++++++--- 1 file changed, 432 insertions(+), 32 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 66edaca3f..ac43ba520 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -428,6 +428,7 @@ public static ReadOnlySpan GetActivityName(Activity actID) { public Handle ForcedInteractionPartner = new(); public NPCInteractionState InteractionState; public Vector3 SavePosition; + public Vector3 LastPosition; public Vector3 EyeLookTarget; public Vector3 CurEyeTarget; public float EyeIntegRate = 0.95f; @@ -2852,6 +2853,8 @@ public virtual bool IsJumpLegal(in Vector3 startPos, in Vector3 apex, in Vector3 return IsJumpLegal(startPos, apex, endPos, MAX_JUMP_RISE, MAX_JUMP_DROP, MAX_JUMP_DISTANCE); } + public virtual bool MovementCost(Capability moveType, in Vector3 start, in Vector3 end, ref float cost) => false; + public override bool CanStandOn(BaseEntity? surface) { if (!surface!.IsAIWalkable()) return false; @@ -2885,6 +2888,51 @@ public virtual bool IsUnusableNode(int nodeID, AI_Hint? hint) { public virtual float CalcYawSpeed() => -1.0f; + public virtual bool OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if (moveGoal.DirectTrace.Obstruction != null) { + if (moveGoal.DirectTrace.Obstruction is BasePropDoor propDoor && OnUpcomingPropDoor(ref moveGoal, propDoor, distClear, ref result)) + return true; + } + + return false; + } + + public virtual bool OnObstructionPreSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if (moveGoal.DirectTrace.Obstruction != null) { + if (moveGoal.DirectTrace.Obstruction is BaseDoor door && OnObstructingDoor(ref moveGoal, door, distClear, ref result)) + return true; + } + + return false; + } + + public virtual bool OnFailedSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => false; + public virtual bool OnFailedLocalNavigation(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => false; + public virtual bool OnInsufficientStopDist(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => false; + public virtual bool OnMoveBlocked(ref AIMoveResult result) => false; + public virtual bool OnMoveStalled(in AILocalMoveGoal move) => false; + public virtual bool OnMoveExecuteFailed(in AILocalMoveGoal move, in AIMoveTrace trace, AIMotorMoveResult motorResult, ref AIMoveResult result) => false; + + public virtual bool OnObstructingDoor(ref AILocalMoveGoal moveGoal, BaseDoor door, float distClear, ref AIMoveResult result) { + if (moveGoal.MaxDist < distClear) + return false; + + if (door.ToggleState == Game.Shared.ToggleState.AtBottom || door.ToggleState == Game.Shared.ToggleState.GoingDown) { + if (distClear < 0.1) + result = AIMoveResult.BlockedEntity; + else { + moveGoal.MaxDist = distClear; + result = AIMoveResult.Ok; + } + + return true; + } + + return false; + } + + public virtual bool OnUpcomingPropDoor(ref AILocalMoveGoal moveGoal, BasePropDoor door, float distClear, ref AIMoveResult result) => throw new NotImplementedException(); + public virtual float HearingSensitivity() => 1.0f; public void SetTaskStatus(TaskStatus status) => ScheduleState.TaskStatus = status; @@ -3485,6 +3533,28 @@ public virtual bool IsCurTaskContinuousMove() { } } + public bool ValidateNavGoal() { + if (GetNavigator()!.GetGoalType() == NavGoalType.Cover) { + if (GetEnemy() != null) { + Activity coverActivity = GetCoverActivity(GetHintNode()); + Vector3 coverLocation = GetNavigator()!.GetGoalPos(); + + float floorZ = GetFloorZ(coverLocation); + coverLocation.Z = floorZ; + + Vector3 eyePos = coverLocation + EyeOffset(coverActivity); + + if (!IsCoverPosition(GetEnemy()!.EyePosition(), eyePos)) { + TaskFail(AI_TaskFailureCode.BadPathGoal); + return false; + } + } + } + return true; + } + + public virtual bool IsCoverPosition(in Vector3 threat, in Vector3 position) => throw new NotImplementedException(); + public bool ShouldMoveWait() => MoveWaitFinished > gpGlobals.CurTime; public virtual bool ShouldMoveAndShoot() => (CapabilitiesGet() & Server.Capability.MoveShoot) != 0; @@ -3666,7 +3736,172 @@ public virtual void StartTask(in Task_t task) { break; case TASK_STOP_MOVING: - SetIdealActivity(GetStoppedActivity()); + if ((GetNavigator()!.IsGoalSet() && GetNavigator()!.IsGoalActive()) || GetNavType() == Navigation.Jump) { + if (task.TaskData == 1) + GetNavigator()!.StopMoving(false); + else + GetNavigator()!.ClearGoal(); + + if (HasPoseMoveYaw()) + SetPoseParameter(PoseMove_Yaw, 0); + } + else { + if (!(task.TaskData == 1 && GetNavigator()!.SetGoalFromStoppingPath())) { + GetNavigator()!.ClearGoal(); + SetIdealActivity(GetStoppedActivity()); + TaskComplete(); + } + } + break; + + case TASK_STORE_LASTPOSITION: + LastPosition = GetLocalOrigin(); + TaskComplete(); + break; + + case TASK_CLEAR_LASTPOSITION: + LastPosition = vec3_origin; + TaskComplete(); + break; + + case TASK_STORE_POSITION_IN_SAVEPOSITION: + SavePosition = GetLocalOrigin(); + TaskComplete(); + break; + + case TASK_GET_PATH_TO_PLAYER: { + BaseEntity? player = AI_GetClosestPlayer(); + if (player == null) + break; + + AI_NavGoal goal = new() { + Type = NavGoalType.Location, + Dest = player.WorldSpaceCenter(), + Target = player, + DefTarget = false + }; + + GetNavigator()!.SetGoal(goal); + break; + } + + case TASK_GET_PATH_TO_TARGET: { + if (TargetEnt.Get() == null) + TaskFail(AI_TaskFailureCode.NoTarget); + else { + AI_NavGoal goal = new(TargetEnt.Get()!.EyePosition()) { + Target = TargetEnt.Get(), + DefTarget = false + }; + GetNavigator()!.SetGoal(goal); + } + break; + } + + case TASK_GET_PATH_TO_LASTPOSITION: { + if (!GetNavigator()!.SetGoal(new AI_NavGoal(LastPosition))) + TaskFail(AI_TaskFailureCode.NoRoute); + else + GetNavigator()!.SetGoalTolerance(48); + break; + } + + case TASK_GET_PATH_TO_SAVEPOSITION: + GetNavigator()!.SetGoal(new AI_NavGoal(SavePosition)); + break; + + case TASK_GET_PATH_TO_RANDOM_NODE: { + if (GetNavigator()!.SetRandomGoal(task.TaskData)) + TaskComplete(); + else + TaskFail(AI_TaskFailureCode.NoReachableNode); + break; + } + + case TASK_RUN_PATH: { + if (TranslateActivity(Activity.ACT_RUN) != Activity.ACT_INVALID) + GetNavigator()!.SetMovementActivity(Activity.ACT_RUN); + else + GetNavigator()!.SetMovementActivity(Activity.ACT_WALK); + Forget(AI_MemoryFlags.Incover); + TaskComplete(); + break; + } + + case TASK_WALK_PATH_FOR_UNITS: + GetNavigator()!.SetMovementActivity(Activity.ACT_WALK); + break; + + case TASK_RUN_PATH_FOR_UNITS: + GetNavigator()!.SetMovementActivity(Activity.ACT_RUN); + break; + + case TASK_WALK_PATH: { + bool isFlying = (GetMoveType() == Source.MoveType.Fly) || (GetMoveType() == Source.MoveType.FlyGravity); + if (isFlying && (TranslateActivity(Activity.ACT_FLY) != Activity.ACT_INVALID)) + GetNavigator()!.SetMovementActivity(Activity.ACT_FLY); + else if (TranslateActivity(Activity.ACT_WALK) != Activity.ACT_INVALID) + GetNavigator()!.SetMovementActivity(Activity.ACT_WALK); + else + GetNavigator()!.SetMovementActivity(Activity.ACT_RUN); + Forget(AI_MemoryFlags.Incover); + TaskComplete(); + break; + } + + case TASK_WALK_PATH_WITHIN_DIST: + GetNavigator()!.SetMovementActivity(Activity.ACT_WALK); + GetNavigator()!.SetArrivalDistance(task.TaskData); + break; + + case TASK_RUN_PATH_WITHIN_DIST: + GetNavigator()!.SetMovementActivity(Activity.ACT_RUN); + GetNavigator()!.SetArrivalDistance(task.TaskData); + break; + + case TASK_RUN_PATH_FLEE: { + Vector3 diff = GetLocalOrigin() - GetNavigator()!.GetGoalPos(); + + if (diff.Length() <= task.TaskData) { + GetNavigator()!.StopMoving(); + TaskFail("Flee path shorter than task parameter"); + } + else + GetNavigator()!.SetMovementActivity(Activity.ACT_RUN); + break; + } + + case TASK_WALK_PATH_TIMED: + GetNavigator()!.SetMovementActivity(Activity.ACT_WALK); + SetWait(task.TaskData); + break; + + case TASK_RUN_PATH_TIMED: + GetNavigator()!.SetMovementActivity(Activity.ACT_RUN); + SetWait(task.TaskData); + break; + + case TASK_WAIT_FOR_MOVEMENT_STEP: { + if (!GetNavigator()!.IsGoalActive()) { + TaskComplete(); + return; + } + + if (IsActivityFinished()) { + TaskComplete(); + return; + } + ValidateNavGoal(); + break; + } + + case TASK_SET_TOLERANCE_DISTANCE: + GetNavigator()!.SetGoalTolerance((int)task.TaskData); + TaskComplete(); + break; + + case TASK_SET_ROUTE_SEARCH_TIME: + GetNavigator()!.SetMaxRouteRebuildTime((int)task.TaskData); TaskComplete(); break; @@ -3703,7 +3938,14 @@ public virtual void StartTask(in Task_t task) { } case TASK_WAIT_FOR_MOVEMENT: - TaskComplete(); + if (GetNavigator()!.GetGoalType() == NavGoalType.None) { + TaskComplete(); + GetNavigator()!.ClearGoal(); + } + else if (!GetNavigator()!.IsGoalActive()) + SetIdealActivity(GetStoppedActivity()); + else + ValidateNavGoal(); break; case TASK_PLAY_SCENE: @@ -3748,9 +3990,6 @@ public virtual void StartTask(in Task_t task) { case TASK_FIND_HINTNODE: case TASK_FIND_LOCK_HINTNODE: case TASK_LOCK_HINTNODE: - case TASK_STORE_LASTPOSITION: - case TASK_CLEAR_LASTPOSITION: - case TASK_STORE_POSITION_IN_SAVEPOSITION: case TASK_STORE_BESTSOUND_IN_SAVEPOSITION: case TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION: case TASK_CLEAR_HINTNODE: @@ -3804,34 +4043,19 @@ public virtual void StartTask(in Task_t task) { case TASK_GET_PATH_TO_GOAL: case TASK_GET_PATH_TO_ENEMY: case TASK_GET_PATH_TO_ENEMY_CORPSE: - case TASK_GET_PATH_TO_PLAYER: case TASK_GET_PATH_TO_SAVEPOSITION_LOS: case TASK_GET_PATH_TO_TARGET_WEAPON: - case TASK_GET_PATH_TO_TARGET: case TASK_GET_PATH_TO_HINTNODE: case TASK_GET_PATH_TO_COMMAND_GOAL: case TASK_MARK_COMMAND_GOAL_POS: case TASK_CLEAR_COMMAND_GOAL: - case TASK_GET_PATH_TO_LASTPOSITION: - case TASK_GET_PATH_TO_SAVEPOSITION: - case TASK_GET_PATH_TO_RANDOM_NODE: case TASK_GET_PATH_TO_BESTSOUND: case TASK_GET_PATH_TO_BESTSCENT: case TASK_GET_PATH_AWAY_FROM_BEST_SOUND: case TASK_MOVE_AWAY_PATH: case TASK_WEAPON_RUN_PATH: case TASK_ITEM_RUN_PATH: - case TASK_RUN_PATH: - case TASK_WALK_PATH_FOR_UNITS: - case TASK_RUN_PATH_FOR_UNITS: - case TASK_WALK_PATH: - case TASK_WALK_PATH_WITHIN_DIST: - case TASK_RUN_PATH_WITHIN_DIST: - case TASK_RUN_PATH_FLEE: - case TASK_WALK_PATH_TIMED: - case TASK_RUN_PATH_TIMED: case TASK_STRAFE_PATH: - case TASK_WAIT_FOR_MOVEMENT_STEP: case TASK_SMALL_FLINCH: case TASK_BIG_FLINCH: case TASK_DIE: @@ -3850,8 +4074,6 @@ public virtual void StartTask(in Task_t task) { case TASK_ENABLE_SCRIPT: case TASK_PLANT_ON_SCRIPT: case TASK_FACE_SCRIPT: - case TASK_SET_TOLERANCE_DISTANCE: - case TASK_SET_ROUTE_SEARCH_TIME: case TASK_WEAPON_FIND: case TASK_ITEM_PICKUP: case TASK_WEAPON_PICKUP: @@ -3873,6 +4095,20 @@ public virtual void RunTask(in Task_t task) { if (task.TaskData == 1) ChainRunTask(TASK_WAIT_FOR_MOVEMENT); else { + if (GetNavType() == Navigation.Jump) { + if ((GetFlags() & EntityFlags.OnGround) != 0) + SetNavType(Navigation.Ground); + else if (GetSmoothedVelocity().Length() > 0.01) + break; + else { + SetNavType(Navigation.Ground); + TaskFail(AI_TaskFailureCode.StuckOnTop); + } + } + + if (GetNavType() == Navigation.Climb) + break; + SetIdealActivity(GetStoppedActivity()); TaskComplete(); @@ -3927,10 +4163,54 @@ public virtual void RunTask(in Task_t task) { case TASK_WAIT_FOR_MOVEMENT_STEP: case TASK_WAIT_FOR_MOVEMENT: { - TaskComplete(); + bool timeExpired = task.TaskData != 0 && task.TaskData < gpGlobals.CurTime - GetTimeTaskStarted(); + + if (timeExpired || GetNavigator()!.GetGoalType() == NavGoalType.None) { + TaskComplete(); + GetNavigator()!.StopMoving(); + } + else if (!GetNavigator()!.IsGoalActive()) + SetIdealActivity(GetStoppedActivity()); + else + ValidateNavGoal(); + break; + } + + case TASK_RUN_PATH_FOR_UNITS: + case TASK_WALK_PATH_FOR_UNITS: { + float distance = (LastPosition - GetLocalOrigin()).Length2D(); + + if (distance > task.TaskData || + GetNavigator()!.GetGoalType() == NavGoalType.None) + TaskComplete(); break; } + case TASK_RUN_PATH_FLEE: { + Vector3 diff = GetLocalOrigin() - GetNavigator()!.GetGoalPos(); + + if (diff.Length() <= task.TaskData) + TaskComplete(); + break; + } + + case TASK_WALK_PATH_WITHIN_DIST: + case TASK_RUN_PATH_WITHIN_DIST: { + Vector3 diff = GetLocalOrigin() - GetNavigator()!.GetGoalPos(); + + if (diff.Length() <= task.TaskData) + TaskComplete(); + break; + } + + case TASK_WALK_PATH_TIMED: + case TASK_RUN_PATH_TIMED: { + if (IsWaitFinished() || + GetNavigator()!.GetGoalType() == NavGoalType.None) + TaskComplete(); + } + break; + case TASK_PLAY_SCENE: { if (!IsInLockedScene()) ClearSchedule("Playing a scene, but not in a scene!"); @@ -4020,13 +4300,6 @@ public virtual void RunTask(in Task_t task) { case TASK_PLAY_SCRIPT: case TASK_PLAY_SCRIPT_POST_IDLE: case TASK_ENABLE_SCRIPT: - case TASK_RUN_PATH_FOR_UNITS: - case TASK_WALK_PATH_FOR_UNITS: - case TASK_RUN_PATH_FLEE: - case TASK_WALK_PATH_WITHIN_DIST: - case TASK_RUN_PATH_WITHIN_DIST: - case TASK_WALK_PATH_TIMED: - case TASK_RUN_PATH_TIMED: case TASK_WEAPON_PICKUP: case TASK_ITEM_PICKUP: throw new NotImplementedException(); @@ -4085,7 +4358,76 @@ public void ClearAttackConditions() { ClearCondition((int)SCOND_t.COND_WEAPON_SIGHT_OCCLUDED); } - public virtual bool IsNavigationUrgent() => throw new NotImplementedException(); + public virtual bool IsNavigationUrgent() { + if (IsCurSchedule(SCHED_SCRIPTED_WALK, false) || + IsCurSchedule(SCHED_SCRIPTED_RUN, false) || + IsCurSchedule(SCHED_SCRIPTED_CUSTOM_MOVE, false) || + (IsCurSchedule(SCHED_SCENE_GENERIC, false) && IsInLockedScene())) + return true; + return false; + } + + public virtual bool ShouldFailNav(bool movementFailed) { +#if HL2_EPISODIC + if (ai_vehicle_avoidance.GetBool()) { + BaseEntity? entity = GetNavigator()!.GetBlockingEntity(); + if (entity != null && entity.GetServerVehicle() != null) { + if (Classify() == Class_T.PlayerAllyVital || IsNavigationUrgent()) + return false; + } + } +#endif + + if (IsNavigationUrgent()) + return false; + + return true; + } + + public virtual bool ShouldBruteForceFailedNav() => false; + + public virtual void OnMovementFailed() { } + public virtual void OnMovementComplete() { } + + public virtual float GetDefaultNavGoalTolerance() => GetHullWidth() * 2.0f; + + public virtual void TranslateNavGoal(BaseEntity enemy, ref Vector3 chasePosition) { + if (GetNavType() == Navigation.Fly) { + Vector3 offset = enemy.EyePosition() - enemy.GetAbsOrigin(); + chasePosition += offset; + } + } + + public void OpenPropDoorBegin(BasePropDoor door) => throw new NotImplementedException(); + + public void TaskMovementComplete() { + switch (GetTaskStatus()) { + case TaskStatus.New: + case TaskStatus.RunMoveAndTask: + SetTaskStatus(TaskStatus.RunTask); + break; + + case TaskStatus.RunMove: + TaskComplete(); + break; + + case TaskStatus.RunTask: + break; + + case TaskStatus.Complete: + break; + } + + if (ScriptState != ScriptStateType.CustomMoveToMark) + SetIdealActivity(GetStoppedActivity()); + + if (GetNavigator()!.IsGoalActive()) + GetNavigator()!.AdvancePath(); + + GetNavigator()!.ClearGoal(); + + OnMovementComplete(); + } public virtual bool ShouldProbeCollideAgainstEntity(BaseEntity entity) { if (entity.GetMoveType() == Source.MoveType.VPhysics) { @@ -4578,6 +4920,14 @@ public bool IsInPlayerSquad() { public BaseEntity? GetTarget() => TargetEnt.Get(); + public virtual BaseEntity? GetNavTargetEntity() { + if (GetNavigator()!.GetGoalType() == NavGoalType.Enemy) + return Enemy.Get(); + else if (GetNavigator()!.GetGoalType() == NavGoalType.TargetEnt) + return TargetEnt.Get(); + return null; + } + public float EnemyDistance(BaseEntity enemy) { Vector3 enemyDelta = enemy.WorldSpaceCenter() - WorldSpaceCenter(); @@ -4647,6 +4997,7 @@ public void CheckOnGround() { } public Navigation GetNavType() => Navigator!.GetNavType(); + public void SetNavType(Navigation navType) => Navigator!.SetNavType(navType); public virtual bool ShouldPlayIdleSound() { if ((NPCState == NPCState.Idle || NPCState == NPCState.Alert) && @@ -4795,7 +5146,47 @@ public virtual float MaxYawSpeed() { return 45; } - public virtual float GetTimeToNavGoal() => throw new NotImplementedException(); + public virtual bool ScheduledMoveToGoalEntity(int scheduleType, BaseEntity goalEntity, Activity movementActivity) { + if (NPCState == NPCState.None) + NPCState = IdealNPCState; + + SetSchedule(scheduleType); + + SetGoalEnt(goalEntity); + + AI_NavGoal goal = new(goalEntity.GetAbsOrigin(), movementActivity, AIN_DEF_TOLERANCE, AI_NavGoalFlags.YawToDest); + + TranslateNavGoal(goalEntity, ref goal.Dest); + + return GetNavigator()!.SetGoal(goal); + } + + public virtual bool ScheduledFollowPath(int scheduleType, BaseEntity pathStart, Activity movementActivity) { + if (NPCState == NPCState.None) + NPCState = IdealNPCState; + + SetSchedule(scheduleType); + + SetGoalEnt(pathStart); + + AI_NavGoal goal = new(NavGoalType.PathCorner, pathStart.GetLocalOrigin(), movementActivity, AIN_DEF_TOLERANCE, AI_NavGoalFlags.YawToDest); + + TranslateNavGoal(pathStart, ref goal.Dest); + + return GetNavigator()!.SetGoal(goal); + } + + public virtual float GetTimeToNavGoal() { + float dist = GetNavigator()!.BuildAndGetPathDistToGoal(); + if (dist < 0) + return -1.0f; + + float speed = GetIdealSpeed(); + + if (speed > 0 && dist > 0) + return dist / speed; + return 0.0f; + } public void VacateStrategySlot() => throw new NotImplementedException(); @@ -5177,6 +5568,8 @@ public override Activity NPC_TranslateActivity(Activity newActivity) { static readonly List sUniqueActivities = []; + public Activity TranslateActivity(Activity idealActivity) => TranslateActivity(idealActivity, out _); + public Activity TranslateActivity(Activity idealActivity, out Activity idealWeaponActivityOut) { const int MAX_TRIES = 5; int count = 0; @@ -6267,11 +6660,18 @@ public virtual void RunAnimation() { } public virtual bool OverrideMove(float interval) => false; + public virtual bool OverrideMoveFacing(in AILocalMoveGoal move, float interval) => false; + + public bool HasPoseMoveYaw() => PoseMove_Yaw >= 0; + public int LookupPoseMoveYaw() => PoseMove_Yaw; public virtual void PerformMovement() { if (!IsAlive()) return; + TimeUnit_t interval = (TimeLastMovement != float.MaxValue) ? gpGlobals.CurTime - TimeLastMovement : 0.1; + + Navigator!.Move((float)(TICK_INTERVAL * TIME_TO_TICKS(interval))); TimeLastMovement = gpGlobals.CurTime; } From f1dba9721025b6d39dd651c6ae8ba8d6279c01cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:28:39 +0300 Subject: [PATCH 32/73] Port behavior host bridges and behavior schedules --- Game.Server/AI_BehaviorBase.cs | 202 ++++++++++++++++++- Game.Server/AI_BehaviorHost_AI_BaseNPC.cs | 167 +++++++++++++++ Game.Server/AI_Behavior_AI_BaseNPC_100000.cs | 36 ++++ Game.Server/IBehaviorBackBridge.cs | 7 + 4 files changed, 408 insertions(+), 4 deletions(-) diff --git a/Game.Server/AI_BehaviorBase.cs b/Game.Server/AI_BehaviorBase.cs index b2b220db0..2044e00cd 100644 --- a/Game.Server/AI_BehaviorBase.cs +++ b/Game.Server/AI_BehaviorBase.cs @@ -33,12 +33,91 @@ public void SetBackBridge(IBehaviorBackBridge? backBridge) { public void BridgePrecache() => Precache(); public void BridgeSpawn() => Spawn(); + public void BridgeUpdateOnRemove() => UpdateOnRemove(); + public void BridgeEvent_Killed(in TakeDamageInfo info) => Event_Killed(info); - public int BridgeSelectSchedule() => throw new NotImplementedException(); + public void BridgeGatherConditions() => GatherConditions(); + public void BridgePrescheduleThink() => PrescheduleThink(); + public void BridgeOnScheduleChange() => OnScheduleChange(); - public Activity BridgeNPC_TranslateActivity(Activity activity) => throw new NotImplementedException(); - public bool BridgeIsCrouching() => throw new NotImplementedException(); - public bool BridgeShouldPlayerAvoid() => throw new NotImplementedException(); + public void BridgeOnStartSchedule(int scheduleType) { + int localId = AI_IdIsGlobal(scheduleType) ? GetClassScheduleIdSpace().ScheduleGlobalToLocal(scheduleType) : scheduleType; + OnStartSchedule(localId); + } + + public int BridgeSelectSchedule() { + int result = SelectSchedule(); + + if (IsBehaviorSchedule(result)) + return GetClassScheduleIdSpace().ScheduleLocalToGlobal(result); + + return result; + } + + public bool BridgeSelectFailSchedule(int failedSchedule, int failedTask, AI_TaskFailureCode taskFailCode, out int result) { + result = 0; + Overrode = true; + int selected = SelectFailSchedule(failedSchedule, failedTask, taskFailCode); + if (Overrode) { + if (selected != SCHED_NONE) { + if (IsBehaviorSchedule(selected)) + result = GetClassScheduleIdSpace().ScheduleLocalToGlobal(selected); + else + result = selected; + return true; + } + Warning("An AI behavior is in control but has no recommended schedule\n"); + } + return false; + } + + public bool BridgeStartTask(in Task_t task) { + Overrode = true; + StartTask(task); + return Overrode; + } + + public bool BridgeRunTask(in Task_t task) { + Overrode = true; + RunTask(task); + return Overrode; + } + + public bool BridgeAimGun() { + Overrode = true; + AimGun(); + return Overrode; + } + + public int BridgeTranslateSchedule(int scheduleType) { + int localId = AI_IdIsGlobal(scheduleType) ? GetClassScheduleIdSpace().ScheduleGlobalToLocal(scheduleType) : scheduleType; + return TranslateSchedule(localId); + } + + public bool BridgeGetSchedule(int localScheduleID, out AI_Schedule? result) { + result = GetSchedule(localScheduleID); + return result != null; + } + + public Activity BridgeNPC_TranslateActivity(Activity activity) => NPC_TranslateActivity(activity); + public void BridgeBuildScheduleTestBits() => BuildScheduleTestBits(); + + public bool BridgeIsCurTaskContinuousMove(out bool result) { + bool prevOverride = Overrode; + Overrode = true; + result = IsCurTaskContinuousMove(); + bool overrode = Overrode; + Overrode = prevOverride; + return overrode; + } + + public void BridgeOnMovementFailed() => OnMovementFailed(); + public void BridgeOnMovementComplete() => OnMovementComplete(); + public float BridgeGetDefaultNavGoalTolerance() => GetDefaultNavGoalTolerance(); + public bool BridgeIsNavigationUrgent() => IsNavigationUrgent(); + public bool BridgeShouldPlayerAvoid() => ShouldPlayerAvoid(); + public bool BridgeIsCrouching() => IsCrouching(); + public bool BridgeOnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => OnCalcBaseMove(ref moveGoal, distClear, ref result); public virtual void GatherConditions() { Assert(BackBridge != null); @@ -46,8 +125,18 @@ public virtual void GatherConditions() { BackBridge!.BackBridge_GatherConditions(); } + public virtual void GatherConditionsNotActive() { } + + public virtual AI_ClassScheduleIdSpace GetClassScheduleIdSpace() => GetOuter()!.GetClassScheduleIdSpace(); + protected virtual void Precache() { } protected virtual void Spawn() { } + protected virtual void UpdateOnRemove() { } + protected virtual void Event_Killed(in TakeDamageInfo info) { } + + protected virtual void PrescheduleThink() { } + protected virtual void OnScheduleChange() { } + protected virtual void OnStartSchedule(int scheduleType) { } protected virtual int SelectSchedule() { Assert(BackBridge != null); @@ -55,6 +144,111 @@ protected virtual int SelectSchedule() { return BackBridge!.BackBridge_SelectSchedule(); } + protected virtual int SelectFailSchedule(int failedSchedule, int failedTask, AI_TaskFailureCode taskFailCode) { + Overrode = false; + return SCHED_NONE; + } + + protected virtual void StartTask(in Task_t task) => Overrode = false; + protected virtual void RunTask(in Task_t task) => Overrode = false; + protected virtual void AimGun() => Overrode = false; + + protected virtual int TranslateSchedule(int scheduleType) { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_TranslateSchedule(scheduleType); + } + + protected virtual AI_Schedule? GetSchedule(int schedule) { + if (!GetClassScheduleIdSpace().IsGlobalBaseSet()) { + Warning($"ERROR: {GetSchedulingErrorName()} missing schedule!\n"); + return g_AI_SchedulesManager.GetScheduleFromID(SCHED_IDLE_STAND); + } + if (AI_IdIsLocal(schedule)) + schedule = GetClassScheduleIdSpace().ScheduleLocalToGlobal(schedule); + + if (schedule == -1) + return null; + + return g_AI_SchedulesManager.GetScheduleFromID(schedule); + } + + protected virtual string GetSchedulingErrorName() => "CAI_Behavior"; + + protected virtual void BuildScheduleTestBits() { } + + protected bool IsCurSchedule(int schedule, bool ideal = true) { + if (AI_IdIsLocal(schedule)) + schedule = GetClassScheduleIdSpace().ScheduleLocalToGlobal(schedule); + + return GetOuter()!.IsCurSchedule(schedule, ideal); + } + + protected void ChainStartTask(int task, float taskData = 0) { + Task_t tempTask = new() { Task = task, TaskData = taskData }; + + bool prevOverride = Overrode; + GetOuter()!.StartTask(tempTask); + Overrode = prevOverride; + } + + protected void ChainRunTask(int task, float taskData = 0) { + Task_t tempTask = new() { Task = task, TaskData = taskData }; + + bool prevOverride = Overrode; + GetOuter()!.RunTask(tempTask); + Overrode = prevOverride; + } + + protected virtual Activity NPC_TranslateActivity(Activity activity) { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_NPC_TranslateActivity(activity); + } + + protected virtual bool IsCurTaskContinuousMove() { + Overrode = false; + return false; + } + + protected virtual void OnMovementFailed() { } + protected virtual void OnMovementComplete() { } + + protected virtual float GetDefaultNavGoalTolerance() { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_GetDefaultNavGoalTolerance(); + } + + protected virtual bool IsNavigationUrgent() { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_IsNavigationUrgent(); + } + + protected virtual bool ShouldPlayerAvoid() { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_ShouldPlayerAvoid(); + } + + protected virtual bool IsCrouching() { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_IsCrouching(); + } + + protected virtual bool OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_OnCalcBaseMove(ref moveGoal, distClear, ref result); + } + + protected virtual bool IsBehaviorSchedule(int scheduleType) => false; + + protected AI_Navigator? GetNavigator() => GetOuter()!.GetNavigator(); + protected AI_Motor? GetMotor() => GetOuter()!.GetMotor(); + protected bool Overrode; protected IBehaviorBackBridge? BackBridge; } diff --git a/Game.Server/AI_BehaviorHost_AI_BaseNPC.cs b/Game.Server/AI_BehaviorHost_AI_BaseNPC.cs index e59e5fcb1..48b2460d9 100644 --- a/Game.Server/AI_BehaviorHost_AI_BaseNPC.cs +++ b/Game.Server/AI_BehaviorHost_AI_BaseNPC.cs @@ -1,3 +1,5 @@ +using Game.Shared; + namespace Game.Server; public class AI_BehaviorHost_AI_BaseNPC : AI_BaseNPC, IBehaviorBackBridge @@ -16,6 +18,18 @@ public override bool CreateComponents() { public virtual bool CreateBehaviors() => true; + public override bool ScheduledMoveToGoalEntity(int scheduleType, BaseEntity goalEntity, Activity movementActivity) { + ChangeBehaviorTo(null); + + return base.ScheduledMoveToGoalEntity(scheduleType, goalEntity, movementActivity); + } + + public override bool ScheduledFollowPath(int scheduleType, BaseEntity pathStart, Activity movementActivity) { + ChangeBehaviorTo(null); + + return base.ScheduledFollowPath(scheduleType, pathStart, movementActivity); + } + public override void Precache() { base.Precache(); for (int i = 0; i < Behaviors.Count; i++) @@ -28,6 +42,51 @@ public override void NPCInit() { Behaviors[i].BridgeSpawn(); } + public override void UpdateOnRemove() { + for (int i = 0; i < Behaviors.Count; i++) + Behaviors[i].BridgeUpdateOnRemove(); + base.UpdateOnRemove(); + } + + public override void Event_Killed(in TakeDamageInfo info) { + for (int i = 0; i < Behaviors.Count; i++) + Behaviors[i].BridgeEvent_Killed(info); + base.Event_Killed(info); + } + + public override void GatherConditions() { + for (int i = 0; i < Behaviors.Count; i++) { + if (Behaviors[i] != CurBehavior) + Behaviors[i].GatherConditionsNotActive(); + } + + if (CurBehavior != null) + CurBehavior.BridgeGatherConditions(); + else + base.GatherConditions(); + } + + public override void OnScheduleChange() { + CurBehavior?.BridgeOnScheduleChange(); + base.OnScheduleChange(); + } + + public override void OnStartSchedule(int scheduleType) { + CurBehavior?.BridgeOnStartSchedule(scheduleType); + base.OnStartSchedule(scheduleType); + } + + public override int TranslateSchedule(int scheduleType) { + if (CurBehavior != null) + return CurBehavior.BridgeTranslateSchedule(scheduleType); + return base.TranslateSchedule(scheduleType); + } + + public override void PrescheduleThink() { + base.PrescheduleThink(); + CurBehavior?.BridgePrescheduleThink(); + } + public override int SelectSchedule() { CalledBehaviorSelectSchedule = true; if (CurBehavior != null) @@ -36,12 +95,82 @@ public override int SelectSchedule() { return base.SelectSchedule(); } + public void KeepRunningBehavior() { + if (CurBehavior != null) + CalledBehaviorSelectSchedule = true; + } + + public override int SelectFailSchedule(int failedSchedule, int failedTask, AI_TaskFailureCode taskFailCode) { + CalledBehaviorSelectSchedule = true; + if (CurBehavior != null && CurBehavior.BridgeSelectFailSchedule(failedSchedule, failedTask, taskFailCode, out int result)) + return result; + return base.SelectFailSchedule(failedSchedule, failedTask, taskFailCode); + } + + public override void StartTask(in Task_t task) { + if (CurBehavior != null && CurBehavior.BridgeStartTask(task)) + return; + base.StartTask(task); + } + + public override void RunTask(in Task_t task) { + if (CurBehavior != null && CurBehavior.BridgeRunTask(task)) + return; + base.RunTask(task); + } + + public override void AimGun() { + if (CurBehavior != null && CurBehavior.BridgeAimGun()) + return; + base.AimGun(); + } + + public override AI_Schedule? GetSchedule(int localScheduleID) { + if (CurBehavior != null && CurBehavior.BridgeGetSchedule(localScheduleID, out AI_Schedule? result)) + return result; + return base.GetSchedule(localScheduleID); + } + + public override void BuildScheduleTestBits() { + CurBehavior?.BridgeBuildScheduleTestBits(); + base.BuildScheduleTestBits(); + } + public override Activity NPC_TranslateActivity(Activity activity) { if (CurBehavior != null) return CurBehavior.BridgeNPC_TranslateActivity(activity); return base.NPC_TranslateActivity(activity); } + public override bool IsCurTaskContinuousMove() { + if (CurBehavior != null && CurBehavior.BridgeIsCurTaskContinuousMove(out bool result)) + return result; + return base.IsCurTaskContinuousMove(); + } + + public override void OnMovementFailed() { + CurBehavior?.BridgeOnMovementFailed(); + base.OnMovementFailed(); + } + + public override void OnMovementComplete() { + CurBehavior?.BridgeOnMovementComplete(); + base.OnMovementComplete(); + } + + public override float GetDefaultNavGoalTolerance() { + if (CurBehavior != null) + return CurBehavior.BridgeGetDefaultNavGoalTolerance(); + return base.GetDefaultNavGoalTolerance(); + } + + public override bool IsNavigationUrgent() { + if (CurBehavior != null) + return CurBehavior.BridgeIsNavigationUrgent(); + + return base.IsNavigationUrgent(); + } + public override bool ShouldPlayerAvoid() { if (CurBehavior != null) return CurBehavior.BridgeShouldPlayerAvoid(); @@ -56,6 +185,21 @@ public override bool IsCrouching() { return base.IsCrouching(); } + public override bool OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if (CurBehavior != null) + return CurBehavior.BridgeOnCalcBaseMove(ref moveGoal, distClear, ref result); + + return base.OnCalcBaseMove(ref moveGoal, distClear, ref result); + } + + public virtual bool OnBehaviorChangeStatus(AI_BehaviorBase behavior, bool canFinishSchedule) { + if (behavior == GetRunningBehavior() && !behavior.CanSelectSchedule() && !canFinishSchedule) { + DeferSchedulingToBehavior(null); + return true; + } + return false; + } + public virtual void OnChangeRunningBehavior(AI_BehaviorBase? oldBehavior, AI_BehaviorBase? newBehavior) { } protected void AddBehavior(AI_BehaviorBase behavior) { @@ -111,6 +255,22 @@ protected void ChangeBehaviorTo(AI_BehaviorBase? newBehavior) { } } + public override AI_Schedule? GetNewSchedule() { + CalledBehaviorSelectSchedule = false; + AI_Schedule? result = base.GetNewSchedule(); + if (!CalledBehaviorSelectSchedule && CurBehavior != null) + DeferSchedulingToBehavior(null); + return result; + } + + public override AI_Schedule? GetFailSchedule() { + CalledBehaviorSelectSchedule = false; + AI_Schedule? result = base.GetFailSchedule(); + if (!CalledBehaviorSelectSchedule && CurBehavior != null) + DeferSchedulingToBehavior(null); + return result; + } + void IBehaviorBackBridge.BackBridge_GatherConditions() { if (g_bBehaviorHost_PreventBaseClassGatherConditions) return; @@ -119,6 +279,13 @@ void IBehaviorBackBridge.BackBridge_GatherConditions() { } int IBehaviorBackBridge.BackBridge_SelectSchedule() => base.SelectSchedule(); + int IBehaviorBackBridge.BackBridge_TranslateSchedule(int scheduleType) => base.TranslateSchedule(scheduleType); + Activity IBehaviorBackBridge.BackBridge_NPC_TranslateActivity(Activity activity) => base.NPC_TranslateActivity(activity); + bool IBehaviorBackBridge.BackBridge_IsNavigationUrgent() => base.IsNavigationUrgent(); + bool IBehaviorBackBridge.BackBridge_ShouldPlayerAvoid() => base.ShouldPlayerAvoid(); + float IBehaviorBackBridge.BackBridge_GetDefaultNavGoalTolerance() => base.GetDefaultNavGoalTolerance(); + bool IBehaviorBackBridge.BackBridge_IsCrouching() => base.IsCrouching(); + bool IBehaviorBackBridge.BackBridge_OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => base.OnCalcBaseMove(ref moveGoal, distClear, ref result); AI_BehaviorBase? CurBehavior; readonly List Behaviors = []; diff --git a/Game.Server/AI_Behavior_AI_BaseNPC_100000.cs b/Game.Server/AI_Behavior_AI_BaseNPC_100000.cs index a0b8e3b3f..e1350af4b 100644 --- a/Game.Server/AI_Behavior_AI_BaseNPC_100000.cs +++ b/Game.Server/AI_Behavior_AI_BaseNPC_100000.cs @@ -2,5 +2,41 @@ namespace Game.Server; public abstract class AI_Behavior_AI_BaseNPC_100000 : AI_ComponentWithOuter_AI_BaseNPC_AI_BehaviorBase { + const int ID_SPACE_OFFSET = 100000; + + public const int NEXT_TASK = ID_SPACE_OFFSET; + public const int NEXT_SCHEDULE = ID_SPACE_OFFSET; + public const int NEXT_CONDITION = ID_SPACE_OFFSET; + protected AI_Behavior_AI_BaseNPC_100000(AI_BaseNPC? outer = null) : base(outer) { } + + public void SetCondition(int condition) { + if (condition >= ID_SPACE_OFFSET && condition < ID_SPACE_OFFSET + 10000) + condition = GetClassScheduleIdSpace().ConditionLocalToGlobal(condition); + GetOuter()!.SetCondition(condition); + } + + public bool HasCondition(int condition) { + if (condition >= ID_SPACE_OFFSET && condition < ID_SPACE_OFFSET + 10000) + condition = GetClassScheduleIdSpace().ConditionLocalToGlobal(condition); + return GetOuter()!.HasCondition(condition); + } + + public bool HasInterruptCondition(int condition) { + if (condition >= ID_SPACE_OFFSET && condition < ID_SPACE_OFFSET + 10000) + condition = GetClassScheduleIdSpace().ConditionLocalToGlobal(condition); + return GetOuter()!.HasInterruptCondition(condition); + } + + public void ClearCondition(int condition) { + if (condition >= ID_SPACE_OFFSET && condition < ID_SPACE_OFFSET + 10000) + condition = GetClassScheduleIdSpace().ConditionLocalToGlobal(condition); + GetOuter()!.ClearCondition(condition); + } + + protected static AI_GlobalScheduleNamespace GetSchedulingSymbols() => AI_BaseNPC.GetSchedulingSymbols(); + + protected static AI_ClassScheduleIdSpace AccessClassScheduleIdSpaceDirect() => AI_BaseNPC.ClassScheduleIdSpace; + + protected override bool IsBehaviorSchedule(int scheduleType) => scheduleType >= ID_SPACE_OFFSET && scheduleType < ID_SPACE_OFFSET + 10000; } diff --git a/Game.Server/IBehaviorBackBridge.cs b/Game.Server/IBehaviorBackBridge.cs index 9c328ff66..ca06d0c09 100644 --- a/Game.Server/IBehaviorBackBridge.cs +++ b/Game.Server/IBehaviorBackBridge.cs @@ -4,4 +4,11 @@ public interface IBehaviorBackBridge { void BackBridge_GatherConditions(); int BackBridge_SelectSchedule(); + int BackBridge_TranslateSchedule(int scheduleType); + Activity BackBridge_NPC_TranslateActivity(Activity activity); + bool BackBridge_IsNavigationUrgent(); + bool BackBridge_ShouldPlayerAvoid(); + float BackBridge_GetDefaultNavGoalTolerance(); + bool BackBridge_IsCrouching(); + bool BackBridge_OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result); } From fed4aff4ad6bcf86e4ff5427fb460b055793b15b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:33:07 +0300 Subject: [PATCH 33/73] Port AI senses and NPC sensing --- Game.Server/AI_BaseNPC.cs | 222 ++++++++++++++++ Game.Server/AI_Default.cs | 3 + Game.Server/AI_Senses.cs | 526 +++++++++++++++++++++++++++++++++++++- Game.Server/BaseEntity.cs | 39 ++- 4 files changed, 788 insertions(+), 2 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index ac43ba520..46ff27f1b 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -113,6 +113,30 @@ public static class AI_BaseNPCGlobals public static readonly AI_Manager g_AI_Manager = new(); + public static bool FBoxVisible(BaseEntity looker, BaseEntity target, out Vector3 targetOrigin, float size = 0.0f) { + targetOrigin = default; + + if (((int)looker.GetWaterLevel() != 3 && (int)target.GetWaterLevel() == 3) + || ((int)looker.GetWaterLevel() == 3 && (int)target.GetWaterLevel() == 0)) + return false; + + Vector3 lookerOrigin = looker.EyePosition(); + for (int i = 0; i < 5; i++) { + Vector3 vecTarget = target.GetAbsOrigin(); + vecTarget.X += random.RandomFloat(target.WorldAlignMins().X + size, target.WorldAlignMaxs().X - size); + vecTarget.Y += random.RandomFloat(target.WorldAlignMins().Y + size, target.WorldAlignMaxs().Y - size); + vecTarget.Z += random.RandomFloat(target.WorldAlignMins().Z + size, target.WorldAlignMaxs().Z - size); + + Util.TraceLine(lookerOrigin, vecTarget, Mask.BlockLOS, looker, CollisionGroup.None, out Trace tr); + + if (tr.Fraction == 1.0) { + targetOrigin = vecTarget; + return true; + } + } + return false; + } + public static readonly Stopwatch g_AIRunTimer = new(); public static float g_NpcTimeThisFrame; @@ -441,6 +465,8 @@ public static ReadOnlySpan GetActivityName(Activity actID) { public OutputEvent OnLostEnemy = new(); public OutputEvent OnLostPlayer = new(); + public WorldSoundInstance LockedBestSound = new(); + static readonly BASEPTR CallNPCThinkPtr = static self => ((AI_BaseNPC)self).CallNPCThink(); public AI_BaseNPC() { @@ -2799,6 +2825,201 @@ public virtual bool QuerySeeEntity(BaseEntity entity, bool onlyHateOrFearIfNPC = return true; } + public virtual bool QueryHearSound(ref WorldSoundInstance sound) { + if ((sound.SoundContext() & SoundInstanceType.ContextCombineOnly) != 0) + return false; + + if ((sound.SoundContext() & SoundInstanceType.ContextAlliesOnly) != 0) { + if (!IsPlayerAlly()) + return false; + } + + if (sound.IsSoundType(SoundInstanceType.Player) && GetState() == NPCState.Idle && !FVisible(sound.GetSoundReactOrigin())) + return false; + + if (sound.IsSoundType(SoundInstanceType.Combat) && sound.SoundChannel() == SoundEntChannel.NPCFootstep) { + if (sound.Owner.Get() != null && sound.Owner.Get()!.ClassMatches(GetClassname())) + return false; + } + + if (ShouldIgnoreSound(ref sound)) + return false; + + return true; + } + + static readonly int[] LookConditionsToClear = [ + (int)SCOND_t.COND_SEE_HATE, + (int)SCOND_t.COND_SEE_DISLIKE, + (int)SCOND_t.COND_SEE_ENEMY, + (int)SCOND_t.COND_SEE_FEAR, + (int)SCOND_t.COND_SEE_NEMESIS, + (int)SCOND_t.COND_SEE_PLAYER, + (int)SCOND_t.COND_LOST_PLAYER, + (int)SCOND_t.COND_ENEMY_WENT_NULL, + ]; + + public virtual void OnLooked(int distance) { + bool hadSeePlayer = HasCondition((int)SCOND_t.COND_SEE_PLAYER); + + ClearConditions(LookConditionsToClear); + + BaseEntity? sightEnt = GetSenses()!.GetFirstSeenEntity(out AISightIter iter); + + while (sightEnt != null) { + if (sightEnt.IsPlayer()) { + SetCondition((int)SCOND_t.COND_SEE_PLAYER); + LastSawPlayerTime = gpGlobals.CurTime; + } + + Disposition relation = IRelationType(sightEnt); + + if (relation != Disposition.NU) { + if (sightEnt == GetEnemy()) + SetCondition((int)SCOND_t.COND_SEE_ENEMY); + + switch (relation) { + case Disposition.HT: { + int priority = IRelationPriority(sightEnt); + if (priority < 0) + SetCondition((int)SCOND_t.COND_SEE_DISLIKE); + else if (priority > 10) + SetCondition((int)SCOND_t.COND_SEE_NEMESIS); + else + SetCondition((int)SCOND_t.COND_SEE_HATE); + UpdateEnemyMemory(sightEnt, sightEnt.GetAbsOrigin()); + break; + } + case Disposition.FR: + UpdateEnemyMemory(sightEnt, sightEnt.GetAbsOrigin()); + SetCondition((int)SCOND_t.COND_SEE_FEAR); + break; + case Disposition.LI: + case Disposition.NU: + break; + default: + DevWarning(2, $"{GetClassname()} can't assess {sightEnt.GetClassname()}\n"); + break; + } + } + + sightEnt = GetSenses()!.GetNextSeenEntity(ref iter); + } + + if (hadSeePlayer && !HasCondition((int)SCOND_t.COND_SEE_PLAYER)) + SetCondition((int)SCOND_t.COND_LOST_PLAYER); + } + + static readonly int[] ListenConditionsToClear = [ + (int)SCOND_t.COND_HEAR_DANGER, + (int)SCOND_t.COND_HEAR_COMBAT, + (int)SCOND_t.COND_HEAR_WORLD, + (int)SCOND_t.COND_HEAR_PLAYER, + (int)SCOND_t.COND_HEAR_THUMPER, + (int)SCOND_t.COND_HEAR_BUGBAIT, + (int)SCOND_t.COND_HEAR_PHYSICS_DANGER, + (int)SCOND_t.COND_HEAR_BULLET_IMPACT, + (int)SCOND_t.COND_HEAR_MOVE_AWAY, + + (int)SCOND_t.COND_NO_HEAR_DANGER, + + (int)SCOND_t.COND_SMELL, + ]; + + public virtual void OnListened() { + ClearConditions(ListenConditionsToClear); + + ref WorldSoundInstance currentSound = ref GetSenses()!.GetFirstHeardSound(out int iter); + + while (!Unsafe.IsNullRef(ref currentSound)) { + int condition = (int)SCOND_t.COND_NONE; + + if (currentSound.FIsSound()) { + switch (currentSound.SoundTypeNoContext()) { + case SoundInstanceType.Danger: + if (gpGlobals.CurTime > IgnoreDangerSoundsUntil) + condition = (int)SCOND_t.COND_HEAR_DANGER; + break; + + case SoundInstanceType.Thumper: condition = (int)SCOND_t.COND_HEAR_THUMPER; break; + case SoundInstanceType.Bugbait: condition = (int)SCOND_t.COND_HEAR_BUGBAIT; break; + case SoundInstanceType.Combat: + if (currentSound.SoundChannel() == SoundEntChannel.SpookyNoise) + condition = (int)SCOND_t.COND_HEAR_SPOOKY; + else + condition = (int)SCOND_t.COND_HEAR_COMBAT; + break; + + case SoundInstanceType.World: condition = (int)SCOND_t.COND_HEAR_WORLD; break; + case SoundInstanceType.Player: condition = (int)SCOND_t.COND_HEAR_PLAYER; break; + case SoundInstanceType.BulletImpact: condition = (int)SCOND_t.COND_HEAR_BULLET_IMPACT; break; + case SoundInstanceType.PhysicsDanger: condition = (int)SCOND_t.COND_HEAR_PHYSICS_DANGER; break; + case SoundInstanceType.DangerSniperOnly: break; + case SoundInstanceType.MoveAway: condition = (int)SCOND_t.COND_HEAR_MOVE_AWAY; break; + case SoundInstanceType.PlayerVehicle: condition = (int)SCOND_t.COND_HEAR_PLAYER; break; + + default: + DevMsg($"**ERROR: NPC {GetClassname()} hearing sound of unknown type {(int)currentSound.SoundType()}!\n"); + break; + } + } + else + condition = (int)SCOND_t.COND_SMELL; + + if (condition != (int)SCOND_t.COND_NONE) + SetCondition(condition); + + currentSound = ref GetSenses()!.GetNextHeardSound(ref iter); + } + + if (!HasCondition((int)SCOND_t.COND_HEAR_DANGER)) + SetCondition((int)SCOND_t.COND_NO_HEAR_DANGER); + + if (HasCondition((int)SCOND_t.COND_HEAR_WORLD)) + OnHearWorld.FireOutput(this, this); + + if (HasCondition((int)SCOND_t.COND_HEAR_PLAYER)) + OnHearPlayer.FireOutput(this, this); + + if (HasCondition((int)SCOND_t.COND_HEAR_COMBAT) || + HasCondition((int)SCOND_t.COND_HEAR_BULLET_IMPACT) || + HasCondition((int)SCOND_t.COND_HEAR_DANGER)) { + OnHearCombat.FireOutput(this, this); + } + } + + public virtual ref WorldSoundInstance GetBestSound(SoundInstanceType validTypes = SoundInstanceType.AllSounds) { + if (LockedBestSound.Type != SoundInstanceType.None) + return ref LockedBestSound; + ref WorldSoundInstance result = ref GetSenses()!.GetClosestSound(false, validTypes); + if (Unsafe.IsNullRef(ref result)) + DevMsg("Warning: NULL Return from GetBestSound\n"); + return ref result; + } + + public ref WorldSoundInstance GetBestScent() { + ref WorldSoundInstance result = ref GetSenses()!.GetClosestSound(true); + if (Unsafe.IsNullRef(ref result)) + DevMsg("Warning: NULL Return from GetBestScent\n"); + return ref result; + } + + public void LockBestSound() { + UnlockBestSound(); + ref WorldSoundInstance bestSound = ref GetBestSound(); + if (!Unsafe.IsNullRef(ref bestSound)) + LockedBestSound = bestSound; + } + + public void UnlockBestSound() { + if (LockedBestSound.Type != SoundInstanceType.None) { + LockedBestSound.Type = SoundInstanceType.None; + OnListened(); + } + } + + public void PerformSensing() => GetSenses()!.PerformSensing(); + public void SetTarget(BaseEntity? target) => TargetEnt.Set(target); public float GetHullWidth() => NAI_Hull.Width(GetHullType()); @@ -4825,6 +5046,7 @@ public virtual void GatherConditions() { if (ShouldPlayIdleSound()) IdleSound(); + PerformSensing(); if (Weapon_IsBetterAvailable()) SetCondition((int)SCOND_t.COND_BETTER_WEAPON_AVAILABLE); diff --git a/Game.Server/AI_Default.cs b/Game.Server/AI_Default.cs index 850f4e08f..3fad11c84 100644 --- a/Game.Server/AI_Default.cs +++ b/Game.Server/AI_Default.cs @@ -1319,7 +1319,10 @@ public override void LevelInitPreEntity() { AI_BaseNPC.NextThinkRebalanceTick = 0; } + public override void LevelInitPostEntity() => g_AI_SensedObjectsManager.Init(); + public override void LevelShutdownPostEntity() { + g_AI_SensedObjectsManager.Term(); AI_NetworkManager.DeleteAllAINetworks(); g_AI_SchedulesManager.DeleteAllSchedules(); g_AI_SchedulesManager.DestroyStringRegistries(); diff --git a/Game.Server/AI_Senses.cs b/Game.Server/AI_Senses.cs index 61884389d..2c5b99963 100644 --- a/Game.Server/AI_Senses.cs +++ b/Game.Server/AI_Senses.cs @@ -1,14 +1,538 @@ +global using static Game.Server.AI_SensesGlobals; + +using Game.Shared; + +using Source; + +using System.Numerics; +using System.Runtime.CompilerServices; + namespace Game.Server; +public static class AI_SensesGlobals +{ + public static readonly AI_SensedObjectsManager g_AI_SensedObjectsManager = new(); +} + +public enum SeenType +{ + All = -1, + HighPriority = 0, + NPCs, + Misc +} + +[Flags] +public enum SensingFlags +{ + None = 0x00000000, + DontLook = 0x00000001, + DontListen = 0x00000002, +} + +public struct AISightIter +{ + public int Array; + public int Next; + public SeenType SeenArray; + public bool Done; +} + public class AI_Senses : AI_Component { + const float AI_STANDARD_NPC_SEARCH_TIME = .25f; + const float AI_EFFICIENT_NPC_SEARCH_TIME = .35f; + const float AI_HIGH_PRIORITY_SEARCH_TIME = 0.15f; + const float AI_MISC_SEARCH_TIME = 0.45f; + public AI_Senses() { LookDist = 2048; + LastLookDist = -1; + TimeLastLook = -1; + AudibleList = 0; + TimeLastLookHighPriority = -1; + TimeLastLookNPCs = -1; + TimeLastLookMisc = -1; + + SeenArrays = [SeenHighPriority, SeenNPCs, SeenMisc]; + SensingFlagsValue = SensingFlags.None; } + public float GetDistLook() => LookDist; public void SetDistLook(float distLook) => LookDist = distLook; - public bool CanHearSound(ref WorldSoundInstance sound) => throw new NotImplementedException(); + public bool CanHearSound(ref WorldSoundInstance sound) { + if (sound.Owner.Get() == GetOuter()) + return false; + + if (sound.Owner.Get() != null && sound.Owner.Get()!.IsPlayer() && g_IgnorePlayers.GetBool()) + return false; + + if (GetOuter()!.GetState() == NPCState.Script && sound.IsSoundType(SoundInstanceType.Danger)) + return false; + + if (GetOuter()!.IsInAScript()) + return false; + + float hearDistanceSq = sound.Volume() * GetOuter()!.HearingSensitivity(); + hearDistanceSq *= hearDistanceSq; + if (Vector3.DistanceSquared(sound.GetSoundOrigin(), GetOuter()!.EarPosition()) <= hearDistanceSq) + return GetOuter()!.QueryHearSound(ref sound); + + return false; + } + + public void Listen() { + AudibleList = SOUNDLIST_EMPTY; + + int soundMask = GetOuter()!.GetSoundInterests(); + + if (soundMask != (int)SoundInstanceType.None && !GetOuter()!.HasSpawnFlags(SF_NPC_WAIT_TILL_SEEN)) { + int iSound = SoundEnt.ActiveList(); + + while (iSound != SOUNDLIST_EMPTY) { + ref WorldSoundInstance currentSound = ref SoundEnt.SoundPointerForIndex(iSound); + + if (!Unsafe.IsNullRef(ref currentSound) && (soundMask & (int)currentSound.SoundType()) != 0 && CanHearSound(ref currentSound)) { + currentSound.NextAudible = AudibleList; + AudibleList = iSound; + } + + iSound = currentSound.NextSound(); + } + } + + GetOuter()!.OnListened(); + } + + public bool ShouldSeeEntity(BaseEntity sightEnt) { + if (sightEnt == GetOuter() || !sightEnt.IsAlive()) + return false; + + if (sightEnt.IsPlayer() && (sightEnt.GetFlags() & EntityFlags.NoTarget) != 0) + return false; + + if (sightEnt.IsPlayer() && g_IgnorePlayers.GetBool()) + return false; + + if ((sightEnt.SpawnFlags & SF_NPC_WAIT_TILL_SEEN) != 0) + return false; + + if (!sightEnt.CanBeSeenBy(GetOuter()!)) + return false; + + if (!GetOuter()!.QuerySeeEntity(sightEnt, true)) + return false; + + return true; + } + + public bool CanSeeEntity(BaseEntity? sightEnt) { + if (sightEnt != null && sightEnt.IsPlayer() && g_IgnorePlayers.GetBool()) + return false; + + return GetOuter()!.FInViewCone(sightEnt!) && GetOuter()!.FVisible(sightEnt!); + } + + public bool DidSeeEntity(BaseEntity? sightEnt) { + BaseEntity? testEnt = GetFirstSeenEntity(out AISightIter iter); + + while (testEnt != null) { + if (sightEnt == testEnt) + return true; + testEnt = GetNextSeenEntity(ref iter); + } + return false; + } + + void NoteSeenEntity(BaseEntity sightEnt) { + sightEnt.Link = GetOuter()!.Link; + GetOuter()!.Link = sightEnt; + } + + bool WaitingUntilSeen(BaseEntity sightEnt) { + if ((GetOuter()!.SpawnFlags & SF_NPC_WAIT_TILL_SEEN) != 0) { + if (sightEnt.IsPlayer()) { + BasePlayer? player = ToBasePlayer(sightEnt); + if (player != null + && player.FInViewCone(GetOuter()!) + && FBoxVisible(sightEnt, GetOuter()!, out _)) { + GetOuter()!.SpawnFlags &= ~SF_NPC_WAIT_TILL_SEEN; + return false; + } + } + return true; + } + + return false; + } + + bool SeeEntity(BaseEntity sightEnt) { + GetOuter()!.OnSeeEntity(sightEnt); + + NoteSeenEntity(sightEnt); + + return true; + } + + public BaseEntity? GetFirstSeenEntity(out AISightIter iter, SeenType seenType = SeenType.All) { + iter = default; + iter.SeenArray = seenType; + int firstArray = (seenType == SeenType.All) ? 0 : (int)seenType; + + for (int i = firstArray; i < SeenArrays.Length; i++) { + if (SeenArrays[i].Count != 0) { + iter.Array = i; + iter.Next = 1; + return SeenArrays[i][0].Get(); + } + } + + iter.Done = true; + return null; + } + + public BaseEntity? GetNextSeenEntity(ref AISightIter iter) { + if (!iter.Done) { + for (int i = iter.Array; i < SeenArrays.Length; i++) { + for (int j = iter.Next; j < SeenArrays[i].Count; j++) { + if (SeenArrays[i][j].Get() != null) { + iter.Array = i; + iter.Next = j + 1; + return SeenArrays[i][j].Get(); + } + } + iter.Next = 0; + + if (iter.SeenArray != SeenType.All) + break; + } + iter.Done = true; + } + return null; + } + + void BeginGather() => GetOuter()!.Link = null; + + void EndGather(int nSeen, List result) { + result.Clear(); + if (nSeen != 0) { + BaseEntity? current = GetOuter()!.Link; + for (int i = 0; i < nSeen; i++) { + Assert(current != null); + result.Add(current!.GetRefEHandle()); + current = current!.Link; + } + GetOuter()!.Link = null; + } + } + + public void Look(int distance) { + if (TimeLastLook != gpGlobals.CurTime || LastLookDist != distance) { + LookForHighPriorityEntities(distance); + LookForNPCs(distance); + LookForObjects(distance); + + LastLookDist = distance; + TimeLastLook = gpGlobals.CurTime; + } + + GetOuter()!.OnLooked(distance); + } + + bool Look(BaseEntity sightEnt) { + if (WaitingUntilSeen(sightEnt)) + return false; + + if (ShouldSeeEntity(sightEnt) && CanSeeEntity(sightEnt)) + return SeeEntity(sightEnt); + return false; + } + + int LookForHighPriorityEntities(int distance) { + int nSeen = 0; + if (gpGlobals.CurTime - TimeLastLookHighPriority > AI_HIGH_PRIORITY_SEARCH_TIME) { + TimeLastLookHighPriority = gpGlobals.CurTime; + + BeginGather(); + + float distSq = distance * distance; + Vector3 origin = GetOuter()!.GetAbsOrigin(); + + for (int i = 1; i <= gpGlobals.MaxClients; i++) { + BaseEntity? player = Util.PlayerByIndex(i); + + if (player != null) { + if (Vector3.DistanceSquared(origin, player.GetAbsOrigin()) < distSq && Look(player)) + nSeen++; + } + } + + EndGather(nSeen, SeenHighPriority); + } + else { + for (int i = SeenHighPriority.Count - 1; i >= 0; --i) { + if (SeenHighPriority[i].Get() == null) + FastRemove(SeenHighPriority, i); + } + nSeen = SeenHighPriority.Count; + } + + return nSeen; + } + + int LookForNPCs(int distance) { + bool removeStaleFromCache = false; + float distSq = distance * distance; + Vector3 origin = GetOuter()!.GetAbsOrigin(); + AI_Efficiency efficiency = GetOuter()!.GetEfficiency(); + float timeNPCs = (efficiency < AI_Efficiency.VeryEfficient) ? AI_STANDARD_NPC_SEARCH_TIME : AI_EFFICIENT_NPC_SEARCH_TIME; + if (gpGlobals.CurTime - TimeLastLookNPCs > timeNPCs) { + TimeLastLookNPCs = gpGlobals.CurTime; + + if (efficiency < AI_Efficiency.SuperEfficient) { + int i, nSeen = 0; + + BeginGather(); + + List ais = g_AI_Manager.AccessAIs(); + + for (i = 0; i < g_AI_Manager.NumAIs(); i++) { + if (ais[i] != GetOuter() && (ais[i].ShouldNotDistanceCull() || Vector3.DistanceSquared(origin, ais[i].GetAbsOrigin()) < distSq)) { + if (Look(ais[i])) + nSeen++; + } + } + + EndGather(nSeen, SeenNPCs); + + return nSeen; + } + + removeStaleFromCache = true; + } + + for (int i = SeenNPCs.Count - 1; i >= 0; --i) { + BaseEntity? seen = SeenNPCs[i].Get(); + if (seen == null) + FastRemove(SeenNPCs, i); + else if (removeStaleFromCache) { + if ((!((AI_BaseNPC)seen).ShouldNotDistanceCull() && + Vector3.DistanceSquared(origin, seen.GetAbsOrigin()) > distSq) || + !Look(seen)) + FastRemove(SeenNPCs, i); + } + } + + return SeenNPCs.Count; + } + + int LookForObjects(int distance) { + const EntityFlags BOX_QUERY_MASK = EntityFlags.Object; + int nSeen = 0; + + if (gpGlobals.CurTime - TimeLastLookMisc > AI_MISC_SEARCH_TIME) { + TimeLastLookMisc = gpGlobals.CurTime; + + BeginGather(); + + float distSq = distance * distance; + Vector3 origin = GetOuter()!.GetAbsOrigin(); + BaseEntity? ent = g_AI_SensedObjectsManager.GetFirst(out int iter); + while (ent != null) { + if ((ent.GetFlags() & BOX_QUERY_MASK) != 0) { + if (Vector3.DistanceSquared(origin, ent.GetAbsOrigin()) < distSq && Look(ent)) + nSeen++; + } + ent = g_AI_SensedObjectsManager.GetNext(ref iter); + } + + EndGather(nSeen, SeenMisc); + } + else { + for (int i = SeenMisc.Count - 1; i >= 0; --i) { + if (SeenMisc[i].Get() == null) + FastRemove(SeenMisc, i); + } + nSeen = SeenMisc.Count; + } + + return nSeen; + } + + static void FastRemove(List list, int i) { + list[i] = list[^1]; + list.RemoveAt(list.Count - 1); + } + + public TimeUnit_t GetTimeLastUpdate(BaseEntity? entity) { + if (entity == null) + return 0; + if (entity.IsPlayer()) + return TimeLastLookHighPriority; + if (entity.IsNPC()) + return TimeLastLookNPCs; + return TimeLastLookMisc; + } + + public ref WorldSoundInstance GetFirstHeardSound(out int iter) { + int first = AudibleList; + + if (first == SOUNDLIST_EMPTY) { + iter = SOUNDLIST_EMPTY; + return ref Unsafe.NullRef(); + } + + iter = first; + return ref SoundEnt.SoundPointerForIndex(first); + } + + public ref WorldSoundInstance GetNextHeardSound(scoped ref int iter) { + if (iter == SOUNDLIST_EMPTY) + return ref Unsafe.NullRef(); + + int current = SoundEnt.SoundPointerForIndex(iter).NextAudible; + if (current == SOUNDLIST_EMPTY) { + iter = SOUNDLIST_EMPTY; + return ref Unsafe.NullRef(); + } + + iter = current; + return ref SoundEnt.SoundPointerForIndex(current); + } + + public ref WorldSoundInstance GetClosestSound(bool scent = false, SoundInstanceType validTypes = SoundInstanceType.AllSounds | SoundInstanceType.AllScents, bool usePriority = true) { + float bestDist = MAX_COORD_RANGE * MAX_COORD_RANGE; + float dist; + SoundPriority bestPriority = SoundPriority.VeryLow; + + ref WorldSoundInstance result = ref Unsafe.NullRef(); + ref WorldSoundInstance current = ref GetFirstHeardSound(out int iter); + + Vector3 earPosition = GetOuter()!.EarPosition(); + + while (!Unsafe.IsNullRef(ref current)) { + if ((!scent && current.FIsSound()) || + (scent && current.FIsScent())) { + if (current.IsSoundType(validTypes) && !GetOuter()!.ShouldIgnoreSound(ref current)) { + if (!usePriority || GetOuter()!.GetSoundPriority(ref current) >= bestPriority) { + dist = (current.GetSoundOrigin() - earPosition).LengthSquared(); + + if (dist < bestDist) { + result = ref current; + bestDist = dist; + + bestPriority = GetOuter()!.GetSoundPriority(ref current); + } + } + } + } + + current = ref GetNextHeardSound(ref iter); + } + + return ref result; + } + + public void PerformSensing() { + if (!HasSensingFlags(SensingFlags.DontLook)) + Look((int)LookDist); + + if (!HasSensingFlags(SensingFlags.DontListen)) + Listen(); + } + + public void AddSensingFlags(SensingFlags flags) => SensingFlagsValue |= flags; + public void RemoveSensingFlags(SensingFlags flags) => SensingFlagsValue &= ~flags; + public bool HasSensingFlags(SensingFlags flags) => (SensingFlagsValue & flags) == flags; public float LookDist; + float LastLookDist; + TimeUnit_t TimeLastLook; + + int AudibleList; + + readonly List SeenHighPriority = []; + readonly List SeenNPCs = []; + readonly List SeenMisc = []; + + readonly List[] SeenArrays; + + TimeUnit_t TimeLastLookHighPriority; + TimeUnit_t TimeLastLookNPCs; + TimeUnit_t TimeLastLookMisc; + + SensingFlags SensingFlagsValue; +} + +public class AI_SensedObjectsManager : IEntityListener +{ + public void Init() { + BaseEntity? ent = null; + while ((ent = gEntList.NextEnt(ent)) != null) + OnEntitySpawned(ent); + + gEntList.AddListenerEntity(this); + } + + public void Term() { + gEntList.RemoveListenerEntity(this); + SensedObjects.Clear(); + } + + public BaseEntity? GetFirst(out int iter) { + if (SensedObjects.Count != 0) { + iter = 1; + return SensedObjects[0].Get(); + } + + iter = 0; + return null; + } + + public BaseEntity? GetNext(ref int iter) { + int i = iter; + if (i != 0 && i < SensedObjects.Count) { + iter++; + return SensedObjects[i].Get(); + } + + iter = 0; + return null; + } + + public virtual void AddEntity(BaseEntity entity) { + if (Find(entity) != -1) + return; + + Assert(!entity.IsPlayer() && !entity.IsNPC()); + + entity.AddFlag(EntityFlags.Object); + SensedObjects.Add(entity.GetRefEHandle()); + } + + public void OnEntitySpawned(BaseEntity entity) { + if ((entity.GetFlags() & EntityFlags.Object) != 0 && !entity.IsPlayer() && !entity.IsNPC()) + SensedObjects.Add(entity.GetRefEHandle()); + } + + public void OnEntityDeleted(BaseEntity entity) { + if ((entity.GetFlags() & EntityFlags.Object) != 0 && !entity.IsPlayer() && !entity.IsNPC()) { + int i = Find(entity); + if (i != -1) { + SensedObjects[i] = SensedObjects[^1]; + SensedObjects.RemoveAt(SensedObjects.Count - 1); + } + } + } + + int Find(BaseEntity entity) { + for (int i = 0; i < SensedObjects.Count; i++) { + if (SensedObjects[i].Get() == entity) + return i; + } + return -1; + } + + readonly List SensedObjects = []; } diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 19867f72e..8a9bb1242 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -3216,7 +3216,11 @@ public virtual void Teleport(Vector3? newPosition, QAngle? newAngles, Vector3? n public virtual bool CanBeHitByMeleeAttack(BaseEntity? attacker) => true; - public virtual bool FVisible(BaseEntity entity, Mask traceMask = Mask.BlockLOS) { + public bool FVisible(BaseEntity entity, Mask traceMask = Mask.BlockLOS) => FVisible(entity, traceMask, out _); + + public virtual bool FVisible(BaseEntity entity, Mask traceMask, out BaseEntity? blocker) { + blocker = null; + if ((entity.GetFlags() & EntityFlags.NoTarget) != 0) return false; @@ -3250,6 +3254,39 @@ public virtual bool FVisible(BaseEntity entity, Mask traceMask = Mask.BlockLOS) return true; } + blocker = tr.Ent; + + return false; + } + + return true; + } + + public virtual bool FVisible(in Vector3 vecTarget, Mask traceMask = Mask.BlockLOS) => FVisible(vecTarget, traceMask, out _); + + public virtual bool FVisible(in Vector3 vecTarget, Mask traceMask, out BaseEntity? blocker) { + blocker = null; + + Trace tr; + Vector3 vecLookerOrigin = EyePosition(); + + if (AI_BaseNPCGlobals.ai_LOS_mode.GetBool()) + Util.TraceLine(vecLookerOrigin, vecTarget, traceMask, this, Source.CollisionGroup.None, out tr); + else { + if (traceMask == Mask.BlockLOS) + traceMask = Mask.BlockLOSAndNPCs; + + if (IsPlayer()) { + traceMask |= (Mask)Contents.IgnoreNoDrawOpaque; + traceMask &= ~(Mask)Contents.BlockLOS; + } + + TraceFilterLOS traceFilter = new(this, Source.CollisionGroup.None); + Util.TraceLine(vecLookerOrigin, vecTarget, traceMask, ref traceFilter, out tr); + } + + if (tr.Fraction != 1.0) { + blocker = tr.Ent; return false; } From 40c3d08c6acf167f09afe7e2f5445a3cba0f4101 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:38:52 +0300 Subject: [PATCH 34/73] Port NPC enemy memory and enemy selection --- Game.Server/AI_BaseNPC.cs | 652 +++++++++++++++++++++++++++++++++++++- Game.Server/AI_Memory.cs | 385 ++++++++++++++++++++++ Game.Server/AI_Squad.cs | 28 ++ Game.Server/SimTimer.cs | 22 +- 4 files changed, 1077 insertions(+), 10 deletions(-) create mode 100644 Game.Server/AI_Memory.cs diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 46ff27f1b..87f8e59ff 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -60,6 +60,13 @@ public enum AI_DebugFlags StepAI = 0x00000002 } +public struct UnreachableEnt +{ + public EHANDLE UnreachableEntity; + public TimeUnit_t ExpireTime; + public Vector3 LocationWhenUnreachable; +} + public static class AI_BaseNPCGlobals { // TODO: Enum these @@ -105,6 +112,8 @@ public static class AI_BaseNPCGlobals public static readonly ConVar g_IgnorePlayers = new("ai_ignoreplayers", "0", FCvar.Notify); public static readonly ConVar ai_LOS_mode = new("ai_LOS_mode", "0", FCvar.Replicated); public static readonly ConVar ai_auto_contact_solver = new("ai_auto_contact_solver", "1"); + public static readonly ConVar ai_reaction_delay_idle = new("ai_reaction_delay_idle", "0.3"); + public static readonly ConVar ai_reaction_delay_alert = new("ai_reaction_delay_alert", "0.1"); public static bool ShouldUseEfficiency() => ai_use_think_optimizations.GetBool() && ai_use_efficiency.GetBool(); public static bool ShouldUseFrameThinkLimits() => ai_use_think_optimizations.GetBool() && ai_use_frame_think_limits.GetBool(); @@ -308,11 +317,17 @@ public static ReadOnlySpan GetActivityName(Activity actID) { DEFINE.KEYFIELD(nameof(SpawnEquipment), FieldType.String, "additionalequipment"), DEFINE.KEYFIELD(nameof(HintGroup), FieldType.String, "hintgroup"), DEFINE.KEYFIELD(nameof(HintGroupNavLimiting), FieldType.Boolean, "hintlimiting"), + DEFINE.KEYFIELD(nameof(IgnoreUnseenEnemies), FieldType.Boolean, "ignoreunseenenemies"), + DEFINE.KEYFIELD(nameof(EnemyFilterName), FieldType.String, "enemyfilter"), DEFINE.OUTPUT(nameof(OnHearWorld), "OnHearWorld", eventFuncs), DEFINE.OUTPUT(nameof(OnHearPlayer), "OnHearPlayer", eventFuncs), DEFINE.OUTPUT(nameof(OnHearCombat), "OnHearCombat", eventFuncs), + DEFINE.OUTPUT(nameof(OnFoundEnemy), "OnFoundEnemy", eventFuncs), + DEFINE.OUTPUT(nameof(OnLostEnemyLOS), "OnLostEnemyLOS", eventFuncs), DEFINE.OUTPUT(nameof(OnLostEnemy), "OnLostEnemy", eventFuncs), + DEFINE.OUTPUT(nameof(OnFoundPlayer), "OnFoundPlayer", eventFuncs), + DEFINE.OUTPUT(nameof(OnLostPlayerLOS), "OnLostPlayerLOS", eventFuncs), DEFINE.OUTPUT(nameof(OnLostPlayer), "OnLostPlayer", eventFuncs), ]); public override DataMap? GetDataDescMap() => DataDesc; @@ -464,8 +479,23 @@ public static ReadOnlySpan GetActivityName(Activity actID) { public OutputEvent OnHearCombat = new(); public OutputEvent OnLostEnemy = new(); public OutputEvent OnLostPlayer = new(); - + public OutputEHANDLE OnFoundEnemy = new(); + public OutputEvent OnLostEnemyLOS = new(); + public OutputEHANDLE OnFoundPlayer = new(); + public OutputEvent OnLostPlayerLOS = new(); + + public readonly AI_Enemies Enemies = new(); + public bool IgnoreUnseenEnemies; + public TimeUnit_t AcceptableTimeSeenEnemy; + public readonly SimpleSimTimer FailChooseEnemyTimer = new(); + public readonly SimpleSimTimer UpdateEnemyPosTimer = new(); + public bool SkippedChooseEnemy; public WorldSoundInstance LockedBestSound = new(); + public Handle EnemyFilter = new(); + public string? EnemyFilterName; + public EHANDLE EnemyOccluder = new(); + public SquadSlot MySquadSlot = SquadSlot.None; + public readonly List UnreachableEnts = []; static readonly BASEPTR CallNPCThinkPtr = static self => ((AI_BaseNPC)self).CallNPCThink(); @@ -2720,7 +2750,41 @@ public void RelaxAim() { SetPoseParameter(PoseAim_Yaw, newYaw); } - public Vector3 GetEnemyLKP() => throw new NotImplementedException(); + public AI_Enemies GetEnemies() => Enemies; + + public Vector3 GetEnemyLKP() => GetEnemies().LastKnownPosition(GetEnemy()); + public TimeUnit_t GetEnemyLastTimeSeen() => GetEnemies().LastTimeSeen(GetEnemy()); + public void MarkEnemyAsEluded() => GetEnemies().MarkAsEluded(GetEnemy()); + public void ClearEnemyMemory() => GetEnemies().ClearMemory(GetEnemy()); + public bool EnemyHasEludedMe() => GetEnemies().HasEludedMe(GetEnemy()); + + public virtual float GetReactionDelay(BaseEntity? enemy) { + return (NPCState == NPCState.Alert || NPCState == NPCState.Combat) ? + ai_reaction_delay_alert.GetFloat() : + ai_reaction_delay_idle.GetFloat(); + } + + public bool UpdateEnemyMemory(BaseEntity? enemy, in Vector3 position, BaseEntity? informer = null) { + bool firstHand = (informer == null || informer == this); + + if (GetEnemies() != null) { + if (GetEnemies().HasEludedMe(enemy)) + FoundEnemySound(); + float reactionDelay = (informer == null || informer == this) ? GetReactionDelay(enemy) : 0.0f; + bool result = GetEnemies().UpdateMemory(GetNavigator()!.GetNetwork(), enemy, position, reactionDelay, firstHand); + + if (!firstHand && enemy != null && result && GetState() == NPCState.Idle) + ForceDecisionThink(); + + if (firstHand && enemy != null && Squad != null) + Squad.UpdateEnemyMemory(this, enemy, position); + return result; + } + return true; + } + + public void SetEnemyOccluder(BaseEntity? blocker) => EnemyOccluder.Set(blocker); + public BaseEntity? GetEnemyOccluder() => EnemyOccluder.Get(); public virtual Vector3 GetShootEnemyDir(in Vector3 shootOrigin, bool noisy = true) { BaseEntity? enemy = GetEnemy(); @@ -5048,6 +5112,9 @@ public virtual void GatherConditions() { PerformSensing(); + GetEnemies().RefreshMemories(); + ChooseEnemy(); + if (Weapon_IsBetterAvailable()) SetCondition((int)SCOND_t.COND_BETTER_WEAPON_AVAILABLE); @@ -5072,15 +5139,566 @@ public virtual void GatherConditions() { SetEnemy(null); } + if (GetTarget() != null) + CheckTarget(GetTarget()!); + CheckAmmo(); CheckFlinches(); + + CheckSquad(); } else ClearCondition((int)SCOND_t.COND_IN_PVS); } - public virtual void GatherEnemyConditions(BaseEntity enemy) => throw new NotImplementedException(); + public virtual void GatherEnemyConditions(BaseEntity enemy) { + ClearCondition((int)SCOND_t.COND_ENEMY_FACING_ME); + ClearCondition((int)SCOND_t.COND_BEHIND_ENEMY); + + if (HasCondition((int)SCOND_t.COND_NEW_ENEMY) || GetSenses()!.GetTimeLastUpdate(GetEnemy()) == gpGlobals.CurTime) { + ClearCondition((int)SCOND_t.COND_HAVE_ENEMY_LOS); + ClearCondition((int)SCOND_t.COND_ENEMY_OCCLUDED); + + BaseEntity? blocker = null; + SetEnemyOccluder(null); + + bool sensesDidSee = GetSenses()!.DidSeeEntity(enemy); + + if (!sensesDidSee && ((EnemyDistance(enemy) >= GetSenses()!.GetDistLook()) || !FVisible(enemy, Mask.BlockLOS, out blocker))) { + SetEnemyOccluder(blocker); + SetCondition((int)SCOND_t.COND_ENEMY_OCCLUDED); + ClearCondition((int)SCOND_t.COND_SEE_ENEMY); + + if (HasMemory(AI_MemoryFlags.HadLOS)) { + if (GetEnemy()!.IsPlayer()) + OnLostPlayerLOS.FireOutput(GetEnemy(), this); + OnLostEnemyLOS.FireOutput(GetEnemy(), this); + } + Forget(AI_MemoryFlags.HadLOS); + } + else { + SetCondition((int)SCOND_t.COND_HAVE_ENEMY_LOS); + + if (sensesDidSee) + SetCondition((int)SCOND_t.COND_SEE_ENEMY); + else + ClearCondition((int)SCOND_t.COND_SEE_ENEMY); + + if (!HasMemory(AI_MemoryFlags.HadLOS)) { + EHANDLE hEnemy = new(); + hEnemy.Set(GetEnemy()); + + if (GetEnemy()!.IsPlayer()) { + OnFoundPlayer.Set(hEnemy, this, this); + OnFoundEnemy.Set(hEnemy, this, this); + } + else + OnFoundEnemy.Set(hEnemy, this, this); + } + Remember(AI_MemoryFlags.HadLOS); + } + } + + if (!enemy.IsAlive()) { + SetCondition((int)SCOND_t.COND_ENEMY_DEAD); + ClearCondition((int)SCOND_t.COND_SEE_ENEMY); + ClearCondition((int)SCOND_t.COND_ENEMY_OCCLUDED); + return; + } + + float distToEnemy = EnemyDistance(enemy); + + if (HasCondition((int)SCOND_t.COND_SEE_ENEMY)) { + if (enemy.GetSmoothedVelocity() != vec3_origin) { + Vector3 trailPos = enemy.GetAbsOrigin() - enemy.GetSmoothedVelocity() * random.RandomFloat(-0.05f, 0); + UpdateEnemyMemory(enemy, trailPos); + } + else + UpdateEnemyMemory(enemy, enemy.GetAbsOrigin()); + + if (enemy is BaseCombatCharacter enemyBCC && enemyBCC.FInViewCone(this)) { + SetCondition((int)SCOND_t.COND_ENEMY_FACING_ME); + ClearCondition((int)SCOND_t.COND_BEHIND_ENEMY); + } + else { + ClearCondition((int)SCOND_t.COND_ENEMY_FACING_ME); + SetCondition((int)SCOND_t.COND_BEHIND_ENEMY); + } + } + else if ((!HasCondition((int)SCOND_t.COND_ENEMY_OCCLUDED) && !HasCondition((int)SCOND_t.COND_SEE_ENEMY)) && (distToEnemy <= 256)) + UpdateEnemyMemory(enemy, enemy.GetAbsOrigin(), enemy); + + float tooFar = DistTooFar; + if (GetActiveWeapon() != null && HasCondition((int)SCOND_t.COND_SEE_ENEMY)) + tooFar = Math.Max(DistTooFar, GetActiveWeapon()!.MaxRange1); + + if (distToEnemy >= tooFar) + SetCondition((int)SCOND_t.COND_ENEMY_TOO_FAR); + else + ClearCondition((int)SCOND_t.COND_ENEMY_TOO_FAR); + + if (FCanCheckAttacks()) + GatherAttackConditions(GetEnemy()!, distToEnemy); + else + ClearAttackConditions(); + + UpdateEnemyPos(); + + UpdateTargetPos(); + + if (GetNavigator()!.IsOnNetwork()) { + if (IsUnreachable(GetEnemy())) + SetCondition((int)SCOND_t.COND_ENEMY_UNREACHABLE); + } + + if (gpGlobals.CurTime - GetEnemyLastTimeSeen() > 8) { + Vector3 enemyLKP = GetEnemyLKP(); + if (((enemyLKP - GetAbsOrigin()).AsVector2D().Length() < 48) && + !HasCondition((int)SCOND_t.COND_SEE_ENEMY)) { + MarkEnemyAsEluded(); + } + + if (!HasCondition((int)SCOND_t.COND_SEE_ENEMY) && HasCondition((int)SCOND_t.COND_ENEMY_UNREACHABLE)) { + if (!FVisible(enemyLKP)) + MarkEnemyAsEluded(); + } + } + } + + public virtual void GatherAttackConditions(BaseEntity target, float dist) => throw new NotImplementedException(); + + public virtual bool FCanCheckAttacks() { + if (GetNavType() == Navigation.Climb || GetNavType() == Navigation.Jump) + return false; + + if (HasCondition((int)SCOND_t.COND_SEE_ENEMY) && !HasCondition((int)SCOND_t.COND_ENEMY_TOO_FAR)) + return true; + + return false; + } + + public virtual float GetGoalRepathTolerance(BaseEntity goalEnt, NavGoalType type, in Vector3 curGoal, in Vector3 curTargetPos) { + float distToGoal = (GetAbsOrigin() - curTargetPos).Length() - GetNavigator()!.GetArrivalDistance(); + float distMoved1Sec = GetSmoothedVelocity().Length(); + float result = 120; + + if (distMoved1Sec > 0.0) { + float t = distToGoal / distMoved1Sec; + + result = Math.Clamp(120.0f * t, 0.0f, 120.0f); + } + + if (!goalEnt.IsPlayer()) + result *= 1.20f; + + return result; + } + + public void UpdateEnemyPos() { + if (!GetNavigator()!.IsInterruptable()) + return; + + if (AnyUpdateEnemyPosTimer.Expired() && UpdateEnemyPosTimer.Expired()) { + if (GetNavigator()!.GetGoalType() == NavGoalType.Enemy) { + if (Enemy.Get() != GetNavigator()!.GetGoalTarget()) + GetNavigator()!.SetGoalTarget(Enemy.Get(), vec3_origin); + else { + Vector3 enemyLKP = GetEnemyLKP(); + TranslateNavGoal(GetEnemy(), ref enemyLKP); + float tolerance = GetGoalRepathTolerance(GetEnemy()!, NavGoalType.Enemy, GetNavigator()!.GetGoalPos(), enemyLKP); + if ((GetNavigator()!.GetGoalPos() - enemyLKP).Length() > tolerance) { + AnyUpdateEnemyPosTimer.Set(0.1f); + if (!GetNavigator()!.RefindPathToGoal(false)) + TaskFail(AI_TaskFailureCode.NoRoute); + } + } + } + } + } + + public void UpdateTargetPos() { + if (!GetNavigator()!.IsInterruptable()) + return; + + if (GetNavigator()!.GetGoalType() == NavGoalType.TargetEnt) { + if (TargetEnt.Get() != GetNavigator()!.GetGoalTarget()) + GetNavigator()!.SetGoalTarget(TargetEnt.Get(), vec3_origin); + else if ((GetNavigator()!.GetGoalFlags() & AI_NavGoalFlags.UpdateTargetPos) != 0) { + if (GetTarget() == null || (GetNavigator()!.GetGoalPos() - GetTarget()!.GetAbsOrigin()).Length() > GetGoalRepathTolerance(GetTarget()!, NavGoalType.TargetEnt, GetNavigator()!.GetGoalPos(), GetTarget()!.GetAbsOrigin())) { + if (!GetNavigator()!.RefindPathToGoal(false)) + TaskFail(AI_TaskFailureCode.NoRoute); + } + } + } + } + + public void CheckTarget(BaseEntity target) { + ClearCondition((int)SCOND_t.COND_HAVE_TARGET_LOS); + ClearCondition((int)SCOND_t.COND_TARGET_OCCLUDED); + + if ((EnemyDistance(target) >= GetSenses()!.GetDistLook()) || !FVisible(target)) + SetCondition((int)SCOND_t.COND_TARGET_OCCLUDED); + else + SetCondition((int)SCOND_t.COND_HAVE_TARGET_LOS); + + UpdateTargetPos(); + } + + public void RememberUnreachable(BaseEntity entity, float duration = -1) { + if (entity == GetEnemy()) + ForceChooseNewEnemy(); + + float NPC_UNREACHABLE_TIMEOUT = (duration > 0.0) ? duration : 3; + for (int i = UnreachableEnts.Count - 1; i >= 0; i--) { + if (entity == UnreachableEnts[i].UnreachableEntity.Get()) { + UnreachableEnt existing = UnreachableEnts[i]; + existing.ExpireTime = gpGlobals.CurTime + NPC_UNREACHABLE_TIMEOUT; + existing.LocationWhenUnreachable = entity.GetAbsOrigin(); + UnreachableEnts[i] = existing; + return; + } + } + + UnreachableEnt added = new() { + ExpireTime = gpGlobals.CurTime + NPC_UNREACHABLE_TIMEOUT, + LocationWhenUnreachable = entity.GetAbsOrigin() + }; + added.UnreachableEntity.Set(entity); + UnreachableEnts.Add(added); + } + + public bool IsUnreachable(BaseEntity? entity) { + float UNREACHABLE_DIST_TOLERANCE_SQ = 120 * 120; + + for (int i = UnreachableEnts.Count - 1; i >= 0; i--) { + if (UnreachableEnts[i].UnreachableEntity.Get() == null) + FastRemoveUnreachable(i); + else if (entity == UnreachableEnts[i].UnreachableEntity.Get()) { + if (gpGlobals.CurTime > UnreachableEnts[i].ExpireTime || + Vector3.DistanceSquared(entity.GetAbsOrigin(), UnreachableEnts[i].LocationWhenUnreachable) > UNREACHABLE_DIST_TOLERANCE_SQ) { + FastRemoveUnreachable(i); + return false; + } + return true; + } + } + return false; + } + + void FastRemoveUnreachable(int i) { + UnreachableEnts[i] = UnreachableEnts[^1]; + UnreachableEnts.RemoveAt(UnreachableEnts.Count - 1); + } + + public void ForceChooseNewEnemy() => EnemiesSerialNumber = -1; + + public bool DidChooseEnemy() => !SkippedChooseEnemy; + + public TimeUnit_t GetAcceptableTimeSeenEnemy() => AcceptableTimeSeenEnemy; + + public virtual float EnemyDistTolerance() => 0; + + public virtual bool ShouldChooseNewEnemy() { + BaseEntity? enemy = GetEnemy(); + if (enemy != null) { + if (GetEnemies().GetSerialNumber() != EnemiesSerialNumber) + return true; + + EnemiesSerialNumber = GetEnemies().GetSerialNumber(); + + if (EnemyHasEludedMe() || (IRelationType(enemy) != Disposition.HT && IRelationType(enemy) != Disposition.FR) || !IsValidEnemy(enemy)) + return true; + if (HasCondition((int)SCOND_t.COND_SEE_HATE) || HasCondition((int)SCOND_t.COND_SEE_DISLIKE) || HasCondition((int)SCOND_t.COND_SEE_NEMESIS) || HasCondition((int)SCOND_t.COND_SEE_FEAR)) + return true; + if (!enemy.IsAlive()) { + if (GiveUpOnDeadEnemyTimer.IsRunning()) { + if (GiveUpOnDeadEnemyTimer.Expired()) + return true; + } + else + GiveUpOnDeadEnemyTimer.Start(); + } + + AI_EnemyInfo? info = GetEnemies().Find(enemy); + + if (FailChooseEnemyTimer.Expired()) { + FailChooseEnemyTimer.Set(1.5f); + if (HasCondition((int)SCOND_t.COND_TASK_FAILED) || + (info != null && (info.TimeAtFirstHand == AI_INVALID_TIME || gpGlobals.CurTime - info.TimeLastSeen > 10))) { + return true; + } + } + + if (info != null && info.TimeValidEnemy < gpGlobals.CurTime) + return false; + } + + EnemiesSerialNumber = GetEnemies().GetSerialNumber(); + + return true; + } + + public bool ChooseEnemy() { + BaseEntity? initialEnemy = GetEnemy(); + BaseEntity? chosenEnemy = initialEnemy; + + bool hadEnemy = HasMemory(AI_MemoryFlags.HadEnemy | AI_MemoryFlags.HadPlayer); + bool enemyWasPlayer = HasMemory(AI_MemoryFlags.HadPlayer); + bool enemyWentNull = (hadEnemy && initialEnemy == null); + bool enemyEluded = (enemyWentNull || (initialEnemy != null && GetEnemies().HasEludedMe(initialEnemy))); + + bool haveCondNewEnemy; + bool haveCondLostEnemy; + + if (!ScheduleState.ScheduleWasInterrupted && GetCurSchedule() != null && !FScheduleDone()) { + Assert(InterruptFromCondition((int)SCOND_t.COND_NEW_ENEMY) == (int)SCOND_t.COND_NEW_ENEMY && InterruptFromCondition((int)SCOND_t.COND_LOST_ENEMY) == (int)SCOND_t.COND_LOST_ENEMY); + haveCondNewEnemy = GetCurSchedule()!.HasInterrupt((int)SCOND_t.COND_NEW_ENEMY); + haveCondLostEnemy = GetCurSchedule()!.HasInterrupt((int)SCOND_t.COND_LOST_ENEMY); + + if (!haveCondNewEnemy) + haveCondNewEnemy = IsCustomInterruptConditionSet((int)SCOND_t.COND_NEW_ENEMY); + if (!haveCondLostEnemy) + haveCondLostEnemy = IsCustomInterruptConditionSet((int)SCOND_t.COND_LOST_ENEMY); + } + else { + haveCondNewEnemy = true; + haveCondLostEnemy = true; + } + + if (!enemyWentNull) { + if (!haveCondNewEnemy && !(haveCondLostEnemy && enemyEluded)) { + SkippedChooseEnemy = true; + + return (chosenEnemy != null); + } + } + else if (!haveCondNewEnemy && !haveCondLostEnemy && GetCurSchedule() != null) + DevMsg(2, $"WARNING: AI enemy went NULL but schedule ({GetCurSchedule()!.GetName()}) is not interested\n"); + + SkippedChooseEnemy = false; + + if (ShouldChooseNewEnemy()) + chosenEnemy = BestEnemy(); + + bool changingEnemy = (chosenEnemy != initialEnemy); + + if (changingEnemy || enemyWentNull) { + Forget(AI_MemoryFlags.HadEnemy | AI_MemoryFlags.HadPlayer); + + if (initialEnemy != null && !initialEnemy.IsAlive()) + SetCondition((int)SCOND_t.COND_ENEMY_DEAD); + + SetEnemy(chosenEnemy); + + if (hadEnemy) { + VacateStrategySlot(); + + Forget(AI_MemoryFlags.HadLOS); + } + + if (chosenEnemy == null) { + if (!HasCondition((int)SCOND_t.COND_ENEMY_DEAD)) + SetCondition((int)SCOND_t.COND_ENEMY_WENT_NULL); + + if (enemyEluded) { + SetCondition((int)SCOND_t.COND_LOST_ENEMY); + LostEnemySound(); + } + + if (enemyWasPlayer) + OnLostPlayer.FireOutput(initialEnemy, this); + OnLostEnemy.FireOutput(initialEnemy, this); + } + else + Remember((chosenEnemy.IsPlayer()) ? AI_MemoryFlags.HadPlayer : AI_MemoryFlags.HadEnemy); + } + + return (chosenEnemy != null); + } + + public virtual BaseEntity? BestEnemy() { + BaseEntity? bestEnemy = null; + int bestDistSq = (int)(MAX_COORD_RANGE * MAX_COORD_RANGE); + int bestPriority = -1000; + bool bestUnreachable = true; + ThreeState bestSeen = ThreeState.None; + ThreeState bestVisible = ThreeState.None; + int distSq; + bool unreachable = false; + + for (AI_EnemyInfo? eMemory = GetEnemies().GetFirst(out int iter); eMemory != null; eMemory = GetEnemies().GetNext(ref iter)) { + BaseEntity? enemy = eMemory.Enemy.Get(); + + if (enemy == null || !enemy.IsAlive()) + continue; + + if (g_IgnorePlayers.GetBool() && enemy.IsPlayer()) + continue; + + if ((enemy.GetFlags() & EntityFlags.NoTarget) != 0) + continue; + + if (IgnoreUnseenEnemies) { + const float TIME_CONSIDER_ENEMY_UNSEEN = .4f; + if (eMemory.TimeLastSeen < gpGlobals.CurTime - TIME_CONSIDER_ENEMY_UNSEEN) + continue; + } + + Disposition relation = IRelationType(enemy); + if (relation != Disposition.HT && relation != Disposition.FR) + continue; + + if (AcceptableTimeSeenEnemy > 0.0 && eMemory.TimeLastSeen < AcceptableTimeSeenEnemy) + continue; + + if (eMemory.TimeValidEnemy > gpGlobals.CurTime) + continue; + + if (eMemory.EludedMe) + continue; + + if (relation == Disposition.FR && !eMemory.Unforgettable && eMemory.TimeFirstSeen == AI_INVALID_TIME) + continue; + + if (!IsValidEnemy(enemy)) + continue; + + unreachable = IsUnreachable(enemy); + + if (!bestUnreachable && unreachable) + continue; + + if (bestUnreachable && !unreachable) { + bestPriority = IRelationPriority(enemy); + bestDistSq = (int)(enemy.GetAbsOrigin() - GetAbsOrigin()).LengthSquared(); + bestEnemy = enemy; + bestUnreachable = unreachable; + bestSeen = ThreeState.None; + bestVisible = ThreeState.None; + } + else if (IRelationPriority(enemy) > bestPriority) { + bestPriority = IRelationPriority(enemy); + bestDistSq = (int)(enemy.GetAbsOrigin() - GetAbsOrigin()).LengthSquared(); + bestEnemy = enemy; + bestUnreachable = unreachable; + bestSeen = ThreeState.None; + bestVisible = ThreeState.None; + } + else if (IRelationPriority(enemy) == bestPriority) { + distSq = (int)(enemy.GetAbsOrigin() - GetAbsOrigin()).LengthSquared(); + + bool acceptCurrent = false; + bool closer = ((bestDistSq - distSq) > EnemyDistTolerance()); + ThreeState curSeen = ThreeState.None; + ThreeState curVisible = ThreeState.None; + + if (!closer) { + if (bestSeen == ThreeState.True || bestVisible == ThreeState.True) + continue; + } + + if (closer) { + if (bestSeen == ThreeState.False && bestVisible == ThreeState.False) + acceptCurrent = true; + } + + if (!acceptCurrent) { + if (closer) { + curSeen = (GetSenses()!.DidSeeEntity(enemy)) ? ThreeState.True : ThreeState.False; + + acceptCurrent = (curSeen == ThreeState.True); + } + } + + if (!acceptCurrent) { + if (!closer) { + if (bestSeen == ThreeState.None) + bestSeen = (GetSenses()!.DidSeeEntity(bestEnemy)) ? ThreeState.True : ThreeState.False; + + if (bestSeen == ThreeState.True) + continue; + } + + if (closer && bestVisible == ThreeState.None) { + curVisible = ((EnemyDistance(enemy) < GetSenses()!.GetDistLook()) && FVisible(enemy)) ? ThreeState.True : ThreeState.False; + + acceptCurrent = (curVisible == ThreeState.True); + } + + if (!acceptCurrent) { + if (bestSeen == ThreeState.None) + bestSeen = (GetSenses()!.DidSeeEntity(bestEnemy)) ? ThreeState.True : ThreeState.False; + + if (bestVisible == ThreeState.None) + bestVisible = ((EnemyDistance(bestEnemy!) < GetSenses()!.GetDistLook()) && FVisible(bestEnemy!)) ? ThreeState.True : ThreeState.False; + + if (curSeen == ThreeState.None) + curSeen = (GetSenses()!.DidSeeEntity(enemy)) ? ThreeState.True : ThreeState.False; + + if (curVisible == ThreeState.None) + curVisible = ((EnemyDistance(enemy) < GetSenses()!.GetDistLook()) && FVisible(enemy)) ? ThreeState.True : ThreeState.False; + + bool bestSeenOrVisible = (bestSeen == ThreeState.True || bestVisible == ThreeState.True); + bool curSeenOrVisible = (curSeen == ThreeState.True || curVisible == ThreeState.True); + + if (!closer) { + if (bestSeenOrVisible) + continue; + else if (!curSeenOrVisible) + continue; + } + else { + if (!curSeenOrVisible && bestSeenOrVisible) + continue; + } + } + } + + bestSeen = curSeen; + bestVisible = curVisible; + bestDistSq = distSq; + bestPriority = IRelationPriority(enemy); + bestEnemy = enemy; + bestUnreachable = unreachable; + } + } + + return bestEnemy; + } + + public bool IsInSquad() => Squad != null; + public AI_Squad? GetSquad() => Squad; + + public void CheckSquad() { + if (!IsInSquad()) + return; + + if (!GetSquad()!.IsLeader(this)) + return; + + if (VPhysicsGetObject() != null && (VPhysicsGetObject()!.GetGameFlags() & PhysicsFlags.PlayerHeld) != 0) + return; + + AI_BaseNPC? squadmate = Squad!.GetFirstMember(out int iter); + while (squadmate != null) { + if (IRelationType(squadmate) < Disposition.LI) { + bool warn = true; + + if (squadmate.VPhysicsGetObject() != null) { + if ((squadmate.VPhysicsGetObject()!.GetGameFlags() & PhysicsFlags.PlayerHeld) != 0) + warn = false; + } + + if (warn) { + Warning($"ERROR: Squad '{GetSquad()!.GetName()}' has enemies in it!\n"); + Warning($"{GetDebugName()} doesn't like {squadmate.GetDebugName()}\n\n"); + } + } + + squadmate = Squad.GetNextMember(ref iter); + } + } public virtual void CheckAmmo() { } @@ -5284,7 +5902,26 @@ public void ForceDecisionThink() { SetEfficiency(AI_Efficiency.Normal); } - public virtual bool IsValidEnemy(BaseEntity enemy) => throw new NotImplementedException(); + public override void Activate() { + base.Activate(); + + if (EnemyFilterName != null) { + BaseEntity? filter = gEntList.FindEntityByName(null, EnemyFilterName); + if (filter != null) + EnemyFilter.Set(filter as BaseFilter); + } + } + + public virtual bool IsValidEnemy(BaseEntity enemy) { + AI_BaseNPC? enemyNPC = enemy.MyNPCPointer(); + if (enemyNPC != null && enemyNPC.CanBeAnEnemyOf(this) == false) + return false; + + if (EnemyFilter.Get() != null && EnemyFilter.Get()!.PassesFilter(this, enemy) == false) + return false; + + return true; + } public virtual bool CanBeAnEnemyOf(BaseEntity enemy) { if (GetSleepState() > AI_SleepState.WaitingForThreat) @@ -5410,7 +6047,12 @@ public virtual float GetTimeToNavGoal() { return 0.0f; } - public void VacateStrategySlot() => throw new NotImplementedException(); + public void VacateStrategySlot() { + if (Squad != null) { + Squad.VacateStrategySlot(GetEnemy(), MySquadSlot); + MySquadSlot = SquadSlot.None; + } + } public virtual bool CreateVPhysics() { if (IsAlive() && VPhysicsGetObject() == null) diff --git a/Game.Server/AI_Memory.cs b/Game.Server/AI_Memory.cs new file mode 100644 index 000000000..bb193870e --- /dev/null +++ b/Game.Server/AI_Memory.cs @@ -0,0 +1,385 @@ +global using static Game.Server.AI_MemoryGlobals; + +using Game.Shared; + +using Source; + +using System.Numerics; + +namespace Game.Server; + +public static class AI_MemoryGlobals +{ + public const float AI_DEF_ENEMY_DISCARD_TIME = 60.0f; + public const TimeUnit_t AI_INVALID_TIME = -float.MaxValue; + public const float AI_FREE_KNOWLEDGE_DURATION = 1.75f; +} + +public class AI_EnemyInfo +{ + public AI_EnemyInfo() { + Enemy.Set(null); + LastKnownLocation = vec3_origin; + LastSeenLocation = vec3_origin; + TimeLastSeen = 0; + TimeFirstSeen = 0; + TimeLastReacquired = 0; + TimeValidEnemy = 0; + TimeLastReceivedDamageFrom = 0; + TimeAtFirstHand = AI_INVALID_TIME; + DangerMemory = false; + EludedMe = false; + Unforgettable = false; + MobbedMe = false; + } + + public EHANDLE Enemy = new(); + + public Vector3 LastKnownLocation; + public Vector3 LastSeenLocation; + public TimeUnit_t TimeLastSeen; + public TimeUnit_t TimeFirstSeen; + public TimeUnit_t TimeLastReacquired; + public TimeUnit_t TimeValidEnemy; + public TimeUnit_t TimeLastReceivedDamageFrom; + public TimeUnit_t TimeAtFirstHand; + public bool DangerMemory; + public bool EludedMe; + public bool Unforgettable; + public bool MobbedMe; +} + +public class AI_Enemies +{ + readonly record struct MemoryEntry(BaseEntity? Key, AI_EnemyInfo Info); + + public AI_Enemies() { + FreeKnowledgeDuration = AI_FREE_KNOWLEDGE_DURATION; + EnemyDiscardTime = AI_DEF_ENEMY_DISCARD_TIME; + DefaultLKP = vec3_invalid; + DefaultLSP = vec3_invalid; + Serial = 0; + } + + public AI_EnemyInfo? GetFirst(out int iter) { + iter = 0; + + if (iter >= Map.Count) + return null; + + if (Map[iter].Info.Enemy.Get() == null) + return GetNext(ref iter); + + return Map[iter].Info; + } + + public AI_EnemyInfo? GetNext(ref int iter) { + if (iter >= Map.Count) + return null; + + iter++; + if (iter >= Map.Count) + return null; + + if (Map[iter].Info.Enemy.Get() == null) + return GetNext(ref iter); + + return Map[iter].Info; + } + + int FindIndex(BaseEntity? entity) { + for (int i = 0; i < Map.Count; i++) { + if (Map[i].Key == entity) + return i; + } + return -1; + } + + public AI_EnemyInfo? Find(BaseEntity? entity, bool tryDangerMemory = false) { + int i = FindIndex(entity); + if (i == -1) { + if (!tryDangerMemory || (i = FindIndex(null)) == -1) + return null; + Assert(Map[i].Info.DangerMemory == true); + } + return Map[i].Info; + } + + public AI_EnemyInfo? GetDangerMemory() { + int i = FindIndex(null); + if (i == -1) + return null; + Assert(Map[i].Info.DangerMemory == true); + return Map[i].Info; + } + + public int NumEnemies() => Map.Count; + public int GetSerialNumber() => Serial; + + bool ShouldDiscardMemory(AI_EnemyInfo memory) { + BaseEntity? enemy = memory.Enemy.Get(); + + if (enemy != null) { + AI_BaseNPC? enemyNPC = enemy.MyNPCPointer(); + if (enemyNPC != null && enemyNPC.GetState() == NPCState.Dead) + return true; + } + else { + if (!memory.DangerMemory) + return true; + } + + if (!memory.Unforgettable && + gpGlobals.CurTime > memory.TimeLastSeen + EnemyDiscardTime) + return true; + + return false; + } + + public void RefreshMemories() { + if (FreeKnowledgeDuration >= EnemyDiscardTime) + FreeKnowledgeDuration = EnemyDiscardTime - .1f; + + int i = 0; + while (i < Map.Count) { + AI_EnemyInfo memory = Map[i].Info; + + if (ShouldDiscardMemory(memory)) { + Map.RemoveAt(i); + continue; + } + else { + BaseEntity? enemy = memory.Enemy.Get(); + if (enemy != null) { + if (!enemy.IsPlayer() || !g_IgnorePlayers.GetBool()) { + if (gpGlobals.CurTime <= memory.TimeLastSeen + FreeKnowledgeDuration) { + if ((enemy.GetFlags() & EntityFlags.NoTarget) == 0) + memory.LastKnownLocation = enemy.GetAbsOrigin(); + } + } + + if (gpGlobals.CurTime <= memory.TimeLastSeen) + memory.LastSeenLocation = enemy.GetAbsOrigin(); + } + } + i++; + } + } + + public bool UpdateMemory(AI_Network? aiNet, BaseEntity? enemy, in Vector3 position, float reactionDelay, bool firstHand) { + const float DIST_TRIGGER_REACQUIRE_SQ = (20.0f * 12.0f) * (20.0f * 12.0f); + const float TIME_TRIGGER_REACQUIRE = 4.0f; + const float MIN_DIST_TIME_TRIGGER_REACQUIRE_SQ = (4.0f * 12.0f) * (4.0f * 12.0f); + + AI_EnemyInfo? memory = Find(enemy); + if (memory != null) { + Assert(enemy != null || memory.DangerMemory == true); + + if (firstHand) + memory.TimeLastSeen = gpGlobals.CurTime; + memory.EludedMe = false; + + float deltaDist = (memory.LastKnownLocation - position).LengthSquared(); + + if (deltaDist > DIST_TRIGGER_REACQUIRE_SQ || (deltaDist > MIN_DIST_TIME_TRIGGER_REACQUIRE_SQ && (gpGlobals.CurTime - memory.TimeLastSeen) > TIME_TRIGGER_REACQUIRE)) + memory.TimeLastReacquired = gpGlobals.CurTime; + + if (deltaDist > 12.0f * 12.0f) + memory.LastKnownLocation = position; + + if (firstHand && memory.TimeAtFirstHand == AI_INVALID_TIME) + memory.TimeAtFirstHand = gpGlobals.CurTime; + + return false; + } + + AI_EnemyInfo addMemory = new(); + addMemory.LastKnownLocation = position; + + if (firstHand) + addMemory.TimeLastReacquired = addMemory.TimeFirstSeen = addMemory.TimeLastSeen = addMemory.TimeAtFirstHand = gpGlobals.CurTime; + else { + addMemory.TimeLastReacquired = addMemory.TimeFirstSeen = addMemory.TimeLastSeen = gpGlobals.CurTime - (FreeKnowledgeDuration + 0.01); + addMemory.TimeAtFirstHand = AI_INVALID_TIME; + } + + if (reactionDelay > 0.0) + addMemory.TimeValidEnemy = gpGlobals.CurTime + reactionDelay; + + addMemory.EludedMe = false; + + addMemory.Enemy.Set(enemy); + addMemory.DangerMemory = enemy == null; + + Map.Add(new(enemy, addMemory)); + Serial++; + + return true; + } + + public void OnTookDamageFrom(BaseEntity? enemy) { + AI_EnemyInfo? memory = Find(enemy, true); + if (memory != null) + memory.TimeLastReceivedDamageFrom = gpGlobals.CurTime; + } + + public bool HasMemory(BaseEntity? enemy) => Find(enemy) != null; + + public void ClearMemory(BaseEntity? enemy) { + int i = FindIndex(enemy); + if (i != -1) + Map.RemoveAt(i); + } + + public void MarkAsEluded(BaseEntity? enemy) { + AI_EnemyInfo? memory = Find(enemy); + if (memory != null) + memory.EludedMe = true; + } + + public Vector3 LastKnownPosition(BaseEntity? enemy) { + AI_EnemyInfo? memory = Find(enemy, true); + if (memory != null) + DefaultLKP = memory.LastKnownLocation; + else + DevWarning(2, "Asking LastKnownPosition for enemy that's not in my memory!!\n"); + return DefaultLKP; + } + + public Vector3 LastSeenPosition(BaseEntity? enemy) { + AI_EnemyInfo? memory = Find(enemy, true); + if (memory != null) + DefaultLSP = memory.LastSeenLocation; + else + DevWarning(2, "Asking LastSeenPosition for enemy that's not in my memory!!\n"); + return DefaultLSP; + } + + public TimeUnit_t TimeLastReacquired(BaseEntity? enemy) { + if (enemy == null) + return 0; + + AI_EnemyInfo? memory = Find(enemy, true); + if (memory != null) + return memory.TimeLastReacquired; + + DevWarning(2, "Asking TimeLastReacquired for enemy that's not in my memory!!\n"); + return AI_INVALID_TIME; + } + + public TimeUnit_t LastTimeSeen(BaseEntity? enemy, bool checkDangerMemory = true) { + if (enemy == null) + return 0; + + AI_EnemyInfo? memory = Find(enemy, checkDangerMemory); + if (memory != null) + return memory.TimeLastSeen; + + DevWarning(2, "Asking LastTimeSeen for enemy that's not in my memory!!\n"); + return AI_INVALID_TIME; + } + + public TimeUnit_t FirstTimeSeen(BaseEntity? enemy) { + if (enemy == null) + return 0; + + AI_EnemyInfo? memory = Find(enemy, true); + if (memory != null) + return memory.TimeFirstSeen; + + DevWarning(2, "Asking FirstTimeSeen for enemy that's not in my memory!!\n"); + return AI_INVALID_TIME; + } + + public bool HasFreeKnowledgeOf(BaseEntity? enemy) { + if (enemy == null) + return false; + + AI_EnemyInfo? memory = Find(enemy, true); + if (memory != null) { + TimeUnit_t freeKnowledgeTime = memory.TimeLastSeen + FreeKnowledgeDuration; + return gpGlobals.CurTime < freeKnowledgeTime; + } + + DevWarning(2, "Asking HasFreeKnowledgeOf for enemy that's not in my memory!!\n"); + return AI_INVALID_TIME != 0; + } + + public TimeUnit_t LastTimeTookDamageFrom(BaseEntity? enemy) { + if (enemy == null) + return 0; + + AI_EnemyInfo? memory = Find(enemy, true); + if (memory != null) + return memory.TimeLastReceivedDamageFrom; + + DevWarning(2, "Asking LastTimeTookDamageFrom for enemy that's not in my memory!!\n"); + return AI_INVALID_TIME; + } + + public TimeUnit_t TimeAtFirstHand(BaseEntity? enemy) { + if (enemy == null) + return 0; + + AI_EnemyInfo? memory = Find(enemy, true); + if (memory != null) + return memory.TimeAtFirstHand; + + DevWarning(2, "Asking TimeAtFirstHand for enemy that's not in my memory!!\n"); + return AI_INVALID_TIME; + } + + public bool HasEludedMe(BaseEntity? enemy) { + AI_EnemyInfo? memory = Find(enemy); + if (memory != null) + return memory.EludedMe; + return false; + } + + public void SetTimeValidEnemy(BaseEntity? enemy, TimeUnit_t time) { + AI_EnemyInfo? memory = Find(enemy); + if (memory != null) + memory.TimeValidEnemy = time; + } + + public void SetUnforgettable(BaseEntity? enemy, bool unforgettable = true) { + AI_EnemyInfo? memory = Find(enemy); + if (memory != null) + memory.Unforgettable = unforgettable; + } + + public void SetMobbedMe(BaseEntity? enemy, bool mobbedMe = true) { + AI_EnemyInfo? memory = Find(enemy); + if (memory != null) + memory.MobbedMe = mobbedMe; + } + + public void SetFreeKnowledgeDuration(float duration) { + FreeKnowledgeDuration = duration; + + if (FreeKnowledgeDuration >= EnemyDiscardTime) { + Assert(FreeKnowledgeDuration < EnemyDiscardTime); + + FreeKnowledgeDuration = EnemyDiscardTime - .1f; + } + } + + public void SetEnemyDiscardTime(float time) { + EnemyDiscardTime = time; + + if (FreeKnowledgeDuration >= EnemyDiscardTime) { + Assert(FreeKnowledgeDuration < EnemyDiscardTime); + + FreeKnowledgeDuration = EnemyDiscardTime - .1f; + } + } + + public float GetEnemyDiscardTime() => EnemyDiscardTime; + + readonly List Map = []; + float FreeKnowledgeDuration; + float EnemyDiscardTime; + Vector3 DefaultLKP; + Vector3 DefaultLSP; + int Serial; +} diff --git a/Game.Server/AI_Squad.cs b/Game.Server/AI_Squad.cs index b20d19577..8374e64f2 100644 --- a/Game.Server/AI_Squad.cs +++ b/Game.Server/AI_Squad.cs @@ -1,5 +1,33 @@ +using System.Numerics; + namespace Game.Server; +public enum SquadSlot +{ + None = -1, + + Attack1 = 0, + Attack2, + + InvestigateSound, + + ExclusiveHandsign, + ExclusiveReload, + + PickupWeapon1, + PickupWeapon2, + + SpecialAttack, + + LastShared, +} + public class AI_Squad { + public string GetName() => throw new NotImplementedException(); + public bool IsLeader(AI_BaseNPC npc) => throw new NotImplementedException(); + public AI_BaseNPC? GetFirstMember(out int iter) => throw new NotImplementedException(); + public AI_BaseNPC? GetNextMember(ref int iter) => throw new NotImplementedException(); + public void VacateStrategySlot(BaseEntity? enemy, SquadSlot slot) => throw new NotImplementedException(); + public void UpdateEnemyMemory(AI_BaseNPC updater, BaseEntity enemy, in Vector3 position) => throw new NotImplementedException(); } diff --git a/Game.Server/SimTimer.cs b/Game.Server/SimTimer.cs index ed6f7ac9a..c178ba429 100644 --- a/Game.Server/SimTimer.cs +++ b/Game.Server/SimTimer.cs @@ -70,17 +70,19 @@ public void Reset(float interval = -1.0f) { public class StopwatchBase : SimpleSimTimer { public StopwatchBase() { - IsRunning = false; + IsRunningValue = false; } - public void Stop() => IsRunning = false; + public bool IsRunning() => IsRunningValue; - public new bool Expired() => IsRunning && base.Expired(); + public void Stop() => IsRunningValue = false; - protected bool IsRunning; + public new bool Expired() => IsRunningValue && base.Expired(); + + protected bool IsRunningValue; public static readonly new DataMap DataDesc = new(typeof(StopwatchBase), SimpleSimTimer.DataDesc, [ - DEFINE.FIELD(nameof(IsRunning), FieldType.Boolean), + DEFINE.FIELD(nameof(IsRunningValue), FieldType.Boolean), ]); } @@ -95,6 +97,16 @@ public RandStopwatch(float minInterval = 0.0f, float maxInterval = 0.0f) { MaxInterval = maxInterval; } + public void Start(float minOverride, float maxOverride = 0.0f) { + IsRunningValue = true; + if (maxOverride == 0) + Next = gpGlobals.CurTime + minOverride; + else + Next = gpGlobals.CurTime + RandomFloat(minOverride, maxOverride); + } + + public void Start() => Start(MinInterval, MaxInterval); + float MinInterval; float MaxInterval; From a72316b5b745d73b682899d4cd3483278880a58f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:43:21 +0300 Subject: [PATCH 35/73] Port AI sentence queue and NPC sound timing --- Game.Server/AI_BaseNPC.cs | 27 ++++++ Game.Server/AI_Sentence.cs | 184 +++++++++++++++++++++++++++++++++++++ Game.Server/AI_Squad.cs | 3 + 3 files changed, 214 insertions(+) create mode 100644 Game.Server/AI_Sentence.cs diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 87f8e59ff..ee92d33fa 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -489,6 +489,8 @@ public static ReadOnlySpan GetActivityName(Activity actID) { public TimeUnit_t AcceptableTimeSeenEnemy; public readonly SimpleSimTimer FailChooseEnemyTimer = new(); public readonly SimpleSimTimer UpdateEnemyPosTimer = new(); + public TimeUnit_t SoundWaitTime; + public SentencePriority SoundPriorityValue; public bool SkippedChooseEnemy; public WorldSoundInstance LockedBestSound = new(); public Handle EnemyFilter = new(); @@ -5848,6 +5850,31 @@ public virtual bool ShouldPlayIdleSound() { return false; } + public bool FOkToMakeSound(SentencePriority soundPriority = SentencePriority.Normal) { + if (Squad != null) { + if (!Squad.FOkToMakeSound(soundPriority)) + return false; + } + else { + if (gpGlobals.CurTime <= SoundWaitTime) { + if (soundPriority <= SoundPriorityValue) + return false; + } + } + + if (HasSpawnFlags(SF_NPC_GAG) && (NPCState != NPCState.Combat)) + return false; + + return true; + } + + public void JustMadeSound(SentencePriority soundPriority = SentencePriority.Normal, float soundLength = 0.0f) { + SoundWaitTime = gpGlobals.CurTime + soundLength + random.RandomFloat(1.5f, 2.0f); + SoundPriorityValue = soundPriority; + + Squad?.JustMadeSound(soundPriority, gpGlobals.CurTime + soundLength + random.RandomFloat(1.5f, 2.0f)); + } + public virtual void IdleSound() { } public virtual void LostEnemySound() { } public virtual void FoundEnemySound() { } diff --git a/Game.Server/AI_Sentence.cs b/Game.Server/AI_Sentence.cs new file mode 100644 index 000000000..bc8ca606d --- /dev/null +++ b/Game.Server/AI_Sentence.cs @@ -0,0 +1,184 @@ +using Game.Shared; + +using Source.Common.Audio; +using Source.Common.Commands; +using Source.Common.SoundEmitterSystem; + +namespace Game.Server; + +public enum SentenceCriteria +{ + Always = 0, + Normal, + InSquad, + SquadLeader, +} + +public enum SentencePriority +{ + Invalid = -1, + Normal = 0, + Medium = 1, + High = 2, +} + +public abstract class AI_SentenceBase : AI_Component +{ + public static readonly ConVar npc_sentences = new("npc_sentences", "0"); + + protected AI_SentenceBase() => ClearQueue(); + + public void SetVoicePitch(int voicePitch) => VoicePitch = voicePitch; + public int GetVoicePitch() => VoicePitch; + + void SentenceMsg(ReadOnlySpan status, ReadOnlySpan sentence) { + int mode = npc_sentences.GetInt(); + switch (mode) { + case 0: + return; + + case 1: + DevMsg($"SENTENCE [{GetOuter()!.EntIndex()} {gpGlobals.CurTime:F2}] {status}: {sentence}\n"); + break; + } + } + + public void ClearQueue() => QueuedSentenceIndex = -1; + + public void UpdateSentenceQueue() { + if (QueuedSentenceIndex == -1) + return; + + if (QueueTimeout < gpGlobals.CurTime) { + ClearQueue(); + return; + } + + if (GetOuter()!.FOkToMakeSound(QueueSoundPriority)) { + SENTENCEG_PlaySentenceIndex(GetOuter()!.Edict(), QueuedSentenceIndex, GetVolume(), GetSoundLevel(), 0, GetVoicePitch()); + + ReadOnlySpan sentenceName = engine.SentenceNameFromIndex(QueuedSentenceIndex); + SentenceMsg("Speaking [from QUEUE]", sentenceName); + + GetOuter()!.JustMadeSound(QueueSoundPriority); + ClearQueue(); + } + } + + bool MatchesCriteria(SentenceCriteria criteria) { + switch (criteria) { + case SentenceCriteria.Always: + return true; + + case SentenceCriteria.Normal: + return (GetOuter()!.GetState() == NPCState.Combat) || (GetOuter()!.HasSpawnFlags(SF_NPC_GAG) == false); + + case SentenceCriteria.InSquad: + if ((GetOuter()!.GetState() != NPCState.Combat) && GetOuter()!.HasSpawnFlags(SF_NPC_GAG)) + return false; + return GetOuter()!.GetSquad() != null && (GetOuter()!.GetSquad()!.NumMembers() > 1); + + case SentenceCriteria.SquadLeader: { + if ((GetOuter()!.GetState() != NPCState.Combat) && GetOuter()!.HasSpawnFlags(SF_NPC_GAG)) + return false; + + AI_Squad? squad = GetOuter()!.GetSquad(); + return squad != null && (squad.NumMembers() > 1) && squad.IsLeader(GetOuter()!); + } + } + + return true; + } + + int PlaySentence(ReadOnlySpan sentence) { + int sentenceIndex = SENTENCEG_PlayRndSz(GetOuter()!.Edict(), sentence, GetVolume(), GetSoundLevel(), 0, GetVoicePitch()); + if (sentenceIndex < 0) { + SentenceMsg("BOGUS", sentence); + return -1; + } + + ReadOnlySpan sentenceName = engine.SentenceNameFromIndex(sentenceIndex); + SentenceMsg("Speaking", sentenceName); + return sentenceIndex; + } + + public int Speak(ReadOnlySpan sentence, SentencePriority soundPriority = SentencePriority.Normal, SentenceCriteria criteria = SentenceCriteria.InSquad) { + if (!MatchesCriteria(criteria)) + return -1; + + ClearQueue(); + + if (soundPriority == SentencePriority.Invalid) + return PlaySentence(sentence); + + int sentenceIndex = -1; + if (GetOuter()!.FOkToMakeSound(soundPriority)) { + sentenceIndex = PlaySentence(sentence); + + GetOuter()!.JustMadeSound(soundPriority, 2.0f); + } + else + SentenceMsg("CULL", sentence); + + return sentenceIndex; + } + + public int SpeakQueued(ReadOnlySpan sentence, SentencePriority soundPriority = SentencePriority.Normal, SentenceCriteria criteria = SentenceCriteria.InSquad) { + if (!MatchesCriteria(criteria)) + return -1; + + ClearQueue(); + + int sentenceIndex = Speak(sentence, soundPriority, criteria); + if (sentenceIndex >= 0) + return sentenceIndex; + + int queuedSentenceIndex = SENTENCEG_PickRndSz(sentence); + if (queuedSentenceIndex == -1) + return -1; + + int squadCount = GetOuter()!.GetSquad() != null ? GetOuter()!.GetSquad()!.NumMembers() : 1; + QueueTimeout = gpGlobals.CurTime + squadCount * 2.0f; + QueueSoundPriority = soundPriority; + QueuedSentenceIndex = queuedSentenceIndex; + return -1; + } + + protected abstract float GetVolume(); + protected abstract SoundLevel GetSoundLevel(); + + int VoicePitch; + int QueuedSentenceIndex; + TimeUnit_t QueueTimeout; + SentencePriority QueueSoundPriority; +} + +public class AI_Sentence_NPC_MetroPolice : AI_SentenceBase +{ + public void Init(NPC_MetroPolice outer, ReadOnlySpan gameSound) { + SetOuter(outer); + + if (VoicePitchMin <= 0 || VoicePitchMax <= 0) { + SoundParameters parms = new(); + if (BaseEntity.GetParametersForSound(gameSound, ref parms, null)) { + SentenceVolume = parms.Volume; + SentenceSoundlevel = parms.SoundLevel; + VoicePitchMin = parms.PitchLow; + VoicePitchMax = parms.PitchHigh; + } + } + + if (random.RandomInt(0, 1) != 0) + SetVoicePitch(random.RandomInt(VoicePitchMin, VoicePitchMax)); + else + SetVoicePitch(100); + } + + protected override float GetVolume() => SentenceVolume; + protected override SoundLevel GetSoundLevel() => SentenceSoundlevel; + + static float SentenceVolume = 1.0f; + static SoundLevel SentenceSoundlevel = SoundLevel.LvlNorm; + static int VoicePitchMin = 0; + static int VoicePitchMax = 0; +} diff --git a/Game.Server/AI_Squad.cs b/Game.Server/AI_Squad.cs index 8374e64f2..1fe1ea4d9 100644 --- a/Game.Server/AI_Squad.cs +++ b/Game.Server/AI_Squad.cs @@ -25,6 +25,9 @@ public enum SquadSlot public class AI_Squad { public string GetName() => throw new NotImplementedException(); + public int NumMembers(bool ignoreSilentMembers = true) => throw new NotImplementedException(); + 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? GetFirstMember(out int iter) => throw new NotImplementedException(); public AI_BaseNPC? GetNextMember(ref int iter) => throw new NotImplementedException(); From 8b96dd30936fbd18eadec88b6b8a011cd92d67f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:46:04 +0300 Subject: [PATCH 36/73] Fix OnScheduleChange missing goal and sound cleanup --- Game.Server/AI_BaseNPC.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index ee92d33fa..1ec835f8e 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -3865,8 +3865,16 @@ public void RunTaskOverlay() { public virtual void OnScheduleChange() { EndTaskOverlay(); + Navigator!.OnScheduleChange(); + MoveWaitFinished = 0; + VacateStrategySlot(); + + GetNavigator()!.ClearGoal(); + + UnlockBestSound(); + if (HasMemory(AI_MemoryFlags.LockedHint) && GetHintNode() != null) { float hintDelay = GetHintDelay(GetHintNode()!.HintType()); GetHintNode()!.Unlock(hintDelay); From 1e78d7105f32a87c8257f28a4f4426f0991a7b62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:51:37 +0300 Subject: [PATCH 37/73] Port ai_goal_police and policing behavior --- Game.Server/AI_BaseNPC.cs | 27 ++ Game.Server/AI_GoalPolice.cs | 117 ++++++ Game.Server/AI_PolicingBehavior.cs | 552 +++++++++++++++++++++++++++++ Game.Server/AI_Schedule.cs | 52 +++ Game.Server/NPC_MetroPolice.cs | 39 ++ 5 files changed, 787 insertions(+) create mode 100644 Game.Server/AI_GoalPolice.cs create mode 100644 Game.Server/AI_PolicingBehavior.cs diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 1ec835f8e..e74422c90 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -67,6 +67,12 @@ public struct UnreachableEnt public Vector3 LocationWhenUnreachable; } +public struct AI_SchedLoadStatus +{ + public bool Valid; + public int Signature; +} + public static class AI_BaseNPCGlobals { // TODO: Enum these @@ -146,6 +152,27 @@ public static bool FBoxVisible(BaseEntity looker, BaseEntity target, out Vector3 return false; } + public static bool AI_DoLoadSchedules(Func baseLoad, Action initCustomSchedules, ref AI_SchedLoadStatus loadStatus) { + baseLoad(); + + if (loadStatus.Signature != g_AI_SchedulesManager.GetScheduleLoadSignature()) { + initCustomSchedules(); + loadStatus.Valid = true; + loadStatus.Signature = g_AI_SchedulesManager.GetScheduleLoadSignature(); + } + return loadStatus.Valid; + } + + public static bool ValidateConditionLimits(string newCondition) { + int globalConditions = AI_BaseNPC.GetSchedulingSymbols().NumConditions(); + if (globalConditions >= MAX_CONDITIONS) { + AssertMsg(false, $"Exceeded max number of conditions ({MAX_CONDITIONS}), ignoring condition {newCondition}\n"); + DevWarning($"Exceeded max number of conditions ({MAX_CONDITIONS}), ignoring condition {newCondition}\n"); + return false; + } + return true; + } + public static readonly Stopwatch g_AIRunTimer = new(); public static float g_NpcTimeThisFrame; diff --git a/Game.Server/AI_GoalPolice.cs b/Game.Server/AI_GoalPolice.cs new file mode 100644 index 000000000..68f4ee3e1 --- /dev/null +++ b/Game.Server/AI_GoalPolice.cs @@ -0,0 +1,117 @@ +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Mathematics; + +using System.Numerics; + +using DEFINE = Source.DEFINE; + +namespace Game.Server; + +[LinkEntityToClass("ai_goal_police")] +public class AI_PoliceGoal : BaseEntity +{ + public const int SF_POLICE_GOAL_KNOCKOUT_BEHIND = 1 << 1; + public const int SF_POLICE_GOAL_DO_NOT_LEAVE_POST = 1 << 2; + + public static readonly new DataMap DataDesc = new(typeof(AI_PoliceGoal), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(Radius), FieldType.Float, "PoliceRadius"), + DEFINE.KEYFIELD(nameof(TargetName), FieldType.String, "PoliceTarget"), + + DEFINE.FIELD(nameof(OverrideKnockOut), FieldType.Boolean), + + DEFINE.INPUTFUNC(FieldType.Void, "EnableKnockOut", nameof(InputEnableKnockOut), (INPUTFUNCPTR)((self, data) => ((AI_PoliceGoal)self).InputEnableKnockOut(data))), + DEFINE.INPUTFUNC(FieldType.Void, "DisableKnockOut", nameof(InputDisableKnockOut), (INPUTFUNCPTR)((self, data) => ((AI_PoliceGoal)self).InputDisableKnockOut(data))), + + DEFINE.OUTPUT(nameof(OnKnockOut), "OnKnockOut", eventFuncs), + DEFINE.OUTPUT(nameof(OnFirstWarning), "OnFirstWarning", eventFuncs), + DEFINE.OUTPUT(nameof(OnSecondWarning), "OnSecondWarning", eventFuncs), + DEFINE.OUTPUT(nameof(OnLastWarning), "OnLastWarning", eventFuncs), + DEFINE.OUTPUT(nameof(OnSupressingTarget), "OnSupressingTarget", eventFuncs), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public AI_PoliceGoal() { + Target.Set(null); + OverrideKnockOut = false; + } + + public float GetRadius() => Radius; + + public BaseEntity? GetTarget() { + if (Target.Get() == null) { + BaseEntity? target = gEntList.FindEntityByName(null, TargetName); + + if (target == null) { + DevMsg($"Unable to find ai_goal_police target: {TargetName}\n"); + return null; + } + + Target.Set(target); + } + + return Target.Get(); + } + + public bool ShouldKnockOutTarget(in Vector3 targetPos, bool targetVisible) { + if (OverrideKnockOut) + return true; + + if (HasSpawnFlags(SF_POLICE_GOAL_KNOCKOUT_BEHIND) == false) + return false; + + if (!targetVisible) + return false; + + Vector3 targetDir = targetPos - GetAbsOrigin(); + MathLib.VectorNormalize(ref targetDir); + + MathLib.AngleVectors(GetAbsAngles(), out Vector3 facingDir); + + if (Vector3.Dot(facingDir, targetDir) < 0) + return true; + + return false; + } + + public void KnockOutTarget(BaseEntity? target) => OnKnockOut.FireOutput(target, this); + + public bool ShouldRemainAtPost() => HasSpawnFlags(SF_POLICE_GOAL_DO_NOT_LEAVE_POST); + + public void FireWarningLevelOutput(int level) { + switch (level) { + case 1: + OnFirstWarning.FireOutput(this, this); + break; + + case 2: + OnSecondWarning.FireOutput(this, this); + break; + + case 3: + OnLastWarning.FireOutput(this, this); + break; + + default: + OnSupressingTarget.FireOutput(this, this); + break; + } + } + + public void InputEnableKnockOut(InputData data) => OverrideKnockOut = true; + + public void InputDisableKnockOut(InputData data) => OverrideKnockOut = false; + + public float Radius; + public EHANDLE Target = new(); + public string? TargetName; + public bool OverrideKnockOut; + + readonly OutputEvent OnKnockOut = new(); + readonly OutputEvent OnFirstWarning = new(); + readonly OutputEvent OnSecondWarning = new(); + readonly OutputEvent OnLastWarning = new(); + readonly OutputEvent OnSupressingTarget = new(); +} diff --git a/Game.Server/AI_PolicingBehavior.cs b/Game.Server/AI_PolicingBehavior.cs new file mode 100644 index 000000000..a83de5c5b --- /dev/null +++ b/Game.Server/AI_PolicingBehavior.cs @@ -0,0 +1,552 @@ +using Game.Shared; + +using Source.Common; +using Source.Common.Mathematics; + +using System.Numerics; + +namespace Game.Server; + +public class AI_PolicingBehavior : AI_Behavior_AI_BaseNPC_100000 +{ + const float PATROL_RADIUS_RATIO = 2.0f; + const int POLICE_MAX_WARNINGS = 4; + + public const int SCHED_POLICE_RETURN_FROM_HARASS = NEXT_SCHEDULE; + public const int SCHED_POLICE_WARN_TARGET = NEXT_SCHEDULE + 1; + public const int SCHED_POLICE_HARASS_TARGET = NEXT_SCHEDULE + 2; + public const int SCHED_POLICE_SUPPRESS_TARGET = NEXT_SCHEDULE + 3; + public const int SCHED_POLICE_FACE_ALONG_GOAL = NEXT_SCHEDULE + 4; + public const int SCHED_POLICE_TRACK_TARGET = NEXT_SCHEDULE + 5; + + public const int TASK_POLICE_GET_PATH_TO_HARASS_GOAL = NEXT_TASK; + public const int TASK_POLICE_GET_PATH_TO_POLICE_GOAL = NEXT_TASK + 1; + public const int TASK_POLICE_FACE_ALONG_GOAL = NEXT_TASK + 2; + public const int TASK_POLICE_ANNOUNCE_HARASS = NEXT_TASK + 3; + + public const int COND_POLICE_TARGET_TOO_CLOSE_HARASS = NEXT_CONDITION; + public const int COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS = NEXT_CONDITION + 1; + + static readonly AI_ClassScheduleIdSpace gm_ClassScheduleIdSpace = new(); + const string gm_pszErrorClassName = "CAI_PolicingBehavior"; + + static readonly string[] Warnings = [ + "METROPOLICE_MOVE_ALONG_A", + "METROPOLICE_MOVE_ALONG_B", + "METROPOLICE_MOVE_ALONG_C", + ]; + + public AI_PolicingBehavior() { + LoadSchedules(); + + Enabled = false; + NumWarnings = 0; + TargetIsHostileValue = false; + } + + public override string GetName() => "Policing"; + + public override AI_ClassScheduleIdSpace GetClassScheduleIdSpace() => gm_ClassScheduleIdSpace; + protected override string GetSchedulingErrorName() => gm_pszErrorClassName; + + public static bool LoadSchedules() => CustomSchedules.Load(AI_BaseNPC.LoadSchedules); + + static readonly AI_CustomSchedules CustomSchedules = new() { + ClassName = gm_pszErrorClassName, + IdSpace = gm_ClassScheduleIdSpace, + ParentIdSpace = AccessClassScheduleIdSpaceDirect(), + Schedules = [ + (nameof(SCHED_POLICE_WARN_TARGET), SCHED_POLICE_WARN_TARGET), + (nameof(SCHED_POLICE_HARASS_TARGET), SCHED_POLICE_HARASS_TARGET), + (nameof(SCHED_POLICE_SUPPRESS_TARGET), SCHED_POLICE_SUPPRESS_TARGET), + (nameof(SCHED_POLICE_RETURN_FROM_HARASS), SCHED_POLICE_RETURN_FROM_HARASS), + (nameof(SCHED_POLICE_TRACK_TARGET), SCHED_POLICE_TRACK_TARGET), + (nameof(SCHED_POLICE_FACE_ALONG_GOAL), SCHED_POLICE_FACE_ALONG_GOAL), + ], + Tasks = [ + (nameof(TASK_POLICE_GET_PATH_TO_HARASS_GOAL), TASK_POLICE_GET_PATH_TO_HARASS_GOAL), + (nameof(TASK_POLICE_GET_PATH_TO_POLICE_GOAL), TASK_POLICE_GET_PATH_TO_POLICE_GOAL), + (nameof(TASK_POLICE_ANNOUNCE_HARASS), TASK_POLICE_ANNOUNCE_HARASS), + (nameof(TASK_POLICE_FACE_ALONG_GOAL), TASK_POLICE_FACE_ALONG_GOAL), + ], + Conditions = [ + (nameof(COND_POLICE_TARGET_TOO_CLOSE_HARASS), COND_POLICE_TARGET_TOO_CLOSE_HARASS), + (nameof(COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS), COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS), + ], + Definitions = [ + new(SCHED_POLICE_WARN_TARGET, + [ + TASK_STOP_MOVING, + TASK_FACE_TARGET, + TASK_POLICE_ANNOUNCE_HARASS, + (TASK_PLAY_SEQUENCE, Activity.ACT_POLICE_HARASS1), + ], + [ + COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS, + ]), + + new(SCHED_POLICE_HARASS_TARGET, + [ + TASK_STOP_MOVING, + TASK_FACE_TARGET, + (TASK_POLICE_GET_PATH_TO_HARASS_GOAL, 64), + TASK_WAIT_FOR_MOVEMENT, + TASK_POLICE_ANNOUNCE_HARASS, + (TASK_PLAY_SEQUENCE, Activity.ACT_POLICE_HARASS1), + ], + [ + COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS, + ]), + + new(SCHED_POLICE_SUPPRESS_TARGET, + [ + TASK_STOP_MOVING, + TASK_FACE_TARGET, + TASK_POLICE_ANNOUNCE_HARASS, + (TASK_PLAY_SEQUENCE, Activity.ACT_POLICE_HARASS1), + ]), + + new(SCHED_POLICE_RETURN_FROM_HARASS, + [ + TASK_STOP_MOVING, + (TASK_POLICE_GET_PATH_TO_POLICE_GOAL, 16), + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + ], + [ + COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS, + ]), + + new(SCHED_POLICE_TRACK_TARGET, + [ + TASK_FACE_TARGET, + ], + [ + COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS, + ]), + + new(SCHED_POLICE_FACE_ALONG_GOAL, + [ + (TASK_WAIT_RANDOM, 2), + TASK_POLICE_FACE_ALONG_GOAL, + ], + [ + COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS, + ]), + ], + }; + + public bool TargetIsHostile() { + if ((TargetHostileTime < gpGlobals.CurTime) && (!TargetIsHostileValue)) + return false; + + return true; + } + + public void Enable(AI_PoliceGoal goal) { + PoliceGoal.Set(goal); + Enabled = true; + + StartPolicing = true; + + GetOuter()!.ClearSchedule("Enable police behavior"); + } + + public void Disable() { + PoliceGoal.Set(null); + Enabled = false; + } + + public bool IsEnabled() => Enabled; + + AI_PoliceGoal? GetPoliceGoal() => (AI_PoliceGoal?)PoliceGoal.Get(); + + public override bool CanSelectSchedule() { + if (IsEnabled() == false || GetPoliceGoal() == null || GetPoliceGoal()!.GetTarget() == null) + return false; + + return true; + } + + void HostSetBatonState(bool state) { + if (GetOuter() is NPC_MetroPolice cop) { + cop.SetBatonState(state); + cop.SetTarget(GetPoliceGoal()!.GetTarget()); + } + } + + bool HostBatonIsOn() { + if (GetOuter() is NPC_MetroPolice cop) + return cop.BatonActive(); + + return false; + } + + void HostSpeakSentence(string sentence, SentencePriority soundPriority, SentenceCriteria criteria) { + if (GetOuter() is NPC_MetroPolice cop) { + AI_Sentence_NPC_MetroPolice sentences = cop.GetSentences(); + + sentences.Speak(sentence, soundPriority, criteria); + } + } + + protected override void BuildScheduleTestBits() { + if (IsCurSchedule(SCHED_IDLE_STAND) || IsCurSchedule(SCHED_ALERT_STAND)) { + if (NextHarassTime < gpGlobals.CurTime) + GetOuter()!.SetCustomInterruptCondition(GetClassScheduleIdSpace().ConditionLocalToGlobal(COND_POLICE_TARGET_TOO_CLOSE_HARASS)); + + GetOuter()!.SetCustomInterruptCondition(GetClassScheduleIdSpace().ConditionLocalToGlobal(COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS)); + } + } + + public override void GatherConditions() { + base.GatherConditions(); + + if (GetPoliceGoal() == null) { + Disable(); + return; + } + + ClearCondition(COND_POLICE_TARGET_TOO_CLOSE_HARASS); + ClearCondition(COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS); + + BaseEntity? target = GetPoliceGoal()!.GetTarget(); + + if (target == null) { + DevMsg("ai_goal_police with NULL target entity!\n"); + return; + } + + if (ShouldKnockOutTarget(target)) + SetCondition(COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS); + + Vector3 goalCenter = GetPoliceGoal()!.WorldSpaceCenter(); + Vector3 targetCenter = target.WorldSpaceCenter(); + float distSqr = (goalCenter - targetCenter).Length2DSqr(); + float radius = GetPoliceGoal()!.GetRadius() * PATROL_RADIUS_RATIO; + float zDiff = MathF.Abs(goalCenter.Z - targetCenter.Z); + + if (distSqr < (radius * radius) && zDiff < 32.0f) { + SetCondition(COND_POLICE_TARGET_TOO_CLOSE_HARASS); + + if (distSqr < (GetPoliceGoal()!.GetRadius() * GetPoliceGoal()!.GetRadius())) + SetCondition(COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS); + } + + if (TargetIsHostileValue && AggressiveTime < gpGlobals.CurTime && IsCurSchedule(SCHED_CHASE_ENEMY)) + GetOuter()!.ClearSchedule("Stopped chasing, aggression over"); + } + + void AnnouncePolicing() { + if (NumWarnings <= 3) + HostSpeakSentence(Warnings[NumWarnings - 1], SentencePriority.Medium, SentenceCriteria.Normal); + else { + int sentence = random.RandomInt(0, 1); + HostSpeakSentence(Warnings[sentence], SentencePriority.Medium, SentenceCriteria.Normal); + } + } + + protected override int TranslateSchedule(int scheduleType) { + if (scheduleType == SCHED_CHASE_ENEMY) { + if (GetPoliceGoal()!.ShouldRemainAtPost() && !MaintainGoalPosition()) + return base.TranslateSchedule(SCHED_COMBAT_FACE); + } + + return base.TranslateSchedule(scheduleType); + } + + protected override Activity NPC_TranslateActivity(Activity newActivity) { + if (newActivity == Activity.ACT_POLICE_HARASS1) { + switch (NumWarnings) { + case 1: + return Activity.ACT_POLICE_HARASS1; + + default: + case 2: + return Activity.ACT_POLICE_HARASS2; + } + } + + return base.NPC_TranslateActivity(newActivity); + } + + public BaseEntity? GetGoalTarget() { + if (GetPoliceGoal() == null) { + Assert(false); + return null; + } + + return GetPoliceGoal()!.GetTarget(); + } + + protected override void StartTask(in Task_t task) { + switch (task.Task) { + case TASK_POLICE_GET_PATH_TO_HARASS_GOAL: { + Vector3 harassDir = GetPoliceGoal()!.GetTarget()!.WorldSpaceCenter() - GetOuter()!.WorldSpaceCenter(); + float dist = MathLib.VectorNormalize(ref harassDir); + + if (dist < task.TaskData) { + GetOuter()!.TaskComplete(); + break; + } + + Vector3 harassPos = GetOuter()!.GetAbsOrigin() + (harassDir * (dist - task.TaskData)); + + if (CollisionUtils.IntersectInfiniteRayWithSphere(GetOuter()!.GetAbsOrigin(), harassDir, GetPoliceGoal()!.GetAbsOrigin(), GetPoliceGoal()!.GetRadius(), out float inter1, out float inter2)) { + Vector3 pos = GetPoliceGoal()!.GetAbsOrigin() + harassDir * Math.Max(inter1, inter2); + + float testDist = Util.DistApprox2D(GetPoliceGoal()!.GetAbsOrigin(), harassPos); + + if (testDist > Util.DistApprox2D(GetPoliceGoal()!.GetAbsOrigin(), pos)) + harassPos = pos; + } + + if (GetNavigator()!.SetGoal(new AI_NavGoal(harassPos), (AI_NavSetGoalFlags)(uint)task.TaskData)) { + GetNavigator()!.SetMovementActivity(Activity.ACT_WALK_ANGRY); + GetNavigator()!.SetArrivalDirection(GetPoliceGoal()!.GetTarget()); + GetOuter()!.TaskComplete(); + } + else + GetOuter()!.TaskFail(AI_TaskFailureCode.NoRoute); + } + break; + + case TASK_POLICE_GET_PATH_TO_POLICE_GOAL: { + if (GetNavigator()!.SetGoal(new AI_NavGoal(GetPoliceGoal()!.GetAbsOrigin()), (AI_NavSetGoalFlags)(uint)task.TaskData)) { + GetNavigator()!.SetArrivalDirection(GetPoliceGoal()!.GetAbsAngles()); + GetOuter()!.TaskComplete(); + } + else + GetOuter()!.TaskFail(AI_TaskFailureCode.NoRoute); + } + break; + + case TASK_POLICE_ANNOUNCE_HARASS: { + AnnouncePolicing(); + + NextHarassTime = gpGlobals.CurTime + random.RandomInt(4, 6); + + SoundEnt.InsertSound(SoundInstanceType.MoveAway, GetOuter()!.GetAbsOrigin(), 256, 2.0f, GetOuter()); + } + GetOuter()!.TaskComplete(); + break; + + case TASK_POLICE_FACE_ALONG_GOAL: { + if (GetPoliceGoal() != null) { + GetMotor()!.SetIdealYaw(GetPoliceGoal()!.GetAbsAngles().Y); + GetOuter()!.SetTurnActivity(); + } + } + break; + + default: + base.StartTask(task); + break; + } + } + + protected override void RunTask(in Task_t task) { + switch (task.Task) { + case TASK_POLICE_FACE_ALONG_GOAL: { + GetMotor()!.UpdateYaw(); + + if (GetOuter()!.FacingIdeal()) + GetOuter()!.TaskComplete(); + break; + } + + default: + base.RunTask(task); + break; + } + } + + bool MaintainGoalPosition() { + Vector3 org = GetOuter()!.GetAbsOrigin(); + Vector3 target = GetPoliceGoal()!.GetAbsOrigin(); + + if (MathF.Abs(org.Z - target.Z) > 64) + return true; + + if ((org - target).Length2D() > 16) + return true; + + return false; + } + + public bool ShouldKnockOutTarget(BaseEntity target) { + if (GetPoliceGoal() == null) { + Assert(false); + return false; + } + + bool visible = GetOuter()!.FVisible(target); + return GetPoliceGoal()!.ShouldKnockOutTarget(target.WorldSpaceCenter(), visible); + } + + public void KnockOutTarget(BaseEntity? target) { + if (GetPoliceGoal() == null) { + Assert(false); + return; + } + + GetPoliceGoal()!.KnockOutTarget(target); + } + + int SelectSuppressSchedule() { + BaseEntity target = GetPoliceGoal()!.GetTarget()!; + + AggressiveTime = gpGlobals.CurTime + 4.0f; + + if (TargetIsHostileValue == false) { + TargetIsHostileValue = true; + + GetOuter()!.SetEnemy(target); + GetOuter()!.SetState(NPCState.Combat); + GetOuter()!.UpdateEnemyMemory(target, target.GetAbsOrigin()); + + HostSetBatonState(true); + + NumWarnings = POLICE_MAX_WARNINGS; + + return SCHED_COMBAT_FACE; + } + + if (GetPoliceGoal()!.ShouldRemainAtPost()) { + if (MaintainGoalPosition()) + return SCHED_CHASE_ENEMY; + + if (NextHarassTime < gpGlobals.CurTime) + return SCHED_POLICE_WARN_TARGET; + else + return SCHED_COMBAT_FACE; + } + + return SCHED_CHASE_ENEMY; + } + + int SelectHarassSchedule() { + BaseEntity target = GetPoliceGoal()!.GetTarget()!; + + AggressiveTime = gpGlobals.CurTime + 4.0f; + + if (MaintainGoalPosition()) + return SCHED_POLICE_RETURN_FROM_HARASS; + + GetOuter()!.AddLookTarget(target, 0.5f, 5.0f); + + if (NextHarassTime < gpGlobals.CurTime) { + GetOuter()!.SetTarget(target); + + if (NumWarnings == 0) + GetPoliceGoal()!.FireWarningLevelOutput(1); + else if (NumWarnings == 1) + GetPoliceGoal()!.FireWarningLevelOutput(2); + + if (NumWarnings < POLICE_MAX_WARNINGS) + NumWarnings++; + + if (NumWarnings >= POLICE_MAX_WARNINGS) { + if (TargetIsHostileValue == false) { + TargetIsHostileValue = true; + + GetOuter()!.SetEnemy(target); + GetOuter()!.SetState(NPCState.Combat); + GetOuter()!.UpdateEnemyMemory(target, target.GetAbsOrigin()); + HostSetBatonState(true); + + GetPoliceGoal()!.FireWarningLevelOutput(4); + + return SCHED_COMBAT_FACE; + } + + if (GetPoliceGoal()!.ShouldRemainAtPost() == false) + return SCHED_CHASE_ENEMY; + } + + if (NumWarnings == (POLICE_MAX_WARNINGS - 1)) { + GetPoliceGoal()!.FireWarningLevelOutput(3); + + GetOuter()!.SetTarget(target); + + HostSetBatonState(true); + + if (GetPoliceGoal()!.ShouldRemainAtPost() == false) + return SCHED_POLICE_HARASS_TARGET; + } + + return SCHED_POLICE_WARN_TARGET; + } + + return SCHED_NONE; + } + + protected override int SelectSchedule() { + BaseEntity? target = GetPoliceGoal()!.GetTarget(); + + if (target == null) { + DevMsg("ai_goal_police with NULL target entity!\n"); + + Disable(); + return SCHED_NONE; + } + + if ((AggressiveTime >= gpGlobals.CurTime) && HasCondition((int)SCOND_t.COND_CAN_MELEE_ATTACK1)) + return SCHED_MELEE_ATTACK1; + + if (HasCondition(COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS)) + return SelectSuppressSchedule(); + + int newSchedule = SCHED_NONE; + + if (HasCondition(COND_POLICE_TARGET_TOO_CLOSE_HARASS)) + newSchedule = SelectHarassSchedule(); + + if (newSchedule != SCHED_NONE) + return newSchedule; + + if (AggressiveTime < gpGlobals.CurTime) { + if (GetOuter()!.GetEnemy() != null) { + GetOuter()!.SetEnemy(null); + GetOuter()!.SetState(NPCState.Alert); + GetOuter()!.GetEnemies().RefreshMemories(); + } + + HostSetBatonState(false); + TargetIsHostileValue = false; + } + + if (MaintainGoalPosition()) + return SCHED_POLICE_RETURN_FROM_HARASS; + + if (HostBatonIsOn()) + return SCHED_POLICE_TRACK_TARGET; + + if (MathF.Abs(Util.AngleDiff(GetOuter()!.GetAbsAngles().Y, GetPoliceGoal()!.GetAbsAngles().Y)) > 15) + return SCHED_POLICE_FACE_ALONG_GOAL; + + return SCHED_IDLE_STAND; + } + + protected override int SelectFailSchedule(int failedSchedule, int failedTask, AI_TaskFailureCode taskFailCode) { + if (failedSchedule == SCHED_CHASE_ENEMY) { + if (MaintainGoalPosition()) + return SCHED_POLICE_RETURN_FROM_HARASS; + + return SCHED_POLICE_WARN_TARGET; + } + + return base.SelectFailSchedule(failedSchedule, failedTask, taskFailCode); + } + + protected bool Enabled; + protected bool StartPolicing; + protected TimeUnit_t NextHarassTime; + protected TimeUnit_t AggressiveTime; + protected int NumWarnings; + protected bool TargetIsHostileValue; + protected TimeUnit_t TargetHostileTime; + + protected EHANDLE PoliceGoal = new(); +} diff --git a/Game.Server/AI_Schedule.cs b/Game.Server/AI_Schedule.cs index 2deade91e..02a150d4e 100644 --- a/Game.Server/AI_Schedule.cs +++ b/Game.Server/AI_Schedule.cs @@ -184,6 +184,58 @@ public readonly struct AI_ScheduleCondition(int condition) public readonly record struct AI_ScheduleDef(int Schedule, AI_TaskDef[] Tasks, AI_ScheduleCondition[]? Interrupts = null); +public sealed class AI_CustomSchedules +{ + public required string ClassName { get; init; } + public required AI_ClassScheduleIdSpace IdSpace { get; init; } + public required AI_ClassScheduleIdSpace ParentIdSpace { get; init; } + + public (string Name, int LocalId)[] Schedules { get; init; } = []; + public (string Name, int LocalId)[] Tasks { get; init; } = []; + public (string Name, int LocalId)[] Conditions { get; init; } = []; + + public Action? Declare { get; init; } + public AI_ScheduleDef[] Definitions { get; init; } = []; + + AI_SchedLoadStatus LoadStatus = new() { Valid = true, Signature = -1 }; + + public bool Valid => LoadStatus.Valid; + + public bool Load(Func baseLoad) => AI_DoLoadSchedules(baseLoad, Init, ref LoadStatus); + + void Init() { + Declare?.Invoke(); + + IdSpace.Init(ClassName, AI_BaseNPC.GetSchedulingSymbols(), ParentIdSpace); + + foreach ((string name, int localId) in SortedByLocalId(Schedules)) { + if (!IdSpace.AddSchedule(name, localId, ClassName)) + return; + } + + foreach ((string name, int localId) in SortedByLocalId(Tasks)) { + if (!IdSpace.AddTask(name, localId, ClassName)) + return; + } + + foreach ((string name, int localId) in SortedByLocalId(Conditions)) { + if (ValidateConditionLimits(name)) { + if (!IdSpace.AddCondition(name, localId, ClassName)) + return; + } + } + + if (LoadStatus.Valid) + LoadStatus.Valid = g_AI_SchedulesManager.DefineSchedules(ClassName, IdSpace, Definitions); + } + + static (string Name, int LocalId)[] SortedByLocalId((string Name, int LocalId)[] symbols) { + (string Name, int LocalId)[] sorted = [.. symbols]; + Array.Sort(sorted, static (left, right) => left.LocalId - right.LocalId); + return sorted; + } +} + public class AI_Schedule { public int GetId() => ScheduleID; diff --git a/Game.Server/NPC_MetroPolice.cs b/Game.Server/NPC_MetroPolice.cs index efd1fbf88..52d9f8fb0 100644 --- a/Game.Server/NPC_MetroPolice.cs +++ b/Game.Server/NPC_MetroPolice.cs @@ -1,4 +1,5 @@ using Game.Shared; +using Game.Shared.GarrysMod; using Source; using Source.Common; @@ -33,6 +34,8 @@ public class NPC_MetroPolice : AI_BaseActor DEFINE.OUTPUT(nameof(OnStunnedPlayer), "OnStunnedPlayer", eventFuncs), DEFINE.OUTPUT(nameof(OnCupCopped), "OnCupCopped", eventFuncs), + + DEFINE.INPUTFUNC(FieldType.String, "SetPoliceGoal", nameof(InputSetPoliceGoal), (INPUTFUNCPTR)((self, data) => ((NPC_MetroPolice)self).InputSetPoliceGoal(data))), ]); public override DataMap? GetDataDescMap() => DataDesc; @@ -44,6 +47,9 @@ public class NPC_MetroPolice : AI_BaseActor public OutputEvent OnStunnedPlayer = new(); public OutputEvent OnCupCopped = new(); + readonly AI_PolicingBehavior PolicingBehavior = new(); + readonly AI_Sentence_NPC_MetroPolice Sentences = new(); + public override void Precache() { if (HasSpawnFlags(SF_NPC_START_EFFICIENT)) SetModelName("models/police_cheaple.mdl"); @@ -157,6 +163,39 @@ public override float MaxYawSpeed() { } } + public override bool CreateBehaviors() { + AddBehavior(PolicingBehavior); + + return base.CreateBehaviors(); + } + + public void InputSetPoliceGoal(InputData inputdata) { + BaseEntity? goal = gEntList.FindEntityByName(null, inputdata.Value.String()); + + if (goal == null) { + DevMsg($"SetPoliceGoal: {GetClassname()} ({GetDebugName()}) unable to find ai_goal_police: {inputdata.Value.String()}\n"); + return; + } + + if (goal is not AI_PoliceGoal policeGoal) { + DevMsg($"SetPoliceGoal: {GetClassname()} ({GetDebugName()})'s target {inputdata.Value.String()} is not an ai_goal_police entity!\n"); + return; + } + + PolicingBehavior.Enable(policeGoal); + } + + public bool BatonActive() { + if (GetActiveWeapon() is WeaponStunStick stick) + return stick.GetStunState(); + + return false; + } + + public void SetBatonState(bool state) => throw new NotImplementedException(); + + public AI_Sentence_NPC_MetroPolice GetSentences() => Sentences; + public override Class_T Classify() => Class_T.MetroPolice; public bool PlayerIsCriminal() { From ae6e0696a7c74bab0bb7cd20aeb1bd83c496b93d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Sun, 11 Oct 2026 23:32:57 +0300 Subject: [PATCH 38/73] Rename hl2 game directory to sdn and add skill cfgs --- .gitignore | 20 +- Game.Assets/Assets.cs | 22 +- Game.Assets/Game.Assets.csproj | 2 +- .../{hl2 => sdn}/cfg/config_default.cfg | 0 Game.Assets/sdn/cfg/skill.cfg | 274 ++++++++++++++++++ Game.Assets/sdn/cfg/skill_manifest.cfg | 1 + Game.Assets/{hl2 => sdn}/cfg/valve.rc | 0 Game.Assets/{hl2 => sdn}/gameinfo.txt | 6 +- .../{hl2 => sdn}/materials/console/kagami.vmt | 0 .../{hl2 => sdn}/materials/console/kagami.vtf | Bin .../materials/console/startup_loading.vtf | Bin .../materials/startup_loading.vtf | Bin .../sdn_resource/ConsoleExtraItems.res | 0 .../{hl2 => sdn}/sdn_resource/FontManager.res | 0 .../{hl2 => sdn}/sdn_resource/GameMenu.res | 0 .../sdn_resource/mountable_game_manifest.txt | 0 .../{hl2 => sdn}/shaders/bloomadd_gl460.fs | 0 .../{hl2 => sdn}/shaders/blurfilter_gl460.fs | 0 .../{hl2 => sdn}/shaders/blurfilter_gl460.vs | 0 .../shaders/common_clipplanes_gl460.vs | 0 .../shaders/common_flashlight_gl460.fs | 0 .../{hl2 => sdn}/shaders/common_gl460.fs | 0 .../{hl2 => sdn}/shaders/common_gl460.glsl | 0 .../{hl2 => sdn}/shaders/common_gl460.vs | 0 .../shaders/common_lighting_gl460.vs | 0 .../common_lightmappedgeneric_gl460.fs | 0 .../shaders/common_morph_gl460.vs | 0 .../shaders/common_skinning_gl460.vs | 0 .../shaders/common_vertex_shared_gl460.vs | 0 .../shaders/common_vertexlitgeneric_gl460.fs | 0 .../shaders/constant_color_gl460.fs | 0 .../{hl2 => sdn}/shaders/downsample_gl460.vs | 0 .../shaders/downsample_nohdr_gl460.fs | 0 .../{hl2 => sdn}/shaders/eyeglint_gl460.fs | 0 .../{hl2 => sdn}/shaders/eyeglint_gl460.vs | 0 .../{hl2 => sdn}/shaders/eyes_gl460.fs | 0 .../{hl2 => sdn}/shaders/eyes_gl460.vs | 0 .../shaders/introscreenspaceeffect_gl460.fs | 0 .../shaders/lightmappedgeneric_gl460.fs | 0 .../shaders/lightmappedgeneric_gl460.vs | 0 .../shaders/luminance_compare_gl460.fs | 0 .../shaders/screenspaceeffect_gl460.vs | 0 .../{hl2 => sdn}/shaders/shadow_gl460.fs | 0 .../{hl2 => sdn}/shaders/shadow_gl460.vs | 0 .../{hl2 => sdn}/shaders/shadowmodel_gl460.fs | 0 .../{hl2 => sdn}/shaders/shadowmodel_gl460.vs | 0 .../{hl2 => sdn}/shaders/skin_gl460.fs | 0 .../{hl2 => sdn}/shaders/skin_gl460.vs | 0 Game.Assets/{hl2 => sdn}/shaders/sky_gl460.fs | 0 Game.Assets/{hl2 => sdn}/shaders/sky_gl460.vs | 0 .../shaders/sky_hdr_compressed_gl460.fs | 0 .../shaders/sky_hdr_compressed_rgbs_gl460.fs | 0 .../{hl2 => sdn}/shaders/teeth_bump_gl460.fs | 0 .../{hl2 => sdn}/shaders/teeth_bump_gl460.vs | 0 .../{hl2 => sdn}/shaders/teeth_gl460.fs | 0 .../{hl2 => sdn}/shaders/teeth_gl460.vs | 0 .../shaders/unlitgeneric_gl460.fs | 0 .../shaders/unlitgeneric_gl460.vs | 0 .../shaders/unlittwotexture_gl460.fs | 0 .../shaders/unlittwotexture_gl460.vs | 0 .../shaders/vertexlitgeneric_bump_gl460.fs | 0 .../shaders/vertexlitgeneric_bump_gl460.vs | 0 .../shaders/vertexlitgeneric_gl460.fs | 0 .../shaders/vertexlitgeneric_gl460.vs | 0 .../{hl2 => sdn}/shaders/vortwarp_gl460.vs | 0 .../{hl2 => sdn}/shaders/water_gl460.fs | 0 .../{hl2 => sdn}/shaders/water_gl460.vs | 0 .../{hl2 => sdn}/shaders/watercheap_gl460.fs | 0 .../{hl2 => sdn}/shaders/watercheap_gl460.vs | 0 .../{hl2 => sdn}/shaders/white_gl460.fs | 0 .../shaders/worldvertextransition_gl460.fs | 0 .../shaders/worldvertextransition_gl460.vs | 0 .../{hl2 => sdn}/shaders/writez_gl460.vs | 0 Game.Shared/AchievementMgr.cs | 2 +- Source.Dedicated/Program.cs | 2 +- Source.Launcher/Program.cs | 2 +- 76 files changed, 303 insertions(+), 28 deletions(-) rename Game.Assets/{hl2 => sdn}/cfg/config_default.cfg (100%) create mode 100644 Game.Assets/sdn/cfg/skill.cfg create mode 100644 Game.Assets/sdn/cfg/skill_manifest.cfg rename Game.Assets/{hl2 => sdn}/cfg/valve.rc (100%) rename Game.Assets/{hl2 => sdn}/gameinfo.txt (89%) rename Game.Assets/{hl2 => sdn}/materials/console/kagami.vmt (100%) rename Game.Assets/{hl2 => sdn}/materials/console/kagami.vtf (100%) rename Game.Assets/{hl2 => sdn}/materials/console/startup_loading.vtf (100%) rename Game.Assets/{hl2 => sdn}/materials/startup_loading.vtf (100%) rename Game.Assets/{hl2 => sdn}/sdn_resource/ConsoleExtraItems.res (100%) rename Game.Assets/{hl2 => sdn}/sdn_resource/FontManager.res (100%) rename Game.Assets/{hl2 => sdn}/sdn_resource/GameMenu.res (100%) rename Game.Assets/{hl2 => sdn}/sdn_resource/mountable_game_manifest.txt (100%) rename Game.Assets/{hl2 => sdn}/shaders/bloomadd_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/blurfilter_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/blurfilter_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_clipplanes_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_flashlight_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_gl460.glsl (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_lighting_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_lightmappedgeneric_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_morph_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_skinning_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_vertex_shared_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/common_vertexlitgeneric_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/constant_color_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/downsample_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/downsample_nohdr_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/eyeglint_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/eyeglint_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/eyes_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/eyes_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/introscreenspaceeffect_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/lightmappedgeneric_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/lightmappedgeneric_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/luminance_compare_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/screenspaceeffect_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/shadow_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/shadow_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/shadowmodel_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/shadowmodel_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/skin_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/skin_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/sky_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/sky_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/sky_hdr_compressed_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/sky_hdr_compressed_rgbs_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/teeth_bump_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/teeth_bump_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/teeth_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/teeth_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/unlitgeneric_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/unlitgeneric_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/unlittwotexture_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/unlittwotexture_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/vertexlitgeneric_bump_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/vertexlitgeneric_bump_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/vertexlitgeneric_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/vertexlitgeneric_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/vortwarp_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/water_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/water_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/watercheap_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/watercheap_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/white_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/worldvertextransition_gl460.fs (100%) rename Game.Assets/{hl2 => sdn}/shaders/worldvertextransition_gl460.vs (100%) rename Game.Assets/{hl2 => sdn}/shaders/writez_gl460.vs (100%) diff --git a/.gitignore b/.gitignore index 7687d8596..621a8decd 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore # Source .VPK files. Mklink them if you want them. -Game.Assets/hl2/*.vpk +Game.Assets/sdn/*.vpk datatables_dump/* # User-specific files @@ -400,18 +400,18 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml -Game.Assets/hl2/steam.inf -Game.Assets/hl2/maps/* -Game.Assets/hl2/scripts -Game.Assets/hl2/maps +Game.Assets/sdn/steam.inf +Game.Assets/sdn/maps/* +Game.Assets/sdn/scripts +Game.Assets/sdn/maps Game.Assets/platform Game.Assets/sourceengine -Game.Assets/hl2/cfg/autoexec.cfg +Game.Assets/sdn/cfg/autoexec.cfg Game.Assets/**/*_bak/ -Game.Assets/hl2/resource +Game.Assets/sdn/resource Source.Launcher/Properties/launchSettings.json /.idea Source.DataDescGen/ -Game.Assets/hl2/cache/workshop -Game.Assets/hl2/gamemodes -Game.Assets/hl2/lua +Game.Assets/sdn/cache/workshop +Game.Assets/sdn/gamemodes +Game.Assets/sdn/lua diff --git a/Game.Assets/Assets.cs b/Game.Assets/Assets.cs index 78a8c55fc..498313de0 100644 --- a/Game.Assets/Assets.cs +++ b/Game.Assets/Assets.cs @@ -28,31 +28,31 @@ public static void CheckRequired() { public static List GetRequiredAssets() { List list = [ - new("hl2/steam.inf", "garrysmod/steam.inf"), + new("sdn/steam.inf", "garrysmod/steam.inf"), new("sourceengine", "sourceengine", IsDirectory: true), new("platform", "platform", IsDirectory: true), - new("hl2/maps", "garrysmod/maps", IsDirectory: true), - new("hl2/materials", "garrysmod/materials", IsDirectory: true), - new("hl2/resource", "garrysmod/resource", IsDirectory: true), - new("hl2/scenes", "garrysmod/scenes", IsDirectory: true), + new("sdn/maps", "garrysmod/maps", IsDirectory: true), + new("sdn/materials", "garrysmod/materials", IsDirectory: true), + new("sdn/resource", "garrysmod/resource", IsDirectory: true), + new("sdn/scenes", "garrysmod/scenes", IsDirectory: true), #if GMOD_DLL - new("hl2/gamemodes", "garrysmod/gamemodes", IsDirectory: true), - new("hl2/lua", "garrysmod/lua", IsDirectory: true), + new("sdn/gamemodes", "garrysmod/gamemodes", IsDirectory: true), + new("sdn/lua", "garrysmod/lua", IsDirectory: true), #endif - new("hl2/cache/workshop", "garrysmod/cache/workshop", IsDirectory: true, Optional: false), - new("hl2/settings", "garrysmod/settings", IsDirectory: true) + new("sdn/cache/workshop", "garrysmod/cache/workshop", IsDirectory: true, Optional: false), + new("sdn/settings", "garrysmod/settings", IsDirectory: true) ]; string[] specificGmodVpks = ["dir", "000", "001", "002"]; foreach (var suffix in specificGmodVpks) - list.Add(new($"hl2/garrysmod_{suffix}.vpk", $"garrysmod/garrysmod_{suffix}.vpk")); + list.Add(new($"sdn/garrysmod_{suffix}.vpk", $"garrysmod/garrysmod_{suffix}.vpk")); return list; } public static List GetOptionalAssets() { return [ - new("hl2/cfg/autoexec.cfg", "garrysmod/cfg/autoexec.cfg", Optional: true) + new("sdn/cfg/autoexec.cfg", "garrysmod/cfg/autoexec.cfg", Optional: true) ]; } diff --git a/Game.Assets/Game.Assets.csproj b/Game.Assets/Game.Assets.csproj index 3024508f2..007937c07 100644 --- a/Game.Assets/Game.Assets.csproj +++ b/Game.Assets/Game.Assets.csproj @@ -16,7 +16,7 @@ - + diff --git a/Game.Assets/hl2/cfg/config_default.cfg b/Game.Assets/sdn/cfg/config_default.cfg similarity index 100% rename from Game.Assets/hl2/cfg/config_default.cfg rename to Game.Assets/sdn/cfg/config_default.cfg diff --git a/Game.Assets/sdn/cfg/skill.cfg b/Game.Assets/sdn/cfg/skill.cfg new file mode 100644 index 000000000..f850ee57f --- /dev/null +++ b/Game.Assets/sdn/cfg/skill.cfg @@ -0,0 +1,274 @@ +// =========== +// NPCs +// ============ +// Barnacle +sk_barnacle_health "35" + +// Barney +sk_barney_health "35" + +// Bullseye +sk_bullseye_health "35" + +// Bullsquid +//sk_bullsquid_health "120" +//sk_bullsquid_dmg_bite "15" +//sk_bullsquid_dmg_whip "25" + +// Citizen +sk_citizen_health "40" + +// Combine Soldier +sk_combine_s_health "50" +sk_combine_s_kick "10" + +// Combine Guard +sk_combine_guard_health "70" +sk_combine_guard_kick "15" + +// strider +sk_strider_health "350" +sk_strider_num_missiles1 "5" +sk_strider_num_missiles2 "7" +sk_strider_num_missiles3 "7" + +// Headcrab +sk_headcrab_health "10" +sk_headcrab_melee_dmg "5" + +// Fast Headcrab +sk_headcrab_fast_health "10" + +// Poison Headcrab +sk_headcrab_poison_health "35" + +// Houndeye +//sk_houndeye_health "80" +//sk_houndeye_dmg_blast "25" + +// Manhack +sk_manhack_health "25" +sk_manhack_melee_dmg "20" + +// Metropolice +sk_metropolice_health "40" +sk_metropolice_stitch_reaction "1.0" +sk_metropolice_stitch_tight_hitcount "2" +sk_metropolice_stitch_at_hitcount "1" +sk_metropolice_stitch_behind_hitcount "3" +sk_metropolice_stitch_along_hitcount "2" + +// Rollermine +sk_rollermine_shock "10" +sk_rollermine_stun_delay "3" +sk_rollermine_vehicle_intercept "1" + +// Scanner (City) +sk_scanner_health "30" +sk_scanner_dmg_dive "25" + +// Stalker +sk_stalker_health "50" +sk_stalker_melee_dmg "5" + +// Vortigaunt +sk_vortigaunt_health "100" +sk_vortigaunt_dmg_claw "10" +sk_vortigaunt_dmg_rake "25" +sk_vortigaunt_dmg_zap "50" +sk_vortigaunt_armor_charge "30" + +// Zombie +sk_zombie_health "50" +sk_zombie_dmg_one_slash "10" +sk_zombie_dmg_both_slash "25" + +// Poison Zombie +sk_zombie_poison_health "175" +sk_zombie_poison_dmg_spit "20" + +//Antlion +sk_antlion_health "30" +sk_antlion_swipe_damage "5" +sk_antlion_jump_damage "5" + +//Antlion Guard +sk_antlionguard_health "500" +sk_antlionguard_dmg_charge "20" +sk_antlionguard_dmg_shove "10" + +//Antlion Grub +//sk_antliongrub_health "5" + +//Ichthyosaur +sk_ichthyosaur_health "200" +sk_ichthyosaur_melee_dmg "8" +sk_ichthyosaur_shake "20" + +// Combine Gunship +sk_gunship_burst_size "15" +sk_gunship_health_increments "5" +sk_npc_dmg_gunship "40" +sk_npc_dmg_gunship_to_plr "3" + +// Combine Helicopter +sk_npc_dmg_helicopter "6" +sk_npc_dmg_helicopter_to_plr "3" +sk_helicopter_grenadedamage "30" +sk_helicopter_grenaderadius "275" +sk_helicopter_grenadeforce "55000" + +// Combine Dropship +sk_npc_dmg_dropship "2" + +// Combine APC +sk_apc_health "750" + + +// ================= +// WEAPONS +// ================= + +sk_plr_dmg_ar2 "8" +sk_npc_dmg_ar2 "3" +sk_max_ar2 "60" +sk_max_ar2_altfire "3" + +sk_plr_dmg_alyxgun "5" +sk_npc_dmg_alyxgun "3" +sk_max_alyxgun "150" + +sk_plr_dmg_pistol "5" +sk_npc_dmg_pistol "3" +sk_max_pistol "150" + +sk_plr_dmg_smg1 "4" +sk_npc_dmg_smg1 "3" +sk_max_smg1 "225" + +sk_plr_dmg_buckshot "8" +sk_npc_dmg_buckshot "3" +sk_max_buckshot "30" + +sk_plr_dmg_rpg_round "100" +sk_npc_dmg_rpg_round "50" +sk_max_rpg_round "3" + +sk_plr_dmg_smg1_grenade "100" +sk_npc_dmg_smg1_grenade "50" +sk_max_smg1_grenade "3" +sk_smg1_grenade_radius "250" + +//sk_plr_dmg_gauss "25" +//sk_plr_max_dmg_gauss "30" + +sk_plr_dmg_sniper_round "20" +sk_npc_dmg_sniper_round "100" +sk_max_sniper_round "30" + +sk_plr_dmg_357 "40" +sk_npc_dmg_357 "30" +sk_max_357 "12" + +sk_plr_dmg_crossbow "100" +sk_npc_dmg_crossbow "10" +sk_max_crossbow "10" + +sk_plr_dmg_airboat "3" +sk_npc_dmg_airboat "3" + +//sk_dmg_sniper_penetrate_plr "10" +//sk_dmg_sniper_penetrate_npc "100" + +sk_plr_dmg_grenade "150" +sk_npc_dmg_grenade "75" +sk_max_grenade "5" + +sk_plr_dmg_crowbar "10" +sk_npc_dmg_crowbar "5" + +sk_plr_dmg_stunstick "10" +sk_npc_dmg_stunstick "40" // Kill a citizen in one hit + +//sk_plr_dmg_satchel "150" +//sk_npc_dmg_satchel "75" +//sk_satchel_radius "150" + +// Mortar Synth projectile +//sk_dmg_energy_grenade "2" +//sk_energy_grenade_radius "100" + +sk_dmg_homer_grenade "20" +sk_homer_grenade_radius "100" + +// Bullsquid spit +//sk_dmg_spit_grenade "5" +//sk_spit_grenade_radius "50" + +//sk_plr_dmg_tripmine "150" +//sk_npc_dmg_tripmine "125" +//sk_tripmine_radius "200" + +sk_plr_dmg_fraggrenade "125" +sk_npc_dmg_fraggrenade "75" +sk_fraggrenade_radius "250" + +// HEALTH/SUIT CHARGE DISTRIBUTION +sk_suitcharger "75" +sk_suitcharger_citadel "500" +sk_suitcharger_citadel_maxarmor "200" +sk_battery "15" +sk_healthcharger "50" +sk_healthkit "25" +sk_healthvial "10" + +// Combine balls +sk_combineball_seek_angle "15" +sk_combineball_guidefactor "1.0" + +// NPC damage adjusters +sk_npc_head "3" +sk_npc_chest "1" +sk_npc_stomach "1" +sk_npc_arm "1" +sk_npc_leg "1" + +// player damage adjusters +sk_player_head "3" +sk_player_chest "1" +sk_player_stomach "1" +sk_player_arm "1" +sk_player_leg "1" + +// Allies +sk_ally_regen_time "0.2" + +// Jeep +sk_max_gauss_round "30" + + +ai_enable_fear_behavior "1" + +// zombine +sk_zombie_soldier_health "100" + +// Episodic APC - Experimental +sk_apc_missile_damage "50" + +// Antlion air attack +sk_antlion_air_attack_dmg "10" + +// Antlion worker +sk_antlion_worker_spit_speed "600" +sk_antlion_worker_health "60" + +// Vortigaunt charge limit +sk_vortigaunt_armor_charge "15" +sk_vortigaunt_armor_charge_per_token "5" +sk_vortigaunt_dmg_zap "25" + +// Poison headcrab +sk_headcrab_poison_npc_damage "20.0" + +// advisor +sk_advisor_health "1000" diff --git a/Game.Assets/sdn/cfg/skill_manifest.cfg b/Game.Assets/sdn/cfg/skill_manifest.cfg new file mode 100644 index 000000000..585f27f80 --- /dev/null +++ b/Game.Assets/sdn/cfg/skill_manifest.cfg @@ -0,0 +1 @@ +exec skill.cfg diff --git a/Game.Assets/hl2/cfg/valve.rc b/Game.Assets/sdn/cfg/valve.rc similarity index 100% rename from Game.Assets/hl2/cfg/valve.rc rename to Game.Assets/sdn/cfg/valve.rc diff --git a/Game.Assets/hl2/gameinfo.txt b/Game.Assets/sdn/gameinfo.txt similarity index 89% rename from Game.Assets/hl2/gameinfo.txt rename to Game.Assets/sdn/gameinfo.txt index 373904494..7cbf4e740 100644 --- a/Game.Assets/hl2/gameinfo.txt +++ b/Game.Assets/sdn/gameinfo.txt @@ -15,7 +15,7 @@ SearchPaths { - game+mod hl2/garrysmod.vpk + game+mod sdn/garrysmod.vpk game |all_source_engine_paths|sourceengine/hl2_textures.vpk game |all_source_engine_paths|sourceengine/hl2_sound_vo_english.vpk @@ -26,12 +26,12 @@ mod+mod_write+default_write_path |gameinfo_path|. - game+game_write hl2 + game+game_write sdn game |all_source_engine_paths|sourceengine platform |all_source_engine_paths|platform - game+download hl2/download + game+download sdn/download } } } diff --git a/Game.Assets/hl2/materials/console/kagami.vmt b/Game.Assets/sdn/materials/console/kagami.vmt similarity index 100% rename from Game.Assets/hl2/materials/console/kagami.vmt rename to Game.Assets/sdn/materials/console/kagami.vmt diff --git a/Game.Assets/hl2/materials/console/kagami.vtf b/Game.Assets/sdn/materials/console/kagami.vtf similarity index 100% rename from Game.Assets/hl2/materials/console/kagami.vtf rename to Game.Assets/sdn/materials/console/kagami.vtf diff --git a/Game.Assets/hl2/materials/console/startup_loading.vtf b/Game.Assets/sdn/materials/console/startup_loading.vtf similarity index 100% rename from Game.Assets/hl2/materials/console/startup_loading.vtf rename to Game.Assets/sdn/materials/console/startup_loading.vtf diff --git a/Game.Assets/hl2/materials/startup_loading.vtf b/Game.Assets/sdn/materials/startup_loading.vtf similarity index 100% rename from Game.Assets/hl2/materials/startup_loading.vtf rename to Game.Assets/sdn/materials/startup_loading.vtf diff --git a/Game.Assets/hl2/sdn_resource/ConsoleExtraItems.res b/Game.Assets/sdn/sdn_resource/ConsoleExtraItems.res similarity index 100% rename from Game.Assets/hl2/sdn_resource/ConsoleExtraItems.res rename to Game.Assets/sdn/sdn_resource/ConsoleExtraItems.res diff --git a/Game.Assets/hl2/sdn_resource/FontManager.res b/Game.Assets/sdn/sdn_resource/FontManager.res similarity index 100% rename from Game.Assets/hl2/sdn_resource/FontManager.res rename to Game.Assets/sdn/sdn_resource/FontManager.res diff --git a/Game.Assets/hl2/sdn_resource/GameMenu.res b/Game.Assets/sdn/sdn_resource/GameMenu.res similarity index 100% rename from Game.Assets/hl2/sdn_resource/GameMenu.res rename to Game.Assets/sdn/sdn_resource/GameMenu.res diff --git a/Game.Assets/hl2/sdn_resource/mountable_game_manifest.txt b/Game.Assets/sdn/sdn_resource/mountable_game_manifest.txt similarity index 100% rename from Game.Assets/hl2/sdn_resource/mountable_game_manifest.txt rename to Game.Assets/sdn/sdn_resource/mountable_game_manifest.txt diff --git a/Game.Assets/hl2/shaders/bloomadd_gl460.fs b/Game.Assets/sdn/shaders/bloomadd_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/bloomadd_gl460.fs rename to Game.Assets/sdn/shaders/bloomadd_gl460.fs diff --git a/Game.Assets/hl2/shaders/blurfilter_gl460.fs b/Game.Assets/sdn/shaders/blurfilter_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/blurfilter_gl460.fs rename to Game.Assets/sdn/shaders/blurfilter_gl460.fs diff --git a/Game.Assets/hl2/shaders/blurfilter_gl460.vs b/Game.Assets/sdn/shaders/blurfilter_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/blurfilter_gl460.vs rename to Game.Assets/sdn/shaders/blurfilter_gl460.vs diff --git a/Game.Assets/hl2/shaders/common_clipplanes_gl460.vs b/Game.Assets/sdn/shaders/common_clipplanes_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/common_clipplanes_gl460.vs rename to Game.Assets/sdn/shaders/common_clipplanes_gl460.vs diff --git a/Game.Assets/hl2/shaders/common_flashlight_gl460.fs b/Game.Assets/sdn/shaders/common_flashlight_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/common_flashlight_gl460.fs rename to Game.Assets/sdn/shaders/common_flashlight_gl460.fs diff --git a/Game.Assets/hl2/shaders/common_gl460.fs b/Game.Assets/sdn/shaders/common_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/common_gl460.fs rename to Game.Assets/sdn/shaders/common_gl460.fs diff --git a/Game.Assets/hl2/shaders/common_gl460.glsl b/Game.Assets/sdn/shaders/common_gl460.glsl similarity index 100% rename from Game.Assets/hl2/shaders/common_gl460.glsl rename to Game.Assets/sdn/shaders/common_gl460.glsl diff --git a/Game.Assets/hl2/shaders/common_gl460.vs b/Game.Assets/sdn/shaders/common_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/common_gl460.vs rename to Game.Assets/sdn/shaders/common_gl460.vs diff --git a/Game.Assets/hl2/shaders/common_lighting_gl460.vs b/Game.Assets/sdn/shaders/common_lighting_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/common_lighting_gl460.vs rename to Game.Assets/sdn/shaders/common_lighting_gl460.vs diff --git a/Game.Assets/hl2/shaders/common_lightmappedgeneric_gl460.fs b/Game.Assets/sdn/shaders/common_lightmappedgeneric_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/common_lightmappedgeneric_gl460.fs rename to Game.Assets/sdn/shaders/common_lightmappedgeneric_gl460.fs diff --git a/Game.Assets/hl2/shaders/common_morph_gl460.vs b/Game.Assets/sdn/shaders/common_morph_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/common_morph_gl460.vs rename to Game.Assets/sdn/shaders/common_morph_gl460.vs diff --git a/Game.Assets/hl2/shaders/common_skinning_gl460.vs b/Game.Assets/sdn/shaders/common_skinning_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/common_skinning_gl460.vs rename to Game.Assets/sdn/shaders/common_skinning_gl460.vs diff --git a/Game.Assets/hl2/shaders/common_vertex_shared_gl460.vs b/Game.Assets/sdn/shaders/common_vertex_shared_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/common_vertex_shared_gl460.vs rename to Game.Assets/sdn/shaders/common_vertex_shared_gl460.vs diff --git a/Game.Assets/hl2/shaders/common_vertexlitgeneric_gl460.fs b/Game.Assets/sdn/shaders/common_vertexlitgeneric_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/common_vertexlitgeneric_gl460.fs rename to Game.Assets/sdn/shaders/common_vertexlitgeneric_gl460.fs diff --git a/Game.Assets/hl2/shaders/constant_color_gl460.fs b/Game.Assets/sdn/shaders/constant_color_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/constant_color_gl460.fs rename to Game.Assets/sdn/shaders/constant_color_gl460.fs diff --git a/Game.Assets/hl2/shaders/downsample_gl460.vs b/Game.Assets/sdn/shaders/downsample_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/downsample_gl460.vs rename to Game.Assets/sdn/shaders/downsample_gl460.vs diff --git a/Game.Assets/hl2/shaders/downsample_nohdr_gl460.fs b/Game.Assets/sdn/shaders/downsample_nohdr_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/downsample_nohdr_gl460.fs rename to Game.Assets/sdn/shaders/downsample_nohdr_gl460.fs diff --git a/Game.Assets/hl2/shaders/eyeglint_gl460.fs b/Game.Assets/sdn/shaders/eyeglint_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/eyeglint_gl460.fs rename to Game.Assets/sdn/shaders/eyeglint_gl460.fs diff --git a/Game.Assets/hl2/shaders/eyeglint_gl460.vs b/Game.Assets/sdn/shaders/eyeglint_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/eyeglint_gl460.vs rename to Game.Assets/sdn/shaders/eyeglint_gl460.vs diff --git a/Game.Assets/hl2/shaders/eyes_gl460.fs b/Game.Assets/sdn/shaders/eyes_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/eyes_gl460.fs rename to Game.Assets/sdn/shaders/eyes_gl460.fs diff --git a/Game.Assets/hl2/shaders/eyes_gl460.vs b/Game.Assets/sdn/shaders/eyes_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/eyes_gl460.vs rename to Game.Assets/sdn/shaders/eyes_gl460.vs diff --git a/Game.Assets/hl2/shaders/introscreenspaceeffect_gl460.fs b/Game.Assets/sdn/shaders/introscreenspaceeffect_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/introscreenspaceeffect_gl460.fs rename to Game.Assets/sdn/shaders/introscreenspaceeffect_gl460.fs diff --git a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs b/Game.Assets/sdn/shaders/lightmappedgeneric_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/lightmappedgeneric_gl460.fs rename to Game.Assets/sdn/shaders/lightmappedgeneric_gl460.fs diff --git a/Game.Assets/hl2/shaders/lightmappedgeneric_gl460.vs b/Game.Assets/sdn/shaders/lightmappedgeneric_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/lightmappedgeneric_gl460.vs rename to Game.Assets/sdn/shaders/lightmappedgeneric_gl460.vs diff --git a/Game.Assets/hl2/shaders/luminance_compare_gl460.fs b/Game.Assets/sdn/shaders/luminance_compare_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/luminance_compare_gl460.fs rename to Game.Assets/sdn/shaders/luminance_compare_gl460.fs diff --git a/Game.Assets/hl2/shaders/screenspaceeffect_gl460.vs b/Game.Assets/sdn/shaders/screenspaceeffect_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/screenspaceeffect_gl460.vs rename to Game.Assets/sdn/shaders/screenspaceeffect_gl460.vs diff --git a/Game.Assets/hl2/shaders/shadow_gl460.fs b/Game.Assets/sdn/shaders/shadow_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/shadow_gl460.fs rename to Game.Assets/sdn/shaders/shadow_gl460.fs diff --git a/Game.Assets/hl2/shaders/shadow_gl460.vs b/Game.Assets/sdn/shaders/shadow_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/shadow_gl460.vs rename to Game.Assets/sdn/shaders/shadow_gl460.vs diff --git a/Game.Assets/hl2/shaders/shadowmodel_gl460.fs b/Game.Assets/sdn/shaders/shadowmodel_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/shadowmodel_gl460.fs rename to Game.Assets/sdn/shaders/shadowmodel_gl460.fs diff --git a/Game.Assets/hl2/shaders/shadowmodel_gl460.vs b/Game.Assets/sdn/shaders/shadowmodel_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/shadowmodel_gl460.vs rename to Game.Assets/sdn/shaders/shadowmodel_gl460.vs diff --git a/Game.Assets/hl2/shaders/skin_gl460.fs b/Game.Assets/sdn/shaders/skin_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/skin_gl460.fs rename to Game.Assets/sdn/shaders/skin_gl460.fs diff --git a/Game.Assets/hl2/shaders/skin_gl460.vs b/Game.Assets/sdn/shaders/skin_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/skin_gl460.vs rename to Game.Assets/sdn/shaders/skin_gl460.vs diff --git a/Game.Assets/hl2/shaders/sky_gl460.fs b/Game.Assets/sdn/shaders/sky_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/sky_gl460.fs rename to Game.Assets/sdn/shaders/sky_gl460.fs diff --git a/Game.Assets/hl2/shaders/sky_gl460.vs b/Game.Assets/sdn/shaders/sky_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/sky_gl460.vs rename to Game.Assets/sdn/shaders/sky_gl460.vs diff --git a/Game.Assets/hl2/shaders/sky_hdr_compressed_gl460.fs b/Game.Assets/sdn/shaders/sky_hdr_compressed_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/sky_hdr_compressed_gl460.fs rename to Game.Assets/sdn/shaders/sky_hdr_compressed_gl460.fs diff --git a/Game.Assets/hl2/shaders/sky_hdr_compressed_rgbs_gl460.fs b/Game.Assets/sdn/shaders/sky_hdr_compressed_rgbs_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/sky_hdr_compressed_rgbs_gl460.fs rename to Game.Assets/sdn/shaders/sky_hdr_compressed_rgbs_gl460.fs diff --git a/Game.Assets/hl2/shaders/teeth_bump_gl460.fs b/Game.Assets/sdn/shaders/teeth_bump_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/teeth_bump_gl460.fs rename to Game.Assets/sdn/shaders/teeth_bump_gl460.fs diff --git a/Game.Assets/hl2/shaders/teeth_bump_gl460.vs b/Game.Assets/sdn/shaders/teeth_bump_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/teeth_bump_gl460.vs rename to Game.Assets/sdn/shaders/teeth_bump_gl460.vs diff --git a/Game.Assets/hl2/shaders/teeth_gl460.fs b/Game.Assets/sdn/shaders/teeth_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/teeth_gl460.fs rename to Game.Assets/sdn/shaders/teeth_gl460.fs diff --git a/Game.Assets/hl2/shaders/teeth_gl460.vs b/Game.Assets/sdn/shaders/teeth_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/teeth_gl460.vs rename to Game.Assets/sdn/shaders/teeth_gl460.vs diff --git a/Game.Assets/hl2/shaders/unlitgeneric_gl460.fs b/Game.Assets/sdn/shaders/unlitgeneric_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/unlitgeneric_gl460.fs rename to Game.Assets/sdn/shaders/unlitgeneric_gl460.fs diff --git a/Game.Assets/hl2/shaders/unlitgeneric_gl460.vs b/Game.Assets/sdn/shaders/unlitgeneric_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/unlitgeneric_gl460.vs rename to Game.Assets/sdn/shaders/unlitgeneric_gl460.vs diff --git a/Game.Assets/hl2/shaders/unlittwotexture_gl460.fs b/Game.Assets/sdn/shaders/unlittwotexture_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/unlittwotexture_gl460.fs rename to Game.Assets/sdn/shaders/unlittwotexture_gl460.fs diff --git a/Game.Assets/hl2/shaders/unlittwotexture_gl460.vs b/Game.Assets/sdn/shaders/unlittwotexture_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/unlittwotexture_gl460.vs rename to Game.Assets/sdn/shaders/unlittwotexture_gl460.vs diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.fs b/Game.Assets/sdn/shaders/vertexlitgeneric_bump_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.fs rename to Game.Assets/sdn/shaders/vertexlitgeneric_bump_gl460.fs diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.vs b/Game.Assets/sdn/shaders/vertexlitgeneric_bump_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/vertexlitgeneric_bump_gl460.vs rename to Game.Assets/sdn/shaders/vertexlitgeneric_bump_gl460.vs diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.fs b/Game.Assets/sdn/shaders/vertexlitgeneric_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/vertexlitgeneric_gl460.fs rename to Game.Assets/sdn/shaders/vertexlitgeneric_gl460.fs diff --git a/Game.Assets/hl2/shaders/vertexlitgeneric_gl460.vs b/Game.Assets/sdn/shaders/vertexlitgeneric_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/vertexlitgeneric_gl460.vs rename to Game.Assets/sdn/shaders/vertexlitgeneric_gl460.vs diff --git a/Game.Assets/hl2/shaders/vortwarp_gl460.vs b/Game.Assets/sdn/shaders/vortwarp_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/vortwarp_gl460.vs rename to Game.Assets/sdn/shaders/vortwarp_gl460.vs diff --git a/Game.Assets/hl2/shaders/water_gl460.fs b/Game.Assets/sdn/shaders/water_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/water_gl460.fs rename to Game.Assets/sdn/shaders/water_gl460.fs diff --git a/Game.Assets/hl2/shaders/water_gl460.vs b/Game.Assets/sdn/shaders/water_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/water_gl460.vs rename to Game.Assets/sdn/shaders/water_gl460.vs diff --git a/Game.Assets/hl2/shaders/watercheap_gl460.fs b/Game.Assets/sdn/shaders/watercheap_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/watercheap_gl460.fs rename to Game.Assets/sdn/shaders/watercheap_gl460.fs diff --git a/Game.Assets/hl2/shaders/watercheap_gl460.vs b/Game.Assets/sdn/shaders/watercheap_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/watercheap_gl460.vs rename to Game.Assets/sdn/shaders/watercheap_gl460.vs diff --git a/Game.Assets/hl2/shaders/white_gl460.fs b/Game.Assets/sdn/shaders/white_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/white_gl460.fs rename to Game.Assets/sdn/shaders/white_gl460.fs diff --git a/Game.Assets/hl2/shaders/worldvertextransition_gl460.fs b/Game.Assets/sdn/shaders/worldvertextransition_gl460.fs similarity index 100% rename from Game.Assets/hl2/shaders/worldvertextransition_gl460.fs rename to Game.Assets/sdn/shaders/worldvertextransition_gl460.fs diff --git a/Game.Assets/hl2/shaders/worldvertextransition_gl460.vs b/Game.Assets/sdn/shaders/worldvertextransition_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/worldvertextransition_gl460.vs rename to Game.Assets/sdn/shaders/worldvertextransition_gl460.vs diff --git a/Game.Assets/hl2/shaders/writez_gl460.vs b/Game.Assets/sdn/shaders/writez_gl460.vs similarity index 100% rename from Game.Assets/hl2/shaders/writez_gl460.vs rename to Game.Assets/sdn/shaders/writez_gl460.vs diff --git a/Game.Shared/AchievementMgr.cs b/Game.Shared/AchievementMgr.cs index 5490f9b4d..04659f6bc 100644 --- a/Game.Shared/AchievementMgr.cs +++ b/Game.Shared/AchievementMgr.cs @@ -311,7 +311,7 @@ public void DownloadUserData() { static ReadOnlySpan COM_GetModDirectory() { if (modDir[0] == '\0') { ICommandLine commandLine = Singleton(); - string gamedir = commandLine.ParmValue("-game", commandLine.ParmValue("-defaultgamedir", "hl2")); + string gamedir = commandLine.ParmValue("-game", commandLine.ParmValue("-defaultgamedir", "sdn")); strcpy(modDir, gamedir); if (!strchr(modDir, '/').IsEmpty || !strchr(modDir, '\\').IsEmpty) { StrTools.StripLastDir(modDir); diff --git a/Source.Dedicated/Program.cs b/Source.Dedicated/Program.cs index 300dad181..7a7f00776 100644 --- a/Source.Dedicated/Program.cs +++ b/Source.Dedicated/Program.cs @@ -169,7 +169,7 @@ private void PreInit() { info.TextMode = isTextMode; } - const string defaultHalfLife2GameDirectory = "hl2"; + const string defaultHalfLife2GameDirectory = "sdn"; private string DetermineInitialMod() { return !isEditMode ? commandLine.ParmValue("-game", defaultHalfLife2GameDirectory) : throw new NotImplementedException("No editmode support"); diff --git a/Source.Launcher/Program.cs b/Source.Launcher/Program.cs index 2978c38a8..77bbf40ca 100644 --- a/Source.Launcher/Program.cs +++ b/Source.Launcher/Program.cs @@ -129,7 +129,7 @@ private void PreInit() { Panel.InitializeControls(); } - const string defaultHalfLife2GameDirectory = "hl2"; + const string defaultHalfLife2GameDirectory = "sdn"; private string DetermineInitialMod() { return !isEditMode ? commandLine.ParmValue("-game", defaultHalfLife2GameDirectory) : throw new NotImplementedException("No editmode support"); From 5d9a5b353a234ed06285682019bdf7d81f1f59b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 00:41:17 +0300 Subject: [PATCH 39/73] Port NPC facing, sequence, chase path and turn tasks --- Game.Server/AI_BaseNPC.cs | 465 +++++++++++++++++++++++++++++++--- Game.Server/BaseAnimating.cs | 36 +++ Game.Server/HL2/HL2_Player.cs | 11 +- Game.Server/Player.cs | 1 + 4 files changed, 480 insertions(+), 33 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index e74422c90..6aa4ef6c4 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -152,6 +152,16 @@ public static bool FBoxVisible(BaseEntity looker, BaseEntity target, out Vector3 return false; } + public static void AI_TraceLOS(in Vector3 absStart, in Vector3 absEnd, BaseEntity? looker, out Trace tr) { + if (ai_LOS_mode.GetBool()) { + Util.TraceLine(absStart, absEnd, Mask.BlockLOS, looker, CollisionGroup.None, out tr); + return; + } + + TraceFilterLOS traceFilter = new(looker, CollisionGroup.None); + Util.TraceLine(absStart, absEnd, Mask.BlockLOSAndNPCs, ref traceFilter, out tr); + } + public static bool AI_DoLoadSchedules(Func baseLoad, Action initCustomSchedules, ref AI_SchedLoadStatus loadStatus) { baseLoad(); @@ -3989,6 +3999,113 @@ public void ResetIdealActivity(Activity newIdealActivity) { SetIdealActivity(newIdealActivity); } + public void StartTurn(float deltaYaw) { + float currentYaw = Util.AngleMod(GetLocalAngles().Y); + GetMotor()!.SetIdealYaw(Util.AngleMod(currentYaw + deltaYaw)); + SetTurnActivity(); + } + + public float CalcReasonableFacing(bool ignoreOriginalFacing = false) { + float reasonableYaw; + + if (!ignoreOriginalFacing && !HasMemory(AI_MemoryFlags.MovedFromSpawn) && !HasCondition((int)SCOND_t.COND_SEE_ENEMY)) + reasonableYaw = OriginalYaw; + else { + QAngle angles = new(0, 0, 0); + + float idealYaw = GetMotor()!.GetIdealYaw(); + + reasonableYaw = idealYaw; + + float MIN_DIST = GetReasonableFacingDist(); + float longestTrace = 0; + + if (MIN_DIST == 0) + return reasonableYaw; + + const float SLICES = 8.0f; + const float SIZE_SLICE = 360.0f / SLICES; + const int SEARCH_MAX = (int)SLICES / 2; + + float zEye = GetAbsOrigin().Z + DefaultEyeOffset.Z; + + for (int i = 0; i <= SEARCH_MAX; i++) { + float offset = i * SIZE_SLICE; + for (int j = -1; j <= 1; j += 2) { + angles.Y = idealYaw + (offset * j); + MathLib.AngleVectors(angles, out Vector3 forward); + float curTrace; + if ((curTrace = LineOfSightDist(forward, zEye)) > longestTrace && IsValidReasonableFacing(forward, curTrace)) { + reasonableYaw = angles.Y; + longestTrace = curTrace; + } + + if (longestTrace > MIN_DIST) + break; + + if (i == 0 || i == SEARCH_MAX) + break; + } + + if (longestTrace > MIN_DIST) + break; + } + } + + return reasonableYaw; + } + + public virtual float GetReasonableFacingDist() { + if (GetTask() != null && GetTask()!.Value.Task == TASK_FACE_ENEMY) { + const float dist = 3.5f * 12; + if (GetEnemy() != null) { + float distEnemy = (GetEnemy()!.GetAbsOrigin().AsVector2D() - GetAbsOrigin().AsVector2D()).Length() - 1.0f; + return MathF.Min(distEnemy, dist); + } + + return dist; + } + return 5 * 12; + } + + public virtual bool IsValidReasonableFacing(in Vector3 sightDir, float sightDist) => true; + + public float LineOfSightDist(in Vector3 dir, float zEye = float.MaxValue) { + Vector3 testDir; + if (dir == vec3_invalid) + testDir = EyeDirection3D(); + else + testDir = dir; + + if (zEye == float.MaxValue) + zEye = EyePosition().Z; + + Vector3 testPos = new(GetAbsOrigin().X, GetAbsOrigin().Y, zEye); + AI_TraceLOS(testPos, testPos + testDir * MAX_COORD_RANGE, this, out Trace tr); + return (tr.StartPos - tr.EndPos).Length(); + } + + public bool FInAimCone(in Vector3 spot) { + Vector3 los = spot - GetAbsOrigin(); + + los.Z = 0; + MathLib.VectorNormalize(ref los); + + Vector3 facingDir = BodyDirection2D(); + + float dot = Vector3.Dot(los, facingDir); + + if ((CapabilitiesGet() & Capability.AimGun) != 0) + return dot > BasePlayer.DOT_30DEGREE; + + if (dot > 0.994) + return true; + + return false; + } + + public virtual void SpeakSentence(int sentenceType) { } + public bool FacingIdeal() { if (MathF.Abs(GetMotor()!.DeltaIdealYaw()) <= 0.006) return true; @@ -4301,25 +4418,216 @@ public virtual void StartTask(in Task_t task) { TaskComplete(); break; - case TASK_CREATE_PENDING_WEAPON: - case TASK_RANDOMIZE_FRAMERATE: - case TASK_DEFER_DODGE: - case TASK_ANNOUNCE_ATTACK: case TASK_TURN_RIGHT: + StartTurn(-task.TaskData); + break; + case TASK_TURN_LEFT: + StartTurn(task.TaskData); + break; + case TASK_REMEMBER: + Remember((AI_MemoryFlags)(int)task.TaskData); + TaskComplete(); + break; + case TASK_FORGET: - case TASK_FIND_HINTNODE: - case TASK_FIND_LOCK_HINTNODE: - case TASK_LOCK_HINTNODE: - case TASK_STORE_BESTSOUND_IN_SAVEPOSITION: - case TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION: - case TASK_CLEAR_HINTNODE: + Forget((AI_MemoryFlags)(int)task.TaskData); + TaskComplete(); + break; + + case TASK_STORE_BESTSOUND_IN_SAVEPOSITION: { + ref WorldSoundInstance bestSound = ref GetBestSound(); + if (!Unsafe.IsNullRef(ref bestSound)) { + SavePosition = bestSound.GetSoundOrigin(); + BaseEntity? soundEnt = bestSound.Owner.Get(); + if (soundEnt != null) { + soundEnt.GetVelocity(out Vector3 vel, out _); + SavePosition += vel * 2; + } + TaskComplete(); + } + else { + TaskFail("No Sound!"); + return; + } + } + break; + + case TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION: { + ref WorldSoundInstance bestSound = ref GetBestSound(); + if (!Unsafe.IsNullRef(ref bestSound)) { + SavePosition = bestSound.GetSoundReactOrigin(); + TaskComplete(); + } + else { + TaskFail("No Sound!"); + return; + } + } + break; + case TASK_PLAY_PRIVATE_SEQUENCE: case TASK_PLAY_PRIVATE_SEQUENCE_FACE_ENEMY: case TASK_PLAY_SEQUENCE_FACE_ENEMY: case TASK_PLAY_SEQUENCE_FACE_TARGET: case TASK_PLAY_SEQUENCE: + SetIdealActivity((Activity)(int)task.TaskData); + break; + + case TASK_FACE_LASTPOSITION: + GetMotor()!.SetIdealYawToTarget(LastPosition); + GetMotor()!.SetIdealYaw(CalcReasonableFacing(true)); + SetTurnActivity(); + break; + + case TASK_FACE_SAVEPOSITION: + GetMotor()!.SetIdealYawToTarget(SavePosition); + GetMotor()!.SetIdealYaw(CalcReasonableFacing(true)); + SetTurnActivity(); + break; + + case TASK_FACE_AWAY_FROM_SAVEPOSITION: + GetMotor()!.SetIdealYawToTarget(SavePosition, 0, 180.0f); + GetMotor()!.SetIdealYaw(CalcReasonableFacing(true)); + SetTurnActivity(); + break; + + case TASK_SET_IDEAL_YAW_TO_CURRENT: + GetMotor()!.SetIdealYaw(Util.AngleMod(GetLocalAngles().Y)); + TaskComplete(); + break; + + case TASK_FACE_TARGET: + if (TargetEnt.Get() != null) { + GetMotor()!.SetIdealYawToTarget(TargetEnt.Get()!.GetAbsOrigin()); + SetTurnActivity(); + } + else + TaskFail(AI_TaskFailureCode.NoTarget); + break; + + case TASK_FACE_PLAYER: + SetWait(task.TaskData); + break; + + case TASK_FACE_ENEMY: { + Vector3 enemyLKP = GetEnemyLKP(); + if (!FInAimCone(enemyLKP)) { + GetMotor()!.SetIdealYawToTarget(enemyLKP); + GetMotor()!.SetIdealYaw(CalcReasonableFacing(true)); + SetTurnActivity(); + } + else { + float reasonableFacing = CalcReasonableFacing(true); + if (MathF.Abs(reasonableFacing - GetMotor()!.GetIdealYaw()) < 1) + TaskComplete(); + else { + GetMotor()!.SetIdealYaw(reasonableFacing); + SetTurnActivity(); + } + } + break; + } + + case TASK_FACE_REASONABLE: + GetMotor()!.SetIdealYaw(CalcReasonableFacing()); + SetTurnActivity(); + break; + + case TASK_FACE_PATH: { + if (!GetNavigator()!.IsGoalActive()) { + DevWarning(2, "No route to face!\n"); + TaskFail(AI_TaskFailureCode.NoRoute); + } + else { + const float NPC_TRIVIAL_TURN = 15; + + GetMotor()!.SetIdealYawToTarget(GetNavigator()!.GetCurWaypointPos()); + + if (MathF.Abs(GetMotor()!.DeltaIdealYaw()) <= NPC_TRIVIAL_TURN) { + TaskComplete(); + break; + } + SetTurnActivity(); + } + } + break; + + case TASK_SPEAK_SENTENCE: + SpeakSentence((int)task.TaskData); + TaskComplete(); + break; + + case TASK_GET_CHASE_PATH_TO_ENEMY: { + BaseEntity? enemy = GetEnemy(); + if (enemy == null) { + TaskFail(AI_TaskFailureCode.NoRoute); + return; + } + + if ((enemy.GetAbsOrigin() - GetEnemyLKP()).LengthSquared() < task.TaskData * task.TaskData) + ChainStartTask(TASK_GET_PATH_TO_ENEMY); + else + ChainStartTask(TASK_GET_PATH_TO_ENEMY_LKP); + + if (!TaskIsComplete() && !HasCondition((int)SCOND_t.COND_TASK_FAILED)) + TaskFail(AI_TaskFailureCode.NoRoute); + break; + } + + case TASK_GET_PATH_TO_ENEMY_LKP: { + BaseEntity? enemy = GetEnemy(); + if (enemy == null || IsUnreachable(enemy)) { + TaskFail(AI_TaskFailureCode.NoRoute); + return; + } + AI_NavGoal goal = new(GetEnemyLKP()); + + TranslateNavGoal(enemy, ref goal.Dest); + + if (GetNavigator()!.SetGoal(goal, AI_NavSetGoalFlags.ClearTarget)) + TaskComplete(); + else { + DevWarning(2, "GetPathToEnemyLKP failed!!\n"); + RememberUnreachable(GetEnemy()!); + TaskFail(AI_TaskFailureCode.NoRoute); + } + break; + } + + case TASK_GET_PATH_TO_ENEMY: { + if (IsUnreachable(GetEnemy())) { + TaskFail(AI_TaskFailureCode.NoRoute); + return; + } + + BaseEntity? enemy = GetEnemy(); + + if (enemy == null) { + TaskFail(AI_TaskFailureCode.NoEnemy); + return; + } + + if (GetNavigator()!.SetGoal(new AI_NavGoal(NavGoalType.Enemy))) + TaskComplete(); + else { + DevWarning(2, "GetPathToEnemy failed!!\n"); + RememberUnreachable(GetEnemy()!); + TaskFail(AI_TaskFailureCode.NoRoute); + } + break; + } + + case TASK_CREATE_PENDING_WEAPON: + case TASK_RANDOMIZE_FRAMERATE: + case TASK_DEFER_DODGE: + case TASK_ANNOUNCE_ATTACK: + case TASK_FIND_HINTNODE: + case TASK_FIND_LOCK_HINTNODE: + case TASK_LOCK_HINTNODE: + case TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION: + case TASK_CLEAR_HINTNODE: case TASK_ADD_GESTURE_WAIT: case TASK_ADD_GESTURE: case TASK_PLAY_HINT_ACTIVITY: @@ -4331,13 +4639,6 @@ public virtual void StartTask(in Task_t task) { case TASK_FIND_COVER_FROM_ORIGIN: case TASK_FIND_COVER_FROM_BEST_SOUND: case TASK_FACE_HINTNODE: - case TASK_FACE_LASTPOSITION: - case TASK_FACE_AWAY_FROM_SAVEPOSITION: - case TASK_SET_IDEAL_YAW_TO_CURRENT: - case TASK_FACE_TARGET: - case TASK_FACE_PLAYER: - case TASK_FACE_ENEMY: - case TASK_FACE_PATH: case TASK_MOVE_TO_TARGET_RANGE: case TASK_MOVE_TO_GOAL_RANGE: case TASK_WAIT_UNTIL_NO_DANGER_SOUND: @@ -4353,8 +4654,6 @@ public virtual void StartTask(in Task_t task) { case TASK_RELOAD: case TASK_SPECIAL_ATTACK1: case TASK_SPECIAL_ATTACK2: - case TASK_GET_CHASE_PATH_TO_ENEMY: - case TASK_GET_PATH_TO_ENEMY_LKP: case TASK_GET_PATH_TO_INTERACTION_PARTNER: case TASK_GET_PATH_TO_RANGE_ENEMY_LKP_LOS: case TASK_GET_PATH_TO_ENEMY_LOS: @@ -4363,7 +4662,6 @@ public virtual void StartTask(in Task_t task) { case TASK_GET_PATH_TO_ENEMY_LKP_LOS: case TASK_SET_GOAL: case TASK_GET_PATH_TO_GOAL: - case TASK_GET_PATH_TO_ENEMY: case TASK_GET_PATH_TO_ENEMY_CORPSE: case TASK_GET_PATH_TO_SAVEPOSITION_LOS: case TASK_GET_PATH_TO_TARGET_WEAPON: @@ -4386,7 +4684,6 @@ public virtual void StartTask(in Task_t task) { case TASK_SOUND_IDLE: case TASK_SOUND_PAIN: case TASK_SOUND_ANGRY: - case TASK_SPEAK_SENTENCE: case TASK_WAIT_FOR_SPEAK_FINISH: case TASK_WAIT_FOR_SCRIPT: case TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY: @@ -4574,23 +4871,93 @@ public virtual void RunTask(in Task_t task) { break; case TASK_TURN_RIGHT: - case TASK_TURN_LEFT: + case TASK_TURN_LEFT: { + Assert(GetMotor()!.IsYawLocked() == false); + + GetMotor()!.UpdateYaw(); + + if (FacingIdeal()) + TaskComplete(); + break; + } + case TASK_PLAY_PRIVATE_SEQUENCE_FACE_ENEMY: case TASK_PLAY_SEQUENCE_FACE_ENEMY: - case TASK_PLAY_SEQUENCE_FACE_TARGET: - case TASK_PLAY_HINT_ACTIVITY: + case TASK_PLAY_SEQUENCE_FACE_TARGET: { + BaseEntity? target; + + if (task.Task == TASK_PLAY_SEQUENCE_FACE_TARGET) + target = TargetEnt.Get(); + else + target = GetEnemy(); + if (target != null) + GetMotor()!.SetIdealYawAndUpdate(target.GetAbsOrigin() - GetLocalOrigin(), AI_Motor.AI_KEEP_YAW_SPEED); + + if (IsActivityFinished()) + TaskComplete(); + } + break; + case TASK_PLAY_SEQUENCE: - case TASK_PLAY_PRIVATE_SEQUENCE: - case TASK_ADD_GESTURE_WAIT: - case TASK_FACE_ENEMY: - case TASK_FACE_PLAYER: - case TASK_FIND_COVER_FROM_BEST_SOUND: - case TASK_FACE_HINTNODE: + case TASK_PLAY_PRIVATE_SEQUENCE: { + AutoMovement(); + if (IsActivityFinished()) + TaskComplete(); + break; + } + + case TASK_FACE_ENEMY: { + Assert(GetMotor()!.IsYawLocked() == false); + + Vector3 enemyLKP = GetEnemyLKP(); + if (!FInAimCone(enemyLKP)) { + GetMotor()!.SetIdealYawToTarget(enemyLKP); + GetMotor()!.SetIdealYaw(CalcReasonableFacing(true)); + } + else { + float reasonableFacing = CalcReasonableFacing(true); + if (MathF.Abs(reasonableFacing - GetMotor()!.GetIdealYaw()) > 1) + GetMotor()!.SetIdealYaw(reasonableFacing); + } + + GetMotor()!.UpdateYaw(); + + if (FacingIdeal()) + TaskComplete(); + break; + } + + case TASK_FACE_PLAYER: { + BasePlayer? player = AI_GetClosestPlayer(); + if (player != null) { + GetMotor()!.SetIdealYawToTargetAndUpdate(player.GetAbsOrigin(), AI_Motor.AI_KEEP_YAW_SPEED); + SetTurnActivity(); + if (IsWaitFinished() && GetMotor()!.DeltaIdealYaw() < 10) + TaskComplete(); + } + else + TaskFail(AI_TaskFailureCode.NoPlayer); + } + break; + case TASK_FACE_LASTPOSITION: case TASK_FACE_AWAY_FROM_SAVEPOSITION: + case TASK_FACE_HINTNODE: case TASK_FACE_TARGET: case TASK_FACE_SCRIPT: - case TASK_FACE_PATH: + case TASK_FACE_PATH: { + Assert(GetMotor()!.IsYawLocked() == false); + + GetMotor()!.UpdateYaw(); + + if (FacingIdeal()) + TaskComplete(); + break; + } + + case TASK_PLAY_HINT_ACTIVITY: + case TASK_ADD_GESTURE_WAIT: + case TASK_FIND_COVER_FROM_BEST_SOUND: case TASK_WAIT_FACE_ENEMY: case TASK_WAIT_FACE_ENEMY_RANDOM: case TASK_WAIT_UNTIL_NO_DANGER_SOUND: @@ -7534,7 +7901,41 @@ public virtual void RunAI() { g_AIRunTimer.Stop(); } - public virtual bool AutoMovement(BaseEntity? target = null) => throw new NotImplementedException(); + public virtual bool AutoMovement(BaseEntity? target = null) => AutoMovement(GetAnimTimeInterval(), target, out _); + public virtual bool AutoMovement(BaseEntity? target, out AIMoveTrace traceResult) => AutoMovement(GetAnimTimeInterval(), target, out traceResult); + + public virtual bool AutoMovement(TimeUnit_t interval, BaseEntity? target, out AIMoveTrace traceResult) { + traceResult = default; + + if (interval <= 0.0) + return true; + + ScheduleState.TaskRanAutomovement = true; + + if (GetIntervalMovement(interval, out _, out Vector3 newPos, out QAngle newAngles)) { + if (GetMoveType() == Source.MoveType.Step) { + if ((GetFlags() & EntityFlags.Fly) == 0) { + target ??= GetNavTargetEntity(); + + return GetMotor()!.MoveGroundStep(newPos, target, newAngles.Y, false, true, out traceResult) == AIMotorMoveResult.Success; + } + else { + SetLocalOrigin(newPos); + SetLocalAngles(newAngles); + return true; + } + } + else if (GetMoveType() == Source.MoveType.Fly) { + Vector3 dist = newPos - GetLocalOrigin(); + + dist *= (float)(1.0 / interval); + + SetLocalVelocity(dist); + return true; + } + } + return false; + } public virtual void PostRun() { if (!IsMoving()) { diff --git a/Game.Server/BaseAnimating.cs b/Game.Server/BaseAnimating.cs index 52fa5c83f..ee2346693 100644 --- a/Game.Server/BaseAnimating.cs +++ b/Game.Server/BaseAnimating.cs @@ -742,6 +742,42 @@ public TimeUnit_t GetAnimTimeInterval() { return interval; } + public bool GetIntervalMovement(TimeUnit_t intervalUsed, out bool moveSeqFinished, out Vector3 newPosition, out QAngle newAngles) { + StudioHdr? studioHdr = GetModelPtr(); + if (studioHdr == null || !studioHdr.SequencesAvailable()) { + moveSeqFinished = default; + newPosition = default; + newAngles = default; + return false; + } + + float computedCycleRate = GetSequenceCycleRate(GetSequence()); + + TimeUnit_t nextCycle = GetCycle() + intervalUsed * computedCycleRate * PlaybackRate; + + if (!SequenceLoops && nextCycle > 1.0) { + intervalUsed = GetCycle() / (computedCycleRate * PlaybackRate); + nextCycle = 1.0; + moveSeqFinished = true; + } + else { + moveSeqFinished = false; + } + + if (BoneSetup.Studio_SeqMovement(studioHdr, GetSequence(), (float)GetCycle(), (float)nextCycle, GetPoseParameterArray(), out Vector3 deltaPos, out QAngle deltaAngles)) { + MathLib.VectorYawRotate(deltaPos, GetLocalAngles().Y, out deltaPos); + newPosition = GetLocalOrigin() + deltaPos; + newAngles = default; + newAngles.Y = GetLocalAngles().Y + deltaAngles.Y; + return true; + } + else { + newPosition = GetLocalOrigin(); + newAngles = GetLocalAngles(); + return false; + } + } + public void InvalidateBoneCache() => Studio.InvalidateBoneCache(BoneCacheHandle); public void InvalidateBoneCacheIfOlderThan(TimeUnit_t deltaTime) { diff --git a/Game.Server/HL2/HL2_Player.cs b/Game.Server/HL2/HL2_Player.cs index ce8b6a8e8..5d106982c 100644 --- a/Game.Server/HL2/HL2_Player.cs +++ b/Game.Server/HL2/HL2_Player.cs @@ -4,6 +4,7 @@ using Source.Common; using Source.Common.Commands; +using Source.Common.Mathematics; using Source.Common.Physics; using Source; using Game.Shared.HL2; @@ -576,7 +577,15 @@ void UpdateClientData() { } void OnRestore() { } public override Vector3 EyeDirection2D() { - throw new NotImplementedException(); + Vector3 vecReturn = EyeDirection3D(); + vecReturn.Z = 0; + + Vector2 vecReturn2D = new(vecReturn.X, vecReturn.Y); + MathLib.VectorNormalize(ref vecReturn2D); + vecReturn.X = vecReturn2D.X; + vecReturn.Y = vecReturn2D.Y; + + return vecReturn; } public override Vector3 EyeDirection3D() { diff --git a/Game.Server/Player.cs b/Game.Server/Player.cs index 75d832897..b89c377e1 100644 --- a/Game.Server/Player.cs +++ b/Game.Server/Player.cs @@ -249,6 +249,7 @@ public enum PlayerPhysFlag public partial class BasePlayer : BaseCombatCharacter { public const int SF_NORESPAWN = 1 << 30; + public const float DOT_30DEGREE = 0.866025403784f; public static readonly SendTable DT_PlayerState = new(nameof(DT_PlayerState), [ SendPropInt(FIELD.OF(nameof(PlayerState.DeadFlag)), 1, PropFlags.Unsigned) ]); From 95a5db817d7c1ad812ddf51bec467a065054d969 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 02:26:44 +0300 Subject: [PATCH 40/73] Port npc_metropolice schedules, tasks, sentences and anim events --- Game.Server/AI_BaseNPC.cs | 56 + Game.Server/AI_Schedule.cs | 10 + Game.Server/AI_Squad.cs | 3 + Game.Server/BaseCombatCharacter.cs | 11 + Game.Server/BaseEntity.cs | 6 + Game.Server/NPC_MetroPolice.cs | 1989 +++++++++++++++++++++++++++- Game.Server/Props.cs | 2 + Game.Server/Util.cs | 8 + 8 files changed, 2058 insertions(+), 27 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 6aa4ef6c4..140400138 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -438,6 +438,10 @@ public static ReadOnlySpan GetActivityName(Activity actID) { public static AI_DebugFlags DebugBits = 0; public static int DebugPauseIndex = -1; + public const int NEXT_SCHEDULE = LAST_SHARED_SCHEDULE; + public const int NEXT_TASK = LAST_SHARED_TASK; + public const int NEXT_CONDITION = (int)SCOND_t.LAST_SHARED_CONDITION; + public static readonly AI_ClassScheduleIdSpace ClassScheduleIdSpace = new(true); public static readonly AI_GlobalScheduleNamespace SchedulingSymbols = new(); @@ -613,6 +617,34 @@ public override void Precache() { public static StringRegistry? ActivitySR; public static StringRegistry? EventSR; + public static int NumEvents; + + public static readonly AI_GlobalNamespace SquadSlotNamespace = new(); + public static readonly AI_LocalIdSpace SquadSlotIdSpace = new(true); + + public static void AddEventToSR(ReadOnlySpan eventName, int eventID) { + Assert(EventSR != null); + + EventSR!.AddString(eventName, eventID); + NumEvents++; + } + + public static Animevent DeclareAnimEvent(ReadOnlySpan name) { + Animevent animEvent = EventList.RegisterPrivateEvent(name); + AddEventToSR(name, (int)animEvent); + return animEvent; + } + + public static void InitDefaultSquadSlotSR() { + SquadSlotNamespace.AddSymbol("SQUAD_SLOT_ATTACK1", AI_RemapToGlobal((int)SquadSlot.Attack1)); + SquadSlotNamespace.AddSymbol("SQUAD_SLOT_ATTACK2", AI_RemapToGlobal((int)SquadSlot.Attack2)); + SquadSlotNamespace.AddSymbol("SQUAD_SLOT_INVESTIGATE_SOUND", AI_RemapToGlobal((int)SquadSlot.InvestigateSound)); + SquadSlotNamespace.AddSymbol("SQUAD_SLOT_EXCLUSIVE_HANDSIGN", AI_RemapToGlobal((int)SquadSlot.ExclusiveHandsign)); + SquadSlotNamespace.AddSymbol("SQUAD_SLOT_EXCLUSIVE_RELOAD", AI_RemapToGlobal((int)SquadSlot.ExclusiveReload)); + SquadSlotNamespace.AddSymbol("SQUAD_SLOT_PICKUP_WEAPON1", AI_RemapToGlobal((int)SquadSlot.PickupWeapon1)); + SquadSlotNamespace.AddSymbol("SQUAD_SLOT_PICKUP_WEAPON2", AI_RemapToGlobal((int)SquadSlot.PickupWeapon2)); + SquadSlotNamespace.AddSymbol("SQUAD_SLOT_SPECIAL_ATTACK", AI_RemapToGlobal((int)SquadSlot.SpecialAttack)); + } public static int GetScheduleID(ReadOnlySpan schedName) => GetSchedulingSymbols().ScheduleSymbolToId(schedName); public static int GetTaskID(ReadOnlySpan taskName) => GetSchedulingSymbols().TaskSymbolToId(taskName); @@ -962,6 +994,12 @@ public static void AddActivityToSR(ReadOnlySpan actName, int actID) { NumActivities++; } + public static Activity DeclareActivity(ReadOnlySpan name) { + Activity activity = ActivityList.RegisterPrivateActivity(name); + AddActivityToSR(name, (int)activity); + return activity; + } + public static void InitDefaultActivitySR() { AddActivityToSR("ACT_INVALID", (int)Activity.ACT_INVALID); AddActivityToSR("ACT_RESET", (int)Activity.ACT_RESET); @@ -2570,6 +2608,7 @@ public static void InitSchedulingTables() { InitDefaultConditionSR(); InitDefaultTaskSR(); InitDefaultActivitySR(); + InitDefaultSquadSlotSR(); } public static bool LoadDefaultSchedules() => g_AI_SchedulesManager.DefineSchedules("CAI_BaseNPC", ClassScheduleIdSpace, DefaultSchedules); @@ -6278,6 +6317,7 @@ public void JustMadeSound(SentencePriority soundPriority = SentencePriority.Norm } public virtual void IdleSound() { } + public virtual void DeathSound(in TakeDamageInfo info) { } public virtual void LostEnemySound() { } public virtual void FoundEnemySound() { } @@ -6476,6 +6516,22 @@ public virtual float GetTimeToNavGoal() { return 0.0f; } + public bool OccupyStrategySlot(SquadSlot squadSlotID) => OccupyStrategySlotRange(squadSlotID, squadSlotID); + + public bool OccupyStrategySlotRange(SquadSlot slotIDStart, SquadSlot slotIDEnd) { + return Squad == null || Squad.OccupyStrategySlotRange(GetEnemy(), slotIDStart, slotIDEnd, ref MySquadSlot); + } + + public bool HasStrategySlot(SquadSlot squadSlotID) => MySquadSlot == squadSlotID; + + public bool HasStrategySlotRange(SquadSlot slotIDStart, SquadSlot slotIDEnd) { + if (MySquadSlot < slotIDStart || MySquadSlot > slotIDEnd) + return false; + return true; + } + + public void SetLastAttackTime(TimeUnit_t time) => LastAttackTime = time; + public void VacateStrategySlot() { if (Squad != null) { Squad.VacateStrategySlot(GetEnemy(), MySquadSlot); diff --git a/Game.Server/AI_Schedule.cs b/Game.Server/AI_Schedule.cs index 02a150d4e..16a6b7cd9 100644 --- a/Game.Server/AI_Schedule.cs +++ b/Game.Server/AI_Schedule.cs @@ -43,6 +43,7 @@ public AI_SchedulesManager() { public void DestroyStringRegistries() { AI_BaseNPC.GetSchedulingSymbols().Clear(); + AI_BaseNPC.SquadSlotNamespace.Clear(); AI_BaseNPC.ActivitySR = null; AI_BaseNPC.NumActivities = 0; @@ -50,6 +51,7 @@ public void DestroyStringRegistries() { public void CreateStringRegistries() { AI_BaseNPC.GetSchedulingSymbols().Clear(); + AI_BaseNPC.SquadSlotNamespace.Clear(); AI_BaseNPC.ActivitySR = new(); AI_BaseNPC.EventSR = new(); @@ -189,10 +191,12 @@ public sealed class AI_CustomSchedules public required string ClassName { get; init; } public required AI_ClassScheduleIdSpace IdSpace { get; init; } public required AI_ClassScheduleIdSpace ParentIdSpace { get; init; } + public AI_LocalIdSpace? SquadSlotIdSpace { get; init; } public (string Name, int LocalId)[] Schedules { get; init; } = []; public (string Name, int LocalId)[] Tasks { get; init; } = []; public (string Name, int LocalId)[] Conditions { get; init; } = []; + public (string Name, int LocalId)[] SquadSlots { get; init; } = []; public Action? Declare { get; init; } public AI_ScheduleDef[] Definitions { get; init; } = []; @@ -207,6 +211,7 @@ void Init() { Declare?.Invoke(); IdSpace.Init(ClassName, AI_BaseNPC.GetSchedulingSymbols(), ParentIdSpace); + SquadSlotIdSpace?.Init(AI_BaseNPC.SquadSlotNamespace, AI_BaseNPC.SquadSlotIdSpace); foreach ((string name, int localId) in SortedByLocalId(Schedules)) { if (!IdSpace.AddSchedule(name, localId, ClassName)) @@ -225,6 +230,11 @@ void Init() { } } + foreach ((string name, int localId) in SortedByLocalId(SquadSlots)) { + if (!SquadSlotIdSpace!.AddSymbol(name, localId, "squadslot", ClassName)) + return; + } + if (LoadStatus.Valid) LoadStatus.Valid = g_AI_SchedulesManager.DefineSchedules(ClassName, IdSpace, Definitions); } diff --git a/Game.Server/AI_Squad.cs b/Game.Server/AI_Squad.cs index 1fe1ea4d9..79e0040ab 100644 --- a/Game.Server/AI_Squad.cs +++ b/Game.Server/AI_Squad.cs @@ -29,8 +29,11 @@ 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 void SquadRemember(AI_MemoryFlags memory) => throw new NotImplementedException(); + public void BroadcastInteraction(int interactionType, object? data, BaseCombatCharacter? sender) => throw new NotImplementedException(); public AI_BaseNPC? GetFirstMember(out int iter) => throw new NotImplementedException(); public AI_BaseNPC? GetNextMember(ref int iter) => throw new NotImplementedException(); public void VacateStrategySlot(BaseEntity? enemy, SquadSlot slot) => throw new NotImplementedException(); + public bool OccupyStrategySlotRange(BaseEntity? enemy, SquadSlot slotIDStart, SquadSlot slotIDEnd, ref SquadSlot slot) => throw new NotImplementedException(); public void UpdateEnemyMemory(AI_BaseNPC updater, BaseEntity enemy, in Vector3 position) => throw new NotImplementedException(); } diff --git a/Game.Server/BaseCombatCharacter.cs b/Game.Server/BaseCombatCharacter.cs index 19204d862..2be3d1a27 100644 --- a/Game.Server/BaseCombatCharacter.cs +++ b/Game.Server/BaseCombatCharacter.cs @@ -585,6 +585,17 @@ public virtual void OnChangeActiveWeapon(BaseCombatWeapon? oldWeapon, BaseCombat public void SetCurrentWeaponProficiency(WeaponProficiency proficiency) => CurrentWeaponProficiency = proficiency; public virtual WeaponProficiency CalcWeaponProficiency(BaseCombatWeapon? weapon) => WeaponProficiency.Average; + static int LastInteraction = 0; + + public static int GetInteractionID() { + LastInteraction++; + return LastInteraction; + } + + public bool DispatchInteraction(int interactionType, object? data, BaseCombatCharacter? sourceEnt) => (interactionType > 0) ? HandleInteraction(interactionType, data, sourceEnt) : false; + + public virtual bool HandleInteraction(int interactionType, object? data, BaseCombatCharacter? sourceEnt) => false; + public override void SetLightingOriginRelative(BaseEntity? lightingOrigin) { base.SetLightingOriginRelative(lightingOrigin); if (GetActiveWeapon() != null) diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 8a9bb1242..103aedfaf 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -2104,6 +2104,10 @@ public virtual int OnTakeDamage(in TakeDamageInfo info) { return 1; } + public virtual void DeathNotice(BaseEntity victim) { } + + public IPhysicsObject? VPhysicsInitStatic() => throw new NotImplementedException(); + public virtual void Event_KilledOther(BaseEntity killed, in TakeDamageInfo info) { } @@ -2978,6 +2982,8 @@ protected void CalcAbsolutePosition() { } } + public bool IsOnFire() => (GetFlags() & EntityFlags.OnFire) != 0; + public virtual void Use(BaseEntity? activator, BaseEntity? caller, UseType useType, float value) { if (FnUse != null) FnUse(activator, caller, useType, value); diff --git a/Game.Server/NPC_MetroPolice.cs b/Game.Server/NPC_MetroPolice.cs index 52d9f8fb0..604ec5bd5 100644 --- a/Game.Server/NPC_MetroPolice.cs +++ b/Game.Server/NPC_MetroPolice.cs @@ -4,6 +4,14 @@ using Source; using Source.Common; using Source.Common.Commands; +using Source.Common.Engine; +using Source.Common.Formats.BSP; +using Source.Common.Mathematics; + +using System.Numerics; +using System.Runtime.CompilerServices; + +using static Game.Server.SCOND_t; namespace Game.Server; @@ -23,33 +31,797 @@ public class NPC_MetroPolice : AI_BaseActor public const float METROPOLICE_MID_RANGE_ATTACK_RANGE = 3500.0f; + const float METROPOLICE_SQUAD_STITCH_MIN_INTERVAL = 1.0f; + const float METROPOLICE_SQUAD_STITCH_MAX_INTERVAL = 1.2f; + + const float RECENT_DAMAGE_INTERVAL = 3.0f; + + const int METROPOLICE_MAX_WARNINGS = 3; + public const int METROPOLICE_BODYGROUP_MANHACK = 1; + const int METROPOLICE_NUM_CLIPS = 5; + const int METROPOLICE_BURST_RELOAD_COUNT = 20; + + const int METROPOLICE_SENTENCE_FREEZE = 0; + const int METROPOLICE_SENTENCE_HES_OVER_HERE = 1; + const int METROPOLICE_SENTENCE_HES_RUNNING = 2; + const int METROPOLICE_SENTENCE_TAKE_HIM_DOWN = 3; + const int METROPOLICE_SENTENCE_ARREST_IN_POSITION = 4; + const int METROPOLICE_SENTENCE_DEPLOY_MANHACK = 5; + const int METROPOLICE_SENTENCE_MOVE_INTO_POSITION = 6; + const int METROPOLICE_SENTENCE_HEARD_SOMETHING = 7; + + const int METROPOLICE_CHATTER_WAIT_FOR_RESPONSE = 0; + const int METROPOLICE_CHATTER_ASK_QUESTION = 1; + const int METROPOLICE_CHATTER_RESPONSE = 2; + const int METROPOLICE_CHATTER_RESPONSE_TYPE_COUNT = 2; + + const AI_MemoryFlags bits_MEMORY_PAIN_LIGHT_SOUND = AI_MemoryFlags.Custom1; + const AI_MemoryFlags bits_MEMORY_PAIN_HEAVY_SOUND = AI_MemoryFlags.Custom2; + const AI_MemoryFlags bits_MEMORY_PLAYER_HURT = AI_MemoryFlags.Custom3; + const AI_MemoryFlags bits_MEMORY_PLAYER_HARASSED = AI_MemoryFlags.Custom4; + + public static int g_interactionMetrocopStartedStitch = 0; + public static int g_interactionMetrocopIdleChatter = 0; + public static int g_interactionMetrocopClearSentenceQueues = 0; + public static readonly ConVar sk_metropolice_health = new("sk_metropolice_health", "0"); public static readonly ConVar sk_metropolice_simple_health = new("sk_metropolice_simple_health", "26"); + public static readonly ConVar metropolice_chase_use_follow = new("metropolice_chase_use_follow", "0"); + public static readonly ConVar metropolice_move_and_melee = new("metropolice_move_and_melee", "1"); + public static readonly ConVar metropolice_charge = new("metropolice_charge", "1"); + + public static Animevent AE_METROPOLICE_BATON_ON; + public static Animevent AE_METROPOLICE_BATON_OFF; + public static Animevent AE_METROPOLICE_SHOVE; + public static Animevent AE_METROPOLICE_START_DEPLOY; + public static Animevent AE_METROPOLICE_DRAW_PISTOL; + public static Animevent AE_METROPOLICE_DEPLOY_MANHACK; + + const SquadSlot SQUAD_SLOT_POLICE_CHARGE_ENEMY = SquadSlot.LastShared; + const SquadSlot SQUAD_SLOT_POLICE_HARASS = SquadSlot.LastShared + 1; + const SquadSlot SQUAD_SLOT_POLICE_DEPLOY_MANHACK = SquadSlot.LastShared + 2; + const SquadSlot SQUAD_SLOT_POLICE_ADVANCE = SquadSlot.LastShared + 3; + const SquadSlot SQUAD_SLOT_POLICE_ATTACK_OCCLUDER1 = SquadSlot.LastShared + 4; + const SquadSlot SQUAD_SLOT_POLICE_ATTACK_OCCLUDER2 = SquadSlot.LastShared + 5; + const SquadSlot SQUAD_SLOT_POLICE_COVERING_FIRE1 = SquadSlot.LastShared + 6; + const SquadSlot SQUAD_SLOT_POLICE_COVERING_FIRE2 = SquadSlot.LastShared + 7; + const SquadSlot SQUAD_SLOT_POLICE_ARREST_ENEMY = SquadSlot.LastShared + 8; + + public static Activity ACT_METROPOLICE_DRAW_PISTOL; + public static Activity ACT_METROPOLICE_DEPLOY_MANHACK; + public static Activity ACT_METROPOLICE_FLINCH_BEHIND; + + public static Activity ACT_WALK_BATON; + public static Activity ACT_IDLE_ANGRY_BATON; + public static Activity ACT_PUSH_PLAYER; + public static Activity ACT_MELEE_ATTACK_THRUST; + public static Activity ACT_ACTIVATE_BATON; + public static Activity ACT_DEACTIVATE_BATON; + + const int COND_METROPOLICE_ON_FIRE = NEXT_CONDITION; + const int COND_METROPOLICE_ENEMY_RESISTING_ARREST = NEXT_CONDITION + 1; + const int COND_METROPOLICE_PLAYER_TOO_CLOSE = NEXT_CONDITION + 2; + const int COND_METROPOLICE_CHANGE_BATON_STATE = NEXT_CONDITION + 3; + const int COND_METROPOLICE_PHYSOBJECT_ASSAULT = NEXT_CONDITION + 4; + + const int SCHED_METROPOLICE_WALK = NEXT_SCHEDULE; + const int SCHED_METROPOLICE_WAKE_ANGRY = NEXT_SCHEDULE + 1; + const int SCHED_METROPOLICE_HARASS = NEXT_SCHEDULE + 2; + const int SCHED_METROPOLICE_CHASE_ENEMY = NEXT_SCHEDULE + 3; + const int SCHED_METROPOLICE_ESTABLISH_LINE_OF_FIRE = NEXT_SCHEDULE + 4; + const int SCHED_METROPOLICE_DRAW_PISTOL = NEXT_SCHEDULE + 5; + const int SCHED_METROPOLICE_DEPLOY_MANHACK = NEXT_SCHEDULE + 6; + const int SCHED_METROPOLICE_ADVANCE = NEXT_SCHEDULE + 7; + const int SCHED_METROPOLICE_CHARGE = NEXT_SCHEDULE + 8; + const int SCHED_METROPOLICE_BURNING_RUN = NEXT_SCHEDULE + 9; + const int SCHED_METROPOLICE_BURNING_STAND = NEXT_SCHEDULE + 10; + const int SCHED_METROPOLICE_SMG_NORMAL_ATTACK = NEXT_SCHEDULE + 11; + const int SCHED_METROPOLICE_SMG_BURST_ATTACK = NEXT_SCHEDULE + 12; + const int SCHED_METROPOLICE_AIM_STITCH_AT_AIRBOAT = NEXT_SCHEDULE + 13; + const int SCHED_METROPOLICE_AIM_STITCH_IN_FRONT_OF_AIRBOAT = NEXT_SCHEDULE + 14; + const int SCHED_METROPOLICE_AIM_STITCH_TIGHTLY = NEXT_SCHEDULE + 15; + const int SCHED_METROPOLICE_AIM_STITCH_ALONG_SIDE_OF_AIRBOAT = NEXT_SCHEDULE + 16; + const int SCHED_METROPOLICE_AIM_STITCH_BEHIND_AIRBOAT = NEXT_SCHEDULE + 17; + const int SCHED_METROPOLICE_ESTABLISH_STITCH_LINE_OF_FIRE = NEXT_SCHEDULE + 18; + const int SCHED_METROPOLICE_INVESTIGATE_SOUND = NEXT_SCHEDULE + 19; + const int SCHED_METROPOLICE_WARN_AND_ARREST_ENEMY = NEXT_SCHEDULE + 20; + const int SCHED_METROPOLICE_ARREST_ENEMY = NEXT_SCHEDULE + 21; + const int SCHED_METROPOLICE_ENEMY_RESISTING_ARREST = NEXT_SCHEDULE + 22; + const int SCHED_METROPOLICE_WARN_TARGET = NEXT_SCHEDULE + 23; + const int SCHED_METROPOLICE_HARASS_TARGET = NEXT_SCHEDULE + 24; + const int SCHED_METROPOLICE_SUPPRESS_TARGET = NEXT_SCHEDULE + 25; + const int SCHED_METROPOLICE_RETURN_FROM_HARASS = NEXT_SCHEDULE + 26; + const int SCHED_METROPOLICE_SHOVE = NEXT_SCHEDULE + 27; + const int SCHED_METROPOLICE_ACTIVATE_BATON = NEXT_SCHEDULE + 28; + const int SCHED_METROPOLICE_DEACTIVATE_BATON = NEXT_SCHEDULE + 29; + const int SCHED_METROPOLICE_ALERT_FACE_BESTSOUND = NEXT_SCHEDULE + 30; + const int SCHED_METROPOLICE_RETURN_TO_PRECHASE = NEXT_SCHEDULE + 31; + const int SCHED_METROPOLICE_SMASH_PROP = NEXT_SCHEDULE + 32; + + const int TASK_METROPOLICE_HARASS = NEXT_TASK; + const int TASK_METROPOLICE_DIE_INSTANTLY = NEXT_TASK + 1; + const int TASK_METROPOLICE_BURST_ATTACK = NEXT_TASK + 2; + const int TASK_METROPOLICE_STOP_FIRE_BURST = NEXT_TASK + 3; + const int TASK_METROPOLICE_AIM_STITCH_AT_PLAYER = NEXT_TASK + 4; + const int TASK_METROPOLICE_AIM_STITCH_AT_AIRBOAT = NEXT_TASK + 5; + const int TASK_METROPOLICE_AIM_STITCH_TIGHTLY = NEXT_TASK + 6; + const int TASK_METROPOLICE_AIM_STITCH_IN_FRONT_OF_AIRBOAT = NEXT_TASK + 7; + const int TASK_METROPOLICE_AIM_STITCH_ALONG_SIDE_OF_AIRBOAT = NEXT_TASK + 8; + const int TASK_METROPOLICE_AIM_STITCH_BEHIND_AIRBOAT = NEXT_TASK + 9; + const int TASK_METROPOLICE_RELOAD_FOR_BURST = NEXT_TASK + 10; + const int TASK_METROPOLICE_GET_PATH_TO_STITCH = NEXT_TASK + 11; + const int TASK_METROPOLICE_RESET_LEDGE_CHECK_TIME = NEXT_TASK + 12; + const int TASK_METROPOLICE_GET_PATH_TO_BESTSOUND_LOS = NEXT_TASK + 13; + const int TASK_METROPOLICE_AIM_WEAPON_AT_ENEMY = NEXT_TASK + 14; + const int TASK_METROPOLICE_ARREST_ENEMY = NEXT_TASK + 15; + const int TASK_METROPOLICE_LEAD_ARREST_ENEMY = NEXT_TASK + 16; + const int TASK_METROPOLICE_SIGNAL_FIRING_TIME = NEXT_TASK + 17; + const int TASK_METROPOLICE_ACTIVATE_BATON = NEXT_TASK + 18; + const int TASK_METROPOLICE_WAIT_FOR_SENTENCE = NEXT_TASK + 19; + const int TASK_METROPOLICE_GET_PATH_TO_PRECHASE = NEXT_TASK + 20; + const int TASK_METROPOLICE_CLEAR_PRECHASE = NEXT_TASK + 21; + + static readonly AI_ClassScheduleIdSpace gm_ClassScheduleIdSpace = new(); + static readonly AI_LocalIdSpace gm_SquadSlotIdSpace = new(); + const string gm_pszErrorClassName = "CNPC_MetroPolice"; + public static readonly new DataMap DataDesc = new(typeof(NPC_MetroPolice), AI_BaseNPC.DataDesc, [ DEFINE.KEYFIELD(nameof(WeaponDrawn), FieldType.Boolean, "weapondrawn"), DEFINE.KEYFIELD(nameof(Manhacks), FieldType.Integer, "manhacks"), + DEFINE.INPUTFUNC(FieldType.Void, "EnableManhackToss", nameof(InputEnableManhackToss), (INPUTFUNCPTR)((self, data) => ((NPC_MetroPolice)self).InputEnableManhackToss(data))), + DEFINE.INPUTFUNC(FieldType.String, "SetPoliceGoal", nameof(InputSetPoliceGoal), (INPUTFUNCPTR)((self, data) => ((NPC_MetroPolice)self).InputSetPoliceGoal(data))), + DEFINE.INPUTFUNC(FieldType.Void, "ActivateBaton", nameof(InputActivateBaton), (INPUTFUNCPTR)((self, data) => ((NPC_MetroPolice)self).InputActivateBaton(data))), + DEFINE.OUTPUT(nameof(OnStunnedPlayer), "OnStunnedPlayer", eventFuncs), DEFINE.OUTPUT(nameof(OnCupCopped), "OnCupCopped", eventFuncs), - - DEFINE.INPUTFUNC(FieldType.String, "SetPoliceGoal", nameof(InputSetPoliceGoal), (INPUTFUNCPTR)((self, data) => ((NPC_MetroPolice)self).InputSetPoliceGoal(data))), ]); public override DataMap? GetDataDescMap() => DataDesc; - public bool WeaponDrawn; + public int PistolClips; public int Manhacks; + public bool WeaponDrawn; bool SimpleCops; + public readonly SimpleSimTimer BatonSwingTimer = new(); + public readonly SimpleSimTimer NextChargeTimer = new(); + + int BurstReloadCount; + TimeUnit_t ValidStitchTime; + TimeUnit_t NextLedgeCheckTime; + TimeUnit_t TaskCompletionTime; + + bool ShouldActivateBaton; + TimeUnit_t BatonDebounceTime; + TimeUnit_t LastPhysicsFlinchTime; + TimeUnit_t LastDamageFlinchTime; + + TimeUnit_t NextPainSoundTime; + TimeUnit_t NextLostSoundTime; + int IdleChatterType; + bool PlayerIsNear; + + bool PlayerTooClose; + bool KeepFacingPlayer; TimeUnit_t ChasePlayerTime; + Vector3 PreChaseOrigin; + float PreChaseYaw; + int NumWarnings; + int NumPlayerHits; public OutputEvent OnStunnedPlayer = new(); public OutputEvent OnCupCopped = new(); + Handle Manhack = new(); + Handle BlockingProp = new(); + readonly AI_PolicingBehavior PolicingBehavior = new(); readonly AI_Sentence_NPC_MetroPolice Sentences = new(); + int RecentDamage; + TimeUnit_t RecentDamageTime; + + public NPC_MetroPolice() => LoadSchedules(); + + public override AI_ClassScheduleIdSpace GetClassScheduleIdSpace() => gm_ClassScheduleIdSpace; + + public static new bool LoadSchedules() => CustomSchedules.Load(AI_BaseNPC.LoadSchedules); + + public override bool LoadedSchedules() => CustomSchedules.Valid; + + static readonly AI_CustomSchedules CustomSchedules = new() { + ClassName = gm_pszErrorClassName, + IdSpace = gm_ClassScheduleIdSpace, + ParentIdSpace = AI_BaseNPC.ClassScheduleIdSpace, + SquadSlotIdSpace = gm_SquadSlotIdSpace, + Schedules = [ + (nameof(SCHED_METROPOLICE_WAKE_ANGRY), SCHED_METROPOLICE_WAKE_ANGRY), + (nameof(SCHED_METROPOLICE_INVESTIGATE_SOUND), SCHED_METROPOLICE_INVESTIGATE_SOUND), + (nameof(SCHED_METROPOLICE_HARASS), SCHED_METROPOLICE_HARASS), + (nameof(SCHED_METROPOLICE_DRAW_PISTOL), SCHED_METROPOLICE_DRAW_PISTOL), + (nameof(SCHED_METROPOLICE_CHASE_ENEMY), SCHED_METROPOLICE_CHASE_ENEMY), + (nameof(SCHED_METROPOLICE_ESTABLISH_LINE_OF_FIRE), SCHED_METROPOLICE_ESTABLISH_LINE_OF_FIRE), + (nameof(SCHED_METROPOLICE_ESTABLISH_STITCH_LINE_OF_FIRE), SCHED_METROPOLICE_ESTABLISH_STITCH_LINE_OF_FIRE), + (nameof(SCHED_METROPOLICE_DEPLOY_MANHACK), SCHED_METROPOLICE_DEPLOY_MANHACK), + (nameof(SCHED_METROPOLICE_ADVANCE), SCHED_METROPOLICE_ADVANCE), + (nameof(SCHED_METROPOLICE_CHARGE), SCHED_METROPOLICE_CHARGE), + (nameof(SCHED_METROPOLICE_BURNING_RUN), SCHED_METROPOLICE_BURNING_RUN), + (nameof(SCHED_METROPOLICE_BURNING_STAND), SCHED_METROPOLICE_BURNING_STAND), + (nameof(SCHED_METROPOLICE_RETURN_TO_PRECHASE), SCHED_METROPOLICE_RETURN_TO_PRECHASE), + (nameof(SCHED_METROPOLICE_ALERT_FACE_BESTSOUND), SCHED_METROPOLICE_ALERT_FACE_BESTSOUND), + (nameof(SCHED_METROPOLICE_ENEMY_RESISTING_ARREST), SCHED_METROPOLICE_ENEMY_RESISTING_ARREST), + (nameof(SCHED_METROPOLICE_WARN_AND_ARREST_ENEMY), SCHED_METROPOLICE_WARN_AND_ARREST_ENEMY), + (nameof(SCHED_METROPOLICE_ARREST_ENEMY), SCHED_METROPOLICE_ARREST_ENEMY), + (nameof(SCHED_METROPOLICE_SMG_NORMAL_ATTACK), SCHED_METROPOLICE_SMG_NORMAL_ATTACK), + (nameof(SCHED_METROPOLICE_SMG_BURST_ATTACK), SCHED_METROPOLICE_SMG_BURST_ATTACK), + (nameof(SCHED_METROPOLICE_AIM_STITCH_TIGHTLY), SCHED_METROPOLICE_AIM_STITCH_TIGHTLY), + (nameof(SCHED_METROPOLICE_AIM_STITCH_AT_AIRBOAT), SCHED_METROPOLICE_AIM_STITCH_AT_AIRBOAT), + (nameof(SCHED_METROPOLICE_AIM_STITCH_IN_FRONT_OF_AIRBOAT), SCHED_METROPOLICE_AIM_STITCH_IN_FRONT_OF_AIRBOAT), + (nameof(SCHED_METROPOLICE_AIM_STITCH_ALONG_SIDE_OF_AIRBOAT), SCHED_METROPOLICE_AIM_STITCH_ALONG_SIDE_OF_AIRBOAT), + (nameof(SCHED_METROPOLICE_AIM_STITCH_BEHIND_AIRBOAT), SCHED_METROPOLICE_AIM_STITCH_BEHIND_AIRBOAT), + (nameof(SCHED_METROPOLICE_SHOVE), SCHED_METROPOLICE_SHOVE), + (nameof(SCHED_METROPOLICE_ACTIVATE_BATON), SCHED_METROPOLICE_ACTIVATE_BATON), + (nameof(SCHED_METROPOLICE_DEACTIVATE_BATON), SCHED_METROPOLICE_DEACTIVATE_BATON), + (nameof(SCHED_METROPOLICE_SMASH_PROP), SCHED_METROPOLICE_SMASH_PROP), + ], + Tasks = [ + (nameof(TASK_METROPOLICE_HARASS), TASK_METROPOLICE_HARASS), + (nameof(TASK_METROPOLICE_DIE_INSTANTLY), TASK_METROPOLICE_DIE_INSTANTLY), + (nameof(TASK_METROPOLICE_BURST_ATTACK), TASK_METROPOLICE_BURST_ATTACK), + (nameof(TASK_METROPOLICE_STOP_FIRE_BURST), TASK_METROPOLICE_STOP_FIRE_BURST), + (nameof(TASK_METROPOLICE_AIM_STITCH_AT_PLAYER), TASK_METROPOLICE_AIM_STITCH_AT_PLAYER), + (nameof(TASK_METROPOLICE_AIM_STITCH_AT_AIRBOAT), TASK_METROPOLICE_AIM_STITCH_AT_AIRBOAT), + (nameof(TASK_METROPOLICE_AIM_STITCH_IN_FRONT_OF_AIRBOAT), TASK_METROPOLICE_AIM_STITCH_IN_FRONT_OF_AIRBOAT), + (nameof(TASK_METROPOLICE_AIM_STITCH_TIGHTLY), TASK_METROPOLICE_AIM_STITCH_TIGHTLY), + (nameof(TASK_METROPOLICE_AIM_STITCH_ALONG_SIDE_OF_AIRBOAT), TASK_METROPOLICE_AIM_STITCH_ALONG_SIDE_OF_AIRBOAT), + (nameof(TASK_METROPOLICE_AIM_STITCH_BEHIND_AIRBOAT), TASK_METROPOLICE_AIM_STITCH_BEHIND_AIRBOAT), + (nameof(TASK_METROPOLICE_RELOAD_FOR_BURST), TASK_METROPOLICE_RELOAD_FOR_BURST), + (nameof(TASK_METROPOLICE_GET_PATH_TO_STITCH), TASK_METROPOLICE_GET_PATH_TO_STITCH), + (nameof(TASK_METROPOLICE_RESET_LEDGE_CHECK_TIME), TASK_METROPOLICE_RESET_LEDGE_CHECK_TIME), + (nameof(TASK_METROPOLICE_GET_PATH_TO_BESTSOUND_LOS), TASK_METROPOLICE_GET_PATH_TO_BESTSOUND_LOS), + (nameof(TASK_METROPOLICE_ARREST_ENEMY), TASK_METROPOLICE_ARREST_ENEMY), + (nameof(TASK_METROPOLICE_LEAD_ARREST_ENEMY), TASK_METROPOLICE_LEAD_ARREST_ENEMY), + (nameof(TASK_METROPOLICE_SIGNAL_FIRING_TIME), TASK_METROPOLICE_SIGNAL_FIRING_TIME), + (nameof(TASK_METROPOLICE_ACTIVATE_BATON), TASK_METROPOLICE_ACTIVATE_BATON), + (nameof(TASK_METROPOLICE_WAIT_FOR_SENTENCE), TASK_METROPOLICE_WAIT_FOR_SENTENCE), + (nameof(TASK_METROPOLICE_GET_PATH_TO_PRECHASE), TASK_METROPOLICE_GET_PATH_TO_PRECHASE), + (nameof(TASK_METROPOLICE_CLEAR_PRECHASE), TASK_METROPOLICE_CLEAR_PRECHASE), + ], + Conditions = [ + (nameof(COND_METROPOLICE_ON_FIRE), COND_METROPOLICE_ON_FIRE), + (nameof(COND_METROPOLICE_ENEMY_RESISTING_ARREST), COND_METROPOLICE_ENEMY_RESISTING_ARREST), + (nameof(COND_METROPOLICE_PLAYER_TOO_CLOSE), COND_METROPOLICE_PLAYER_TOO_CLOSE), + (nameof(COND_METROPOLICE_CHANGE_BATON_STATE), COND_METROPOLICE_CHANGE_BATON_STATE), + (nameof(COND_METROPOLICE_PHYSOBJECT_ASSAULT), COND_METROPOLICE_PHYSOBJECT_ASSAULT), + ], + SquadSlots = [ + (nameof(SQUAD_SLOT_POLICE_CHARGE_ENEMY), (int)SQUAD_SLOT_POLICE_CHARGE_ENEMY), + (nameof(SQUAD_SLOT_POLICE_HARASS), (int)SQUAD_SLOT_POLICE_HARASS), + (nameof(SQUAD_SLOT_POLICE_DEPLOY_MANHACK), (int)SQUAD_SLOT_POLICE_DEPLOY_MANHACK), + (nameof(SQUAD_SLOT_POLICE_ATTACK_OCCLUDER1), (int)SQUAD_SLOT_POLICE_ATTACK_OCCLUDER1), + (nameof(SQUAD_SLOT_POLICE_ATTACK_OCCLUDER2), (int)SQUAD_SLOT_POLICE_ATTACK_OCCLUDER2), + (nameof(SQUAD_SLOT_POLICE_ARREST_ENEMY), (int)SQUAD_SLOT_POLICE_ARREST_ENEMY), + ], + Declare = static () => { + AE_METROPOLICE_BATON_ON = DeclareAnimEvent(nameof(AE_METROPOLICE_BATON_ON)); + AE_METROPOLICE_BATON_OFF = DeclareAnimEvent(nameof(AE_METROPOLICE_BATON_OFF)); + AE_METROPOLICE_SHOVE = DeclareAnimEvent(nameof(AE_METROPOLICE_SHOVE)); + AE_METROPOLICE_START_DEPLOY = DeclareAnimEvent(nameof(AE_METROPOLICE_START_DEPLOY)); + AE_METROPOLICE_DRAW_PISTOL = DeclareAnimEvent(nameof(AE_METROPOLICE_DRAW_PISTOL)); + AE_METROPOLICE_DEPLOY_MANHACK = DeclareAnimEvent(nameof(AE_METROPOLICE_DEPLOY_MANHACK)); + ACT_METROPOLICE_DRAW_PISTOL = DeclareActivity(nameof(ACT_METROPOLICE_DRAW_PISTOL)); + ACT_METROPOLICE_DEPLOY_MANHACK = DeclareActivity(nameof(ACT_METROPOLICE_DEPLOY_MANHACK)); + ACT_METROPOLICE_FLINCH_BEHIND = DeclareActivity(nameof(ACT_METROPOLICE_FLINCH_BEHIND)); + ACT_PUSH_PLAYER = DeclareActivity(nameof(ACT_PUSH_PLAYER)); + ACT_MELEE_ATTACK_THRUST = DeclareActivity(nameof(ACT_MELEE_ATTACK_THRUST)); + ACT_ACTIVATE_BATON = DeclareActivity(nameof(ACT_ACTIVATE_BATON)); + ACT_DEACTIVATE_BATON = DeclareActivity(nameof(ACT_DEACTIVATE_BATON)); + ACT_WALK_BATON = DeclareActivity(nameof(ACT_WALK_BATON)); + ACT_IDLE_ANGRY_BATON = DeclareActivity(nameof(ACT_IDLE_ANGRY_BATON)); + g_interactionMetrocopStartedStitch = GetInteractionID(); + g_interactionMetrocopIdleChatter = GetInteractionID(); + g_interactionMetrocopClearSentenceQueues = GetInteractionID(); + }, + Definitions = [ + new(SCHED_METROPOLICE_WAKE_ANGRY, + [ + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + TASK_FACE_ENEMY, + ]), + + new(SCHED_METROPOLICE_INVESTIGATE_SOUND, + [ + TASK_STOP_MOVING, + TASK_STORE_LASTPOSITION, + TASK_METROPOLICE_GET_PATH_TO_BESTSOUND_LOS, + TASK_FACE_IDEAL, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + (TASK_WAIT, 5), + TASK_GET_PATH_TO_LASTPOSITION, + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + TASK_CLEAR_LASTPOSITION, + TASK_FACE_REASONABLE, + ], + [ + COND_NEW_ENEMY, + COND_SEE_FEAR, + COND_SEE_ENEMY, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_HEAR_DANGER, + ]), + + new(SCHED_METROPOLICE_HARASS, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_WAIT_FACE_ENEMY, 6), + TASK_METROPOLICE_HARASS, + TASK_WAIT_PVS, + ], + [ + COND_CAN_RANGE_ATTACK1, + COND_NEW_ENEMY, + ]), + + new(SCHED_METROPOLICE_DRAW_PISTOL, + [ + TASK_STOP_MOVING, + (TASK_PLAY_SEQUENCE_FACE_ENEMY, nameof(ACT_METROPOLICE_DRAW_PISTOL)), + (TASK_WAIT_FACE_ENEMY, 0.1f), + ]), + + new(SCHED_METROPOLICE_CHASE_ENEMY, + [ + TASK_STOP_MOVING, + (TASK_SET_FAIL_SCHEDULE, SCHED_METROPOLICE_ESTABLISH_LINE_OF_FIRE), + (TASK_SET_TOLERANCE_DISTANCE, 24), + (TASK_GET_CHASE_PATH_TO_ENEMY, 300), + (TASK_SPEAK_SENTENCE, 6), + TASK_RUN_PATH, + TASK_METROPOLICE_RESET_LEDGE_CHECK_TIME, + TASK_WAIT_FOR_MOVEMENT, + TASK_FACE_ENEMY, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_ENEMY_UNREACHABLE, + COND_CAN_RANGE_ATTACK1, + COND_CAN_MELEE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK2, + COND_TOO_CLOSE_TO_ATTACK, + COND_TASK_FAILED, + COND_LOST_ENEMY, + COND_BETTER_WEAPON_AVAILABLE, + COND_HEAR_DANGER, + ]), + + new(SCHED_METROPOLICE_ESTABLISH_LINE_OF_FIRE, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_FAIL_ESTABLISH_LINE_OF_FIRE), + TASK_FACE_ENEMY, + (TASK_SET_TOLERANCE_DISTANCE, 48), + TASK_GET_PATH_TO_ENEMY_LKP_LOS, + (TASK_SPEAK_SENTENCE, 6), + TASK_RUN_PATH, + TASK_METROPOLICE_RESET_LEDGE_CHECK_TIME, + TASK_WAIT_FOR_MOVEMENT, + (TASK_SET_SCHEDULE, SCHED_COMBAT_FACE), + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_CAN_RANGE_ATTACK1, + COND_CAN_RANGE_ATTACK2, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_HEAR_DANGER, + COND_HEAVY_DAMAGE, + ]), + + new(SCHED_METROPOLICE_ESTABLISH_STITCH_LINE_OF_FIRE, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_FAIL_ESTABLISH_LINE_OF_FIRE), + TASK_FACE_ENEMY, + (TASK_SET_TOLERANCE_DISTANCE, 48), + TASK_METROPOLICE_GET_PATH_TO_STITCH, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_SET_SCHEDULE, SCHED_COMBAT_FACE), + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_HEAR_DANGER, + COND_HEAVY_DAMAGE, + ]), + + new(SCHED_METROPOLICE_DEPLOY_MANHACK, + [ + (TASK_SPEAK_SENTENCE, 5), + (TASK_PLAY_SEQUENCE, nameof(ACT_METROPOLICE_DEPLOY_MANHACK)), + ]), + + new(SCHED_METROPOLICE_ADVANCE, + [ + TASK_STOP_MOVING, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE_ANGRY), + TASK_FACE_ENEMY, + (TASK_WAIT_FACE_ENEMY, 1), + (TASK_WAIT_FACE_ENEMY_RANDOM, 3), + TASK_GET_PATH_TO_ENEMY_LOS, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE_ANGRY), + TASK_FACE_ENEMY, + ], + [ + COND_CAN_RANGE_ATTACK1, + COND_ENEMY_DEAD, + ]), + + new(SCHED_METROPOLICE_CHARGE, + [ + TASK_STOP_MOVING, + (TASK_SET_FAIL_SCHEDULE, SCHED_METROPOLICE_ADVANCE), + TASK_STORE_LASTPOSITION, + (TASK_GET_CHASE_PATH_TO_ENEMY, 300), + (TASK_RUN_PATH_FOR_UNITS, 150), + (TASK_STOP_MOVING, 1), + TASK_FACE_ENEMY, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LOST_ENEMY, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_HEAR_DANGER, + COND_METROPOLICE_PLAYER_TOO_CLOSE, + ]), + + new(SCHED_METROPOLICE_BURNING_RUN, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_METROPOLICE_BURNING_STAND), + (TASK_SET_TOLERANCE_DISTANCE, 24), + TASK_GET_PATH_TO_ENEMY, + (TASK_RUN_PATH_TIMED, 10), + TASK_METROPOLICE_DIE_INSTANTLY, + ]), + + new(SCHED_METROPOLICE_BURNING_STAND, + [ + (TASK_SET_ACTIVITY, Activity.ACT_IDLE_ON_FIRE), + (TASK_WAIT, 1.5f), + (TASK_METROPOLICE_DIE_INSTANTLY, DamageType.Burn), + (TASK_WAIT, 1f), + ]), + + new(SCHED_METROPOLICE_RETURN_TO_PRECHASE, + [ + (TASK_WAIT_RANDOM, 1), + TASK_METROPOLICE_GET_PATH_TO_PRECHASE, + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + TASK_METROPOLICE_CLEAR_PRECHASE, + ], + [ + COND_NEW_ENEMY, + COND_CAN_MELEE_ATTACK1, + COND_CAN_MELEE_ATTACK2, + COND_TASK_FAILED, + COND_LOST_ENEMY, + COND_HEAR_DANGER, + ]), + + new(SCHED_METROPOLICE_ALERT_FACE_BESTSOUND, + [ + (TASK_SPEAK_SENTENCE, 7), + (TASK_SET_SCHEDULE, SCHED_ALERT_FACE_BESTSOUND), + ]), + + new(SCHED_METROPOLICE_ENEMY_RESISTING_ARREST, + [ + TASK_METROPOLICE_SIGNAL_FIRING_TIME, + ]), + + new(SCHED_METROPOLICE_WARN_AND_ARREST_ENEMY, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_METROPOLICE_ENEMY_RESISTING_ARREST), + TASK_STOP_MOVING, + (TASK_PLAY_SEQUENCE_FACE_ENEMY, Activity.ACT_IDLE_ANGRY), + TASK_SPEAK_SENTENCE, + (TASK_METROPOLICE_ARREST_ENEMY, 0.5f), + TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION, + (TASK_METROPOLICE_ARREST_ENEMY, 1), + (TASK_METROPOLICE_WAIT_FOR_SENTENCE, 1), + (TASK_SPEAK_SENTENCE, 1), + (TASK_METROPOLICE_LEAD_ARREST_ENEMY, 5), + (TASK_METROPOLICE_ARREST_ENEMY, 2), + (TASK_METROPOLICE_WAIT_FOR_SENTENCE, 1), + (TASK_SPEAK_SENTENCE, 3), + (TASK_METROPOLICE_ARREST_ENEMY, 1.5f), + (TASK_METROPOLICE_WAIT_FOR_SENTENCE, 2), + TASK_METROPOLICE_SIGNAL_FIRING_TIME, + ], + [ + COND_NEW_ENEMY, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_HEAR_DANGER, + COND_ENEMY_DEAD, + COND_METROPOLICE_ENEMY_RESISTING_ARREST, + ]), + + new(SCHED_METROPOLICE_ARREST_ENEMY, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_METROPOLICE_ENEMY_RESISTING_ARREST), + TASK_GET_PATH_TO_ENEMY_LOS, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + (TASK_PLAY_SEQUENCE_FACE_ENEMY, Activity.ACT_IDLE_ANGRY), + TASK_METROPOLICE_WAIT_FOR_SENTENCE, + (TASK_SPEAK_SENTENCE, 4), + (TASK_METROPOLICE_ARREST_ENEMY, 30), + ], + [ + COND_NEW_ENEMY, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_HEAR_DANGER, + COND_ENEMY_DEAD, + COND_METROPOLICE_ENEMY_RESISTING_ARREST, + COND_WEAPON_BLOCKED_BY_FRIEND, + COND_WEAPON_SIGHT_OCCLUDED, + ]), + + new(SCHED_METROPOLICE_SMG_NORMAL_ATTACK, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + TASK_METROPOLICE_STOP_FIRE_BURST, + TASK_RANGE_ATTACK1, + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_ENEMY_OCCLUDED, + COND_NO_PRIMARY_AMMO, + COND_HEAR_DANGER, + COND_WEAPON_BLOCKED_BY_FRIEND, + COND_WEAPON_SIGHT_OCCLUDED, + ]), + + new(SCHED_METROPOLICE_SMG_BURST_ATTACK, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + (TASK_METROPOLICE_RELOAD_FOR_BURST, 1.4f), + (TASK_METROPOLICE_AIM_STITCH_AT_PLAYER, 1.4f), + TASK_METROPOLICE_BURST_ATTACK, + TASK_FACE_ENEMY, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_NO_PRIMARY_AMMO, + COND_HEAR_DANGER, + COND_WEAPON_BLOCKED_BY_FRIEND, + ]), + + new(SCHED_METROPOLICE_AIM_STITCH_TIGHTLY, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + (TASK_METROPOLICE_RELOAD_FOR_BURST, 1f), + (TASK_METROPOLICE_AIM_STITCH_TIGHTLY, 1f), + TASK_METROPOLICE_BURST_ATTACK, + TASK_FACE_ENEMY, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_NO_PRIMARY_AMMO, + COND_HEAR_DANGER, + COND_WEAPON_BLOCKED_BY_FRIEND, + ]), + + new(SCHED_METROPOLICE_AIM_STITCH_AT_AIRBOAT, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + (TASK_METROPOLICE_RELOAD_FOR_BURST, 2.5f), + (TASK_METROPOLICE_AIM_STITCH_AT_AIRBOAT, 2.5f), + TASK_METROPOLICE_BURST_ATTACK, + TASK_FACE_ENEMY, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_NO_PRIMARY_AMMO, + COND_HEAR_DANGER, + COND_WEAPON_BLOCKED_BY_FRIEND, + ]), + + new(SCHED_METROPOLICE_AIM_STITCH_IN_FRONT_OF_AIRBOAT, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + (TASK_METROPOLICE_RELOAD_FOR_BURST, 2.5f), + (TASK_METROPOLICE_AIM_STITCH_IN_FRONT_OF_AIRBOAT, 2.5f), + TASK_METROPOLICE_BURST_ATTACK, + TASK_FACE_ENEMY, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_NO_PRIMARY_AMMO, + COND_HEAR_DANGER, + COND_WEAPON_BLOCKED_BY_FRIEND, + ]), + + new(SCHED_METROPOLICE_AIM_STITCH_ALONG_SIDE_OF_AIRBOAT, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + (TASK_METROPOLICE_RELOAD_FOR_BURST, 2.5f), + (TASK_METROPOLICE_AIM_STITCH_ALONG_SIDE_OF_AIRBOAT, 2.5f), + TASK_METROPOLICE_BURST_ATTACK, + TASK_FACE_ENEMY, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_NO_PRIMARY_AMMO, + COND_HEAR_DANGER, + COND_WEAPON_BLOCKED_BY_FRIEND, + ]), + + new(SCHED_METROPOLICE_AIM_STITCH_BEHIND_AIRBOAT, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + (TASK_METROPOLICE_RELOAD_FOR_BURST, 2.5f), + (TASK_METROPOLICE_AIM_STITCH_BEHIND_AIRBOAT, 2.5f), + TASK_METROPOLICE_BURST_ATTACK, + TASK_FACE_ENEMY, + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_NO_PRIMARY_AMMO, + COND_HEAR_DANGER, + COND_WEAPON_BLOCKED_BY_FRIEND, + ]), + + new(SCHED_METROPOLICE_SHOVE, + [ + TASK_STOP_MOVING, + (TASK_FACE_PLAYER, 0.1f), + (TASK_METROPOLICE_ACTIVATE_BATON, 1), + (TASK_PLAY_SEQUENCE, nameof(ACT_PUSH_PLAYER)), + ]), + + new(SCHED_METROPOLICE_ACTIVATE_BATON, + [ + TASK_STOP_MOVING, + TASK_FACE_TARGET, + (TASK_METROPOLICE_ACTIVATE_BATON, 1), + ]), + + new(SCHED_METROPOLICE_DEACTIVATE_BATON, + [ + TASK_STOP_MOVING, + TASK_METROPOLICE_ACTIVATE_BATON, + ]), + + new(SCHED_METROPOLICE_SMASH_PROP, + [ + TASK_GET_PATH_TO_TARGET, + (TASK_MOVE_TO_TARGET_RANGE, 50), + TASK_STOP_MOVING, + TASK_FACE_TARGET, + (TASK_ANNOUNCE_ATTACK, 1), + (TASK_PLAY_SEQUENCE, Activity.ACT_MELEE_ATTACK1), + ], + [ + COND_NEW_ENEMY, + COND_ENEMY_DEAD, + ]), + ], + }; + + public override BaseEntity? CheckTraceHullAttack(in Vector3 start, in Vector3 end, in Vector3 mins, in Vector3 maxs, float damage, DamageType dmgType, float forceScale = 1.0f, bool damageAnyNPC = false) { + TakeDamageInfo dmgInfo = new(this, this, damage, DamageType.Slash); + + TraceFilterMetroPolice traceFilter = new(this, Source.CollisionGroup.None, dmgInfo, forceScale, damageAnyNPC); + + Ray ray = default; + ray.Init(start, end, mins, maxs); + + enginetrace.TraceRay(in ray, Mask.Shot, ref traceFilter, out Trace tr); + + BaseEntity? entity = traceFilter.Hit; + + if (entity == null) { + Vector3 topCenter = GetAbsOrigin(); + CollisionProp().WorldSpaceAABB(out _, out Vector3 aabbMaxs); + topCenter.Z = aabbMaxs.Z + 1.0f; + + ray.Init(topCenter, end, mins, maxs); + enginetrace.TraceRay(in ray, Mask.ShotHull, ref traceFilter, out tr); + + entity = traceFilter.Hit; + } + + return entity; + } + + public override void OnScheduleChange() { + base.OnScheduleChange(); + + if (GetEnemy() != null && HasCondition((int)SCOND_t.COND_ENEMY_DEAD)) + AnnounceEnemyKill(GetEnemy()); + } + + public override void PrescheduleThink() { + base.PrescheduleThink(); + + Sentences.UpdateSentenceQueue(); + + PlayerIsNear = false; + if (PlayerIsCriminal() == false) { + BasePlayer? player = AI_GetClosestPlayer(); + + if (player != null && (player.WorldSpaceCenter() - WorldSpaceCenter()).LengthSquared() < (128 * 128)) { + PlayerIsNear = true; + AddLookTarget(player, 0.75f, 5.0f); + + if ((PolicingBehavior.IsEnabled() == false) && (NumWarnings >= METROPOLICE_MAX_WARNINGS)) { + BatonDebounceTime = gpGlobals.CurTime + random.RandomFloat(2.5f, 4.0f); + SetTarget(player); + SetBatonState(true); + } + } + else { + if (PolicingBehavior.IsEnabled() == false && gpGlobals.CurTime > BatonDebounceTime) + SetBatonState(false); + + KeepFacingPlayer = false; + } + } + + if (IsOnFire()) + SetCondition(COND_METROPOLICE_ON_FIRE); + else + ClearCondition(COND_METROPOLICE_ON_FIRE); + + if (gpGlobals.CurTime > RecentDamageTime + RECENT_DAMAGE_INTERVAL) { + RecentDamage = 0; + RecentDamageTime = 0; + } + } + public override void Precache() { if (HasSpawnFlags(SF_NPC_START_EFFICIENT)) SetModelName("models/police_cheaple.mdl"); @@ -63,10 +835,19 @@ public override void Precache() { PrecacheScriptSound("NPC_Metropolice.Shove"); PrecacheScriptSound("NPC_MetroPolice.WaterSpeech"); PrecacheScriptSound("NPC_MetroPolice.HidingSpeech"); + enginesound.PrecacheSentenceGroup("METROPOLICE"); base.Precache(); } + public override bool CreateComponents() { + if (!base.CreateComponents()) + return false; + + Sentences.Init(this, "NPC_Metropolice.SentenceParameters"); + return true; + } + public override void Spawn() { Precache(); @@ -79,6 +860,7 @@ public override void Spawn() { AddSolidFlags(SolidFlags.NotStandable); SetMoveType(Source.MoveType.Step); SetBloodColor(Shared.BloodColor.Red); + IdleChatterType = METROPOLICE_CHATTER_ASK_QUESTION; SimpleCops = HasSpawnFlags(SF_METROPOLICE_SIMPLE_VERSION); if (HasSpawnFlags(SF_METROPOLICE_NOCHATTER)) AddSpawnFlags(SF_NPC_GAG); @@ -100,6 +882,8 @@ public override void Spawn() { CapabilitiesAdd(Capability.Duck | Capability.AutoDoors | Capability.OpenDoors); CapabilitiesAdd(Capability.UseShotRegulator); + PistolClips = METROPOLICE_NUM_CLIPS; + NPCInit(); if (HasSpawnFlags(SF_METROPOLICE_MID_RANGE_ATTACK)) { @@ -107,6 +891,8 @@ public override void Spawn() { SetDistLook(METROPOLICE_MID_RANGE_ATTACK_RANGE); } + Manhack.Set(null); + BaseCombatWeapon? weapon = GetActiveWeapon(); if (weapon != null) { if (!FClassnameIs(weapon, "weapon_pistol")) @@ -116,6 +902,13 @@ public override void Spawn() { weapon.AddEffects(EntityEffects.NoDraw); } + GetEnemies().SetFreeKnowledgeDuration(6.0f); + + ShouldActivateBaton = false; + ValidStitchTime = -1.0f; + NextLedgeCheckTime = -1.0f; + BurstReloadCount = METROPOLICE_BURST_RELOAD_COUNT; + if (HasSpawnFlags(SF_METROPOLICE_ALWAYS_STITCH)) { if (Weapon_OwnsThisType("weapon_smg1", 0) == null) { Warning("Warning! Metrocop is trying to use the stitch behavior but he has no smg1!\n"); @@ -123,7 +916,14 @@ public override void Spawn() { } } + NumWarnings = 0; + PlayerTooClose = false; + KeepFacingPlayer = false; ChasePlayerTime = 0; + PreChaseOrigin = vec3_origin; + PreChaseYaw = 0; + + FnUse = PrecriminalUse; if (Manhacks != 0) SetBodygroup(METROPOLICE_BODYGROUP_MANHACK, 1); @@ -138,29 +938,125 @@ public override void Weapon_Equip(BaseCombatWeapon weapon) { } } - public override int GetSoundInterests() { - return (int)(SoundInstanceType.World | SoundInstanceType.Combat | SoundInstanceType.Player | SoundInstanceType.PlayerVehicle | SoundInstanceType.Danger | - SoundInstanceType.PhysicsDanger | SoundInstanceType.BulletImpact | SoundInstanceType.MoveAway); + public override EntityCapabilities ObjectCaps() => UsableNPCObjectCaps(base.ObjectCaps()); + + public override void SpeakSentence(int sentenceType) { + if (!PlayerIsCriminal()) + return; + + switch (sentenceType) { + case METROPOLICE_SENTENCE_FREEZE: + Sentences.Speak("METROPOLICE_FREEZE", SentencePriority.Medium, SentenceCriteria.Normal); + break; + + case METROPOLICE_SENTENCE_HES_OVER_HERE: + Sentences.Speak("METROPOLICE_OVER_HERE", SentencePriority.Medium, SentenceCriteria.Normal); + break; + + case METROPOLICE_SENTENCE_HES_RUNNING: + Sentences.Speak("METROPOLICE_HES_RUNNING", SentencePriority.High, SentenceCriteria.Normal); + break; + + case METROPOLICE_SENTENCE_TAKE_HIM_DOWN: + Sentences.Speak("METROPOLICE_TAKE_HIM_DOWN", SentencePriority.High, SentenceCriteria.Normal); + break; + + case METROPOLICE_SENTENCE_ARREST_IN_POSITION: + Sentences.Speak("METROPOLICE_ARREST_IN_POS", SentencePriority.Medium, SentenceCriteria.Normal); + break; + + case METROPOLICE_SENTENCE_DEPLOY_MANHACK: + Sentences.Speak("METROPOLICE_DEPLOY_MANHACK"); + break; + + case METROPOLICE_SENTENCE_MOVE_INTO_POSITION: { + BaseEntity? entity = GetEnemy(); + + if (entity != null && !HasSpawnFlags(SF_METROPOLICE_ARREST_ENEMY)) { + if (entity.IsPlayer() && (entity.GetHealth() <= 20)) { + if (!HasMemory(bits_MEMORY_PLAYER_HURT)) { + if (Sentences.Speak("METROPOLICE_PLAYERHIT", SentencePriority.High) >= 0) + Squad!.SquadRemember(bits_MEMORY_PLAYER_HURT); + } + } + + if (GetNavigator()!.GetPath().GetPathLength() > 20 * 12.0f) + Sentences.Speak("METROPOLICE_FLANK"); + } + } + break; + + case METROPOLICE_SENTENCE_HEARD_SOMETHING: + if ((GetState() == NPCState.Alert) || (GetState() == NPCState.Idle)) + Sentences.Speak("METROPOLICE_HEARD_SOMETHING", SentencePriority.Medium); + break; + } } - public override float MaxYawSpeed() { - switch (GetActivity()) { - case Activity.ACT_TURN_LEFT: - case Activity.ACT_TURN_RIGHT: - return 120; + void AnnounceEnemyKill(BaseEntity? enemy) { + if (enemy == null) + return; - case Activity.ACT_RUN: - case Activity.ACT_RUN_HURT: - return 15; + string sentenceName = "METROPOLICE_KILL_MONST"; + switch (enemy.Classify()) { + case Class_T.Player: + sentenceName = "METROPOLICE_KILL_PLAYER"; + break; - case Activity.ACT_WALK: - case Activity.ACT_WALK_CROUCH: - case Activity.ACT_RUN_CROUCH: - return 25; + case Class_T.PlayerAlly: + case Class_T.CitizenRebel: + case Class_T.CitizenPassive: + case Class_T.Vortigaunt: + sentenceName = "METROPOLICE_KILL_CITIZENS"; + break; - default: - return 45; + case Class_T.PlayerAllyVital: + sentenceName = "METROPOLICE_KILL_CHARACTER"; + break; + + case Class_T.Antlion: + sentenceName = "METROPOLICE_KILL_BUGS"; + break; + + case Class_T.Zombie: + sentenceName = "METROPOLICE_KILL_ZOMBIES"; + break; + + case Class_T.Headcrab: + case Class_T.Barnacle: + sentenceName = "METROPOLICE_KILL_PARASITES"; + break; + } + + Sentences.Speak(sentenceName, SentencePriority.High); + } + + void AnnounceOutOfAmmo() { + if (HasCondition((int)SCOND_t.COND_NO_PRIMARY_AMMO)) + Sentences.Speak("METROPOLICE_COVER_NO_AMMO"); + else + Sentences.Speak("METROPOLICE_COVER_LOW_AMMO"); + } + + void AnnounceTakeCoverFromDanger(ref WorldSoundInstance sound) { + BaseEntity? soundOwner = sound.Owner.Get(); + if (soundOwner != null) { + if (soundOwner is BaseGrenade grenade) { + if (IRelationType(grenade.Thrower.Get()) != Disposition.LI) + Sentences.Speak("METROPOLICE_DANGER_GREN", SentencePriority.High, SentenceCriteria.Normal); + return; + } + + if (soundOwner.GetServerVehicle() != null) { + Sentences.Speak("METROPOLICE_DANGER_VEHICLE", SentencePriority.High, SentenceCriteria.Normal); + return; + } + + if (FClassnameIs(soundOwner, "npc_manhack")) + throw new NotImplementedException(); } + + Sentences.Speak("METROPOLICE_DANGER", SentencePriority.High, SentenceCriteria.Normal); } public override bool CreateBehaviors() { @@ -169,6 +1065,11 @@ public override bool CreateBehaviors() { return base.CreateBehaviors(); } + public void InputEnableManhackToss(InputData inputdata) { + if (HasSpawnFlags(SF_METROPOLICE_NO_MANHACK_DEPLOY)) + RemoveSpawnFlags(SF_METROPOLICE_NO_MANHACK_DEPLOY); + } + public void InputSetPoliceGoal(InputData inputdata) { BaseEntity? goal = gEntList.FindEntityByName(null, inputdata.Value.String()); @@ -185,20 +1086,133 @@ public void InputSetPoliceGoal(InputData inputdata) { PolicingBehavior.Enable(policeGoal); } - public bool BatonActive() { - if (GetActiveWeapon() is WeaponStunStick stick) - return stick.GetStunState(); + public void InputActivateBaton(InputData inputdata) => SetBatonState(inputdata.Value.Bool()); - return false; + public override void DeathSound(in TakeDamageInfo info) { + if (IsOnFire()) + return; + + Sentences.Speak("METROPOLICE_DIE", SentencePriority.Invalid, SentenceCriteria.Always); } - public void SetBatonState(bool state) => throw new NotImplementedException(); + public override void LostEnemySound() { + if (!PlayerIsCriminal()) + return; + + if (gpGlobals.CurTime <= NextLostSoundTime) + return; - public AI_Sentence_NPC_MetroPolice GetSentences() => Sentences; + string sentence; + if (GetEnemy() == null || gpGlobals.CurTime - GetEnemyLastTimeSeen() > 10) + sentence = "METROPOLICE_LOST_LONG"; + else + sentence = "METROPOLICE_LOST_SHORT"; + + if (Sentences.Speak(sentence) >= 0) + NextLostSoundTime = gpGlobals.CurTime + random.RandomFloat(5.0f, 15.0f); + } + + public override void FoundEnemySound() { + if (HasSpawnFlags(SF_METROPOLICE_ARREST_ENEMY)) + return; + + Sentences.Speak("METROPOLICE_REFIND_ENEMY", SentencePriority.High); + } + + public override bool ShouldPlayIdleSound() { + if ((NPCState == NPCState.Idle) || (NPCState == NPCState.Alert)) { + if (IdleChatterType >= METROPOLICE_CHATTER_RESPONSE) + return FOkToMakeSound(); + } + + return base.ShouldPlayIdleSound(); + } + + static readonly string[,] IdleQuestions = { + { "METROPOLICE_IDLE_CHECK", "METROPOLICE_IDLE_QUEST" }, + { "METROPOLICE_IDLE_CHECK_CR", "METROPOLICE_IDLE_QUEST_CR" }, + }; + + static readonly string[,] IdleResponses = { + { "METROPOLICE_IDLE_CLEAR", "METROPOLICE_IDLE_ANSWER" }, + { "METROPOLICE_IDLE_CLEAR_CR", "METROPOLICE_IDLE_ANSWER_CR" }, + }; + + public override void IdleSound() { + bool isCriminal = PlayerIsCriminal(); + + switch (IdleChatterType) { + case METROPOLICE_CHATTER_WAIT_FOR_RESPONSE: + break; + + case METROPOLICE_CHATTER_ASK_QUESTION: { + if (PlayerIsNear && !HasMemory(bits_MEMORY_PLAYER_HARASSED)) { + if (Sentences.Speak("METROPOLICE_IDLE_HARASS_PLAYER", SentencePriority.Normal, SentenceCriteria.Normal) >= 0) { + Remember(bits_MEMORY_PLAYER_HARASSED); + GetSquad()?.SquadRemember(bits_MEMORY_PLAYER_HARASSED); + } + return; + } + + if (random.RandomInt(0, 1) == 0) + break; + + int questionType = random.RandomInt(0, METROPOLICE_CHATTER_RESPONSE_TYPE_COUNT); + if (!IsInSquad() || (questionType == METROPOLICE_CHATTER_RESPONSE_TYPE_COUNT)) { + Sentences.Speak(isCriminal ? "METROPOLICE_IDLE_CR" : "METROPOLICE_IDLE"); + break; + } + + if (Sentences.Speak(IdleQuestions[isCriminal ? 1 : 0, questionType]) >= 0) { + GetSquad()!.BroadcastInteraction(g_interactionMetrocopIdleChatter, METROPOLICE_CHATTER_RESPONSE + questionType, this); + IdleChatterType = METROPOLICE_CHATTER_WAIT_FOR_RESPONSE; + } + } + break; + + default: { + int responseType = IdleChatterType - METROPOLICE_CHATTER_RESPONSE; + + if (Sentences.Speak(IdleResponses[isCriminal ? 1 : 0, responseType]) >= 0) { + GetSquad()!.BroadcastInteraction(g_interactionMetrocopIdleChatter, METROPOLICE_CHATTER_ASK_QUESTION, this); + IdleChatterType = METROPOLICE_CHATTER_ASK_QUESTION; + } + } + break; + } + } + + public override int GetSoundInterests() { + return (int)(SoundInstanceType.World | SoundInstanceType.Combat | SoundInstanceType.Player | SoundInstanceType.PlayerVehicle | SoundInstanceType.Danger | + SoundInstanceType.PhysicsDanger | SoundInstanceType.BulletImpact | SoundInstanceType.MoveAway); + } + + public override float MaxYawSpeed() { + switch (GetActivity()) { + case Activity.ACT_TURN_LEFT: + case Activity.ACT_TURN_RIGHT: + return 120; + + case Activity.ACT_RUN: + case Activity.ACT_RUN_HURT: + return 15; + + case Activity.ACT_WALK: + case Activity.ACT_WALK_CROUCH: + case Activity.ACT_RUN_CROUCH: + return 25; + + default: + return 45; + } + } public override Class_T Classify() => Class_T.MetroPolice; - public bool PlayerIsCriminal() { + bool PlayerIsCriminal() { + if (PolicingBehavior.IsEnabled() && PolicingBehavior.TargetIsHostile()) + return true; + if (GlobalEntity.GetState("gordon_precriminal") == GlobalEState.On) return false; @@ -221,4 +1235,925 @@ public override Disposition IRelationType(BaseEntity? target) { return disp; } + + void OnAnimEventShove() { + BaseEntity? hurt = CheckTraceHullAttack(16, new Vector3(-16, -16, -16), new Vector3(16, 16, 16), 15, DamageType.Club, 1.0f, false); + + if (hurt != null) { + BasePlayer? player = ToBasePlayer(hurt); + + if (player != null) { + player.ViewPunch(new QAngle(8, 14, 0)); + + Vector3 dir = hurt.GetAbsOrigin() - GetAbsOrigin(); + MathLib.VectorNormalize(ref dir); + + MathLib.VectorAngles(dir, out QAngle angles); + MathLib.AngleVectors(angles, out Vector3 forward, out _, out _); + + if ((hurt.GetFlags() & EntityFlags.OnGround) == 0) + forward.Z = 0.0f; + + hurt.ApplyAbsVelocityImpulse(forward * 250.0f); + + player.ForceDropOfCarriedPhysObjects(null); + } + + EmitSound("NPC_Metropolice.Shove"); + } + } + + void OnAnimEventBatonOn() { + if (GetActiveWeapon() is WeaponStunStick stick) + stick.SetStunState(true); + } + + void OnAnimEventBatonOff() { + if (GetActiveWeapon() is WeaponStunStick stick) + stick.SetStunState(false); + } + + public override void HandleAnimEvent(ref AnimEvent animEvent) { + if (animEvent.Event == (int)AE_METROPOLICE_SHOVE) { + OnAnimEventShove(); + return; + } + + if (animEvent.Event == (int)AE_METROPOLICE_BATON_ON) { + OnAnimEventBatonOn(); + return; + } + + if (animEvent.Event == (int)AE_METROPOLICE_BATON_OFF) { + OnAnimEventBatonOff(); + return; + } + + if (animEvent.Event == (int)AE_METROPOLICE_START_DEPLOY) + throw new NotImplementedException(); + + if (animEvent.Event == (int)AE_METROPOLICE_DRAW_PISTOL) { + WeaponDrawn = true; + GetActiveWeapon()?.RemoveEffects(EntityEffects.NoDraw); + return; + } + + if (animEvent.Event == (int)AE_METROPOLICE_DEPLOY_MANHACK) + throw new NotImplementedException(); + + base.HandleAnimEvent(ref animEvent); + } + + public override bool HandleInteraction(int interactionType, object? data, BaseCombatCharacter? sourceEnt) { + if (interactionType == g_interactionMetrocopStartedStitch) { + ValidStitchTime = gpGlobals.CurTime + random.RandomFloat(METROPOLICE_SQUAD_STITCH_MIN_INTERVAL, METROPOLICE_SQUAD_STITCH_MAX_INTERVAL); + return true; + } + + if (interactionType == g_interactionMetrocopIdleChatter) { + IdleChatterType = (int)data!; + return true; + } + + if (interactionType == g_interactionMetrocopClearSentenceQueues) { + Sentences.ClearQueue(); + return true; + } + + if (interactionType == Props.g_interactionHitByPlayerThrownPhysObj) { + if (!IsInAScript() && (NPCState != NPCState.Script)) + SetCondition(COND_METROPOLICE_PHYSOBJECT_ASSAULT); + else + AdministerJustice(); + + if (data is BaseProp prop) { + if (prop.NameMatches("cupcop_can")) + OnCupCopped.FireOutput(this, null); + } + + return true; + } + + return base.HandleInteraction(interactionType, data, sourceEnt); + } + + public override Activity NPC_TranslateActivity(Activity newActivity) { + if (IsOnFire() && newActivity == Activity.ACT_RUN) + return Activity.ACT_RUN_ON_FIRE; + + if (newActivity == ACT_PUSH_PLAYER) { + if (NumWarnings >= METROPOLICE_MAX_WARNINGS) + return Activity.ACT_MELEE_ATTACK1; + } + + newActivity = base.NPC_TranslateActivity(newActivity); + + if (WeaponDrawn && newActivity == Activity.ACT_IDLE && (GetState() == NPCState.Combat || BatonActive())) + newActivity = Activity.ACT_IDLE_ANGRY; + + return newActivity; + } + + int SelectScheduleInvestigateSound() { + if (PlayerIsCriminal() && !HasCondition((int)SCOND_t.COND_SEE_ENEMY)) { + if (HasCondition((int)SCOND_t.COND_HEAR_COMBAT) || HasCondition((int)SCOND_t.COND_HEAR_PLAYER)) { + if (Squad != null && OccupyStrategySlot(SquadSlot.InvestigateSound)) + return SCHED_METROPOLICE_INVESTIGATE_SOUND; + } + } + + return SCHED_NONE; + } + + public override bool OnObstructionPreSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if (moveGoal.DirectTrace.Obstruction != null) { + if (moveGoal.DirectTrace.Obstruction is PhysicsProp prop && prop.GetHealth() != 0) + BlockingProp.Set(prop); + else + BlockingProp.Set(null); + } + + return base.OnObstructionPreSteer(ref moveGoal, distClear, ref result); + } + + int SelectCombatSchedule() => throw new NotImplementedException(); + + int SelectAirboatCombatSchedule() => throw new NotImplementedException(); + + int SelectMoveToLedgeSchedule() => throw new NotImplementedException(); + + int SelectStitchSchedule() => throw new NotImplementedException(); + + bool ShouldAttemptToStitch() => throw new NotImplementedException(); + + bool TryToEnterPistolSlot(SquadSlot squadSlot) => throw new NotImplementedException(); + + bool IsEnemyInAnAirboat() { + if (GetEnemy() == null || !GetEnemy()!.IsPlayer()) + return false; + + BaseEntity? vehicle = ((BasePlayer)GetEnemy()!).GetVehicleEntity(); + if (vehicle == null) + return false; + + return FClassnameIs(vehicle, "prop_vehicle_airboat"); + } + + static readonly string[] HarassmentWarnings = [ + "METROPOLICE_BACK_UP_A", + "METROPOLICE_BACK_UP_B", + "METROPOLICE_BACK_UP_C", + ]; + + void AnnounceHarrassment() => + Sentences.Speak(HarassmentWarnings[random.RandomInt(0, HarassmentWarnings.Length - 1)], SentencePriority.Medium, SentenceCriteria.Normal); + + void IncrementPlayerCriminalStatus() { + BasePlayer? player = AI_GetClosestPlayer(); + + if (player != null) { + AddLookTarget(player, 0.8f, 5.0f); + + if (NumWarnings < METROPOLICE_MAX_WARNINGS) + NumWarnings++; + + if (NumWarnings >= (METROPOLICE_MAX_WARNINGS - 1)) { + SetTarget(player); + SetBatonState(true); + } + } + + BatonDebounceTime = gpGlobals.CurTime + random.RandomFloat(2.0f, 4.0f); + + AnnounceHarrassment(); + + KeepFacingPlayer = true; + } + + int SelectShoveSchedule() { + IncrementPlayerCriminalStatus(); + + ChasePlayerTime = 0; + return SCHED_METROPOLICE_SHOVE; + } + + public override float GetIdealAccel() => GetIdealSpeed() * 2.0f; + + void AdministerJustice() { + if (!AI_IsSinglePlayer()) + return; + + if (!IsInAScript() && (NPCState != NPCState.Script) && HasSpawnFlags(SF_METROPOLICE_ALLOWED_TO_RESPOND)) { + if (PreChaseOrigin == vec3_origin) { + PreChaseOrigin = GetAbsOrigin(); + PreChaseYaw = GetAbsAngles().Y; + } + ChasePlayerTime = gpGlobals.CurTime + RandomFloat(3, 7); + + BasePlayer? player = AI_GetClosestPlayer(); + SetEnemy(player); + SetState(NPCState.Combat); + UpdateEnemyMemory(player, player!.GetAbsOrigin()); + } + else { + KeepFacingPlayer = true; + + List ais = g_AI_Manager.AccessAIs(); + int numAIs = g_AI_Manager.NumAIs(); + for (int i = 0; i < numAIs; i++) { + if (ais[i] == this) + continue; + + if (ais[i].Classify() == Class_T.MetroPolice && FClassnameIs(ais[i], "npc_metropolice")) { + NPC_MetroPolice npc = (NPC_MetroPolice)ais[i]; + if (npc.HasSpawnFlags(SF_METROPOLICE_ALLOWED_TO_RESPOND)) { + BasePlayer? player = AI_GetClosestPlayer(); + if (FVisible(npc) && player != null && npc.FVisible(player) && + Util.DistApprox(WorldSpaceCenter(), npc.WorldSpaceCenter()) < 512) { + npc.AdministerJustice(); + break; + } + } + } + } + } + } + + public override int SelectSchedule() { + BasePlayer? player = AI_GetClosestPlayer(); + if (GetEnemy() == null && HasCondition((int)SCOND_t.COND_IN_PVS) && player != null && !player.IsAlive()) + return SCHED_PATROL_WALK; + + if (HasCondition(COND_METROPOLICE_ON_FIRE)) { + Sentences.Speak("METROPOLICE_ON_FIRE", SentencePriority.Invalid, SentenceCriteria.Always); + return SCHED_METROPOLICE_BURNING_STAND; + } + + if (HasCondition(COND_METROPOLICE_PHYSOBJECT_ASSAULT)) { + ClearCondition(COND_METROPOLICE_PHYSOBJECT_ASSAULT); + + if (PlayerIsCriminal() == false) { + Sentences.Speak("METROPOLICE_HIT_BY_PHYSOBJECT", SentencePriority.Invalid, SentenceCriteria.Always); + NumWarnings = METROPOLICE_MAX_WARNINGS; + AdministerJustice(); + } + else if (GlobalEntity.GetState("gordon_precriminal") == GlobalEState.On) + Sentences.Speak("METROPOLICE_IDLE_HARASS_PLAYER", SentencePriority.Invalid, SentenceCriteria.Always); + } + + int sched = SelectFlinchSchedule(); + if (sched != SCHED_NONE) + return sched; + + if (HasBaton()) { + if (ShouldActivateBaton && BatonActive() == false && IsCurSchedule(SCHED_METROPOLICE_ACTIVATE_BATON) == false) + return SCHED_METROPOLICE_ACTIVATE_BATON; + + if (ShouldActivateBaton == false && BatonActive() && IsCurSchedule(SCHED_METROPOLICE_DEACTIVATE_BATON) == false) + return SCHED_METROPOLICE_DEACTIVATE_BATON; + + if (metropolice_chase_use_follow.GetBool()) { + if (GetEnemy() != null) + throw new NotImplementedException(); + } + } + + if (PlayerIsCriminal() == false) { + if (!IsInAScript() && (HasCondition(COND_METROPOLICE_PLAYER_TOO_CLOSE) || PlayerTooClose)) { + if (NumPlayerHits < 3 || PreChaseOrigin == vec3_origin) { + ClearCondition(COND_METROPOLICE_PLAYER_TOO_CLOSE); + PlayerTooClose = false; + + return SelectShoveSchedule(); + } + } + else if (NumPlayerHits != 0) { + if ((NPCState != NPCState.Combat) && + (PreChaseOrigin != vec3_origin) && + (ChasePlayerTime < gpGlobals.CurTime)) { + return SCHED_METROPOLICE_RETURN_TO_PRECHASE; + } + } + } + + if (HasCondition((int)SCOND_t.COND_HEAR_PHYSICS_DANGER)) { + if (LastPhysicsFlinchTime + 4.0f <= gpGlobals.CurTime) { + LastPhysicsFlinchTime = gpGlobals.CurTime; + return SCHED_FLINCH_PHYSICS; + } + } + + if (HasCondition((int)SCOND_t.COND_HEAR_DANGER)) { + ref WorldSoundInstance sound = ref GetBestSound(); + + Assert(!Unsafe.IsNullRef(ref sound)); + if (!Unsafe.IsNullRef(ref sound)) { + if ((sound.Type & SoundInstanceType.Danger) != 0) { + AnnounceTakeCoverFromDanger(ref sound); + return SCHED_TAKE_COVER_FROM_BEST_SOUND; + } + if (!HasCondition((int)SCOND_t.COND_SEE_ENEMY) && (sound.Type & (SoundInstanceType.Player | SoundInstanceType.PlayerVehicle | SoundInstanceType.Combat)) != 0) + GetMotor()!.SetIdealYawToTarget(sound.GetSoundReactOrigin()); + } + } + + bool highHealth = ((float)GetHealth() / (float)GetMaxHealth() > 0.75f); + + if (!highHealth && !HasBaton()) { + if (GetActiveWeapon() != null && (GetActiveWeapon()!.Clip1() <= 5)) { + Sentences.Speak("METROPOLICE_COVER_LOW_AMMO"); + return SCHED_HIDE_AND_RELOAD; + } + } + + if (HasCondition((int)SCOND_t.COND_NO_PRIMARY_AMMO)) { + if (highHealth) + return SCHED_RELOAD; + + AnnounceOutOfAmmo(); + return SCHED_HIDE_AND_RELOAD; + } + + if (NPCState == NPCState.Combat && ChasePlayerTime > gpGlobals.CurTime) + return SCHED_CHASE_ENEMY; + + if (!BehaviorSelectSchedule()) { + if (KeepFacingPlayer && !PlayerIsCriminal()) + return SCHED_TARGET_FACE; + + switch (NPCState) { + case NPCState.Idle: { + sched = SelectScheduleInvestigateSound(); + if (sched != SCHED_NONE) + return sched; + break; + } + + case NPCState.Alert: { + sched = SelectScheduleInvestigateSound(); + if (sched != SCHED_NONE) + return sched; + } + break; + + case NPCState.Combat: + if (!IsEnemyInAnAirboat() || Weapon_OwnsThisType("weapon_smg1", 0) == null) { + int result = SelectCombatSchedule(); + if (result != SCHED_NONE) + return result; + } + else { + int result = SelectAirboatCombatSchedule(); + if (result != SCHED_NONE) + return result; + } + break; + } + } + + if ((NPCState != NPCState.Combat) && + (PreChaseOrigin != vec3_origin) && + (ChasePlayerTime < gpGlobals.CurTime)) { + return SCHED_METROPOLICE_RETURN_TO_PRECHASE; + } + + return base.SelectSchedule(); + } + + public override int SelectFailSchedule(int failedSchedule, int failedTask, AI_TaskFailureCode taskFailCode) { + if (failedSchedule == SCHED_METROPOLICE_CHASE_ENEMY) + return SCHED_METROPOLICE_ESTABLISH_LINE_OF_FIRE; + + return base.SelectFailSchedule(failedSchedule, failedTask, taskFailCode); + } + + public override int TranslateSchedule(int scheduleType) { + switch (scheduleType) { + case SCHED_ALERT_FACE_BESTSOUND: + if (!IsCurSchedule(SCHED_METROPOLICE_ALERT_FACE_BESTSOUND, false)) + return SCHED_METROPOLICE_ALERT_FACE_BESTSOUND; + return SCHED_ALERT_FACE_BESTSOUND; + + case SCHED_CHASE_ENEMY: + if (!IsRunningBehavior()) + return SCHED_METROPOLICE_CHASE_ENEMY; + + break; + + case SCHED_ESTABLISH_LINE_OF_FIRE: + case SCHED_METROPOLICE_ESTABLISH_LINE_OF_FIRE: + if (IsEnemyInAnAirboat()) { + int sched = SelectMoveToLedgeSchedule(); + if (sched != SCHED_NONE) + return sched; + } + return SCHED_METROPOLICE_ESTABLISH_LINE_OF_FIRE; + + case SCHED_WAKE_ANGRY: + return SCHED_METROPOLICE_WAKE_ANGRY; + + case SCHED_FAIL_TAKE_COVER: + if (HasCondition((int)SCOND_t.COND_CAN_RANGE_ATTACK1)) { + if (TryToEnterPistolSlot(SquadSlot.Attack1) || TryToEnterPistolSlot(SquadSlot.Attack2)) + return SCHED_RANGE_ATTACK1; + } + + if (HasCondition((int)SCOND_t.COND_NO_PRIMARY_AMMO)) + return SCHED_RELOAD; + return SCHED_RUN_RANDOM; + + case SCHED_RANGE_ATTACK1: + Assert(!HasCondition((int)SCOND_t.COND_NO_PRIMARY_AMMO)); + + if (!WeaponDrawn) + return SCHED_METROPOLICE_DRAW_PISTOL; + + if (Weapon_OwnsThisType("weapon_smg1", 0) != null) { + if (IsEnemyInAnAirboat()) { + int sched = SelectStitchSchedule(); + if (sched != SCHED_NONE) + return sched; + } + + if (ShouldAttemptToStitch()) + return SCHED_METROPOLICE_SMG_BURST_ATTACK; + else + return SCHED_METROPOLICE_SMG_NORMAL_ATTACK; + } + break; + + case SCHED_METROPOLICE_ADVANCE: + if (NextChargeTimer.Expired() && metropolice_charge.GetBool()) { + if (Weapon_OwnsThisType("weapon_pistol", 0) != null) { + if (GetEnemy() != null && Vector3.DistanceSquared(GetEnemy()!.GetAbsOrigin(), GetAbsOrigin()) > 300 * 300) { + if (OccupyStrategySlot(SQUAD_SLOT_POLICE_CHARGE_ENEMY)) { + NextChargeTimer.Set(3, 7); + return SCHED_METROPOLICE_CHARGE; + } + } + } + else + NextChargeTimer.Set(99999); + } + break; + } + + return base.TranslateSchedule(scheduleType); + } + + public override void StartTask(in Task_t task) { + switch (task.Task) { + case TASK_METROPOLICE_WAIT_FOR_SENTENCE: { + if (FOkToMakeSound((SentencePriority)(int)task.TaskData)) + TaskComplete(); + } + break; + + case TASK_METROPOLICE_GET_PATH_TO_PRECHASE: { + Assert(PreChaseOrigin != vec3_origin); + if (GetNavigator()!.SetGoal(new AI_NavGoal(PreChaseOrigin))) { + QAngle angles = new(0, PreChaseYaw, 0); + GetNavigator()!.SetArrivalDirection(angles); + TaskComplete(); + } + else + TaskFail(AI_TaskFailureCode.NoRoute); + break; + } + + case TASK_METROPOLICE_CLEAR_PRECHASE: { + PreChaseOrigin = vec3_origin; + PreChaseYaw = 0; + TaskComplete(); + break; + } + + case TASK_METROPOLICE_ACTIVATE_BATON: { + if (HasBaton() == false) { + TaskComplete(); + break; + } + + bool activate = (task.TaskData != 0); + + if (activate) { + if (BatonActive() || ShouldActivateBaton == false) { + TaskComplete(); + break; + } + + Sentences.Speak("METROPOLICE_ACTIVATE_BATON", SentencePriority.Normal, SentenceCriteria.Normal); + SetIdealActivity(ACT_ACTIVATE_BATON); + } + else { + if (BatonActive() == false || ShouldActivateBaton) { + TaskComplete(); + break; + } + + Sentences.Speak("METROPOLICE_DEACTIVATE_BATON", SentencePriority.Normal, SentenceCriteria.Normal); + SetIdealActivity(ACT_DEACTIVATE_BATON); + } + } + break; + + case TASK_METROPOLICE_DIE_INSTANTLY: { + TakeDamageInfo info = new(); + + info.SetAttacker(this); + info.SetInflictor(this); + info.SetDamage(Health); + info.SetDamageType((DamageType)(int)task.TaskData); + info.SetDamageForce(new Vector3(0.1f, 0.1f, 0.1f)); + + TakeDamage(info); + + TaskComplete(); + } + break; + + case TASK_METROPOLICE_RESET_LEDGE_CHECK_TIME: + NextLedgeCheckTime = gpGlobals.CurTime; + TaskComplete(); + break; + + case TASK_METROPOLICE_LEAD_ARREST_ENEMY: + case TASK_METROPOLICE_ARREST_ENEMY: + TaskCompletionTime = gpGlobals.CurTime + task.TaskData; + break; + + case TASK_METROPOLICE_SIGNAL_FIRING_TIME: + EnemyResistingArrest(); + TaskComplete(); + break; + + case TASK_METROPOLICE_GET_PATH_TO_STITCH: + case TASK_METROPOLICE_AIM_STITCH_TIGHTLY: + case TASK_METROPOLICE_AIM_STITCH_AT_PLAYER: + case TASK_METROPOLICE_AIM_STITCH_AT_AIRBOAT: + case TASK_METROPOLICE_AIM_STITCH_IN_FRONT_OF_AIRBOAT: + case TASK_METROPOLICE_AIM_STITCH_ALONG_SIDE_OF_AIRBOAT: + case TASK_METROPOLICE_AIM_STITCH_BEHIND_AIRBOAT: + case TASK_METROPOLICE_BURST_ATTACK: + case TASK_METROPOLICE_STOP_FIRE_BURST: + case TASK_METROPOLICE_RELOAD_FOR_BURST: + throw new NotImplementedException(); + + case TASK_METROPOLICE_HARASS: { + if ((SpawnFlags & SF_METROPOLICE_NOCHATTER) == 0) { + if (GetEnemy() != null && GetEnemy()!.GetWaterLevel() > 0) + EmitSound("NPC_MetroPolice.WaterSpeech"); + else + EmitSound("NPC_MetroPolice.HidingSpeech"); + } + + TaskComplete(); + } + break; + + case TASK_RELOAD: + BurstReloadCount = METROPOLICE_BURST_RELOAD_COUNT; + base.StartTask(task); + break; + + case TASK_METROPOLICE_GET_PATH_TO_BESTSOUND_LOS: + break; + + default: + base.StartTask(task); + break; + } + } + + void EnemyResistingArrest() { + if (Squad != null) { + AI_BaseNPC? squadmate = Squad.GetFirstMember(out int iter); + while (squadmate != null) { + squadmate.RemoveSpawnFlags(SF_METROPOLICE_ARREST_ENEMY); + squadmate.SetCondition(COND_METROPOLICE_ENEMY_RESISTING_ARREST); + squadmate = Squad.GetNextMember(ref iter); + } + } + } + + const float FLEEING_DISTANCE_SQR = 100 * 100; + + int SquadArrestCount() { + int count = 0; + + AI_BaseNPC? squadmate = Squad!.GetFirstMember(out int iter); + while (squadmate != null) { + if (squadmate.IsCurSchedule(SCHED_METROPOLICE_ARREST_ENEMY) || + squadmate.IsCurSchedule(SCHED_METROPOLICE_WARN_AND_ARREST_ENEMY)) { + ++count; + } + + squadmate = Squad.GetNextMember(ref iter); + } + + return count; + } + + public override void RunTask(in Task_t task) { + switch (task.Task) { + case TASK_WAIT_FOR_MOVEMENT: + base.RunTask(task); + break; + + case TASK_METROPOLICE_WAIT_FOR_SENTENCE: { + if (FOkToMakeSound((SentencePriority)(int)task.TaskData)) + TaskComplete(); + } + break; + + case TASK_METROPOLICE_ACTIVATE_BATON: + AutoMovement(); + + if (IsActivityFinished()) + TaskComplete(); + break; + + case TASK_METROPOLICE_BURST_ATTACK: + case TASK_METROPOLICE_RELOAD_FOR_BURST: + case TASK_METROPOLICE_GET_PATH_TO_BESTSOUND_LOS: + throw new NotImplementedException(); + + case TASK_METROPOLICE_LEAD_ARREST_ENEMY: + case TASK_METROPOLICE_ARREST_ENEMY: { + if (GetEnemy() == null) { + TaskComplete(); + break; + } + + if (gpGlobals.CurTime >= TaskCompletionTime) { + TaskComplete(); + break; + } + + if (task.Task == TASK_METROPOLICE_LEAD_ARREST_ENEMY) { + int arrestCount = SquadArrestCount(); + if (arrestCount == Squad!.NumMembers()) { + TaskComplete(); + break; + } + + if (Vector3.DistanceSquared(SavePosition, GetEnemy()!.GetAbsOrigin()) > FLEEING_DISTANCE_SQR) { + SpeakSentence(METROPOLICE_SENTENCE_HES_RUNNING); + EnemyResistingArrest(); + break; + } + } + + if (GetEnemy() != null && FacingIdeal()) { + float newIdealYaw = CalcIdealYaw(GetEnemy()!.EyePosition()); + if (MathF.Abs(Util.AngleDiff(GetMotor()!.GetIdealYaw(), newIdealYaw)) >= 45.0f) { + GetMotor()!.SetIdealYawToTarget(GetEnemy()!.EyePosition()); + SetTurnActivity(); + } + } + GetMotor()!.UpdateYaw(); + } + break; + + default: + base.RunTask(task); + break; + } + } + + bool CanDeployManhack() { + if (HasSpawnFlags(SF_METROPOLICE_NO_MANHACK_DEPLOY)) + return false; + + if (Manhack.Get() != null) + return false; + + if (Manhacks < 1) + return false; + + return true; + } + + public override void BuildScheduleTestBits() { + base.BuildScheduleTestBits(); + + if (PlayerIsCriminal() == false) + SetCustomInterruptCondition(COND_METROPOLICE_PHYSOBJECT_ASSAULT); + + if (!IsInAScript() && + !IsCurSchedule(SCHED_METROPOLICE_SHOVE) && + !IsCurSchedule(SCHED_MELEE_ATTACK1) && + !IsCurSchedule(SCHED_RELOAD) && + !IsCurSchedule(SCHED_METROPOLICE_ACTIVATE_BATON)) { + SetCustomInterruptCondition(COND_METROPOLICE_PLAYER_TOO_CLOSE); + } + + if (!IsCurSchedule(SCHED_METROPOLICE_BURNING_RUN) && !IsCurSchedule(SCHED_METROPOLICE_BURNING_STAND) && !IsMoving()) + SetCustomInterruptCondition(COND_METROPOLICE_ON_FIRE); + + if (IsCurSchedule(SCHED_TAKE_COVER_FROM_ENEMY)) { + ClearCustomInterruptCondition((int)SCOND_t.COND_LIGHT_DAMAGE); + ClearCustomInterruptCondition((int)SCOND_t.COND_HEAVY_DAMAGE); + } + + if (!IsCurSchedule(SCHED_CHASE_ENEMY) && + !IsCurSchedule(SCHED_METROPOLICE_ACTIVATE_BATON) && + !IsCurSchedule(SCHED_METROPOLICE_DEACTIVATE_BATON) && + !IsCurSchedule(SCHED_METROPOLICE_SHOVE) && + !IsCurSchedule(SCHED_METROPOLICE_RETURN_TO_PRECHASE)) { + SetCustomInterruptCondition(COND_METROPOLICE_CHANGE_BATON_STATE); + } + + if (IsCurSchedule(SCHED_MELEE_ATTACK1)) { + if (gpGlobals.CurTime - LastDamageFlinchTime < 10.0) { + ClearCustomInterruptCondition((int)SCOND_t.COND_LIGHT_DAMAGE); + ClearCustomInterruptCondition((int)SCOND_t.COND_HEAVY_DAMAGE); + } + } + else if (HasBaton() && IsCurSchedule(SCHED_COMBAT_FACE) && !BatonSwingTimer.Expired()) + ClearCustomInterruptCondition((int)SCOND_t.COND_CAN_MELEE_ATTACK1); + } + + public override void GatherConditions() { + base.GatherConditions(); + + if (PlayerTooClose == false) + ClearCondition(COND_METROPOLICE_PLAYER_TOO_CLOSE); + + BasePlayer? player = AI_GetClosestPlayer(); + + if (player == null) + return; + + float distToPlayerSqr = (player.GetAbsOrigin() - GetAbsOrigin()).LengthSquared(); + + if (player.GetGroundEntity() == this) { + NumPlayerHits = 0; + SetCondition(COND_METROPOLICE_PLAYER_TOO_CLOSE); + } + else if (distToPlayerSqr < (42.0f * 42.0f) && FVisible(player)) { + if (NumPlayerHits < 3 || PreChaseOrigin == vec3_origin) + SetCondition(COND_METROPOLICE_PLAYER_TOO_CLOSE); + } + else { + ClearCondition(COND_METROPOLICE_PLAYER_TOO_CLOSE); + + if ((gpGlobals.CurTime - GetLastAttackTime()) > 3) + NumPlayerHits = 0; + + PlayerTooClose = false; + } + + if (metropolice_move_and_melee.GetBool()) { + if (IsMoving() && HasCondition((int)SCOND_t.COND_CAN_MELEE_ATTACK1) && HasBaton()) { + if (BatonSwingTimer.Expired()) { + BatonSwingTimer.Set(1.0f, 1.75f); + + Activity activity = TranslateActivity(Activity.ACT_MELEE_ATTACK_SWING_GESTURE); + Assert(activity != Activity.ACT_INVALID); + AddGesture(activity); + } + } + } + } + + bool HasBaton() { + BaseCombatWeapon? weapon = GetActiveWeapon(); + + if (weapon != null) + return FClassnameIs(weapon, "weapon_stunstick"); + + return false; + } + + public bool BatonActive() { + if (GetActiveWeapon() is WeaponStunStick stick) + return stick.GetStunState(); + + return false; + } + + public void SetBatonState(bool state) { + if (!HasBaton()) + return; + + if (ShouldActivateBaton != state) { + ShouldActivateBaton = state; + SetCondition(COND_METROPOLICE_CHANGE_BATON_STATE); + } + } + + public override bool QueryHearSound(ref WorldSoundInstance sound) { + if (PlayerIsCriminal() == false) { + if (sound.IsSoundType(SoundInstanceType.Danger) && sound.Owner.Get() != null && IRelationType(sound.Owner.Get()) == Disposition.NU) + return false; + } + + return base.QueryHearSound(ref sound); + } + + public void StunnedTarget(BaseEntity? target) { + SetLastAttackTime(gpGlobals.CurTime); + + if (target != null && target.IsPlayer()) { + OnStunnedPlayer.FireOutput(this, this); + NumPlayerHits++; + } + } + + void PrecriminalUse(BaseEntity? activator, BaseEntity? caller, UseType useType, float value) { + if (IsInAScript()) + return; + + if (IRelationType(activator) == Disposition.HT || ((GetState() != NPCState.Alert) && (GetState() != NPCState.Idle))) + return; + if (PlayerIsCriminal()) + return; + + IncrementPlayerCriminalStatus(); + + if (NumWarnings == METROPOLICE_MAX_WARNINGS) + AdministerJustice(); + } + + public AI_Sentence_NPC_MetroPolice GetSentences() => Sentences; + +} + +public struct TraceFilterMetroPolice(IHandleEntity? passentity, CollisionGroup collisionGroup, TakeDamageInfo dmgInfo, float forceScale, bool damageAnyNPC) : ITraceFilter +{ + public IHandleEntity? PassEnt = passentity; + public CollisionGroup CollisionGroup = collisionGroup; + public TakeDamageInfo DmgInfo = dmgInfo; + public BaseEntity? Hit = null; + public float ForceScale = forceScale; + public bool DamageAnyNPC = damageAnyNPC; + + public bool ShouldHitEntity(IHandleEntity handleEntity, Contents contentsMask) { + if (!StandardFilterRules(handleEntity, contentsMask)) + return false; + + if (!PassServerEntityFilter(handleEntity, PassEnt)) + return false; + + BaseEntity? entity = EntityFromEntityHandle(handleEntity); + + if (entity != null) { + if (!entity.ShouldCollide(CollisionGroup, contentsMask)) + return false; + + if (!g_pGameRules.ShouldCollide(CollisionGroup, entity.GetCollisionGroup())) + return false; + + if (entity.m_takedamage == (byte)Damage.No) + return false; + + if (entity.GetServerVehicle() != null) { + BaseEntity? driver = entity.GetServerVehicle()!.GetPassenger(); + + if (driver != null) + entity = driver; + } + + Vector3 attackDir = entity.WorldSpaceCenter() - DmgInfo.GetAttacker()!.WorldSpaceCenter(); + MathLib.VectorNormalize(ref attackDir); + + TakeDamageInfo info = DmgInfo; + CalculateMeleeDamageForce(ref info, attackDir, info.GetAttacker()!.WorldSpaceCenter(), ForceScale); + + if ((entity.GetFlags() & EntityFlags.OnGround) == 0) + info.ScaleDamageForce(0.001f); + + BaseCombatCharacter? bcc = ToBaseCombatCharacter(info.GetAttacker()); + BaseCombatCharacter? victimBCC = ToBaseCombatCharacter(entity); + + if (bcc != null && victimBCC != null) { + if (DamageAnyNPC || bcc.IRelationType(entity) == Disposition.HT || entity.IsPlayer()) { + if (info.GetDamage() != 0) { + if (!entity.IsPlayer() || GlobalEntity.GetState("gordon_precriminal") == GlobalEState.Off) { + if (entity.IsPlayer() && ((BasePlayer)entity).IsSuitEquipped()) { + info.ScaleDamage(.25f); + info.ScaleDamageForce(.25f); + } + + entity.TakeDamage(info); + } + } + + Hit = entity; + return true; + } + } + else { + Pickup.ForcePlayerToDropThisObject(entity); + + if (info.GetDamage() != 0) + entity.TakeDamage(info); + } + } + + return false; + } + + public readonly TraceType GetTraceType() => TraceType.EntitiesOnly; } diff --git a/Game.Server/Props.cs b/Game.Server/Props.cs index 3f887c0fc..7809985f4 100644 --- a/Game.Server/Props.cs +++ b/Game.Server/Props.cs @@ -400,6 +400,8 @@ public class PropDoorRotatingBreakable : PropDoorRotating; public static class Props { + public static int g_interactionHitByPlayerThrownPhysObj = 0; + public static PhysicsProp? CreatePhysicsProp(ReadOnlySpan modelName, in Vector3 traceStart, in Vector3 traceEnd, IHandleEntity? traceIgnore, bool requireVCollide, ReadOnlySpan className = default) { if (className.IsStringEmpty) className = "physics_prop"; diff --git a/Game.Server/Util.cs b/Game.Server/Util.cs index ba8947014..189f498a1 100644 --- a/Game.Server/Util.cs +++ b/Game.Server/Util.cs @@ -334,6 +334,14 @@ public static void SetMinMaxSize(BaseEntity ent, in Vector3 mins, in Vector3 max ent.SetCollisionBounds(mins, maxs); } + public static float DistApprox(in Vector3 vec1, in Vector3 vec2) { + float dx = vec1.X - vec2.X; + float dy = vec1.Y - vec2.Y; + float dz = vec1.Z - vec2.Z; + + return MathF.Abs(dx) + MathF.Abs(dy) + MathF.Abs(dz); + } + public static float DistApprox2D(in Vector3 vec1, in Vector3 vec2) { float dx = vec1.X - vec2.X; float dy = vec1.Y - vec2.Y; From c312073599e08b4e03fab0f929ed40c00b6cdb37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 02:58:09 +0300 Subject: [PATCH 41/73] Port default AI relationships and player classification --- Game.Server/HL2/HL2_Player.cs | 16 +- Game.Server/IServerVehicle.cs | 2 +- Game.Server/Player.cs | 1 + Game.Server/World.cs | 2 +- Game.Shared/GarrysMod/GMODGameRules.cs | 687 +++++++++++++++++++++++++ 5 files changed, 705 insertions(+), 3 deletions(-) diff --git a/Game.Server/HL2/HL2_Player.cs b/Game.Server/HL2/HL2_Player.cs index 5d106982c..5b9dc7de3 100644 --- a/Game.Server/HL2/HL2_Player.cs +++ b/Game.Server/HL2/HL2_Player.cs @@ -48,6 +48,7 @@ public class HL2_Player : BaseMultiplayerPlayer public virtual void SuspendUse(TimeUnit_t duration) { TimeUseSuspended = gpGlobals.CurTime + duration; } bool SprintEnabled; + Class_T ControlClass; [NetworkName("m_fIsSprinting")] public bool m_bIsSprinting; @@ -114,7 +115,20 @@ public override void Activate() { // GetPlayerProxy(); } - // Class_T Classify() { } + public override Class_T Classify() { + if (ControlClass != Class_T.None) + return ControlClass; + else { + if (IsInAVehicle()) { + IServerVehicle vehicle = GetVehicle()!; + return vehicle.ClassifyPassenger(this, Class_T.Player); + } + else + return Class_T.Player; + } + } + + public void SetControlClass(Class_T controlClass) => ControlClass = controlClass; // bool HandleInteraction(int interactionType, void* data, BaseCombatCharacter sourceEnt) { } diff --git a/Game.Server/IServerVehicle.cs b/Game.Server/IServerVehicle.cs index 93371de48..598684d4d 100644 --- a/Game.Server/IServerVehicle.cs +++ b/Game.Server/IServerVehicle.cs @@ -40,7 +40,7 @@ public interface IServerVehicle : IVehicle int GetEntryAnimForPoint(out Vector3 point); int GetExitAnimToUse(out Vector3 eyeExitEndpoint, out bool allPointsBlocked); void HandleEntryExitFinish(bool exitAnimOn, bool resetAnim); - // TODO: Class_T ClassifyPassenger(CBaseCombatCharacter? passenger, Class_T defaultClassification); + Class_T ClassifyPassenger(BaseCombatCharacter? passenger, Class_T defaultClassification); // float PassengerDamageModifier(in TakeDamageInfo info ); // const vehicleparams_t* GetVehicleParams(); // IPhysicsVehicleController GetVehicleController(); diff --git a/Game.Server/Player.cs b/Game.Server/Player.cs index b89c377e1..095cdeffa 100644 --- a/Game.Server/Player.cs +++ b/Game.Server/Player.cs @@ -255,6 +255,7 @@ public partial class BasePlayer : BaseCombatCharacter ]); public override bool IsPlayer() => true; + public override Class_T Classify() => Class_T.Player; public virtual bool IsBot() => (GetFlags() & EntityFlags.FakeClient) != 0; public virtual bool IsFakeClient() => (GetFlags() & EntityFlags.FakeClient) != 0; public virtual bool IsBotOfType(int botType) => (GetBotType() != 0) && (GetBotType() == botType); diff --git a/Game.Server/World.cs b/Game.Server/World.cs index 8bdefced2..24c256a34 100644 --- a/Game.Server/World.cs +++ b/Game.Server/World.cs @@ -95,7 +95,7 @@ public override void Precache() { AI_NetworkManager.InitializeAINetworks(); g_AI_SchedulesManager.LoadAllSchedules(); - // g_pGameRules.InitDefaultAIRelationships(); + g_pGameRules.InitDefaultAIRelationships(); // BaseCombatCharacter.InitInteractionSystem(); diff --git a/Game.Shared/GarrysMod/GMODGameRules.cs b/Game.Shared/GarrysMod/GMODGameRules.cs index 8ff3cd755..a6acd22f4 100644 --- a/Game.Shared/GarrysMod/GMODGameRules.cs +++ b/Game.Shared/GarrysMod/GMODGameRules.cs @@ -108,6 +108,693 @@ public override bool FlPlayerFallDeathDoesScreenFade(BasePlayer player) { public override float FlPlayerFallDamage(BasePlayer player) { return 10; // todo: lua hook } + + public override void InitDefaultAIRelationships() { + int i, j; + BaseCombatCharacter.AllocateDefaultRelationships(); + + for (i = 0; i < (int)Class_T.NumAIClasses; i++) { + for (j = 0; j < (int)Class_T.NumAIClasses; j++) + BaseCombatCharacter.SetDefaultRelationship((Class_T)i, (Class_T)j, Disposition.NU, 0); + } + + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.CitizenPassive, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.CombineHunter, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Manhack, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Military, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Scanner, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Stalker, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.ProtoSniper, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.Antlion, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Antlion, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Barnacle, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.CitizenPassive, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Manhack, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Military, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Stalker, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.EarthFauna, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Barnacle, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Player, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Antlion, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.CitizenRebel, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Combine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Headcrab, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Vortigaunt, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.Zombie, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.PlayerAlly, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.PlayerAllyVital, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Bullseye, Class_T.HackedRollermine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Player, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Barnacle, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.CitizenRebel, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Combine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.CombineHunter, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Headcrab, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Manhack, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Missile, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Vortigaunt, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.Zombie, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.PlayerAlly, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.PlayerAllyVital, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenPassive, Class_T.HackedRollermine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Player, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Barnacle, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.CitizenRebel, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.CombineHunter, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Manhack, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Military, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Missile, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Scanner, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Stalker, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Vortigaunt, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.PlayerAlly, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.PlayerAllyVital, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CitizenRebel, Class_T.HackedRollermine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Barnacle, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Combine, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.CombineGunship, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.CombineHunter, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Combine, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Combine, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.CombineGunship, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.CombineHunter, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Headcrab, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Missile, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineGunship, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.CitizenPassive, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Combine, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.CombineGunship, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.CombineHunter, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.CombineHunter, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Player, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Barnacle, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.CitizenRebel, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.CombineHunter, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Manhack, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Military, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Scanner, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Stalker, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Vortigaunt, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.PlayerAlly, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.PlayerAllyVital, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Conscript, Class_T.HackedRollermine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Player, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Antlion, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.CitizenRebel, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Combine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Headcrab, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Vortigaunt, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.Zombie, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.PlayerAlly, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.PlayerAllyVital, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Flare, Class_T.HackedRollermine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.CitizenPassive, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Headcrab, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.Zombie, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Headcrab, Class_T.HackedRollermine, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.CitizenPassive, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Combine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Headcrab, Disposition.HT, -1); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Manhack, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Combine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.MetroPolice, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Combine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Military, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Combine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Missile, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Player, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Antlion, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.CitizenRebel, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Combine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Headcrab, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Vortigaunt, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.Zombie, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.PlayerAlly, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.PlayerAllyVital, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.None, Class_T.HackedRollermine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Player, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Barnacle, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Bullseye, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.CitizenPassive, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.CitizenRebel, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.CombineGunship, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.CombineHunter, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Manhack, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Military, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Scanner, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Stalker, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Vortigaunt, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.ProtoSniper, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.PlayerAlly, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.PlayerAllyVital, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Player, Class_T.HackedRollermine, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Player, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Barnacle, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.CitizenRebel, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.CombineHunter, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Headcrab, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Manhack, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Military, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Scanner, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Stalker, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Vortigaunt, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.Zombie, Disposition.FR, 1); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.ProtoSniper, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.PlayerAlly, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.PlayerAllyVital, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAlly, Class_T.HackedRollermine, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Player, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Barnacle, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.CitizenRebel, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.CombineHunter, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Manhack, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Military, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Scanner, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Stalker, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Vortigaunt, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.ProtoSniper, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.PlayerAlly, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.PlayerAllyVital, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.PlayerAllyVital, Class_T.HackedRollermine, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Combine, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.CombineGunship, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.CombineHunter, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Headcrab, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Manhack, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.MetroPolice, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Military, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Scanner, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Stalker, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.Zombie, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.ProtoSniper, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Scanner, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Combine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Headcrab, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.Zombie, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Stalker, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Player, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Barnacle, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.CitizenPassive, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.CitizenRebel, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.CombineHunter, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Manhack, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Military, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Scanner, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Stalker, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Vortigaunt, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.PlayerAlly, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.PlayerAllyVital, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Vortigaunt, Class_T.HackedRollermine, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.CitizenPassive, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.CombineHunter, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Headcrab, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Manhack, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Military, Disposition.FR, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.Zombie, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.Zombie, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.CitizenPassive, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Combine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.MetroPolice, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Military, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Missile, Disposition.NU, 5); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Stalker, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.ProtoSniper, Class_T.HackedRollermine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.None, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Player, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.CitizenPassive, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.CitizenRebel, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.CombineGunship, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.CombineHunter, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Conscript, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Flare, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Manhack, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Military, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Missile, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Scanner, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Stalker, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Vortigaunt, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.Zombie, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.ProtoSniper, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.EarthFauna, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.PlayerAlly, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.PlayerAllyVital, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.EarthFauna, Class_T.HackedRollermine, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.None, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Player, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Antlion, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Barnacle, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Bullseye, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.CitizenPassive, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.CitizenRebel, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Combine, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.CombineGunship, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.CombineHunter, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Conscript, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Flare, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Headcrab, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Manhack, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.MetroPolice, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Military, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Missile, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Scanner, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Stalker, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Vortigaunt, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.Zombie, Disposition.HT, 1); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.ProtoSniper, Disposition.NU, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.EarthFauna, Disposition.HT, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.PlayerAlly, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.PlayerAllyVital, Disposition.LI, 0); + BaseCombatCharacter.SetDefaultRelationship(Class_T.HackedRollermine, Class_T.HackedRollermine, Disposition.LI, 0); + } #endif } #endif From ee3448d0b22d3f550e012fffc4e5c61d1299056b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 04:12:36 +0300 Subject: [PATCH 42/73] Port scripted_sequence and NPC script tasks --- Game.Server/AI_BaseNPC.cs | 696 +++++++++++++++++++++++++++- Game.Server/BaseAnimating.cs | 32 ++ Game.Server/EntityList.cs | 38 ++ Game.Server/Scripted.cs | 852 ++++++++++++++++++++++++++++++++++- Game.Server/Util.cs | 6 +- Game.Shared/NPCEvent.cs | 13 + Game.Shared/ScriptEvent.cs | 25 + Game.Shared/UtilShared.cs | 24 + 8 files changed, 1659 insertions(+), 27 deletions(-) create mode 100644 Game.Shared/ScriptEvent.cs diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 140400138..3c6013a8e 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -262,6 +262,13 @@ public enum ScriptStateType CustomMoveToMark, } +public enum CanPlaySequence_t +{ + CannotPlay = 0, + CanPlayNow, + CanPlayEnqueued, +} + public enum NPCInteractionState { NotRunning = 0, @@ -356,6 +363,7 @@ public static ReadOnlySpan GetActivityName(Activity actID) { DEFINE.KEYFIELD(nameof(HintGroupNavLimiting), FieldType.Boolean, "hintlimiting"), DEFINE.KEYFIELD(nameof(IgnoreUnseenEnemies), FieldType.Boolean, "ignoreunseenenemies"), DEFINE.KEYFIELD(nameof(EnemyFilterName), FieldType.String, "enemyfilter"), + DEFINE.KEYFIELD(nameof(WakeSquad), FieldType.Boolean, "wakesquad"), DEFINE.OUTPUT(nameof(OnHearWorld), "OnHearWorld", eventFuncs), DEFINE.OUTPUT(nameof(OnHearPlayer), "OnHearPlayer", eventFuncs), @@ -366,6 +374,7 @@ public static ReadOnlySpan GetActivityName(Activity actID) { DEFINE.OUTPUT(nameof(OnFoundPlayer), "OnFoundPlayer", eventFuncs), DEFINE.OUTPUT(nameof(OnLostPlayerLOS), "OnLostPlayerLOS", eventFuncs), DEFINE.OUTPUT(nameof(OnLostPlayer), "OnLostPlayer", eventFuncs), + DEFINE.OUTPUT(nameof(OnWake), "OnWake", eventFuncs), ]); public override DataMap? GetDataDescMap() => DataDesc; @@ -520,6 +529,9 @@ public static ReadOnlySpan GetActivityName(Activity actID) { public OutputEvent OnHearCombat = new(); public OutputEvent OnLostEnemy = new(); public OutputEvent OnLostPlayer = new(); + public OutputEvent OnWake = new(); + public bool WakeSquad; + public long WakeTick; public OutputEHANDLE OnFoundEnemy = new(); public OutputEvent OnLostEnemyLOS = new(); public OutputEHANDLE OnFoundPlayer = new(); @@ -2618,7 +2630,364 @@ public static void InitSchedulingTables() { public bool IsInAScript() => InAScript; public void SetInAScript(bool script) => InAScript = script; - public bool CineCleanup() => throw new NotImplementedException(); + public NPCState GetIdealState() => IdealNPCState; + + public bool IsRunningDynamicInteraction() => InteractionState != NPCInteractionState.NotRunning && Cine.Get() != null; + + public static readonly ConVar sv_test_scripted_sequences = new("sv_test_scripted_sequences", "0", FCvar.None, "Tests for scripted sequences that are embedded in the world. Run through your map with this set to check for NPCs falling through the world."); + + public bool CineCleanup() { + AI_ScriptedSequence? oldCine = Cine.Get(); + EntityFlags savedFlags = oldCine != null ? oldCine.SavedFlags : GetFlags(); + + bool destroyCine = false; + if (IsRunningDynamicInteraction()) + throw new NotImplementedException(); + + if (oldCine != null) { + oldCine.SetTarget(null); + SetEffects(oldCine.SavedEffects); + + SetCollisionGroup(oldCine.SavedCollisionGroup); + } + else + AddSolidFlags(SolidFlags.NotStandable); + + Cine.Set(null); + SetTarget(null); + SetGoalEnt(null); + if (LifeState == (int)Source.LifeState.Dying) + throw new NotImplementedException(); + + if (oldCine != null && !string.IsNullOrEmpty(oldCine.Play) && oldCine.PlayedSequence()) { + if (!oldCine.HasSpawnFlags(AI_ScriptedSequence.SF_SCRIPT_DONT_TELEPORT_AT_END)) { + GetBonePosition(0, out Vector3 newOrigin, out _); + + Vector3 oldOrigin = GetLocalOrigin(); + + if ((oldOrigin - newOrigin).Length2D() < 8.0) + newOrigin = oldOrigin; + + Vector3 origin = GetLocalOrigin(); + + origin.X = newOrigin.X; + origin.Y = newOrigin.Y; + origin.Z += 1; + + if ((savedFlags & EntityFlags.Fly) != 0) { + origin.Z = newOrigin.Z; + SetLocalOrigin(origin); + } + else { + SetLocalOrigin(origin); + + int drop = Util.DropToFloor(this, Mask.NPCSolid, AI_GetClosestPlayer()); + + if (drop < 0 || sv_test_scripted_sequences.GetBool()) + SetLocalOrigin(oldOrigin); + else if (drop == 0) { + Vector3 dropOrigin = GetLocalOrigin(); + dropOrigin.Z = newOrigin.Z; + SetLocalOrigin(dropOrigin); + SetGroundEntity(null); + } + } + + origin = GetLocalOrigin(); + + if ((oldOrigin - origin).Length() > 8.0) { + Teleport(origin, null, null); + SetLocalOrigin(origin); + IncrementInterpolationFrame(); + } + + if (Health <= 0) { + SetIdealState(NPCState.Dead); + SetCondition((int)SCOND_t.COND_LIGHT_DAMAGE); + LifeState = (int)Source.LifeState.Dying; + } + } + + Activity = Activity.ACT_RESET; + } + + if (Health > 0) + SetIdealState(NPCState.Idle); + else { + SetIdealState(NPCState.Dead); + SetCondition((int)SCOND_t.COND_LIGHT_DAMAGE); + } + + RemoveSpawnFlags(SF_NPC_WAIT_FOR_SCRIPT); + + if (destroyCine) + Util.Remove(oldCine); + + return true; + } + + public override void HandleAnimEvent(ref AnimEvent animEvent) { + switch (animEvent.Event) { + case SCRIPT_EVENT_DEAD: + if (NPCState == NPCState.Script) { + LifeState = (int)Source.LifeState.Dying; + Health = 0; + } + break; + case SCRIPT_EVENT_NOT_DEAD: + if (NPCState == NPCState.Script) { + LifeState = (int)Source.LifeState.Alive; + Health = MaxHealth; + } + break; + + case SCRIPT_EVENT_SOUND: + EmitSound(animEvent.Options); + break; + + case SCRIPT_EVENT_SOUND_VOICE: + EmitSound(animEvent.Options); + break; + + case SCRIPT_EVENT_SENTENCE_RND1: + if (random.RandomInt(0, 2) == 0) + break; + goto case SCRIPT_EVENT_SENTENCE; + case SCRIPT_EVENT_SENTENCE: + SENTENCEG_PlayRndSz(Edict()!, animEvent.Options, 1.0f, Source.Common.Audio.SoundLevel.LvlTalking, 0, 100); + break; + + case SCRIPT_EVENT_FIREEVENT: + Cine.Get()?.FireScriptEvent(atoi(animEvent.Options)); + break; + case SCRIPT_EVENT_FIRE_INPUT: { + Variant_t emptyVariant = default; + AcceptInput(animEvent.Options, this, this, emptyVariant, 0); + break; + } + + case SCRIPT_EVENT_NOINTERRUPT: + Cine.Get()?.AllowInterrupt(false); + break; + + case SCRIPT_EVENT_CANINTERRUPT: + Cine.Get()?.AllowInterrupt(true); + break; + + case SCRIPT_EVENT_BODYGROUPON: + case SCRIPT_EVENT_BODYGROUPOFF: + case SCRIPT_EVENT_BODYGROUPTEMP: + DevMsg("Bodygroup!\n"); + break; + + case (int)Animevent.AE_NPC_ATTACK_BROADCAST: + break; + + case NPC_EVENT_BODYDROP_HEAVY: + if ((GetFlags() & EntityFlags.OnGround) != 0) + EmitSound("AI_BaseNPC.BodyDrop_Heavy"); + break; + + case NPC_EVENT_BODYDROP_LIGHT: + if ((GetFlags() & EntityFlags.OnGround) != 0) + EmitSound("AI_BaseNPC.BodyDrop_Light"); + break; + + case NPC_EVENT_SWISHSOUND: + EmitSound("AI_BaseNPC.SwishSound"); + break; + + case NPC_EVENT_180TURN: + SetIdealActivity(Activity.ACT_IDLE); + Forget(AI_MemoryFlags.Turning); + SetBoneController(0, GetLocalAngles().Y); + IncrementInterpolationFrame(); + break; + + case NPC_EVENT_ITEM_PICKUP: + throw new NotImplementedException(); + + case NPC_EVENT_WEAPON_SET_SEQUENCE_NUMBER: { + BaseCombatWeapon? weapon = GetActiveWeapon(); + if (weapon != null && animEvent.Options != null) { + int sequence = atoi(animEvent.Options); + if (sequence != -1) + weapon.ResetSequence(sequence); + } + break; + } + + case NPC_EVENT_WEAPON_SET_SEQUENCE_NAME: { + BaseCombatWeapon? weapon = GetActiveWeapon(); + if (weapon != null && animEvent.Options != null) { + int sequence = weapon.LookupSequence(animEvent.Options); + if (sequence != -1) + weapon.ResetSequence(sequence); + } + break; + } + + case NPC_EVENT_WEAPON_SET_ACTIVITY: { + BaseCombatWeapon? weapon = GetActiveWeapon(); + if (weapon != null && animEvent.Options != null) { + Activity act = weapon.LookupActivity(animEvent.Options); + if (act != Activity.ACT_INVALID) + Weapon_SetActivity(act, 0); + } + break; + } + + case NPC_EVENT_WEAPON_DROP: + throw new NotImplementedException(); + + case EVENT_WEAPON_RELOAD: { + BaseCombatWeapon? weapon = GetActiveWeapon(); + if (weapon != null) { + weapon.WeaponSound(WeaponSound.ReloadNPC); + weapon.iClip1 = weapon.GetMaxClip1(); + ClearCondition((int)SCOND_t.COND_LOW_PRIMARY_AMMO); + ClearCondition((int)SCOND_t.COND_NO_PRIMARY_AMMO); + ClearCondition((int)SCOND_t.COND_NO_SECONDARY_AMMO); + } + break; + } + + case EVENT_WEAPON_RELOAD_SOUND: + GetActiveWeapon()?.WeaponSound(WeaponSound.ReloadNPC); + break; + + case EVENT_WEAPON_RELOAD_FILL_CLIP: { + BaseCombatWeapon? weapon = GetActiveWeapon(); + if (weapon != null) { + weapon.iClip1 = weapon.GetMaxClip1(); + ClearCondition((int)SCOND_t.COND_LOW_PRIMARY_AMMO); + ClearCondition((int)SCOND_t.COND_NO_PRIMARY_AMMO); + ClearCondition((int)SCOND_t.COND_NO_SECONDARY_AMMO); + } + break; + } + + case NPC_EVENT_LEFTFOOT: + case NPC_EVENT_RIGHTFOOT: + break; + + case NPC_EVENT_OPEN_DOOR: + throw new NotImplementedException(); + + default: + if ((animEvent.Type & AnimEventType.NewEventSystem) != 0 && (animEvent.Type & AnimEventType.Server) != 0) { + if (animEvent.Event == (int)Animevent.AE_NPC_HOLSTER) { + BaseCombatWeapon? weapon = GetActiveWeapon(); + + Assert(weapon != null); + + GetActiveWeapon()!.Holster(); + SetActiveWeapon(null); + + GetNavigator()!.SetArrivalSequence((int)Activity.ACT_INVALID); + + if (DesiredWeaponState == DesiredWeaponState.ChangingDestroy) + Util.Remove(weapon); + + if (DesiredWeaponState != DesiredWeaponState.Ignore) { + DesiredWeaponState = DesiredWeaponState.Ignore; + Activity = Activity.ACT_RESET; + } + + return; + } + else if (animEvent.Event == (int)Animevent.AE_NPC_DRAW) { + if (GetActiveWeapon() != null) { + GetActiveWeapon()!.Deploy(); + + GetNavigator()!.SetArrivalSequence((int)Activity.ACT_INVALID); + + if (DesiredWeaponState != DesiredWeaponState.Ignore) { + DesiredWeaponState = DesiredWeaponState.Ignore; + Activity = Activity.ACT_RESET; + } + } + return; + } + else if (animEvent.Event == (int)Animevent.AE_NPC_BODYDROP_HEAVY) { + if ((GetFlags() & EntityFlags.OnGround) != 0) + EmitSound("AI_BaseNPC.BodyDrop_Heavy"); + return; + } + else if (animEvent.Event == (int)Animevent.AE_NPC_LEFTFOOT || animEvent.Event == (int)Animevent.AE_NPC_RIGHTFOOT) + return; + else if (animEvent.Event == (int)Animevent.AE_NPC_RAGDOLL) + throw new NotImplementedException(); + else if (animEvent.Event == (int)Animevent.AE_NPC_ADDGESTURE) { + Activity act = LookupActivity(animEvent.Options); + if (act != Activity.ACT_INVALID) { + act = TranslateActivity(act); + if (act != Activity.ACT_INVALID) + AddGesture(act); + } + return; + } + else if (animEvent.Event == (int)Animevent.AE_NPC_RESTARTGESTURE) + throw new NotImplementedException(); + else if (animEvent.Event == (int)Animevent.AE_NPC_WEAPON_DROP) + throw new NotImplementedException(); + else if (animEvent.Event == (int)Animevent.AE_NPC_WEAPON_SET_ACTIVITY) { + BaseCombatWeapon? weapon = GetActiveWeapon(); + if (weapon != null && animEvent.Options != null) { + Activity act = weapon.LookupActivity(animEvent.Options); + if (act == Activity.ACT_INVALID) + { + bool required = false; + act = Weapon_TranslateActivity((Activity)GetActivityID(animEvent.Options), ref required); + } + + if (act != Activity.ACT_INVALID) + Weapon_SetActivity(act, 0); + } + return; + } + else if (animEvent.Event == (int)Animevent.AE_NPC_SET_INTERACTION_CANTDIE) + throw new NotImplementedException(); + else if (animEvent.Event == (int)Animevent.AE_NPC_HURT_INTERACTION_PARTNER) + throw new NotImplementedException(); + } + + if (animEvent.Source != this || ((animEvent.Type & AnimEventType.NewEventSystem) != 0 && (animEvent.Type & AnimEventType.Weapon) != 0) || (animEvent.Event >= EVENT_WEAPON && animEvent.Event <= EVENT_WEAPON_LAST)) + Weapon_HandleAnimEvent(ref animEvent); + else + base.HandleAnimEvent(ref animEvent); + break; + } + } + + public CanPlaySequence_t CanPlaySequence(bool disregardNPCState, ScriptInterrupt interruptLevel) { + CanPlaySequence_t ret = CanPlaySequence_t.CanPlayNow; + + AI_ScriptedSequence? cine = Cine.Get(); + if (cine != null) { + if (!cine.CanEnqueueAfter()) + return CanPlaySequence_t.CannotPlay; + + ret = CanPlaySequence_t.CanPlayEnqueued; + } + + if (!IsAlive()) + return CanPlaySequence_t.CannotPlay; + + if (IsInAVehicle()) + return CanPlaySequence_t.CannotPlay; + + if (disregardNPCState) + return ret; + + if (NPCState == NPCState.None || NPCState == NPCState.Idle || IdealNPCState == NPCState.Idle) + return ret; + + if (NPCState == NPCState.Alert && interruptLevel >= ScriptInterrupt.ByName) + return ret; + + return CanPlaySequence_t.CannotPlay; + } public bool IsInLockedScene() => SceneTime > gpGlobals.CurTime; public void AddSceneLock(TimeUnit_t duration = 0.2) => SceneTime = Math.Max(gpGlobals.CurTime + duration, SceneTime); @@ -4598,6 +4967,123 @@ public virtual void StartTask(in Task_t task) { TaskComplete(); break; + case TASK_SCRIPT_RUN_TO_TARGET: + case TASK_SCRIPT_WALK_TO_TARGET: + case TASK_SCRIPT_CUSTOM_MOVE_TO_TARGET: + StartScriptMoveToTargetTask(task.Task); + break; + + case TASK_WAIT_FOR_SCRIPT: { + if (Cine.Get() == null) { + DevMsg("Scripted sequence destroyed while in use\n"); + TaskFail(AI_TaskFailureCode.ScheduleNotFound); + break; + } + + break; + } + + case TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY: { + AI_ScriptedSequence? cine = Cine.Get(); + if (cine == null) { + DevMsg("Scripted sequence destroyed while in use\n"); + TaskFail(AI_TaskFailureCode.ScheduleNotFound); + break; + } + + string? arrivalText; + + if (!string.IsNullOrEmpty(cine.EntryName)) + arrivalText = cine.EntryName; + else if (!string.IsNullOrEmpty(cine.Play)) + arrivalText = cine.Play; + else if (!string.IsNullOrEmpty(cine.PostIdle)) + arrivalText = cine.PostIdle; + else + arrivalText = null; + + ScriptArrivalActivity = AIN_DEF_ACTIVITY; + ScriptArrivalSequence = null; + + if (arrivalText != null) { + ScriptArrivalActivity = (Activity)GetActivityID(arrivalText); + if (ScriptArrivalActivity == Activity.ACT_INVALID) + ScriptArrivalSequence = arrivalText; + } + + TaskComplete(); + break; + } + + case TASK_PLAY_SCRIPT: { + GetNavigator()!.IgnoreStoppingPath(); + + if (HasMovement(GetSequence()) || Cine.Get()!.IgnoreGravity) { + AddFlag(EntityFlags.Fly); + SetGroundEntity(null); + } + + Cine.Get()?.SynchronizeSequence(this); + + ScriptState = ScriptStateType.Playing; + break; + } + + case TASK_PLAY_SCRIPT_POST_IDLE: + ScriptState = ScriptStateType.PostIdle; + break; + + case TASK_PRE_SCRIPT: { + if (!AI_ScriptedSequence.ai_task_pre_script.GetBool()) + TaskComplete(); + else if (Cine.Get() == null) + TaskComplete(); + else { + Cine.Get()!.DelayStart(true); + TaskComplete(); + } + break; + } + + case TASK_ENABLE_SCRIPT: { + AI_ScriptedSequence cine = Cine.Get()!; + if (!string.IsNullOrEmpty(cine.PreIdle)) { + cine.StartSequence(this, cine.PreIdle, false); + if (cine.PreIdle == cine.Play) + PlaybackRate = 0; + } + else if (ScriptState != ScriptStateType.CustomMoveToMark) { + if (GetActivity() == Activity.ACT_WALK || + GetActivity() == Activity.ACT_RUN || + GetActivity() == Activity.ACT_WALK_AIM || + GetActivity() == Activity.ACT_RUN_AIM) + SetActivity(Activity.ACT_IDLE); + } + break; + } + + case TASK_PLANT_ON_SCRIPT: { + if (TargetEnt.Get() != null) + SetLocalOrigin(TargetEnt.Get()!.GetAbsOrigin()); + + TaskComplete(); + break; + } + + case TASK_FACE_SCRIPT: { + if (TargetEnt.Get() != null) + GetMotor()!.SetIdealYaw(Util.AngleMod(TargetEnt.Get()!.GetLocalAngles().Y)); + + if (ScriptState != ScriptStateType.CustomMoveToMark) { + SetTurnActivity(); + + SetActivity(GetIdealActivity()); + } + + GetNavigator()!.StopMoving(); + break; + } + case TASK_GET_CHASE_PATH_TO_ENEMY: { BaseEntity? enemy = GetEnemy(); if (enemy == null) { @@ -4682,9 +5168,6 @@ public virtual void StartTask(in Task_t task) { case TASK_MOVE_TO_GOAL_RANGE: case TASK_WAIT_UNTIL_NO_DANGER_SOUND: case TASK_TARGET_PLAYER: - case TASK_SCRIPT_RUN_TO_TARGET: - case TASK_SCRIPT_WALK_TO_TARGET: - case TASK_SCRIPT_CUSTOM_MOVE_TO_TARGET: case TASK_CLEAR_MOVE_WAIT: case TASK_MELEE_ATTACK1: case TASK_MELEE_ATTACK2: @@ -4724,14 +5207,6 @@ public virtual void StartTask(in Task_t task) { case TASK_SOUND_PAIN: case TASK_SOUND_ANGRY: case TASK_WAIT_FOR_SPEAK_FINISH: - case TASK_WAIT_FOR_SCRIPT: - case TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY: - case TASK_PLAY_SCRIPT: - case TASK_PLAY_SCRIPT_POST_IDLE: - case TASK_PRE_SCRIPT: - case TASK_ENABLE_SCRIPT: - case TASK_PLANT_ON_SCRIPT: - case TASK_FACE_SCRIPT: case TASK_WEAPON_FIND: case TASK_ITEM_PICKUP: case TASK_WEAPON_PICKUP: @@ -4994,6 +5469,80 @@ public virtual void RunTask(in Task_t task) { break; } + case TASK_SCRIPT_RUN_TO_TARGET: + case TASK_SCRIPT_WALK_TO_TARGET: + case TASK_SCRIPT_CUSTOM_MOVE_TO_TARGET: + StartScriptMoveToTargetTask(task.Task); + break; + + case TASK_WAIT_FOR_SCRIPT: { + AI_ScriptedSequence? cine = Cine.Get(); + if (cine != null && cine.IsTimeToStart()) { + TaskComplete(); + cine.OnBeginSequence(); + + if (!string.IsNullOrEmpty(cine.EntryName)) + cine.StartSequence(this, cine.EntryName, true); + else + cine.StartSequence(this, cine.Play, true); + + if (Cine.Get() == null) + ClearSchedule("Waiting for script, but lost script!"); + + PlaybackRate = 1.0; + } + else if (cine == null) { + DevMsg("Cine died!\n"); + TaskComplete(); + } + else if (IsRunningDynamicInteraction()) + throw new NotImplementedException(); + break; + } + + case TASK_PLAY_SCRIPT: { + AutoMovement(); + + if (IsSequenceFinished()) { + if (Cine.Get()!.FinishedActionSequence(this)) { + Cine.Get()?.SequenceDone(this); + + TaskComplete(); + } + else if (Cine.Get() != null && Cine.Get()!.ForceSynch) + Cine.Get()!.SynchronizeSequence(this); + } + break; + } + + case TASK_PLAY_SCRIPT_POST_IDLE: { + AI_ScriptedSequence? cine = Cine.Get(); + if (cine == null) { + DevMsg("Scripted sequence destroyed while in use\n"); + TaskFail(AI_TaskFailureCode.ScheduleNotFound); + break; + } + + if (IsSequenceFinished() || cine.NextCine.Get() != null) + cine.PostIdleDone(this); + break; + } + + case TASK_ENABLE_SCRIPT: { + AI_ScriptedSequence? cine = Cine.Get(); + if (cine == null) { + DevMsg("Scripted sequence destroyed while in use\n"); + TaskFail(AI_TaskFailureCode.ScheduleNotFound); + break; + } + + if (!cine.IsWaitingForBegin()) { + cine.DelayStart(false); + TaskComplete(); + } + break; + } + case TASK_PLAY_HINT_ACTIVITY: case TASK_ADD_GESTURE_WAIT: case TASK_FIND_COVER_FROM_BEST_SOUND: @@ -5012,9 +5561,6 @@ public virtual void RunTask(in Task_t task) { case TASK_ITEM_RUN_PATH: case TASK_DIE: case TASK_WAIT_FOR_SPEAK_FINISH: - case TASK_SCRIPT_RUN_TO_TARGET: - case TASK_SCRIPT_WALK_TO_TARGET: - case TASK_SCRIPT_CUSTOM_MOVE_TO_TARGET: case TASK_RANGE_ATTACK1: case TASK_RANGE_ATTACK2: case TASK_MELEE_ATTACK1: @@ -5024,10 +5570,6 @@ public virtual void RunTask(in Task_t task) { case TASK_RELOAD: case TASK_SMALL_FLINCH: case TASK_BIG_FLINCH: - case TASK_WAIT_FOR_SCRIPT: - case TASK_PLAY_SCRIPT: - case TASK_PLAY_SCRIPT_POST_IDLE: - case TASK_ENABLE_SCRIPT: case TASK_WEAPON_PICKUP: case TASK_ITEM_PICKUP: throw new NotImplementedException(); @@ -6983,7 +7525,98 @@ public Activity TranslateActivity(Activity idealActivity, out Activity idealWeap return idealActivity; } - public virtual int GetScriptCustomMoveSequence() => throw new NotImplementedException(); + public Activity GetScriptCustomMoveActivity() { + Activity activity = Activity.ACT_WALK; + + AI_ScriptedSequence? cine = Cine.Get(); + if (cine != null && !string.IsNullOrEmpty(cine.CustomMove)) { + activity = LookupActivity(cine.CustomMove); + if (activity == Activity.ACT_INVALID) { + if (LookupSequence(cine.CustomMove) != (int)Activity.ACT_INVALID) + activity = Activity.ACT_SCRIPT_CUSTOM_MOVE; + else + activity = Activity.ACT_WALK; + } + } + else if (!string.IsNullOrEmpty(SceneCustomMoveSeq)) + activity = Activity.ACT_SCRIPT_CUSTOM_MOVE; + + return activity; + } + + public virtual int GetScriptCustomMoveSequence() { + int sequence = StudioHdr.ACTIVITY_NOT_AVAILABLE; + + AI_ScriptedSequence? cine = Cine.Get(); + if (cine != null) { + sequence = LookupSequence(cine.CustomMove); + if (sequence == StudioHdr.ACTIVITY_NOT_AVAILABLE) + DevMsg($"SCRIPT_CUSTOM_MOVE: {GetClassname()} has no sequence:{cine.CustomMove}\n"); + } + else if (!string.IsNullOrEmpty(SceneCustomMoveSeq)) { + sequence = LookupSequence(SceneCustomMoveSeq); + if (sequence == StudioHdr.ACTIVITY_NOT_AVAILABLE) + Warning($"SCRIPT_CUSTOM_MOVE: {GetClassname()} failed scripted custom move. Has no sequence called: {SceneCustomMoveSeq}\n"); + } + + if (sequence == StudioHdr.ACTIVITY_NOT_AVAILABLE) + sequence = SelectWeightedSequence(Activity.ACT_WALK); + + return sequence; + } + + public void StartScriptMoveToTargetTask(int task) { + Activity newActivity; + + if (TargetEnt.Get() == null) + TaskFail(AI_TaskFailureCode.NoTarget); + else if ((TargetEnt.Get()!.GetAbsOrigin() - GetLocalOrigin()).Length() < 1) + TaskComplete(); + else { + if (task == TASK_SCRIPT_WALK_TO_TARGET) + newActivity = Activity.ACT_WALK; + else if (task == TASK_SCRIPT_RUN_TO_TARGET) + newActivity = Activity.ACT_RUN; + else + newActivity = GetScriptCustomMoveActivity(); + + if (newActivity != Activity.ACT_SCRIPT_CUSTOM_MOVE && TranslateActivity(newActivity) == Activity.ACT_INVALID) + Assert(false); + else { + if (TargetEnt.Get() == null) + TaskFail(AI_TaskFailureCode.NoTarget); + else { + AI_NavGoal goal = new(NavGoalType.TargetEnt, newActivity); + + if (GetState() == NPCState.Script && + (ScriptArrivalActivity != AIN_DEF_ACTIVITY || + ScriptArrivalSequence != null)) { + if (ScriptArrivalActivity != AIN_DEF_ACTIVITY) + goal.ArrivalActivity = ScriptArrivalActivity; + else + goal.ArrivalSequence = LookupSequence(ScriptArrivalSequence); + } + + if (!GetNavigator()!.SetGoal(goal, AI_NavSetGoalFlags.DiscardIfFail)) { + if (GetNavigator()!.GetNavFailCounter() == 0) { + DevWarning($"{GetDebugName()} {TaskName(task)} failed Urgent Movement, retrying\n"); + return; + } + + DevWarning($"{GetDebugName()} {TaskName(task)} failed Urgent Movement, abandoning schedule\n"); + TaskFail(AI_TaskFailureCode.NoRoute); + } + else + GetNavigator()!.SetArrivalDirection(TargetEnt.Get()!.GetAbsAngles()); + } + } + } + + ScriptArrivalActivity = AIN_DEF_ACTIVITY; + ScriptArrivalSequence = null; + + TaskComplete(); + } static AI_BaseNPC? ResolveLastWarn; static Activity ResolveLastWarnActivity; @@ -7608,7 +8241,26 @@ public void CheckPhysicsContacts() { } } - public void Wake(bool fireOutput = true) => throw new NotImplementedException(); + public bool WokeThisTick() => WakeTick == gpGlobals.TickCount; + + public void Wake(bool fireOutput = true) { + if (GetSleepState() != AI_SleepState.Awake) { + WakeTick = gpGlobals.TickCount; + SetSleepState(AI_SleepState.Awake); + RemoveEffects(EntityEffects.NoDraw); + if (fireOutput) + OnWake.FireOutput(this, this); + + if (WakeSquad && GetSquad() != null) { + for (AI_BaseNPC? squadMember = GetSquad()!.GetFirstMember(out int iter); squadMember != null; squadMember = GetSquad()!.GetNextMember(ref iter)) { + if (squadMember.IsAlive() && squadMember != this) { + squadMember.WakeSquad = false; + squadMember.Wake(); + } + } + } + } + } public void UpdateSleepState(bool inPVS) { if (GetSleepState() > AI_SleepState.Awake) { @@ -7969,6 +8621,8 @@ public virtual bool AutoMovement(TimeUnit_t interval, BaseEntity? target, out AI ScheduleState.TaskRanAutomovement = true; if (GetIntervalMovement(interval, out _, out Vector3 newPos, out QAngle newAngles)) { + Cine.Get()?.ModifyScriptedAutoMovement(ref newPos); + if (GetMoveType() == Source.MoveType.Step) { if ((GetFlags() & EntityFlags.Fly) == 0) { target ??= GetNavTargetEntity(); diff --git a/Game.Server/BaseAnimating.cs b/Game.Server/BaseAnimating.cs index ee2346693..d841f4aa0 100644 --- a/Game.Server/BaseAnimating.cs +++ b/Game.Server/BaseAnimating.cs @@ -438,6 +438,27 @@ public bool GetPoseParameterRange(int parameter, out float minValue, out float m return false; } + public void GetBonePosition(int bone, out Vector3 origin, out QAngle angles) { + StudioHdr? studioHdr = GetModelPtr(); + if (studioHdr == null) { + AssertMsg(false, "BaseAnimating.GetBonePosition: model missing"); + origin = default; + angles = default; + return; + } + + if (bone < 0 || bone >= studioHdr.NumBones()) { + AssertMsg(false, "BaseAnimating.GetBonePosition: invalid bone index"); + origin = default; + angles = default; + return; + } + + GetBoneTransform(bone, out Matrix3x4 boneToWorld); + + MathLib.MatrixAngles(boneToWorld, out angles, out origin); + } + public void GetBoneTransform(int bone, out Matrix3x4 boneToWorld) { StudioHdr? studioHdr = GetModelPtr(); @@ -742,6 +763,17 @@ public TimeUnit_t GetAnimTimeInterval() { return interval; } + public bool HasMovement(int sequence) { + StudioHdr? studioHdr = GetModelPtr(); + if (studioHdr == null) + return false; + + if (BoneSetup.Studio_SeqMovement(studioHdr, sequence, 0.0f, 1.0f, GetPoseParameterArray(), out _, out _)) + return true; + + return false; + } + public bool GetIntervalMovement(TimeUnit_t intervalUsed, out bool moveSeqFinished, out Vector3 newPosition, out QAngle newAngles) { StudioHdr? studioHdr = GetModelPtr(); if (studioHdr == null || !studioHdr.SequencesAvailable()) { diff --git a/Game.Server/EntityList.cs b/Game.Server/EntityList.cs index 043bd7432..0b471fd3f 100644 --- a/Game.Server/EntityList.cs +++ b/Game.Server/EntityList.cs @@ -414,6 +414,44 @@ public int ResetDeleteList() { return null; } + public BaseEntity? FindEntityByNameWithin(BaseEntity? startEntity, ReadOnlySpan name, in Vector3 src, float radius, BaseEntity? searchingEntity = null, BaseEntity? activator = null, BaseEntity? caller = null) { + BaseEntity? entity = startEntity; + float maxDist2 = radius * radius; + if (maxDist2 == 0) + return gEntList.FindEntityByName(entity, name, searchingEntity, activator, caller); + + while ((entity = gEntList.FindEntityByName(entity, name, searchingEntity, activator, caller)) != null) { + if (entity.Edict() == null) + continue; + + float dist2 = (entity.GetAbsOrigin() - src).LengthSquared(); + + if (maxDist2 > dist2) + return entity; + } + + return null; + } + + public BaseEntity? FindEntityByClassnameWithin(BaseEntity? startEntity, ReadOnlySpan name, in Vector3 src, float radius) { + BaseEntity? entity = startEntity; + float maxDist2 = radius * radius; + if (maxDist2 == 0) + return gEntList.FindEntityByClassname(entity, name); + + while ((entity = gEntList.FindEntityByClassname(entity, name)) != null) { + if (entity.Edict() == null) + continue; + + float dist2 = (entity.GetAbsOrigin() - src).LengthSquared(); + + if (maxDist2 > dist2) + return entity; + } + + return null; + } + public BaseEntity? FindEntityGeneric(BaseEntity? startEntity, ReadOnlySpan name, BaseEntity? searchingEntity = null, BaseEntity? activator = null, BaseEntity? caller = null) { BaseEntity? entity = FindEntityByName(startEntity, name, searchingEntity, activator, caller); entity ??= FindEntityByClassname(startEntity, name); diff --git a/Game.Server/Scripted.cs b/Game.Server/Scripted.cs index 13e19135c..53d50648c 100644 --- a/Game.Server/Scripted.cs +++ b/Game.Server/Scripted.cs @@ -1,6 +1,13 @@ using Game.Shared; using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Mathematics; + +using System.Numerics; + +using DEFINE = Source.DEFINE; namespace Game.Server; @@ -20,21 +27,858 @@ public enum ScriptPlayerDeath Cancel = 1, } +public enum ScriptInterrupt +{ + ByClass = 0, + ByName, +} + [LinkEntityToClass("scripted_sequence")] public class AI_ScriptedSequence : BaseEntity { + public const int MAX_SCRIPT_EVENTS = 8; + + public const int SF_SCRIPT_WAITTILLSEEN = 1; + public const int SF_SCRIPT_EXITAGITATED = 2; + public const int SF_SCRIPT_REPEATABLE = 4; + public const int SF_SCRIPT_LEAVECORPSE = 8; public const int SF_SCRIPT_START_ON_SPAWN = 16; + public const int SF_SCRIPT_NOINTERRUPT = 32; + public const int SF_SCRIPT_OVERRIDESTATE = 64; + public const int SF_SCRIPT_DONT_TELEPORT_AT_END = 128; + public const int SF_SCRIPT_LOOP_IN_POST_IDLE = 256; + public const int SF_SCRIPT_HIGH_PRIORITY = 512; + public const int SF_SCRIPT_SEARCH_CYCLICALLY = 1024; + public const int SF_SCRIPT_NO_COMPLAINTS = 2048; + public const int SF_SCRIPT_ALLOW_DEATH = 4096; - public ScriptMoveTo MoveTo; + public static readonly ConVar ai_task_pre_script = new("ai_task_pre_script", "0", FCvar.None); + + public static readonly new DataMap DataDesc = new(typeof(AI_ScriptedSequence), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(EntryName), FieldType.String, "m_iszEntry"), + DEFINE.KEYFIELD(nameof(PreIdle), FieldType.String, "m_iszIdle"), + DEFINE.KEYFIELD(nameof(Play), FieldType.String, "m_iszPlay"), + DEFINE.KEYFIELD(nameof(PostIdle), FieldType.String, "m_iszPostIdle"), + DEFINE.KEYFIELD(nameof(CustomMove), FieldType.String, "m_iszCustomMove"), + DEFINE.KEYFIELD(nameof(NextScript), FieldType.String, "m_iszNextScript"), + DEFINE.KEYFIELD(nameof(Entity), FieldType.String, "m_iszEntity"), + DEFINE.KEYFIELD(nameof(MoveTo), FieldType.Integer, "m_fMoveTo"), + DEFINE.KEYFIELD(nameof(Radius), FieldType.Float, "m_flRadius"), + DEFINE.KEYFIELD(nameof(Repeat), FieldType.Float, "m_flRepeat"), + + DEFINE.FIELD(nameof(IsPlayingEntryValue), FieldType.Boolean), + DEFINE.KEYFIELD(nameof(LoopActionSequence), FieldType.Boolean, "m_bLoopActionSequence"), + DEFINE.KEYFIELD(nameof(SynchPostIdles), FieldType.Boolean, "m_bSynchPostIdles"), + DEFINE.KEYFIELD(nameof(IgnoreGravity), FieldType.Boolean, "m_bIgnoreGravity"), + DEFINE.KEYFIELD(nameof(DisableNPCCollisions), FieldType.Boolean, "m_bDisableNPCCollisions"), + + DEFINE.FIELD(nameof(Delay), FieldType.Integer), + DEFINE.FIELD(nameof(Delayed), FieldType.Boolean), + DEFINE.FIELD(nameof(StartTime), FieldType.Time), + DEFINE.FIELD(nameof(WaitForBeginSequence), FieldType.Boolean), + + DEFINE.FIELD(nameof(SavedEffects), FieldType.Integer), + DEFINE.FIELD(nameof(SavedFlags), FieldType.Integer), + DEFINE.FIELD(nameof(SavedCollisionGroup), FieldType.Integer), + + DEFINE.FIELD(nameof(Interruptable), FieldType.Boolean), + DEFINE.FIELD(nameof(SequenceStarted), FieldType.Boolean), + DEFINE.FIELD(nameof(TargetEnt), FieldType.EHandle), + DEFINE.FIELD(nameof(NextCine), FieldType.EHandle), + DEFINE.FIELD(nameof(LastFoundEntity), FieldType.EHandle), + DEFINE.FIELD(nameof(ForcedTarget), FieldType.EHandle), + DEFINE.FIELD(nameof(DontCancelOtherSequences), FieldType.Boolean), + DEFINE.FIELD(nameof(ForceSynch), FieldType.Boolean), + + DEFINE.FIELD(nameof(Thinking), FieldType.Boolean), + DEFINE.FIELD(nameof(InitiatedSelfDelete), FieldType.Boolean), + + DEFINE.FIELD(nameof(IsTeleportingDueToMoveToValue), FieldType.Boolean), + + DEFINE.FIELD(nameof(InteractionRelativeEntity), FieldType.EHandle), + + DEFINE.FIELD(nameof(TargetWasAsleep), FieldType.Boolean), + + DEFINE.INPUTFUNC(FieldType.Void, "MoveToPosition", nameof(InputMoveToPosition), (INPUTFUNCPTR)((self, data) => ((AI_ScriptedSequence)self).InputMoveToPosition(data))), + DEFINE.INPUTFUNC(FieldType.Void, "BeginSequence", nameof(InputBeginSequence), (INPUTFUNCPTR)((self, data) => ((AI_ScriptedSequence)self).InputBeginSequence(data))), + DEFINE.INPUTFUNC(FieldType.Void, "CancelSequence", nameof(InputCancelSequence), (INPUTFUNCPTR)((self, data) => ((AI_ScriptedSequence)self).InputCancelSequence(data))), + + DEFINE.KEYFIELD(nameof(PlayerDeathBehavior), FieldType.Integer, "onplayerdeath"), + DEFINE.INPUTFUNC(FieldType.Void, "ScriptPlayerDeath", nameof(InputScriptPlayerDeath), (INPUTFUNCPTR)((self, data) => ((AI_ScriptedSequence)self).InputScriptPlayerDeath(data))), + + DEFINE.OUTPUT(nameof(OnBeginSequenceOutput), "OnBeginSequence", eventFuncs), + DEFINE.OUTPUT(nameof(OnEndSequence), "OnEndSequence", eventFuncs), + DEFINE.OUTPUT(nameof(OnPostIdleEndSequence), "OnPostIdleEndSequence", eventFuncs), + DEFINE.OUTPUT(nameof(OnCancelSequence), "OnCancelSequence", eventFuncs), + DEFINE.OUTPUT(nameof(OnCancelFailedSequence), "OnCancelFailedSequence", eventFuncs), + DEFINE.OUTPUT(nameof(OnScriptEvent01), "OnScriptEvent01", eventFuncs), + DEFINE.OUTPUT(nameof(OnScriptEvent02), "OnScriptEvent02", eventFuncs), + DEFINE.OUTPUT(nameof(OnScriptEvent03), "OnScriptEvent03", eventFuncs), + DEFINE.OUTPUT(nameof(OnScriptEvent04), "OnScriptEvent04", eventFuncs), + DEFINE.OUTPUT(nameof(OnScriptEvent05), "OnScriptEvent05", eventFuncs), + DEFINE.OUTPUT(nameof(OnScriptEvent06), "OnScriptEvent06", eventFuncs), + DEFINE.OUTPUT(nameof(OnScriptEvent07), "OnScriptEvent07", eventFuncs), + DEFINE.OUTPUT(nameof(OnScriptEvent08), "OnScriptEvent08", eventFuncs), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public string? EntryName; public string? PreIdle; + public string? Play; + public string? PostIdle; + public string? CustomMove; + public string? NextScript; public string? Entity; + + public ScriptMoveTo MoveTo; + bool IsPlayingEntryValue; + bool LoopActionSequence; + bool SynchPostIdles; + public bool IgnoreGravity; + bool DisableNPCCollisions; + + float Radius; + float Repeat; + + int Delay; + + bool Delayed; + + TimeUnit_t StartTime; + bool WaitForBeginSequence; + + public EntityEffects SavedEffects; public EntityFlags SavedFlags; + public Source.CollisionGroup SavedCollisionGroup; + + bool Interruptable; + bool SequenceStarted; + + EHANDLE TargetEnt = new(); + + public EHANDLE NextCine = new(); + + bool Thinking; + bool InitiatedSelfDelete; + + bool IsTeleportingDueToMoveToValue; + + EHANDLE LastFoundEntity = new(); + + EHANDLE ForcedTarget = new(); + bool DontCancelOtherSequences; + public bool ForceSynch; + + bool TargetWasAsleep; + + readonly OutputEvent OnBeginSequenceOutput = new(); + readonly OutputEvent OnEndSequence = new(); + readonly OutputEvent OnPostIdleEndSequence = new(); + readonly OutputEvent OnCancelSequence = new(); + readonly OutputEvent OnCancelFailedSequence = new(); + readonly OutputEvent OnScriptEvent01 = new(); + readonly OutputEvent OnScriptEvent02 = new(); + readonly OutputEvent OnScriptEvent03 = new(); + readonly OutputEvent OnScriptEvent04 = new(); + readonly OutputEvent OnScriptEvent05 = new(); + readonly OutputEvent OnScriptEvent06 = new(); + readonly OutputEvent OnScriptEvent07 = new(); + readonly OutputEvent OnScriptEvent08 = new(); + + EHANDLE InteractionRelativeEntity = new(); + + ScriptPlayerDeath PlayerDeathBehavior; + + public override EntityCapabilities ObjectCaps() => base.ObjectCaps() & ~EntityCapabilities.AcrossTransition; + + public void SetTarget(BaseEntity? target) => TargetEnt.Set(target); + public BaseEntity? GetTarget() => TargetEnt.Get(); + + public bool PlayedSequence() => SequenceStarted; + + public bool IsPlayingEntry() => IsPlayingEntryValue; + public bool IsPlayingAction() => SequenceStarted && !IsPlayingEntryValue; + public void SetLoopActionSequence(bool loop) => LoopActionSequence = loop; + public bool ShouldLoopActionSequence() => LoopActionSequence; + public void SetSynchPostIdles(bool synch) => SynchPostIdles = synch; + + public bool IsTeleportingDueToMoveTo() => IsTeleportingDueToMoveToValue; + + static void ScriptEntityCancel(BaseEntity cine, bool pretendSuccess = false) { + if (FClassnameIs(cine, "scripted_sequence")) { + AI_ScriptedSequence cineTarget = (AI_ScriptedSequence)cine; + + BaseEntity? entity = cineTarget.GetTarget(); + AI_BaseNPC? target = null; + if (entity != null) + target = entity.MyNPCPointer(); + + if (target != null) { + if (target.NPCState == NPCState.Script) { + target.ScriptState = ScriptStateType.Cleanup; + + EntityFlags savedFlags = target.Cine.Get() != null ? target.Cine.Get()!.SavedFlags : 0; + + target.CineCleanup(); + cineTarget.FixScriptNPCSchedule(target, savedFlags); + } + else { + cineTarget.SetTarget(null); + target.SetEffects(cineTarget.SavedEffects); + target.Cine.Set(null); + target.SetTarget(null); + target.SetGoalEnt(null); + target.SetIdealState(NPCState.Idle); + } + } + + cineTarget.Delay = 0; + + if (pretendSuccess) { + cineTarget.OnEndSequence.FireOutput(null, cineTarget); + cineTarget.OnPostIdleEndSequence.FireOutput(null, cineTarget); + } + else { + cineTarget.OnCancelSequence.FireOutput(null, cineTarget); + + if (cineTarget.StartTime == 0) + cineTarget.OnCancelFailedSequence.FireOutput(null, cineTarget); + } + } + } + + public override void Spawn() { + SetSolid(SolidType.None); + + if (string.IsNullOrEmpty(GetEntityName()) || HasSpawnFlags(SF_SCRIPT_START_ON_SPAWN)) { + StartThink(); + SetNextThink(gpGlobals.CurTime + 1.0f); + + if (!string.IsNullOrEmpty(GetEntityName())) + WaitForBeginSequence = true; + } + + if (HasSpawnFlags(SF_SCRIPT_NOINTERRUPT)) + Interruptable = false; + else + Interruptable = true; + + SequenceStarted = false; + StartTime = 0; + NextCine.Set(null); + + LastFoundEntity.Set(null); + } + + public override void UpdateOnRemove() { + ScriptEntityCancel(this); + base.UpdateOnRemove(); + } + + void StartThink() { + SequenceStarted = false; + Thinking = true; + SetThink(ScriptThink); + } + + void StopThink() { + if (Thinking) { + Assert(!InitiatedSelfDelete); + SetThink(null); + Thinking = false; + } + } + + public bool FCanOverrideState() { + if (HasSpawnFlags(SF_SCRIPT_OVERRIDESTATE)) + return true; + return false; + } + + public void FireScriptEvent(int nEvent) { + switch (nEvent) { + case 1: OnScriptEvent01.FireOutput(this, this); break; + case 2: OnScriptEvent02.FireOutput(this, this); break; + case 3: OnScriptEvent03.FireOutput(this, this); break; + case 4: OnScriptEvent04.FireOutput(this, this); break; + case 5: OnScriptEvent05.FireOutput(this, this); break; + case 6: OnScriptEvent06.FireOutput(this, this); break; + case 7: OnScriptEvent07.FireOutput(this, this); break; + case 8: OnScriptEvent08.FireOutput(this, this); break; + } + } + + void InputMoveToPosition(InputData inputdata) { + if (InitiatedSelfDelete) + return; + + BaseEntity? entity = GetTarget(); + AI_BaseNPC? target = null; + + if (entity != null) + target = entity.MyNPCPointer(); + + if (target != null) { + if (target.ScriptState == ScriptStateType.Playing || target.ScriptState == ScriptStateType.PostIdle) { + if (target.CanPlaySequence(FCanOverrideState(), ScriptInterrupt.ByName) != CanPlaySequence_t.CannotPlay) { + StartScript(); + WaitForBeginSequence = true; + } + } + } + else { + StartThink(); + SetNextThink(gpGlobals.CurTime); + WaitForBeginSequence = true; + } + } + + void InputBeginSequence(InputData inputdata) { + if (InitiatedSelfDelete) + return; + + WaitForBeginSequence = false; + + BaseEntity? entity = GetTarget(); + AI_BaseNPC? target = null; + + if (entity == null && ForcedTarget.Get() != null) { + if (FindEntity()) + entity = GetTarget(); + } + + if (entity != null) + target = entity.MyNPCPointer(); + + if (target != null) { + if (target.ScriptState == ScriptStateType.Playing || target.ScriptState == ScriptStateType.PostIdle) { + if (target.CanPlaySequence(FCanOverrideState(), ScriptInterrupt.ByName) != CanPlaySequence_t.CannotPlay) + StartScript(); + } + } + else { + StartThink(); + + SetNextThink(TICK_NEVER_THINK); + ScriptThink(); + } + } + + void InputCancelSequence(InputData inputdata) { + if (InitiatedSelfDelete) + return; + + DevMsg(2, $"InputCancelScript: Cancelling script '{Play}'\n"); + StopThink(); + ScriptEntityCancel(this); + } + + void InputScriptPlayerDeath(InputData inputdata) { + if (PlayerDeathBehavior == ScriptPlayerDeath.Cancel) { + if (InitiatedSelfDelete) + return; + + DevMsg(2, $"InputCancelScript: Cancelling script '{Play}'\n"); + StopThink(); + ScriptEntityCancel(this); + } + } + + public bool IsTimeToStart() { + Assert(!WaitForBeginSequence); + + return Delay == 0; + } + + public bool IsWaitingForBegin() => WaitForBeginSequence; + + AI_BaseNPC? FindScriptEntity() { + AI_BaseNPC? enqueueNPC = null; + + BaseEntity? entity; + ScriptInterrupt interrupt; + if (ForcedTarget.Get() != null) { + interrupt = ScriptInterrupt.ByName; + entity = ForcedTarget.Get(); + } + else { + interrupt = ScriptInterrupt.ByName; + + entity = gEntList.FindEntityByNameWithin(LastFoundEntity.Get(), Entity, GetAbsOrigin(), Radius); + if (entity == null) { + entity = gEntList.FindEntityByClassnameWithin(LastFoundEntity.Get(), Entity, GetAbsOrigin(), Radius); + interrupt = ScriptInterrupt.ByClass; + } + } + + while (entity != null) { + AI_BaseNPC? npc = entity.MyNPCPointer(); + if (npc != null) { + CanPlaySequence_t canPlay = npc.CanPlaySequence(FCanOverrideState(), interrupt); + if (canPlay == CanPlaySequence_t.CanPlayNow) + return npc; + else if (canPlay == CanPlaySequence_t.CanPlayEnqueued) + enqueueNPC = npc; + else if (!HasSpawnFlags(SF_SCRIPT_NO_COMPLAINTS)) + DevMsg($"Found {Entity}, but can't play!\n"); + } + + if (ForcedTarget.Get() != null) { + Warning($"Code forced {entity.GetClassname()}({entity.GetDebugName()}), to be the target of scripted sequence {GetDebugName()}, but it can't play it.\n"); + entity = null; + Util.Remove(this); + return null; + } + else { + if (interrupt == ScriptInterrupt.ByName) + entity = gEntList.FindEntityByNameWithin(entity, Entity, GetAbsOrigin(), Radius); + else + entity = gEntList.FindEntityByClassnameWithin(entity, Entity, GetAbsOrigin(), Radius); + } + } + + if (enqueueNPC != null) + return enqueueNPC; + + return null; + } + + bool FindEntity() { + AI_BaseNPC? target = FindScriptEntity(); + + if (HasSpawnFlags(SF_SCRIPT_SEARCH_CYCLICALLY)) + LastFoundEntity.Set(target); + + SetTarget(target); + + return target != null; + } + + public void StartScript() { + BaseEntity? entity = GetTarget(); + AI_BaseNPC? target = null; + if (entity != null) + target = entity.MyNPCPointer(); + + if (target != null) { + target.RemoveSpawnFlags(SF_NPC_WAIT_FOR_SCRIPT); + + AI_ScriptedSequence? targetCine = target.Cine.Get(); + if (targetCine != null) { + if (targetCine.NextCine.Get() != null) { + AI_ScriptedSequence cine = (AI_ScriptedSequence)targetCine.NextCine.Get()!; + + if (targetCine.NextCine.Get() != targetCine) + cine.SetTarget(null); + DevMsg(2, $"script \"{GetDebugName()}\" kicking script \"{cine.GetDebugName()}\" out of the queue\n"); + } + + targetCine.NextCine.Set(this); + return; + } + + if (string.IsNullOrEmpty(NextScript)) + NextCine.Set(null); - public bool CanInterrupt() => throw new NotImplementedException(); + target.SetGoalEnt(this); + target.ForceDecisionThink(); + target.Cine.Set(this); + target.SetTarget(this); - public void CancelScript() => throw new NotImplementedException(); + target.OnStartScene(); - public void RemoveIgnoredConditions() => throw new NotImplementedException(); + { + TargetWasAsleep = target.GetSleepState() != AI_SleepState.Awake; + bool justAwoke = target.WokeThisTick(); + if (TargetWasAsleep || justAwoke) { + if (TargetWasAsleep) + target.Wake(); + TargetWasAsleep = true; + + target.AddEffects(EntityEffects.NoDraw); + } + } + + SavedEffects = (EntityEffects)target.Effects & ~EntityEffects.NoDraw; + target.AddEffects((EntityEffects)Effects); + SavedFlags = target.GetFlags(); + SavedCollisionGroup = target.GetCollisionGroup(); + + if (DisableNPCCollisions) + target.SetCollisionGroup(Source.CollisionGroup.NPCScripted); + + switch (MoveTo) { + case ScriptMoveTo.Wait: + case ScriptMoveTo.WaitFacing: + target.ScriptState = ScriptStateType.Wait; + + if (IgnoreGravity) { + target.AddFlag(EntityFlags.Fly); + target.SetGroundEntity(null); + } + + break; + + case ScriptMoveTo.Walk: + target.ScriptState = ScriptStateType.WalkToMark; + break; + + case ScriptMoveTo.Run: + target.ScriptState = ScriptStateType.RunToMark; + break; + + case ScriptMoveTo.Custom: + target.ScriptState = ScriptStateType.CustomMoveToMark; + break; + + case ScriptMoveTo.Teleport: + IsTeleportingDueToMoveToValue = true; + target.Teleport(GetAbsOrigin(), null, vec3_origin); + IsTeleportingDueToMoveToValue = false; + target.GetMotor()!.SetIdealYaw(GetLocalAngles().Y); + target.SetLocalAngularVelocity(vec3_angle); + target.IncrementInterpolationFrame(); + QAngle angles = target.GetLocalAngles(); + angles.Y = GetLocalAngles().Y; + target.SetLocalAngles(angles); + target.ScriptState = ScriptStateType.Wait; + + if (IgnoreGravity) { + target.AddFlag(EntityFlags.Fly); + target.SetGroundEntity(null); + } + + break; + } + + Delayed = false; + DelayStart(true); + + target.SetIdealState(NPCState.Script); + + if (target.IsEFlagSet(EFL.NoThinkFunction) && target.GetNextThink() != TICK_NEVER_THINK) { + DevWarning($"scripted_sequence {EntIndex()}:{GetDebugName()} - restarting dormant entity {target.EntIndex()}:{target.GetDebugName()} : {gpGlobals.CurTime:0.0}:{target.GetNextThink():0.0}\n"); + target.SetNextThink(gpGlobals.CurTime); + } + } + } + + void ScriptThink() { + if (g_pAINetworkManager != null && !g_pAINetworkManager.IsInitialized()) + SetNextThink(gpGlobals.CurTime + 0.1f); + else if (FindEntity()) { + StartScript(); + DevMsg(2, $"scripted_sequence {EntIndex()}:\"{GetDebugName()}\" using NPC {GetTarget()!.EntIndex()}:\"{GetTarget()!.GetEntityName()}\"({Entity})\n"); + } + else { + CancelScript(); + DevMsg(2, $"scripted_sequence {EntIndex()}:\"{GetDebugName()}\" can't find NPC \"{Entity}\"\n"); + SetNextThink(gpGlobals.CurTime + 1.0f); + } + } + + public void OnBeginSequence() => OnBeginSequenceOutput.FireOutput(this, this); + + public bool StartSequence(AI_BaseNPC target, string? seq, bool completeOnEmpty) { + Assert(target != null); + SequenceStarted = true; + IsPlayingEntryValue = seq == EntryName; + + if (string.IsNullOrEmpty(seq) && completeOnEmpty) { + SequenceDone(target!); + return false; + } + + int sequence = target!.LookupSequence(seq); + if (sequence == -1) { + Warning($"{target.GetDebugName()}: unknown scripted sequence \"{seq}\"\n"); + sequence = 0; + } + + Activity act = target.GetSequenceActivity(sequence); + if (act == Activity.ACT_INVALID) + act = Activity.ACT_IDLE; + + target.SetActivityAndSequence(act, sequence, act, act); + + if (TargetWasAsleep && seq != PreIdle) { + TargetWasAsleep = false; + target.RemoveEffects(EntityEffects.NoDraw); + target.IncrementInterpolationFrame(); + } + + return true; + } + + public void SynchronizeSequence(AI_BaseNPC npc) { + Assert(Delay == 0); + Assert(WaitForBeginSequence == false); + ForceSynch = false; + + float cycleRate = npc.GetSequenceCycleRate(npc.GetSequence()); + TimeUnit_t interval = gpGlobals.CurTime - StartTime; + + interval = Math.Clamp(interval, 0.0, 0.15); + + if (interval == 0) + return; + + npc.SetCycle(0.0f); + npc.AutoMovement(interval, null, out _); + + npc.SetCycle(interval * cycleRate); + } + + public bool FinishedActionSequence(AI_BaseNPC npc) { + if (IsPlayingEntry()) { + if (!string.IsNullOrEmpty(GetEntityName())) + SynchNewSequence(ScriptStateType.Playing, Play, true); + else + StartSequence(npc, Play, true); + return false; + } + + if (ShouldLoopActionSequence()) { + if (npc.ScriptState == ScriptStateType.PostIdle) + return true; + + return false; + } + + return true; + } + + public void SequenceDone(AI_BaseNPC npc) { + if (SynchPostIdles && !string.IsNullOrEmpty(GetEntityName())) { + if (npc.ScriptState != ScriptStateType.PostIdle) { + if (!string.IsNullOrEmpty(PostIdle) && NextCine.Get() == null) + SynchNewSequence(ScriptStateType.PostIdle, PostIdle, true); + else + PostIdleDone(npc); + } + } + else { + if (!string.IsNullOrEmpty(PostIdle) && NextCine.Get() == null) { + npc.ScriptState = ScriptStateType.PostIdle; + StartSequence(npc, PostIdle, false); + } + else + PostIdleDone(npc); + } + + OnEndSequence.FireOutput(null, this); + } + + public void SynchNewSequence(ScriptStateType newState, string? sequence, bool synchOtherScenes) { + if (synchOtherScenes) { + BaseEntity? entCine = gEntList.FindEntityByName(null, GetEntityName(), null); + while (entCine != null) { + if (entCine is AI_ScriptedSequence scene && scene != this) + scene.SynchNewSequence(newState, sequence, false); + entCine = gEntList.FindEntityByName(entCine, GetEntityName(), null); + } + } + + if (GetTarget() == null) + return; + AI_BaseNPC? npc = GetTarget()!.MyNPCPointer(); + if (npc == null) + return; + + StartTime = gpGlobals.CurTime; + npc.ScriptState = newState; + StartSequence(npc, sequence, false); + + ForceSynch = true; + } + + public void PostIdleDone(AI_BaseNPC npc) { + if (!string.IsNullOrEmpty(PostIdle) && HasSpawnFlags(SF_SCRIPT_LOOP_IN_POST_IDLE) && NextCine.Get() == null) { + npc.ScriptState = ScriptStateType.PostIdle; + StartSequence(npc, PostIdle, false); + } + else { + if (!HasSpawnFlags(SF_SCRIPT_REPEATABLE)) { + SetThink(SUB_Remove); + SetNextThink(gpGlobals.CurTime + 0.1f); + Thinking = false; + InitiatedSelfDelete = true; + } + + npc.CineCleanup(); + + FixScriptNPCSchedule(npc, SavedFlags); + + if (NextCine.Get() != null) { + AI_ScriptedSequence nextCine = (AI_ScriptedSequence)NextCine.Get()!; + + if (nextCine != this || HasSpawnFlags(SF_SCRIPT_REPEATABLE)) { + nextCine.SetTarget(npc); + nextCine.StartScript(); + } + } + } + + OnPostIdleEndSequence.FireOutput(null, this); + } + + public void FixScriptNPCSchedule(AI_BaseNPC npc, EntityFlags savedCineFlags) { + if (npc.GetIdealState() != NPCState.Dead) + npc.SetIdealState(NPCState.Idle); + + if (npc == null) + return; + + FixFlyFlag(npc, savedCineFlags); + + npc.ClearSchedule("Finished scripted sequence"); + } + + public void FixFlyFlag(AI_BaseNPC npc, EntityFlags savedCineFlags) { + Task_t? task = npc.GetTask(); + if (task != null && (task.Value.Task == TASK_PLAY_SCRIPT || task.Value.Task == TASK_PLAY_SCRIPT_POST_IDLE)) { + if ((savedCineFlags & EntityFlags.Fly) == 0) { + if ((npc.GetFlags() & EntityFlags.Fly) != 0) + npc.RemoveFlag(EntityFlags.Fly); + } + } + } + + public void AllowInterrupt(bool allow) { + if (HasSpawnFlags(SF_SCRIPT_NOINTERRUPT)) + return; + Interruptable = allow; + } + + public bool CanInterrupt() { + if (!Interruptable) + return false; + + BaseEntity? target = GetTarget(); + + if (target != null && target.IsAlive()) + return true; + + return false; + } + + public void RemoveIgnoredConditions() { + if (CanInterrupt()) + return; + + BaseEntity? entity = GetTarget(); + if (entity == null) + return; + + AI_BaseNPC? target = entity.MyNPCPointer(); + if (target == null) + return; + + if (target != null) { + target.ClearCondition((int)SCOND_t.COND_LIGHT_DAMAGE); + target.ClearCondition((int)SCOND_t.COND_HEAVY_DAMAGE); + } + } + + public bool CanEnqueueAfter() { + if (NextCine.Get() == null) + return true; + + if (!string.IsNullOrEmpty(NextScript)) { + DevMsg(2, $"{NextCine.Get()!.GetDebugName()} is specified as the 'Next Script' and cannot be kicked out of the queue\n"); + return false; + } + + if (!NextCine.Get()!.HasSpawnFlags(SF_SCRIPT_HIGH_PRIORITY)) + return true; + + DevMsg(2, $"{NextCine.Get()!.GetDebugName()} is a priority script and cannot be kicked out of the queue\n"); + + return false; + } + + public void StopActionLoop(bool stopSynchronizedScenes) { + LoopActionSequence = false; + + if (!stopSynchronizedScenes || string.IsNullOrEmpty(GetEntityName())) + return; + + BaseEntity? entCine = gEntList.FindEntityByName(null, GetEntityName(), null); + while (entCine != null) { + if (entCine is AI_ScriptedSequence scene && scene != this) + scene.StopActionLoop(false); + + entCine = gEntList.FindEntityByName(entCine, GetEntityName(), null); + } + } + + public void ForceSetTargetEntity(AI_BaseNPC target, bool dontCancelOtherSequences) { + ForcedTarget.Set(target); + Entity = ForcedTarget.Get()!.GetEntityName(); + DontCancelOtherSequences = dontCancelOtherSequences; + } + + public void ModifyScriptedAutoMovement(ref Vector3 newPos) { + if (InteractionRelativeEntity.Get() != null) + throw new NotImplementedException(); + } + + public void CancelScript() { + DevMsg(2, $"Cancelling script: {Play}\n"); + + bool dontCancelOther = (DontCancelOtherSequences || HasSpawnFlags(SF_SCRIPT_ALLOW_DEATH)) && StartTime != 0; + if (dontCancelOther || string.IsNullOrEmpty(GetEntityName())) { + ScriptEntityCancel(this); + return; + } + + BaseEntity? entCineTarget = gEntList.FindEntityByName(null, GetEntityName()); + + while (entCineTarget != null) { + ScriptEntityCancel(entCineTarget); + entCineTarget = gEntList.FindEntityByName(entCineTarget, GetEntityName()); + } + } + + public void DelayStart(bool delay) { + if (ai_task_pre_script.GetBool()) { + if (delay == Delayed) + return; + + Delayed = delay; + } + + if (string.IsNullOrEmpty(GetEntityName())) { + Delay = delay ? 1 : 0; + StartTime = gpGlobals.CurTime; + return; + } + + BaseEntity? entCine = gEntList.FindEntityByName(null, GetEntityName()); + + while (entCine != null) { + if (FClassnameIs(entCine, "scripted_sequence")) { + AI_ScriptedSequence target = (AI_ScriptedSequence)entCine; + if (delay) + Delay++; + else { + target.Delay--; + + if (target.Delay == 0) + target.StartTime = gpGlobals.CurTime; + } + } + entCine = gEntList.FindEntityByName(entCine, GetEntityName()); + } + } + + public override void Activate() { + base.Activate(); + + NextCine.Set(gEntList.FindEntityByName(null, NextScript)); + if (NextCine.Get() == null) + NextScript = null; + } public static string? GetSpawnPreIdleSequenceForScript(BaseEntity entity) { AI_ScriptedSequence? script = gEntList.NextEntByClass(null); diff --git a/Game.Server/Util.cs b/Game.Server/Util.cs index 189f498a1..327ba9f7c 100644 --- a/Game.Server/Util.cs +++ b/Game.Server/Util.cs @@ -256,10 +256,12 @@ public static void PointAtNamedEntity(BaseEntity dest, string? target) { DevMsg(1, $"{dest.GetClassname()} ({dest.GetDebugName()}) was unable to point at an entity named: {target}\n"); } - public static int DropToFloor(BaseEntity entity, Mask mask) { + public static int DropToFloor(BaseEntity entity, Mask mask) => DropToFloor(entity, mask, null); + + public static int DropToFloor(BaseEntity entity, Mask mask, BaseEntity? ignore) { entity.SetGroundEntity(null); - TraceEntity(entity, entity.GetAbsOrigin(), entity.GetAbsOrigin() - new Vector3(0, 0, 256), mask, out Trace trace); + TraceEntity(entity, entity.GetAbsOrigin(), entity.GetAbsOrigin() - new Vector3(0, 0, 256), mask, ignore, entity.GetCollisionGroup(), out Trace trace); if (trace.AllSolid) return -1; diff --git a/Game.Shared/NPCEvent.cs b/Game.Shared/NPCEvent.cs index 0b0fe414c..c0b4c443c 100644 --- a/Game.Shared/NPCEvent.cs +++ b/Game.Shared/NPCEvent.cs @@ -25,6 +25,19 @@ public static class NPCEventGlobals public const int EVENT_WEAPON = 3000; public const int EVENT_CLIENT = 5000; + public const int NPC_EVENT_BODYDROP_LIGHT = 2001; + public const int NPC_EVENT_BODYDROP_HEAVY = 2002; + public const int NPC_EVENT_SWISHSOUND = 2010; + public const int NPC_EVENT_180TURN = 2020; + public const int NPC_EVENT_ITEM_PICKUP = 2040; + public const int NPC_EVENT_WEAPON_DROP = 2041; + public const int NPC_EVENT_WEAPON_SET_SEQUENCE_NAME = 2042; + public const int NPC_EVENT_WEAPON_SET_SEQUENCE_NUMBER = 2043; + public const int NPC_EVENT_WEAPON_SET_ACTIVITY = 2044; + public const int NPC_EVENT_LEFTFOOT = 2050; + public const int NPC_EVENT_RIGHTFOOT = 2051; + public const int NPC_EVENT_OPEN_DOOR = 2060; + public const int EVENT_WEAPON_MELEE_HIT = 3001; public const int EVENT_WEAPON_SMG1 = 3002; public const int EVENT_WEAPON_MELEE_SWISH = 3003; diff --git a/Game.Shared/ScriptEvent.cs b/Game.Shared/ScriptEvent.cs new file mode 100644 index 000000000..04a03c32b --- /dev/null +++ b/Game.Shared/ScriptEvent.cs @@ -0,0 +1,25 @@ +#if CLIENT_DLL || GAME_DLL +global using static Game.Shared.ScriptEventGlobals; + +namespace Game.Shared; + +public static class ScriptEventGlobals +{ + public const int SCRIPT_EVENT_DEAD = 1000; + public const int SCRIPT_EVENT_NOINTERRUPT = 1001; + public const int SCRIPT_EVENT_CANINTERRUPT = 1002; + public const int SCRIPT_EVENT_FIREEVENT = 1003; + public const int SCRIPT_EVENT_SOUND = 1004; + public const int SCRIPT_EVENT_SENTENCE = 1005; + public const int SCRIPT_EVENT_INAIR = 1006; + public const int SCRIPT_EVENT_ENDANIMATION = 1007; + public const int SCRIPT_EVENT_SOUND_VOICE = 1008; + public const int SCRIPT_EVENT_SENTENCE_RND1 = 1009; + public const int SCRIPT_EVENT_NOT_DEAD = 1010; + public const int SCRIPT_EVENT_EMPHASIS = 1011; + public const int SCRIPT_EVENT_BODYGROUPON = 1020; + public const int SCRIPT_EVENT_BODYGROUPOFF = 1021; + public const int SCRIPT_EVENT_BODYGROUPTEMP = 1022; + public const int SCRIPT_EVENT_FIRE_INPUT = 1100; +} +#endif diff --git a/Game.Shared/UtilShared.cs b/Game.Shared/UtilShared.cs index ccffb9e88..22d9724b6 100644 --- a/Game.Shared/UtilShared.cs +++ b/Game.Shared/UtilShared.cs @@ -289,6 +289,17 @@ public static void TraceEntity(BaseEntity entity, in Vector3 absStart, in Vector #endif } + public static void TraceEntity(BaseEntity entity, in Vector3 absStart, in Vector3 absEnd, Mask mask, IHandleEntity? ignore, CollisionGroup collisionGroup, out Trace ptr) { + ICollideable collision = entity.GetCollideable()!; + + Assert(collision.GetCollisionAngles() == vec3_angle); + + TraceFilterEntityIgnoreOther traceFilter = new(entity, ignore, collisionGroup); + + ptr = default; + enginetrace.SweepCollideable(collision, absStart, absEnd, collision.GetCollisionAngles(), mask, ref traceFilter, ref ptr); + } + public static void TraceEntity(BaseEntity entity, in Vector3 absStart, in Vector3 absEnd, Mask mask, scoped ref IF filter, out Trace ptr) where IF : struct, ITraceFilter { ICollideable collision = entity.GetCollideable()!; @@ -511,6 +522,19 @@ public bool ShouldHitEntity(IHandleEntity handleEntity, Contents contentsMask) { } } +public struct TraceFilterEntityIgnoreOther(BaseEntity entity, IHandleEntity? ignore, CollisionGroup collisionGroup) : ITraceFilter +{ + public TraceFilterEntity TraceFilterEntity = new(entity, collisionGroup); + public IHandleEntity? IgnoreOther = ignore; + + public bool ShouldHitEntity(IHandleEntity handleEntity, Contents contentsMask) { + if (handleEntity == IgnoreOther) + return false; + + return TraceFilterEntity.ShouldHitEntity(handleEntity, contentsMask); + } +} + public struct TraceFilterSkipTwoEntities(IHandleEntity? passentity, IHandleEntity? passentity2, CollisionGroup collisionGroup) : ITraceFilter { public TraceFilterSimple Simple = new(passentity, collisionGroup); From 68e76c2b8b6b0e748604b1b71f3da4be2911c201 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 04:47:53 +0300 Subject: [PATCH 43/73] Port NPC death schedule, die task and ragdoll handoff --- Game.Server/AI_BaseNPC.cs | 130 ++++++++++++++++++++++++++++- Game.Server/AI_Squad.cs | 1 + Game.Server/BaseAnimating.cs | 45 ++++++++++ Game.Server/BaseCombatCharacter.cs | 95 +++++++++++++++++++++ 4 files changed, 267 insertions(+), 4 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 3c6013a8e..c2e35df74 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -375,6 +375,8 @@ public static ReadOnlySpan GetActivityName(Activity actID) { DEFINE.OUTPUT(nameof(OnLostPlayerLOS), "OnLostPlayerLOS", eventFuncs), DEFINE.OUTPUT(nameof(OnLostPlayer), "OnLostPlayer", eventFuncs), DEFINE.OUTPUT(nameof(OnWake), "OnWake", eventFuncs), + DEFINE.FIELD(nameof(DidDeathCleanup), FieldType.Boolean), + DEFINE.OUTPUT(nameof(OnDeath), "OnDeath", eventFuncs), ]); public override DataMap? GetDataDescMap() => DataDesc; @@ -530,6 +532,8 @@ public static ReadOnlySpan GetActivityName(Activity actID) { public OutputEvent OnLostEnemy = new(); public OutputEvent OnLostPlayer = new(); public OutputEvent OnWake = new(); + public OutputEvent OnDeath = new(); + public bool DidDeathCleanup; public bool WakeSquad; public long WakeTick; public OutputEHANDLE OnFoundEnemy = new(); @@ -4967,6 +4971,19 @@ public virtual void StartTask(in Task_t task) { TaskComplete(); break; + case TASK_DIE: + GetNavigator()!.StopMoving(); + SetIdealActivity(GetDeathActivity()); + LifeState = (int)Source.LifeState.Dying; + break; + + case TASK_SOUND_DIE: { + TakeDamageInfo info = new(); + DeathSound(info); + TaskComplete(); + break; + } + case TASK_SCRIPT_RUN_TO_TARGET: case TASK_SCRIPT_WALK_TO_TARGET: case TASK_SCRIPT_CUSTOM_MOVE_TO_TARGET: @@ -5200,9 +5217,7 @@ public virtual void StartTask(in Task_t task) { case TASK_STRAFE_PATH: case TASK_SMALL_FLINCH: case TASK_BIG_FLINCH: - case TASK_DIE: case TASK_SOUND_WAKE: - case TASK_SOUND_DIE: case TASK_SOUND_IDLE: case TASK_SOUND_PAIN: case TASK_SOUND_ANGRY: @@ -5469,6 +5484,10 @@ public virtual void RunTask(in Task_t task) { break; } + case TASK_DIE: + RunDieTask(); + break; + case TASK_SCRIPT_RUN_TO_TARGET: case TASK_SCRIPT_WALK_TO_TARGET: case TASK_SCRIPT_CUSTOM_MOVE_TO_TARGET: @@ -5559,7 +5578,6 @@ public virtual void RunTask(in Task_t task) { case TASK_MOVE_AWAY_PATH: case TASK_WEAPON_RUN_PATH: case TASK_ITEM_RUN_PATH: - case TASK_DIE: case TASK_WAIT_FOR_SPEAK_FINISH: case TASK_RANGE_ATTACK1: case TASK_RANGE_ATTACK2: @@ -5892,7 +5910,111 @@ public virtual int SelectAlertSchedule() { public virtual int SelectCombatSchedule() => throw new NotImplementedException(); - public virtual int SelectDeadSchedule() => throw new NotImplementedException(); + public virtual int SelectDeadSchedule() { + if (BecomeRagdollOnClient(vec3_origin)) { + CleanupOnDeath(); + return SCHED_DIE_RAGDOLL; + } + + if (LifeState == (int)Source.LifeState.Dead) + return SCHED_NONE; + + CleanupOnDeath(); + return SCHED_DIE; + } + + public void RunDieTask() { + AutoMovement(); + + if (IsActivityFinished() && GetCycle() >= 1.0f) { + LifeState = (int)Source.LifeState.Dead; + + SetThink(null); + StopAnimation(); + + if (!BBoxFlat()) + Util.SetSize(this, new Vector3(-4, -4, 0), new Vector3(4, 4, 1)); + else + Util.SetSize(this, WorldAlignMins(), new Vector3(WorldAlignMaxs().X, WorldAlignMaxs().Y, WorldAlignMins().Z + 1)); + } + } + + public bool BBoxFlat() { + Vector3 point; + float xSize, ySize; + float length; + float length2; + + xSize = WorldAlignSize().X / 2; + ySize = WorldAlignSize().Y / 2; + + point.X = GetAbsOrigin().X + xSize; + point.Y = GetAbsOrigin().Y + ySize; + point.Z = GetAbsOrigin().Z; + + Util.TraceLine(point, point - new Vector3(0, 0, 100), Mask.NPCSolidBrushOnly, this, Source.CollisionGroup.None, out Trace tr); + length = (point - tr.EndPos).Length(); + + point.X = GetAbsOrigin().X - xSize; + point.Y = GetAbsOrigin().Y - ySize; + + Util.TraceLine(point, point - new Vector3(0, 0, 100), Mask.NPCSolidBrushOnly, this, Source.CollisionGroup.None, out tr); + length2 = (point - tr.EndPos).Length(); + if (length2 > length) + return false; + length = length2; + + point.X = GetAbsOrigin().X - xSize; + point.Y = GetAbsOrigin().Y + ySize; + Util.TraceLine(point, point - new Vector3(0, 0, 100), Mask.NPCSolidBrushOnly, this, Source.CollisionGroup.None, out tr); + length2 = (point - tr.EndPos).Length(); + if (length2 > length) + return false; + length = length2; + + point.X = GetAbsOrigin().X + xSize; + point.Y = GetAbsOrigin().Y - ySize; + Util.TraceLine(point, point - new Vector3(0, 0, 100), Mask.NPCSolidBrushOnly, this, Source.CollisionGroup.None, out tr); + length2 = (point - tr.EndPos).Length(); + if (length2 > length) + return false; + length = length2; + + return true; + } + + public void CleanupOnDeath(BaseEntity? culprit = null, bool fireDeathOutput = true) { + if (!DidDeathCleanup) { + DidDeathCleanup = true; + + if (NPCState == NPCState.Script && Cine.Get() != null) + Cine.Get()!.CancelScript(); + + if (GetHintNode() != null) { + GetHintNode()!.Unlock(0.0f); + SetHintNode(null); + } + + if (fireDeathOutput) + OnDeath.FireOutput(culprit, this); + + VacateStrategySlot(); + + if (Squad != null) { + if (NPCState == NPCState.Idle && culprit != null) { + if (GetEnemies().GetDangerMemory() == null) + UpdateEnemyMemory(culprit, GetAbsOrigin()); + } + + Squad.RemoveFromSquad(this, true); + Squad = null; + } + + SceneEntityGlobals.RemoveActorFromScriptedScenes(this, false); + } + else + DevMsg("Unexpected double-death-cleanup\n"); + } public virtual int SelectScriptSchedule() { Assert(Cine.Get() != null); diff --git a/Game.Server/AI_Squad.cs b/Game.Server/AI_Squad.cs index 79e0040ab..a43d46992 100644 --- a/Game.Server/AI_Squad.cs +++ b/Game.Server/AI_Squad.cs @@ -35,5 +35,6 @@ public class AI_Squad public AI_BaseNPC? GetNextMember(ref int iter) => throw new NotImplementedException(); public void VacateStrategySlot(BaseEntity? enemy, SquadSlot slot) => throw new NotImplementedException(); public bool OccupyStrategySlotRange(BaseEntity? enemy, SquadSlot slotIDStart, SquadSlot slotIDEnd, ref SquadSlot slot) => throw new NotImplementedException(); + public void RemoveFromSquad(AI_BaseNPC npc, bool death = false) => throw new NotImplementedException(); public void UpdateEnemyMemory(AI_BaseNPC updater, BaseEntity enemy, in Vector3 position) => throw new NotImplementedException(); } diff --git a/Game.Server/BaseAnimating.cs b/Game.Server/BaseAnimating.cs index d841f4aa0..7861a6f1b 100644 --- a/Game.Server/BaseAnimating.cs +++ b/Game.Server/BaseAnimating.cs @@ -534,8 +534,53 @@ public BoneCache GetBoneCache() { return pcache; } + public void StopAnimation() => PlaybackRate = 0; + + public virtual void ClampRagdollForce(in Vector3 forceIn, out Vector3 forceOut) => forceOut = forceIn; + + public virtual bool BecomeRagdollOnClient(in Vector3 force) { + if (CanBecomeRagdoll()) { + VPhysicsDestroyObject(); + AddSolidFlags(SolidFlags.NotSolid); + RenderFX = (byte)RenderFx.Ragdoll; + + ClampRagdollForce(force, out Vector3 clampedForce); + Force = clampedForce; + + SetParent(null); + + AddFlag(EntityFlags.TransRagdoll); + + SetMoveType(Source.MoveType.None); + SetThink(null); + + SetNextThink(gpGlobals.CurTime + 2.0f); + SetThink(SUB_Remove); + + if (EffectEntity.Get() is EntityFlame fireChild) { + fireChild.SetThink(fireChild.SUB_Remove); + fireChild.SetNextThink(gpGlobals.CurTime + 0.1f); + } + + return true; + } + return false; + } + public bool IsRagdoll() => RenderFX == (byte)RenderFx.Ragdoll; + public virtual bool CanBecomeRagdoll() { + int ragdollSequence = SelectWeightedSequence(Activity.ACT_DIERAGDOLL); + + if (ragdollSequence == StudioHdr.ACTIVITY_NOT_AVAILABLE) + return false; + + if ((GetFlags() & EntityFlags.TransRagdoll) != 0) + return false; + + return true; + } + public virtual void GetSkeleton(StudioHdr? studioHdr, Span pos, Span q, int boneMask) { if (studioHdr == null) { AssertMsg(false, "BaseAnimating.GetSkeleton() without a model"); diff --git a/Game.Server/BaseCombatCharacter.cs b/Game.Server/BaseCombatCharacter.cs index 2be3d1a27..5db1794c5 100644 --- a/Game.Server/BaseCombatCharacter.cs +++ b/Game.Server/BaseCombatCharacter.cs @@ -98,6 +98,101 @@ public virtual Vector3 BodyDirection3D() { public virtual Vector3 EyeDirection3D() => HeadDirection3D(); // No eye motion so just return head dir + public HitGroup LastHitGroupValue; + public HitGroup LastHitGroup() => LastHitGroupValue; + + public virtual Activity GetDeathActivity() { + Activity deathActivity; + bool triedDirection; + float dot; + Vector3 src; + + if (IsPlayer()) { + switch (random.RandomInt(0, 7)) { + case 0: return Activity.ACT_DIESIMPLE; + case 1: return Activity.ACT_DIEBACKWARD; + case 2: return Activity.ACT_DIEFORWARD; + case 3: return Activity.ACT_DIEVIOLENT; + case 4: return Activity.ACT_DIE_HEADSHOT; + case 5: return Activity.ACT_DIE_CHESTSHOT; + case 6: return Activity.ACT_DIE_GUTSHOT; + case 7: return Activity.ACT_DIE_BACKSHOT; + } + } + + src = WorldSpaceCenter(); + + triedDirection = false; + deathActivity = Activity.ACT_DIESIMPLE; + + MathLib.AngleVectors(GetLocalAngles(), out Vector3 forward); + dot = -Vector3.Dot(forward, g_vecAttackDir); + + switch (LastHitGroupValue) { + case HitGroup.Head: + deathActivity = Activity.ACT_DIE_HEADSHOT; + break; + + case HitGroup.Stomach: + deathActivity = Activity.ACT_DIE_GUTSHOT; + break; + + case HitGroup.Generic: + triedDirection = true; + + if (dot > 0.3) + deathActivity = Activity.ACT_DIEFORWARD; + else if (dot <= -0.3) + deathActivity = Activity.ACT_DIEBACKWARD; + break; + + default: + triedDirection = true; + + if (dot > 0.3) + deathActivity = Activity.ACT_DIEFORWARD; + else if (dot <= -0.3) + deathActivity = Activity.ACT_DIEBACKWARD; + break; + } + + if (SelectWeightedSequence(deathActivity) == StudioHdr.ACTIVITY_NOT_AVAILABLE) { + if (triedDirection) + deathActivity = Activity.ACT_DIESIMPLE; + else { + if (dot > 0.3) + deathActivity = Activity.ACT_DIEFORWARD; + else if (dot <= -0.3) + deathActivity = Activity.ACT_DIEBACKWARD; + } + } + + if (SelectWeightedSequence(deathActivity) == StudioHdr.ACTIVITY_NOT_AVAILABLE) { + deathActivity = Activity.ACT_DIESIMPLE; + + if (SelectWeightedSequence(deathActivity) == StudioHdr.ACTIVITY_NOT_AVAILABLE) + Msg($"ERROR! {GetModelName()} missing ACT_DIESIMPLE\n"); + } + + if (deathActivity == Activity.ACT_DIEFORWARD) { + Util.TraceHull(src, src + forward * 64, new Vector3(-16, -16, -18), + new Vector3(16, 16, 18), Mask.Solid, this, Source.CollisionGroup.None, out Trace tr); + + if (tr.Fraction != 1.0) + deathActivity = Activity.ACT_DIESIMPLE; + } + + if (deathActivity == Activity.ACT_DIEBACKWARD) { + Util.TraceHull(src, src - forward * 64, new Vector3(-16, -16, -18), + new Vector3(16, 16, 18), Mask.Solid, this, Source.CollisionGroup.None, out Trace tr); + + if (tr.Fraction != 1.0) + deathActivity = Activity.ACT_DIESIMPLE; + } + + return deathActivity; + } + public virtual bool FInViewCone(BaseEntity entity) => FInViewCone(entity.WorldSpaceCenter()); public virtual bool FInViewCone(in Vector3 spot) { From d88c1e532d355dd4fa1b0742d718c527ddb751aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 05:03:28 +0300 Subject: [PATCH 44/73] Port RefreshSkillData skill cfg execution --- Game.Shared/GameRules.cs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/Game.Shared/GameRules.cs b/Game.Shared/GameRules.cs index 18195d164..9660bd478 100644 --- a/Game.Shared/GameRules.cs +++ b/Game.Shared/GameRules.cs @@ -310,7 +310,25 @@ public virtual void CheckHaptics(BasePlayer player) { public virtual void Precache() { return; } public virtual void RefreshSkillData(bool forceUpdate) { - // todo +#if !CLIENT_DLL + if (!forceUpdate) { + if (GlobalEntity.IsInTable("skill.cfg")) + return; + } + GlobalEntity.Add("skill.cfg", gpGlobals.MapName, GlobalEState.On); + + ConVarRef skill = new("skill"); + + SetSkillLevel(skill.IsValid() ? skill.GetInt() : 1); + +#if HL2_DLL + engine.ServerCommand("exec skill_manifest.cfg\n"); + engine.ServerExecute(); +#elif !TF_DLL && !DOD_DLL + engine.ServerCommand($"exec skill{GetSkillLevel()}.cfg\n"); + engine.ServerExecute(); +#endif +#endif } // Called each frame. This just forwards the call to Think(). From 72a6d8fb3d102dbe5dbfef87b39edf9d63249c88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 05:11:42 +0300 Subject: [PATCH 45/73] Fix shared activities missing from the activity remap database --- Game.Shared/ActivityList.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Game.Shared/ActivityList.cs b/Game.Shared/ActivityList.cs index 580a22888..dfaf22862 100644 --- a/Game.Shared/ActivityList.cs +++ b/Game.Shared/ActivityList.cs @@ -74,6 +74,7 @@ public static ActivityList AddActivityEntry(ReadOnlySpan name, Activity ac if (activityIndex > HighestActivity) HighestActivity = activityIndex; g_ActivityList.Add(list); + SharedActivityRemapDatabase[list.StringKey] = g_ActivityList.Count - 1; return list; } @@ -111,7 +112,6 @@ public static bool RegisterSharedActivity(ReadOnlySpan activityName, Activ } // ---------------------------------------------------------------- AddActivityEntry(activityName, activityIndex, false); - SharedActivityRemapDatabase[g_ActivityList[^1].StringKey] = g_ActivityList.Count - 1; return true; } From 290c27ddb12ce8754c0be0880fda9c99c364e1df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 05:44:15 +0300 Subject: [PATCH 46/73] Port physics_npc_solver --- Game.Server/PhysicsNPCSolver.cs | 270 +++++++++++++++++++++++++++++++- 1 file changed, 269 insertions(+), 1 deletion(-) diff --git a/Game.Server/PhysicsNPCSolver.cs b/Game.Server/PhysicsNPCSolver.cs index b7f8c8035..56c57185b 100644 --- a/Game.Server/PhysicsNPCSolver.cs +++ b/Game.Server/PhysicsNPCSolver.cs @@ -1,9 +1,277 @@ global using static Game.Server.PhysicsNPCSolverGlobals; +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Formats.BSP; +using Source.Common.Mathematics; +using Source.Common.Physics; + +using System.Numerics; + +using DEFINE = Source.DEFINE; + namespace Game.Server; +[LinkEntityToClass("physics_npc_solver")] +public class PhysicsNPCSolver : LogicalEntity, IMotionEvent +{ + public static readonly new DataMap DataDesc = new(typeof(PhysicsNPCSolver), LogicalEntity.DataDesc, [ + DEFINE.FIELD(nameof(NPC), FieldType.EHandle), + DEFINE.FIELD(nameof(Entity), FieldType.EHandle), + DEFINE.FIELD(nameof(SeparationDuration), FieldType.Float), + DEFINE.FIELD(nameof(CancelTime), FieldType.Time), + DEFINE.FIELD(nameof(AllowIntersection), FieldType.Boolean), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public static readonly List g_SolverList = []; + + Handle NPC = new(); + EHANDLE Entity = new(); + IPhysicsMotionController? Controller; + float SeparationDuration; + TimeUnit_t CancelTime; + bool AllowIntersection; + + public PhysicsNPCSolver() { + g_SolverList.Add(this); + } + + public override void Term() { + g_SolverList.Remove(this); + base.Term(); + } + + public override void OnRestore() { + base.OnRestore(); + if (AllowIntersection) + PhysDisableEntityCollisions(NPC.Get(), Entity.Get()); + } + + public static bool NPCPhysics_SolverExists(AI_BaseNPC npc, BaseEntity physicsObject) { + foreach (PhysicsNPCSolver solver in g_SolverList) { + if (solver.Entity.Get() == physicsObject && solver.NPC.Get() == npc) + return true; + } + + return false; + } + + public static PhysicsNPCSolver Create(AI_BaseNPC npc, BaseEntity physicsObject, bool disableCollisions, float separationTime) { + PhysicsNPCSolver solver = (PhysicsNPCSolver)CreateNoSpawn("physics_npc_solver", vec3_origin, vec3_angle, null)!; + solver.Init(npc, physicsObject, disableCollisions, separationTime); + solver.Spawn(); + return solver; + } + + public void Init(AI_BaseNPC npc, BaseEntity physicsObject, bool disableCollisions, float separationTime) { + NPC.Set(npc); + Entity.Set(physicsObject); + Controller = null; + SeparationDuration = separationTime; + AllowIntersection = disableCollisions; + } + + void ResetCancelTime() { + CancelTime = gpGlobals.CurTime + SeparationDuration; + SetNextThink(CancelTime); + } + + void BecomePenetrationSolver() { + BaseEntity? entity = Entity.Get(); + if (entity != null) { + AllowIntersection = true; + Span list = new IPhysicsObject[VPHYSICS_MAX_OBJECT_LIST_COUNT]; + int listCount = entity.VPhysicsGetObjectList(list); + PhysDisableEntityCollisions(NPC.Get(), entity); + Controller = physenv.CreateMotionController(this); + for (int i = 0; i < listCount; i++) { + Controller.AttachObject(list[i], false); + list[i].Wake(); + } + Controller.SetPriority(IPhysicsMotionController.Priority.HighPriority); + } + } + + public override void Spawn() { + if (AllowIntersection) + BecomePenetrationSolver(); + else { +#if GMOD_DLL + Entity.Get()?.SetNavIgnore(); +#else + Entity.Get()!.SetNavIgnore(); +#endif + } + ResetCancelTime(); + } + + public override void UpdateOnRemove() { + if (AllowIntersection) { + physenv.DestroyMotionController(Controller!); + Controller = null; + PhysEnableEntityCollisions(NPC.Get(), Entity.Get()); + } + else + Entity.Get()?.ClearNavIgnore(); + + base.UpdateOnRemove(); + } + + bool IsIntersecting() { + AI_BaseNPC? npc = NPC.Get(); + BaseEntity? physics = Entity.Get(); + if (npc != null && physics != null) { + Ray ray = default; + Vector3 mins = npc.WorldAlignMins() - new Vector3(1, 1, 1); + Vector3 maxs = npc.WorldAlignMaxs() + new Vector3(1, 1, 1); + + ray.Init(npc.GetAbsOrigin(), npc.GetAbsOrigin(), mins, maxs); + Trace tr = default; + enginetrace.ClipRayToEntity(in ray, npc.PhysicsSolidMaskForEntity(), physics, ref tr); + if (tr.StartSolid) + return true; + } + return false; + } + + static bool IsContactOnNPCHead(IPhysicsFrictionSnapshot snapshot, IPhysicsObject physics, AI_BaseNPC npc) { + float heightCheck = npc.GetAbsOrigin().Z + npc.GetHullMaxs().Z; + physics.GetVelocity(out Vector3 vel, out _); + snapshot.GetContactPoint(out Vector3 point); + if (vel.LengthSquared() < 10.0f * 10.0f) { + float topdist = MathF.Abs(point.Z - heightCheck); + if (topdist < 2.0f) + return true; + } + return false; + } + + bool CheckTouching() { + AI_BaseNPC? npc = NPC.Get(); + if (npc == null) + return false; + + BaseEntity? physicsEnt = Entity.Get(); + if (physicsEnt == null) + return false; + + IPhysicsObject? physics = physicsEnt.VPhysicsGetObject(); + IPhysicsObject? npcPhysics = npc.VPhysicsGetObject(); + if (npcPhysics == null || physics == null) + return false; + + IPhysicsFrictionSnapshot snapshot = physics.CreateFrictionSnapshot(); + bool found = false; + bool penetrate = false; + + while (snapshot.IsValid()) { + IPhysicsObject? other = snapshot.GetObject(1); + if (other == npcPhysics) { + found = true; + if (IsContactOnNPCHead(snapshot, physics, npc)) { + penetrate = true; + snapshot.MarkContactForDelete(); + } + break; + } + snapshot.NextFrictionData(); + } + snapshot.DeleteAllMarkedContacts(true); + physics.DestroyFrictionSnapshot(snapshot); + + if (!penetrate && (physics.GetGameFlags() & PhysicsFlags.Penetrating) != 0) + penetrate = IsIntersecting(); + + if (penetrate) { + physicsEnt.ClearNavIgnore(); + BecomePenetrationSolver(); + } + + return found; + } + + public override void Think() { + bool finished = AllowIntersection ? !IsIntersecting() : !CheckTouching(); + + if (finished) { + Util.Remove(this); + return; + } + if (AllowIntersection) { + IPhysicsObject? obj = Entity.Get()!.VPhysicsGetObject(); + if (obj == null) { + Util.Remove(this); + return; + } + obj.Wake(); + } + ResetCancelTime(); + } + + public SimResult Simulate(IPhysicsMotionController? controller, IPhysicsObject? obj, TimeUnit_t deltaTime, out Vector3 linear, out Vector3 angular) { + linear = default; + angular = default; + + if (IsIntersecting()) { + const float PUSH_SPEED = 150.0f; + + if ((obj!.GetGameFlags() & PhysicsFlags.PlayerHeld) != 0) { +#if GMOD_DLL + for (int i = 0; i < gpGlobals.MaxClients; i++) { + BasePlayer? player = Util.PlayerByIndex(i); + player?.ForceDropOfCarriedPhysObjects(Entity.Get()); + } +#endif + } + + ResetCancelTime(); + angular = default; + linear = default; + + if ((obj.GetGameFlags() & PhysicsFlags.MultiObjectEntity) != 0) { + if (Entity.Get()!.GetServerVehicle() != null) + return SimResult.Nothing; + } + + obj.GetPosition(out Vector3 origin, out _); + obj.GetVelocity(out Vector3 vel, out _); + Vector3 dir = origin - NPC.Get()!.GetAbsOrigin(); + dir.Z = dir.Z > 0 ? 0.1f : -0.1f; + MathLib.VectorNormalize(ref dir); + Vector3 angVel = default; + + PhysComputeSlideDirection(obj, dir * PUSH_SPEED, angVel, out Vector3 pushImpulse, out _, false, 0); + + dir = pushImpulse; + MathLib.VectorNormalize(ref dir); + + if (Vector3.Dot(vel, dir) < PUSH_SPEED * 0.5f) { + linear = pushImpulse; + if (obj.GetContactPoint(out _, null!)) + linear.Z += GetCurrentGravity(); + } + return SimResult.GlobalAcceleration; + } + return SimResult.Nothing; + } +} + public static class PhysicsNPCSolverGlobals { - public static BaseEntity? NPCPhysics_CreateSolver(AI_BaseNPC npc, BaseEntity? physicsObject, bool disableCollisions, TimeUnit_t separationDuration) => throw new NotImplementedException(); + public static BaseEntity? NPCPhysics_CreateSolver(AI_BaseNPC npc, BaseEntity? physicsObject, bool disableCollisions, TimeUnit_t separationDuration) { + if (disableCollisions) { + if (PhysEntityCollisionsAreDisabled(npc, physicsObject!)) + return null; + } + else { + if (physicsObject!.IsNavIgnored()) + return null; + } + return PhysicsNPCSolver.Create(npc, physicsObject!, disableCollisions, (float)separationDuration); + } + public static BaseEntity? EntityPhysics_CreateSolver(BaseEntity movingEntity, BaseEntity physicsObject, bool disableCollisions, TimeUnit_t separationDuration) => null; } From 241ac2368742219d0976e7005d2ce20a868afbcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:27:31 +0300 Subject: [PATCH 47/73] Fix VPhysicsUpdate not touching triggers or relinking children --- Game.Server/BaseEntity.cs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index 103aedfaf..bcbfb1da9 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -1368,22 +1368,35 @@ public void VPhysicsUpdate(IPhysicsObject physics) { switch (GetMoveType()) { case Source.MoveType.VPhysics: { if (GetMoveParent() != null) { +#if !GMOD_DLL DevWarning($"Updating physics on object in hierarchy {GetClassname()}!\n"); +#endif return; } physics.GetPosition(out Vector3 origin, out QAngle angles); - if (!IsEntityQAngleReasonable(angles)) + if (!IsEntityQAngleReasonable(angles)) { + if (CheckEmitReasonablePhysicsSpew()) + Warning($"Ignoring bogus angles ({angles.X:F6},{angles.Y:F6},{angles.Z:F6}) from vphysics! (entity {GetDebugName()})\n"); angles = vec3_angle; + } + Vector3 prevOrigin = GetAbsOrigin(); if (IsEntityPositionReasonable(origin)) SetAbsOrigin(origin); + else { + if (CheckEmitReasonablePhysicsSpew()) + Warning($"Ignoring unreasonable position ({origin.X:F6},{origin.Y:F6},{origin.Z:F6}) from vphysics! (entity {GetDebugName()})\n"); + } angles.X = MathLib.AngleNormalize(angles.X); angles.Y = MathLib.AngleNormalize(angles.Y); angles.Z = MathLib.AngleNormalize(angles.Z); SetAbsAngles(angles); + + PhysicsTouchTriggers(prevOrigin); + PhysicsRelinkChildren(gpGlobals.FrameTime); break; } default: @@ -1391,6 +1404,23 @@ public void VPhysicsUpdate(IPhysicsObject physics) { } } + public void PhysicsRelinkChildren(TimeUnit_t dt) { + BaseEntity? child; + + for (child = FirstMoveChild(); child != null; child = child.NextMovePeer()) { + if (child.IsSolid() || child.IsSolidFlagSet(SolidFlags.Trigger)) + child.PhysicsTouchTriggers(); + + if (child.GetMoveType() != Source.MoveType.VPhysics) + child.UpdatePhysicsShadowToCurrentPosition(dt); + else if (child.GetOwnerEntity() != this) + Assert(false); + + if (child.FirstMoveChild() != null) + child.PhysicsRelinkChildren(dt); + } + } + public virtual void VPhysicsShadowCollision(int index, ref GameVCollisionEvent ev) { } public virtual void VPhysicsCollision(int index, ref GameVCollisionEvent ev) { From a968b42671d5d460a9744c4346f75de10da222a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 14:22:06 +0300 Subject: [PATCH 48/73] Port AI hint system and info_node_hint spawning --- Game.Server/AI_BaseNPC.cs | 54 ++- Game.Server/AI_Hint.cs | 796 +++++++++++++++++++++++++++++++++++- Game.Server/AI_InitUtils.cs | 34 +- Game.Server/MapEntities.cs | 10 +- 4 files changed, 872 insertions(+), 22 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index c2e35df74..e096155e6 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -4333,6 +4333,13 @@ public virtual void OnScheduleChange() { public virtual float GetHintDelay(Hint hintType) => 0; + public virtual Activity GetHintActivity(short hintType, Activity hintsActivity) { + if (hintsActivity != Activity.ACT_INVALID) + return hintsActivity; + + return Activity.ACT_IDLE; + } + public Activity GetIdealActivity() => IdealActivity; public bool IsActivityStarted() => GetSequence() == IdealSequence; @@ -4977,6 +4984,40 @@ public virtual void StartTask(in Task_t task) { LifeState = (int)Source.LifeState.Dying; break; + case TASK_FACE_HINTNODE: + Assert(GetMotor()!.IsYawLocked() == false); + + GetMotor()!.SetIdealYaw(GetHintNode()!.Yaw()); + GetMotor()!.SetIdealYaw(CalcReasonableFacing(true)); + if (FacingIdeal()) + TaskComplete(); + else + SetTurnActivity(); + break; + + case TASK_GET_PATH_TO_HINTNODE: { + if (GetHintNode() == null) + TaskFail(AI_TaskFailureCode.NoHintNode); + else { + GetHintNode()!.GetPosition(this, out Vector3 hintPos); + + GetNavigator()!.SetGoal(new AI_NavGoal(hintPos, Activity.ACT_RUN)); + if (task.TaskData == 0) + GetNavigator()!.SetArrivalDirection(GetHintNode()!.GetDirection()); + if (GetHintNode()!.HintActivityName() != null) { + Activity hintActivity = (Activity)GetActivityID(GetHintNode()!.HintActivityName()); + if (hintActivity != Activity.ACT_INVALID) + GetNavigator()!.SetArrivalActivity(GetHintActivity((short)GetHintNode()!.HintType(), hintActivity)); + else { + int sequence = LookupSequence(GetHintNode()!.HintActivityName()); + if (sequence != (int)Activity.ACT_INVALID) + GetNavigator()!.SetArrivalSequence(sequence); + } + } + } + break; + } + case TASK_SOUND_DIE: { TakeDamageInfo info = new(); DeathSound(info); @@ -5180,7 +5221,6 @@ public virtual void StartTask(in Task_t task) { case TASK_FIND_COVER_FROM_ENEMY: case TASK_FIND_COVER_FROM_ORIGIN: case TASK_FIND_COVER_FROM_BEST_SOUND: - case TASK_FACE_HINTNODE: case TASK_MOVE_TO_TARGET_RANGE: case TASK_MOVE_TO_GOAL_RANGE: case TASK_WAIT_UNTIL_NO_DANGER_SOUND: @@ -5204,7 +5244,6 @@ public virtual void StartTask(in Task_t task) { case TASK_GET_PATH_TO_ENEMY_CORPSE: case TASK_GET_PATH_TO_SAVEPOSITION_LOS: case TASK_GET_PATH_TO_TARGET_WEAPON: - case TASK_GET_PATH_TO_HINTNODE: case TASK_GET_PATH_TO_COMMAND_GOAL: case TASK_MARK_COMMAND_GOAL_POS: case TASK_CLEAR_COMMAND_GOAL: @@ -7929,6 +7968,17 @@ public void SetSchedule(AI_Schedule newSchedule) { public void SetHintNode(AI_Hint? hintNode) => HintNode.Set(hintNode); + public void ClearHintNode(float reuseDelay = 0.0f) { + AI_Hint? hint = HintNode.Get(); + if (hint != null) { + if (hint.IsLockedBy(this)) + hint.Unlock(reuseDelay); + HintNode.Set(null); + } + } + + public virtual bool FValidateHintType(AI_Hint hint) => false; + public BaseEntity? GetEnemy() => Enemy.Get(); public void SetEnemy(BaseEntity? enemy, bool setCondNewEnemy = true) { diff --git a/Game.Server/AI_Hint.cs b/Game.Server/AI_Hint.cs index a1099ba4c..326c19296 100644 --- a/Game.Server/AI_Hint.cs +++ b/Game.Server/AI_Hint.cs @@ -1,3 +1,15 @@ +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Formats.BSP; +using Source.Common.Mathematics; + +using System.Numerics; + +using DEFINE = Source.DEFINE; + namespace Game.Server; public enum Hint : short @@ -73,26 +85,749 @@ public enum Hint : short CStrikeHostageEscape = 1100, } +[Flags] +public enum AI_HintNodeFlags +{ + None = 0x00000000, + Visible = 0x00000001, + Nearest = 0x00000002, + Random = 0x00000004, + Clear = 0x00000008, + UseGroup = 0x00000010, + VisibleToPlayer = 0x00000020, + NotVisibleToPlayer = 0x00000040, + ReportFailures = 0x00000080, + InViewcone = 0x00000100, + InAimcone = 0x00000200, + NPCInNodeFOV = 0x00000400, + NotCloseToEnemy = 0x00000800, + HasLOSToPlayer = 0x00001000, + HasEyePositionLOSToPlayer = 0x00002000, +} + +public class HintCriteria +{ + struct HintZone + { + public Vector3 Position; + public float RadiusSqr; + } + + readonly List HintTypes = []; + + AI_HintNodeFlags Flags; + Hint FirstHintType; + Hint LastHintType; + string? Group; + + readonly List ZoneInclude = []; + readonly List ZoneExclude = []; + + public HintCriteria() { + FirstHintType = Hint.None; + LastHintType = Hint.None; + Group = null; + Flags = 0; + HintTypes.Clear(); + } + + public bool HasFlag(AI_HintNodeFlags bitmask) => (Flags & bitmask) != 0; + + public void SetHintType(Hint hintType) { + FirstHintType = hintType; + LastHintType = Hint.None; + HintTypes.Clear(); + } + + public void AddHintType(Hint hintType) => HintTypes.Add(hintType); + + public int NumHintTypes() => HintTypes.Count; + + public Hint GetHintType(int idx) => HintTypes[idx]; + + public Hint GetFirstHintType() => FirstHintType; + public Hint GetLastHintType() => LastHintType; + + public bool MatchesSingleHintType() { + if (HintTypes.Count != 0) + return false; + + if (FirstHintType != Hint.Any && LastHintType == Hint.None) + return true; + + return false; + } + + public bool MatchesHintType(Hint hintType) { + int c = HintTypes.Count; + for (int i = 0; i < c; ++i) { + if (HintTypes[i] == hintType) + return true; + } + + if (GetFirstHintType() != Hint.Any) { + if (GetLastHintType() == Hint.None) { + if (GetFirstHintType() != hintType) + return false; + } + else { + if (hintType < GetFirstHintType() || hintType > GetLastHintType()) + return false; + } + + return true; + } + + return false; + } + + public void SetHintTypeRange(Hint firstType, Hint lastType) { + if (lastType < firstType) { + DevMsg(2, "Hint Type Range is backwards - Fixing up.\n"); + + (lastType, firstType) = (firstType, lastType); + } + + FirstHintType = firstType; + LastHintType = lastType; + HintTypes.Clear(); + } + + public void SetFlag(AI_HintNodeFlags bitmask) => Flags |= bitmask; + + public void ClearFlag(AI_HintNodeFlags bitmask) => Flags &= ~bitmask; + + public void SetGroup(string? group) => Group = group; + public string? GetGroup() => Group; + + public bool HasIncludeZones() => ZoneInclude.Count != 0; + public bool HasExcludeZones() => ZoneExclude.Count != 0; + + static void AddZone(List list, in Vector3 position, float radius) { + list.Add(new HintZone { + Position = position, + RadiusSqr = radius * radius + }); + } + + public void AddIncludePosition(in Vector3 position, float radius) => AddZone(ZoneInclude, position, radius); + + public void AddExcludePosition(in Vector3 position, float radius) => AddZone(ZoneExclude, position, radius); + + static bool InZone(List zone, in Vector3 testPosition) { + int numZones = zone.Count; + + for (int i = 0; i < numZones; i++) { + if ((zone[i].Position - testPosition).LengthSquared() < zone[i].RadiusSqr) + return true; + } + + return false; + } + + public bool InIncludedZone(in Vector3 testPosition) => InZone(ZoneInclude, testPosition); + + public bool InExcludedZone(in Vector3 testPosition) => InZone(ZoneExclude, testPosition); +} + +[LinkEntityToClass("ai_hint")] public class AI_Hint : ServerOnlyEntity { public const int SF_ALLOW_JUMP_UP = 65536; - public Hint HintType() => throw new NotImplementedException(); - public string? GetGroup() => throw new NotImplementedException(); - public int GetTargetNode() => throw new NotImplementedException(); - public void Unlock(float delay) => throw new NotImplementedException(); -} + public static readonly new DataMap DataDesc = new(typeof(AI_Hint), BaseEntity.DataDesc, [ + DEFINE.EMBEDDED(nameof(NodeData)), -[Flags] -public enum AI_HintNodeFlags { - None = 0x00000000, - Visible = 0x00000001, - Nearest = 0x00000002, - Random = 0x00000004 + DEFINE.FIELD(nameof(HintOwner), FieldType.EHandle), + DEFINE.FIELD(nameof(NextUseTime), FieldType.Time), + DEFINE.FIELD(nameof(Forward), FieldType.Vector), + DEFINE.KEYFIELD(nameof(NodeFOV), FieldType.Float, "nodeFOV"), + + DEFINE.INPUTFUNC(FieldType.Void, "EnableHint", nameof(InputEnableHint), (INPUTFUNCPTR)((self, data) => ((AI_Hint)self).InputEnableHint(data))), + DEFINE.INPUTFUNC(FieldType.Void, "DisableHint", nameof(InputDisableHint), (INPUTFUNCPTR)((self, data) => ((AI_Hint)self).InputDisableHint(data))), + + DEFINE.OUTPUT(nameof(OnNPCStartedUsing), "OnNPCStartedUsing", eventFuncs), + DEFINE.OUTPUT(nameof(OnNPCStoppedUsing), "OnNPCStoppedUsing", eventFuncs), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public HintNodeData NodeData = new(); + int TargetNodeID; + EHANDLE HintOwner = new(); + TimeUnit_t NextUseTime; + readonly OutputEHANDLE OnNPCStartedUsing = new(); + readonly OutputEHANDLE OnNPCStoppedUsing = new(); + float NodeFOV; + Vector3 Forward; + + public AI_Hint() { + NextUseTime = 0; + TargetNodeID = NO_NODE; + } + + public string? GetGroup() => NodeData.Group; + public BaseEntity? User() => HintOwner.Get(); + public Hint HintType() => (Hint)NodeData.HintType; + public string? HintActivityName() => NodeData.ActivityName; + public int GetTargetNode() => TargetNodeID; + public bool IsDisabled() => NodeData.Disabled != 0; + public void SetDisabled(bool disabled) => NodeData.Disabled = disabled ? 1 : 0; + public HintIgnoreFacing GetIgnoreFacing() => NodeData.IgnoreFacing; + public NPCState GetMinState() => NodeData.MinState; + public NPCState GetMaxState() => NodeData.MaxState; + public int GetNodeId() => NodeData.NodeID; + public int GetWCId() => NodeData.WCNodeID; + + public override EntityCapabilities ObjectCaps() => base.ObjectCaps() & ~EntityCapabilities.AcrossTransition; + + public void SetHintType(Hint hintType, bool force = false) { + if (!force && (short)hintType == NodeData.HintType) + return; + + AI_HintManager.RemoveHintByType(this); + NodeData.HintType = (short)hintType; + AI_HintManager.AddHintByType(this); + } + + void InputEnableHint(InputData inputdata) => NodeData.Disabled = 0; + + void InputDisableHint(InputData inputdata) => NodeData.Disabled = 1; + + public override void Spawn() { + GetVectors(out Forward, out _, out _); + + if (NodeFOV != 360) + NodeFOV = MathF.Cos(MathLib.DEG2RAD(NodeFOV / 2)); + + SetSolid(SolidType.None); + } + + public override void Activate() { + base.Activate(); + AI_HintManager.AddHint(this); + } + + public override void UpdateOnRemove() { + AI_HintManager.RemoveHint(this); + base.UpdateOnRemove(); + } + + public void GetPosition(BaseCombatCharacter? bcc, out Vector3 position) { + if (NodeData.NodeID != NO_NODE) + position = g_pBigAINet!.GetNodePosition(bcc, NodeData.NodeID); + else + position = GetAbsOrigin(); + } + + public void GetPosition(AI_HullType hull, out Vector3 position) { + if (NodeData.NodeID != NO_NODE) + position = g_pBigAINet!.GetNodePosition(hull, NodeData.NodeID); + else + position = GetAbsOrigin(); + } + + public Vector3 GetDirection() => Util.YawToVector(Yaw()); + + public float Yaw() { + if (NodeData.NodeID != NO_NODE) + return g_pBigAINet!.GetNodeYaw(NodeData.NodeID); + else + return GetLocalAngles().Y; + } + + bool IsViewable() { + if (NodeData.Disabled != 0) + return false; + + switch (HintType()) { + case Hint.WorldVisuallyInteresting: + case Hint.WorldVisuallyInterestingDontAim: + case Hint.WorldVisuallyInterestingStealth: + return true; + } + + return false; + } + + public bool IsInNodeFOV(BaseEntity other) { + if (NodeFOV == 360) + return true; + + Vector3 vecToNPC = other.GetAbsOrigin() - GetAbsOrigin(); + MathLib.VectorNormalize(ref vecToNPC); + float dot = Vector3.Dot(vecToNPC, Forward); + + if (dot > NodeFOV) + return true; + + return false; + } + + public bool Lock(BaseEntity? npc) { + if (HintOwner.Get() != npc && HintOwner.Get() != null) + return false; + HintOwner.Set(npc); + return true; + } + + public void Unlock(float delay = 0.0f) { + HintOwner.Set(null); + NextUseTime = gpGlobals.CurTime + delay; + } + + public bool IsLockedBy(BaseEntity? npc) => HintOwner.Get() == npc; + + public bool IsLocked() { + if (NodeData.Disabled != 0) + return true; + + if (gpGlobals.CurTime < NextUseTime) + return true; + + if (HintOwner.Get() != null) + return true; + return false; + } + + public bool HintMatchesCriteria(AI_BaseNPC? npc, HintCriteria hintCriteria, in Vector3 position, ref float nearestDistance, bool ignoreLock = false, bool ignoreHintType = false) { + if (!ignoreLock && IsLocked()) + return false; + + if (!ignoreHintType && !hintCriteria.MatchesHintType(HintType())) + return false; + + if (GetMinState() > NPCState.Idle || GetMaxState() < NPCState.Combat) { + if (npc != null && (npc.GetState() < GetMinState() || npc.GetState() > GetMaxState())) + return false; + } + + if (hintCriteria.GetGroup() != null) { + if (GetGroup() == null || GetGroup() != hintCriteria.GetGroup()) + return false; + } + + if (hintCriteria.HasIncludeZones() && hintCriteria.InIncludedZone(GetAbsOrigin()) == false) + return false; + + if (hintCriteria.HasExcludeZones() && hintCriteria.InExcludedZone(GetAbsOrigin())) + return false; + + if (npc != null && npc.FValidateHintType(this) == false) + return false; + + if (hintCriteria.HasFlag(AI_HintNodeFlags.NPCInNodeFOV)) { + if (npc == null) + AssertMsg(false, "Hint node attempted to verify NPC in node FOV without NPC!\n"); + else { + if (!IsInNodeFOV(npc)) + return false; + } + } + + if (hintCriteria.HasFlag(AI_HintNodeFlags.InAimcone)) { + if (npc == null) + AssertMsg(false, "Hint node attempted to find node in aimcone without specifying NPC!\n"); + else { + if (!npc.FInAimCone(GetAbsOrigin())) + return false; + } + } + + if (hintCriteria.HasFlag(AI_HintNodeFlags.InViewcone)) { + if (npc == null) + AssertMsg(false, "Hint node attempted to find node in viewcone without specifying NPC!\n"); + else { + if (!npc.FInViewCone(this)) + return false; + } + } + + if (hintCriteria.HasFlag(AI_HintNodeFlags.NotCloseToEnemy)) { + if (npc == null) + AssertMsg(false, "Hint node attempted to find node not close to enemy without specifying NPC!\n"); + else { + if (npc.GetEnemy() != null) { + float distHintToEnemySqr = Vector3.DistanceSquared(GetAbsOrigin(), npc.GetEnemy()!.GetAbsOrigin()); + + if (distHintToEnemySqr < (30.0f * 12.0f) * (30.0f * 12.0f)) + return false; + } + } + } + + { + if (hintCriteria.HasFlag(AI_HintNodeFlags.Visible)) { + if (npc == null) + AssertMsg(false, "Hint node attempted to find visible node without specifying NPC!\n"); + else { + if (NodeData.NodeID == NO_NODE) { + if (!npc.FVisible(this)) + return false; + } + else { + GetPosition(npc, out Vector3 hintPos); + Util.TraceLine(npc.EyePosition(), hintPos + npc.GetViewOffset(), Mask.NPCSolidBrushOnly, npc, Source.CollisionGroup.None, out Trace tr); + if (tr.Fraction != 1.0f) + return false; + } + } + } + } + + if (hintCriteria.HasFlag(AI_HintNodeFlags.Clear)) { + if (npc == null) + AssertMsg(false, "Hint node attempted to find clear node without specifying NPC!\n"); + else { + Util.TraceHull(GetAbsOrigin(), GetAbsOrigin(), npc.WorldAlignMins(), npc.WorldAlignMaxs(), + Mask.Solid, npc, Source.CollisionGroup.None, out Trace tr); + + if (tr.Fraction != 1.0) + return false; + } + } + + if (hintCriteria.HasFlag(AI_HintNodeFlags.Nearest)) { + float distance = (GetAbsOrigin() - position).Length(); + + if (distance > nearestDistance) + return false; + + nearestDistance = distance; + } + + if (hintCriteria.HasFlag(AI_HintNodeFlags.HasLOSToPlayer | AI_HintNodeFlags.HasEyePositionLOSToPlayer)) { + BasePlayer? player = AI_GetClosestPlayer(); + if (player != null) { + Vector3 dest = GetAbsOrigin(); + + if (hintCriteria.HasFlag(AI_HintNodeFlags.HasEyePositionLOSToPlayer)) + dest += npc!.DefaultEyeOffset; + + if (!player.FVisible(dest)) + return false; + } + } + + if (hintCriteria.HasFlag(AI_HintNodeFlags.NotVisibleToPlayer | AI_HintNodeFlags.VisibleToPlayer)) { + bool wasSeen = false; + for (int i = 1; i <= gpGlobals.MaxClients; i++) { + BasePlayer? player = Util.PlayerByIndex(i); + + if (player != null) { + Vector3 lookDir = player.EyeDirection3D(); + Vector3 targetDir = GetAbsOrigin() - player.EyePosition(); + MathLib.VectorNormalize(ref targetDir); + + float dotPr = Vector3.Dot(lookDir, targetDir); + if (dotPr > 0) { + Util.TraceLine(player.EyePosition(), GetAbsOrigin(), Mask.SolidBrushOnly, player, Source.CollisionGroup.None, out Trace tr); + + if (tr.Fraction == 1.0) { + if (hintCriteria.HasFlag(AI_HintNodeFlags.NotVisibleToPlayer)) + return false; + wasSeen = true; + } + } + } + } + + if (!wasSeen && hintCriteria.HasFlag(AI_HintNodeFlags.VisibleToPlayer)) + return false; + } + + return true; + } + + public AI_Node? GetNode() { + if (NodeData.NodeID != NO_NODE) + return g_pBigAINet!.GetNode(NodeData.NodeID, false); + return null; + } + + public void DisableForSeconds(float seconds) => Unlock(seconds); + + public void EnableThink() { + SetDisabled(false); + SetThink(null); + } + + public void FixupTargetNode() { + if (NodeData.TargetWCNodeID != -1) + TargetNodeID = g_pAINetworkManager!.GetEditOps().GetNodeIdFromWCId(NodeData.TargetWCNodeID); + else + TargetNodeID = NO_NODE; + } + + public override void OnRestore() { + base.OnRestore(); + + NodeData.NodeID = g_pAINetworkManager!.GetEditOps().GetNodeIdFromWCId(NodeData.WCNodeID); + FixupTargetNode(); + + AI_Node? node = GetNode(); + + if (node == null) { + if (NodeData.WCNodeID > 0) + DevMsg("Warning: AI hint has incorrect or no AI node\n"); + } + else { + NodeData.Position = node.GetOrigin(); + Teleport(NodeData.Position, null, null); + node.SetHint(this); + } + } + + public void NPCStartedUsing(AI_BaseNPC npc) { + EHANDLE hNPC = new(); + hNPC.Set(npc); + OnNPCStartedUsing.Set(hNPC, npc, this); + } + + public void NPCStoppedUsing(AI_BaseNPC npc) { + EHANDLE hNPC = new(); + hNPC.Set(npc); + OnNPCStoppedUsing.Set(hNPC, npc, this); + } } public static class AI_HintManager { + const int HINT_HISTORY = 1 << 3; + const int HINT_HISTORY_MASK = HINT_HISTORY - 1; + + static int gm_nFoundHintIndex = 0; + static readonly AI_Hint?[] gm_pLastFoundHints = new AI_Hint?[HINT_HISTORY]; + static readonly List gm_AllHints = []; + static readonly SortedDictionary> gm_TypedHints = []; + + static AI_Hint? AddFoundHint(AI_Hint? hint) { + if (hint != null) { + gm_nFoundHintIndex = (gm_nFoundHintIndex + 1) & HINT_HISTORY_MASK; + gm_pLastFoundHints[gm_nFoundHintIndex] = hint; + } + return hint; + } + + static int GetFoundHintCount() => HINT_HISTORY; + + static AI_Hint? GetFoundHint(int index) => gm_pLastFoundHints[(gm_nFoundHintIndex + index) & HINT_HISTORY_MASK]; + + static AI_Hint? GetLastFoundHint() { + for (int i = 0; i < HINT_HISTORY; ++i) { + int slot = (gm_nFoundHintIndex - i) & HINT_HISTORY_MASK; + if (gm_pLastFoundHints[slot] != null) + return gm_pLastFoundHints[slot]; + } + return null; + } + + static void ResetFoundHints() { + Array.Clear(gm_pLastFoundHints); + gm_nFoundHintIndex = 0; + } + + static bool IsInFoundHintList(AI_Hint hint) { + for (int i = 0; i < HINT_HISTORY; ++i) { + if (gm_pLastFoundHints[i] == hint) + return true; + } + return false; + } + + public static int FindAllHints(AI_BaseNPC? npc, in Vector3 position, HintCriteria hintCriteria, List result) { + int c = gm_AllHints.Count; + if (c == 0) + return 0; + + bool hadNearest = hintCriteria.HasFlag(AI_HintNodeFlags.Nearest); + hintCriteria.ClearFlag(AI_HintNodeFlags.Nearest); + + AI_Hint testHint; + float unused = 0; + for (int i = 0; i < c; ++i) { + testHint = gm_AllHints[i]; + Assert(testHint != null); + if (testHint!.HintMatchesCriteria(npc, hintCriteria, position, ref unused)) + result.Add(testHint); + } + + if (hadNearest) + hintCriteria.SetFlag(AI_HintNodeFlags.Nearest); + + return result.Count; + } + + public static int FindAllHints(in Vector3 position, HintCriteria hintCriteria, List result) => FindAllHints(null, position, hintCriteria, result); + public static int FindAllHints(AI_BaseNPC npc, HintCriteria hintCriteria, List result) => FindAllHints(npc, npc.GetAbsOrigin(), hintCriteria, result); + + public static AI_Hint? FindHintRandom(AI_BaseNPC? npc, in Vector3 position, HintCriteria hintCriteria) { + List hintList = []; + + if (FindAllHints(npc, position, hintCriteria, hintList) > 0) + return AddFoundHint(hintList[random.RandomInt(0, hintList.Count - 1)]); + + ResetFoundHints(); + return null; + } + + public static AI_Hint? FindHint(AI_BaseNPC? npc, in Vector3 position, HintCriteria hintCriteria) { + bool singleType = hintCriteria.MatchesSingleHintType(); + bool lookingForNearest = hintCriteria.HasFlag(AI_HintNodeFlags.Nearest); + bool ignoreHintType = true; + + List> lists = []; + if (singleType) { + if (gm_TypedHints.TryGetValue(hintCriteria.GetFirstHintType(), out List? typed)) + lists.Add(typed); + } + else { + int typeCount = hintCriteria.NumHintTypes(); + if (typeCount > 0) { + for (int listType = 0; listType < typeCount; ++listType) { + if (gm_TypedHints.TryGetValue(hintCriteria.GetHintType(listType), out List? typed)) + lists.Add(typed); + } + } + else { + lists.Add(gm_AllHints); + ignoreHintType = false; + } + } + + AI_Hint? bestHint = null; + + int listCount = lists.Count; + + if (listCount == 0) + return null; + + int i, count; + AI_Hint? testHint; + + float bestDistance = MAX_TRACE_LENGTH; + + if (!lookingForNearest) { + count = GetFoundHintCount(); + for (i = 0; i < count; ++i) { + testHint = GetFoundHint(i); + if (testHint != null) { + if (testHint.HintMatchesCriteria(npc, hintCriteria, position, ref bestDistance)) + return testHint; + } + } + } + + bestDistance = MAX_TRACE_LENGTH; + + for (int listNum = 0; listNum < listCount; ++listNum) { + List list = lists[listNum]; + count = list.Count; + if (count == 0) + continue; + + for (i = 0; i < count; ++i) { + testHint = list[i]; + Assert(testHint != null); + + if (testHint!.HintMatchesCriteria(npc, hintCriteria, position, ref bestDistance, false, ignoreHintType)) { + if (lookingForNearest) + bestHint = testHint; + else { + AddFoundHint(testHint); + return testHint; + } + } + } + } + + if (bestHint != null) + AddFoundHint(bestHint); + + return bestHint; + } + + public static AI_Hint? FindHint(AI_BaseNPC? npc, Hint hintType, AI_HintNodeFlags flags, float maxDist, Vector3? maxDistFrom = null) { + Assert(npc != null); + if (npc == null) + return null; + + HintCriteria hintCriteria = new(); + hintCriteria.SetHintType(hintType); + hintCriteria.SetFlag(flags); + + if ((flags & AI_HintNodeFlags.UseGroup) != 0) + hintCriteria.SetGroup(npc.GetHintGroup()); + + Vector3 position = maxDistFrom ?? npc.GetAbsOrigin(); + hintCriteria.AddIncludePosition(position, maxDist); + + if ((flags & AI_HintNodeFlags.Random) != 0) + return FindHintRandom(npc, position, hintCriteria); + + return FindHint(npc, position, hintCriteria); + } + + public static AI_Hint? FindHint(in Vector3 position, HintCriteria hintCriteria) => FindHint(null, position, hintCriteria); + + public static AI_Hint? FindHint(AI_BaseNPC? npc, HintCriteria hintCriteria) { + Assert(npc != null); + if (npc == null) + return null; + + return FindHint(npc, npc.GetAbsOrigin(), hintCriteria); + } + + public static AI_Hint? CreateHint(HintNodeData nodeData, ReadOnlyMemory? mapData = null) { + ResetFoundHints(); + + AI_Hint? hint = (AI_Hint?)CreateEntityByName("ai_hint"); + if (hint != null) { + if (mapData != null) { + EntityMapData entData = new(mapData.Value); + hint.ParseMapData(entData); + + hint.SetClassname("ai_hint"); + } + + hint.SetName(nodeData.EntityName); + hint.SetAbsOrigin(nodeData.Position); + hint.NodeData = nodeData.Copy(); + Util.DispatchSpawn(hint); + + return hint; + } + + return null; + } + + public static void AddHint(AI_Hint hint) { + gm_AllHints.Add(hint); + AddHintByType(hint); + } + + public static void AddHintByType(AI_Hint hint) { + Hint type = hint.HintType(); + + if (!gm_TypedHints.TryGetValue(type, out List? list)) { + list = []; + gm_TypedHints[type] = list; + } + list.Add(hint); + } + + public static void RemoveHintByType(AI_Hint hintToRemove) { + if (gm_TypedHints.TryGetValue(hintToRemove.HintType(), out List? list)) + list.Remove(hintToRemove); + } + + public static void RemoveHint(AI_Hint hintToRemove) { + gm_AllHints.Remove(hintToRemove); + RemoveHintByType(hintToRemove); + + if (IsInFoundHintList(hintToRemove)) + ResetFoundHints(); + } + public static AI_HintNodeFlags GetFlags(ReadOnlySpan token) { if (token.Length <= 0) return AI_HintNodeFlags.None; @@ -122,4 +857,43 @@ public static AI_HintNodeFlags GetFlags(ReadOnlySpan token) { return bits; } + + public static AI_Hint? GetFirstHint(out int iter) { + if (gm_AllHints.Count == 0) { + iter = -1; + return null; + } + iter = 0; + return gm_AllHints[0]; + } + + public static AI_Hint? GetNextHint(ref int iter) { + if (iter != -1) { + int i = iter + 1; + if (gm_AllHints.Count <= i) { + iter = -1; + return null; + } + iter = i; + return gm_AllHints[i]; + } + return null; + } + + public static void DumpHints() { + AI_Hint? curHint = GetFirstHint(out int iter); + while (curHint != null) { + Vector3 v = curHint.GetAbsOrigin(); + Msg($"({v.X:F1}, {v.Y:F1}, {v.Z:F1}) -- Node ID: {curHint.GetNodeId()}; WC id {curHint.GetWCId()}; type {(int)curHint.HintType()}\n"); + curHint = GetNextHint(ref iter); + } + } + + [ConCommand("ai_dump_hints", "")] + public static void ai_dump_hints(in TokenizedCommand args) { + if (!Util.IsCommandIssuedByServerAdmin()) + return; + + DumpHints(); + } } diff --git a/Game.Server/AI_InitUtils.cs b/Game.Server/AI_InitUtils.cs index 9c18c2a26..8f519dd97 100644 --- a/Game.Server/AI_InitUtils.cs +++ b/Game.Server/AI_InitUtils.cs @@ -43,6 +43,8 @@ public class HintNodeData public NPCState MaxState; public int WCNodeID; + + public HintNodeData Copy() => (HintNodeData)MemberwiseClone(); } [LinkEntityToClass("info_hint")] @@ -62,7 +64,9 @@ public class NodeEnt : ServerOnlyPointEntity public HintNodeData NodeData = new(); - public override void Spawn() { + public override void Spawn() => Spawn(null); + + public int Spawn(ReadOnlyMemory? mapData) { NodeData.EntityName = GetEntityName(); NodeData.Position = GetAbsOrigin(); NodeData.NodeID = NO_NODE; @@ -72,21 +76,41 @@ public override void Spawn() { NodeData.MaxState = NPCState.Combat; if (FClassnameIs(this, "info_hint")) { - if (NodeData.HintType == 0) + if (NodeData.HintType != 0) + AI_HintManager.CreateHint(NodeData, mapData); + else Warning($"info_hint (HammerID: {NodeData.WCNodeID}, position ({NodeData.Position.X:0.00}, {NodeData.Position.Y:0.00}, {NodeData.Position.Z:0.00})) with no hint type.\n"); Util.RemoveImmediate(this); - return; + return -1; + } + + AI_Hint? hint = null; + + if (ClassMatches("info_node_hint") || ClassMatches("info_node_air_hint")) { + if (NodeData.HintType != 0 || NodeData.Group != null || NodeData.EntityName != null) { + NodeData.NodeID = NodeCount; + hint = AI_HintManager.CreateHint(NodeData, mapData); + hint!.AddSpawnFlags(SpawnFlags); + } } if (AI_NetworkManager.NetworksLoaded()) { + if (hint != null) { + AI_Node? node = g_pBigAINet!.GetNode(NodeCount); + if (node != null) + node.SetHint(hint); + else + DevMsg("AI node graph corrupt\n"); + } NodeCount++; Util.RemoveImmediate(this); - return; + return -1; } else NodeCount++; AI_Node newNode = g_pBigAINet!.AddNode(GetAbsOrigin(), GetAbsAngles().Y); + newNode.SetHint(hint); AI_NetworkEditTools editOps = g_pAINetworkManager!.GetEditOps(); if (editOps.NodeIndexTable != null) @@ -104,5 +128,7 @@ public override void Spawn() { newNode.NodeInfo = (NodeInfoBits)(SpawnFlags << AI_Node.NODE_ENT_FLAGS_SHIFT); Util.RemoveImmediate(this); + + return -1; } } diff --git a/Game.Server/MapEntities.cs b/Game.Server/MapEntities.cs index 522a06749..c85dce55d 100644 --- a/Game.Server/MapEntities.cs +++ b/Game.Server/MapEntities.cs @@ -136,11 +136,11 @@ public static void MapEntity_ParseAllEntities(ReadOnlyMemory mapData, IMap // dispatch their spawn now to free up the edict slot inside this loop. Those entity // classes are not ported yet, so they fall through to the regular queue for now. - // if (entity is NodeEnt ne) { - // if (ne.Spawn(curMapData) < 0) - // gEntList.CleanupDeleteList(); - // continue; - // } + if (entity is NodeEnt ne) { + if (ne.Spawn(curMapData) < 0) + gEntList.CleanupDeleteList(); + continue; + } // if (entity is Light light) { // if (Util.DispatchSpawn(light) < 0) From 759a48d7ee5e9774a992fe0107444696b76acfb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 14:39:58 +0300 Subject: [PATCH 49/73] Port AI goal entity base class --- Game.Server/AI_GoalEntity.cs | 265 +++++++++++++++++++++++++++++++++++ 1 file changed, 265 insertions(+) create mode 100644 Game.Server/AI_GoalEntity.cs diff --git a/Game.Server/AI_GoalEntity.cs b/Game.Server/AI_GoalEntity.cs new file mode 100644 index 000000000..0023dda34 --- /dev/null +++ b/Game.Server/AI_GoalEntity.cs @@ -0,0 +1,265 @@ +using Game.Shared; + +using Source; +using Source.Common; + +using DEFINE = Source.DEFINE; + +namespace Game.Server; + +public class AI_GoalEntity : BaseEntity, IEntityListener +{ + [Flags] + enum GoalFlags + { + Active = 0x01, + ResolvedName = 0x02, + Dormant = 0x04, + } + + enum SearchType + { + EntName, + ClassName, + } + + public static readonly new DataMap DataDesc = new(typeof(AI_GoalEntity), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(Actor), FieldType.String, "Actor"), + DEFINE.KEYFIELD(nameof(Goal), FieldType.String, "Goal"), + DEFINE.KEYFIELD(nameof(StartActive), FieldType.Boolean, "StartActive"), + DEFINE.KEYFIELD(nameof(ConceptModifiers), FieldType.String, "BaseConceptModifiers"), + DEFINE.KEYFIELD(nameof(Search), FieldType.Integer, "SearchType"), + DEFINE.UTLVECTOR(nameof(Actors), FieldType.EHandle), + DEFINE.FIELD(nameof(GoalEntity), FieldType.EHandle), + DEFINE.FIELD(nameof(Flags), FieldType.Integer), + + DEFINE.INPUTFUNC(FieldType.Void, "Activate", nameof(InputActivate), (INPUTFUNCPTR)((self, data) => ((AI_GoalEntity)self).InputActivate(data))), + DEFINE.INPUTFUNC(FieldType.Void, "UpdateActors", nameof(InputUpdateActors), (INPUTFUNCPTR)((self, data) => ((AI_GoalEntity)self).InputUpdateActors(data))), + DEFINE.INPUTFUNC(FieldType.Void, "Deactivate", nameof(InputDeactivate), (INPUTFUNCPTR)((self, data) => ((AI_GoalEntity)self).InputDeactivate(data))), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + string? Actor; + string? Goal; + bool StartActive; + SearchType Search; + string? ConceptModifiers; + + readonly List> Actors = []; + EHANDLE GoalEntity = new(); + GoalFlags Flags; + + public AI_GoalEntity() { + Actor = null; + Goal = null; + StartActive = false; + Search = SearchType.EntName; + ConceptModifiers = null; + GoalEntity.Set(null); + Flags = 0; + } + + public override EntityCapabilities ObjectCaps() => (base.ObjectCaps() & ~EntityCapabilities.AcrossTransition) | EntityCapabilities.NotifyOnTransition; + + public override void Spawn() { + SetThink(DelayedRefresh); + SetNextThink(gpGlobals.CurTime + 0.1f); + } + + public override void OnRestore() { + base.OnRestore(); + + ExitDormant(); + + if ((Flags & GoalFlags.Active) != 0) + gEntList.AddListenerEntity(this); + } + + void DelayedRefresh() { + InputData ignored = default; + if (StartActive) { + Assert((Flags & GoalFlags.Active) == 0); + InputActivate(ignored); + StartActive = false; + } + else + InputUpdateActors(ignored); + + SetThink(null); + } + + void PruneActors() { + for (int i = Actors.Count - 1; i >= 0; i--) { + AI_BaseNPC? actor = Actors[i].Get(); + if (actor == null || actor.IsMarkedForDeletion() || actor.GetState() == NPCState.Dead) { + Actors[i] = Actors[^1]; + Actors.RemoveAt(Actors.Count - 1); + } + } + } + + void ResolveNames() { + Actors.Clear(); + + BaseEntity? entity = null; + for (; ; ) { + switch (Search) { + case SearchType.EntName: + entity = gEntList.FindEntityByName(entity, Actor); + break; + + case SearchType.ClassName: + entity = gEntList.FindEntityByClassname(entity, Actor); + break; + } + + if (entity == null) + break; + + AI_BaseNPC? actor = entity.MyNPCPointer(); + + if (actor != null && actor.GetState() != NPCState.Dead) { + Handle temp = new(); + temp.Set(actor); + Actors.Add(temp); + } + } + + GoalEntity.Set(gEntList.FindEntityByName(null, Goal)); + } + + protected void UpdateActors() { + if ((Flags & GoalFlags.Active) == 0 || (Flags & GoalFlags.ResolvedName) == 0) { + ResolveNames(); + Flags |= GoalFlags.ResolvedName; + } + else + PruneActors(); + } + + public bool IsActive() { + if ((Flags & GoalFlags.Active) != 0) { + UpdateActors(); + return Actors.Count != 0; + } + return false; + } + + public int NumActors() { + UpdateActors(); + return Actors.Count; + } + + public AI_BaseNPC? GetActor(int actor = 0) { + UpdateActors(); + if (Actors.Count > actor) + return Actors[actor].Get(); + return null; + } + + public void SetGoalEntity(BaseEntity goalEntity) { + Goal = goalEntity.GetEntityName(); + GoalEntity.Set(goalEntity); + } + + public BaseEntity? GetGoalEntity() { + UpdateActors(); + return GoalEntity.Get(); + } + + public string? GetGoalEntityName() => Goal; + + public string? GetConceptModifiers() => ConceptModifiers; + + protected List> AccessActors() => Actors; + + protected virtual void EnableGoal(AI_BaseNPC? ai) { } + protected virtual void DisableGoal(AI_BaseNPC? ai) { } + + public virtual void InputActivate(InputData inputdata) { + if ((Flags & GoalFlags.Active) == 0) { + gEntList.AddListenerEntity(this); + + UpdateActors(); + Flags |= GoalFlags.Active; + + for (int i = 0; i < Actors.Count; i++) + EnableGoal(Actors[i].Get()); + } + } + + public virtual void InputUpdateActors(InputData inputdata) { + int i; + HashSet prevActors = []; + + PruneActors(); + + for (i = 0; i < Actors.Count; i++) + prevActors.Add(Actors[i].Get()); + + ResolveNames(); + + for (i = 0; i < Actors.Count; i++) { + if (!prevActors.Contains(Actors[i].Get())) { + if ((Flags & GoalFlags.Active) != 0) + EnableGoal(Actors[i].Get()); + } + else + prevActors.Remove(Actors[i].Get()); + } + + foreach (AI_BaseNPC? prev in prevActors) { + if ((Flags & GoalFlags.Active) != 0) + DisableGoal(prev); + } + } + + public virtual void InputDeactivate(InputData inputdata) { + if ((Flags & GoalFlags.Active) != 0) { + gEntList.RemoveListenerEntity(this); + UpdateActors(); + Flags &= ~GoalFlags.Active; + + for (int i = 0; i < Actors.Count; i++) + DisableGoal(Actors[i].Get()); + } + } + + public void EnterDormant() { + if ((Flags & GoalFlags.Active) != 0) { + Flags |= GoalFlags.Dormant; + for (int i = 0; i < Actors.Count; i++) + DisableGoal(Actors[i].Get()); + } + } + + public void ExitDormant() { + if ((Flags & GoalFlags.Dormant) != 0) { + Flags &= ~GoalFlags.Dormant; + + InputData ignored = default; + InputUpdateActors(ignored); + } + } + + public override void UpdateOnRemove() { + if ((Flags & GoalFlags.Active) != 0) { + InputData inputdata = default; + InputDeactivate(inputdata); + } + base.UpdateOnRemove(); + } + + public virtual void OnEntityCreated(BaseEntity entity) { + Assert((Flags & GoalFlags.Active) != 0); + + if (entity.MyNPCPointer() != null) { + SetThink(DelayedRefresh); + SetNextThink(gpGlobals.CurTime + 0.1f); + } + } + + public virtual void OnEntityDeleted(BaseEntity entity) { + Assert(entity != this); + } +} From 8200a4b3d0ba395249de10413629591932223250 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:51:24 +0300 Subject: [PATCH 50/73] Port act busy behavior and ai_goal_actbusy --- Game.Server/AI_ActBusyBehavior.cs | 1788 +++++++++++++++++++++ Game.Server/AI_BaseNPC.cs | 41 + Game.Server/AI_BehaviorBase.cs | 68 + Game.Server/AI_BehaviorHost_AI_BaseNPC.cs | 68 + Game.Server/AI_Expresser.cs | 4 + Game.Server/AI_PlayerAlly.cs | 2 + Game.Server/EntityBlocker.cs | 32 + Game.Server/IBehaviorBackBridge.cs | 7 + Game.Server/NPC_MetroPolice.cs | 3 + Game.Shared/UtilShared.cs | 18 + 10 files changed, 2031 insertions(+) create mode 100644 Game.Server/AI_ActBusyBehavior.cs create mode 100644 Game.Server/EntityBlocker.cs diff --git a/Game.Server/AI_ActBusyBehavior.cs b/Game.Server/AI_ActBusyBehavior.cs new file mode 100644 index 000000000..ce76c92d5 --- /dev/null +++ b/Game.Server/AI_ActBusyBehavior.cs @@ -0,0 +1,1788 @@ +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Formats.BSP; +using Source.Common.Formats.Keyvalues; +using Source.Common.Mathematics; +using Source.Common.SoundEmitterSystem; + +using System.Numerics; + +using DEFINE = Source.DEFINE; + +using static Game.Server.SCOND_t; + +namespace Game.Server; + +public enum ActBusyType +{ + Default = 0, + Combat, +} + +public enum BusyInterrupt +{ + None, + Danger, + Player, + Ambush, + Combat, + ZombieSlump, + SiegeDefense, +} + +public enum BusyAnimParts +{ + Busy, + Entry, + Exit, + + MaxAnims, +} + +public class BusyAnim +{ + public string? Name; + public readonly Activity[] Activities = new Activity[(int)BusyAnimParts.MaxAnims]; + public readonly string?[] Sequences = new string?[(int)BusyAnimParts.MaxAnims]; + public readonly string?[] Sounds = new string?[(int)BusyAnimParts.MaxAnims]; + public float MinTime; + public float MaxTime; + public BusyInterrupt BusyInterruptType; + public bool UseAutomovement; +} + +public struct BusySafeZone +{ + public Vector3 Mins; + public Vector3 Maxs; +} + +public enum ActBusySightMethod +{ + Full = 0, + LOSOnly, +} + +public class ActBusyAnimData() : AutoGameSystem("CActBusyAnimData") +{ + public static readonly ActBusyAnimData g_ActBusyAnimDataSystem = new(); + + readonly List ActBusyAnims = []; + + public override void LevelInitPostEntity() => ParseAnimDataFile(); + + public override void LevelShutdownPostEntity() => ActBusyAnims.Clear(); + + public void ParseAnimDataFile() { + KeyValues kvAnimData = new("ActBusyAnimDatafile"); + if (kvAnimData.LoadFromFile(filesystem, "scripts/actbusy.txt")) { + KeyValues? kvAnim = kvAnimData.GetFirstSubKey(); + while (kvAnim != null) { + BusyAnim anim = new(); + if (ParseActBusyFromKV(anim, kvAnim)) + ActBusyAnims.Add(anim); + + kvAnim = kvAnim.GetNextKey(); + } + } + } + + static string? AllocPooledString(ReadOnlySpan str) => str.IsEmpty ? null : new(str); + + public static bool ParseActBusyFromKV(BusyAnim anim, KeyValues section) { + anim.Name = AllocPooledString(section.Name); + + anim.Activities[(int)BusyAnimParts.Busy] = (Activity)AI_BaseNPC.GetActivityID(section.GetString("busy_anim", "ACT_INVALID")); + anim.Activities[(int)BusyAnimParts.Entry] = (Activity)AI_BaseNPC.GetActivityID(section.GetString("entry_anim", "ACT_INVALID")); + anim.Activities[(int)BusyAnimParts.Exit] = (Activity)AI_BaseNPC.GetActivityID(section.GetString("exit_anim", "ACT_INVALID")); + + anim.Sequences[(int)BusyAnimParts.Busy] = AllocPooledString(section.GetString("busy_sequence", null)); + anim.Sequences[(int)BusyAnimParts.Entry] = AllocPooledString(section.GetString("entry_sequence", null)); + anim.Sequences[(int)BusyAnimParts.Exit] = AllocPooledString(section.GetString("exit_sequence", null)); + + anim.Sounds[(int)BusyAnimParts.Busy] = AllocPooledString(section.GetString("busy_sound", null)); + anim.Sounds[(int)BusyAnimParts.Entry] = AllocPooledString(section.GetString("entry_sound", null)); + anim.Sounds[(int)BusyAnimParts.Exit] = AllocPooledString(section.GetString("exit_sound", null)); + + anim.MinTime = section.GetFloat("min_time", 10.0f); + anim.MaxTime = section.GetFloat("max_time", 20.0f); + + anim.UseAutomovement = section.GetInt("use_automovement", 0) != 0; + + ReadOnlySpan interrupt = section.GetString("interrupts", "BA_INT_DANGER"); + if (interrupt.SequenceEqual("BA_INT_PLAYER")) + anim.BusyInterruptType = BusyInterrupt.Player; + else if (interrupt.SequenceEqual("BA_INT_DANGER")) + anim.BusyInterruptType = BusyInterrupt.Danger; + else if (interrupt.SequenceEqual("BA_INT_AMBUSH")) + anim.BusyInterruptType = BusyInterrupt.Ambush; + else if (interrupt.SequenceEqual("BA_INT_COMBAT")) + anim.BusyInterruptType = BusyInterrupt.Combat; + else if (interrupt.SequenceEqual("BA_INT_ZOMBIESLUMP")) + anim.BusyInterruptType = BusyInterrupt.ZombieSlump; + else if (interrupt.SequenceEqual("BA_INT_SIEGE_DEFENSE")) + anim.BusyInterruptType = BusyInterrupt.SiegeDefense; + else + anim.BusyInterruptType = BusyInterrupt.None; + + return true; + } + + public int FindBusyAnim(Activity activity, ReadOnlySpan sequence) { + int count = ActBusyAnims.Count; + for (int i = 0; i < count; i++) { + BusyAnim busyAnim = ActBusyAnims[i]; + Assert(busyAnim != null); + + if (!sequence.IsEmpty && busyAnim.Name != null && busyAnim.Name.AsSpan().Equals(sequence, StringComparison.OrdinalIgnoreCase)) + return i; + + if (activity != Activity.ACT_INVALID && busyAnim.Activities[(int)BusyAnimParts.Busy] == activity) + return i; + } + + if (!sequence.IsEmpty) + Warning($"Specified '{sequence}' as a busy anim name, and it's not in the act busy anim list.\n"); + else if (activity != Activity.ACT_INVALID) + Warning($"Tried to use Activity {(int)activity} as a busy anim, and it's not in the act busy anim list.\n"); + + return -1; + } + + public BusyAnim? GetBusyAnim(int index) => index >= 0 && index < ActBusyAnims.Count ? ActBusyAnims[index] : null; +} + +public class AI_ActBusyBehavior : AI_Behavior_AI_BaseNPC_100000 +{ + const float ACTBUSY_SEE_ENTITY_TIMEOUT = 1.0f; + const float ACTBUSY_COMBAT_PLAYER_MAX_DIST = 720.0f; + const float ACTBUSY_ENEMY_TOO_CLOSE_DIST_SQR = 240 * 240; + public const float NO_MAX_TIME = -1; + + public static readonly ConVar ai_actbusy_search_time = new("ai_actbusy_search_time", "10.0"); + public static readonly ConVar ai_debug_actbusy = new("ai_debug_actbusy", "0", FCvar.Cheat, "Used to debug actbusy behavior. Usage:\n" + + "1: Constantly draw lines from NPCs to the actbusy nodes they've chosen to actbusy at.\n" + + "2: Whenever an NPC makes a decision to use an actbusy, show which actbusy they've chosen.\n" + + "3: Selected NPCs (with npc_select) will report why they're not choosing actbusy nodes.\n" + + "4: Display debug output of actbusy logic.\n" + + "5: Display safe zone volumes and info.\n"); + + static Animevent AE_ACTBUSY_WEAPON_FIRE_ON; + static Animevent AE_ACTBUSY_WEAPON_FIRE_OFF; + + public const int SCHED_ACTBUSY_START_BUSYING = NEXT_SCHEDULE; + public const int SCHED_ACTBUSY_BUSY = NEXT_SCHEDULE + 1; + public const int SCHED_ACTBUSY_STOP_BUSYING = NEXT_SCHEDULE + 2; + public const int SCHED_ACTBUSY_LEAVE = NEXT_SCHEDULE + 3; + public const int SCHED_ACTBUSY_TELEPORT_TO_BUSY = NEXT_SCHEDULE + 4; + + public const int TASK_ACTBUSY_PLAY_BUSY_ANIM = NEXT_TASK; + public const int TASK_ACTBUSY_PLAY_ENTRY = NEXT_TASK + 1; + public const int TASK_ACTBUSY_PLAY_EXIT = NEXT_TASK + 2; + public const int TASK_ACTBUSY_TELEPORT_TO_BUSY = NEXT_TASK + 3; + public const int TASK_ACTBUSY_WALK_PATH_TO_BUSY = NEXT_TASK + 4; + public const int TASK_ACTBUSY_GET_PATH_TO_ACTBUSY = NEXT_TASK + 5; + public const int TASK_ACTBUSY_VERIFY_EXIT = NEXT_TASK + 6; + + public const int COND_ACTBUSY_LOST_SEE_ENTITY = NEXT_CONDITION; + public const int COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE = NEXT_CONDITION + 1; + public const int COND_ACTBUSY_ENEMY_TOO_CLOSE = NEXT_CONDITION + 2; + + static readonly AI_ClassScheduleIdSpace gm_ClassScheduleIdSpace = new(); + const string gm_pszErrorClassName = "CAI_ActBusyBehavior"; + + static ActBusyAnimData g_ActBusyAnimDataSystem => ActBusyAnimData.g_ActBusyAnimDataSystem; + + bool Enabled; + bool ForceActBusy; + Activity ForcedActivity; + bool TeleportToBusy; + bool UseNearestBusy; + bool Leaving; + bool VisibleOnly; + bool UseRenderBoundsForCollision; + float ForcedMaxTime; + bool Busy; + bool MovingToBusy; + bool NeedsToPlayExitAnimValue; + TimeUnit_t NextBusySearchTime; + TimeUnit_t EndBusyAt; + float BusySearchRange; + bool InQueue; + int CurrentBusyAnim; + Handle ActBusyGoal = new(); + bool NeedToSetBounds; + EHANDLE SeeEntity = new(); + TimeUnit_t TimeLastSawSeeEntity; + bool ExitedBusyToDueLostSeeEntity; + bool ExitedBusyToDueSeeEnemy; + + int NumConsecutivePathFailures; + bool AutoFireWeapon; + TimeUnit_t DeferUntil; + int NumEnemiesInSafeZone; + + readonly List SafeZones = []; + + public AI_ActBusyBehavior() { + LoadSchedules(); + + Enabled = false; + UseRenderBoundsForCollision = false; + DeferUntil = 0; + } + + public override string GetName() => "ActBusy"; + + public override AI_ClassScheduleIdSpace GetClassScheduleIdSpace() => gm_ClassScheduleIdSpace; + protected override string GetSchedulingErrorName() => gm_pszErrorClassName; + + public static bool LoadSchedules() => CustomSchedules.Load(AI_BaseNPC.LoadSchedules); + + static readonly AI_CustomSchedules CustomSchedules = new() { + ClassName = gm_pszErrorClassName, + IdSpace = gm_ClassScheduleIdSpace, + ParentIdSpace = AccessClassScheduleIdSpaceDirect(), + Schedules = [ + (nameof(SCHED_ACTBUSY_START_BUSYING), SCHED_ACTBUSY_START_BUSYING), + (nameof(SCHED_ACTBUSY_BUSY), SCHED_ACTBUSY_BUSY), + (nameof(SCHED_ACTBUSY_STOP_BUSYING), SCHED_ACTBUSY_STOP_BUSYING), + (nameof(SCHED_ACTBUSY_LEAVE), SCHED_ACTBUSY_LEAVE), + (nameof(SCHED_ACTBUSY_TELEPORT_TO_BUSY), SCHED_ACTBUSY_TELEPORT_TO_BUSY), + ], + Tasks = [ + (nameof(TASK_ACTBUSY_PLAY_BUSY_ANIM), TASK_ACTBUSY_PLAY_BUSY_ANIM), + (nameof(TASK_ACTBUSY_PLAY_ENTRY), TASK_ACTBUSY_PLAY_ENTRY), + (nameof(TASK_ACTBUSY_PLAY_EXIT), TASK_ACTBUSY_PLAY_EXIT), + (nameof(TASK_ACTBUSY_TELEPORT_TO_BUSY), TASK_ACTBUSY_TELEPORT_TO_BUSY), + (nameof(TASK_ACTBUSY_WALK_PATH_TO_BUSY), TASK_ACTBUSY_WALK_PATH_TO_BUSY), + (nameof(TASK_ACTBUSY_GET_PATH_TO_ACTBUSY), TASK_ACTBUSY_GET_PATH_TO_ACTBUSY), + (nameof(TASK_ACTBUSY_VERIFY_EXIT), TASK_ACTBUSY_VERIFY_EXIT), + ], + Conditions = [ + (nameof(COND_ACTBUSY_LOST_SEE_ENTITY), COND_ACTBUSY_LOST_SEE_ENTITY), + (nameof(COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE), COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE), + (nameof(COND_ACTBUSY_ENEMY_TOO_CLOSE), COND_ACTBUSY_ENEMY_TOO_CLOSE), + ], + Declare = static () => { + AE_ACTBUSY_WEAPON_FIRE_ON = AI_BaseNPC.DeclareAnimEvent(nameof(AE_ACTBUSY_WEAPON_FIRE_ON)); + AE_ACTBUSY_WEAPON_FIRE_OFF = AI_BaseNPC.DeclareAnimEvent(nameof(AE_ACTBUSY_WEAPON_FIRE_OFF)); + }, + Definitions = [ + new(SCHED_ACTBUSY_START_BUSYING, + [ + (TASK_SET_TOLERANCE_DISTANCE, 4), + TASK_ACTBUSY_GET_PATH_TO_ACTBUSY, + TASK_ACTBUSY_WALK_PATH_TO_BUSY, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + TASK_FACE_HINTNODE, + TASK_ACTBUSY_PLAY_ENTRY, + (TASK_SET_SCHEDULE, SCHED_ACTBUSY_BUSY), + ], + [ + COND_ACTBUSY_LOST_SEE_ENTITY, + ]), + + new(SCHED_ACTBUSY_BUSY, + [ + TASK_ACTBUSY_PLAY_BUSY_ANIM, + ], + [ + COND_PROVOKED, + ]), + + new(SCHED_ACTBUSY_STOP_BUSYING, + [ + TASK_ACTBUSY_VERIFY_EXIT, + TASK_ACTBUSY_PLAY_EXIT, + (TASK_WAIT, 0.1f), + ], + [ + COND_NO_CUSTOM_INTERRUPTS, + ]), + + new(SCHED_ACTBUSY_LEAVE, + [ + (TASK_SET_TOLERANCE_DISTANCE, 4), + TASK_ACTBUSY_GET_PATH_TO_ACTBUSY, + TASK_ACTBUSY_WALK_PATH_TO_BUSY, + TASK_WAIT_FOR_MOVEMENT, + ], + [ + COND_PROVOKED, + ]), + + new(SCHED_ACTBUSY_TELEPORT_TO_BUSY, + [ + TASK_ACTBUSY_TELEPORT_TO_BUSY, + TASK_ACTBUSY_PLAY_ENTRY, + (TASK_SET_SCHEDULE, SCHED_ACTBUSY_BUSY), + ], + [ + COND_PROVOKED, + ]), + ], + }; + + public bool IsMovingToBusy() => MovingToBusy; + public bool IsEnabled() => Enabled; + public void SetUseRenderBounds(bool useBounds) => UseRenderBoundsForCollision = useBounds; + public bool NeedsToPlayExitAnim() => NeedsToPlayExitAnimValue; + public bool IsInsideActBusy() => Busy; + + Task_t? GetCurTask() => GetOuter()!.GetTask(); + BaseEntity? GetEnemy() => GetOuter()!.GetEnemy(); + Vector3 GetAbsOrigin() => GetOuter()!.GetAbsOrigin(); + void TaskComplete() => GetOuter()!.TaskComplete(); + void TaskFail(AI_TaskFailureCode code) => GetOuter()!.TaskFail(code); + void TaskFail(string failText) => GetOuter()!.TaskFail(failText); + + public void Enable(AI_ActBusyGoal? goal, float range, bool visibleOnly) { + NotifyBusyEnding(); + + if (goal != null) + ActBusyGoal.Set(goal); + Enabled = true; + Busy = false; + MovingToBusy = false; + NeedsToPlayExitAnimValue = false; + Leaving = false; + NextBusySearchTime = gpGlobals.CurTime + ai_actbusy_search_time.GetFloat(); + EndBusyAt = 0; + VisibleOnly = visibleOnly; + InQueue = false; + ForcedActivity = Activity.ACT_INVALID; + SeeEntity.Set(null); + ExitedBusyToDueLostSeeEntity = false; + ExitedBusyToDueSeeEnemy = false; + NumConsecutivePathFailures = 0; + + SetBusySearchRange(range); + + if (ai_debug_actbusy.GetInt() == 4) + Msg($"ACTBUSY: behavior enabled on NPC {GetOuter()!.GetClassname()} ({GetOuter()!.GetDebugName()})\n"); + + if (IsCombatActBusy()) + CollectSafeZoneVolumes(goal!); + + if (IsCurScheduleOverridable()) { + NextBusySearchTime = gpGlobals.CurTime; + GetOuter()!.ClearSchedule("Enabling act busy"); + } + + ClearCondition(COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE); + } + + public void SetBusySearchRange(float range) => BusySearchRange = range; + + public void Disable() { + if (ai_debug_actbusy.GetInt() == 4) + Msg($"ACTBUSY: behavior disabled on NPC {GetOuter()!.GetClassname()} ({GetOuter()!.GetDebugName()})\n"); + + if (Enabled) + SetCondition((int)SCOND_t.COND_PROVOKED); + + StopBusying(); + Enabled = false; + } + + public void ForceActBusyNow(AI_ActBusyGoal? goal, AI_Hint? hintNode = null, float maxTime = NO_MAX_TIME, bool visibleOnly = false, bool teleportToBusy = false, bool useNearestBusy = false, BaseEntity? seeEntity = null, Activity activity = Activity.ACT_INVALID) { + Assert(!Leaving); + + if (NeedsToPlayExitAnimValue) { + if (HasAnimForActBusy(CurrentBusyAnim, BusyAnimParts.Exit)) { + Warning($"ACTBUSY: {GetOuter()!.GetDebugName()}({GetOuter()!.GetClassname()}) was told to actbusy while inside an actbusy that needs to exit first. IGNORING.\n"); + return; + } + } + + if (ai_debug_actbusy.GetInt() == 4) { + Msg($"ACTBUSY: ForceActBusy on NPC {GetOuter()!.GetClassname()} ({GetOuter()!.GetDebugName()}): "); + if (hintNode != null) + Msg($"Hintnode {hintNode.GetDebugName()}"); + else + Msg("No Hintnode specified"); + Msg("\n"); + } + + Enable(goal, BusySearchRange, visibleOnly); + ForceActBusy = true; + ForcedMaxTime = maxTime; + TeleportToBusy = teleportToBusy; + UseNearestBusy = useNearestBusy; + ForcedActivity = activity; + SeeEntity.Set(seeEntity); + + if (hintNode != null) { + if (GetHintNode() != null && GetHintNode() != hintNode) + GetHintNode()!.Unlock(); + + if (hintNode.Lock(GetOuter())) + SetHintNode(hintNode); + } + + SetCondition((int)SCOND_t.COND_PROVOKED); + } + + public void ForceActBusyLeave(bool visibleOnly = false) { + if (ai_debug_actbusy.GetInt() == 4) + Msg($"ACTBUSY: ForceActBusyLeave on NPC {GetOuter()!.GetClassname()} ({GetOuter()!.GetDebugName()})\n"); + + Enable(null, BusySearchRange, visibleOnly); + ForceActBusy = true; + Leaving = true; + ForcedActivity = Activity.ACT_INVALID; + SeeEntity.Set(null); + + SetCondition((int)SCOND_t.COND_PROVOKED); + } + + public void StopBusying() { + if (GetOuter() == null) + return; + + AutoFireWeapon = false; + + if (ai_debug_actbusy.GetInt() == 4) + Msg($"ACTBUSY: StopBusying on NPC {GetOuter()!.GetClassname()} ({GetOuter()!.GetDebugName()})\n"); + + if (Busy || MovingToBusy) + SetCondition((int)SCOND_t.COND_PROVOKED); + + EndBusyAt = gpGlobals.CurTime; + ForceActBusy = false; + TeleportToBusy = false; + UseNearestBusy = false; + Leaving = false; + MovingToBusy = false; + ForcedActivity = Activity.ACT_INVALID; + SeeEntity.Set(null); + } + + public bool IsStopBusying() => IsCurSchedule(SCHED_ACTBUSY_STOP_BUSYING); + + public AI_Hint? FindActBusyHintNode() { + Assert(!IsCombatActBusy()); + + AI_HintNodeFlags bits = AI_HintNodeFlags.UseGroup; + if (VisibleOnly) + bits |= AI_HintNodeFlags.Visible; + + if (ai_debug_actbusy.GetInt() == 3 && (GetOuter()!.DebugOverlays & DebugOverlayBits.NPCSelected) != 0) + bits |= AI_HintNodeFlags.ReportFailures; + + if (UseNearestBusy) + bits |= AI_HintNodeFlags.Nearest; + else + bits |= AI_HintNodeFlags.Random; + + AI_Hint? node = AI_HintManager.FindHint(GetOuter(), Hint.WorldWorkPosition, bits, BusySearchRange); + + return node; + } + + public AI_Hint? FindCombatActBusyHintNode() { + Assert(IsCombatActBusy()); + + BasePlayer? player = GetOuter()!.AI_GetClosestPlayer(); + + if (player == null) + return null; + + HintCriteria criteria = new(); + + AI_HintNodeFlags bits = AI_HintNodeFlags.UseGroup; + + if (VisibleOnly) + bits |= AI_HintNodeFlags.Visible; + + if (ai_debug_actbusy.GetInt() == 3 && (GetOuter()!.DebugOverlays & DebugOverlayBits.NPCSelected) != 0) + bits |= AI_HintNodeFlags.ReportFailures; + + if (UseNearestBusy) + bits |= AI_HintNodeFlags.Nearest; + else + bits |= AI_HintNodeFlags.Random; + + bits |= AI_HintNodeFlags.HasEyePositionLOSToPlayer; + + criteria.AddHintType(Hint.WorldWorkPosition); + criteria.SetFlag(bits); + criteria.AddIncludePosition(player.GetAbsOrigin(), ACTBUSY_COMBAT_PLAYER_MAX_DIST); + + AI_Hint? node = AI_HintManager.FindHint(GetOuter(), criteria); + + return node; + } + + public AI_Hint? FindCombatActBusyTeleportHintNode() { + Assert(IsCombatActBusy()); + + BasePlayer? player = GetOuter()!.AI_GetClosestPlayer(); + + if (player == null) + return null; + + HintCriteria criteria = new(); + + AI_HintNodeFlags bits = AI_HintNodeFlags.UseGroup; + + if (ai_debug_actbusy.GetInt() == 3 && (GetOuter()!.DebugOverlays & DebugOverlayBits.NPCSelected) != 0) + bits |= AI_HintNodeFlags.ReportFailures; + + bits |= AI_HintNodeFlags.Random; + bits |= AI_HintNodeFlags.NotVisibleToPlayer; + + criteria.AddHintType(Hint.WorldWorkPosition); + criteria.SetFlag(bits); + criteria.AddIncludePosition(player.GetAbsOrigin(), ACTBUSY_COMBAT_PLAYER_MAX_DIST * 1.1f); + + AI_Hint? node = AI_HintManager.FindHint(GetOuter(), criteria); + + return node; + } + + protected override bool FValidateHintType(AI_Hint hint) { + if (hint.HintType() != Hint.WorldWorkPosition && hint.HintType() != Hint.NpcExitPoint) + return false; + + ReadOnlySpan sequenceOrActivity = hint.HintActivityName(); + int space = sequenceOrActivity.IndexOf(' '); + if (space >= 0) { + if (sequenceOrActivity[(space + 1)..].StartsWith("teleport")) + return true; + } + + Util.TraceHull(hint.GetAbsOrigin(), hint.GetAbsOrigin(), GetOuter()!.WorldAlignMins(), GetOuter()!.WorldAlignMaxs(), Mask.Solid, GetOuter(), Source.CollisionGroup.None, out Trace tr); + if (tr.Fraction == 1.0) + return true; + + return false; + } + + public override bool CanSelectSchedule() { + if (Busy || ForceActBusy || NeedsToPlayExitAnimValue) + return true; + + if (!Enabled) + return false; + + if (DeferUntil > gpGlobals.CurTime) + return false; + + if (CountEnemiesInSafeZone() > 0) + return false; + + if (!IsCurScheduleOverridable()) + return false; + + return NextBusySearchTime < gpGlobals.CurTime; + } + + public bool IsCurScheduleOverridable() { + if (IsCombatActBusy()) + return GetOuter()!.GetState() != NPCState.Script; + + if (GetOuter()!.IsInAVehicle()) + return false; + + return IsCurSchedule(SCHED_IDLE_STAND) || IsCurSchedule(SCHED_NONE); + } + + protected override bool ShouldIgnoreSound(ref WorldSoundInstance sound) { + if (Busy) { + BusyAnim? busyAnim = g_ActBusyAnimDataSystem.GetBusyAnim(CurrentBusyAnim); + + if (busyAnim != null && busyAnim.BusyInterruptType == BusyInterrupt.ZombieSlump) + return true; + + if (busyAnim != null && (busyAnim.BusyInterruptType == BusyInterrupt.Ambush || busyAnim.BusyInterruptType == BusyInterrupt.Combat)) { + if (!GetOuter()!.FVisible(sound.GetSoundReactOrigin())) + return true; + } + } + + return base.ShouldIgnoreSound(ref sound); + } + + public int CountEnemiesInSafeZone() { + if (!IsCombatActBusy()) + return 0; + + List ais = g_AI_Manager.AccessAIs(); + int nAIs = g_AI_Manager.NumAIs(); + int count = 0; + + for (int i = 0; i < nAIs; i++) { + if (GetOuter()!.IRelationType(ais[i]) < Disposition.LI) { + if (IsInSafeZone(ais[i])) + count++; + } + } + + return count; + } + + public override void GatherConditions() { + if (!IsCurSchedule(SCHED_ACTBUSY_BUSY, false)) + ClearCondition(COND_ACTBUSY_ENEMY_TOO_CLOSE); + + base.GatherConditions(); + + bool checkLOS = true; + bool checkFOV = true; + + if (ActBusyGoal.Get() != null && ActBusyGoal.Get()!.SightMethod == ActBusySightMethod.LOSOnly) + checkFOV = false; + + BaseEntity? seeEntity = SeeEntity.Get(); + if (seeEntity != null && Busy) { + if ((!checkFOV || GetOuter()!.FInViewCone(seeEntity)) && GetOuter()!.QuerySeeEntity(seeEntity) && (!checkLOS || GetOuter()!.FVisible(seeEntity))) { + TimeLastSawSeeEntity = gpGlobals.CurTime; + ClearCondition(COND_ACTBUSY_LOST_SEE_ENTITY); + } + else if (ActBusyGoal.Get() != null) { + TimeUnit_t delta = gpGlobals.CurTime - TimeLastSawSeeEntity; + if (delta >= ActBusyGoal.Get()!.SeeEntityTimeout) { + SetCondition(COND_ACTBUSY_LOST_SEE_ENTITY); + ActBusyGoal.Get()!.NPCLostSeeEntity(GetOuter()!); + + if (IsCombatActBusy() && (GetOuter()!.Classify() == Class_T.PlayerAllyVital && seeEntity.IsPlayer())) + DeferUntil = gpGlobals.CurTime + 4.0f; + } + } + } + else + ClearCondition(COND_ACTBUSY_LOST_SEE_ENTITY); + + if (Busy) { + BusyAnim? busyAnim = g_ActBusyAnimDataSystem.GetBusyAnim(CurrentBusyAnim); + if (busyAnim != null) { + switch (busyAnim.BusyInterruptType) { + case BusyInterrupt.Danger: + break; + + case BusyInterrupt.Ambush: + break; + + case BusyInterrupt.ZombieSlump: { + ClearCondition((int)SCOND_t.COND_HEAR_PLAYER); + ClearCondition((int)SCOND_t.COND_SEE_ENEMY); + ClearCondition((int)SCOND_t.COND_NEW_ENEMY); + + BasePlayer? player = GetOuter()!.AI_GetClosestPlayer(); + + if (player != null) { + float dist = Vector3.Distance(player.GetAbsOrigin(), GetAbsOrigin()); + + if (dist <= 60) + StopBusying(); + } + } + break; + + case BusyInterrupt.Combat: + ClearCondition((int)SCOND_t.COND_HEAR_PLAYER); + ClearCondition((int)SCOND_t.COND_SEE_ENEMY); + ClearCondition((int)SCOND_t.COND_NEW_ENEMY); + break; + + case BusyInterrupt.Player: + ClearCondition((int)SCOND_t.COND_HEAR_DANGER); + ClearCondition((int)SCOND_t.COND_HEAR_COMBAT); + ClearCondition((int)SCOND_t.COND_HEAR_WORLD); + ClearCondition((int)SCOND_t.COND_HEAR_BULLET_IMPACT); + break; + + case BusyInterrupt.SiegeDefense: + ClearCondition((int)SCOND_t.COND_HEAR_PLAYER); + ClearCondition((int)SCOND_t.COND_SEE_ENEMY); + ClearCondition((int)SCOND_t.COND_NEW_ENEMY); + ClearCondition((int)SCOND_t.COND_HEAR_COMBAT); + ClearCondition((int)SCOND_t.COND_HEAR_WORLD); + ClearCondition((int)SCOND_t.COND_HEAR_BULLET_IMPACT); + break; + + case BusyInterrupt.None: + ClearCondition((int)SCOND_t.COND_HEAR_DANGER); + ClearCondition((int)SCOND_t.COND_HEAR_COMBAT); + ClearCondition((int)SCOND_t.COND_HEAR_WORLD); + ClearCondition((int)SCOND_t.COND_HEAR_BULLET_IMPACT); + ClearCondition((int)SCOND_t.COND_HEAR_PLAYER); + break; + + default: + break; + } + } + } + + if (AutoFireWeapon && random.RandomInt(0, 5) <= 3) { + BaseCombatWeapon? weapon = GetOuter()!.GetActiveWeapon(); + + weapon?.Operator_ForceNPCFire(GetOuter()!, false); + } + } + + public override void EndScheduleSelection() { + NotifyBusyEnding(); + + CheckAndCleanupOnExit(); + } + + protected override Activity NPC_TranslateActivity(Activity activity) { + Activity newActivity = base.NPC_TranslateActivity(activity); + + if (activity == Activity.ACT_RUN) { + if (GetOuter() is AI_PlayerAlly) + return Activity.ACT_RUN_STIMULATED; + } + + return newActivity; + } + + protected override void HandleAnimEvent(ref AnimEvent animEvent) { + if (animEvent.Event == (int)AE_ACTBUSY_WEAPON_FIRE_ON) { + AutoFireWeapon = true; + return; + } + else if (animEvent.Event == (int)AE_ACTBUSY_WEAPON_FIRE_OFF) { + AutoFireWeapon = false; + return; + } + + base.HandleAnimEvent(ref animEvent); + } + + public void CheckAndCleanupOnExit() { + if (NeedsToPlayExitAnimValue && !GetOuter()!.IsMarkedForDeletion() && GetOuter()!.IsAlive()) { + Warning($"NPC {GetOuter()!.GetDebugName()}({GetOuter()!.GetClassname()}) left actbusy without playing exit anim.\n"); + NeedsToPlayExitAnimValue = false; + } + + GetOuter()!.RemoveFlag(EntityFlags.Fly); + + if (UseRenderBoundsForCollision) + GetOuter()!.SetHullSizeNormal(true); + } + + protected override void BuildScheduleTestBits() { + base.BuildScheduleTestBits(); + + if (IsCurSchedule(SCHED_ACTBUSY_START_BUSYING)) { + if (GetOuter()!.GetTask()!.Value.Task == TASK_ACTBUSY_PLAY_ENTRY) + return; + + GetOuter()!.SetCustomInterruptCondition((int)SCOND_t.COND_PROVOKED); + + if (IsCombatActBusy()) + GetOuter()!.SetCustomInterruptCondition(GetClassScheduleIdSpace().ConditionLocalToGlobal(COND_ACTBUSY_ENEMY_TOO_CLOSE)); + } + + if (InQueue || IsCurSchedule(SCHED_ACTBUSY_LEAVE)) + return; + + if (!Busy || IsCurSchedule(SCHED_ACTBUSY_STOP_BUSYING)) + return; + + BusyAnim? busyAnim = g_ActBusyAnimDataSystem.GetBusyAnim(CurrentBusyAnim); + if (busyAnim != null) { + AI_BaseNPC outer = GetOuter()!; + switch (busyAnim.BusyInterruptType) { + case BusyInterrupt.ZombieSlump: + outer.SetCustomInterruptCondition((int)SCOND_t.COND_LIGHT_DAMAGE); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAVY_DAMAGE); + break; + + case BusyInterrupt.SiegeDefense: + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAR_DANGER); + outer.SetCustomInterruptCondition(GetClassScheduleIdSpace().ConditionLocalToGlobal(COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE)); + outer.SetCustomInterruptCondition(GetClassScheduleIdSpace().ConditionLocalToGlobal(COND_ACTBUSY_ENEMY_TOO_CLOSE)); + break; + + case BusyInterrupt.Ambush: + case BusyInterrupt.Danger: + outer.SetCustomInterruptCondition((int)SCOND_t.COND_LIGHT_DAMAGE); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAVY_DAMAGE); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAR_DANGER); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAR_COMBAT); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAR_BULLET_IMPACT); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_NEW_ENEMY); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_SEE_ENEMY); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_PLAYER_ADDED_TO_SQUAD); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_RECEIVED_ORDERS); + break; + + case BusyInterrupt.Player: + outer.SetCustomInterruptCondition((int)SCOND_t.COND_LIGHT_DAMAGE); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAVY_DAMAGE); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAR_DANGER); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAR_COMBAT); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAR_BULLET_IMPACT); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_NEW_ENEMY); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_PLAYER_ADDED_TO_SQUAD); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_RECEIVED_ORDERS); + + outer.SetCustomInterruptCondition((int)SCOND_t.COND_SEE_PLAYER); + break; + + case BusyInterrupt.Combat: + outer.SetCustomInterruptCondition((int)SCOND_t.COND_LIGHT_DAMAGE); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAVY_DAMAGE); + outer.SetCustomInterruptCondition((int)SCOND_t.COND_HEAR_DANGER); + break; + + case BusyInterrupt.None: + break; + + default: + break; + } + } + } + + int SelectScheduleForLeaving() { + if (GetHintNode() != null) { + if (GetHintNode()!.HintType() == Hint.NpcExitPoint) { + if (Util.DistApprox(GetHintNode()!.GetAbsOrigin(), GetAbsOrigin()) < 64) { + if (!GetOuter()!.IsMarkedForDeletion()) { + BaseEntity? owner = GetOuter()!.GetOwnerEntity(); + if (owner != null) { + owner.DeathNotice(GetOuter()!); + GetOuter()!.SetOwnerEntity(null); + } + GetOuter()!.SetThink(GetOuter()!.SUB_Remove); + GetOuter()!.SetNextThink(gpGlobals.CurTime + 0.1); + + ActBusyGoal.Get()?.NPCLeft(GetOuter()!); + } + + return SCHED_IDLE_STAND; + } + + return SCHED_ACTBUSY_LEAVE; + } + else { + GetHintNode()!.NPCStoppedUsing(GetOuter()!); + GetHintNode()!.Unlock(); + SetHintNode(null); + } + } + + HintCriteria hintCriteria = new(); + hintCriteria.SetHintType(Hint.NpcExitPoint); + hintCriteria.SetFlag(AI_HintNodeFlags.Random | AI_HintNodeFlags.Clear | AI_HintNodeFlags.UseGroup); + AI_Hint? node = AI_HintManager.FindHintRandom(GetOuter(), GetOuter()!.GetAbsOrigin(), hintCriteria); + if (node != null) { + SetHintNode(node); + return SCHED_ACTBUSY_LEAVE; + } + + return SCHED_IDLE_STAND; + } + + int SelectScheduleWhileNotBusy(int baseSchedule) { + if (ForceActBusy || NextBusySearchTime < gpGlobals.CurTime) { + if (ForceActBusy || IsCombatActBusy()) + NextBusySearchTime = gpGlobals.CurTime + 2.0; + else + NextBusySearchTime = gpGlobals.CurTime + random.RandomFloat(ai_actbusy_search_time.GetFloat(), ai_actbusy_search_time.GetFloat() * 2); + + bool forceTeleport = false; + AI_Hint? node = GetHintNode(); + if (node == null) { + if (IsCombatActBusy()) { + if (ActBusyGoal.Get()!.IsCombatActBusyTeleportAllowed() && NumConsecutivePathFailures >= 2 && !GetOuter()!.AI_GetClosestPlayer()!.FInViewCone(GetOuter()!)) { + node = FindCombatActBusyTeleportHintNode(); + forceTeleport = true; + } + else + node = FindCombatActBusyHintNode(); + } + else + node = FindActBusyHintNode(); + } + if (node != null) { + ReadOnlySpan sequenceOrActivity = node.HintActivityName(); + Activity nodeActivity; + int busyAnim; + + int space = sequenceOrActivity.IndexOf(' '); + if (space >= 0) { + if (sequenceOrActivity[(space + 1)..].StartsWith("teleport")) + TeleportToBusy = true; + + ReadOnlySpan actOrSeqName = sequenceOrActivity[..space]; + nodeActivity = (Activity)AI_BaseNPC.GetActivityID(actOrSeqName); + busyAnim = g_ActBusyAnimDataSystem.FindBusyAnim(nodeActivity, actOrSeqName); + } + else { + nodeActivity = (Activity)AI_BaseNPC.GetActivityID(sequenceOrActivity); + busyAnim = g_ActBusyAnimDataSystem.FindBusyAnim(nodeActivity, sequenceOrActivity); + } + + if (HasAnimForActBusy(busyAnim, BusyAnimParts.Busy)) { + if (HasCondition(COND_ACTBUSY_LOST_SEE_ENTITY)) { + if (ForceActBusy) + StopBusying(); + return baseSchedule; + } + + CurrentBusyAnim = busyAnim; + if (CurrentBusyAnim == -1) + return baseSchedule; + + if (ai_debug_actbusy.GetInt() == 4) + Msg($"ACTBUSY: NPC {GetOuter()!.GetClassname()} ({GetOuter()!.GetDebugName()}) found Actbusy node {node.GetDebugName()} \n"); + + GetHintNode()?.Unlock(); + + SetHintNode(node); + if (GetHintNode() != null && GetHintNode()!.Lock(GetOuter())) { + ActBusyGoal.Get()?.NPCMovingToBusy(GetOuter()!); + + MovingToBusy = true; + + if (ActBusyGoal.Get() != null && ActBusyGoal.Get()!.SeeEntityName != null) + SeeEntity.Set(gEntList.FindEntityByName(null, ActBusyGoal.Get()!.SeeEntityName)); + + ClearCondition(COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE); + + if (TeleportToBusy) + return SCHED_ACTBUSY_TELEPORT_TO_BUSY; + else if (forceTeleport) { + NumConsecutivePathFailures = 0; + return SCHED_ACTBUSY_TELEPORT_TO_BUSY; + } + + return SCHED_ACTBUSY_START_BUSYING; + } + } + } + else { + if (IsCombatActBusy()) + NextBusySearchTime = gpGlobals.CurTime + 10.0; + } + } + + return SCHED_NONE; + } + + int SelectScheduleWhileBusy() { + if (!ActBusyNodeStillActive() || (EndBusyAt != 0 && gpGlobals.CurTime >= EndBusyAt)) { + if (ai_debug_actbusy.GetInt() == 4) + Msg($"ACTBUSY: NPC {GetOuter()!.GetClassname()} ({GetOuter()!.GetDebugName()}) ending actbusy.\n"); + + StopBusying(); + return SCHED_ACTBUSY_STOP_BUSYING; + } + + if (IsCombatActBusy() && (HasCondition(COND_ACTBUSY_AWARE_OF_ENEMY_IN_SAFE_ZONE) || HasCondition(COND_ACTBUSY_ENEMY_TOO_CLOSE))) + return SCHED_ACTBUSY_STOP_BUSYING; + + return SCHED_ACTBUSY_BUSY; + } + + protected override int SelectSchedule() { + int baseSchedule = base.SelectSchedule(); + + if (!IsCombatActBusy() && !ForceActBusy && baseSchedule != SCHED_IDLE_STAND) { + if (Busy) + return SCHED_ACTBUSY_STOP_BUSYING; + + CheckAndCleanupOnExit(); + return baseSchedule; + } + + if (Leaving) + return SelectScheduleForLeaving(); + + bool shouldNotBeBusy = !Enabled || HasCondition((int)SCOND_t.COND_PLAYER_ADDED_TO_SQUAD) || HasCondition((int)SCOND_t.COND_RECEIVED_ORDERS); + if (shouldNotBeBusy) { + if (!GetOuter()!.IsMarkedForDeletion() && GetOuter()!.IsAlive()) + return SCHED_ACTBUSY_STOP_BUSYING; + } + else { + if (Busy) + return SelectScheduleWhileBusy(); + + int schedule = SelectScheduleWhileNotBusy(baseSchedule); + if (schedule != SCHED_NONE) + return schedule; + } + + CheckAndCleanupOnExit(); + return baseSchedule; + } + + public bool ActBusyNodeStillActive() { + if (GetHintNode() == null) + return false; + + return GetHintNode()!.IsDisabled() == false; + } + + protected override bool IsInterruptable() { + if (IsActive()) + return false; + + return base.IsInterruptable(); + } + + protected override bool CanFlinch() { + if (NeedsToPlayExitAnimValue) + return false; + + return base.CanFlinch(); + } + + protected override float GetReasonableFacingDist() => 0; + + protected override void OnScheduleChange() { + if (IsCurSchedule(SCHED_ACTBUSY_BUSY, false)) { + if (HasCondition((int)SCOND_t.COND_SEE_ENEMY)) + ExitedBusyToDueSeeEnemy = true; + + if (HasCondition(COND_ACTBUSY_LOST_SEE_ENTITY)) + ExitedBusyToDueLostSeeEntity = true; + } + + base.OnScheduleChange(); + } + + protected override bool QueryHearSound(ref WorldSoundInstance sound) { + if (sound.IsSoundType(SoundInstanceType.Combat) || sound.IsSoundType(SoundInstanceType.BulletImpact)) { + if (GetOuter()!.IRelationType(sound.Owner.Get()) == Disposition.LI) + return false; + } + + return base.QueryHearSound(ref sound); + } + + protected override void OnSeeEntity(BaseEntity entity) { + base.OnSeeEntity(entity); + + if (IsCombatActBusy() && GetOuter()!.IRelationType(entity) < Disposition.LI) { + if (Vector3.DistanceSquared(entity.GetAbsOrigin(), GetAbsOrigin()) <= ACTBUSY_ENEMY_TOO_CLOSE_DIST_SQR) + SetCondition(COND_ACTBUSY_ENEMY_TOO_CLOSE); + } + } + + protected override bool ShouldPlayerAvoid() { + if (IsCombatActBusy()) { + if (IsCurSchedule(SCHED_ACTBUSY_START_BUSYING)) { + if (GetCurTask() != null && GetCurTask()!.Value.Task == TASK_ACTBUSY_PLAY_ENTRY) + return true; + } + else if (IsCurSchedule(SCHED_ACTBUSY_STOP_BUSYING)) { + if (GetCurTask() != null && GetCurTask()!.Value.Task == TASK_ACTBUSY_PLAY_EXIT) + return true; + } + } + else { + if (IsCurSchedule(SCHED_ACTBUSY_START_BUSYING)) { + if ((GetCurTask() != null && GetCurTask()!.Value.Task == TASK_WAIT_FOR_MOVEMENT) || GetOuter()!.GetTask()!.Value.Task == TASK_ACTBUSY_PLAY_ENTRY) + return true; + } + else if (IsCurSchedule(SCHED_ACTBUSY_STOP_BUSYING)) { + if (GetCurTask() != null && GetCurTask()!.Value.Task == TASK_ACTBUSY_PLAY_EXIT) + return true; + } + } + + return base.ShouldPlayerAvoid(); + } + + public void ComputeAndSetRenderBounds() { + if (GetOuter()!.ComputeHitboxSurroundingBox(out Vector3 mins, out Vector3 maxs)) { + Util.SetSize(GetOuter()!, mins - GetAbsOrigin(), maxs - GetAbsOrigin()); + if (GetOuter()!.VPhysicsGetObject() != null) + GetOuter()!.SetupVPhysicsHull(); + } + } + + public bool IsActive() => Busy || ForceActBusy || NeedsToPlayExitAnimValue || Leaving; + + public bool IsCombatActBusy() { + if (ActBusyGoal.Get() != null) + return ActBusyGoal.Get()!.GetBusyType() == ActBusyType.Combat; + + return false; + } + + public void CollectSafeZoneVolumes(AI_ActBusyGoal actBusyGoal) { + SafeZones.Clear(); + + if (actBusyGoal.SafeZoneVolume != null) { + BaseEntity? volume = gEntList.FindEntityByName(null, actBusyGoal.SafeZoneVolume); + + while (volume != null) { + BusySafeZone newSafeZone = default; + volume.CollisionProp().WorldSpaceAABB(out newSafeZone.Mins, out newSafeZone.Maxs); + SafeZones.Add(newSafeZone); + volume = gEntList.FindEntityByName(volume, actBusyGoal.SafeZoneVolume); + } + } + + if (ai_debug_actbusy.GetInt() == 5) + Msg($"Actbusy collected {SafeZones.Count} safe zones\n"); + } + + public bool IsInSafeZone(BaseEntity entity) { + Vector3 location = entity.WorldSpaceCenter(); + + for (int i = 0; i < SafeZones.Count; i++) { + BusySafeZone safeZone = SafeZones[i]; + + if (location.X > safeZone.Mins.X && + location.Y > safeZone.Mins.Y && + location.Z > safeZone.Mins.Z && + + location.X < safeZone.Maxs.X && + location.Y < safeZone.Maxs.Y && + location.Z < safeZone.Maxs.Z) + return true; + } + + return false; + } + + bool HasAnimForActBusy(int actBusy, BusyAnimParts animPart) { + if (actBusy == -1) + return false; + + BusyAnim? busyAnim = g_ActBusyAnimDataSystem.GetBusyAnim(actBusy); + if (busyAnim == null) + return false; + + if (busyAnim.Sequences[(int)animPart] != null) + return GetOuter()!.LookupSequence(busyAnim.Sequences[(int)animPart]) != StudioHdr.ACTIVITY_NOT_AVAILABLE; + + if (busyAnim.Activities[(int)animPart] != Activity.ACT_INVALID) + return GetOuter()!.HaveSequenceForActivity(busyAnim.Activities[(int)animPart]); + + return false; + } + + void PlaySoundForActBusy(BusyAnimParts animPart) { + BusyAnim? busyAnim = g_ActBusyAnimDataSystem.GetBusyAnim(CurrentBusyAnim); + if (busyAnim == null) + return; + + string? sound = busyAnim.Sounds[(int)animPart]; + if (sound != null) { + SoundParameters parms = default; + if (BaseEntity.GetParametersForSound(sound, ref parms, GetOuter()!.GetModelName())) { + PASAttenuationFilter filter = new(GetOuter()!); + BaseEntity.EmitSound(filter, GetOuter()!.EntIndex(), sound); + } + else { + AI_Expresser? expresser = GetOuter()!.GetExpresser(); + if (expresser != null) { + if (!expresser.IsSpeaking() && expresser.CanSpeakConcept(sound)) + expresser.Speak(sound); + } + } + } + } + + bool PlayAnimForActBusy(BusyAnimParts animPart) { + BusyAnim? busyAnim = g_ActBusyAnimDataSystem.GetBusyAnim(CurrentBusyAnim); + if (busyAnim == null) + return false; + + if (busyAnim.Sequences[(int)animPart] != null) { + GetOuter()!.SetSequenceByName(busyAnim.Sequences[(int)animPart]); + GetOuter()!.SetIdealActivity(Activity.ACT_DO_NOT_DISTURB); + return true; + } + + if (busyAnim.Activities[(int)animPart] != Activity.ACT_INVALID) { + GetOuter()!.SetIdealActivity(busyAnim.Activities[(int)animPart]); + return true; + } + + return false; + } + + protected override void StartTask(in Task_t task) { + switch (task.Task) { + case TASK_ACTBUSY_PLAY_BUSY_ANIM: { + if (!Enabled) { + TaskComplete(); + return; + } + + NeedToSetBounds = true; + + BusyAnim? busyAnim = g_ActBusyAnimDataSystem.GetBusyAnim(CurrentBusyAnim); + + if (busyAnim == null || !busyAnim.UseAutomovement) + GetOuter()!.AddFlag(EntityFlags.Fly); + + GetOuter()!.SetGroundEntity(null); + + if (MovingToBusy) { + if (Util.DistApprox(GetHintNode()!.GetAbsOrigin(), GetAbsOrigin()) > 16 || !GetOuter()!.FacingIdeal()) { + TaskFail("Not correctly on hintnode"); + EndBusyAt = gpGlobals.CurTime; + return; + } + } + + MovingToBusy = false; + + if (!ActBusyNodeStillActive()) { + TaskFail(AI_TaskFailureCode.NoHintNode); + return; + } + + if (!Busy) { + Busy = true; + + GetHintNode()!.NPCStartedUsing(GetOuter()!); + ActBusyGoal.Get()?.NPCStartedBusy(GetOuter()!); + + if (busyAnim != null) { + float maxTime = busyAnim.MaxTime; + float minTime = busyAnim.MinTime; + + if (ForceActBusy && ForcedMaxTime != NO_MAX_TIME) { + maxTime = ForcedMaxTime; + + if (maxTime != 0 && maxTime < minTime) + minTime = maxTime; + } + + if (maxTime == 0 || InQueue) { + EndBusyAt = 0; + GetOuter()!.SetWait(99999); + } + else { + float time = random.RandomFloat(minTime, maxTime); + EndBusyAt = gpGlobals.CurTime + time; + GetOuter()!.SetWait(time); + } + } + } + + PlayAnimForActBusy(BusyAnimParts.Busy); + PlaySoundForActBusy(BusyAnimParts.Busy); + + ForceActBusy = false; + TeleportToBusy = false; + UseNearestBusy = false; + ForcedActivity = Activity.ACT_INVALID; + + if (UseRenderBoundsForCollision) + ComputeAndSetRenderBounds(); + } + break; + + case TASK_ACTBUSY_PLAY_ENTRY: { + BusyAnim? busyAnim = g_ActBusyAnimDataSystem.GetBusyAnim(CurrentBusyAnim); + + if (busyAnim == null || !busyAnim.UseAutomovement) + GetOuter()!.AddFlag(EntityFlags.Fly); + + GetOuter()!.SetGroundEntity(null); + + MovingToBusy = false; + NeedsToPlayExitAnimValue = HasAnimForActBusy(CurrentBusyAnim, BusyAnimParts.Exit); + + if (!ActBusyNodeStillActive()) { + TaskFail(AI_TaskFailureCode.NoHintNode); + return; + } + + if (Util.DistApprox(GetHintNode()!.GetAbsOrigin(), GetAbsOrigin()) > 16 || !GetOuter()!.FacingIdeal()) { + Busy = false; + TaskFail("Not correctly on hintnode"); + return; + } + + PlaySoundForActBusy(BusyAnimParts.Entry); + + if (!PlayAnimForActBusy(BusyAnimParts.Entry)) + TaskComplete(); + } + break; + + case TASK_ACTBUSY_VERIFY_EXIT: { + if (!UseRenderBoundsForCollision) { + TaskComplete(); + break; + } + + GetOuter()!.SetWait(0); + } + break; + + case TASK_ACTBUSY_PLAY_EXIT: { + if (UseRenderBoundsForCollision) + GetOuter()!.SetHullSizeNormal(true); + + ActBusyGoal.Get()?.NPCStartedLeavingBusy(GetOuter()!); + + PlaySoundForActBusy(BusyAnimParts.Exit); + + if (!PlayAnimForActBusy(BusyAnimParts.Exit)) { + NeedsToPlayExitAnimValue = false; + GetOuter()!.RemoveFlag(EntityFlags.Fly); + NotifyBusyEnding(); + TaskComplete(); + } + } + break; + + case TASK_ACTBUSY_TELEPORT_TO_BUSY: { + if (!ActBusyNodeStillActive()) { + TaskFail(AI_TaskFailureCode.NoHintNode); + return; + } + + Vector3 absOrigin = GetHintNode()!.GetAbsOrigin(); + QAngle absAngles = GetHintNode()!.GetAbsAngles(); + GetOuter()!.Teleport(absOrigin, absAngles, null); + GetOuter()!.GetMotor()!.SetIdealYaw(absAngles.Y); + + TaskComplete(); + } + break; + + case TASK_ACTBUSY_WALK_PATH_TO_BUSY: { + if (ForcedActivity != Activity.ACT_INVALID && ForcedActivity != Activity.ACT_RESET) { + GetNavigator()!.SetMovementActivity(ForcedActivity); + + GetOuter()!.Forget(AI_MemoryFlags.Incover); + + TaskComplete(); + } + else { + if (IsCombatActBusy()) + ChainStartTask(TASK_RUN_PATH); + else + ChainStartTask(TASK_WALK_PATH); + } + break; + } + + case TASK_ACTBUSY_GET_PATH_TO_ACTBUSY: { + ChainStartTask(TASK_GET_PATH_TO_HINTNODE); + + if (!HasCondition((int)SCOND_t.COND_TASK_FAILED)) { + NumConsecutivePathFailures = 0; + + BusyAnim? busyAnim = g_ActBusyAnimDataSystem.GetBusyAnim(CurrentBusyAnim); + if (busyAnim != null && busyAnim.Sequences[(int)BusyAnimParts.Entry] == null && busyAnim.Activities[(int)BusyAnimParts.Entry] == Activity.ACT_INVALID) { + if (busyAnim.Sequences[(int)BusyAnimParts.Busy] != null) + GetNavigator()!.SetArrivalSequence(GetOuter()!.LookupSequence(busyAnim.Sequences[(int)BusyAnimParts.Busy])); + else if (busyAnim.Activities[(int)BusyAnimParts.Busy] != Activity.ACT_INVALID) + GetNavigator()!.SetArrivalActivity(busyAnim.Activities[(int)BusyAnimParts.Busy]); + } + else { + if (busyAnim!.Sequences[(int)BusyAnimParts.Entry] != null) + GetNavigator()!.SetArrivalSequence(GetOuter()!.LookupSequence(busyAnim.Sequences[(int)BusyAnimParts.Entry])); + else if (busyAnim.Activities[(int)BusyAnimParts.Entry] != Activity.ACT_INVALID) + GetNavigator()!.SetArrivalActivity(busyAnim.Activities[(int)BusyAnimParts.Entry]); + } + } + else + NumConsecutivePathFailures++; + + break; + } + + default: + base.StartTask(task); + break; + } + } + + protected override void RunTask(in Task_t task) { + switch (task.Task) { + case TASK_WAIT_FOR_MOVEMENT: { + if (IsCurSchedule(SCHED_ACTBUSY_START_BUSYING)) { + if (!ActBusyNodeStillActive()) { + TaskFail(AI_TaskFailureCode.NoHintNode); + return; + } + } + + base.RunTask(task); + break; + } + + case TASK_ACTBUSY_PLAY_BUSY_ANIM: { + if (UseRenderBoundsForCollision) { + if (GetOuter()!.IsSequenceFinished() && NeedToSetBounds) { + ComputeAndSetRenderBounds(); + NeedToSetBounds = false; + } + } + + if (IsCombatActBusy()) { + if (GetEnemy() != null && !HasCondition((int)SCOND_t.COND_ENEMY_OCCLUDED)) { + float distSqr = Vector3.DistanceSquared(GetAbsOrigin(), GetEnemy()!.GetAbsOrigin()); + + if (distSqr < (12.0f * 15.0f) * (12.0f * 15.0f)) { + EndBusyAt = gpGlobals.CurTime; + TaskComplete(); + return; + } + } + } + + GetOuter()!.AutoMovement(); + if (!ActBusyNodeStillActive() || GetOuter()!.IsWaitFinished()) + TaskComplete(); + else { + if (GetOuter() is AI_PlayerAlly ally) + ally.SelectInterjection(); + + if (HasCondition(COND_ACTBUSY_LOST_SEE_ENTITY)) { + StopBusying(); + TaskComplete(); + } + } + break; + } + + case TASK_ACTBUSY_PLAY_ENTRY: { + GetOuter()!.AutoMovement(); + if (!ActBusyNodeStillActive() || GetOuter()!.IsSequenceFinished()) + TaskComplete(); + } + break; + + case TASK_ACTBUSY_VERIFY_EXIT: { + if (GetOuter()!.IsWaitFinished()) { + TraceFilterOnlyNPCsAndPlayer filter = new(GetOuter(), Source.CollisionGroup.None); + Util.TraceHull(GetOuter()!.GetAbsOrigin(), GetOuter()!.GetAbsOrigin(), NAI_Hull.Mins(AI_HullType.Human), NAI_Hull.Maxs(AI_HullType.Human), Mask.NPCSolid, ref filter, out Trace tr); + + if (tr.StartSolid) + GetOuter()!.SetWait(1.0f); + else { + BaseEntity? blocker = EntityBlocker.Create(GetOuter()!.GetAbsOrigin(), NAI_Hull.Mins(AI_HullType.Human), NAI_Hull.Maxs(AI_HullType.Human), GetOuter(), true); + g_EventQueue.AddEvent(blocker, "Kill", 1.0f, GetOuter(), GetOuter()); + TaskComplete(); + } + } + } + break; + + case TASK_ACTBUSY_PLAY_EXIT: { + GetOuter()!.AutoMovement(); + if (GetOuter()!.IsSequenceFinished()) { + NeedsToPlayExitAnimValue = false; + GetOuter()!.RemoveFlag(EntityFlags.Fly); + NotifyBusyEnding(); + TaskComplete(); + } + } + break; + + default: + base.RunTask(task); + break; + } + } + + void NotifyBusyEnding() { + AutoFireWeapon = false; + + if (GetHintNode() != null) { + if (Busy || MovingToBusy) + GetHintNode()!.NPCStoppedUsing(GetOuter()!); + + GetHintNode()!.Unlock(); + + if (IsCombatActBusy()) + GetHintNode()!.DisableForSeconds(random.RandomFloat(10, 15)); + + SetHintNode(null); + } + + if (Busy) { + Busy = false; + + AI_ActBusyGoal? goal = ActBusyGoal.Get(); + if (goal != null) { + goal.NPCFinishedBusy(GetOuter()!); + + if (ExitedBusyToDueLostSeeEntity) { + goal.NPCLostSeeEntity(GetOuter()!); + ExitedBusyToDueLostSeeEntity = false; + } + + if (ExitedBusyToDueSeeEnemy) { + goal.NPCSeeEnemy(GetOuter()!); + ExitedBusyToDueSeeEnemy = false; + } + } + } + else if (MovingToBusy && ActBusyGoal.Get() != null) + ActBusyGoal.Get()!.NPCAbortedMoveTo(GetOuter()!); + + EndBusyAt = 0; + + if (IsCombatActBusy()) + NextBusySearchTime = gpGlobals.CurTime; + else + NextBusySearchTime = gpGlobals.CurTime + random.RandomFloat(ai_actbusy_search_time.GetFloat(), ai_actbusy_search_time.GetFloat() * 2); + } + +} + +[LinkEntityToClass("ai_goal_actbusy")] +public class AI_ActBusyGoal : AI_GoalEntity +{ + public static readonly new DataMap DataDesc = new(typeof(AI_ActBusyGoal), AI_GoalEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(BusySearchRange), FieldType.Float, "busysearchrange"), + DEFINE.KEYFIELD(nameof(VisibleOnly), FieldType.Boolean, "visibleonly"), + DEFINE.KEYFIELD(nameof(BusyType), FieldType.Integer, "type"), + DEFINE.KEYFIELD(nameof(AllowCombatActBusyTeleport), FieldType.Boolean, "allowteleport"), + DEFINE.KEYFIELD(nameof(SeeEntityName), FieldType.String, "SeeEntity"), + DEFINE.KEYFIELD(nameof(SeeEntityTimeout), FieldType.Float, "SeeEntityTimeout"), + DEFINE.KEYFIELD(nameof(SafeZoneVolume), FieldType.String, "SafeZone"), + DEFINE.KEYFIELD(nameof(SightMethod), FieldType.Integer, "sightmethod"), + + DEFINE.INPUTFUNC(FieldType.Float, "SetBusySearchRange", nameof(InputSetBusySearchRange), (INPUTFUNCPTR)((self, data) => ((AI_ActBusyGoal)self).InputSetBusySearchRange(data))), + DEFINE.INPUTFUNC(FieldType.String, "ForceNPCToActBusy", nameof(InputForceNPCToActBusy), (INPUTFUNCPTR)((self, data) => ((AI_ActBusyGoal)self).InputForceNPCToActBusy(data))), + DEFINE.INPUTFUNC(FieldType.EHandle, "ForceThisNPCToActBusy", nameof(InputForceThisNPCToActBusy), (INPUTFUNCPTR)((self, data) => ((AI_ActBusyGoal)self).InputForceThisNPCToActBusy(data))), + DEFINE.INPUTFUNC(FieldType.EHandle, "ForceThisNPCToLeave", nameof(InputForceThisNPCToLeave), (INPUTFUNCPTR)((self, data) => ((AI_ActBusyGoal)self).InputForceThisNPCToLeave(data))), + + DEFINE.OUTPUT(nameof(OnNPCStartedBusy), "OnNPCStartedBusy", eventFuncs), + DEFINE.OUTPUT(nameof(OnNPCFinishedBusy), "OnNPCFinishedBusy", eventFuncs), + DEFINE.OUTPUT(nameof(OnNPCLeft), "OnNPCLeft", eventFuncs), + DEFINE.OUTPUT(nameof(OnNPCLostSeeEntity), "OnNPCLostSeeEntity", eventFuncs), + DEFINE.OUTPUT(nameof(OnNPCSeeEnemy), "OnNPCSeeEnemy", eventFuncs), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + protected float BusySearchRange; + protected bool VisibleOnly; + protected ActBusyType BusyType; + protected bool AllowCombatActBusyTeleport; + + public string? SeeEntityName; + public float SeeEntityTimeout; + public string? SafeZoneVolume; + public ActBusySightMethod SightMethod; + + protected readonly OutputEHANDLE OnNPCStartedBusy = new(); + protected readonly OutputEHANDLE OnNPCFinishedBusy = new(); + protected readonly OutputEHANDLE OnNPCLeft = new(); + protected readonly OutputEHANDLE OnNPCLostSeeEntity = new(); + protected readonly OutputEHANDLE OnNPCSeeEnemy = new(); + + public AI_ActBusyGoal() { + SeeEntityTimeout = 1; + } + + public ActBusyType GetBusyType() => BusyType; + public bool IsCombatActBusyTeleportAllowed() => AllowCombatActBusyTeleport; + + protected static AI_ActBusyBehavior? GetBusyBehaviorForNPC(BaseEntity? entity, ReadOnlySpan inputName) { + if (entity is not AI_BaseNPC actor) { + Msg($"ai_goal_actbusy input {inputName} fired targeting an entity that isn't an NPC.\n"); + return null; + } + + if (!actor.GetBehavior(out AI_ActBusyBehavior? behavior)) { + Msg($"ai_goal_actbusy input {inputName} fired on an NPC that doesn't support ActBusy behavior.\n"); + return null; + } + + return behavior; + } + + protected static AI_ActBusyBehavior? GetBusyBehaviorForNPC(ReadOnlySpan actorName, BaseEntity? activator, BaseEntity? caller, ReadOnlySpan inputName) { + BaseEntity? entity = gEntList.FindEntityByName(null, actorName, null, activator, caller); + if (entity == null) { + Msg($"ai_goal_actbusy input {inputName} fired targeting a non-existant entity ({actorName}).\n"); + return null; + } + + return GetBusyBehaviorForNPC(entity, inputName); + } + + protected override void EnableGoal(AI_BaseNPC? ai) { + base.EnableGoal(ai); + + if (ai!.GetBehavior(out AI_ActBusyBehavior? behavior)) { + if (!behavior!.IsEnabled()) + behavior.Enable(this, BusySearchRange, VisibleOnly); + } + else { + DevMsg($"ActBusy goal entity activated for an NPC ({ai.GetDebugName()}) that doesn't have the ActBusy behavior\n"); + return; + } + } + + public override void InputActivate(InputData inputdata) { + if (AI_ActBusyBehavior.ai_debug_actbusy.GetInt() == 4) + Msg($"ACTBUSY: Actbusy goal {GetClassname()} ({GetDebugName()}) activated.\n"); + + base.InputActivate(inputdata); + } + + public override void InputDeactivate(InputData inputdata) { + if (AI_ActBusyBehavior.ai_debug_actbusy.GetInt() == 4) + Msg($"ACTBUSY: Actbusy goal {GetClassname()} ({GetDebugName()}) disabled.\n"); + + base.InputDeactivate(inputdata); + + for (int i = 0; i < NumActors(); i++) { + AI_BaseNPC? actor = GetActor(i); + + if (actor != null) { + if (actor.GetBehavior(out AI_ActBusyBehavior? behavior)) + behavior!.Disable(); + else { + DevMsg("ActBusy goal entity deactivated for an NPC that doesn't have the ActBusy behavior\n"); + return; + } + } + } + } + + void InputSetBusySearchRange(InputData inputdata) { + BusySearchRange = inputdata.Value.Float(); + + for (int i = 0; i < NumActors(); i++) { + AI_BaseNPC? actor = GetActor(i); + + if (actor != null) { + if (actor.GetBehavior(out AI_ActBusyBehavior? behavior)) + behavior!.SetBusySearchRange(BusySearchRange); + } + } + } + + void InputForceNPCToActBusy(InputData inputdata) { + string parseString = new(inputdata.Value.String()); + + AI_Hint? hintNode = null; + float maxTime = AI_ActBusyBehavior.NO_MAX_TIME; + bool teleport = false; + bool useNearestBusy = false; + BaseEntity? seeEntity = null; + + string[] tokens = parseString.Split(' ', StringSplitOptions.RemoveEmptyEntries); + int tokenIndex = 0; + string? NextToken() => tokenIndex < tokens.Length ? tokens[tokenIndex++] : null; + + string? param = NextToken(); + AI_ActBusyBehavior? behavior = GetBusyBehaviorForNPC(param, inputdata.Activator, inputdata.Caller, "InputForceNPCToActBusy"); + if (behavior == null) + return; + + bool episodicBugFix = hl2_episodic.GetBool(); + + param = NextToken(); + if (param != null) { + BaseEntity? entity = gEntList.FindEntityByName(null, param, null, inputdata.Activator, inputdata.Caller); + if (entity != null) { + hintNode = entity as AI_Hint; + if (hintNode == null) { + Msg("ai_goal_actbusy input ForceNPCToActBusy fired targeting an entity that isn't a hintnode.\n"); + return; + } + + if (episodicBugFix) + param = NextToken(); + } + } + + Activity activity = Activity.ACT_INVALID; + + if (!episodicBugFix) + param = NextToken(); + + while (param != null) { + if (param.StartsWith("teleport")) + teleport = true; + else if (param.StartsWith("nearest")) + useNearestBusy = true; + else if (param.StartsWith("see:")) + seeEntity = gEntList.FindEntityByName(null, param[4..]); + else if (param[0] == '$') { + string animName = param[1..]; + activity = (Activity)ActivityList.IndexForName(animName); + if (activity == Activity.ACT_INVALID) { + behavior.GetOuter()!.SceneCustomMoveSeq = animName; + activity = Activity.ACT_SCRIPT_CUSTOM_MOVE; + } + } + else + maxTime = (float)atof(param); + + param = NextToken(); + } + + if (AI_ActBusyBehavior.ai_debug_actbusy.GetInt() == 4) + Msg($"ACTBUSY: Actbusy goal {GetClassname()} ({GetDebugName()}) ForceNPCToActBusy input with data: {parseString}.\n"); + + behavior.SetBusySearchRange(BusySearchRange); + behavior.ForceActBusyNow(this, hintNode, maxTime, VisibleOnly, teleport, useNearestBusy, seeEntity, activity); + } + + void InputForceThisNPCToActBusy(InputData inputdata) { + AI_ActBusyBehavior? behavior = GetBusyBehaviorForNPC(inputdata.Value.Entity().Get(), "InputForceThisNPCToActBusy"); + if (behavior == null) + return; + + behavior.SetBusySearchRange(BusySearchRange); + behavior.ForceActBusyNow(this); + } + + void InputForceThisNPCToLeave(InputData inputdata) { + AI_ActBusyBehavior? behavior = GetBusyBehaviorForNPC(inputdata.Value.Entity().Get(), "InputForceThisNPCToLeave"); + if (behavior == null) + return; + + behavior.SetBusySearchRange(BusySearchRange); + behavior.ForceActBusyLeave(); + } + + public virtual void NPCMovingToBusy(AI_BaseNPC npc) { } + + public virtual void NPCStartedBusy(AI_BaseNPC npc) { + EHANDLE hNPC = new(); + hNPC.Set(npc); + OnNPCStartedBusy.Set(hNPC, npc, this); + } + + public virtual void NPCStartedLeavingBusy(AI_BaseNPC npc) { } + + public virtual void NPCAbortedMoveTo(AI_BaseNPC npc) { } + + public virtual void NPCFinishedBusy(AI_BaseNPC npc) { + EHANDLE hNPC = new(); + hNPC.Set(npc); + OnNPCFinishedBusy.Set(hNPC, npc, this); + } + + public virtual void NPCLeft(AI_BaseNPC npc) { + EHANDLE hNPC = new(); + hNPC.Set(npc); + OnNPCLeft.Set(hNPC, npc, this); + } + + public virtual void NPCLostSeeEntity(AI_BaseNPC npc) { + EHANDLE hNPC = new(); + hNPC.Set(npc); + OnNPCLostSeeEntity.Set(hNPC, npc, this); + } + + public virtual void NPCSeeEnemy(AI_BaseNPC npc) { + EHANDLE hNPC = new(); + hNPC.Set(npc); + OnNPCSeeEnemy.Set(hNPC, npc, this); + } +} diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index e096155e6..6cb99b036 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -4333,6 +4333,31 @@ public virtual void OnScheduleChange() { public virtual float GetHintDelay(Hint hintType) => 0; + public void SetSequenceByName(ReadOnlySpan sequenceName) { + int sequence = LookupSequence(sequenceName); + + if (sequence > StudioHdr.ACTIVITY_NOT_AVAILABLE) + SetSequenceById(sequence); + else { + DevWarning(2, $"{GetClassname()} has no sequence {sequenceName} to match request\n"); + SetSequence(0); + } + } + + public void SetSequenceById(int sequence) { + if (sequence > StudioHdr.ACTIVITY_NOT_AVAILABLE) { + if (GetSequence() != sequence || !SequenceLoops) + SetCycle(0); + + ResetSequence(sequence); + GetMotor()!.RecalculateYawSpeed(); + } + else { + DevWarning(2, $"{GetClassname()} invalid sequence requested\n"); + SetSequence(0); + } + } + public virtual Activity GetHintActivity(short hintType, Activity hintsActivity) { if (hintsActivity != Activity.ACT_INVALID) return hintsActivity; @@ -7979,6 +8004,22 @@ public void ClearHintNode(float reuseDelay = 0.0f) { public virtual bool FValidateHintType(AI_Hint hint) => false; + public bool GetBehavior(out T? behavior) where T : AI_BehaviorBase { + List? behaviors = AccessBehaviors(); + + behavior = null; + if (behaviors != null) { + for (int i = 0; i < behaviors.Count; i++) { + behavior = behaviors[i] as T; + if (behavior != null) + return true; + } + } + return false; + } + + protected virtual List? AccessBehaviors() => null; + public BaseEntity? GetEnemy() => Enemy.Get(); public void SetEnemy(BaseEntity? enemy, bool setCondNewEnemy = true) { diff --git a/Game.Server/AI_BehaviorBase.cs b/Game.Server/AI_BehaviorBase.cs index 2044e00cd..07a81552c 100644 --- a/Game.Server/AI_BehaviorBase.cs +++ b/Game.Server/AI_BehaviorBase.cs @@ -119,6 +119,74 @@ public bool BridgeIsCurTaskContinuousMove(out bool result) { public bool BridgeIsCrouching() => IsCrouching(); public bool BridgeOnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => OnCalcBaseMove(ref moveGoal, distClear, ref result); + public bool BridgeFValidateHintType(AI_Hint hint, out bool result) { + bool prevOverride = Overrode; + Overrode = true; + result = FValidateHintType(hint); + bool overrode = Overrode; + Overrode = prevOverride; + return overrode; + } + + public bool BridgeShouldIgnoreSound(ref WorldSoundInstance sound) => ShouldIgnoreSound(ref sound); + public void BridgeOnSeeEntity(BaseEntity entity) => OnSeeEntity(entity); + public bool BridgeIsInterruptable() => IsInterruptable(); + public bool BridgeCanFlinch() => CanFlinch(); + public bool BridgeQueryHearSound(ref WorldSoundInstance sound) => QueryHearSound(ref sound); + public float BridgeGetReasonableFacingDist() => GetReasonableFacingDist(); + public void BridgeHandleAnimEvent(ref AnimEvent animEvent) => HandleAnimEvent(ref animEvent); + + protected virtual bool FValidateHintType(AI_Hint hint) { + Overrode = false; + return false; + } + + protected virtual bool ShouldIgnoreSound(ref WorldSoundInstance sound) { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_ShouldIgnoreSound(ref sound); + } + + protected virtual void OnSeeEntity(BaseEntity entity) { + Assert(BackBridge != null); + + BackBridge!.BackBridge_OnSeeEntity(entity); + } + + protected virtual bool IsInterruptable() { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_IsInterruptable(); + } + + protected virtual bool CanFlinch() { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_CanFlinch(); + } + + protected virtual bool QueryHearSound(ref WorldSoundInstance sound) { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_QueryHearSound(ref sound); + } + + protected virtual float GetReasonableFacingDist() { + Assert(BackBridge != null); + + return BackBridge!.BackBridge_GetReasonableFacingDist(); + } + + protected virtual void HandleAnimEvent(ref AnimEvent animEvent) { + Assert(BackBridge != null); + + BackBridge!.BackBridge_HandleAnimEvent(ref animEvent); + } + + protected AI_Hint? GetHintNode() => GetOuter()!.GetHintNode(); + protected void SetHintNode(AI_Hint? hintNode) => GetOuter()!.SetHintNode(hintNode); + protected void ClearHintNode(float reuseDelay = 0.0f) => GetOuter()!.ClearHintNode(reuseDelay); + public virtual void GatherConditions() { Assert(BackBridge != null); diff --git a/Game.Server/AI_BehaviorHost_AI_BaseNPC.cs b/Game.Server/AI_BehaviorHost_AI_BaseNPC.cs index 48b2460d9..472e246a0 100644 --- a/Game.Server/AI_BehaviorHost_AI_BaseNPC.cs +++ b/Game.Server/AI_BehaviorHost_AI_BaseNPC.cs @@ -192,6 +192,67 @@ public override bool OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClea return base.OnCalcBaseMove(ref moveGoal, distClear, ref result); } + public override bool FValidateHintType(AI_Hint hint) { + if (CurBehavior != null && CurBehavior.BridgeFValidateHintType(hint, out bool result)) + return result; + return base.FValidateHintType(hint); + } + + public override bool ShouldIgnoreSound(ref WorldSoundInstance sound) { + if (CurBehavior != null) + return CurBehavior.BridgeShouldIgnoreSound(ref sound); + + return base.ShouldIgnoreSound(ref sound); + } + + public override void OnSeeEntity(BaseEntity entity) { + if (CurBehavior != null) { + CurBehavior.BridgeOnSeeEntity(entity); + return; + } + + base.OnSeeEntity(entity); + } + + public override bool IsInterruptable() { + if (CurBehavior != null) + return CurBehavior.BridgeIsInterruptable(); + + return base.IsInterruptable(); + } + + public override bool CanFlinch() { + if (CurBehavior != null) + return CurBehavior.BridgeCanFlinch(); + + return base.CanFlinch(); + } + + public override bool QueryHearSound(ref WorldSoundInstance sound) { + if (CurBehavior != null) + return CurBehavior.BridgeQueryHearSound(ref sound); + + return base.QueryHearSound(ref sound); + } + + public override float GetReasonableFacingDist() { + if (CurBehavior != null) + return CurBehavior.BridgeGetReasonableFacingDist(); + + return base.GetReasonableFacingDist(); + } + + public override void HandleAnimEvent(ref AnimEvent animEvent) { + if (CurBehavior != null) { + CurBehavior.BridgeHandleAnimEvent(ref animEvent); + return; + } + + base.HandleAnimEvent(ref animEvent); + } + + protected override List? AccessBehaviors() => Behaviors; + public virtual bool OnBehaviorChangeStatus(AI_BehaviorBase behavior, bool canFinishSchedule) { if (behavior == GetRunningBehavior() && !behavior.CanSelectSchedule() && !canFinishSchedule) { DeferSchedulingToBehavior(null); @@ -286,6 +347,13 @@ void IBehaviorBackBridge.BackBridge_GatherConditions() { float IBehaviorBackBridge.BackBridge_GetDefaultNavGoalTolerance() => base.GetDefaultNavGoalTolerance(); bool IBehaviorBackBridge.BackBridge_IsCrouching() => base.IsCrouching(); bool IBehaviorBackBridge.BackBridge_OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) => base.OnCalcBaseMove(ref moveGoal, distClear, ref result); + bool IBehaviorBackBridge.BackBridge_ShouldIgnoreSound(ref WorldSoundInstance sound) => base.ShouldIgnoreSound(ref sound); + void IBehaviorBackBridge.BackBridge_OnSeeEntity(BaseEntity entity) => base.OnSeeEntity(entity); + bool IBehaviorBackBridge.BackBridge_IsInterruptable() => base.IsInterruptable(); + bool IBehaviorBackBridge.BackBridge_CanFlinch() => base.CanFlinch(); + bool IBehaviorBackBridge.BackBridge_QueryHearSound(ref WorldSoundInstance sound) => base.QueryHearSound(ref sound); + float IBehaviorBackBridge.BackBridge_GetReasonableFacingDist() => base.GetReasonableFacingDist(); + void IBehaviorBackBridge.BackBridge_HandleAnimEvent(ref AnimEvent animEvent) => base.HandleAnimEvent(ref animEvent); AI_BehaviorBase? CurBehavior; readonly List Behaviors = []; diff --git a/Game.Server/AI_Expresser.cs b/Game.Server/AI_Expresser.cs index 0b8ac6dd3..1682031df 100644 --- a/Game.Server/AI_Expresser.cs +++ b/Game.Server/AI_Expresser.cs @@ -105,6 +105,10 @@ public bool IsSpeaking() { return StopTalkTime > gpGlobals.CurTime; } + public bool CanSpeakConcept(ReadOnlySpan concept) => throw new NotImplementedException(); + + public bool Speak(ReadOnlySpan concept) => throw new NotImplementedException(); + public AI_TimedSemaphore? GetMySpeechSemaphore(BaseEntity? npc) { if (npc!.MyNPCPointer() == null) return null; diff --git a/Game.Server/AI_PlayerAlly.cs b/Game.Server/AI_PlayerAlly.cs index 8476658d2..5d0df8d7d 100644 --- a/Game.Server/AI_PlayerAlly.cs +++ b/Game.Server/AI_PlayerAlly.cs @@ -4,5 +4,7 @@ public class AI_PlayerAlly : AI_BaseActor { public override int SelectSchedule() => throw new NotImplementedException(); + public bool SelectInterjection() => throw new NotImplementedException(); + public override EntityCapabilities ObjectCaps() => UsableNPCObjectCaps(base.ObjectCaps()); } diff --git a/Game.Server/EntityBlocker.cs b/Game.Server/EntityBlocker.cs new file mode 100644 index 000000000..3b97c148b --- /dev/null +++ b/Game.Server/EntityBlocker.cs @@ -0,0 +1,32 @@ +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Formats.BSP; + +using System.Numerics; + +namespace Game.Server; + +[LinkEntityToClass("entity_blocker")] +public class EntityBlocker : BaseEntity +{ + public static EntityBlocker? Create(in Vector3 origin, in Vector3 mins, in Vector3 maxs, BaseEntity? owner = null, bool blockPhysics = false) { + EntityBlocker? blocker = (EntityBlocker?)Create("entity_blocker", origin, vec3_angle, owner); + + if (blocker != null) { + Util.SetSize(blocker, mins, maxs); + if (blockPhysics) + blocker.VPhysicsInitStatic(); + } + + return blocker; + } + + public override void Spawn() { + SetSolid(SolidType.BBox); + AddSolidFlags(SolidFlags.CustomRayTest); + } + + public override bool TestCollision(in Ray ray, Contents mask, ref Trace trace) => false; +} diff --git a/Game.Server/IBehaviorBackBridge.cs b/Game.Server/IBehaviorBackBridge.cs index ca06d0c09..2585d580c 100644 --- a/Game.Server/IBehaviorBackBridge.cs +++ b/Game.Server/IBehaviorBackBridge.cs @@ -11,4 +11,11 @@ public interface IBehaviorBackBridge float BackBridge_GetDefaultNavGoalTolerance(); bool BackBridge_IsCrouching(); bool BackBridge_OnCalcBaseMove(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result); + bool BackBridge_ShouldIgnoreSound(ref WorldSoundInstance sound); + void BackBridge_OnSeeEntity(BaseEntity entity); + bool BackBridge_IsInterruptable(); + bool BackBridge_CanFlinch(); + bool BackBridge_QueryHearSound(ref WorldSoundInstance sound); + float BackBridge_GetReasonableFacingDist(); + void BackBridge_HandleAnimEvent(ref Game.Shared.AnimEvent animEvent); } diff --git a/Game.Server/NPC_MetroPolice.cs b/Game.Server/NPC_MetroPolice.cs index 604ec5bd5..837b0443f 100644 --- a/Game.Server/NPC_MetroPolice.cs +++ b/Game.Server/NPC_MetroPolice.cs @@ -218,6 +218,8 @@ public class NPC_MetroPolice : AI_BaseActor Handle BlockingProp = new(); readonly AI_PolicingBehavior PolicingBehavior = new(); + readonly AI_ActBusyBehavior ActBusyBehavior = new(); + readonly AI_Sentence_NPC_MetroPolice Sentences = new(); int RecentDamage; @@ -1061,6 +1063,7 @@ void AnnounceTakeCoverFromDanger(ref WorldSoundInstance sound) { public override bool CreateBehaviors() { AddBehavior(PolicingBehavior); + AddBehavior(ActBusyBehavior); return base.CreateBehaviors(); } diff --git a/Game.Shared/UtilShared.cs b/Game.Shared/UtilShared.cs index 22d9724b6..335015bbe 100644 --- a/Game.Shared/UtilShared.cs +++ b/Game.Shared/UtilShared.cs @@ -564,6 +564,24 @@ public bool ShouldHitEntity(IHandleEntity handleEntity, Contents contentsMask) { } #endif +public struct TraceFilterOnlyNPCsAndPlayer(IHandleEntity? passentity, CollisionGroup collisionGroup) : ITraceFilter +{ + TraceFilterSimple Inner = new(passentity, collisionGroup); + + public readonly TraceType GetTraceType() => TraceType.EntitiesOnly; + + public bool ShouldHitEntity(IHandleEntity handleEntity, Contents contentsMask) { + if (Inner.ShouldHitEntity(handleEntity, contentsMask)) { + BaseEntity? entity = EntityFromEntityHandle(handleEntity); + if (entity == null) + return false; + + return entity.IsNPC() || entity.IsPlayer(); + } + return false; + } +} + public struct TraceFilterNoNPCsOrPlayer(IHandleEntity? passentity, CollisionGroup collisionGroup) : ITraceFilter { TraceFilterSimple Inner = new(passentity, collisionGroup); From 82f3a661c95248af4cfb88c124853750d4b383f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:03:47 +0300 Subject: [PATCH 51/73] Port engine trace GetCollideable --- Source.Engine/EngineTrace.cs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/Source.Engine/EngineTrace.cs b/Source.Engine/EngineTrace.cs index ec3adbfbc..4cb07e67e 100644 --- a/Source.Engine/EngineTrace.cs +++ b/Source.Engine/EngineTrace.cs @@ -370,9 +370,7 @@ public bool GetBrushInfo(int iBrush, ref List planesOut, out Contents c throw new NotImplementedException(); } - public ICollideable? GetCollideable(IHandleEntity? entity) { - throw new NotImplementedException(); - } + public abstract ICollideable? GetCollideable(IHandleEntity? entity); public int GetLeafContainingPoint(in Vector3 test) { throw new NotImplementedException(); @@ -626,6 +624,17 @@ public class EngineTraceClient : EngineTrace return pUnk?.GetCollideable(); } + public override ICollideable? GetCollideable(IHandleEntity? entity) { + Assert(entity != null); + + ICollideable? prop = StaticPropMgr().GetStaticProp(entity); + if (prop != null) + return prop; + + IClientUnknown? unk = entitylist.GetClientUnknownFromHandle(entity!.GetRefEHandle()); + return unk!.GetCollideable(); + } + public override void SetTraceEntity(ICollideable? collideable, ref Trace trace) { if (!trace.DidHit()) return; @@ -658,6 +667,17 @@ public class EngineTraceServer : EngineTrace return sv.Edicts[0].GetCollideable(); } + public override ICollideable? GetCollideable(IHandleEntity? entity) { + Assert(entity != null); + + ICollideable? prop = StaticPropMgr().GetStaticProp(entity); + if (prop != null) + return prop; + + IServerUnknown netUnknown = (IServerUnknown)entity!; + return netUnknown.GetCollideable(); + } + public override void SetTraceEntity(ICollideable? collideable, ref Trace trace) { if (!trace.DidHit()) return; From c19643ff9d031d9a5f8272467046b8613ae62e8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:34:19 +0300 Subject: [PATCH 52/73] Port breakable prop physgun pickup and pickup outputs --- Game.Server/Props.cs | 208 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 207 insertions(+), 1 deletion(-) diff --git a/Game.Server/Props.cs b/Game.Server/Props.cs index 7809985f4..39bd58495 100644 --- a/Game.Server/Props.cs +++ b/Game.Server/Props.cs @@ -58,7 +58,7 @@ public void ParsePropData() { } } [NetworkName("CBreakableProp")] -public class BreakableProp : BaseProp, IBreakableWithPropData +public class BreakableProp : BaseProp, IBreakableWithPropData, IPlayerPickupVPhysics { public static readonly SendTable DT_BreakableProp = new(DT_BaseAnimating, []); public static readonly new ServerClass ServerClass = new ServerClass(DT_BreakableProp); @@ -70,6 +70,149 @@ public void DisableAutoFade() { DefaultFadeScale = 0; } + const string s_pFadeScaleThink = "FadeScaleThink"; + const float PROP_FLARE_LIFETIME = 30.0f; + + public QAngle m_preferredCarryAngles; + + Handle PhysicsAttacker = new(); + TimeUnit_t LastPhysicsInfluenceTime; + bool OriginalBlockLOS; + string? PuntSound; + bool UsePuntSound; + + public BreakableProp() { + FadeMinDist = -1; + FadeMaxDist = 0; + FadeScale = 1; + DefaultFadeScale = 1; + MpBreakMode = MultiplayerBreak.Default; + + UsePuntSound = true; + } + + public override void Spawn() { + DefaultFadeScale = FadeScale; + + base.Spawn(); + + if (IsMarkedForDeletion()) + return; + + StudioHdr? studioHdr = GetModelPtr(); + + if (studioHdr == null) { + Msg("GARRY SEZ: CBreakableProp::Spawn - GetModelPtr returned NULL!\n"); + Msg($"Model Name: {GetModelName()}\n"); + } + + if (studioHdr != null && (studioHdr.Flags() & StudioHdrFlags.NoForcedFade) != 0) + DisableAutoFade(); + else + FadeScale = DefaultFadeScale; + + m_preferredCarryAngles = new(-5, 0, 0); + } + + public virtual void PlayPuntSound() { + if (!UsePuntSound) + return; + + if (PuntSound == null) + return; + + EmitSound(PuntSound); + } + + public void CheckRemoveRagdolls() { + if (HasSpawnFlags(SF_PHYSPROP_HAS_ATTACHED_RAGDOLLS)) + throw new NotImplementedException(); + } + + public void SetPhysicsAttacker(BasePlayer? entity, TimeUnit_t time) { + PhysicsAttacker.Set(entity); + LastPhysicsInfluenceTime = time; + } + + void ForceFadeScaleToAlwaysVisible() { + FadeScale = 0.0f; + SetContextThink(null, gpGlobals.CurTime, s_pFadeScaleThink); + } + + void RampToDefaultFadeScale() { + FadeScale += DefaultFadeScale * (float)TICK_INTERVAL / 2.0f; + if (FadeScale >= DefaultFadeScale) { + FadeScale = DefaultFadeScale; + SetContextThink(null, gpGlobals.CurTime, s_pFadeScaleThink); + } + else + SetContextThink(RampToDefaultFadeScale, gpGlobals.CurTime + TICK_INTERVAL, s_pFadeScaleThink); + } + + public virtual bool OnAttemptPhysGunPickup(BasePlayer physGunUser, PhysGunPickup reason = PhysGunPickup.PickedUpByCannon) => true; + + public virtual BaseEntity? OnFailedPhysGunPickup(Vector3 physgunPos) => null; + + public virtual void OnPhysGunPickup(BasePlayer physGunUser, PhysGunPickup reason = PhysGunPickup.PickedUpByCannon) { + if (reason == PhysGunPickup.PickedUpByCannon) + ForceFadeScaleToAlwaysVisible(); + else + SetContextThink(RampToDefaultFadeScale, gpGlobals.CurTime + 2.0f, s_pFadeScaleThink); + + if (reason == PhysGunPickup.PuntedByCannon) + PlayPuntSound(); + + SetPhysicsAttacker(physGunUser, gpGlobals.CurTime); + + OriginalBlockLOS = BlocksLOS(); + SetBlocksLOS(false); + + if (HasInteraction(PropDataInteractions.PhysgunCreateFlare)) + CreateFlare(PROP_FLARE_LIFETIME); + } + + public void CreateFlare(float lifetime) => throw new NotImplementedException(); + + public virtual void OnPhysGunDrop(BasePlayer physGunUser, PhysGunDrop reason) { + SetContextThink(RampToDefaultFadeScale, gpGlobals.CurTime + 2.0f, s_pFadeScaleThink); + + SetPhysicsAttacker(physGunUser, gpGlobals.CurTime); + + if ((PhysGunPickup)reason == PhysGunPickup.PuntedByCannon) + PlayPuntSound(); + + SetBlocksLOS(OriginalBlockLOS); + } + + public virtual bool HasPreferredCarryAnglesForPlayer(BasePlayer? player = null) { + if (HasInteraction(PropDataInteractions.PhysgunLaunchSpinZ)) + return true; + + return false; + } + + public virtual QAngle PreferredCarryAngles() => m_preferredCarryAngles; + + public virtual bool ForcePhysgunOpen(BasePlayer player) => false; + + public virtual Vector3 PhysGunLaunchAngularImpulse() { + if (HasInteraction(PropDataInteractions.PhysgunLaunchSpinNone) || HasInteraction(PropDataInteractions.PhysgunLaunchSpinZ)) + return new(0, 0, 0); + + return RandomAngularImpulse(-600, 600); + } + + public virtual bool ShouldPuntUseLaunchForces(PhysGunForce reason) => false; + + public virtual Vector3 PhysGunLaunchVelocity(in Vector3 forward, float mass) => Pickup.DefaultPhysGunLaunchVelocity(forward, mass); + + public virtual BasePlayer? HasPhysicsAttacker(TimeUnit_t dt) { + if (gpGlobals.CurTime - dt <= LastPhysicsInfluenceTime) + return PhysicsAttacker.Get(); + + return null; + } + public void SetDmgModBullet(float dmgMod) => DmgModBullet = dmgMod; public void SetDmgModClub(float dmgMod) => DmgModClub = dmgMod; public void SetDmgModExplosive(float dmgMod) => DmgModExplosive = dmgMod; @@ -163,6 +306,13 @@ public class PhysicsProp : BreakableProp DEFINE.KEYFIELD(nameof(OverrideScript), FieldType.String, "overridescript"), DEFINE.KEYFIELD(nameof(DamageToEnableMotion), FieldType.Integer, "damagetoenablemotion"), DEFINE.KEYFIELD(nameof(ForceToEnableMotion), FieldType.Float, "forcetoenablemotion"), + + DEFINE.OUTPUT(nameof(OnPhysGunPickup_), "OnPhysGunPickup", eventFuncs), + DEFINE.OUTPUT(nameof(OnPhysGunOnlyPickup), "OnPhysGunOnlyPickup", eventFuncs), + DEFINE.OUTPUT(nameof(OnPhysGunPunt), "OnPhysGunPunt", eventFuncs), + DEFINE.OUTPUT(nameof(OnPhysGunDrop_), "OnPhysGunDrop", eventFuncs), + DEFINE.OUTPUT(nameof(OnPlayerUse), "OnPlayerUse", eventFuncs), + DEFINE.OUTPUT(nameof(OnPlayerPickup), "OnPlayerPickup", eventFuncs), ]); public override DataMap? GetDataDescMap() => DataDesc; @@ -175,6 +325,62 @@ public class PhysicsProp : BreakableProp int DamageToEnableMotion; float ForceToEnableMotion; + bool FirstCollisionAfterLaunch; + bool ThrownByPlayer; + + public OutputEvent OnPhysGunPickup_ = new(); + public OutputEvent OnPhysGunPunt = new(); + public OutputEvent OnPhysGunOnlyPickup = new(); + public OutputEvent OnPhysGunDrop_ = new(); + public OutputEvent OnPlayerUse = new(); + public OutputEvent OnPlayerPickup = new(); + + public void EnableMotion() => throw new NotImplementedException(); + + public override void OnPhysGunPickup(BasePlayer physGunUser, PhysGunPickup reason = PhysGunPickup.PickedUpByCannon) { + base.OnPhysGunPickup(physGunUser, reason); + + IPhysicsObject? physicsObject = VPhysicsGetObject(); + if (physicsObject != null && !physicsObject.IsMoveable()) { + if (!HasSpawnFlags(SF_PHYSPROP_ENABLE_ON_PHYSCANNON)) + return; + + EnableMotion(); + } + + OnPhysGunPickup_.FireOutput(physGunUser, this); + + if (reason == PhysGunPickup.PickedUpByCannon) + OnPhysGunOnlyPickup.FireOutput(physGunUser, this); + + if (reason == PhysGunPickup.PuntedByCannon) + OnPhysGunPunt.FireOutput(physGunUser, this); + + if (reason == PhysGunPickup.PickedUpByCannon || reason == PhysGunPickup.PickedUpByPlayer) + OnPlayerPickup.FireOutput(physGunUser, this); + + CheckRemoveRagdolls(); + } + + public override void OnPhysGunDrop(BasePlayer physGunUser, PhysGunDrop reason) { + base.OnPhysGunDrop(physGunUser, reason); + + if (reason == PhysGunDrop.LaunchedByCannon) { + if (HasInteraction(PropDataInteractions.PhysgunLaunchSpinZ)) + throw new NotImplementedException(); + + PhysSetGameFlags(VPhysicsGetObject(), PhysicsFlags.WasThrown); + FirstCollisionAfterLaunch = true; + } + else if (reason == PhysGunDrop.ThrownByPlayer) + ThrownByPlayer = true; + + OnPhysGunDrop_.FireOutput(physGunUser, this); + + if (HasInteraction(PropDataInteractions.PhysgunNotifyChildren)) + throw new NotImplementedException(); + } + public override void Term() { if (HasSpawnFlags(SF_PHYSPROP_IS_GIB)) g_ActiveGibCount--; From 55fe0bbd177ef68d71eb159d6ad02d2535de2c2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:21:52 +0300 Subject: [PATCH 53/73] Port AI shot regulator and move-and-shoot overlay --- Game.Server/AI_BaseNPC.cs | 62 +++++++++++ Game.Server/AI_BehaviorBase.cs | 2 + Game.Server/AI_MoveAndShootOverlay.cs | 154 +++++++++++++++++++++++++- Game.Server/AI_Utils.cs | 104 +++++++++++++++++ Game.Server/BaseAnimatingOverlay.cs | 13 +++ Game.Server/NPC_MetroPolice.cs | 14 +++ Game.Shared/BaseCombatWeaponShared.cs | 3 + 7 files changed, 348 insertions(+), 4 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 6cb99b036..fb9311238 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -5687,6 +5687,21 @@ public bool HasCondition(int condition) { return ret; } + public bool HasCondition(int condition, bool useIgnoreConditions) { + if (useIgnoreConditions) + return HasCondition(condition); + + int interrupt = InterruptFromCondition(condition); + + if (interrupt == -1) { + Assert(false); + return false; + } + + bool ret = ConditionsPreIgnore.IsBitSet(interrupt); + return ret; + } + public void ClearCondition(int condition) { int interrupt = InterruptFromCondition(condition); @@ -7260,6 +7275,53 @@ public bool HasStrategySlotRange(SquadSlot slotIDStart, SquadSlot slotIDEnd) { public void SetLastAttackTime(TimeUnit_t time) => LastAttackTime = time; + protected readonly AI_ShotRegulator ShotRegulator = new(); + + public AI_ShotRegulator GetShotRegulator() => ShotRegulator; + + public bool ConditionsGathered() => ConditionsGatheredValue; + + public virtual BaseEntity? GetAlternateMoveShootTarget() => null; + + public virtual bool OnBeginMoveAndShoot() => true; + public virtual void OnEndMoveAndShoot() { } + + public virtual void OnUpdateShotRegulator() { + BaseCombatWeapon? weapon = GetActiveWeapon(); + if (weapon == null) + return; + + ShotRegulator.SetBurstInterval(weapon.GetFireRate(), weapon.GetFireRate()); + ShotRegulator.SetBurstShotCountRange(weapon.GetMinBurst(), weapon.GetMaxBurst()); + ShotRegulator.SetRestInterval((float)weapon.GetMinRestTime(), (float)weapon.GetMaxRestTime()); + + GetRunningBehavior()?.OnUpdateShotRegulator(); + } + + public override void OnChangeActiveWeapon(BaseCombatWeapon? oldWeapon, BaseCombatWeapon? newWeapon) { + base.OnChangeActiveWeapon(oldWeapon, newWeapon); + + if (newWeapon != null) { + OnUpdateShotRegulator(); + ShotRegulator.Reset(true); + } + } + + public virtual void OnRangeAttack1() { + SetLastAttackTime(gpGlobals.CurTime); + + Assert(GetShotRegulator().ShouldShoot()); + + ShotRegulator.OnFiredWeapon(); + if (ShotRegulator.IsInRestInterval()) + OnUpdateShotRegulator(); + + SetNextAttack(ShotRegulator.NextShotTime()); + + BaseCombatWeapon? wep = GetActiveWeapon(); + wep?.OnRangeAttack1(); + } + public void VacateStrategySlot() { if (Squad != null) { Squad.VacateStrategySlot(GetEnemy(), MySquadSlot); diff --git a/Game.Server/AI_BehaviorBase.cs b/Game.Server/AI_BehaviorBase.cs index 07a81552c..b811d0224 100644 --- a/Game.Server/AI_BehaviorBase.cs +++ b/Game.Server/AI_BehaviorBase.cs @@ -26,6 +26,8 @@ public bool IsRunning() { public virtual void BeginScheduleSelection() { } public virtual void EndScheduleSelection() { } + public virtual void OnUpdateShotRegulator() { } + public void SetBackBridge(IBehaviorBackBridge? backBridge) { Assert(BackBridge == null || backBridge == null); BackBridge = backBridge; diff --git a/Game.Server/AI_MoveAndShootOverlay.cs b/Game.Server/AI_MoveAndShootOverlay.cs index 5b3a8170b..fc52a4a39 100644 --- a/Game.Server/AI_MoveAndShootOverlay.cs +++ b/Game.Server/AI_MoveAndShootOverlay.cs @@ -1,5 +1,7 @@ using Game.Shared; +using System.Numerics; + namespace Game.Server; public class AI_MoveAndShootOverlay : AI_Component @@ -30,21 +32,165 @@ public void StartShootWhileMove() { return; } - throw new NotImplementedException(); + GetOuter()!.GetShotRegulator().FireNoEarlierThan(gpGlobals.CurTime + InitialDelay); + NoShootWhileMoveValue = false; + } + + bool CanAimAtEnemy() { + AI_BaseNPC outer = GetOuter()!; + bool result = false; + bool resetConditions = false; + AI_ScheduleBits savedConditions = default; + + if (!GetOuter()!.ConditionsGathered()) { + savedConditions = GetOuter()!.Conditions; + GetOuter()!.GatherEnemyConditions(GetOuter()!.GetEnemy()!); + } + + if (outer.HasCondition((int)SCOND_t.COND_CAN_RANGE_ATTACK1)) + result = true; + else if (!outer.HasCondition((int)SCOND_t.COND_ENEMY_DEAD) && + !outer.HasCondition((int)SCOND_t.COND_TOO_FAR_TO_ATTACK) && + !outer.HasCondition((int)SCOND_t.COND_ENEMY_TOO_FAR) && + !outer.HasCondition((int)SCOND_t.COND_ENEMY_OCCLUDED)) + result = true; + + if (!HasAvailableRangeAttack()) + result = false; + + if (resetConditions) + GetOuter()!.Conditions = savedConditions; + + return result; + } + + void UpdateMoveShootActivity(bool moveAimAtEnemy) { + Activity curActivity = GetOuter()!.GetNavigator()!.GetMovementActivity(); + Activity newActivity = curActivity; + + if (moveAimAtEnemy) { + switch (curActivity) { + case Activity.ACT_WALK: + newActivity = Activity.ACT_WALK_AIM; + break; + case Activity.ACT_RUN: + newActivity = Activity.ACT_RUN_AIM; + break; + } + } + else { + switch (curActivity) { + case Activity.ACT_WALK_AIM: + newActivity = Activity.ACT_WALK; + break; + case Activity.ACT_RUN_AIM: + newActivity = Activity.ACT_RUN; + break; + } + } + + if (curActivity != newActivity) { + GetOuter()!.GetShotRegulator().FireNoEarlierThan(gpGlobals.CurTime + 0.3f); + GetOuter()!.GetNavigator()!.SetMovementActivity(newActivity); + } } public void RunShootWhileMove() { if (NoShootWhileMoveValue) return; - throw new NotImplementedException(); + if (gpGlobals.CurTime < SuspendUntilTime) + return; + + SuspendUntilTime = MOVESHOOT_DO_NOT_SUSPEND; + + AI_BaseNPC outer = GetOuter()!; + + if (outer.GetEnemy() == null || !outer.GetEnemy()!.IsAlive()) { + BaseEntity? newEnemy = outer.BestEnemy(); + + if (newEnemy != null) { + outer.SetEnemy(newEnemy); + outer.SetState(NPCState.Combat); + } + else + outer.ClearAttackConditions(); + } + + if (!outer.GetNavigator()!.IsGoalActive()) + return; + + if (outer.GetEnemy() == null) { + if (outer.GetAlternateMoveShootTarget() != null) + outer.AddFacingTarget(outer.GetAlternateMoveShootTarget(), outer.GetAlternateMoveShootTarget()!.GetAbsOrigin(), 1.0f, 0.2f); + + return; + } + + bool moveAimAtEnemy = CanAimAtEnemy(); + UpdateMoveShootActivity(moveAimAtEnemy); + if (!moveAimAtEnemy) { + EndShootWhileMove(); + return; + } + + Assert(HasAvailableRangeAttack()); + + Activity activity; + bool isReloading = false; + + if ((activity = outer.TranslateActivity(Activity.ACT_GESTURE_RELOAD)) != Activity.ACT_INVALID) + isReloading = outer.IsPlayingGesture(activity); + + if (!isReloading && HasAvailableRangeAttack()) { + if (outer.HasCondition((int)SCOND_t.COND_CAN_RANGE_ATTACK1, false)) { + if (outer.GetShotRegulator().IsInRestInterval()) + EndShootWhileMove(); + else if (outer.GetShotRegulator().ShouldShoot()) { + if (MovingAndShooting || outer.OnBeginMoveAndShoot()) { + MovingAndShooting = true; + outer.OnRangeAttack1(); + + activity = outer.TranslateActivity(Activity.ACT_GESTURE_RANGE_ATTACK1); + Assert(activity != Activity.ACT_INVALID); + + outer.RestartGesture(activity); + + bool identical = false; + outer.Weapon_SetActivity(outer.Weapon_TranslateActivity(Activity.ACT_RANGE_ATTACK1, ref identical), 0); + } + } + } + else if (outer.HasCondition((int)SCOND_t.COND_NO_PRIMARY_AMMO, false)) { + if (outer.GetNavigator()!.GetPathTimeToGoal() > 1.0) { + activity = outer.TranslateActivity(Activity.ACT_GESTURE_RELOAD); + if (activity != Activity.ACT_INVALID && GetOuter()!.HaveSequenceForActivity(activity)) + outer.AddGesture(activity); + } + } + } + + Vector3 enemyLKP = outer.GetEnemyLKP(); + outer.AddFacingTarget(outer.GetEnemy(), enemyLKP, 1.0f, 0.8f); } public void EndShootWhileMove() { - if (MovingAndShooting) - throw new NotImplementedException(); + if (MovingAndShooting) { + if (!GetOuter()!.GetShotRegulator().IsInRestInterval()) + GetOuter()!.GetShotRegulator().Reset(false); + + MovingAndShooting = false; + GetOuter()!.OnEndMoveAndShoot(); + } } + public void SuspendMoveAndShoot(float duration) { + EndShootWhileMove(); + SuspendUntilTime = gpGlobals.CurTime + duration; + } + + public void SetInitialDelay(float delay) => InitialDelay = delay; + public bool IsMovingAndShooting() => MovingAndShooting; bool MovingAndShooting; diff --git a/Game.Server/AI_Utils.cs b/Game.Server/AI_Utils.cs index 37fd42092..f6229e668 100644 --- a/Game.Server/AI_Utils.cs +++ b/Game.Server/AI_Utils.cs @@ -72,6 +72,110 @@ public bool TargetMoved2D(BaseEntity? entity) { float MarkTolerance; } +public class AI_ShotRegulator +{ + public AI_ShotRegulator() { + MinBurstShots = 1; + MaxBurstShots = 1; + MinRestInterval = 0.0f; + MaxRestInterval = 0.0f; + MinBurstInterval = 0.0f; + MaxBurstInterval = 0.0f; + NextShotTimeValue = -1; + BurstShotsRemaining = 1; + InRestInterval = false; + Disabled = false; + } + + public void SetParameters(int minShotsPerBurst, int maxShotsPerBurst, float minRestTime, float maxRestTime = 0.0f) { + SetBurstShotCountRange(minShotsPerBurst, maxShotsPerBurst); + SetRestInterval(minRestTime, maxRestTime); + Reset(false); + } + + public void SetBurstShotCountRange(int minShotsPerBurst, int maxShotsPerBurst) { + MinBurstShots = (ushort)minShotsPerBurst; + MaxBurstShots = (ushort)maxShotsPerBurst; + } + + public void SetRestInterval(float minRestInterval, float maxRestInterval) { + MinRestInterval = minRestInterval; + MaxRestInterval = maxRestInterval; + } + + public void SetBurstInterval(float minBurstInterval, float maxBurstInterval) { + MinBurstInterval = minBurstInterval; + MaxBurstInterval = maxBurstInterval; + } + + public void GetBurstShotCountRange(out int minShotsPerBurst, out int maxShotsPerBurst) { + minShotsPerBurst = MinBurstShots; + maxShotsPerBurst = MaxBurstShots; + } + + public void GetRestInterval(out float minRestInterval, out float maxRestInterval) { + minRestInterval = MinRestInterval; + maxRestInterval = MaxRestInterval; + } + + public void GetBurstInterval(out float minBurstInterval, out float maxBurstInterval) { + minBurstInterval = MinBurstInterval; + maxBurstInterval = MaxBurstInterval; + } + + public void Reset(bool startShooting = true) { + Disabled = false; + BurstShotsRemaining = (ushort)random.RandomInt(MinBurstShots, MaxBurstShots); + if (startShooting) { + NextShotTimeValue = gpGlobals.CurTime; + InRestInterval = false; + } + else { + NextShotTimeValue = gpGlobals.CurTime + random.RandomFloat(MinRestInterval, MaxRestInterval); + InRestInterval = true; + } + } + + public bool ShouldShoot() => !Disabled && NextShotTimeValue <= gpGlobals.CurTime; + + public bool IsInRestInterval() => InRestInterval && !ShouldShoot(); + + public TimeUnit_t NextShotTime() => NextShotTimeValue; + + public void FireNoEarlierThan(TimeUnit_t time) { + if (time > NextShotTimeValue) + NextShotTimeValue = time; + } + + public int GetBurstShotsRemaining() => BurstShotsRemaining; + + public void SetBurstShotsRemaining(int shots) => BurstShotsRemaining = (ushort)shots; + + public void OnFiredWeapon() { + --BurstShotsRemaining; + if (BurstShotsRemaining <= 0) + Reset(false); + else { + InRestInterval = false; + NextShotTimeValue += random.RandomFloat(MinBurstInterval, MaxBurstInterval); + if (NextShotTimeValue < gpGlobals.CurTime) + NextShotTimeValue = gpGlobals.CurTime; + } + } + + public void EnableShooting() => Disabled = false; + + public void DisableShooting() => Disabled = true; + + TimeUnit_t NextShotTimeValue; + bool InRestInterval; + ushort BurstShotsRemaining; + ushort MinBurstShots, MaxBurstShots; + float MinRestInterval, MaxRestInterval; + float MinBurstInterval, MaxBurstInterval; + bool Disabled; +} + public struct TraceFilterNav : ITraceFilter { public TraceFilterNav(AI_BaseNPC prober, bool ignoreTransientEntities, IHandleEntity? passedict, CollisionGroup collisionGroup, bool allowPlayerAvoid = true) { diff --git a/Game.Server/BaseAnimatingOverlay.cs b/Game.Server/BaseAnimatingOverlay.cs index 04954c736..5688a99c2 100644 --- a/Game.Server/BaseAnimatingOverlay.cs +++ b/Game.Server/BaseAnimatingOverlay.cs @@ -216,6 +216,19 @@ public int FindGestureLayer(Activity activity) { public bool IsPlayingGesture(Activity activity) => FindGestureLayer(activity) != -1; + public void RestartGesture(Activity activity, bool addIfMissing = true, bool autokill = true) { + int idx = FindGestureLayer(activity); + if (idx == -1) { + if (addIfMissing) + AddGesture(activity, autokill); + return; + } + + AnimOverlay[idx].Cycle = 0.0f; + AnimOverlay[idx].PrevCycle = 0.0f; + AnimOverlay[idx].LastEventCheck = 0.0f; + } + public int AddLayeredSequence(int sequence, int priority) { int i = AllocateLayer(priority); if (IsValidLayer(i)) { diff --git a/Game.Server/NPC_MetroPolice.cs b/Game.Server/NPC_MetroPolice.cs index 837b0443f..170db7b24 100644 --- a/Game.Server/NPC_MetroPolice.cs +++ b/Game.Server/NPC_MetroPolice.cs @@ -1061,6 +1061,20 @@ void AnnounceTakeCoverFromDanger(ref WorldSoundInstance sound) { Sentences.Speak("METROPOLICE_DANGER", SentencePriority.High, SentenceCriteria.Normal); } + public override bool OnBeginMoveAndShoot() { + if (base.OnBeginMoveAndShoot()) { + if (HasStrategySlotRange(SquadSlot.Attack1, SquadSlot.Attack2)) + return true; + + if (OccupyStrategySlotRange(SquadSlot.Attack1, SquadSlot.Attack2)) + return true; + } + + return false; + } + + public override void OnEndMoveAndShoot() => VacateStrategySlot(); + public override bool CreateBehaviors() { AddBehavior(PolicingBehavior); AddBehavior(ActBusyBehavior); diff --git a/Game.Shared/BaseCombatWeaponShared.cs b/Game.Shared/BaseCombatWeaponShared.cs index 188fc34d6..574f19aba 100644 --- a/Game.Shared/BaseCombatWeaponShared.cs +++ b/Game.Shared/BaseCombatWeaponShared.cs @@ -821,6 +821,9 @@ public virtual void WeaponIdle() { public virtual TimeUnit_t GetMinRestTime() => 0.3; public virtual TimeUnit_t GetMaxRestTime() => 0.6; public virtual int GetRandomBurst() => random.RandomInt(GetMinBurst(), GetMaxBurst()); +#if !CLIENT_DLL + public virtual void OnRangeAttack1() { } +#endif public virtual void SecondaryAttack() { } public bool DefaultReload(int clipSize1, int clipSize2, Activity activity) { From c217bbbfe966cdb8136c5b3c24a3df8dfee230a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 18:06:41 +0300 Subject: [PATCH 54/73] Rename Animevent to AnimEventId --- Game.Server/AI_ActBusyBehavior.cs | 4 +- Game.Server/AI_BaseNPC.cs | 28 ++++----- Game.Server/BaseAnimating.cs | 6 +- Game.Server/BaseCombatWeapon.cs | 4 +- Game.Server/NPC_MetroPolice.cs | 12 ++-- Game.Shared/EventList.cs | 98 +++++++++++++++---------------- 6 files changed, 76 insertions(+), 76 deletions(-) diff --git a/Game.Server/AI_ActBusyBehavior.cs b/Game.Server/AI_ActBusyBehavior.cs index ce76c92d5..8cf00a864 100644 --- a/Game.Server/AI_ActBusyBehavior.cs +++ b/Game.Server/AI_ActBusyBehavior.cs @@ -170,8 +170,8 @@ public class AI_ActBusyBehavior : AI_Behavior_AI_BaseNPC_100000 "4: Display debug output of actbusy logic.\n" + "5: Display safe zone volumes and info.\n"); - static Animevent AE_ACTBUSY_WEAPON_FIRE_ON; - static Animevent AE_ACTBUSY_WEAPON_FIRE_OFF; + static AnimEventId AE_ACTBUSY_WEAPON_FIRE_ON; + static AnimEventId AE_ACTBUSY_WEAPON_FIRE_OFF; public const int SCHED_ACTBUSY_START_BUSYING = NEXT_SCHEDULE; public const int SCHED_ACTBUSY_BUSY = NEXT_SCHEDULE + 1; diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index fb9311238..ad4787b6f 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -645,8 +645,8 @@ public static void AddEventToSR(ReadOnlySpan eventName, int eventID) { NumEvents++; } - public static Animevent DeclareAnimEvent(ReadOnlySpan name) { - Animevent animEvent = EventList.RegisterPrivateEvent(name); + public static AnimEventId DeclareAnimEvent(ReadOnlySpan name) { + AnimEventId animEvent = EventList.RegisterPrivateEvent(name); AddEventToSR(name, (int)animEvent); return animEvent; } @@ -2784,7 +2784,7 @@ public override void HandleAnimEvent(ref AnimEvent animEvent) { DevMsg("Bodygroup!\n"); break; - case (int)Animevent.AE_NPC_ATTACK_BROADCAST: + case (int)AnimEventId.AE_NPC_ATTACK_BROADCAST: break; case NPC_EVENT_BODYDROP_HEAVY: @@ -2880,7 +2880,7 @@ public override void HandleAnimEvent(ref AnimEvent animEvent) { default: if ((animEvent.Type & AnimEventType.NewEventSystem) != 0 && (animEvent.Type & AnimEventType.Server) != 0) { - if (animEvent.Event == (int)Animevent.AE_NPC_HOLSTER) { + if (animEvent.Event == (int)AnimEventId.AE_NPC_HOLSTER) { BaseCombatWeapon? weapon = GetActiveWeapon(); Assert(weapon != null); @@ -2900,7 +2900,7 @@ public override void HandleAnimEvent(ref AnimEvent animEvent) { return; } - else if (animEvent.Event == (int)Animevent.AE_NPC_DRAW) { + else if (animEvent.Event == (int)AnimEventId.AE_NPC_DRAW) { if (GetActiveWeapon() != null) { GetActiveWeapon()!.Deploy(); @@ -2913,16 +2913,16 @@ public override void HandleAnimEvent(ref AnimEvent animEvent) { } return; } - else if (animEvent.Event == (int)Animevent.AE_NPC_BODYDROP_HEAVY) { + else if (animEvent.Event == (int)AnimEventId.AE_NPC_BODYDROP_HEAVY) { if ((GetFlags() & EntityFlags.OnGround) != 0) EmitSound("AI_BaseNPC.BodyDrop_Heavy"); return; } - else if (animEvent.Event == (int)Animevent.AE_NPC_LEFTFOOT || animEvent.Event == (int)Animevent.AE_NPC_RIGHTFOOT) + else if (animEvent.Event == (int)AnimEventId.AE_NPC_LEFTFOOT || animEvent.Event == (int)AnimEventId.AE_NPC_RIGHTFOOT) return; - else if (animEvent.Event == (int)Animevent.AE_NPC_RAGDOLL) + else if (animEvent.Event == (int)AnimEventId.AE_NPC_RAGDOLL) throw new NotImplementedException(); - else if (animEvent.Event == (int)Animevent.AE_NPC_ADDGESTURE) { + else if (animEvent.Event == (int)AnimEventId.AE_NPC_ADDGESTURE) { Activity act = LookupActivity(animEvent.Options); if (act != Activity.ACT_INVALID) { act = TranslateActivity(act); @@ -2931,11 +2931,11 @@ public override void HandleAnimEvent(ref AnimEvent animEvent) { } return; } - else if (animEvent.Event == (int)Animevent.AE_NPC_RESTARTGESTURE) + else if (animEvent.Event == (int)AnimEventId.AE_NPC_RESTARTGESTURE) throw new NotImplementedException(); - else if (animEvent.Event == (int)Animevent.AE_NPC_WEAPON_DROP) + else if (animEvent.Event == (int)AnimEventId.AE_NPC_WEAPON_DROP) throw new NotImplementedException(); - else if (animEvent.Event == (int)Animevent.AE_NPC_WEAPON_SET_ACTIVITY) { + else if (animEvent.Event == (int)AnimEventId.AE_NPC_WEAPON_SET_ACTIVITY) { BaseCombatWeapon? weapon = GetActiveWeapon(); if (weapon != null && animEvent.Options != null) { Activity act = weapon.LookupActivity(animEvent.Options); @@ -2950,9 +2950,9 @@ public override void HandleAnimEvent(ref AnimEvent animEvent) { } return; } - else if (animEvent.Event == (int)Animevent.AE_NPC_SET_INTERACTION_CANTDIE) + else if (animEvent.Event == (int)AnimEventId.AE_NPC_SET_INTERACTION_CANTDIE) throw new NotImplementedException(); - else if (animEvent.Event == (int)Animevent.AE_NPC_HURT_INTERACTION_PARTNER) + else if (animEvent.Event == (int)AnimEventId.AE_NPC_HURT_INTERACTION_PARTNER) throw new NotImplementedException(); } diff --git a/Game.Server/BaseAnimating.cs b/Game.Server/BaseAnimating.cs index 7861a6f1b..45dad5666 100644 --- a/Game.Server/BaseAnimating.cs +++ b/Game.Server/BaseAnimating.cs @@ -981,14 +981,14 @@ public virtual void DispatchAnimEvents(BaseAnimating eventHandler) { public virtual void HandleAnimEvent(ref AnimEvent animEvent) { if ((animEvent.Type & AnimEventType.NewEventSystem) != 0 && (animEvent.Type & AnimEventType.Server) != 0) { - if (animEvent.Event == (int)Animevent.AE_SV_PLAYSOUND) { + if (animEvent.Event == (int)AnimEventId.AE_SV_PLAYSOUND) { EmitSound(animEvent.Options); return; } - else if (animEvent.Event == (int)Animevent.AE_RAGDOLL) { + else if (animEvent.Event == (int)AnimEventId.AE_RAGDOLL) { throw new NotImplementedException(); } - else if (animEvent.Event == (int)Animevent.AE_SV_DUSTTRAIL) { + else if (animEvent.Event == (int)AnimEventId.AE_SV_DUSTTRAIL) { throw new NotImplementedException(); } } diff --git a/Game.Server/BaseCombatWeapon.cs b/Game.Server/BaseCombatWeapon.cs index cb8da7d66..aaa817f2f 100644 --- a/Game.Server/BaseCombatWeapon.cs +++ b/Game.Server/BaseCombatWeapon.cs @@ -132,12 +132,12 @@ public virtual void Operator_FrameUpdate(BaseCombatCharacter op) { public virtual void Operator_HandleAnimEvent(ref AnimEvent animEvent, BaseCombatCharacter op) { if ((animEvent.Type & AnimEventType.NewEventSystem) != 0 && (animEvent.Type & AnimEventType.Server) != 0) { - if (animEvent.Event == (int)Animevent.AE_NPC_WEAPON_FIRE) { + if (animEvent.Event == (int)AnimEventId.AE_NPC_WEAPON_FIRE) { bool secondary = int.TryParse(animEvent.Options, out int value) && value != 0; Operator_ForceNPCFire(op, secondary); return; } - else if (animEvent.Event == (int)Animevent.AE_WPN_PLAYWPNSOUND) { + else if (animEvent.Event == (int)AnimEventId.AE_WPN_PLAYWPNSOUND) { int snd = WeaponParse.GetWeaponSoundFromString(animEvent.Options); if (snd != -1) WeaponSound((WeaponSound)snd); diff --git a/Game.Server/NPC_MetroPolice.cs b/Game.Server/NPC_MetroPolice.cs index 170db7b24..7a34ca54f 100644 --- a/Game.Server/NPC_MetroPolice.cs +++ b/Game.Server/NPC_MetroPolice.cs @@ -73,12 +73,12 @@ public class NPC_MetroPolice : AI_BaseActor public static readonly ConVar metropolice_move_and_melee = new("metropolice_move_and_melee", "1"); public static readonly ConVar metropolice_charge = new("metropolice_charge", "1"); - public static Animevent AE_METROPOLICE_BATON_ON; - public static Animevent AE_METROPOLICE_BATON_OFF; - public static Animevent AE_METROPOLICE_SHOVE; - public static Animevent AE_METROPOLICE_START_DEPLOY; - public static Animevent AE_METROPOLICE_DRAW_PISTOL; - public static Animevent AE_METROPOLICE_DEPLOY_MANHACK; + public static AnimEventId AE_METROPOLICE_BATON_ON; + public static AnimEventId AE_METROPOLICE_BATON_OFF; + public static AnimEventId AE_METROPOLICE_SHOVE; + public static AnimEventId AE_METROPOLICE_START_DEPLOY; + public static AnimEventId AE_METROPOLICE_DRAW_PISTOL; + public static AnimEventId AE_METROPOLICE_DEPLOY_MANHACK; const SquadSlot SQUAD_SLOT_POLICE_CHARGE_ENEMY = SquadSlot.LastShared; const SquadSlot SQUAD_SLOT_POLICE_HARASS = SquadSlot.LastShared + 1; diff --git a/Game.Shared/EventList.cs b/Game.Shared/EventList.cs index 666f73fc6..b48907856 100644 --- a/Game.Shared/EventList.cs +++ b/Game.Shared/EventList.cs @@ -15,7 +15,7 @@ public enum AnimEventType NewEventSystem = 1 << 10 } -public enum Animevent +public enum AnimEventId { AE_INVALID = -1, AE_EMPTY, @@ -169,20 +169,20 @@ public static bool RegisterSharedEvent(ReadOnlySpan eventName, int eventIn return true; } - public static Animevent RegisterPrivateEvent(ReadOnlySpan eventName) { + public static AnimEventId RegisterPrivateEvent(ReadOnlySpan eventName) { int list = ListFromString(eventName); if (list != -1) { if (g_EventList[list].IsPrivate) - return (Animevent)g_EventList[list].EventIndex; + return (AnimEventId)g_EventList[list].EventIndex; else { Warning("***\nShared<->Private Event collision!\n***\n"); Assert(false); - return Animevent.AE_INVALID; + return AnimEventId.AE_INVALID; } } EventListEntry entry = AddEventEntry(eventName, g_HighestEvent + 1, true, AnimEventType.Server); - return (Animevent)entry.EventIndex; + return (AnimEventId)entry.EventIndex; } public static int IndexForName(ReadOnlySpan eventName) { @@ -202,68 +202,68 @@ public static int IndexForName(ReadOnlySpan eventName) { return null; } - static void REGISTER_SHARED_ANIMEVENT(Animevent n, AnimEventType b) => RegisterSharedEvent(Enum.GetName(n), (int)n, b); + static void REGISTER_SHARED_ANIMEVENT(AnimEventId n, AnimEventType b) => RegisterSharedEvent(Enum.GetName(n), (int)n, b); public static void RegisterSharedEvents() { - REGISTER_SHARED_ANIMEVENT(Animevent.AE_EMPTY, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_EMPTY, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_LEFTFOOT, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_RIGHTFOOT, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_BODYDROP_LIGHT, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_BODYDROP_HEAVY, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_SWISHSOUND, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_180TURN, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_ITEM_PICKUP, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_WEAPON_DROP, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_WEAPON_SET_SEQUENCE_NAME, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_WEAPON_SET_SEQUENCE_NUMBER, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_WEAPON_SET_ACTIVITY, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_HOLSTER, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_DRAW, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_WEAPON_FIRE, AnimEventType.Server | AnimEventType.Weapon); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_LEFTFOOT, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_RIGHTFOOT, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_BODYDROP_LIGHT, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_BODYDROP_HEAVY, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_SWISHSOUND, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_180TURN, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_ITEM_PICKUP, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_WEAPON_DROP, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_WEAPON_SET_SEQUENCE_NAME, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_WEAPON_SET_SEQUENCE_NUMBER, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_WEAPON_SET_ACTIVITY, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_HOLSTER, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_DRAW, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_WEAPON_FIRE, AnimEventType.Server | AnimEventType.Weapon); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_CL_PLAYSOUND, AnimEventType.Client); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_SV_PLAYSOUND, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_CL_STOPSOUND, AnimEventType.Client); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CL_PLAYSOUND, AnimEventType.Client); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_SV_PLAYSOUND, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CL_STOPSOUND, AnimEventType.Client); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_START_SCRIPTED_EFFECT, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_STOP_SCRIPTED_EFFECT, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_START_SCRIPTED_EFFECT, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_STOP_SCRIPTED_EFFECT, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_CLIENT_EFFECT_ATTACH, AnimEventType.Client); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CLIENT_EFFECT_ATTACH, AnimEventType.Client); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_MUZZLEFLASH, AnimEventType.Client); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_MUZZLEFLASH, AnimEventType.Client); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_MUZZLEFLASH, AnimEventType.Client); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_MUZZLEFLASH, AnimEventType.Client); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_THUMPER_THUMP, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_AMMOCRATE_PICKUP_AMMO, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_THUMPER_THUMP, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_AMMOCRATE_PICKUP_AMMO, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_RAGDOLL, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_RAGDOLL, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_ADDGESTURE, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_RESTARTGESTURE, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_ADDGESTURE, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_RESTARTGESTURE, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_ATTACK_BROADCAST, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_ATTACK_BROADCAST, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_HURT_INTERACTION_PARTNER, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_NPC_SET_INTERACTION_CANTDIE, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_HURT_INTERACTION_PARTNER, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_NPC_SET_INTERACTION_CANTDIE, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_SV_DUSTTRAIL, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_SV_DUSTTRAIL, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_CL_CREATE_PARTICLE_EFFECT, AnimEventType.Client); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CL_CREATE_PARTICLE_EFFECT, AnimEventType.Client); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_RAGDOLL, AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_RAGDOLL, AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_CL_ENABLE_BODYGROUP, AnimEventType.Client); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_CL_DISABLE_BODYGROUP, AnimEventType.Client); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_CL_BODYGROUP_SET_VALUE, AnimEventType.Client); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_CL_BODYGROUP_SET_VALUE_CMODEL_WPN, AnimEventType.Client); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CL_ENABLE_BODYGROUP, AnimEventType.Client); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CL_DISABLE_BODYGROUP, AnimEventType.Client); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CL_BODYGROUP_SET_VALUE, AnimEventType.Client); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CL_BODYGROUP_SET_VALUE_CMODEL_WPN, AnimEventType.Client); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_WPN_PRIMARYATTACK, AnimEventType.Client | AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_WPN_INCREMENTAMMO, AnimEventType.Client | AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_WPN_PRIMARYATTACK, AnimEventType.Client | AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_WPN_INCREMENTAMMO, AnimEventType.Client | AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_WPN_HIDE, AnimEventType.Client | AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_WPN_UNHIDE, AnimEventType.Client | AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_WPN_HIDE, AnimEventType.Client | AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_WPN_UNHIDE, AnimEventType.Client | AnimEventType.Server); - REGISTER_SHARED_ANIMEVENT(Animevent.AE_WPN_PLAYWPNSOUND, AnimEventType.Client | AnimEventType.Server); + REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_WPN_PLAYWPNSOUND, AnimEventType.Client | AnimEventType.Server); } } From 80547987fe417fae63f4e0e09d098784e7220d08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 18:46:42 +0300 Subject: [PATCH 55/73] Scrap this idiotic GetInteractionID system --- Game.Server/AI_Interaction.cs | 64 ++++++++++++++++++++++++++++++ Game.Server/AI_Squad.cs | 2 +- Game.Server/BaseCombatCharacter.cs | 11 +---- Game.Server/NPC_MetroPolice.cs | 21 ++++------ Game.Server/Props.cs | 2 - 5 files changed, 74 insertions(+), 26 deletions(-) create mode 100644 Game.Server/AI_Interaction.cs diff --git a/Game.Server/AI_Interaction.cs b/Game.Server/AI_Interaction.cs new file mode 100644 index 000000000..107618c06 --- /dev/null +++ b/Game.Server/AI_Interaction.cs @@ -0,0 +1,64 @@ +namespace Game.Server; + +// All of them used to by dynamically allocated via GetInteractionID, +// to simplify things its now a fixed identifier, nothing stores them and dynamically +// allocating has no advantage. +public enum AI_Interaction +{ + None = 0, + + AntlionFoundTarget, + AntlionFiredAtTarget, + AntlionKilled, + + AntlionGuardFoundPhysicsObject, + AntlionGuardShovedPhysicsObject, + + BarnacleVictimDangle, + BarnacleVictimReleased, + BarnacleVictimGrab, + BarnacleVictimBite, + + BullsquidThrow, + + CombineBash, + CombineRequestCover, + + HoundeyeGroupAttack, + HoundeyeGroupRetreat, + HoundeyeGroupRalley, + + HunterFoundEnemy, + + ScannerInspect, + ScannerInspectBegin, + ScannerInspectDone, + ScannerInspectHandsUp, + ScannerInspectShowArmband, + ScannerSupportEntity, + ScannerSupportPosition, + + MetrocopPointed, + MetrocopStartedStitch, + MetrocopIdleChatter, + MetrocopClearSentenceQueues, + + ScriptedTarget, + + StalkerBurn, + + VortigauntStomp, + VortigauntStompFail, + VortigauntStompHit, + VortigauntKick, + VortigauntClaw, + + TurretStillStanding, + + PlayerLaunchedRPG, + + HitByPlayerThrownPhysObj, + PlayerPuntedHeavyObject, + + ZombieMeleeWarning, +} diff --git a/Game.Server/AI_Squad.cs b/Game.Server/AI_Squad.cs index a43d46992..386aec703 100644 --- a/Game.Server/AI_Squad.cs +++ b/Game.Server/AI_Squad.cs @@ -30,7 +30,7 @@ public class AI_Squad public void JustMadeSound(SentencePriority soundPriority, TimeUnit_t time) => throw new NotImplementedException(); public bool IsLeader(AI_BaseNPC npc) => throw new NotImplementedException(); public void SquadRemember(AI_MemoryFlags memory) => throw new NotImplementedException(); - public void BroadcastInteraction(int interactionType, object? data, BaseCombatCharacter? sender) => 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(); public AI_BaseNPC? GetNextMember(ref int iter) => throw new NotImplementedException(); public void VacateStrategySlot(BaseEntity? enemy, SquadSlot slot) => throw new NotImplementedException(); diff --git a/Game.Server/BaseCombatCharacter.cs b/Game.Server/BaseCombatCharacter.cs index 5db1794c5..07d1fb3bb 100644 --- a/Game.Server/BaseCombatCharacter.cs +++ b/Game.Server/BaseCombatCharacter.cs @@ -680,16 +680,9 @@ public virtual void OnChangeActiveWeapon(BaseCombatWeapon? oldWeapon, BaseCombat public void SetCurrentWeaponProficiency(WeaponProficiency proficiency) => CurrentWeaponProficiency = proficiency; public virtual WeaponProficiency CalcWeaponProficiency(BaseCombatWeapon? weapon) => WeaponProficiency.Average; - static int LastInteraction = 0; + public bool DispatchInteraction(AI_Interaction interactionType, object? data, BaseCombatCharacter? sourceEnt) => (interactionType > AI_Interaction.None) ? HandleInteraction(interactionType, data, sourceEnt) : false; - public static int GetInteractionID() { - LastInteraction++; - return LastInteraction; - } - - public bool DispatchInteraction(int interactionType, object? data, BaseCombatCharacter? sourceEnt) => (interactionType > 0) ? HandleInteraction(interactionType, data, sourceEnt) : false; - - public virtual bool HandleInteraction(int interactionType, object? data, BaseCombatCharacter? sourceEnt) => false; + public virtual bool HandleInteraction(AI_Interaction interactionType, object? data, BaseCombatCharacter? sourceEnt) => false; public override void SetLightingOriginRelative(BaseEntity? lightingOrigin) { base.SetLightingOriginRelative(lightingOrigin); diff --git a/Game.Server/NPC_MetroPolice.cs b/Game.Server/NPC_MetroPolice.cs index 7a34ca54f..6b5a72534 100644 --- a/Game.Server/NPC_MetroPolice.cs +++ b/Game.Server/NPC_MetroPolice.cs @@ -62,10 +62,6 @@ public class NPC_MetroPolice : AI_BaseActor const AI_MemoryFlags bits_MEMORY_PLAYER_HURT = AI_MemoryFlags.Custom3; const AI_MemoryFlags bits_MEMORY_PLAYER_HARASSED = AI_MemoryFlags.Custom4; - public static int g_interactionMetrocopStartedStitch = 0; - public static int g_interactionMetrocopIdleChatter = 0; - public static int g_interactionMetrocopClearSentenceQueues = 0; - public static readonly ConVar sk_metropolice_health = new("sk_metropolice_health", "0"); public static readonly ConVar sk_metropolice_simple_health = new("sk_metropolice_simple_health", "26"); @@ -322,9 +318,6 @@ public class NPC_MetroPolice : AI_BaseActor ACT_DEACTIVATE_BATON = DeclareActivity(nameof(ACT_DEACTIVATE_BATON)); ACT_WALK_BATON = DeclareActivity(nameof(ACT_WALK_BATON)); ACT_IDLE_ANGRY_BATON = DeclareActivity(nameof(ACT_IDLE_ANGRY_BATON)); - g_interactionMetrocopStartedStitch = GetInteractionID(); - g_interactionMetrocopIdleChatter = GetInteractionID(); - g_interactionMetrocopClearSentenceQueues = GetInteractionID(); }, Definitions = [ new(SCHED_METROPOLICE_WAKE_ANGRY, @@ -1181,7 +1174,7 @@ public override void IdleSound() { } if (Sentences.Speak(IdleQuestions[isCriminal ? 1 : 0, questionType]) >= 0) { - GetSquad()!.BroadcastInteraction(g_interactionMetrocopIdleChatter, METROPOLICE_CHATTER_RESPONSE + questionType, this); + GetSquad()!.BroadcastInteraction(AI_Interaction.MetrocopIdleChatter, METROPOLICE_CHATTER_RESPONSE + questionType, this); IdleChatterType = METROPOLICE_CHATTER_WAIT_FOR_RESPONSE; } } @@ -1191,7 +1184,7 @@ public override void IdleSound() { int responseType = IdleChatterType - METROPOLICE_CHATTER_RESPONSE; if (Sentences.Speak(IdleResponses[isCriminal ? 1 : 0, responseType]) >= 0) { - GetSquad()!.BroadcastInteraction(g_interactionMetrocopIdleChatter, METROPOLICE_CHATTER_ASK_QUESTION, this); + GetSquad()!.BroadcastInteraction(AI_Interaction.MetrocopIdleChatter, METROPOLICE_CHATTER_ASK_QUESTION, this); IdleChatterType = METROPOLICE_CHATTER_ASK_QUESTION; } } @@ -1321,23 +1314,23 @@ public override void HandleAnimEvent(ref AnimEvent animEvent) { base.HandleAnimEvent(ref animEvent); } - public override bool HandleInteraction(int interactionType, object? data, BaseCombatCharacter? sourceEnt) { - if (interactionType == g_interactionMetrocopStartedStitch) { + public override bool HandleInteraction(AI_Interaction interactionType, object? data, BaseCombatCharacter? sourceEnt) { + if (interactionType == AI_Interaction.MetrocopStartedStitch) { ValidStitchTime = gpGlobals.CurTime + random.RandomFloat(METROPOLICE_SQUAD_STITCH_MIN_INTERVAL, METROPOLICE_SQUAD_STITCH_MAX_INTERVAL); return true; } - if (interactionType == g_interactionMetrocopIdleChatter) { + if (interactionType == AI_Interaction.MetrocopIdleChatter) { IdleChatterType = (int)data!; return true; } - if (interactionType == g_interactionMetrocopClearSentenceQueues) { + if (interactionType == AI_Interaction.MetrocopClearSentenceQueues) { Sentences.ClearQueue(); return true; } - if (interactionType == Props.g_interactionHitByPlayerThrownPhysObj) { + if (interactionType == AI_Interaction.HitByPlayerThrownPhysObj) { if (!IsInAScript() && (NPCState != NPCState.Script)) SetCondition(COND_METROPOLICE_PHYSOBJECT_ASSAULT); else diff --git a/Game.Server/Props.cs b/Game.Server/Props.cs index 39bd58495..50f310133 100644 --- a/Game.Server/Props.cs +++ b/Game.Server/Props.cs @@ -606,8 +606,6 @@ public class PropDoorRotatingBreakable : PropDoorRotating; public static class Props { - public static int g_interactionHitByPlayerThrownPhysObj = 0; - public static PhysicsProp? CreatePhysicsProp(ReadOnlySpan modelName, in Vector3 traceStart, in Vector3 traceEnd, IHandleEntity? traceIgnore, bool requireVCollide, ReadOnlySpan className = default) { if (className.IsStringEmpty) className = "physics_prop"; From 3babb54009a61f36dfda2cf7ac7d77ea3a09f733 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 19:49:37 +0300 Subject: [PATCH 56/73] Simplify schedule class names using nameof --- Game.Server/AI_ActBusyBehavior.cs | 6 ++---- Game.Server/AI_PolicingBehavior.cs | 6 ++---- Game.Server/AI_Schedule.cs | 17 ++++++++--------- Game.Server/NPC_MetroPolice.cs | 5 ++--- 4 files changed, 14 insertions(+), 20 deletions(-) diff --git a/Game.Server/AI_ActBusyBehavior.cs b/Game.Server/AI_ActBusyBehavior.cs index 8cf00a864..4717e1ab4 100644 --- a/Game.Server/AI_ActBusyBehavior.cs +++ b/Game.Server/AI_ActBusyBehavior.cs @@ -192,7 +192,6 @@ public class AI_ActBusyBehavior : AI_Behavior_AI_BaseNPC_100000 public const int COND_ACTBUSY_ENEMY_TOO_CLOSE = NEXT_CONDITION + 2; static readonly AI_ClassScheduleIdSpace gm_ClassScheduleIdSpace = new(); - const string gm_pszErrorClassName = "CAI_ActBusyBehavior"; static ActBusyAnimData g_ActBusyAnimDataSystem => ActBusyAnimData.g_ActBusyAnimDataSystem; @@ -238,12 +237,11 @@ public AI_ActBusyBehavior() { public override string GetName() => "ActBusy"; public override AI_ClassScheduleIdSpace GetClassScheduleIdSpace() => gm_ClassScheduleIdSpace; - protected override string GetSchedulingErrorName() => gm_pszErrorClassName; + protected override string GetSchedulingErrorName() => nameof(AI_ActBusyBehavior); - public static bool LoadSchedules() => CustomSchedules.Load(AI_BaseNPC.LoadSchedules); + public static bool LoadSchedules() => CustomSchedules.Load(AI_BaseNPC.LoadSchedules, nameof(AI_ActBusyBehavior)); static readonly AI_CustomSchedules CustomSchedules = new() { - ClassName = gm_pszErrorClassName, IdSpace = gm_ClassScheduleIdSpace, ParentIdSpace = AccessClassScheduleIdSpaceDirect(), Schedules = [ diff --git a/Game.Server/AI_PolicingBehavior.cs b/Game.Server/AI_PolicingBehavior.cs index a83de5c5b..9d20074e3 100644 --- a/Game.Server/AI_PolicingBehavior.cs +++ b/Game.Server/AI_PolicingBehavior.cs @@ -28,7 +28,6 @@ public class AI_PolicingBehavior : AI_Behavior_AI_BaseNPC_100000 public const int COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS = NEXT_CONDITION + 1; static readonly AI_ClassScheduleIdSpace gm_ClassScheduleIdSpace = new(); - const string gm_pszErrorClassName = "CAI_PolicingBehavior"; static readonly string[] Warnings = [ "METROPOLICE_MOVE_ALONG_A", @@ -47,12 +46,11 @@ public AI_PolicingBehavior() { public override string GetName() => "Policing"; public override AI_ClassScheduleIdSpace GetClassScheduleIdSpace() => gm_ClassScheduleIdSpace; - protected override string GetSchedulingErrorName() => gm_pszErrorClassName; + protected override string GetSchedulingErrorName() => nameof(AI_PolicingBehavior); - public static bool LoadSchedules() => CustomSchedules.Load(AI_BaseNPC.LoadSchedules); + public static bool LoadSchedules() => CustomSchedules.Load(AI_BaseNPC.LoadSchedules, nameof(AI_PolicingBehavior)); static readonly AI_CustomSchedules CustomSchedules = new() { - ClassName = gm_pszErrorClassName, IdSpace = gm_ClassScheduleIdSpace, ParentIdSpace = AccessClassScheduleIdSpaceDirect(), Schedules = [ diff --git a/Game.Server/AI_Schedule.cs b/Game.Server/AI_Schedule.cs index 16a6b7cd9..1274a88f2 100644 --- a/Game.Server/AI_Schedule.cs +++ b/Game.Server/AI_Schedule.cs @@ -188,7 +188,6 @@ public readonly struct AI_ScheduleCondition(int condition) public sealed class AI_CustomSchedules { - public required string ClassName { get; init; } public required AI_ClassScheduleIdSpace IdSpace { get; init; } public required AI_ClassScheduleIdSpace ParentIdSpace { get; init; } public AI_LocalIdSpace? SquadSlotIdSpace { get; init; } @@ -205,38 +204,38 @@ public sealed class AI_CustomSchedules public bool Valid => LoadStatus.Valid; - public bool Load(Func baseLoad) => AI_DoLoadSchedules(baseLoad, Init, ref LoadStatus); + public bool Load(Func baseLoad, string className) => AI_DoLoadSchedules(baseLoad, () => Init(className), ref LoadStatus); - void Init() { + void Init(string className) { Declare?.Invoke(); - IdSpace.Init(ClassName, AI_BaseNPC.GetSchedulingSymbols(), ParentIdSpace); + IdSpace.Init(className, AI_BaseNPC.GetSchedulingSymbols(), ParentIdSpace); SquadSlotIdSpace?.Init(AI_BaseNPC.SquadSlotNamespace, AI_BaseNPC.SquadSlotIdSpace); foreach ((string name, int localId) in SortedByLocalId(Schedules)) { - if (!IdSpace.AddSchedule(name, localId, ClassName)) + if (!IdSpace.AddSchedule(name, localId, className)) return; } foreach ((string name, int localId) in SortedByLocalId(Tasks)) { - if (!IdSpace.AddTask(name, localId, ClassName)) + if (!IdSpace.AddTask(name, localId, className)) return; } foreach ((string name, int localId) in SortedByLocalId(Conditions)) { if (ValidateConditionLimits(name)) { - if (!IdSpace.AddCondition(name, localId, ClassName)) + if (!IdSpace.AddCondition(name, localId, className)) return; } } foreach ((string name, int localId) in SortedByLocalId(SquadSlots)) { - if (!SquadSlotIdSpace!.AddSymbol(name, localId, "squadslot", ClassName)) + if (!SquadSlotIdSpace!.AddSymbol(name, localId, "squadslot", className)) return; } if (LoadStatus.Valid) - LoadStatus.Valid = g_AI_SchedulesManager.DefineSchedules(ClassName, IdSpace, Definitions); + LoadStatus.Valid = g_AI_SchedulesManager.DefineSchedules(className, IdSpace, Definitions); } static (string Name, int LocalId)[] SortedByLocalId((string Name, int LocalId)[] symbols) { diff --git a/Game.Server/NPC_MetroPolice.cs b/Game.Server/NPC_MetroPolice.cs index 6b5a72534..5e53f43c2 100644 --- a/Game.Server/NPC_MetroPolice.cs +++ b/Game.Server/NPC_MetroPolice.cs @@ -162,7 +162,6 @@ public class NPC_MetroPolice : AI_BaseActor static readonly AI_ClassScheduleIdSpace gm_ClassScheduleIdSpace = new(); static readonly AI_LocalIdSpace gm_SquadSlotIdSpace = new(); - const string gm_pszErrorClassName = "CNPC_MetroPolice"; public static readonly new DataMap DataDesc = new(typeof(NPC_MetroPolice), AI_BaseNPC.DataDesc, [ DEFINE.KEYFIELD(nameof(WeaponDrawn), FieldType.Boolean, "weapondrawn"), @@ -224,13 +223,13 @@ public class NPC_MetroPolice : AI_BaseActor public NPC_MetroPolice() => LoadSchedules(); public override AI_ClassScheduleIdSpace GetClassScheduleIdSpace() => gm_ClassScheduleIdSpace; + public override ReadOnlySpan GetSchedulingErrorName() => nameof(NPC_MetroPolice); - public static new bool LoadSchedules() => CustomSchedules.Load(AI_BaseNPC.LoadSchedules); + public static new bool LoadSchedules() => CustomSchedules.Load(AI_BaseNPC.LoadSchedules, nameof(NPC_MetroPolice)); public override bool LoadedSchedules() => CustomSchedules.Valid; static readonly AI_CustomSchedules CustomSchedules = new() { - ClassName = gm_pszErrorClassName, IdSpace = gm_ClassScheduleIdSpace, ParentIdSpace = AI_BaseNPC.ClassScheduleIdSpace, SquadSlotIdSpace = gm_SquadSlotIdSpace, From 4bc4538e6fc57522f6b92a20e00e8a7b7b2ab946 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:08:23 +0300 Subject: [PATCH 57/73] Fix PostRunStopMoving skipping the stopping path --- Game.Server/AI_BaseNPC.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index ad4787b6f..64f44ff97 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -8938,7 +8938,8 @@ public virtual void PostRun() { } public virtual void PostRunStopMoving() { - SetIdealActivity(GetStoppedActivity()); + if (!GetNavigator()!.SetGoalFromStoppingPath()) + SetIdealActivity(GetStoppedActivity()); } public virtual void RunAnimation() { From ec502832f51517890796599444e422435d5e38ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:17:52 +0300 Subject: [PATCH 58/73] Port NPC helpers used by player allies --- Game.Server/AI_BaseNPC.cs | 154 ++++++++++++++++++++++++++- Source.Common/Mathematics/MathLib.cs | 31 ++++++ 2 files changed, 183 insertions(+), 2 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 64f44ff97..a57c4d392 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -377,6 +377,7 @@ public static ReadOnlySpan GetActivityName(Activity actID) { DEFINE.OUTPUT(nameof(OnWake), "OnWake", eventFuncs), DEFINE.FIELD(nameof(DidDeathCleanup), FieldType.Boolean), DEFINE.OUTPUT(nameof(OnDeath), "OnDeath", eventFuncs), + DEFINE.OUTPUT(nameof(OnDenyCommanderUse), "OnDenyCommanderUse", eventFuncs), ]); public override DataMap? GetDataDescMap() => DataDesc; @@ -533,6 +534,7 @@ public static ReadOnlySpan GetActivityName(Activity actID) { public OutputEvent OnLostPlayer = new(); public OutputEvent OnWake = new(); public OutputEvent OnDeath = new(); + public OutputEvent OnDenyCommanderUse = new(); public bool DidDeathCleanup; public bool WakeSquad; public long WakeTick; @@ -6892,7 +6894,7 @@ public virtual void CheckAmmo() { } public bool IsMovingToPickupWeapon() => IsCurSchedule(SCHED_NEW_WEAPON); - public bool ShouldLookForBetterWeapon() { + public virtual bool ShouldLookForBetterWeapon() { if (NextWeaponSearchTime > gpGlobals.CurTime) return false; @@ -7194,6 +7196,8 @@ public Capability CapabilitiesAdd(Capability capability) { return Capability; } + public void CapabilitiesClear() => Capability = 0; + public void SetHullSizeNormal(bool force = false) { if (IsUsingSmallHullValue || force) { float scale = GetModelScale(); @@ -8003,6 +8007,144 @@ public virtual void ClearCommandGoal() { CommandMoveMonitor.ClearMark(); } + public Vector3 GetCommandGoal() => CommandGoal; + + public void SentenceStop() => EmitSound("AI_BaseNPC.SentenceStop"); + + public virtual bool CanBeUsedAsAFriend() { + if (IsCurSchedule(SCHED_FORCED_GO) || IsCurSchedule(SCHED_FORCED_GO_RUN)) + return false; + return true; + } + + public bool ConditionInterruptsCurSchedule(int condition) { + if (GetCurSchedule() == null) + return false; + + int interrupt = InterruptFromCondition(condition); + + if (interrupt == -1) { + Assert(false); + return false; + } + return GetCurSchedule()!.HasInterrupt(interrupt); + } + + public void TestPlayerPushing(BaseEntity? entity) { + if (HasSpawnFlags(SF_NPC_NO_PLAYER_PUSHAWAY)) + return; + + BasePlayer? player = ToBasePlayer(entity); + if (player != null && (player.GetFlags() & EntityFlags.NoTarget) == 0) { + if (g_IgnorePlayers.GetBool()) + return; + + if ((player.Buttons & (InButtons.Forward | InButtons.Back | InButtons.MoveLeft | InButtons.MoveRight)) != 0 || + player.GetAbsVelocity().AsVector2D().LengthSquared() > 50 * 50) { + SetCondition((int)SCOND_t.COND_PLAYER_PUSHING); + Vector3 push = GetAbsOrigin() - player.GetAbsOrigin(); + MathLib.VectorNormalize(ref push); + CascadePlayerPush(push, player.WorldSpaceCenter()); + } + } + } + + public void CascadePlayerPush(in Vector3 push, in Vector3 pushOrigin) { + float hullWidth = GetHullWidth(); + Vector3 origin = GetAbsOrigin(); + Vector2 origin2D = origin.AsVector2D(); + + float MIN_Z_TO_TRANSMIT = GetHullHeight() * 0.5f + 0.1f; + float DIST_REQD_TO_TRANSMIT_PUSH_SQ = (hullWidth * 5 + 0.1f) * (hullWidth * 5 + 0.1f); + float DIST_FROM_PUSH_VECTOR_REQD_SQ = (hullWidth + 0.1f) * (hullWidth + 0.1f); + + Vector2 pushTestPoint = vec2_invalid; + + for (int i = 0; i < g_AI_Manager.NumAIs(); i++) { + AI_BaseNPC other = g_AI_Manager.AccessAIs()[i]; + if (other != this && other.IRelationType(this) == Disposition.LI && !other.HasCondition((int)SCOND_t.COND_PLAYER_PUSHING)) { + Vector3 friendOrigin = other.GetAbsOrigin(); + if (MathF.Abs(friendOrigin.Z - origin.Z) < MIN_Z_TO_TRANSMIT && + (friendOrigin.AsVector2D() - origin.AsVector2D()).LengthSquared() < DIST_REQD_TO_TRANSMIT_PUSH_SQ) { + if (pushTestPoint == vec2_invalid) { + pushTestPoint = origin2D - pushOrigin.AsVector2D(); + pushTestPoint *= 2000; + pushTestPoint += origin2D; + } + float distSq = MathLib.CalcDistanceSqrToLine2D(friendOrigin.AsVector2D(), origin2D, pushTestPoint, out float t); + if (t > 0 && distSq < DIST_FROM_PUSH_VECTOR_REQD_SQ) + other.SetCondition((int)SCOND_t.COND_PLAYER_PUSHING); + } + } + } + } + + public bool IsSquadmateInSpread(in Vector3 sourcePos, in Vector3 targetPos, float spread, float maxDistOffCenter) { + if (Squad == null) + return false; + + AI_BaseNPC? squadmate = Squad.GetFirstMember(out int iter); + while (squadmate != null) { + if (squadmate.m_takedamage != (byte)Damage.No) { + if (squadmate != this) { + if (PointInSpread(squadmate, sourcePos, targetPos, squadmate.GetAbsOrigin(), spread, maxDistOffCenter)) + return true; + } + } + squadmate = Squad.GetNextMember(ref iter); + } + return false; + } + + public bool PointInSpread(BaseCombatCharacter? checkEntity, in Vector3 sourcePos, in Vector3 targetPos, in Vector3 testPoint, float spread, float maxDistOffCenter) { + float distOffLine = MathLib.CalcDistanceToLine2D(testPoint.AsVector2D(), sourcePos.AsVector2D(), targetPos.AsVector2D(), out _); + if (distOffLine < maxDistOffCenter) { + Vector3 toTarget = targetPos - sourcePos; + float distTarget = MathLib.VectorNormalize(ref toTarget); + + Vector3 toTest = testPoint - sourcePos; + float distTest = MathLib.VectorNormalize(ref toTest); + if (distTarget > distTest) { + toTarget.Z = 0.0f; + toTest.Z = 0.0f; + + float dotProduct = Vector3.Dot(toTarget, toTest); + if (dotProduct > spread) + return true; + else if (dotProduct > 0.0f) { + if (checkEntity != null) { + float bboxDist = NAI_Hull.Width(checkEntity.GetHullType()); + bboxDist *= 1.414f; + + distOffLine = MathLib.CalcDistanceToLine(testPoint, sourcePos, targetPos, out _); + if (distOffLine < bboxDist) + return true; + } + } + } + } + return false; + } + + public int NumWeaponsInSquad(ReadOnlySpan weaponClassname) { + if (GetSquad() == null) { + if (GetActiveWeapon() != null && GetActiveWeapon()!.ClassMatches(weaponClassname)) + return 1; + + return 0; + } + + int count = 0; + AI_BaseNPC? squadmate = Squad!.GetFirstMember(out int iter); + while (squadmate != null) { + if (squadmate.GetActiveWeapon() != null && squadmate.GetActiveWeapon()!.ClassMatches(weaponClassname)) + count++; + squadmate = Squad.GetNextMember(ref iter); + } + + return count; + } + public void ClearSchedule(string? reason) { if (reason != null && (DebugOverlays & DebugOverlayBits.TaskText) != 0) DevMsg($" Schedule cleared: {reason}\n"); @@ -8601,7 +8743,15 @@ public void UpdateSleepState(bool inPVS) { } } - public bool SoundIsVisible(ref WorldSoundInstance sound) => throw new NotImplementedException(); + public bool SoundIsVisible(ref WorldSoundInstance sound) { + if (!FVisible(sound.GetSoundReactOrigin(), Mask.BlockLOS, out BaseEntity? blocker)) { + if (blocker != null && blocker == sound.Owner.Get()) + return true; + + return false; + } + return true; + } static Vector3 UpdateEfficiencyPlayerEyePosition; static Vector3 UpdateEfficiencyPlayerForward; diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index cac36b599..74830d11c 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -26,6 +26,7 @@ public static class MathLibConsts public static readonly Vector3 vec3_origin = new(0, 0, 0); public static readonly QAngle vec3_angle = new(0, 0, 0); public static readonly Vector3 vec3_invalid = new(float.MaxValue, float.MaxValue, float.MaxValue); + public static readonly Vector2 vec2_invalid = new(float.MaxValue, float.MaxValue); public static Vector3 RandomAngularImpulse(float minVal, float maxVal) { Vector3 angImp = default; @@ -1390,6 +1391,36 @@ public static float CalcDistanceSqrToLine(in Vector3 P, in Vector3 vLineA, in Ve return P.DistToSqr(vClosest); } + public static float CalcClosestPointToLineT2D(in Vector2 P, in Vector2 vLineA, in Vector2 vLineB, out Vector2 vDir) { + Assert(MathlibInitialized); + vDir = vLineB - vLineA; + + float div = Vector2.Dot(vDir, vDir); + if (div < 0.00001f) + return 0; + else + return (Vector2.Dot(vDir, P) - Vector2.Dot(vDir, vLineA)) / div; + } + + public static void CalcClosestPointOnLine2D(in Vector2 P, in Vector2 vLineA, in Vector2 vLineB, out Vector2 vClosest, out float outT) { + Assert(MathlibInitialized); + float t = CalcClosestPointToLineT2D(P, vLineA, vLineB, out Vector2 vDir); + outT = t; + vClosest = vLineA + vDir * t; + } + + public static float CalcDistanceToLine2D(in Vector2 P, in Vector2 vLineA, in Vector2 vLineB, out float outT) { + Assert(MathlibInitialized); + CalcClosestPointOnLine2D(P, vLineA, vLineB, out Vector2 vClosest, out outT); + return Vector2.Distance(P, vClosest); + } + + public static float CalcDistanceSqrToLine2D(in Vector2 P, in Vector2 vLineA, in Vector2 vLineB, out float outT) { + Assert(MathlibInitialized); + CalcClosestPointOnLine2D(P, vLineA, vLineB, out Vector2 vClosest, out outT); + return Vector2.DistanceSquared(P, vClosest); + } + public static void CalculateAABBFromProjectionMatrixInverse(in Matrix4x4 volumeToWorld, out Vector3 mins, out Vector3 maxs) { ClearBounds(out mins, out maxs); From a4e888764551033e287c481c4ac078ec6fe817c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:26:09 +0300 Subject: [PATCH 59/73] Port AI_PlayerAlly without speech --- Game.Server/AI_PlayerAlly.cs | 66 ++++++++++++++++++++++++++++++++++-- 1 file changed, 63 insertions(+), 3 deletions(-) diff --git a/Game.Server/AI_PlayerAlly.cs b/Game.Server/AI_PlayerAlly.cs index 5d0df8d7d..0830adebe 100644 --- a/Game.Server/AI_PlayerAlly.cs +++ b/Game.Server/AI_PlayerAlly.cs @@ -1,10 +1,70 @@ +using Game.Shared; + namespace Game.Server; public class AI_PlayerAlly : AI_BaseActor { - public override int SelectSchedule() => throw new NotImplementedException(); + public override EntityCapabilities ObjectCaps() => UsableNPCObjectCaps(base.ObjectCaps()); - public bool SelectInterjection() => throw new NotImplementedException(); + public bool SelectInterjection() => false; - public override EntityCapabilities ObjectCaps() => UsableNPCObjectCaps(base.ObjectCaps()); + public override int TranslateSchedule(int scheduleType) { + switch (scheduleType) { + case SCHED_CHASE_ENEMY_FAILED: { + int baseType = base.TranslateSchedule(scheduleType); + if (baseType != SCHED_CHASE_ENEMY_FAILED) + return baseType; + + return SCHED_TAKE_COVER_FROM_ENEMY; + } + } + return base.TranslateSchedule(scheduleType); + } + + public override void StartTask(in Task_t task) { + switch (task.Task) { + case TASK_MOVE_AWAY_PATH: + if (HasCondition((int)SCOND_t.COND_PLAYER_PUSHING)) + GetMotor()!.SetIdealYawToTarget(AI_GetClosestPlayer()!.WorldSpaceCenter()); + + base.StartTask(task); + break; + + default: + base.StartTask(task); + break; + } + } + + public override void Touch(BaseEntity? other) { + base.Touch(other); + + if (other!.IsPlayer()) { + if (HasMemory(AI_MemoryFlags.Provoked)) + return; + + if (GetExpresser()!.IsSpeaking()) + return; + + TestPlayerPushing(other); + } + } + + public override void Event_Killed(in TakeDamageInfo info) { + if (IsInPlayerSquad()) { + BasePlayer? player = AI_GetClosestPlayer(); + if (player != null) { + Variant_t emptyVariant = default; + player.AcceptInput("OnSquadMemberKilled", this, this, emptyVariant, 0); + } + } + + if (GetSpeechSemaphore(this).GetOwner() == this) + GetSpeechSemaphore(this).Release(); + + SetTarget(null); + SentenceStop(); + FnUse = null; + base.Event_Killed(info); + } } From f4183bed7b99657dbff7bfd5c74b82f033db8753 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:41:37 +0300 Subject: [PATCH 60/73] Port NPC_PlayerCompanion schedule core --- Game.Server/AI_BaseNPC.cs | 2 + Game.Server/NPC_PlayerCompanion.cs | 985 +++++++++++++++++++++++++++++ Game.Server/Player.cs | 1 + 3 files changed, 988 insertions(+) create mode 100644 Game.Server/NPC_PlayerCompanion.cs diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index a57c4d392..7cd42dbc6 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -7624,6 +7624,8 @@ public virtual void OnStateChange(NPCState oldState, NPCState newState) { } public Activity GetActivity() => Activity; + public void ResetActivity() => Activity = Activity.ACT_RESET; + public virtual void SetActivity(Activity newActivity) { if (Activity == newActivity) return; diff --git a/Game.Server/NPC_PlayerCompanion.cs b/Game.Server/NPC_PlayerCompanion.cs new file mode 100644 index 000000000..6777e1279 --- /dev/null +++ b/Game.Server/NPC_PlayerCompanion.cs @@ -0,0 +1,985 @@ +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Formats.BSP; +using Source.Common.Mathematics; +using Source.Common.Physics; + +using System.Numerics; +using System.Runtime.CompilerServices; + +using static Game.Server.SCOND_t; + +namespace Game.Server; + +using DEFINE = DEFINE; + +public enum AIReadiness +{ + Panic = -2, + Stealth = -1, + Relaxed = 0, + Stimulated, + Agitated, +} + +public class NPC_PlayerCompanion : AI_PlayerAlly +{ + public const float READINESS_MIN_VALUE = -2; + public const float READINESS_MODE_PANIC = -2; + public const float READINESS_MODE_STEALTH = -1; + + public const float READINESS_VALUE_RELAXED = 0.1f; + public const float READINESS_VALUE_STIMULATED = 0.95f; + public const float READINESS_VALUE_AGITATED = 1.0f; + + const float MORTAR_BLAST_RADIUS = 350; + + public static readonly ConVar ai_debug_readiness = new("ai_debug_readiness", "0"); + public static readonly ConVar ai_readiness_decay = new("ai_readiness_decay", "120"); + + protected const int COND_PC_HURTBYFIRE = AI_BaseNPC.NEXT_CONDITION; + protected const int COND_PC_SAFE_FROM_MORTAR = AI_BaseNPC.NEXT_CONDITION + 1; + protected const int COND_PC_BECOMING_PASSENGER = AI_BaseNPC.NEXT_CONDITION + 2; + public new const int NEXT_CONDITION = AI_BaseNPC.NEXT_CONDITION + 3; + + protected const int SCHED_PC_COWER = AI_BaseNPC.NEXT_SCHEDULE; + protected const int SCHED_PC_MOVE_TOWARDS_COVER_FROM_BEST_SOUND = AI_BaseNPC.NEXT_SCHEDULE + 1; + protected const int SCHED_PC_TAKE_COVER_FROM_BEST_SOUND = AI_BaseNPC.NEXT_SCHEDULE + 2; + protected const int SCHED_PC_FLEE_FROM_BEST_SOUND = AI_BaseNPC.NEXT_SCHEDULE + 3; + protected const int SCHED_PC_FAIL_TAKE_COVER_TURRET = AI_BaseNPC.NEXT_SCHEDULE + 4; + protected const int SCHED_PC_FAKEOUT_MORTAR = AI_BaseNPC.NEXT_SCHEDULE + 5; + protected const int SCHED_PC_GET_OFF_COMPANION = AI_BaseNPC.NEXT_SCHEDULE + 6; + public new const int NEXT_SCHEDULE = AI_BaseNPC.NEXT_SCHEDULE + 7; + + protected const int TASK_PC_WAITOUT_MORTAR = AI_BaseNPC.NEXT_TASK; + protected const int TASK_PC_GET_PATH_OFF_COMPANION = AI_BaseNPC.NEXT_TASK + 1; + public new const int NEXT_TASK = AI_BaseNPC.NEXT_TASK + 2; + + static readonly AI_ClassScheduleIdSpace gm_ClassScheduleIdSpace = new(); + public static new AI_ClassScheduleIdSpace ClassScheduleIdSpace => gm_ClassScheduleIdSpace; + + public static readonly new DataMap DataDesc = new(typeof(NPC_PlayerCompanion), AI_BaseNPC.DataDesc, [ + DEFINE.KEYFIELD(nameof(DontPickupWeapons), FieldType.Boolean, "DontPickupWeapons"), + + DEFINE.INPUTFUNC(FieldType.Void, "SetReadinessPanic", nameof(InputSetReadinessPanic), (INPUTFUNCPTR)((self, data) => ((NPC_PlayerCompanion)self).InputSetReadinessPanic(data))), + DEFINE.INPUTFUNC(FieldType.Void, "SetReadinessStealth", nameof(InputSetReadinessStealth), (INPUTFUNCPTR)((self, data) => ((NPC_PlayerCompanion)self).InputSetReadinessStealth(data))), + DEFINE.INPUTFUNC(FieldType.Void, "SetReadinessLow", nameof(InputSetReadinessLow), (INPUTFUNCPTR)((self, data) => ((NPC_PlayerCompanion)self).InputSetReadinessLow(data))), + DEFINE.INPUTFUNC(FieldType.Void, "SetReadinessMedium", nameof(InputSetReadinessMedium), (INPUTFUNCPTR)((self, data) => ((NPC_PlayerCompanion)self).InputSetReadinessMedium(data))), + DEFINE.INPUTFUNC(FieldType.Void, "SetReadinessHigh", nameof(InputSetReadinessHigh), (INPUTFUNCPTR)((self, data) => ((NPC_PlayerCompanion)self).InputSetReadinessHigh(data))), + DEFINE.INPUTFUNC(FieldType.Float, "LockReadiness", nameof(InputLockReadiness), (INPUTFUNCPTR)((self, data) => ((NPC_PlayerCompanion)self).InputLockReadiness(data))), + + DEFINE.INPUTFUNC(FieldType.Void, "EnableWeaponPickup", nameof(InputEnableWeaponPickup), (INPUTFUNCPTR)((self, data) => ((NPC_PlayerCompanion)self).InputEnableWeaponPickup(data))), + DEFINE.INPUTFUNC(FieldType.Void, "DisableWeaponPickup", nameof(InputDisableWeaponPickup), (INPUTFUNCPTR)((self, data) => ((NPC_PlayerCompanion)self).InputDisableWeaponPickup(data))), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + bool MovingAwayFromPlayer; + + protected float Readiness; + protected float ReadinessSensitivity; + protected bool ReadinessCapable; + protected TimeUnit_t ReadinessLockedUntil; + + protected bool DontPickupWeapons; + + protected readonly AI_ActBusyBehavior ActBusyBehavior = new(); + + public NPC_PlayerCompanion() => LoadSchedules(); + + public override AI_ClassScheduleIdSpace GetClassScheduleIdSpace() => gm_ClassScheduleIdSpace; + public override ReadOnlySpan GetSchedulingErrorName() => nameof(NPC_PlayerCompanion); + + public static new bool LoadSchedules() => CustomSchedules.Load(AI_BaseNPC.LoadSchedules, nameof(NPC_PlayerCompanion)); + + public override bool LoadedSchedules() => CustomSchedules.Valid; + + static readonly AI_CustomSchedules CustomSchedules = new() { + IdSpace = gm_ClassScheduleIdSpace, + ParentIdSpace = AI_BaseNPC.ClassScheduleIdSpace, + Schedules = [ + (nameof(SCHED_PC_COWER), SCHED_PC_COWER), + (nameof(SCHED_PC_MOVE_TOWARDS_COVER_FROM_BEST_SOUND), SCHED_PC_MOVE_TOWARDS_COVER_FROM_BEST_SOUND), + (nameof(SCHED_PC_TAKE_COVER_FROM_BEST_SOUND), SCHED_PC_TAKE_COVER_FROM_BEST_SOUND), + (nameof(SCHED_PC_FLEE_FROM_BEST_SOUND), SCHED_PC_FLEE_FROM_BEST_SOUND), + (nameof(SCHED_PC_FAIL_TAKE_COVER_TURRET), SCHED_PC_FAIL_TAKE_COVER_TURRET), + (nameof(SCHED_PC_FAKEOUT_MORTAR), SCHED_PC_FAKEOUT_MORTAR), + (nameof(SCHED_PC_GET_OFF_COMPANION), SCHED_PC_GET_OFF_COMPANION), + ], + Tasks = [ + (nameof(TASK_PC_WAITOUT_MORTAR), TASK_PC_WAITOUT_MORTAR), + (nameof(TASK_PC_GET_PATH_OFF_COMPANION), TASK_PC_GET_PATH_OFF_COMPANION), + ], + Conditions = [ + (nameof(COND_PC_HURTBYFIRE), COND_PC_HURTBYFIRE), + (nameof(COND_PC_SAFE_FROM_MORTAR), COND_PC_SAFE_FROM_MORTAR), + (nameof(COND_PC_BECOMING_PASSENGER), COND_PC_BECOMING_PASSENGER), + ], + Definitions = [ + new(SCHED_PC_MOVE_TOWARDS_COVER_FROM_BEST_SOUND, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_FLEE_FROM_BEST_SOUND), + TASK_STOP_MOVING, + (TASK_SET_TOLERANCE_DISTANCE, 24), + TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION, + TASK_FIND_COVER_FROM_BEST_SOUND, + (TASK_RUN_PATH_TIMED, 1.0f), + TASK_STOP_MOVING, + TASK_FACE_SAVEPOSITION, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + ], + [ + COND_PC_SAFE_FROM_MORTAR, + ]), + + new(SCHED_PC_TAKE_COVER_FROM_BEST_SOUND, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_FLEE_FROM_BEST_SOUND), + TASK_STOP_MOVING, + (TASK_SET_TOLERANCE_DISTANCE, 24), + TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION, + TASK_FIND_COVER_FROM_BEST_SOUND, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + TASK_FACE_SAVEPOSITION, + (TASK_SET_ACTIVITY, Activity.ACT_IDLE), + ], + [ + COND_NEW_ENEMY, + COND_PC_SAFE_FROM_MORTAR, + ]), + + new(SCHED_PC_COWER, + [ + (TASK_WAIT_RANDOM, 0.1f), + (TASK_SET_ACTIVITY, Activity.ACT_COWER), + TASK_PC_WAITOUT_MORTAR, + (TASK_WAIT, 0.1f), + (TASK_WAIT_RANDOM, 0.5f), + ]), + + new(SCHED_PC_FLEE_FROM_BEST_SOUND, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_COWER), + (TASK_GET_PATH_AWAY_FROM_BEST_SOUND, 600), + (TASK_RUN_PATH_TIMED, 1.5f), + TASK_STOP_MOVING, + (TASK_TURN_LEFT, 179), + ], + [ + COND_NEW_ENEMY, + COND_PC_SAFE_FROM_MORTAR, + ]), + + new(SCHED_PC_FAIL_TAKE_COVER_TURRET, + [ + (TASK_SET_FAIL_SCHEDULE, SCHED_COWER), + TASK_STOP_MOVING, + (TASK_MOVE_AWAY_PATH, 600), + (TASK_RUN_PATH_FLEE, 100), + TASK_STOP_MOVING, + (TASK_TURN_LEFT, 179), + ], + [ + COND_NEW_ENEMY, + ]), + + new(SCHED_PC_FAKEOUT_MORTAR, + [ + (TASK_MOVE_AWAY_PATH, 300), + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ], + [ + COND_HEAR_DANGER, + ]), + + new(SCHED_PC_GET_OFF_COMPANION, + [ + TASK_PC_GET_PATH_OFF_COMPANION, + TASK_RUN_PATH, + TASK_WAIT_FOR_MOVEMENT, + ]), + ], + }; + + public override bool CreateBehaviors() { + AddBehavior(ActBusyBehavior); + + return base.CreateBehaviors(); + } + + public virtual void SelectModel() { } + + public override void Precache() { + PrecacheModel(GetModelName()); + + base.Precache(); + } + + public override void Spawn() { + SelectModel(); + + Precache(); + + SetModel(GetModelName()); + + SetHullType(AI_HullType.Human); + SetHullSizeNormal(); + + SetSolid(SolidType.BBox); + AddSolidFlags(SolidFlags.NotStandable); + SetBloodColor(Shared.BloodColor.Red); + FieldOfView = 0.02f; + NPCState = NPCState.None; + + CapabilitiesClear(); + CapabilitiesAdd(Capability.Squad); + + if (!HasSpawnFlags(SF_NPC_START_EFFICIENT)) { + CapabilitiesAdd(Capability.AnimatedFace | Capability.TurnHead); + CapabilitiesAdd(Capability.UseWeapons | Capability.AimGun | Capability.MoveShoot); + CapabilitiesAdd(Capability.Duck | Capability.AutoDoors | Capability.OpenDoors); + CapabilitiesAdd(Capability.UseShotRegulator); + } + CapabilitiesAdd(Capability.NoHitPlayer | Capability.NoHitSquadmates | Capability.FriendlyDmgImmune); + CapabilitiesAdd(Capability.MoveGround); + SetMoveType(Source.MoveType.Step); + + ReadinessCapable = IsReadinessCapable(); + SetReadinessValue(0.0f); + SetReadinessSensitivity(random.RandomFloat(0.7f, 1.3f)); + ReadinessLockedUntil = 0.0f; + + if (HasSpawnFlags(SF_NPC_ALTCOLLISION)) { + Warning($"NPC {GetEntityName()} using alternate collision! -- DISABLED\n"); + RemoveSpawnFlags(SF_NPC_ALTCOLLISION); + } + + base.Spawn(); + } + + public override void GatherConditions() { + base.GatherConditions(); + + if (IsReadinessCapable()) + UpdateReadiness(); + + PredictPlayerPush(); + + for (AI_EnemyInfo? memory = GetEnemies().GetFirst(out int iter); memory != null; memory = GetEnemies().GetNext(ref iter)) { + if (IsMortar(memory.Enemy.Get()) || IsSniper(memory.Enemy.Get())) { + memory.Unforgettable = IRelationType(memory.Enemy.Get()) < Disposition.LI; + memory.EludedMe = false; + } + } + + if (GetMotor()!.IsDeceleratingToGoal() && IsCurTaskContinuousMove() && + HasCondition((int)COND_PLAYER_PUSHING) && IsCurSchedule(SCHED_MOVE_AWAY)) + ClearSchedule("Being pushed by player"); + + ClearCondition(COND_PC_SAFE_FROM_MORTAR); + if (IsCurSchedule(SCHED_TAKE_COVER_FROM_BEST_SOUND)) { + ref WorldSoundInstance sound = ref GetBestSound(SoundInstanceType.Danger); + + if (!Unsafe.IsNullRef(ref sound) && (sound.Type & SoundInstanceType.ContextMortar) != 0) { + float distSq = (sound.GetSoundOrigin() - GetAbsOrigin()).LengthSquared(); + float safeDist = MORTAR_BLAST_RADIUS + GetHullWidth() * 2; + if (distSq > safeDist * safeDist) + SetCondition(COND_PC_SAFE_FROM_MORTAR); + } + } + + if (hl2_episodic.GetBool() && GetEnemy() == null && HasCondition((int)COND_HEAR_PLAYER)) { + BasePlayer? player = AI_GetClosestPlayer(); + + Vector3 los = player!.EyePosition() - EyePosition(); + los.Z = 0; + MathLib.VectorNormalize(ref los); + + if (Vector3.Dot(los, EyeDirection2D()) > BasePlayer.DOT_45DEGREE) + ClearCondition((int)COND_HEAR_PLAYER); + } + } + + public virtual void PredictPlayerPush() { + BasePlayer? player = AI_GetClosestPlayer(); + if (player != null && player.GetSmoothedVelocity().LengthSquared() >= 140 * 140) { + Vector3 predictedPosition = player.WorldSpaceCenter() + player.GetSmoothedVelocity() * .4f; + Vector3 delta = WorldSpaceCenter() - predictedPosition; + float pushWidth = GetHullWidth() * 1.414f; + if (delta.Z < GetHullHeight() * .5f && delta.Length2DSqr() < pushWidth * pushWidth) + TestPlayerPushing(player); + } + } + + public override void BuildScheduleTestBits() { + base.BuildScheduleTestBits(); + + SetCustomInterruptCondition(COND_PC_BECOMING_PASSENGER); + + if (IsCurSchedule(SCHED_RANGE_ATTACK1)) + SetCustomInterruptCondition((int)COND_PLAYER_PUSHING); + + if (ConditionInterruptsCurSchedule((int)COND_GIVE_WAY) || + IsCurSchedule(SCHED_HIDE_AND_RELOAD) || + IsCurSchedule(SCHED_RELOAD) || + IsCurSchedule(SCHED_STANDOFF) || + IsCurSchedule(SCHED_TAKE_COVER_FROM_ENEMY) || + IsCurSchedule(SCHED_COMBAT_FACE) || + IsCurSchedule(SCHED_ALERT_FACE) || + IsCurSchedule(SCHED_COMBAT_STAND) || + IsCurSchedule(SCHED_ALERT_FACE_BESTSOUND) || + IsCurSchedule(SCHED_ALERT_STAND)) { + SetCustomInterruptCondition((int)COND_HEAR_MOVE_AWAY); + SetCustomInterruptCondition((int)COND_PLAYER_PUSHING); + SetCustomInterruptCondition(COND_PC_HURTBYFIRE); + } + } + + public override ref WorldSoundInstance GetBestSound(SoundInstanceType validTypes = SoundInstanceType.AllSounds) { + ref WorldSoundInstance currentSound = ref GetSenses()!.GetFirstHeardSound(out int iter); + while (!Unsafe.IsNullRef(ref currentSound)) { + if (currentSound.FIsSound()) { + if ((currentSound.SoundContext() & SoundInstanceType.ContextMortar) != 0) + return ref currentSound; + } + + currentSound = ref GetSenses()!.GetNextHeardSound(ref iter); + } + + return ref base.GetBestSound(validTypes); + } + + public override bool QueryHearSound(ref WorldSoundInstance sound) { + if (!base.QueryHearSound(ref sound)) + return false; + + switch (sound.SoundTypeNoContext()) { + case SoundInstanceType.ReadinessLow: + SetReadinessLevel(AIReadiness.Relaxed, false, true); + return false; + + case SoundInstanceType.ReadinessMedium: + SetReadinessLevel(AIReadiness.Stimulated, false, true); + return false; + + case SoundInstanceType.ReadinessHigh: + SetReadinessLevel(AIReadiness.Agitated, false, true); + return false; + + default: + return true; + } + } + + public override bool QuerySeeEntity(BaseEntity entity, bool onlyHateOrFearIfNPC = false) { + AI_BaseNPC? other = entity.MyNPCPointer(); + if (other != null && + (other.GetState() == NPCState.Alert || GetState() == NPCState.Alert || other.GetState() == NPCState.Combat || GetState() == NPCState.Combat) && + other.IsPlayerAlly()) + return true; + + return base.QuerySeeEntity(entity, onlyHateOrFearIfNPC); + } + + public override bool ShouldIgnoreSound(ref WorldSoundInstance sound) { + if (!base.ShouldIgnoreSound(ref sound)) { + if (sound.IsSoundType(SoundInstanceType.Danger) && !SoundIsVisible(ref sound)) + return true; + } + + return false; + } + + public override int SelectSchedule() { + MovingAwayFromPlayer = false; + + if (ActBusyBehavior.IsRunning() && ActBusyBehavior.NeedsToPlayExitAnim()) { + Vector3 up = GetAbsOrigin(); + up.Z += .25f; + + Util.TraceHull(GetAbsOrigin(), up, GetHullMins(), GetHullMaxs(), Mask.Solid, this, Source.CollisionGroup.None, out Trace tr); + + if (tr.StartSolid) { + if (HasCondition((int)COND_HEAR_DANGER)) + ActBusyBehavior.StopBusying(); + + DeferSchedulingToBehavior(ActBusyBehavior); + return base.SelectSchedule(); + } + } + + int sched = SelectFlinchSchedule(); + if (sched != SCHED_NONE) + return sched; + + int schedule = SelectScheduleDanger(); + if (schedule != SCHED_NONE) + return schedule; + + schedule = SelectSchedulePriorityAction(); + if (schedule != SCHED_NONE) + return schedule; + + if (!BehaviorSelectSchedule()) { + if (NPCState == NPCState.Idle || NPCState == NPCState.Alert) { + schedule = SelectScheduleNonCombat(); + if (schedule != SCHED_NONE) + return schedule; + } + else if (NPCState == NPCState.Combat) { + schedule = SelectScheduleCombat(); + if (schedule != SCHED_NONE) + return schedule; + } + } + + return base.SelectSchedule(); + } + + public virtual int SelectScheduleDanger() { + if (HasCondition((int)COND_HEAR_DANGER)) { + ref WorldSoundInstance sound = ref GetBestSound(SoundInstanceType.Danger); + + Assert(!Unsafe.IsNullRef(ref sound)); + + if (!Unsafe.IsNullRef(ref sound) && (sound.Type & SoundInstanceType.Danger) != 0) { + if (HasCondition(COND_PC_SAFE_FROM_MORTAR)) + return SCHED_COWER; + else if ((sound.Type & SoundInstanceType.ContextFromSniper) != 0) + return SCHED_COWER; + + return SCHED_TAKE_COVER_FROM_BEST_SOUND; + } + } + + if (HasCondition((int)COND_HEAR_MOVE_AWAY)) + return SCHED_MOVE_AWAY; + + if (HasCondition(COND_PC_HURTBYFIRE)) { + ClearCondition(COND_PC_HURTBYFIRE); + return SCHED_MOVE_AWAY; + } + + return SCHED_NONE; + } + + public virtual int SelectSchedulePriorityAction() { + BaseEntity? groundEntity = GetGroundEntity(); + if (groundEntity != null && !IsInAScript()) { + if (groundEntity.IsPlayer()) + return SCHED_PC_GET_OFF_COMPANION; + + if (groundEntity.IsNPC() && + IRelationType(groundEntity) == Disposition.LI && + WorldSpaceCenter().Z - groundEntity.WorldSpaceCenter().Z > GetHullHeight() * .5f) + return SCHED_PC_GET_OFF_COMPANION; + } + + int schedule = SelectSchedulePlayerPush(); + if (schedule != SCHED_NONE) + return schedule; + + return SCHED_NONE; + } + + public virtual int SelectScheduleNonCombat() => SCHED_NONE; + + public virtual int SelectScheduleCombat() { + if (CanReload() && (HasCondition((int)COND_NO_PRIMARY_AMMO) || HasCondition((int)COND_LOW_PRIMARY_AMMO))) + return SCHED_HIDE_AND_RELOAD; + + return SCHED_NONE; + } + + public int SelectSchedulePlayerPush() { + if (HasCondition((int)COND_PLAYER_PUSHING) && !IsInAScript() && !IgnorePlayerPushing()) { + if (GlobalEntity.GetState("gordon_precriminal") != GlobalEState.On) { + MovingAwayFromPlayer = true; + return SCHED_MOVE_AWAY; + } + } + + return SCHED_NONE; + } + + public virtual bool IgnorePlayerPushing() => false; + + public virtual bool CanReload() { + if (IsRunningDynamicInteraction()) + return false; + + return true; + } + + public override int TranslateSchedule(int scheduleType) { + switch (scheduleType) { + case SCHED_IDLE_STAND: + case SCHED_ALERT_STAND: + if (GetActiveWeapon() != null) { + BaseCombatWeapon weapon = GetActiveWeapon()!; + + if (CanReload() && weapon.UsesClipsForAmmo1() && weapon.Clip1() < (weapon.GetMaxClip1() * .5) && OccupyStrategySlot(SquadSlot.ExclusiveReload)) + return SCHED_RELOAD; + } + break; + + case SCHED_COWER: + return SCHED_PC_COWER; + + case SCHED_TAKE_COVER_FROM_BEST_SOUND: { + ref WorldSoundInstance sound = ref GetBestSound(SoundInstanceType.Danger); + + if (!Unsafe.IsNullRef(ref sound) && sound.Owner.Get() != null) { + if (sound.Owner.Get()!.IsNPC() && FClassnameIs(sound.Owner.Get(), "npc_zombine")) + return SCHED_PC_TAKE_COVER_FROM_BEST_SOUND; + } + + return SCHED_PC_MOVE_TOWARDS_COVER_FROM_BEST_SOUND; + } + + case SCHED_FLEE_FROM_BEST_SOUND: + return SCHED_PC_FLEE_FROM_BEST_SOUND; + + case SCHED_ESTABLISH_LINE_OF_FIRE: + case SCHED_MOVE_TO_WEAPON_RANGE: + if (IsMortar(GetEnemy())) + return SCHED_TAKE_COVER_FROM_ENEMY; + break; + + case SCHED_CHASE_ENEMY: + if (IsMortar(GetEnemy())) + return SCHED_TAKE_COVER_FROM_ENEMY; + if (GetEnemy() != null && FClassnameIs(GetEnemy(), "npc_combinegunship")) + return SCHED_ESTABLISH_LINE_OF_FIRE; + break; + + case SCHED_ESTABLISH_LINE_OF_FIRE_FALLBACK: + if (GetEnemy() != null && FClassnameIs(GetEnemy(), "npc_combinegunship")) + return SCHED_ESTABLISH_LINE_OF_FIRE; + break; + + case SCHED_RANGE_ATTACK1: + if (IsMortar(GetEnemy())) + return SCHED_TAKE_COVER_FROM_ENEMY; + + if (GetShotRegulator().IsInRestInterval()) + return SCHED_STANDOFF; + + if (!OccupyStrategySlotRange(SquadSlot.Attack1, SquadSlot.Attack2)) + return SCHED_STANDOFF; + break; + + case SCHED_FAIL_TAKE_COVER: + if (IsEnemyTurret()) + return SCHED_PC_FAIL_TAKE_COVER_TURRET; + break; + + case SCHED_RUN_FROM_ENEMY_FALLBACK: + if (HasCondition((int)COND_CAN_RANGE_ATTACK1)) + return SCHED_RANGE_ATTACK1; + break; + } + + return base.TranslateSchedule(scheduleType); + } + + public override void StartTask(in Task_t task) { + switch (task.Task) { + case TASK_SOUND_WAKE: + LocateEnemySound(); + SetWait(0.5f); + break; + + case TASK_PC_WAITOUT_MORTAR: + if (HasCondition((int)COND_NO_HEAR_DANGER)) + TaskComplete(); + break; + + case TASK_PC_GET_PATH_OFF_COMPANION: + Assert(GetGroundEntity() != null && (GetGroundEntity()!.IsPlayer() || (GetGroundEntity()!.IsNPC() && IRelationType(GetGroundEntity()) == Disposition.LI))); + GetNavigator()!.SetAllowBigStep(GetGroundEntity()); + ChainStartTask(TASK_MOVE_AWAY_PATH, 48); + break; + + default: + base.StartTask(task); + break; + } + } + + public override void RunTask(in Task_t task) { + switch (task.Task) { + case TASK_SOUND_WAKE: + if (IsWaitFinished()) + TaskComplete(); + break; + + case TASK_PC_WAITOUT_MORTAR: + if (HasCondition((int)COND_NO_HEAR_DANGER)) + TaskComplete(); + break; + + case TASK_MOVE_AWAY_PATH: + base.RunTask(task); + + if (GetNavigator()!.IsGoalActive() && GetEnemy() == null) + AddFacingTarget(EyePosition() + BodyDirection2D() * 240, 1.0f, 2.0f); + break; + + case TASK_PC_GET_PATH_OFF_COMPANION: + GetNavigator()!.SetAllowBigStep(AI_GetClosestPlayer()); + ChainRunTask(TASK_MOVE_AWAY_PATH, 48); + break; + + default: + base.RunTask(task); + break; + } + } + + public virtual void LocateEnemySound() { } + + public override Activity NPC_TranslateActivity(Activity activity) { + if (activity == Activity.ACT_COWER) + return Activity.ACT_COVER_LOW; + + if (activity == Activity.ACT_RUN && (IsCurSchedule(SCHED_TAKE_COVER_FROM_BEST_SOUND) || IsCurSchedule(SCHED_FLEE_FROM_BEST_SOUND))) { + if (random.RandomInt(0, 1) != 0 && HaveSequenceForActivity(Activity.ACT_RUN_PROTECTED)) + activity = Activity.ACT_RUN_PROTECTED; + } + + activity = base.NPC_TranslateActivity(activity); + + if (activity == Activity.ACT_IDLE) { + if ((NPCState == NPCState.Combat || NPCState == NPCState.Alert) && gpGlobals.CurTime - LastAttackTime < 3) + activity = Activity.ACT_IDLE_ANGRY; + } + + return activity; + } + + public override void HandleAnimEvent(ref AnimEvent animEvent) { + switch (animEvent.Event) { + case EVENT_WEAPON_RELOAD: + if (GetActiveWeapon() != null) { + GetActiveWeapon()!.WeaponSound(WeaponSound.ReloadNPC); + GetActiveWeapon()!.iClip1 = GetActiveWeapon()!.GetMaxClip1(); + ClearCondition((int)COND_LOW_PRIMARY_AMMO); + ClearCondition((int)COND_NO_PRIMARY_AMMO); + ClearCondition((int)COND_NO_SECONDARY_AMMO); + } + break; + + default: + base.HandleAnimEvent(ref animEvent); + break; + } + } + + public override bool HandleInteraction(AI_Interaction interactionType, object? data, BaseCombatCharacter? sourceEnt) { + if (interactionType == AI_Interaction.HitByPlayerThrownPhysObj) + return true; + + return base.HandleInteraction(interactionType, data, sourceEnt); + } + + public override int GetSoundInterests() { + return (int)(SoundInstanceType.World | + SoundInstanceType.Combat | + SoundInstanceType.Player | + SoundInstanceType.Danger | + SoundInstanceType.BulletImpact | + SoundInstanceType.MoveAway | + SoundInstanceType.ReadinessLow | + SoundInstanceType.ReadinessMedium | + SoundInstanceType.ReadinessHigh); + } + + public override void Touch(BaseEntity? other) { + base.Touch(other); + + if (other!.IsPlayer() || (other.VPhysicsGetObject() != null && (other.VPhysicsGetObject()!.GetGameFlags() & PhysicsFlags.PlayerHeld) != 0)) { + if (HasMemory(AI_MemoryFlags.Provoked)) + return; + + TestPlayerPushing(other.IsPlayer() ? other : AI_GetClosestPlayer()); + } + } + + protected virtual bool IsReadinessCapable() { + if (GlobalEntity.GetState("gordon_precriminal") == GlobalEState.On) + return false; + + if (GetActiveWeapon() != null && LookupActivity("ACT_IDLE_AIM_RIFLE_STIMULATED") == Activity.ACT_INVALID) + return false; + + if (GetActiveWeapon() != null && FClassnameIs(GetActiveWeapon(), "weapon_rpg")) + return false; + + return true; + } + + protected bool IsReadinessLocked() => gpGlobals.CurTime < ReadinessLockedUntil; + + protected void AddReadiness(float add, bool overrideLock = false) { + if (IsReadinessLocked() && !overrideLock) + return; + + SetReadinessValue(GetReadinessValue() + add); + } + + protected void SubtractReadiness(float sub, bool overrideLock = false) { + if (IsReadinessLocked() && !overrideLock) + return; + + SetReadinessValue(Math.Max(GetReadinessValue() - sub, 0)); + } + + public bool AllowReadinessValueChange() { + if (GetIdealActivity() == Activity.ACT_IDLE || GetIdealActivity() == Activity.ACT_WALK || GetIdealActivity() == Activity.ACT_RUN) + return true; + + if (HasActiveLayer()) + return false; + + return false; + } + + protected void SetReadinessValue(float set) { + if (!AllowReadinessValueChange()) + return; + + AIReadiness priorReadiness = GetReadinessLevel(); + + set = Math.Min(1.0f, set); + set = Math.Max(READINESS_MIN_VALUE, set); + + Readiness = set; + + if (GetReadinessLevel() != priorReadiness) { + SetCondition((int)COND_IDLE_INTERRUPT); + + ResetActivity(); + + GetNavigator()!.SetArrivalSequence((int)Activity.ACT_INVALID); + + ReadinessLevelChanged(priorReadiness); + } + } + + protected void SetReadinessSensitivity(float sensitivity) => ReadinessSensitivity = sensitivity; + + protected virtual void UpdateReadiness() { + if (!IsInScriptedReadinessState()) { + if (HasCondition((int)COND_HEAR_COMBAT) || HasCondition((int)COND_HEAR_BULLET_IMPACT)) + SetReadinessLevel(AIReadiness.Stimulated, false, false); + + if (HasCondition((int)COND_HEAR_DANGER) || HasCondition((int)COND_SEE_ENEMY)) + SetReadinessLevel(AIReadiness.Agitated, false, false); + + if (Readiness > 0.0f && GetReadinessDecay() > 0) + SubtractReadiness((0.1f * (1.0f / GetReadinessDecay())) * ReadinessSensitivity); + } + + if (ai_debug_readiness.GetBool() && AI_IsSinglePlayer()) { + Vector3 spot; + Vector3 offset = new(0, 0, 12); + const float BARLENGTH = 12.0f; + const float GRADLENGTH = 4.0f; + + AI_GetClosestPlayer()!.GetVectors(out _, out Vector3 right, out _); + + if (IsInScriptedReadinessState()) { + spot = EyePosition() + offset; + + if (GetReadinessLevel() == AIReadiness.Stealth) + DebugOverlay.Text(spot, "Stealth", true, 0.1f); + else if (GetReadinessLevel() == AIReadiness.Panic) + DebugOverlay.Text(spot, "Panic", true, 0.1f); + else + DebugOverlay.Text(spot, "Unspecified", true, 0.1f); + } + else { + spot = EyePosition() + offset; + DebugOverlay.Line(spot, spot + right * GRADLENGTH, 255, 255, 255, false, 0.1f); + + spot = EyePosition() + offset + new Vector3(0, 0, BARLENGTH * READINESS_VALUE_RELAXED); + DebugOverlay.Line(spot, spot + right * GRADLENGTH, 0, 255, 0, false, 0.1f); + + spot = EyePosition() + offset + new Vector3(0, 0, BARLENGTH * READINESS_VALUE_STIMULATED); + DebugOverlay.Line(spot, spot + right * GRADLENGTH, 255, 255, 0, false, 0.1f); + + spot = EyePosition() + offset + new Vector3(0, 0, BARLENGTH * READINESS_VALUE_AGITATED); + DebugOverlay.Line(spot, spot + right * GRADLENGTH, 255, 0, 0, false, 0.1f); + + spot = EyePosition() + offset; + DebugOverlay.Line(spot, spot + new Vector3(0, 0, BARLENGTH * GetReadinessValue()), 255, 255, 0, false, 0.1f); + } + } + } + + protected virtual float GetReadinessDecay() => ai_readiness_decay.GetFloat(); + + protected bool IsInScriptedReadinessState() => Readiness < 0; + + public float GetReadinessValue() => Readiness; + + public AIReadiness GetReadinessLevel() { + if (!ReadinessCapable) + return AIReadiness.Relaxed; + + if (Readiness == READINESS_MODE_PANIC) + return AIReadiness.Panic; + + if (Readiness == READINESS_MODE_STEALTH) + return AIReadiness.Stealth; + + if (Readiness <= READINESS_VALUE_RELAXED) + return AIReadiness.Relaxed; + + if (Readiness <= READINESS_VALUE_STIMULATED) + return AIReadiness.Stimulated; + + return AIReadiness.Agitated; + } + + public void SetReadinessLevel(AIReadiness level, bool overrideLock, bool slam) { + if (IsReadinessLocked() && !overrideLock) + return; + + switch (level) { + case AIReadiness.Panic: + if (slam) + SetReadinessValue(READINESS_MODE_PANIC); + break; + case AIReadiness.Stealth: + if (slam) + SetReadinessValue(READINESS_MODE_STEALTH); + break; + case AIReadiness.Relaxed: + if (slam || GetReadinessValue() < READINESS_VALUE_RELAXED) + SetReadinessValue(READINESS_VALUE_RELAXED); + break; + case AIReadiness.Stimulated: + if (slam || GetReadinessValue() < READINESS_VALUE_STIMULATED) + SetReadinessValue(READINESS_VALUE_STIMULATED); + break; + case AIReadiness.Agitated: + if (slam || GetReadinessValue() < READINESS_VALUE_AGITATED) + SetReadinessValue(READINESS_VALUE_AGITATED); + break; + default: + DevMsg("ERROR: Bad readiness level\n"); + break; + } + } + + public void LockReadiness(float duration = -1.0f) { + if (duration == -1.0f) + ReadinessLockedUntil = float.MaxValue; + else + ReadinessLockedUntil = gpGlobals.CurTime + duration; + } + + public void UnlockReadiness() => ReadinessLockedUntil = gpGlobals.CurTime - 0.1f; + + public virtual void ReadinessLevelChanged(AIReadiness priorLevel) { } + + public bool IsEnemyTurret() => GetEnemy() != null && IsTurret(GetEnemy()); + + public static bool IsMortar(BaseEntity? entity) { + if (entity == null) + return false; + BaseEntity? entityParent = entity.GetParent(); + return entityParent != null && entityParent.Classname == "func_tankmortar"; + } + + public static bool IsSniper(BaseEntity? entity) { + if (entity == null) + return false; + return entity.Classify() == Class_T.ProtoSniper; + } + + public static bool IsTurret(BaseEntity? entity) { + if (entity == null) + return false; + string? classname = entity.Classname; + return classname == "npc_turret_floor" || classname == "npc_turret_ground"; + } + + public override bool ShouldLookForBetterWeapon() { + if (DontPickupWeapons) + return false; + + return base.ShouldLookForBetterWeapon(); + } + + public override void Weapon_Equip(BaseCombatWeapon weapon) { + base.Weapon_Equip(weapon); + ReadinessCapable = IsReadinessCapable(); + } + + public override bool FValidateHintType(AI_Hint hint) { + switch (hint.HintType()) { + case Hint.PlayerSquadTransitonPoint: + case Hint.WorldVisuallyInterestingDontAim: + case Hint.PlayerAllyMoveAwayDest: + case Hint.PlayerAllyFearDest: + return true; + + default: + break; + } + + return base.FValidateHintType(hint); + } + + public override float GetIdealAccel() { + float multiplier = 1.0f; + if (AI_IsSinglePlayer()) { + if (MovingAwayFromPlayer && (AI_GetClosestPlayer()!.GetAbsOrigin() - GetAbsOrigin()).Length2DSqr() < (3.0f * 12.0f) * (3.0f * 12.0f)) + multiplier = 2.0f; + } + return base.GetIdealAccel() * multiplier; + } + + public override bool OnObstructionPreSteer(ref AILocalMoveGoal moveGoal, float distClear, ref AIMoveResult result) { + if (moveGoal.DirectTrace.TotalDist - moveGoal.DirectTrace.DistObstructed < GetHullWidth() * 1.5f) { + AI_BaseNPC? blocker = moveGoal.DirectTrace.Obstruction?.MyNPCPointer(); + if (blocker != null && blocker.IsPlayerAlly() && !blocker.IsMoving() && !blocker.IsInAScript() && + (IsCurSchedule(SCHED_NEW_WEAPON) || + IsCurSchedule(SCHED_GET_HEALTHKIT) || + blocker.IsCurSchedule(SCHED_FAIL) || + (IsInPlayerSquad() && !blocker.IsInPlayerSquad()) || + Classify() == Class_T.PlayerAllyVital || + IsInAScript())) { + if (blocker.ConditionInterruptsCurSchedule((int)COND_GIVE_WAY) || + blocker.ConditionInterruptsCurSchedule((int)COND_PLAYER_PUSHING)) { + blocker.GetMotor()!.SetIdealYawToTarget(WorldSpaceCenter()); + blocker.SetSchedule(SCHED_MOVE_AWAY); + } + } + } + + return base.OnObstructionPreSteer(ref moveGoal, distClear, ref result); + } + + public void InputSetReadinessPanic(InputData inputdata) => SetReadinessLevel(AIReadiness.Panic, true, true); + public void InputSetReadinessStealth(InputData inputdata) => SetReadinessLevel(AIReadiness.Stealth, true, true); + public void InputSetReadinessLow(InputData inputdata) => SetReadinessLevel(AIReadiness.Relaxed, true, true); + public void InputSetReadinessMedium(InputData inputdata) => SetReadinessLevel(AIReadiness.Stimulated, true, true); + public void InputSetReadinessHigh(InputData inputdata) => SetReadinessLevel(AIReadiness.Agitated, true, true); + + public void InputLockReadiness(InputData inputdata) { + float value = inputdata.Value.Float(); + LockReadiness(value); + } + + public void InputEnableWeaponPickup(InputData inputdata) => DontPickupWeapons = false; + public void InputDisableWeaponPickup(InputData inputdata) => DontPickupWeapons = true; +} diff --git a/Game.Server/Player.cs b/Game.Server/Player.cs index 095cdeffa..2282ba616 100644 --- a/Game.Server/Player.cs +++ b/Game.Server/Player.cs @@ -250,6 +250,7 @@ public partial class BasePlayer : BaseCombatCharacter { public const int SF_NORESPAWN = 1 << 30; public const float DOT_30DEGREE = 0.866025403784f; + public const float DOT_45DEGREE = 0.707106781187f; public static readonly SendTable DT_PlayerState = new(nameof(DT_PlayerState), [ SendPropInt(FIELD.OF(nameof(PlayerState.DeadFlag)), 1, PropFlags.Unsigned) ]); From a8b954e4a53db0f1ff9481c47e7e01e421dfe349 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:52:14 +0300 Subject: [PATCH 61/73] Port npc_citizen --- Game.Server/NPC_Citizen.cs | 826 +++++++++++++++++++++++++++++++++++++ 1 file changed, 826 insertions(+) create mode 100644 Game.Server/NPC_Citizen.cs diff --git a/Game.Server/NPC_Citizen.cs b/Game.Server/NPC_Citizen.cs new file mode 100644 index 000000000..bb6f18ca7 --- /dev/null +++ b/Game.Server/NPC_Citizen.cs @@ -0,0 +1,826 @@ +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Mathematics; + +using System.Numerics; + +using static Game.Server.SCOND_t; + +namespace Game.Server; + +using DEFINE = DEFINE; + +public enum CitizenType +{ + Default, + Downtrodden, + Refugee, + Rebel, + Unique +} + +public enum CitizenExpressionType +{ + Unassigned, + + Scared, + Normal, + Angry, + + LastType, +} + +[LinkEntityToClass("npc_citizen")] +public class NPC_Citizen : NPC_PlayerCompanion +{ + public const int SF_CITIZEN_FOLLOW = 1 << 16; + public const int SF_CITIZEN_MEDIC = 1 << 17; + public const int SF_CITIZEN_RANDOM_HEAD = 1 << 18; + public const int SF_CITIZEN_AMMORESUPPLIER = 1 << 19; + public const int SF_CITIZEN_NOT_COMMANDABLE = 1 << 20; + public const int SF_CITIZEN_IGNORE_SEMAPHORE = 1 << 21; + public const int SF_CITIZEN_RANDOM_HEAD_MALE = 1 << 22; + public const int SF_CITIZEN_RANDOM_HEAD_FEMALE = 1 << 23; + public const int SF_CITIZEN_USE_RENDER_BOUNDS = 1 << 24; + + const int CIT_INSPECTED_DELAY_TIME = 120; + + const float SHOTGUN_DEFER_SEARCH_TIME = 20.0f; + const float OTHER_DEFER_SEARCH_TIME = float.MaxValue; + + const int STATES_WITH_EXPRESSIONS = 3; + + public static readonly ConVar sk_citizen_health = new("sk_citizen_health", "0"); + public static readonly ConVar npc_citizen_dont_precache_all = new("npc_citizen_dont_precache_all", "1"); + + static readonly string[][] ScaredExpressions = [ + ["scenes/Expressions/citizen_scared_idle_01.vcd"], + ["scenes/Expressions/citizen_scared_alert_01.vcd"], + ["scenes/Expressions/citizen_scared_combat_01.vcd"], + ]; + + static readonly string[][] NormalExpressions = [ + ["scenes/Expressions/citizen_normal_idle_01.vcd"], + ["scenes/Expressions/citizen_normal_alert_01.vcd"], + ["scenes/Expressions/citizen_normal_combat_01.vcd"], + ]; + + static readonly string[][] AngryExpressions = [ + ["scenes/Expressions/citizen_angry_idle_01.vcd"], + ["scenes/Expressions/citizen_angry_alert_01.vcd"], + ["scenes/Expressions/citizen_angry_combat_01.vcd"], + ]; + + static readonly string[] RandomHeads = [ + "male_01.mdl", + "male_02.mdl", + "female_01.mdl", + "male_03.mdl", + "female_02.mdl", + "male_04.mdl", + "female_03.mdl", + "male_05.mdl", + "female_04.mdl", + "male_06.mdl", + "female_06.mdl", + "male_07.mdl", + "female_07.mdl", + "male_08.mdl", + "male_09.mdl", + ]; + + static readonly string[] ModelLocs = [ + "Group01", + "Group01", + "Group02", + "Group03{0}", + ]; + + public static Activity ACT_CIT_HANDSUP; + public static Activity ACT_CIT_BLINDED; + public static Activity ACT_CIT_SHOWARMBAND; + public static Activity ACT_CIT_HEAL; + public static Activity ACT_CIT_STARTLED; + + public static AnimEventId AE_CITIZEN_GET_PACKAGE; + public static AnimEventId AE_CITIZEN_HEAL; + + const int COND_CIT_PLAYERHEALREQUEST = NPC_PlayerCompanion.NEXT_CONDITION; + const int COND_CIT_COMMANDHEAL = NPC_PlayerCompanion.NEXT_CONDITION + 1; + const int COND_CIT_HURTBYFIRE = NPC_PlayerCompanion.NEXT_CONDITION + 2; + const int COND_CIT_START_INSPECTION = NPC_PlayerCompanion.NEXT_CONDITION + 3; + + const int SCHED_CITIZEN_PLAY_INSPECT_ACTIVITY = NPC_PlayerCompanion.NEXT_SCHEDULE; + const int SCHED_CITIZEN_HEAL = NPC_PlayerCompanion.NEXT_SCHEDULE + 1; + const int SCHED_CITIZEN_RANGE_ATTACK1_RPG = NPC_PlayerCompanion.NEXT_SCHEDULE + 2; + const int SCHED_CITIZEN_PATROL = NPC_PlayerCompanion.NEXT_SCHEDULE + 3; + const int SCHED_CITIZEN_MOURN_PLAYER = NPC_PlayerCompanion.NEXT_SCHEDULE + 4; + const int SCHED_CITIZEN_SIT_ON_TRAIN = NPC_PlayerCompanion.NEXT_SCHEDULE + 5; + const int SCHED_CITIZEN_STRIDER_RANGE_ATTACK1_RPG = NPC_PlayerCompanion.NEXT_SCHEDULE + 6; + const int SCHED_CITIZEN_HEAL_TOSS = NPC_PlayerCompanion.NEXT_SCHEDULE + 7; + + const int TASK_CIT_HEAL = NPC_PlayerCompanion.NEXT_TASK; + const int TASK_CIT_RPG_AUGER = NPC_PlayerCompanion.NEXT_TASK + 1; + const int TASK_CIT_PLAY_INSPECT_SEQUENCE = NPC_PlayerCompanion.NEXT_TASK + 2; + const int TASK_CIT_SIT_ON_TRAIN = NPC_PlayerCompanion.NEXT_TASK + 3; + const int TASK_CIT_LEAVE_TRAIN = NPC_PlayerCompanion.NEXT_TASK + 4; + const int TASK_CIT_SPEAK_MOURNING = NPC_PlayerCompanion.NEXT_TASK + 5; + const int TASK_CIT_HEAL_TOSS = NPC_PlayerCompanion.NEXT_TASK + 6; + + static readonly AI_ClassScheduleIdSpace gm_ClassScheduleIdSpace = new(); + + public static readonly new DataMap DataDesc = new(typeof(NPC_Citizen), NPC_PlayerCompanion.DataDesc, [ + DEFINE.KEYFIELD(nameof(Type), FieldType.Integer, "citizentype"), + DEFINE.KEYFIELD(nameof(ExpressionType), FieldType.Integer, "expressiontype"), + + DEFINE.INPUTFUNC(FieldType.Void, "StartPatrolling", nameof(InputStartPatrolling), (INPUTFUNCPTR)((self, data) => ((NPC_Citizen)self).InputStartPatrolling(data))), + DEFINE.INPUTFUNC(FieldType.Void, "StopPatrolling", nameof(InputStopPatrolling), (INPUTFUNCPTR)((self, data) => ((NPC_Citizen)self).InputStopPatrolling(data))), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + Activity InspectActivity; + TimeUnit_t NextInspectTime; + bool ShouldPatrol; + + CitizenType Type; + CitizenExpressionType ExpressionType; + + int Head = -1; + + public NPC_Citizen() => LoadSchedules(); + + public override AI_ClassScheduleIdSpace GetClassScheduleIdSpace() => gm_ClassScheduleIdSpace; + public override ReadOnlySpan GetSchedulingErrorName() => nameof(NPC_Citizen); + + public static new bool LoadSchedules() => CustomSchedules.Load(NPC_PlayerCompanion.LoadSchedules, nameof(NPC_Citizen)); + + public override bool LoadedSchedules() => CustomSchedules.Valid; + + static readonly AI_CustomSchedules CustomSchedules = new() { + IdSpace = gm_ClassScheduleIdSpace, + ParentIdSpace = NPC_PlayerCompanion.ClassScheduleIdSpace, + Schedules = [ + (nameof(SCHED_CITIZEN_PLAY_INSPECT_ACTIVITY), SCHED_CITIZEN_PLAY_INSPECT_ACTIVITY), + (nameof(SCHED_CITIZEN_HEAL), SCHED_CITIZEN_HEAL), + (nameof(SCHED_CITIZEN_RANGE_ATTACK1_RPG), SCHED_CITIZEN_RANGE_ATTACK1_RPG), + (nameof(SCHED_CITIZEN_PATROL), SCHED_CITIZEN_PATROL), + (nameof(SCHED_CITIZEN_MOURN_PLAYER), SCHED_CITIZEN_MOURN_PLAYER), + (nameof(SCHED_CITIZEN_SIT_ON_TRAIN), SCHED_CITIZEN_SIT_ON_TRAIN), + (nameof(SCHED_CITIZEN_STRIDER_RANGE_ATTACK1_RPG), SCHED_CITIZEN_STRIDER_RANGE_ATTACK1_RPG), + (nameof(SCHED_CITIZEN_HEAL_TOSS), SCHED_CITIZEN_HEAL_TOSS), + ], + Tasks = [ + (nameof(TASK_CIT_HEAL), TASK_CIT_HEAL), + (nameof(TASK_CIT_RPG_AUGER), TASK_CIT_RPG_AUGER), + (nameof(TASK_CIT_PLAY_INSPECT_SEQUENCE), TASK_CIT_PLAY_INSPECT_SEQUENCE), + (nameof(TASK_CIT_SIT_ON_TRAIN), TASK_CIT_SIT_ON_TRAIN), + (nameof(TASK_CIT_LEAVE_TRAIN), TASK_CIT_LEAVE_TRAIN), + (nameof(TASK_CIT_SPEAK_MOURNING), TASK_CIT_SPEAK_MOURNING), + (nameof(TASK_CIT_HEAL_TOSS), TASK_CIT_HEAL_TOSS), + ], + Conditions = [ + (nameof(COND_CIT_PLAYERHEALREQUEST), COND_CIT_PLAYERHEALREQUEST), + (nameof(COND_CIT_COMMANDHEAL), COND_CIT_COMMANDHEAL), + (nameof(COND_CIT_START_INSPECTION), COND_CIT_START_INSPECTION), + ], + Declare = static () => { + ACT_CIT_HANDSUP = DeclareActivity(nameof(ACT_CIT_HANDSUP)); + ACT_CIT_BLINDED = DeclareActivity(nameof(ACT_CIT_BLINDED)); + ACT_CIT_SHOWARMBAND = DeclareActivity(nameof(ACT_CIT_SHOWARMBAND)); + ACT_CIT_HEAL = DeclareActivity(nameof(ACT_CIT_HEAL)); + ACT_CIT_STARTLED = DeclareActivity(nameof(ACT_CIT_STARTLED)); + AE_CITIZEN_GET_PACKAGE = DeclareAnimEvent(nameof(AE_CITIZEN_GET_PACKAGE)); + AE_CITIZEN_HEAL = DeclareAnimEvent(nameof(AE_CITIZEN_HEAL)); + }, + Definitions = [ + new(SCHED_CITIZEN_HEAL, + [ + TASK_GET_PATH_TO_TARGET, + (TASK_MOVE_TO_TARGET_RANGE, 50), + TASK_STOP_MOVING, + TASK_FACE_IDEAL, + TASK_CIT_HEAL, + ]), + + new(SCHED_CITIZEN_HEAL_TOSS, + [ + TASK_STOP_MOVING, + TASK_FACE_IDEAL, + TASK_CIT_HEAL_TOSS, + ]), + + new(SCHED_CITIZEN_RANGE_ATTACK1_RPG, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + TASK_RANGE_ATTACK1, + (TASK_CIT_RPG_AUGER, 1), + ]), + + new(SCHED_CITIZEN_STRIDER_RANGE_ATTACK1_RPG, + [ + TASK_STOP_MOVING, + TASK_FACE_ENEMY, + (TASK_ANNOUNCE_ATTACK, 1), + (TASK_WAIT, 1), + TASK_RANGE_ATTACK1, + (TASK_CIT_RPG_AUGER, 1), + (TASK_SET_SCHEDULE, SCHED_TAKE_COVER_FROM_ENEMY), + ]), + + new(SCHED_CITIZEN_PATROL, + [ + TASK_STOP_MOVING, + (TASK_WANDER, 901024), + TASK_WALK_PATH, + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + (TASK_WAIT, 3), + (TASK_WAIT_RANDOM, 3), + (TASK_SET_SCHEDULE, SCHED_CITIZEN_PATROL), + ], + [ + COND_ENEMY_DEAD, + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_HEAR_DANGER, + COND_NEW_ENEMY, + ]), + + new(SCHED_CITIZEN_MOURN_PLAYER, + [ + TASK_GET_PATH_TO_PLAYER, + (TASK_RUN_PATH_WITHIN_DIST, 180), + TASK_WAIT_FOR_MOVEMENT, + TASK_STOP_MOVING, + TASK_TARGET_PLAYER, + TASK_FACE_TARGET, + TASK_CIT_SPEAK_MOURNING, + (TASK_SUGGEST_STATE, NPCState.Idle), + ], + [ + COND_LIGHT_DAMAGE, + COND_HEAVY_DAMAGE, + COND_HEAR_DANGER, + COND_NEW_ENEMY, + ]), + + new(SCHED_CITIZEN_PLAY_INSPECT_ACTIVITY, + [ + TASK_STOP_MOVING, + TASK_CIT_PLAY_INSPECT_SEQUENCE, + (TASK_WAIT, 2), + ]), + + new(SCHED_CITIZEN_SIT_ON_TRAIN, + [ + TASK_CIT_SIT_ON_TRAIN, + (TASK_WAIT_RANDOM, 1), + TASK_CIT_LEAVE_TRAIN, + ]), + ], + }; + + public bool IsMedic() => HasSpawnFlags(SF_CITIZEN_MEDIC); + public bool IsAmmoResupplier() => HasSpawnFlags(SF_CITIZEN_AMMORESUPPLIER); + + public override void Precache() { + SelectModel(); + SelectExpressionType(); + + if (!npc_citizen_dont_precache_all.GetBool()) + PrecacheAllOfType(Type); + else + PrecacheModel(GetModelName()); + + PrecacheScriptSound("NPC_Citizen.FootstepLeft"); + PrecacheScriptSound("NPC_Citizen.FootstepRight"); + PrecacheScriptSound("NPC_Citizen.Die"); + + PrecacheInstancedScene("scenes/Expressions/CitizenIdle.vcd"); + PrecacheInstancedScene("scenes/Expressions/CitizenAlert_loop.vcd"); + PrecacheInstancedScene("scenes/Expressions/CitizenCombat_loop.vcd"); + + for (int i = 0; i < STATES_WITH_EXPRESSIONS; i++) { + for (int j = 0; j < ScaredExpressions[i].Length; j++) + PrecacheInstancedScene(ScaredExpressions[i][j]); + for (int j = 0; j < NormalExpressions[i].Length; j++) + PrecacheInstancedScene(NormalExpressions[i][j]); + for (int j = 0; j < AngryExpressions[i].Length; j++) + PrecacheInstancedScene(AngryExpressions[i][j]); + } + + base.Precache(); + } + + void PrecacheAllOfType(CitizenType type) { + if (Type == CitizenType.Unique) + return; + + for (int i = 0; i < RandomHeads.Length; ++i) + PrecacheModel($"models/Humans/{string.Format(ModelLocs[(int)Type], "")}/{RandomHeads[i]}"); + + if (Type == CitizenType.Rebel) { + for (int i = 0; i < RandomHeads.Length; ++i) + PrecacheModel($"models/Humans/{string.Format(ModelLocs[(int)Type], "m")}/{RandomHeads[i]}"); + } + } + + public override void Spawn() { + base.Spawn(); + + if (IsAmmoResupplier()) + Skin = 2; + + ShouldPatrol = false; + Health = (int)sk_citizen_health.GetFloat(); + + if (GetMoveParent() != null && FClassnameIs(GetMoveParent(), "func_tracktrain")) { + CapabilitiesRemove(Capability.MoveGround); + SetMoveType(Source.MoveType.None); + if (NameMatches("citizen_train_2")) { + SetSequenceByName("d1_t01_TrainRide_Sit_Idle"); + SetIdealActivity(Activity.ACT_DO_NOT_DISTURB); + } + else { + SetSequenceByName("d1_t01_TrainRide_Stand"); + SetIdealActivity(Activity.ACT_DO_NOT_DISTURB); + } + } + + IdleExpression = "scenes/expressions/citizenidle.vcd"; + AlertExpression = "scenes/expressions/citizenalert_loop.vcd"; + CombatExpression = "scenes/expressions/citizencombat_loop.vcd"; + + AddEFlags(EFL.NoDissolve | EFL.NoMegaPhysCannonRagdoll | EFL.NoPhysCannonInteraction); + + RemoveEFlags(EFL.NoDissolve); + + NPCInit(); + + ActBusyBehavior.SetUseRenderBounds(HasSpawnFlags(SF_CITIZEN_USE_RENDER_BOUNDS)); + } + + public override void SelectModel() { + string? modelName = null; + + if (Type == CitizenType.Default) { + ReadOnlySpan mapName = gpGlobals.MapName; + + if (mapName.Contains("trainstation", StringComparison.OrdinalIgnoreCase)) + Type = CitizenType.Downtrodden; + else if (mapName.Contains("canals", StringComparison.OrdinalIgnoreCase)) + Type = CitizenType.Refugee; + else if (mapName.Contains("town", StringComparison.OrdinalIgnoreCase)) + Type = CitizenType.Refugee; + else if (mapName.Contains("coast", StringComparison.OrdinalIgnoreCase)) + Type = CitizenType.Refugee; + else if (mapName.Contains("prison", StringComparison.OrdinalIgnoreCase)) + Type = CitizenType.Downtrodden; + else if (mapName.Contains("c17", StringComparison.OrdinalIgnoreCase)) + Type = CitizenType.Rebel; + else if (mapName.Contains("citadel", StringComparison.OrdinalIgnoreCase)) + Type = CitizenType.Downtrodden; + + if (Type == CitizenType.Default) + Type = CitizenType.Downtrodden; + } + + if (HasSpawnFlags(SF_CITIZEN_RANDOM_HEAD | SF_CITIZEN_RANDOM_HEAD_MALE | SF_CITIZEN_RANDOM_HEAD_FEMALE) || GetModelName().IsEmpty) { + Assert(Head == -1); + char gender = HasSpawnFlags(SF_CITIZEN_RANDOM_HEAD_MALE) ? 'm' : + HasSpawnFlags(SF_CITIZEN_RANDOM_HEAD_FEMALE) ? 'f' : '\0'; + + RemoveSpawnFlags(SF_CITIZEN_RANDOM_HEAD | SF_CITIZEN_RANDOM_HEAD_MALE | SF_CITIZEN_RANDOM_HEAD_FEMALE); + if (HasSpawnFlags(SF_NPC_START_EFFICIENT)) { + SetModelName("models/humans/male_cheaple.mdl"); + return; + } + else { + Span headCounts = stackalloc int[RandomHeads.Length]; + int i; + + List ais = g_AI_Manager.AccessAIs(); + for (i = 0; i < g_AI_Manager.NumAIs(); i++) { + if (ais[i] is NPC_Citizen citizen && citizen != this && citizen.Head >= 0 && citizen.Head < RandomHeads.Length) + headCounts[citizen.Head]++; + } + + Span<(int Head, int Heads)> candidates = stackalloc (int, int)[RandomHeads.Length]; + int numCandidates = 0; + + for (i = 0; i < RandomHeads.Length; i++) { + if (gender == '\0' || RandomHeads[i][0] == gender) + candidates[numCandidates++] = (i, headCounts[i]); + } + + Assert(numCandidates != 0); + candidates[..numCandidates].Sort(static (left, right) => left.Heads - right.Heads); + + int smallestCount = candidates[0].Heads; + int limit; + + for (limit = 0; limit < numCandidates; limit++) { + if (candidates[limit].Heads > smallestCount) + break; + } + + Head = candidates[random.RandomInt(0, limit - 1)].Head; + modelName = RandomHeads[Head]; + SetModelName(default(ReadOnlySpan)); + } + } + + Assert(modelName != null || !GetModelName().IsEmpty); + + if (modelName == null) { + if (GetModelName().IsEmpty) + return; + + ReadOnlySpan currentModel = GetModelName(); + int slash = currentModel.LastIndexOf('/'); + if (slash == -1) + modelName = currentModel.ToString(); + else { + modelName = currentModel[(slash + 1)..].ToString(); + if (Head == -1) { + for (int i = 0; i < RandomHeads.Length; i++) { + if (string.Equals(RandomHeads[i], modelName, StringComparison.OrdinalIgnoreCase)) { + Head = i; + break; + } + } + } + } + if (modelName.Length == 0) + return; + } + + if (Type != CitizenType.Unique) + SetModelName($"models/Humans/{string.Format(ModelLocs[(int)Type], IsMedic() ? "m" : "")}/{modelName}"); + } + + void SelectExpressionType() { + if (ExpressionType != CitizenExpressionType.Unassigned) + return; + + switch (Type) { + case CitizenType.Downtrodden: + ExpressionType = (CitizenExpressionType)random.RandomInt((int)CitizenExpressionType.Scared, (int)CitizenExpressionType.Normal); + break; + case CitizenType.Refugee: + ExpressionType = (CitizenExpressionType)random.RandomInt((int)CitizenExpressionType.Scared, (int)CitizenExpressionType.Normal); + break; + case CitizenType.Rebel: + ExpressionType = (CitizenExpressionType)random.RandomInt((int)CitizenExpressionType.Scared, (int)CitizenExpressionType.Angry); + break; + + case CitizenType.Default: + case CitizenType.Unique: + default: + break; + } + } + + public override Class_T Classify() { + if (GlobalEntity.GetState("gordon_precriminal") == GlobalEState.On) + return Class_T.CitizenPassive; + + if (GlobalEntity.GetState("citizens_passive") == GlobalEState.On) + return Class_T.CitizenPassive; + + return Class_T.PlayerAlly; + } + + public override void BuildScheduleTestBits() { + base.BuildScheduleTestBits(); + + if (IsCurSchedule(SCHED_IDLE_STAND) || IsCurSchedule(SCHED_ALERT_STAND)) + SetCustomInterruptCondition(COND_CIT_START_INSPECTION); + + if (!IsCurSchedule(SCHED_NEW_WEAPON)) + SetCustomInterruptCondition((int)COND_RECEIVED_ORDERS); + + if (GetCurSchedule()!.HasInterrupt((int)COND_IDLE_INTERRUPT)) + SetCustomInterruptCondition((int)COND_BETTER_WEAPON_AVAILABLE); + } + + public override int SelectSchedule() { + if (GetMoveType() == Source.MoveType.None) { + Assert(GetMoveParent() != null && FClassnameIs(GetMoveParent(), "func_tracktrain")); + return SCHED_CITIZEN_SIT_ON_TRAIN; + } + + return base.SelectSchedule(); + } + + public override int SelectScheduleNonCombat() { + if (NPCState == NPCState.Idle) { + if (HasCondition(COND_CIT_START_INSPECTION)) { + ClearCondition(COND_CIT_START_INSPECTION); + return SCHED_CITIZEN_PLAY_INSPECT_ACTIVITY; + } + } + + ClearCondition(COND_CIT_START_INSPECTION); + + if (ShouldPatrol) + return SCHED_CITIZEN_PATROL; + + return SCHED_NONE; + } + + public override int TranslateSchedule(int scheduleType) { + switch (scheduleType) { + case SCHED_IDLE_STAND: + case SCHED_ALERT_STAND: { + BasePlayer? localPlayer = AI_GetClosestPlayer(); + if (NPCState != NPCState.Combat && localPlayer != null && !localPlayer.IsAlive() && CanJoinPlayerSquad()) { + float dist = (localPlayer.GetAbsOrigin() - GetAbsOrigin()).Length(); + + if (dist < 50 * 12) { + AddSpawnFlags(SF_CITIZEN_NOT_COMMANDABLE); + return SCHED_CITIZEN_MOURN_PLAYER; + } + } + } + break; + } + + return base.TranslateSchedule(scheduleType); + } + + public override void StartTask(in Task_t task) { + switch (task.Task) { + case TASK_CIT_PLAY_INSPECT_SEQUENCE: + SetIdealActivity(InspectActivity); + break; + + case TASK_CIT_SIT_ON_TRAIN: + if (NameMatches("citizen_train_2")) { + SetSequenceByName("d1_t01_TrainRide_Sit_Idle"); + SetIdealActivity(Activity.ACT_DO_NOT_DISTURB); + } + else { + SetSequenceByName("d1_t01_TrainRide_Stand"); + SetIdealActivity(Activity.ACT_DO_NOT_DISTURB); + } + break; + + case TASK_CIT_LEAVE_TRAIN: + if (NameMatches("citizen_train_2")) { + SetSequenceByName("d1_t01_TrainRide_Sit_Exit"); + SetIdealActivity(Activity.ACT_DO_NOT_DISTURB); + } + else { + SetSequenceByName("d1_t01_TrainRide_Stand_Exit"); + SetIdealActivity(Activity.ACT_DO_NOT_DISTURB); + } + break; + + case TASK_CIT_SPEAK_MOURNING: + TaskComplete(); + break; + + default: + base.StartTask(task); + break; + } + } + + public override void RunTask(in Task_t task) { + switch (task.Task) { + case TASK_CIT_PLAY_INSPECT_SEQUENCE: + AutoMovement(); + + if (IsSequenceFinished()) + TaskComplete(); + break; + + case TASK_CIT_SIT_ON_TRAIN: + if (GetMoveParent() == null) { + SetMoveType(Source.MoveType.Step); + CapabilitiesAdd(Capability.MoveGround); + TaskComplete(); + } + break; + + case TASK_CIT_LEAVE_TRAIN: + if (IsSequenceFinished()) { + SetupVPhysicsHull(); + TaskComplete(); + } + break; + + default: + base.RunTask(task); + break; + } + } + + public override void HandleAnimEvent(ref AnimEvent animEvent) { + if (animEvent.Event == (int)AE_CITIZEN_GET_PACKAGE) { + BaseCombatWeapon? weapon = Weapon_Create("weapon_citizenpackage"); + if (weapon != null) { + if (GetEntityName() != null) + weapon.SetName($"{GetEntityName()}_weapon"); + Weapon_Equip(weapon); + } + return; + } + + switch (animEvent.Event) { + case NPC_EVENT_LEFTFOOT: + EmitSound("NPC_Citizen.FootstepLeft", animEvent.EventTime); + break; + + case NPC_EVENT_RIGHTFOOT: + EmitSound("NPC_Citizen.FootstepRight", animEvent.EventTime); + break; + + default: + base.HandleAnimEvent(ref animEvent); + break; + } + } + + public override string? SelectRandomExpressionForState(NPCState state) { + int expressionState; + switch (state) { + case NPCState.Idle: + expressionState = 0; + break; + + case NPCState.Alert: + expressionState = 1; + break; + + case NPCState.Combat: + expressionState = 2; + break; + + default: + return null; + } + + switch (ExpressionType) { + case CitizenExpressionType.Scared: { + int randomIndex = random.RandomInt(0, ScaredExpressions[expressionState].Length - 1); + return ScaredExpressions[expressionState][randomIndex]; + } + + case CitizenExpressionType.Normal: { + int randomIndex = random.RandomInt(0, NormalExpressions[expressionState].Length - 1); + return NormalExpressions[expressionState][randomIndex]; + } + + case CitizenExpressionType.Angry: { + int randomIndex = random.RandomInt(0, AngryExpressions[expressionState].Length - 1); + return AngryExpressions[expressionState][randomIndex]; + } + + default: + break; + } + + return null; + } + + public override bool ShouldLookForBetterWeapon() { + if (base.ShouldLookForBetterWeapon()) { + if (GetActiveWeapon() != null && IsMoving()) + return false; + + if (GlobalEntity.GetState("gordon_precriminal") == GlobalEState.On) { + NextWeaponSearchTime = float.MaxValue; + return false; + } + + BaseCombatWeapon? weapon = GetActiveWeapon(); + if (weapon != null) { + bool defer = false; + + if (FClassnameIs(weapon, "weapon_ar2")) { + NextWeaponSearchTime = OTHER_DEFER_SEARCH_TIME; + defer = true; + } + else if (FClassnameIs(weapon, "weapon_rpg")) { + NextWeaponSearchTime = OTHER_DEFER_SEARCH_TIME; + defer = true; + } + else if (FClassnameIs(weapon, "weapon_shotgun")) { + if (NumWeaponsInSquad("weapon_shotgun") > 1) + defer = false; + else { + if (random.RandomInt(0, 1) == 0) + NextWeaponSearchTime = gpGlobals.CurTime + SHOTGUN_DEFER_SEARCH_TIME; + else + NextWeaponSearchTime = gpGlobals.CurTime + SHOTGUN_DEFER_SEARCH_TIME + 10.0f; + + defer = true; + } + } + + if (defer) + return false; + } + + return true; + } + + return false; + } + + public override bool IsPlayerAlly(BasePlayer? player = null) { + if (Classify() == Class_T.CitizenPassive && GlobalEntity.GetState("gordon_precriminal") == GlobalEState.On) + return true; + + return base.IsPlayerAlly(player); + } + + public bool CanJoinPlayerSquad() { + if (NPCState == NPCState.Script || NPCState == NPCState.Prone) + return false; + + if (HasSpawnFlags(SF_CITIZEN_NOT_COMMANDABLE)) + return false; + + if (IsInAScript()) + return false; + + if (!CanBeUsedAsAFriend()) + return false; + + if (IRelationType(AI_GetClosestPlayer()) != Disposition.LI) + return false; + + return true; + } + + public override bool HandleInteraction(AI_Interaction interactionType, object? data, BaseCombatCharacter? sourceEnt) { + if (interactionType == AI_Interaction.ScannerInspect) { + if (gpGlobals.CurTime > NextInspectTime) { + NextInspectTime = gpGlobals.CurTime + 5.0; + return true; + } + return false; + } + else if (interactionType == AI_Interaction.ScannerInspectBegin) { + NextInspectTime = gpGlobals.CurTime + CIT_INSPECTED_DELAY_TIME; + + Vector3 targetDir = sourceEnt!.WorldSpaceCenter() - WorldSpaceCenter(); + MathLib.VectorNormalize(ref targetDir); + + if (Vector3.Dot(targetDir, BodyDirection3D()) < 0) + InspectActivity = ACT_CIT_STARTLED; + else + InspectActivity = ACT_CIT_BLINDED; + + SetCondition(COND_CIT_START_INSPECTION); + return true; + } + else if (interactionType == AI_Interaction.ScannerInspectHandsUp) { + InspectActivity = ACT_CIT_HANDSUP; + SetSchedule(SCHED_CITIZEN_PLAY_INSPECT_ACTIVITY); + return true; + } + else if (interactionType == AI_Interaction.ScannerInspectShowArmband) { + InspectActivity = ACT_CIT_SHOWARMBAND; + SetSchedule(SCHED_CITIZEN_PLAY_INSPECT_ACTIVITY); + return true; + } + else if (interactionType == AI_Interaction.ScannerInspectDone) { + SetSchedule(SCHED_IDLE_WANDER); + return true; + } + else if (interactionType == AI_Interaction.HitByPlayerThrownPhysObj) + return true; + + return base.HandleInteraction(interactionType, data, sourceEnt); + } + + public override bool FValidateHintType(AI_Hint hint) { + switch (hint.HintType()) { + case Hint.WorldVisuallyInteresting: + return true; + + default: + break; + } + + return base.FValidateHintType(hint); + } + + public void InputStartPatrolling(InputData inputdata) => ShouldPatrol = true; + public void InputStopPatrolling(InputData inputdata) => ShouldPatrol = false; + + public override void DeathSound(in TakeDamageInfo info) { + SentenceStop(); + + EmitSound("NPC_Citizen.Die"); + } +} From 4cd98e438d6bda0aebcb7bbed6e305be00b21e34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:58:46 +0300 Subject: [PATCH 62/73] Fix template NPCs spawning instead of being stored --- Game.Server/AI_BaseNPC.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 7cd42dbc6..9d77c1798 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -2638,6 +2638,8 @@ public static void InitSchedulingTables() { public NPCState GetIdealState() => IdealNPCState; + public override bool IsTemplate() => HasSpawnFlags(SF_NPC_TEMPLATE); + public bool IsRunningDynamicInteraction() => InteractionState != NPCInteractionState.NotRunning && Cine.Get() != null; public static readonly ConVar sv_test_scripted_sequences = new("sv_test_scripted_sequences", "0", FCvar.None, "Tests for scripted sequences that are embedded in the world. Run through your map with this set to check for NPCs falling through the world."); From 21e7fa33b1016860f89f3e4efe0959daf1144277 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:03:21 +0300 Subject: [PATCH 63/73] Fix owner death notices for removed characters --- Game.Server/BaseCombatCharacter.cs | 16 ++++++++++++++++ Game.Server/BaseEntity.cs | 4 ++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Game.Server/BaseCombatCharacter.cs b/Game.Server/BaseCombatCharacter.cs index 07d1fb3bb..bcc289611 100644 --- a/Game.Server/BaseCombatCharacter.cs +++ b/Game.Server/BaseCombatCharacter.cs @@ -527,6 +527,22 @@ public bool Weapon_IsOnGround(BaseCombatWeapon weapon) { return bestWeapon; } + public override void UpdateOnRemove() { + int i; + for (i = 0; i < MAX_WEAPONS; i++) { + if (MyWeapons[i].Get() != null) + Util.Remove(MyWeapons[i].Get()); + } + + BaseEntity? owner = GetOwnerEntity(); + if (owner != null) { + owner.DeathNotice(this); + SetOwnerEntity(null); + } + + base.UpdateOnRemove(); + } + public BaseCombatWeapon? Weapon_Create(ReadOnlySpan weaponName) { BaseCombatWeapon? weapon = (BaseCombatWeapon?)Create(weaponName, GetLocalOrigin(), GetLocalAngles(), this); diff --git a/Game.Server/BaseEntity.cs b/Game.Server/BaseEntity.cs index bcbfb1da9..ede311582 100644 --- a/Game.Server/BaseEntity.cs +++ b/Game.Server/BaseEntity.cs @@ -2545,7 +2545,7 @@ public void InputColor(InputData inputdata) { public void InputKill(InputData inputdata) { BaseEntity? owner = GetOwnerEntity(); if (owner != null) { - // owner.DeathNotice(this); + owner.DeathNotice(this); SetOwnerEntity(null); } @@ -2561,7 +2561,7 @@ public void InputKillHierarchy(InputData inputdata) { BaseEntity? owner = GetOwnerEntity(); if (owner != null) { - // owner.DeathNotice(this); + owner.DeathNotice(this); SetOwnerEntity(null); } From dfcdde14a3995ef759f870a0b3ac28cf5bcbc14d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:11:48 +0300 Subject: [PATCH 64/73] Port npc_maker and npc_template_maker --- Game.Server/AI_BaseNPC.cs | 31 ++ Game.Server/MapEntities.cs | 2 +- Game.Server/NPCMaker.cs | 752 ++++++++++++++++++++++++++++++++ Game.Server/TemplateEntities.cs | 11 + Game.Server/Util.cs | 10 + 5 files changed, 805 insertions(+), 1 deletion(-) create mode 100644 Game.Server/NPCMaker.cs diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 9d77c1798..42413465d 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -2640,6 +2640,37 @@ public static void InitSchedulingTables() { public override bool IsTemplate() => HasSpawnFlags(SF_NPC_TEMPLATE); + public static bool FindSpotForNPCInRadius(out Vector3 result, in Vector3 startPos, AI_BaseNPC npc, float radius, bool outOfPlayerViewcone = false) { + BasePlayer? player = npc.AI_GetClosestPlayer(); + QAngle fan; + + fan.X = 0; + fan.Z = 0; + + for (fan.Y = 0; fan.Y < 360; fan.Y += 18.0f) { + MathLib.AngleVectors(fan, out Vector3 dir); + + Vector3 test = startPos + dir * radius; + + if (outOfPlayerViewcone && player != null && !player.FInViewCone(test)) + continue; + + Util.TraceLine(test, test - new Vector3(0, 0, 8192), Mask.Shot, npc, Source.CollisionGroup.None, out Trace tr); + if (tr.Fraction == 1.0f) + continue; + + Util.TraceHull(tr.EndPos, tr.EndPos + new Vector3(0, 0, 10), npc.GetHullMins(), npc.GetHullMaxs(), Mask.NPCSolid, npc, Source.CollisionGroup.None, out tr); + + if (tr.Fraction == 1.0f && npc.GetMoveProbe()!.CheckStandPosition(tr.EndPos, Mask.NPCSolid)) { + result = tr.EndPos; + return true; + } + } + + result = default; + return false; + } + public bool IsRunningDynamicInteraction() => InteractionState != NPCInteractionState.NotRunning && Cine.Get() != null; public static readonly ConVar sv_test_scripted_sequences = new("sv_test_scripted_sequences", "0", FCvar.None, "Tests for scripted sequences that are embedded in the world. Run through your map with this set to check for NPCs falling through the world."); diff --git a/Game.Server/MapEntities.cs b/Game.Server/MapEntities.cs index c85dce55d..d2bee2abc 100644 --- a/Game.Server/MapEntities.cs +++ b/Game.Server/MapEntities.cs @@ -352,7 +352,7 @@ static void SpawnHierarchicalList(int entities, HierarchicalSpawn_t[] spawnList, // entData - Data block to parse to extract entity keys. // Output : Returns the current position in the entity data block. //----------------------------------------------------------------------------- - static ReadOnlyMemory ParseEntity(out BaseEntity? entity, ReadOnlyMemory entDataMem, IMapEntityFilter? filter) { + public static ReadOnlyMemory ParseEntity(out BaseEntity? entity, ReadOnlyMemory entDataMem, IMapEntityFilter? filter) { EntityMapData entData = new(entDataMem); Span className = stackalloc byte[EntityMapData.MAPKEY_MAXLENGTH]; diff --git a/Game.Server/NPCMaker.cs b/Game.Server/NPCMaker.cs new file mode 100644 index 000000000..0dedc4bee --- /dev/null +++ b/Game.Server/NPCMaker.cs @@ -0,0 +1,752 @@ +using Game.Shared; + +using Source; +using Source.Common; +using Source.Common.Commands; +using Source.Common.Formats.BSP; +using Source.Common.Mathematics; + +using System.Numerics; + +namespace Game.Server; + +[LinkEntityToClass("info_npc_spawn_destination")] +public class NPCSpawnDestination : PointEntity +{ + public static readonly new DataMap DataDesc = new(typeof(NPCSpawnDestination), PointEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(ReuseDelay), FieldType.Float, "ReuseDelay"), + DEFINE.KEYFIELD(nameof(RenameNPC), FieldType.String, "RenameNPC"), + + DEFINE.OUTPUT(nameof(OnSpawnNPC), "OnSpawnNPC", eventFuncs), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public float ReuseDelay; + public string? RenameNPC; + public TimeUnit_t TimeNextAvailable; + + public OutputEvent OnSpawnNPC = new(); + + public NPCSpawnDestination() => TimeNextAvailable = gpGlobals.CurTime; + + public bool IsAvailable() { + if (TimeNextAvailable > gpGlobals.CurTime) + return false; + + return true; + } + + public void OnSpawnedNPC(AI_BaseNPC npc) { + if (RenameNPC != null) + npc.SetName(RenameNPC); + + OnSpawnNPC.FireOutput(npc, this); + TimeNextAvailable = gpGlobals.CurTime + ReuseDelay; + } +} + +public abstract class BaseNPCMaker : BaseEntity +{ + public const int SF_NPCMAKER_START_ON = 1; + public const int SF_NPCMAKER_NPCCLIP = 8; + public const int SF_NPCMAKER_FADE = 16; + public const int SF_NPCMAKER_INF_CHILD = 32; + public const int SF_NPCMAKER_NO_DROP = 64; + public const int SF_NPCMAKER_HIDEFROMPLAYER = 128; + public const int SF_NPCMAKER_ALWAYSUSERADIUS = 256; + public const int SF_NPCMAKER_NOPRELOADMODELS = 512; + + public static readonly ConVar ai_inhibit_spawners = new("ai_inhibit_spawners", "0", FCvar.Cheat); + + public static readonly new DataMap DataDesc = new(typeof(BaseNPCMaker), BaseEntity.DataDesc, [ + DEFINE.KEYFIELD(nameof(MaxNumNPCs), FieldType.Integer, "MaxNPCCount"), + DEFINE.KEYFIELD(nameof(MaxLiveChildren), FieldType.Integer, "MaxLiveChildren"), + DEFINE.KEYFIELD(nameof(SpawnFrequency), FieldType.Float, "SpawnFrequency"), + DEFINE.KEYFIELD(nameof(Disabled), FieldType.Boolean, "StartDisabled"), + + DEFINE.INPUTFUNC(FieldType.Void, "Spawn", nameof(InputSpawnNPC), (INPUTFUNCPTR)((self, data) => ((BaseNPCMaker)self).InputSpawnNPC(data))), + DEFINE.INPUTFUNC(FieldType.Void, "Enable", nameof(InputEnable), (INPUTFUNCPTR)((self, data) => ((BaseNPCMaker)self).InputEnable(data))), + DEFINE.INPUTFUNC(FieldType.Void, "Disable", nameof(InputDisable), (INPUTFUNCPTR)((self, data) => ((BaseNPCMaker)self).InputDisable(data))), + DEFINE.INPUTFUNC(FieldType.Void, "Toggle", nameof(InputToggle), (INPUTFUNCPTR)((self, data) => ((BaseNPCMaker)self).InputToggle(data))), + DEFINE.INPUTFUNC(FieldType.Integer, "SetMaxChildren", nameof(InputSetMaxChildren), (INPUTFUNCPTR)((self, data) => ((BaseNPCMaker)self).InputSetMaxChildren(data))), + DEFINE.INPUTFUNC(FieldType.Integer, "AddMaxChildren", nameof(InputAddMaxChildren), (INPUTFUNCPTR)((self, data) => ((BaseNPCMaker)self).InputAddMaxChildren(data))), + DEFINE.INPUTFUNC(FieldType.Integer, "SetMaxLiveChildren", nameof(InputSetMaxLiveChildren), (INPUTFUNCPTR)((self, data) => ((BaseNPCMaker)self).InputSetMaxLiveChildren(data))), + DEFINE.INPUTFUNC(FieldType.Float, "SetSpawnFrequency", nameof(InputSetSpawnFrequency), (INPUTFUNCPTR)((self, data) => ((BaseNPCMaker)self).InputSetSpawnFrequency(data))), + + DEFINE.OUTPUT(nameof(OnAllSpawned), "OnAllSpawned", eventFuncs), + DEFINE.OUTPUT(nameof(OnAllSpawnedDead), "OnAllSpawnedDead", eventFuncs), + DEFINE.OUTPUT(nameof(OnAllLiveChildrenDead), "OnAllLiveChildrenDead", eventFuncs), + DEFINE.OUTPUT(nameof(OnSpawnNPC), "OnSpawnNPC", eventFuncs), + + DEFINE.KEYFIELD(nameof(IgnoreEntName), FieldType.String, "IgnoreEntity"), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public int MaxNumNPCs; + public float SpawnFrequency; + + public readonly OutputEHANDLE OnSpawnNPC = new(); + public OutputEvent OnAllSpawned = new(); + public OutputEvent OnAllSpawnedDead = new(); + public OutputEvent OnAllLiveChildrenDead = new(); + + public int LiveChildren; + public int MaxLiveChildren; + + public bool Disabled; + + public EHANDLE IgnoreEntity = new(); + public string? IgnoreEntName; + + public override void Spawn() { + SetSolid(SolidType.None); + LiveChildren = 0; + Precache(); + + if ((SpawnFlags & SF_NPCMAKER_INF_CHILD) != 0) + SpawnFlags |= SF_NPCMAKER_FADE; + + if (!Disabled) { + SetThink(MakerThink); + SetNextThink(gpGlobals.CurTime + 0.1f); + } + else + SetThink(SUB_DoNothing); + } + + public override EntityCapabilities ObjectCaps() => base.ObjectCaps() & ~EntityCapabilities.AcrossTransition; + + public bool HumanHullFits(in Vector3 location) { + Util.TraceHull(location, location + new Vector3(0, 0, 1), NAI_Hull.Mins(AI_HullType.Human), NAI_Hull.Maxs(AI_HullType.Human), Mask.NPCSolid, IgnoreEntity.Get(), Source.CollisionGroup.None, out Trace tr); + + if (tr.Fraction == 1.0f) + return true; + + return false; + } + + public bool CanMakeNPC(bool ignoreSolidEntities = false) { + if (ai_inhibit_spawners.GetBool()) + return false; + + if (MaxLiveChildren > 0 && LiveChildren >= MaxLiveChildren) + return false; + + if (IgnoreEntName != null) + IgnoreEntity.Set(gEntList.FindEntityByName(null, IgnoreEntName)); + + Vector3 mins = GetAbsOrigin() - new Vector3(34, 34, 0); + Vector3 maxs = GetAbsOrigin() + new Vector3(34, 34, 0); + maxs.Z = GetAbsOrigin().Z; + + if (!ignoreSolidEntities) { + BaseEntity[] list = new BaseEntity[128]; + + int count = Util.EntitiesInBox(list, mins, maxs, EntityFlags.Client | EntityFlags.NPC); + if (count != 0) { + for (int i = 0; i < count; i++) { + if (list[i] == null) + continue; + + if ((list[i].GetSolidFlags() & SolidFlags.NotSolid) == 0) { + Util.TraceHull(GetAbsOrigin() + new Vector3(0, 0, 2), GetAbsOrigin() - new Vector3(0, 0, 8192), NAI_Hull.Mins(AI_HullType.Human), NAI_Hull.Maxs(AI_HullType.Human), Mask.NPCSolid, IgnoreEntity.Get(), Source.CollisionGroup.None, out Trace tr); + + if (!HumanHullFits(tr.EndPos + new Vector3(0, 0, 1))) + return false; + } + } + } + } + + if (HasSpawnFlags(SF_NPCMAKER_HIDEFROMPLAYER)) { + for (int i = 1; i <= gpGlobals.MaxClients; i++) { + BasePlayer? player = Util.PlayerByIndex(i); + if (player != null) { + if (player.FInViewCone(GetAbsOrigin()) && player.FVisible(GetAbsOrigin())) { + if ((player.GetFlags() & EntityFlags.NoTarget) == 0) + return false; + DevMsg(2, $"Spawner {GetEntityName()} spawning even though seen due to notarget\n"); + } + } + } + } + + return true; + } + + public override void DeathNotice(BaseEntity victim) { + LiveChildren--; + + AssertMsg(LiveChildren >= 0, "npc_maker receiving child death notice but thinks has no children\n"); + + if (LiveChildren <= 0) { + OnAllLiveChildrenDead.FireOutput(this, this); + + if ((SpawnFlags & SF_NPCMAKER_INF_CHILD) == 0 && IsDepleted()) + OnAllSpawnedDead.FireOutput(this, this); + } + } + + public abstract void MakeNPC(); + + public virtual void ChildPreSpawn(AI_BaseNPC child) { } + + public virtual void ChildPostSpawn(AI_BaseNPC child) { + bool found = true; + while (found) { + Util.TraceHull(child.GetAbsOrigin(), child.GetAbsOrigin(), child.WorldAlignMins(), child.WorldAlignMaxs(), Mask.NPCSolid, child, Source.CollisionGroup.None, out Trace tr); + if (tr.Fraction != 1.0f && tr.Ent != null) { + if (FClassnameIs(tr.Ent, "prop_physics")) { + tr.Ent.AddSolidFlags(SolidFlags.NotSolid); + Util.RemoveImmediate(tr.Ent); + continue; + } + } + + found = false; + } + if (IgnoreEntity.Get() != null) + child.SetOwnerEntity(IgnoreEntity.Get()); + } + + public void MakerThink() { + SetNextThink(gpGlobals.CurTime + SpawnFrequency); + + MakeNPC(); + } + + public virtual bool IsDepleted() { + if ((SpawnFlags & SF_NPCMAKER_INF_CHILD) != 0 || MaxNumNPCs > 0) + return false; + + return true; + } + + public void Toggle() { + if (Disabled) + Enable(); + else + Disable(); + } + + public virtual void Enable() { + if (IsDepleted()) + return; + + Disabled = false; + SetThink(MakerThink); + SetNextThink(gpGlobals.CurTime); + } + + public virtual void Disable() { + Disabled = true; + SetThink(null); + } + + public void InputSpawnNPC(InputData inputdata) { + if (!IsDepleted()) + MakeNPC(); + } + + public void InputEnable(InputData inputdata) => Enable(); + public void InputDisable(InputData inputdata) => Disable(); + public void InputToggle(InputData inputdata) => Toggle(); + public void InputSetMaxChildren(InputData inputdata) => MaxNumNPCs = inputdata.Value.Int(); + public void InputAddMaxChildren(InputData inputdata) => MaxNumNPCs += inputdata.Value.Int(); + public void InputSetMaxLiveChildren(InputData inputdata) => MaxLiveChildren = inputdata.Value.Int(); + public void InputSetSpawnFrequency(InputData inputdata) => SpawnFrequency = inputdata.Value.Float(); +} + +[LinkEntityToClass("npc_maker")] +public class NPCMaker : BaseNPCMaker +{ + public static readonly new DataMap DataDesc = new(typeof(NPCMaker), BaseNPCMaker.DataDesc, [ + DEFINE.KEYFIELD(nameof(NPCClassname), FieldType.String, "NPCType"), + DEFINE.KEYFIELD(nameof(ChildTargetName), FieldType.String, "NPCTargetname"), + DEFINE.KEYFIELD(nameof(SquadName), FieldType.String, "NPCSquadName"), + DEFINE.KEYFIELD(nameof(SpawnEquipment), FieldType.String, "additionalequipment"), + DEFINE.KEYFIELD(nameof(HintGroup), FieldType.String, "NPCHintGroup"), + DEFINE.KEYFIELD(nameof(RelationshipString), FieldType.String, "Relationship"), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + public string? NPCClassname; + public string? SquadName; + public string? HintGroup; + public string? SpawnEquipment; + public string? RelationshipString; + public string? ChildTargetName; + + public override void Precache() { + base.Precache(); + + if (string.IsNullOrEmpty(NPCClassname)) + Warning($"npc_maker {GetEntityName()} has no specified NPC-to-spawn classname.\n"); + else + Util.PrecacheOther(NPCClassname); + } + + public override void MakeNPC() { + if (!CanMakeNPC()) + return; + + AI_BaseNPC? ent = (AI_BaseNPC?)CreateEntityByName(NPCClassname); + + if (ent == null) { + Warning("NULL Ent in NPCMaker!\n"); + return; + } + + ent.RelationshipString = RelationshipString; + + OnSpawnNPC.Set(ent.GetRefEHandle(), ent, this); + + ent.SetAbsOrigin(GetAbsOrigin()); + + QAngle angles = GetAbsAngles(); + angles.X = 0.0f; + angles.Z = 0.0f; + ent.SetAbsAngles(angles); + + ent.AddSpawnFlags(SF_NPC_FALL_TO_GROUND); + + if ((SpawnFlags & SF_NPCMAKER_FADE) != 0) + ent.AddSpawnFlags(SF_NPC_FADE_CORPSE); + + ent.SpawnEquipment = SpawnEquipment; + ent.SquadName = SquadName; + ent.HintGroup = HintGroup; + + ChildPreSpawn(ent); + + Util.DispatchSpawn(ent); + ent.SetOwnerEntity(this); + ent.Activate(); + + if (ChildTargetName != null) + ent.SetName(ChildTargetName); + + ChildPostSpawn(ent); + + LiveChildren++; + + if ((SpawnFlags & SF_NPCMAKER_INF_CHILD) == 0) { + MaxNumNPCs--; + + if (IsDepleted()) { + OnAllSpawned.FireOutput(this, this); + + SetThink(null); + FnUse = null; + } + } + } +} + +[LinkEntityToClass("npc_template_maker")] +public class TemplateNPCMaker : BaseNPCMaker +{ + public enum ThreeStateYesNo + { + Yes = 0, + No, + DontCare, + } + + public enum ThreeStateDist + { + Nearest = 0, + Farthest, + DontCare, + } + + const int MAX_DESTINATION_ENTS = 100; + + public static readonly new DataMap DataDesc = new(typeof(TemplateNPCMaker), BaseNPCMaker.DataDesc, [ + DEFINE.KEYFIELD(nameof(TemplateName), FieldType.String, "TemplateName"), + DEFINE.KEYFIELD(nameof(Radius), FieldType.Float, "radius"), + DEFINE.KEYFIELD(nameof(DestinationGroup), FieldType.String, "DestinationGroup"), + DEFINE.KEYFIELD(nameof(CriterionVisibility), FieldType.Integer, "CriterionVisibility"), + DEFINE.KEYFIELD(nameof(CriterionDistance), FieldType.Integer, "CriterionDistance"), + DEFINE.KEYFIELD(nameof(MinSpawnDistance), FieldType.Integer, "MinSpawnDistance"), + + DEFINE.INPUTFUNC(FieldType.Void, "SpawnNPCInRadius", nameof(InputSpawnInRadius), (INPUTFUNCPTR)((self, data) => ((TemplateNPCMaker)self).InputSpawnInRadius(data))), + DEFINE.INPUTFUNC(FieldType.Void, "SpawnNPCInLine", nameof(InputSpawnInLine), (INPUTFUNCPTR)((self, data) => ((TemplateNPCMaker)self).InputSpawnInLine(data))), + DEFINE.INPUTFUNC(FieldType.Integer, "SpawnMultiple", nameof(InputSpawnMultiple), (INPUTFUNCPTR)((self, data) => ((TemplateNPCMaker)self).InputSpawnMultiple(data))), + DEFINE.INPUTFUNC(FieldType.String, "ChangeDestinationGroup", nameof(InputChangeDestinationGroup), (INPUTFUNCPTR)((self, data) => ((TemplateNPCMaker)self).InputChangeDestinationGroup(data))), + DEFINE.INPUTFUNC(FieldType.Integer, "SetMinimumSpawnDistance", nameof(InputSetMinimumSpawnDistance), (INPUTFUNCPTR)((self, data) => ((TemplateNPCMaker)self).InputSetMinimumSpawnDistance(data))), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + protected float Radius; + + protected string? TemplateName; + protected Memory TemplateData; + protected string? DestinationGroup; + + protected int MinSpawnDistance; + + ThreeStateYesNo CriterionVisibility; + ThreeStateDist CriterionDistance; + + protected virtual void PrecacheTemplateEntity(BaseEntity entity) => entity.Precache(); + + public override void Precache() { + base.Precache(); + + if (TemplateData.IsEmpty) { + if (TemplateName == null) { + Warning($"npc_template_maker {GetEntityName()} has no template NPC!\n"); + Util.Remove(this); + return; + } + else { + TemplateData = Templates.FindByTargetName(TemplateName); + if (TemplateData.IsEmpty) { + DevWarning($"npc_template_maker {GetEntityName()}: template NPC {TemplateName} not found!\n"); + Util.Remove(this); + return; + } + } + } + + Assert(!TemplateData.IsEmpty); + + if (!TemplateData.IsEmpty) { + ParseEntity(out BaseEntity? entity, TemplateData, null); + if (entity != null) { + PrecacheTemplateEntity(entity); + Util.RemoveImmediate(entity); + } + } + } + + public virtual NPCSpawnDestination? FindSpawnDestination() { + NPCSpawnDestination[] destinations = new NPCSpawnDestination[MAX_DESTINATION_ENTS]; + BaseEntity? ent; + BasePlayer? player = AI_GetClosestPlayer(); + int count = 0; + + if (player == null) + return null; + + ent = gEntList.FindEntityByName(null, DestinationGroup); + + if (ent == null) { + DevWarning($"Template NPC Spawner ({GetDebugName()}) doesn't have any spawn destinations!\n"); + return null; + } + + while (ent != null) { + if (ent is NPCSpawnDestination destination && destination.IsAvailable()) { + bool valid = true; + Vector3 test = destination.GetAbsOrigin(); + + if (CriterionVisibility != ThreeStateYesNo.DontCare) { + Vector3 topOfHull = NAI_Hull.Maxs(AI_HullType.Human); + topOfHull.X = 0; + topOfHull.Y = 0; + bool visible = player.FVisible(test) || player.FVisible(test + topOfHull); + + if (CriterionVisibility == ThreeStateYesNo.Yes) { + if (!visible) + valid = false; + } + else { + if (visible) { + if ((player.GetFlags() & EntityFlags.NoTarget) == 0) + valid = false; + else + DevMsg(2, $"Spawner {GetEntityName()} spawning even though seen due to notarget\n"); + } + } + } + + if (valid) { + destinations[count] = destination; + count++; + } + } + + ent = gEntList.FindEntityByName(ent, DestinationGroup); + } + + if (count < 1) + return null; + + if (CriterionDistance == ThreeStateDist.DontCare) { + for (int i = 0; i < 5; i++) { + NPCSpawnDestination randomDest = destinations[random.RandomInt(0, count - 1)]; + + if (HumanHullFits(randomDest.GetAbsOrigin())) + return randomDest; + } + + return null; + } + else { + if (CriterionDistance == ThreeStateDist.Nearest) { + float nearest = float.MaxValue; + NPCSpawnDestination? nearestDest = null; + + for (int i = 0; i < count; i++) { + Vector3 test = destinations[i].GetAbsOrigin(); + + float dist = (test - player.GetAbsOrigin()).Length(); + + if (MinSpawnDistance != 0 && MinSpawnDistance > dist) + continue; + + if (dist < nearest && HumanHullFits(test)) { + nearest = dist; + nearestDest = destinations[i]; + } + } + + return nearestDest; + } + else { + float farthest = 0; + NPCSpawnDestination? farthestDest = null; + + for (int i = 0; i < count; i++) { + Vector3 test = destinations[i].GetAbsOrigin(); + + float dist = (test - player.GetAbsOrigin()).Length(); + + if (MinSpawnDistance != 0 && MinSpawnDistance > dist) + continue; + + if (dist > farthest && HumanHullFits(test)) { + farthest = dist; + farthestDest = destinations[i]; + } + } + + return farthestDest; + } + } + } + + public override void MakeNPC() { + if (Radius != 0 && HasSpawnFlags(SF_NPCMAKER_ALWAYSUSERADIUS)) { + MakeNPCInRadius(); + return; + } + + if (!CanMakeNPC(DestinationGroup != null)) + return; + + NPCSpawnDestination? destination = null; + if (DestinationGroup != null) { + destination = FindSpawnDestination(); + if (destination == null) { + DevMsg(2, $"{GetClassname()} '{GetEntityName()}' failed to find a valid spawnpoint in destination group: '{DestinationGroup}'\n"); + return; + } + } + + AI_BaseNPC? ent = null; + ParseEntity(out BaseEntity? entity, TemplateData, null); + if (entity != null) + ent = (AI_BaseNPC)entity; + + if (ent == null) { + Warning("NULL Ent in NPCMaker!\n"); + return; + } + + if (destination != null) { + ent.SetAbsOrigin(destination.GetAbsOrigin()); + + QAngle angles = destination.GetAbsAngles(); + angles.X = 0.0f; + angles.Z = 0.0f; + ent.SetAbsAngles(angles); + + destination.OnSpawnedNPC(ent); + } + else { + ent.SetAbsOrigin(GetAbsOrigin()); + + QAngle angles = GetAbsAngles(); + angles.X = 0.0f; + angles.Z = 0.0f; + ent.SetAbsAngles(angles); + } + + OnSpawnNPC.Set(entity!.GetRefEHandle(), entity, this); + + if ((SpawnFlags & SF_NPCMAKER_FADE) != 0) + ent.AddSpawnFlags(SF_NPC_FADE_CORPSE); + + ent.RemoveSpawnFlags(SF_NPC_TEMPLATE); + + if ((SpawnFlags & SF_NPCMAKER_NO_DROP) == 0) + ent.RemoveSpawnFlags(SF_NPC_FALL_TO_GROUND); + + ChildPreSpawn(ent); + + Util.DispatchSpawn(ent); + ent.SetOwnerEntity(this); + ent.Activate(); + + ChildPostSpawn(ent); + + LiveChildren++; + + if ((SpawnFlags & SF_NPCMAKER_INF_CHILD) == 0) { + MaxNumNPCs--; + + if (IsDepleted()) { + OnAllSpawned.FireOutput(this, this); + + SetThink(null); + FnUse = null; + } + } + } + + public void MakeNPCInLine() { + if (!CanMakeNPC(true)) + return; + + AI_BaseNPC? ent = null; + ParseEntity(out BaseEntity? entity, TemplateData, null); + if (entity != null) + ent = (AI_BaseNPC)entity; + + if (ent == null) { + Warning("NULL Ent in NPCMaker!\n"); + return; + } + + OnSpawnNPC.Set(entity!.GetRefEHandle(), entity, this); + + PlaceNPCInLine(ent); + + ent.AddSpawnFlags(SF_NPC_FALL_TO_GROUND); + + ent.RemoveSpawnFlags(SF_NPC_TEMPLATE); + + ChildPreSpawn(ent); + + Util.DispatchSpawn(ent); + ent.SetOwnerEntity(this); + ent.Activate(); + + ChildPostSpawn(ent); + + LiveChildren++; + + if ((SpawnFlags & SF_NPCMAKER_INF_CHILD) == 0) { + MaxNumNPCs--; + + if (IsDepleted()) { + OnAllSpawned.FireOutput(this, this); + + SetThink(null); + FnUse = null; + } + } + } + + protected bool PlaceNPCInLine(AI_BaseNPC npc) { + Vector3 place; + + GetVectors(out Vector3 line, out _, out _); + + line *= -1; + + Util.TraceLine(GetAbsOrigin(), GetAbsOrigin() - new Vector3(0, 0, 8192), Mask.Shot, npc, Source.CollisionGroup.None, out Trace tr); + place = tr.EndPos; + float stepSize = npc.GetHullWidth(); + + for (int i = 0; i < 10; i++) { + Util.TraceHull(place, place + new Vector3(0, 0, 10), npc.GetHullMins(), npc.GetHullMaxs(), Mask.Shot, npc, Source.CollisionGroup.None, out tr); + + if (tr.Fraction == 1.0f) { + npc.SetAbsOrigin(tr.EndPos); + return true; + } + + place += line * stepSize; + } + + DevMsg("**Failed to place NPC in line!\n"); + return false; + } + + public void MakeNPCInRadius() { + if (!CanMakeNPC(true)) + return; + + AI_BaseNPC? ent = null; + ParseEntity(out BaseEntity? entity, TemplateData, null); + if (entity != null) + ent = (AI_BaseNPC)entity; + + if (ent == null) { + Warning("NULL Ent in NPCMaker!\n"); + return; + } + + if (!PlaceNPCInRadius(ent)) { + Util.RemoveImmediate(ent); + return; + } + + OnSpawnNPC.Set(entity!.GetRefEHandle(), entity, this); + + ent.AddSpawnFlags(SF_NPC_FALL_TO_GROUND); + + ent.RemoveSpawnFlags(SF_NPC_TEMPLATE); + + ChildPreSpawn(ent); + + Util.DispatchSpawn(ent); + ent.SetOwnerEntity(this); + ent.Activate(); + + ChildPostSpawn(ent); + + LiveChildren++; + + if ((SpawnFlags & SF_NPCMAKER_INF_CHILD) == 0) { + MaxNumNPCs--; + + if (IsDepleted()) { + OnAllSpawned.FireOutput(this, this); + + SetThink(null); + FnUse = null; + } + } + } + + protected bool PlaceNPCInRadius(AI_BaseNPC npc) { + if (AI_BaseNPC.FindSpotForNPCInRadius(out Vector3 pos, GetAbsOrigin(), npc, Radius)) { + npc.SetAbsOrigin(pos); + return true; + } + + DevMsg("**Failed to place NPC in radius!\n"); + return false; + } + + public virtual void MakeMultipleNPCS(int npcs) { + bool inRadius = DestinationGroup == null && Radius > 0.1f; + while (npcs-- != 0) { + if (!inRadius) + MakeNPC(); + else + MakeNPCInRadius(); + } + } + + public void InputSpawnInRadius(InputData inputdata) => MakeNPCInRadius(); + public void InputSpawnInLine(InputData inputdata) => MakeNPCInLine(); + public void InputSpawnMultiple(InputData inputdata) => MakeMultipleNPCS(inputdata.Value.Int()); + public void InputChangeDestinationGroup(InputData inputdata) => DestinationGroup = inputdata.Value.StringID(); + public void InputSetMinimumSpawnDistance(InputData inputdata) => MinSpawnDistance = inputdata.Value.Int(); +} diff --git a/Game.Server/TemplateEntities.cs b/Game.Server/TemplateEntities.cs index 10aac5cba..411c9f179 100644 --- a/Game.Server/TemplateEntities.cs +++ b/Game.Server/TemplateEntities.cs @@ -80,4 +80,15 @@ public static Memory FindByIndex(int index){ return g_Templates[index].iszMapData; } + + public static Memory FindByTargetName(ReadOnlySpan name) { + int count = g_Templates.Count; + for (int i = 0; i < count; i++) { + TemplateEntityData template = g_Templates[i]; + if (name.Equals(template.Name, StringComparison.OrdinalIgnoreCase)) + return FindByIndex(i); + } + + return default; + } } diff --git a/Game.Server/Util.cs b/Game.Server/Util.cs index 327ba9f7c..2bdf8fb3f 100644 --- a/Game.Server/Util.cs +++ b/Game.Server/Util.cs @@ -373,6 +373,16 @@ public static void SetSize(BaseEntity ent, in Vector3 min, in Vector3 max) { SetMinMaxSize(ent, min, max); } + public static int EntitiesInBox(Span list, in Vector3 mins, in Vector3 maxs, EntityFlags flagMask) { + FlaggedEntitiesEnum boxEnum = new(list, flagMask); + return EntitiesInBox(mins, maxs, ref boxEnum); + } + + public static int EntitiesInBox(in Vector3 mins, in Vector3 maxs, scoped ref FlaggedEntitiesEnum enumerator) { + partition.EnumerateElementsInBox((SpatialPartitionListMask_t)PartitionListMask.EngineNonStaticEdicts, mins, maxs, false, ref enumerator); + return enumerator.GetCount(); + } + public static int EntitiesInSphere(Span list, in Vector3 center, float radius, EntityFlags flagMask) { FlaggedEntitiesEnum sphereEnum = new(list, flagMask); return EntitiesInSphere(center, radius, ref sphereEnum); From afe3c868694b10d017f89da81b41fb421ad0a22a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:16:56 +0300 Subject: [PATCH 65/73] Report inaccessible field accessor types as compile errors --- .../NetworkVarGenerator.FieldAccessors.cs | 90 +++++++++++++------ .../NetworkVarGenerator.PredictedFields.cs | 2 +- .../NetworkVarGenerator.cs | 8 ++ 3 files changed, 73 insertions(+), 27 deletions(-) diff --git a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs index 0721990fd..e22287af0 100644 --- a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs +++ b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs @@ -101,29 +101,41 @@ private static bool IsInvocationNamed(SyntaxNode node, HashSet names) { return null; Compilation compilation = ctx.SemanticModel.Compilation; + var failure = new AccessFailure(); + FieldAccessorModel? model; if (container.Name == "DEFINE") { if (method.Parameters.Length == 0 || method.Parameters[0].Name != "name") return null; INamedTypeSymbol? declaring = FindDataMapField(owner, expression)?.ContainingType ?? FindNetworkVarProperty(owner, expression)?.ContainingType; - return declaring == null ? null : BuildScalar(compilation, declaring, expression, null); + model = declaring == null ? null : BuildScalar(compilation, declaring, expression, null, failure); } - - switch (method.Name) { - case "OF": - return BuildScalar(compilation, owner, expression, null); - case "OF_NAMED": - if (args.Count < 2 || !(ctx.SemanticModel.GetConstantValue(args[1].Expression, ct).Value is string name)) - return null; - return BuildScalar(compilation, owner, expression, name); - case "OF_LIST": - return BuildArray(compilation, owner, expression, true); - default: - return BuildArray(compilation, owner, expression, false); + else { + switch (method.Name) { + case "OF": + model = BuildScalar(compilation, owner, expression, null, failure); + break; + case "OF_NAMED": + if (args.Count < 2 || !(ctx.SemanticModel.GetConstantValue(args[1].Expression, ct).Value is string name)) + return null; + model = BuildScalar(compilation, owner, expression, name, failure); + break; + case "OF_LIST": + model = BuildArray(compilation, owner, expression, true, failure); + break; + default: + model = BuildArray(compilation, owner, expression, false, failure); + break; + } } + + if (model == null && failure.Type != null) + return FieldAccessorModel.Inaccessible(args[0].Expression.GetLocation(), expression, owner.ToDisplayString(), failure.Type.ToDisplayString()); + + return model; } - private static FieldAccessorModel? BuildScalar(Compilation compilation, INamedTypeSymbol owner, string expression, string? name) { - ResolvedPath? path = Resolve(compilation, owner, expression); + private static FieldAccessorModel? BuildScalar(Compilation compilation, INamedTypeSymbol owner, string expression, string? name, AccessFailure failure) { + ResolvedPath? path = Resolve(compilation, owner, expression, failure); if (path == null) return null; @@ -153,14 +165,16 @@ private static bool IsInvocationNamed(SyntaxNode node, HashSet names) { return new FieldAccessorModel("S|" + ownerDisplay + "|" + expression + "|" + (name ?? "\0"), registration, body.ToString(), string.Join("\n", conversions)); } - private static FieldAccessorModel? BuildArray(Compilation compilation, INamedTypeSymbol owner, string expression, bool isList) { - ResolvedPath? path = Resolve(compilation, owner, expression); + private static FieldAccessorModel? BuildArray(Compilation compilation, INamedTypeSymbol owner, string expression, bool isList, AccessFailure failure) { + ResolvedPath? path = Resolve(compilation, owner, expression, failure); if (path == null) return null; ContainerKind kind = GetContainer(compilation, path.Type, out ITypeSymbol? element, out int length); - if (kind == ContainerKind.None || element == null || !IsAccessible(compilation, element)) + if (kind == ContainerKind.None || element == null) return null; + if (!IsAccessible(compilation, element)) + return failure.Fail(element); bool listFlag = false; if (kind != ContainerKind.InlineArray) { @@ -209,9 +223,9 @@ private static bool IsInvocationNamed(SyntaxNode node, HashSet names) { return new FieldAccessorModel("A|" + ownerDisplay + "|" + expression, registration, body.ToString(), string.Join("\n", conversions)); } - private static ResolvedPath? Resolve(Compilation compilation, INamedTypeSymbol owner, string expression) { + private static ResolvedPath? Resolve(Compilation compilation, INamedTypeSymbol owner, string expression, AccessFailure failure) { if (!IsAccessible(compilation, owner)) - return null; + return failure.Fail(owner); List? segments = Tokenize(expression); if (segments == null || segments.Count == 0) @@ -228,8 +242,10 @@ private static bool IsInvocationNamed(SyntaxNode node, HashSet names) { Segment segment = segments[i]; if (segment.Name == null) { ContainerKind kind = GetContainer(compilation, current, out ITypeSymbol? element, out _); - if (kind == ContainerKind.None || element == null || !IsAccessible(compilation, element)) + if (kind == ContainerKind.None || element == null) return null; + if (!IsAccessible(compilation, element)) + return failure.Fail(element); path.Expression = IndexExpression(kind, current, element, path.Expression, segment.Index.ToString(CultureInfo.InvariantCulture)); path.Parts.Add(NamePart.ConstantIndex(segment.Index)); @@ -238,7 +254,7 @@ private static bool IsInvocationNamed(SyntaxNode node, HashSet names) { continue; } - ITypeSymbol? next = ApplyMember(compilation, path, current, segment.Name, i == segments.Count - 1); + ITypeSymbol? next = ApplyMember(compilation, path, current, segment.Name, i == segments.Count - 1, failure); if (next == null) return null; current = next; @@ -248,7 +264,7 @@ private static bool IsInvocationNamed(SyntaxNode node, HashSet names) { return path; } - private static ITypeSymbol? ApplyMember(Compilation compilation, ResolvedPath path, ITypeSymbol current, string name, bool last) { + private static ITypeSymbol? ApplyMember(Compilation compilation, ResolvedPath path, ITypeSymbol current, string name, bool last, AccessFailure failure) { ISymbol? member = FindMember(current, name) ?? FindNetworkVarProperty(current, name); string fieldName; ITypeSymbol memberType; @@ -273,13 +289,15 @@ private static bool IsInvocationNamed(SyntaxNode node, HashSet names) { return null; if (!IsAccessible(compilation, memberType)) - return null; + return failure.Fail(memberType); if (direct) path.Expression = path.Expression + "." + Identifier(fieldName); else { - if (declaring.IsGenericType || !IsAccessible(compilation, declaring)) + if (declaring.IsGenericType) return null; + if (!IsAccessible(compilation, declaring)) + return failure.Fail(declaring); string accessorName = "__F" + path.Accessors.Count.ToString(CultureInfo.InvariantCulture); string byRef = declaring.IsValueType ? "ref " : ""; @@ -539,6 +557,10 @@ private static void EmitFieldAccessors(SourceProductionContext spc, ImmutableArr foreach (FieldAccessorModel? model in models) { if (model == null) continue; + if (model.ErrorLocation != null) { + spc.ReportDiagnostic(Diagnostic.Create(InaccessibleFieldType, model.ErrorLocation, model.ErrorArgs)); + continue; + } if (!unique.ContainsKey(model.Key)) unique.Add(model.Key, model); AddLines(conversions, model.Conversions); @@ -626,6 +648,17 @@ private sealed class NamePart public static NamePart SymbolicIndex() => new NamePart { IsIndex = true, Symbolic = true }; } + private sealed class AccessFailure + { + public ITypeSymbol? Type; + + public T? Fail(ITypeSymbol type) where T : class { + if (Type == null) + Type = type; + return null; + } + } + private sealed class ResolvedPath { public string Expression = ""; @@ -645,13 +678,18 @@ public FieldAccessorModel(string key, string registration, string body, string c Conversions = conversions; } + public static FieldAccessorModel Inaccessible(Location location, string member, string owner, string type) + => new FieldAccessorModel("E|" + owner + "|" + member, "", "", "") { ErrorLocation = location, ErrorArgs = new object[] { member, owner, type } }; + public string Key { get; } public string Registration { get; } public string Body { get; } public string Conversions { get; } + public Location? ErrorLocation { get; private set; } + public object[]? ErrorArgs { get; private set; } public bool Equals(FieldAccessorModel? other) - => other != null && Key == other.Key && Registration == other.Registration && Body == other.Body && Conversions == other.Conversions; + => other != null && Key == other.Key && Registration == other.Registration && Body == other.Body && Conversions == other.Conversions && Equals(ErrorLocation, other.ErrorLocation); public override bool Equals(object? obj) => Equals(obj as FieldAccessorModel); public override int GetHashCode() => Key.GetHashCode(); diff --git a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.PredictedFields.cs b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.PredictedFields.cs index 8197cec8d..3afcefd89 100644 --- a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.PredictedFields.cs +++ b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.PredictedFields.cs @@ -102,7 +102,7 @@ private static string BuildPredictionEntry(GeneratorSyntaxContext ctx, Expressio if (declaring == null) return "X"; - ResolvedPath? path = Resolve(compilation, declaring, name); + ResolvedPath? path = Resolve(compilation, declaring, name, new AccessFailure()); if (path == null) return "X"; diff --git a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.cs b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.cs index 04e56beb2..cae8680db 100644 --- a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.cs +++ b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.cs @@ -38,6 +38,14 @@ public sealed partial class NetworkVarGenerator : IIncrementalGenerator defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); + private static readonly DiagnosticDescriptor InaccessibleFieldType = new DiagnosticDescriptor( + id: "NETVAR004", + title: "Field accessor cannot reference an inaccessible type", + messageFormat: "Field '{0}' on '{1}' involves type '{2}', which is not accessible outside its declaring type; generated field accessors cannot reference it", + category: "NetworkVars", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true); + public void Initialize(IncrementalGeneratorInitializationContext context) { context.RegisterPostInitializationOutput(ctx => ctx.AddSource("NetworkVarAttribute.g.cs", SourceText.From(AttributeSource, Encoding.UTF8))); From c4b46e92a62befc5b2e8795668d94661a63a9a61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:19:26 +0300 Subject: [PATCH 66/73] Fix keyfields using private enum types --- Game.Server/AI_GoalEntity.cs | 4 ++-- Game.Server/LogicEntities.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Game.Server/AI_GoalEntity.cs b/Game.Server/AI_GoalEntity.cs index 0023dda34..1fa3326e9 100644 --- a/Game.Server/AI_GoalEntity.cs +++ b/Game.Server/AI_GoalEntity.cs @@ -10,14 +10,14 @@ namespace Game.Server; public class AI_GoalEntity : BaseEntity, IEntityListener { [Flags] - enum GoalFlags + public enum GoalFlags { Active = 0x01, ResolvedName = 0x02, Dormant = 0x04, } - enum SearchType + public enum SearchType { EntName, ClassName, diff --git a/Game.Server/LogicEntities.cs b/Game.Server/LogicEntities.cs index c4de862bd..fbc1cf883 100644 --- a/Game.Server/LogicEntities.cs +++ b/Game.Server/LogicEntities.cs @@ -1737,7 +1737,7 @@ public class LogicBranchList : LogicalEntity { const int MAX_LOGIC_BRANCH_NAMES = 16; - enum LogicBranchListenerLastState + public enum LogicBranchListenerLastState { NotInit = 0, AllTrue, From 184679dae062129aaaac66c66b5348a2b9d24307 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:28:17 +0300 Subject: [PATCH 67/73] Port instanced scenes for actor expressions --- Game.Server/AI_BaseActor.cs | 13 ++- Game.Server/SceneEntity.cs | 195 +++++++++++++++++++++++++++++++++++- 2 files changed, 203 insertions(+), 5 deletions(-) diff --git a/Game.Server/AI_BaseActor.cs b/Game.Server/AI_BaseActor.cs index 5be302bfe..2010f40a7 100644 --- a/Game.Server/AI_BaseActor.cs +++ b/Game.Server/AI_BaseActor.cs @@ -686,18 +686,25 @@ public float SetExpression(string? expressionScene) { return 0; if (ExpressionSceneEnt.Get() != null) - throw new NotImplementedException(); + StopScriptedScene(this, ExpressionSceneEnt); if (ai_debug_expressions.GetInt() != 0) Msg($"{GetClassname()} ({GetDebugName()}) set expression to: {expressionScene}\n"); ExpressionScene = null; - throw new NotImplementedException(); + float duration = InstancedScriptedScene(this, expressionScene, ref ExpressionSceneEnt, 0.0f, true); + + ExpressionEndTime = gpGlobals.CurTime + duration; + + if (ExpressionSceneEnt.Get() != null) + ExpressionScene = expressionScene; + + return duration; } public void ClearExpression() { if (ExpressionSceneEnt.Get() != null) - throw new NotImplementedException(); + StopScriptedScene(this, ExpressionSceneEnt); ExpressionScene = null; } diff --git a/Game.Server/SceneEntity.cs b/Game.Server/SceneEntity.cs index 359a3a9df..f63687dac 100644 --- a/Game.Server/SceneEntity.cs +++ b/Game.Server/SceneEntity.cs @@ -98,6 +98,42 @@ public static void PrecacheInstancedScene(ReadOnlySpan scene) { g_pStringTableClientSideChoreoScenes!.AddString(true, scene); } + public static float InstancedScriptedScene(BaseFlex? actor, ReadOnlySpan sceneName, ref EHANDLE sceneEnt, float postDelay = 0.0f, bool isBackground = false, bool multiplayer = false, IRecipientFilter? filter = null) { + InstancedSceneEntity scene = (InstancedSceneEntity)BaseEntity.CreateNoSpawn("instanced_scripted_scene", vec3_origin, vec3_angle)!; + + if (actor != null) { + Span instanceFilename = stackalloc char[ChoreoScene.MAX_SCENE_FILENAME]; + soundemitterbase.GenderExpandString(actor.GetModelName(), sceneName, instanceFilename); + scene.SceneFile = new string(instanceFilename.SliceNullTerminatedString()); + } + else + scene.SceneFile = new string(sceneName); + + scene.Owner.Set(actor); + scene.HadOwner = actor != null; + scene.Multiplayer = multiplayer; + scene.SetPostSpeakDelay(postDelay); + Util.DispatchSpawn(scene); + scene.Activate(); + scene.IsBackgroundScene = isBackground; + + scene.SetBackground(isBackground); + scene.SetRecipientFilter(filter); + + scene.StartPlayback(); + + sceneEnt.Set(scene); + + return scene.EstimateLength(); + } + + public static void StopScriptedScene(BaseFlex? actor, EHANDLE sceneEnt) { + if (sceneEnt.Get() is SceneEntity scene) { + Scene_Printf($"{scene.SceneFile} : stop scripted scene\n"); + scene.CancelPlayback(); + } + } + public static void RemoveActorFromScriptedScenes(BaseFlex actor, bool instancedscenesonly, bool nonidlescenesonly = false, ReadOnlySpan thisSceneOnly = default) => GetSceneManager()!.RemoveActorFromScenes(actor, instancedscenesonly, nonidlescenesonly, thisSceneOnly); public static void RemoveAllScenesInvolvingActor(BaseFlex actor) => GetSceneManager()!.RemoveScenesInvolvingActor(actor); public static void PauseActorsScriptedScenes(BaseFlex actor, bool instancedscenesonly) => GetSceneManager()!.PauseActorsScenes(actor, instancedscenesonly); @@ -224,9 +260,164 @@ public class SceneListManager : LogicalEntity public void SceneStarted(BaseEntity sceneOrManager) => throw new NotImplementedException(); } +[LinkEntityToClass("instanced_scripted_scene")] public class InstancedSceneEntity : SceneEntity { public EHANDLE Owner = new(); + public bool HadOwner; + public float PostSpeakDelay; + public float PreDelay; + public bool IsBackgroundScene; + + public override void StartPlayback() { + if (GetPreDelay() != 0) + return; + + base.StartPlayback(); + } + + public override void DoThink(TimeUnit_t frametime) { + CheckInterruptCompletion(); + + if (PreDelay > 0) { + PreDelay = (float)Math.Max(0, PreDelay - frametime); + StartPlayback(); + if (!IsPlayingBack) + return; + } + + if (Scene == null || !IsPlayingBack || (HadOwner && Owner.Get() == null)) { + Util.Remove(this); + return; + } + + Assert(Pitch >= SCENE_MIN_PITCH && Pitch <= SCENE_MAX_PITCH); + Pitch = Math.Clamp(Pitch, SCENE_MIN_PITCH, SCENE_MAX_PITCH); + + if (Paused) { + PauseThink(); + return; + } + + TimeUnit_t dt = frametime; + + Scene.SetSoundFileStartupLatency(GetSoundSystemLatency()); + + Scene.Think(CurrentTime); + SetCurrentTime(CurrentTime + dt * Pitch, false); + + if (Scene.SimulationFinished()) { + OnSceneFinished(false, false); + + Util.Remove(this); + } + } + + public override BaseFlex? FindNamedActor(ReadOnlySpan name) { + if (Scene!.GetNumActors() == 1 || stricmp(name, "!self") == 0) { + if (Owner.Get() != null) { + if (Owner.Get() is BaseCombatCharacter character) + return character; + } + } + return base.FindNamedActor(name); + } + + public BaseEntity? FindNamedEntity(ReadOnlySpan name) { + BaseEntity? other = null; + + BaseEntity? owner = Owner.Get(); + if (owner != null) { + AI_BaseNPC? npc = owner.MyNPCPointer(); + + if (npc != null) + other = npc.FindNamedEntity(name); + else if (owner is BaseCombatCharacter) + other = owner; + } + + if (other == null) + other = base.FindNamedEntity(name); + return other; + } + + public override float GetPostSpeakDelay() => PostSpeakDelay; + public virtual void SetPostSpeakDelay(float delay) => PostSpeakDelay = delay; + public virtual float GetPreDelay() => PreDelay; + public virtual void SetPreDelay(float delay) => PreDelay = delay; + + public override void OnLoaded() { + base.OnLoaded(); + SetBackground(IsBackgroundScene); + } + + public override void DispatchStartMoveTo(ChoreoScene scene, BaseFlex actor, BaseEntity actor2, ChoreoEvent ev) { + if (PassThrough(actor)) + base.DispatchStartMoveTo(scene, actor, actor2, ev); + } + + public override void DispatchEndMoveTo(ChoreoScene scene, BaseFlex actor, ChoreoEvent ev) { + if (PassThrough(actor)) + base.DispatchEndMoveTo(scene, actor, ev); + } + + public override void DispatchStartFace(ChoreoScene scene, BaseFlex actor, BaseEntity actor2, ChoreoEvent ev) { + if (PassThrough(actor)) + base.DispatchStartFace(scene, actor, actor2, ev); + } + + public override void DispatchEndFace(ChoreoScene scene, BaseFlex actor, ChoreoEvent ev) { + if (PassThrough(actor)) + base.DispatchEndFace(scene, actor, ev); + } + + public override void DispatchStartSequence(ChoreoScene scene, BaseFlex actor, ChoreoEvent ev) { + if (IsMultiplayer()) + base.DispatchStartSequence(scene, actor, ev); + } + + public override void DispatchEndSequence(ChoreoScene scene, BaseFlex actor, ChoreoEvent ev) { + if (IsMultiplayer()) + base.DispatchEndSequence(scene, actor, ev); + } + + public override void DispatchPauseScene(ChoreoScene scene, ReadOnlySpan parameters) { } + + public override void OnRestore() { + if (HadOwner && Owner.Get() == null) { + Util.Remove(this); + return; + } + + Scene?.SetBackground(IsBackgroundScene); + base.OnRestore(); + } + + public override float EstimateLength() => base.EstimateLength() + GetPreDelay(); + + bool PassThrough(BaseFlex? actor) { + if (actor == null) + return false; + + AI_BaseNPC? myNpc = actor.MyNPCPointer(); + + if (myNpc == null) + return false; + + if (myNpc.IsCurSchedule(SCHED_SCENE_GENERIC)) + return true; + + if (myNpc.GetCurSchedule() != null) { + myNpc.GetCurSchedule()!.GetInterruptMask(out AI_ScheduleBits testBits); + + if (testBits.IsBitSet((int)SCOND_t.COND_IDLE_INTERRUPT)) + return true; + } + + Scene_Printf($"{SceneFile} : event suppressed\n"); + + return false; + } } [LinkEntityToClass("logic_choreographed_scene")] @@ -425,7 +616,7 @@ public struct SpeakEventSound bool SceneMissing; - ChoreoScene? Scene; + protected ChoreoScene? Scene; static ConVar? SndMixahead; @@ -539,7 +730,7 @@ public override void Activate() { GetSceneManager()?.AddSceneEntity(this); } - float GetSoundSystemLatency() { + protected float GetSoundSystemLatency() { if (SndMixahead != null) return SndMixahead.GetFloat(); From 0bd3887a777d466491f27ae568e0b955daa846b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:36:44 +0300 Subject: [PATCH 68/73] Port ai_goal_actbusy_queue --- Game.Server/AI_ActBusyBehavior.cs | 315 +++++++++++++++++++++++++++++- 1 file changed, 314 insertions(+), 1 deletion(-) diff --git a/Game.Server/AI_ActBusyBehavior.cs b/Game.Server/AI_ActBusyBehavior.cs index 4717e1ab4..c9d26b07a 100644 --- a/Game.Server/AI_ActBusyBehavior.cs +++ b/Game.Server/AI_ActBusyBehavior.cs @@ -352,7 +352,7 @@ public void Enable(AI_ActBusyGoal? goal, float range, bool visibleOnly) { NextBusySearchTime = gpGlobals.CurTime + ai_actbusy_search_time.GetFloat(); EndBusyAt = 0; VisibleOnly = visibleOnly; - InQueue = false; + InQueue = ActBusyGoal.Get() is AI_ActBusyQueueGoal; ForcedActivity = Activity.ACT_INVALID; SeeEntity.Set(null); ExitedBusyToDueLostSeeEntity = false; @@ -1784,3 +1784,316 @@ public virtual void NPCSeeEnemy(AI_BaseNPC npc) { OnNPCSeeEnemy.Set(hNPC, npc, this); } } + +[LinkEntityToClass("ai_goal_actbusy_queue")] +public class AI_ActBusyQueueGoal : AI_ActBusyGoal +{ + public const int MAX_QUEUE_NODES = 20; + + const string QUEUE_THINK_CONTEXT = "ActBusyQueueThinkContext"; + const string QUEUE_MOVEUP_THINK_CONTEXT = "ActBusyQueueMoveUpThinkContext"; + + public static readonly new DataMap DataDesc = new(typeof(AI_ActBusyQueueGoal), AI_ActBusyGoal.DataDesc, [ + DEFINE.KEYFIELD(nameof(ForceReachFront), FieldType.Boolean, "mustreachfront"), + DEFINE.KEYFIELD(nameof(Node01), FieldType.String, "node01"), + DEFINE.KEYFIELD(nameof(Node02), FieldType.String, "node02"), + DEFINE.KEYFIELD(nameof(Node03), FieldType.String, "node03"), + DEFINE.KEYFIELD(nameof(Node04), FieldType.String, "node04"), + DEFINE.KEYFIELD(nameof(Node05), FieldType.String, "node05"), + DEFINE.KEYFIELD(nameof(Node06), FieldType.String, "node06"), + DEFINE.KEYFIELD(nameof(Node07), FieldType.String, "node07"), + DEFINE.KEYFIELD(nameof(Node08), FieldType.String, "node08"), + DEFINE.KEYFIELD(nameof(Node09), FieldType.String, "node09"), + DEFINE.KEYFIELD(nameof(Node10), FieldType.String, "node10"), + DEFINE.KEYFIELD(nameof(Node11), FieldType.String, "node11"), + DEFINE.KEYFIELD(nameof(Node12), FieldType.String, "node12"), + DEFINE.KEYFIELD(nameof(Node13), FieldType.String, "node13"), + DEFINE.KEYFIELD(nameof(Node14), FieldType.String, "node14"), + DEFINE.KEYFIELD(nameof(Node15), FieldType.String, "node15"), + DEFINE.KEYFIELD(nameof(Node16), FieldType.String, "node16"), + DEFINE.KEYFIELD(nameof(Node17), FieldType.String, "node17"), + DEFINE.KEYFIELD(nameof(Node18), FieldType.String, "node18"), + DEFINE.KEYFIELD(nameof(Node19), FieldType.String, "node19"), + DEFINE.KEYFIELD(nameof(Node20), FieldType.String, "node20"), + DEFINE.KEYFIELD(nameof(ExitNodeName), FieldType.String, "node_exit"), + + DEFINE.INPUTFUNC(FieldType.Integer, "PlayerStartedBlocking", nameof(InputPlayerStartedBlocking), (INPUTFUNCPTR)((self, data) => ((AI_ActBusyQueueGoal)self).InputPlayerStartedBlocking(data))), + DEFINE.INPUTFUNC(FieldType.Integer, "PlayerStoppedBlocking", nameof(InputPlayerStoppedBlocking), (INPUTFUNCPTR)((self, data) => ((AI_ActBusyQueueGoal)self).InputPlayerStoppedBlocking(data))), + DEFINE.INPUTFUNC(FieldType.Void, "MoveQueueUp", nameof(InputMoveQueueUp), (INPUTFUNCPTR)((self, data) => ((AI_ActBusyQueueGoal)self).InputMoveQueueUp(data))), + + DEFINE.OUTPUT(nameof(OnQueueMoved), "OnQueueMoved", eventFuncs), + DEFINE.OUTPUT(nameof(OnNPCLeftQueue), "OnNPCLeftQueue", eventFuncs), + DEFINE.OUTPUT(nameof(OnNPCStartedLeavingQueue), "OnNPCStartedLeavingQueue", eventFuncs), + ]); + public override DataMap? GetDataDescMap() => DataDesc; + + int CurrentQueueCount; + Handle[] Nodes = new Handle[MAX_QUEUE_NODES]; + bool[] PlayerBlockedNodes = new bool[MAX_QUEUE_NODES]; + EHANDLE ExitNode = new(); + EHANDLE ExitingNPC = new(); + bool ForceReachFront; + + string? Node01, Node02, Node03, Node04, Node05, Node06, Node07, Node08, Node09, Node10, + Node11, Node12, Node13, Node14, Node15, Node16, Node17, Node18, Node19, Node20; + string? ExitNodeName; + + readonly OutputInt OnQueueMoved = new(); + readonly OutputEHANDLE OnNPCLeftQueue = new(); + readonly OutputEHANDLE OnNPCStartedLeavingQueue = new(); + + string? NodeName(int i) => i switch { + 0 => Node01, 1 => Node02, 2 => Node03, 3 => Node04, 4 => Node05, 5 => Node06, 6 => Node07, 7 => Node08, 8 => Node09, 9 => Node10, + 10 => Node11, 11 => Node12, 12 => Node13, 13 => Node14, 14 => Node15, 15 => Node16, 16 => Node17, 17 => Node18, 18 => Node19, 19 => Node20, + _ => null + }; + + public override void Spawn() { + base.Spawn(); + + RegisterThinkContext(QUEUE_MOVEUP_THINK_CONTEXT); + } + + public override void DrawDebugGeometryOverlays() { + base.DrawDebugGeometryOverlays(); + + for (int i = 0; i < MAX_QUEUE_NODES; i++) { + if (Nodes[i].Get() == null) + continue; + if (PlayerBlockedNodes[i]) + DebugOverlay.Box(Nodes[i].Get()!.GetAbsOrigin(), -new Vector3(5, 5, 5), new Vector3(5, 5, 5), 255, 0, 0, 0, 0.1f); + else + DebugOverlay.Box(Nodes[i].Get()!.GetAbsOrigin(), -new Vector3(5, 5, 5), new Vector3(5, 5, 5), 255, 255, 255, 0, 0.1f); + } + } + + public override void InputActivate(InputData inputdata) { + if (!IsActive()) { + for (int i = 0; i < MAX_QUEUE_NODES; i++) { + string? nodeName = NodeName(i); + if (nodeName == null) { + Nodes[i].Set(null); + continue; + } + + BaseEntity? entity = gEntList.FindEntityByName(null, nodeName); + if (entity == null) { + Warning($"Unable to find ai_goal_actbusy_queue {GetEntityName()}'s node {i}: {nodeName}\n"); + Util.Remove(this); + return; + } + Nodes[i].Set(entity as AI_Hint); + if (Nodes[i].Get() == null) { + Warning($"ai_goal_actbusy_queue {GetEntityName()}'s node {i}: '{nodeName}' is not an ai_hint.\n"); + Util.Remove(this); + return; + } + + if (i == 0) + Nodes[i].Get()!.SetDisabled(false); + else + Nodes[i].Get()!.SetDisabled(true); + } + + ExitNode.Set(gEntList.FindEntityByName(null, ExitNodeName)); + if (ExitNode.Get() == null) { + Warning($"Unable to find ai_goal_actbusy_queue {GetEntityName()}'s exit node: {ExitNodeName}\n"); + Util.Remove(this); + return; + } + + RecalculateQueueCount(); + + SetContextThink(QueueThink, gpGlobals.CurTime + 5, QUEUE_THINK_CONTEXT); + } + + base.InputActivate(inputdata); + } + + public void RecalculateQueueCount() { + int count = 0; + for (int i = 0; i < MAX_QUEUE_NODES; i++) { + if (NodeIsOccupied(i) || PlayerBlockedNodes[i]) + count = i + 1; + } + + if (count == CurrentQueueCount) + return; + + for (int i = 0; i < MAX_QUEUE_NODES; i++) { + AI_Hint? node = Nodes[i].Get(); + if (node != null) { + if (i > count) + node.SetDisabled(true); + else { + node.SetDisabled(false); + + if (i == count) + node.SetHintType(Hint.WorldWorkPosition); + else + node.SetHintType(Hint.None); + } + } + } + + CurrentQueueCount = count; + OnQueueMoved.Set(CurrentQueueCount, this, this); + } + + public void InputPlayerStartedBlocking(InputData inputdata) { + int node = inputdata.Value.Int() - 1; + Assert(node >= 0 && node < MAX_QUEUE_NODES); + + PlayerBlockedNodes[node] = true; + + AI_BaseNPC? npc = GetNPCOnNode(node); + PushNPCBackInQueue(npc, node); + + RecalculateQueueCount(); + } + + public void PushNPCBackInQueue(AI_BaseNPC? npc, int startingNode) { + while (npc != null) { + AI_ActBusyBehavior behavior = GetQueueBehaviorForNPC(npc)!; + behavior.StopBusying(); + + for (int next = startingNode + 1; next < MAX_QUEUE_NODES; next++) { + if (!PlayerBlockedNodes[next]) { + AI_BaseNPC? targetNPC = GetNPCOnNode(next); + if (targetNPC != null) { + AI_ActBusyBehavior targetBehavior = GetQueueBehaviorForNPC(targetNPC)!; + targetBehavior.StopBusying(); + } + + behavior.ForceActBusyNow(this, Nodes[next].Get()); + + npc = targetNPC; + startingNode = next; + break; + } + } + } + } + + public void InputPlayerStoppedBlocking(InputData inputdata) { + int node = inputdata.Value.Int() - 1; + Assert(node >= 0 && node < MAX_QUEUE_NODES); + + PlayerBlockedNodes[node] = false; + + RecalculateQueueCount(); + MoveQueueUp(); + } + + public void InputMoveQueueUp(InputData inputdata) { + AI_BaseNPC? npc = null; + for (int i = 0; i < MAX_QUEUE_NODES; i++) { + npc = GetNPCOnNode(i); + if (npc != null) { + AI_ActBusyBehavior behavior = GetQueueBehaviorForNPC(npc)!; + if (!behavior.IsMovingToBusy() || !ForceReachFront) + break; + + npc = null; + } + + if (ForceReachFront) + break; + } + + if (npc != null) { + AI_ActBusyBehavior behavior = GetQueueBehaviorForNPC(npc)!; + behavior.Disable(); + ExitingNPC.Set(npc); + } + } + + public override void NPCMovingToBusy(AI_BaseNPC npc) { + base.NPCMovingToBusy(npc); + RecalculateQueueCount(); + } + + public override void NPCStartedBusy(AI_BaseNPC npc) { + base.NPCStartedBusy(npc); + MoveQueueUp(); + } + + public void MoveQueueUp() { + if (GetNextThink(QUEUE_MOVEUP_THINK_CONTEXT) < gpGlobals.CurTime) { + TimeUnit_t time = gpGlobals.CurTime + random.RandomFloat(0.3f, 0.5f); + SetContextThink(MoveQueueUpThink, time, QUEUE_MOVEUP_THINK_CONTEXT); + } + } + + public void MoveQueueUpThink() { + for (int emptyNode = 0; emptyNode < (MAX_QUEUE_NODES - 1); emptyNode++) { + if (!NodeIsOccupied(emptyNode) && !PlayerBlockedNodes[emptyNode]) { + for (int next = emptyNode + 1; next < MAX_QUEUE_NODES; next++) { + if (PlayerBlockedNodes[next]) + break; + + AI_BaseNPC? npc = GetNPCOnNode(next); + if (npc != null) { + AI_ActBusyBehavior behavior = GetQueueBehaviorForNPC(npc)!; + + behavior.ForceActBusyNow(this, Nodes[emptyNode].Get()); + break; + } + } + } + } + } + + public override void NPCAbortedMoveTo(AI_BaseNPC npc) { + base.NPCAbortedMoveTo(npc); + + RemoveNPCFromQueue(npc); + } + + public override void NPCFinishedBusy(AI_BaseNPC npc) { + base.NPCFinishedBusy(npc); + + if (ExitingNPC.Get() == npc) { + npc.ScheduledMoveToGoalEntity(SCHED_IDLE_WALK, ExitNode.Get()!, Activity.ACT_WALK); + OnNPCLeftQueue.Set(npc.GetRefEHandle(), npc, this); + ExitingNPC.Set(null); + } + + RemoveNPCFromQueue(npc); + } + + public override void NPCStartedLeavingBusy(AI_BaseNPC npc) { + base.NPCStartedLeavingBusy(npc); + + if (ExitingNPC.Get() == npc) + OnNPCStartedLeavingQueue.Set(npc.GetRefEHandle(), npc, this); + } + + public void RemoveNPCFromQueue(AI_BaseNPC npc) { + RecalculateQueueCount(); + + MoveQueueUp(); + } + + public void QueueThink() { + if (GetNPCOnNode(0) == null) + MoveQueueUp(); + + SetContextThink(QueueThink, gpGlobals.CurTime + 5, QUEUE_THINK_CONTEXT); + } + + public bool NodeIsOccupied(int i) => Nodes[i].Get() != null && !Nodes[i].Get()!.IsDisabled() && Nodes[i].Get()!.IsLocked(); + + public AI_BaseNPC? GetNPCOnNode(int node) { + if (Nodes[node].Get() == null) + return null; + + return Nodes[node].Get()!.User() as AI_BaseNPC; + } + + public AI_ActBusyBehavior? GetQueueBehaviorForNPC(AI_BaseNPC npc) { + npc.GetBehavior(out AI_ActBusyBehavior? behavior); + Assert(behavior != null); + return behavior; + } +} From 0f6396a40507668c6fd4564006039b8128520a3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:42:31 +0300 Subject: [PATCH 69/73] Port TASK_MOVE_AWAY_PATH --- Game.Server/AI_BaseNPC.cs | 110 ++++++++++++++++++++++++++++- Game.Server/AI_TacticalServices.cs | 4 ++ 2 files changed, 112 insertions(+), 2 deletions(-) diff --git a/Game.Server/AI_BaseNPC.cs b/Game.Server/AI_BaseNPC.cs index 42413465d..13a09a9b5 100644 --- a/Game.Server/AI_BaseNPC.cs +++ b/Game.Server/AI_BaseNPC.cs @@ -5309,8 +5309,11 @@ public virtual void StartTask(in Task_t task) { case TASK_CLEAR_COMMAND_GOAL: case TASK_GET_PATH_TO_BESTSOUND: case TASK_GET_PATH_TO_BESTSCENT: - case TASK_GET_PATH_AWAY_FROM_BEST_SOUND: case TASK_MOVE_AWAY_PATH: + DesireStand(); + break; + + case TASK_GET_PATH_AWAY_FROM_BEST_SOUND: case TASK_WEAPON_RUN_PATH: case TASK_ITEM_RUN_PATH: case TASK_STRAFE_PATH: @@ -5673,8 +5676,107 @@ public virtual void RunTask(in Task_t task) { case TASK_GET_FLANK_RADIUS_PATH_TO_ENEMY_LOS: case TASK_GET_FLANK_ARC_PATH_TO_ENEMY_LOS: case TASK_GET_PATH_TO_ENEMY_LKP_LOS: + case TASK_MOVE_AWAY_PATH: { + QAngle ang = GetLocalAngles(); + ang.Y = GetMotor()!.GetIdealYaw() + 180; + Vector3 move; + + switch (GetTaskInterrupt()) { + case 0: { + if (IsPlayerAlly()) { + AI_Hint? hint; + HintCriteria hintCriteria = new(); + + hintCriteria.AddHintType(Hint.PlayerAllyMoveAwayDest); + hintCriteria.SetFlag(AI_HintNodeFlags.Nearest); + hintCriteria.AddIncludePosition(GetAbsOrigin(), 20.0f * 12.0f); + hintCriteria.AddExcludePosition(GetAbsOrigin(), 28.0f); + + hint = AI_HintManager.FindHint(this, hintCriteria); + + if (hint != null) { + BasePlayer? player = AI_GetClosestPlayer(); + Vector3 goal = hint.GetAbsOrigin(); + + if (goal.DistToSqr(GetAbsOrigin()) < goal.DistToSqr(player!.GetAbsOrigin())) { + if (GetNavigator()!.SetGoal(new AI_NavGoal(goal))) { + hint.DisableForSeconds(0.1f); + TaskComplete(); + break; + } + } + } + } + + ref WorldSoundInstance bestSound = ref GetBestSound(SoundInstanceType.MoveAway); + if (!Unsafe.IsNullRef(ref bestSound) && bestSound.Owner.Get() != null && bestSound.Owner.Get()!.GetServerVehicle() != null) { + move = GetAbsOrigin() - bestSound.Owner.Get()!.WorldSpaceCenter(); + MathLib.VectorNormalize(ref move); + } + else + MathLib.AngleVectors(ang, out move); + + if (GetNavigator()!.SetVectorGoal(move, task.TaskData, Math.Min(36, task.TaskData), true) && IsValidMoveAwayDest(GetNavigator()!.GetGoalPos())) + TaskComplete(); + else { + ang.Y = GetMotor()!.GetIdealYaw() + 91; + MathLib.AngleVectors(ang, out move); + + if (GetNavigator()!.SetVectorGoal(move, task.TaskData, Math.Min(24, task.TaskData), true) && IsValidMoveAwayDest(GetNavigator()!.GetGoalPos())) + TaskComplete(); + else + TaskInterrupt(); + } + } + break; + + case 1: { + ang.Y = GetMotor()!.GetIdealYaw() + 271; + MathLib.AngleVectors(ang, out move); + + if (GetNavigator()!.SetVectorGoal(move, task.TaskData, Math.Min(24, task.TaskData), true) && IsValidMoveAwayDest(GetNavigator()!.GetGoalPos())) + TaskComplete(); + else { + ang.Y = GetMotor()!.GetIdealYaw() + 180; + while (ang.Y < 0) + ang.Y += 360; + while (ang.Y >= 360) + ang.Y -= 360; + if (ang.Y < 45 || ang.Y >= 315) + ang.Y = 0; + else if (ang.Y < 135) + ang.Y = 90; + else if (ang.Y < 225) + ang.Y = 180; + else + ang.Y = 270; + + MathLib.AngleVectors(ang, out move); + + if (GetNavigator()!.SetVectorGoal(move, task.TaskData, Math.Min(6, task.TaskData), false) && IsValidMoveAwayDest(GetNavigator()!.GetGoalPos())) + TaskComplete(); + else + TaskInterrupt(); + } + } + break; + + case 2: { + ClearTaskInterrupt(); + + if (GetTacticalServices()!.FindCoverPos(GetLocalOrigin(), EyePosition(), 0, CoverRadius(), out Vector3 coverPos) && IsValidMoveAwayDest(GetNavigator()!.GetGoalPos())) { + GetNavigator()!.SetGoal(new AI_NavGoal(coverPos, Activity.ACT_RUN)); + MoveWaitFinished = gpGlobals.CurTime + 2; + } + else + TaskFail(AI_TaskFailureCode.NoRoute); + } + break; + } + } + break; + case TASK_GET_PATH_AWAY_FROM_BEST_SOUND: - case TASK_MOVE_AWAY_PATH: case TASK_WEAPON_RUN_PATH: case TASK_ITEM_RUN_PATH: case TASK_WAIT_FOR_SPEAK_FINISH: @@ -5873,6 +5975,10 @@ public virtual bool Stand() { public void DesireStand() => CrouchDesired = false; + public virtual bool IsValidMoveAwayDest(in Vector3 dest) => true; + + public virtual float CoverRadius() => 1024; + public virtual void OnChangeActivity(Activity newActivity) { if (newActivity == Activity.ACT_RUN || newActivity == Activity.ACT_RUN_AIM || diff --git a/Game.Server/AI_TacticalServices.cs b/Game.Server/AI_TacticalServices.cs index 57fa34966..fc8586b4a 100644 --- a/Game.Server/AI_TacticalServices.cs +++ b/Game.Server/AI_TacticalServices.cs @@ -1,3 +1,5 @@ +using System.Numerics; + namespace Game.Server; public class AI_TacticalServices : AI_Component @@ -13,6 +15,8 @@ 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 AI_Network? Network; public AI_Pathfinder? Pathfinder; } From d7f85981bed6ca98fe6c77b0e87a62d72b9dea56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:46:58 +0300 Subject: [PATCH 70/73] Port citizen package activity tables --- Game.Server/HL2/Weapon_Stubs_HL2.cs | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Game.Server/HL2/Weapon_Stubs_HL2.cs b/Game.Server/HL2/Weapon_Stubs_HL2.cs index 876a5bd33..9925a257e 100644 --- a/Game.Server/HL2/Weapon_Stubs_HL2.cs +++ b/Game.Server/HL2/Weapon_Stubs_HL2.cs @@ -3,6 +3,8 @@ using Source.Common; +using System.Numerics; + namespace Game.Server.HL2; [LinkEntityToClass("cycler_weapon")] @@ -27,6 +29,20 @@ public class WeaponCitizenPackage : BaseHLCombatWeapon { public static readonly SendTable DT_WeaponCitizenPackage = new(DT_BaseHLCombatWeapon, []); public static new readonly ServerClass ServerClass = new ServerClass(DT_WeaponCitizenPackage); + + static readonly ActTable[] acttable = [ + new() { BaseAct = Activity.ACT_IDLE, WeaponAct = Activity.ACT_IDLE_PACKAGE, Required = false }, + new() { BaseAct = Activity.ACT_WALK, WeaponAct = Activity.ACT_WALK_PACKAGE, Required = false }, + ]; + + public override ReadOnlySpan ActivityList() => acttable; + + public override void ItemPostFrame() { } + + public override void Drop(in Vector3 velocity) { + base.Drop(velocity); + Util.Remove(this); + } } [LinkEntityToClass("weapon_citizensuitcase")] @@ -35,6 +51,13 @@ public class WeaponCitizenSuitcase : WeaponCitizenPackage { public static readonly SendTable DT_WeaponCitizenSuitcase = new(DT_WeaponCitizenPackage, []); public static new readonly ServerClass ServerClass = new ServerClass(DT_WeaponCitizenSuitcase); + + static readonly ActTable[] acttable = [ + new() { BaseAct = Activity.ACT_IDLE, WeaponAct = Activity.ACT_IDLE_SUITCASE, Required = false }, + new() { BaseAct = Activity.ACT_WALK, WeaponAct = Activity.ACT_WALK_SUITCASE, Required = false }, + ]; + + public override ReadOnlySpan ActivityList() => acttable; } [LinkEntityToClass("weapon_oldmanharpoon")] @@ -43,4 +66,11 @@ public class WeaponOldManHarpoon : WeaponCitizenPackage { public static readonly SendTable DT_WeaponOldManHarpoon = new(DT_WeaponCitizenPackage, []); public static new readonly ServerClass ServerClass = new ServerClass(DT_WeaponOldManHarpoon); + + static readonly ActTable[] acttable = [ + new() { BaseAct = Activity.ACT_IDLE, WeaponAct = Activity.ACT_IDLE_SUITCASE, Required = false }, + new() { BaseAct = Activity.ACT_WALK, WeaponAct = Activity.ACT_WALK_SUITCASE, Required = false }, + ]; + + public override ReadOnlySpan ActivityList() => acttable; } From 0b251bd7cb2aa2aa1b6a90dbb3cabd1157269212 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:51:12 +0300 Subject: [PATCH 71/73] Port WorldSpaceSlerp --- Source.Common/BoneSetup.cs | 88 +++++++++++++++++++++++++++- Source.Common/Mathematics/MathLib.cs | 60 +++++++++++++++++++ 2 files changed, 147 insertions(+), 1 deletion(-) diff --git a/Source.Common/BoneSetup.cs b/Source.Common/BoneSetup.cs index 9cb878f64..494c046fa 100644 --- a/Source.Common/BoneSetup.cs +++ b/Source.Common/BoneSetup.cs @@ -1271,7 +1271,93 @@ private static void SlerpBones(StudioHdr studioHdr, Span q1, Span q1, Span pos1, MStudioSeqDesc seqdesc, int sequence, Span q2, Span pos2, float s, int boneMask) { - throw new NotImplementedException(); + int i, j; + float s1; + float s2; + + MathLib.SetIdentityMatrix(out Matrix3x4 rootXform); + + Matrix3x4[] srcBoneToWorld = MatrixPool.Alloc(); + BoneBitList srcBoneComputed = default; + + Matrix3x4[] destBoneToWorld = MatrixPool.Alloc(); + BoneBitList destBoneComputed = default; + + Matrix3x4[] targetBoneToWorld = MatrixPool.Alloc(); + + VirtualModel? vModel = studioHdr.GetVirtualModel(); + VirtualGroup? seqGroup = null; + if (vModel != null) + seqGroup = vModel.SeqGroup(sequence); + + for (i = 0; i < studioHdr.NumBones(); i++) { + if ((studioHdr.BoneFlags(i) & boneMask) == 0) + continue; + + int n = studioHdr.BoneParent(i); + s1 = 0.0f; + if (seqGroup != null) { + j = seqGroup.BoneMap[i]; + if (j >= 0) { + s2 = s * seqdesc.Weight(j); + if (n != -1) + s1 = s * seqdesc.Weight(seqGroup.BoneMap[n]); + } + else + s2 = 0.0f; + } + else { + s2 = s * seqdesc.Weight(i); + if (n != -1) + s1 = s * seqdesc.Weight(n); + } + + if (s1 == 1.0f && s2 == 1.0f) { + pos1[i] = pos2[i]; + q1[i] = q2[i]; + } + else if (s2 > 0.0f) { + BuildBoneChain(studioHdr, rootXform, pos1, q1, i, destBoneToWorld, ref destBoneComputed); + BuildBoneChain(studioHdr, rootXform, pos2, q2, i, srcBoneToWorld, ref srcBoneComputed); + + MathLib.MatrixAngles(destBoneToWorld[i], out Quaternion destQ, out Vector3 destPos); + MathLib.MatrixAngles(srcBoneToWorld[i], out Quaternion srcQ, out _); + + MathLib.QuaternionSlerp(destQ, srcQ, s2, out Quaternion targetQ); + MathLib.QuaternionAngles(targetQ, out RadianEuler targetAngles); + MathLib.AngleMatrix(targetAngles, destPos, out targetBoneToWorld[i]); + + if (n == -1) + MathLib.MatrixAngles(targetBoneToWorld[i], out q1[i], out _); + else { + MathLib.MatrixInvert(targetBoneToWorld[n], out Matrix3x4 worldToBone); + + MathLib.ConcatTransforms(worldToBone, targetBoneToWorld[i], out Matrix3x4 local); + MathLib.MatrixAngles(local, out q1[i], out _); + + pos1[i] = Vector3.Lerp(pos1[i], pos2[i], s2); + } + } + } + MatrixPool.Free(srcBoneToWorld); + MatrixPool.Free(destBoneToWorld); + MatrixPool.Free(targetBoneToWorld); + } + + private static void BuildBoneChain(StudioHdr studioHdr, in Matrix3x4 rootxform, ReadOnlySpan pos, ReadOnlySpan q, int bone, Matrix3x4[] boneToWorld, ref BoneBitList boneComputed) { + if (boneComputed.IsBoneMarked(bone)) + return; + + MathLib.QuaternionMatrix(q[bone], pos[bone], out Matrix3x4 bonematrix); + + int parent = studioHdr.BoneParent(bone); + if (parent == -1) + MathLib.ConcatTransforms(rootxform, bonematrix, out boneToWorld[bone]); + else { + BuildBoneChain(studioHdr, rootxform, pos, q, parent, boneToWorld, ref boneComputed); + MathLib.ConcatTransforms(boneToWorld[parent], bonematrix, out boneToWorld[bone]); + } + boneComputed.MarkBone(bone); } private void AddSequenceLayers(Span pos, Span q, MStudioSeqDesc seqdesc, int sequence, double cycle, float weight, double time, object? ikContext) { diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index 74830d11c..1902ce959 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -1878,6 +1878,66 @@ public static void MatrixAngles(in Matrix3x4 matrix, out QAngle angles, out Vect MatrixPosition(matrix, out position); } + public static void MatrixAngles(in Matrix3x4 matrix, out Quaternion q, out Vector3 pos) { + float trace; + trace = matrix[0, 0] + matrix[1, 1] + matrix[2, 2] + 1.0f; + if (trace > 1.0f + FLT_EPSILON) { + q.X = matrix[2, 1] - matrix[1, 2]; + q.Y = matrix[0, 2] - matrix[2, 0]; + q.Z = matrix[1, 0] - matrix[0, 1]; + q.W = trace; + } + else if (matrix[0, 0] > matrix[1, 1] && matrix[0, 0] > matrix[2, 2]) { + trace = 1.0f + matrix[0, 0] - matrix[1, 1] - matrix[2, 2]; + q.X = trace; + q.Y = matrix[1, 0] + matrix[0, 1]; + q.Z = matrix[0, 2] + matrix[2, 0]; + q.W = matrix[2, 1] - matrix[1, 2]; + } + else if (matrix[1, 1] > matrix[2, 2]) { + trace = 1.0f + matrix[1, 1] - matrix[0, 0] - matrix[2, 2]; + q.X = matrix[0, 1] + matrix[1, 0]; + q.Y = trace; + q.Z = matrix[2, 1] + matrix[1, 2]; + q.W = matrix[0, 2] - matrix[2, 0]; + } + else { + trace = 1.0f + matrix[2, 2] - matrix[0, 0] - matrix[1, 1]; + q.X = matrix[0, 2] + matrix[2, 0]; + q.Y = matrix[2, 1] + matrix[1, 2]; + q.Z = trace; + q.W = matrix[1, 0] - matrix[0, 1]; + } + + QuaternionNormalize2(ref q); + + MatrixGetColumn(matrix, 3, out pos); + } + + public static void MatrixAngles(in Matrix3x4 matrix, out RadianEuler angles) { + MatrixAngles(matrix, out QAngle degrees); + + angles.X = DEG2RAD(degrees.Z); + angles.Y = DEG2RAD(degrees.X); + angles.Z = DEG2RAD(degrees.Y); + } + + public static void QuaternionAngles(in Quaternion q, out RadianEuler angles) { + QuaternionMatrix(q, out Matrix3x4 matrix); + MatrixAngles(matrix, out angles); + } + + public static void AngleMatrix(in RadianEuler angles, out Matrix3x4 matrix) { + QAngle quakeEuler = new(RAD2DEG(angles.Y), RAD2DEG(angles.Z), RAD2DEG(angles.X)); + + AngleMatrix(quakeEuler, out matrix); + } + + public static void AngleMatrix(in RadianEuler angles, in Vector3 position, out Matrix3x4 matrix) { + AngleMatrix(angles, out matrix); + MatrixSetColumn(position, 3, ref matrix); + } + public static void MatrixAngles(in Matrix3x4 matrix, out QAngle angles) { angles = default; Span forward = stackalloc float[3]; From e77a5ab6ff73eafcc3188e628469b4b60be5b634 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 23:06:10 +0300 Subject: [PATCH 72/73] Put back the lost AggressiveInlining --- Source.Common/Mathematics/MathLib.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs index 1902ce959..8754f9b0c 100644 --- a/Source.Common/Mathematics/MathLib.cs +++ b/Source.Common/Mathematics/MathLib.cs @@ -2269,6 +2269,7 @@ public static float Vector2DNormalize(ref Vector2 v) { return l; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float VectorNormalize(ref Vector3 vec) { float radius = MathF.Sqrt(vec.X * vec.X + vec.Y * vec.Y + vec.Z * vec.Z); From 2b632bbc7e5fe1b76720fb8bc962c739fd3fee93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=B6eh=20Matt?= <5415177+ZehMatt@users.noreply.github.com> Date: Mon, 12 Oct 2026 23:18:41 +0300 Subject: [PATCH 73/73] Fix bad loop using Util.PlayerByIndex --- Game.Server/PhysicsNPCSolver.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Game.Server/PhysicsNPCSolver.cs b/Game.Server/PhysicsNPCSolver.cs index 56c57185b..e24da636a 100644 --- a/Game.Server/PhysicsNPCSolver.cs +++ b/Game.Server/PhysicsNPCSolver.cs @@ -220,7 +220,7 @@ public SimResult Simulate(IPhysicsMotionController? controller, IPhysicsObject? if ((obj!.GetGameFlags() & PhysicsFlags.PlayerHeld) != 0) { #if GMOD_DLL - for (int i = 0; i < gpGlobals.MaxClients; i++) { + for (int i = 1; i <= gpGlobals.MaxClients; i++) { BasePlayer? player = Util.PlayerByIndex(i); player?.ForceDropOfCarriedPhysObjects(Entity.Get()); }