Merge branch '1.4.4' of https://github.com/CalamityTeam/CalamityMod into 1.4.4
This commit is contained in:
commit
6fc562efe3
11 files changed
+456
-320
No files matched your search
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using CalamityMod.NPCs;
|
||||
using CalamityMod.Particles;
|
||||
using CalamityMod.Projectiles;
|
||||
using CalamityMod.Projectiles.Typeless;
|
||||
using Microsoft.Xna.Framework;
|
||||
using Terraria;
|
||||
@@ -12,8 +13,8 @@ namespace CalamityMod.Buffs.DamageOverTime
|
||||
{
|
||||
internal const int StackFalloffFrames = 320;
|
||||
|
||||
// 150 DPS (30x5) per stack may seem low, but it gets boosted by ranged stats and can supercrit.
|
||||
internal static int BaseDamage = 30;
|
||||
// This deals 600 DPS per stack, is boosted by ranged stats and can supercrit.
|
||||
internal static int BaseDamage = 120;
|
||||
internal static int FramesPerDamageTick = 12;
|
||||
|
||||
public override void SetStaticDefaults()
|
||||
@@ -62,15 +63,20 @@ namespace CalamityMod.Buffs.DamageOverTime
|
||||
// This cannot be done with SimpleStrikeNPC because that would not allow for supercrits.
|
||||
int bleedTickDamage = (int)applicator.GetTotalDamage<RangedDamageClass>().ApplyTo(BaseDamage * cgn.somaShredStacks);
|
||||
Projectile tick = Projectile.NewProjectileDirect(target.GetSource_FromThis(), target.Center, Vector2.Zero, ModContent.ProjectileType<DirectStrike>(), bleedTickDamage, 0f, applicator.whoAmI, target.whoAmI);
|
||||
|
||||
tick.DamageType = DamageClass.Ranged; // Uncommon for DirectStrikes, but it needs to be able to crit.
|
||||
tick.Calamity().supercritHits = -1;
|
||||
|
||||
// All ticks of Shred have a 3x base crit multiplier and have supercrits enabled.
|
||||
CalamityGlobalProjectile cgp = tick.Calamity();
|
||||
cgp.supercritHits = -1;
|
||||
cgp.bonusCritDamage += 1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal static void DrawEffects(Player player)
|
||||
{
|
||||
|
||||
// TODO -- Players inflicted with Shred don't display any visuals.
|
||||
}
|
||||
|
||||
// Enemies suffering from Soma Prime's Shred spray blood like Violence
|
||||
|
||||
@@ -362,9 +362,23 @@ namespace CalamityMod.CalPlayer
|
||||
CalamityGlobalProjectile cgp = proj.Calamity();
|
||||
if (cgp.appliesSomaShred)
|
||||
{
|
||||
target.AddBuff(BuffType<Shred>(), 320);
|
||||
// This information cannot be transferred through the buff, but is necessary to calculate damage
|
||||
cgn.somaShredApplicator = Player.whoAmI;
|
||||
// 08MAR2025: Ozzatron: Obsessive Warframe accuracy.
|
||||
// Typical endgame Soma Prime builds have a 5% chance to apply debuff, then 30% extra chance if it's a crit, rolled separately.
|
||||
bool actuallyApplyShred = false;
|
||||
if (Main.rand.NextFloat() < 0.05f)
|
||||
actuallyApplyShred = true;
|
||||
if (hit.Crit && Main.rand.NextFloat() < 0.3f)
|
||||
actuallyApplyShred = true;
|
||||
|
||||
if (actuallyApplyShred)
|
||||
{
|
||||
target.AddBuff(BuffType<Shred>(), 320);
|
||||
// This information cannot be transferred through the buff, but is necessary to calculate damage
|
||||
cgn.somaShredApplicator = Player.whoAmI;
|
||||
|
||||
// 08MAR2025: Ozzatron: God Slayer Slugs can no longer apply Shred multiple times.
|
||||
cgp.appliesSomaShred = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Similarly, all shots from Animosity are also marked
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace CalamityMod.Items.Weapons.Ranged
|
||||
{
|
||||
Item.width = 94;
|
||||
Item.height = 34;
|
||||
Item.damage = 488;
|
||||
Item.damage = 705;
|
||||
Item.DamageType = DamageClass.Ranged;
|
||||
Item.useAnimation = Item.useTime = 5;
|
||||
Item.useStyle = ItemUseStyleID.Shoot;
|
||||
@@ -38,7 +38,7 @@ namespace CalamityMod.Items.Weapons.Ranged
|
||||
}
|
||||
|
||||
// Terraria seems to really dislike high crit values in SetDefaults
|
||||
public override void ModifyWeaponCrit(Player player, ref float crit) => crit += 30;
|
||||
public override void ModifyWeaponCrit(Player player, ref float crit) => crit += 26;
|
||||
|
||||
public override Vector2? HoldoutOffset() => new Vector2(-25, 0);
|
||||
|
||||
@@ -54,8 +54,12 @@ namespace CalamityMod.Items.Weapons.Ranged
|
||||
velocity.Y += Main.rand.NextFloat(-XYInaccuracy, XYInaccuracy);
|
||||
Vector2 vel = velocity;
|
||||
Projectile shot = Projectile.NewProjectileDirect(source, position, vel, type, damage, knockback, player.whoAmI);
|
||||
|
||||
// Set all projectiles fired from Soma Prime to have 3x base crit multiplier and to have supercrits enabled.
|
||||
// They also are able to apply one stack of Shred.
|
||||
CalamityGlobalProjectile cgp = shot.Calamity();
|
||||
cgp.supercritHits = -1;
|
||||
cgp.bonusCritDamage += 1f;
|
||||
cgp.appliesSomaShred = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1157,9 +1157,10 @@ SomaPrime: {
|
||||
Tooltip:
|
||||
'''
|
||||
This weapon can supercrit if its crit chance is over 100%
|
||||
All bullets fired inflict Shred, a stacking bleed debuff
|
||||
Shred deals 150 DPS per stack and scales with your ranged stats
|
||||
Damage ticks of Shred can also critically strike or supercrit
|
||||
All bullets fired have a 5% chance to inflict Shred, a stacking bleed debuff
|
||||
Critical strikes deal 3x damage instead of 2x by default and have a 30% chance to inflict Shred
|
||||
Shred deals 600 DPS per stack and scales with your ranged stats
|
||||
Damage ticks of Shred can critically strike for 3x damage and can supercrit
|
||||
Replaces musket balls with enhanced High Velocity Bullets
|
||||
80% chance to save ammo
|
||||
'''
|
||||
|
||||
@@ -6304,6 +6304,10 @@ namespace CalamityMod.NPCs
|
||||
}
|
||||
}
|
||||
|
||||
// 08MAR2025: Simplistic crit damage increase. Doesn't force a crit, though you can do that separately.
|
||||
// STACKS MULTIPLICATIVELY (!!!) with above supercrit behavior.
|
||||
modifiers.CritDamage += cgp.bonusCritDamage;
|
||||
|
||||
//
|
||||
// DAAWNLIGHT SPIRIT ORIGIN AIM IMPLEMENTATION
|
||||
//
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Xml.XPath;
|
||||
using CalamityMod.Enums;
|
||||
using CalamityMod.Items.Placeables.Banners;
|
||||
using CalamityMod.Tiles;
|
||||
@@ -18,7 +19,7 @@ using static Terraria.ModLoader.ModContent;
|
||||
|
||||
namespace CalamityMod.NPCs.SunkenSea
|
||||
{
|
||||
public class Probesnout : SunkenSeaNPC, IPathFinder
|
||||
public class Probesnout : SunkenSeaNPC
|
||||
{
|
||||
#region Members
|
||||
|
||||
@@ -94,7 +95,11 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
|
||||
private Action _previousBehavior;
|
||||
|
||||
public PathfindingTask Path { get; set; }
|
||||
private int HuntCooldown
|
||||
{
|
||||
get => (int)NPC.ai[3];
|
||||
set => NPC.ai[3] = value;
|
||||
}
|
||||
|
||||
public Vector2 Position => NPC.Center;
|
||||
|
||||
@@ -128,6 +133,12 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt();
|
||||
NPC.GravityMultiplier *= 2f;
|
||||
NPC.MaxFallSpeedMultiplier *= 2f;
|
||||
pathfinding = new PathfindingManager(NPC)
|
||||
{
|
||||
Acceleration = 0.4f,
|
||||
MaxSpeed = 8f,
|
||||
MinimumPointDistance = 60f
|
||||
};
|
||||
}
|
||||
|
||||
public override void AI()
|
||||
@@ -140,9 +151,12 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
else if (NPC.velocity.LengthSquared() != 0f)
|
||||
NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X);
|
||||
|
||||
if (Main.rand.NextBool(50) && !HasEatenSponge && CurrentBehavior == IdlingBehavior)
|
||||
if (Main.rand.NextBool(150) && !HasEatenSponge && CurrentBehavior == IdlingBehavior)
|
||||
ThreadPool.QueueUserWorkItem(_ => DetectSponges(), null);
|
||||
|
||||
if (Main.rand.NextBool(300) && HasEatenSponge && Vector2.DistanceSquared(NPC.Center, SpongeFoundPosition) > 160f * 160f)
|
||||
HasEatenSponge = false;
|
||||
|
||||
if (!NPC.wet && CurrentBehavior != OutsideWaterBehavior)
|
||||
{
|
||||
NPC.noGravity = false;
|
||||
@@ -181,14 +195,8 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
private void IdlingBehavior()
|
||||
{
|
||||
// At random, the mob will choose a random nearby point and pathfind there.
|
||||
PathfindingTask parameters = null;
|
||||
if (Main.rand.NextBool(150))
|
||||
{
|
||||
_randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * 300f;
|
||||
NPC.netUpdate = true;
|
||||
parameters = new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity);
|
||||
}
|
||||
this.DoPathfinding(parameters);
|
||||
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(500f, 3000f), SunkenSeaTileValidity));
|
||||
pathfinding.MaxSpeed = 6f;
|
||||
}
|
||||
|
||||
private void FleeingBehavior()
|
||||
@@ -210,18 +218,19 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
do
|
||||
{
|
||||
var randomNormalDirection = headedDirection.RotatedBy(MathHelper.PiOver2 * Main.rand.NextBool().ToDirectionInt());
|
||||
_randomPathPoint = randomNormalDirection.RotatedByRandom(MathHelper.PiOver4);
|
||||
_randomPathPoint = randomNormalDirection.RotatedByRandom(MathHelper.PiOver4 * 0.7f);
|
||||
if (!Main.tile[(NPC.Center + _randomPathPoint).ToTileCoordinates()].IsTileSolid())
|
||||
break;
|
||||
}
|
||||
while (!Main.tile[(NPC.Center + _randomPathPoint).ToTileCoordinates()].IsTileSolid());
|
||||
NPC.netUpdate = true;
|
||||
this.DoPathfinding(new PathfindingTask(NPC.Center, NPC.Center + _randomPathPoint, SunkenSeaTileValidity));
|
||||
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + _randomPathPoint, SunkenSeaTileValidity));
|
||||
pathfinding.MaxSpeed = 8f;
|
||||
}
|
||||
else
|
||||
{
|
||||
NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration;
|
||||
Path = null;
|
||||
pathfinding.ClearResults();
|
||||
|
||||
// Cap the speed if MaxSpeed has been surpassed.
|
||||
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
|
||||
@@ -238,8 +247,28 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
return;
|
||||
}
|
||||
|
||||
bool huntReady = HuntCooldown == 0;
|
||||
if (huntReady)
|
||||
HuntCooldown = Main.rand.Next(13, 30);
|
||||
|
||||
// With sight, just go straight at him. Without it, try to pathfind over them.
|
||||
this.DoPathfinding(new PathfindingTask(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), continuouslyUpdatePath: true);
|
||||
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;
|
||||
};
|
||||
|
||||
HuntCooldown--;
|
||||
}
|
||||
|
||||
private void EatingBehavior()
|
||||
@@ -253,11 +282,15 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
HasEatenSponge = true;
|
||||
Animation = AnimationState.Idle;
|
||||
CurrentBehavior = IdlingBehavior;
|
||||
SpongeFoundPosition = Vector2.Zero;
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
this.DoPathfinding(new PathfindingTask(NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity));
|
||||
{
|
||||
pathfinding.DoPathfinding(new(NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity));
|
||||
pathfinding.MaxSpeed = 6f;
|
||||
}
|
||||
}
|
||||
|
||||
private void OutsideWaterBehavior()
|
||||
@@ -271,60 +304,39 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
|
||||
private void DetectSponges()
|
||||
{
|
||||
Vector2? closestSpongeFound = null;
|
||||
float closestDistanceSquared = float.MaxValue;
|
||||
|
||||
foreach (var direction in Directions)
|
||||
Vector2? spongeFoundPosition = null;
|
||||
int? tileIndexFound = null;
|
||||
for (int i = 0; i < 360 && spongeFoundPosition == null; i += 15)
|
||||
{
|
||||
// var points = GetIntersectingPoints(NPC.Center, NPC.Center + direction * 360f);
|
||||
var points = new Point[1];
|
||||
foreach (var point in points)
|
||||
var points = GetIntersectingPointsInLine(NPC.Center, NPC.Center - Vector2.UnitY.RotatedBy(MathHelper.ToRadians(i)) * 360f);
|
||||
for (int j = points.Count - 1; j >= 0; j--)
|
||||
{
|
||||
// Check if the tile coordinates are within the valid range
|
||||
if (!WorldGen.InWorld(point.X, point.Y))
|
||||
continue;
|
||||
|
||||
// Check if the current tile is AerialiteBrick
|
||||
if (Main.tile[point].TileType == TileType<AerialiteBrick>())
|
||||
if (Main.tile[points[j]].TileType == TileType<AerialiteBrick>())
|
||||
{
|
||||
// Check all adjacent directions for a non-solid tile with line of sight
|
||||
foreach (var adjacentDirection in Directions)
|
||||
{
|
||||
Point adjacentPoint = point + adjacentDirection.ToPoint();
|
||||
|
||||
// Validate adjacent tile coordinates
|
||||
if (!WorldGen.InWorld(adjacentPoint.X, adjacentPoint.Y))
|
||||
continue;
|
||||
|
||||
// Skip if the adjacent tile is solid
|
||||
if (Main.tile[adjacentPoint].IsTileSolid())
|
||||
continue;
|
||||
|
||||
Vector2 worldPos = adjacentPoint.ToWorldCoordinates();
|
||||
if (NPC.HasSight(worldPos))
|
||||
{
|
||||
// Calculate the squared distance from NPC to the adjacent tile
|
||||
float distanceSquared = Vector2.DistanceSquared(NPC.Center, worldPos);
|
||||
if (distanceSquared < closestDistanceSquared)
|
||||
{
|
||||
closestDistanceSquared = distanceSquared;
|
||||
closestSpongeFound = worldPos;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Break after checking the first sponge nutrient in this direction
|
||||
tileIndexFound = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (tileIndexFound == null)
|
||||
continue;
|
||||
|
||||
for (int k = tileIndexFound.Value; k >= 0; k--)
|
||||
{
|
||||
Vector2 worldPos = points[k].ToWorldCoordinates();
|
||||
if (NPC.HasSight(worldPos) && SunkenSeaTileValidity(points[k]))
|
||||
{
|
||||
CurrentBehavior = EatingBehavior;
|
||||
spongeFoundPosition = worldPos;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
tileIndexFound = null;
|
||||
}
|
||||
|
||||
// Update behavior if a valid tile was found
|
||||
if (closestSpongeFound.HasValue)
|
||||
{
|
||||
CurrentBehavior = EatingBehavior;
|
||||
SpongeFoundPosition = closestSpongeFound.Value;
|
||||
}
|
||||
if (spongeFoundPosition.HasValue)
|
||||
SpongeFoundPosition = spongeFoundPosition.Value;
|
||||
}
|
||||
|
||||
public override void HitEffect(NPC.HitInfo hit)
|
||||
@@ -385,8 +397,8 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
public override void SetDefaults()
|
||||
{
|
||||
base.SetDefaults();
|
||||
|
||||
// BannerItem = ItemType<ProbesnoutBanner>();
|
||||
|
||||
BannerItem = ItemType<ProbesnoutBanner>();
|
||||
|
||||
NPC.lifeMax = 5;
|
||||
|
||||
|
||||
+46
-47
@@ -18,7 +18,7 @@ using static Terraria.ModLoader.ModContent;
|
||||
|
||||
namespace CalamityMod.NPCs.SunkenSea
|
||||
{
|
||||
public class Sharkoon : SunkenSeaNPC, IPathFinder
|
||||
public class Sharkoon : SunkenSeaNPC
|
||||
{
|
||||
#region Fields & Properties
|
||||
|
||||
@@ -99,7 +99,7 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
/// <summary>
|
||||
/// The squish of this NPC while drawing.
|
||||
/// </summary>
|
||||
private Vector2 _scaleSquish = Vector2.One;
|
||||
private Vector2 ScaleSquish = Vector2.One;
|
||||
|
||||
private Entity _avoidedEntity;
|
||||
|
||||
@@ -133,6 +133,12 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
|
||||
private Action _previousBehavior;
|
||||
|
||||
private int HuntCooldown
|
||||
{
|
||||
get => (int)NPC.ai[3];
|
||||
set => NPC.ai[3] = value;
|
||||
}
|
||||
|
||||
#region SunkenSeaNPC Implementation
|
||||
|
||||
protected override List<int> PreyIDs =>
|
||||
@@ -157,20 +163,6 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
|
||||
#endregion
|
||||
|
||||
#region IPathFinder Implementation
|
||||
|
||||
public PathfindingTask Path { get; set; }
|
||||
|
||||
public Vector2 Position => NPC.Center;
|
||||
|
||||
public Vector2 Velocity { get => NPC.velocity; set => NPC.velocity = value; }
|
||||
|
||||
public float Acceleration { get; set; } = 0.25f;
|
||||
|
||||
public float MaxSpeed { get; set; } = 6f;
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
#region SetDefaults
|
||||
@@ -185,7 +177,7 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
{
|
||||
base.SetDefaults();
|
||||
|
||||
// BannerItem = ItemType<SharkoonBanner>();
|
||||
BannerItem = ItemType<SharkoonBanner>();
|
||||
|
||||
NPC.damage = 20;
|
||||
NPC.lifeMax = 350;
|
||||
@@ -223,6 +215,11 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
|
||||
public override void OnSpawn(IEntitySource source)
|
||||
{
|
||||
pathfinding = new PathfindingManager(NPC)
|
||||
{
|
||||
Acceleration = 0.3f,
|
||||
MaxSpeed = 6f,
|
||||
};
|
||||
CurrentBehavior = IdlingBehavior;
|
||||
NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt();
|
||||
NPC.GravityMultiplier *= 2f;
|
||||
@@ -250,25 +247,14 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
CurrentBehavior = OutsideWaterBehavior;
|
||||
|
||||
// Reset any squish that is done to the Sharkoon.
|
||||
if (_scaleSquish.Y > 1f)
|
||||
{
|
||||
_scaleSquish.Y -= 0.025f;
|
||||
if (_scaleSquish.Y < 1f)
|
||||
_scaleSquish.Y = 1f;
|
||||
}
|
||||
if (ScaleSquish.Y > 1f)
|
||||
ScaleSquish.Y = Math.Max(1f, ScaleSquish.Y - 0.025f);
|
||||
}
|
||||
|
||||
private void IdlingBehavior()
|
||||
{
|
||||
// At random, the mob will choose a random nearby point and pathfind there.
|
||||
PathfindingTask task = null;
|
||||
if (Main.rand.NextBool(IdleRandomMovementUnlikeliness))
|
||||
{
|
||||
_randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance);
|
||||
NPC.netUpdate = true;
|
||||
task = new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity);
|
||||
}
|
||||
this.DoPathfinding(task);
|
||||
pathfinding.DoPathfinding(new(NPC.Center, NPC.Center + Main.rand.NextVector2Unit() * 2000f, SunkenSeaTileValidity));
|
||||
}
|
||||
|
||||
private void HuntingBehavior()
|
||||
@@ -280,15 +266,27 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
return;
|
||||
}
|
||||
|
||||
bool huntReady = HuntCooldown == 0;
|
||||
if (huntReady)
|
||||
HuntCooldown = Main.rand.Next(13, 30);
|
||||
|
||||
// With sight, just go straight at him. Without it, try to pathfind over them.
|
||||
if (!NPC.HasSight(CurrentPrey.Center))
|
||||
this.DoPathfinding(new PathfindingTask(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity));
|
||||
else
|
||||
pathfinding.DoPathfinding(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), forceNewTask: huntReady);
|
||||
pathfinding.CustomIdleBehavior = () =>
|
||||
{
|
||||
NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration;
|
||||
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
|
||||
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
|
||||
}
|
||||
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;
|
||||
};
|
||||
|
||||
HuntCooldown--;
|
||||
}
|
||||
|
||||
private void FleeingBehavior()
|
||||
@@ -307,18 +305,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) * Acceleration;
|
||||
NPC.velocity += NPC.DirectionFrom(_avoidedEntity.Center) * pathfinding.Acceleration;
|
||||
pathfinding.ClearResults();
|
||||
|
||||
// Cap the speed if MaxSpeed has been surpassed.
|
||||
if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed)
|
||||
NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed;
|
||||
if (NPC.velocity.LengthSquared() > pathfinding.MaxSpeed * pathfinding.MaxSpeed)
|
||||
NPC.velocity = Vector2.Normalize(NPC.velocity) * pathfinding.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;
|
||||
this.DoPathfinding(new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity));
|
||||
pathfinding.DoPathfinding(new(NPC.Center, _randomPathPoint, SunkenSeaTileValidity));
|
||||
}
|
||||
|
||||
// If it's capable of exploding and the predator's within distance, kaboom.
|
||||
@@ -398,7 +397,7 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
if (newBehavior == OutsideWaterBehavior)
|
||||
NPC.noGravity = false;
|
||||
|
||||
Path = null;
|
||||
pathfinding.MinimumPointDistance = newBehavior == HuntingBehavior ? 20f : 48f;
|
||||
}
|
||||
|
||||
protected override void OnPreyDetection(NPC prey)
|
||||
@@ -407,7 +406,7 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
if (CanExplode && CurrentPredator is null && !IsExploding)
|
||||
{
|
||||
CurrentBehavior = HuntingBehavior;
|
||||
_scaleSquish.Y += 0.4f;
|
||||
ScaleSquish.Y += 0.4f;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -418,7 +417,7 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
{
|
||||
CurrentBehavior = FleeingBehavior;
|
||||
_avoidedEntity = predator;
|
||||
_scaleSquish.Y += 0.4f;
|
||||
ScaleSquish.Y += 0.4f;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -430,7 +429,7 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
|
||||
CurrentBehavior = FleeingBehavior;
|
||||
_avoidedEntity = player;
|
||||
_scaleSquish.Y += 0.4f;
|
||||
ScaleSquish.Y += 0.4f;
|
||||
}
|
||||
|
||||
public override void HitEffect(NPC.HitInfo hit)
|
||||
@@ -552,7 +551,7 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
Vector2 anchorPoint = frame.Size() * 0.5f;
|
||||
SpriteEffects flip = NPC.spriteDirection == -1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None;
|
||||
|
||||
spriteBatch.Draw(texture, drawPosition, frame, NPC.GetAlpha(drawColor), NPC.rotation, anchorPoint, _scaleSquish, flip, 0f);
|
||||
spriteBatch.Draw(texture, drawPosition, frame, NPC.GetAlpha(drawColor), NPC.rotation, anchorPoint, ScaleSquish, flip, 0f);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
/// </summary>
|
||||
public abstract class SunkenSeaNPC : ModNPC
|
||||
{
|
||||
protected PathfindingManager pathfinding = null;
|
||||
|
||||
private NPC _currentPrey;
|
||||
private NPC _currentPredator;
|
||||
private Player _currentPlayer;
|
||||
@@ -188,7 +190,7 @@ namespace CalamityMod.NPCs.SunkenSea
|
||||
Point actualFuckingPoint = new Point(point.X * 16, point.Y * 16);
|
||||
return NPC.Hitbox.Contains(actualFuckingPoint)
|
||||
|| !NPC.GetIntersectingHitboxPoints(
|
||||
actualFuckingPoint, 10, 10).Any(a => Main.tile[a].IsTileSolid() || Main.tile[a].LiquidAmount < 255 || Main.tile[a].LiquidType != LiquidID.Water);
|
||||
actualFuckingPoint, 10, 10).Any(a => Main.tile[a].IsTileSolidGround() || Main.tile[a].LiquidAmount < 255 || Main.tile[a].LiquidType != LiquidID.Water);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,15 @@ namespace CalamityMod.Projectiles
|
||||
/// </summary>
|
||||
public int supercritHits = 0;
|
||||
|
||||
// TODO -- In the TML 1.4.4 port, there is a much better way to set NPC strike events to be forced crits.
|
||||
/// <summary>
|
||||
/// Bonus damage on critical strikes expressed as a ratio. <br />
|
||||
/// 0f = 200% crit damage, vanilla standard.<br />
|
||||
/// 1f = 300% crit damage.<br /><br />
|
||||
/// This applies independently of supercrits and will stack additively with them.
|
||||
/// </summary>
|
||||
public float bonusCritDamage = 0f;
|
||||
|
||||
// 08MAR2025: This remains so that "delayed forced crits" can still be set. This is used for Marksman Ricoshots.
|
||||
/// <summary> Set to true to force a projectile to critically strike. </summary>
|
||||
public bool forcedCrit = false;
|
||||
|
||||
|
||||
@@ -86,10 +86,6 @@ namespace CalamityMod.Projectiles.Ranged
|
||||
HasPlayedSound = true;
|
||||
}
|
||||
|
||||
// This projectile is forced to critically strike.
|
||||
// This technically is a nerf, as it makes DSO's crits deal less damage.
|
||||
Projectile.Calamity().forcedCrit = true;
|
||||
|
||||
Lighting.AddLight(Projectile.Center, Color.White.ToVector3());
|
||||
if (Projectile.frameCounter >= Projectile.extraUpdates * 2)
|
||||
{
|
||||
@@ -173,6 +169,10 @@ namespace CalamityMod.Projectiles.Ranged
|
||||
return false;
|
||||
}
|
||||
|
||||
// This projectile is forced to critically strike.
|
||||
// This technically is a nerf, as it makes DSO's crits deal less damage.
|
||||
public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) => modifiers.SetCrit();
|
||||
|
||||
public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType<MiracleBlight>(), 300);
|
||||
|
||||
public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType<MiracleBlight>(), 300);
|
||||
|
||||
+277
-191
@@ -2,212 +2,300 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CalamityMod.Projectiles.Typeless;
|
||||
using Microsoft.Xna.Framework;
|
||||
using Terraria;
|
||||
using static CalamityMod.CalamityUtils;
|
||||
|
||||
namespace CalamityMod
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents an entity that is capable of finding and following a complex path.<br/>
|
||||
/// To use this interface, supply all of the required properties, and then simply call <c>this.DoPathfinding()</c> in your entity's movement logic.
|
||||
/// </summary>
|
||||
public interface IPathFinder
|
||||
#region Pathfinding Parameters
|
||||
public readonly struct PathfindingParameters
|
||||
{
|
||||
internal static readonly Func<Point, bool> DefaultTileValidity = point => true;
|
||||
internal static readonly Func<Point, Point, float> DefaultDistanceFunction = OctileDistance;
|
||||
internal static readonly Func<Point, Point, float> DefaultHeuristic = OctileDistance;
|
||||
|
||||
internal readonly Vector2 Start;
|
||||
internal readonly Vector2 End;
|
||||
internal readonly Func<Point, bool> TileValidity;
|
||||
internal readonly Func<Point, Point, float> DistanceFunction;
|
||||
internal readonly Func<Point, Point, float> Heuristic;
|
||||
|
||||
public PathfindingParameters(
|
||||
Vector2 start,
|
||||
Vector2 end,
|
||||
Func<Point, bool> tileValidity = null,
|
||||
Func<Point, Point, float> distanceFunction = null,
|
||||
Func<Point, Point, float> heuristic = null)
|
||||
{
|
||||
Start = start;
|
||||
End = end;
|
||||
TileValidity = tileValidity;
|
||||
DistanceFunction = distanceFunction;
|
||||
Heuristic = heuristic;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Pathfinding Manager
|
||||
/// <summary>
|
||||
/// Creates a new PathfindingManager for the selected entity.<br />
|
||||
/// Entities should only ever need one PathfindingManager for their lifetime, but more can be created.
|
||||
/// </summary>
|
||||
/// <param name="e">The entity to pathfind for.</param>
|
||||
public class PathfindingManager(Entity e)
|
||||
{
|
||||
public List<Vector2> Path { get => lastSuccessfulTask?.Result ?? []; }
|
||||
|
||||
/// <summary>
|
||||
/// The entity which this PathfindingManager manages. This cannot be changed after creation.
|
||||
/// </summary>
|
||||
internal readonly Entity entity = e;
|
||||
|
||||
/// <summary>
|
||||
/// The acceleration this PathfindingManager will impart to its Entity when making it follow a found path.<br />
|
||||
/// This has no impact on the Entity's other behaviors, AI, etc.
|
||||
/// </summary>
|
||||
internal float Acceleration { get; set; } = 0.2f;
|
||||
|
||||
/// <summary>
|
||||
/// The maximum speed this PathfindingManager allow its Entity to move at when making it follow a found path.<br />
|
||||
/// This has no impact on the Entity's other behaviors, AI, etc.
|
||||
/// </summary>
|
||||
internal float MaxSpeed { get; set; } = 4f;
|
||||
|
||||
/// <summary>
|
||||
/// The minimum distance this PathdingManager requires its Entity to reach from its target point before the point is marked as "reached".<br />
|
||||
/// This has no impact on the Entity's other behaviors, AI, etc.
|
||||
/// </summary>
|
||||
internal float MinimumPointDistance { get; set; } = 48f;
|
||||
|
||||
/// <summary>
|
||||
/// The last completed pathfinding task that this manager has performed.<br />
|
||||
/// This is kept in place so that the entity may continue to follow its last successful path while calculating a new one.<br />
|
||||
/// <br />
|
||||
/// This task will always be in a Completed state with a valid Result.
|
||||
/// </summary>
|
||||
private PathfindingTask lastSuccessfulTask;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the working task for calculating this entity's complex path.<br/>
|
||||
/// <br/>
|
||||
/// If you want to manually access the result of this task, make sure to check <see cref="PathfindingTask.Ready"/> before accessing the value of <see cref="PathfindingTask.Result"/>.<br/>
|
||||
/// <br/>
|
||||
/// Accessing <see cref="PathfindingTask.Result"/> before execution has completed will result in the calling thread being blocked until execution is complete.
|
||||
/// </summary>
|
||||
public PathfindingTask Path { get; set; }
|
||||
private PathfindingTask currentTask;
|
||||
|
||||
/// <summary>
|
||||
/// The current position of this entity. Only used to calculate movement for this entity, not pathfinding.<br/>
|
||||
/// In most cases, this should look like the following, where <c>ENTITY</c> is replace by your entity instance.
|
||||
/// <code>public Vector2 Position { get => ENTITY.center; }</code>
|
||||
/// You may override the path-following behavior imposed on the Entity by the PathfindingManager by providing a Func here.
|
||||
/// <br /><br />
|
||||
/// This Func should return <see langword="true"/> when the entity has reached its target point, and <see langword="false"/> otherwise.<br/>
|
||||
/// </summary>
|
||||
public Vector2 Position { get; }
|
||||
public Func<Vector2, bool> CustomFollowPath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The current velocity of this entity. Only used to calculate movement for this entity, not pathfinding.<br/>
|
||||
/// In most cases, this should look like the following, where <c>ENTITY</c> is replace by your entity instance.
|
||||
/// <code>public Vector2 Velocity { get => ENTITY.velocity; }</code>
|
||||
/// You may override the idling behavior imposed on the Entity by the PathfindingManager by providing an Action here.
|
||||
/// <br /><br />
|
||||
/// This Action has no parameters and no return value, and can do basically anything you want.
|
||||
/// <br />
|
||||
/// It will usually only run for a frame or two while the PathfindingManager is finding the next path to take.
|
||||
/// </summary>
|
||||
public Vector2 Velocity { get; set; }
|
||||
public Action CustomIdleBehavior { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The acceleration this entity should use when moving. Only used to calculate movement for this entity, not pathfinding.
|
||||
/// Finds a path based on the specified parameters and assigns it to this manager's entity.<br/>
|
||||
/// This method does not force the entity to begin following the path - it only locates a new path.
|
||||
/// </summary>
|
||||
public float Acceleration { get; }
|
||||
public void FindPath(PathfindingParameters parameters, bool forceNewTask = true)
|
||||
{
|
||||
var potentialNewTask = new PathfindingTask(parameters);
|
||||
|
||||
// Case 1: No current pathfinding task.
|
||||
// Set the current task to be the potential new task.
|
||||
if (currentTask is null)
|
||||
{
|
||||
currentTask = potentialNewTask;
|
||||
currentTask.Run();
|
||||
}
|
||||
|
||||
// Case 2: Current task exists and is currently running.
|
||||
// Make the Entity idle and continue to await results.
|
||||
if (currentTask.Running)
|
||||
{
|
||||
// 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 forceNewPathAttempt = forceNewTask && !sameEndPosition;
|
||||
|
||||
if (forceNewPathAttempt)
|
||||
{
|
||||
currentTask = potentialNewTask;
|
||||
currentTask.Run();
|
||||
}
|
||||
|
||||
// Regardles of whether a new pathing execution is forced, the entity will continue to behave based on any previous successful pathing.
|
||||
// Its calculations have not finished.
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 3: Current task exists, but is not currently running.
|
||||
// There are two reasons why this can be the case.
|
||||
bool previousTaskHadNoResult = currentTask.Result is null;
|
||||
bool previousTaskPathFollowed = (currentTask.Result?.Count ?? -1) == 0;
|
||||
// The third case is that you are forcing it to start a new task, either to the same or a new destination.
|
||||
|
||||
// Regardless of which reason the pathfinding has ended, start the new task.
|
||||
if (previousTaskHadNoResult || previousTaskPathFollowed || forceNewTask)
|
||||
{
|
||||
currentTask = potentialNewTask;
|
||||
currentTask.Run();
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 4: "Your paths found."
|
||||
// The pathfinding task has completed its execution and a valid path has been found.
|
||||
// Lock in that successful pathfinding task so the entity may consume its results.
|
||||
lastSuccessfulTask = currentTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The maximum speed this entity should be able to reach while moving. Only used to calculate movement for this entity, not pathfinding.
|
||||
/// Glue code to cause the Entity to either follow its last successful path, or idle.
|
||||
/// </summary>
|
||||
public float MaxSpeed { get; }
|
||||
public void PathfindingBehavior()
|
||||
{
|
||||
if (lastSuccessfulTask is null)
|
||||
{
|
||||
IdleBehavior();
|
||||
return;
|
||||
}
|
||||
|
||||
Vector2 nextPoint = lastSuccessfulTask.Result[0];
|
||||
|
||||
// If that point is reached, it is removed from the list of points to follow.
|
||||
bool nextPointReached = FollowPath(nextPoint);
|
||||
if (nextPointReached)
|
||||
lastSuccessfulTask.Result.RemoveAt(0);
|
||||
|
||||
// If the previous successful found path has been followed to its endpoint, delete the task.
|
||||
if (lastSuccessfulTask.Result.Count == 0)
|
||||
lastSuccessfulTask = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines how this entity should move to the next point. Contains a default implementation with basic acceleration towards the next point.<br/>
|
||||
/// This method should return <see langword="true"/> when the entity has reached its target point, and <see langword="false"/> otherwise.<br/>
|
||||
/// <br/>
|
||||
/// The target point is specified by <paramref name="nextPoint"/> - usually index 0 in the <see cref="Paths"/> task result.
|
||||
/// Performs appropriate "path-finding behavior" for the Entity this PathfindingManager is attached to.<br />
|
||||
/// This method is intended to be called every frame that you want the Entity to obey its pathfinding logic.
|
||||
/// </summary>
|
||||
/// <param name="nextPoint"></param>
|
||||
/// <returns></returns>
|
||||
public bool FollowPath(Vector2 nextPoint)
|
||||
public void DoPathfinding(PathfindingParameters parameters, bool forceNewTask = false)
|
||||
{
|
||||
FindPath(parameters, forceNewTask);
|
||||
PathfindingBehavior();
|
||||
}
|
||||
|
||||
private bool DefaultFollowPath(Vector2 nextPoint)
|
||||
{
|
||||
// Accelerate to the target point.
|
||||
Velocity += (nextPoint - Position).SafeNormalize(Vector2.Zero) * Acceleration;
|
||||
entity.velocity += (nextPoint - entity.Center).SafeNormalize(Vector2.Zero) * Acceleration;
|
||||
|
||||
// Cap the speed if MaxSpeed has been surpassed.
|
||||
if (Velocity.LengthSquared() > MaxSpeed * MaxSpeed)
|
||||
Velocity = Velocity.SafeNormalize(Vector2.UnitY) * MaxSpeed;
|
||||
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(Position, nextPoint) < 48f * 48f)
|
||||
if (Vector2.DistanceSquared(entity.Center, nextPoint) < MinimumPointDistance * MinimumPointDistance)
|
||||
return true;
|
||||
|
||||
// Otherwise, continue following.
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defines how this entity should move to the next point. Contains a default implementation with basic acceleration towards the next point.<br/>
|
||||
/// This method should return <see langword="true"/> when the entity has reached its target point, and <see langword="false"/> otherwise.<br/>
|
||||
/// <br/>
|
||||
/// The target point is specified by <paramref name="nextPoint"/> - usually index 0 in the <see cref="Paths"/> task result.
|
||||
/// <br /><br />
|
||||
/// The behavior of this function can be completely overridden by providing a CustomFollowPath Func.
|
||||
/// </summary>
|
||||
/// <param name="nextPoint">The next point in the path that this PathfindingManager has made.</param>
|
||||
/// <returns>Whether or not the destination has been reached.</returns>
|
||||
public bool FollowPath(Vector2 nextPoint) => CustomFollowPath?.Invoke(nextPoint) ?? DefaultFollowPath(nextPoint);
|
||||
|
||||
private static readonly float DefaultSlowdown = 0.95f;
|
||||
private void DefaultIdleBehavior() => entity.velocity *= DefaultSlowdown;
|
||||
|
||||
/// <summary>
|
||||
/// Defines how this entity should behave while there is no current path to follow.<br/>
|
||||
/// By default, decelerates and stops based on <see cref="Acceleration"/>.
|
||||
/// By default, decelerates to a stop using the DefaultSlowdown value.<br />
|
||||
/// This behavior will usually only run for a frame or two while the PathfindingManager is finding the next path to take.
|
||||
/// </summary>
|
||||
public void IdleBehavior() => Velocity *= 0.95f;
|
||||
|
||||
/// <summary>
|
||||
/// Assigns the value of <see cref="Paths"/> to <paramref name="pathfindingTask"/> and executes the pathfinding calculations on a background thread.<br/>
|
||||
/// You can override this to do your own modifications to the pathfinding task before assigning and starting the calculations.
|
||||
/// </summary>
|
||||
public void FindPath(PathfindingTask pathfindingTask)
|
||||
public void IdleBehavior()
|
||||
{
|
||||
if (pathfindingTask == null)
|
||||
return;
|
||||
|
||||
Path = pathfindingTask;
|
||||
Path.Run();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a task for calculating a complex path.<br/>
|
||||
/// Allows for synchronous access to an asynchronous execution state, while still providing blocking access where needed.
|
||||
/// </summary>
|
||||
public class PathfindingTask(
|
||||
Vector2 start,
|
||||
Vector2 end,
|
||||
Func<Point, bool> tileValidity = null,
|
||||
Func<Point, Point, float> distanceFunction = null,
|
||||
Func<Point, Point, float> heuristic = null)
|
||||
{
|
||||
public PathfindingTask(Vector2 start, Vector2 end) : this(start, end, null, null, null)
|
||||
{ }
|
||||
|
||||
/// <summary>
|
||||
/// The result of this pathfinding task.
|
||||
/// </summary>
|
||||
public List<Vector2> Result { get => _task.Task.Result; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether this pathfinding task has completed running.
|
||||
/// </summary>
|
||||
public bool Ready { get; private set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Whether this pathfinding task is still currently running.
|
||||
/// </summary>
|
||||
public bool Running { get; private set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// The starting position of this pathfinding task.
|
||||
/// </summary>
|
||||
public Vector2 StartPosition { get; init; } = start;
|
||||
|
||||
/// <summary>
|
||||
/// The ending position of this pathfinding task.
|
||||
/// </summary>
|
||||
public Vector2 EndPosition { get; init; } = end;
|
||||
|
||||
// Interal task representation of the work.
|
||||
private readonly TaskCompletionSource<List<Vector2>> _task = new();
|
||||
|
||||
// Internal containing object for the actual work.
|
||||
private readonly PathfindingWork _work = new(start, end, tileValidity, distanceFunction, heuristic);
|
||||
|
||||
/// <summary>
|
||||
/// Begins execution of this pathfinding task on a background thread.
|
||||
/// </summary>
|
||||
public void Run()
|
||||
{
|
||||
Running = true;
|
||||
|
||||
ThreadPool.QueueUserWorkItem((pathfindingTask) =>
|
||||
{
|
||||
var task = pathfindingTask as PathfindingTask;
|
||||
task._task.TrySetResult(task._work.CalculatePath());
|
||||
|
||||
task.Ready = true;
|
||||
task.Running = false;
|
||||
},
|
||||
this);
|
||||
}
|
||||
}
|
||||
|
||||
public static partial class CalamityUtils
|
||||
{
|
||||
/// <summary>
|
||||
/// Causes this <see cref="IPathFinder"/> to perform path finding and follow the path result, idling when a path is not available.<br/>
|
||||
/// This method should be called every frame that you want your entity to follow it's pathfinding logic.
|
||||
/// </summary>
|
||||
public static void DoPathfinding(this IPathFinder pathfinder, Vector2 target) => pathfinder.DoPathfinding(new PathfindingTask(pathfinder.Position, target));
|
||||
|
||||
/// <summary>
|
||||
/// Causes this <see cref="IPathFinder"/> to perform path finding and follow the path result, idling when a path is not available.<br/>
|
||||
/// This method should be called every frame that you want your entity to follow it's pathfinding logic.
|
||||
/// </summary>
|
||||
public static void DoPathfinding(this IPathFinder pathfinder, PathfindingTask task, bool continuouslyUpdatePath = false)
|
||||
{
|
||||
// If the task has been started but is not finished yet, just idle.
|
||||
if (pathfinder.Path?.Running ?? false)
|
||||
pathfinder.IdleBehavior();
|
||||
|
||||
// If the task has not been started,
|
||||
// or was previously unable to find a path,
|
||||
// OR is now being told to follow a new path...
|
||||
//
|
||||
// start the task (potentially again).
|
||||
else if (pathfinder.Path == null || // Not started
|
||||
pathfinder.Path.Result == null || // Unable to find previous path
|
||||
pathfinder.Path.Result.Count == 0 || // Previous path is done being followed
|
||||
(continuouslyUpdatePath && pathfinder.Path.EndPosition != task.EndPosition)) // New path
|
||||
{
|
||||
pathfinder.FindPath(task);
|
||||
pathfinder.IdleBehavior();
|
||||
}
|
||||
|
||||
// Otherwise, the task has been started, completed, and found a valid path.
|
||||
// Follow the found path.
|
||||
if (CustomIdleBehavior is not null)
|
||||
CustomIdleBehavior();
|
||||
else
|
||||
{
|
||||
// Follows the point at index 0 of the path result.
|
||||
Vector2 nextPoint = pathfinder.Path.Result[0];
|
||||
|
||||
// Once that point is reached, it is removed from the list of points to follow.
|
||||
if (pathfinder.FollowPath(nextPoint))
|
||||
pathfinder.Path.Result.RemoveAt(0);
|
||||
}
|
||||
DefaultIdleBehavior();
|
||||
}
|
||||
|
||||
public void ClearResults()
|
||||
{
|
||||
currentTask = null;
|
||||
lastSuccessfulTask = null;
|
||||
}
|
||||
|
||||
#region Pathfinding Task
|
||||
/// <summary>
|
||||
/// Represents a task for calculating a complex path.<br/>
|
||||
/// Allows for synchronous access to an asynchronous execution state, while still providing blocking access where needed.
|
||||
/// </summary>
|
||||
private class PathfindingTask(PathfindingParameters parameters)
|
||||
{
|
||||
/// <summary>
|
||||
/// The result of this pathfinding task.
|
||||
/// </summary>
|
||||
internal List<Vector2> Result { get => _task.Task.Result; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether this pathfinding task has completed running.
|
||||
/// </summary>
|
||||
internal bool Ready { get; private set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Whether this pathfinding task is still currently running.
|
||||
/// </summary>
|
||||
internal bool Running { get; private set; } = false;
|
||||
|
||||
// Interal task representation of the work.
|
||||
internal readonly TaskCompletionSource<List<Vector2>> _task = new();
|
||||
|
||||
// Internal containing object for the actual work.
|
||||
internal readonly PathfindingWork work = new(parameters);
|
||||
|
||||
/// <summary>
|
||||
/// Begins execution of this pathfinding task on a background thread.
|
||||
/// </summary>
|
||||
internal void Run()
|
||||
{
|
||||
Running = true;
|
||||
|
||||
ThreadPool.QueueUserWorkItem((pathfindingTask) =>
|
||||
{
|
||||
var task = pathfindingTask as PathfindingTask;
|
||||
task._task.TrySetResult(task.work.CalculatePath());
|
||||
|
||||
task.Ready = true;
|
||||
task.Running = false;
|
||||
},
|
||||
this);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Pathfinding Work Record
|
||||
/// <summary>
|
||||
/// Represents the working computation for a <see cref="PathfindingTask"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Has 2 overloads, one for inputting the start and end nodes as <see cref="Vector2"/>, and the other one as <see cref="Point"/>.
|
||||
/// Has 2 constructors. One option provides the start and end positions as <see cref="Vector2"/>, and the other one as <see cref="Point"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This record contains the start and end nodes, along with functions for tile validity, distance calculation, and heuristic estimation.
|
||||
@@ -218,38 +306,31 @@ namespace CalamityMod
|
||||
/// - <see cref="Heuristic"/>: A function that estimates the cost from a given point to the end point. Defaults to <see cref="OctileDistance"/>.<br/>
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public record PathfindingWork(Node Start, Node End, Func<Point, bool> TileValidity, Func<Point, Point, float> DistanceFunction, Func<Point, Point, float> Heuristic)
|
||||
private record PathfindingWork(PathfindingNode Start, PathfindingNode End, Func<Point, bool> TileValidity, Func<Point, Point, float> DistanceFunction, Func<Point, Point, float> Heuristic)
|
||||
{
|
||||
private static readonly Func<Point, bool> DefaultTileValidity = point => true;
|
||||
private static readonly Func<Point, Point, float> DefaultDistanceFunction = OctileDistance;
|
||||
private static readonly Func<Point, Point, float> DefaultHeuristic = OctileDistance;
|
||||
|
||||
public PathfindingWork(
|
||||
Point start,
|
||||
Point end,
|
||||
float minimalPointDistance,
|
||||
Func<Point, bool> tileValidity = null,
|
||||
Func<Point, Point, float> distanceFunction = null,
|
||||
Func<Point, Point, float> heuristic = null) : this(
|
||||
new Node(start),
|
||||
new Node(end),
|
||||
tileValidity ?? DefaultTileValidity,
|
||||
distanceFunction ?? DefaultDistanceFunction,
|
||||
heuristic ?? DefaultHeuristic
|
||||
new PathfindingNode(start),
|
||||
new PathfindingNode(end),
|
||||
tileValidity ?? PathfindingParameters.DefaultTileValidity,
|
||||
distanceFunction ?? PathfindingParameters.DefaultDistanceFunction,
|
||||
heuristic ?? PathfindingParameters.DefaultHeuristic
|
||||
)
|
||||
{
|
||||
}
|
||||
|
||||
public PathfindingWork(
|
||||
Vector2 start,
|
||||
Vector2 end,
|
||||
Func<Point, bool> tileValidity = null,
|
||||
Func<Point, Point, float> distanceFunction = null,
|
||||
Func<Point, Point, float> heuristic = null) : this(
|
||||
new Node(start.ToTileCoordinates()),
|
||||
new Node(end.ToTileCoordinates()),
|
||||
tileValidity ?? DefaultTileValidity,
|
||||
distanceFunction ?? DefaultDistanceFunction,
|
||||
heuristic ?? DefaultHeuristic
|
||||
PathfindingParameters p) : this(
|
||||
new PathfindingNode(p.Start.ToTileCoordinates()),
|
||||
new PathfindingNode(p.End.ToTileCoordinates()),
|
||||
p.TileValidity ?? PathfindingParameters.DefaultTileValidity,
|
||||
p.DistanceFunction ?? PathfindingParameters.DefaultDistanceFunction,
|
||||
p.Heuristic ?? PathfindingParameters.DefaultHeuristic
|
||||
)
|
||||
{
|
||||
}
|
||||
@@ -261,13 +342,13 @@ namespace CalamityMod
|
||||
/// <returns>
|
||||
/// A list of <see cref="Vector2"/> positions representing the path from start to end, or <see langword="null"/> if no path is found.
|
||||
/// </returns>
|
||||
public List<Vector2> CalculatePath()
|
||||
internal List<Vector2> CalculatePath()
|
||||
{
|
||||
if (Main.tile[End.Position].IsTileSolid())
|
||||
return null;
|
||||
|
||||
var openSet = new List<Node>();
|
||||
var closedSet = new HashSet<Node>();
|
||||
var openSet = new List<PathfindingNode>();
|
||||
var closedSet = new HashSet<PathfindingNode>();
|
||||
openSet.Add(Start);
|
||||
|
||||
while (openSet.Count > 0)
|
||||
@@ -310,30 +391,32 @@ namespace CalamityMod
|
||||
return null; // No path found.
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Pathfinding Node
|
||||
/// <summary>
|
||||
/// Represents a node in a pathfinding algorithm, containing position, cost, and parent information.
|
||||
/// </summary>
|
||||
public class Node(Point position)
|
||||
private class PathfindingNode(Point position)
|
||||
{
|
||||
public Point Position { get; set; } = position;
|
||||
public float G { get; set; } // Cost from start to this node.
|
||||
public float H { get; set; } // Heuristic cost to goal.
|
||||
public float F => G + H; // Total cost.
|
||||
public Node Parent { get; set; }
|
||||
internal Point Position { get; set; } = position;
|
||||
internal float G { get; set; } // Cost from start to this node.
|
||||
internal float H { get; set; } // Heuristic cost to goal.
|
||||
internal float F => G + H; // Total cost.
|
||||
internal PathfindingNode Parent { get; set; }
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
if (obj is Node other)
|
||||
if (obj is PathfindingNode other)
|
||||
return Position == other.Position;
|
||||
return false;
|
||||
}
|
||||
|
||||
public override int GetHashCode() => Position.GetHashCode();
|
||||
|
||||
public List<Node> GetNeighbors()
|
||||
internal List<PathfindingNode> GetNeighbors()
|
||||
{
|
||||
var neighbors = new List<Node>(Directions.Count);
|
||||
var neighbors = new List<PathfindingNode>(Directions.Count);
|
||||
|
||||
int nodeX = Position.X;
|
||||
int nodeY = Position.Y;
|
||||
@@ -344,13 +427,13 @@ namespace CalamityMod
|
||||
int newY = nodeY + (int)direction.Y;
|
||||
|
||||
if (WorldGen.InWorld(newX, newY))
|
||||
neighbors.Add(new Node(new Point(newX, newY)));
|
||||
neighbors.Add(new PathfindingNode(new Point(newX, newY)));
|
||||
}
|
||||
|
||||
return neighbors;
|
||||
}
|
||||
|
||||
public List<Vector2> ReconstructPath()
|
||||
internal List<Vector2> ReconstructPath()
|
||||
{
|
||||
var pathStack = new Stack<Vector2>();
|
||||
var node = this;
|
||||
@@ -367,9 +450,13 @@ namespace CalamityMod
|
||||
return path;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
#endregion
|
||||
|
||||
public static partial class CalamityUtils
|
||||
{
|
||||
#region Heuristic Functions
|
||||
|
||||
public static float TaxicabDistance(Point a, Point b) => MathF.Abs(a.X - b.X) + MathF.Abs(a.Y - b.Y);
|
||||
|
||||
public static float EuclideanDistance(Point a, Point b)
|
||||
@@ -387,7 +474,6 @@ namespace CalamityMod
|
||||
float dy = MathF.Abs(a.Y - b.Y);
|
||||
return dx + dy - 0.586f * MathF.Min(dx, dy);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
|
||||
Reference in new issue
Block a user