From b614c30bc28c2ef5b778bb66c40a5e1b8ce0efa4 Mon Sep 17 00:00:00 2001 From: Memes <114233643+Mr-Memes@users.noreply.github.com> Date: Fri, 21 Nov 2025 10:10:50 +0100 Subject: [PATCH] First Implementation --- DataStructures/HeapDict.cs | 117 +++++++ NPCs/SunkenSea/AlphaSeaMinnow.cs | 22 +- NPCs/SunkenSea/EutrophicRay.cs | 28 +- NPCs/SunkenSea/GhostBell.cs | 11 +- NPCs/SunkenSea/KelpieSeadragon.cs | 52 +-- NPCs/SunkenSea/LazarusLampfish.cs | 84 +++-- NPCs/SunkenSea/PodobooKoi.cs | 38 +-- NPCs/SunkenSea/PolypPanasea.cs | 28 +- NPCs/SunkenSea/PrismBack.cs | 10 +- NPCs/SunkenSea/PrismaticGuppy.cs | 32 +- NPCs/SunkenSea/Probesnout.cs | 72 ++-- NPCs/SunkenSea/SeaMinnow.cs | 20 +- NPCs/SunkenSea/Sharkoon.cs | 62 ++-- NPCs/SunkenSea/SunkenSeaNPC.cs | 35 +- Pathfinding/IPathfinder.cs | 21 ++ Pathfinding/Movements/BaseEntityMovement.cs | 18 + Pathfinding/Movements/IMovement.cs | 45 +++ Pathfinding/Movements/Movement.cs | 14 + .../Movements/SunkenSeaSwinMovement.cs | 45 +++ Utilities/PathfindingUtils.cs | 318 ++++-------------- 20 files changed, 576 insertions(+), 496 deletions(-) create mode 100644 DataStructures/HeapDict.cs create mode 100644 Pathfinding/IPathfinder.cs create mode 100644 Pathfinding/Movements/BaseEntityMovement.cs create mode 100644 Pathfinding/Movements/IMovement.cs create mode 100644 Pathfinding/Movements/Movement.cs create mode 100644 Pathfinding/Movements/SunkenSeaSwinMovement.cs diff --git a/DataStructures/HeapDict.cs b/DataStructures/HeapDict.cs new file mode 100644 index 0000000000..8516bdde75 --- /dev/null +++ b/DataStructures/HeapDict.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; + +namespace CalamityMod.DataStructures +{ + /// + /// A is a Dictionary-like data structure + /// that also keeps its entries in a binary-heap ordered by (The priority).
+ /// This allows for O(log n) retrievals of the with the lowest + /// (Thanks to the MinHeap/PriorityQueue structure) and O(1) lookups of any element (Thanks to the Dictionary structure).
+ /// This data structure is specially useful for graph algorithms where getting the minimum element is a constant process, like A*.
+ /// It essentially combines a and a into one data structure. + ///
+ /// + /// + public class HeapDict where TValue : IComparable + { + private readonly Dictionary _indexMap = []; + private readonly List<(TKey Key, TValue Value)> _heap = []; + + public int Count => _heap.Count; + + public void Add(TKey key, TValue value) + { + if (_indexMap.TryGetValue(key, out int index)) + { + TValue oldValue = _heap[index].Value; + _heap[index] = (key, value); + + int cmp = value.CompareTo(oldValue); + if (cmp < 0) + HeapifyUp(index); + else if (cmp > 0) + HeapifyDown(index); + } + else + { + _heap.Add((key, value)); + index = _heap.Count - 1; + _indexMap[key] = index; + HeapifyUp(index); + } + } + + public (TKey, TValue) PopMin() + { + if (_heap.Count == 0) + throw new InvalidOperationException("Heap is empty"); + + var min = _heap[0]; + var last = _heap[^1]; + _heap[0] = last; + _indexMap[last.Key] = 0; + _heap.RemoveAt(_heap.Count - 1); + _indexMap.Remove(min.Key); + if (_heap.Count > 0) + HeapifyDown(0); + + return min; + } + + public (TKey, TValue) PeekMin() + { + if (_heap.Count == 0) + throw new InvalidOperationException("Heap is empty"); + + return _heap[0]; + } + + private void HeapifyUp(int index) + { + while (index > 0) + { + int parent = (index - 1) / 2; + if (_heap[index].Value.CompareTo(_heap[parent].Value) >= 0) + break; + + Swap(index, parent); + index = parent; + } + } + + private void HeapifyDown(int index) + { + int lastIndex = _heap.Count - 1; + while (true) + { + int left = 2 * index + 1; + int right = 2 * index + 2; + int smallest = index; + + if (left <= lastIndex && _heap[left].Value.CompareTo(_heap[smallest].Value) < 0) + smallest = left; + + if (right <= lastIndex && _heap[right].Value.CompareTo(_heap[smallest].Value) < 0) + smallest = right; + + if (smallest == index) + break; + + Swap(index, smallest); + index = smallest; + } + } + + private void Swap(int i, int j) + { + (_heap[i], _heap[j]) = (_heap[j], _heap[i]); + _indexMap[_heap[i].Key] = i; + _indexMap[_heap[j].Key] = j; + } + + public bool ContainsKey(TKey key) => _indexMap.ContainsKey(key); + + public TValue GetValue(TKey key) => _heap[_indexMap[key]].Value; + } +} diff --git a/NPCs/SunkenSea/AlphaSeaMinnow.cs b/NPCs/SunkenSea/AlphaSeaMinnow.cs index 0f3161411d..61dda41f82 100644 --- a/NPCs/SunkenSea/AlphaSeaMinnow.cs +++ b/NPCs/SunkenSea/AlphaSeaMinnow.cs @@ -116,11 +116,9 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.6f, - MaxSpeed = 4f, - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.6f; + MaxSpeed = 4f; } if (NPC.wet) { @@ -150,7 +148,7 @@ namespace CalamityMod.NPCs.SunkenSea public void IdleBehavior() { // At random, the mob will choose a random nearby point and pathfind there. - pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity)); } public void FleeBehavior() @@ -159,30 +157,30 @@ namespace CalamityMod.NPCs.SunkenSea if (CurrentPredator == null) { CurrentBehavior = (int)PhaseType.Idle; - pathfinding.MaxSpeed = 4; + MaxSpeed = 4f; return; } - pathfinding.MaxSpeed = 8; + MaxSpeed = 8f; // While it doesn't have any obstacles in front of it, run away in a straight line. // Try to manuever if there are any obstacles. Point lookAheadPosition = (NPC.Center + NPC.DirectionFrom(CurrentPredator.Center) * FleeTileAnticipationDistance).ToTileCoordinates(); if (!CalamityUtils.ParanoidTileRetrieval(lookAheadPosition.X, lookAheadPosition.Y).IsTileSolid()) { - NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * pathfinding.Acceleration; + NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; } else { float distanceFromAvoided = Vector2.Distance(NPC.Center, CurrentPredator.Center); randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f); NPC.netUpdate = true; - pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity)); } } diff --git a/NPCs/SunkenSea/EutrophicRay.cs b/NPCs/SunkenSea/EutrophicRay.cs index 2992606a4a..e14ba0960a 100644 --- a/NPCs/SunkenSea/EutrophicRay.cs +++ b/NPCs/SunkenSea/EutrophicRay.cs @@ -114,11 +114,9 @@ namespace CalamityMod.NPCs.SunkenSea public override void OnSpawn(IEntitySource source) { - pathfinding = new PathfindingManager(NPC) - { - MaxSpeed = 4.85f, - Acceleration = 0.5f - }; + pathfinding = new PathfindingManager(this); + MaxSpeed = 4.85f; + Acceleration = 0.5f; CurrentBehavior = IdleBehavior; } @@ -127,11 +125,9 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - MaxSpeed = 4.85f, - Acceleration = 0.5f - }; + pathfinding = new PathfindingManager(this); + MaxSpeed = 4.85f; + Acceleration = 0.5f; } CurrentBehavior?.Invoke(); @@ -160,7 +156,7 @@ namespace CalamityMod.NPCs.SunkenSea if (newBehavior == OutOfWaterBehavior) NPC.noGravity = false; - pathfinding.MaxSpeed = newBehavior == FleeBehavior ? 6.5f : 5f; + MaxSpeed = newBehavior == FleeBehavior ? 6.5f : 5f; } private void IdleBehavior() @@ -175,7 +171,7 @@ namespace CalamityMod.NPCs.SunkenSea NPC.velocity *= 0.98f; } - pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(200f, 800f), SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(200f, 800f), SunkenSeaTileValidity)); } private void AttackBehavior() { @@ -237,19 +233,19 @@ namespace CalamityMod.NPCs.SunkenSea // Flee in a straight line if possible, otherwise pathfind away from the attacker. if (!Main.tile[(NPC.Center + NPC.DirectionFrom(AvoidedEntity.Center) * 64f).ToTileCoordinates()].IsTileSolid()) { - NPC.velocity += NPC.DirectionFrom(AvoidedEntity.Center) * pathfinding.Acceleration; + NPC.velocity += NPC.DirectionFrom(AvoidedEntity.Center) * Acceleration; pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; } else { float distanceFromAvoided = Vector2.Distance(NPC.Center, AvoidedEntity.Center); Vector2 pathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f); NPC.netUpdate = true; - pathfinding.DoPathfinding(new(NPC.Center, pathPoint, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, pathPoint, SunkenSeaTileValidity)); } } private void OutOfWaterBehavior() diff --git a/NPCs/SunkenSea/GhostBell.cs b/NPCs/SunkenSea/GhostBell.cs index fc7a89e6ff..071844fd1c 100644 --- a/NPCs/SunkenSea/GhostBell.cs +++ b/NPCs/SunkenSea/GhostBell.cs @@ -159,13 +159,10 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.1f, - MaxSpeed = 1f, - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.1f; + MaxSpeed = 1f; } - CreateTentacles(); NPC.ai[2]++; @@ -253,7 +250,7 @@ namespace CalamityMod.NPCs.SunkenSea // Move towards target else if (target != null) { - pathfinding.DoPathfinding(new PathfindingParameters(NPC.Center, target.Center, SunkenSeaTileValiditySizeless)); + pathfinding.DoPathfinding(new PathfindingParameters(this, NPC.Center, target.Center, SunkenSeaTileValiditySizeless)); if (pathfinding.Path.Count > 0) if (pathfinding.Path[^1].Distance(target.Center) > 300) { diff --git a/NPCs/SunkenSea/KelpieSeadragon.cs b/NPCs/SunkenSea/KelpieSeadragon.cs index 4b5185fdaf..f8e8a505e8 100644 --- a/NPCs/SunkenSea/KelpieSeadragon.cs +++ b/NPCs/SunkenSea/KelpieSeadragon.cs @@ -94,11 +94,9 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.3f, - MaxSpeed = 3f, - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.3f; + MaxSpeed = 3f; } if (NPC.direction == 0) { @@ -166,20 +164,7 @@ namespace CalamityMod.NPCs.SunkenSea NPC.ai[2] = Main.rand.Next(13, 30); // With sight, just go straight at him. Without it, try to pathfind over them. - pathfinding.DoPathfinding(new(NPC.Center, currentTarget.Center, SunkenSeaTileValidity), forceNewTask: huntReady); - pathfinding.CustomIdleBehavior = () => - { - if (currentTarget != null) - { - NPC.velocity += NPC.DirectionTo(currentTarget.Center) * pathfinding.Acceleration; - - // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; - } - else - NPC.velocity *= 0.95f; - }; + pathfinding.DoPathfinding(new(this, NPC.Center, currentTarget.Center, SunkenSeaTileValidity), forceNewTask: huntReady); NPC.ai[2]--; @@ -248,19 +233,19 @@ namespace CalamityMod.NPCs.SunkenSea // Try to manuever if there are any obstacles. if (!Main.tile[(NPC.Center + NPC.DirectionFrom(CurrentPredator.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid()) { - NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * pathfinding.Acceleration; + NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; } else { float distanceFromAvoided = Vector2.Distance(NPC.Center, CurrentPredator.Center); randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f); NPC.netUpdate = true; - pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity)); } break; } @@ -329,6 +314,27 @@ namespace CalamityMod.NPCs.SunkenSea SquishY = 1.05f; } + public override void AwaitingPathBehavior() + { + Player target = Main.player[NPC.target]; + bool hasSight = Collision.CanHitLine(NPC.Center, 1, 1, target.Center, 1, 1); + if (NPC.ai[0] == 1f && (currentTarget.Distance(NPC.Center) > 300 || !hasSight || currentTarget is NPC)) + { + if (currentTarget != null) + { + NPC.velocity += NPC.DirectionTo(currentTarget.Center) * Acceleration; + + // Cap the speed if MaxSpeed has been surpassed. + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + } + else + NPC.velocity *= 0.95f; + } + else + base.AwaitingPathBehavior(); + } + protected override bool NPCSearchFilter(NPC n) { return base.NPCSearchFilter(n) || (n == CurrentPredator || n == CurrentPrey) && Vector2.DistanceSquared(NPC.Center, n.Center) < 900f * 900f; diff --git a/NPCs/SunkenSea/LazarusLampfish.cs b/NPCs/SunkenSea/LazarusLampfish.cs index 70f8a15548..9f37b31a56 100644 --- a/NPCs/SunkenSea/LazarusLampfish.cs +++ b/NPCs/SunkenSea/LazarusLampfish.cs @@ -116,11 +116,9 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.2f, - MaxSpeed = 3f, - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.2f; + MaxSpeed = 3f; } if (NPC.direction == 0) { @@ -154,24 +152,11 @@ namespace CalamityMod.NPCs.SunkenSea NPC.ai[2] = Main.rand.Next(13, 30); // With sight, just go straight at him. Without it, try to pathfind over them. - pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), forceNewTask: huntReady); - pathfinding.CustomIdleBehavior = () => - { - if (CurrentPrey != null) - { - NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * pathfinding.Acceleration; - - // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; - } - else - NPC.velocity *= 0.95f; - }; + pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), forceNewTask: huntReady); } else { - pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity)); } break; case (int)PhaseType.Attacking: @@ -181,12 +166,12 @@ namespace CalamityMod.NPCs.SunkenSea CurrentPhase = (int)PhaseType.Idle; Timer = 0; NPC.ai[2] = 0; - pathfinding.MaxSpeed = 3; - pathfinding.Acceleration = 0.2f; + MaxSpeed = 3; + Acceleration = 0.2f; break; } - pathfinding.MaxSpeed = 8; - pathfinding.Acceleration = 0.3f; + MaxSpeed = 8; + Acceleration = 0.3f; NPC.chaseable = true; bool hasSight = Collision.CanHitLine(NPC.Center, 1, 1, currentTarget.Center, 1, 1); // If the target is too far from its shooting range or a tile is in the way, move closer @@ -197,20 +182,7 @@ namespace CalamityMod.NPCs.SunkenSea NPC.ai[2] = Main.rand.Next(13, 30); // With sight, just go straight at him. Without it, try to pathfind over them. - pathfinding.DoPathfinding(new(NPC.Center, currentTarget.Center, SunkenSeaTileValidity), forceNewTask: restart); - pathfinding.CustomIdleBehavior = () => - { - if (currentTarget != null) - { - NPC.velocity += NPC.DirectionTo(currentTarget.Center) * pathfinding.Acceleration; - - // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; - } - else - NPC.velocity *= 0.95f; - }; + pathfinding.DoPathfinding(new(this, NPC.Center, currentTarget.Center, SunkenSeaTileValidity), forceNewTask: restart); NPC.ai[2]--; } @@ -248,8 +220,8 @@ namespace CalamityMod.NPCs.SunkenSea { CurrentPhase = currentTarget != null ? (int)PhaseType.Attacking : (int)PhaseType.Idle; Timer = 0; - pathfinding.MaxSpeed = 3; - pathfinding.Acceleration = 0.2f; + MaxSpeed = 3; + Acceleration = 0.2f; NPC.ai[2] = currentTarget != null ? 0 : 120; break; } @@ -258,8 +230,8 @@ namespace CalamityMod.NPCs.SunkenSea NPC.spriteDirection = NPC.direction *= -1; } Timer++; - pathfinding.MaxSpeed = 8; - pathfinding.Acceleration = 0.4f; + MaxSpeed = 8; + Acceleration = 0.4f; if (Math.Abs(NPC.velocity.X) > 0) { @@ -274,19 +246,19 @@ namespace CalamityMod.NPCs.SunkenSea // Try to manuever if there are any obstacles. if (!Main.tile[(NPC.Center + NPC.DirectionFrom(currentTarget.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid()) { - NPC.velocity += NPC.DirectionFrom(currentTarget.Center) * pathfinding.Acceleration; + NPC.velocity += NPC.DirectionFrom(currentTarget.Center) * Acceleration; pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; } else { float distanceFromAvoided = Vector2.Distance(NPC.Center, currentTarget.Center); randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f); NPC.netUpdate = true; - pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity)); } break; } @@ -344,6 +316,26 @@ namespace CalamityMod.NPCs.SunkenSea public override bool CanBeHitByNPC(NPC attacker) => PredatorIDs.Contains(attacker.type); + public override void AwaitingPathBehavior() + { + bool hasSight = Collision.CanHitLine(NPC.Center, 1, 1, currentTarget.Center, 1, 1); + if (CurrentPhase == (int)PhaseType.Idle && CurrentPrey != null || CurrentPhase == (int)PhaseType.Attacking && currentTarget.Distance(NPC.Center) > 200 || !hasSight) + { + if (CurrentPrey != null) + { + NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; + + // Cap the speed if MaxSpeed has been surpassed. + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + } + else + NPC.velocity *= 0.95f; + } + else + base.AwaitingPathBehavior(); + } + public override void SendExtraAI(BinaryWriter writer) { writer.WriteVector2(randomPathPoint); diff --git a/NPCs/SunkenSea/PodobooKoi.cs b/NPCs/SunkenSea/PodobooKoi.cs index dddc7c97b3..130a385a49 100644 --- a/NPCs/SunkenSea/PodobooKoi.cs +++ b/NPCs/SunkenSea/PodobooKoi.cs @@ -125,11 +125,9 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.5f, - MaxSpeed = 4f, - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.5f; + MaxSpeed = 4f; } if (NPC.ai[3] <= 0) { @@ -171,7 +169,7 @@ namespace CalamityMod.NPCs.SunkenSea public void IdleBehavior() { // At random, the mob will choose a random nearby point and pathfind there. - pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), LavaTileValidityLenient)); + pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), LavaTileValidityLenient)); } /// @@ -194,29 +192,29 @@ namespace CalamityMod.NPCs.SunkenSea if (CurrentPredator == null) { CurrentBehavior = (int)PhaseType.Idle; - pathfinding.MaxSpeed = 4; + MaxSpeed = 4; return; } - pathfinding.MaxSpeed = 8; + MaxSpeed = 8; // While it doesn't have any obstacles in front of it, run away in a straight line. // Try to manuever if there are any obstacles. if (!Main.tile[(NPC.Center + NPC.DirectionFrom(CurrentPredator.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid()) { - NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * pathfinding.Acceleration; + NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; } else { float distanceFromAvoided = Vector2.Distance(NPC.Center, CurrentPredator.Center); randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f); NPC.netUpdate = true; - pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, LavaTileValidityLenient)); + pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, LavaTileValidityLenient)); } } @@ -224,13 +222,13 @@ namespace CalamityMod.NPCs.SunkenSea { if (CurrentPrey == null) { - pathfinding.MaxSpeed = 4; + MaxSpeed = 4; CurrentBehavior = (int)PhaseType.Idle; pathfinding.ClearResults(); return; } - pathfinding.MaxSpeed = 8; - pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, LavaTileValidityLenient)); + MaxSpeed = 8; + pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPrey.Center, LavaTileValidityLenient)); } public void HostileBehavior() @@ -238,7 +236,7 @@ namespace CalamityMod.NPCs.SunkenSea // Reset if (CurrentPlayer == null || !NPC.HasSight(CurrentPlayer.Center)) { - pathfinding.MaxSpeed = 4; + MaxSpeed = 4; CurrentBehavior = (int)PhaseType.Idle; NPC.ai[2] = 0; pathfinding.ClearResults(); @@ -277,7 +275,7 @@ namespace CalamityMod.NPCs.SunkenSea // Go to the location if not close enough, otherwise slow down if (NPC.Distance(destination) > distNeeded) { - pathfinding.DoPathfinding(new(NPC.Center, destination)); + pathfinding.DoPathfinding(new(this, NPC.Center, destination)); } else { @@ -292,8 +290,8 @@ namespace CalamityMod.NPCs.SunkenSea { NPC.velocity.Y = 4; } - pathfinding.MaxSpeed = 6; - pathfinding.DoPathfinding(new(NPC.Center, CurrentPlayer.Center, LavaTileValidityLenient)); + MaxSpeed = 6; + pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPlayer.Center, LavaTileValidityLenient)); // Mark the fish as currently trying to chase the player NPC.Calamity().newAI[0] = 1; } @@ -365,7 +363,7 @@ namespace CalamityMod.NPCs.SunkenSea // Air attack, shoot projectiles at the player in arches else if (useAirAI) { - pathfinding.MaxSpeed = 4; + MaxSpeed = 4; ShootTimer--; if (ShootTimer <= -40) diff --git a/NPCs/SunkenSea/PolypPanasea.cs b/NPCs/SunkenSea/PolypPanasea.cs index 8d25c15808..5abd06516d 100644 --- a/NPCs/SunkenSea/PolypPanasea.cs +++ b/NPCs/SunkenSea/PolypPanasea.cs @@ -180,11 +180,9 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.5f, - MaxSpeed = 4f, - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.5f; + MaxSpeed = 4f; } // Reset polyp index in case the polyp dies if (PolypIndex > -1) @@ -238,7 +236,7 @@ namespace CalamityMod.NPCs.SunkenSea public void IdleBehavior() { // At random, the mob will choose a random nearby point and pathfind there. - pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(100, IdleMaxPathDistance), SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(100, IdleMaxPathDistance), SunkenSeaTileValidity)); } public void HideBehavior() { @@ -253,10 +251,10 @@ namespace CalamityMod.NPCs.SunkenSea // Become invincible while hiding NPC.dontTakeDamage = true; - pathfinding.MaxSpeed = 2; + MaxSpeed = 2; // At random, the mob will choose a random nearby point and pathfind there. - pathfinding.DoPathfinding(new(NPC.Center, Main.npc[PolypIndex].Center + Main.rand.NextVector2Unit() * Main.rand.Next(20, 30), SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, Main.npc[PolypIndex].Center + Main.rand.NextVector2Unit() * Main.rand.Next(20, 30), SunkenSeaTileValidity)); } public void FleeBehavior() @@ -265,18 +263,18 @@ namespace CalamityMod.NPCs.SunkenSea if (CurrentPredator == null && PolypIndex <= -1) { CurrentBehavior = (int)PhaseType.Idle; - pathfinding.MaxSpeed = 4; + MaxSpeed = 4; return; } - pathfinding.MaxSpeed = 6; + MaxSpeed = 6; // If a polyp is found, try to run into it if (PolypIndex > -1) { NPC.netUpdate = true; Vector2 polypPos = Main.npc[PolypIndex].position; - pathfinding.DoPathfinding(new(NPC.Center, polypPos, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, polypPos, SunkenSeaTileValidity)); if (NPC.Distance(Main.npc[PolypIndex].Center) < 50) { @@ -288,19 +286,19 @@ namespace CalamityMod.NPCs.SunkenSea // Try to manuever if there are any obstacles. else if (!Main.tile[(NPC.Center + NPC.DirectionFrom(CurrentPredator.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid()) { - NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * pathfinding.Acceleration; + NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; } else { float distanceFromAvoided = Vector2.Distance(NPC.Center, CurrentPredator.Center); randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f); NPC.netUpdate = true; - pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity)); } } diff --git a/NPCs/SunkenSea/PrismBack.cs b/NPCs/SunkenSea/PrismBack.cs index 131fbe6889..6b4c6f3362 100644 --- a/NPCs/SunkenSea/PrismBack.cs +++ b/NPCs/SunkenSea/PrismBack.cs @@ -103,10 +103,8 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - MaxSpeed = 1.8f - }; + pathfinding = new PathfindingManager(this); + MaxSpeed = 1.8f; } NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); @@ -154,7 +152,7 @@ namespace CalamityMod.NPCs.SunkenSea // Go to the vine if not far enough if (tilePos.Value.Distance(NPC.Center) > 40 && BiteCount == 0) { - pathfinding.DoPathfinding(new(NPC.Center, tilePos.Value, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, tilePos.Value, SunkenSeaTileValidity)); } // Slow down and eat the kelp else @@ -189,7 +187,7 @@ namespace CalamityMod.NPCs.SunkenSea TileX = 0; TileY = 0; BiteCount = 0; - pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(200f, 800f), SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(200f, 800f), SunkenSeaTileValidity)); } } else diff --git a/NPCs/SunkenSea/PrismaticGuppy.cs b/NPCs/SunkenSea/PrismaticGuppy.cs index 71e21a9021..9d6347cd79 100644 --- a/NPCs/SunkenSea/PrismaticGuppy.cs +++ b/NPCs/SunkenSea/PrismaticGuppy.cs @@ -244,11 +244,9 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.5f, - MaxSpeed = 4f, - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.5f; + MaxSpeed = 4f; } // Spawn more guppies if a leader/naturally spawned guppy if (Role == 0 && NPC.releaseOwner == 255) @@ -280,12 +278,12 @@ namespace CalamityMod.NPCs.SunkenSea // Just do generic pathfinding if a leader. Target prey if one exists case (int)PhaseType.Idle: { - pathfinding.Acceleration = 0.5f; - pathfinding.MaxSpeed = 4; + Acceleration = 0.5f; + MaxSpeed = 4; if (CurrentPrey is not null) - pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); else - pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity)); } break; // The unenlightened masses, They cannot make the judgement call @@ -302,7 +300,7 @@ namespace CalamityMod.NPCs.SunkenSea return; if (NPC.Distance(owner.Center) > 20) - pathfinding.DoPathfinding(new(NPC.Center, owner.Center, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, owner.Center, SunkenSeaTileValidity)); else { float passiveMvtFloat = 0.5f; @@ -421,8 +419,8 @@ namespace CalamityMod.NPCs.SunkenSea { if (CurrentPredator is not null) { - pathfinding.Acceleration = 0.6f; - pathfinding.MaxSpeed = 6; + Acceleration = 0.6f; + MaxSpeed = 6; Vector2? tilePos = tilePosition; // Find a sea prism @@ -436,7 +434,7 @@ namespace CalamityMod.NPCs.SunkenSea { TileX = tilePos.Value.X; TileY = tilePos.Value.Y; - pathfinding.DoPathfinding(new(NPC.Center, tilePos.Value, SunkenSeaTileValiditySizeless)); + pathfinding.DoPathfinding(new(this, NPC.Center, tilePos.Value, SunkenSeaTileValiditySizeless)); if (NPC.Distance(tilePos.Value) < 16) { CurrentPhase = (int)PhaseType.Hiding; @@ -448,19 +446,19 @@ namespace CalamityMod.NPCs.SunkenSea // Try to manuever if there are any obstacles. else if (!Main.tile[(NPC.Center + NPC.DirectionFrom(CurrentPredator.Center) * 96).ToTileCoordinates()].IsTileSolid()) { - NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * pathfinding.Acceleration; + NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; } else { float distanceFromAvoided = Vector2.Distance(NPC.Center, CurrentPredator.Center); randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f); NPC.netUpdate = true; - pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity)); } } else diff --git a/NPCs/SunkenSea/Probesnout.cs b/NPCs/SunkenSea/Probesnout.cs index 7df2ad1bec..43d2cecb39 100644 --- a/NPCs/SunkenSea/Probesnout.cs +++ b/NPCs/SunkenSea/Probesnout.cs @@ -107,10 +107,6 @@ namespace CalamityMod.NPCs.SunkenSea public Vector2 Velocity { get => NPC.velocity; set => NPC.velocity = value; } - public float Acceleration => 0.4f; - - public float MaxSpeed => 8f; - private Vector2 SpongeFoundPosition; private bool HasEatenSponge; @@ -131,12 +127,10 @@ namespace CalamityMod.NPCs.SunkenSea public override void OnSpawn(IEntitySource source) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.4f, - MaxSpeed = 8f, - MinimumPointDistance = 60f - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.4f; + MaxSpeed = 8f; + MinimumPointDistance = 60f; CurrentBehavior = IdlingBehavior; NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; @@ -147,12 +141,10 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.4f, - MaxSpeed = 8f, - MinimumPointDistance = 60f - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.4f; + MaxSpeed = 8f; + MinimumPointDistance = 60f; } CurrentBehavior?.Invoke(); @@ -206,8 +198,8 @@ namespace CalamityMod.NPCs.SunkenSea private void IdlingBehavior() { // At random, the mob will choose a random nearby point and pathfind there. - pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(500f, 3000f), SunkenSeaTileValidity)); - pathfinding.MaxSpeed = 6f; + pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(500f, 3000f), SunkenSeaTileValidity)); + MaxSpeed = 6f; } private void FleeingBehavior() @@ -235,8 +227,8 @@ namespace CalamityMod.NPCs.SunkenSea } while (!Main.tile[(NPC.Center + _randomPathPoint).ToTileCoordinates()].IsTileSolid()); NPC.netUpdate = true; - pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + _randomPathPoint, SunkenSeaTileValidity)); - pathfinding.MaxSpeed = 8f; + pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + _randomPathPoint, SunkenSeaTileValidity)); + MaxSpeed = 8f; } else { @@ -263,21 +255,8 @@ namespace CalamityMod.NPCs.SunkenSea HuntCooldown = Main.rand.Next(13, 30); // With sight, just go straight at him. Without it, try to pathfind over them. - pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, tileValidity: SunkenSeaTileValidity), forceNewTask: huntReady); - pathfinding.MaxSpeed = 8f; - pathfinding.CustomIdleBehavior = () => - { - if (CurrentPrey != null) - { - NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * pathfinding.Acceleration; - - // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; - } - else - NPC.velocity *= 0.95f; - }; + pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPrey.Center, tileValidity: SunkenSeaTileValidity), forceNewTask: huntReady); + MaxSpeed = 8f; HuntCooldown--; } @@ -299,8 +278,8 @@ namespace CalamityMod.NPCs.SunkenSea } else { - pathfinding.DoPathfinding(new(NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity)); - pathfinding.MaxSpeed = 6f; + pathfinding.DoPathfinding(new(this, NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity)); + MaxSpeed = 6f; } } @@ -361,6 +340,25 @@ namespace CalamityMod.NPCs.SunkenSea public override bool CanBeHitByNPC(NPC attacker) => PredatorIDs.Contains(attacker.type); + public override void AwaitingPathBehavior() + { + if (CurrentBehavior == HuntBehavior) + { + if (CurrentPrey != null) + { + NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; + + // Cap the speed if MaxSpeed has been surpassed. + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + } + else + NPC.velocity *= 0.95f; + } + else + base.AwaitingPathBehavior(); + } + #endregion #region Drawing & Animation diff --git a/NPCs/SunkenSea/SeaMinnow.cs b/NPCs/SunkenSea/SeaMinnow.cs index b6161eddb8..ab8799a02f 100644 --- a/NPCs/SunkenSea/SeaMinnow.cs +++ b/NPCs/SunkenSea/SeaMinnow.cs @@ -76,11 +76,9 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.6f, - MaxSpeed = 5f, - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.6f; + MaxSpeed = 5f; } NPC owner = Main.npc[(int)NPC.ai[2]]; if (NPC.wet) @@ -208,24 +206,24 @@ namespace CalamityMod.NPCs.SunkenSea // Try to manuever if there are any obstacles. if (!Main.tile[(NPC.Center + NPC.DirectionFrom(avoidedEntity.Center) * 96).ToTileCoordinates()].IsTileSolid()) { - NPC.velocity += NPC.DirectionFrom(avoidedEntity.Center) * pathfinding.Acceleration; + NPC.velocity += NPC.DirectionFrom(avoidedEntity.Center) * Acceleration; pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; } else { float distanceFromAvoided = Vector2.Distance(NPC.Center, avoidedEntity.Center); randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f); NPC.netUpdate = true; - pathfinding.DoPathfinding(new(NPC.Center, randomPathPoint, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, randomPathPoint, SunkenSeaTileValidity)); } } else { - pathfinding.DoPathfinding(new(NPC.Center, Main.rand.NextVector2Unit() * Main.rand.Next(300, 1000), SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, Main.rand.NextVector2Unit() * Main.rand.Next(300, 1000), SunkenSeaTileValidity)); } } } @@ -235,7 +233,7 @@ namespace CalamityMod.NPCs.SunkenSea return; if (NPC.Distance(owner.Center) > 200) - pathfinding.DoPathfinding(new(NPC.Center, owner.Center, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, owner.Center, SunkenSeaTileValidity)); else { float passiveMvtFloat = 0.5f; diff --git a/NPCs/SunkenSea/Sharkoon.cs b/NPCs/SunkenSea/Sharkoon.cs index 10c5fe18f1..21095c9de8 100644 --- a/NPCs/SunkenSea/Sharkoon.cs +++ b/NPCs/SunkenSea/Sharkoon.cs @@ -217,11 +217,9 @@ namespace CalamityMod.NPCs.SunkenSea public override void OnSpawn(IEntitySource source) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.3f, - MaxSpeed = 6f, - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.3f; + MaxSpeed = 6f; CurrentBehavior = IdlingBehavior; NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; @@ -232,11 +230,9 @@ namespace CalamityMod.NPCs.SunkenSea { if (pathfinding == null) { - pathfinding = new PathfindingManager(NPC) - { - Acceleration = 0.3f, - MaxSpeed = 6f, - }; + pathfinding = new PathfindingManager(this); + Acceleration = 0.3f; + MaxSpeed = 6f; } CurrentBehavior?.Invoke(); @@ -266,7 +262,7 @@ namespace CalamityMod.NPCs.SunkenSea private void IdlingBehavior() { // At random, the mob will choose a random nearby point and pathfind there. - pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.Next(IdleMinPathDistance, IdleMaxPathDistance), SunkenSeaTileValidity)); } private void HuntingBehavior() @@ -283,20 +279,7 @@ namespace CalamityMod.NPCs.SunkenSea HuntCooldown = Main.rand.Next(13, 30); // With sight, just go straight at him. Without it, try to pathfind over them. - pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), forceNewTask: huntReady); - pathfinding.CustomIdleBehavior = () => - { - if (CurrentPrey != null) - { - NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * pathfinding.Acceleration; - - // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; - } - else - NPC.velocity *= 0.95f; - }; + pathfinding.DoPathfinding(new(this, NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), forceNewTask: huntReady); HuntCooldown--; } @@ -317,19 +300,19 @@ namespace CalamityMod.NPCs.SunkenSea // Try to manuever if there are any obstacles. if (!Main.tile[(NPC.Center + NPC.DirectionFrom(_avoidedEntity.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid()) { - NPC.velocity += NPC.DirectionFrom(_avoidedEntity.Center) * pathfinding.Acceleration; + NPC.velocity += NPC.DirectionFrom(_avoidedEntity.Center) * Acceleration; pathfinding.ClearResults(); // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.MaxSpeed; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; } else { float distanceFromAvoided = Vector2.Distance(NPC.Center, _avoidedEntity.Center); _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Utils.Remap(distanceFromAvoided, 0f, 960f, 80f, 3200f); NPC.netUpdate = true; - pathfinding.DoPathfinding(new(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); + pathfinding.DoPathfinding(new(this, NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); } // If it's capable of exploding and the predator's within distance, kaboom. @@ -409,7 +392,7 @@ namespace CalamityMod.NPCs.SunkenSea if (newBehavior == OutsideWaterBehavior) NPC.noGravity = false; - pathfinding.MinimumPointDistance = newBehavior == HuntingBehavior ? 20f : 48f; + MinimumPointDistance = newBehavior == HuntingBehavior ? 20f : 48f; } protected override void OnPreyDetection(NPC prey) @@ -528,6 +511,25 @@ namespace CalamityMod.NPCs.SunkenSea } } + public override void AwaitingPathBehavior() + { + if (CurrentBehavior == HuntingBehavior) + { + if (CurrentPrey != null) + { + NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; + + // Cap the speed if MaxSpeed has been surpassed. + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + } + else + NPC.velocity *= 0.95f; + } + else + base.AwaitingPathBehavior(); + } + public override float SpawnChance(NPCSpawnInfo spawnInfo) { if (spawnInfo.Water && !spawnInfo.Player.Calamity().clamity) diff --git a/NPCs/SunkenSea/SunkenSeaNPC.cs b/NPCs/SunkenSea/SunkenSeaNPC.cs index 0d9a00f454..79991669b4 100644 --- a/NPCs/SunkenSea/SunkenSeaNPC.cs +++ b/NPCs/SunkenSea/SunkenSeaNPC.cs @@ -2,8 +2,9 @@ using System.Collections.Generic; using System.Linq; using CalamityMod.Enums; +using CalamityMod.Pathfinding; +using CalamityMod.Pathfinding.Movements; using CalamityMod.Systems.Collections; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Xna.Framework; using Terraria; using Terraria.GameContent.Bestiary; @@ -17,10 +18,10 @@ namespace CalamityMod.NPCs.SunkenSea /// An abstract class that provides the necessary members for an NPC to function as a Sunken Sea NPC.
/// These NPCs can hunt both players and other NPCs, and maintain lists of NPCs they hunt and avoid. ///
- public abstract class SunkenSeaNPC : ModNPC + public abstract class SunkenSeaNPC : ModNPC, IPathfinder { protected PathfindingManager pathfinding = null; - + private NPC _currentPrey; private NPC _currentPredator; private Player _currentPlayer; @@ -203,7 +204,7 @@ namespace CalamityMod.NPCs.SunkenSea public static bool SunkenSeaTileValidity(NPC npc, Point point, bool accountForSize = true) { Point actualFuckingPoint = new Point(point.X * 16, point.Y * 16); - + if (accountForSize) { return npc.Hitbox.Contains(actualFuckingPoint) @@ -229,5 +230,31 @@ namespace CalamityMod.NPCs.SunkenSea || !NPC.GetIntersectingHitboxPoints( actualFuckingPoint, 10, 10).Any(a => Main.tile[a].IsTileSolidGround() || Main.tile[a].LiquidAmount < 255 || Main.tile[a].LiquidType != LiquidID.Lava); } + + #region IPathfinder Implementation + + /// + /// The acceleration this PathfindingManager will impart to its Entity when making it follow a found path.
+ /// This has no impact on the Entity's other behaviors, AI, etc. + ///
+ public float Acceleration { get; set; } = 0.2f; + + /// + /// The maximum speed this PathfindingManager allow its Entity to move at when making it follow a found path.
+ /// This has no impact on the Entity's other behaviors, AI, etc. + ///
+ public float MaxSpeed { get; set; } = 4f; + + /// + /// The minimum distance this PathdingManager requires its Entity to reach from its target point before the point is marked as "reached".
+ /// This has no impact on the Entity's other behaviors, AI, etc. + ///
+ public float MinimumPointDistance { get; set; } = 48f; + + public virtual IEnumerable Movements => [new SunkenSeaSwimMovement(NPC)]; + + public virtual void AwaitingPathBehavior() => NPC.velocity *= 0.95f; + + #endregion } } diff --git a/Pathfinding/IPathfinder.cs b/Pathfinding/IPathfinder.cs new file mode 100644 index 0000000000..da5e7c1c6f --- /dev/null +++ b/Pathfinding/IPathfinder.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using CalamityMod.Pathfinding.Movements; + +namespace CalamityMod.Pathfinding +{ + /// + /// Defines an interface for a class that can use pathfinding. + /// + public interface IPathfinder + { + /// + /// A enumerable collection of this pathfinder can use. + /// + IEnumerable Movements { get; } + + /// + /// A method that defines behavior when the pathfinding is still being calculated. + /// + void AwaitingPathBehavior(); + } +} diff --git a/Pathfinding/Movements/BaseEntityMovement.cs b/Pathfinding/Movements/BaseEntityMovement.cs new file mode 100644 index 0000000000..6cf102ef10 --- /dev/null +++ b/Pathfinding/Movements/BaseEntityMovement.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using Microsoft.Xna.Framework; +using Terraria.ModLoader; + +namespace CalamityMod.Pathfinding.Movements +{ + public abstract class BaseEntityMovement(TEntity pathfinder) : IMovement where TEntity : ModType, IPathfinder + { + public TEntity Pathfinder { get; } = pathfinder; + public abstract string RegistrationName { get; } + public abstract Func Cost { get; } + + public abstract void Start(); + public abstract bool FollowPath(Vector2 nextPoint); + public abstract IEnumerable GetDestinations(Point current); + } +} diff --git a/Pathfinding/Movements/IMovement.cs b/Pathfinding/Movements/IMovement.cs new file mode 100644 index 0000000000..2b0584d28c --- /dev/null +++ b/Pathfinding/Movements/IMovement.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using Microsoft.Xna.Framework; + +namespace CalamityMod.Pathfinding.Movements +{ + /// + /// Defines an interface for what is a movement in the context of pathfinding. + /// Every movement has a cost function, and a way to follow a path. + /// + public interface IMovement + { + /// + /// The internal name given to this movement.
+ /// Needed to differentiate between movements. + ///
+ string RegistrationName { get; } + + /// + /// The cost function of this movement.
+ /// Takes in two positions and returns the cost of the movement. + ///
+ Func Cost { get; } + + /// + /// Defines a method that is run whenever this movement starts execution.
+ /// Useful to get any variable set up for this movement's action. + ///
+ void Start(); + + /// + /// A method that defines the way to follow from one position to another. + /// + /// The destination of this movement. + /// if it this movement has finished; otherwise . + bool FollowPath(Vector2 nextPoint); + + /// + /// Defines a method to retrieve the possiblement destinations that this movement can achieve + /// + /// The starting position where this movement takes place. + /// An enumerable collection of with all the destinations. + IEnumerable GetDestinations(Point current); + } +} diff --git a/Pathfinding/Movements/Movement.cs b/Pathfinding/Movements/Movement.cs new file mode 100644 index 0000000000..072afa87ea --- /dev/null +++ b/Pathfinding/Movements/Movement.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using Microsoft.Xna.Framework; + +namespace CalamityMod.Pathfinding.Movements +{ + public abstract class Movement + { + public abstract float Cost { get; } + + public abstract bool FollowPath(IPathfinder pathfinder, Vector2 nextPoint); + + public abstract IEnumerable GetNeighborPositions(Point current); + } +} diff --git a/Pathfinding/Movements/SunkenSeaSwinMovement.cs b/Pathfinding/Movements/SunkenSeaSwinMovement.cs new file mode 100644 index 0000000000..bea2a10629 --- /dev/null +++ b/Pathfinding/Movements/SunkenSeaSwinMovement.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using CalamityMod.NPCs.SunkenSea; +using Microsoft.Xna.Framework; +using Terraria; + +namespace CalamityMod.Pathfinding.Movements +{ + public class SunkenSeaSwimMovement(NPC creature) : IMovement + { + public NPC Creature = creature; + private SunkenSeaNPC ssn => Creature.ModNPC(); + + public Func Cost => (_, _) => 0; + + public string RegistrationName => "Swim"; + + public bool FollowPath(Vector2 nextPoint) + { + // Accelerate to the target point. + Creature.velocity += (nextPoint - Creature.Center).SafeNormalize(Vector2.Zero) * ssn.Acceleration; + + // Cap the speed if MaxSpeed has been surpassed. + if (Creature.velocity.LengthSquared() > ssn.MaxSpeed * ssn.MaxSpeed) + Creature.velocity = Creature.velocity.SafeNormalize(Vector2.UnitY) * ssn.MaxSpeed; + + // If the NPC is within 48 pixels of its target point, consider the point reached. + if (Vector2.DistanceSquared(Creature.Center, nextPoint) < ssn.MinimumPointDistance * ssn.MinimumPointDistance) + return true; + + // Otherwise, continue following. + return false; + } + + public IEnumerable GetDestinations(Point current) + { + int nodeX = current.X; + int nodeY = current.Y; + foreach (var direction in CalamityUtils.Directions) + yield return new Point(nodeX + (int)direction.X, nodeY + (int)direction.Y); + } + + public void Start() { } + } +} diff --git a/Utilities/PathfindingUtils.cs b/Utilities/PathfindingUtils.cs index 56b9fae3d0..a987b06b93 100644 --- a/Utilities/PathfindingUtils.cs +++ b/Utilities/PathfindingUtils.cs @@ -1,11 +1,12 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +using CalamityMod.DataStructures; +using CalamityMod.Pathfinding; +using CalamityMod.Pathfinding.Movements; using Microsoft.Xna.Framework; using Terraria; -using Terraria.ID; using static CalamityMod.CalamityUtils; namespace CalamityMod @@ -17,6 +18,7 @@ namespace CalamityMod internal static readonly Func DefaultDistanceFunction = OctileDistance; internal static readonly Func DefaultHeuristic = OctileDistance; + internal readonly IPathfinder Pathfinder; internal readonly Vector2 Start; internal readonly Vector2 End; internal readonly Func TileValidity; @@ -24,12 +26,14 @@ namespace CalamityMod internal readonly Func Heuristic; public PathfindingParameters( + IPathfinder pathfinder, Vector2 start, Vector2 end, Func tileValidity = null, Func distanceFunction = null, Func heuristic = null) { + Pathfinder = pathfinder; Start = start; End = end; TileValidity = tileValidity; @@ -44,33 +48,31 @@ namespace CalamityMod /// Creates a new PathfindingManager for the selected entity.
/// Entities should only ever need one PathfindingManager for their lifetime, but more can be created. /// - /// The entity to pathfind for. - public class PathfindingManager(Entity e) + /// The entity to pathfind for. + public class PathfindingManager(IPathfinder p) { - public List Path { get => lastSuccessfulTask?.Result ?? []; } - + public List Path + { + get + { + if (lastSuccessfulTask == null) + return []; + else if (lastSuccessfulTask.Result == null) + return []; + else + { + var path = new List(); + foreach (var node in lastSuccessfulTask.Result) + path.Add(node.Position.ToWorldCoordinates()); + return path; + } + } + } + /// /// The entity which this PathfindingManager manages. This cannot be changed after creation. /// - internal readonly Entity entity = e; - - /// - /// The acceleration this PathfindingManager will impart to its Entity when making it follow a found path.
- /// This has no impact on the Entity's other behaviors, AI, etc. - ///
- internal float Acceleration { get; set; } = 0.2f; - - /// - /// The maximum speed this PathfindingManager allow its Entity to move at when making it follow a found path.
- /// This has no impact on the Entity's other behaviors, AI, etc. - ///
- internal float MaxSpeed { get; set; } = 4f; - - /// - /// The minimum distance this PathdingManager requires its Entity to reach from its target point before the point is marked as "reached".
- /// This has no impact on the Entity's other behaviors, AI, etc. - ///
- internal float MinimumPointDistance { get; set; } = 48f; + internal readonly IPathfinder pathfinder = p; /// /// The last completed pathfinding task that this manager has performed.
@@ -87,22 +89,6 @@ namespace CalamityMod ///
private PathfindingTask currentTask; - /// - /// You may override the path-following behavior imposed on the Entity by the PathfindingManager by providing a Func here. - ///

- /// This Func should return when the entity has reached its target point, and otherwise.
- ///
- public Func CustomFollowPath { get; set; } - - /// - /// You may override the idling behavior imposed on the Entity by the PathfindingManager by providing an Action here. - ///

- /// This Action has no parameters and no return value, and can do basically anything you want. - ///
- /// It will usually only run for a frame or two while the PathfindingManager is finding the next path to take. - ///
- public Action CustomIdleBehavior { get; set; } - /// /// Finds a path based on the specified parameters and assigns it to this manager's entity.
/// This method does not force the entity to begin following the path - it only locates a new path. @@ -125,7 +111,7 @@ namespace CalamityMod { // Case 2A: We don't care about the previous pathfinding task. We have changed our goals. // In order to trigger this behavior, you must set forceNewTask to true, and provide a different end goal position. - bool sameEndPosition = parameters.End.ToTileCoordinates() == currentTask.work.End.Position; + bool sameEndPosition = parameters.End.ToTileCoordinates() == currentTask.work.End; bool forceNewPathAttempt = forceNewTask && !sameEndPosition; if (forceNewPathAttempt) @@ -166,16 +152,19 @@ namespace CalamityMod { if (lastSuccessfulTask is null) { - IdleBehavior(); + pathfinder.AwaitingPathBehavior(); return; } - Vector2 nextPoint = lastSuccessfulTask.Result[0]; + PathfindingNode nextPoint = lastSuccessfulTask.Result[0]; // If that point is reached, it is removed from the list of points to follow. - bool nextPointReached = FollowPath(nextPoint); + bool nextPointReached = nextPoint.Move.FollowPath(nextPoint.Position.ToWorldCoordinates()); if (nextPointReached) + { + Main.NewText(lastSuccessfulTask.Result[0].Move.RegistrationName); lastSuccessfulTask.Result.RemoveAt(0); + } // If the previous successful found path has been followed to its endpoint, delete the task. if (lastSuccessfulTask.Result.Count == 0) @@ -192,51 +181,6 @@ namespace CalamityMod PathfindingBehavior(); } - private bool DefaultFollowPath(Vector2 nextPoint) - { - // Accelerate to the target point. - entity.velocity += (nextPoint - entity.Center).SafeNormalize(Vector2.Zero) * Acceleration; - - // Cap the speed if MaxSpeed has been surpassed. - if (entity.velocity.LengthSquared() > MaxSpeed * MaxSpeed) - entity.velocity = entity.velocity.SafeNormalize(Vector2.UnitY) * MaxSpeed; - - // If the entity is within 48 pixels of its target point, consider the point reached. - if (Vector2.DistanceSquared(entity.Center, nextPoint) < MinimumPointDistance * MinimumPointDistance) - return true; - - // Otherwise, continue following. - return false; - } - - /// - /// Defines how this entity should move to the next point. Contains a default implementation with basic acceleration towards the next point.
- /// This method should return when the entity has reached its target point, and otherwise.
- ///
- /// The target point is specified by - usually index 0 in the task result. - ///

- /// The behavior of this function can be completely overridden by providing a CustomFollowPath Func. - ///
- /// The next point in the path that this PathfindingManager has made. - /// Whether or not the destination has been reached. - public bool FollowPath(Vector2 nextPoint) => CustomFollowPath?.Invoke(nextPoint) ?? DefaultFollowPath(nextPoint); - - private static readonly float DefaultSlowdown = 0.95f; - private void DefaultIdleBehavior() => entity.velocity *= DefaultSlowdown; - - /// - /// Defines how this entity should behave while there is no current path to follow.
- /// By default, decelerates to a stop using the DefaultSlowdown value.
- /// This behavior will usually only run for a frame or two while the PathfindingManager is finding the next path to take. - ///
- public void IdleBehavior() - { - if (CustomIdleBehavior is not null) - CustomIdleBehavior(); - else - DefaultIdleBehavior(); - } - public void ClearResults() { currentTask = null; @@ -253,7 +197,7 @@ namespace CalamityMod /// /// The result of this pathfinding task. /// - internal List Result { get => _task.Task.Result; } + internal List Result { get => _task.Task.Result; } /// /// Whether this pathfinding task has completed running. @@ -266,7 +210,7 @@ namespace CalamityMod internal bool Running { get; private set; } = false; // Interal task representation of the work. - internal readonly TaskCompletionSource> _task = new(); + internal readonly TaskCompletionSource> _task = new(); // Internal containing object for the actual work. internal readonly PathfindingWork work = new(parameters); @@ -293,118 +237,6 @@ namespace CalamityMod #region Pathfinding Work Record - /// - /// A is a Dictionary-like data structure - /// that also keeps its entries in a binary-heap ordered by (The priority).
- /// This allows for O(log n) retrievals of the with the lowest - /// (Thanks to the MinHeap/PriorityQueue structure) and O(1) lookups of any element (Thanks to the Dictionary structure).
- /// This data structure is specially useful for graph algorithms where getting the minimum element is a constant process, like A*.
- /// It essentially combines a and a into one data structure. - ///
- /// - /// - public class HeapDict where TValue : IComparable - { - private readonly Dictionary _indexMap = []; - private readonly List<(TKey Key, TValue Value)> _heap = []; - - public int Count => _heap.Count; - - public void Add(TKey key, TValue value) - { - if (_indexMap.TryGetValue(key, out int index)) - { - TValue oldValue = _heap[index].Value; - _heap[index] = (key, value); - - int cmp = value.CompareTo(oldValue); - if (cmp < 0) - HeapifyUp(index); - else if (cmp > 0) - HeapifyDown(index); - } - else - { - _heap.Add((key, value)); - index = _heap.Count - 1; - _indexMap[key] = index; - HeapifyUp(index); - } - } - - public (TKey, TValue) PopMin() - { - if (_heap.Count == 0) - throw new InvalidOperationException("Heap is empty"); - - var min = _heap[0]; - var last = _heap[^1]; - _heap[0] = last; - _indexMap[last.Key] = 0; - _heap.RemoveAt(_heap.Count - 1); - _indexMap.Remove(min.Key); - if (_heap.Count > 0) - HeapifyDown(0); - - return min; - } - - public (TKey, TValue) PeekMin() - { - if (_heap.Count == 0) - throw new InvalidOperationException("Heap is empty"); - - return _heap[0]; - } - - private void HeapifyUp(int index) - { - while (index > 0) - { - int parent = (index - 1) / 2; - if (_heap[index].Value.CompareTo(_heap[parent].Value) >= 0) - break; - - Swap(index, parent); - index = parent; - } - } - - private void HeapifyDown(int index) - { - int lastIndex = _heap.Count - 1; - while (true) - { - int left = 2 * index + 1; - int right = 2 * index + 2; - int smallest = index; - - if (left <= lastIndex && _heap[left].Value.CompareTo(_heap[smallest].Value) < 0) - smallest = left; - - if (right <= lastIndex && _heap[right].Value.CompareTo(_heap[smallest].Value) < 0) - smallest = right; - - if (smallest == index) - break; - - Swap(index, smallest); - index = smallest; - } - } - - private void Swap(int i, int j) - { - (_heap[i], _heap[j]) = (_heap[j], _heap[i]); - _indexMap[_heap[i].Key] = i; - _indexMap[_heap[j].Key] = j; - } - - public bool ContainsKey(TKey key) => _indexMap.ContainsKey(key); - - public TValue GetValue(TKey key) => _heap[_indexMap[key]].Value; - } - /// /// Represents the working computation for a . /// @@ -421,28 +253,13 @@ namespace CalamityMod /// - : A function that estimates the cost from a given point to the end point. Defaults to .
/// /// - private record PathfindingWork(PathfindingNode Start, PathfindingNode End, Func TileValidity, Func DistanceFunction, Func Heuristic) + private record PathfindingWork(IPathfinder Pathfinder, Point Start, Point End, Func TileValidity, Func DistanceFunction, Func Heuristic) { - public PathfindingWork( - Point start, - Point end, - float minimalPointDistance, - Func tileValidity = null, - Func distanceFunction = null, - Func heuristic = null) : this( - new PathfindingNode(start), - new PathfindingNode(end), - tileValidity ?? PathfindingParameters.DefaultTileValidity, - distanceFunction ?? PathfindingParameters.DefaultDistanceFunction, - heuristic ?? PathfindingParameters.DefaultHeuristic - ) - { - } - public PathfindingWork( PathfindingParameters p) : this( - new PathfindingNode(p.Start.ToTileCoordinates()), - new PathfindingNode(p.End.ToTileCoordinates()), + p.Pathfinder, + p.Start.ToTileCoordinates(), + p.End.ToTileCoordinates(), p.TileValidity ?? PathfindingParameters.DefaultTileValidity, p.DistanceFunction ?? PathfindingParameters.DefaultDistanceFunction, p.Heuristic ?? PathfindingParameters.DefaultHeuristic @@ -457,10 +274,10 @@ namespace CalamityMod /// /// A list of positions representing the path from start to end, or if no path is found. /// - internal List CalculatePath() + internal List CalculatePath() { // Trying to pathfind to a solid tile would be a waste of resources, we don't even consider pathfinding to it. - Tile endTile = ParanoidTileRetrieval(End.Position.X, End.Position.Y); + Tile endTile = ParanoidTileRetrieval(End.X, End.Y); if (endTile.IsTileSolid()) return null; @@ -468,8 +285,12 @@ namespace CalamityMod var explored = new HashSet(); // At first, we only know the starting node. - (Start.Distance, Start.Total) = (0, Heuristic.Invoke(Start.Position, End.Position)); - candidates.Add(Start, Start.Total); + foreach (var movement in Pathfinder.Movements) + { + var start = new PathfindingNode(Start, movement); + (start.Distance, start.Total) = (0f, Heuristic.Invoke(start.Position, End)); + candidates.Add(start, start.Total); + } while (candidates.Count > 0) { @@ -477,7 +298,7 @@ namespace CalamityMod var current = candidates.PeekMin().Item1; // Check if we've reached the goal. - if (current.Position == End.Position) + if (current.Position == End) return current.ReconstructPath(); // Add the current node to the set of explored nodes so we don't have to check it again, @@ -485,7 +306,7 @@ namespace CalamityMod candidates.PopMin(); explored.Add(current); - foreach (var neighbor in current.GetNeighbors()) + foreach (var neighbor in current.GetNeighborSteps(Pathfinder)) { // If the node has already been explored or is not a valid neighbor, we can skip it. if (explored.Contains(neighbor) || Main.tile[neighbor.Position].IsTileSolid() || !TileValidity.Invoke(neighbor.Position)) @@ -499,7 +320,7 @@ namespace CalamityMod neighbor.Parent = current; neighbor.Distance = newDistance; - neighbor.Total = newDistance + Heuristic.Invoke(neighbor.Position, End.Position); + neighbor.Total = newDistance + Heuristic.Invoke(neighbor.Position, End) + neighbor.Move.Cost.Invoke(current.Position, neighbor.Position); // We put it on our heap of candidates. // If the node was already on our heap of candidates, it updates its priority. @@ -508,7 +329,7 @@ namespace CalamityMod } // If we ran out of candidates and no path was found, we return null. - return null; + return null; } } #endregion @@ -517,48 +338,41 @@ namespace CalamityMod /// /// Represents a node in a pathfinding algorithm, containing position, cost, and parent information. /// - private class PathfindingNode(Point position) + public class PathfindingNode(Point position, IMovement move) { internal Point Position { get; set; } = position; internal float Distance { get; set; } = float.MaxValue; // Cost from start to this node. internal float Total { get; set; } = float.MaxValue; // Total cost. + internal IMovement Move { get; set; } = move; internal PathfindingNode Parent { get; set; } public override bool Equals(object obj) { if (obj is PathfindingNode other) - return Position == other.Position; + return Position == other.Position && Move.RegistrationName.Equals(other.Move.RegistrationName); return false; } - public override int GetHashCode() => Position.GetHashCode(); + public override int GetHashCode() => Position.GetHashCode() ^ Move.RegistrationName.GetHashCode(); - internal List GetNeighbors() + internal IEnumerable GetNeighborSteps(IPathfinder pathfinder) { - var neighbors = new List(Directions.Count); - - int nodeX = Position.X; - int nodeY = Position.Y; - - foreach (var direction in Directions) + foreach (var movement in pathfinder.Movements) { - int newX = nodeX + (int)direction.X; - int newY = nodeY + (int)direction.Y; - - if (WorldGen.InWorld(newX, newY)) - neighbors.Add(new PathfindingNode(new Point(newX, newY))); + foreach (var neighbor in movement.GetDestinations(Position)) + { + yield return new PathfindingNode(neighbor, movement); + } } - - return neighbors; } - internal List ReconstructPath() + internal List ReconstructPath() { - var path = new List(); + var path = new List(); var current = this; while (current != null) { - path.Add(current.Position.ToWorldCoordinates()); + path.Add(current); current = current.Parent; } path.Reverse(); @@ -622,7 +436,7 @@ namespace CalamityMod Rectangle hitbox = entity.Hitbox; hitbox.Location = new Point(position.X - hitbox.Width / 2, position.Y - hitbox.Height / 2); hitbox.Inflate(fluffX, fluffY); - + int startX = (int)MathF.Floor(hitbox.Left / 16); int endX = (int)Math.Floor((hitbox.Right - float.Epsilon) / 16); int startY = (int)MathF.Floor(hitbox.Top / 16);