From d5d60b33e9174ed1947836e9fd6c6843c2f41ab3 Mon Sep 17 00:00:00 2001 From: mochi-angel Date: Mon, 21 Oct 2024 16:12:05 -0700 Subject: [PATCH 01/18] Hadopelagic Pressure start --- Buffs/DamageOverTime/HadopelagicPressure.cs | 98 ++++++++++++++++++ Buffs/DamageOverTime/HadopelagicPressure.png | Bin 0 -> 611 bytes CalPlayer/CalamityPlayer.cs | 4 + CalPlayer/CalamityPlayerOnHit.cs | 2 +- .../en-US/Mods.CalamityMod.Buffs.hjson | 5 + NPCs/CalamityGlobalNPC.cs | 15 +++ Projectiles/Magic/EidolicWailSoundwave.cs | 2 +- Projectiles/Melee/NeptunesBountyProjectile.cs | 2 +- .../Melee/NeptunesBountySplitProjectile.cs | 2 +- Projectiles/Ranged/AstralRound.cs | 2 +- Projectiles/Ranged/TheMaelstromExplosion.cs | 4 +- Projectiles/Rogue/DeepSeaDumbbell1.cs | 4 +- Projectiles/Rogue/DeepSeaDumbbell2.cs | 4 +- Projectiles/Rogue/DeepSeaDumbbell3.cs | 4 +- Projectiles/Rogue/DeepSeaDumbbellWeight.cs | 4 +- Projectiles/Rogue/JawsProjectile.cs | 4 +- Projectiles/Rogue/JawsShockwave.cs | 4 +- Projectiles/Rogue/ValedictionBoomerang.cs | 4 +- 18 files changed, 143 insertions(+), 21 deletions(-) create mode 100644 Buffs/DamageOverTime/HadopelagicPressure.cs create mode 100644 Buffs/DamageOverTime/HadopelagicPressure.png diff --git a/Buffs/DamageOverTime/HadopelagicPressure.cs b/Buffs/DamageOverTime/HadopelagicPressure.cs new file mode 100644 index 0000000000..a861ccc55a --- /dev/null +++ b/Buffs/DamageOverTime/HadopelagicPressure.cs @@ -0,0 +1,98 @@ +using CalamityMod.Particles; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Buffs.DamageOverTime +{ + public class HadopelagicPressure : ModBuff + { + public override void SetStaticDefaults() + { + Main.debuff[Type] = true; + Main.pvpBuff[Type] = true; + Main.buffNoSave[Type] = true; + BuffID.Sets.LongerExpertDebuff[Type] = true; + } + + public override void Update(Player player, ref int buffIndex) + { + player.Calamity().hadopelagicpressure = true; + } + + public override void Update(NPC npc, ref int buffIndex) + { + if (npc.Calamity().hadopelagicpressure < npc.buffTime[buffIndex]) + npc.Calamity().hadopelagicpressure = npc.buffTime[buffIndex]; + npc.DelBuff(buffIndex); + buffIndex--; + } + + internal static void DrawEffects(PlayerDrawSet drawInfo) + { + Player Player = drawInfo.drawPlayer; + // A bit of blood + if (Main.rand.NextBool(30)) + { + int bloodLifetime = Main.rand.Next(22, 36); + float bloodScale = Main.rand.NextFloat(0.6f, 0.8f); + Color bloodColor = Color.Lerp(Color.Red, Color.DarkRed, Main.rand.NextFloat()); + bloodColor = Color.Lerp(bloodColor, new Color(51, 22, 94), Main.rand.NextFloat(0.65f)); + + if (Main.rand.NextBool(15)) + bloodScale *= 1.3f; + + float randomSpeedMultiplier = Main.rand.NextFloat(1.25f, 1.5f); + Vector2 bloodVelocity = Main.rand.NextVector2Unit() * 2 * randomSpeedMultiplier; + bloodVelocity.Y -= 5f; + BloodParticle blood = new BloodParticle(Player.Center, bloodVelocity, bloodLifetime, bloodScale, bloodColor); + GeneralParticleHandler.SpawnParticle(blood); + } + + // Blue n black dust + Dust water = Dust.NewDustDirect(drawInfo.Position - new Vector2(2f), Player.width + 4, Player.height + 4, DustID.Water, Player.velocity.X * 0.4f, Player.velocity.Y * 0.4f, 100, default, 1.4f); + water.noGravity = true; + water.velocity *= 0.75f; + water.velocity.X *= 0.75f; + water.velocity.Y -= 1f; + if (Main.rand.NextBool(4)) + { + water.noGravity = false; + water.scale *= 0.5f; + } + if (Main.rand.NextBool(5)) + { + DirectionalPulseRing pulse = new DirectionalPulseRing(Player.Calamity().RandomDebuffVisualSpot, new Vector2(Main.rand.NextFloat(-1f, 1f), Main.rand.NextFloat(-3f, -4f)), Main.rand.NextBool() ? Color.DarkBlue : Color.Blue, new Vector2(0.8f, 1), 0, 0.09f, 0f, 45); + GeneralParticleHandler.SpawnParticle(pulse); + } + } + + internal static void DrawEffects(NPC npc, ref Color drawColor) + { + Vector2 npcSize = npc.Center + new Vector2(Main.rand.NextFloat(-npc.width / 2, npc.width / 2), Main.rand.NextFloat(-npc.height / 2, npc.height / 2)); + if (Main.rand.NextBool(13)) + { + Color smokeColor = Color.MediumBlue; + Particle smoke = new HeavySmokeParticle(npcSize, new Vector2(2f, 2f).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 0.7f), smokeColor, 40, Main.rand.NextFloat(0.3f, 0.4f), 0.5f, Main.rand.NextFloat(-0.2f, 0.2f), false, required: true); + GeneralParticleHandler.SpawnParticle(smoke); + } + Dust water = Dust.NewDustDirect(npc.position - new Vector2(2f), npc.width + 4, npc.height + 4, 360, npc.velocity.X * 0.4f, npc.velocity.Y * 0.4f, 100, default, 1.4f); + water.noGravity = true; + water.velocity *= 0.75f; + water.velocity.X = water.velocity.X * 0.75f; + water.velocity.Y = water.velocity.Y - 1f; + if (Main.rand.NextBool(4)) + { + water.noGravity = false; + water.scale *= 0.5f; + } + if (Main.rand.NextBool(6)) + { + DirectionalPulseRing pulse = new DirectionalPulseRing(npcSize, new Vector2(Main.rand.NextFloat(-1f, 1f), Main.rand.NextFloat(-4.5f, -6f)), Main.rand.NextBool() ? Color.DeepSkyBlue : Color.MediumBlue, new Vector2(1f), 0, 0.12f + (0.0000007f * npc.width * npc.height), 0f, 35); + GeneralParticleHandler.SpawnParticle(pulse); + } + } + } +} diff --git a/Buffs/DamageOverTime/HadopelagicPressure.png b/Buffs/DamageOverTime/HadopelagicPressure.png new file mode 100644 index 0000000000000000000000000000000000000000..338abc479221124d02c60bd3e3a26b5b076d3799 GIT binary patch literal 611 zcmV-p0-XJcP)Px%9Z5t%R9J=8mp@EXQ5431CAKLAQZ*%RBGfbMN`?cka0_ zl}Tp-*!{J$M;nnzXHx(j?VL0YDPRwvuXiBU;q1jr02EK1_@}_N_a6aRT9}Xh{&jN| z2$=z8F6=M~K=T4(v9U&&(ZGrL69bd{O}tf(n9sMtBS-K*rx%D-`k4-tXJI13uVX9diAvD zS17&n{LWo<<2t&}w~QY?1NEOTfhhBX5c#=r#s8iG!K%7Yia!a3zpa|^7*L(2ap%Bb z=LI0DhJl;+0qB}@XTEwv|MhDCtUkHtjk9qr!eL-*^BVxU-XpP&I@{InPd=Cc;KSW` zKZ{1a;>{z3!+=H9*ZuykJ%{7cR zP1tI%-)mK0ET2}KJ#hw_8nEhD<~Acidn~Q!sdGSGQ1*S*6&wQ=HY36Icik0j{cC)q x{v6Z+t;R-M|BiD#`7r*D{{TTgr!*Pjv{(QD002ovPDHLkV1hp+ARzz% literal 0 HcmV?d00001 diff --git a/CalPlayer/CalamityPlayer.cs b/CalPlayer/CalamityPlayer.cs index 8232fae24e..73f18d9bfa 100644 --- a/CalPlayer/CalamityPlayer.cs +++ b/CalPlayer/CalamityPlayer.cs @@ -5,6 +5,7 @@ using CalamityMod.Balancing; using CalamityMod.BiomeManagers; using CalamityMod.Buffs; using CalamityMod.Buffs.Alcohol; +using CalamityMod.Buffs.DamageOverTime; using CalamityMod.Buffs.Placeables; using CalamityMod.Buffs.StatBuffs; using CalamityMod.Buffs.StatDebuffs; @@ -932,6 +933,7 @@ namespace CalamityMod.CalPlayer public bool warped = false; public bool cDepth = false; public bool rTide = false; + public bool hadopelagicpressure = false; public bool fishAlert = false; public bool clamity = false; public bool NOU = false; @@ -2041,6 +2043,7 @@ namespace CalamityMod.CalPlayer warped = false; cDepth = false; rTide = false; + hadopelagicpressure = false; fishAlert = false; clamity = false; NOU = false; @@ -2489,6 +2492,7 @@ namespace CalamityMod.CalPlayer warped = false; cDepth = false; rTide = false; + hadopelagicpressure = false; fishAlert = false; clamity = false; NOU = false; diff --git a/CalPlayer/CalamityPlayerOnHit.cs b/CalPlayer/CalamityPlayerOnHit.cs index bb08e86a54..a1e9226bb4 100644 --- a/CalPlayer/CalamityPlayerOnHit.cs +++ b/CalPlayer/CalamityPlayerOnHit.cs @@ -1226,7 +1226,7 @@ namespace CalamityMod.CalPlayer if (frostFlare) CalamityUtils.Inflict246DebuffsNPC(target, BuffID.Frostburn2); if (omegaBlueChestplate) - target.AddBuff(BuffType(), 180); + target.AddBuff(BuffType(), 180); if (sulphurSet) target.AddBuff(BuffID.Poisoned, 60); if (aSpark && Player.IsUnderwater()) diff --git a/Localization/en-US/Mods.CalamityMod.Buffs.hjson b/Localization/en-US/Mods.CalamityMod.Buffs.hjson index 99fb0a30ba..4dd3983728 100644 --- a/Localization/en-US/Mods.CalamityMod.Buffs.hjson +++ b/Localization/en-US/Mods.CalamityMod.Buffs.hjson @@ -1577,3 +1577,8 @@ AmphibiansGuitarBuff: { DisplayName: Amphibian's Guitars Description: Worthless human... } + +HadopelagicPressure: { + DisplayName: Hadopelagic Pressure + Description: Rapidly sinking to a watery grave +} diff --git a/NPCs/CalamityGlobalNPC.cs b/NPCs/CalamityGlobalNPC.cs index 47ed3a8f12..3a3a711d04 100644 --- a/NPCs/CalamityGlobalNPC.cs +++ b/NPCs/CalamityGlobalNPC.cs @@ -301,6 +301,7 @@ namespace CalamityMod.NPCs public int cDepth = 0; public int rTide = 0; + public int hadopelagicpressure = 0; public int gsInferno = 0; public int dragonFire = 0; public int vermillionFlux = 0; @@ -529,6 +530,7 @@ namespace CalamityMod.NPCs myClone.cDepth = cDepth; myClone.rTide = rTide; + myClone.hadopelagicpressure = hadopelagicpressure; myClone.gsInferno = gsInferno; myClone.miracleBlight = miracleBlight; myClone.dragonFire = dragonFire; @@ -1171,6 +1173,13 @@ namespace CalamityMod.NPCs int baseCrushDepthDoTValue = (int)(100 * waterDamageMult); ApplyDPSDebuff(baseCrushDepthDoTValue, baseCrushDepthDoTValue / 2, ref npc.lifeRegen, ref damage); } + + //Hadopelagic Pressure + if (hadopelagicpressure > 0) + { + int baseHadopelagicPressureDoTValue = (int)(400 * waterDamageMult); + ApplyDPSDebuff(baseHadopelagicPressureDoTValue, baseHadopelagicPressureDoTValue / 2, ref npc.lifeRegen, ref damage); + } #endregion if (npc.dryadBane) @@ -5535,6 +5544,8 @@ namespace CalamityMod.NPCs crumble--; if (cDepth > 0) cDepth--; + if (hadopelagicpressure > 0) + hadopelagicpressure--; if (rTide > 0) rTide--; if (gsInferno > 0) @@ -6996,6 +7007,9 @@ namespace CalamityMod.NPCs if (cDepth > 0) CrushDepth.DrawEffects(npc, ref drawColor); + if (hadopelagicpressure > 0) + HadopelagicPressure.DrawEffects(npc, ref drawColor); + if (dragonFire > 0) Dragonfire.DrawEffects(npc, ref drawColor); @@ -7205,6 +7219,7 @@ namespace CalamityMod.NPCs ("CalamityMod/Buffs/DamageOverTime/Dragonfire", NPC => NPC.Calamity().dragonFire > 0), ("CalamityMod/Buffs/DamageOverTime/ElementalMix", NPC => NPC.Calamity().elementalMix > 0), ("CalamityMod/Buffs/DamageOverTime/GodSlayerInferno", NPC => NPC.Calamity().gsInferno > 0), + ("CalamityMod/Buffs/DamageOverTime/HadopelagicPressure", NPC => NPC.Calamity().hadopelagicpressure > 0), ("CalamityMod/Buffs/DamageOverTime/HolyFlames", NPC => NPC.Calamity().hFlames > 0), ("CalamityMod/Buffs/DamageOverTime/Laceration", NPC => NPC.Calamity().laceration > 0), ("CalamityMod/Buffs/DamageOverTime/MiracleBlight", NPC => NPC.Calamity().miracleBlight > 0), diff --git a/Projectiles/Magic/EidolicWailSoundwave.cs b/Projectiles/Magic/EidolicWailSoundwave.cs index 0f15340a45..23316f5c74 100644 --- a/Projectiles/Magic/EidolicWailSoundwave.cs +++ b/Projectiles/Magic/EidolicWailSoundwave.cs @@ -72,7 +72,7 @@ namespace CalamityMod.Projectiles.Magic public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 240); + target.AddBuff(ModContent.BuffType(), 240); if (Projectile.numHits == 0) Projectile.velocity *= 0.4f; } diff --git a/Projectiles/Melee/NeptunesBountyProjectile.cs b/Projectiles/Melee/NeptunesBountyProjectile.cs index f86a683e98..6208cb9cc0 100644 --- a/Projectiles/Melee/NeptunesBountyProjectile.cs +++ b/Projectiles/Melee/NeptunesBountyProjectile.cs @@ -254,7 +254,7 @@ namespace CalamityMod.Projectiles.Melee public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 300); + target.AddBuff(ModContent.BuffType(), 300); if (spinMode2 && Projectile.numHits == 0) { diff --git a/Projectiles/Melee/NeptunesBountySplitProjectile.cs b/Projectiles/Melee/NeptunesBountySplitProjectile.cs index b57d6e0f38..439bf42e1c 100644 --- a/Projectiles/Melee/NeptunesBountySplitProjectile.cs +++ b/Projectiles/Melee/NeptunesBountySplitProjectile.cs @@ -81,7 +81,7 @@ namespace CalamityMod.Projectiles.Melee public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 240); + target.AddBuff(ModContent.BuffType(), 240); } } } diff --git a/Projectiles/Ranged/AstralRound.cs b/Projectiles/Ranged/AstralRound.cs index 834728bd1c..145dd26d58 100644 --- a/Projectiles/Ranged/AstralRound.cs +++ b/Projectiles/Ranged/AstralRound.cs @@ -76,7 +76,7 @@ namespace CalamityMod.Projectiles.Ranged } public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 900); } } } diff --git a/Projectiles/Ranged/TheMaelstromExplosion.cs b/Projectiles/Ranged/TheMaelstromExplosion.cs index d4c0e99c0c..82c94f4baf 100644 --- a/Projectiles/Ranged/TheMaelstromExplosion.cs +++ b/Projectiles/Ranged/TheMaelstromExplosion.cs @@ -61,9 +61,9 @@ namespace CalamityMod.Projectiles.Ranged } } - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 180); + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 180); - public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType(), 180); + public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType(), 180); public override bool PreDraw(ref Color lightColor) { diff --git a/Projectiles/Rogue/DeepSeaDumbbell1.cs b/Projectiles/Rogue/DeepSeaDumbbell1.cs index 7c58cfb78b..0d9fcd7c32 100644 --- a/Projectiles/Rogue/DeepSeaDumbbell1.cs +++ b/Projectiles/Rogue/DeepSeaDumbbell1.cs @@ -72,7 +72,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 240); + target.AddBuff(ModContent.BuffType(), 240); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); @@ -112,7 +112,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitPlayer(Player target, Player.HurtInfo info) { - target.AddBuff(ModContent.BuffType(), 240); + target.AddBuff(ModContent.BuffType(), 240); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); diff --git a/Projectiles/Rogue/DeepSeaDumbbell2.cs b/Projectiles/Rogue/DeepSeaDumbbell2.cs index 6a1671bc6e..5bfb9bcbc1 100644 --- a/Projectiles/Rogue/DeepSeaDumbbell2.cs +++ b/Projectiles/Rogue/DeepSeaDumbbell2.cs @@ -79,7 +79,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 180); + target.AddBuff(ModContent.BuffType(), 180); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); @@ -119,7 +119,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitPlayer(Player target, Player.HurtInfo info) { - target.AddBuff(ModContent.BuffType(), 180); + target.AddBuff(ModContent.BuffType(), 180); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); diff --git a/Projectiles/Rogue/DeepSeaDumbbell3.cs b/Projectiles/Rogue/DeepSeaDumbbell3.cs index f1f25a14da..c4bb1358bb 100644 --- a/Projectiles/Rogue/DeepSeaDumbbell3.cs +++ b/Projectiles/Rogue/DeepSeaDumbbell3.cs @@ -71,7 +71,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); @@ -105,7 +105,7 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitPlayer(Player target, Player.HurtInfo info) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); SoundEngine.PlaySound(SoundID.NPCDeath43 with { Volume = SoundID.NPCDeath43.Volume * 0.35f }, Projectile.position); diff --git a/Projectiles/Rogue/DeepSeaDumbbellWeight.cs b/Projectiles/Rogue/DeepSeaDumbbellWeight.cs index c5953a8397..dc4d6fb937 100644 --- a/Projectiles/Rogue/DeepSeaDumbbellWeight.cs +++ b/Projectiles/Rogue/DeepSeaDumbbellWeight.cs @@ -57,12 +57,12 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); } public override void OnHitPlayer(Player target, Player.HurtInfo info) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); } } } diff --git a/Projectiles/Rogue/JawsProjectile.cs b/Projectiles/Rogue/JawsProjectile.cs index 897081520a..8536ab15ec 100644 --- a/Projectiles/Rogue/JawsProjectile.cs +++ b/Projectiles/Rogue/JawsProjectile.cs @@ -64,7 +64,7 @@ namespace CalamityMod.Projectiles.Rogue target.AddBuff(ModContent.BuffType(), 120); if (Projectile.Calamity().stealthStrike) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); int shockwaveDamage = (int)player.GetTotalDamage().ApplyTo(100f); Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), shockwaveDamage, 10f, Projectile.owner, 0, 0); } @@ -77,7 +77,7 @@ namespace CalamityMod.Projectiles.Rogue target.AddBuff(ModContent.BuffType(), 120); if (Projectile.Calamity().stealthStrike) { - target.AddBuff(ModContent.BuffType(), 120); + target.AddBuff(ModContent.BuffType(), 120); int shockwaveDamage = (int)player.GetTotalDamage().ApplyTo(100f); Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), shockwaveDamage, 10f, Projectile.owner, 0, 0); } diff --git a/Projectiles/Rogue/JawsShockwave.cs b/Projectiles/Rogue/JawsShockwave.cs index 41437e9836..b1eb5e72ba 100644 --- a/Projectiles/Rogue/JawsShockwave.cs +++ b/Projectiles/Rogue/JawsShockwave.cs @@ -58,9 +58,9 @@ namespace CalamityMod.Projectiles.Rogue } } - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 240); + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 240); - public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType(), 240); + public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(ModContent.BuffType(), 240); public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, 160f, targetHitbox); } diff --git a/Projectiles/Rogue/ValedictionBoomerang.cs b/Projectiles/Rogue/ValedictionBoomerang.cs index 739bd2364b..a06515a9e8 100644 --- a/Projectiles/Rogue/ValedictionBoomerang.cs +++ b/Projectiles/Rogue/ValedictionBoomerang.cs @@ -121,13 +121,13 @@ namespace CalamityMod.Projectiles.Rogue public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 180); + target.AddBuff(ModContent.BuffType(), 180); OnHitEffects(); } public override void OnHitPlayer(Player target, Player.HurtInfo info) { - target.AddBuff(ModContent.BuffType(), 180); + target.AddBuff(ModContent.BuffType(), 180); OnHitEffects(); } From b5dc0df3760be67c7008a7151dcc1b97fd7e42a1 Mon Sep 17 00:00:00 2001 From: mochi-angel Date: Tue, 22 Oct 2024 06:31:23 -0700 Subject: [PATCH 02/18] Player effects and enemy infliction --- Buffs/DamageOverTime/HadopelagicPressure.cs | 32 +++++++-------------- CalPlayer/CalamityPlayerDrawEffects.cs | 9 ++++-- CalPlayer/CalamityPlayerLifeRegen.cs | 1 + NPCs/Abyss/BobbitWormHead.cs | 2 +- NPCs/Abyss/ColossalSquid.cs | 2 +- NPCs/Abyss/EidolonWyrmHead.cs | 2 +- NPCs/Abyss/OarfishHead.cs | 2 +- NPCs/Abyss/ReaperShark.cs | 2 +- NPCs/PrimordialWyrm/PrimordialWyrmHead.cs | 2 +- 9 files changed, 23 insertions(+), 31 deletions(-) diff --git a/Buffs/DamageOverTime/HadopelagicPressure.cs b/Buffs/DamageOverTime/HadopelagicPressure.cs index a861ccc55a..3893bbf245 100644 --- a/Buffs/DamageOverTime/HadopelagicPressure.cs +++ b/Buffs/DamageOverTime/HadopelagicPressure.cs @@ -33,26 +33,8 @@ namespace CalamityMod.Buffs.DamageOverTime internal static void DrawEffects(PlayerDrawSet drawInfo) { Player Player = drawInfo.drawPlayer; - // A bit of blood - if (Main.rand.NextBool(30)) - { - int bloodLifetime = Main.rand.Next(22, 36); - float bloodScale = Main.rand.NextFloat(0.6f, 0.8f); - Color bloodColor = Color.Lerp(Color.Red, Color.DarkRed, Main.rand.NextFloat()); - bloodColor = Color.Lerp(bloodColor, new Color(51, 22, 94), Main.rand.NextFloat(0.65f)); - - if (Main.rand.NextBool(15)) - bloodScale *= 1.3f; - - float randomSpeedMultiplier = Main.rand.NextFloat(1.25f, 1.5f); - Vector2 bloodVelocity = Main.rand.NextVector2Unit() * 2 * randomSpeedMultiplier; - bloodVelocity.Y -= 5f; - BloodParticle blood = new BloodParticle(Player.Center, bloodVelocity, bloodLifetime, bloodScale, bloodColor); - GeneralParticleHandler.SpawnParticle(blood); - } - // Blue n black dust - Dust water = Dust.NewDustDirect(drawInfo.Position - new Vector2(2f), Player.width + 4, Player.height + 4, DustID.Water, Player.velocity.X * 0.4f, Player.velocity.Y * 0.4f, 100, default, 1.4f); + Dust water = Dust.NewDustDirect(drawInfo.Position - new Vector2(2f), Player.width + 4, Player.height + 4, 390, Player.velocity.X * 0.4f, Player.velocity.Y * 0.4f, 100, default, 1.4f); water.noGravity = true; water.velocity *= 0.75f; water.velocity.X *= 0.75f; @@ -62,11 +44,17 @@ namespace CalamityMod.Buffs.DamageOverTime water.noGravity = false; water.scale *= 0.5f; } - if (Main.rand.NextBool(5)) + if (Main.rand.NextBool(4)) { - DirectionalPulseRing pulse = new DirectionalPulseRing(Player.Calamity().RandomDebuffVisualSpot, new Vector2(Main.rand.NextFloat(-1f, 1f), Main.rand.NextFloat(-3f, -4f)), Main.rand.NextBool() ? Color.DarkBlue : Color.Blue, new Vector2(0.8f, 1), 0, 0.09f, 0f, 45); + DirectionalPulseRing pulse = new DirectionalPulseRing(Player.Calamity().RandomDebuffVisualSpot, new Vector2(Main.rand.NextFloat(-1f, 1f), Main.rand.NextFloat(-3f, -4f)), Main.rand.NextBool() ? Color.DeepSkyBlue : Color.MediumBlue, new Vector2(0.8f, 1), 0, 0.09f, 0f, 45); GeneralParticleHandler.SpawnParticle(pulse); } + if (Main.rand.NextBool(10)) + { + Color smokeColor = Color.MediumBlue; + Particle smoke = new HeavySmokeParticle(Player.Calamity().RandomDebuffVisualSpot, new Vector2(2f, 2f).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 0.7f), smokeColor, 40, Main.rand.NextFloat(0.3f, 0.4f), 0.5f, Main.rand.NextFloat(-0.2f, 0.2f), false, required: true); + GeneralParticleHandler.SpawnParticle(smoke); + } } internal static void DrawEffects(NPC npc, ref Color drawColor) @@ -75,7 +63,7 @@ namespace CalamityMod.Buffs.DamageOverTime if (Main.rand.NextBool(13)) { Color smokeColor = Color.MediumBlue; - Particle smoke = new HeavySmokeParticle(npcSize, new Vector2(2f, 2f).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 0.7f), smokeColor, 40, Main.rand.NextFloat(0.3f, 0.4f), 0.5f, Main.rand.NextFloat(-0.2f, 0.2f), false, required: true); + Particle smoke = new HeavySmokeParticle(npcSize, new Vector2(2f, 2f).RotatedByRandom(100) * Main.rand.NextFloat(0.3f, 0.7f), smokeColor, 40, Main.rand.NextFloat(0.3f, 0.4f) + (0.00000013f * npc.width * npc.height), 0.5f, Main.rand.NextFloat(-0.2f, 0.2f), false, required: true); GeneralParticleHandler.SpawnParticle(smoke); } Dust water = Dust.NewDustDirect(npc.position - new Vector2(2f), npc.width + 4, npc.height + 4, 360, npc.velocity.X * 0.4f, npc.velocity.Y * 0.4f, 100, default, 1.4f); diff --git a/CalPlayer/CalamityPlayerDrawEffects.cs b/CalPlayer/CalamityPlayerDrawEffects.cs index 33b65d6b27..5dc228856e 100644 --- a/CalPlayer/CalamityPlayerDrawEffects.cs +++ b/CalPlayer/CalamityPlayerDrawEffects.cs @@ -255,6 +255,9 @@ namespace CalamityMod.CalPlayer if (drawInfo.shadow == 0f && (calamityPlayer.hFlames || calamityPlayer.hInferno || calamityPlayer.banishingFire)) HolyFlames.DrawEffects(drawInfo); + if (calamityPlayer.hadopelagicpressure && drawInfo.shadow == 0f) + HadopelagicPressure.DrawEffects(drawInfo); + // Icarus' Folly has visual effects but they are mutually exclusive with all Holy Flames variations to prevent visual clutter else if (calamityPlayer.icarusFolly && drawInfo.shadow == 0f) IcarusFolly.DrawEffects(drawInfo); @@ -269,9 +272,6 @@ namespace CalamityMod.CalPlayer if (calamityPlayer.nightwither && drawInfo.shadow == 0f) // Looks weaker if you have Moon Stone equipped Nightwither.DrawEffects(drawInfo, reducedNightwitherDamage); - if (calamityPlayer.voidfrost && drawInfo.shadow == 0f) - Voidfrost.DrawEffects(drawInfo); - if (calamityPlayer.pFlames && drawInfo.shadow == 0f) Plague.DrawEffects(drawInfo); @@ -300,6 +300,9 @@ namespace CalamityMod.CalPlayer if (calamityPlayer.vermillionFlux && drawInfo.shadow == 0f) VermillionFlux.DrawEffects(drawInfo); + if (calamityPlayer.voidfrost && drawInfo.shadow == 0f) + Voidfrost.DrawEffects(drawInfo); + if (calamityPlayer.vHex && drawInfo.shadow == 0f) VulnerabilityHex.DrawEffects(drawInfo); #endregion diff --git a/CalPlayer/CalamityPlayerLifeRegen.cs b/CalPlayer/CalamityPlayerLifeRegen.cs index 355f877134..12fd94b098 100644 --- a/CalPlayer/CalamityPlayerLifeRegen.cs +++ b/CalPlayer/CalamityPlayerLifeRegen.cs @@ -112,6 +112,7 @@ namespace CalamityMod.CalPlayer ApplyDoTDebuff(vHex, 35); ApplyDoTDebuff(trueVHex, 50); ApplyDoTDebuff(cDepth, 18, purity); + ApplyDoTDebuff(hadopelagicpressure, 40, purity); ApplyDoTDebuff(astralInfection, 24, infectedJewel || purity); ApplyDoTDebuff(pFlames, alchFlask ? 10 : 30, purity); ApplyDoTDebuff(cragsLava, 30); diff --git a/NPCs/Abyss/BobbitWormHead.cs b/NPCs/Abyss/BobbitWormHead.cs index 7d28b94911..5a5095e12b 100644 --- a/NPCs/Abyss/BobbitWormHead.cs +++ b/NPCs/Abyss/BobbitWormHead.cs @@ -256,7 +256,7 @@ namespace CalamityMod.NPCs.Abyss public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 300, true); + target.AddBuff(ModContent.BuffType(), 300, true); } public override void ModifyNPCLoot(NPCLoot npcLoot) diff --git a/NPCs/Abyss/ColossalSquid.cs b/NPCs/Abyss/ColossalSquid.cs index 569955cea9..6a5b4acd13 100644 --- a/NPCs/Abyss/ColossalSquid.cs +++ b/NPCs/Abyss/ColossalSquid.cs @@ -624,7 +624,7 @@ namespace CalamityMod.NPCs.Abyss public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 300, true); + target.AddBuff(ModContent.BuffType(), 300, true); } public override void ModifyNPCLoot(NPCLoot npcLoot) diff --git a/NPCs/Abyss/EidolonWyrmHead.cs b/NPCs/Abyss/EidolonWyrmHead.cs index 658b2aad26..9bcd93843b 100644 --- a/NPCs/Abyss/EidolonWyrmHead.cs +++ b/NPCs/Abyss/EidolonWyrmHead.cs @@ -512,7 +512,7 @@ namespace CalamityMod.NPCs.Abyss public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 300, true); + target.AddBuff(ModContent.BuffType(), 300, true); } } } diff --git a/NPCs/Abyss/OarfishHead.cs b/NPCs/Abyss/OarfishHead.cs index 20a9467a9b..a1876b577a 100644 --- a/NPCs/Abyss/OarfishHead.cs +++ b/NPCs/Abyss/OarfishHead.cs @@ -364,7 +364,7 @@ namespace CalamityMod.NPCs.Abyss public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 90); + target.AddBuff(ModContent.BuffType(), 90); } public override bool PreDraw(SpriteBatch spriteBatch, Vector2 screenPos, Color drawColor) diff --git a/NPCs/Abyss/ReaperShark.cs b/NPCs/Abyss/ReaperShark.cs index 57d5e59a7b..e89c7c779c 100644 --- a/NPCs/Abyss/ReaperShark.cs +++ b/NPCs/Abyss/ReaperShark.cs @@ -709,7 +709,7 @@ namespace CalamityMod.NPCs.Abyss public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 300, true); + target.AddBuff(ModContent.BuffType(), 300, true); } public override float SpawnChance(NPCSpawnInfo spawnInfo) diff --git a/NPCs/PrimordialWyrm/PrimordialWyrmHead.cs b/NPCs/PrimordialWyrm/PrimordialWyrmHead.cs index 690eb437ff..aa29f2cc64 100644 --- a/NPCs/PrimordialWyrm/PrimordialWyrmHead.cs +++ b/NPCs/PrimordialWyrm/PrimordialWyrmHead.cs @@ -1505,7 +1505,7 @@ namespace CalamityMod.NPCs.PrimordialWyrm public override void OnHitPlayer(Player target, Player.HurtInfo hurtInfo) { if (NPC.Opacity == 1f && hurtInfo.Damage > 0) - target.AddBuff(ModContent.BuffType(), 1200, true); + target.AddBuff(ModContent.BuffType(), 1200, true); } } } From 3adbd4aee0ac72df7574dea199f5f6e85e28c436 Mon Sep 17 00:00:00 2001 From: mochi-angel Date: Wed, 23 Oct 2024 16:49:42 -0700 Subject: [PATCH 03/18] Death messages (Thank you Rebecca) --- CalPlayer/CalamityPlayerHitHurt.cs | 4 ++++ Localization/en-US/Mods.CalamityMod.Status.Death.hjson | 3 +++ 2 files changed, 7 insertions(+) diff --git a/CalPlayer/CalamityPlayerHitHurt.cs b/CalPlayer/CalamityPlayerHitHurt.cs index 996755b417..721d2f1e0e 100644 --- a/CalPlayer/CalamityPlayerHitHurt.cs +++ b/CalPlayer/CalamityPlayerHitHurt.cs @@ -459,6 +459,10 @@ namespace CalamityMod.CalPlayer { damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.Riptide" + Main.rand.Next(1, 2 + 1)).Format(Player.name)); } + if (hadopelagicpressure) + { + damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.HadopelagicPressure" + Main.rand.Next(1, 3 + 1)).Format(Player.name)); + } if (bFlames || weakBrimstoneFlames) { damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.BrimstoneFlames" + Main.rand.Next(1, 3 + 1)).Format(Player.name)); diff --git a/Localization/en-US/Mods.CalamityMod.Status.Death.hjson b/Localization/en-US/Mods.CalamityMod.Status.Death.hjson index b8dd397c36..779b51536e 100644 --- a/Localization/en-US/Mods.CalamityMod.Status.Death.hjson +++ b/Localization/en-US/Mods.CalamityMod.Status.Death.hjson @@ -52,6 +52,9 @@ CorpusAvertor: "{0} became the Blood God's sacrifice." CrushDepth1: "{0} was crushed by the pressure." CrushDepth2: "{0}'s lungs collapsed." CrushDepth3: "{0}'s bones crunched under the deep pressure." +HadopelagicPressure1: "{0} couldn't see the radiant light." +HadopelagicPressure2: "{0}'s body was never found." +HadopelagicPressure3: "{0} was crushed by nature." Daybroken: "{0} was incinerated by solar rays." Dragonfire1: "{0}'s ashes scatter in the wind." Dragonfire2: "{0}'s embers fade away in a warm glow." From 127fd97f82b681a787b5ba2ddcec6ea2e3a74c5c Mon Sep 17 00:00:00 2001 From: mochi-angel Date: Thu, 12 Dec 2024 19:42:19 -0800 Subject: [PATCH 04/18] Updated Icon --- Buffs/DamageOverTime/HadopelagicPressure.png | Bin 611 -> 557 bytes Projectiles/Summon/CalamarisLamentMinion.cs | 5 ++++- Projectiles/Summon/CalamarisLamentProjectile.cs | 5 ++++- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Buffs/DamageOverTime/HadopelagicPressure.png b/Buffs/DamageOverTime/HadopelagicPressure.png index 338abc479221124d02c60bd3e3a26b5b076d3799..ac56060a6924c66a232c4abe8f7307c37eba0874 100644 GIT binary patch delta 520 zcmV+j0{8vn1g!*+Fn%S!_>5Qo2Qi=thtMG--?P`s$1UVGJ}_~&{Q zPvS{@fOrtZ2ZEG}T3cUO*F!REcih+>#EsvjnaL!Z`DL=323STHHX^#{G#UWpCni#D zjjP`^PpiHg0OV3<`$G!hWGw>7mqX*2Dg*F-^RumS^}FT?A%DUP1#;~s0G+#5qNA5B z8NHrdL6?Gp_=UIA^MozW&0Ya%NOijG;Ox-&tIMfzuJMKDwQ-cDp(}I29|huCPtG&IKaru!%e6xL=h|7#v0a;Or#YDhIv6SkUJ=S}w2`6i& zVdLaELiP&8nSU2ehT4{Qc%-XWWhC)}_`_l?HO{{p5cCSehN%H;El9P0?QL?r)QtFb zjrdms(s1piWDsYj{F?YaP*0!NUj;PZPKA08xRCdQD`Sm+3b<-P5PxB134pP^M*yOV z`8MP(&Qiy@l<-dhK`Sx5whqA4)+PW0<1+xf=n1VdF@HP%tp+rK-P^(0IRKt3$$LO# zZ%9LP^8mcvn!Dip!BJle@LvHr*N^+#0F13}q{ivYd!2tFa|HtIKa^g?Uq1)>e$X#o zC?NEu#BV=4a|J#D1+L!BqPoh)0000EWmrjOO-%qQ00008000000002eQS;Q1mgsdFnKTK0m6vlrgwkbqPs8l3S4gO)F;Gab|moA1l zI5Cl!I2%_Jqk}FcE+)<X`?zu0ONoN7r{k5}48<9z8Qve<9oHPz8U=N_LcYh$(;q1jr02EK1_@}_N z_a6aRT9}Xh{&jN|2$=z8F6=M~K==T|7b^Zd?Tb>lj^&$o;pJ_GfiFM%lYgAn<-amD|h0l})eP>MeZ zg}<$u@EA~?rg7)MVCMxOs)m7^_W|gdb7#JKL;v+_0Dr7Lx#x|uaV^4OU~BUm0J+{H zv5q?1)$dO}m;m6z-FQEXM!n+ABZR|%Mby{*{;oZT3C~_Ak9hBE)6e~YnfQ4UXQ0^) zj}Q5GJ!v7mTlVZyyC6;2YOvpHRbMQhR-8R?2AUeM>R0AABSCvCt>~$9KwVJwebp5l z0~R(T!8i7I-4$*9YkZ^rxa9&8XCRg9akty8#ztHJj&nWvF#eAJ06{*dG#TQwSO5S3 M07*qoM6N<$f{U#iRsaA1 diff --git a/Projectiles/Summon/CalamarisLamentMinion.cs b/Projectiles/Summon/CalamarisLamentMinion.cs index 867337a78c..c18b37282d 100644 --- a/Projectiles/Summon/CalamarisLamentMinion.cs +++ b/Projectiles/Summon/CalamarisLamentMinion.cs @@ -1,4 +1,5 @@ -using CalamityMod.Buffs.Summon; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Buffs.Summon; using CalamityMod.Items.Weapons.Summon; using CalamityMod.Projectiles.BaseProjectiles; using Microsoft.Xna.Framework; @@ -211,6 +212,8 @@ namespace CalamityMod.Projectiles.Summon // The minion will only have contact damage if it's on latching mode. public override bool MinionContactDamage() => State == AIState.Latching; + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 240); + // The minion will do 1.5x damage if it's latched on. public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) => modifiers.SourceDamage *= CalamarisLament.LatchingDamageMultiplier; diff --git a/Projectiles/Summon/CalamarisLamentProjectile.cs b/Projectiles/Summon/CalamarisLamentProjectile.cs index fc710a4973..6b89f77c5d 100644 --- a/Projectiles/Summon/CalamarisLamentProjectile.cs +++ b/Projectiles/Summon/CalamarisLamentProjectile.cs @@ -1,4 +1,5 @@ -using CalamityMod.Items.Weapons.Summon; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Items.Weapons.Summon; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -72,6 +73,8 @@ namespace CalamityMod.Projectiles.Summon // and hit DoG's head and/or tail reliably and without penetration. public override bool? CanDamage() => Projectile.getRect().Intersects(TargetShot.getRect()) ? null : false; + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 120); + public override void OnKill(int timeLeft) { for (int i = 0; i < 15; i++) From 190e1a6f0f3f8fe004c4b89a3d52663ca6494978 Mon Sep 17 00:00:00 2001 From: mochi-angel Date: Sun, 23 Feb 2025 17:22:38 -0800 Subject: [PATCH 05/18] ADS now grants resistance to Hado --- CalPlayer/CalamityPlayerMiscEffects.cs | 6 +++++- Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson | 1 + Projectiles/Rogue/JawsProjectile.cs | 6 +----- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/CalPlayer/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index 9889e84da4..e272f79f54 100644 --- a/CalPlayer/CalamityPlayerMiscEffects.cs +++ b/CalPlayer/CalamityPlayerMiscEffects.cs @@ -2710,7 +2710,7 @@ namespace CalamityMod.CalPlayer abyssBreathLossRateStat = (float)tick; // Reduce breath over ticks (frames) - abyssBreathCD++; + abyssBreathCD++; if (abyssBreathCD >= (int)tick) { // Reset modded breath variable @@ -2718,7 +2718,11 @@ namespace CalamityMod.CalPlayer // Reduce breath if (Player.breath > 0) + { + Main.NewText(Player.breath); Player.breath -= (int)(cDepth && !depthCharm ? breathLoss + 1D : breathLoss); + Player.breath -= (int)(hadopelagicpressure && !abyssalDivingSuit ? breathLoss + 0.5D : breathLoss); + } } // If breath is greater than 0 and player has gills or is merfolk, balance out the effects by reducing breath diff --git a/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson b/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson index a83fa2f974..3d43ec34de 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson @@ -34,6 +34,7 @@ AbyssalDivingSuit: { Provides a moderate amount of light and reduces breath loss in the abyss Abyss creatures are less likely to see you, mitigates the abyss' defense reduction, and lets you sink faster in liquids Grants immunity to the sulphurous waters and Crush Depth's increased breath loss + Grants resistance to the increased breath loss caused by Hadopelagic Pressure ''' } diff --git a/Projectiles/Rogue/JawsProjectile.cs b/Projectiles/Rogue/JawsProjectile.cs index 1e269dbca3..25b55a5c37 100644 --- a/Projectiles/Rogue/JawsProjectile.cs +++ b/Projectiles/Rogue/JawsProjectile.cs @@ -65,8 +65,7 @@ namespace CalamityMod.Projectiles.Rogue if (Projectile.Calamity().stealthStrike) { target.AddBuff(ModContent.BuffType(), 120); - int shockwaveDamage = (int)player.GetTotalDamage().ApplyTo(100f); - Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), shockwaveDamage, 10f, Projectile.owner, 0, 0); + Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), Projectile.damage, 10f, Projectile.owner, 0, 0); } } @@ -77,11 +76,8 @@ namespace CalamityMod.Projectiles.Rogue target.AddBuff(ModContent.BuffType(), 120); if (Projectile.Calamity().stealthStrike) { - target.AddBuff(ModContent.BuffType(), 120); Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), Projectile.damage, 10f, Projectile.owner, 0, 0); target.AddBuff(ModContent.BuffType(), 120); - int shockwaveDamage = (int)player.GetTotalDamage().ApplyTo(100f); - Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), shockwaveDamage, 10f, Projectile.owner, 0, 0); } } From 5460935913c34cf87216f229dc3a3c324af512f3 Mon Sep 17 00:00:00 2001 From: mochi-angel Date: Sun, 23 Feb 2025 17:28:05 -0800 Subject: [PATCH 06/18] I fucked it up ignore the last commit --- CalPlayer/CalamityPlayerMiscEffects.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CalPlayer/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index e272f79f54..0b69b5e284 100644 --- a/CalPlayer/CalamityPlayerMiscEffects.cs +++ b/CalPlayer/CalamityPlayerMiscEffects.cs @@ -2709,6 +2709,8 @@ namespace CalamityMod.CalPlayer // Record the final breath loss rate for the stat meter abyssBreathLossRateStat = (float)tick; + float resistanceSlowdownFactor = 1f; + // Reduce breath over ticks (frames) abyssBreathCD++; if (abyssBreathCD >= (int)tick) @@ -2721,7 +2723,9 @@ namespace CalamityMod.CalPlayer { Main.NewText(Player.breath); Player.breath -= (int)(cDepth && !depthCharm ? breathLoss + 1D : breathLoss); - Player.breath -= (int)(hadopelagicpressure && !abyssalDivingSuit ? breathLoss + 0.5D : breathLoss); + + if (hadopelagicpressure) + resistanceSlowdownFactor -= (int)(!abyssalDivingSuit ? 1.2f : 0.5f); } } From 04423ec283cc82900d15ef1efc4d5d897b576ba8 Mon Sep 17 00:00:00 2001 From: mochi-angel Date: Sun, 23 Feb 2025 17:30:16 -0800 Subject: [PATCH 07/18] Slight edit to a death message --- CalPlayer/CalamityPlayerMiscEffects.cs | 2 +- Localization/en-US/Mods.CalamityMod.Status.Death.hjson | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CalPlayer/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index 0b69b5e284..3fe22550ce 100644 --- a/CalPlayer/CalamityPlayerMiscEffects.cs +++ b/CalPlayer/CalamityPlayerMiscEffects.cs @@ -2713,7 +2713,7 @@ namespace CalamityMod.CalPlayer // Reduce breath over ticks (frames) abyssBreathCD++; - if (abyssBreathCD >= (int)tick) + if (abyssBreathCD >= (int)(tick * resistanceSlowdownFactor)) { // Reset modded breath variable abyssBreathCD = 0; diff --git a/Localization/en-US/Mods.CalamityMod.Status.Death.hjson b/Localization/en-US/Mods.CalamityMod.Status.Death.hjson index bb50bd0532..b6d5d5cbc1 100644 --- a/Localization/en-US/Mods.CalamityMod.Status.Death.hjson +++ b/Localization/en-US/Mods.CalamityMod.Status.Death.hjson @@ -54,7 +54,7 @@ CrushDepth2: "{0}'s lungs collapsed." CrushDepth3: "{0}'s bones crunched under the deep pressure." HadopelagicPressure1: "{0} couldn't see the radiant light." HadopelagicPressure2: "{0}'s body was never found." -HadopelagicPressure3: "{0} was crushed by nature." +HadopelagicPressure3: "{0} was crushed by the void." Daybroken: "{0} was incinerated by solar rays." Dragonfire1: "{0}'s ashes scatter in the wind." Dragonfire2: "{0}'s embers fade away in a warm glow." From 6f1e5086e1e49b8990edbbd64329a8ab61431d5d Mon Sep 17 00:00:00 2001 From: mochi-angel Date: Sun, 23 Feb 2025 17:39:35 -0800 Subject: [PATCH 08/18] Final cleanup --- CalPlayer/CalamityPlayerHitHurt.cs | 1 - .../en-US/Mods.CalamityMod.Items.Armor.PostMoonLord.hjson | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/CalPlayer/CalamityPlayerHitHurt.cs b/CalPlayer/CalamityPlayerHitHurt.cs index 5e75182c77..4c4b07ed02 100644 --- a/CalPlayer/CalamityPlayerHitHurt.cs +++ b/CalPlayer/CalamityPlayerHitHurt.cs @@ -455,7 +455,6 @@ namespace CalamityMod.CalPlayer { damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.HadopelagicPressure" + Main.rand.Next(1, 3 + 1)).Format(Player.name)); } - if (bFlames || weakBrimstoneFlames) if (bFlames || weakBrimstoneFlames || demonicFlames) { damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.BrimstoneFlames" + Main.rand.Next(1, 3 + 1)).Format(Player.name)); diff --git a/Localization/en-US/Mods.CalamityMod.Items.Armor.PostMoonLord.hjson b/Localization/en-US/Mods.CalamityMod.Items.Armor.PostMoonLord.hjson index 360e51e89a..f94a0fd15a 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Armor.PostMoonLord.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Armor.PostMoonLord.hjson @@ -369,7 +369,7 @@ OmegaBlueChestplate: { Tooltip: ''' 12% increased damage and 8% increased critical strike chance - Your attacks inflict Crush Depth + Your attacks inflict Hadopelagic Pressure No positive life regen ''' } From 52a266c8bd9d03dc5878f7bab665ac1a4c8f9fe4 Mon Sep 17 00:00:00 2001 From: mochi-angel Date: Sun, 23 Feb 2025 17:57:32 -0800 Subject: [PATCH 09/18] Localization is in the proper area now --- Localization/en-US/Mods.CalamityMod.Buffs.hjson | 10 +++++----- Projectiles/Ranged/AstralRound.cs | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Localization/en-US/Mods.CalamityMod.Buffs.hjson b/Localization/en-US/Mods.CalamityMod.Buffs.hjson index 18a19f4736..a14bf4da75 100644 --- a/Localization/en-US/Mods.CalamityMod.Buffs.hjson +++ b/Localization/en-US/Mods.CalamityMod.Buffs.hjson @@ -1008,6 +1008,11 @@ GlacialState: { Description: Cannot move } +HadopelagicPressure: { + DisplayName: Hadopelagic Pressure + Description: Rapidly sinking to a watery grave +} + IcarusFolly: { DisplayName: Icarus' Folly Description: @@ -1598,8 +1603,3 @@ PopoNoselessBuff: { DisplayName: Noseless Popo Description: Your nose has been stolen! } - -HadopelagicPressure: { - DisplayName: Hadopelagic Pressure - Description: Rapidly sinking to a watery grave -} diff --git a/Projectiles/Ranged/AstralRound.cs b/Projectiles/Ranged/AstralRound.cs index 145dd26d58..834728bd1c 100644 --- a/Projectiles/Ranged/AstralRound.cs +++ b/Projectiles/Ranged/AstralRound.cs @@ -76,7 +76,7 @@ namespace CalamityMod.Projectiles.Ranged } public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 900); + target.AddBuff(ModContent.BuffType(), 120); } } } From cfeb14cbc6d822ff5fc8791f920c35c40bc108af Mon Sep 17 00:00:00 2001 From: CongratsIsTrash <1q2w3e4dasd@gmail.com> Date: Sat, 1 Mar 2025 13:03:27 -0500 Subject: [PATCH 10/18] Moved biome key drops off of bosses As decided by a democracy vote over a year ago Frozen: Ice Golem @ 10% Desert: Sand Elemental @ 10% Corruption: Corrupt Mimic @ 10% Crimson: Crimson Mimic @ 10% Hallow: Hallowed Mimic @ 10% Jungle: Lihzahrd and Flying Snake @ 0.67% --- NPCs/CalamityGlobalNPCLoot.cs | 50 +++++++++++++++++++-------- NPCs/Cryogen/Cryogen.cs | 2 -- NPCs/GreatSandShark/GreatSandShark.cs | 3 -- 3 files changed, 36 insertions(+), 19 deletions(-) diff --git a/NPCs/CalamityGlobalNPCLoot.cs b/NPCs/CalamityGlobalNPCLoot.cs index 7ebe6fa3cd..a35904f55e 100644 --- a/NPCs/CalamityGlobalNPCLoot.cs +++ b/NPCs/CalamityGlobalNPCLoot.cs @@ -221,9 +221,11 @@ namespace CalamityMod.NPCs // Sand Elemental // Elemental in a Bottle @ 20% Normal, 33.33% Expert+ // Rare Elemental in a Bottle @ 10% Normal, 16.67% Expert+ + // Desert Key @ 10% case NPCID.SandElemental: npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 5, 3)); npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 10, 6)); + npcLoot.Add(ItemID.DungeonDesertKey, 10); break; #endregion @@ -302,8 +304,10 @@ namespace CalamityMod.NPCs // Ice Golem // 8-10 Essence of Eleum @ 100%, 10-12 Expert+ + // Frozen Key @ 10% case NPCID.IceGolem: npcLoot.Add(DropHelper.NormalVsExpertQuantity(ModContent.ItemType(), 1, 8, 10, 10, 12)); + npcLoot.Add(ItemID.FrozenKey, 10); break; #endregion @@ -363,13 +367,27 @@ namespace CalamityMod.NPCs npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 25, 15)); break; - // Biome Mimics + // Corrupt Mimic // Celestial Claymore @ 14.29% Normal, 25% Expert+ - case NPCID.BigMimicHallow: case NPCID.BigMimicCorruption: - case NPCID.BigMimicCrimson: - case NPCID.BigMimicJungle: npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 7, 4)); + npcLoot.Add(ItemID.CorruptionKey, 10); + break; + + // Crimson Mimic + // Celestial Claymore @ 14.29% Normal, 25% Expert+ + // Crimson Key @ 10% + case NPCID.BigMimicCrimson: + npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 7, 4)); + npcLoot.Add(ItemID.CrimsonKey, 10); + break; + + // Hallowed Mimic + // Celestial Claymore @ 14.29% Normal, 25% Expert+ + // Hallowed Key @ 10% + case NPCID.BigMimicHallow: + npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 7, 4)); + npcLoot.Add(ItemID.HallowedKey, 10); break; // World Feeder @@ -411,6 +429,20 @@ namespace CalamityMod.NPCs case NPCID.Moth: npcLoot.ChangeDropRate(ItemID.ButterflyDust, 1, 1); break; + + // Jungle Mimic + // Celestial Claymore @ 14.29% Normal, 25% Expert+ + case NPCID.BigMimicJungle: + npcLoot.Add(ItemDropRule.NormalvsExpert(ModContent.ItemType(), 7, 4)); + break; + + // Lihzahrd + Flying Snake + // Jungle Key @ 0.67% + case NPCID.Lihzahrd: + case NPCID.LihzahrdCrawler: + case NPCID.FlyingSnake: + npcLoot.Add(ItemID.JungleKey, 150); + break; #endregion #region Dungeon @@ -1222,10 +1254,6 @@ namespace CalamityMod.NPCs // Would be in the bag otherwise npcLoot.AddNormalOnly(ModContent.ItemType(), ThankYouPainting.DropInt); - // WoF drops Evil Keys - npcLoot.Add(ItemID.CorruptionKey, 3); - npcLoot.Add(ItemID.CrimsonKey, 3); - // Master items drop in Revengeance rev.Add(ItemID.WallofFleshMasterTrophy); rev.Add(ItemID.WallOfFleshGoatMountItem, 4); @@ -1248,9 +1276,6 @@ namespace CalamityMod.NPCs // Would be in the bag otherwise npcLoot.AddNormalOnly(ModContent.ItemType(), ThankYouPainting.DropInt); - // Queen Slime drops the Hallowed Key - npcLoot.Add(ItemID.HallowedKey, 3); - // Master items drop in Revengeance rev.Add(ItemID.QueenSlimeMasterTrophy); rev.Add(ItemID.QueenSlimePetItem, 4); @@ -1404,9 +1429,6 @@ namespace CalamityMod.NPCs npcLoot.AddNormalOnly(DropHelper.PerPlayer(ModContent.ItemType(), 1, 25, 30)); npcLoot.AddNormalOnly(ModContent.ItemType(), ThankYouPainting.DropInt); - // Plantera drops Jungle Key - npcLoot.Add(ItemID.JungleKey, 3); - // Master items drop in Revengeance rev.Add(ItemID.PlanteraMasterTrophy); rev.Add(ItemID.PlanteraPetItem, 4); diff --git a/NPCs/Cryogen/Cryogen.cs b/NPCs/Cryogen/Cryogen.cs index 3fda713ab3..cc397cdec9 100644 --- a/NPCs/Cryogen/Cryogen.cs +++ b/NPCs/Cryogen/Cryogen.cs @@ -1428,8 +1428,6 @@ namespace CalamityMod.NPCs.Cryogen normalOnly.Add(ModContent.ItemType(), DropHelper.NormalWeaponDropRateFraction); } - npcLoot.Add(ItemID.FrozenKey, 3); - // Trophy (always directly from boss, never in bag) npcLoot.Add(ModContent.ItemType(), 10); diff --git a/NPCs/GreatSandShark/GreatSandShark.cs b/NPCs/GreatSandShark/GreatSandShark.cs index e295167654..008c2637d5 100644 --- a/NPCs/GreatSandShark/GreatSandShark.cs +++ b/NPCs/GreatSandShark/GreatSandShark.cs @@ -677,9 +677,6 @@ IL_6899: { npcLoot.Add(ItemID.AncientBattleArmorMaterial); - // Great Sand Shark drops the Desert Key - npcLoot.Add(ItemID.DungeonDesertKey, 3); - // 1 Grand Scale guaranteed; on Expert, 33% chance of getting a second one npcLoot.Add(ModContent.ItemType()); npcLoot.AddIf(() => Main.expertMode, ModContent.ItemType(), 3); From 83cf3554eb393ae5a9ded359e78d2851036d5a7c Mon Sep 17 00:00:00 2001 From: Ozzatron Date: Sat, 1 Mar 2025 13:45:41 -0500 Subject: [PATCH 11/18] 1 - Improve Hadopelagic Pressure death messages. 2 - Change internal debuff name to match other debuffs. --- Buffs/DamageOverTime/HadopelagicPressure.cs | 6 +++--- CalPlayer/CalamityPlayer.cs | 6 +++--- CalPlayer/CalamityPlayerDrawEffects.cs | 2 +- CalPlayer/CalamityPlayerHitHurt.cs | 2 +- CalPlayer/CalamityPlayerLifeRegen.cs | 2 +- CalPlayer/CalamityPlayerMiscEffects.cs | 2 +- .../en-US/Mods.CalamityMod.Status.Death.hjson | 6 +++--- NPCs/CalamityGlobalNPC.cs | 14 +++++++------- 8 files changed, 20 insertions(+), 20 deletions(-) diff --git a/Buffs/DamageOverTime/HadopelagicPressure.cs b/Buffs/DamageOverTime/HadopelagicPressure.cs index 3893bbf245..f4edd97b85 100644 --- a/Buffs/DamageOverTime/HadopelagicPressure.cs +++ b/Buffs/DamageOverTime/HadopelagicPressure.cs @@ -19,13 +19,13 @@ namespace CalamityMod.Buffs.DamageOverTime public override void Update(Player player, ref int buffIndex) { - player.Calamity().hadopelagicpressure = true; + player.Calamity().hPressure = true; } public override void Update(NPC npc, ref int buffIndex) { - if (npc.Calamity().hadopelagicpressure < npc.buffTime[buffIndex]) - npc.Calamity().hadopelagicpressure = npc.buffTime[buffIndex]; + if (npc.Calamity().hPressure < npc.buffTime[buffIndex]) + npc.Calamity().hPressure = npc.buffTime[buffIndex]; npc.DelBuff(buffIndex); buffIndex--; } diff --git a/CalPlayer/CalamityPlayer.cs b/CalPlayer/CalamityPlayer.cs index cb7da226ab..f79064373e 100644 --- a/CalPlayer/CalamityPlayer.cs +++ b/CalPlayer/CalamityPlayer.cs @@ -1204,7 +1204,7 @@ namespace CalamityMod.CalPlayer public bool warped = false; public bool cDepth = false; public bool rTide = false; - public bool hadopelagicpressure = false; + public bool hPressure = false; public bool fishAlert = false; public bool clamity = false; public bool NOU = false; @@ -2390,7 +2390,7 @@ namespace CalamityMod.CalPlayer warped = false; cDepth = false; rTide = false; - hadopelagicpressure = false; + hPressure = false; fishAlert = false; clamity = false; NOU = false; @@ -2846,7 +2846,7 @@ namespace CalamityMod.CalPlayer warped = false; cDepth = false; rTide = false; - hadopelagicpressure = false; + hPressure = false; fishAlert = false; clamity = false; NOU = false; diff --git a/CalPlayer/CalamityPlayerDrawEffects.cs b/CalPlayer/CalamityPlayerDrawEffects.cs index 447765f33d..eaaeda1189 100644 --- a/CalPlayer/CalamityPlayerDrawEffects.cs +++ b/CalPlayer/CalamityPlayerDrawEffects.cs @@ -263,7 +263,7 @@ namespace CalamityMod.CalPlayer if (drawInfo.shadow == 0f && (calamityPlayer.hFlames || calamityPlayer.hInferno || calamityPlayer.banishingFire)) HolyFlames.DrawEffects(drawInfo); - if (calamityPlayer.hadopelagicpressure && drawInfo.shadow == 0f) + if (calamityPlayer.hPressure && drawInfo.shadow == 0f) HadopelagicPressure.DrawEffects(drawInfo); // Icarus' Folly has visual effects but they are mutually exclusive with all Holy Flames variations to prevent visual clutter diff --git a/CalPlayer/CalamityPlayerHitHurt.cs b/CalPlayer/CalamityPlayerHitHurt.cs index 4c4b07ed02..2ef0997336 100644 --- a/CalPlayer/CalamityPlayerHitHurt.cs +++ b/CalPlayer/CalamityPlayerHitHurt.cs @@ -451,7 +451,7 @@ namespace CalamityMod.CalPlayer { damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.Riptide" + Main.rand.Next(1, 2 + 1)).Format(Player.name)); } - if (hadopelagicpressure) + if (hPressure) { damageSource = PlayerDeathReason.ByCustomReason(CalamityUtils.GetText("Status.Death.HadopelagicPressure" + Main.rand.Next(1, 3 + 1)).Format(Player.name)); } diff --git a/CalPlayer/CalamityPlayerLifeRegen.cs b/CalPlayer/CalamityPlayerLifeRegen.cs index cb5cf46359..5a65730151 100644 --- a/CalPlayer/CalamityPlayerLifeRegen.cs +++ b/CalPlayer/CalamityPlayerLifeRegen.cs @@ -120,7 +120,7 @@ namespace CalamityMod.CalPlayer ApplyDoTDebuff(trueVHex, 50); ApplyDoTDebuff(cDepth, 18, purity); ApplyDoTDebuff(astralInfection, 24, infectedJewel || hideOfDeus || purity); - ApplyDoTDebuff(hadopelagicpressure, 40, purity); + ApplyDoTDebuff(hPressure, 40, purity); ApplyDoTDebuff(pFlames, alchFlask ? 10 : 30, purity); ApplyDoTDebuff(cragsLava, 30); ApplyDoTDebuff(shadowflame, 30, purity); diff --git a/CalPlayer/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index 11e0d986a0..a6c43fed1c 100644 --- a/CalPlayer/CalamityPlayerMiscEffects.cs +++ b/CalPlayer/CalamityPlayerMiscEffects.cs @@ -2818,7 +2818,7 @@ namespace CalamityMod.CalPlayer Main.NewText(Player.breath); Player.breath -= (int)(cDepth && !depthCharm ? breathLoss + 1D : breathLoss); - if (hadopelagicpressure) + if (hPressure) resistanceSlowdownFactor -= (int)(!abyssalDivingSuit ? 1.2f : 0.5f); } } diff --git a/Localization/en-US/Mods.CalamityMod.Status.Death.hjson b/Localization/en-US/Mods.CalamityMod.Status.Death.hjson index b6d5d5cbc1..472bb07020 100644 --- a/Localization/en-US/Mods.CalamityMod.Status.Death.hjson +++ b/Localization/en-US/Mods.CalamityMod.Status.Death.hjson @@ -52,9 +52,9 @@ CorpusAvertor: "{0} became the Blood God's sacrifice." CrushDepth1: "{0} was crushed by the pressure." CrushDepth2: "{0}'s lungs collapsed." CrushDepth3: "{0}'s bones crunched under the deep pressure." -HadopelagicPressure1: "{0} couldn't see the radiant light." -HadopelagicPressure2: "{0}'s body was never found." -HadopelagicPressure3: "{0} was crushed by the void." +HadopelagicPressure1: "{0} was crushed in the lightless void." +HadopelagicPressure2: "{0} was reduced to a smear of waterlogged paste." +HadopelagicPressure3: "{0} suffered a critical pressurization event." Daybroken: "{0} was incinerated by solar rays." Dragonfire1: "{0}'s ashes scatter in the wind." Dragonfire2: "{0}'s embers fade away in a warm glow." diff --git a/NPCs/CalamityGlobalNPC.cs b/NPCs/CalamityGlobalNPC.cs index 30f64924ff..4901c9851d 100644 --- a/NPCs/CalamityGlobalNPC.cs +++ b/NPCs/CalamityGlobalNPC.cs @@ -358,7 +358,7 @@ namespace CalamityMod.NPCs public int cDepth = 0; public int rTide = 0; - public int hadopelagicpressure = 0; + public int hPressure = 0; public int gsInferno = 0; public int dragonFire = 0; public int vermillionFlux = 0; @@ -609,7 +609,7 @@ namespace CalamityMod.NPCs myClone.cDepth = cDepth; myClone.rTide = rTide; - myClone.hadopelagicpressure = hadopelagicpressure; + myClone.hPressure = hPressure; myClone.gsInferno = gsInferno; myClone.miracleBlight = miracleBlight; myClone.dragonFire = dragonFire; @@ -1274,7 +1274,7 @@ namespace CalamityMod.NPCs } //Hadopelagic Pressure - if (hadopelagicpressure > 0) + if (hPressure > 0) { int baseHadopelagicPressureDoTValue = (int)(400 * waterDamageMult); ApplyDPSDebuff(baseHadopelagicPressureDoTValue, baseHadopelagicPressureDoTValue / 2, ref npc.lifeRegen, ref damage); @@ -5646,8 +5646,8 @@ namespace CalamityMod.NPCs crumble--; if (cDepth > 0) cDepth--; - if (hadopelagicpressure > 0) - hadopelagicpressure--; + if (hPressure > 0) + hPressure--; if (rTide > 0) rTide--; if (gsInferno > 0) @@ -7199,7 +7199,7 @@ namespace CalamityMod.NPCs if (cDepth > 0) CrushDepth.DrawEffects(npc, ref drawColor); - if (hadopelagicpressure > 0) + if (hPressure > 0) HadopelagicPressure.DrawEffects(npc, ref drawColor); if (dragonFire > 0) @@ -7418,7 +7418,7 @@ namespace CalamityMod.NPCs ("CalamityMod/Buffs/DamageOverTime/Dragonfire", NPC => NPC.Calamity().dragonFire > 0), ("CalamityMod/Buffs/DamageOverTime/ElementalMix", NPC => NPC.Calamity().elementalMix > 0), ("CalamityMod/Buffs/DamageOverTime/GodSlayerInferno", NPC => NPC.Calamity().gsInferno > 0), - ("CalamityMod/Buffs/DamageOverTime/HadopelagicPressure", NPC => NPC.Calamity().hadopelagicpressure > 0), + ("CalamityMod/Buffs/DamageOverTime/HadopelagicPressure", NPC => NPC.Calamity().hPressure > 0), ("CalamityMod/Buffs/DamageOverTime/HolyFlames", NPC => NPC.Calamity().hFlames > 0), ("CalamityMod/Buffs/DamageOverTime/Laceration", NPC => NPC.Calamity().laceration > 0), ("CalamityMod/Buffs/DamageOverTime/HeavyBleeding", NPC => NPC.Calamity().heavybleeding > 0), From 7dae1c829aaa09917a295604533e15a5b2fef853 Mon Sep 17 00:00:00 2001 From: CongratsIsTrash <1q2w3e4dasd@gmail.com> Date: Sat, 1 Mar 2025 13:54:02 -0500 Subject: [PATCH 12/18] Hado Pressure debug text dies --- CalPlayer/CalamityPlayerMiscEffects.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/CalPlayer/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index 5b0d9a934d..4cb915bd96 100644 --- a/CalPlayer/CalamityPlayerMiscEffects.cs +++ b/CalPlayer/CalamityPlayerMiscEffects.cs @@ -2828,7 +2828,6 @@ namespace CalamityMod.CalPlayer // Reduce breath if (Player.breath > 0) { - Main.NewText(Player.breath); Player.breath -= (int)(cDepth && !depthCharm ? breathLoss + 1D : breathLoss); if (hPressure) From 4ef36e28a8fb643753e23fb9d4d8215db76edf0d Mon Sep 17 00:00:00 2001 From: NycroV <83246959+NycroV@users.noreply.github.com> Date: Wed, 5 Feb 2025 14:13:24 -0500 Subject: [PATCH 13/18] Basic implementation of an interface for providing pathfinding functionality. For Memes <3 --- NPCs/SunkenSea/Sharkoon.cs | 74 +++++++++------------ Utilities/PathfindingUtils.cs | 120 ++++++++++++++++++++++++++++++++++ 2 files changed, 152 insertions(+), 42 deletions(-) diff --git a/NPCs/SunkenSea/Sharkoon.cs b/NPCs/SunkenSea/Sharkoon.cs index 90b6707b47..74c11e6a09 100644 --- a/NPCs/SunkenSea/Sharkoon.cs +++ b/NPCs/SunkenSea/Sharkoon.cs @@ -18,7 +18,7 @@ using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { - public class Sharkoon : SunkenSeaNPC + public class Sharkoon : SunkenSeaNPC, IPathFinder { public static float DistanceToKaboom = 80f; public static float IdleMovementMaxRange = 300f; @@ -26,8 +26,6 @@ namespace CalamityMod.NPCs.SunkenSea public static float TimeToRecover = 600f; public static float TimeRecovering = 120f; - private Task> _pathfindingTask = null; - #region Fields & Properties protected override List HuntNPCs => new() @@ -129,16 +127,6 @@ namespace CalamityMod.NPCs.SunkenSea /// private ref float RecoverTimer => ref NPC.ai[2]; - /// - /// The maximum speed this NPC can have, it cannot be faster than this number. - /// - private float MaximumSpeed = 4f; - - /// - /// The acceleration of the Sharkoon. - /// - private const float Acceleration = 0.25f; - /// /// How unlikely is the Sharkoon going to move normally.
/// Defaults to 250. @@ -159,6 +147,18 @@ namespace CalamityMod.NPCs.SunkenSea protected override float SpawningChance => SpawnCondition.CaveJellyfish.Chance * 0.9f; + public CalamityUtils.PathfindingParams Pathfinding { get; set; } + + public Task> Paths { 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; } = 4f; + /// /// The squish of this NPC while drawing. /// @@ -268,7 +268,7 @@ namespace CalamityMod.NPCs.SunkenSea } if (Personality == PersonalityType.Paranoid) - MaximumSpeed *= 1.5f; + MaxSpeed *= 1.5f; NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; @@ -312,10 +312,6 @@ namespace CalamityMod.NPCs.SunkenSea if (!NPC.wet && !IsExploding) CurrentBehavior = OutsideWaterBehavior; - // Clamps the velocity at all times. - if (NPC.velocity.LengthSquared() > MaximumSpeed * MaximumSpeed) - NPC.velocity = NPC.velocity.SafeNormalize(Vector2.UnitY) * MaximumSpeed; - if (ScaleSquish.Y > 1f) { ScaleSquish.Y -= 0.025f; @@ -384,17 +380,15 @@ namespace CalamityMod.NPCs.SunkenSea private void IdlingBehavior() { - if (_pathfindingTask.Result != null) - { - // While it hasn't decided yet which path to follow, it'll deaccelerate and stand still. - NPC.velocity *= 0.95f; + // Randomly, it'll decide a path whose destination is somewhere around him. + if (Main.rand.NextBool(RandomIdleMovementUnlikeliness)) + Pathfinding = new(NPC.Center, Main.rand.NextVector2Circular(400f, 400f), SunkenSeaTileValidity); - // Randomly, it'll decide a path whose destination is somewhere around him. - if (Main.rand.NextBool(RandomIdleMovementUnlikeliness) && !_pathfindingTask.IsCompleted) - _pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, Main.rand.NextVector2Circular(400f, 400f), SunkenSeaTileValidity)); - } + // While it hasn't decided yet which path to follow, it'll deaccelerate and stand still. else - GenericPathFollowing(Acceleration); + Pathfinding = null; + + this.DoPathfinding(); } private void HuntBehavior() @@ -408,14 +402,10 @@ namespace CalamityMod.NPCs.SunkenSea if (!HasLineOfSight(CurrentPrey.Center)) { - if (_pathfindingTask.Result != null) - PathfindingPoints = _pathfindingTask.Result; - - if (_pathfindingTask.Result != null) - GenericPathFollowing(Acceleration); - else - _pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); + Pathfinding = new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity); + this.DoPathfinding(); } + else NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; } @@ -448,6 +438,7 @@ namespace CalamityMod.NPCs.SunkenSea const int MaxAttemptsToFindPath = 20; const int MinimumEscapeDistance = 160; const int MaximumEscapeDistance = 320; + if (Main.tile[(NPC.Center + NPC.DirectionFrom(entityToAvoid.Center) * TileAnticipationDistance).ToTileCoordinates()].IsTileSolid() && !HasPath) { Vector2 randomEscapePoint; @@ -459,15 +450,14 @@ namespace CalamityMod.NPCs.SunkenSea } while (Main.tile[randomEscapePoint.ToTileCoordinates()].IsTileSolid() || attempts < MaxAttemptsToFindPath); - _pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, randomEscapePoint, SunkenSeaTileValidity)); + Pathfinding = new(NPC.Center, randomEscapePoint, SunkenSeaTileValidity); } - if (_pathfindingTask.Result != null) - PathfindingPoints = _pathfindingTask.Result; + // Attempt to path find through an escape route. + this.DoPathfinding(); - if (HasPath) - GenericPathFollowing(Acceleration); - else + // If one couldn't be found, just try to swim away. + if (Paths.IsCompleted && Paths.Result == null) NPC.velocity += NPC.DirectionFrom(entityToAvoid.Center) * Acceleration; // If it's capable of exploding and the predator's within distance, kaboom. @@ -631,7 +621,7 @@ namespace CalamityMod.NPCs.SunkenSea writer.Write7BitEncodedInt(AnimationFrames); writer.Write7BitEncodedInt(TimePerAnimationFrame); writer.Write(AnimationLoop); - writer.Write(MaximumSpeed); + writer.Write(MaxSpeed); writer.Write7BitEncodedInt(RandomIdleMovementUnlikeliness); } @@ -641,7 +631,7 @@ namespace CalamityMod.NPCs.SunkenSea AnimationFrames = reader.Read7BitEncodedInt(); TimePerAnimationFrame = reader.Read7BitEncodedInt(); AnimationLoop = reader.ReadBoolean(); - MaximumSpeed = reader.ReadSingle(); + MaxSpeed = reader.ReadSingle(); RandomIdleMovementUnlikeliness = reader.Read7BitEncodedInt(); } diff --git a/Utilities/PathfindingUtils.cs b/Utilities/PathfindingUtils.cs index c157e2ddcf..b2d4c8854c 100644 --- a/Utilities/PathfindingUtils.cs +++ b/Utilities/PathfindingUtils.cs @@ -1,13 +1,128 @@ using System; using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Terraria; +using static CalamityMod.CalamityUtils; namespace CalamityMod { + /// + /// Represents an entity that is capable of finding and following a complex path.
+ /// To use this interface, supply all of the required properties, and then simply call this.DoPathfinding() in your entity's movement logic. + ///
+ public interface IPathFinder + { + /// + /// The parameters to be used in that determines how pathfinding should be calculated.
+ /// This can return if you do not want the entity to find a path. + ///
+ public PathfindingParams Pathfinding { get; } + + /// + /// The result of the pathfinding task that contains a set of points this entity should follow. + /// + public Task> Paths { get; set; } + + /// + /// The current position of this entity. Only used to calculate movement for this entity, not pathfinding.
+ /// In most cases, this should look like the following, where ENTITY is replace by your entity instance. + /// public Vector2 Position { get => ENTITY.center; } + ///
+ public Vector2 Position { get; } + + /// + /// The current velocity of this entity. Only used to calculate movement for this entity, not pathfinding.
+ /// In most cases, this should look like the following, where ENTITY is replace by your entity instance. + /// public Vector2 Velocity { get => ENTITY.velocity; } + ///
+ public Vector2 Velocity { get; set; } + + /// + /// The acceleration this entity should use when moving. Only used to calculate movement for this entity, not pathfinding. + /// + public float Acceleration { get; } + + /// + /// The maximum speed this entity should be able to reach while moving. Only used to calculate movement for this entity, not pathfinding. + /// + public float MaxSpeed { get; } + + /// + /// 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. + ///
+ /// + /// + public bool FollowPath(Vector2 nextPoint) + { + // Accelerate to the target point. + Velocity += Vector2.Normalize(nextPoint - Position) * Acceleration; + + // Cap the speed if MaxSpeed has been surpassed. + if (Velocity.LengthSquared() > MaxSpeed * MaxSpeed) + Velocity = Vector2.Normalize(Velocity) * MaxSpeed; + + // If the entity is within 48 pixels of its target point, consider the point reached. + if (Vector2.DistanceSquared(Position, nextPoint) < 48f * 48f) + return true; + + // Otherwise, continue following. + return false; + } + + /// + /// Defines how this entity should behave while there is no current path to follow.
+ /// By default, decelerates and stops based on . + ///
+ public void IdleBehavior() => Velocity -= Velocity.SafeNormalize(Vector2.Zero) * Math.Min(Velocity.Length(), Acceleration); + + /// + /// Assigns the value of to based on .
+ /// You can override this and do + public void FindPath() => Paths = FindPathAsync(Pathfinding); + } + public static partial class CalamityUtils { + /// + /// Causes this to perform path finding and follow the path result, idling when a path is not available.
+ /// This method should be called every frame that you want your entity to follow it's pathfinding logic. + ///
+ /// The entity that should be moving. + public static void DoPathfinding(this IPathFinder pathfinder) + { + // Checks to make sure that: + // A. The pathfinding task has completed + // B. There is a valid result + // C. There are points left in the previously found path + if (pathfinder.Paths.Result != null && + pathfinder.Paths.Result.Count > 0) + { + // Follows the point at index 0 of the path result. + Vector2 nextPoint = pathfinder.Paths.Result[0]; + + // Once that point is reached, it is removed from the list of points to follow. + if (pathfinder.FollowPath(nextPoint)) + pathfinder.Paths.Result.RemoveAt(0); + } + + // Idle if the task is currently finding a path or there is no path to be followed. + else + { + pathfinder.IdleBehavior(); + + // Only attempt to find a path again if the task is not currently running. + if (pathfinder.Paths.Status != TaskStatus.Running) + pathfinder.FindPath(); + } + } + /// /// Represents a node in a pathfinding algorithm, containing position, cost, and parent information. /// @@ -113,6 +228,11 @@ namespace CalamityMod { return await Task.Run(() => { + // If the entity isn't actually supposed to follow a path right now, null + // can be passed as the parameters to make implementation more concise. + if (parameters is null) + return null; + var openSet = new List(); var closedSet = new HashSet(); openSet.Add(parameters.Start); From 523a712987da75af1ed7944176b0fd39a73d6cb0 Mon Sep 17 00:00:00 2001 From: Memes <114233643+Mr-Memes@users.noreply.github.com> Date: Mon, 10 Feb 2025 12:08:44 +0100 Subject: [PATCH 14/18] Major change to IPathFinder. 1. Fixed lag in IPathFinder. 2. Deleted Pathfinding property in IPathFinder. 3. Improvements to SunkenSeaNPC to fit IPathFinder. 4. Adaptation of Probesnaut and Sharkoon to the new changes. --- NPCs/SunkenSea/Probesnout.cs | 249 ++++++------ NPCs/SunkenSea/Sharkoon.cs | 531 +++++++++++-------------- NPCs/SunkenSea/SunkenSeaNPC.cs | 425 ++++---------------- Projectiles/Enemy/SharkoonExplosion.cs | 4 +- Utilities/NPCUtils.cs | 2 + Utilities/PathfindingUtils.cs | 55 ++- 6 files changed, 445 insertions(+), 821 deletions(-) diff --git a/NPCs/SunkenSea/Probesnout.cs b/NPCs/SunkenSea/Probesnout.cs index 4ef95c1c49..adaa978d5f 100644 --- a/NPCs/SunkenSea/Probesnout.cs +++ b/NPCs/SunkenSea/Probesnout.cs @@ -3,51 +3,44 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using CalamityMod.Enums; -using CalamityMod.Particles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; +using Terraria.DataStructures; using Terraria.GameContent; using Terraria.ID; -using Terraria.Utilities; +using static CalamityMod.CalamityUtils; using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { - public class Probesnout : SunkenSeaNPC + public class Probesnout : SunkenSeaNPC, IPathFinder { - public static float PathDetectionSize = 300f; - private static Task> _pathfindingTask; - #region Members - protected override List HuntNPCs => new() - { - // NPCType(), - }; + public static int IdleRandomMovementUnlikeliness = 250; + public static int IdleMinPathDistance = 200; + public static int IdleMaxPathDistance = 400; - protected override List AvoidNPCs => new() - { + public static int FleeTileAnticipationDistance = 5 * 16; + public static int FleeMinPathDistance = 80; + public static int FleeMaxPathDistance = 160; + + protected override List PreyIDs => + [ + // NPCType(), + ]; + + protected override List PredatorIDs => + [ // NPCType(), NPCType(), // NPCType(), // NPCType(), // NPCType(), - }; + ]; - private enum PersonalityType { Curious, Shy, Paranoid } - - private PersonalityType Personality - { - get => (PersonalityType)NPC.ai[0]; - set - { - NPC.ai[0] = (float)value; - NetUpdate(); - } - } - - private enum AnimationState { Idle, Attack } + private enum AnimationState { Idle, Eating } private AnimationState Animation { @@ -66,166 +59,157 @@ namespace CalamityMod.NPCs.SunkenSea AnimationFrames = 8; TimePerAnimationFrame = 5; break; - case AnimationState.Attack: + case AnimationState.Eating: AnimationFrames = 12; TimePerAnimationFrame = 7; break; } NPC.ai[1] = (float)value; - NetUpdate(); } } protected override SunkenSeaBiomeFlags BiomeDesignation => SunkenSeaBiomeFlags.RadiantReefs; - protected override float SpawningChance => 0f; - private int AnimationFrames = 8; private int TimePerAnimationFrame = 5; - private float MaximumSpeed = 6f; - private Vector2 ScaleSquish = Vector2.One; + private Action _currentBehavior; + private Action CurrentBehavior + { + get => _currentBehavior; + set + { + if (value != _currentBehavior) + OnBehaviorChange(value); + _previousBehavior = _currentBehavior; + _currentBehavior = value; + } + } + + private Action _previousBehavior; + + public Task> Paths { get; set; } + + public Vector2 Position => NPC.Center; + + public Vector2 Velocity { get => NPC.velocity; set => NPC.velocity = value; } + + public float Acceleration => 0.4f; + + public float MaxSpeed => 8f; + #endregion #region AI - protected override void BehaviorOnSpawn() + protected override bool PlayerSearchFilter(Player p) { - CurrentBehavior = IdleBehavior; + return base.PlayerSearchFilter(p) || p == CurrentPlayer && Vector2.DistanceSquared(NPC.Center, p.Center) < 960f * 960f; + } - WeightedRandom randomPersonality = new(); - randomPersonality.Add(PersonalityType.Curious, 0.6f); - randomPersonality.Add(PersonalityType.Shy, 0.3f); - randomPersonality.Add(PersonalityType.Paranoid, 0.1f); - Personality = randomPersonality.Get(); + protected override bool NPCSearchFilter(NPC n) + { + return base.NPCSearchFilter(n) || (n == CurrentPrey || n == CurrentPredator) && Vector2.DistanceSquared(NPC.Center, n.Center) < 960f * 960f; + } + public override void OnSpawn(IEntitySource source) + { + CurrentBehavior = IdlingBehavior; NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; NPC.MaxFallSpeedMultiplier *= 2f; } - protected override void CreatureAI() + public override void AI() { - CurrentBehavior.Invoke(); + CurrentBehavior?.Invoke(); - if (!NPC.velocity.HasNaNs()) - ConeDetectionDirection = (NPC.rotation * MathF.Sign(NPC.velocity.Y) + (NPC.spriteDirection == -1 ? MathHelper.Pi : 0f)).ToRotationVector2(); + NPC.rotation = MathHelper.ToRadians(NPC.velocity.X * 3f); + NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); - NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X); - if (MathF.Abs(NPC.velocity.X) > 2f) - NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); if (!NPC.wet) CurrentBehavior = OutsideWaterBehavior; - if (NPC.velocity.LengthSquared() > MaximumSpeed * MaximumSpeed) - NPC.velocity = NPC.velocity.SafeNormalize(-Vector2.UnitY) * MaximumSpeed; - if (ScaleSquish.Y > 1f) + { ScaleSquish.Y -= 0.025f; - - if (ScaleSquish.Y < 1f) - ScaleSquish.Y = 1f; + if (ScaleSquish.Y < 1f) + ScaleSquish.Y = 1f; + } } - protected override void OnBehaviorChange(Action newBehavior) => NPC.noGravity = newBehavior != OutsideWaterBehavior; + private void OnBehaviorChange(Action newBehavior) => NPC.noGravity = newBehavior != OutsideWaterBehavior; protected override void OnPreyDetection(NPC prey) { // If it's not a small fish and it's not being chased by a predator, the Probesnout may hunt. - if (CurrentPredator is null) - { - CurrentBehavior = HuntBehavior; - React(Color.Orange * 0.6f, EmoteExpressionParticle.EmoteType.Exclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - } + if (CurrentPredator != null) + return; - ScaleSquish.Y += 1.4f; + CurrentBehavior = HuntBehavior; + ScaleSquish.Y += 0.4f; } protected override void OnPredatorDetection(NPC predator) { // Regardless of anything, if it detects a predator, time to run. - CurrentBehavior = AvoidBehavior; - - React(Color.Red * 0.6f, EmoteExpressionParticle.EmoteType.DoubleExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - - ScaleSquish.Y += 1.4f; + CurrentBehavior = FleeingBehavior; + ScaleSquish.Y += 0.4f; } protected override void OnPlayerDetection(Player player) { - // If the Probesnout is shy, it'll run away from the player. - if (Personality == PersonalityType.Shy) - { - CurrentBehavior = AvoidBehavior; - React(Color.Orange, EmoteExpressionParticle.EmoteType.QuestionExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - } - - if (Personality == PersonalityType.Curious) - React(Color.Green, EmoteExpressionParticle.EmoteType.Question, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); + if (CurrentPredator != null) + return; ScaleSquish.Y += 0.4f; } - private void IdleBehavior() + private void IdlingBehavior() { - if (_pathfindingTask.Result == null) + // At random, the mob will choose a random nearby point and pathfind there. + PathfindingParams parameters = null; + if (Main.rand.NextBool(IdleRandomMovementUnlikeliness)) { - NPC.velocity *= 0.95f; - - if (Main.rand.NextBool(125)) - _pathfindingTask = CalamityUtils.FindPathAsync(new( - NPC.Center, - NPC.Center + Main.rand.NextVector2CircularEdge(PathDetectionSize, PathDetectionSize) * Main.rand.NextFloat(0.75f, 1f), - SunkenSeaTileValidity)); + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance); + NPC.netUpdate = true; + parameters = new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); } - else - GenericPathFollowing(acceleration: 0.03f); + this.DoPathfinding(parameters); } - private void AvoidBehavior() + private void FleeingBehavior() { - // Depending on the personality, the Sharkoon will choose who to avoid. - Entity entityToAvoid = null; - switch (Personality) + // If the avoided entity is gone, go back to idling. + if (CurrentPredator == null) { - case PersonalityType.Shy: - entityToAvoid = (NearestEntity is NPC nearestNPC && HuntNPCs.Contains(nearestNPC.type)) ? null : NearestEntity; - break; - case PersonalityType.Curious: - entityToAvoid = CurrentPredator; - break; - case PersonalityType.Paranoid: - entityToAvoid = CurrentPredator; - break; - } - - // If there aren't any more targets detected, go back to idling. - if (entityToAvoid is null) - { - CurrentBehavior = IdleBehavior; + CurrentBehavior = IdlingBehavior; return; } - bool isAvoidingPredator = entityToAvoid is NPC npc && npc.whoAmI == CurrentPredator.whoAmI; - - if (HasPath) + // 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 (!Collision.CanHitLine(NPC.Center, 1, 1, NPC.Center + CurrentPredator.DirectionTo(NPC.Center) * 120f, 1, 1)) { - float fleeingDistance = isAvoidingPredator ? 600f : 300f; - - Vector2 randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(fleeingDistance, fleeingDistance + 100f); - while (Main.tile[randomEscapePoint.ToTileCoordinates()].IsTileSolid()) - randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(fleeingDistance, fleeingDistance + 100f); - - + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * 80f; + NPC.netUpdate = true; + this.DoPathfinding(new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); } else - GenericPathFollowing(acceleration: 0.14f); + { + NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; + Paths = null; + + // Cap the speed if MaxSpeed has been surpassed. + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + } } private void HuntBehavior() @@ -233,25 +217,24 @@ namespace CalamityMod.NPCs.SunkenSea // If there's no more prey, go back to idling. if (CurrentPrey is null) { - CurrentBehavior = IdleBehavior; + CurrentBehavior = IdlingBehavior; return; } - if (!HasLineOfSight(CurrentPrey.Center)) - { - if (HasPath) - GenericPathFollowing(acceleration: 0.14f); - else - _pathfindingTask = CalamityUtils.FindPathAsync(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); - } + // With sight, just go straight at him. Without it, try to pathfind over them. + if (!NPC.HasSight(CurrentPrey.Center)) + this.DoPathfinding(new PathfindingParams(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); else - NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * 0.14f; + NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; } private void OutsideWaterBehavior() { if (NPC.wet) - CurrentBehavior = PreviousBehavior; + { + NPC.noGravity = true; + CurrentBehavior = _previousBehavior; + } } #endregion @@ -274,7 +257,7 @@ namespace CalamityMod.NPCs.SunkenSea { Texture2D texture = TextureAssets.Npc[Type].Value; Vector2 drawPosition = NPC.Center - screenPos; - Rectangle frame = texture.Frame(horizontalFrames: 2, verticalFrames: 12, frameX: (int)Animation, frameY: NPC.frame.Y / NPC.height); + Rectangle frame = texture.Frame(horizontalFrames: 2, verticalFrames: 12, frameX: (int)Animation, frameY: NPC.frame.Y / 44); Vector2 anchorPoint = frame.Size() * 0.5f; SpriteEffects flip = NPC.spriteDirection == 1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; @@ -301,32 +284,28 @@ namespace CalamityMod.NPCs.SunkenSea NPC.lifeMax = 5; - NPC.aiStyle = -1; - AIType = -1; NPC.npcSlots = 0.1f; NPC.noGravity = true; NPC.chaseable = false; - NPC.width = 44; - NPC.height = 55; + NPC.width = 32; + NPC.height = 32; } #endregion #region Syncing + private Vector2 _randomPathPoint; + public override void SendExtraAI(BinaryWriter writer) { - base.SendExtraAI(writer); - writer.Write7BitEncodedInt(AnimationFrames); - writer.Write7BitEncodedInt(TimePerAnimationFrame); + writer.WriteVector2(_randomPathPoint); } public override void ReceiveExtraAI(BinaryReader reader) { - base.ReceiveExtraAI(reader); - AnimationFrames = reader.Read7BitEncodedInt(); - TimePerAnimationFrame = reader.Read7BitEncodedInt(); + _randomPathPoint = reader.ReadVector2(); } #endregion diff --git a/NPCs/SunkenSea/Sharkoon.cs b/NPCs/SunkenSea/Sharkoon.cs index 74c11e6a09..b3bf5326f1 100644 --- a/NPCs/SunkenSea/Sharkoon.cs +++ b/NPCs/SunkenSea/Sharkoon.cs @@ -9,59 +9,34 @@ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.Audio; +using Terraria.DataStructures; using Terraria.GameContent; -using Terraria.GameContent.UI.Elements; using Terraria.ID; -using Terraria.ModLoader.Utilities; -using Terraria.Utilities; +using static CalamityMod.CalamityUtils; using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { public class Sharkoon : SunkenSeaNPC, IPathFinder { - public static float DistanceToKaboom = 80f; - public static float IdleMovementMaxRange = 300f; - public static int ExplosionRadius = 80; - public static float TimeToRecover = 600f; - public static float TimeRecovering = 120f; - #region Fields & Properties - protected override List HuntNPCs => new() - { - // NPCType(), - NPCType(), - NPCType(), - NPCType(), - NPCType(), - }; + #region Static Fields - protected override List AvoidNPCs => new() - { - // NPCType(), - // NPCType(), - NPCType(), - // NPCType, - }; + public static int IdleRandomMovementUnlikeliness = 250; + public static int IdleMinPathDistance = 200; + public static int IdleMaxPathDistance = 400; - /// - /// The different types of personality this NPC can have. - /// - private enum PersonalityType { Shy, Curious, Paranoid } + public static int FleeTileAnticipationDistance = 64; + public static int FleeMinPathDistance = 80; + public static int FleeMaxPathDistance = 160; - /// - /// The current personality of this NPC. - /// - private PersonalityType Personality - { - get => (PersonalityType)NPC.ai[0]; - set - { - NPC.ai[0] = (float)value; - NetUpdate(); - } - } + public static int ExplosionDistance = 80; + public static int ExplosionRadius = 80; + public static int ExplosionCooldown = 600; + public static int RecoveringTime = 120; + + #endregion /// /// The different types of animation this enemy can have. @@ -99,8 +74,6 @@ namespace CalamityMod.NPCs.SunkenSea ChangeAnimation(animationFrames: 6, timePerAnimationFrame: 6, loops: true); break; } - - NetUpdate(); } } @@ -108,46 +81,81 @@ namespace CalamityMod.NPCs.SunkenSea /// The amount of frames that one column of sprites has.
/// Defaults to 7 since that's the first column's amount of frames. ///
- private int AnimationFrames = 7; + private int _animationFrames = 7; /// /// The amount, in frames, that it takes to go to the next animation frame.
/// Defaults to 7. ///
- private int TimePerAnimationFrame = 7; + private int _timePerAnimationFrame = 7; /// /// Whether or not the animation loops or not.
/// Defaults to . ///
- private bool AnimationLoop = true; + private bool _animationLoop = true; + + /// + /// The squish of this NPC while drawing. + /// + private Vector2 _scaleSquish = Vector2.One; + + private Entity _avoidedEntity; /// /// A timer used to know when the NPC should recover after it explodes. /// private ref float RecoverTimer => ref NPC.ai[2]; - /// - /// How unlikely is the Sharkoon going to move normally.
- /// Defaults to 250. - ///
- private int RandomIdleMovementUnlikeliness = 250; - /// /// Whether or not the Sharkoon is capable of exploding. /// - private bool IsBig => Animation == AnimationState.Normal; + private bool CanExplode => Animation == AnimationState.Normal; /// /// Whether or not the Sharkoon is currently exploding. /// private bool IsExploding => CurrentBehavior == ExplodingBehavior; + private Action _currentBehavior; + private Action CurrentBehavior + { + get => _currentBehavior; + set + { + if (value != _currentBehavior) + OnBehaviorChange(value); + _previousBehavior = _currentBehavior; + _currentBehavior = value; + } + } + + private Action _previousBehavior; + + #region SunkenSeaNPC Implementation + + protected override List PreyIDs => + [ + // NPCType(), + NPCType(), + // NPCType(), + NPCType(), + NPCType(), + ]; + + protected override List PredatorIDs => + [ + // NPCType(), + // NPCType(), + NPCType(), + // NPCType, + ]; + protected override SunkenSeaBiomeFlags BiomeDesignation => SunkenSeaBiomeFlags.RadiantReefs; - protected override float SpawningChance => SpawnCondition.CaveJellyfish.Chance * 0.9f; + #endregion - public CalamityUtils.PathfindingParams Pathfinding { get; set; } + #region IPathFinder Implementation public Task> Paths { get; set; } @@ -157,16 +165,13 @@ namespace CalamityMod.NPCs.SunkenSea public float Acceleration { get; set; } = 0.25f; - public float MaxSpeed { get; set; } = 4f; - - /// - /// The squish of this NPC while drawing. - /// - private Vector2 ScaleSquish = Vector2.One; + public float MaxSpeed { get; set; } = 6f; #endregion - #region Other Overridden Methods + #endregion + + #region SetDefaults public override void SetStaticDefaults() { @@ -184,8 +189,6 @@ namespace CalamityMod.NPCs.SunkenSea NPC.knockBackResist = 0.15f; NPC.chaseable = false; - NPC.aiStyle = -1; - AIType = -1; NPC.width = 52; NPC.height = 46; NPC.noGravity = true; @@ -193,8 +196,6 @@ namespace CalamityMod.NPCs.SunkenSea NPC.HitSound = SoundID.NPCHit1; NPC.DeathSound = SoundID.NPCDeath1; NPC.value = Item.buyPrice(0, 0, 5, 0); - // Banner = NPC.type; - // BannerItem = ModContent.ItemType(); NPC.Calamity().VulnerableToHeat = false; NPC.Calamity().VulnerableToSickness = true; @@ -202,109 +203,41 @@ namespace CalamityMod.NPCs.SunkenSea NPC.Calamity().VulnerableToWater = false; } - public override void HitEffect(NPC.HitInfo hit) - { - for (int k = 0; k < 5; k++) - { - Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f); - } - if (NPC.life <= 0) - { - for (int k = 0; k < 25; k++) - { - Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f); - } - } - } - - public override bool CanBeHitByNPC(NPC attacker) - { - if (attacker.whoAmI == NPC.whoAmI) - return false; - - return true; - } - - public override void OnHitByNPC(NPC attacker) - { - if (IsBig) - CurrentBehavior = ExplodingBehavior; - } - - public override void OnHitByItem(Player player, Item item, NPC.HitInfo hit, int damageDone) - { - if (IsBig) - CurrentBehavior = ExplodingBehavior; - } - - public override void OnHitByProjectile(Projectile projectile, NPC.HitInfo hit, int damageDone) - { - if (IsBig) - CurrentBehavior = ExplodingBehavior; - } - #endregion - #region AI + #region Behavior - protected override void BehaviorOnSpawn() + protected override bool PlayerSearchFilter(Player p) { - CurrentBehavior = IdlingBehavior; + return base.PlayerSearchFilter(p) || p == CurrentPlayer && Vector2.DistanceSquared(NPC.Center, p.Center) < 960f * 960f; + } - WeightedRandom randomPersonality = new(); - randomPersonality.Add(PersonalityType.Shy, 0.4f); - randomPersonality.Add(PersonalityType.Curious, 0.4f); - randomPersonality.Add(PersonalityType.Paranoid, 0.2f); - Personality = randomPersonality.Get(); - - DetectionDistance = 320f; - ConeDetectionAngle = MathHelper.ToRadians(30f); - - if (Personality == PersonalityType.Curious) - { - DetectionDistance *= 1.5f; - ConeDetectionAngle *= 1.5f; - RandomIdleMovementUnlikeliness /= 2; - } - - if (Personality == PersonalityType.Paranoid) - MaxSpeed *= 1.5f; + protected override bool NPCSearchFilter(NPC n) + { + return base.NPCSearchFilter(n) || (n == CurrentPrey || n == CurrentPredator) && Vector2.DistanceSquared(NPC.Center, n.Center) < 960f * 960f; + } + public override void OnSpawn(IEntitySource source) + { + //CurrentBehavior = IdlingBehavior; NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; NPC.MaxFallSpeedMultiplier *= 2f; } - protected override void CreatureAI() + public override void AI() { CurrentBehavior?.Invoke(); - // Sets the direction at which it looks at the cone. - // This makes it look at the direction it's going. - if (!NPC.velocity.HasNaNs()) - ConeDetectionDirection = (NPC.rotation * MathF.Sign(NPC.velocity.Y) + (NPC.spriteDirection == -1 ? MathHelper.Pi : 0f)).ToRotationVector2(); - // Leans the Sharkoon towards the direction it's going. - NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X); - - // When the Sharkoon is fast enough in one direction, it'll turn to that direction. - if (MathF.Abs(NPC.velocity.X) > 1f) - NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); - - // When the Sharkoon's paranoid, it'll explode at anything that isn't prey which gets close to the Sharkoon. - bool isEntityPlayerOrNonPreyNPC = NearestEntity is not null && (NearestEntity is Player || NearestEntity is NPC npc && !HuntNPCs.Contains(npc.type)); - if (isEntityPlayerOrNonPreyNPC) - { - bool isWithinDistance = NPC.DistanceSQ(NearestEntity.Center) < DistanceToKaboom * DistanceToKaboom; - if (IsBig && Personality == PersonalityType.Paranoid && isEntityPlayerOrNonPreyNPC && isWithinDistance) - CurrentBehavior = ExplodingBehavior; - } + NPC.rotation = MathHelper.ToRadians(NPC.velocity.X * 3f); + NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); // When it has already exploded, a timer will start, which when finished it'll make the Sharkoon recover. - if (!IsBig) + if (!CanExplode) { RecoverTimer++; - if (RecoverTimer > TimeToRecover) + if (RecoverTimer > ExplosionCooldown) CurrentBehavior = RecoveringBehavior; } @@ -312,86 +245,29 @@ namespace CalamityMod.NPCs.SunkenSea if (!NPC.wet && !IsExploding) CurrentBehavior = OutsideWaterBehavior; - if (ScaleSquish.Y > 1f) + // Reset any squish that is done to the Sharkoon. + if (_scaleSquish.Y > 1f) { - ScaleSquish.Y -= 0.025f; - if (ScaleSquish.Y < 1f) - ScaleSquish.Y = 1f; - } - } - - protected override void OnBehaviorChange(Action newBehavior) - { - // Obviously, when it gets to the exploding behaivor, it should make the explosion animation. - if (newBehavior == ExplodingBehavior) - Animation = AnimationState.Explosion; - - // Resets the timer when it needs to use it again. - if (newBehavior == RecoveringBehavior || CurrentBehavior == RecoveringBehavior) - RecoverTimer = 0f; - - // When it gets outside of water, it'll try to gravitate downards towards the water. - if (newBehavior == OutsideWaterBehavior) - NPC.noGravity = false; - } - - protected override void OnPreyDetection(NPC prey) - { - // If it's not a small fish and it's not being chased by a predator, the Sharkoon may hunt. - if (IsBig && CurrentPredator is null && !IsExploding) - { - CurrentBehavior = HuntBehavior; - ScaleSquish.Y += 0.4f; - React(Color.Orange * 0.6f, EmoteExpressionParticle.EmoteType.Exclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - } - } - - protected override void OnPredatorDetection(NPC predator) - { - // If it detects a predator, time to run. - if (!IsExploding) - { - CurrentBehavior = AvoidBehavior; - React(Color.Red * 0.6f, EmoteExpressionParticle.EmoteType.DoubleExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - ScaleSquish.Y += 0.4f; - } - } - - protected override void OnPlayerDetection(Player player) - { - // When there's a predator, player's shouldn't matter. - if (CurrentPredator is not null) - return; - - // If the Sharkoon is shy, it'll run away from the player. - if (Personality == PersonalityType.Shy) - { - CurrentBehavior = AvoidBehavior; - React(Color.Orange, EmoteExpressionParticle.EmoteType.QuestionExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - ScaleSquish.Y += 0.4f; - } - - if (Personality == PersonalityType.Curious) - { - React(Color.Green, EmoteExpressionParticle.EmoteType.Question, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - ScaleSquish.Y += 0.4f; + _scaleSquish.Y -= 0.025f; + if (_scaleSquish.Y < 1f) + _scaleSquish.Y = 1f; } } private void IdlingBehavior() { - // Randomly, it'll decide a path whose destination is somewhere around him. - if (Main.rand.NextBool(RandomIdleMovementUnlikeliness)) - Pathfinding = new(NPC.Center, Main.rand.NextVector2Circular(400f, 400f), SunkenSeaTileValidity); - - // While it hasn't decided yet which path to follow, it'll deaccelerate and stand still. - else - Pathfinding = null; - - this.DoPathfinding(); + // At random, the mob will choose a random nearby point and pathfind there. + PathfindingParams parameters = null; + if (Main.rand.NextBool(IdleRandomMovementUnlikeliness)) + { + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance); + NPC.netUpdate = true; + parameters = new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); + } + this.DoPathfinding(parameters); } - private void HuntBehavior() + private void HuntingBehavior() { // If there's no more prey, go back to idling. if (CurrentPrey is null) @@ -400,68 +276,46 @@ namespace CalamityMod.NPCs.SunkenSea return; } - if (!HasLineOfSight(CurrentPrey.Center)) - { - Pathfinding = new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity); - this.DoPathfinding(); - } - + // With sight, just go straight at him. Without it, try to pathfind over them. + if (!NPC.HasSight(CurrentPrey.Center)) + this.DoPathfinding(new PathfindingParams(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); else NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; } - private void AvoidBehavior() - { - // Depending on the personality, the Sharkoon will choose who to avoid. - Entity entityToAvoid = null; - switch (Personality) - { - case PersonalityType.Shy: - entityToAvoid = (NearestEntity is NPC nearestNPC && HuntNPCs.Contains(nearestNPC.type)) ? null : NearestEntity; - break; - case PersonalityType.Curious: - case PersonalityType.Paranoid: - entityToAvoid = CurrentPredator; - break; - } - // If there aren't any more targets detected, go back to idling. - if (entityToAvoid is null) + private void FleeingBehavior() + { + // Check who is the avoided entity specifically. + _avoidedEntity = _avoidedEntity is NPC ? CurrentPredator : CurrentPlayer; + + // If the avoided entity is gone, go back to idling. + if (_avoidedEntity == null) { CurrentBehavior = IdlingBehavior; return; } - // When it's going in a direction and it detects that it'll stumble into tiles, it'll try to path-find a way to continue avoiding whichever entity. - const int TileAnticipationDistance = 5 * 16; - const float AngleVariance = 2.2f; // In radians. - const int MaxAttemptsToFindPath = 20; - const int MinimumEscapeDistance = 160; - const int MaximumEscapeDistance = 320; - - if (Main.tile[(NPC.Center + NPC.DirectionFrom(entityToAvoid.Center) * TileAnticipationDistance).ToTileCoordinates()].IsTileSolid() && !HasPath) + // 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(_avoidedEntity.Center) * FleeTileAnticipationDistance).ToTileCoordinates()].IsTileSolid()) { - Vector2 randomEscapePoint; - int attempts = 0; - do - { - randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(AngleVariance) * Main.rand.NextFloat(MinimumEscapeDistance, MaximumEscapeDistance); - attempts++; - } - while (Main.tile[randomEscapePoint.ToTileCoordinates()].IsTileSolid() || attempts < MaxAttemptsToFindPath); + NPC.velocity += NPC.DirectionFrom(_avoidedEntity.Center) * Acceleration; - Pathfinding = new(NPC.Center, randomEscapePoint, SunkenSeaTileValidity); + // Cap the speed if MaxSpeed has been surpassed. + 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; + this.DoPathfinding(new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); } - // Attempt to path find through an escape route. - this.DoPathfinding(); - - // If one couldn't be found, just try to swim away. - if (Paths.IsCompleted && Paths.Result == null) - NPC.velocity += NPC.DirectionFrom(entityToAvoid.Center) * Acceleration; - // If it's capable of exploding and the predator's within distance, kaboom. - if (IsBig && NPC.DistanceSQ(entityToAvoid.Center) < DistanceToKaboom * DistanceToKaboom && entityToAvoid is NPC predator && AvoidNPCs.Contains(predator.type)) + if (CanExplode && NPC.DistanceSQ(_avoidedEntity.Center) < ExplosionDistance * ExplosionDistance && _avoidedEntity is NPC predator && PredatorIDs.Contains(predator.type)) CurrentBehavior = ExplodingBehavior; } @@ -481,16 +335,16 @@ namespace CalamityMod.NPCs.SunkenSea if (NPC.frame.Y >= NPC.height * 16) { Animation = AnimationState.Shrunk; - CurrentBehavior = PreviousBehavior; + CurrentBehavior = _previousBehavior; } } private void RecoveringBehavior() { - if (RecoverTimer >= TimeRecovering) + if (RecoverTimer >= RecoveringTime) { Animation = AnimationState.Normal; - CurrentBehavior = PreviousBehavior; + CurrentBehavior = _previousBehavior; } // Deaccelerates to stay still. @@ -500,12 +354,10 @@ namespace CalamityMod.NPCs.SunkenSea // a dedicated server doesn't need to load these. if (!Main.dedServ) { - float fade = Utils.GetLerpValue(TimeRecovering, 0, RecoverTimer); - float rotFactor = 360f; + float fade = Utils.GetLerpValue(RecoveringTime, 0, RecoverTimer); if (Main.rand.NextBool()) { - float rot = MathHelper.ToRadians(rotFactor); - Vector2 velOffset = CalamityUtils.RandomVelocity(50f, 20f, 70f, 0.04f); + Vector2 velOffset = RandomVelocity(50f, 20f, 70f, 0.04f); velOffset *= Main.rand.NextFloat(15, 20) * fade; Dust dust = Dust.NewDustPerfect(NPC.Center + velOffset * 2.5f, 267, -velOffset * Main.rand.NextFloat(0.08f, 0.12f) * 1.5f, 0, default, Main.rand.NextFloat(0.8f, 0.95f)); dust.noGravity = true; @@ -521,10 +373,92 @@ namespace CalamityMod.NPCs.SunkenSea if (NPC.wet) { NPC.noGravity = true; - CurrentBehavior = PreviousBehavior; + CurrentBehavior = _previousBehavior; } } + private void OnBehaviorChange(Action newBehavior) + { + // Obviously, when it gets to the exploding behaivor, it should make the explosion animation. + if (newBehavior == ExplodingBehavior) + Animation = AnimationState.Explosion; + + // Resets the timer when it needs to use it again. + if (newBehavior == RecoveringBehavior || CurrentBehavior == RecoveringBehavior) + RecoverTimer = 0f; + + // When it gets outside of water, it'll try to gravitate downards towards the water. + if (newBehavior == OutsideWaterBehavior) + NPC.noGravity = false; + } + + protected override void OnPreyDetection(NPC prey) + { + // If it's not a small fish and it's not being chased by a predator, the Sharkoon may hunt. + if (CanExplode && CurrentPredator is null && !IsExploding) + { + CurrentBehavior = HuntingBehavior; + _scaleSquish.Y += 0.4f; + } + } + + protected override void OnPredatorDetection(NPC predator) + { + // If it detects a predator, time to run. + if (!IsExploding) + { + CurrentBehavior = FleeingBehavior; + _avoidedEntity = predator; + _scaleSquish.Y += 0.4f; + } + } + + protected override void OnPlayerDetection(Player player) + { + // When there's a predator, player's shouldn't matter. + if (CurrentPredator is not null && !IsExploding) + return; + + CurrentBehavior = FleeingBehavior; + _avoidedEntity = player; + _scaleSquish.Y += 0.4f; + } + + public override void HitEffect(NPC.HitInfo hit) + { + for (int k = 0; k < 5; k++) + { + Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f); + } + if (NPC.life <= 0) + { + for (int k = 0; k < 25; k++) + { + Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.RedMoss, hit.HitDirection, -1f, 0, default, 1f); + } + } + } + + public override bool CanBeHitByNPC(NPC attacker) => attacker.whoAmI != NPC.whoAmI; + + public override void OnHitByNPC(NPC attacker) + { + if (CanExplode) + CurrentBehavior = ExplodingBehavior; + } + + public override void OnHitByItem(Player player, Item item, NPC.HitInfo hit, int damageDone) + { + if (CanExplode) + CurrentBehavior = ExplodingBehavior; + } + + public override void OnHitByProjectile(Projectile projectile, NPC.HitInfo hit, int damageDone) + { + if (CanExplode) + CurrentBehavior = ExplodingBehavior; + } + private void Kaboom() { if (Main.netMode != NetmodeID.MultiplayerClient) @@ -534,11 +468,13 @@ namespace CalamityMod.NPCs.SunkenSea NPC.Center, Vector2.Zero, ProjectileType(), - NPC.damage, + NPC.damage * 10, 10f, - Main.myPlayer); + ai0: NPC.whoAmI); } + AddScreenshakeAt(NPC.Center, 15f); + // VFX and sound effects go here, // a dedicated server doesn't need to load these. if (!Main.dedServ) @@ -564,8 +500,6 @@ namespace CalamityMod.NPCs.SunkenSea SoundStyle boom = new("CalamityMod/Sounds/Custom/SharkoonBoom"); SoundEngine.PlaySound(boom with { Volume = 0.7f, PitchVariance = 0.15f }, NPC.Center); } - - NetUpdate(); } #endregion @@ -577,21 +511,21 @@ namespace CalamityMod.NPCs.SunkenSea ///
private void ChangeAnimation(int animationFrames, int timePerAnimationFrame, bool loops) { - AnimationFrames = animationFrames; - TimePerAnimationFrame = timePerAnimationFrame; - AnimationLoop = loops; + _animationFrames = animationFrames; + _timePerAnimationFrame = timePerAnimationFrame; + _animationLoop = loops; } public override void FindFrame(int frameHeight) { NPC.frameCounter++; - if (NPC.frameCounter > TimePerAnimationFrame) + if (NPC.frameCounter > _timePerAnimationFrame) { NPC.frame.Y += frameHeight; - NPC.frame.Y = Math.Min(NPC.frame.Y, AnimationFrames * frameHeight); + NPC.frame.Y = Math.Min(NPC.frame.Y, _animationFrames * frameHeight); NPC.frameCounter = 0; - if (AnimationLoop) - NPC.frame.Y = NPC.frame.Y % (AnimationFrames * frameHeight); + if (_animationLoop) + NPC.frame.Y = NPC.frame.Y % (_animationFrames * frameHeight); } } @@ -603,36 +537,25 @@ namespace CalamityMod.NPCs.SunkenSea Vector2 anchorPoint = frame.Size() * 0.5f; SpriteEffects flip = NPC.spriteDirection == -1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; - if (Personality == PersonalityType.Paranoid) - drawPosition += Main.rand.NextVector2Circular(1.5f, 1.5f); - - 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; } #endregion - #region Syncing + #region Sycning + + private Vector2 _randomPathPoint; public override void SendExtraAI(BinaryWriter writer) { - base.SendExtraAI(writer); - writer.Write7BitEncodedInt(AnimationFrames); - writer.Write7BitEncodedInt(TimePerAnimationFrame); - writer.Write(AnimationLoop); - writer.Write(MaxSpeed); - writer.Write7BitEncodedInt(RandomIdleMovementUnlikeliness); + writer.WriteVector2(_randomPathPoint); } public override void ReceiveExtraAI(BinaryReader reader) { - base.ReceiveExtraAI(reader); - AnimationFrames = reader.Read7BitEncodedInt(); - TimePerAnimationFrame = reader.Read7BitEncodedInt(); - AnimationLoop = reader.ReadBoolean(); - MaxSpeed = reader.ReadSingle(); - RandomIdleMovementUnlikeliness = reader.Read7BitEncodedInt(); + _randomPathPoint = reader.ReadVector2(); } #endregion diff --git a/NPCs/SunkenSea/SunkenSeaNPC.cs b/NPCs/SunkenSea/SunkenSeaNPC.cs index ee29a2e843..03b84f2512 100644 --- a/NPCs/SunkenSea/SunkenSeaNPC.cs +++ b/NPCs/SunkenSea/SunkenSeaNPC.cs @@ -1,13 +1,10 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using CalamityMod.Enums; -using CalamityMod.Particles; using CalamityMod.Systems.Collections; using Microsoft.Xna.Framework; using Terraria; -using Terraria.Audio; using Terraria.GameContent.Bestiary; using Terraria.ID; using Terraria.ModLoader; @@ -16,182 +13,71 @@ using static Terraria.Utilities.NPCUtils; namespace CalamityMod.NPCs.SunkenSea { /// - /// An abstract class that gives an NPC the memebers needed to be a Sunken Sea NPC.
- /// These have the ability to hunt both players and NPCs, and also have a list of NPCs they hunt and avoid. + /// 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 { - #region Fields & Properties + private NPC _currentPrey; + private NPC _currentPredator; + private Player _currentPlayer; /// - /// Since a lot of these NPCs change behaviors a lot, this abstract class provides an property to store and trigger behaviors.
- /// Automatically resets and to not cause errors. + /// A list of NPC IDs that this creature hunts. ///
- protected Action CurrentBehavior - { - get => _currentBehavior; - set - { - OnBehaviorChange(value); - - PathfindingPoints = null; - PathPointIndex = 0; - - PreviousBehavior = _currentBehavior; - _currentBehavior = value; - - NetUpdate(); - } - } - private Action _currentBehavior; + protected abstract List PreyIDs { get; } /// - /// The previous behavior that was used for . + /// A list of NPC IDs that this creature avoids. /// - protected Action PreviousBehavior { get; private set; } + protected abstract List PredatorIDs { get; } /// - /// A lot of these Sunken Sea creatures use the pathfinding algorithm,
- /// so this abstract class provides a so you can store the paths.
- /// Defaults to . + /// The biome flags that define where this Sunken Sea NPC can spawn. ///
- protected List PathfindingPoints { get; set; } + protected abstract SunkenSeaBiomeFlags BiomeDesignation { get; } /// - /// The probablity that this Sunken Sea NPC spawns given the conditions. - /// - protected abstract float SpawningChance { get; } - - protected int PathPointIndex { get; set; } - - private bool _hasSpawned; - - #region Targetting - - /// - /// A list which stores the NPC's IDs that this creature hunts. - /// - protected abstract List HuntNPCs { get; } - - /// - /// A list which stores the NPC's IDs that this creature avoids. - /// - protected abstract List AvoidNPCs { get; } - - /// - /// The current NPC that this creature has detected as prey. + /// The current NPC that this creature has identified as prey. /// protected NPC CurrentPrey { get => _currentPrey; private set { - if (value != _currentPrey && value != null) + if (value != null && (_currentPrey == null || _currentPrey.whoAmI != value.whoAmI)) OnPreyDetection(value); - _currentPrey = value; } } - private NPC _currentPrey; /// - /// The current NPC that this creature has detected as a predator. + /// The current NPC that this creature has identified as a predator. /// protected NPC CurrentPredator { get => _currentPredator; private set { - if (value != _currentPredator && value != null) + if (value != null && (_currentPredator == null || _currentPredator.whoAmI != value.whoAmI)) OnPredatorDetection(value); - _currentPredator = value; } } - private NPC _currentPredator; /// - /// The current Player that this creature has detected. + /// The current player that this creature has detected. /// protected Player CurrentPlayer { get => _currentPlayer; private set { - if (value != _currentPlayer && value != null) + if (value != null && (_currentPlayer == null || _currentPlayer.whoAmI != value.whoAmI)) OnPlayerDetection(value); - _currentPlayer = value; } } - private Player _currentPlayer; - - /// - /// The nearest entity detected, could be an NPC or Player. - /// - protected Entity NearestEntity { get; private set; } - - /// - /// The distance detection radius.
- /// Defaults to 300 pixels. - ///
- protected float DetectionDistance { get; set; } = 300f; - - /// - /// The direction of the cone used to detect targets.
- /// Defaults to times the direction.
- /// When set, it normalizes the vector. - ///
- protected Vector2 ConeDetectionDirection - { - get => _coneDetectionDirection; - set - { - _coneDetectionDirection = value.SafeNormalize(Vector2.UnitX * NPC.direction); - NetUpdate(); - } - } - private Vector2 _coneDetectionDirection; - - /// - /// How open the cone detection is -- given an angle.
- /// Defaults to 45 degrees. - ///
- protected float ConeDetectionAngle { get; set; } = MathHelper.ToRadians(45f); - - /// - /// When a this creature has lost sight of a target, it'll still have a sense of permanence.
- /// This means that, even if it can't see it, it can know it's there.
- /// This property states how much seconds it can know it's there.
- /// Defaults to 3 seconds. - ///
- protected virtual float PermanenceSenseTime => CalamityUtils.SecondsToFrames(3f); - private int _permanenceSenseTimer; - - /// - /// Whether or not the creature has detected anything at all. - /// - protected bool HasAnyTargets => CurrentPrey != null || CurrentPredator != null || CurrentPlayer != null; - - #endregion - - #region Biome Designation - - /// - /// The biomes that this Sunken Sea NPC belongs to. - /// - protected abstract SunkenSeaBiomeFlags BiomeDesignation { get; } - - /// - /// The spawn conditions for each biome that this Sunken Sea NPC belongs to. - /// - protected List> BiomeSpawnConditions { get; private set; } = []; - - #endregion - - #endregion - - #region ModNPC Overrides public override void SetStaticDefaults() { @@ -201,273 +87,108 @@ namespace CalamityMod.NPCs.SunkenSea public override void SetDefaults() { - List biomeTypes = []; - foreach (var flag in Enum.GetValues()) + NPC.aiStyle = -1; + AIType = -1; + + SpawnModBiomes = Enum.GetValues() + .Where(flag => flag != SunkenSeaBiomeFlags.None && + flag != SunkenSeaBiomeFlags.UndergroundDesert && + BiomeDesignation.HasFlag(flag)) + .Select(flag => SunkenSeaBiomeCorrespondentDict.Dict[flag].BiomeType) + .ToArray(); + + try { - if (flag == SunkenSeaBiomeFlags.None) - continue; - - if (!BiomeDesignation.HasFlag(flag)) - continue; - - if (!SunkenSeaBiomeCorrespondentDict.TryGet(flag, out var spawnCondition, out var biomeType)) - continue; - - // Apply Conditions and Biome Types - BiomeSpawnConditions.Add(spawnCondition); - if (flag != SunkenSeaBiomeFlags.UndergroundDesert) - biomeTypes.Add(biomeType); + Banner = Type; + BannerItem = ModContent.Find($"{Name}Banner").Type; + } + catch (Exception ex) + { + CalamityMod.Instance.Logger.Warn(ex); } - SpawnModBiomes = [.. biomeTypes]; } - public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) => bestiaryEntry.Info.AddRange([new FlavorTextBestiaryInfoElement($"Mods.CalamityMod.Bestiary.{Name}")]); + public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) + => bestiaryEntry.Info.AddRange([new FlavorTextBestiaryInfoElement($"Mods.CalamityMod.Bestiary.{Name}")]); - public override float SpawnChance(NPCSpawnInfo spawnInfo) + public override bool PreAI() { - if (BiomeSpawnConditions.Any(f => f.Invoke(spawnInfo)) && spawnInfo.Water && !spawnInfo.Player.Calamity().clamity) - return SpawningChance; - return 0f; - } - - public sealed override void AI() - { - if (!_hasSpawned) - { - _coneDetectionDirection = Vector2.UnitX * NPC.direction; - BehaviorOnSpawn(); - _hasSpawned = true; - NetUpdate(); - } - UpdateTargets(); - - CreatureAI(); + return true; } - #endregion - - #region Methods - /// - /// Same function as OnSpawn, but this one actually syncs to the server. + /// Called when this NPC is hit by another NPC. Override this method to define custom behavior when attacked. /// - protected virtual void BehaviorOnSpawn() { } - - /// - /// A method that is called on every frame, to put your actual enemy AI. - /// - protected virtual void CreatureAI() { } - - /// - /// A method that is triggered when this NPC's behavior is changed. - /// - protected virtual void OnBehaviorChange(Action newBehavior) { } - - /// - /// A custom method for when this NPC is hit by another NPC. - /// - /// + /// The NPC that attacked this creature. public virtual void OnHitByNPC(NPC attacker) { } /// - /// A method that is triggered when this creature has detected a prey. + /// Called when this creature detects a prey NPC. Override this method to define custom behavior upon detecting prey. /// + /// The NPC that has been detected as prey. protected virtual void OnPreyDetection(NPC prey) { } /// - /// A method that is triggered when this creature has detected a predator. + /// Called when this creature detects a predator NPC. Override this method to define custom behavior upon detecting a predator. /// + /// The NPC that has been detected as a predator. protected virtual void OnPredatorDetection(NPC predator) { } /// - /// A method that is triggered when this creature detects a player. + /// Called when this creature detects a player. Override this method to define custom behavior upon detecting a player. /// + /// The player that has been detected. protected virtual void OnPlayerDetection(Player player) { } /// - /// Whether or not a detected player is valid to be set as a target given some conditions. + /// Determines whether a detected player is a valid target based on specific conditions. /// - protected virtual bool PlayerSearchFilter(Player p) - { - if (!HasLineOfSight(p.Center)) - return false; - - bool isInsideCone = Vector2.Dot(_coneDetectionDirection, NPC.DirectionTo(p.Center)) >= MathF.Cos(ConeDetectionAngle) && NPC.DistanceSQ(p.Center) < DetectionDistance * DetectionDistance; - bool isInsideCirlceWhenAware = HasAnyTargets && NPC.DistanceSQ(p.Center) <= DetectionDistance * DetectionDistance; - if (isInsideCone || isInsideCirlceWhenAware) - return true; - - return false; - } + /// The player to evaluate. + /// if the NPC is a valid target; otherwise, . + protected virtual bool PlayerSearchFilter(Player p) => NPC.HasSight(p.Center) && Vector2.DistanceSquared(NPC.Center, p.Center) < 72900f; /// - /// Whether or not a detected NPC is valid to be set as a target given some conditions. + /// Determines whether a detected NPC is a valid target based on specific conditions. /// - protected virtual bool NPCSearchFilter(NPC n) - { - if (!HasLineOfSight(n.Center)) - return false; - - bool isInsideCone = Vector2.Dot(_coneDetectionDirection, NPC.DirectionTo(n.Center)) >= MathF.Cos(ConeDetectionAngle) && NPC.DistanceSQ(n.Center) < DetectionDistance * DetectionDistance; - bool isInsideCirlceWhenAware = HasAnyTargets && NPC.DistanceSQ(n.Center) <= DetectionDistance * DetectionDistance; - if (isInsideCone || isInsideCirlceWhenAware) - return true; - - return false; - } + /// The NPC to evaluate. + /// if the NPC is a valid target; otherwise, . + protected virtual bool NPCSearchFilter(NPC n) => NPC.HasSight(n.Center) && Vector2.DistanceSquared(NPC.Center, n.Center) < 72900f; /// - /// A method that finds and updates the current detected targets of this creature. + /// Updates the current targets of this creature, including prey, predators, and players, based on detection logic. /// protected void UpdateTargets() { var searchResults = SearchForTarget(NPC, playerFilter: PlayerSearchFilter, npcFilter: NPCSearchFilter); if (searchResults.FoundTarget) { + if (PredatorIDs.Contains(searchResults.NearestNPC.type)) + CurrentPredator = searchResults.NearestNPC; + else + CurrentPredator = null; + + if (PreyIDs.Contains(searchResults.NearestNPC.type)) + CurrentPrey = searchResults.NearestNPC; + else + CurrentPrey = null; + CurrentPlayer = searchResults.NearestTankOwner; - NearestEntity = searchResults.NearestTankOwner; - - if (searchResults.FoundNPC) - { - if (AvoidNPCs.Contains(searchResults.NearestNPC.type)) - CurrentPredator = searchResults.NearestNPC; - - else if (HuntNPCs.Contains(searchResults.NearestNPC.type)) - CurrentPrey = searchResults.NearestNPC; - - if (searchResults.NearestNPCDistance < searchResults.NearestTankDistance) - NearestEntity = searchResults.NearestNPC; - } - - NetUpdate(); } else { - _permanenceSenseTimer++; - if (_permanenceSenseTimer > PermanenceSenseTime) - { - CurrentPlayer = null; - NearestEntity = null; - CurrentPredator = null; - CurrentPrey = null; - _permanenceSenseTimer = 0; - } - } - } - - #endregion - - #region Helper Methods - - protected bool HasPath => PathfindingPoints is not null; - - protected bool SunkenSeaTileValidity(Point point) => - Main.tile[point].LiquidAmount > 125 && Main.tile[point].LiquidType == LiquidID.Water && NPC.DoesEntityFitInPath(point, 6, 6); - - /// - /// A quickhand method to follow a path found. - /// - protected void GenericPathFollowing(float acceleration) - { - Vector2 currentlyFollowedPathPoint = PathfindingPoints[PathPointIndex]; - - NPC.velocity += NPC.DirectionTo(currentlyFollowedPathPoint) * acceleration; - - if (NPC.DistanceSQ(currentlyFollowedPathPoint) < 48f * 48f) - { - PathPointIndex++; - PathPointIndex = (int)MathHelper.Clamp(PathPointIndex, 0, PathfindingPoints.Count - 1); - } - - if (PathPointIndex == PathfindingPoints.Count - 1) - { - PathPointIndex = 0; - PathfindingPoints = null; + CurrentPredator = null; + CurrentPrey = null; + CurrentPlayer = null; } } /// - /// A quick method to check whether this NPC has line of sight with something. + /// Checks whether a specific tile is valid for this NPC, considering water level and entity size. /// - protected bool HasLineOfSight(Vector2 position) => Collision.CanHitLine(NPC.Center, 0, 0, position, 0, 0); - - /// - /// Spawns an emote particle. - /// - protected void React(Color emoteColor, EmoteExpressionParticle.EmoteType emoteImage, SoundStyle? sound = null) - { - if (!Main.dedServ) - { - var emoteDirection = -Vector2.UnitY.RotatedByRandom(MathHelper.PiOver4) * Main.rand.NextFloat(2f, 3f); - Particle emote = new EmoteExpressionParticle( - NPC.Center + emoteDirection * 2f, - emoteDirection, - 2.2f, - emoteColor, - Main.rand.Next(30, 46), - emoteImage); - GeneralParticleHandler.SpawnParticle(emote); - - if (sound is not null) - SoundEngine.PlaySound(sound, NPC.Center); - } - } - - #endregion - - #region Syncing - - /// - /// A quick method to both do and set .
- /// Defaults to 0. - ///
- protected void NetUpdate(int netSpam = 0) - { - NPC.netUpdate = true; - NPC.netSpam = netSpam; - } - - public override void SendExtraAI(BinaryWriter writer) - { - writer.Write7BitEncodedInt(CurrentPrey.whoAmI); - writer.Write7BitEncodedInt(CurrentPredator.whoAmI); - writer.Write7BitEncodedInt(CurrentPlayer.whoAmI); - writer.Write7BitEncodedInt(NearestEntity.whoAmI); - - writer.Write(DetectionDistance); - writer.WritePackedVector2(_coneDetectionDirection); - writer.Write(ConeDetectionAngle); - writer.Write7BitEncodedInt(_permanenceSenseTimer); - - writer.Write7BitEncodedInt(PathfindingPoints.Count); - foreach (var point in PathfindingPoints) - writer.WritePackedVector2(point); - writer.Write7BitEncodedInt(PathPointIndex); - - writer.Write(_hasSpawned); - } - - public override void ReceiveExtraAI(BinaryReader reader) - { - CurrentPrey.whoAmI = reader.Read7BitEncodedInt(); - CurrentPredator.whoAmI = reader.Read7BitEncodedInt(); - CurrentPlayer.whoAmI = reader.Read7BitEncodedInt(); - NearestEntity.whoAmI = reader.Read7BitEncodedInt(); - - DetectionDistance = reader.ReadSingle(); - _coneDetectionDirection = reader.ReadPackedVector2(); - ConeDetectionAngle = reader.ReadSingle(); - _permanenceSenseTimer = reader.Read7BitEncodedInt(); - - int count = reader.Read7BitEncodedInt(); - for (int i = 0; i < count; i++) - PathfindingPoints.Add(reader.ReadPackedVector2()); - PathPointIndex = reader.Read7BitEncodedInt(); - - _hasSpawned = reader.ReadBoolean(); - } - - #endregion + /// The tile location to check. + /// if the tile is valid; otherwise, . + protected bool SunkenSeaTileValidity(Point point) + => Main.tile[point].LiquidAmount > 128 && Main.tile[point].LiquidType == LiquidID.Water && NPC.DoesEntityFitInPath(point, 6, 6); } } diff --git a/Projectiles/Enemy/SharkoonExplosion.cs b/Projectiles/Enemy/SharkoonExplosion.cs index c672ea04e8..ce4efa0722 100644 --- a/Projectiles/Enemy/SharkoonExplosion.cs +++ b/Projectiles/Enemy/SharkoonExplosion.cs @@ -1,5 +1,6 @@ using CalamityMod.NPCs.SunkenSea; using Microsoft.Xna.Framework; +using Terraria; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Enemy @@ -13,12 +14,13 @@ namespace CalamityMod.Projectiles.Enemy public override void SetDefaults() { Projectile.hostile = true; - Projectile.friendly = true; Projectile.width = Projectile.height = Sharkoon.ExplosionRadius * 2; Projectile.timeLeft = 2; } public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, Sharkoon.ExplosionRadius, targetHitbox); + + public override bool? CanHitNPC(NPC target) => target.whoAmI != Projectile.ai[0]; } } diff --git a/Utilities/NPCUtils.cs b/Utilities/NPCUtils.cs index bddf8b9e8d..b035594a15 100644 --- a/Utilities/NPCUtils.cs +++ b/Utilities/NPCUtils.cs @@ -893,6 +893,8 @@ namespace CalamityMod return false; } + public static bool HasSight(this NPC npc, Vector2 target) => Collision.CanHit(npc.Center, 1, 1, target, 1, 1); + #region Boss Spawning /// /// Shortcut for the generic boss summon message. diff --git a/Utilities/PathfindingUtils.cs b/Utilities/PathfindingUtils.cs index b2d4c8854c..5f1127d8ae 100644 --- a/Utilities/PathfindingUtils.cs +++ b/Utilities/PathfindingUtils.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Terraria; @@ -15,12 +13,6 @@ namespace CalamityMod /// public interface IPathFinder { - /// - /// The parameters to be used in that determines how pathfinding should be calculated.
- /// This can return if you do not want the entity to find a path. - ///
- public PathfindingParams Pathfinding { get; } - /// /// The result of the pathfinding task that contains a set of points this entity should follow. /// @@ -85,7 +77,7 @@ namespace CalamityMod /// Assigns the value of to based on .
/// You can override this and do - public void FindPath() => Paths = FindPathAsync(Pathfinding); + public void FindPath(PathfindingParams parameters) => Paths = FindPathAsync(parameters); } public static partial class CalamityUtils @@ -95,34 +87,39 @@ namespace CalamityMod /// This method should be called every frame that you want your entity to follow it's pathfinding logic. ///
/// The entity that should be moving. - public static void DoPathfinding(this IPathFinder pathfinder) + public static void DoPathfinding(this IPathFinder pathfinder, PathfindingParams parameters) { - // Checks to make sure that: - // A. The pathfinding task has completed - // B. There is a valid result - // C. There are points left in the previously found path - if (pathfinder.Paths.Result != null && - pathfinder.Paths.Result.Count > 0) + // If the task is NOT in-progress... + if (pathfinder.Paths == null || pathfinder.Paths.IsCompleted) { - // Follows the point at index 0 of the path result. - Vector2 nextPoint = pathfinder.Paths.Result[0]; + // If the task result has entries... + if ((pathfinder.Paths?.Result?.Count ?? 0) > 0) + { + // Follows the point at index 0 of the path result. + Vector2 nextPoint = pathfinder.Paths.Result[0]; - // Once that point is reached, it is removed from the list of points to follow. - if (pathfinder.FollowPath(nextPoint)) - pathfinder.Paths.Result.RemoveAt(0); + // Once that point is reached, it is removed from the list of points to follow. + if (pathfinder.FollowPath(nextPoint)) + pathfinder.Paths.Result.RemoveAt(0); + } + + // If it does not have entries, that means the pathfinding task is + // complete OR the last pathfinding attempt was invalid. + // We need to attempt pathfinding again. Idle in the meantime. + else + { + pathfinder.FindPath(parameters); + pathfinder.IdleBehavior(); + } } - // Idle if the task is currently finding a path or there is no path to be followed. + // If the task IS in-progress, just idle while waiting for it to complete. else - { pathfinder.IdleBehavior(); - - // Only attempt to find a path again if the task is not currently running. - if (pathfinder.Paths.Status != TaskStatus.Running) - pathfinder.FindPath(); - } } + public static void DoPathfinding(this IPathFinder pathfinder, Vector2 target) => pathfinder.DoPathfinding(new PathfindingParams(pathfinder.Position, target)); + /// /// Represents a node in a pathfinding algorithm, containing position, cost, and parent information. /// @@ -230,7 +227,7 @@ namespace CalamityMod { // If the entity isn't actually supposed to follow a path right now, null // can be passed as the parameters to make implementation more concise. - if (parameters is null) + if (parameters is null || Main.tile[parameters.End.Position].IsTileSolid()) return null; var openSet = new List(); From 9585fe76dda6472426f8131a5b51cfca4ff7a602 Mon Sep 17 00:00:00 2001 From: NycroV <83246959+NycroV@users.noreply.github.com> Date: Mon, 10 Feb 2025 17:26:37 -0500 Subject: [PATCH 15/18] Better implementation of multithreading --- NPCs/SunkenSea/Probesnout.cs | 247 ++++++++++--------- NPCs/SunkenSea/Sharkoon.cs | 13 +- Utilities/PathfindingUtils.cs | 430 +++++++++++++++++++--------------- 3 files changed, 381 insertions(+), 309 deletions(-) diff --git a/NPCs/SunkenSea/Probesnout.cs b/NPCs/SunkenSea/Probesnout.cs index adaa978d5f..aad10dcaf6 100644 --- a/NPCs/SunkenSea/Probesnout.cs +++ b/NPCs/SunkenSea/Probesnout.cs @@ -3,44 +3,51 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using CalamityMod.Enums; +using CalamityMod.Particles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; -using Terraria.DataStructures; using Terraria.GameContent; using Terraria.ID; -using static CalamityMod.CalamityUtils; +using Terraria.Utilities; using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { - public class Probesnout : SunkenSeaNPC, IPathFinder + public class Probesnout : SunkenSeaNPC { + public static float PathDetectionSize = 300f; + private static Task> _pathfindingTask; + #region Members - public static int IdleRandomMovementUnlikeliness = 250; - public static int IdleMinPathDistance = 200; - public static int IdleMaxPathDistance = 400; - - public static int FleeTileAnticipationDistance = 5 * 16; - public static int FleeMinPathDistance = 80; - public static int FleeMaxPathDistance = 160; - - protected override List PreyIDs => - [ + protected override List HuntNPCs => new() + { // NPCType(), - ]; + }; - protected override List PredatorIDs => - [ + protected override List AvoidNPCs => new() + { // NPCType(), NPCType(), // NPCType(), // NPCType(), // NPCType(), - ]; + }; - private enum AnimationState { Idle, Eating } + private enum PersonalityType { Curious, Shy, Paranoid } + + private PersonalityType Personality + { + get => (PersonalityType)NPC.ai[0]; + set + { + NPC.ai[0] = (float)value; + NetUpdate(); + } + } + + private enum AnimationState { Idle, Attack } private AnimationState Animation { @@ -59,157 +66,166 @@ namespace CalamityMod.NPCs.SunkenSea AnimationFrames = 8; TimePerAnimationFrame = 5; break; - case AnimationState.Eating: + case AnimationState.Attack: AnimationFrames = 12; TimePerAnimationFrame = 7; break; } NPC.ai[1] = (float)value; + NetUpdate(); } } protected override SunkenSeaBiomeFlags BiomeDesignation => SunkenSeaBiomeFlags.RadiantReefs; + protected override float SpawningChance => 0f; + private int AnimationFrames = 8; private int TimePerAnimationFrame = 5; + private float MaximumSpeed = 6f; + private Vector2 ScaleSquish = Vector2.One; - private Action _currentBehavior; - private Action CurrentBehavior - { - get => _currentBehavior; - set - { - if (value != _currentBehavior) - OnBehaviorChange(value); - _previousBehavior = _currentBehavior; - _currentBehavior = value; - } - } - - private Action _previousBehavior; - - public Task> Paths { get; set; } - - public Vector2 Position => NPC.Center; - - public Vector2 Velocity { get => NPC.velocity; set => NPC.velocity = value; } - - public float Acceleration => 0.4f; - - public float MaxSpeed => 8f; - #endregion #region AI - protected override bool PlayerSearchFilter(Player p) + protected override void BehaviorOnSpawn() { - return base.PlayerSearchFilter(p) || p == CurrentPlayer && Vector2.DistanceSquared(NPC.Center, p.Center) < 960f * 960f; - } + CurrentBehavior = IdleBehavior; - protected override bool NPCSearchFilter(NPC n) - { - return base.NPCSearchFilter(n) || (n == CurrentPrey || n == CurrentPredator) && Vector2.DistanceSquared(NPC.Center, n.Center) < 960f * 960f; - } + WeightedRandom randomPersonality = new(); + randomPersonality.Add(PersonalityType.Curious, 0.6f); + randomPersonality.Add(PersonalityType.Shy, 0.3f); + randomPersonality.Add(PersonalityType.Paranoid, 0.1f); + Personality = randomPersonality.Get(); - public override void OnSpawn(IEntitySource source) - { - CurrentBehavior = IdlingBehavior; NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; NPC.MaxFallSpeedMultiplier *= 2f; } - public override void AI() + protected override void CreatureAI() { - CurrentBehavior?.Invoke(); + CurrentBehavior.Invoke(); - NPC.rotation = MathHelper.ToRadians(NPC.velocity.X * 3f); - NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); + if (!NPC.velocity.HasNaNs()) + ConeDetectionDirection = (NPC.rotation * MathF.Sign(NPC.velocity.Y) + (NPC.spriteDirection == -1 ? MathHelper.Pi : 0f)).ToRotationVector2(); + NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X); + if (MathF.Abs(NPC.velocity.X) > 2f) + NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); if (!NPC.wet) CurrentBehavior = OutsideWaterBehavior; + if (NPC.velocity.LengthSquared() > MaximumSpeed * MaximumSpeed) + NPC.velocity = NPC.velocity.SafeNormalize(-Vector2.UnitY) * MaximumSpeed; + if (ScaleSquish.Y > 1f) - { ScaleSquish.Y -= 0.025f; - if (ScaleSquish.Y < 1f) - ScaleSquish.Y = 1f; - } + + if (ScaleSquish.Y < 1f) + ScaleSquish.Y = 1f; } - private void OnBehaviorChange(Action newBehavior) => NPC.noGravity = newBehavior != OutsideWaterBehavior; + protected override void OnBehaviorChange(Action newBehavior) => NPC.noGravity = newBehavior != OutsideWaterBehavior; protected override void OnPreyDetection(NPC prey) { // If it's not a small fish and it's not being chased by a predator, the Probesnout may hunt. - if (CurrentPredator != null) - return; + if (CurrentPredator is null) + { + CurrentBehavior = HuntBehavior; + React(Color.Orange * 0.6f, EmoteExpressionParticle.EmoteType.Exclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); + } - CurrentBehavior = HuntBehavior; - ScaleSquish.Y += 0.4f; + ScaleSquish.Y += 1.4f; } protected override void OnPredatorDetection(NPC predator) { // Regardless of anything, if it detects a predator, time to run. - CurrentBehavior = FleeingBehavior; - ScaleSquish.Y += 0.4f; + CurrentBehavior = AvoidBehavior; + + React(Color.Red * 0.6f, EmoteExpressionParticle.EmoteType.DoubleExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); + + ScaleSquish.Y += 1.4f; } protected override void OnPlayerDetection(Player player) { - if (CurrentPredator != null) - return; + // If the Probesnout is shy, it'll run away from the player. + if (Personality == PersonalityType.Shy) + { + CurrentBehavior = AvoidBehavior; + React(Color.Orange, EmoteExpressionParticle.EmoteType.QuestionExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); + } + + if (Personality == PersonalityType.Curious) + React(Color.Green, EmoteExpressionParticle.EmoteType.Question, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); ScaleSquish.Y += 0.4f; } - private void IdlingBehavior() + private void IdleBehavior() { - // At random, the mob will choose a random nearby point and pathfind there. - PathfindingParams parameters = null; - if (Main.rand.NextBool(IdleRandomMovementUnlikeliness)) + if (_pathfindingTask.Result == null) { - _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance); - NPC.netUpdate = true; - parameters = new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); + NPC.velocity *= 0.95f; + + if (Main.rand.NextBool(125)) + _pathfindingTask = CalamityUtils.FindPath(new( + NPC.Center, + NPC.Center + Main.rand.NextVector2CircularEdge(PathDetectionSize, PathDetectionSize) * Main.rand.NextFloat(0.75f, 1f), + SunkenSeaTileValidity)); } - this.DoPathfinding(parameters); + else + GenericPathFollowing(acceleration: 0.03f); } - private void FleeingBehavior() + private void AvoidBehavior() { - // If the avoided entity is gone, go back to idling. - if (CurrentPredator == null) + // Depending on the personality, the Sharkoon will choose who to avoid. + Entity entityToAvoid = null; + switch (Personality) { - CurrentBehavior = IdlingBehavior; + case PersonalityType.Shy: + entityToAvoid = (NearestEntity is NPC nearestNPC && HuntNPCs.Contains(nearestNPC.type)) ? null : NearestEntity; + break; + case PersonalityType.Curious: + entityToAvoid = CurrentPredator; + break; + case PersonalityType.Paranoid: + entityToAvoid = CurrentPredator; + break; + } + + // If there aren't any more targets detected, go back to idling. + if (entityToAvoid is null) + { + CurrentBehavior = IdleBehavior; return; } - // 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 (!Collision.CanHitLine(NPC.Center, 1, 1, NPC.Center + CurrentPredator.DirectionTo(NPC.Center) * 120f, 1, 1)) + bool isAvoidingPredator = entityToAvoid is NPC npc && npc.whoAmI == CurrentPredator.whoAmI; + + if (HasPath) { - _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * 80f; - NPC.netUpdate = true; - this.DoPathfinding(new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); + float fleeingDistance = isAvoidingPredator ? 600f : 300f; + + Vector2 randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(fleeingDistance, fleeingDistance + 100f); + while (Main.tile[randomEscapePoint.ToTileCoordinates()].IsTileSolid()) + randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(fleeingDistance, fleeingDistance + 100f); + + } else - { - NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; - Paths = null; - - // Cap the speed if MaxSpeed has been surpassed. - if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) - NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; - } + GenericPathFollowing(acceleration: 0.14f); } private void HuntBehavior() @@ -217,24 +233,25 @@ namespace CalamityMod.NPCs.SunkenSea // If there's no more prey, go back to idling. if (CurrentPrey is null) { - CurrentBehavior = IdlingBehavior; + CurrentBehavior = IdleBehavior; return; } - // With sight, just go straight at him. Without it, try to pathfind over them. - if (!NPC.HasSight(CurrentPrey.Center)) - this.DoPathfinding(new PathfindingParams(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); + if (!HasLineOfSight(CurrentPrey.Center)) + { + if (HasPath) + GenericPathFollowing(acceleration: 0.14f); + else + _pathfindingTask = CalamityUtils.FindPath(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); + } else - NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; + NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * 0.14f; } private void OutsideWaterBehavior() { if (NPC.wet) - { - NPC.noGravity = true; - CurrentBehavior = _previousBehavior; - } + CurrentBehavior = PreviousBehavior; } #endregion @@ -257,7 +274,7 @@ namespace CalamityMod.NPCs.SunkenSea { Texture2D texture = TextureAssets.Npc[Type].Value; Vector2 drawPosition = NPC.Center - screenPos; - Rectangle frame = texture.Frame(horizontalFrames: 2, verticalFrames: 12, frameX: (int)Animation, frameY: NPC.frame.Y / 44); + Rectangle frame = texture.Frame(horizontalFrames: 2, verticalFrames: 12, frameX: (int)Animation, frameY: NPC.frame.Y / NPC.height); Vector2 anchorPoint = frame.Size() * 0.5f; SpriteEffects flip = NPC.spriteDirection == 1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; @@ -284,28 +301,32 @@ namespace CalamityMod.NPCs.SunkenSea NPC.lifeMax = 5; + NPC.aiStyle = -1; + AIType = -1; NPC.npcSlots = 0.1f; NPC.noGravity = true; NPC.chaseable = false; - NPC.width = 32; - NPC.height = 32; + NPC.width = 44; + NPC.height = 55; } #endregion #region Syncing - private Vector2 _randomPathPoint; - public override void SendExtraAI(BinaryWriter writer) { - writer.WriteVector2(_randomPathPoint); + base.SendExtraAI(writer); + writer.Write7BitEncodedInt(AnimationFrames); + writer.Write7BitEncodedInt(TimePerAnimationFrame); } public override void ReceiveExtraAI(BinaryReader reader) { - _randomPathPoint = reader.ReadVector2(); + base.ReceiveExtraAI(reader); + AnimationFrames = reader.Read7BitEncodedInt(); + TimePerAnimationFrame = reader.Read7BitEncodedInt(); } #endregion diff --git a/NPCs/SunkenSea/Sharkoon.cs b/NPCs/SunkenSea/Sharkoon.cs index b3bf5326f1..5701fd5711 100644 --- a/NPCs/SunkenSea/Sharkoon.cs +++ b/NPCs/SunkenSea/Sharkoon.cs @@ -12,7 +12,6 @@ using Terraria.Audio; using Terraria.DataStructures; using Terraria.GameContent; using Terraria.ID; -using static CalamityMod.CalamityUtils; using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea @@ -157,7 +156,7 @@ namespace CalamityMod.NPCs.SunkenSea #region IPathFinder Implementation - public Task> Paths { get; set; } + public PathfindingTask Path { get; set; } public Vector2 Position => NPC.Center; @@ -257,14 +256,14 @@ namespace CalamityMod.NPCs.SunkenSea private void IdlingBehavior() { // At random, the mob will choose a random nearby point and pathfind there. - PathfindingParams parameters = null; + PathfindingTask task = null; if (Main.rand.NextBool(IdleRandomMovementUnlikeliness)) { _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance); NPC.netUpdate = true; - parameters = new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); + task = new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); } - this.DoPathfinding(parameters); + this.DoPathfinding(task); } private void HuntingBehavior() @@ -278,7 +277,7 @@ namespace CalamityMod.NPCs.SunkenSea // With sight, just go straight at him. Without it, try to pathfind over them. if (!NPC.HasSight(CurrentPrey.Center)) - this.DoPathfinding(new PathfindingParams(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); + this.DoPathfinding(new PathfindingTask(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); else NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; } @@ -311,7 +310,7 @@ namespace CalamityMod.NPCs.SunkenSea 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 PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); + this.DoPathfinding(new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); } // If it's capable of exploding and the predator's within distance, kaboom. diff --git a/Utilities/PathfindingUtils.cs b/Utilities/PathfindingUtils.cs index 5f1127d8ae..c288b110a4 100644 --- a/Utilities/PathfindingUtils.cs +++ b/Utilities/PathfindingUtils.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Terraria; @@ -14,9 +15,13 @@ namespace CalamityMod public interface IPathFinder { /// - /// The result of the pathfinding task that contains a set of points this entity should follow. + /// Represents the working task for calculating this entity's complex path.
+ ///
+ /// If you want to manually access the result of this task, make sure to check before accessing the value of .
+ ///
+ /// Accessing before execution has completed will result in the calling thread being blocked until execution is complete. ///
- public Task> Paths { get; set; } + public PathfindingTask Path { get; set; } /// /// The current position of this entity. Only used to calculate movement for this entity, not pathfinding.
@@ -53,11 +58,11 @@ namespace CalamityMod public bool FollowPath(Vector2 nextPoint) { // Accelerate to the target point. - Velocity += Vector2.Normalize(nextPoint - Position) * Acceleration; + Velocity += (nextPoint - Position).SafeNormalize(Vector2.Zero) * Acceleration; // Cap the speed if MaxSpeed has been surpassed. if (Velocity.LengthSquared() > MaxSpeed * MaxSpeed) - Velocity = Vector2.Normalize(Velocity) * MaxSpeed; + Velocity = 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) @@ -74,10 +79,78 @@ namespace CalamityMod public void IdleBehavior() => Velocity -= Velocity.SafeNormalize(Vector2.Zero) * Math.Min(Velocity.Length(), Acceleration); /// - /// Assigns the value of to based on .
- /// You can override this and do to and executes the pathfinding calculations on a background thread.
+ /// You can override this to do your own modifications to the pathfinding task before assigning and starting the calculations. ///
- public void FindPath(PathfindingParams parameters) => Paths = FindPathAsync(parameters); + public void FindPath(PathfindingTask pathfindingTask) + { + Path = pathfindingTask; + Path.Run(); + } + } + + /// + /// Represents a task for calculating a complex path.
+ /// Allows for synchronous access to an asynchronous execution state, while still providing blocking access where needed. + ///
+ public class PathfindingTask( + Vector2 start, + Vector2 end, + Func tileValidity = null, + Func distanceFunction = null, + Func heuristic = null) + { + public PathfindingTask(Vector2 start, Vector2 end) : this(start, end, null, null, null) + { } + + /// + /// The result of this pathfinding task. + /// + public List Result { get => _task.Task.Result; } + + /// + /// Whether this pathfinding task has completed running. + /// + public bool Ready { get; private set; } = false; + + /// + /// Whether this pathfinding task is still currently running. + /// + public bool Running { get; private set; } = false; + + /// + /// The starting position of this pathfinding task. + /// + public Vector2 StartPosition { get; init; } = start; + + /// + /// The ending position of this pathfinding task. + /// + public Vector2 EndPosition { get; init; } = end; + + // Interal task representation of the work. + private readonly TaskCompletionSource> _task = new(); + + // Internal containing object for the actual work. + private readonly PathfindingWork _work = new(start, end, tileValidity, distanceFunction, heuristic); + + /// + /// Begins execution of this pathfinding task on a background thread. + /// + 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 @@ -86,39 +159,150 @@ namespace CalamityMod /// Causes this to perform path finding and follow the path result, idling when a path is not available.
/// This method should be called every frame that you want your entity to follow it's pathfinding logic. ///
- /// The entity that should be moving. - public static void DoPathfinding(this IPathFinder pathfinder, PathfindingParams parameters) + public static void DoPathfinding(this IPathFinder pathfinder, Vector2 target) => pathfinder.DoPathfinding(new PathfindingTask(pathfinder.Position, target)); + + /// + /// Causes this to perform path finding and follow the path result, idling when a path is not available.
+ /// This method should be called every frame that you want your entity to follow it's pathfinding logic. + ///
+ public static void DoPathfinding(this IPathFinder pathfinder, PathfindingTask task) { - // If the task is NOT in-progress... - if (pathfinder.Paths == null || pathfinder.Paths.IsCompleted) + // 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). + + if (pathfinder.Path == null || // Not started + pathfinder.Path.EndPosition != task.EndPosition || // New destination + (pathfinder.Path.Ready && pathfinder.Path.Result == null)) // Unable to find previous path { - // If the task result has entries... - if ((pathfinder.Paths?.Result?.Count ?? 0) > 0) - { - // Follows the point at index 0 of the path result. - Vector2 nextPoint = pathfinder.Paths.Result[0]; - - // Once that point is reached, it is removed from the list of points to follow. - if (pathfinder.FollowPath(nextPoint)) - pathfinder.Paths.Result.RemoveAt(0); - } - - // If it does not have entries, that means the pathfinding task is - // complete OR the last pathfinding attempt was invalid. - // We need to attempt pathfinding again. Idle in the meantime. - else - { - pathfinder.FindPath(parameters); - pathfinder.IdleBehavior(); - } + pathfinder.FindPath(task); + pathfinder.IdleBehavior(); } - // If the task IS in-progress, just idle while waiting for it to complete. - else + // If the task has been started but is not finished yet, just idle. + else if (pathfinder.Path.Running) pathfinder.IdleBehavior(); + + // Otherwise, the task has been started, completed, and found a valid path. + // Follow the found path. + 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); + } } - public static void DoPathfinding(this IPathFinder pathfinder, Vector2 target) => pathfinder.DoPathfinding(new PathfindingParams(pathfinder.Position, target)); + /// + /// Represents the working computation for a . + /// + /// + /// + /// Has 2 overloads, one for inputting the start and end nodes as , and the other one as . + /// + /// + /// This record contains the start and end nodes, along with functions for tile validity, distance calculation, and heuristic estimation. + /// + /// + /// - : A function that checks if a tile at a given point is valid for traversal. If not provided, all non-solid tiles are considered valid.
+ /// - : A function that calculates the distance between two points. Defaults to .
+ /// - : A function that estimates the cost from a given point to the end point. Defaults to .
+ ///
+ ///
+ public record PathfindingWork(Node Start, Node End, Func TileValidity, Func DistanceFunction, Func Heuristic) + { + private static readonly Func DefaultTileValidity = point => true; + private static readonly Func DefaultDistanceFunction = OctileDistance; + private static readonly Func DefaultHeuristic = OctileDistance; + + public PathfindingWork( + Point start, + Point end, + Func tileValidity = null, + Func distanceFunction = null, + Func heuristic = null) : this( + new Node(start), + new Node(end), + tileValidity ?? DefaultTileValidity, + distanceFunction ?? DefaultDistanceFunction, + heuristic ?? DefaultHeuristic + ) + { + } + + public PathfindingWork( + Vector2 start, + Vector2 end, + Func tileValidity = null, + Func distanceFunction = null, + Func heuristic = null) : this( + new Node(start.ToTileCoordinates()), + new Node(end.ToTileCoordinates()), + tileValidity ?? DefaultTileValidity, + distanceFunction ?? DefaultDistanceFunction, + heuristic ?? DefaultHeuristic + ) + { + } + + /// + /// Calculates a path from the start to the end position using the A* pathfinding algorithm. + /// + /// + /// + /// A list of positions representing the path from start to end, or if no path is found. + /// + public List CalculatePath() + { + if (Main.tile[End.Position].IsTileSolid()) + return null; + + var openSet = new List(); + var closedSet = new HashSet(); + openSet.Add(Start); + + while (openSet.Count > 0) + { + // Get the node with the lowest F value. + var current = openSet[0]; + for (int i = 1; i < openSet.Count; i++) + { + if (openSet[i].F < current.F || (openSet[i].F == current.F && openSet[i].H < current.H)) + current = openSet[i]; + } + + openSet.Remove(current); + closedSet.Add(current); + + // Check if we've reached the goal. + if (current.Position == End.Position) + return current.ReconstructPath(); + + // Generate neighbors. + foreach (var neighbor in current.GetNeighbors()) + { + if (closedSet.Contains(neighbor) || Main.tile[neighbor.Position].IsTileSolid() || !TileValidity.Invoke(neighbor.Position)) + continue; + + float tentativeG = current.G + DistanceFunction.Invoke(current.Position, neighbor.Position); + + if (!openSet.Contains(neighbor) || tentativeG < neighbor.G) + { + neighbor.Parent = current; + neighbor.G = tentativeG; + neighbor.H = Heuristic.Invoke(neighbor.Position, End.Position); + + if (!openSet.Contains(neighbor)) + openSet.Add(neighbor); + } + } + } + + return null; // No path found. + } + } /// /// Represents a node in a pathfinding algorithm, containing position, cost, and parent information. @@ -139,174 +323,42 @@ namespace CalamityMod } public override int GetHashCode() => Position.GetHashCode(); - } - /// - /// Represents the parameters required for the method. - /// - /// - /// - /// Has 2 overloads, one for inputting the start and end nodes as , and the other one as . - /// - /// - /// This record contains the start and end nodes, along with functions for tile validity, distance calculation, and heuristic estimation. - /// - /// - /// - : A function that checks if a tile at a given point is valid for traversal. If not provided, all non-solid tiles are considered valid.
- /// - : A function that calculates the distance between two points. Defaults to .
- /// - : A function that estimates the cost from a given point to the end point. Defaults to .
- ///
- ///
- public record PathfindingParams(Node Start, Node End, Func TileValidity, Func DistanceFunction, Func Heuristic) - { - private static readonly Func DefaultTileValidity = point => true; - private static readonly Func DefaultDistanceFunction = OctileDistance; - private static readonly Func DefaultHeuristic = OctileDistance; - - public PathfindingParams( - Point start, - Point end, - Func tileValidity = null, - Func distanceFunction = null, - Func heuristic = null) : this( - new Node(start), - new Node(end), - tileValidity ?? DefaultTileValidity, - distanceFunction ?? DefaultDistanceFunction, - heuristic ?? DefaultHeuristic - ) + public List GetNeighbors() { - } + var neighbors = new List(Directions.Count); - public PathfindingParams( - Vector2 start, - Vector2 end, - Func tileValidity = null, - Func distanceFunction = null, - Func heuristic = null) : this( - new Node(start.ToTileCoordinates()), - new Node(end.ToTileCoordinates()), - tileValidity ?? DefaultTileValidity, - distanceFunction ?? DefaultDistanceFunction, - heuristic ?? DefaultHeuristic - ) - { - } - } + int nodeX = Position.X; + int nodeY = Position.Y; - /// - /// Asynchronously finds a path from the start to the end position using the A* pathfinding algorithm. - /// - /// - /// The parameters for the pathfinding algorithm, including start, end, and cost functions. - /// - /// - /// A task that represents the asynchronous operation.
The task result contains a list of positions - /// representing the path from start to end, or if no path is found. - ///
- /// - /// - /// - /// This method runs the pathfinding calculations on a separate CPU thread using .
- /// Use to check if the pathfinding is complete, and - /// to retrieve the resulting path. - ///
- ///
- /// - /// - /// - /// var parameters = new PathfindingParams(start, end, TileValidity, DistanceFunction, Heuristic); - /// var pathTask = FindPathAsync(parameters); - /// if (pathTask.Result != null) - /// PathPoints = pathTask.Result; - /// - /// - public static async Task> FindPathAsync(PathfindingParams parameters) - { - return await Task.Run(() => - { - // If the entity isn't actually supposed to follow a path right now, null - // can be passed as the parameters to make implementation more concise. - if (parameters is null || Main.tile[parameters.End.Position].IsTileSolid()) - return null; - - var openSet = new List(); - var closedSet = new HashSet(); - openSet.Add(parameters.Start); - - while (openSet.Count > 0) + foreach (var direction in Directions) { - // Get the node with the lowest F value. - var current = openSet[0]; - for (int i = 1; i < openSet.Count; i++) - { - if (openSet[i].F < current.F || (openSet[i].F == current.F && openSet[i].H < current.H)) - current = openSet[i]; - } + int newX = nodeX + (int)direction.X; + int newY = nodeY + (int)direction.Y; - openSet.Remove(current); - closedSet.Add(current); - - // Check if we've reached the goal. - if (current.Position == parameters.End.Position) - return ReconstructPath(current); - - // Generate neighbors. - foreach (var neighbor in GetNeighbors(current)) - { - if (closedSet.Contains(neighbor) || Main.tile[neighbor.Position].IsTileSolid() || !parameters.TileValidity.Invoke(neighbor.Position)) - continue; - - float tentativeG = current.G + parameters.DistanceFunction.Invoke(current.Position, neighbor.Position); - - if (!openSet.Contains(neighbor) || tentativeG < neighbor.G) - { - neighbor.Parent = current; - neighbor.G = tentativeG; - neighbor.H = parameters.Heuristic.Invoke(neighbor.Position, parameters.End.Position); - - if (!openSet.Contains(neighbor)) - openSet.Add(neighbor); - } - } + if (WorldGen.InWorld(newX, newY)) + neighbors.Add(new Node(new Point(newX, newY))); } - return null; // No path found. - }); - } - - private static List GetNeighbors(Node node) - { - var neighbors = new List(Directions.Count); - - int nodeX = node.Position.X; - int nodeY = node.Position.Y; - - foreach (var direction in Directions) - { - int newX = nodeX + (int)direction.X; - int newY = nodeY + (int)direction.Y; - - if (WorldGen.InWorld(newX, newY)) - neighbors.Add(new Node(new Point(newX, newY))); + return neighbors; } - return neighbors; - } - - private static List ReconstructPath(Node node) - { - var pathStack = new Stack(); - while (node != null) + public List ReconstructPath() { - pathStack.Push(node.Position.ToWorldCoordinates()); - node = node.Parent; + var pathStack = new Stack(); + var node = this; + + while (node != null) + { + pathStack.Push(node.Position.ToWorldCoordinates()); + node = node.Parent; + } + + var path = new List(pathStack.Count); + path.AddRange(pathStack); + + return path; } - - var path = new List(pathStack.Count); - path.AddRange(pathStack); - - return path; } #region Heuristic Functions From 1041d7485e186f81d35544cad5d1159b5b36c8e7 Mon Sep 17 00:00:00 2001 From: NycroV <83246959+NycroV@users.noreply.github.com> Date: Mon, 10 Feb 2025 17:30:52 -0500 Subject: [PATCH 16/18] Sorry Memes --- NPCs/SunkenSea/Probesnout.cs | 249 ++++++++++++++++------------------- 1 file changed, 114 insertions(+), 135 deletions(-) diff --git a/NPCs/SunkenSea/Probesnout.cs b/NPCs/SunkenSea/Probesnout.cs index aad10dcaf6..adaa978d5f 100644 --- a/NPCs/SunkenSea/Probesnout.cs +++ b/NPCs/SunkenSea/Probesnout.cs @@ -3,51 +3,44 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using CalamityMod.Enums; -using CalamityMod.Particles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; +using Terraria.DataStructures; using Terraria.GameContent; using Terraria.ID; -using Terraria.Utilities; +using static CalamityMod.CalamityUtils; using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea { - public class Probesnout : SunkenSeaNPC + public class Probesnout : SunkenSeaNPC, IPathFinder { - public static float PathDetectionSize = 300f; - private static Task> _pathfindingTask; - #region Members - protected override List HuntNPCs => new() - { - // NPCType(), - }; + public static int IdleRandomMovementUnlikeliness = 250; + public static int IdleMinPathDistance = 200; + public static int IdleMaxPathDistance = 400; - protected override List AvoidNPCs => new() - { + public static int FleeTileAnticipationDistance = 5 * 16; + public static int FleeMinPathDistance = 80; + public static int FleeMaxPathDistance = 160; + + protected override List PreyIDs => + [ + // NPCType(), + ]; + + protected override List PredatorIDs => + [ // NPCType(), NPCType(), // NPCType(), // NPCType(), // NPCType(), - }; + ]; - private enum PersonalityType { Curious, Shy, Paranoid } - - private PersonalityType Personality - { - get => (PersonalityType)NPC.ai[0]; - set - { - NPC.ai[0] = (float)value; - NetUpdate(); - } - } - - private enum AnimationState { Idle, Attack } + private enum AnimationState { Idle, Eating } private AnimationState Animation { @@ -66,166 +59,157 @@ namespace CalamityMod.NPCs.SunkenSea AnimationFrames = 8; TimePerAnimationFrame = 5; break; - case AnimationState.Attack: + case AnimationState.Eating: AnimationFrames = 12; TimePerAnimationFrame = 7; break; } NPC.ai[1] = (float)value; - NetUpdate(); } } protected override SunkenSeaBiomeFlags BiomeDesignation => SunkenSeaBiomeFlags.RadiantReefs; - protected override float SpawningChance => 0f; - private int AnimationFrames = 8; private int TimePerAnimationFrame = 5; - private float MaximumSpeed = 6f; - private Vector2 ScaleSquish = Vector2.One; + private Action _currentBehavior; + private Action CurrentBehavior + { + get => _currentBehavior; + set + { + if (value != _currentBehavior) + OnBehaviorChange(value); + _previousBehavior = _currentBehavior; + _currentBehavior = value; + } + } + + private Action _previousBehavior; + + public Task> Paths { get; set; } + + public Vector2 Position => NPC.Center; + + public Vector2 Velocity { get => NPC.velocity; set => NPC.velocity = value; } + + public float Acceleration => 0.4f; + + public float MaxSpeed => 8f; + #endregion #region AI - protected override void BehaviorOnSpawn() + protected override bool PlayerSearchFilter(Player p) { - CurrentBehavior = IdleBehavior; + return base.PlayerSearchFilter(p) || p == CurrentPlayer && Vector2.DistanceSquared(NPC.Center, p.Center) < 960f * 960f; + } - WeightedRandom randomPersonality = new(); - randomPersonality.Add(PersonalityType.Curious, 0.6f); - randomPersonality.Add(PersonalityType.Shy, 0.3f); - randomPersonality.Add(PersonalityType.Paranoid, 0.1f); - Personality = randomPersonality.Get(); + protected override bool NPCSearchFilter(NPC n) + { + return base.NPCSearchFilter(n) || (n == CurrentPrey || n == CurrentPredator) && Vector2.DistanceSquared(NPC.Center, n.Center) < 960f * 960f; + } + public override void OnSpawn(IEntitySource source) + { + CurrentBehavior = IdlingBehavior; NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; NPC.MaxFallSpeedMultiplier *= 2f; } - protected override void CreatureAI() + public override void AI() { - CurrentBehavior.Invoke(); + CurrentBehavior?.Invoke(); - if (!NPC.velocity.HasNaNs()) - ConeDetectionDirection = (NPC.rotation * MathF.Sign(NPC.velocity.Y) + (NPC.spriteDirection == -1 ? MathHelper.Pi : 0f)).ToRotationVector2(); + NPC.rotation = MathHelper.ToRadians(NPC.velocity.X * 3f); + NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); - NPC.rotation = MathHelper.ToRadians(NPC.velocity.Length() * 3f) * MathF.Sign(NPC.velocity.X); - if (MathF.Abs(NPC.velocity.X) > 2f) - NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); if (!NPC.wet) CurrentBehavior = OutsideWaterBehavior; - if (NPC.velocity.LengthSquared() > MaximumSpeed * MaximumSpeed) - NPC.velocity = NPC.velocity.SafeNormalize(-Vector2.UnitY) * MaximumSpeed; - if (ScaleSquish.Y > 1f) + { ScaleSquish.Y -= 0.025f; - - if (ScaleSquish.Y < 1f) - ScaleSquish.Y = 1f; + if (ScaleSquish.Y < 1f) + ScaleSquish.Y = 1f; + } } - protected override void OnBehaviorChange(Action newBehavior) => NPC.noGravity = newBehavior != OutsideWaterBehavior; + private void OnBehaviorChange(Action newBehavior) => NPC.noGravity = newBehavior != OutsideWaterBehavior; protected override void OnPreyDetection(NPC prey) { // If it's not a small fish and it's not being chased by a predator, the Probesnout may hunt. - if (CurrentPredator is null) - { - CurrentBehavior = HuntBehavior; - React(Color.Orange * 0.6f, EmoteExpressionParticle.EmoteType.Exclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - } + if (CurrentPredator != null) + return; - ScaleSquish.Y += 1.4f; + CurrentBehavior = HuntBehavior; + ScaleSquish.Y += 0.4f; } protected override void OnPredatorDetection(NPC predator) { // Regardless of anything, if it detects a predator, time to run. - CurrentBehavior = AvoidBehavior; - - React(Color.Red * 0.6f, EmoteExpressionParticle.EmoteType.DoubleExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - - ScaleSquish.Y += 1.4f; + CurrentBehavior = FleeingBehavior; + ScaleSquish.Y += 0.4f; } protected override void OnPlayerDetection(Player player) { - // If the Probesnout is shy, it'll run away from the player. - if (Personality == PersonalityType.Shy) - { - CurrentBehavior = AvoidBehavior; - React(Color.Orange, EmoteExpressionParticle.EmoteType.QuestionExclamation, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); - } - - if (Personality == PersonalityType.Curious) - React(Color.Green, EmoteExpressionParticle.EmoteType.Question, new("CalamityMod/Sounds/Custom/ur") { PitchVariance = 0.2f }); + if (CurrentPredator != null) + return; ScaleSquish.Y += 0.4f; } - private void IdleBehavior() + private void IdlingBehavior() { - if (_pathfindingTask.Result == null) + // At random, the mob will choose a random nearby point and pathfind there. + PathfindingParams parameters = null; + if (Main.rand.NextBool(IdleRandomMovementUnlikeliness)) { - NPC.velocity *= 0.95f; - - if (Main.rand.NextBool(125)) - _pathfindingTask = CalamityUtils.FindPath(new( - NPC.Center, - NPC.Center + Main.rand.NextVector2CircularEdge(PathDetectionSize, PathDetectionSize) * Main.rand.NextFloat(0.75f, 1f), - SunkenSeaTileValidity)); + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance); + NPC.netUpdate = true; + parameters = new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); } - else - GenericPathFollowing(acceleration: 0.03f); + this.DoPathfinding(parameters); } - private void AvoidBehavior() + private void FleeingBehavior() { - // Depending on the personality, the Sharkoon will choose who to avoid. - Entity entityToAvoid = null; - switch (Personality) + // If the avoided entity is gone, go back to idling. + if (CurrentPredator == null) { - case PersonalityType.Shy: - entityToAvoid = (NearestEntity is NPC nearestNPC && HuntNPCs.Contains(nearestNPC.type)) ? null : NearestEntity; - break; - case PersonalityType.Curious: - entityToAvoid = CurrentPredator; - break; - case PersonalityType.Paranoid: - entityToAvoid = CurrentPredator; - break; - } - - // If there aren't any more targets detected, go back to idling. - if (entityToAvoid is null) - { - CurrentBehavior = IdleBehavior; + CurrentBehavior = IdlingBehavior; return; } - bool isAvoidingPredator = entityToAvoid is NPC npc && npc.whoAmI == CurrentPredator.whoAmI; - - if (HasPath) + // 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 (!Collision.CanHitLine(NPC.Center, 1, 1, NPC.Center + CurrentPredator.DirectionTo(NPC.Center) * 120f, 1, 1)) { - float fleeingDistance = isAvoidingPredator ? 600f : 300f; - - Vector2 randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(fleeingDistance, fleeingDistance + 100f); - while (Main.tile[randomEscapePoint.ToTileCoordinates()].IsTileSolid()) - randomEscapePoint = NPC.Center + NPC.DirectionFrom(entityToAvoid.Center).RotatedByRandom(MathHelper.PiOver2) * Main.rand.NextFloat(fleeingDistance, fleeingDistance + 100f); - - + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * 80f; + NPC.netUpdate = true; + this.DoPathfinding(new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); } else - GenericPathFollowing(acceleration: 0.14f); + { + NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; + Paths = null; + + // Cap the speed if MaxSpeed has been surpassed. + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + } } private void HuntBehavior() @@ -233,25 +217,24 @@ namespace CalamityMod.NPCs.SunkenSea // If there's no more prey, go back to idling. if (CurrentPrey is null) { - CurrentBehavior = IdleBehavior; + CurrentBehavior = IdlingBehavior; return; } - if (!HasLineOfSight(CurrentPrey.Center)) - { - if (HasPath) - GenericPathFollowing(acceleration: 0.14f); - else - _pathfindingTask = CalamityUtils.FindPath(new(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); - } + // With sight, just go straight at him. Without it, try to pathfind over them. + if (!NPC.HasSight(CurrentPrey.Center)) + this.DoPathfinding(new PathfindingParams(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); else - NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * 0.14f; + NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; } private void OutsideWaterBehavior() { if (NPC.wet) - CurrentBehavior = PreviousBehavior; + { + NPC.noGravity = true; + CurrentBehavior = _previousBehavior; + } } #endregion @@ -274,7 +257,7 @@ namespace CalamityMod.NPCs.SunkenSea { Texture2D texture = TextureAssets.Npc[Type].Value; Vector2 drawPosition = NPC.Center - screenPos; - Rectangle frame = texture.Frame(horizontalFrames: 2, verticalFrames: 12, frameX: (int)Animation, frameY: NPC.frame.Y / NPC.height); + Rectangle frame = texture.Frame(horizontalFrames: 2, verticalFrames: 12, frameX: (int)Animation, frameY: NPC.frame.Y / 44); Vector2 anchorPoint = frame.Size() * 0.5f; SpriteEffects flip = NPC.spriteDirection == 1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; @@ -301,32 +284,28 @@ namespace CalamityMod.NPCs.SunkenSea NPC.lifeMax = 5; - NPC.aiStyle = -1; - AIType = -1; NPC.npcSlots = 0.1f; NPC.noGravity = true; NPC.chaseable = false; - NPC.width = 44; - NPC.height = 55; + NPC.width = 32; + NPC.height = 32; } #endregion #region Syncing + private Vector2 _randomPathPoint; + public override void SendExtraAI(BinaryWriter writer) { - base.SendExtraAI(writer); - writer.Write7BitEncodedInt(AnimationFrames); - writer.Write7BitEncodedInt(TimePerAnimationFrame); + writer.WriteVector2(_randomPathPoint); } public override void ReceiveExtraAI(BinaryReader reader) { - base.ReceiveExtraAI(reader); - AnimationFrames = reader.Read7BitEncodedInt(); - TimePerAnimationFrame = reader.Read7BitEncodedInt(); + _randomPathPoint = reader.ReadVector2(); } #endregion From 6acac7c18afd77d64c0a9de48003adc78b362f98 Mon Sep 17 00:00:00 2001 From: Memes <114233643+Mr-Memes@users.noreply.github.com> Date: Wed, 26 Feb 2025 22:50:35 +0100 Subject: [PATCH 17/18] Pathfinding Interface Finished. --- Utilities/PathfindingUtils.cs | 50 +++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/Utilities/PathfindingUtils.cs b/Utilities/PathfindingUtils.cs index c288b110a4..b4143f8482 100644 --- a/Utilities/PathfindingUtils.cs +++ b/Utilities/PathfindingUtils.cs @@ -2,6 +2,7 @@ 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; @@ -76,7 +77,7 @@ namespace CalamityMod /// Defines how this entity should behave while there is no current path to follow.
/// By default, decelerates and stops based on . ///
- public void IdleBehavior() => Velocity -= Velocity.SafeNormalize(Vector2.Zero) * Math.Min(Velocity.Length(), Acceleration); + public void IdleBehavior() => Velocity *= 0.95f; /// /// Assigns the value of to and executes the pathfinding calculations on a background thread.
@@ -84,6 +85,9 @@ namespace CalamityMod ///
public void FindPath(PathfindingTask pathfindingTask) { + if (pathfindingTask == null) + return; + Path = pathfindingTask; Path.Run(); } @@ -165,23 +169,26 @@ namespace CalamityMod /// Causes this to perform path finding and follow the path result, idling when a path is not available.
/// This method should be called every frame that you want your entity to follow it's pathfinding logic. /// - public static void DoPathfinding(this IPathFinder pathfinder, PathfindingTask task) + public static void DoPathfinding(this IPathFinder pathfinder, PathfindingTask task, bool continuouslyUpdatePath = false) { - // 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). + // If the task has been started but is not finished yet, just idle. + if (pathfinder.Path?.Running ?? false) + pathfinder.IdleBehavior(); - if (pathfinder.Path == null || // Not started - pathfinder.Path.EndPosition != task.EndPosition || // New destination - (pathfinder.Path.Ready && pathfinder.Path.Result == null)) // Unable to find previous path + // 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(); } - // If the task has been started but is not finished yet, just idle. - else if (pathfinder.Path.Running) - pathfinder.IdleBehavior(); - // Otherwise, the task has been started, completed, and found a valid path. // Follow the found path. else @@ -408,5 +415,26 @@ namespace CalamityMod return doesFit; } + + public static List GetIntersectingHitboxPoints(this Entity entity, Point position, int fluffX = 0, int fluffY = 0) + { + 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); + int endY = (int)Math.Floor((hitbox.Bottom - float.Epsilon) / 16); + + List intersectingPoints = []; + for (int i = startX; i <= endX; i++) + { + for (int j = startY; j <= endY; j++) + intersectingPoints.Add(new Point(i, j)); + } + + return intersectingPoints; + } } } From d7ed5a8a173c923b2bd40632b9aa9f911fcc65c0 Mon Sep 17 00:00:00 2001 From: Memes <114233643+Mr-Memes@users.noreply.github.com> Date: Wed, 26 Feb 2025 23:03:42 +0100 Subject: [PATCH 18/18] No compile errors. --- NPCs/SunkenSea/Probesnout.cs | 186 +++++++++++++++++++++++++++------ NPCs/SunkenSea/Sharkoon.cs | 20 +++- NPCs/SunkenSea/SunkenSeaNPC.cs | 36 +++---- 3 files changed, 187 insertions(+), 55 deletions(-) diff --git a/NPCs/SunkenSea/Probesnout.cs b/NPCs/SunkenSea/Probesnout.cs index adaa978d5f..1c138250c2 100644 --- a/NPCs/SunkenSea/Probesnout.cs +++ b/NPCs/SunkenSea/Probesnout.cs @@ -1,14 +1,18 @@ using System; using System.Collections.Generic; using System.IO; -using System.Threading.Tasks; +using System.Linq; +using System.Threading; using CalamityMod.Enums; +using CalamityMod.Items.Placeables.Banners; +using CalamityMod.Tiles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.DataStructures; using Terraria.GameContent; using Terraria.ID; +using Terraria.ModLoader; using static CalamityMod.CalamityUtils; using static Terraria.ModLoader.ModContent; @@ -83,8 +87,6 @@ namespace CalamityMod.NPCs.SunkenSea get => _currentBehavior; set { - if (value != _currentBehavior) - OnBehaviorChange(value); _previousBehavior = _currentBehavior; _currentBehavior = value; } @@ -92,7 +94,7 @@ namespace CalamityMod.NPCs.SunkenSea private Action _previousBehavior; - public Task> Paths { get; set; } + public PathfindingTask Path { get; set; } public Vector2 Position => NPC.Center; @@ -102,6 +104,10 @@ namespace CalamityMod.NPCs.SunkenSea public float MaxSpeed => 8f; + private Vector2 SpongeFoundPosition; + + private bool HasEatenSponge; + #endregion #region AI @@ -129,23 +135,24 @@ namespace CalamityMod.NPCs.SunkenSea CurrentBehavior?.Invoke(); NPC.rotation = MathHelper.ToRadians(NPC.velocity.X * 3f); - NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); + if (CurrentBehavior == EatingBehavior && Vector2.DistanceSquared(NPC.Center, SpongeFoundPosition) <= 64f * 64f) + NPC.spriteDirection = NPC.direction = MathF.Sign(SpongeFoundPosition.X - NPC.Center.X); + else if (NPC.velocity.LengthSquared() != 0f) + NPC.spriteDirection = NPC.direction = MathF.Sign(NPC.velocity.X); + if (Main.rand.NextBool(50) && !HasEatenSponge && CurrentBehavior == IdlingBehavior) + ThreadPool.QueueUserWorkItem(_ => DetectSponges(), null); - - if (!NPC.wet) + if (!NPC.wet && CurrentBehavior != OutsideWaterBehavior) + { + NPC.noGravity = false; CurrentBehavior = OutsideWaterBehavior; + } if (ScaleSquish.Y > 1f) - { - ScaleSquish.Y -= 0.025f; - if (ScaleSquish.Y < 1f) - ScaleSquish.Y = 1f; - } + ScaleSquish.Y = Math.Max(1f, ScaleSquish.Y - 0.025f); } - private void OnBehaviorChange(Action newBehavior) => NPC.noGravity = newBehavior != OutsideWaterBehavior; - protected override void OnPreyDetection(NPC prey) { // If it's not a small fish and it's not being chased by a predator, the Probesnout may hunt. @@ -174,12 +181,12 @@ namespace CalamityMod.NPCs.SunkenSea private void IdlingBehavior() { // At random, the mob will choose a random nearby point and pathfind there. - PathfindingParams parameters = null; - if (Main.rand.NextBool(IdleRandomMovementUnlikeliness)) + PathfindingTask parameters = null; + if (Main.rand.NextBool(150)) { - _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * Main.rand.NextFloat(IdleMinPathDistance, IdleMaxPathDistance); + _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * 300f; NPC.netUpdate = true; - parameters = new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); + parameters = new PathfindingTask(NPC.Center, _randomPathPoint, SunkenSeaTileValidity); } this.DoPathfinding(parameters); } @@ -195,16 +202,26 @@ namespace CalamityMod.NPCs.SunkenSea // 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 (!Collision.CanHitLine(NPC.Center, 1, 1, NPC.Center + CurrentPredator.DirectionTo(NPC.Center) * 120f, 1, 1)) + var headedDirection = CurrentPredator.DirectionTo(NPC.Center) * 200f; + // bool tileNotWater = GetIntersectingPoints(NPC.Center, NPC.Center + headedDirection).Any(point => Main.tile[point].IsTileSolid() || Main.tile[point].LiquidAmount < 255); + + if (false) { - _randomPathPoint = NPC.Center + Main.rand.NextVector2Unit() * 80f; + do + { + var randomNormalDirection = headedDirection.RotatedBy(MathHelper.PiOver2 * Main.rand.NextBool().ToDirectionInt()); + _randomPathPoint = randomNormalDirection.RotatedByRandom(MathHelper.PiOver4); + if (!Main.tile[(NPC.Center + _randomPathPoint).ToTileCoordinates()].IsTileSolid()) + break; + } + while (!Main.tile[(NPC.Center + _randomPathPoint).ToTileCoordinates()].IsTileSolid()); NPC.netUpdate = true; - this.DoPathfinding(new PathfindingParams(NPC.Center, _randomPathPoint, SunkenSeaTileValidity)); + this.DoPathfinding(new PathfindingTask(NPC.Center, NPC.Center + _randomPathPoint, SunkenSeaTileValidity)); } else { NPC.velocity += NPC.DirectionFrom(CurrentPredator.Center) * Acceleration; - Paths = null; + Path = null; // Cap the speed if MaxSpeed has been surpassed. if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) @@ -222,10 +239,25 @@ namespace CalamityMod.NPCs.SunkenSea } // With sight, just go straight at him. Without it, try to pathfind over them. - if (!NPC.HasSight(CurrentPrey.Center)) - this.DoPathfinding(new PathfindingParams(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); + this.DoPathfinding(new PathfindingTask(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity), continuouslyUpdatePath: true); + } + + private void EatingBehavior() + { + if (Vector2.DistanceSquared(NPC.Center, SpongeFoundPosition) <= 64f * 64f) + { + NPC.velocity *= 0.9f; + Animation = AnimationState.Eating; + if (NPC.frame.Y >= NPC.height * AnimationFrames) + { + HasEatenSponge = true; + Animation = AnimationState.Idle; + CurrentBehavior = IdlingBehavior; + return; + } + } else - NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; + this.DoPathfinding(new PathfindingTask(NPC.Center, SpongeFoundPosition, SunkenSeaTileValidity)); } private void OutsideWaterBehavior() @@ -237,6 +269,77 @@ namespace CalamityMod.NPCs.SunkenSea } } + private void DetectSponges() + { + Vector2? closestSpongeFound = null; + float closestDistanceSquared = float.MaxValue; + + foreach (var direction in Directions) + { + // var points = GetIntersectingPoints(NPC.Center, NPC.Center + direction * 360f); + var points = new Point[1]; + foreach (var point in points) + { + // 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()) + { + // 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 + break; + } + } + } + + // Update behavior if a valid tile was found + if (closestSpongeFound.HasValue) + { + CurrentBehavior = EatingBehavior; + SpongeFoundPosition = closestSpongeFound.Value; + } + } + + public override void HitEffect(NPC.HitInfo hit) + { + for (int k = 0; k < 25; k++) + { + Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.Blood, hit.HitDirection, -1f, 0, default, 1f); + } + if (NPC.life <= 0) + { + for (int i = 0; i < 4; i++) + Gore.NewGoreDirect(NPC.GetSource_Death(), NPC.Center, new Vector2(hit.HitDirection, -1f), Mod.Find($"{Name}{i + 1}").Type); + } + } + #endregion #region Drawing & Animation @@ -248,8 +351,9 @@ namespace CalamityMod.NPCs.SunkenSea { NPC.frame.Y += frameHeight; NPC.frame.Y = Math.Min(NPC.frame.Y, AnimationFrames * frameHeight); - NPC.frame.Y = NPC.frame.Y % (AnimationFrames * frameHeight); NPC.frameCounter = 0; + if (Animation == AnimationState.Idle) + NPC.frame.Y %= AnimationFrames * frameHeight; } } @@ -257,7 +361,7 @@ namespace CalamityMod.NPCs.SunkenSea { Texture2D texture = TextureAssets.Npc[Type].Value; Vector2 drawPosition = NPC.Center - screenPos; - Rectangle frame = texture.Frame(horizontalFrames: 2, verticalFrames: 12, frameX: (int)Animation, frameY: NPC.frame.Y / 44); + Rectangle frame = texture.Frame(horizontalFrames: 2, verticalFrames: 12, frameX: (int)Animation, frameY: NPC.frame.Y / NPC.height); Vector2 anchorPoint = frame.Size() * 0.5f; SpriteEffects flip = NPC.spriteDirection == 1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None; @@ -273,7 +377,7 @@ namespace CalamityMod.NPCs.SunkenSea public override void SetStaticDefaults() { base.SetStaticDefaults(); - Main.npcFrameCount[Type] = 15; + Main.npcFrameCount[Type] = 12; Main.npcCatchable[Type] = true; NPCID.Sets.CountsAsCritter[Type] = true; } @@ -281,6 +385,8 @@ namespace CalamityMod.NPCs.SunkenSea public override void SetDefaults() { base.SetDefaults(); + + // BannerItem = ItemType(); NPC.lifeMax = 5; @@ -288,8 +394,17 @@ namespace CalamityMod.NPCs.SunkenSea NPC.noGravity = true; NPC.chaseable = false; - NPC.width = 32; - NPC.height = 32; + NPC.width = 44; + NPC.height = 50; + + NPC.HitSound = SoundID.NPCHit1; + NPC.DeathSound = SoundID.NPCDeath1; + NPC.value = Item.buyPrice(0, 0, 5, 0); + + NPC.Calamity().VulnerableToHeat = false; + NPC.Calamity().VulnerableToSickness = true; + NPC.Calamity().VulnerableToElectricity = true; + NPC.Calamity().VulnerableToWater = false; } #endregion @@ -327,8 +442,15 @@ namespace CalamityMod.NPCs.SunkenSea public override void HitEffect(NPC.HitInfo hit) { - for (int i = 0; i < 5; i++) - Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.GoldCritter, hit.HitDirection, -1f); + for (int k = 0; k < 25; k++) + { + Dust.NewDust(NPC.position, NPC.width, NPC.height, DustID.GoldCritter, hit.HitDirection, -1f, 0, default, 1f); + } + if (NPC.life <= 0) + { + for (int i = 0; i < 4; i++) + Gore.NewGoreDirect(NPC.GetSource_Death(), NPC.Center, new Vector2(hit.HitDirection, -1f), Mod.Find($"{Name}{i + 1}").Type); + } } } } diff --git a/NPCs/SunkenSea/Sharkoon.cs b/NPCs/SunkenSea/Sharkoon.cs index 5701fd5711..020db79c93 100644 --- a/NPCs/SunkenSea/Sharkoon.cs +++ b/NPCs/SunkenSea/Sharkoon.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.IO; -using System.Threading.Tasks; using CalamityMod.Enums; +using CalamityMod.Items.Placeables.Banners; using CalamityMod.Particles; using CalamityMod.Projectiles.Enemy; using Microsoft.Xna.Framework; @@ -12,6 +12,8 @@ using Terraria.Audio; using Terraria.DataStructures; using Terraria.GameContent; using Terraria.ID; +using Terraria.ModLoader; +using static CalamityMod.CalamityUtils; using static Terraria.ModLoader.ModContent; namespace CalamityMod.NPCs.SunkenSea @@ -137,7 +139,8 @@ namespace CalamityMod.NPCs.SunkenSea [ // NPCType(), NPCType(), - // NPCType(), + NPCType(), + NPCType(), NPCType(), NPCType(), ]; @@ -182,6 +185,8 @@ namespace CalamityMod.NPCs.SunkenSea { base.SetDefaults(); + // BannerItem = ItemType(); + NPC.damage = 20; NPC.lifeMax = 350; NPC.defense = 5; @@ -218,7 +223,7 @@ namespace CalamityMod.NPCs.SunkenSea public override void OnSpawn(IEntitySource source) { - //CurrentBehavior = IdlingBehavior; + CurrentBehavior = IdlingBehavior; NPC.spriteDirection = Main.rand.NextBool().ToDirectionInt(); NPC.GravityMultiplier *= 2f; NPC.MaxFallSpeedMultiplier *= 2f; @@ -279,10 +284,13 @@ namespace CalamityMod.NPCs.SunkenSea if (!NPC.HasSight(CurrentPrey.Center)) this.DoPathfinding(new PathfindingTask(NPC.Center, CurrentPrey.Center, SunkenSeaTileValidity)); else + { NPC.velocity += NPC.DirectionTo(CurrentPrey.Center) * Acceleration; + if (NPC.velocity.LengthSquared() > MaxSpeed * MaxSpeed) + NPC.velocity = Vector2.Normalize(NPC.velocity) * MaxSpeed; + } } - private void FleeingBehavior() { // Check who is the avoided entity specifically. @@ -389,6 +397,8 @@ namespace CalamityMod.NPCs.SunkenSea // When it gets outside of water, it'll try to gravitate downards towards the water. if (newBehavior == OutsideWaterBehavior) NPC.noGravity = false; + + Path = null; } protected override void OnPreyDetection(NPC prey) @@ -438,7 +448,7 @@ namespace CalamityMod.NPCs.SunkenSea } } - public override bool CanBeHitByNPC(NPC attacker) => attacker.whoAmI != NPC.whoAmI; + public override bool CanBeHitByNPC(NPC attacker) => attacker.type != Type; public override void OnHitByNPC(NPC attacker) { diff --git a/NPCs/SunkenSea/SunkenSeaNPC.cs b/NPCs/SunkenSea/SunkenSeaNPC.cs index 03b84f2512..1f1680f7a0 100644 --- a/NPCs/SunkenSea/SunkenSeaNPC.cs +++ b/NPCs/SunkenSea/SunkenSeaNPC.cs @@ -97,15 +97,7 @@ namespace CalamityMod.NPCs.SunkenSea .Select(flag => SunkenSeaBiomeCorrespondentDict.Dict[flag].BiomeType) .ToArray(); - try - { - Banner = Type; - BannerItem = ModContent.Find($"{Name}Banner").Type; - } - catch (Exception ex) - { - CalamityMod.Instance.Logger.Warn(ex); - } + Banner = Type; } public override void SetBestiary(BestiaryDatabase database, BestiaryEntry bestiaryEntry) @@ -163,15 +155,18 @@ namespace CalamityMod.NPCs.SunkenSea var searchResults = SearchForTarget(NPC, playerFilter: PlayerSearchFilter, npcFilter: NPCSearchFilter); if (searchResults.FoundTarget) { - if (PredatorIDs.Contains(searchResults.NearestNPC.type)) - CurrentPredator = searchResults.NearestNPC; - else - CurrentPredator = null; + if (searchResults.FoundNPC) + { + if (PredatorIDs.Contains(searchResults.NearestNPC.type)) + CurrentPredator = searchResults.NearestNPC; + else + CurrentPredator = null; - if (PreyIDs.Contains(searchResults.NearestNPC.type)) - CurrentPrey = searchResults.NearestNPC; - else - CurrentPrey = null; + if (PreyIDs.Contains(searchResults.NearestNPC.type)) + CurrentPrey = searchResults.NearestNPC; + else + CurrentPrey = null; + } CurrentPlayer = searchResults.NearestTankOwner; } @@ -189,6 +184,11 @@ namespace CalamityMod.NPCs.SunkenSea /// The tile location to check. /// if the tile is valid; otherwise, . protected bool SunkenSeaTileValidity(Point point) - => Main.tile[point].LiquidAmount > 128 && Main.tile[point].LiquidType == LiquidID.Water && NPC.DoesEntityFitInPath(point, 6, 6); + { + 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); + } } }