diff --git a/Balancing/BalancingChangesManager.cs b/Balancing/BalancingChangesManager.cs index 01d5406569..e357f081a4 100644 --- a/Balancing/BalancingChangesManager.cs +++ b/Balancing/BalancingChangesManager.cs @@ -171,9 +171,6 @@ namespace CalamityMod.Balancing // 50% resist to Aftershock's rocks. NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.DestroyerIDs, Do(new ProjectileResistBalancingRule(0.5f, ProjectileType())))); - // 50% resist to Avalanche's Ice Bombs and shards. - NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.DestroyerIDs, Do(new ProjectileResistBalancingRule(0.5f, ProjectileType(), ProjectileType())))); - // 50% resist to Dormant Brimseeker. NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.DestroyerIDs, Do(new ProjectileResistBalancingRule(0.5f, ProjectileType())))); @@ -183,6 +180,9 @@ namespace CalamityMod.Balancing // 30% resist to Meowthrower. NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.DestroyerIDs, Do(new ProjectileResistBalancingRule(0.7f, ProjectileType())))); + // 25% resist to Avalanche's Ice Bombs and shards. + NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.DestroyerIDs, Do(new ProjectileResistBalancingRule(0.75f, ProjectileType(), ProjectileType())))); + // 25% resist to SHPC. NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.DestroyerIDs, Do(new ProjectileResistBalancingRule(0.75f, ProjectileType())))); @@ -276,6 +276,9 @@ namespace CalamityMod.Balancing // 50% resist to Aurora Blazer. NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.AstrumDeusIDs, Do(new ProjectileResistBalancingRule(0.5f, ProjectileType())))); + // 35% resist to Aerial Bane. + NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.AstrumDeusIDs, Do(new ProjectileResistBalancingRule(0.65f, ProjectileID.DD2BetsyArrow)))); + // 35% resist to Ballistic Poison Bomb's clouds. NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.AstrumDeusIDs, Do(new ProjectileResistBalancingRule(0.65f, ProjectileType())))); @@ -480,6 +483,9 @@ namespace CalamityMod.Balancing // 15% resist to The Final Dawn's AoE sweep flames. NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.ThanatosIDs, Do(new ProjectileResistBalancingRule(0.85f, ProjectileType())))); + // 15% resist to Dragon's Breath Beam. + NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.ThanatosIDs, Do(new ProjectileResistBalancingRule(0.85f, ProjectileType())))); + // 15% resist to God Slayer Slugs. NPCSpecificBalancingChanges.AddRange(Bundle(CalamityLists.ThanatosIDs, Do(new ProjectileResistBalancingRule(0.85f, ProjectileType())))); diff --git a/Buffs/Summon/FlarebatBuff.cs b/Buffs/Summon/FlarebatBuff.cs new file mode 100644 index 0000000000..e1e2c6b14b --- /dev/null +++ b/Buffs/Summon/FlarebatBuff.cs @@ -0,0 +1,35 @@ +using CalamityMod.CalPlayer; +using CalamityMod.Projectiles.Summon; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.Buffs.Summon +{ + public class FlarebatBuff : ModBuff + { + public override void SetStaticDefaults() + { + Main.buffNoTimeDisplay[Type] = true; + Main.buffNoSave[Type] = true; + } + + public override void Update(Player player, ref int buffIndex) + { + CalamityPlayer modPlayer = player.Calamity(); + if (player.ownedProjectileCounts[ModContent.ProjectileType()] > 0) + { + modPlayer.FlarebatBool = true; + } + + if (!modPlayer.FlarebatBool) + { + player.DelBuff(buffIndex); + buffIndex--; + } + else + { + player.buffTime[buffIndex] = 18000; + } + } + } +} diff --git a/Buffs/Summon/FlarebatBuff.png b/Buffs/Summon/FlarebatBuff.png new file mode 100644 index 0000000000..7ead34d654 Binary files /dev/null and b/Buffs/Summon/FlarebatBuff.png differ diff --git a/Buffs/Summon/FrostbatBuff.cs b/Buffs/Summon/FrostbatBuff.cs new file mode 100644 index 0000000000..3c2d57186f --- /dev/null +++ b/Buffs/Summon/FrostbatBuff.cs @@ -0,0 +1,35 @@ +using CalamityMod.CalPlayer; +using CalamityMod.Projectiles.Summon; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.Buffs.Summon +{ + public class FrostbatBuff : ModBuff + { + public override void SetStaticDefaults() + { + Main.buffNoTimeDisplay[Type] = true; + Main.buffNoSave[Type] = true; + } + + public override void Update(Player player, ref int buffIndex) + { + CalamityPlayer modPlayer = player.Calamity(); + if (player.ownedProjectileCounts[ModContent.ProjectileType()] > 0) + { + modPlayer.FrostbatBool = true; + } + + if (!modPlayer.FrostbatBool) + { + player.DelBuff(buffIndex); + buffIndex--; + } + else + { + player.buffTime[buffIndex] = 18000; + } + } + } +} diff --git a/Buffs/Summon/FrostbatBuff.png b/Buffs/Summon/FrostbatBuff.png new file mode 100644 index 0000000000..c67a052b2f Binary files /dev/null and b/Buffs/Summon/FrostbatBuff.png differ diff --git a/CalPlayer/CalamityPlayer.cs b/CalPlayer/CalamityPlayer.cs index 8d353a7079..29d1911da8 100644 --- a/CalPlayer/CalamityPlayer.cs +++ b/CalPlayer/CalamityPlayer.cs @@ -823,6 +823,7 @@ namespace CalamityMod.CalPlayer public bool astralStarRain = false; public int astralStarRainCooldown = 0; public int AbaddonCooldown = 0; + public int VoidCooldown = 0; public int ursaSergeantCooldown = 0; public int AlchFlaskCooldown = 0; public bool plagueReaper = false; @@ -1132,6 +1133,8 @@ namespace CalamityMod.CalPlayer public bool KalandraMirror = false; public bool StellarTorus = false; public bool LiliesOfFinalityBool = false; + public bool FlarebatBool = false; + public bool FrostbatBool = false; #endregion #region Biome @@ -1608,7 +1611,6 @@ namespace CalamityMod.CalPlayer noLifeRegen = false; // Shields. Has to intentionally be above resetting accessories and armor or the shields would clear instantly - drawnAnyShieldThisFrame = false; if (!roverDrive) RoverDriveShieldDurability = 0; if (!lunicCorpsSet) @@ -2227,6 +2229,8 @@ namespace CalamityMod.CalPlayer KalandraMirror = false; StellarTorus = false; LiliesOfFinalityBool = false; + FlarebatBool = false; + FrostbatBool = false; /* Spawn blockers from back when they used to work by being favorited and not a toggleable item noStupidNaturalARSpawns = false @@ -2391,6 +2395,7 @@ namespace CalamityMod.CalPlayer gSabatonTempJumpSpeed = 0; astralStarRainCooldown = 0; AbaddonCooldown = 0; + VoidCooldown = 0; ursaSergeantCooldown = 0; AlchFlaskCooldown = 0; ascendantInsigniaCooldown = 0; diff --git a/CalPlayer/CalamityPlayerDrawParameters.cs b/CalPlayer/CalamityPlayerDrawParameters.cs new file mode 100644 index 0000000000..a270396544 --- /dev/null +++ b/CalPlayer/CalamityPlayerDrawParameters.cs @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Items.Accessories; +using CalamityMod.Items.Armor.LunicCorps; +using CalamityMod.Packets; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.CalPlayer +{ + // This should be a thing for reason: + // - Draw call invoke faster than Player.Update on different thread + // - Therefore draw call often gets default value for shield charge or such, results in flickering bug + // So we calculate those value as same rate as Player.Update and does NOT reset between updates + public struct CalamityPlayerDrawingParameters + { + // Profaned Shield (Profaned Soul Artifact / Profaned Soul Crystal) + public float ProfanedShieldCharge; + public Color ProfanedShieldColor; + + // The Sponge Shield + public float SpongeShieldCharge; + + // RoverDrive Shield + public float RoverShieldCharge; + + // Lunic Corps + public float LunicShieldCharge; + + public static bool operator ==(CalamityPlayerDrawingParameters left, CalamityPlayerDrawingParameters right) + { + if (left.RoverShieldCharge != right.RoverShieldCharge) return false; + if (left.LunicShieldCharge != right.LunicShieldCharge) return false; + if (left.ProfanedShieldCharge != right.ProfanedShieldCharge) return false; + if (left.ProfanedShieldColor != right.ProfanedShieldColor) return false; + if (left.SpongeShieldCharge != right.SpongeShieldCharge) return false; + return true; + } + + public static bool operator !=(CalamityPlayerDrawingParameters left, CalamityPlayerDrawingParameters right) + { + return !(left == right); + } + + public override readonly bool Equals(object obj) => base.Equals(obj); + public override readonly int GetHashCode() => base.GetHashCode(); + } + + public partial class CalamityPlayer : ModPlayer + { + public CalamityPlayerDrawingParameters drawingParameters; + private CalamityPlayerDrawingParameters drawingParameters_LastNetSyncValue; + private int drawingParameters_NetSyncCountdown = 0; + + private void UpdateDrawingParameters() + { + // Non-Owner should receive update via network! + if (Player.whoAmI == Main.myPlayer) + { + UpdateDrawParameter_RoverDriveShield(); + UpdateDrawParameter_LunicCorps(); + UpdateDrawParameter_ProfanedShield(); + UpdateDrawParameter_TheSponge(); + + if (Main.netMode == NetmodeID.MultiplayerClient) + { + if (drawingParameters_NetSyncCountdown > 0) + { + drawingParameters_NetSyncCountdown--; + return; + } + + if (drawingParameters != drawingParameters_LastNetSyncValue) + { + drawingParameters_NetSyncCountdown = 8; + drawingParameters_LastNetSyncValue = drawingParameters; + SyncPlayerDrawParameterPacket.Send(this); + } + } + } + } + + #region RoverDrive Shield + private void UpdateDrawParameter_RoverDriveShield() + { + bool isVanityOnly = roverDriveShieldVisible && !roverDrive; + bool shieldExists = isVanityOnly || RoverDriveShieldDurability > 0; + if (roverDriveShieldVisible && shieldExists) + { + float visualShieldStrength = 1f; + if (!isVanityOnly) + { + float shieldDurabilityRatio = RoverDriveShieldDurability / (float)RoverDrive.ShieldDurabilityMax; + visualShieldStrength = MathF.Pow(shieldDurabilityRatio, 0.5f); + } + + drawingParameters.RoverShieldCharge = visualShieldStrength; + } + else + { + drawingParameters.RoverShieldCharge = -1.0f; + } + } + #endregion + + #region LunicCorps Shield + private void UpdateDrawParameter_LunicCorps() + { + if (LunicCorpsShieldDurability > 0) + { + float shieldDurabilityRatio = LunicCorpsShieldDurability / (float)LunicCorpsHelmet.ShieldDurabilityMax; + float visualShieldStrength = MathF.Pow(shieldDurabilityRatio, 0.5f); + + drawingParameters.LunicShieldCharge = visualShieldStrength; + } + else + { + drawingParameters.LunicShieldCharge = -1.0f; + } + } + #endregion + + #region Profaned Shield (Profaned Soul Artifact / Profaned Soul Crystal) + private void UpdateDrawParameter_ProfanedShield() + { + bool isVanityOnly = pSoulShieldVisible && !pSoulArtifact; + bool shouldNotDraw = andromedaState >= AndromedaPlayerState.LargeRobot; //I am not dealing with drawing that :taxevasion: + bool shieldExists = isVanityOnly || pSoulShieldDurability > 0; + if (pSoulShieldVisible && !shouldNotDraw && shieldExists) + { + ProfanedSoulCrystal.DetermineTransformationEligibility(Player); + var psState = (int)ProfanedSoulCrystal.GetPscStateFor(Player, profanedCrystalAnim >= 0); + var psc = profanedCrystalBuffs || (profanedCrystalAnim >= 0 && psState >= (int)ProfanedSoulCrystal.ProfanedSoulCrystalState.Buffs); + + float visualShieldStrength = 1f; + if (!isVanityOnly) + { + float max = psc ? ProfanedSoulCrystal.ShieldDurabilityMax : ProfanedSoulArtifact.ShieldDurabilityMax; + float shieldDurabilityRatio = pSoulShieldDurability / max; + visualShieldStrength = MathF.Pow(shieldDurabilityRatio, 0.5f); + } + + Color shieldColor = ProfanedSoulCrystal.GetColorForPsc(psState, Main.dayTime); + if (psState >= (int)(ProfanedSoulCrystal.ProfanedSoulCrystalState.Buffs)) + { + bool tester = ProfanedSoulCrystal.contributorNames.Any(name => name.Equals(Player.name)); + shieldColor = tester ? CalamityUtils.ColorSwap(new Color(255, 166, 0), new Color(25, 250, 25) * 0.8f, 6f) : + ProfanedSoulCrystal.GetLerpedColorForPsc(this); + } + drawingParameters.ProfanedShieldColor = shieldColor; + drawingParameters.ProfanedShieldCharge = visualShieldStrength; + } + else + { + drawingParameters.ProfanedShieldCharge = -1.0f; + drawingParameters.ProfanedShieldColor = Color.White; + } + } + #endregion + + #region Sponge Shield + private void UpdateDrawParameter_TheSponge() + { + bool isVanityOnly = spongeShieldVisible && !sponge; + bool shieldExists = isVanityOnly || SpongeShieldDurability > 0; + if (spongeShieldVisible && shieldExists) + { + float visualShieldStrength = 1f; + if (!isVanityOnly) + { + float shieldDurabilityRatio = SpongeShieldDurability / (float)TheSponge.ShieldDurabilityMax; + visualShieldStrength = MathF.Pow(shieldDurabilityRatio, 0.5f); + } + + drawingParameters.SpongeShieldCharge = visualShieldStrength; + } + else + { + drawingParameters.SpongeShieldCharge = -1.0f; + } + } + #endregion + } +} diff --git a/CalPlayer/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index fd9012ac99..c473ec355b 100644 --- a/CalPlayer/CalamityPlayerMiscEffects.cs +++ b/CalPlayer/CalamityPlayerMiscEffects.cs @@ -45,6 +45,7 @@ using CalamityMod.NPCs.NormalNPCs; using CalamityMod.NPCs.Other; using CalamityMod.NPCs.PlagueEnemies; using CalamityMod.NPCs.TownNPCs; +using CalamityMod.Packets; using CalamityMod.Particles; using CalamityMod.Projectiles.Boss; using CalamityMod.Projectiles.Magic; @@ -154,6 +155,9 @@ namespace CalamityMod.CalPlayer // Handle Androomba's Right Click function AndroombaRightClick(); + // Drawing parameters + UpdateDrawingParameters(); + // Update all particle sets for items. // This must be done here instead of in the item logic because these sets are not properly instanced // in the global classes. Attempting to update them there will cause multiple updates to one set for multiple items. @@ -246,7 +250,7 @@ namespace CalamityMod.CalPlayer Player.velocity.X *= 1.2f; int damage = Player.ApplyArmorAccDamageBonusesTo(Player.GetBestClassDamage().ApplyTo(75)); - Projectile.NewProjectile(Player.GetSource_FromThis(), Player.Center + Player.velocity * 1.5f, Vector2.Zero, ModContent.ProjectileType(), damage, 20f, Player.whoAmI); + Projectile.NewProjectile(Player.GetSource_FromThis(), Player.Center + Player.velocity * 1.5f, Vector2.Zero, ModContent.ProjectileType(), damage, 0f, Player.whoAmI); HasIncreasedDashFirstFrame = true; } float numberOfDusts = 10f; @@ -1477,6 +1481,8 @@ namespace CalamityMod.CalPlayer astralStarRainCooldown--; if (AbaddonCooldown > 0) AbaddonCooldown--; + if (VoidCooldown > 0) + VoidCooldown--; if (ursaSergeantCooldown > 0) ursaSergeantCooldown--; if (AlchFlaskCooldown > 0) @@ -4452,11 +4458,7 @@ namespace CalamityMod.CalPlayer } else { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SyncAndroombaSolution); - netMessage.Write(npc.whoAmI); - netMessage.Write(soltype); - netMessage.Send(); + SyncAndroombaSolutionPacket.Send(npc.ModNPC(), soltype); } if (npc.ai[0] == 0f) { @@ -4466,11 +4468,7 @@ namespace CalamityMod.CalPlayer } else { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SyncAndroombaAI); - netMessage.Write(npc.whoAmI); - netMessage.Write(1); - netMessage.Send(); + SyncAndroombaAIPacket.Send(npc.ModNPC(), phase: 1); } } if (Main.netMode == NetmodeID.Server) diff --git a/CalPlayer/CalamityPlayerNetcode.cs b/CalPlayer/CalamityPlayerNetcode.cs index 16df37c22c..0981541481 100644 --- a/CalPlayer/CalamityPlayerNetcode.cs +++ b/CalPlayer/CalamityPlayerNetcode.cs @@ -1,6 +1,8 @@ using System.Collections.Generic; using System.IO; +using System.Linq; using CalamityMod.Cooldowns; +using CalamityMod.Packets; using Terraria; using Terraria.ID; using Terraria.ModLoader; @@ -12,219 +14,50 @@ namespace CalamityMod.CalPlayer #region Standard Syncs internal const int GlobalSyncPacketTimer = 15; - internal void StandardSync() - { - SyncRage(false); - SyncAdrenaline(false); - SyncDefenseDamage(false); - } - private void EnterWorldSync() { StandardSync(); } + internal void StandardSync() + { + RageSyncPacket.Send(this); + AdrenalineSyncPacket.Send(this); + DefenseDamageSyncPacket.Send(this); + } + internal void MouseControlsSync() { - SyncRightClick(false); - SyncMousePosition(false); + RightClickSyncPacket.Send(this); + MousePositionSyncPacket.Send(this); } #endregion #region Creating and Sending Packets - public void SyncDefenseDamage(bool server) - { - ModPacket packet = Mod.GetPacket(256); - packet.Write((byte)CalamityModMessageType.DefenseDamageSync); - packet.Write(Player.whoAmI); - packet.Write(totalDefenseDamage); - packet.Write(defenseDamageRecoveryFrames); - packet.Write(totalDefenseDamageRecoveryFrames); - packet.Write(defenseDamageDelayFrames); - Player.SendPacket(packet, server); - } - - public void SyncRage(bool server) - { - ModPacket packet = Mod.GetPacket(256); - packet.Write((byte)CalamityModMessageType.RageSync); - packet.Write(Player.whoAmI); - packet.Write(rage); - packet.Write(rageCombatFrames); - Player.SendPacket(packet, server); - } - - public void SyncAdrenaline(bool server) - { - ModPacket packet = Mod.GetPacket(256); - packet.Write((byte)CalamityModMessageType.AdrenalineSync); - packet.Write(Player.whoAmI); - packet.Write(adrenaline); - Player.SendPacket(packet, server); - } - public void SyncCooldownAddition(bool server, CooldownInstance cd) { if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(256); - packet.Write((byte)CalamityModMessageType.CooldownAddition); - packet.Write(Player.whoAmI); - cd.Write(packet); - Player.SendPacket(packet, server); + + CooldownAdditionPacket.Send(this, cd); } public void SyncCooldownRemoval(bool server, IList cooldownIDs) { if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(256); - packet.Write((byte)CalamityModMessageType.CooldownRemoval); - packet.Write(Player.whoAmI); - packet.Write(cooldownIDs.Count); - foreach (string id in cooldownIDs) - packet.Write(CooldownRegistry.Get(id).netID); - Player.SendPacket(packet, server); + + CooldownRemovalPacket.Send(this, cooldownIDs.Select(id => CooldownRegistry.Get(id).netID).ToArray()); } public void SyncCooldownDictionary(bool server) { if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(1024); - packet.Write((byte)CalamityModMessageType.SyncCooldownDictionary); - packet.Write(Player.whoAmI); - packet.Write(cooldowns.Count); - foreach (CooldownInstance cd in cooldowns.Values) - cd.Write(packet); - Player.SendPacket(packet, server); + + SyncCooldownDictionaryPacket.Send(this); } - public void SyncRightClick(bool server) - { - ModPacket packet = Mod.GetPacket(256); - packet.Write((byte)CalamityModMessageType.RightClickSync); - packet.Write(Player.whoAmI); - packet.Write(mouseRight); - Player.SendPacket(packet, server); - } - public void SyncMousePosition(bool server) - { - ModPacket packet = Mod.GetPacket(256); - packet.Write((byte)CalamityModMessageType.MousePositionSync); - packet.Write(Player.whoAmI); - packet.WriteVector2(mouseWorld); - Player.SendPacket(packet, server); - } - - #endregion - - #region Reading and Handling Packets - internal void HandleRage(BinaryReader reader) - { - rage = reader.ReadSingle(); - rageCombatFrames = reader.ReadInt32(); - if (Main.netMode == NetmodeID.Server) - SyncRage(true); - } - - internal void HandleAdrenaline(BinaryReader reader) - { - adrenaline = reader.ReadSingle(); - if (Main.netMode == NetmodeID.Server) - SyncAdrenaline(true); - } - - internal void HandleCooldownAddition(BinaryReader reader) - { - // The player ID and message ID are already read. The only remaining data is the serialization of the cooldown instance. - CooldownInstance instance = new CooldownInstance(reader); - - // Actually assign this freshly synced cooldown to the appropriate player. - string id = CooldownRegistry.registry[instance.netID].ID; - cooldowns[id] = instance; - } - - internal void HandleCooldownRemoval(BinaryReader reader) - { - int count = reader.ReadInt32(); - for (int i = 0; i < count; ++i) - { - ushort netID = reader.ReadUInt16(); - cooldowns.Remove(CooldownRegistry.registry[netID].ID); - } - } - - internal void HandleCooldownDictionary(BinaryReader reader) - { - int count = reader.ReadInt32(); - if (count <= 0) - return; - - // Cooldown dictionary packets are just a span of serialized cooldown instances. So each one can be read exactly as with a single cooldown. - Dictionary syncedCooldowns = new Dictionary(count); - for (int i = 0; i < count; ++i) - { - CooldownInstance instance = new CooldownInstance(reader); - syncedCooldowns[instance.netID] = instance; - } - - HashSet localIDs = new HashSet(); - foreach (CooldownInstance localInstance in cooldowns.Values) - localIDs.Add(localInstance.netID); - - HashSet syncedIDs = new HashSet(); - foreach (ushort syncedID in syncedCooldowns.Keys) - syncedIDs.Add(syncedID); - - HashSet combinedIDSet = new HashSet(); - combinedIDSet.UnionWith(localIDs); - combinedIDSet.UnionWith(syncedIDs); - - foreach (ushort netID in combinedIDSet) - { - bool existsLocally = localIDs.Contains(netID); - bool existsRemotely = syncedIDs.Contains(netID); - string id = CooldownRegistry.registry[netID].ID; - - // Exists locally but not remotely = cull -- destroy the local copy. - if (existsLocally && !existsRemotely) - cooldowns.Remove(id); - // Exists remotely but not locally = add -- insert into the dictionary. - else if (existsRemotely && !existsLocally) - cooldowns[id] = syncedCooldowns[netID]; - // Exists in both places = update -- update timing fields but don't replace the instance. - else if (existsLocally && existsRemotely) - { - CooldownInstance localInstance = cooldowns[id]; - localInstance.duration = syncedCooldowns[netID].duration; - localInstance.timeLeft = syncedCooldowns[netID].timeLeft; - } - } - } - - internal void HandleDefenseDamage(BinaryReader reader) - { - totalDefenseDamage = reader.ReadInt32(); - defenseDamageRecoveryFrames = reader.ReadInt32(); - totalDefenseDamageRecoveryFrames = reader.ReadInt32(); - defenseDamageDelayFrames = reader.ReadInt32(); - if (Main.netMode == NetmodeID.Server) - SyncDefenseDamage(true); - } - - internal void HandleRightClick(BinaryReader reader) - { - mouseRight = reader.ReadBoolean(); - if (Main.netMode == NetmodeID.Server) - SyncRightClick(true); - } - internal void HandleMousePosition(BinaryReader reader) - { - mouseWorld = reader.ReadVector2(); - if (Main.netMode == NetmodeID.Server) - SyncMousePosition(true); - } #endregion } } diff --git a/CalPlayer/CalamityPlayerOnHit.cs b/CalPlayer/CalamityPlayerOnHit.cs index 67923f05c9..c48bcca191 100644 --- a/CalPlayer/CalamityPlayerOnHit.cs +++ b/CalPlayer/CalamityPlayerOnHit.cs @@ -673,18 +673,25 @@ namespace CalamityMod.CalPlayer } } - if (abaddon && crit && AbaddonCooldown <= 0) + if (abaddon && crit && AbaddonCooldown <= 0 && !voidOfExtinction) { AbaddonCooldown = 15; - int AbaddonExploDamage = CalamityUtils.DamageSoftCap(proj.damage * 0.03f, 25); + int AbaddonExploDamage = CalamityUtils.DamageSoftCap(proj.damage * 0.3f, 50); Projectile.NewProjectile(source, position, Vector2.Zero, ProjectileType(), AbaddonExploDamage, 0f, Player.whoAmI); } + if (voidOfExtinction && crit && VoidCooldown <= 0) + { + VoidCooldown = 15; + int VoidExploDamage = CalamityUtils.DamageSoftCap(proj.damage * 0.3f, 70); + Projectile.NewProjectile(source, position, Vector2.Zero, ProjectileType(), VoidExploDamage, 0f, Player.whoAmI); + } + if (ursaSergeant && ursaSergeantCooldown <= 0) { ursaSergeantCooldown = 300; - int ursaSlashdamage = (int)Player.GetBestClassDamage().ApplyTo(333); + int ursaSlashdamage = (int)Player.GetBestClassDamage().ApplyTo(200); ursaSlashdamage = Player.ApplyArmorAccDamageBonusesTo(ursaSlashdamage); Projectile.NewProjectile(source, position, Vector2.Zero, ProjectileType(), ursaSlashdamage, 0f, Player.whoAmI); diff --git a/CalamityConfig.cs b/CalamityConfig.cs index 6d19bd6f3e..00b5eed916 100644 --- a/CalamityConfig.cs +++ b/CalamityConfig.cs @@ -25,6 +25,18 @@ namespace CalamityMod ParticleLimit = (int)Utils.Clamp(ParticleLimit, MinParticleLimit, MaxParticleLimit); } + #region Multi-Threading Settings + [Header("Multithreading")] + + [BackgroundColor(192, 54, 64, 192)] + [SliderColor(224, 165, 56, 128)] + [Range(0f, 2f)] + [DefaultValue(0f)] + [Increment(1f)] + [DrawTicks] + public float SunkenSeaMultiThreading { get; set; } + #endregion + #region Graphics Changes [Header("Graphics")] @@ -54,6 +66,13 @@ namespace CalamityMod [BackgroundColor(192, 54, 64, 192)] [DefaultValue(true)] public bool StealthInvisibility { get; set; } + + [BackgroundColor(192, 54, 64, 192)] + [SliderColor(224, 165, 56, 128)] + [DefaultValue(1.0f)] + [Range(0.0f, 1.0f)] + public float EnergyShieldOpacity { get; set; } + #endregion #region UI Changes diff --git a/CalamityLists.cs b/CalamityLists.cs index 6c88ca808b..ef301ee5e9 100644 --- a/CalamityLists.cs +++ b/CalamityLists.cs @@ -1508,7 +1508,7 @@ namespace CalamityMod ItemType(), ItemType(), ItemType(), - ItemType(), + ItemType(), ItemType(), ItemType(), ItemType(), diff --git a/CalamityNetcode.cs b/CalamityNetcode.cs index bb9191606f..1888f34647 100644 --- a/CalamityNetcode.cs +++ b/CalamityNetcode.cs @@ -1,5 +1,10 @@ using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices.JavaScript; using CalamityMod.Events; using CalamityMod.Items; using CalamityMod.Items.Potions.Alcohol; @@ -7,6 +12,7 @@ using CalamityMod.NPCs; using CalamityMod.NPCs.NormalNPCs; using CalamityMod.NPCs.Providence; using CalamityMod.NPCs.TownNPCs; +using CalamityMod.Packets; using CalamityMod.Systems; using CalamityMod.TileEntities; using CalamityMod.World; @@ -15,387 +21,108 @@ using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; +using Terraria.ModLoader.Core; namespace CalamityMod { - public class CalamityNetcode + public class CalamityNetcode : ModSystem { + private static CalamityPacket[] _PacketRegistry; + + public override void OnModLoad() + { + _PacketRegistry = new CalamityPacket[256]; // This should allow to use 0-255 range (full byte range) + + var types = ModLoader.Mods.SelectMany(mod => AssemblyManager.GetLoadableTypes(mod.Code)); + foreach (var type in types) + { + try + { + if (type.IsAbstract || !type.IsSubclassOf(typeof(CalamityPacket))) + continue; + + if (Activator.CreateInstance(type) is not CalamityPacket packetHandler) + continue; + + var msgType = packetHandler.MessageType; + var existingHandler = _PacketRegistry[msgType]; + if (existingHandler != null) + { + CalamityMod.Instance.Logger.Error($"Packet instance has already registered by other type!" + + $" [Failed On: '{type.FullName}'" + + $" Current Owner: '{existingHandler.GetType().FullName}'," + + $" msgTypeToRegister: '{msgType}']"); + continue; + } + + _PacketRegistry[packetHandler.MessageType] = packetHandler; + + var instanceProperty = type.GetProperty("Instance", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic); + if (instanceProperty is not null) + { + if (instanceProperty.PropertyType.IsAssignableFrom(type)) + { + instanceProperty.SetValue(null, packetHandler); + packetHandler._Prop_Static_Instance = instanceProperty; // We saving this for Unload Steps + } + else + { + CalamityMod.Instance.Logger.Error($"Packet instance's 'Instance' property is not asssignable with given type!" + + $" [Failed On: '{type.FullName}']"); + } + } + + // We should not print error message if "Instance" property is missing + // Addons still can assign them with OnLoaded overload, and it's up to their implementation + // Still, Calamity's Standard is having "Instance" property for every packet types + + packetHandler.OnLoaded(); + } + catch (Exception e) + { + CalamityMod.Instance.Logger.Error($"Exception was thrown while loading for Packets! {e}"); + continue; + } + } + } + + public override void OnModUnload() + { + if (_PacketRegistry is not null) + { + foreach (var packetHandler in _PacketRegistry) + { + if (packetHandler is null) + continue; + + packetHandler.OnUnloaded(); + packetHandler._Prop_Static_Instance?.SetValue(null, null); + packetHandler._Prop_Static_Instance = null; + } + + _PacketRegistry = null; + } + } + public static void HandlePacket(Mod mod, BinaryReader reader, int whoAmI) { try { CalamityModMessageType msgType = (CalamityModMessageType)reader.ReadByte(); - switch (msgType) + var packetHandler = _PacketRegistry[(byte)msgType]; + if (packetHandler is not null) + { + packetHandler.HandlePacket(in reader, whoAmI); + } + else { - // - // Player mechanic syncs - // - - case CalamityModMessageType.DefenseDamageSync: - Main.player[reader.ReadInt32()].Calamity().HandleDefenseDamage(reader); - break; - case CalamityModMessageType.RageSync: - Main.player[reader.ReadInt32()].Calamity().HandleRage(reader); - break; - case CalamityModMessageType.AdrenalineSync: - Main.player[reader.ReadInt32()].Calamity().HandleAdrenaline(reader); - break; - case CalamityModMessageType.CooldownAddition: - Main.player[reader.ReadInt32()].Calamity().HandleCooldownAddition(reader); - break; - case CalamityModMessageType.CooldownRemoval: - Main.player[reader.ReadInt32()].Calamity().HandleCooldownRemoval(reader); - break; - case CalamityModMessageType.SyncCooldownDictionary: - Main.player[reader.ReadInt32()].Calamity().HandleCooldownDictionary(reader); - break; - - // - // Syncs for specific bosses or entities - // - - case CalamityModMessageType.SyncDestroyerLaserColor: - byte npcIdx3 = reader.ReadByte(); - int laserColor = reader.ReadInt32(); - - // If the NPC in question isn't valid, don't do anything. - NPC npc3 = Main.npc[npcIdx3]; - if (!npc3.active) - break; - - CalamityGlobalNPC cgn3 = npc3.Calamity(); - cgn3.destroyerLaserColor = laserColor; - break; - - // This code has been edited to fail gracefully when trying to provide data for an invalid NPC. - case CalamityModMessageType.SyncCalamityNPCAIArray: - // Read the entire packet regardless of anything - byte npcIdx = reader.ReadByte(); - float ai0 = reader.ReadSingle(); - float ai1 = reader.ReadSingle(); - float ai2 = reader.ReadSingle(); - float ai3 = reader.ReadSingle(); - - // If the NPC in question isn't valid, don't do anything. - NPC npc = Main.npc[npcIdx]; - if (!npc.active) - break; - - CalamityGlobalNPC cgn = npc.Calamity(); - cgn.newAI[0] = ai0; - cgn.newAI[1] = ai1; - cgn.newAI[2] = ai2; - cgn.newAI[3] = ai3; - break; - - case CalamityModMessageType.SyncVanillaNPCLocalAIArray: - // Read the entire packet regardless of anything - byte npcIdx2 = reader.ReadByte(); - float localAI0 = reader.ReadSingle(); - float localAI1 = reader.ReadSingle(); - float localAI2 = reader.ReadSingle(); - float localAI3 = reader.ReadSingle(); - - // If the NPC in question isn't valid, don't do anything. - NPC npc2 = Main.npc[npcIdx2]; - if (!npc2.active) - break; - - npc2.localAI[0] = localAI0; - npc2.localAI[1] = localAI1; - npc2.localAI[2] = localAI2; - npc2.localAI[3] = localAI3; - break; - - case CalamityModMessageType.SpawnSuperDummy: - int x = reader.ReadInt32(); - int y = reader.ReadInt32(); - // Not strictly necessary, but helps prevent unnecessary packetstorm in MP - if (Main.netMode != NetmodeID.MultiplayerClient) - NPC.NewNPC(new EntitySource_WorldEvent(), x, y, ModContent.NPCType()); - break; - - case CalamityModMessageType.DeleteAllSuperDummies: - if (Main.netMode != NetmodeID.MultiplayerClient) - SuperDummy.DeleteDummies(); - break; - - case CalamityModMessageType.SyncAndroombaSolution: - int index = reader.ReadInt32(); - int solType = reader.ReadInt32(); - if (Main.netMode != NetmodeID.MultiplayerClient) - AndroombaFriendly.SwapSolution(index, solType); - break; - - case CalamityModMessageType.SyncAndroombaAI: - { - int idx = reader.ReadInt32(); - int phase = reader.ReadInt32(); - if (Main.netMode != NetmodeID.MultiplayerClient) - AndroombaFriendly.ChangeAI(idx, phase); - } - break; - - case CalamityModMessageType.SyncSlabCrabAI: - { - int idx = reader.ReadInt32(); - int phase = reader.ReadInt32(); - if (Main.netMode != NetmodeID.MultiplayerClient) - AndroombaFriendly.ChangeAI(idx, phase); - } - break; - - case CalamityModMessageType.PlaceAltCritter: - { - int placerplayer = reader.ReadInt32(); - int posX = reader.ReadInt32(); - int posY = reader.ReadInt32(); - int type = reader.ReadInt32(); - int itemType = reader.ReadInt32(); - float color = reader.ReadInt32(); - if (Main.netMode != NetmodeID.MultiplayerClient) - { - int n = NPC.NewNPC(Main.player[placerplayer].GetSource_ReleaseEntity(), posX, posY, type, ai1: color); - Main.npc[n].catchItem = itemType; - Main.npc[n].releaseOwner = (short)placerplayer; - } - } - break; - - case CalamityModMessageType.ServersideSpawnOldDuke: - byte playerIndex2 = reader.ReadByte(); - CalamityUtils.SpawnOldDuke(playerIndex2); - break; - - case CalamityModMessageType.ProvidenceDyeConditionSync: - byte npcIndex3 = reader.ReadByte(); - (Main.npc[npcIndex3].ModNPC as Providence).hasTakenDaytimeDamage = reader.ReadBoolean(); - break; - - case CalamityModMessageType.PSCChallengeSync: - byte npcIndex4 = reader.ReadByte(); - (Main.npc[npcIndex4].ModNPC as Providence).challenge = reader.ReadBoolean(); - break; - - // - // General syncs for entities - // - - case CalamityModMessageType.SpawnNPCOnPlayer: - x = reader.ReadInt32(); - y = reader.ReadInt32(); - int npcType = reader.ReadInt32(); - int player = reader.ReadInt32(); - Vector2 spawnPosition = reader.ReadVector2(); - if (Main.netMode != NetmodeID.MultiplayerClient) - { - int spawnedNPC = NPC.NewNPC(new EntitySource_WorldEvent(), x, y, npcType, Target: player); - NetMessage.SendData(MessageID.SyncNPC, -1, player, null, spawnedNPC); - } - break; - - case CalamityModMessageType.SyncNPCMotionDataToServer: - int npcIndex = reader.ReadInt32(); - Vector2 center = reader.ReadVector2(); - Vector2 velocity = reader.ReadVector2(); - if (Main.netMode != NetmodeID.MultiplayerClient) - { - Main.npc[npcIndex].Center = center; - Main.npc[npcIndex].velocity = velocity; - NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, npcIndex); - } - break; - - case CalamityModMessageType.SyncNPCPosAndRotOnly: - npcIndex = reader.ReadByte(); - Vector2 position = reader.ReadVector2(); - float rotation = (float)reader.ReadHalf(); //rotation unit is radian (-π/2 ≤ rotation ≤ π/2) so Half precision should works - - if (npcIndex >= Main.maxNPCs) - break; - - npc = Main.npc[npcIndex]; - npc.position = position; - npc.rotation = rotation; - - if (Main.dedServ) - { - ModPacket packet = CalamityMod.Instance.GetPacket(); - packet.Write((byte)CalamityModMessageType.SyncNPCPosAndRotOnly); - packet.Write((byte)npcIndex); - packet.WriteVector2(position); - packet.Write((Half)rotation); - packet.Send(ignoreClient: whoAmI); - } - break; - - // - // Tile Entities - // - - case CalamityModMessageType.UnlockAbyssChests: - Abyss.UnlockAllAbyssChests(); - break; - case CalamityModMessageType.PowerCellFactory: - TEPowerCellFactory.ReadSyncPacket(mod, reader); - break; - case CalamityModMessageType.ChargingStationStandard: - TEChargingStation.ReadSyncPacket(mod, reader); - break; - case CalamityModMessageType.ChargingStationItemChange: - TEChargingStation.ReadItemSyncPacket(mod, reader); - break; - case CalamityModMessageType.Turret: - TEBaseTurret.ReadSyncPacket(mod, reader); - break; - case CalamityModMessageType.LabHologramProjector: - TELabHologramProjector.ReadSyncPacket(mod, reader); - break; - case CalamityModMessageType.UpdateCodebreakerConstituents: - TECodebreaker.ReadConstituentsUpdateSync(mod, reader); - break; - case CalamityModMessageType.UpdateCodebreakerContainedStuff: - TECodebreaker.ReadContainmentSync(mod, reader); - break; - case CalamityModMessageType.UpdateCodebreakerDecryptCountdown: - TECodebreaker.ReadDecryptCountdownSync(mod, reader); - break; - - // - // Boss Rush - // - - case CalamityModMessageType.BossRushStage: - int stage = reader.ReadInt32(); - BossRushEvent.BossRushStage = stage; - break; - case CalamityModMessageType.BossRushStartTimer: - BossRushEvent.StartTimer = reader.ReadInt32(); - break; - case CalamityModMessageType.BossRushEndTimer: - BossRushEvent.EndTimer = reader.ReadInt32(); - break; - case CalamityModMessageType.EndBossRush: - BossRushEvent.EndEffects(); - break; - case CalamityModMessageType.BRHostileProjKillSync: - int countdown3 = reader.ReadInt32(); - BossRushEvent.HostileProjectileKillCounter = countdown3; - break; - - // - // Acid Rain - // - - case CalamityModMessageType.AcidRainSync: - AcidRainEvent.AcidRainEventIsOngoing = reader.ReadBoolean(); - AcidRainEvent.AccumulatedKillPoints = reader.ReadInt32(); - AcidRainEvent.TimeSinceLastAcidRainKill = reader.ReadInt32(); - break; - case CalamityModMessageType.AcidRainOldDukeSummonSync: - AcidRainEvent.HasTriedToSummonOldDuke = reader.ReadBoolean(); - break; - case CalamityModMessageType.EncounteredOldDukeSync: - AcidRainEvent.OldDukeHasBeenEncountered = reader.ReadBoolean(); - break; - - // - // Draedon Summoner stuff - // - case CalamityModMessageType.CodebreakerSummonStuff: - CalamityWorld.DraedonSummonCountdown = reader.ReadInt32(); - CalamityWorld.DraedonSummonPosition = reader.ReadVector2(); - CalamityWorld.DraedonMechdusa = reader.ReadBoolean(); - break; - case CalamityModMessageType.ExoMechSelection: - CalamityWorld.DraedonMechToSummon = (ExoMech)reader.ReadInt32(); - break; - - // - // Mouse control syncs - // - - case CalamityModMessageType.RightClickSync: - Main.player[reader.ReadInt32()].Calamity().HandleRightClick(reader); - break; - case CalamityModMessageType.MousePositionSync: - Main.player[reader.ReadInt32()].Calamity().HandleMousePosition(reader); - break; - - - // - // Difficulty syncs - // - - case CalamityModMessageType.SyncDifficulties: - int sender = reader.ReadInt32(); - CalamityWorld.revenge = reader.ReadBoolean(); - CalamityWorld.death = reader.ReadBoolean(); - //TODO - Something so that other mods that hijack the difficulty ui can also use the remainder of the reader to have their own shit - - if (Main.netMode == NetmodeID.Server) - SyncCalamityWorldDifficulties(sender); - break; - - // - // Music event syncs - // - case CalamityModMessageType.MusicEventSyncRequest: - MusicEventSystem.FulfillSyncRequest(whoAmI); - break; - - case CalamityModMessageType.MusicEventSyncResponse: - MusicEventSystem.ReceiveSyncResponse(reader); - break; - - // - // Bandit refund syncs - // - case CalamityModMessageType.SomeoneGotScammedByTinkerer: - int scammedOne = reader.ReadByte(); - int stolen = reader.Read7BitEncodedInt(); - - CalamityWorld.MoneyStolenByBandit += stolen; - CalamityWorld.Reforges++; - - // Broadcast back for tragic event - // WorldSync DO sync the MoneyStolenByBandit and Refores variable, But spamming SyncWorld is not a ideal action - if (Main.dedServ) - { - ModPacket packet = CalamityMod.Instance.GetPacket(); - packet.Write((byte)CalamityModMessageType.SomeoneGotScammedByTinkerer); - packet.Write((byte)scammedOne); - packet.Write7BitEncodedInt(stolen); - packet.Send(ignoreClient: scammedOne); - } - - break; - - case CalamityModMessageType.WantToRefundReforges: - int requester = reader.ReadByte(); - - // Only Server should handle this action! - if (!Main.dedServ) - break; - - int banditIdx = NPC.FindFirstNPC(ModContent.NPCType()); - if (banditIdx == -1) - break; - - NPC bandit = Main.npc[banditIdx]; - if (bandit == null || !bandit.active) - break; - - THIEF.DoRefund(bandit); - break; - // // Default case: with no idea how long the packet is, we can't safely read data. // Throw an exception now instead of allowing the network stream to corrupt. // - default: - CalamityMod.Instance.Logger.Error($"Failed to parse Calamity packet: No Calamity packet exists with ID {msgType}."); - throw new Exception("Failed to parse Calamity packet: Invalid Calamity packet ID."); + + CalamityMod.Instance.Logger.Error($"Failed to parse Calamity packet: No Calamity packet exists with ID {msgType}."); + throw new Exception("Failed to parse Calamity packet: Invalid Calamity packet ID."); } } catch (Exception e) @@ -417,19 +144,56 @@ namespace CalamityMod NetMessage.SendData(MessageID.WorldData); } + /// + /// Shorthand Method for SyncNPC + /// + /// This Equals to: + /// + /// if (Main.dedServ and npc != null) + /// NetMessage.SendData(MessageID.SyncNPC, ...) + /// + /// + public static void SyncNPC(NPC npcToSync, int toClient = -1, int ignoreClient = -1) + { + if (!Main.dedServ) + return; + + if (npcToSync is null) + return; + + var npcWhoAmI = npcToSync.whoAmI; + if (npcWhoAmI < 0 || npcWhoAmI >= Main.maxNPCs) + return; + + NetMessage.SendData(MessageID.SyncNPC, toClient, ignoreClient, null, npcWhoAmI); + } + + /// + /// Shorthand Method for SyncNPC + /// + /// This Equals to: + /// + /// if (Main.dedServ and npcWhoAmI in valid range) + /// NetMessage.SendData(MessageID.SyncNPC, ...) + /// + /// + public static void SyncNPC(int npcWhoAmI, int toClient = -1, int ignoreClient = -1) + { + if (!Main.dedServ) + return; + + if (npcWhoAmI < 0 || npcWhoAmI >= Main.maxNPCs) + return; + + NetMessage.SendData(MessageID.SyncNPC, toClient, ignoreClient, null, npcWhoAmI); + } + public static void SyncCalamityWorldDifficulties(int sender) { if (Main.netMode == NetmodeID.SinglePlayer) return; - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SyncDifficulties); - netMessage.Write(sender); - netMessage.Write(CalamityWorld.revenge); - netMessage.Write(CalamityWorld.death); - - //TODO - Let other mods also add their own bits in that sync. Ideally would be done through the difficultystem itself - netMessage.Send(-1, sender); + SyncDifficultiesPacket.Send(); } public static void NewNPC_ClientSide(Vector2 spawnPosition, int npcType, Player player) @@ -439,14 +203,10 @@ namespace CalamityMod NPC.NewNPC(new EntitySource_WorldEvent(), (int)spawnPosition.X, (int)spawnPosition.Y, npcType, Target: player.whoAmI); return; } - - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SpawnNPCOnPlayer); - netMessage.Write((int)spawnPosition.X); - netMessage.Write((int)spawnPosition.Y); - netMessage.Write(npcType); - netMessage.Write(player.whoAmI); - netMessage.Send(); + else if (Main.netMode == NetmodeID.MultiplayerClient) + { + SpawnNPCOnPlayerPacket.Send(player, (int)spawnPosition.X, (int)spawnPosition.Y, npcType); + } } } @@ -470,12 +230,12 @@ namespace CalamityMod SyncAndroombaAI, SyncSlabCrabAI, PlaceAltCritter, - ServersideSpawnOldDuke, ProvidenceDyeConditionSync, // TODO -- this packetstorms if you hit Provi with spam weapons. It should ONLY send a packet if the status changes. PSCChallengeSync, // TODO -- once you've failed the PSC challenge this packetstorms // General things for entities SpawnNPCOnPlayer, + SpawnBossOnPosition, SyncNPCMotionDataToServer, SyncNPCPosAndRotOnly, @@ -518,7 +278,12 @@ namespace CalamityMod MusicEventSyncResponse, // Bandit Reforge Refund - SomeoneGotScammedByTinkerer, - WantToRefundReforges + BanditStolenMoneySync, + WantToRefundReforges, + + // Player Draw Effect Parameters + SyncPlayerDrawParameter, + + Reserved = 150 } } diff --git a/Cooldowns/CooldownInstance.cs b/Cooldowns/CooldownInstance.cs index b21e8f7c15..ca8d98120a 100644 --- a/Cooldowns/CooldownInstance.cs +++ b/Cooldowns/CooldownInstance.cs @@ -60,6 +60,17 @@ namespace CalamityMod.Cooldowns AssignHandler(cd); } + internal CooldownInstance(Player player, ushort netID, int duration, int timeLeft) + { + this.netID = netID; + this.player = player; + this.duration = duration; + this.timeLeft = timeLeft; + + string id = CooldownRegistry.registry[netID].ID; + AssignHandler(CooldownRegistry.Get(id)); + } + /// /// Creates a cooldown instance from serialized binary data, used in netcode. /// diff --git a/DataStructures/IDyeableShaderRenderer.cs b/DataStructures/IDyeableShaderRenderer.cs index bdae07c587..6c7dd5a03e 100644 --- a/DataStructures/IDyeableShaderRenderer.cs +++ b/DataStructures/IDyeableShaderRenderer.cs @@ -1,4 +1,5 @@ using Microsoft.Xna.Framework.Graphics; +using Terraria; namespace CalamityMod.DataStructures { @@ -14,6 +15,11 @@ namespace CalamityMod.DataStructures public const float SpongeShieldDepth = 4f; #endregion + /// + /// Owner of this Renderer Item + /// + public Player OwnerPlayer { get; set; } + /// /// The draw depth of the renderer. This is used to draw them in descending order; higher values are drawn first. /// diff --git a/Dusts/LightDust.cs b/Dusts/LightDust.cs new file mode 100644 index 0000000000..3ebac6f2cc --- /dev/null +++ b/Dusts/LightDust.cs @@ -0,0 +1,44 @@ +using System; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.Dusts +{ + public class LightDust : ModDust + { + public override void OnSpawn(Dust dust) + { + dust.scale *= Main.rand.NextFloat(0.8f, 1f); + } + + public override bool Update(Dust dust) + { + dust.rotation += MathF.Sign(dust.velocity.X); + dust.velocity *= 0.98f; + dust.scale += 0.02f; + + float light = MathHelper.Clamp(dust.scale * 0.8f, 0f, 1f); + if (!dust.noLightEmittence) + Lighting.AddLight(dust.position, dust.color.ToVector3() * light); + + return true; + } + public override bool PreDraw(Dust dust) + { + Vector2 dustCenter = dust.position + new Vector2(0.25f, 0.25f); + Texture2D rechargeTexture2 = ModContent.Request("CalamityMod/ExtraTextures/BasicCircle").Value; + if (!dust.noLight) + { + Texture2D rechargeTexture = ModContent.Request("CalamityMod/Particles/BloomCircle").Value; + // Glow Orb + Main.EntitySpriteDraw(rechargeTexture, dustCenter - Main.screenPosition, null, dust.color with { A = 0 } * Utils.GetLerpValue(255, 0, dust.alpha), dust.rotation, rechargeTexture.Size() * 0.5f, dust.scale * 0.1f, SpriteEffects.None, 0); + if (dust.alpha < 1) + Main.EntitySpriteDraw(rechargeTexture, dustCenter - Main.screenPosition, null, dust.color with { A = 0 } * 0.85f * Utils.GetLerpValue(255, 0, dust.alpha), dust.rotation, rechargeTexture.Size() * 0.5f, dust.scale * 0.04f, SpriteEffects.None, 0); + } + Main.EntitySpriteDraw(rechargeTexture2, dustCenter - Main.screenPosition, null, Color.Lerp(dust.color, Color.White, 0.3f) with { A = 0 } * Utils.GetLerpValue(255, 0, dust.alpha), dust.rotation, rechargeTexture2.Size() * 0.5f, dust.scale * 0.075f, SpriteEffects.None, 0); + return false; + } + } +} diff --git a/Projectiles/Melee/GalaxySmasherMini.png b/Dusts/LightDust.png similarity index 65% rename from Projectiles/Melee/GalaxySmasherMini.png rename to Dusts/LightDust.png index 3931f7748e..d4653059dc 100644 Binary files a/Projectiles/Melee/GalaxySmasherMini.png and b/Dusts/LightDust.png differ diff --git a/Events/AcidRainEvent.cs b/Events/AcidRainEvent.cs index a56fbe8ce2..6b8f8e7c5f 100644 --- a/Events/AcidRainEvent.cs +++ b/Events/AcidRainEvent.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using CalamityMod.NPCs.AcidRain; using CalamityMod.NPCs.OldDuke; +using CalamityMod.Packets; using CalamityMod.Projectiles.Boss; using CalamityMod.UI; using CalamityMod.World; @@ -334,32 +335,13 @@ namespace CalamityMod.Events } CalamityNetcode.SyncWorld(); - // You will be tempted to turn this into a single if conditional. - // Don't do this. Doing so has caused so much misery, with various things being read instead - // of the correct thing, like booleans being mixed up in the sending and receiving process. - // In short, leave this alone. + // Flow: 2024/09/06 + // Salute for the one who wrote 3 if conditional block after experiencing immeasurable torment with packet generations if (Main.netMode == NetmodeID.Server) { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.AcidRainSync); - netMessage.Write(AcidRainEventIsOngoing); - netMessage.Write(AccumulatedKillPoints); - netMessage.Write(TimeSinceLastAcidRainKill); - netMessage.Send(); - } - if (Main.netMode == NetmodeID.Server) - { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.AcidRainOldDukeSummonSync); - netMessage.Write(HasTriedToSummonOldDuke); - netMessage.Send(); - } - if (Main.netMode == NetmodeID.Server) - { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.EncounteredOldDukeSync); - netMessage.Write(OldDukeHasBeenEncountered); - netMessage.Send(); + AcidRainSyncPacket.Send(); + AcidRainOldDukeSummonSyncPacket.Send(); + EncounteredOldDukeSyncPacket.Send(); } } } diff --git a/Events/BossRushEvent.cs b/Events/BossRushEvent.cs index c702f6da53..db51f2cc3a 100644 --- a/Events/BossRushEvent.cs +++ b/Events/BossRushEvent.cs @@ -34,6 +34,7 @@ using CalamityMod.NPCs.SlimeGod; using CalamityMod.NPCs.StormWeaver; using CalamityMod.NPCs.SupremeCalamitas; using CalamityMod.NPCs.Yharon; +using CalamityMod.Packets; using CalamityMod.Projectiles.Typeless; using CalamityMod.Skies; using CalamityMod.Systems; @@ -542,10 +543,7 @@ namespace CalamityMod.Events if (Main.netMode == NetmodeID.Server) { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.BRHostileProjKillSync); - netMessage.Write(HostileProjectileKillCounter); - netMessage.Send(); + BRHostileProjKillSyncPacket.Send(); } } } @@ -561,10 +559,7 @@ namespace CalamityMod.Events BossRushStage = 0; if (Main.netMode == NetmodeID.Server) { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.BossRushStage); - netMessage.Write(BossRushStage); - netMessage.Send(); + BossRushStagePacket.Send(); } } return; @@ -633,9 +628,7 @@ namespace CalamityMod.Events } else { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.EndBossRush); - netMessage.Send(); + EndBossRushPacket.Send(); } } @@ -665,18 +658,9 @@ namespace CalamityMod.Events CalamityNetcode.SyncWorld(); if (Main.netMode == NetmodeID.Server) { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.BossRushStage); - netMessage.Write(BossRushStage); - netMessage.Send(); - var netMessage2 = CalamityMod.Instance.GetPacket(); - netMessage2.Write((byte)CalamityModMessageType.BossRushStartTimer); - netMessage2.Write(StartTimer); - netMessage2.Send(); - var netMessage3 = CalamityMod.Instance.GetPacket(); - netMessage3.Write((byte)CalamityModMessageType.BossRushEndTimer); - netMessage3.Write(EndTimer); - netMessage3.Send(); + BossRushStagePacket.Send(); + BossRushStartTimerPacket.Send(); + BossRushEndTimerPacket.Send(); } } @@ -763,14 +747,8 @@ namespace CalamityMod.Events // Sync the stage and progress of Boss Rush whenever a relevant boss dies. if (Main.netMode == NetmodeID.Server) { - var netMessage = mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.BossRushStage); - netMessage.Write(BossRushStage); - netMessage.Send(); - var netMessage2 = mod.GetPacket(); - netMessage2.Write((byte)CalamityModMessageType.BRHostileProjKillSync); - netMessage2.Write(HostileProjectileKillCounter); - netMessage2.Send(); + BossRushStagePacket.Send(); + BRHostileProjKillSyncPacket.Send(); } BossRushSky.CurrentInterest = 0.85f; @@ -801,10 +779,7 @@ namespace CalamityMod.Events if (Main.netMode != NetmodeID.Server) return; - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.BossRushStartTimer); - netMessage.Write(StartTimer); - netMessage.Send(); + BossRushStartTimerPacket.Send(); } public static void SyncEndTimer(int time) @@ -813,10 +788,7 @@ namespace CalamityMod.Events if (Main.netMode != NetmodeID.Server) return; - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.BossRushEndTimer); - netMessage.Write(EndTimer); - netMessage.Send(); + BossRushEndTimerPacket.Send(); } #endregion } diff --git a/Gores/KylieGore1.png b/Gores/KylieGore1.png new file mode 100644 index 0000000000..d6066fc50a Binary files /dev/null and b/Gores/KylieGore1.png differ diff --git a/Gores/KylieGore2.png b/Gores/KylieGore2.png new file mode 100644 index 0000000000..a32dd8c3fe Binary files /dev/null and b/Gores/KylieGore2.png differ diff --git a/Graphics/Metaballs/GalaxyMetaball.cs b/Graphics/Metaballs/GalaxyMetaball.cs new file mode 100644 index 0000000000..1a82913348 --- /dev/null +++ b/Graphics/Metaballs/GalaxyMetaball.cs @@ -0,0 +1,103 @@ +using System.Collections.Generic; +using System.Linq; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using ReLogic.Content; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Graphics.Metaballs +{ + public class GalaxyMetaball : Metaball + { + public class CosmicParticle + { + public float Size; + + public Vector2 Velocity; + + public Vector2 Center; + + public CosmicParticle(Vector2 center, Vector2 velocity, float size) + { + Center = center; + Velocity = velocity; + Size = size; + } + + public void Update() + { + Center += Velocity; + Velocity *= 0.96f; + Size *= 0.91f; + } + } + + public static Asset LayerAsset + { + get; + private set; + } + + public static List Particles + { + get; + private set; + } = new(); + + public override bool AnythingToDraw => Particles.Any(); + + public override IEnumerable Layers + { + get + { + yield return LayerAsset.Value; + } + } + + public override MetaballDrawLayer DrawContext => MetaballDrawLayer.BeforeNPCs; + + public override Color EdgeColor => Color.Lerp(Color.DarkBlue, Color.Black, 0.75f); + + public override void Load() + { + if (Main.netMode == NetmodeID.Server) + return; + + // Load the layer asset wrapper. + LayerAsset = ModContent.Request($"CalamityMod/Graphics/Metaballs/StreamGougeLayer", AssetRequestMode.ImmediateLoad); + } + + public override void Update() + { + // Update all particle instances. + // Once sufficiently small, they vanish. + for (int i = 0; i < Particles.Count; i++) + Particles[i].Update(); + Particles.RemoveAll(p => p.Size <= 2f); + } + + public static void SpawnParticle(Vector2 position, Vector2 velocity, float size) => + Particles.Add(new(position, velocity, size)); + + // Make the texture scroll. + public override Vector2 CalculateManualOffsetForLayer(int layerIndex) + { + return Vector2.UnitX * Main.GlobalTimeWrappedHourly * 0.037f; + } + + public override void DrawInstances() + { + Texture2D tex = ModContent.Request("CalamityMod/ExtraTextures/BasicCircle").Value; + + foreach (CosmicParticle particle in Particles) + { + Vector2 drawPosition = particle.Center - Main.screenPosition; + Vector2 origin = tex.Size() * 0.5f; + Vector2 scale = Vector2.One * particle.Size / tex.Size(); + Main.spriteBatch.Draw(tex, drawPosition, null, Color.White, 0f, origin, scale, SpriteEffects.None, 0f); + } + } + } +} diff --git a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs index d0570d372e..045e039a55 100644 --- a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs +++ b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs @@ -44,8 +44,13 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers public override void Unload() { + Targets?.Clear(); Targets = null; + + Dyes?.Clear(); Dyes = null; + + RenderersToDrawThisFrame?.Clear(); RenderersToDrawThisFrame = null; } #endregion @@ -61,7 +66,8 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers if (armorItem.ModItem is not IDyeableShaderRenderer drawer) return; - // Store the dye in the slot. + // Store the dye and player in the slot. + drawer.OwnerPlayer = self; Dyes[drawer] = GameShaders.Armor.GetShaderFromItemId(dyeItem.type); } @@ -149,7 +155,10 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers #region Updates/Drawing // Clear the list at the beginning of each update, to ensure its only populated by correct ones. - public override void PreUpdate() => RenderersToDrawThisFrame?.Clear(); + public override void PreUpdate() + { + RenderersToDrawThisFrame?.Clear(); + } public override void DrawToTarget(SpriteBatch spriteBatch) { @@ -157,7 +166,7 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers return; // Leave if nothing to draw. - if (!RenderersToDrawThisFrame.Any()) + if (RenderersToDrawThisFrame.Count <= 0) return; // Sort the list by draw order. @@ -180,7 +189,7 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers return; // Leave if nothing to draw. - if (!RenderersToDrawThisFrame.Any()) + if (RenderersToDrawThisFrame.Count <= 0) return; foreach (var renderer in RenderersToDrawThisFrame) diff --git a/Graphics/Renderers/RendererManager.cs b/Graphics/Renderers/RendererManager.cs index e7e5967a5f..64289533ea 100644 --- a/Graphics/Renderers/RendererManager.cs +++ b/Graphics/Renderers/RendererManager.cs @@ -86,29 +86,22 @@ namespace CalamityMod.Graphics.Renderers if (Main.gameMenu || Main.dedServ) return; + // Reset drawn frame check + foreach (var player in Main.ActivePlayers) + { + player.Calamity().drawnAnyShieldThisFrame = false; + } + foreach (var renderer in Renderers) { if (!renderer.ShouldDraw) continue; - try + Main.spriteBatch.SafeAction(() => { renderer.MainTarget.SwapTo(Color.Transparent); - Main.spriteBatch.TryBegin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix); renderer.DrawToTarget(Main.spriteBatch); - } - catch (Exception e) - { - Main.QueueMainThreadAction(() => - { - CalamityMod.Instance.Logger.Error($"Exception Found on RenderDetour: {e}"); - }); - } - finally - { - // Always end the Batch! - Main.spriteBatch.TryEnd(); - } + }); } Main.instance.GraphicsDevice.SetRenderTarget(null); diff --git a/ILEditing/ILChangesLoading.cs b/ILEditing/ILChangesLoading.cs index 5e05f4eabd..2cf0c90e80 100644 --- a/ILEditing/ILChangesLoading.cs +++ b/ILEditing/ILChangesLoading.cs @@ -193,6 +193,7 @@ namespace CalamityMod.ILEditing IL_Main.UpdateTime_StartNight += BloodMoonsRequire200MaxLife; IL_WorldGen.AttemptFossilShattering += PreventFossilShattering; On_Player.GetPickaxeDamage += RemoveHellforgePickaxeRequirement; + IL_Player.Update += PreventUFODismountInWater; On_Player.GetAnglerReward += ImproveAnglerRewards; On_Player.ItemCheck_CheckCanUse += RemoveCelestialSigilUseLock; diff --git a/ILEditing/NetProtectionILChanges.cs b/ILEditing/NetProtectionILChanges.cs new file mode 100644 index 0000000000..6ba19e43a5 --- /dev/null +++ b/ILEditing/NetProtectionILChanges.cs @@ -0,0 +1,122 @@ +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria.Localization; +using Terraria.ModLoader; + +namespace CalamityMod.ILEditing +{ + // These IL edits are contained in their own ModSystem instead of the main ILChanges system for the following reasons: + // - Easily filter out only the NetProtectionILChanges from the call stack, and not other IL edits + // - No interference with the existing ILChanges system, which contains gameplay changes and is already packed + // + // Original comment by Flowaria: + // + // We want to set this as Separate ILChages type for reasons: + // - To easily filter ILChanges callstack from StackTrace + // - To make no impact on ILChanges type which is already clustered + public sealed class NetProtectionILChanges : ModSystem + { + private static string[] _ModNames; + + public override void OnModLoad() + { + _ModNames = ModLoader.Mods.Select(mod => mod.Name).ToArray(); + + On_NPC.NewNPC += NewNPCRule; + On_NetMessage.SendData += SendDataRule; + } + + public override void OnModUnload() + { + _ModNames = null; + } + + private int NewNPCRule(On_NPC.orig_NewNPC orig, IEntitySource source, int X, int Y, int Type, int Start, float ai0, float ai1, float ai2, float ai3, int Target) + { + if (Main.netMode == NetmodeID.MultiplayerClient) + { + CalamityMod.Instance.Logger.Error($"NETCODE SAFETY VIOLATION DETECTED: {nameof(NPC.NewNPC)} was called from a Multiplayer Client"); + CalamityMod.Instance.Logger.Error(GetSimplifiedStackTrace()); + return Main.maxNPCs; + } + + return orig(source, X, Y, Type, Start, ai0, ai1, ai2, ai3, Target); + } + + private static void SendDataRule(On_NetMessage.orig_SendData orig, int msgType, int remoteClient, int ignoreClient, NetworkText text, int number, float number2, float number3, float number4, int number5, int number6, int number7) + { + // Sending SyncNPC as Client will cause Server to not read their bytes + // So we simply stop that from happening + if (msgType == MessageID.SyncNPC && Main.netMode == NetmodeID.MultiplayerClient) + { + CalamityMod.Instance.Logger.Error($"NETCODE SAFETY VIOLATION DETECTED: {nameof(NetMessage.SendData)} ({nameof(MessageID.SyncNPC)}) was called from a Multiplayer Client"); + CalamityMod.Instance.Logger.Error(GetSimplifiedStackTrace()); + return; + } + + orig(msgType, remoteClient, ignoreClient, text, number, number2, number3, number4, number5, number6, number7); + } + + #region Simplified StackTrace Util Method + + private static bool ContainsAnyModName(string str) + { + return _ModNames?.Any(str.Contains) ?? false; + } + + [MethodImpl(MethodImplOptions.NoInlining)] // Force No Inlining to easily filter current stack (skipFrames: 1) + private static string GetSimplifiedStackTrace() + { + var stringBuilder = new StringBuilder(); + try + { + stringBuilder.AppendLine("STACKTRACE:"); + + var stacktrace = new StackTrace(skipFrames: 1); + var frames = stacktrace.GetFrames(); + var didPrintSomethingUselessLastTime = false; + var didEverPrintSomethingUseful = false; + foreach (var frame in frames) + { + var method = frame.GetMethod(); + var methodName = method?.ToString() ?? "UNKNOWN_METHOD"; + var typeName = method?.DeclaringType?.FullName ?? "UNKNOWN_TYPE"; + + // Logging Rule: + // - It should contains ANY ModName in their FullName + // - It should NOT contains NetProtectionILChanges in their FullName (Calamity Codebase Exclusive) + if (ContainsAnyModName(typeName) && !typeName.Contains(nameof(NetProtectionILChanges))) + { + didPrintSomethingUselessLastTime = false; + didEverPrintSomethingUseful = true; + stringBuilder.AppendFormat(" at {0}::{1}", typeName, methodName); + stringBuilder.AppendLine(); + } + else if (!didPrintSomethingUselessLastTime && didEverPrintSomethingUseful) + { + stringBuilder.AppendLine(" ..."); + didPrintSomethingUselessLastTime = true; + } + } + + stringBuilder.AppendLine("END OF STACKTRACE"); + return stringBuilder.ToString(); + } + catch + { + return ""; + } + finally + { + stringBuilder?.Clear(); + } + } + + #endregion + } +} diff --git a/ILEditing/VanillaStupidityFixingILChanges.cs b/ILEditing/VanillaStupidityFixingILChanges.cs index 88e296f0c8..510c5dd121 100644 --- a/ILEditing/VanillaStupidityFixingILChanges.cs +++ b/ILEditing/VanillaStupidityFixingILChanges.cs @@ -276,6 +276,37 @@ namespace CalamityMod.ILEditing // TODO -- Finish this #endregion Fix Chlorophyte Crystal Attacking Where it Shouldn't + #region Prevent UFO Mount from Dismounting in Water + private static void PreventUFODismountInWater(ILContext il) + { + // Prevent the Cosmic Car Key's UFO mount from dismounting when the player is in water. + var cursor = new ILCursor(il); + + // Unfortunately, the code responsible for this is 4000 lines into Player.Update, meaning that reaching it is far from simple. + // The following method was the easiest way I could find to reach it: + // Move to the third call of Mount.Dismount. + for (int i = 0; i < 3; i++) + { + if (!cursor.TryGotoNext(MoveType.Before, i => i.MatchCallvirt("Dismount"))) + { + LogFailure("Prevent UFO Dismounting in Water", "Could not reach the Dismount instruction."); + return; + } + } + // Move the cursor backwards to place it right after the instruction which loads Main.myPlayer onto the stack. + if (!cursor.TryGotoPrev(MoveType.After, i => i.MatchLdsfld
("myPlayer"))) + { + LogFailure("Prevent UFO Dismounting in Water", "Could not locate the myPlayer check."); + return; + } + + // Remove the instruction and replace it with the integer limit. The next instruction checks if this value is equal to Player.whoAmI. + // Player.whoAmI will never be the integer limit, so the check will always fail and the UFO will not dismount. + cursor.EmitPop(); + cursor.Emit(OpCodes.Ldc_I4, int.MaxValue); + } + #endregion Prevent UFO Mount from Dismounting in Water + #region Color Blighted Gel private static void ColorBlightedGel(Terraria.GameContent.ItemDropRules.On_CommonCode.orig_ModifyItemDropFromNPC orig, NPC npc, int itemIndex) { diff --git a/Items/Accessories/ProfanedSoulArtifact.cs b/Items/Accessories/ProfanedSoulArtifact.cs index 1d866fbb10..8eeee886e0 100644 --- a/Items/Accessories/ProfanedSoulArtifact.cs +++ b/Items/Accessories/ProfanedSoulArtifact.cs @@ -31,28 +31,28 @@ namespace CalamityMod.Items.Accessories public static int ShieldDurabilityMax = 25; // Interface stuff. + public Player OwnerPlayer { get; set; } public float RenderDepth => IDyeableShaderRenderer.ProfanedSoulShieldDepth; public bool ShouldDrawDyeableShader { get { - bool result = false; - foreach (Player player in Main.ActivePlayers) - { - if (player.outOfRange || player.dead) - continue; + if (CalamityClientConfig.Instance.EnergyShieldOpacity <= 0.0f) + return false; - CalamityPlayer modPlayer = player.Calamity(); + var player = OwnerPlayer; + if (player is null) + return false; - // Do not render the shield if its visibility is off (or it does not exist) - bool isVanityOnly = modPlayer.pSoulShieldVisible && !modPlayer.pSoulArtifact; - bool shouldNotDraw = modPlayer.andromedaState >= AndromedaPlayerState.LargeRobot; //I am not dealing with drawing that :taxevasion: - bool shieldExists = isVanityOnly || modPlayer.pSoulShieldDurability > 0; - bool shouldntDraw = !modPlayer.pSoulShieldVisible || modPlayer.drawnAnyShieldThisFrame || shouldNotDraw || !shieldExists; - result |= !shouldntDraw; - } - return result; + if (player.outOfRange || player.dead) + return false; + + CalamityPlayer modPlayer = player.Calamity(); + if (modPlayer.drawingParameters.ProfanedShieldCharge <= 0.0f) + return false; + + return true; } } @@ -62,7 +62,7 @@ namespace CalamityMod.Items.Accessories ItemID.Sets.AnimatesAsSoul[Type] = true; } - public void DrawDyeableShader(SpriteBatch spriteBatch) => DrawProfanedSoulShields(); + public void DrawDyeableShader(SpriteBatch spriteBatch) => DrawProfanedSoulShields(OwnerPlayer); public override void SetDefaults() { @@ -109,121 +109,82 @@ namespace CalamityMod.Items.Accessories // Complex drawcode which draws Profaned Soul shields on ALL players who have it available. Supposedly. // This is applied as IL (On hook) which draws right before Inferno Ring. - internal static void DrawProfanedSoulShields() + internal static void DrawProfanedSoulShields(Player player) { - // TODO -- Control flow analysis indicates that this hook is not stable (as it was copied from Rover Drive). - // Profaned Soul shields will be drawn for each player with the Profaned Soul artifact/crystal, yes. - // But there is no guarantee that the shields will be in the right condition for each player. - // Visibility is not net synced, for example. - bool alreadyDrawnShieldForPlayer = false; + if (player is null) + return; - foreach (Player player in Main.ActivePlayers) + if (player.outOfRange || player.dead) + return; + + CalamityPlayer modPlayer = player.Calamity(); + + if (modPlayer.drawnAnyShieldThisFrame) + return; + + if (modPlayer.drawingParameters.ProfanedShieldCharge <= 0.0f) + return; + + // Scale the shield is drawn at. + // The "i" parameter is to make different player's shields not be perfectly synced. + int i = player.whoAmI; + float scale = 0.15f + 0.03f * (0.5f + 0.5f * MathF.Sin(Main.GlobalTimeWrappedHourly * 0.5f + i * 0.2f)); + float visualShieldStrength = modPlayer.drawingParameters.ProfanedShieldCharge; + Color shieldColor = modPlayer.drawingParameters.ProfanedShieldColor; + + // The scale used for the noise overlay polygons also grows and shrinks + // This is intentionally out of sync with the shield, and intentionally desynced per player + // Don't put this anywhere less than 0.25f or higher than 1f. The higher it is, the denser / more zoomed out the noise overlay is. + float noiseScale = MathHelper.Lerp(0.4f, 0.8f, MathF.Sin(Main.GlobalTimeWrappedHourly * 0.3f) * 0.5f + 0.5f); + + // Define shader parameters + Effect shieldEffect = Filters.Scene["CalamityMod:RoverDriveShield"].GetShader().Shader; + shieldEffect.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly * 0.058f); // Scrolling speed of polygonal overlay + shieldEffect.Parameters["blowUpPower"].SetValue(2.8f); + shieldEffect.Parameters["blowUpSize"].SetValue(0.4f); + shieldEffect.Parameters["noiseScale"].SetValue(noiseScale); + + // Shield opacity multiplier slightly changes, this is independent of current shield strength + float baseShieldOpacity = 0.9f + 0.1f * MathF.Sin(Main.GlobalTimeWrappedHourly * 1.95f); + float minShieldStrengthOpacityMultiplier = 0.5f; + float finalShieldOpacity = baseShieldOpacity * MathHelper.Lerp(minShieldStrengthOpacityMultiplier, 1f, visualShieldStrength); + finalShieldOpacity *= CalamityClientConfig.Instance.EnergyShieldOpacity; + + shieldEffect.Parameters["shieldOpacity"].SetValue(finalShieldOpacity); + shieldEffect.Parameters["shieldEdgeBlendStrenght"].SetValue(4f); + + Color primaryEdgeColor = new Color(230, 199, 102) * 0.8f; + Color secondaryEdgeColor = new Color(249, 231, 217) * 0.8f; + Color edgeColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly * 0.2f, primaryEdgeColor, secondaryEdgeColor); + + // Define shader parameters for shield color + shieldEffect.Parameters["shieldColor"].SetValue(shieldColor.ToVector3()); + shieldEffect.Parameters["shieldEdgeColor"].SetValue(edgeColor.ToVector3()); + + var matrix = Main.GameViewMatrix.TransformationMatrix; + Main.spriteBatch.SafeBegin(SpriteSortMode.Immediate, BatchSetting.Additive, shieldEffect, matrix, () => { - if (player.outOfRange || player.dead) - continue; + // Fetch shield heat overlay texture (this is the neutrons fed to the shader) + HeatTex ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Neurons2"); + Vector2 pos = player.MountedCenter + player.gfxOffY * Vector2.UnitY - Main.screenPosition; + Texture2D tex = HeatTex.Value; + Main.spriteBatch.Draw(tex, pos, null, Color.White, 0, tex.Size() / 2f, scale, 0, 0); - CalamityPlayer modPlayer = player.Calamity(); - - // Do not render the shield if its visibility is off (or it does not exist) - bool isVanityOnly = modPlayer.pSoulShieldVisible && !modPlayer.pSoulArtifact; - bool shouldNotDraw = modPlayer.andromedaState >= AndromedaPlayerState.LargeRobot; //I am not dealing with drawing that :taxevasion: - bool shieldExists = isVanityOnly || modPlayer.pSoulShieldDurability > 0; - if (!modPlayer.pSoulShieldVisible || modPlayer.drawnAnyShieldThisFrame || shouldNotDraw || !shieldExists) - continue; - - // Scale the shield is drawn at. - // The "i" parameter is to make different player's shields not be perfectly synced. - int i = player.whoAmI; - float scale = 0.15f + 0.03f * (0.5f + 0.5f * (float)Math.Sin(Main.GlobalTimeWrappedHourly * 0.5f + i * 0.2f)); - - if (!alreadyDrawnShieldForPlayer) - { - CalamityPlayer localModPlayer = Main.LocalPlayer.Calamity(); - DetermineTransformationEligibility(localModPlayer.Player); - var psState = (int)GetPscStateFor(localModPlayer.Player, localModPlayer.profanedCrystalAnim >= 0); - var psc = localModPlayer.profanedCrystalBuffs || (localModPlayer.profanedCrystalAnim >= 0 && psState >= (int)ProfanedSoulCrystalState.Buffs); - - scale += ((ProfanedSoulCrystalState)psState) == ProfanedSoulCrystalState.Empowered ? 0.05f : psc ? 0.025f : 0f; - if (localModPlayer.profanedCrystalAnim >= 0) - scale = MathHelper.Lerp(0f, scale, ((float)maxPscAnimTime - (float)localModPlayer.profanedCrystalAnim) / (float)maxPscAnimTime); //i don't like casting this many times, i'm not a fucking wizard - - float visualShieldStrength = 1f; - if (!isVanityOnly) - { - float max = psc ? ProfanedSoulCrystal.ShieldDurabilityMax : ShieldDurabilityMax; - float shieldDurabilityRatio = localModPlayer.pSoulShieldDurability / max; - visualShieldStrength = MathF.Pow(shieldDurabilityRatio, 0.5f); - } - - // The scale used for the noise overlay polygons also grows and shrinks - // This is intentionally out of sync with the shield, and intentionally desynced per player - // Don't put this anywhere less than 0.25f or higher than 1f. The higher it is, the denser / more zoomed out the noise overlay is. - float noiseScale = MathHelper.Lerp(0.4f, 0.8f, (float)Math.Sin(Main.GlobalTimeWrappedHourly * 0.3f) * 0.5f + 0.5f); - - // Define shader parameters - Effect shieldEffect = Filters.Scene["CalamityMod:RoverDriveShield"].GetShader().Shader; - shieldEffect.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly * 0.058f); // Scrolling speed of polygonal overlay - shieldEffect.Parameters["blowUpPower"].SetValue(2.8f); - shieldEffect.Parameters["blowUpSize"].SetValue(0.4f); - shieldEffect.Parameters["noiseScale"].SetValue(noiseScale); - - // Shield opacity multiplier slightly changes, this is independent of current shield strength - float baseShieldOpacity = 0.9f + 0.1f * MathF.Sin(Main.GlobalTimeWrappedHourly * 1.95f); - float minShieldStrengthOpacityMultiplier = 0.5f; - float finalShieldOpacity = baseShieldOpacity * MathHelper.Lerp(minShieldStrengthOpacityMultiplier, 1f, visualShieldStrength); - shieldEffect.Parameters["shieldOpacity"].SetValue(finalShieldOpacity); - shieldEffect.Parameters["shieldEdgeBlendStrenght"].SetValue(4f); - - // Profaned Soul shields are not team specific - Color shieldColor = GetColorForPsc(psState, Main.dayTime); - if (psState >= (int)(ProfanedSoulCrystalState.Buffs)) - { - bool tester = contributorNames.Any(name => name.Equals(localModPlayer.Player.name)); - shieldColor = tester ? CalamityUtils.ColorSwap(new Color(255, 166, 0), new Color(25, 250, 25) * 0.8f, 6f) : - GetLerpedColorForPsc(modPlayer); - } - - Color primaryEdgeColor = new Color(230, 199, 102) * 0.8f; - Color secondaryEdgeColor = new Color(249, 231, 217) * 0.8f; - Color edgeColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly * 0.2f, primaryEdgeColor, secondaryEdgeColor); - - // Define shader parameters for shield color - shieldEffect.Parameters["shieldColor"].SetValue(shieldColor.ToVector3()); - shieldEffect.Parameters["shieldEdgeColor"].SetValue(edgeColor.ToVector3()); - - // GOD I LOVE END BEGIN CAN THIS GAME PLEASE BE SWALLOWED BY THE FIRES OF HELL THANKS - // yes I copy pasted that comment, I hate end begin that much - // I also copy pasted that comment, this time for consistency :hdfailure: - Main.spriteBatch.End(); - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, shieldEffect, Main.GameViewMatrix.TransformationMatrix); - // Fetch shield heat overlay texture (this is the neutrons fed to the shader) - HeatTex ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Neurons2"); - Vector2 pos = player.MountedCenter + player.gfxOffY * Vector2.UnitY - Main.screenPosition; - Texture2D tex = HeatTex.Value; - Main.spriteBatch.Draw(tex, pos, null, Color.White, 0, tex.Size() / 2f, scale, 0, 0); - - //The border circle MUST be drawn after otherwise it becomes visually fucked. - float shieldScale = scale * 1.75f; - Texture2D shieldTexture = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleOpenCircle").Value; - Rectangle shieldFrame = shieldTexture.Frame(); - Vector2 origin = shieldFrame.Size() * 0.5f; - Main.spriteBatch.End(); - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix); - Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, shieldColor * 0.5f, player.fullRotation, origin, shieldScale, SpriteEffects.None, 0f); - Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, secondaryEdgeColor * 0.5f, player.fullRotation, origin, shieldScale * 0.95f, SpriteEffects.None, 0f); - Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, shieldColor * 0.5f, player.fullRotation, origin, shieldScale, SpriteEffects.None, 0f); - Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, secondaryEdgeColor * 0.5f, player.fullRotation, origin, shieldScale * 0.95f, SpriteEffects.None, 0f); - } - - alreadyDrawnShieldForPlayer = true; - modPlayer.drawnAnyShieldThisFrame = true; - } - - if (alreadyDrawnShieldForPlayer) - { + //The border circle MUST be drawn after otherwise it becomes visually fucked. + float shieldScale = scale * 1.75f; + Texture2D shieldTexture = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleOpenCircle").Value; + Rectangle shieldFrame = shieldTexture.Frame(); + Vector2 origin = shieldFrame.Size() * 0.5f; Main.spriteBatch.End(); - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.Transform); - } + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix); + Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, shieldColor * 0.5f, player.fullRotation, origin, shieldScale, SpriteEffects.None, 0f); + Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, secondaryEdgeColor * 0.5f, player.fullRotation, origin, shieldScale * 0.95f, SpriteEffects.None, 0f); + Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, shieldColor * 0.5f, player.fullRotation, origin, shieldScale, SpriteEffects.None, 0f); + Main.spriteBatch.Draw(shieldTexture, pos, shieldFrame, secondaryEdgeColor * 0.5f, player.fullRotation, origin, shieldScale * 0.95f, SpriteEffects.None, 0f); + Main.spriteBatch.End(); + }); + modPlayer.drawnAnyShieldThisFrame = true; } } } diff --git a/Items/Accessories/ProfanedSoulCrystal.cs b/Items/Accessories/ProfanedSoulCrystal.cs index 42be000b5f..aa06ee325a 100644 --- a/Items/Accessories/ProfanedSoulCrystal.cs +++ b/Items/Accessories/ProfanedSoulCrystal.cs @@ -33,30 +33,29 @@ namespace CalamityMod.Items.Accessories public const int maxPscAnimTime = 120; // Interface stuff. + public Player OwnerPlayer { get; set; } public float RenderDepth => IDyeableShaderRenderer.ProfanedSoulShieldDepth; - public bool ShaderIsDyeable => false; public bool ShouldDrawDyeableShader { get { - bool result = false; - foreach (Player player in Main.ActivePlayers) - { - if (player.outOfRange || player.dead) - continue; + if (CalamityClientConfig.Instance.EnergyShieldOpacity <= 0.0f) + return false; - CalamityPlayer modPlayer = player.Calamity(); + var player = OwnerPlayer; + if (player is null) + return false; - // Do not render the shield if its visibility is off (or it does not exist) - bool isVanityOnly = modPlayer.pSoulShieldVisible && !modPlayer.pSoulArtifact; - bool shouldNotDraw = modPlayer.andromedaState >= AndromedaPlayerState.LargeRobot; //I am not dealing with drawing that :taxevasion: - bool shieldExists = isVanityOnly || modPlayer.pSoulShieldDurability > 0; - bool shouldntDraw = !modPlayer.pSoulShieldVisible || modPlayer.drawnAnyShieldThisFrame || shouldNotDraw || !shieldExists; - result |= !shouldntDraw; - } - return result; + if (player.outOfRange || player.dead) + return false; + + CalamityPlayer modPlayer = player.Calamity(); + if (modPlayer.drawingParameters.ProfanedShieldCharge <= 0.0f) + return false; + + return true; } } @@ -68,7 +67,7 @@ namespace CalamityMod.Items.Accessories Empowered //psc but no other minions, healer guardian functionality, inherits all other functionality (except vanity) and goes even further beyond, any remaining attack changes are here } - public void DrawDyeableShader(SpriteBatch spriteBatch) => ProfanedSoulArtifact.DrawProfanedSoulShields(); + public void DrawDyeableShader(SpriteBatch spriteBatch) => ProfanedSoulArtifact.DrawProfanedSoulShields(OwnerPlayer); internal static ProfanedSoulCrystalState GetPscStateFor(Player player, bool ignoreNoBuffs = false) { diff --git a/Items/Accessories/RoverDrive.cs b/Items/Accessories/RoverDrive.cs index f2669eef54..8a255d86bc 100644 --- a/Items/Accessories/RoverDrive.cs +++ b/Items/Accessories/RoverDrive.cs @@ -31,27 +31,28 @@ namespace CalamityMod.Items.Accessories public static int ShieldDefenseBoost = 10; // Interface stuff. + public Player OwnerPlayer { get; set; } public float RenderDepth => IDyeableShaderRenderer.RoverDriveDepth; public bool ShouldDrawDyeableShader { get { - bool result = false; - foreach (Player player in Main.ActivePlayers) - { - if (player.outOfRange || player.dead) - continue; + if (CalamityClientConfig.Instance.EnergyShieldOpacity <= 0.0f) + return false; - CalamityPlayer modPlayer = player.Calamity(); + var player = OwnerPlayer; + if (player is null) + return false; - // Do not render the shield if its visibility is off (or it does not exist) - bool isVanityOnly = modPlayer.roverDriveShieldVisible && !modPlayer.roverDrive; - bool shieldExists = isVanityOnly || modPlayer.RoverDriveShieldDurability > 0; - bool shouldntDraw = (!modPlayer.roverDriveShieldVisible || modPlayer.drawnAnyShieldThisFrame || !shieldExists); - result |= !shouldntDraw; - } - return result; + if (player.outOfRange || player.dead) + return false; + + CalamityPlayer modPlayer = player.Calamity(); + if (modPlayer.drawingParameters.RoverShieldCharge <= 0.0f) + return false; + + return true; } } @@ -105,88 +106,66 @@ namespace CalamityMod.Items.Accessories // This is applied as IL (On hook) which draws right before Inferno Ring. public void DrawDyeableShader(SpriteBatch spriteBatch) { - // TODO -- Control flow analysis indicates that this hook is not stable. - // Rover Drive shields will be drawn for each player with Rover Drive, yes. - // But there is no guarantee that the shields will be in the right condition for each player. - // Visibility is not net synced, for example. - bool alreadyDrawnShieldForPlayer = false; + var player = OwnerPlayer; + if (player is null) + return; - foreach (Player player in Main.ActivePlayers) + if (player.outOfRange || player.dead) + return; + + CalamityPlayer modPlayer = player.Calamity(); + if (modPlayer.drawnAnyShieldThisFrame) + return; + + if (modPlayer.drawingParameters.RoverShieldCharge <= 0.0f) + return; + + // The shield very gently grows and shrinks + float scale = 0.15f + 0.03f * (0.5f + 0.5f * (float)Math.Sin(Main.GlobalTimeWrappedHourly * 0.5f + player.whoAmI * 0.2f)); + // If in vanity, the shield is always projected as if it's at full strength. + float shieldStrength = modPlayer.drawingParameters.RoverShieldCharge; + + // Noise scale also grows and shrinks, although out of sync with the shield + float noiseScale = MathHelper.Lerp(0.4f, 0.8f, (float)Math.Sin(Main.GlobalTimeWrappedHourly * 0.3f) * 0.5f + 0.5f); + + // Define shader parameters + Effect shieldEffect = Filters.Scene["CalamityMod:RoverDriveShield"].GetShader().Shader; + shieldEffect.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly * 0.24f); + shieldEffect.Parameters["blowUpPower"].SetValue(2.5f); + shieldEffect.Parameters["blowUpSize"].SetValue(0.5f); + shieldEffect.Parameters["noiseScale"].SetValue(noiseScale); + + // Shield opacity multiplier slightly changes, this is independent of current shield strength + float baseShieldOpacity = 0.9f + 0.1f * (float)Math.Sin(Main.GlobalTimeWrappedHourly * 2f); + float finalShieldOpacity = baseShieldOpacity * (0.5f + 0.5f * shieldStrength); + finalShieldOpacity *= CalamityClientConfig.Instance.EnergyShieldOpacity; + + shieldEffect.Parameters["shieldOpacity"].SetValue(finalShieldOpacity); + shieldEffect.Parameters["shieldEdgeBlendStrenght"].SetValue(4f); + + // Get the shield color. + Color blueTint = new Color(51, 102, 255); + Color cyanTint = new Color(71, 202, 255); + Color wulfGreen = new Color(194, 255, 67) * 0.8f; + Color edgeColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly * 0.2f, blueTint, cyanTint, wulfGreen); + Color shieldColor = blueTint; + + + // Define shader parameters for shield color + shieldEffect.Parameters["shieldColor"].SetValue(shieldColor.ToVector3()); + shieldEffect.Parameters["shieldEdgeColor"].SetValue(edgeColor.ToVector3()); + + var matrix = Main.GameViewMatrix.TransformationMatrix; + Main.spriteBatch.SafeBegin(SpriteSortMode.Immediate, BatchSetting.Additive, shieldEffect, matrix, () => { - if (player.outOfRange || player.dead) - continue; - - CalamityPlayer modPlayer = player.Calamity(); - - // Do not render the shield if its visibility is off (or it does not exist) - bool isVanityOnly = modPlayer.roverDriveShieldVisible && !modPlayer.roverDrive; - bool shieldExists = isVanityOnly || modPlayer.RoverDriveShieldDurability > 0; - if (!modPlayer.roverDriveShieldVisible || modPlayer.drawnAnyShieldThisFrame || !shieldExists) - continue; - - // The shield very gently grows and shrinks - float scale = 0.15f + 0.03f * (0.5f + 0.5f * (float)Math.Sin(Main.GlobalTimeWrappedHourly * 0.5f + player.whoAmI * 0.2f)); - - if (!alreadyDrawnShieldForPlayer) - { - // If in vanity, the shield is always projected as if it's at full strength. - float shieldStrength = 1f; - if (!isVanityOnly) - { - // Again, I believe there is no way this looks correct when two players have Rover Drive equipped. - CalamityPlayer localModPlayer = Main.LocalPlayer.Calamity(); - float shieldDurabilityRatio = localModPlayer.RoverDriveShieldDurability / (float)ShieldDurabilityMax; - shieldStrength = MathF.Pow(shieldDurabilityRatio, 0.5f); - } - - // Noise scale also grows and shrinks, although out of sync with the shield - float noiseScale = MathHelper.Lerp(0.4f, 0.8f, (float)Math.Sin(Main.GlobalTimeWrappedHourly * 0.3f) * 0.5f + 0.5f); - - // Define shader parameters - Effect shieldEffect = Filters.Scene["CalamityMod:RoverDriveShield"].GetShader().Shader; - shieldEffect.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly * 0.24f); - shieldEffect.Parameters["blowUpPower"].SetValue(2.5f); - shieldEffect.Parameters["blowUpSize"].SetValue(0.5f); - shieldEffect.Parameters["noiseScale"].SetValue(noiseScale); - - // Shield opacity multiplier slightly changes, this is independent of current shield strength - float baseShieldOpacity = 0.9f + 0.1f * (float)Math.Sin(Main.GlobalTimeWrappedHourly * 2f); - shieldEffect.Parameters["shieldOpacity"].SetValue(baseShieldOpacity * (0.5f + 0.5f * shieldStrength)); - shieldEffect.Parameters["shieldEdgeBlendStrenght"].SetValue(4f); - - // Get the shield color. - Color blueTint = new Color(51, 102, 255); - Color cyanTint = new Color(71, 202, 255); - Color wulfGreen = new Color(194, 255, 67) * 0.8f; - Color edgeColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly * 0.2f, blueTint, cyanTint, wulfGreen); - Color shieldColor = blueTint; - - - // Define shader parameters for shield color - shieldEffect.Parameters["shieldColor"].SetValue(shieldColor.ToVector3()); - shieldEffect.Parameters["shieldEdgeColor"].SetValue(edgeColor.ToVector3()); - - // GOD I LOVE END BEGIN CAN THIS GAME PLEASE BE SWALLOWED BY THE FIRES OF HELL THANKS - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, shieldEffect, Main.GameViewMatrix.TransformationMatrix); - - } - - alreadyDrawnShieldForPlayer = true; - modPlayer.drawnAnyShieldThisFrame = true; - // Fetch shield noise overlay texture (this is the techy overlay fed to the shader) NoiseTex ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/TechyNoise"); Vector2 pos = player.MountedCenter + player.gfxOffY * Vector2.UnitY - Main.screenPosition; Texture2D tex = NoiseTex.Value; spriteBatch.Draw(tex, pos, null, Color.White, 0, tex.Size() / 2f, scale, 0, 0); - } + }); - if (alreadyDrawnShieldForPlayer) - { - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.Transform); - } + modPlayer.drawnAnyShieldThisFrame = true; } } } diff --git a/Items/Accessories/TheSponge.cs b/Items/Accessories/TheSponge.cs index a58d372c0b..d13530730a 100644 --- a/Items/Accessories/TheSponge.cs +++ b/Items/Accessories/TheSponge.cs @@ -40,27 +40,28 @@ namespace CalamityMod.Items.Accessories public static int ShieldActiveDefense = 30; public static float ShieldActiveDamageReduction = 0.1f; + public Player OwnerPlayer { get; set; } public float RenderDepth => IDyeableShaderRenderer.SpongeShieldDepth; public bool ShouldDrawDyeableShader { get { - bool result = false; - foreach (Player player in Main.ActivePlayers) - { - if (player.outOfRange || player.dead) - continue; + if (CalamityClientConfig.Instance.EnergyShieldOpacity <= 0.0f) + return false; - CalamityPlayer modPlayer = player.Calamity(); + var player = OwnerPlayer; + if (player is null) + return false; - // Do not render the shield if its visibility is off (or it does not exist) - bool isVanityOnly = modPlayer.spongeShieldVisible && !modPlayer.sponge; - bool shieldExists = isVanityOnly || modPlayer.SpongeShieldDurability > 0; - bool shouldntDraw = !modPlayer.spongeShieldVisible || modPlayer.drawnAnyShieldThisFrame || !shieldExists; - result |= !shouldntDraw; - } - return result; + if (player.outOfRange || player.dead) + return false; + + CalamityPlayer modPlayer = player.Calamity(); + if (modPlayer.drawingParameters.SpongeShieldCharge <= 0.0f) + return false; + + return true; } } @@ -171,97 +172,73 @@ namespace CalamityMod.Items.Accessories // This is applied as IL (On hook) which draws right before Inferno Ring. public void DrawDyeableShader(SpriteBatch spriteBatch) { - // TODO -- Control flow analysis indicates that this hook is not stable (as it was copied from Rover Drive). - // Sponge shields will be drawn for each player with the Sponge equipped, yes. - // But there is no guarantee that the shields will be in the right condition for each player. - // Visibility is not net synced, for example. - bool alreadyDrawnShieldForPlayer = false; + var player = OwnerPlayer; + if (player is null) + return; - foreach (Player player in Main.ActivePlayers) + if (player.outOfRange || player.dead) + return; + + CalamityPlayer modPlayer = player.Calamity(); + if (modPlayer.drawnAnyShieldThisFrame) + return; + + if (modPlayer.drawingParameters.SpongeShieldCharge <= 0.0f) + return; + + // Scale the shield is drawn at. The Sponge shield gently grows and shrinks; it should be largely imperceptible. + // The "i" parameter is to make different player's shields not be perfectly synced. + int i = player.whoAmI; + float baseScale = 0.155f; + float maxExtraScale = 0.025f; + float extraScalePulseInterpolant = MathF.Pow(4f, MathF.Sin(Main.GlobalTimeWrappedHourly * 0.791f + i) - 1); + float scale = baseScale + maxExtraScale * extraScalePulseInterpolant; + float visualShieldStrength = modPlayer.drawingParameters.SpongeShieldCharge; + + // The scale used for the noise overlay also grows and shrinks + // This is intentionally out of sync with the shield, and intentionally desynced per player + // Don't put this anywhere less than 0.15f or higher than 0.75f. The higher it is, the denser / more zoomed out the noise overlay is. + // Changing this too quickly and/or too much makes the noise grow and shrink visibly, so be careful with that. + float noiseScale = MathHelper.Lerp(0.28f, 0.38f, 0.5f + 0.5f * MathF.Sin(Main.GlobalTimeWrappedHourly * 0.347f + i)); + + // Define shader parameters + Effect shieldEffect = Filters.Scene["CalamityMod:RoverDriveShield"].GetShader().Shader; + shieldEffect.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly * 0.0813f); // Scrolling speed of polygonal overlay + shieldEffect.Parameters["blowUpPower"].SetValue(3f); + shieldEffect.Parameters["blowUpSize"].SetValue(0.56f); + shieldEffect.Parameters["noiseScale"].SetValue(noiseScale); + + // Shield opacity multiplier slightly changes, this is independent of current shield strength + float baseShieldOpacity = 0.9f + 0.1f * MathF.Sin(Main.GlobalTimeWrappedHourly * 1.95f); + float minShieldStrengthOpacityMultiplier = 0.25f; + float finalShieldOpacity = baseShieldOpacity * MathHelper.Lerp(minShieldStrengthOpacityMultiplier, 1f, visualShieldStrength); + finalShieldOpacity *= CalamityClientConfig.Instance.EnergyShieldOpacity; + + shieldEffect.Parameters["shieldOpacity"].SetValue(finalShieldOpacity); + shieldEffect.Parameters["shieldEdgeBlendStrenght"].SetValue(4f); + + Color shieldColor = new Color(24, 156, 204); // #189CCC + Color primaryEdgeColor = shieldColor; + Color secondaryEdgeColor = new Color(34, 224, 227); // #22E0E3 + + // Final shield edge color, which lerps about + Color edgeColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly * 0.2f, primaryEdgeColor, secondaryEdgeColor); + + // Define shader parameters for shield color + shieldEffect.Parameters["shieldColor"].SetValue(shieldColor.ToVector3()); + shieldEffect.Parameters["shieldEdgeColor"].SetValue(edgeColor.ToVector3()); + + var matrix = Main.GameViewMatrix.TransformationMatrix; + Main.spriteBatch.SafeBegin(SpriteSortMode.Immediate, BatchSetting.Additive, shieldEffect, matrix, () => { - if (player.outOfRange || player.dead) - continue; - - CalamityPlayer modPlayer = player.Calamity(); - - // Do not render the shield if its visibility is off (or it does not exist) - bool isVanityOnly = modPlayer.spongeShieldVisible && !modPlayer.sponge; - bool shieldExists = isVanityOnly || modPlayer.SpongeShieldDurability > 0; - if (!modPlayer.spongeShieldVisible || modPlayer.drawnAnyShieldThisFrame || !shieldExists) - continue; - - // Scale the shield is drawn at. The Sponge shield gently grows and shrinks; it should be largely imperceptible. - // The "i" parameter is to make different player's shields not be perfectly synced. - int i = player.whoAmI; - float baseScale = 0.155f; - float maxExtraScale = 0.025f; - float extraScalePulseInterpolant = MathF.Pow(4f, MathF.Sin(Main.GlobalTimeWrappedHourly * 0.791f + i) - 1); - float scale = baseScale + maxExtraScale * extraScalePulseInterpolant; - - if (!alreadyDrawnShieldForPlayer) - { - // If in vanity, the shield is always projected as if it's at full strength. - float visualShieldStrength = 1f; - if (!isVanityOnly) - { - // Again, I believe there is no way this looks correct when two players have The Sponge equipped. - CalamityPlayer localModPlayer = Main.LocalPlayer.Calamity(); - float shieldDurabilityRatio = localModPlayer.SpongeShieldDurability / (float)ShieldDurabilityMax; - visualShieldStrength = MathF.Pow(shieldDurabilityRatio, 0.5f); - } - - // The scale used for the noise overlay also grows and shrinks - // This is intentionally out of sync with the shield, and intentionally desynced per player - // Don't put this anywhere less than 0.15f or higher than 0.75f. The higher it is, the denser / more zoomed out the noise overlay is. - // Changing this too quickly and/or too much makes the noise grow and shrink visibly, so be careful with that. - float noiseScale = MathHelper.Lerp(0.28f, 0.38f, 0.5f + 0.5f * MathF.Sin(Main.GlobalTimeWrappedHourly * 0.347f + i)); - - // Define shader parameters - Effect shieldEffect = Filters.Scene["CalamityMod:RoverDriveShield"].GetShader().Shader; - shieldEffect.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly * 0.0813f); // Scrolling speed of polygonal overlay - shieldEffect.Parameters["blowUpPower"].SetValue(3f); - shieldEffect.Parameters["blowUpSize"].SetValue(0.56f); - shieldEffect.Parameters["noiseScale"].SetValue(noiseScale); - - // Shield opacity multiplier slightly changes, this is independent of current shield strength - float baseShieldOpacity = 0.9f + 0.1f * MathF.Sin(Main.GlobalTimeWrappedHourly * 1.95f); - float minShieldStrengthOpacityMultiplier = 0.25f; - float finalShieldOpacity = baseShieldOpacity * MathHelper.Lerp(minShieldStrengthOpacityMultiplier, 1f, visualShieldStrength); - shieldEffect.Parameters["shieldOpacity"].SetValue(finalShieldOpacity); - shieldEffect.Parameters["shieldEdgeBlendStrenght"].SetValue(4f); - - Color shieldColor = new Color(24, 156, 204); // #189CCC - Color primaryEdgeColor = shieldColor; - Color secondaryEdgeColor = new Color(34, 224, 227); // #22E0E3 - - // Final shield edge color, which lerps about - Color edgeColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly * 0.2f, primaryEdgeColor, secondaryEdgeColor); - - // Define shader parameters for shield color - shieldEffect.Parameters["shieldColor"].SetValue(shieldColor.ToVector3()); - shieldEffect.Parameters["shieldEdgeColor"].SetValue(edgeColor.ToVector3()); - - // GOD I LOVE END BEGIN CAN THIS GAME PLEASE BE SWALLOWED BY THE FIRES OF HELL THANKS - // yes I copy pasted that comment, I hate end begin that much - Main.spriteBatch.End(); - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, shieldEffect, Main.GameViewMatrix.TransformationMatrix); - } - - alreadyDrawnShieldForPlayer = true; - modPlayer.drawnAnyShieldThisFrame = true; - // Fetch shield noise overlay texture (this is the polygons fed to the shader) NoiseTex ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Neurons"); Vector2 pos = player.MountedCenter + player.gfxOffY * Vector2.UnitY - Main.screenPosition; Texture2D tex = NoiseTex.Value; Main.spriteBatch.Draw(tex, pos, null, Color.White, 0, tex.Size() / 2f, scale, 0, 0); - } + }); - if (alreadyDrawnShieldForPlayer) - { - Main.spriteBatch.End(); - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.Transform); - } + modPlayer.drawnAnyShieldThisFrame = true; } } } diff --git a/Items/Armor/LunicCorps/LunicCorpsHelmet.cs b/Items/Armor/LunicCorps/LunicCorpsHelmet.cs index 9333121be6..5391a29066 100644 --- a/Items/Armor/LunicCorps/LunicCorpsHelmet.cs +++ b/Items/Armor/LunicCorps/LunicCorpsHelmet.cs @@ -33,27 +33,29 @@ namespace CalamityMod.Items.Armor.LunicCorps public static int TotalShieldRechargeTime = CalamityUtils.SecondsToFrames(2); // Interface stuff. + public Player OwnerPlayer { get; set; } public float RenderDepth => IDyeableShaderRenderer.HaloShieldDepth; - public bool ShaderIsDyeable => false; public bool ShouldDrawDyeableShader { get { - bool result = false; - foreach (Player player in Main.ActivePlayers) - { - if (player.outOfRange || player.dead) - continue; + if (CalamityClientConfig.Instance.EnergyShieldOpacity <= 0.0f) + return false; - CalamityPlayer modPlayer = player.Calamity(); + var player = OwnerPlayer; + if (player is null) + return false; - // Do not render shield if it does not exist - bool shouldntDraw = modPlayer.LunicCorpsShieldDurability <= 0 || modPlayer.drawnAnyShieldThisFrame; - result |= !shouldntDraw; - } - return result; + if (player.outOfRange || player.dead) + return false; + + CalamityPlayer modPlayer = player.Calamity(); + if (modPlayer.drawingParameters.LunicShieldCharge <= 0.0f) + return false; + + return true; } } @@ -109,88 +111,71 @@ namespace CalamityMod.Items.Armor.LunicCorps // This is applied as IL (On hook) which draws right before Inferno Ring. public void DrawDyeableShader(SpriteBatch spriteBatch) { - // TODO -- Control flow analysis indicates that this hook is not stable (as it was copied from Rover Drive). - // Lunic Corps shields will be drawn for each player with the Lunic Corps armor, yes. - // But there is no guarantee that the shields will be in the right condition for each player. - // Visibility is not net synced, for example. - bool alreadyDrawnShieldForPlayer = false; + var player = OwnerPlayer; + if (player is null) + return; - foreach (Player player in Main.ActivePlayers) + if (player.outOfRange || player.dead) + return; + + CalamityPlayer modPlayer = player.Calamity(); + if (modPlayer.drawnAnyShieldThisFrame) + return; + + if (modPlayer.drawingParameters.LunicShieldCharge <= 0.0f) + return; + + // Scale the shield is drawn at. The Lunic Corps shield sticks very close to the body to mimic Halo and occasionally pulses. + // The "i" parameter is to make different player's shields not be perfectly synced. + int i = player.whoAmI; + float baseScale = 0.11f; + float maxExtraScale = 0.013f; + float extraScalePulseInterpolant = MathF.Pow(12f, MathF.Sin(Main.GlobalTimeWrappedHourly * 1.6f + i) - 1); + float scale = baseScale + maxExtraScale * extraScalePulseInterpolant; + float visualShieldStrength = modPlayer.drawingParameters.LunicShieldCharge; + + // The scale used for the noise overlay polygons also grows and shrinks + // This is intentionally out of sync with the shield, and intentionally desynced per player + // Don't put this anywhere less than 0.25f or higher than 1f. The higher it is, the denser / more zoomed out the noise overlay is. + float noiseScale = MathHelper.Lerp(0.65f, 0.75f, 0.5f + 0.5f * MathF.Sin(Main.GlobalTimeWrappedHourly * 0.87f + i)); + + // Define shader parameters + Effect shieldEffect = Filters.Scene["CalamityMod:RoverDriveShield"].GetShader().Shader; + shieldEffect.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly * 0.058f); // Scrolling speed of polygonal overlay + shieldEffect.Parameters["blowUpPower"].SetValue(2.8f); + shieldEffect.Parameters["blowUpSize"].SetValue(0.4f); + shieldEffect.Parameters["noiseScale"].SetValue(noiseScale); + + // Shield opacity multiplier slightly changes, this is independent of current shield strength + float baseShieldOpacity = 0.9f + 0.1f * MathF.Sin(Main.GlobalTimeWrappedHourly * 1.95f); + float minShieldStrengthOpacityMultiplier = 0.5f; + float finalShieldOpacity = baseShieldOpacity * MathHelper.Lerp(minShieldStrengthOpacityMultiplier, 1f, visualShieldStrength); + finalShieldOpacity *= CalamityClientConfig.Instance.EnergyShieldOpacity; + + shieldEffect.Parameters["shieldOpacity"].SetValue(finalShieldOpacity); + shieldEffect.Parameters["shieldEdgeBlendStrenght"].SetValue(4f); + + // Lunic Corps shields are not team specific + Color shieldColor = new Color(201, 180, 129); + Color primaryEdgeColor = new Color(232, 212, 175); + Color secondaryEdgeColor = new Color(237, 205, 145); + Color edgeColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly * 0.2f, primaryEdgeColor, secondaryEdgeColor); + + // Define shader parameters for shield color + shieldEffect.Parameters["shieldColor"].SetValue(shieldColor.ToVector3()); + shieldEffect.Parameters["shieldEdgeColor"].SetValue(edgeColor.ToVector3()); + + var matrix = Main.GameViewMatrix.TransformationMatrix; + Main.spriteBatch.SafeBegin(SpriteSortMode.Immediate, BatchSetting.Additive, shieldEffect, matrix, () => { - if (player.outOfRange || player.dead) - continue; - - CalamityPlayer modPlayer = player.Calamity(); - - // Do not render shield if it does not exist - if (modPlayer.LunicCorpsShieldDurability <= 0 || modPlayer.drawnAnyShieldThisFrame) - continue; - - // Scale the shield is drawn at. The Lunic Corps shield sticks very close to the body to mimic Halo and occasionally pulses. - // The "i" parameter is to make different player's shields not be perfectly synced. - int i = player.whoAmI; - float baseScale = 0.11f; - float maxExtraScale = 0.013f; - float extraScalePulseInterpolant = MathF.Pow(12f, MathF.Sin(Main.GlobalTimeWrappedHourly * 1.6f + i) - 1); - float scale = baseScale + maxExtraScale * extraScalePulseInterpolant; - - if (!alreadyDrawnShieldForPlayer) - { - // Again, I believe there is no way this looks correct when two players have Lunic Corps armor equipped. - CalamityPlayer localModPlayer = Main.LocalPlayer.Calamity(); - float shieldDurabilityRatio = localModPlayer.LunicCorpsShieldDurability / (float)ShieldDurabilityMax; - float visualShieldStrength = MathF.Pow(shieldDurabilityRatio, 0.5f); - - // The scale used for the noise overlay polygons also grows and shrinks - // This is intentionally out of sync with the shield, and intentionally desynced per player - // Don't put this anywhere less than 0.25f or higher than 1f. The higher it is, the denser / more zoomed out the noise overlay is. - float noiseScale = MathHelper.Lerp(0.65f, 0.75f, 0.5f + 0.5f * MathF.Sin(Main.GlobalTimeWrappedHourly * 0.87f + i)); - - // Define shader parameters - Effect shieldEffect = Filters.Scene["CalamityMod:RoverDriveShield"].GetShader().Shader; - shieldEffect.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly * 0.058f); // Scrolling speed of polygonal overlay - shieldEffect.Parameters["blowUpPower"].SetValue(2.8f); - shieldEffect.Parameters["blowUpSize"].SetValue(0.4f); - shieldEffect.Parameters["noiseScale"].SetValue(noiseScale); - - // Shield opacity multiplier slightly changes, this is independent of current shield strength - float baseShieldOpacity = 0.9f + 0.1f * MathF.Sin(Main.GlobalTimeWrappedHourly * 1.95f); - float minShieldStrengthOpacityMultiplier = 0.5f; - float finalShieldOpacity = baseShieldOpacity * MathHelper.Lerp(minShieldStrengthOpacityMultiplier, 1f, visualShieldStrength); - shieldEffect.Parameters["shieldOpacity"].SetValue(finalShieldOpacity); - shieldEffect.Parameters["shieldEdgeBlendStrenght"].SetValue(4f); - - // Lunic Corps shields are not team specific - Color shieldColor = new Color(201, 180, 129); - Color primaryEdgeColor = new Color(232, 212, 175); - Color secondaryEdgeColor = new Color(237, 205, 145); - Color edgeColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly * 0.2f, primaryEdgeColor, secondaryEdgeColor); - - // Define shader parameters for shield color - shieldEffect.Parameters["shieldColor"].SetValue(shieldColor.ToVector3()); - shieldEffect.Parameters["shieldEdgeColor"].SetValue(edgeColor.ToVector3()); - - // GOD I LOVE END BEGIN CAN THIS GAME PLEASE BE SWALLOWED BY THE FIRES OF HELL THANKS - // yes I copy pasted that comment, I hate end begin that much - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, shieldEffect, Main.GameViewMatrix.TransformationMatrix); - } - - alreadyDrawnShieldForPlayer = true; - modPlayer.drawnAnyShieldThisFrame = true; - // Fetch shield noise overlay texture (this is the polygons fed to the shader) NoiseTex ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/VoronoiShapes2"); Vector2 pos = player.MountedCenter + player.gfxOffY * Vector2.UnitY - Main.screenPosition; Texture2D tex = NoiseTex.Value; spriteBatch.Draw(tex, pos, null, Color.White, 0, tex.Size() / 2f, scale, 0, 0); - } + }); - if (alreadyDrawnShieldForPlayer) - { - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Main.Transform); - } + modPlayer.drawnAnyShieldThisFrame = true; } } } diff --git a/Items/CalamityGlobalItem.cs b/Items/CalamityGlobalItem.cs index 9acc1ea443..34a8e4f2a8 100644 --- a/Items/CalamityGlobalItem.cs +++ b/Items/CalamityGlobalItem.cs @@ -12,6 +12,7 @@ using CalamityMod.Items.Weapons.Melee; using CalamityMod.Items.Weapons.Summon; using CalamityMod.NPCs.Other; using CalamityMod.NPCs.TownNPCs; +using CalamityMod.Packets; using CalamityMod.Particles; using CalamityMod.Projectiles.Magic; using CalamityMod.Projectiles.Melee; @@ -1111,7 +1112,6 @@ namespace CalamityMod.Items break; case ItemID.SquirePlating: player.GetDamage() -= 0.05f; - player.GetDamage() -= 0.05f; break; case ItemID.SquireGreaves: player.GetDamage() -= 0.1f; @@ -1830,11 +1830,7 @@ namespace CalamityMod.Items if (Main.netMode == NetmodeID.MultiplayerClient) { - ModPacket packet = CalamityMod.Instance.GetPacket(); - packet.Write((byte)CalamityModMessageType.SomeoneGotScammedByTinkerer); - packet.Write((byte)p.whoAmI); - packet.Write7BitEncodedInt(stolen); - packet.Send(); + BanditStolenMoneySyncPacket.Send(stolen); } } } diff --git a/Items/CalamityGlobalItemLoot.cs b/Items/CalamityGlobalItemLoot.cs index 6836ee9ae4..9d03030e9b 100644 --- a/Items/CalamityGlobalItemLoot.cs +++ b/Items/CalamityGlobalItemLoot.cs @@ -274,6 +274,7 @@ namespace CalamityMod.Items case ItemID.WoodenCrate: case ItemID.WoodenCrateHard: loot.Add(ModContent.ItemType(), 4, 3, 5); // 25% 3-5 Wulfrum Scrap + loot.Add(ModContent.ItemType(), 20); break; case ItemID.IronCrate: diff --git a/Items/CalamityGlobalItemTooltip.cs b/Items/CalamityGlobalItemTooltip.cs index 72dc5d99c3..191b28a627 100644 --- a/Items/CalamityGlobalItemTooltip.cs +++ b/Items/CalamityGlobalItemTooltip.cs @@ -1147,7 +1147,7 @@ namespace CalamityMod.Items if (item.type == ItemID.SquireGreatHelm) EditTooltipByNum(0, (line) => line.Text = "Increases your max number of sentries by 1 and grants +2 HP/s life regen"); if (item.type == ItemID.SquirePlating) - EditTooltipByNum(0, (line) => line.Text = "10% increased minion and melee damage"); + EditTooltipByNum(0, (line) => line.Text = "10% increased minion damage and 15% increased melee damage"); if (item.type == ItemID.SquireGreaves) EditTooltipByNum(0, (line) => line.Text = "5% increased minion damage and melee critical strike chance\n" + "15% increased movement speed"); diff --git a/Items/CalamityGlobalItemTweaks.cs b/Items/CalamityGlobalItemTweaks.cs index 049ac24776..bfd3286fe7 100644 --- a/Items/CalamityGlobalItemTweaks.cs +++ b/Items/CalamityGlobalItemTweaks.cs @@ -78,7 +78,7 @@ namespace CalamityMod.Items { ItemID.Code2, Do(AutoReuse, DamageExact(43)) }, { ItemID.CorruptYoyo, Do(AutoReuse, DamageExact(20)) }, // Malaise { ItemID.CrimsonYoyo, Do(AutoReuse, DamageExact(20)) }, // Artery - { ItemID.CrystalBullet, Do(DamageExact(8)) }, + { ItemID.CrystalBullet, Do(DamageExact(6)) }, { ItemID.CrystalDart, Do(DamageExact(20)) }, { ItemID.CrystalSerpent, Do(DamageExact(45)) }, { ItemID.CrystalStorm, Do(DamageExact(40)) }, @@ -263,7 +263,7 @@ namespace CalamityMod.Items { ItemID.Trimarang, Do(DamageExact(24)) }, { ItemID.TrueExcalibur, Do(TrueMelee, DamageExact(107)) }, { ItemID.TrueNightsEdge, Do(DamageExact(105)) }, - { ItemID.Tsunami, Do(PointBlank, DamageExact(49)) }, + { ItemID.Tsunami, Do(PointBlank, DamageExact(45)) }, { ItemID.TungstenBullet, Do(DamageExact(8)) }, { ItemID.TungstenShortsword, Do(AutoReuse, TrueMelee, DamageExact(15)) }, { ItemID.UnholyArrow, Do(DamageExact(11)) }, @@ -323,7 +323,7 @@ namespace CalamityMod.Items { ItemID.BloodLustCluster, Do(AxePower(100), UseTimeExact(13), TileBoostExact(+0)) }, { ItemID.BonePickaxe, Do(PickPower(55), UseTimeExact(6)) }, { ItemID.BorealWoodHammer, Do(HammerPower(25), UseTimeExact(11), TileBoostExact(+0)) }, - { ItemID.ButchersChainsaw, Do(TrueMeleeNoSpeed, AxePower(150), UseTimeExact(3), TileBoostExact(+0), DamageExact(177)) }, + { ItemID.ButchersChainsaw, Do(TrueMeleeNoSpeed, AxePower(150), UseTimeExact(3), TileBoostExact(+0), DamageExact(126)) }, { ItemID.CactusPickaxe, Do(PickPower(34), UseTimeExact(9)) }, { ItemID.CnadyCanePickaxe, Do(PickPower(55), UseTimeExact(9), TileBoostExact(+1)) }, // Candy Cane Pickaxe { ItemID.ChlorophyteChainsaw, Do(TrueMeleeNoSpeed, AxePower(120), UseTimeExact(3), TileBoostExact(+0), DamageExact(112)) }, diff --git a/Items/Critters/BabyGhostBellItem.cs b/Items/Critters/BabyGhostBellItem.cs index 6377f5f2d1..cdd7b3e758 100644 --- a/Items/Critters/BabyGhostBellItem.cs +++ b/Items/Critters/BabyGhostBellItem.cs @@ -1,4 +1,5 @@ using CalamityMod.NPCs.SunkenSea; +using CalamityMod.Packets; using Terraria; using Terraria.ID; using Terraria.ModLoader; @@ -71,15 +72,7 @@ namespace CalamityMod.Items.Critters } else { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.PlaceAltCritter); - netMessage.Write(player.whoAmI); - netMessage.Write(mouseX); - netMessage.Write(mouseY); - netMessage.Write(item.makeNPC); - netMessage.Write(item.type); - netMessage.Write(colorType); - netMessage.Send(); + PlaceAltCritterPacket.Send(player, mouseX, mouseY, item, colorType); } } } diff --git a/Items/Critters/PolypPanaseaItem.cs b/Items/Critters/PolypPanaseaItem.cs index 2edefe3eb0..f9514b03f2 100644 --- a/Items/Critters/PolypPanaseaItem.cs +++ b/Items/Critters/PolypPanaseaItem.cs @@ -1,4 +1,5 @@ using CalamityMod.NPCs.SunkenSea; +using CalamityMod.Packets; using Terraria; using Terraria.ID; using Terraria.ModLoader; @@ -74,15 +75,7 @@ namespace CalamityMod.Items.Critters } else { - var netMessage = item.ModItem.Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.PlaceAltCritter); - netMessage.Write(player.whoAmI); - netMessage.Write(mouseX); - netMessage.Write(mouseY); - netMessage.Write(item.makeNPC); - netMessage.Write(item.type); - netMessage.Write(colorType); - netMessage.Send(); + PlaceAltCritterPacket.Send(player, mouseX, mouseY, item, colorType); } } } diff --git a/Items/Placeables/Furniture/ThaumaticChair.cs b/Items/Placeables/Furniture/ThaumaticChair.cs index 91e5a91fac..21bd2c2555 100644 --- a/Items/Placeables/Furniture/ThaumaticChair.cs +++ b/Items/Placeables/Furniture/ThaumaticChair.cs @@ -7,6 +7,7 @@ using CalamityMod.Items.Placeables.FurnitureBotanic; using CalamityMod.Items.Placeables.FurnitureCosmilite; using CalamityMod.Items.Placeables.FurnitureEutrophic; using CalamityMod.Items.Placeables.FurnitureExo; +using CalamityMod.Items.Placeables.FurnitureMarnite; using CalamityMod.Items.Placeables.FurnitureMonolith; using CalamityMod.Items.Placeables.FurnitureOtherworldly; using CalamityMod.Items.Placeables.FurniturePlagued; @@ -55,6 +56,7 @@ namespace CalamityMod.Items.Placeables.Furniture AddIngredient(). AddIngredient(). AddIngredient(). + AddIngredient(). AddIngredient(). AddIngredient(). AddIngredient(). diff --git a/Items/SuperDummy.cs b/Items/SuperDummy.cs index e8c4910e04..8291cf7763 100644 --- a/Items/SuperDummy.cs +++ b/Items/SuperDummy.cs @@ -1,4 +1,5 @@ using CalamityMod.NPCs.NormalNPCs; +using CalamityMod.Packets; using Terraria; using Terraria.DataStructures; using Terraria.ID; @@ -59,9 +60,7 @@ namespace CalamityMod.Items // dummies are gone, and cause them to reappear, making the deletion moot. else { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.DeleteAllSuperDummies); - netMessage.Send(); + DeleteAllSuperDummiesPacket.Send(); } } } @@ -77,11 +76,7 @@ namespace CalamityMod.Items // Otherwise, send a message to the server indicating that a Super Dummy should be spawned at this position. else { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SpawnSuperDummy); - netMessage.Write(x); - netMessage.Write(y); - netMessage.Send(); + SpawnSuperDummyPacket.Send(x, y); } } return true; @@ -98,9 +93,7 @@ namespace CalamityMod.Items } else { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.DeleteAllSuperDummies); - netMessage.Send(); + DeleteAllSuperDummiesPacket.Send(); } Item.RestoreConsumedItemByRightClick(); diff --git a/Items/TreasureBags/LeviathanBag.cs b/Items/TreasureBags/LeviathanBag.cs index a772eed178..c9b2d66a2f 100644 --- a/Items/TreasureBags/LeviathanBag.cs +++ b/Items/TreasureBags/LeviathanBag.cs @@ -69,7 +69,7 @@ namespace CalamityMod.Items.TreasureBags ModContent.ItemType(), ModContent.ItemType(), ModContent.ItemType(), - ModContent.ItemType(), + ModContent.ItemType(), ModContent.ItemType(), })); diff --git a/Items/Weapons/Magic/Atlantis.cs b/Items/Weapons/Magic/Atlantis.cs index 8a0f0fd26a..4181b4fa34 100644 --- a/Items/Weapons/Magic/Atlantis.cs +++ b/Items/Weapons/Magic/Atlantis.cs @@ -2,6 +2,8 @@ using CalamityMod.Projectiles.Magic; using Microsoft.Xna.Framework; using Terraria; +using Terraria.Audio; +using CalamityMod.Particles; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; @@ -30,7 +32,7 @@ namespace CalamityMod.Items.Weapons.Magic Item.knockBack = 5f; Item.value = CalamityGlobalItem.RarityLimeBuyPrice; Item.rare = ItemRarityID.Lime; - Item.UseSound = SoundID.Item34; + Item.UseSound = new SoundStyle("CalamityMod/Sounds/Item/VividClarityBeamAppear") with { Volume = 0.5f, Pitch = 0.2f }; Item.autoReuse = true; Item.shoot = ModContent.ProjectileType(); Item.shootSpeed = 40f; @@ -46,6 +48,32 @@ namespace CalamityMod.Items.Weapons.Magic } } public override float UseSpeedMultiplier(Player player) => (DownedBossSystem.downedDoG && Main.zenithWorld) ? 2.5f : 1f; + public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback) + { + int points = 6; + float radians = MathHelper.TwoPi / points; + Vector2 spinningPoint = Vector2.Normalize(velocity); + for (int k = 0; k < points; k++) + { + Vector2 velocity2 = spinningPoint.RotatedBy(radians * k); + Particle spark = new GlowSparkParticle((position + velocity2 * 7.5f) + velocity * 2.5f, velocity2 * 0.5f, false, 11, 0.01f, Color.LightBlue * 0.9f, new Vector2(3.5f, 1), true, false); + GeneralParticleHandler.SpawnParticle(spark); + for (int b = 0; b < 3; b++) + { + Dust dust = Dust.NewDustPerfect(position + velocity * 2.5f, 278, (velocity2 * 10).RotatedByRandom(0.5) * Main.rand.NextFloat(0.5f, 0.9f)); + dust.scale = Main.rand.NextFloat(0.3f, 0.5f); + dust.color = Main.rand.NextBool() ? Color.Cyan : Color.LightBlue; + dust.noGravity = true; + } + } + Particle blastRing = new CustomPulse(position + velocity * 2.5f, Vector2.Zero, Color.CornflowerBlue, "CalamityMod/Particles/BloomCircle", Vector2.One, Main.rand.NextFloat(-10, 10), 1.25f, 0f, 11, true); + GeneralParticleHandler.SpawnParticle(blastRing); + Particle blastRing2 = new CustomPulse(position + velocity * 2.5f, Vector2.Zero, Color.White, "CalamityMod/Particles/BloomCircle", Vector2.One, Main.rand.NextFloat(-10, 10), 0.6f, 0.1f, 14, true); + GeneralParticleHandler.SpawnParticle(blastRing2); + + Projectile.NewProjectile(source, position + velocity * 2, velocity, type, damage, knockback, player.whoAmI, 0f, 0f, 5f); + return false; + } public override void ModifyTooltips(List list) { diff --git a/Items/Weapons/Magic/ShadowboltStaff.cs b/Items/Weapons/Magic/ShadowboltStaff.cs index 2999b69777..970fa21d21 100644 --- a/Items/Weapons/Magic/ShadowboltStaff.cs +++ b/Items/Weapons/Magic/ShadowboltStaff.cs @@ -41,7 +41,7 @@ namespace CalamityMod.Items.Weapons.Magic CreateRecipe(). AddIngredient(ItemID.ShadowbeamStaff). AddIngredient(2). - AddIngredient(3). + AddIngredient(). AddTile(TileID.LunarCraftingStation). Register(); } diff --git a/Items/Weapons/Melee/Avalanche.cs b/Items/Weapons/Melee/Avalanche.cs index d62182a121..43273d55d4 100644 --- a/Items/Weapons/Melee/Avalanche.cs +++ b/Items/Weapons/Melee/Avalanche.cs @@ -14,7 +14,7 @@ namespace CalamityMod.Items.Weapons.Melee { Item.width = 64; Item.height = 64; - Item.damage = 100; + Item.damage = 75; Item.DamageType = DamageClass.Melee; Item.useAnimation = 35; Item.useTime = 35; @@ -29,39 +29,16 @@ namespace CalamityMod.Items.Weapons.Melee public override void OnHitNPC(Player player, NPC target, NPC.HitInfo hit, int damageDone) { - var source = player.GetSource_ItemUse(Item); - int totalProjectiles = 4; - float radians = MathHelper.TwoPi / totalProjectiles; int type = ModContent.ProjectileType(); - int bombDamage = player.CalcIntDamage(Item.damage); - float velocity = 4f; - double angleA = radians * 0.5; - double angleB = MathHelper.ToRadians(90f) - angleA; - float velocityX = (float)(velocity * Math.Sin(angleA) / Math.Sin(angleB)); - Vector2 spinningPoint = Main.rand.NextBool() ? new Vector2(0f, -velocity) : new Vector2(-velocityX, -velocity); - for (int k = 0; k < totalProjectiles; k++) + if (CalamityUtils.CountProjectiles(type) < 16) { - Vector2 projRotation = spinningPoint.RotatedBy(radians * k); - Projectile.NewProjectile(source, target.Center, projRotation, type, bombDamage, hit.Knockback * 0.5f, Main.myPlayer); - } - } - - public override void OnHitPvp(Player player, Player target, Player.HurtInfo hurtInfo) - { - var source = player.GetSource_ItemUse(Item); - int totalProjectiles = 4; - float radians = MathHelper.TwoPi / totalProjectiles; - int type = ModContent.ProjectileType(); - int bombDamage = player.CalcIntDamage(Item.damage); - float velocity = 4f; - double angleA = radians * 0.5; - double angleB = MathHelper.ToRadians(90f) - angleA; - float velocityX = (float)(velocity * Math.Sin(angleA) / Math.Sin(angleB)); - Vector2 spinningPoint = Main.rand.NextBool() ? new Vector2(0f, -velocity) : new Vector2(-velocityX, -velocity); - for (int k = 0; k < totalProjectiles; k++) - { - Vector2 projRotation = spinningPoint.RotatedBy(radians * k); - Projectile.NewProjectile(source, target.Center, projRotation, type, bombDamage, 0f, Main.myPlayer); + var source = player.GetSource_ItemUse(Item); + int bombDamage = player.CalcIntDamage(Item.damage); + for (int k = 0; k < 4; k++) + { + // ai0: projectile timer. ai1: target index. ai2: rotation offset based on ice bomb number. + Projectile.NewProjectile(source, target.Center, Vector2.Zero, type, bombDamage, hit.Knockback * 0.5f, Main.myPlayer, 0f, target.whoAmI, k); + } } } diff --git a/Items/Weapons/Melee/EmpyreanKnives.cs b/Items/Weapons/Melee/EmpyreanKnives.cs index 649a605bf3..285c560887 100644 --- a/Items/Weapons/Melee/EmpyreanKnives.cs +++ b/Items/Weapons/Melee/EmpyreanKnives.cs @@ -18,7 +18,7 @@ namespace CalamityMod.Items.Weapons.Melee { Item.width = 18; Item.height = 20; - Item.damage = 230; + Item.damage = 130; Item.DamageType = DamageClass.MeleeNoSpeed; Item.noMelee = true; Item.noUseGraphic = true; @@ -97,9 +97,8 @@ namespace CalamityMod.Items.Weapons.Melee CreateRecipe(). AddIngredient(ItemID.VampireKnives). AddIngredient(). - AddIngredient(8). - AddIngredient(8). - AddTile(). + AddIngredient(3). + AddTile(TileID.LunarCraftingStation). Register(); } } diff --git a/Items/Weapons/Melee/FallenPaladinsHammer.cs b/Items/Weapons/Melee/FallenPaladinsHammer.cs index 0c43c3267e..3eac1280c0 100644 --- a/Items/Weapons/Melee/FallenPaladinsHammer.cs +++ b/Items/Weapons/Melee/FallenPaladinsHammer.cs @@ -10,7 +10,7 @@ namespace CalamityMod.Items.Weapons.Melee public class FallenPaladinsHammer : ModItem, ILocalizedModType { public new string LocalizationCategory => "Items.Weapons.Melee"; - public static float Speed = 28.8f; + public static float Speed = 27f; public override void SetDefaults() { diff --git a/Items/Weapons/Melee/FracturedArk.cs b/Items/Weapons/Melee/FracturedArk.cs index f7b6845084..10a53c1d95 100644 --- a/Items/Weapons/Melee/FracturedArk.cs +++ b/Items/Weapons/Melee/FracturedArk.cs @@ -43,7 +43,7 @@ namespace CalamityMod.Items.Weapons.Melee public override void SetDefaults() { Item.width = Item.height = 60; - Item.damage = 35; + Item.damage = 41; Item.DamageType = DamageClass.MeleeNoSpeed; Item.noUseGraphic = true; Item.noMelee = true; diff --git a/Items/Weapons/Melee/GalaxySmasher.cs b/Items/Weapons/Melee/GalaxySmasher.cs index 78c04aef91..4181e6db0e 100644 --- a/Items/Weapons/Melee/GalaxySmasher.cs +++ b/Items/Weapons/Melee/GalaxySmasher.cs @@ -14,18 +14,17 @@ namespace CalamityMod.Items.Weapons.Melee public class GalaxySmasher : ModItem, ILocalizedModType { public new string LocalizationCategory => "Items.Weapons.Melee"; - public static int BaseDamage = 1300; - public static float Speed = 30f; + public static float Speed = 35f; public override void SetDefaults() { Item.width = 86; Item.height = 72; Item.DamageType = DamageClass.MeleeNoSpeed; - Item.damage = BaseDamage; + Item.damage = 1300; Item.knockBack = 14f; - Item.useAnimation = 40; - Item.useTime = 40; + Item.useAnimation = 48; + Item.useTime = 48; Item.autoReuse = true; Item.noMelee = true; Item.noUseGraphic = true; diff --git a/Items/Weapons/Melee/Greentide.cs b/Items/Weapons/Melee/Greentide.cs index 836b4b600d..086741e9f8 100644 --- a/Items/Weapons/Melee/Greentide.cs +++ b/Items/Weapons/Melee/Greentide.cs @@ -1,7 +1,10 @@ using System; +using CalamityMod.Buffs.DamageOverTime; using CalamityMod.Projectiles.Melee; using Microsoft.Xna.Framework; using Terraria; +using Terraria.Audio; +using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; @@ -27,25 +30,47 @@ namespace CalamityMod.Items.Weapons.Melee Item.height = 62; Item.damage = 87; // IS THAT THE BITE OF '87 Item.DamageType = DamageClass.Melee; - Item.useTime = 31; - Item.useAnimation = 31; + Item.useTime = 27; + Item.useAnimation = 27; Item.useTurn = true; Item.useStyle = ItemUseStyleID.Swing; Item.knockBack = 7f; Item.value = CalamityGlobalItem.RarityLimeBuyPrice; Item.rare = ItemRarityID.Lime; Item.UseSound = SoundID.Item1; + Item.shoot = ModContent.ProjectileType(); Item.autoReuse = true; - Item.shootSpeed = ShootSpeed; + Item.shootSpeed = 10; + } + public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback) + { + for (int i = 0; i < 2; ++i) + { + Projectile tooth = Projectile.NewProjectileDirect(source, position, velocity.RotatedBy(-0.1f * (i + 1)).RotatedByRandom(0.06f) * (1 - i * 0.3f), type, (int)(damage * 0.7f), knockback / 3, player.whoAmI, 1f, 0f); + tooth.penetrate = 2; + } + for (int i = 0; i < 2; ++i) + { + Projectile tooth = Projectile.NewProjectileDirect(source, position, velocity.RotatedBy(0.1f * (i + 1)).RotatedByRandom(0.06f) * (1 - i * 0.3f), type, (int)(damage * 0.7), knockback / 3, player.whoAmI, 1f, 0f); + tooth.penetrate = 2; + } + Projectile strongTooth = Projectile.NewProjectileDirect(source, position, velocity * 1.2f, type, (int)(damage), knockback, player.whoAmI, 2f, 0f); + strongTooth.penetrate = -1; + strongTooth.timeLeft = 150; + return false; } public override void OnHitNPC(Player player, NPC target, NPC.HitInfo hit, int damageDone) { + NPC target2 = player.Calamity().mouseWorld.ClosestNPCAt(300); + if (target2 == null) + target2 = target; + Vector2 destination = target.Center; - Vector2 position = destination - (Vector2.UnitY * (destination.Y - Main.screenPosition.Y + 80f)); + Vector2 position = new Vector2(target2.Center.X, target2.Center.Y - 350); Vector2 cachedPosition = position; - Vector2 secondPosition = cachedPosition + (Vector2.UnitY * (Main.screenHeight + 160f)); + Vector2 secondPosition = new Vector2(target2.Center.X, target2.Center.Y + 350); Vector2 secondCachedPosition = secondPosition; Vector2 velocity = (destination - position).SafeNormalize(Vector2.UnitY) * ShootSpeed; @@ -53,7 +78,7 @@ namespace CalamityMod.Items.Weapons.Melee Vector2 secondVelocity = (destination - secondPosition).SafeNormalize(Vector2.UnitY) * ShootSpeed; Vector2 secondCachedVelocity = secondVelocity; - int teethDamage = player.CalcIntDamage((int)(Item.damage * 0.5)); + int teethDamage = player.CalcIntDamage((int)(Item.damage * 0.2)); float teethKnockback = Item.knockBack * 0.2f; bool evenNumberOfProjectiles = TotalTeeth % 2 == 0; float amountToAdd = evenNumberOfProjectiles ? 0.5f : 0f; @@ -71,19 +96,19 @@ namespace CalamityMod.Items.Weapons.Melee velocityAdjustment = ((j == centralProjectile || j == otherCentralProjectile) && evenNumberOfProjectiles) ? minVelocityAdjustment : MathHelper.Lerp(minVelocityAdjustment, maxVelocityAdjustment, Math.Abs((j + amountToAdd) - centralProjectile) / (float)centralProjectile); if (topTeeth) { - position.X += MathHelper.Lerp(-HalvedTeethSpread, HalvedTeethSpread, j / (float)(TotalTeeth - 1)); - velocity = CalamityUtils.CalculatePredictiveAimToTargetMaxUpdates(position, target, ShootSpeed, 1) * velocityAdjustment; + position.X += MathHelper.Lerp(-HalvedTeethSpread * 0.3f, HalvedTeethSpread * 0.3f, j / (float)(TotalTeeth - 1)); + velocity = CalamityUtils.CalculatePredictiveAimToTargetMaxUpdates(position, target2, ShootSpeed, 1) * velocityAdjustment; velocity.X *= teethXVelocityReduction; - Projectile.NewProjectile(player.GetSource_ItemUse(Item), position, velocity, ModContent.ProjectileType(), teethDamage, teethKnockback, player.whoAmI, 0f, i, target.Center.Y); + Projectile.NewProjectile(player.GetSource_ItemUse(Item), position, velocity * 0.25f, ModContent.ProjectileType(), teethDamage, teethKnockback, player.whoAmI, 0f, i, target2.Center.Y); position = cachedPosition; velocity = cachedVelocity; } else { - secondPosition.X += MathHelper.Lerp(-HalvedTeethSpread, HalvedTeethSpread, j / (float)(TotalTeeth - 1)); - secondVelocity = CalamityUtils.CalculatePredictiveAimToTargetMaxUpdates(secondPosition, target, ShootSpeed, 1) * velocityAdjustment; + secondPosition.X += MathHelper.Lerp(-HalvedTeethSpread * 0.3f, HalvedTeethSpread * 0.3f, j / (float)(TotalTeeth - 1)); + secondVelocity = CalamityUtils.CalculatePredictiveAimToTargetMaxUpdates(secondPosition, target2, ShootSpeed, 1) * velocityAdjustment; secondVelocity.X *= teethXVelocityReduction; - Projectile.NewProjectile(player.GetSource_ItemUse(Item), secondPosition, secondVelocity, ModContent.ProjectileType(), teethDamage, teethKnockback, player.whoAmI, 0f, i, target.Center.Y); + Projectile.NewProjectile(player.GetSource_ItemUse(Item), secondPosition, secondVelocity * 0.25f, ModContent.ProjectileType(), teethDamage, teethKnockback, player.whoAmI, 0f, i, target2.Center.Y); secondPosition = secondCachedPosition; secondVelocity = secondCachedVelocity; } @@ -145,8 +170,9 @@ namespace CalamityMod.Items.Weapons.Melee public override void MeleeEffects(Player player, Rectangle hitbox) { - if (Main.rand.NextBool(4)) - Dust.NewDust(new Vector2(hitbox.X, hitbox.Y), hitbox.Width, hitbox.Height, Main.rand.NextBool() ? 33 : 89); + Vector2 dustVel = Vector2.One.RotatedByRandom(100) * Main.rand.NextFloat(0.9f, 1.5f); + if (Main.rand.NextBool(3)) + Dust.NewDust(new Vector2(hitbox.X, hitbox.Y), hitbox.Width, hitbox.Height, 102, dustVel.X, dustVel.Y); } } } diff --git a/Items/Weapons/Melee/Pwnagehammer.cs b/Items/Weapons/Melee/Pwnagehammer.cs index 41e5b2a727..4c0510417d 100644 --- a/Items/Weapons/Melee/Pwnagehammer.cs +++ b/Items/Weapons/Melee/Pwnagehammer.cs @@ -27,7 +27,7 @@ namespace CalamityMod.Items.Weapons.Melee Item.value = CalamityGlobalItem.RarityLightPurpleBuyPrice; Item.rare = ItemRarityID.LightPurple; Item.shoot = ModContent.ProjectileType(); - Item.shootSpeed = 29.4f; + Item.shootSpeed = 22f; } diff --git a/Items/Weapons/Melee/StellarContempt.cs b/Items/Weapons/Melee/StellarContempt.cs index 03487196f7..ca015ca064 100644 --- a/Items/Weapons/Melee/StellarContempt.cs +++ b/Items/Weapons/Melee/StellarContempt.cs @@ -9,7 +9,7 @@ namespace CalamityMod.Items.Weapons.Melee public class StellarContempt : ModItem, ILocalizedModType { public new string LocalizationCategory => "Items.Weapons.Melee"; - public static float Speed = 25f; + public static float Speed = 30f; public override void SetDefaults() { diff --git a/Items/Weapons/Ranged/Animosity.cs b/Items/Weapons/Ranged/Animosity.cs index afd87d2f30..18e17a6d39 100644 --- a/Items/Weapons/Ranged/Animosity.cs +++ b/Items/Weapons/Ranged/Animosity.cs @@ -18,7 +18,7 @@ namespace CalamityMod.Items.Weapons.Ranged public static readonly SoundStyle ShootAndReloadSound = new("CalamityMod/Sounds/Item/WulfrumBlunderbussFireAndReload") { PitchVariance = 0.25f }; // Very cool sound and it would be a shame for it to not be used elsewhere, would be even better if a new sound is made in the future, but for now this is good enough - public float SniperDmgMult = 8f; + public float SniperDmgMult = 9f; public float SniperCritMult = Main.zenithWorld ? 7f : 1.35f; public float SniperVelocityMult = 2f; public new string LocalizationCategory => "Items.Weapons.Ranged"; @@ -29,7 +29,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.width = 70; Item.height = 18; - Item.damage = 45; + Item.damage = 46; Item.DamageType = DamageClass.Ranged; Item.width = 70; Item.height = 18; diff --git a/Items/Weapons/Ranged/Arietes41.cs b/Items/Weapons/Ranged/Arietes41.cs index 17bcbe0b77..c429993437 100644 --- a/Items/Weapons/Ranged/Arietes41.cs +++ b/Items/Weapons/Ranged/Arietes41.cs @@ -22,7 +22,7 @@ namespace CalamityMod.Items.Weapons.Ranged Item.width = 56; Item.height = 30; Item.scale = 0.85f; - Item.damage = 65; + Item.damage = 95; Item.DamageType = DamageClass.Ranged; Item.useTime = 13; Item.useAnimation = 13; diff --git a/Items/Weapons/Ranged/ArterialAssault.cs b/Items/Weapons/Ranged/ArterialAssault.cs index 9623518c5f..9a37c667b7 100644 --- a/Items/Weapons/Ranged/ArterialAssault.cs +++ b/Items/Weapons/Ranged/ArterialAssault.cs @@ -74,13 +74,12 @@ namespace CalamityMod.Items.Weapons.Ranged mouseDistance = arrowSpeed / mouseDistance; mouseXDist *= mouseDistance; mouseYDist *= mouseDistance; - float speedX4 = mouseXDist; - float speedY5 = mouseYDist; - int shotArrow = Projectile.NewProjectile(source, realPlayerPos.X, realPlayerPos.Y, speedX4, speedY5, type, damage, knockback, player.whoAmI); - Main.projectile[shotArrow].noDropItem = true; - Main.projectile[shotArrow].tileCollide = false; - CalamityGlobalProjectile cgp = Main.projectile[shotArrow].Calamity(); - cgp.allProjectilesHome = true; + Vector2 arrowVel = new Vector2(mouseXDist, mouseYDist); + + Projectile shotArrow = Projectile.NewProjectileDirect(source, realPlayerPos, arrowVel, type, damage, knockback, player.whoAmI); + shotArrow.noDropItem = true; + shotArrow.tileCollide = false; + shotArrow.Calamity().conditionalHomingRange = 300f; return false; } diff --git a/Items/Weapons/Ranged/Buzzkill.cs b/Items/Weapons/Ranged/Buzzkill.cs index a8af69f6c4..63c52faec8 100644 --- a/Items/Weapons/Ranged/Buzzkill.cs +++ b/Items/Weapons/Ranged/Buzzkill.cs @@ -21,7 +21,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.width = 76; Item.height = 42; - Item.damage = 50; + Item.damage = 56; Item.useTime = 30; Item.useAnimation = 30; Item.useStyle = ItemUseStyleID.Shoot; diff --git a/Items/Weapons/Ranged/Deathwind.cs b/Items/Weapons/Ranged/Deathwind.cs index 81cf35ba6d..5b485b9487 100644 --- a/Items/Weapons/Ranged/Deathwind.cs +++ b/Items/Weapons/Ranged/Deathwind.cs @@ -37,7 +37,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.DrawItemGlowmaskSingleFrame(spriteBatch, rotation, ModContent.Request("CalamityMod/Items/Weapons/Ranged/DeathwindGlow").Value); } - + public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback) { for (int index = 0; index < 4; ++index) @@ -46,11 +46,11 @@ namespace CalamityMod.Items.Weapons.Ranged float SpeedY = velocity.Y + Main.rand.Next(-20, 21) * 0.05f; if (CalamityUtils.CheckWoodenAmmo(type, player)) { - Projectile.NewProjectile(source, position.X, position.Y, SpeedX, SpeedY, ModContent.ProjectileType(), (int)(damage * 1.75), knockback, player.whoAmI); + Projectile.NewProjectile(source, position.X, position.Y, SpeedX, SpeedY, ModContent.ProjectileType(), (int)(damage * 2), knockback, player.whoAmI); } else { - int baseArrow = Projectile.NewProjectile(source, position.X, position.Y, SpeedX, SpeedY, type, (int)(damage * 0.75), knockback, player.whoAmI); + int baseArrow = Projectile.NewProjectile(source, position.X, position.Y, SpeedX, SpeedY, type, damage, knockback, player.whoAmI); Main.projectile[baseArrow].noDropItem = true; } } diff --git a/Items/Weapons/Ranged/Hellborn.cs b/Items/Weapons/Ranged/Hellborn.cs index 55d6af9366..ff8069195f 100644 --- a/Items/Weapons/Ranged/Hellborn.cs +++ b/Items/Weapons/Ranged/Hellborn.cs @@ -21,7 +21,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.width = 62; Item.height = 34; - Item.damage = 475; + Item.damage = 320; Item.DamageType = DamageClass.Ranged; Item.useAnimation = Item.useTime = 30; Item.useStyle = ItemUseStyleID.Shoot; diff --git a/Items/Weapons/Ranged/LunarianBow.cs b/Items/Weapons/Ranged/LunarianBow.cs index 73882fcfb2..ea46bd671f 100644 --- a/Items/Weapons/Ranged/LunarianBow.cs +++ b/Items/Weapons/Ranged/LunarianBow.cs @@ -15,7 +15,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.width = 32; Item.height = 62; - Item.damage = 25; + Item.damage = 27; Item.DamageType = DamageClass.Ranged; Item.useTime = 22; Item.useAnimation = 22; diff --git a/Items/Weapons/Ranged/Megalodon.cs b/Items/Weapons/Ranged/Megalodon.cs index 80d0526b43..1f8d937a45 100644 --- a/Items/Weapons/Ranged/Megalodon.cs +++ b/Items/Weapons/Ranged/Megalodon.cs @@ -19,7 +19,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.width = 72; Item.height = 32; - Item.damage = 37; + Item.damage = 41; Item.DamageType = DamageClass.Ranged; Item.useTime = 6; Item.useAnimation = 6; @@ -30,7 +30,7 @@ namespace CalamityMod.Items.Weapons.Ranged Item.rare = ItemRarityID.Lime; Item.UseSound = SoundID.Item11; Item.autoReuse = true; - Item.shoot = ModContent.ProjectileType(); + Item.shoot = ModContent.ProjectileType(); Item.shootSpeed = 16f; Item.useAmmo = AmmoID.Bullet; Item.Calamity().canFirePointBlankShots = true; diff --git a/Items/Weapons/Ranged/Norfleet.cs b/Items/Weapons/Ranged/Norfleet.cs index 2f7500ee26..16dc0a289d 100644 --- a/Items/Weapons/Ranged/Norfleet.cs +++ b/Items/Weapons/Ranged/Norfleet.cs @@ -23,7 +23,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.width = 140; Item.height = 42; - Item.damage = 7077; + Item.damage = 8000; Item.knockBack = 15f; Item.shootSpeed = 30f; Item.useStyle = ItemUseStyleID.Shoot; diff --git a/Items/Weapons/Ranged/P90.cs b/Items/Weapons/Ranged/P90.cs index c5874559cb..a8a849fb3e 100644 --- a/Items/Weapons/Ranged/P90.cs +++ b/Items/Weapons/Ranged/P90.cs @@ -18,7 +18,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.width = 60; Item.height = 28; - Item.damage = 5; + Item.damage = 10; Item.DamageType = DamageClass.Ranged; Item.useAnimation = Item.useTime = 2; Item.useStyle = ItemUseStyleID.Shoot; diff --git a/Items/Weapons/Ranged/PolarisParrotfish.cs b/Items/Weapons/Ranged/PolarisParrotfish.cs index 2deeabc7b3..be98bffc27 100644 --- a/Items/Weapons/Ranged/PolarisParrotfish.cs +++ b/Items/Weapons/Ranged/PolarisParrotfish.cs @@ -31,7 +31,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.width = 38; Item.height = 34; - Item.damage = 41; + Item.damage = 46; Item.DamageType = DamageClass.Ranged; Item.useTime = SetUseTime; diff --git a/Items/Weapons/Ranged/SuperradiantSlaughterer.cs b/Items/Weapons/Ranged/SuperradiantSlaughterer.cs index 0431c9500d..e48e8b1315 100644 --- a/Items/Weapons/Ranged/SuperradiantSlaughterer.cs +++ b/Items/Weapons/Ranged/SuperradiantSlaughterer.cs @@ -55,7 +55,7 @@ namespace CalamityMod.Items.Weapons.Ranged { Item.width = 84; Item.height = 46; - Item.damage = 76; + Item.damage = 88; Item.DamageType = DamageClass.Ranged; Item.useTime = 30; Item.useAnimation = 30; diff --git a/Items/Weapons/Rogue/BrackishFlask.png b/Items/Weapons/Rogue/BrackishFlask.png deleted file mode 100644 index 0e5ad78a57..0000000000 Binary files a/Items/Weapons/Rogue/BrackishFlask.png and /dev/null differ diff --git a/Items/Weapons/Rogue/Kylie.cs b/Items/Weapons/Rogue/Kylie.cs index 8184726764..1608b25e4a 100644 --- a/Items/Weapons/Rogue/Kylie.cs +++ b/Items/Weapons/Rogue/Kylie.cs @@ -15,7 +15,7 @@ namespace CalamityMod.Items.Weapons.Rogue { Item.width = 34; Item.height = 50; - Item.damage = 63; + Item.damage = 15; Item.knockBack = 12; Item.DamageType = RogueDamageClass.Instance; Item.value = CalamityGlobalItem.RarityOrangeBuyPrice; @@ -33,22 +33,17 @@ namespace CalamityMod.Items.Weapons.Rogue // Terraria seems to really dislike high crit values in SetDefaults public override void ModifyWeaponCrit(Player player, ref float crit) => crit += 16; - public override float StealthDamageMultiplier => 0.3333f; - public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback) { CalamityPlayer p = Main.player[Main.myPlayer].Calamity(); //If stealth is full, shoot a spread of 3 boomerangs with reduced range if (p.StealthStrikeAvailable()) { - int spread = 10; - for (int i = 0; i < 3; i++) + int proj = Projectile.NewProjectile(source, position, velocity, type, damage, knockback, player.whoAmI); + if (proj.WithinBounds(Main.maxProjectiles)) { - Vector2 perturbedspeed = velocity.RotatedBy(MathHelper.ToRadians(spread)); - int proj = Projectile.NewProjectile(source, position, perturbedspeed, type, damage, knockback, player.whoAmI, 0f, 1f); - if (proj.WithinBounds(Main.maxProjectiles)) - Main.projectile[proj].Calamity().stealthStrike = true; - spread -= 10; + Main.projectile[proj].Calamity().stealthStrike = true; + Main.projectile[proj].penetrate = 7; } return false; } diff --git a/Items/Weapons/Rogue/LeviathanTeeth.cs b/Items/Weapons/Rogue/LeviathanTeeth.cs index f013288b68..adc05255a4 100644 --- a/Items/Weapons/Rogue/LeviathanTeeth.cs +++ b/Items/Weapons/Rogue/LeviathanTeeth.cs @@ -13,10 +13,10 @@ namespace CalamityMod.Items.Weapons.Rogue { Item.width = 36; Item.height = 38; - Item.damage = 64; + Item.damage = 44; Item.noMelee = true; Item.noUseGraphic = true; - Item.useAnimation = Item.useTime = 15; + Item.useAnimation = Item.useTime = 9; Item.useStyle = ItemUseStyleID.Swing; Item.knockBack = 1f; Item.UseSound = SoundID.Item1; @@ -25,43 +25,30 @@ namespace CalamityMod.Items.Weapons.Rogue Item.value = CalamityGlobalItem.RarityLimeBuyPrice; Item.rare = ItemRarityID.Lime; Item.shoot = ModContent.ProjectileType(); - Item.shootSpeed = 12f; + Item.shootSpeed = 5.5f; Item.DamageType = RogueDamageClass.Instance; } public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback) { bool stealthStrike = false; - int teethCount; + if (player.Calamity().StealthStrikeAvailable()) - { - teethCount = 6; stealthStrike = true; - } - else + for (int i = 0; i < 2; i++) { - teethCount = Main.rand.Next(2, 3 + 1); - } - - for (int i = 0; i < teethCount; i++) - { - float offsetSpeedX = velocity.X + Main.rand.NextFloat(-2f, 2f); - float offsetSpeedY = velocity.Y + Main.rand.NextFloat(-2f, 2f); - if (stealthStrike) { - int tooth = Projectile.NewProjectile(source, position.X, position.Y, offsetSpeedX * 1.5f, offsetSpeedY * 1.5f, type, damage, knockback * 10f, player.whoAmI); - if (tooth.WithinBounds(Main.maxProjectiles)) - { - Main.projectile[tooth].Calamity().stealthStrike = true; - Main.projectile[tooth].Calamity().lineColor = Main.rand.Next(3); - } + Projectile tooth = Projectile.NewProjectileDirect(source, position, velocity * 1.5f, type, damage, knockback * 12, player.whoAmI); + tooth.Calamity().stealthStrike = true; + tooth.timeLeft = 140; + tooth.ai[1] = 4; + return false; // This makes it not fire 2 with the for loop, thanks Angel lol } else { - int tooth = Projectile.NewProjectile(source, position.X, position.Y, offsetSpeedX, offsetSpeedY, type, damage, knockback, player.whoAmI); - if (tooth.WithinBounds(Main.maxProjectiles)) - Main.projectile[tooth].Calamity().lineColor = Main.rand.Next(3); + Projectile tooth = Projectile.NewProjectileDirect(source, position, velocity.RotatedByRandom(0.05f + i * 0.15f) * Main.rand.NextFloat(0.7f, 1f), type, damage, knockback, player.whoAmI); + tooth.ai[1] = Main.rand.Next(1, 3 + 1); } } return false; diff --git a/Items/Weapons/Rogue/RefractionRotor.cs b/Items/Weapons/Rogue/RefractionRotor.cs index 2d7451a63e..2adfadd300 100644 --- a/Items/Weapons/Rogue/RefractionRotor.cs +++ b/Items/Weapons/Rogue/RefractionRotor.cs @@ -1,4 +1,5 @@ -using CalamityMod.Projectiles.Rogue; +using CalamityMod.CalPlayer; +using CalamityMod.Projectiles.Rogue; using CalamityMod.Rarities; using Microsoft.Xna.Framework; using Terraria; @@ -13,9 +14,9 @@ namespace CalamityMod.Items.Weapons.Rogue public override void SetDefaults() { Item.width = Item.height = 120; - Item.damage = 616; + Item.damage = 332; Item.knockBack = 8.5f; - Item.useAnimation = Item.useTime = 18; + Item.useAnimation = Item.useTime = 55; Item.DamageType = RogueDamageClass.Instance; Item.autoReuse = true; Item.shootSpeed = 18f; @@ -29,14 +30,26 @@ namespace CalamityMod.Items.Weapons.Rogue Item.rare = ModContent.RarityType(); } - public override float StealthDamageMultiplier => 0.75f; + public override float StealthDamageMultiplier => 0.25f; public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback) { - int shuriken = Projectile.NewProjectile(source, position, velocity, type, damage, knockback, player.whoAmI); - if (player.Calamity().StealthStrikeAvailable() && Main.projectile.IndexInRange(shuriken)) - Main.projectile[shuriken].Calamity().stealthStrike = true; - return false; + CalamityPlayer p = Main.player[Main.myPlayer].Calamity(); + //If stealth is full, shoot a spread of 3 shurikens + if (p.StealthStrikeAvailable()) + { + int spread = 30; + for (int i = 0; i < 3; i++) + { + Vector2 perturbedspeed = velocity.RotatedBy(MathHelper.ToRadians(spread)); + int proj = Projectile.NewProjectile(source, position, perturbedspeed, type, damage, knockback, player.whoAmI, 0f, 1f); + if (proj.WithinBounds(Main.maxProjectiles)) + Main.projectile[proj].Calamity().stealthStrike = true; + spread -= 30; + } + return false; + } + return true; } } } diff --git a/Items/Weapons/Rogue/BrackishFlask.cs b/Items/Weapons/Rogue/Whitewater.cs similarity index 61% rename from Items/Weapons/Rogue/BrackishFlask.cs rename to Items/Weapons/Rogue/Whitewater.cs index cb85473023..c5d57042a6 100644 --- a/Items/Weapons/Rogue/BrackishFlask.cs +++ b/Items/Weapons/Rogue/Whitewater.cs @@ -7,25 +7,27 @@ using Terraria.ModLoader; namespace CalamityMod.Items.Weapons.Rogue { - public class BrackishFlask : RogueWeapon + [LegacyName("BrackishFlask")] + public class Whitewater : RogueWeapon { + public bool splitDirection = false; public override void SetDefaults() { - Item.width = 28; - Item.height = 30; - Item.damage = 60; + Item.width = 36; + Item.height = 40; + Item.damage = 97; Item.noMelee = true; Item.noUseGraphic = true; - Item.useAnimation = 35; + Item.useAnimation = 42; Item.useStyle = ItemUseStyleID.Swing; - Item.useTime = 35; + Item.useTime = 42; Item.knockBack = 6.5f; - Item.UseSound = SoundID.Item106; + Item.UseSound = SoundID.Item106 with { Volume = 0.7f }; Item.autoReuse = true; Item.value = CalamityGlobalItem.RarityLimeBuyPrice; Item.rare = ItemRarityID.Lime; - Item.shoot = ModContent.ProjectileType(); - Item.shootSpeed = 12f; + Item.shoot = ModContent.ProjectileType(); + Item.shootSpeed = 6f; Item.DamageType = RogueDamageClass.Instance; } @@ -37,10 +39,17 @@ namespace CalamityMod.Items.Weapons.Rogue { int stealth = Projectile.NewProjectile(source, position, velocity, type, damage, knockback, player.whoAmI); if (stealth.WithinBounds(Main.maxProjectiles)) + { Main.projectile[stealth].Calamity().stealthStrike = true; - return false; + } } - return true; + else + { + int proj = Projectile.NewProjectile(source, position, velocity, type, damage, knockback, player.whoAmI); + Main.projectile[proj].ai[1] = splitDirection ? 1 : -1; + splitDirection = !splitDirection; + } + return false; } } } diff --git a/Items/Weapons/Rogue/Whitewater.png b/Items/Weapons/Rogue/Whitewater.png new file mode 100644 index 0000000000..665e99c8f2 Binary files /dev/null and b/Items/Weapons/Rogue/Whitewater.png differ diff --git a/Items/Weapons/Summon/FlarebatStaff.cs b/Items/Weapons/Summon/FlarebatStaff.cs new file mode 100644 index 0000000000..997c03e851 --- /dev/null +++ b/Items/Weapons/Summon/FlarebatStaff.cs @@ -0,0 +1,53 @@ +using CalamityMod.Projectiles.Summon; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Items.Weapons.Summon +{ + public class FlarebatStaff : ModItem, ILocalizedModType + { + public new string LocalizationCategory => "Items.Weapons.Summon"; + + public override void SetDefaults() + { + Item.damage = 18; + Item.DamageType = DamageClass.Summon; + Item.shoot = ModContent.ProjectileType(); + Item.knockBack = 1f; + + Item.useTime = Item.useAnimation = 15; + (Item.width, Item.height) = (50, 50); + Item.mana = 10; + Item.noMelee = true; + Item.autoReuse = true; + Item.useStyle = ItemUseStyleID.Swing; + Item.UseSound = SoundID.Item20; + Item.value = CalamityGlobalItem.RarityGreenBuyPrice; + Item.rare = ItemRarityID.Green; + } + + public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback) + { + Projectile flarebatMinion = Projectile.NewProjectileDirect(source, Main.MouseWorld, Vector2.Zero, type, damage, knockback, player.whoAmI); + + int minionIndex = 0; + foreach (var proj in Main.ActiveProjectiles) + { + if ((proj.type != flarebatMinion.type && proj.type != ModContent.ProjectileType()) || proj.owner != flarebatMinion.owner) + continue; + + if (proj.type == flarebatMinion.type) + proj.ModProjectile().MinionIndex = minionIndex; + else + proj.ModProjectile().MinionIndex = minionIndex; + + minionIndex++; + } + + return false; + } + } +} diff --git a/Items/Weapons/Summon/FlarebatStaff.png b/Items/Weapons/Summon/FlarebatStaff.png new file mode 100644 index 0000000000..22e7b112ab Binary files /dev/null and b/Items/Weapons/Summon/FlarebatStaff.png differ diff --git a/Items/Weapons/Summon/FrostbatStaff.cs b/Items/Weapons/Summon/FrostbatStaff.cs new file mode 100644 index 0000000000..b84196b48e --- /dev/null +++ b/Items/Weapons/Summon/FrostbatStaff.cs @@ -0,0 +1,53 @@ +using CalamityMod.Projectiles.Summon; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Items.Weapons.Summon +{ + public class FrostbatStaff : ModItem, ILocalizedModType + { + public new string LocalizationCategory => "Items.Weapons.Summon"; + + public override void SetDefaults() + { + Item.damage = 22; + Item.DamageType = DamageClass.Summon; + Item.shoot = ModContent.ProjectileType(); + Item.knockBack = 1f; + + Item.useTime = Item.useAnimation = 15; + (Item.width, Item.height) = (50, 50); + Item.mana = 10; + Item.noMelee = true; + Item.autoReuse = true; + Item.useStyle = ItemUseStyleID.Swing; + Item.UseSound = SoundID.Item28; + Item.value = CalamityGlobalItem.RarityGreenBuyPrice; + Item.rare = ItemRarityID.Green; + } + + public override bool Shoot(Player player, EntitySource_ItemUse_WithAmmo source, Vector2 position, Vector2 velocity, int type, int damage, float knockback) + { + Projectile frostbatMinion = Projectile.NewProjectileDirect(source, Main.MouseWorld, Vector2.Zero, type, damage, knockback, player.whoAmI); + + int minionIndex = 0; + foreach (var proj in Main.ActiveProjectiles) + { + if ((proj.type != frostbatMinion.type && proj.type != ModContent.ProjectileType()) || proj.owner != frostbatMinion.owner) + continue; + + if (proj.type == frostbatMinion.type) + proj.ModProjectile().MinionIndex = minionIndex; + else + proj.ModProjectile().MinionIndex = minionIndex; + + minionIndex++; + } + + return false; + } + } +} diff --git a/Items/Weapons/Summon/FrostbatStaff.png b/Items/Weapons/Summon/FrostbatStaff.png new file mode 100644 index 0000000000..1c99a19da7 Binary files /dev/null and b/Items/Weapons/Summon/FrostbatStaff.png differ diff --git a/Localization/en-US/Mods.CalamityMod.Bestiary.hjson b/Localization/en-US/Mods.CalamityMod.Bestiary.hjson index 7a17ccfacf..e0aab5b306 100644 --- a/Localization/en-US/Mods.CalamityMod.Bestiary.hjson +++ b/Localization/en-US/Mods.CalamityMod.Bestiary.hjson @@ -70,7 +70,6 @@ ArmoredDigger: Despite being relatively primitive compared to Draedon's current AuroraSpirit: Thought to be no more than an old wives' tale, sightings of aurora spirits have become commonplace since the defeat of the wall of flesh. Upon closer inspection, it appears these "spirits" are rather wisp-like entities clad in a cryonic shell, a sure sign that these were created by Archmage Permafrost. BloomSlime: Imbued with profaned energy, this slime wishes to see the world reduced to ashes to ensure the suffering it brings is no more. However, the simplicity of their form makes it difficult for the slain goddess to fully impose her will onto them. Bohldohr: Bohldohrs were made to serve the lihzahrds, being crafted from ancient stone and brought to life with magical power in the twilight of the great Lihzahrd Dynasty. But the sun sets on every civilization, and once their deity abandoned them, they were left to fend for themselves. -Cnidrion: Once trained to be the steeds of honored Ilmerian warriors, cnidrions survived the Incineration due to their sheer might. They continue to defend what was once the heart of the sea kingdom from intruders, maintaining a fierce loyalty to their masters even after they have passed on. GemCrawler: Relatives to the Ilmeran Sea's prismbacks. The aquatic lizards ended up in the wild after being taken in as pets, though without the proper nutrients to grow prisms on their back, many grew the next best thing– precious gems. BlightSlime: Slimes that have absorbed some of the blighted godly essence. Riddled with impurity, they are now more putrid flesh than gelatin and, having taken in such an amount that they seem ready to burst. Yet unlike most slimes which have relatively basic minds, these seem to be collecting mass with a purpose. Cryon: Archmage Permafrost went through great pains to not take part in combat himself, instead molding cryons to act as his personal guardians. Noticing the spread of godly essence just as many other creatures have, they have come out of stasis to combat any signs of it so that they may defend their master. @@ -92,7 +91,6 @@ Rotdog: Fast and furious, these hounds prowl the night, hunting prey with their ScornEater: For one to be weak of will does not inherently mean they are weak of body. Within these powerful individuals does a powerful fire burn, and She is all too willing to fan the flames. All one need give in return for Her gracious blessing is their free will, and they shall be gifted Her enlightenment. SeaUrchin: Massive urchins that roll and hop their way across the sea floor, catching both fish hiding in the sand thanks to their spikes that allow them to comb the sea floor and those far above with their incredible leaps. Their surprising size is due to this species' carnivorous diet, rather than consuming plants like most types of urchins. ShockstormShuttle: Mining devices and scouts for a civilization from a long lost world. They now seek whatever resources are left on other nearby planets, and perhaps even this world as a potential replacement for their ruined home. -Stormlion: Some survivors of Ilmeris' downfall claim that enough magical lightning surged through the sea during its final days that there existed not a single drop of water without levin coursing through it. Even now, electricity from the battle remains buried in the sands, with several antlions having learned to both channel and harness the former kingdom's power. Sunskater: To the civilization that lived far above clouds, sunskaters were seen as a good omen. These creatures inspired hope in those who saw them, that their society might live on for as long as the sun's light bathes the world. ThiccWaifu: Part of a solitary elemental that rarely appears aside from when her domain is at its strongest. Many attempts were made by what remained of Yharim's forces to hunt down the elementals after Azafure fell. Only now that the war has passed do the weaker elementals dare return. WildBumblefuck: Though but an adolescent dragonfolly, it poses a great threat to all around it regardless of its age. Their species survived the draconic purges by reproducing rapidly and becoming highly reclusive, alongside developing a hyper-aggressive nature. @@ -117,16 +115,26 @@ Sulflounder: A relative to certain hadopelagic creatures living in the depths, t Toxicatfish: Though these fish once threatened none other than their prey, the radiation from nuclear waste generated from Draedon's old experiments has rotted both their bodies and minds. Attacking anything that comes near, this once flourishing species is now on the verge of extinction. Trasher: Despite being equipped with a mouth large enough to swallow a child whole, these crocodiles simply act as scavengers, devouring scraps and bones left over from predators' meals. Needing to conserve energy due to eating relatively little, they rarely move at their full speed unless they feel threatened. //Sunken Sea Enemies -BabyGhostBell: Ghost Bells were bred in large numbers during the Ilmeran war, due to the Ilmerian army needing a staggering amount of electricity to keep Yharim and his forces at bay. Alas, their efforts were for naught, and the kingdom collapsed after the Great Incineration. +BabyGhostBell: Despite their decidedly lower size and development, infant Ghost Bells can deliver just as many volts to unsuspecting creatures. The Ilmerian army bred thousands of Ghost Bells to maintain the lethal electric field around the sea kingdom, but all their efforts were consumed by ash in a single burning moment. BlindedAngler: Lacking most normal senses, these predators use a form of biological sonar to 'see' their surroundings. The glowing crystals on their backs draw in prey that use the sea's shimmering prisms as their guiding light, like a moth to the flame. -Clam: Clams once lived in the upper portion of the Ilmeran Sea before the Incineration, being forced to relocate after the battle. Though it was thanks in part to their adaptability and hardiness that their species survived, luck was also certainly on their side. -EutrophicRay: Eutrophic Rays have formed a commensalistic relationship with Ghost Bells. The rays can store energy given by the Ghost Bells for electrical muscle stimulation, allowing for great bursts of speed. -GhostBell: These high-voltage jellyfish can incapacitate most with a single touch, and were a major factor in the Ilmerian army's strength. The sea kingdom used the electricity produced by Ghost Bells to drive back Yharim's forces, electrifying the waters so that none could cross their borders. -GiantClam: Clams slowly crystalise ambient magic around themselves into pearls, and as they grow larger, so too do their pearls. Upon growing to their full size, they are classified as Giant Clams, and gain the ability to use the magic stored in their pearls to some degree. -PrismBack: Due to the beautiful prisms and calm behavior, these animals have been taken in as pets by many over the course of centuries, even outside of Ilmeris. Though far too slow and bulky to hunt normally, the sea prisms on their back act as a lure for small fish. -SeaFloaty: Flatworms can be found in many seas and oceans across the world, and are exceptional at fitting through cracks or crevices due to their thin bodies. These particular flatworms only ever inhabited the lower sea, and were left entirely unthreatened by the carnage that annihilated most species' homes. -SeaMinnow: Schools of sea minnows were one of the most beautiful things one could witness during the days when Ilmeris was unshattered. Those permitted into the kingdom would gather to see these fish swimming in the open sea… yet, this is but a distant past now, even for the minnows themselves. -SeaSerpent: Despite being one of the few carnivorous creatures to have ever existed in the Ilmeran Sea, even these serpents are unusually passive towards those they do not consider prey by the standards of elsewhere. The sea has only ever known one truly aggressive predator, and it abandoned a life of calming solitude years ago. +Clam: Despite having the same filter feeder appetite of the common clam, the Ilmeran species adopted defensive mechanisms against macrofauna due to their forced relocation by the Incineration. Almost all of the remaining Clams have congregated in a small den at the bottom of the sea; what makes this place unique is unknown, as few divers can withstand the ferocity of the clams in their natural abode. +Cnidrion: Once trained to be the steeds of honored Ilmerian warriors, Cnidrions fought valiantly alongside their masters during the Incineration. Though many perished unceremoniously with the warriors that commanded them, one managed to escape a fiery demise, continuing to defend what was once the heart of the sea kingdom with a fierce loyalty. +EutrophicRay: Living life as a filter feeder, the tranquil Eutrophic Ray is quick to flee from any dangers. They are aided by their commensalistic relationship with Ghost Bells, storing the latent voltage in a sac on their underbelly for electrical muscle stimulation, allowing for great bursts of speed. +GhostBell: Commonly encountered as large walls of electric power, these high-voltage jellyfish can incapacitate most with a single touch. Even when not delivering shocks to prey, they passively release a current into the surrounding water, which the old sea kingdom exploited to drive back Yharim's crusade for decades. +GiantClam: Pearls are formed from ambient mana combining with natural limestone deposits, and are claimed to be capable of storing thoughts and memories. Although most clams die and break down before their shells can act as sufficient conduits, the largest and strongest clams can gather enough mana in their pearls for direct use in feeding and defense. +HauntedChum: During the Witch's razing of Ilmeris' seas, many of the largest fish that had never known fear in their lives were foolish enough to fight back. Even in death they remain consumed by rage, attacking those who draw near, despite being as ruined as the sea itself. +Jellyghoul: The spirits of some Ilmerians were so consumed by grief and despair that, over time, their identity and memories faded away. These souls are now confined in the blank form of phantom jellyfishes, doomed to forever haunt the Timeless Shores. +KelpieSeadragon: Kelpie Seadragons enjoy hiding in the scarlet kelp fronds of the Polyp Forest, where they can observe their surroundings without being noticed. Don’t underestimate them, as their silly-looking faces can shoot highly poisonous pellets! +LostShoal: Shoals of spectral fish swim through the damp air of the Sunken shoreline, fully ignorant of their ominous demeanor and the horrible fate that befell them. +Pearlpod: Residing in the utmost depths of the Sunken Sea, these docile crustaceans consume Lantern Kelp and organic remains to survive. When curled up, their nacreous hide makes them almost identical to pearls and impervious to attacks. +PolypPanasea: The vibrant Panaseas developed a natural coating which counters the toxins of polyps, and now frequently take shelter in their tentacles. Anything that chases the fish into their home swiftly learns about the other side of this partnership. +PrismBack: Far too slow and bulky to hunt normally, these turtles subsist on a diet of purely kelp. As a result of their slow and infrequent movement, large prisms are able to accumulate on their backs, providing natural protection against threats that would not risk swallowing a razor-sharp crystal. +Probesnout: One of just a few known seahorse species who miraculously survived the Incineration. Its efficient snout allows it to streamline nutrients from the abundant sponge in the reefs that it lives in. +SandProwler: These colorful sea serpents prowl through the sand, looking for the gleam of an unsuspecting Guppy to snack on. Due to this creature’s habit of mistakenly capturing dropped coins, Ilmerians fond of avarice began to share the namesake. +SeaFloaty: Flatworms can be found in many seas and oceans across the world, and are exceptional at fitting through cracks or crevices to find kelp due to their thin bodies. These particular flatworms are incredibly skittish, and thus fled with plenty of time to be spared from the infernal carnage. +SeaMinnow: Large schools of Sea Minnows were one of the most beautiful things one could witness during the days when Ilmeris was unsundered. Though the kingdom's grandeur has been lost like ashes in the wind, the tranquil fish continue to swim at peace, a breathtaking reminder that not all was lost. +Sharkoon: The bulbous Sharkoon wanders the reefs on the outskirts of the Sunken Sea. It retaliates against threats through the unusual method of exploding a sac on its body that stores highly reactive chemicals, fleeing in the confusion caused by its shockwave. +Stormlion: Some Ilmerian survivors claim that enough magical lightning surged through the sea during its final days that there existed not a single drop of water without levin coursing through it. Even now, electricity remains buried in the sands, with several antlion species having learned to channel the former kingdom's power. //Town NPCs AndroombaFriendly: Reverse-engineered Androombas that have been retrofitted to spread the Steampunker's solutions rather than clean dust and debris off of floors. They can be used to purify the world– or ruin it further, if one so desires. DILF: One of the world's foremost experts on magical theory, he is renowned for his skill with the arcane arts. In his days when he traveled with Yharim's entourage, he acted as the Godseeker's advisor, due to both his status and his distaste for actively participating in battle. diff --git a/Localization/en-US/Mods.CalamityMod.Buffs.hjson b/Localization/en-US/Mods.CalamityMod.Buffs.hjson index d6435fa8ec..3685987a78 100644 --- a/Localization/en-US/Mods.CalamityMod.Buffs.hjson +++ b/Localization/en-US/Mods.CalamityMod.Buffs.hjson @@ -1562,3 +1562,13 @@ Voidfrost: { DisplayName: Voidfrost Description: The emptiness of space devours all warmth and life } + +FlarebatBuff: { + DisplayName: Flarebat + Description: The construct of fire will protect you +} + +FrostbatBuff: { + DisplayName: Frostbat + Description: The construct of ice will protect you +} diff --git a/Localization/en-US/Mods.CalamityMod.Configs.hjson b/Localization/en-US/Mods.CalamityMod.Configs.hjson index cdc61f30bc..4d6f6332f1 100644 --- a/Localization/en-US/Mods.CalamityMod.Configs.hjson +++ b/Localization/en-US/Mods.CalamityMod.Configs.hjson @@ -7,6 +7,7 @@ CalamityClientConfig: { UI: UI Changes MeterPositions: Meter Positions MusicEvents: In-Game Music Events + Multithreading: Multi-Threading } AdrenalineMeterPosX: { @@ -91,6 +92,15 @@ CalamityClientConfig: { Tooltip: Plays Calamity Mod OST - "Scourge of the Universe (Eulogy for the Ego)", after the Devourer of Gods has been defeated. } + EnergyShieldOpacity: { + Label: "[i:CalamityMod/TheSponge] Energy Shield Opacity" + Tooltip: + ''' + Set the opacity of energy shields rendered over the player. + Setting this to 0 disables energy shield visuals entirely. + ''' + } + FasterFallHotkey: { Label: "[i:CalamityMod/BallAndChain] Enable Fast Falling" Tooltip: @@ -316,6 +326,16 @@ CalamityClientConfig: { Label: "[i:Book] Wiki Status Message" Tooltip: Enable or disable the status message promoting the Official Calamity Wiki that plays on world entry. } + + MultiThreadingType: { + Label: Sunken Sea Multi-Threading Option + Tooltip: + ''' + Option 0 will disable worldgen multi-threading. + Option 1 will enable ReLogic's multi-threading. + Option 2 will enable custom multi-threading. + ''' + } } CalamityServerConfig: { diff --git a/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson b/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson index adedcb5598..69e037d85a 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Accessories.hjson @@ -1200,7 +1200,7 @@ OldDukeScales: { HoldShiftTooltip: ''' [c/c3dfff: Using any dash will consume 20% of your stamina] - [c/c3dfff: Stamina will gradually restore after not dashing for 1 second] + [c/c3dfff: Stamina will gradually restore after not dashing for 1.5 seconds] [c/c3dfff: Stamina recovers faster when you are stationary] [c/c3dfff: If your stamina reaches 0%, you become exhausted] [c/e3545c: While exhausted, this item's damage reduction and movement bonuses are negated] diff --git a/Localization/en-US/Mods.CalamityMod.Items.Weapons.Melee.hjson b/Localization/en-US/Mods.CalamityMod.Items.Weapons.Melee.hjson index d1ce31f223..718a849052 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Weapons.Melee.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Weapons.Melee.hjson @@ -144,7 +144,11 @@ Ataraxia: { Avalanche: { DisplayName: Avalanche - Tooltip: Spawns ice bombs that explode after 3 seconds into ice shards on hit + Tooltip: + ''' + Hitting enemies spawns orbiting ice bombs + After 2 seconds, ice bombs explode into gravity-affected ice shards + ''' } Azathoth: { @@ -334,7 +338,8 @@ DeathsAscension: { Tooltip: ''' Press to launch a barrage of homing scythes - You can feel the hands of Death himself onto yours + 'It feels just right in your grip... + [c/660066:But the hands that wield it are not yours'] ''' } @@ -499,7 +504,7 @@ FallenPaladinsHammer: { DisplayName: Fallen Paladin's Hammer Tooltip: ''' - Throws a heavy, gravity-affected hammer that will return to you after striking an enemy + Throws a heavy, gravity-affected hammer that will explode and return to you after striking an enemy After returning three times, a homing spectral hammer is summoned with devastating impact ''' } @@ -599,7 +604,7 @@ GalaxySmasher: { Tooltip: ''' Throws a heavy, gravity-affected hammer that will return to you after striking an enemy - Consecutive hits summon more and more cosmic hammers + Consecutive hits summon more and more cosmic shards After hitting eight times, the hammer supercharges itself with galactic energies, delivering an apocalyptic strike that reverberates through space and time ''' @@ -668,7 +673,11 @@ GreatswordofJudgement: { Greentide: { DisplayName: Greentide - Tooltip: Summons teeth to chomp your foes on hit + Tooltip: + ''' + Launches a spread of four teeth with one stronger piercing tooth in the center + Hitting with the blade creates two jaws of teeth to chomp on the enemy closest to your cursor + ''' } HellfireFlamberge: { diff --git a/Localization/en-US/Mods.CalamityMod.Items.Weapons.Rogue.hjson b/Localization/en-US/Mods.CalamityMod.Items.Weapons.Rogue.hjson index 5ef4505767..34589228ca 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Weapons.Rogue.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Weapons.Rogue.hjson @@ -100,15 +100,6 @@ BouncySpikyBall: { ''' } -BrackishFlask: { - DisplayName: Brackish Flask - Tooltip: - ''' - Throws a flask that explodes into poisonous seawater blasts - Stealth strikes summon a brackish spear spike - ''' -} - Brimblade: { DisplayName: Brimblade Tooltip: @@ -646,7 +637,7 @@ Kylie: { DisplayName: Kylie Tooltip: ''' - Stealth strikes throws three shorter ranged kylies instead of a single long range one + Stealth strikes throw a kylie that weakly seeks out your cursor 'Also known as Dowak' ''' } @@ -674,9 +665,9 @@ LeviathanTeeth: { DisplayName: Leviathan Teeth Tooltip: ''' - Rapidly throws a spread of venomous teeth that stick to enemies - This venom can stack when more teeth are stuck in an enemy - Stealth strikes cause 6 very fast teeth to be thrown, ignoring gravity and spawning water blasts on hit + Rapidly throws a spread of teeth that stick into enemies + After sticking to an enemy, the teeth will gouge through them and shoot out the other side + Stealth strikes throw a single piercing tooth that creates a jawline of teeth to maul your foes ''' } @@ -914,9 +905,9 @@ RefractionRotor: { DisplayName: Refraction Rotor Tooltip: ''' - Fires a huge prismatic disk shuriken - The shuriken shatters moments after impact into homing rockets - Stealth strikes shatter into many more rockets + Throws a huge prismatic shuriken + The shuriken shatters moments after impact into homing blades + Stealth strikes throw 3 shurikens that rapidly home on enemies ''' } @@ -1396,6 +1387,18 @@ WebBall: { ''' } +Whitewater: { + DisplayName: Whitewater + Tooltip: + ''' + Throws a flask of magic whitewater that tracks your cursor + After a second, the flask will glow brightly + Flasks that hit enemies while glowing create a temporary burst of returning water spears + After exploding or after being thrown for a while, the flask will return to you + Stealth strikes create more water spears and will make a swirling vortex of whitewater that heals any player it touches and knocks back enemies + ''' +} + Wrathwing: { DisplayName: Wrathwing Tooltip: diff --git a/Localization/en-US/Mods.CalamityMod.Items.Weapons.Summon.hjson b/Localization/en-US/Mods.CalamityMod.Items.Weapons.Summon.hjson index f60e9dc57e..46bf3b5200 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Weapons.Summon.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Weapons.Summon.hjson @@ -884,3 +884,21 @@ YharonsKindleStaff: { Requires 5 minion slots to use ''' } + +FlarebatStaff: { + DisplayName: Flarebat Staff + Tooltip: + ''' + Summons a bat construct of pure fire to fight for you + Swoops towards foes with great haste + ''' +} + +FrostbatStaff: { + DisplayName: Frostbat Staff + Tooltip: + ''' + Summons a bat construct of pure ice to fight for you + Swoops towards foes with slow and precise maneuvers + ''' +} diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson index 8f2eb817b0..8c875aa522 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson @@ -130,7 +130,7 @@ GalaxyBlastType3.DisplayName: Galaxy Blast GalaxySmasherBlast.DisplayName: Galactic Blast GalaxySmasherEcho.DisplayName: Galaxy Smasher Echo GalaxySmasherHammer.DisplayName: Galaxy Smasher -GalaxySmasherMini.DisplayName: Galaxy Smasher +GalaxySmasherMini.DisplayName: Cosmic Shard GalileosMoon.DisplayName: Crescent Moon GalileosPlanet.DisplayName: Planet GayBeam.DisplayName: Iridescent Beam @@ -298,3 +298,4 @@ WulfrumScrew.DisplayName: Wulfrum Screw WulfrumScrewdriverProj.DisplayName: Wulfrum Screwdriver YinYoDark.DisplayName: Dark Shard YinYoLight.DisplayName: Light Shard +FallenExplosionSmall.DisplayName: Fallen Hammer Blast diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson index 06072adc94..def4f53730 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson @@ -247,3 +247,4 @@ WulfrumScrapBullet.DisplayName: High Speed Scrap HellbornProj.DisplayName: Hell-born Gunblast HellbornShell.DisplayName: Hell's Shell RubicoPrimeMag.DisplayName: Rubico Prime Mag +MegalodonShot.DisplayName: Megalodon Shot diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson index 3a10c4666b..82c4f549fb 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson @@ -23,10 +23,6 @@ BlunderBoosterLightning.DisplayName: Blunder Bolt BouncingEyeballProjectile.DisplayName: Bouncy Eyeball BouncingEyeballProjectileStealthStrike.DisplayName: Bouncy Eyeball BouncyBol.DisplayName: Bouncy Ball -BrackishFlaskProj.DisplayName: Brackish Flask -BrackishSpear.DisplayName: Not Atlantis Spear -BrackishWater.DisplayName: Brackish Water -BrackishWaterBlast.DisplayName: Brackish Water Brick.DisplayName: Brick BrickFragment.DisplayName: Brick Fragment Brimblade2.DisplayName: Brimblade @@ -322,9 +318,14 @@ ValedictionBoomerang.DisplayName: Valediction VeneratedKnife.DisplayName: Venerated Knife WaveSkipperProjectile.DisplayName: Wave Skipper WebBallBol.DisplayName: Web Ball +WhitewaterAura.DisplayName: Whitewater Aura +WhitewaterProj.DisplayName: Whitewater Flask +WhitewaterSpear.DisplayName: Whitewater Spear WrathwingCinder.DisplayName: Wrathwing Eruption WrathwingFireball.DisplayName: Wrathwing Fireball WrathwingSpear.DisplayName: Wrathwing WulfrumKnifeProj.DisplayName: Wulfrum Knife RadiationBurst.DisplayName: Radiation Burst RadiationRain.DisplayName: Radiation Rain +RefractionRotorSlashCreator.DisplayName: Refraction Rotor Slash Creator +RefractionSlash.DisplayName: Refraction Slash diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Summon.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Summon.hjson index 7ae4b8d809..ba8e932d86 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Summon.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Summon.hjson @@ -330,3 +330,5 @@ WulfrumDroid.DisplayName: Wulfrum Droid WulfrumEnergyBurst.DisplayName: Wulfrum Bolt WulfrumFusionBolt.DisplayName: Fusion Bolt YharonMinionFireball.DisplayName: Dragon Fireball +FlarebatMinion.DisplayName: Flarebat +FrostbatMinion.DisplayName: Frostbat diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Typeless.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Typeless.hjson index 25cee1b8e7..74857bef16 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Typeless.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Typeless.hjson @@ -133,3 +133,4 @@ WulfrumHook.DisplayName: Wulfrum Slingshot WulfrumLureSignal.DisplayName: Signal YanmeisKnifeSlash.DisplayName: Yanmei's Knife YellowLabSeeker.DisplayName: Seeking Mechanism +VoidofExtinctionCrit.DisplayName: Void of Extinction Crit diff --git a/NPCs/Abyss/SlabCrab.cs b/NPCs/Abyss/SlabCrab.cs index 16962f9714..6d932379ea 100644 --- a/NPCs/Abyss/SlabCrab.cs +++ b/NPCs/Abyss/SlabCrab.cs @@ -4,6 +4,7 @@ using CalamityMod.BiomeManagers; using CalamityMod.Buffs.DamageOverTime; using CalamityMod.Items.Placeables; using CalamityMod.Items.Placeables.Banners; +using CalamityMod.Packets; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; @@ -290,11 +291,7 @@ namespace CalamityMod.NPCs.Abyss } else { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SyncSlabCrabAI); - netMessage.Write(NPC.whoAmI); - netMessage.Write((int)phase); - netMessage.Send(); + SyncSlabCrabAIPacket.Send(this, phase: (int)phase); } } diff --git a/NPCs/CalamityAIs/CalamityBossAIs/AstrumDeusAI.cs b/NPCs/CalamityAIs/CalamityBossAIs/AstrumDeusAI.cs index 826432bb36..8949910384 100644 --- a/NPCs/CalamityAIs/CalamityBossAIs/AstrumDeusAI.cs +++ b/NPCs/CalamityAIs/CalamityBossAIs/AstrumDeusAI.cs @@ -17,6 +17,7 @@ using CalamityMod.NPCs.NormalNPCs; using CalamityMod.NPCs.OldDuke; using CalamityMod.NPCs.SulphurousSea; using CalamityMod.NPCs.SunkenSea; +using CalamityMod.Packets; using CalamityMod.Projectiles.Boss; using CalamityMod.Projectiles.Enemy; using CalamityMod.Sounds; @@ -220,14 +221,7 @@ namespace CalamityMod.NPCs.CalamityAIs.CalamityBossAIs // On server, immediately send the correct extra AI of this head to clients. if (Main.netMode == NetmodeID.Server) { - var netMessage = mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SyncCalamityNPCAIArray); - netMessage.Write((byte)headOneID); - netMessage.Write(Main.npc[headOneID].Calamity().newAI[0]); - netMessage.Write(Main.npc[headOneID].Calamity().newAI[1]); - netMessage.Write(Main.npc[headOneID].Calamity().newAI[2]); - netMessage.Write(Main.npc[headOneID].Calamity().newAI[3]); - netMessage.Send(); + SyncCalamityNPCAIArrayPacket.Send(Main.npc[headOneID]); } // Make sure the second split worm is also contiguous. @@ -243,14 +237,7 @@ namespace CalamityMod.NPCs.CalamityAIs.CalamityBossAIs // On server, immediately send the correct extra AI of this head to clients. if (Main.netMode == NetmodeID.Server) { - var netMessage = mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SyncCalamityNPCAIArray); - netMessage.Write((byte)headTwoID); - netMessage.Write(Main.npc[headTwoID].Calamity().newAI[0]); - netMessage.Write(Main.npc[headTwoID].Calamity().newAI[1]); - netMessage.Write(Main.npc[headTwoID].Calamity().newAI[2]); - netMessage.Write(Main.npc[headTwoID].Calamity().newAI[3]); - netMessage.Send(); + SyncCalamityNPCAIArrayPacket.Send(Main.npc[headTwoID]); } } @@ -382,14 +369,7 @@ namespace CalamityMod.NPCs.CalamityAIs.CalamityBossAIs if (Main.netMode == NetmodeID.Server) { - var netMessage = mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SyncCalamityNPCAIArray); - netMessage.Write((byte)lol); - netMessage.Write(Main.npc[lol].Calamity().newAI[0]); - netMessage.Write(Main.npc[lol].Calamity().newAI[1]); - netMessage.Write(Main.npc[lol].Calamity().newAI[2]); - netMessage.Write(Main.npc[lol].Calamity().newAI[3]); - netMessage.Send(); + SyncCalamityNPCAIArrayPacket.Send(Main.npc[lol]); } Main.npc[lol].ai[2] = npc.whoAmI; diff --git a/NPCs/CalamityGlobalNPC.cs b/NPCs/CalamityGlobalNPC.cs index b860cb2446..69299c1688 100644 --- a/NPCs/CalamityGlobalNPC.cs +++ b/NPCs/CalamityGlobalNPC.cs @@ -82,6 +82,7 @@ using Terraria.UI.Chat; using Terraria.Utilities; using static Terraria.ModLoader.ModContent; using CalamityMod.NPCs.SunkenSea; +using CalamityMod.Packets; namespace CalamityMod.NPCs { @@ -8326,33 +8327,32 @@ namespace CalamityMod.NPCs // has an owner, hence the MyPlayer check. if (Main.myPlayer == projectile.owner) { + if (!player.active || player.dead) + return; + + Projectile proj = null; + foreach (Projectile p in Main.ActiveProjectiles) + { + proj = p; + if (p.bobber && p.owner == player.whoAmI) + { + break; + } + } + + if (proj is null) + return; + + var spawnPosX = (int)proj.Center.X; + var spawnPosY = (int)proj.Center.Y + 100; if (Main.netMode == NetmodeID.SinglePlayer) { - if (!player.active || player.dead) - return; - - Projectile proj = null; - foreach (Projectile p in Main.ActiveProjectiles) - { - proj = p; - if (p.bobber && p.owner == player.whoAmI) - { - break; - } - } - - if (proj is null) - return; - - int oldDuke = NPC.NewNPC(NPC.GetBossSpawnSource(player.whoAmI), (int)proj.Center.X, (int)proj.Center.Y + 100, NPCType()); + int oldDuke = NPC.NewNPC(NPC.GetBossSpawnSource(player.whoAmI), spawnPosX, spawnPosY, NPCType()); CalamityUtils.BossAwakenMessage(oldDuke); } - else + else if (Main.netMode == NetmodeID.MultiplayerClient) { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.ServersideSpawnOldDuke); - netMessage.Write((byte)player.whoAmI); - netMessage.Send(); + SpawnBossOnPositionPacket.Send(spawnPosX, spawnPosY, NPCType(), player); } } } diff --git a/NPCs/CalamityGlobalNPCLoot.cs b/NPCs/CalamityGlobalNPCLoot.cs index 0b3b994bc6..5f4225a45c 100644 --- a/NPCs/CalamityGlobalNPCLoot.cs +++ b/NPCs/CalamityGlobalNPCLoot.cs @@ -195,6 +195,13 @@ namespace CalamityMod.NPCs #endregion #region Ice + + // Ice Bat. + // Frostbat Staff @ 6.67% + case NPCID.IceBat: + npcLoot.Add(ModContent.ItemType(), 15); + break; + // Icy Merman, Icy Tortoise, Ice Elemental, Wolf // Essence of Eleum @ 100% case NPCID.IcyMerman: @@ -408,6 +415,13 @@ namespace CalamityMod.NPCs #endregion #region Hell + + // Hellbat. + // Flarebat Staff @ 4% + case NPCID.Hellbat: + npcLoot.Add(ModContent.ItemType(), 25); + break; + // Fire Imp // Ashen Stalactite @ 10% Normal, 16.67% Expert+ case NPCID.FireImp: diff --git a/NPCs/ExoMechs/Draedon.cs b/NPCs/ExoMechs/Draedon.cs index d0b90f2ba2..305940498b 100644 --- a/NPCs/ExoMechs/Draedon.cs +++ b/NPCs/ExoMechs/Draedon.cs @@ -4,6 +4,7 @@ using CalamityMod.Events; using CalamityMod.Items.Weapons.DraedonsArsenal; using CalamityMod.NPCs.ExoMechs.Ares; using CalamityMod.NPCs.ExoMechs.Thanatos; +using CalamityMod.Packets; using CalamityMod.Sounds; using CalamityMod.World; using Microsoft.Xna.Framework; @@ -222,12 +223,7 @@ namespace CalamityMod.NPCs.ExoMechs CalamityWorld.DraedonMechdusa = false; if (Main.netMode != NetmodeID.SinglePlayer) { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.CodebreakerSummonStuff); - netMessage.Write(CalamityWorld.DraedonSummonCountdown); - netMessage.WriteVector2(CalamityWorld.DraedonSummonPosition); - netMessage.Write(CalamityWorld.DraedonMechdusa); - netMessage.Send(); + CodebreakerSummonStuffPacket.Send(); } } @@ -336,10 +332,7 @@ namespace CalamityMod.NPCs.ExoMechs if (Main.netMode != NetmodeID.SinglePlayer) { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.ExoMechSelection); - netMessage.Write((int)CalamityWorld.DraedonMechToSummon); - netMessage.Send(); + ExoMechSelectionPacket.Send(); } } } diff --git a/NPCs/Leviathan/Leviathan.cs b/NPCs/Leviathan/Leviathan.cs index c6ac66eec0..1d1a80c42c 100644 --- a/NPCs/Leviathan/Leviathan.cs +++ b/NPCs/Leviathan/Leviathan.cs @@ -870,7 +870,7 @@ namespace CalamityMod.NPCs.Leviathan ModContent.ItemType(), ModContent.ItemType(), ModContent.ItemType(), - ModContent.ItemType(), + ModContent.ItemType(), ModContent.ItemType() }; normalOnly.Add(DropHelper.CalamityStyle(DropHelper.NormalWeaponDropRateFraction, items)); diff --git a/NPCs/Providence/Providence.cs b/NPCs/Providence/Providence.cs index 97ce46fff2..fc90826d2f 100644 --- a/NPCs/Providence/Providence.cs +++ b/NPCs/Providence/Providence.cs @@ -24,6 +24,7 @@ using CalamityMod.Items.Weapons.Melee; using CalamityMod.Items.Weapons.Ranged; using CalamityMod.Items.Weapons.Rogue; using CalamityMod.Items.Weapons.Summon; +using CalamityMod.Packets; using CalamityMod.Particles; using CalamityMod.Projectiles.Boss; using CalamityMod.Projectiles.Summon; @@ -2584,11 +2585,7 @@ namespace CalamityMod.NPCs.Providence if (Main.netMode != NetmodeID.SinglePlayer) { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.ProvidenceDyeConditionSync); - netMessage.Write((byte)NPC.whoAmI); - netMessage.Write(hasTakenDaytimeDamage); - netMessage.Send(); + ProvidenceDyeConditionSyncPacket.Send(this); } } } @@ -2624,11 +2621,7 @@ namespace CalamityMod.NPCs.Providence if (Main.netMode != NetmodeID.SinglePlayer) { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.PSCChallengeSync); - netMessage.Write((byte)NPC.whoAmI); - netMessage.Write(challenge); - netMessage.Send(); + PSCChallengeSyncPacket.Send(this); } } } @@ -2644,11 +2637,7 @@ namespace CalamityMod.NPCs.Providence if (Main.netMode != NetmodeID.SinglePlayer) { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.ProvidenceDyeConditionSync); - netMessage.Write((byte)NPC.whoAmI); - netMessage.Write(hasTakenDaytimeDamage); - netMessage.Send(); + ProvidenceDyeConditionSyncPacket.Send(this); } } } @@ -2659,11 +2648,7 @@ namespace CalamityMod.NPCs.Providence if (Main.netMode != NetmodeID.SinglePlayer) { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.PSCChallengeSync); - netMessage.Write((byte)NPC.whoAmI); - netMessage.Write(challenge); - netMessage.Send(); + PSCChallengeSyncPacket.Send(this); } } } diff --git a/NPCs/SunkenSea/SandProwler.cs b/NPCs/SunkenSea/SandProwler.cs index 38c002c8d3..57a4fb4d21 100644 --- a/NPCs/SunkenSea/SandProwler.cs +++ b/NPCs/SunkenSea/SandProwler.cs @@ -107,7 +107,7 @@ namespace CalamityMod.NPCs.SunkenSea { bestiaryEntry.Info.AddRange(new IBestiaryInfoElement[] { - new FlavorTextBestiaryInfoElement("Mods.CalamityMod.Bestiary.SeaSerpent") + new FlavorTextBestiaryInfoElement("Mods.CalamityMod.Bestiary.SandProwler") }); } public override bool? DrawHealthBar(byte hbPosition, ref float scale, ref Vector2 position) diff --git a/NPCs/TownNPCs/AndroombaFriendly.cs b/NPCs/TownNPCs/AndroombaFriendly.cs index a1c3038966..30516e97c9 100644 --- a/NPCs/TownNPCs/AndroombaFriendly.cs +++ b/NPCs/TownNPCs/AndroombaFriendly.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using CalamityMod.BiomeManagers; using CalamityMod.Items.Critters; +using CalamityMod.Packets; using CalamityMod.World; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; @@ -166,11 +167,7 @@ namespace CalamityMod.NPCs.TownNPCs } else { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SyncAndroombaAI); - netMessage.Write(NPC.whoAmI); - netMessage.Write(phase); - netMessage.Send(); + SyncAndroombaAIPacket.Send(this, phase: phase); } } diff --git a/NPCs/TownNPCs/THIEF.cs b/NPCs/TownNPCs/THIEF.cs index 9433ea95d2..1f46f4fe14 100644 --- a/NPCs/TownNPCs/THIEF.cs +++ b/NPCs/TownNPCs/THIEF.cs @@ -3,6 +3,7 @@ using CalamityMod.Items; using CalamityMod.Items.Accessories; using CalamityMod.Items.Pets; using CalamityMod.Items.Weapons.Rogue; +using CalamityMod.Packets; using CalamityMod.Projectiles.Rogue; using CalamityMod.World; using Microsoft.Xna.Framework; @@ -231,10 +232,7 @@ namespace CalamityMod.NPCs.TownNPCs // // Other way possible is to having bandit stolen inventory per player // But I didn't wanted to change system too much - ModPacket packet = CalamityMod.Instance.GetPacket(); - packet.Write((byte)CalamityModMessageType.WantToRefundReforges); - packet.Write((byte)Main.myPlayer); - packet.Send(); + WantToRefundReforgesPacket.Send(); } SoundEngine.PlaySound(SoundID.Coins); // Money dink sound @@ -309,12 +307,11 @@ namespace CalamityMod.NPCs.TownNPCs NPCShop shop = new(Type); shop.AddWithCustomValue(ModContent.ItemType(), Item.buyPrice(gold: 9)) .AddWithCustomValue(ModContent.ItemType(), Item.buyPrice(gold: 9)) - .AddWithCustomValue(ModContent.ItemType(), Item.buyPrice(gold: 9)) + .AddWithCustomValue(ModContent.ItemType(), Item.buyPrice(gold: 25)) .AddWithCustomValue(ModContent.ItemType(), Item.buyPrice(gold: 40)) .Add(ItemID.TigerClimbingGear) .AddWithCustomValue(ItemID.InvisibilityPotion, Item.buyPrice(silver: 25), potionSells, Condition.HappyEnough) .AddWithCustomValue(ItemID.NightOwlPotion, Item.buyPrice(silver: 25), potionSells, Condition.HappyEnough) - .AddWithCustomValue(ModContent.ItemType(), Item.buyPrice(gold: 25)) .Add(ModContent.ItemType(), Condition.DownedPirates) .AddWithCustomValue(ModContent.ItemType(), Item.buyPrice(gold: 60), Condition.DownedMechBossAll) .Add(ModContent.ItemType(), downedCalclone) diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/EaterOfWorldsAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/EaterOfWorldsAI.cs index b25c05be66..6018e8964a 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/EaterOfWorldsAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/EaterOfWorldsAI.cs @@ -1,5 +1,6 @@ using System; using CalamityMod.Events; +using CalamityMod.Packets; using CalamityMod.Projectiles.Boss; using CalamityMod.World; using Microsoft.Xna.Framework; @@ -761,14 +762,7 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses // Manually sync newAI because there is no GlobalNPC.SendExtraAI if (npc.active && npc.netUpdate && Main.netMode == NetmodeID.Server) { - ModPacket packet = mod.GetPacket(); - packet.Write((byte)CalamityModMessageType.SyncCalamityNPCAIArray); - packet.Write((byte)npc.whoAmI); - packet.Write(calamityGlobalNPC.newAI[0]); - packet.Write(calamityGlobalNPC.newAI[1]); - packet.Write(calamityGlobalNPC.newAI[2]); - packet.Write(calamityGlobalNPC.newAI[3]); - packet.Send(-1, -1); + SyncCalamityNPCAIArrayPacket.Send(npc); } return false; diff --git a/Packets/CalamityPacket.cs b/Packets/CalamityPacket.cs new file mode 100644 index 0000000000..b21d3795b1 --- /dev/null +++ b/Packets/CalamityPacket.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Packets +{ + public abstract class CalamityPacket + { + public abstract byte MessageType { get; } + public abstract void HandlePacket(in BinaryReader packet, int sender); + + public virtual void OnLoaded() { } + public virtual void OnUnloaded() { } + + internal PropertyInfo _Prop_Static_Instance; + + public void CloneAndBroadcast(in BinaryReader packet, long startIndex, int length, int ignoreClient = -1) + { + if (!Main.dedServ) + return; + + if (startIndex < 0) + return; + + packet.BaseStream.Position = startIndex; + + // Limit stackalloc size to 256 bytes + Span buffer = length <= 256 ? stackalloc byte[length] : new byte[length]; + packet.BaseStream.Read(buffer); + + var newPacket = CreateBasePacket(); + newPacket.Write(buffer); + newPacket.Send(ignoreClient); + } + + public ModPacket CreateBasePacket() + { + var packet = CalamityMod.Instance.GetPacket(); + packet.Write(MessageType); + return packet; + } + } +} diff --git a/Packets/Draedon/CodebreakerSummonStuffPacket.cs b/Packets/Draedon/CodebreakerSummonStuffPacket.cs new file mode 100644 index 0000000000..652eca0e97 --- /dev/null +++ b/Packets/Draedon/CodebreakerSummonStuffPacket.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.World; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class CodebreakerSummonStuffPacket : CalamityPacket + { + public static CodebreakerSummonStuffPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.CodebreakerSummonStuff; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write(CalamityWorld.DraedonSummonCountdown); + packet.WriteVector2(CalamityWorld.DraedonSummonPosition); + packet.Write(CalamityWorld.DraedonMechdusa); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + CalamityWorld.DraedonSummonCountdown = packet.ReadInt32(); + CalamityWorld.DraedonSummonPosition = packet.ReadVector2(); + CalamityWorld.DraedonMechdusa = packet.ReadBoolean(); + } + } +} diff --git a/Packets/Draedon/ExoMechSelectionPacket.cs b/Packets/Draedon/ExoMechSelectionPacket.cs new file mode 100644 index 0000000000..c49253b0b4 --- /dev/null +++ b/Packets/Draedon/ExoMechSelectionPacket.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.World; + +namespace CalamityMod.Packets +{ + public sealed class ExoMechSelectionPacket : CalamityPacket + { + public static ExoMechSelectionPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.ExoMechSelection; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write((int)CalamityWorld.DraedonMechToSummon); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + CalamityWorld.DraedonMechToSummon = (ExoMech)packet.ReadInt32(); + } + } +} diff --git a/Packets/Entities/Androomba/SyncAndroombaAIPacket.cs b/Packets/Entities/Androomba/SyncAndroombaAIPacket.cs new file mode 100644 index 0000000000..96ccf4b5be --- /dev/null +++ b/Packets/Entities/Androomba/SyncAndroombaAIPacket.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.NPCs.DraedonLabThings; +using CalamityMod.NPCs.TownNPCs; +using Microsoft.Build.Execution; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class SyncAndroombaAIPacket : CalamityPacket + { + public static SyncAndroombaAIPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncAndroombaAI; + + public static void Send(AndroombaFriendly roomba, int phase = -1, int toClient = -1, int ignoreClient = -1) + { + if (roomba is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(roomba); + packet.Write(phase != -1 ? phase : (int)roomba.NPC.ai[0]); // Phase + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var roomba = packet.ReadModNPC(); + var phase = packet.ReadInt32(); + + if (roomba is null) + return; + + if (Main.dedServ) + AndroombaFriendly.ChangeAI(roomba.NPC.whoAmI, phase); + } + } +} diff --git a/Packets/Entities/Androomba/SyncAndroombaSolutionPacket.cs b/Packets/Entities/Androomba/SyncAndroombaSolutionPacket.cs new file mode 100644 index 0000000000..e6ac9e69f8 --- /dev/null +++ b/Packets/Entities/Androomba/SyncAndroombaSolutionPacket.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.NPCs.TownNPCs; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class SyncAndroombaSolutionPacket : CalamityPacket + { + public static SyncAndroombaSolutionPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncAndroombaSolution; + + public static void Send(AndroombaFriendly roomba, int solType = -1, int toClient = -1, int ignoreClient = -1) + { + if (roomba is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(roomba); + packet.Write(solType != -1 ? solType : (int)roomba.NPC.ai[3]); // Solution + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var roomba = packet.ReadModNPC(); + var solution = packet.ReadInt32(); + + if (roomba is null) + return; + + if (Main.dedServ) + AndroombaFriendly.SwapSolution(roomba.NPC.whoAmI, solution); + } + } +} diff --git a/Packets/Entities/PlaceAltCritterPacket.cs b/Packets/Entities/PlaceAltCritterPacket.cs new file mode 100644 index 0000000000..fe85f6574e --- /dev/null +++ b/Packets/Entities/PlaceAltCritterPacket.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Terraria.ID; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class PlaceAltCritterPacket : CalamityPacket + { + public static PlaceAltCritterPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.PlaceAltCritter; + + /// + /// Same Method, but uses critterItem.makeNPC and critterItem.type for shorthanded call + /// + public static void Send(Player placer, int x, int y, Item critterItem, int colorType, int toClient = -1, int ignoreClient = -1) + { + if (critterItem is null) + return; + + Send(placer, x, y, critterItem.makeNPC, critterItem.type, colorType, toClient, ignoreClient); + } + + public static void Send(Player placer, int x, int y, int critterNPCType, int itemType, int colorType, int toClient = -1, int ignoreClient = -1) + { + if (placer is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(placer); + packet.Write(x); + packet.Write(y); + packet.Write(critterNPCType); + packet.Write(itemType); + packet.Write(colorType); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var placerplayer = packet.ReadPlayer(); + int posX = packet.ReadInt32(); + int posY = packet.ReadInt32(); + int type = packet.ReadInt32(); + int itemType = packet.ReadInt32(); + float color = packet.ReadInt32(); + if (Main.dedServ && placerplayer is not null) + { + int newNPCIndex = NPC.NewNPC(placerplayer.GetSource_ReleaseEntity(), posX, posY, type, ai1: color); + if (newNPCIndex >= Main.maxNPCs) + return; + + var npc = Main.npc[newNPCIndex]; + npc.catchItem = itemType; + npc.releaseOwner = (short)placerplayer.whoAmI; + CalamityNetcode.SyncNPC(npc); // releaseOwner should be synced in here + } + } + } +} diff --git a/Packets/Entities/Providence/PSCChallengeSyncPacket.cs b/Packets/Entities/Providence/PSCChallengeSyncPacket.cs new file mode 100644 index 0000000000..4aa85f4e3d --- /dev/null +++ b/Packets/Entities/Providence/PSCChallengeSyncPacket.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.NPCs.Providence; + +namespace CalamityMod.Packets +{ + public sealed class PSCChallengeSyncPacket : CalamityPacket + { + public static PSCChallengeSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.PSCChallengeSync; + + public static void Send(Providence providence, int toClient = -1, int ignoreClient = -1) + { + if (providence is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(providence); + packet.Write(providence.challenge); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var providence = packet.ReadModNPC(); + var challenge = packet.ReadBoolean(); + + if (providence is null) + return; + + providence.challenge = challenge; + } + } +} diff --git a/Packets/Entities/Providence/ProvidenceDyeConditionSyncPacket.cs b/Packets/Entities/Providence/ProvidenceDyeConditionSyncPacket.cs new file mode 100644 index 0000000000..c2ca88ae9f --- /dev/null +++ b/Packets/Entities/Providence/ProvidenceDyeConditionSyncPacket.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.NPCs.Providence; + +namespace CalamityMod.Packets +{ + public sealed class ProvidenceDyeConditionSyncPacket : CalamityPacket + { + public static ProvidenceDyeConditionSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.ProvidenceDyeConditionSync; + + public static void Send(Providence providence, int toClient = -1, int ignoreClient = -1) + { + if (providence is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(providence); + packet.Write(providence.hasTakenDaytimeDamage); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var providence = packet.ReadModNPC(); + var hasTakenDaytimeDmg = packet.ReadBoolean(); + + if (providence is null) + return; + + providence.hasTakenDaytimeDamage = hasTakenDaytimeDmg; + } + } +} diff --git a/Packets/Entities/SlabCrab/SyncSlabCrabAIPacket.cs b/Packets/Entities/SlabCrab/SyncSlabCrabAIPacket.cs new file mode 100644 index 0000000000..1c7b9f77d2 --- /dev/null +++ b/Packets/Entities/SlabCrab/SyncSlabCrabAIPacket.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.NPCs.Abyss; +using CalamityMod.NPCs.TownNPCs; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class SyncSlabCrabAIPacket : CalamityPacket + { + public static SyncSlabCrabAIPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncSlabCrabAI; + + public static void Send(SlabCrab crab, int phase = -1, int toClient = -1, int ignoreClient = -1) + { + if (crab is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(crab); + packet.Write(phase != -1 ? phase : (int)crab.NPC.ai[0]); // Phase + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var crab = packet.ReadModNPC(); + var phase = packet.ReadInt32(); + + if (crab is null) + return; + + if (Main.dedServ) + crab.ChangePhase(phase); + } + } +} diff --git a/Packets/Entities/SpawnBossOnPositionPacket.cs b/Packets/Entities/SpawnBossOnPositionPacket.cs new file mode 100644 index 0000000000..33c4ef8f2e --- /dev/null +++ b/Packets/Entities/SpawnBossOnPositionPacket.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; + +namespace CalamityMod.Packets +{ + public sealed class SpawnBossOnPositionPacket : CalamityPacket + { + public static SpawnBossOnPositionPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SpawnBossOnPosition; + + public static void Send(int x, int y, int npcType, Player target = null, int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write(x); + packet.Write(y); + packet.Write(npcType); + packet.Write((byte)(target?.whoAmI ?? byte.MaxValue)); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var x = packet.ReadInt32(); + var y = packet.ReadInt32(); + var npcType = packet.ReadInt32(); + var target = packet.ReadPlayer(); + var targetIndex = target?.whoAmI ?? 255; + + if (!Main.dedServ) + return; + + int spawnedNPCIdx = NPC.NewNPC(NPC.GetBossSpawnSource(targetIndex), x, y, npcType, Start: 1); + if (spawnedNPCIdx >= Main.maxNPCs) + return; + + NPC npc = Main.npc[spawnedNPCIdx]; + npc.timeLeft *= 20; + npc.target = targetIndex; + + CalamityUtils.BossAwakenMessage(spawnedNPCIdx); + CalamityNetcode.SyncNPC(npc); + } + } +} diff --git a/Packets/Entities/SpawnNPCOnPlayerPacket.cs b/Packets/Entities/SpawnNPCOnPlayerPacket.cs new file mode 100644 index 0000000000..a256aa4c57 --- /dev/null +++ b/Packets/Entities/SpawnNPCOnPlayerPacket.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class SpawnNPCOnPlayerPacket : CalamityPacket + { + public static SpawnNPCOnPlayerPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SpawnNPCOnPlayer; + + public static void Send(Player player, int x, int y, int npcType, int toClient = -1, int ignoreClient = -1) + { + if (player is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(player); + packet.Write(x); + packet.Write(y); + packet.Write(npcType); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var player = packet.ReadPlayer(); + var x = packet.ReadInt32(); + var y = packet.ReadInt32(); + var npcType = packet.ReadInt32(); + + if (player is null) + return; + + if (Main.dedServ) + { + int spawnedNPC = NPC.NewNPC(new EntitySource_WorldEvent(), x, y, npcType, Target: player.whoAmI); + if (spawnedNPC >= Main.maxNPCs) + return; + + CalamityNetcode.SyncNPC(spawnedNPC); + } + } + } +} diff --git a/Packets/Entities/SuperDummy/DeleteAllSuperDummiesPacket.cs b/Packets/Entities/SuperDummy/DeleteAllSuperDummiesPacket.cs new file mode 100644 index 0000000000..3ea889f024 --- /dev/null +++ b/Packets/Entities/SuperDummy/DeleteAllSuperDummiesPacket.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Items; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class DeleteAllSuperDummiesPacket : CalamityPacket + { + public static DeleteAllSuperDummiesPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.DeleteAllSuperDummies; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + // There is nothing in the packet! We only need to call delete method on Server + if (Main.dedServ) + SuperDummy.DeleteDummies(); + } + } +} diff --git a/Packets/Entities/SuperDummy/SpawnSuperDummyPacket.cs b/Packets/Entities/SuperDummy/SpawnSuperDummyPacket.cs new file mode 100644 index 0000000000..9eac863d7e --- /dev/null +++ b/Packets/Entities/SuperDummy/SpawnSuperDummyPacket.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.NPCs.NormalNPCs; +using Terraria; +using Terraria.DataStructures; +using Terraria.ModLoader; + +namespace CalamityMod.Packets +{ + public sealed class SpawnSuperDummyPacket : CalamityPacket + { + public static SpawnSuperDummyPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SpawnSuperDummy; + + public static void Send(int x, int y, int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write(x); + packet.Write(y); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var x = packet.ReadInt32(); + var y = packet.ReadInt32(); + + // Not strictly necessary, but helps prevent unnecessary packetstorm in MP + if (Main.dedServ) + NPC.NewNPC(new EntitySource_WorldEvent(), x, y, ModContent.NPCType()); + } + } +} diff --git a/Packets/Entities/SyncCalamityNPCAIArrayPacket.cs b/Packets/Entities/SyncCalamityNPCAIArrayPacket.cs new file mode 100644 index 0000000000..8603df26ac --- /dev/null +++ b/Packets/Entities/SyncCalamityNPCAIArrayPacket.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class SyncCalamityNPCAIArrayPacket : CalamityPacket + { + // MIGRATED COMMENTS FROM: 'CalamityNetcode.cs' + // - This code has been edited to fail gracefully when trying to provide data for an invalid NPC. + + public static SyncCalamityNPCAIArrayPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncCalamityNPCAIArray; + + public static void Send(NPC npc, int toClient = -1, int ignoreClient = -1) + { + if (npc is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(npc); + + var calNPC = npc.Calamity(); + packet.Write(calNPC.newAI[0]); + packet.Write(calNPC.newAI[1]); + packet.Write(calNPC.newAI[2]); + packet.Write(calNPC.newAI[3]); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var npc = packet.ReadNPC(); + var ai0 = packet.ReadSingle(); + var ai1 = packet.ReadSingle(); + var ai2 = packet.ReadSingle(); + var ai3 = packet.ReadSingle(); + + if (npc is null) + return; + + var calNPC = npc.Calamity(); + calNPC.newAI[0] = ai0; + calNPC.newAI[1] = ai1; + calNPC.newAI[2] = ai2; + calNPC.newAI[3] = ai3; + } + } +} diff --git a/Packets/Entities/SyncNPCMotionDataToServerPacket.cs b/Packets/Entities/SyncNPCMotionDataToServerPacket.cs new file mode 100644 index 0000000000..0b86cd640e --- /dev/null +++ b/Packets/Entities/SyncNPCMotionDataToServerPacket.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Terraria; +using Terraria.ID; + +namespace CalamityMod.Packets +{ + public sealed class SyncNPCMotionDataToServerPacket : CalamityPacket + { + public static SyncNPCMotionDataToServerPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncNPCMotionDataToServer; + + public static void Send(NPC npc, int toClient = -1, int ignoreClient = -1) + { + if (npc is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(npc); + packet.WriteVector2(npc.Center); + packet.WriteVector2(npc.velocity); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var npc = packet.ReadNPC(); + var center = packet.ReadVector2(); + var velocity = packet.ReadVector2(); + if (Main.dedServ && npc is not null) + { + npc.Center = center; + npc.velocity = velocity; + NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, npc.whoAmI); + } + } + } +} diff --git a/Packets/Entities/SyncNPCPosAndRotOnlyPacket.cs b/Packets/Entities/SyncNPCPosAndRotOnlyPacket.cs new file mode 100644 index 0000000000..403ccef71c --- /dev/null +++ b/Packets/Entities/SyncNPCPosAndRotOnlyPacket.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.Packets +{ + public sealed class SyncNPCPosAndRotOnlyPacket : CalamityPacket + { + public static SyncNPCPosAndRotOnlyPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncNPCPosAndRotOnly; + + public static void Send(NPC npc, int toClient = -1, int ignoreClient = -1) + { + if (npc is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(npc); + packet.WriteVector2(npc.position); + packet.Write((Half)npc.rotation); //rotation unit is radian (-π/2 ≤ rotation ≤ π/2) so Half precision should works + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var npc = packet.ReadNPC(); + var position = packet.ReadVector2(); + var rotation = (float)packet.ReadHalf(); + + if (npc is null) + return; + + npc.position = position; + npc.rotation = rotation; + + if (Main.dedServ) + { + Send(npc, ignoreClient: sender); + } + } + } +} diff --git a/Packets/Entities/SyncVanillaNPCLocalAIArrayPacket.cs b/Packets/Entities/SyncVanillaNPCLocalAIArrayPacket.cs new file mode 100644 index 0000000000..25f5ba8f6a --- /dev/null +++ b/Packets/Entities/SyncVanillaNPCLocalAIArrayPacket.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class SyncVanillaNPCLocalAIArrayPacket : CalamityPacket + { + public static SyncVanillaNPCLocalAIArrayPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncVanillaNPCLocalAIArray; + + public static void Send(NPC npc, int toClient = -1, int ignoreClient = -1) + { + if (npc is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(npc); + packet.Write(npc.localAI[0]); + packet.Write(npc.localAI[1]); + packet.Write(npc.localAI[2]); + packet.Write(npc.localAI[3]); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var npc = packet.ReadNPC(); + var ai0 = packet.ReadSingle(); + var ai1 = packet.ReadSingle(); + var ai2 = packet.ReadSingle(); + var ai3 = packet.ReadSingle(); + + if (npc is null) + return; + + npc.localAI[0] = ai0; + npc.localAI[1] = ai1; + npc.localAI[2] = ai2; + npc.localAI[3] = ai3; + } + } +} diff --git a/Packets/Entities/VanillaChanges/SyncDestroyerLaserColorPacket.cs b/Packets/Entities/VanillaChanges/SyncDestroyerLaserColorPacket.cs new file mode 100644 index 0000000000..1758573093 --- /dev/null +++ b/Packets/Entities/VanillaChanges/SyncDestroyerLaserColorPacket.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.NPCs; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class SyncDestroyerLaserColorPacket : CalamityPacket + { + public static SyncDestroyerLaserColorPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncDestroyerLaserColor; + + public static void Send(NPC npc, int toClient = -1, int ignoreClient = -1) + { + if (npc is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(npc); + packet.Write(npc.Calamity().destroyerLaserColor); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var npc = packet.ReadNPC(); + var laserColor = packet.ReadInt32(); + + if (npc is null) + return; + + npc.Calamity().destroyerLaserColor = laserColor; + } + } +} diff --git a/Packets/Events/AcidRain/AcidRainOldDukeSummonSyncPacket.cs b/Packets/Events/AcidRain/AcidRainOldDukeSummonSyncPacket.cs new file mode 100644 index 0000000000..e143687386 --- /dev/null +++ b/Packets/Events/AcidRain/AcidRainOldDukeSummonSyncPacket.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Events; + +namespace CalamityMod.Packets +{ + public sealed class AcidRainOldDukeSummonSyncPacket : CalamityPacket + { + public static AcidRainOldDukeSummonSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.AcidRainOldDukeSummonSync; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write(AcidRainEvent.HasTriedToSummonOldDuke); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + AcidRainEvent.HasTriedToSummonOldDuke = packet.ReadBoolean(); + } + } +} diff --git a/Packets/Events/AcidRain/AcidRainSyncPacket.cs b/Packets/Events/AcidRain/AcidRainSyncPacket.cs new file mode 100644 index 0000000000..c45dbf3546 --- /dev/null +++ b/Packets/Events/AcidRain/AcidRainSyncPacket.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Events; + +namespace CalamityMod.Packets +{ + public sealed class AcidRainSyncPacket : CalamityPacket + { + public static AcidRainSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.AcidRainSync; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write(AcidRainEvent.AcidRainEventIsOngoing); + packet.Write(AcidRainEvent.AccumulatedKillPoints); + packet.Write(AcidRainEvent.TimeSinceLastAcidRainKill); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + AcidRainEvent.AcidRainEventIsOngoing = packet.ReadBoolean(); + AcidRainEvent.AccumulatedKillPoints = packet.ReadInt32(); + AcidRainEvent.TimeSinceLastAcidRainKill = packet.ReadInt32(); + } + } +} diff --git a/Packets/Events/AcidRain/EncounteredOldDukeSyncPacket.cs b/Packets/Events/AcidRain/EncounteredOldDukeSyncPacket.cs new file mode 100644 index 0000000000..3062cf61ef --- /dev/null +++ b/Packets/Events/AcidRain/EncounteredOldDukeSyncPacket.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Events; + +namespace CalamityMod.Packets +{ + public sealed class EncounteredOldDukeSyncPacket : CalamityPacket + { + public static EncounteredOldDukeSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.EncounteredOldDukeSync; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write(AcidRainEvent.OldDukeHasBeenEncountered); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + AcidRainEvent.OldDukeHasBeenEncountered = packet.ReadBoolean(); + } + } +} diff --git a/Packets/Events/BossRush/BRHostileProjKillSyncPacket.cs b/Packets/Events/BossRush/BRHostileProjKillSyncPacket.cs new file mode 100644 index 0000000000..d06602c73d --- /dev/null +++ b/Packets/Events/BossRush/BRHostileProjKillSyncPacket.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Events; + +namespace CalamityMod.Packets +{ + public sealed class BRHostileProjKillSyncPacket : CalamityPacket + { + public static BRHostileProjKillSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.BRHostileProjKillSync; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write(BossRushEvent.HostileProjectileKillCounter); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + BossRushEvent.HostileProjectileKillCounter = packet.ReadInt32(); + } + } +} diff --git a/Packets/Events/BossRush/BossRushEndTimerPacket.cs b/Packets/Events/BossRush/BossRushEndTimerPacket.cs new file mode 100644 index 0000000000..c39bdff49c --- /dev/null +++ b/Packets/Events/BossRush/BossRushEndTimerPacket.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Events; + +namespace CalamityMod.Packets +{ + public sealed class BossRushEndTimerPacket : CalamityPacket + { + public static BossRushEndTimerPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.BossRushEndTimer; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write(BossRushEvent.EndTimer); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + BossRushEvent.EndTimer = packet.ReadInt32(); + } + } +} diff --git a/Packets/Events/BossRush/BossRushStagePacket.cs b/Packets/Events/BossRush/BossRushStagePacket.cs new file mode 100644 index 0000000000..ab0ef459bb --- /dev/null +++ b/Packets/Events/BossRush/BossRushStagePacket.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Events; + +namespace CalamityMod.Packets +{ + public sealed class BossRushStagePacket : CalamityPacket + { + public static BossRushStagePacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.BossRushStage; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write(BossRushEvent.BossRushStage); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + BossRushEvent.BossRushStage = packet.ReadInt32(); + } + } +} diff --git a/Packets/Events/BossRush/BossRushStartTimerPacket.cs b/Packets/Events/BossRush/BossRushStartTimerPacket.cs new file mode 100644 index 0000000000..22c1ba7a1f --- /dev/null +++ b/Packets/Events/BossRush/BossRushStartTimerPacket.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Events; + +namespace CalamityMod.Packets +{ + public sealed class BossRushStartTimerPacket : CalamityPacket + { + public static BossRushStartTimerPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.BossRushStartTimer; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write(BossRushEvent.StartTimer); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + BossRushEvent.StartTimer = packet.ReadInt32(); + } + } +} diff --git a/Packets/Events/BossRush/EndBossRushPacket.cs b/Packets/Events/BossRush/EndBossRushPacket.cs new file mode 100644 index 0000000000..52e5e9deea --- /dev/null +++ b/Packets/Events/BossRush/EndBossRushPacket.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Events; + +namespace CalamityMod.Packets +{ + public sealed class EndBossRushPacket : CalamityPacket + { + public static EndBossRushPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.EndBossRush; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + BossRushEvent.EndEffects(); + } + } +} diff --git a/Packets/MusicSystems/MusicEventSyncRequestPacket.cs b/Packets/MusicSystems/MusicEventSyncRequestPacket.cs new file mode 100644 index 0000000000..f2332bba2b --- /dev/null +++ b/Packets/MusicSystems/MusicEventSyncRequestPacket.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Systems; +using Terraria.ModLoader; +using Terraria; +using Terraria.ID; + +namespace CalamityMod.Packets +{ + public sealed class MusicEventSyncRequestPacket : CalamityPacket + { + public static MusicEventSyncRequestPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.MusicEventSyncRequest; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + // Only MP Client should send request! + if (Main.netMode != NetmodeID.MultiplayerClient) + return; + + var packet = Instance.CreateBasePacket(); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + // Only fulfill requests as the server host + if (Main.netMode != NetmodeID.Server) + return; + + MusicEventSyncResponsePacket.Send(toClient: sender); + } + } +} diff --git a/Packets/MusicSystems/MusicEventSyncResponsePacket.cs b/Packets/MusicSystems/MusicEventSyncResponsePacket.cs new file mode 100644 index 0000000000..4584f78089 --- /dev/null +++ b/Packets/MusicSystems/MusicEventSyncResponsePacket.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Systems; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Packets +{ + public sealed class MusicEventSyncResponsePacket : CalamityPacket + { + public static MusicEventSyncResponsePacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.MusicEventSyncResponse; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + // Only Server should send Reponse to Clients + if (Main.netMode != NetmodeID.Server) + return; + + var packet = Instance.CreateBasePacket(); + int trackCount = MusicEventSystem.PlayedEvents.Count; + packet.Write(trackCount); + + for (int i = 0; i < trackCount; i++) + packet.Write(MusicEventSystem.PlayedEvents[i]); + + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + // Only receive info as clients + if (Main.netMode != NetmodeID.MultiplayerClient) + { + // Still consume the packet anyways + int c = packet.ReadInt32(); + for (int i = 0; i < c; i++) + _ = packet.ReadString(); + + return; + } + + MusicEventSystem.PlayedEvents.Clear(); + + int trackCount = packet.ReadInt32(); + for (int i = 0; i < trackCount; i++) + MusicEventSystem.PlayedEvents.Add(packet.ReadString()); + } + } +} diff --git a/Packets/Players/AdrenalineSyncPacket.cs b/Packets/Players/AdrenalineSyncPacket.cs new file mode 100644 index 0000000000..9071e81810 --- /dev/null +++ b/Packets/Players/AdrenalineSyncPacket.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.CalPlayer; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class AdrenalineSyncPacket : CalamityPacket + { + public static AdrenalineSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.AdrenalineSync; + + public static void Send(CalamityPlayer playerToSync, int toClient = -1, int ignoreClient = -1) + { + if (playerToSync is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(playerToSync); + packet.Write(playerToSync.adrenaline); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var player = packet.ReadCalamityPlayer(); + var adrenaline = packet.ReadSingle(); + + if (player is null) + return; + + player.adrenaline = adrenaline; + + if (Main.dedServ) + Send(player, ignoreClient: sender); + } + } +} diff --git a/Packets/Players/CooldownAdditionPacket.cs b/Packets/Players/CooldownAdditionPacket.cs new file mode 100644 index 0000000000..831a0f1c3b --- /dev/null +++ b/Packets/Players/CooldownAdditionPacket.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.CalPlayer; +using CalamityMod.Cooldowns; +using Terraria; +using Terraria.ID; + +namespace CalamityMod.Packets +{ + public sealed class CooldownAdditionPacket : CalamityPacket + { + public static CooldownAdditionPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.CooldownAddition; + + public static void Send(CalamityPlayer player, CooldownInstance cd, int toClient = -1, int ignoreClient = -1) + { + Send(player, cd.netID, cd.duration, cd.timeLeft, toClient, ignoreClient); + } + + public static void Send(CalamityPlayer player, ushort netID, int duration, int timeLeft, int toClient = -1, int ignoreClient = -1) + { + if (player is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(player); + packet.Write(netID); + packet.Write(duration); + packet.Write(timeLeft); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var player = packet.ReadCalamityPlayer(); + var netID = packet.ReadUInt16(); + var duration = packet.ReadInt32(); + var timeLeft = packet.ReadInt32(); + + if (player is null) + return; + + if (Main.netMode == NetmodeID.MultiplayerClient) + { + CooldownInstance instance = new CooldownInstance(player.Player, netID, duration, timeLeft); + + // Actually assign this freshly synced cooldown to the appropriate player. + string id = CooldownRegistry.registry[instance.netID].ID; + player.cooldowns[id] = instance; + } + else if (Main.netMode == NetmodeID.Server) + { + // Server should NOT handle cooldown itself! + // Server doesn't have information for cooldown netIDs! + Send(player, netID, duration, timeLeft, ignoreClient: sender); + } + } + } +} diff --git a/Packets/Players/CooldownRemovalPacket.cs b/Packets/Players/CooldownRemovalPacket.cs new file mode 100644 index 0000000000..bc65bf7636 --- /dev/null +++ b/Packets/Players/CooldownRemovalPacket.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.CalPlayer; +using CalamityMod.Cooldowns; +using Terraria.ID; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class CooldownRemovalPacket : CalamityPacket + { + public static CooldownRemovalPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.CooldownRemoval; + + public static void Send(CalamityPlayer player, ushort[] netIDsToRemove, int toClient = -1, int ignoreClient = -1) + { + if (player is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(player); + packet.Write(netIDsToRemove.Length); + for (int i = 0; i < netIDsToRemove.Length; i++) + { + packet.Write(netIDsToRemove[i]); + } + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var player = packet.ReadCalamityPlayer(); + var count = packet.ReadInt32(); + var netIDsToRemove = new ushort[count]; + for (int i = 0; i < count; i++) + { + netIDsToRemove[i] = packet.ReadUInt16(); + } + + if (player is null) + return; + + if (Main.netMode == NetmodeID.MultiplayerClient) + { + foreach (var netID in netIDsToRemove) + { + player.cooldowns.Remove(CooldownRegistry.registry[netID].ID); + } + } + else if (Main.netMode == NetmodeID.Server) + { + // Server should NOT handle cooldown itself! + // Server doesn't have information for cooldown netIDs! + Send(player, netIDsToRemove, ignoreClient: sender); + } + } + } +} diff --git a/Packets/Players/DefenseDamageSyncPacket.cs b/Packets/Players/DefenseDamageSyncPacket.cs new file mode 100644 index 0000000000..8dfc63ca20 --- /dev/null +++ b/Packets/Players/DefenseDamageSyncPacket.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.CalPlayer; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Packets +{ + public sealed class DefenseDamageSyncPacket : CalamityPacket + { + public static DefenseDamageSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.DefenseDamageSync; + + public static void Send(CalamityPlayer playerToSync, int toClient = -1, int ignoreClient = -1) + { + if (playerToSync is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(playerToSync); + packet.Write(playerToSync.totalDefenseDamage); + packet.Write(playerToSync.defenseDamageRecoveryFrames); + packet.Write(playerToSync.totalDefenseDamageRecoveryFrames); + packet.Write(playerToSync.defenseDamageDelayFrames); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var player = packet.ReadCalamityPlayer(); + var totalDefDamage = packet.ReadInt32(); + var defDamageRecoverFrames = packet.ReadInt32(); + var totalDefDamageRecoverFrames = packet.ReadInt32(); + var defDamageDelayFrames = packet.ReadInt32(); + + if (player is null) + return; + + player.totalDefenseDamage = totalDefDamage; + player.defenseDamageRecoveryFrames = defDamageRecoverFrames; + player.totalDefenseDamageRecoveryFrames = totalDefDamageRecoverFrames; + player.defenseDamageDelayFrames = defDamageDelayFrames; + + if (Main.dedServ) + Send(player, ignoreClient: sender); + } + } +} diff --git a/Packets/Players/MousePositionSyncPacket.cs b/Packets/Players/MousePositionSyncPacket.cs new file mode 100644 index 0000000000..3f853c19c2 --- /dev/null +++ b/Packets/Players/MousePositionSyncPacket.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.CalPlayer; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class MousePositionSyncPacket : CalamityPacket + { + public static MousePositionSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.MousePositionSync; + + public static void Send(CalamityPlayer player, int toClient = -1, int ignoreClient = -1) + { + if (player is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(player); + packet.WriteVector2(player.mouseWorld); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var player = packet.ReadCalamityPlayer(); + var mouseWorldPos = packet.ReadVector2(); + + if (player is null) + return; + + player.mouseWorld = mouseWorldPos; + + if (Main.dedServ) + Send(player, ignoreClient: sender); + } + } +} diff --git a/Packets/Players/RageSyncPacket.cs b/Packets/Players/RageSyncPacket.cs new file mode 100644 index 0000000000..37e3cd3dd3 --- /dev/null +++ b/Packets/Players/RageSyncPacket.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.CalPlayer; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class RageSyncPacket : CalamityPacket + { + public static RageSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.RageSync; + + public static void Send(CalamityPlayer playerToSync, int toClient = -1, int ignoreClient = -1) + { + if (playerToSync is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(playerToSync); + packet.Write(playerToSync.rage); + packet.Write(playerToSync.rageCombatFrames); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var player = packet.ReadCalamityPlayer(); + var rage = packet.ReadSingle(); + var rageCombatFrames = packet.ReadInt32(); + + if (player is null) + return; + + player.rage = rage; + player.rageCombatFrames = rageCombatFrames; + + if (Main.dedServ) + Send(player, ignoreClient: sender); + } + } +} diff --git a/Packets/Players/RightClickSyncPacket.cs b/Packets/Players/RightClickSyncPacket.cs new file mode 100644 index 0000000000..a6c206d2a5 --- /dev/null +++ b/Packets/Players/RightClickSyncPacket.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.CalPlayer; +using CalamityMod.Events; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class RightClickSyncPacket : CalamityPacket + { + public static RightClickSyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.RightClickSync; + + public static void Send(CalamityPlayer player, int toClient = -1, int ignoreClient = -1) + { + if (player is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(player); + packet.Write(player.mouseRight); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var player = packet.ReadCalamityPlayer(); + var rightClick = packet.ReadBoolean(); + + if (player is null) + return; + + player.mouseRight = rightClick; + + if (Main.dedServ) + Send(player, ignoreClient: sender); + } + } +} diff --git a/Packets/Players/SyncCooldownDictionaryPacket.cs b/Packets/Players/SyncCooldownDictionaryPacket.cs new file mode 100644 index 0000000000..b03393c755 --- /dev/null +++ b/Packets/Players/SyncCooldownDictionaryPacket.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.CalPlayer; +using CalamityMod.Cooldowns; +using Terraria; +using Terraria.ID; + +using CooldownInfoTuple = (ushort netID, int duration, int timeLeft); + +namespace CalamityMod.Packets +{ + public sealed class SyncCooldownDictionaryPacket : CalamityPacket + { + public static SyncCooldownDictionaryPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncCooldownDictionary; + + public static void Send(CalamityPlayer player, int toClient = -1, int ignoreClient = -1) + { + if (player is null) + return; + + var cooldowns = player.cooldowns.Values.Select(cd => (cd.netID, cd.duration, cd.timeLeft)); + Send(player, cooldowns, toClient, ignoreClient); + } + + public static void Send(CalamityPlayer player, IEnumerable cooldowns, int toClient = -1, int ignoreClient = -1) + { + if (player is null) + return; + + if (cooldowns is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(player); + packet.Write(player.cooldowns.Count); + foreach (CooldownInfoTuple cd in cooldowns) + { + packet.Write(cd.netID); + packet.Write(cd.duration); + packet.Write(cd.timeLeft); + } + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var player = packet.ReadCalamityPlayer(); + int count = packet.ReadInt32(); + + Dictionary receivedCooldowns = new(count); + for (int i = 0; i < count; ++i) + { + var netID = packet.ReadUInt16(); + var duration = packet.ReadInt32(); + var timeLeft = packet.ReadInt32(); + receivedCooldowns[netID] = (netID, duration, timeLeft); + } + + if (player is null) + return; + + if (Main.netMode == NetmodeID.MultiplayerClient) + { + HashSet localIDs = [.. player.cooldowns.Values.Select(cd => cd.netID)]; + HashSet receivedIDs = [.. receivedCooldowns.Keys]; + + HashSet combinedIDSet = []; + combinedIDSet.UnionWith(localIDs); + combinedIDSet.UnionWith(receivedIDs); + + foreach (ushort netID in combinedIDSet) + { + bool existsLocally = localIDs.Contains(netID); + bool existsRemotely = receivedIDs.Contains(netID); + string id = CooldownRegistry.registry[netID].ID; + + // Exists locally but not remotely = cull -- destroy the local copy. + if (existsLocally && !existsRemotely) + { + player.cooldowns.Remove(id); + } + // Exists remotely but not locally = add -- insert into the dictionary. + else if (existsRemotely && !existsLocally) + { + var cdToAdd = receivedCooldowns[netID]; + player.cooldowns[id] = new CooldownInstance(player.Player, cdToAdd.netID, cdToAdd.duration, cdToAdd.timeLeft); + } + // Exists in both places = update -- update timing fields but don't replace the instance. + else if (existsLocally && existsRemotely) + { + CooldownInstance localInstance = player.cooldowns[id]; + localInstance.duration = receivedCooldowns[netID].duration; + localInstance.timeLeft = receivedCooldowns[netID].timeLeft; + } + } + } + else if (Main.netMode == NetmodeID.Server) + { + // Server should NOT handle cooldown itself! + // Server doesn't have information for cooldown netIDs! + Send(player, receivedCooldowns.Values, ignoreClient: sender); + } + } + } +} diff --git a/Packets/Players/SyncPlayerDrawParameterPacket.cs b/Packets/Players/SyncPlayerDrawParameterPacket.cs new file mode 100644 index 0000000000..1f71ec7a78 --- /dev/null +++ b/Packets/Players/SyncPlayerDrawParameterPacket.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.CalPlayer; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class SyncPlayerDrawParameterPacket : CalamityPacket + { + public static SyncPlayerDrawParameterPacket Instance { get; set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncPlayerDrawParameter; + + public static void Send(CalamityPlayer player, int toClient = -1, int ignoreClient = -1) + { + if (player is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteWhoAmI(player); + packet.Write((Half)player.drawingParameters.RoverShieldCharge); // 2b + packet.Write((Half)player.drawingParameters.LunicShieldCharge); // 2b + packet.Write((Half)player.drawingParameters.ProfanedShieldCharge); // 2b + packet.WriteRGB(player.drawingParameters.ProfanedShieldColor); // 3b + packet.Write((Half)player.drawingParameters.SpongeShieldCharge); // 2b + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var player = packet.ReadCalamityPlayer(); + var roverCharge = (float)packet.ReadHalf(); + var lunicCharge = (float)packet.ReadHalf(); + var profanedCharge = (float)packet.ReadHalf(); + var profanedColor = packet.ReadRGB(); + var spongeCharge = (float)packet.ReadHalf(); + + if (player is null) + return; + + player.drawingParameters.RoverShieldCharge = roverCharge; + player.drawingParameters.LunicShieldCharge = lunicCharge; + player.drawingParameters.ProfanedShieldCharge = profanedCharge; + player.drawingParameters.ProfanedShieldColor = profanedColor; + player.drawingParameters.SpongeShieldCharge = spongeCharge; + + if (Main.dedServ) + Send(player, ignoreClient: sender); + } + } +} diff --git a/Packets/TileEntities/TEChargingStationItemChangePacket.cs b/Packets/TileEntities/TEChargingStationItemChangePacket.cs new file mode 100644 index 0000000000..4aef46d3f6 --- /dev/null +++ b/Packets/TileEntities/TEChargingStationItemChangePacket.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.TileEntities; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria.ModLoader.IO; + +namespace CalamityMod.Packets +{ + public sealed class TEChargingStationItemChangePacket : CalamityPacket + { + public static TEChargingStationItemChangePacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.ChargingStationItemChange; + + public static void Send(TEChargingStation chargingStn, Item pluggedItem, int toClient = -1, int ignoreClient = -1) + { + if (chargingStn is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteTileEntityID(chargingStn); + ItemIO.Send(pluggedItem, packet, writeStack: true, writeFavorite: true); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var chargingStn = packet.ReadTileEntity(); + Item thePlug = ItemIO.Receive(packet, readStack: true, readFavorite: true); + + if (chargingStn is null) + return; + + chargingStn.PluggedItem = thePlug; + + // When a server gets this packet, it immediately sends an equivalent packet to all clients. + if (Main.dedServ) + Send(chargingStn, thePlug); + } + } +} diff --git a/Packets/TileEntities/TEChargingStationStandardPacket.cs b/Packets/TileEntities/TEChargingStationStandardPacket.cs new file mode 100644 index 0000000000..02307d9840 --- /dev/null +++ b/Packets/TileEntities/TEChargingStationStandardPacket.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Items; +using CalamityMod.TileEntities; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria; +using System.Runtime.InteropServices; + +namespace CalamityMod.Packets +{ + public sealed class TEChargingStationStandardPacket : CalamityPacket + { + public static TEChargingStationStandardPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.ChargingStationStandard; + + public static void Send(TEChargingStation chargingStn, short timer, short cellStack, float chargeOrNaN, int toClient = -1, int ignoreClient = -1) + { + if (chargingStn is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteTileEntityID(chargingStn); + packet.Write(timer); + packet.Write(cellStack); + packet.Write(chargeOrNaN); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var chargingStn = packet.ReadTileEntity(); + short timer = packet.ReadInt16(); + short cellStack = packet.ReadInt16(); + float chargeOrNaN = packet.ReadSingle(); + + if (chargingStn is null) + return; + + // Only clients update their timer from this packet. When a server receives this packet it ignores the time variable. + if (Main.netMode == NetmodeID.MultiplayerClient) + chargingStn.Internal_ChargingTimer = timer; + chargingStn.Internal_Stack = cellStack; + + // If the charge value sent is not garbage, then try to apply the new charge to the plugged item. + if (!float.IsNaN(chargeOrNaN)) + { + bool itemExists = chargingStn.PluggedItem != null && !chargingStn.PluggedItem.IsAir; + CalamityGlobalItem modItem = itemExists ? chargingStn.PluggedItem.Calamity() : null; + if (modItem != null && modItem.UsesCharge) + { + if (modItem.Charge != chargeOrNaN && Main.netMode == NetmodeID.MultiplayerClient) + chargingStn.ClientChargingDust = true; + modItem.Charge = chargeOrNaN; + } + } + + if (Main.dedServ) + Send(chargingStn, timer, cellStack, chargeOrNaN); + } + } +} diff --git a/Packets/TileEntities/TELabHologramProjectorPacket.cs b/Packets/TileEntities/TELabHologramProjectorPacket.cs new file mode 100644 index 0000000000..d43785f1ba --- /dev/null +++ b/Packets/TileEntities/TELabHologramProjectorPacket.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.TileEntities; +using Terraria.DataStructures; + +namespace CalamityMod.Packets +{ + public sealed class TELabHologramProjectorPacket : CalamityPacket + { + public static TELabHologramProjectorPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.LabHologramProjector; + + public static void Send(TELabHologramProjector projector, bool poppingUp, int toClient = -1, int ignoreClient = -1) + { + if (projector is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteTileEntityID(projector); + packet.Write(poppingUp); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var projector = packet.ReadTileEntity(); + bool pop = packet.ReadBoolean(); + + if (projector is null) + return; + + projector.PoppingUp = pop; + } + } +} diff --git a/Packets/TileEntities/TEPowerCellFactoryPacket.cs b/Packets/TileEntities/TEPowerCellFactoryPacket.cs new file mode 100644 index 0000000000..6b99b14023 --- /dev/null +++ b/Packets/TileEntities/TEPowerCellFactoryPacket.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.TileEntities; +using Terraria.DataStructures; +using Terraria.ID; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class TEPowerCellFactoryPacket : CalamityPacket + { + public static TEPowerCellFactoryPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.PowerCellFactory; + + public static void Send(TEPowerCellFactory cellFactory, long time, int stack, int toClient = -1, int ignoreClient = -1) + { + if (cellFactory is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteTileEntityID(cellFactory); + packet.Write(time); + packet.Write(stack); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var cellFactory = packet.ReadTileEntity(); + long time = packet.ReadInt64(); + short cellStack = packet.ReadInt16(); + + if (cellFactory is null) + return; + + // Only clients update their timer from this packet. When a server receives this packet it ignores the time variable. + if (Main.netMode == NetmodeID.MultiplayerClient) + cellFactory.Time = time; + cellFactory.Stack_Internal = cellStack; + + // When a server gets this packet, it immediately sends an equivalent packet to all clients. + if (Main.dedServ) + Send(cellFactory, time, cellStack); + } + } +} diff --git a/Packets/TileEntities/TETurretPacket.cs b/Packets/TileEntities/TETurretPacket.cs new file mode 100644 index 0000000000..342d303c6b --- /dev/null +++ b/Packets/TileEntities/TETurretPacket.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection.Metadata; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.TileEntities; +using CalamityMod.Tiles.FurnitureStatigel; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.DataStructures; +using Terraria.ModLoader; + +namespace CalamityMod.Packets +{ + public sealed class TETurretPacket : CalamityPacket + { + public static TETurretPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.Turret; + + public static void Send(TEBaseTurret turret, int toClient = -1, int ignoreClient = -1) + { + if (turret is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteTileEntityID(turret); + packet.Write(turret.FiringTime); + packet.Write(turret.Angle); + packet.WriteVector2(turret.TargetPos); + turret.WriteExtraTurretData(packet); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var turret = packet.ReadTileEntity(); + int firingTime = packet.ReadInt32(); + float angle = packet.ReadSingle(); + Vector2 targetVec = packet.ReadVector2(); + + if (turret is not null) + { + turret.FiringTime = firingTime; + turret.Angle = angle; + turret.TargetPos = targetVec; + turret.ReadExtraTurretData(packet); + } + else + { + // Otherwise, discard the fixed extra bytes so the message stream doesn't go haywire. + _ = packet.ReadBytes(TEBaseTurret.NumExtraBytes); + } + } + } +} diff --git a/Packets/TileEntities/TEUpdateCodebreakerConstituentsPacket.cs b/Packets/TileEntities/TEUpdateCodebreakerConstituentsPacket.cs new file mode 100644 index 0000000000..8746aa37c9 --- /dev/null +++ b/Packets/TileEntities/TEUpdateCodebreakerConstituentsPacket.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.TileEntities; +using Terraria; +using Terraria.DataStructures; +using Terraria.ID; + +namespace CalamityMod.Packets +{ + internal class TEUpdateCodebreakerConstituentsPacket : CalamityPacket + { + public static TEUpdateCodebreakerConstituentsPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.UpdateCodebreakerConstituents; + + public static void Send(TECodebreaker codeBreaker, int toClient = -1, int ignoreClient = -1) + { + if (codeBreaker is null) + return; + + var packet = Instance.CreateBasePacket(); + BitsByte containmentFlagWrapper = new BitsByte(); + containmentFlagWrapper[0] = codeBreaker.ContainsDecryptionComputer; + containmentFlagWrapper[1] = codeBreaker.ContainsSensorArray; + containmentFlagWrapper[2] = codeBreaker.ContainsAdvancedDisplay; + containmentFlagWrapper[3] = codeBreaker.ContainsVoltageRegulationSystem; + containmentFlagWrapper[4] = codeBreaker.ContainsCoolingCell; + + packet.WriteTileEntityID(codeBreaker); + packet.Write(containmentFlagWrapper); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var codeBreaker = packet.ReadTileEntity(); + BitsByte containmentFlagWrapper = packet.ReadByte(); + bool containsDecryptionComputer = containmentFlagWrapper[0]; + bool containsSensorArray = containmentFlagWrapper[1]; + bool containsAdvancedDisplay = containmentFlagWrapper[2]; + bool containsVoltageRegulationSystem = containmentFlagWrapper[3]; + bool containsCoolingCell = containmentFlagWrapper[4]; + + // Verify to ensure that the tile entity is a valid one. + if (codeBreaker is null) + return; + + codeBreaker.ContainsDecryptionComputer = containsDecryptionComputer; + codeBreaker.ContainsSensorArray = containsSensorArray; + codeBreaker.ContainsAdvancedDisplay = containsAdvancedDisplay; + codeBreaker.ContainsVoltageRegulationSystem = containsVoltageRegulationSystem; + codeBreaker.ContainsCoolingCell = containsCoolingCell; + + // Send the packet again to the other clients if this packet was received on the server. + // Since ModPackets go solely to the server when sent by a client this is necesssary + // to ensure that all clients are informed of what happened. + if (Main.dedServ) + Send(codeBreaker, ignoreClient: sender); + } + } +} diff --git a/Packets/TileEntities/TEUpdateCodebreakerContainedStuffPacket.cs b/Packets/TileEntities/TEUpdateCodebreakerContainedStuffPacket.cs new file mode 100644 index 0000000000..3ba126974b --- /dev/null +++ b/Packets/TileEntities/TEUpdateCodebreakerContainedStuffPacket.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.TileEntities; +using Terraria.DataStructures; + +namespace CalamityMod.Packets +{ + public sealed class TEUpdateCodebreakerContainedStuffPacket : CalamityPacket + { + public static TEUpdateCodebreakerContainedStuffPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.UpdateCodebreakerContainedStuff; + + public static void Send(TECodebreaker codeBreaker, int toClient = -1, int ignoreClient = -1) + { + if (codeBreaker is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteTileEntityID(codeBreaker); + packet.Write(codeBreaker.InputtedCellCount); + packet.Write(codeBreaker.InitialCellCountBeforeDecrypting); + packet.Write(codeBreaker.HeldSchematicID); + packet.Write(codeBreaker.ContainsBloodSample); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var codeBreaker = packet.ReadTileEntity(); + int cellCount = packet.ReadInt32(); + int cellCountBeforeDecrypting = packet.ReadInt32(); + int schematicID = packet.ReadInt32(); + bool containsBloodSample = packet.ReadBoolean(); + + // Verify to ensure that the tile entity is a valid one. + if (codeBreaker is null) + return; + + codeBreaker.InputtedCellCount = cellCount; + codeBreaker.InitialCellCountBeforeDecrypting = cellCountBeforeDecrypting; + codeBreaker.HeldSchematicID = schematicID; + codeBreaker.ContainsBloodSample = containsBloodSample; + } + } +} diff --git a/Packets/TileEntities/TEUpdateCodebreakerDecryptCountdownPacket.cs b/Packets/TileEntities/TEUpdateCodebreakerDecryptCountdownPacket.cs new file mode 100644 index 0000000000..933c017352 --- /dev/null +++ b/Packets/TileEntities/TEUpdateCodebreakerDecryptCountdownPacket.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.TileEntities; +using Terraria.DataStructures; + +namespace CalamityMod.Packets +{ + public sealed class TEUpdateCodebreakerDecryptCountdownPacket : CalamityPacket + { + public static TEUpdateCodebreakerDecryptCountdownPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.UpdateCodebreakerDecryptCountdown; + + public static void Send(TECodebreaker codeBreaker, int toClient = -1, int ignoreClient = -1) + { + if (codeBreaker is null) + return; + + var packet = Instance.CreateBasePacket(); + packet.WriteTileEntityID(codeBreaker); + packet.Write(codeBreaker.DecryptionCountdown); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var codeBreaker = packet.ReadTileEntity(); + int countdown = packet.ReadInt32(); + + // Verify to ensure that the tile entity is a valid one. + if (codeBreaker is null) + return; + + codeBreaker.DecryptionCountdown = countdown; + } + } +} diff --git a/Packets/Worlds/BanditStolenMoneySyncPacket.cs b/Packets/Worlds/BanditStolenMoneySyncPacket.cs new file mode 100644 index 0000000000..576f419be8 --- /dev/null +++ b/Packets/Worlds/BanditStolenMoneySyncPacket.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.World; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class BanditStolenMoneySyncPacket : CalamityPacket + { + public static BanditStolenMoneySyncPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.BanditStolenMoneySync; + + public static void Send(int amountStolenByBandit, int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Write7BitEncodedInt(amountStolenByBandit); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var amountStolenByBandit = packet.Read7BitEncodedInt(); + + CalamityWorld.MoneyStolenByBandit += amountStolenByBandit; + CalamityWorld.Reforges++; + + // Broadcast back for tragic event + // WorldSync DO sync the MoneyStolenByBandit and Refores variable, But spamming SyncWorld is not a ideal action + if (Main.dedServ) + Send(amountStolenByBandit, ignoreClient: sender); + } + } +} diff --git a/Packets/Worlds/SyncDifficultiesPacket.cs b/Packets/Worlds/SyncDifficultiesPacket.cs new file mode 100644 index 0000000000..d205f57d8a --- /dev/null +++ b/Packets/Worlds/SyncDifficultiesPacket.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.World; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class SyncDifficultiesPacket : CalamityPacket + { + // MIGRATED COMMENTS FROM: 'CalamityNetcode.cs' + //TODO - Something so that other mods that hijack the difficulty ui can also use the remainder of the reader to have their own shit + + public static SyncDifficultiesPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.SyncDifficulties; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + var difficultyFlags = new BitsByte(); + difficultyFlags[0] = CalamityWorld.revenge; + difficultyFlags[1] = CalamityWorld.death; + packet.Write((byte)difficultyFlags); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + var difficultyFlags = (BitsByte)packet.ReadByte(); + CalamityWorld.revenge = difficultyFlags[0]; + CalamityWorld.death = difficultyFlags[1]; + + if (Main.dedServ) + Send(ignoreClient: sender); + } + } +} diff --git a/Packets/Worlds/UnlockAbyssChestsPacket.cs b/Packets/Worlds/UnlockAbyssChestsPacket.cs new file mode 100644 index 0000000000..f134a64e06 --- /dev/null +++ b/Packets/Worlds/UnlockAbyssChestsPacket.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.World; +using Terraria; + +namespace CalamityMod.Packets +{ + public sealed class UnlockAbyssChestsPacket : CalamityPacket + { + public static UnlockAbyssChestsPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.UnlockAbyssChests; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + Abyss.DoUnlockAllAbyssChests(); + } + } +} diff --git a/Packets/Worlds/WantToRefundReforgesPacket.cs b/Packets/Worlds/WantToRefundReforgesPacket.cs new file mode 100644 index 0000000000..fd019a0ab4 --- /dev/null +++ b/Packets/Worlds/WantToRefundReforgesPacket.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.NPCs.TownNPCs; +using CalamityMod.World; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.Packets +{ + public sealed class WantToRefundReforgesPacket : CalamityPacket + { + public static WantToRefundReforgesPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.WantToRefundReforges; + + public static void Send(int toClient = -1, int ignoreClient = -1) + { + var packet = Instance.CreateBasePacket(); + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + // Only Server should handle this action! + if (!Main.dedServ) + return; + + int banditIdx = NPC.FindFirstNPC(ModContent.NPCType()); + if (banditIdx == -1) + return; + + NPC bandit = Main.npc[banditIdx]; + if (bandit == null || !bandit.active) + return; + + THIEF.DoRefund(bandit); + } + } +} diff --git a/Particles/FlameExplosion2.png b/Particles/FlameExplosion2.png new file mode 100644 index 0000000000..4fcc56314b Binary files /dev/null and b/Particles/FlameExplosion2.png differ diff --git a/Projectiles/CalamityGlobalProjectile.cs b/Projectiles/CalamityGlobalProjectile.cs index 1856d50dd6..30ed8405b5 100644 --- a/Projectiles/CalamityGlobalProjectile.cs +++ b/Projectiles/CalamityGlobalProjectile.cs @@ -116,8 +116,9 @@ namespace CalamityMod.Projectiles // If true, this projectile creates impact sparks upon hitting enemies public bool deepcoreBullet = false; - // If true, causes all projectiles fired by this weapon to have homing. Currently used for Arterial Assault. - public bool allProjectilesHome = false; + // If set to a value greater than 0, causes this projectile to gain homing with a range equal to the value in pixels. + // Currently used for Arterial Assault. + public float conditionalHomingRange = 0f; // Amount of extra updates that are set in SetDefaults. public int defExtraUpdates = -1; @@ -3909,9 +3910,9 @@ namespace CalamityMod.Projectiles } } - if (allProjectilesHome) + if (conditionalHomingRange > 0f) { - CalamityUtils.HomeInOnNPC(projectile, !projectile.tileCollide, 300f, 12f, 20f); + CalamityUtils.HomeInOnNPC(projectile, !projectile.tileCollide, conditionalHomingRange, 12f, 20f); } if (brimstoneBullets) { diff --git a/Projectiles/Magic/AtlantisSpear.cs b/Projectiles/Magic/AtlantisSpear.cs index 40c0fd051a..40e73700a1 100644 --- a/Projectiles/Magic/AtlantisSpear.cs +++ b/Projectiles/Magic/AtlantisSpear.cs @@ -1,5 +1,8 @@ -using Microsoft.Xna.Framework; +using CalamityMod.Particles; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; using Terraria; +using Terraria.Audio; using Terraria.ID; using Terraria.ModLoader; @@ -11,6 +14,8 @@ namespace CalamityMod.Projectiles.Magic public bool devourer = DownedBossSystem.downedDoG; public static int TotalSegments = 16; public float damageMultiplier = 1f; + public int time = 0; + public float fade = 1; public override void SetDefaults() { @@ -48,7 +53,7 @@ namespace CalamityMod.Projectiles.Magic // Spawn the next segment if (Main.myPlayer == Projectile.owner && Projectile.ai[0] < TotalSegments) { - int nextSegment = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center + Projectile.velocity, Projectile.velocity, Projectile.type, Projectile.damage, Projectile.knockBack, Projectile.owner, Projectile.ai[0] + 1f); + int nextSegment = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center + Projectile.velocity, Projectile.velocity, Projectile.type, Projectile.damage, Projectile.knockBack, Projectile.owner, Projectile.ai[0] + 1f, 0f, 5f); NetMessage.SendData(MessageID.SyncProjectile, -1, -1, null, nextSegment); } } @@ -57,21 +62,20 @@ namespace CalamityMod.Projectiles.Magic { int AlphaPerFrame = 12; Projectile.alpha += AlphaPerFrame; - if (Projectile.alpha == AlphaPerFrame * 14) - { - for (int i = 0; i < 8; i++) - { - Dust blue = Dust.NewDustDirect(Projectile.position, Projectile.width, Projectile.height, DustID.UnusedWhiteBluePurple, Projectile.velocity.X * 0.005f, Projectile.velocity.Y * 0.005f, 200, default, 1f); - blue.noGravity = true; - blue.velocity *= 0.5f; - } - } if (Projectile.alpha >= 255) Projectile.Kill(); } - if (Main.rand.NextBool(4)) - Dust.NewDust(Projectile.position + Projectile.velocity, Projectile.width, Projectile.height, DustID.UnusedWhiteBluePurple, Projectile.velocity.X * 0.005f, Projectile.velocity.Y * 0.005f); + if (Main.rand.NextBool(7)) + { + Dust dust = Dust.NewDustPerfect(Projectile.Center + Projectile.velocity * 0.5f, 278, Projectile.velocity.RotatedByRandom(0.8) * Main.rand.NextFloat(0.03f, 0.18f)); + dust.scale = Main.rand.NextFloat(0.3f, 0.5f); + dust.color = Main.rand.NextBool() ? Color.CornflowerBlue : Color.LightBlue; + dust.noGravity = true; + } + time++; + + fade = Utils.GetLerpValue(25, 12, time, true); } // This is essential for Vilethorn-type projectiles, as velocity is a stored parameter and isn't supposed to actually move the projectile @@ -88,9 +92,16 @@ namespace CalamityMod.Projectiles.Magic public override void OnKill(int timeLeft) { - for (int k = 0; k < 3; k++) + if (Projectile.ai[2] == 5) { - Dust.NewDust(Projectile.position + Projectile.velocity, Projectile.width, Projectile.height, DustID.UnusedWhiteBluePurple, Projectile.oldVelocity.X * 0.005f, Projectile.oldVelocity.Y * 0.005f); + for (int k = 0; k < 2; k++) + { + Particle spark = new SparkParticle(Projectile.Center + Projectile.velocity * 0.5f, Projectile.velocity.RotatedByRandom(0.8) * Main.rand.NextFloat(0.1f, 0.6f), false, 23, Main.rand.NextFloat(0.7f, 1.1f), Color.LightBlue * 0.6f); + GeneralParticleHandler.SpawnParticle(spark); + Particle spark2 = new PointParticle(Projectile.Center + Projectile.velocity * 0.5f, Projectile.velocity.RotatedByRandom(0.8) * Main.rand.NextFloat(0.1f, 0.6f), false, 23, Main.rand.NextFloat(0.7f, 1.1f), Color.LightBlue * 0.6f); + GeneralParticleHandler.SpawnParticle(spark2); + } + SoundEngine.PlaySound(SoundID.DD2_WitherBeastCrystalImpact with { Volume = 0.3f, Pitch = (Projectile.ai[0] * -0.02f) - 0.1f }, Projectile.Center); } // Prevent recursion: the segments that are being spawned here will deliberately be set higher than total segments @@ -103,8 +114,17 @@ namespace CalamityMod.Projectiles.Magic for (int i = 0; i < numProj; i++) { Vector2 perturbedSpeed = Projectile.velocity.RotatedBy(MathHelper.Lerp(-rotation, rotation, i / (numProj - 1))); - Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, perturbedSpeed, Projectile.type, Projectile.damage, Projectile.knockBack, Projectile.owner, TotalSegments + 1f); + Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, perturbedSpeed, Projectile.type, Projectile.damage, Projectile.knockBack, Projectile.owner, TotalSegments + 1f, 0, i); } } + public override bool PreDraw(ref Color lightColor) + { + Texture2D tex = Terraria.GameContent.TextureAssets.Projectile[Projectile.type].Value; + + if (time > 0) + Main.EntitySpriteDraw(tex, Projectile.Center - Main.screenPosition, null, Projectile.GetAlpha(lightColor) * fade, Projectile.rotation, tex.Size() / 2f, Projectile.scale, SpriteEffects.None, 0); + + return false; + } } } diff --git a/Projectiles/Melee/FallenBlast.cs b/Projectiles/Melee/FallenBlast.cs index 7f92c854bd..118efd521d 100644 --- a/Projectiles/Melee/FallenBlast.cs +++ b/Projectiles/Melee/FallenBlast.cs @@ -1,12 +1,6 @@ -using System; -using System.IO; -using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Buffs.DamageOverTime; using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; using Terraria; -using Terraria.Audio; -using Terraria.DataStructures; -using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Melee @@ -38,13 +32,21 @@ namespace CalamityMod.Projectiles.Melee Projectile.frame = (Projectile.frame + 1) % Main.projFrames[Type]; if (Projectile.frame >= 8) Projectile.Kill(); - } + Projectile.rotation = Projectile.velocity.ToRotation() - MathHelper.PiOver2 * 1.5f; + } + public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) + { + if (Projectile.numHits > 0) + Projectile.damage = (int)(Projectile.damage * 0.95f); + if (Projectile.damage < 1) + Projectile.damage = 1; + } public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, ExplosionRadius, targetHitbox); public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(ModContent.BuffType(), 180); + target.AddBuff(ModContent.BuffType(), 60); } } } diff --git a/Projectiles/Melee/FallenExplosionSmall.cs b/Projectiles/Melee/FallenExplosionSmall.cs new file mode 100644 index 0000000000..0f7bc1bd9e --- /dev/null +++ b/Projectiles/Melee/FallenExplosionSmall.cs @@ -0,0 +1,39 @@ +using CalamityMod.Buffs.DamageOverTime; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Melee +{ + public class FallenExplosionSmall : ModProjectile, ILocalizedModType + { + public new string LocalizationCategory => "Projectiles.Melee"; + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + public Player Owner => Main.player[Projectile.owner]; + private static float ExplosionRadius = 75f; + + public override void SetDefaults() + { + //These shouldn't matter because its circular + Projectile.width = 75; + Projectile.height = 75; + Projectile.friendly = true; + Projectile.DamageType = DamageClass.MeleeNoSpeed; + Projectile.ignoreWater = true; + Projectile.tileCollide = false; + Projectile.penetrate = -1; + Projectile.timeLeft = 2; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = 10; + } + public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) + { + target.AddBuff(ModContent.BuffType(), 180); + if (Projectile.numHits > 0) + Projectile.damage = (int)(Projectile.damage * 0.85f); + if (Projectile.damage < 1) + Projectile.damage = 1; + } + public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, ExplosionRadius, targetHitbox); + } +} diff --git a/Projectiles/Melee/FallenPaladinsHammerEcho.cs b/Projectiles/Melee/FallenPaladinsHammerEcho.cs index aa2909cc9d..b13a989cf2 100644 --- a/Projectiles/Melee/FallenPaladinsHammerEcho.cs +++ b/Projectiles/Melee/FallenPaladinsHammerEcho.cs @@ -1,5 +1,4 @@ -using System; -using System.IO; +using CalamityMod.Buffs.DamageOverTime; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -15,6 +14,7 @@ namespace CalamityMod.Projectiles.Melee public static readonly SoundStyle SlamHamSound = new("CalamityMod/Sounds/Item/FallenPaladinsHammerBigImpact") { Volume = 0.6f }; public static readonly SoundStyle Kunk = new("CalamityMod/Sounds/Item/TF2PanHit") { Volume = 1.1f }; public float speed = 0f; + public NPC targeted; public override void SetStaticDefaults() { ProjectileID.Sets.CultistIsResistantTo[Type] = true; @@ -23,8 +23,8 @@ namespace CalamityMod.Projectiles.Melee } public override void SetDefaults() { - Projectile.width = 40; - Projectile.height = 40; + Projectile.width = 62; + Projectile.height = 62; Projectile.aiStyle = 0; Projectile.friendly = true; Projectile.DamageType = DamageClass.MeleeNoSpeed; @@ -32,41 +32,48 @@ namespace CalamityMod.Projectiles.Melee Projectile.tileCollide = false; Projectile.ignoreWater = true; Projectile.usesLocalNPCImmunity = true; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = -1; } - - public override Color? GetAlpha(Color lightColor) - { - return new Color(255, 48, 48, 56); - } - public override void AI() { Projectile.ai[0] += 1f; if (Projectile.ai[0] < 42f) { Projectile.velocity *= 0.95f; - Projectile.rotation += MathHelper.ToRadians(Projectile.ai[0] * 0.5f) * Projectile.localAI[0]; + Projectile.rotation += (1f * Utils.GetLerpValue(30, 0, Projectile.ai[0]) * Projectile.direction); } - else if (Projectile.ai[0] > 42f) + else if (Projectile.ai[0] >= 42f) { - Projectile.extraUpdates = 1; - if (Projectile.ai[1] < 0f) - { - CalamityUtils.HomeInOnNPC(Projectile, Projectile.tileCollide, 2000f, speed, 12f); - if (Projectile.ai[0] > 80f) - Projectile.Kill(); - return; - } + Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver2 * 0.5f; + Projectile.extraUpdates = 4; - NPC target = Main.npc[(int)Projectile.ai[1]]; - if (!target.CanBeChasedBy(Projectile, false) || !target.active) - Projectile.Kill(); - else + if (Projectile.ai[1] != -5) + targeted = Main.npc[(int)Projectile.ai[1]]; + if (targeted == null || !targeted.CanBeChasedBy(Projectile, false) || !targeted.active) { - float velConst = 7f; - velConst--; - Projectile.velocity = new Vector2((target.Center.X - Projectile.Center.X) / velConst, (target.Center.Y - Projectile.Center.Y) / velConst); - Projectile.rotation += MathHelper.ToRadians(48f) * Projectile.localAI[0]; + Projectile.ai[1] = -5; + targeted = Projectile.Center.ClosestNPCAt(2000); + } + if (targeted != null) + { + Vector2 moveTotarget = (targeted.Center - Projectile.Center).SafeNormalize(Vector2.UnitX); + if (Projectile.velocity.Length() < MathHelper.Clamp(25 - Projectile.ai[0] * 0.1f, 10, 25)) + Projectile.velocity += moveTotarget * (0.35f + Projectile.ai[0] * 0.03f); + else + Projectile.velocity *= 0.9f; + } + else + Projectile.Kill(); + } + if (Projectile.ai[0] == 42f && targeted != null) + { + for (int i = 0; i < 20; i++) + { + Dust dust = Dust.NewDustPerfect(Projectile.Center, 278, ((targeted.Center - Projectile.Center).SafeNormalize(Vector2.UnitX) * 15).RotatedByRandom(0.4f) * Main.rand.NextFloat(0.2f, 1f)); + dust.noGravity = true; + dust.scale = Main.rand.NextFloat(0.5f, 1.2f); + dust.color = Main.rand.NextBool() ? Color.IndianRed : Color.Red; } } @@ -74,16 +81,9 @@ namespace CalamityMod.Projectiles.Melee { Vector2 offset = new Vector2(7, 0).RotatedByRandom(MathHelper.ToRadians(360f)); Vector2 velOffset = new Vector2(3, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(Projectile.position + offset, DustID.RedTorch, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(255, 245, 198), 2f); - dust.noGravity = true; - } - - if (Main.rand.NextBool(6)) - { - Vector2 offset = new Vector2(7, 0).RotatedByRandom(MathHelper.ToRadians(360f)); - Vector2 velOffset = new Vector2(3, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(Projectile.position + offset, DustID.RedTorch, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(255, 245, 198), 2f); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, 267, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 0, new Color(255, 245, 198), 1f); dust.noGravity = true; + dust.color = Color.DarkRed; } } @@ -98,7 +98,9 @@ namespace CalamityMod.Projectiles.Melee public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - Projectile.localAI[0] = target.whoAmI; + target.AddBuff(ModContent.BuffType(), 180); + if (target == targeted) + Projectile.Kill(); } public override bool PreKill(int timeLeft) @@ -112,27 +114,17 @@ namespace CalamityMod.Projectiles.Melee SoundEngine.PlaySound(SlamHamSound, Projectile.Center); Main.player[Projectile.owner].Calamity().GeneralScreenShakePower = 5; - Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Projectile.velocity * 0f, ModContent.ProjectileType(), Projectile.damage / 2, Projectile.knockBack, Projectile.owner, 0f); + Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Projectile.velocity * 0.001f, ModContent.ProjectileType(), Projectile.damage / 2, Projectile.knockBack, Projectile.owner, 0f); return false; } public override bool PreDraw(ref Color lightColor) { - SpriteEffects spriteEffects = SpriteEffects.None; - if (Projectile.spriteDirection == -1) - spriteEffects = SpriteEffects.FlipHorizontally; - Texture2D texture = Terraria.GameContent.TextureAssets.Projectile[Projectile.type].Value; - Rectangle sourceRectangle = new Rectangle(0, 0, texture.Width, texture.Height); - Vector2 origin = sourceRectangle.Size() / 2f; + Texture2D texture = ModContent.Request("CalamityMod/Items/Weapons/Melee/FallenPaladinsHammer").Value; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], Color.DarkRed with { A = 0 } * 0.5f, 1, texture, true, true); - for (int i = 0; i < Projectile.oldPos.Length; i++) - { - float rot = MathHelper.ToRadians(22.5f) * Math.Sign(Projectile.velocity.X); - Vector2 drawPos = Projectile.oldPos[i] - Main.screenPosition + origin + new Vector2(0f, Projectile.gfxOffY); - Color color = Projectile.GetAlpha(lightColor) * ((Projectile.oldPos.Length - i) / (float)Projectile.oldPos.Length); - Main.EntitySpriteDraw(texture, drawPos, new Rectangle?(), color, Projectile.rotation - i * rot, origin, Projectile.scale, spriteEffects, 0); - } + Projectile.DrawProjectileWithBackglow(Color.Red with { A = 0 }, Color.Lerp(Color.Red, Color.White, 0.5f), 5f, texture); return false; } } diff --git a/Projectiles/Melee/FallenPaladinsHammerProj.cs b/Projectiles/Melee/FallenPaladinsHammerProj.cs index fc5331c3a0..5686dff56a 100644 --- a/Projectiles/Melee/FallenPaladinsHammerProj.cs +++ b/Projectiles/Melee/FallenPaladinsHammerProj.cs @@ -1,8 +1,7 @@ using System; -using System.IO; using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Dusts; using CalamityMod.Items.Weapons.Melee; -using CalamityMod.Projectiles.Melee; using Microsoft.Xna.Framework; using Terraria; using Terraria.Audio; @@ -20,6 +19,7 @@ namespace CalamityMod.Projectiles.Melee public static readonly SoundStyle RedHamSound = new("CalamityMod/Sounds/Item/FallenPaladinsHammerClone") { Volume = 0.6f }; public ref int EmpoweredHammer => ref Main.player[Projectile.owner].Calamity().PHAThammer; public int returnhammer = 0; + public int time = 0; public override void SetStaticDefaults() { @@ -49,8 +49,13 @@ namespace CalamityMod.Projectiles.Melee if (returnhammer == 0) { - Projectile.velocity.X *= 0.9711f; - Projectile.velocity.Y += 0.426f; + int falloffTime = 15; + if (time > falloffTime) + Projectile.velocity.X *= 0.967f; + if (Projectile.velocity.Y < 15 && time > falloffTime) + Projectile.velocity.Y += 0.426f; + if (Projectile.velocity.Y < 5) + Projectile.velocity.Y *= 0.98f; } if (returnhammer == 1) @@ -64,7 +69,7 @@ namespace CalamityMod.Projectiles.Melee if (returnhammer == 2) { - float returnSpeed = FallenPaladinsHammer.Speed; + float returnSpeed = FallenPaladinsHammer.Speed * 0.7f; float acceleration = 1.1f; Player owner = Main.player[Projectile.owner]; Vector2 playerCenter = owner.Center; @@ -108,15 +113,15 @@ namespace CalamityMod.Projectiles.Melee if (EmpoweredHammer == 3) { SoundEngine.PlaySound(RedHamSound, Projectile.Center); - for (int i = 0; i < 30; i++) + for (int i = 0; i < 20; i++) { - Dust fire = Dust.NewDustPerfect(Projectile.Center, 218); + Dust fire = Dust.NewDustPerfect(Projectile.Center, 90); fire.velocity = Projectile.velocity.SafeNormalize(Vector2.UnitY).RotatedByRandom(0.8f) * new Vector2(4f, 1.25f) * Main.rand.NextFloat(0.9f, 1f); fire.velocity = fire.velocity.RotatedBy(Projectile.rotation - MathHelper.PiOver2); fire.velocity += Projectile.velocity * (EmpoweredHammer * 0.1f); fire.noGravity = true; - fire.scale = Main.rand.NextFloat(0.5f, 1.5f) * EmpoweredHammer; + fire.scale = Main.rand.NextFloat(0.7f, 1.2f) + EmpoweredHammer * 0.4f; fire = Dust.CloneDust(fire); fire.velocity = Main.rand.NextVector2Circular(3f, 3f); @@ -131,15 +136,15 @@ namespace CalamityMod.Projectiles.Melee else { SoundEngine.PlaySound(SoundID.DD2_BetsysWrathShot with { Volume = 0.4f }, Projectile.Center); - for (int i = 0; i < 30; i++) + for (int i = 0; i < 20; i++) { - Dust fire = Dust.NewDustPerfect(Projectile.Center, 218); + Dust fire = Dust.NewDustPerfect(Projectile.Center, 90); fire.velocity = Projectile.velocity.SafeNormalize(Vector2.UnitY).RotatedByRandom(0.8f) * new Vector2(4f, 1.25f) * Main.rand.NextFloat(0.9f, 1f); fire.velocity = fire.velocity.RotatedBy(Projectile.rotation - MathHelper.PiOver2); fire.velocity += Projectile.velocity * (EmpoweredHammer * 0.1f); fire.noGravity = true; - fire.scale = Main.rand.NextFloat(0.5f, 1.5f) * EmpoweredHammer; + fire.scale = Main.rand.NextFloat(0.7f, 1.2f) + EmpoweredHammer * 0.4f; fire = Dust.CloneDust(fire); fire.velocity = Main.rand.NextVector2Circular(3f, 3f); @@ -157,17 +162,11 @@ namespace CalamityMod.Projectiles.Melee { Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, DustID.RedTorch, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(205, 38, 38), 2f); - dust.noGravity = true; - } - - if (Main.rand.NextBool(6)) - { - Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); - Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, DustID.RedTorch, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(205, 38, 38), 2f); + Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, 267, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 0, default, 0.7f); dust.noGravity = true; + dust.color = Color.DarkRed; } + time++; } // On hit play GONG and spawn dust. public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) @@ -175,6 +174,8 @@ namespace CalamityMod.Projectiles.Melee Player player = Main.player[Projectile.owner]; if (returnhammer == 0) { + Projectile.ai[1] = target.whoAmI; + if (Main.zenithWorld) SoundEngine.PlaySound(UseSoundFunny with { Pitch = EmpoweredHammer * 0.2f - 0.4f }, Projectile.Center); @@ -183,30 +184,34 @@ namespace CalamityMod.Projectiles.Melee returnhammer = 1; } - float numberOfDusts = 35f; + float numberOfDusts = 30f; float rotFactor = 360f / numberOfDusts; for (int i = 0; i < numberOfDusts; i++) { float rot = MathHelper.ToRadians(i * rotFactor); Vector2 offset = new Vector2(3.6f, 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 4.1f)); Vector2 velOffset = new Vector2(3f, 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 4.1f)); - Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, 90, new Vector2(velOffset.X, velOffset.Y)); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, (Projectile.numHits == 0 ? (Main.rand.NextBool() ? 90 : ModContent.DustType()) : 90), new Vector2(velOffset.X, velOffset.Y)); dust.noGravity = true; - dust.velocity = velOffset; - dust.scale = Main.rand.NextFloat(1.5f, 3.2f); + dust.velocity = velOffset * (Projectile.numHits == 0 ? ( i % 3 == 0 ? 3 : 1.5f) : 1); + dust.scale = Main.rand.NextFloat(1.3f, 2.2f); + if (Projectile.numHits == 0) + dust.color = Color.Red; + } + if (Projectile.numHits == 0) + { + SoundEngine.PlaySound(SoundID.DD2_ExplosiveTrapExplode with { Volume = 0.5f, Pitch = 0.3f }, Projectile.Center); + Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Projectile.velocity * 0f, ModContent.ProjectileType(), Projectile.damage / 3, Projectile.knockBack, Projectile.owner, 0f); } - - SoundEngine.PlaySound(SoundID.Item14 with { Volume = 0.22f }, Projectile.Center); - Projectile.ai[1] = target.whoAmI; } public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) { - if (Projectile.numHits > 0) - Projectile.damage = (int)(Projectile.damage * 0.9f); - if (Projectile.damage < 1) - Projectile.damage = 1; + target.AddBuff(ModContent.BuffType(), 90); + float minMult = 0.7f; + int hitsToMinMult = 10; + float damageMult = Utils.Remap(Projectile.numHits, 0, hitsToMinMult, 1, minMult, true); + modifiers.SourceDamage *= damageMult; } - public override bool PreDraw(ref Color lightColor) { CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 2); diff --git a/Projectiles/Melee/GalaxySmasherBlast.cs b/Projectiles/Melee/GalaxySmasherBlast.cs index 6150711d81..9f86bba778 100644 --- a/Projectiles/Melee/GalaxySmasherBlast.cs +++ b/Projectiles/Melee/GalaxySmasherBlast.cs @@ -1,9 +1,7 @@ -using System; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Graphics.Metaballs; using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; using Terraria; -using Terraria.Audio; -using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Melee @@ -13,23 +11,47 @@ namespace CalamityMod.Projectiles.Melee public new string LocalizationCategory => "Projectiles.Melee"; public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; public Player Owner => Main.player[Projectile.owner]; - private static float ExplosionRadius = 568f; + private static float ExplosionRadius = 868f; public override void SetDefaults() { //These shouldn't matter because its circular - Projectile.width = 568; - Projectile.height = 568; + Projectile.width = 868; + Projectile.height = 868; Projectile.friendly = true; Projectile.DamageType = DamageClass.MeleeNoSpeed; Projectile.ignoreWater = true; Projectile.tileCollide = false; Projectile.penetrate = -1; - Projectile.timeLeft = 2; + Projectile.timeLeft = 18; Projectile.usesLocalNPCImmunity = true; - Projectile.localNPCHitCooldown = 10; + Projectile.localNPCHitCooldown = -1; } + public override void AI() + { + // Pureley visual stuff + float fade = Utils.GetLerpValue(-2, 18, Projectile.timeLeft); + float numberOfDusts = 8f; + for (int i = 0; i < numberOfDusts; i++) + { + Vector2 velOffset = new Vector2(42, 42).RotatedByRandom(100) * Main.rand.NextFloat(0.5f, 1f); + GalaxyMetaball.SpawnParticle(Projectile.Center, velOffset * fade, 300f * Main.rand.NextFloat(0.8f, 1f) * fade); + if (i % 2 == 0) + { + Vector2 velOffset2 = new Vector2(92, 92).RotatedByRandom(100) * Main.rand.NextFloat(0.5f, 1f); + GalaxyMetaball.SpawnParticle(Projectile.Center, velOffset2 * fade, 120f * Main.rand.NextFloat(0.7f, 1f) * fade); + } + } + } + public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) + { + target.AddBuff(ModContent.BuffType(), 180); + if (Projectile.numHits > 0) + Projectile.damage = (int)(Projectile.damage * 0.85f); + if (Projectile.damage < 1) + Projectile.damage = 1; + } public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, ExplosionRadius, targetHitbox); } } diff --git a/Projectiles/Melee/GalaxySmasherEcho.cs b/Projectiles/Melee/GalaxySmasherEcho.cs index 7cf02ce6a8..9afc7239fb 100644 --- a/Projectiles/Melee/GalaxySmasherEcho.cs +++ b/Projectiles/Melee/GalaxySmasherEcho.cs @@ -1,141 +1,143 @@ -using System; -using System.IO; +using System.Collections.Generic; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Graphics.Metaballs; using CalamityMod.Particles; -using CalamityMod.Projectiles.DraedonsArsenal; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using ReLogic.Content; using Terraria; using Terraria.Audio; using Terraria.ID; using Terraria.ModLoader; -using static Humanizer.In; namespace CalamityMod.Projectiles.Melee { public class GalaxySmasherEcho : ModProjectile, ILocalizedModType { public new string LocalizationCategory => "Projectiles.Melee"; - public static readonly SoundStyle SlamHamSound = new("CalamityMod/Sounds/Item/GalaxySmasherSmash") { Volume = 0.6f }; + public override string Texture => "CalamityMod/Items/Weapons/Melee/GalaxySmasher"; + public static readonly SoundStyle SlamHamSound = new("CalamityMod/Sounds/Item/GalaxySmasherSmash") { Volume = 0.7f }; public static readonly SoundStyle Kunk = new("CalamityMod/Sounds/Item/TF2PanHit") { Volume = 1.1f }; - public float rotatehammer = 35f; + public float rotatehammer = 15f; public float speed = 0f; + public NPC targeted; + public Color usedColor = Color.Aqua; public override void SetStaticDefaults() { ProjectileID.Sets.CultistIsResistantTo[Type] = true; ProjectileID.Sets.TrailCacheLength[Projectile.type] = 15; - ProjectileID.Sets.TrailingMode[Projectile.type] = 0; + ProjectileID.Sets.TrailingMode[Projectile.type] = 2; } - //This is all copied straight from PwnagehammerEcho with some minor edits. public override void SetDefaults() { - Projectile.width = 78; - Projectile.height = 78; + Projectile.width = 86; + Projectile.height = 72; Projectile.aiStyle = 0; Projectile.friendly = true; Projectile.DamageType = DamageClass.MeleeNoSpeed; - Projectile.penetrate = 1; + Projectile.penetrate = -1; Projectile.tileCollide = false; Projectile.ignoreWater = true; Projectile.usesLocalNPCImmunity = true; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = -1; } - - public override void AI() { - Projectile.scale = 2.78f; - rotatehammer *= 1.2f; + List eColors = new List() + { + Color.Aqua, + Color.Magenta, + }; + float rate = (Main.GlobalTimeWrappedHourly * 43); + int colorIndex = (int)(rate / 2 % eColors.Count); + Color currentColor = eColors[colorIndex]; + Color nextColor = eColors[(colorIndex + 1) % eColors.Count]; + usedColor = Color.Lerp(currentColor, nextColor, rate % 2f > 1f ? 1f : rate % 1f); + + rotatehammer += 2f; Projectile.rotation += MathHelper.ToRadians(rotatehammer) * Projectile.direction; - Projectile.ai[0] += 1f; - if (Projectile.ai[0] < 42f) + if (true) { - Projectile.velocity *= 0.95f; - Projectile.rotation += MathHelper.ToRadians(Projectile.ai[0] * 0.5f) * Projectile.localAI[0]; - } - else if (Projectile.ai[0] > 42f) - { - Projectile.extraUpdates = 1; - if (Projectile.ai[1] < 0f) + if (Projectile.timeLeft % 2 == 0) { - CalamityUtils.HomeInOnNPC(Projectile, Projectile.tileCollide, 2000f, speed, 12f); - if (Projectile.ai[0] > 80f) - Projectile.Kill(); + Particle spark = new CustomSpark(Projectile.Center, -Projectile.velocity * 0.05f, "CalamityMod/Particles/SmallBloom", false, 13, 0.5f, usedColor, new Vector2(0.6f, 1f), true, false, 0, false, false, 0.7f); + GeneralParticleHandler.SpawnParticle(spark); } - NPC target = Main.npc[(int)Projectile.ai[1]]; - if (!target.CanBeChasedBy(Projectile, false) || !target.active) - Projectile.Kill(); + Projectile.extraUpdates = 7; + + if (Projectile.ai[1] != -5) + targeted = Main.npc[(int)Projectile.ai[1]]; + if (targeted == null || !targeted.CanBeChasedBy(Projectile, false) || !targeted.active) + { + targeted = Projectile.Center.ClosestNPCAt(2000); + Projectile.ai[1] = -5; + } + if (targeted != null) + { + float speedMult = 0.9f; + Vector2 moveTotarget = (targeted.Center - Projectile.Center).SafeNormalize(Vector2.UnitX); + if (Projectile.velocity.Length() < MathHelper.Clamp(25 - Projectile.ai[0] * 0.1f, 10, 25) * speedMult) + Projectile.velocity += moveTotarget * (0.35f + Projectile.ai[0] * 0.03f) * speedMult; + else + Projectile.velocity *= 0.9f; + } else - { - float velConst = 5f; - velConst--; - Projectile.velocity = new Vector2((target.Center.X - Projectile.Center.X) / velConst, (target.Center.Y - Projectile.Center.Y) / velConst); - Projectile.rotation += MathHelper.ToRadians(48f) * Projectile.localAI[0]; - } + Projectile.Kill(); } - if (Main.rand.NextBool()) + Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); + Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, 278, (-Projectile.velocity + velOffset) * Main.rand.NextFloat(0.3f, 1f), 0, default, Main.rand.NextFloat(0.35f, 0.75f)); + dust.noGravity = true; + dust.color = Main.rand.NextBool() ? Color.Magenta : Color.Aqua; + + for (int i = 0; i < 2; i++) { - Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); - Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, 272, new Vector2(Projectile.velocity.X * 0.4f + velOffset.X, Projectile.velocity.Y * 0.4f + velOffset.Y), 100, default, 0.9f); - dust.noGravity = true; + GalaxyMetaball.SpawnParticle(Projectile.Center, -Projectile.velocity.RotatedByRandom(0.4f) * Main.rand.NextFloat(0.2f, 1f), 195f * Main.rand.NextFloat(0.9f, 1f)); } - - if (Main.rand.NextBool(6)) - { - Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); - Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, 226, new Vector2(Projectile.velocity.X * 0.5f + velOffset.X, Projectile.velocity.Y * 0.5f + velOffset.Y), 100, default, 0.9f); - dust.noGravity = true; - } - } public override bool? CanHitNPC(NPC target) { - if (Projectile.ai[0] <= 42f) - return false; return null; } - - public override bool CanHitPvp(Player target) => Projectile.ai[0] > 42f; - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - Projectile.localAI[0] = target.whoAmI; - float damageInterpolant = Utils.GetLerpValue(950f, 2000f, hit.Damage, true); - float impactAngularVelocity = MathHelper.Lerp(0.08f, 0.2f, damageInterpolant); - impactAngularVelocity *= Main.rand.NextBool().ToDirectionInt() * Main.rand.NextFloat(0.75f, 1.25f); - Vector2 splatterDirection = Projectile.velocity; - for (int i = 0; i < 20; i++) - { - int sparkLifetime = Main.rand.Next(55, 70); - float sparkScale = Main.rand.NextFloat(0.7f, Main.rand.NextFloat(3.3f, 5.5f)) + damageInterpolant * 0.85f; - Color sparkColor = Color.Lerp(Color.Fuchsia, Color.Aqua, Main.rand.NextFloat(0.7f)); - sparkColor = Color.Lerp(sparkColor, Color.Fuchsia, Main.rand.NextFloat()); - - Vector2 sparkVelocity = splatterDirection.RotatedByRandom(0.7f) * Main.rand.NextFloat(1f, 1.2f); - sparkVelocity.Y -= 7f; - SparkParticle spark = new SparkParticle(Projectile.Center, sparkVelocity, false, sparkLifetime, sparkScale, sparkColor); - GeneralParticleHandler.SpawnParticle(spark); - } + target.AddBuff(ModContent.BuffType(), 420); + if (target == targeted) + Projectile.Kill(); } public override bool PreKill(int timeLeft) { Player player = Main.player[Projectile.owner]; //This is what we call fucking IMPACT (3). - Main.player[Projectile.owner].Calamity().GeneralScreenShakePower = 12; + Main.player[Projectile.owner].Calamity().GeneralScreenShakePower = 15; if (Main.zenithWorld) SoundEngine.PlaySound(Kunk, Projectile.Center); - else SoundEngine.PlaySound(SlamHamSound, Projectile.Center); + for (int i = 0; i < 8; i++) + { + float rot = MathHelper.PiOver4 * i; + Particle pulse1 = new CustomPulse(Projectile.Center, Vector2.Zero, Color.Aqua * 0.4f, "CalamityMod/Particles/HighResHollowCircleHardEdge", new Vector2(1.4f, 0.6f), rot, 0, 1f, 40); + GeneralParticleHandler.SpawnParticle(pulse1); + } - Particle pulse = new DirectionalPulseRing(Projectile.Center, Vector2.Zero, Color.Violet, new Vector2(2f, 2f), Main.rand.NextFloat(12f, 25f), 0.2f, 4f, 12); - GeneralParticleHandler.SpawnParticle(pulse); - Particle pulse2 = new DirectionalPulseRing(Projectile.Center, Vector2.Zero, Color.Aqua, new Vector2(2f, 2f), Main.rand.NextFloat(12f, 25f), 0.1f, 1.5f, 11); - GeneralParticleHandler.SpawnParticle(pulse2); + float numberOfDusts = 40f; + float rotFactor = 360f / numberOfDusts; + for (int i = 0; i < numberOfDusts; i++) + { + float rot = MathHelper.ToRadians(i * rotFactor); + Vector2 offset = new Vector2(15f, 0).RotatedBy(rot); + Vector2 velOffset = new Vector2(42.5f, 0).RotatedBy(rot) * (i % 2 == 0 ? 0.8f : i % 3 == 0 ? 0.6f : 1f); + + Particle spark = new CustomSpark(Projectile.Center + offset * 6, velOffset, "CalamityMod/Particles/SmallBloom", false, 35, 1f, Color.Magenta * 0.75f, new Vector2(1.2f, 1f), true, false, 0, false, false, 0.3f); + GeneralParticleHandler.SpawnParticle(spark); + } + GalaxyMetaball.SpawnParticle(Projectile.Center, Vector2.Zero, 275f); Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Projectile.velocity * 0f, ModContent.ProjectileType(), Projectile.damage / 2, Projectile.knockBack, Projectile.owner, 0f); @@ -144,20 +146,16 @@ namespace CalamityMod.Projectiles.Melee public override bool PreDraw(ref Color lightColor) { - SpriteEffects spriteEffects = SpriteEffects.None; - if (Projectile.spriteDirection == -1) - spriteEffects = SpriteEffects.FlipHorizontally; - Texture2D texture = Terraria.GameContent.TextureAssets.Projectile[Projectile.type].Value; - Rectangle sourceRectangle = new Rectangle(0, 0, texture.Width + 12, texture.Height + 12); - Vector2 origin = sourceRectangle.Size() / 2f; + Texture2D texture = ModContent.Request("CalamityMod/Items/Weapons/Melee/GalaxySmasher").Value; + Asset p2 = ModContent.Request("CalamityMod/Particles/CircularSmearSmokey"); - for (int i = 0; i < Projectile.oldPos.Length; i++) - { - float rot = MathHelper.ToRadians(22.5f) * Math.Sign(Projectile.velocity.X); - Vector2 drawPos = Projectile.oldPos[i] - Main.screenPosition + origin + new Vector2(0f, Projectile.gfxOffY); - Color color = Projectile.GetAlpha(lightColor) * ((Projectile.oldPos.Length - i) / (float)Projectile.oldPos.Length); - Main.EntitySpriteDraw(texture, drawPos, new Rectangle?(), color, Projectile.rotation - i * rot, origin, Projectile.scale, spriteEffects, 0); - } + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor * 0.5f, 3, texture, true, true); + + Vector2 generalDrawPos = Projectile.Center - Main.screenPosition; + + Projectile.DrawProjectileWithBackglow(usedColor with { A = 0 }, Color.White, 9.5f, texture, null, Projectile.direction < 0 ? SpriteEffects.FlipHorizontally : SpriteEffects.None); + + Main.EntitySpriteDraw(p2.Value, generalDrawPos, null, usedColor with { A = 0 } * 0.65f, Projectile.rotation * Main.rand.NextFloat(1.4f, 1.45f), p2.Size() * 0.5f, 1.2f * Main.rand.NextFloat(0.9f, 1.1f), SpriteEffects.None); return false; } } diff --git a/Projectiles/Melee/GalaxySmasherEcho.png b/Projectiles/Melee/GalaxySmasherEcho.png deleted file mode 100644 index a8e4ed6442..0000000000 Binary files a/Projectiles/Melee/GalaxySmasherEcho.png and /dev/null differ diff --git a/Projectiles/Melee/GalaxySmasherHammer.cs b/Projectiles/Melee/GalaxySmasherHammer.cs index 90739eec1a..9e6a5434f9 100644 --- a/Projectiles/Melee/GalaxySmasherHammer.cs +++ b/Projectiles/Melee/GalaxySmasherHammer.cs @@ -1,9 +1,13 @@ using System; +using System.Collections.Generic; using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Dusts; +using CalamityMod.Graphics.Metaballs; using CalamityMod.Items.Weapons.Melee; using CalamityMod.Particles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using ReLogic.Content; using Terraria; using Terraria.Audio; using Terraria.ID; @@ -25,17 +29,19 @@ namespace CalamityMod.Projectiles.Melee public float EchoHammerPrep = 0f; public float WaitTimer = 0f; public int InPulse = 0; + public int time = 0; + public Color usedColor = Color.Aqua; public override void SetStaticDefaults() { - ProjectileID.Sets.TrailCacheLength[Projectile.type] = 14; - ProjectileID.Sets.TrailingMode[Projectile.type] = 1; + ProjectileID.Sets.TrailCacheLength[Projectile.type] = 20; + ProjectileID.Sets.TrailingMode[Projectile.type] = 2; } public override void SetDefaults() { - Projectile.width = 62; - Projectile.height = 62; + Projectile.width = 86; + Projectile.height = 72; Projectile.friendly = true; Projectile.DamageType = DamageClass.MeleeNoSpeed; Projectile.tileCollide = false; @@ -50,156 +56,202 @@ namespace CalamityMod.Projectiles.Melee { //returnhammer determines if the hammer is slowing down after hitting an enemy, or homing in on the player. Player player = Main.player[Projectile.owner]; - Projectile.direction = Projectile.spriteDirection = Projectile.velocity.X > 0f ? 1 : -1; - Projectile.rotation += MathHelper.ToRadians(rotatehammer) * Projectile.direction; + float targetDist = Vector2.Distance(player.Center, Projectile.Center); + Projectile.rotation += MathHelper.ToRadians(rotatehammer * 2) * Projectile.direction; + + List eColors = new List() + { + Color.Aqua, + Color.Magenta, + }; + float rate = (Main.GlobalTimeWrappedHourly * 12); + int colorIndex = (int)(rate / 2 % eColors.Count); + Color currentColor = eColors[colorIndex]; + Color nextColor = eColors[(colorIndex + 1) % eColors.Count]; + usedColor = Color.Lerp(currentColor, nextColor, rate % 2f > 1f ? 1f : rate % 1f); if (EmpoweredHammer >= 8) EmpoweredHammer = 0; if (returnhammer == 0) { - Projectile.velocity.X *= 0.988f; - Projectile.velocity.Y += 0.326f; + int falloffTime = 18; + if (time > falloffTime) + Projectile.velocity.X *= 0.96f; + if (Projectile.velocity.Y < 25 && time > falloffTime) + Projectile.velocity.Y += 0.54f; + if (Projectile.velocity.Y < 5) + Projectile.velocity.Y *= 0.973f; } if (returnhammer == 1) //Hammer slows after the inital hit { - if (EmpoweredHammer == 7) - { - ++WaitTimer; - if (WaitTimer == 20f) - { - Projectile.velocity *= 0f; - EmpoweredHammer = 0; - returnhammer = 3; - } - } - else - { - Projectile.velocity.Y *= 0.926f; - Projectile.velocity.X *= 0.811f; - if (Projectile.velocity.X > -1.05f && Projectile.velocity.X < 1.05f & Projectile.velocity.Y > -1.05f && Projectile.velocity.Y < 1.05f) - returnhammer = 2; - } + Projectile.velocity.Y *= 0.926f; + Projectile.velocity.X *= 0.811f; + if (Projectile.velocity.X > -1.05f && Projectile.velocity.X < 1.05f & Projectile.velocity.Y > -1.05f && Projectile.velocity.Y < 1.05f) + returnhammer = 2; } if (returnhammer == 2) // Projectile returns to player { - ++PulseCooldown; - Projectile.extraUpdates = 2; - float returnSpeed = StellarContempt.Speed; - float acceleration = 1.1f; - Player owner = Main.player[Projectile.owner]; - Vector2 playerCenter = owner.Center; - float xDist = playerCenter.X - Projectile.Center.X; - float yDist = playerCenter.Y - Projectile.Center.Y; - float dist = (float)Math.Sqrt(xDist * xDist + yDist * yDist); - dist = returnSpeed / dist; - xDist *= dist; - yDist *= dist; + if (WaitTimer == 0) + { + Projectile.extraUpdates = 2; + float returnSpeed = StellarContempt.Speed * 0.7f; + float acceleration = 1.1f; + Player owner = Main.player[Projectile.owner]; + Vector2 playerCenter = owner.Center; + float xDist = playerCenter.X - Projectile.Center.X; + float yDist = playerCenter.Y - Projectile.Center.Y; + float dist = (float)Math.Sqrt(xDist * xDist + yDist * yDist); + dist = returnSpeed / dist; + xDist *= dist; + yDist *= dist; - if (Projectile.velocity.X < xDist) - { - Projectile.velocity.X = Projectile.velocity.X + acceleration; - if (Projectile.velocity.X < 0f && xDist > 0f) - Projectile.velocity.X += acceleration; - } - else if (Projectile.velocity.X > xDist) - { - Projectile.velocity.X = Projectile.velocity.X - acceleration; - if (Projectile.velocity.X > 0f && xDist < 0f) - Projectile.velocity.X -= acceleration; - } - if (Projectile.velocity.Y < yDist) - { - Projectile.velocity.Y = Projectile.velocity.Y + acceleration; - if (Projectile.velocity.Y < 0f && yDist > 0f) - Projectile.velocity.Y += acceleration; - } - else if (Projectile.velocity.Y > yDist) - { - Projectile.velocity.Y = Projectile.velocity.Y - acceleration; - if (Projectile.velocity.Y > 0f && yDist < 0f) - Projectile.velocity.Y -= acceleration; + if (Projectile.velocity.X < xDist) + { + Projectile.velocity.X = Projectile.velocity.X + acceleration; + if (Projectile.velocity.X < 0f && xDist > 0f) + Projectile.velocity.X += acceleration; + } + else if (Projectile.velocity.X > xDist) + { + Projectile.velocity.X = Projectile.velocity.X - acceleration; + if (Projectile.velocity.X > 0f && xDist < 0f) + Projectile.velocity.X -= acceleration; + } + if (Projectile.velocity.Y < yDist) + { + Projectile.velocity.Y = Projectile.velocity.Y + acceleration; + if (Projectile.velocity.Y < 0f && yDist > 0f) + Projectile.velocity.Y += acceleration; + } + else if (Projectile.velocity.Y > yDist) + { + Projectile.velocity.Y = Projectile.velocity.Y - acceleration; + if (Projectile.velocity.Y > 0f && yDist < 0f) + Projectile.velocity.Y -= acceleration; + } } + // Delete the projectile if it touches its owner, increase counter to the big hammer, and spawn a dustsplosion on the player that scales with how close they are to getting a big hammer. if (Main.myPlayer == Projectile.owner) { - if (Projectile.Hitbox.Intersects(player.Hitbox)) + if (Projectile.Hitbox.Intersects(player.Hitbox) || WaitTimer > 0) { - EmpoweredHammer++; - SoundEngine.PlaySound(SoundID.DD2_BetsysWrathShot with { Volume = 0.4f }, Projectile.Center); - for (int i = 0; i < 30; i++) + if (EmpoweredHammer >= 7) { - Dust fire = Dust.NewDustPerfect(Projectile.Center, 181); - fire.velocity = Projectile.velocity.SafeNormalize(Vector2.UnitY).RotatedByRandom(0.8f) * new Vector2(4f, 1.25f) * Main.rand.NextFloat(0.9f, 1f); - fire.velocity = fire.velocity.RotatedBy(Projectile.rotation - MathHelper.PiOver2); - fire.velocity += Projectile.velocity * (EmpoweredHammer * 0.04f); + Projectile.extraUpdates = 1; + if (WaitTimer == 0) + Projectile.velocity = Projectile.velocity.SafeNormalize(Vector2.UnitX) * 20; + WaitTimer++; + Projectile.velocity *= 0.97f; + if (WaitTimer == 20f) + { + EmpoweredHammer = 0; + returnhammer = 3; + } + } + else + { + EmpoweredHammer++; + SoundEngine.PlaySound(SoundID.DD2_BetsysWrathShot with { Volume = 0.4f }, Projectile.Center); + for (int i = 0; i < 30; i++) + { + Dust fire = Dust.NewDustPerfect(Projectile.Center, 181); + fire.velocity = Projectile.velocity.SafeNormalize(Vector2.UnitY).RotatedByRandom(0.8f) * new Vector2(4f, 1.25f) * Main.rand.NextFloat(0.9f, 1f); + fire.velocity = fire.velocity.RotatedBy(Projectile.rotation - MathHelper.PiOver2); + fire.velocity += Projectile.velocity * (EmpoweredHammer * 0.04f); - fire.noGravity = true; - fire.scale = Main.rand.NextFloat(0.2f, 0.6f) * EmpoweredHammer; + fire.noGravity = true; + fire.scale = Main.rand.NextFloat(0.2f, 0.6f) * EmpoweredHammer; - fire = Dust.CloneDust(fire); - fire.velocity = Main.rand.NextVector2Circular(3f, 3f); - fire.velocity += Projectile.velocity * (EmpoweredHammer * 0.04f); + fire = Dust.CloneDust(fire); + fire.velocity = Main.rand.NextVector2Circular(3f, 3f); + fire.velocity += Projectile.velocity * (EmpoweredHammer * 0.04f); + } + Projectile.Kill(); } - Projectile.Kill(); } } } - if (returnhammer == 3) //Hammer prepares to spawn echo hammer, VibroIntensity + if (returnhammer == 3) //Hammer prepares to spawn echo hammer { if (InPulse == 0) { SoundEngine.PlaySound(RedHamSound, Projectile.Center); - Particle pulse = new DirectionalPulseRing(Projectile.Center, Vector2.Zero, Color.Aqua, new Vector2(1f, 1f), Main.rand.NextFloat(12f, 25f), 0.1f, 1.95f, 120); - GeneralParticleHandler.SpawnParticle(pulse); InPulse = 1; } - rotatehammer -= 0.25f; - if (EchoHammerPrep >= 17f) + rotatehammer -= 0.09f; + Projectile.velocity *= 0.96f; + if (EchoHammerPrep >= 5f && InPulse < 2) { - if (InPulse == 1) + if (time % 20 == 0) { - Particle pulse2 = new StaticPulseRing(Projectile.Center, Vector2.Zero, Color.Orchid, new Vector2(1f, 1f), 0f, 4.9f, 0f, 25); + Particle pulse2 = new CustomPulse(Projectile.Center, Vector2.Zero, usedColor * 0.35f, "CalamityMod/Particles/HighResHollowCircleHardEdge", new Vector2(1f, 1f * Utils.GetLerpValue(40, 20, EchoHammerPrep)), 0f, 2f, 0f, (int)(40 * Utils.GetLerpValue(50, 0, EchoHammerPrep, true))); GeneralParticleHandler.SpawnParticle(pulse2); - InPulse = 2; } } - - if (EchoHammerPrep <= 24f) + if (EchoHammerPrep >= 32) { - EchoHammerPrep += 0.2f; - Projectile.scale += 0.017f; - Particle streak = new ManaDrainStreak(player, Main.rand.NextFloat(0.7f, 0.9f), Main.rand.NextVector2CircularEdge(2f, 2f) * Main.rand.NextFloat(135f, 335f), Main.rand.NextFloat(20f, 20f), Color.Aqua, Color.Fuchsia, Main.rand.Next(10, 20), Projectile.Center); - GeneralParticleHandler.SpawnParticle(streak); + InPulse = 2; } - else + if (EchoHammerPrep <= 30f) + { + float fade = Utils.GetLerpValue(40, 0, EchoHammerPrep, true); + float numberOfDusts = 2f; + float rotFactor = 360f / numberOfDusts; + for (int i = 0; i < numberOfDusts; i++) + { + float rot = MathHelper.ToRadians(i * rotFactor); + Vector2 velOffset = CalamityUtils.RandomVelocity(100f, 70f, 250f, 0.04f); + velOffset *= Main.rand.NextFloat(45, 65) * fade; + Particle energy = new SparkParticle(Projectile.Center + velOffset * 2.5f, -velOffset * Main.rand.NextFloat(0.08f, 0.12f) * 1.5f, false, 14, Main.rand.NextFloat(1.1f, 1.25f) - 0.5f * fade, usedColor); + GeneralParticleHandler.SpawnParticle(energy); + Dust dust = Dust.NewDustPerfect(Projectile.Center + velOffset * 2.5f, 278, -velOffset * Main.rand.NextFloat(0.08f, 0.12f) * 1.5f, 0, default, Main.rand.NextFloat(0.4f, 0.6f)); + dust.noGravity = true; + dust.color = usedColor; + GalaxyMetaball.SpawnParticle(Projectile.Center + velOffset * 1.5f, -velOffset * Main.rand.NextFloat(0.08f, 0.12f) * 1.5f, 50f * Main.rand.NextFloat(0.9f, 1.3f) * fade); + } + } + if (EchoHammerPrep > 40) { int hammer = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Projectile.velocity, ModContent.ProjectileType(), Projectile.damage * 10, Projectile.knockBack * 2.5f, Projectile.owner, 0f, Projectile.ai[1]); Main.projectile[hammer].localAI[0] = Math.Sign(Projectile.velocity.X); Main.projectile[hammer].netUpdate = true; Projectile.Kill(); } + else + EchoHammerPrep += 0.2f; } - //Spawn dust as the hammer travels. - if (Main.rand.NextBool()) + if (targetDist < 1400) { - Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); - Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, 272, Projectile.velocity * 0.4f + velOffset, 100, default, 0.7f); - dust.noGravity = true; - } + if (Main.rand.NextBool(3) && returnhammer < 3) + { + Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); + Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, 278, -Projectile.velocity * 0.2f + velOffset, 100, default, 0.7f); + dust.noGravity = true; + dust.color = Main.rand.NextBool() ? Color.Magenta : Color.Aqua; + } - if (Main.rand.NextBool(6)) - { - Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); - Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, 226, Projectile.velocity * 0.5f + velOffset, 100, default, 0.7f); - dust.noGravity = true; + Vector2 offset2 = new Vector2(0, -30).RotatedBy(-MathHelper.PiOver4 * 0.5f).RotatedBy(Projectile.rotation); + Vector2 velOffset2 = new Vector2(0, -5).RotatedBy(-MathHelper.PiOver4).RotatedBy(Projectile.rotation).RotatedByRandom(0.4f) * Main.rand.NextFloat(0.8f, 1.5f); + Vector2 spawnPosition2 = Projectile.Center + offset2 + Main.rand.NextVector2Circular(6, 6); + Particle spark = new CustomSpark(spawnPosition2, velOffset2 * (InPulse > 0 ? 3 : 1), "CalamityMod/Particles/BloomRing", false, Main.rand.Next(7, 16), Main.rand.NextFloat(0.25f, 0.5f) * (InPulse > 0 ? 1.5f : 1), usedColor * 0.35f, new Vector2(1f, 1f), true, false, Main.rand.NextFloat(-10, 10)); + GeneralParticleHandler.SpawnParticle(spark); + + for (int i = 0; i < (InPulse > 0 ? 3 : 2); i++) + { + Vector2 offset = new Vector2(0, -30).RotatedBy(-MathHelper.PiOver4 * 0.5f).RotatedBy(Projectile.rotation); + Vector2 velOffset = new Vector2(0, -5).RotatedBy(-MathHelper.PiOver4).RotatedBy(Projectile.rotation) * Main.rand.NextFloat(0.4f, 1f); + Vector2 spawnPosition = Projectile.Center + offset + Main.rand.NextVector2Circular(6, 6); + GalaxyMetaball.SpawnParticle(spawnPosition, velOffset * (InPulse > 0 ? 3 : 0.2f), 40f * Main.rand.NextFloat(0.9f, 1.3f) * (InPulse > 0 ? 2 : 1)); + } } + time++; } // On hit play GONG and spawn dust. public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) @@ -207,6 +259,8 @@ namespace CalamityMod.Projectiles.Melee Player player = Main.player[Projectile.owner]; if (returnhammer == 0) { + Projectile.ai[1] = target.whoAmI; + if (Main.zenithWorld) SoundEngine.PlaySound(UseSoundFunny with { Pitch = EmpoweredHammer * 0.05f - 0.05f }, Projectile.Center); @@ -215,53 +269,82 @@ namespace CalamityMod.Projectiles.Melee int FunSizeHamID = ModContent.ProjectileType(); int FunSizeHamDamage = (int)(0.1f * Projectile.damage); - float FunSizeHamKB = 0.2f; - int NumOfFunSizeHams = EmpoweredHammer + 1; - for (int i = 0; i < NumOfFunSizeHams; ++i) + float FunSizeHamKB = 0.2f * Projectile.knockBack; + if (Projectile.owner == Main.myPlayer) { - float startDist = Main.rand.NextFloat(160f, 190f); - Vector2 startDir = Main.rand.NextVector2Unit(); - Vector2 startPoint = Projectile.Center + startDir * startDist; - - float FunSizeHamSpeed = Main.rand.NextFloat(10f, 14f); - Vector2 velocity = startDir * -FunSizeHamSpeed; - - if (Projectile.owner == Main.myPlayer) + float numberOfProj = EmpoweredHammer + 1; + float rotFactor2 = 360f / numberOfProj; + float randRot = Main.rand.NextFloat(-6, 6); + for (int i = 1; i < numberOfProj + 1; i++) { - int proj = Projectile.NewProjectile(Projectile.GetSource_FromThis(), startPoint, velocity, FunSizeHamID, FunSizeHamDamage, FunSizeHamKB, Projectile.owner); - if (proj.WithinBounds(Main.maxProjectiles)) - { - Main.projectile[proj].DamageType = DamageClass.MeleeNoSpeed; - Main.projectile[proj].tileCollide = false; - Main.projectile[proj].timeLeft = 30; - Main.projectile[proj].extraUpdates = 2; - } + float rot = MathHelper.ToRadians(i * rotFactor2); + Vector2 offset = new Vector2(5f, 0).RotatedBy(rot).RotatedBy(randRot); + Vector2 velOffset = new Vector2(1f, 0).RotatedBy(rot).RotatedBy(randRot); + + Projectile proj = Projectile.NewProjectileDirect(Projectile.GetSource_FromThis(), target.Center, velOffset, FunSizeHamID, FunSizeHamDamage, FunSizeHamKB, Projectile.owner, EmpoweredHammer, (EmpoweredHammer % 2 == 0 ? -1 : 1), target.whoAmI); } } returnhammer = 1; } - if (PulseCooldown >= 15) + float numberOfDusts = MathHelper.Clamp(30 - Projectile.numHits * 3, 6, 30); + float rotFactor = 360f / numberOfDusts; + for (int i = 0; i < numberOfDusts; i++) { - Particle pulse = new DirectionalPulseRing(Projectile.Center, Vector2.Zero, Color.Violet, new Vector2(0.5f, 0.5f), Main.rand.NextFloat(12f, 25f), 0.2f, 1.4f + (EmpoweredHammer * 0.1f), 14); - GeneralParticleHandler.SpawnParticle(pulse); - PulseCooldown = 0; + float rot = MathHelper.ToRadians(i * rotFactor); + Vector2 offset = new Vector2(4.8f, 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 4.1f)); + Vector2 velOffset = new Vector2(7f, 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 4.1f)); + + if (i % 3 == 0) + { + GalaxyMetaball.SpawnParticle(Projectile.Center + offset, velOffset * Main.rand.NextFloat(1f, 1.2f), 60f * Main.rand.NextFloat(0.9f, 1.3f)); + } + else + { + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, ModContent.DustType()); + dust.noGravity = true; + dust.velocity = velOffset * Main.rand.NextFloat(0.45f, 1); + dust.scale = Main.rand.NextFloat(0.8f, 1.7f); + dust.color = Main.rand.NextBool(3) ? Color.Aqua : Color.Magenta; + } } - SoundEngine.PlaySound(SoundID.Item14 with { Volume = 0.22f }, Projectile.Center); - Projectile.ai[1] = target.whoAmI; } public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) { - if (Projectile.numHits > 0) - Projectile.damage = (int)(Projectile.damage * 0.9f); - if (Projectile.damage < 1) - Projectile.damage = 1; + target.AddBuff(ModContent.BuffType(), 120); + float minMult = 0.7f; + int hitsToMinMult = 10; + float damageMult = Utils.Remap(Projectile.numHits, 0, hitsToMinMult, 1, minMult, true); + modifiers.SourceDamage *= damageMult; } public override bool PreDraw(ref Color lightColor) { - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 3); + Texture2D texture = ModContent.Request("CalamityMod/Items/Weapons/Melee/GalaxySmasher").Value; + Asset p = ModContent.Request("CalamityMod/Particles/FlameExplosion2"); + Asset p2 = ModContent.Request("CalamityMod/Particles/CircularSmearSmokey"); + Asset p3 = ModContent.Request("CalamityMod/Particles/SmallBloom"); + + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor * 0.5f, 3, texture, true, true); + + float shrinkLerp = (Utils.GetLerpValue(40, 35, EchoHammerPrep, true)); + float growLerp = (Utils.GetLerpValue(0, 35, EchoHammerPrep, true)); + float bonusScale = (returnhammer == 3 ? (EchoHammerPrep < 35 ? (growLerp * 3) : (shrinkLerp * 3)) : 1); + + Vector2 generalDrawPos = Projectile.Center - Main.screenPosition; + float fade = (returnhammer == 3 ? 1 : Utils.GetLerpValue(2, 15, Projectile.velocity.Length(), true)); + Main.EntitySpriteDraw(p3.Value, generalDrawPos, null, Color.Black * fade, Projectile.rotation, p3.Size() * 0.5f, 0.6f * bonusScale, SpriteEffects.None); + for (int i = 0; i < 3; i++) + Main.EntitySpriteDraw(p.Value, generalDrawPos, null, Color.Indigo * 0.95f * fade, Projectile.rotation * Main.rand.NextFloat(1.2f, 1.3f) + i * 0.2f, p.Size() * 0.5f, (0.05f + i * 0.004f) * bonusScale, SpriteEffects.None); + + Main.EntitySpriteDraw(texture, generalDrawPos, null, lightColor, Projectile.rotation, texture.Size() * 0.5f, Projectile.scale, Projectile.direction < 0 ? SpriteEffects.FlipHorizontally : SpriteEffects.None); + if (returnhammer < 3) + Main.EntitySpriteDraw(p2.Value, generalDrawPos, null, usedColor with { A = 0 } * 0.45f * fade, Projectile.rotation * Main.rand.NextFloat(1.4f, 1.45f), p2.Size() * 0.5f, 0.9f * Main.rand.NextFloat(0.9f, 1.1f), SpriteEffects.None); + else + { + Projectile.DrawProjectileWithBackglow(usedColor with { A = 0 }, Color.White, 6.5f * growLerp, texture, null, Projectile.direction < 0 ? SpriteEffects.FlipHorizontally : SpriteEffects.None); + } return false; } } diff --git a/Projectiles/Melee/GalaxySmasherMini.cs b/Projectiles/Melee/GalaxySmasherMini.cs index b6da381e62..81b77b82c9 100644 --- a/Projectiles/Melee/GalaxySmasherMini.cs +++ b/Projectiles/Melee/GalaxySmasherMini.cs @@ -1,8 +1,10 @@ -using CalamityMod.Particles; +using System.Collections.Generic; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Dusts; +using CalamityMod.Graphics.Metaballs; +using CalamityMod.Particles; using Microsoft.Xna.Framework; using Terraria; -using Terraria.Audio; -using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Melee @@ -10,57 +12,91 @@ namespace CalamityMod.Projectiles.Melee public class GalaxySmasherMini : ModProjectile, ILocalizedModType { public new string LocalizationCategory => "Projectiles.Melee"; - public override string Texture => "CalamityMod/Projectiles/Melee/GalaxySmasherMini"; - public static readonly SoundStyle HitSound = new("CalamityMod/Sounds/Item/WulfrumKnifeTileHit2") { Volume = 0.5f, PitchVariance = 0.7f }; - public float rotatehammer = 20f; + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + public float radius = 50f; + public int time = 0; + public bool homing = false; + public NPC targeted; public override void SetDefaults() { - Projectile.width = 86; - Projectile.height = 72; + Projectile.width = 90; + Projectile.height = 90; Projectile.friendly = true; Projectile.ignoreWater = true; - Projectile.DamageType = DamageClass.Melee; - Projectile.alpha = 80; + Projectile.tileCollide = false; + Projectile.DamageType = DamageClass.MeleeNoSpeed; Projectile.penetrate = -1; - Projectile.timeLeft = 30; - Projectile.scale = 0.7f; + Projectile.timeLeft = 500; + Projectile.extraUpdates = 3; Projectile.usesLocalNPCImmunity = true; - Projectile.localNPCHitCooldown = 60; + Projectile.localNPCHitCooldown = -1; } public override void AI() { - Projectile.direction = Projectile.spriteDirection = Projectile.velocity.X > 0f ? 1 : -1; - Projectile.rotation += MathHelper.ToRadians(rotatehammer) * Projectile.direction; + List eColors = new List() + { + Color.Aqua, + Color.Magenta, + }; + float rate = (Main.GlobalTimeWrappedHourly * 20); + int colorIndex = (int)(rate / 2 % eColors.Count); + Color currentColor = eColors[colorIndex]; + Color nextColor = eColors[(colorIndex + 1) % eColors.Count]; + Color usedColor = Color.Lerp(currentColor, nextColor, rate % 2f > 1f ? 1f : rate % 1f); + + if (time % 2 == 0) + { + Particle spark = new CustomSpark(Projectile.Center, -Projectile.velocity * 0.05f, "CalamityMod/Particles/SmallBloom", false, 6, 0.2f, usedColor, new Vector2(Utils.Remap(Projectile.velocity.Length(), 0, 5, 1, 0.6f, true), 1f), true, false, 0, false, false, Utils.Remap(Projectile.velocity.Length(), 0, 5, 0, 0.9f, true)); + GeneralParticleHandler.SpawnParticle(spark); + } + GalaxyMetaball.SpawnParticle(Projectile.Center, -Projectile.velocity.RotatedByRandom(0.25f) * Main.rand.NextFloat(0.2f, 0.7f), 30f * Main.rand.NextFloat(0.9f, 1f)); + + if (time > 45 || homing) + { + homing = true; + if (Projectile.ai[2] != -5) + targeted = Main.npc[(int)Projectile.ai[2]]; + if (targeted == null || !targeted.CanBeChasedBy(Projectile, false) || !targeted.active) + { + targeted = Projectile.Center.ClosestNPCAt(1000); + Projectile.ai[2] = -5; + } + + if (targeted != null) + { + float speedMult = 0.5f; + Vector2 moveTotarget = (targeted.Center - Projectile.Center).SafeNormalize(Vector2.UnitX); + if (Projectile.velocity.Length() < MathHelper.Clamp(25, 10, 25) * speedMult) + Projectile.velocity += moveTotarget * (0.35f) * speedMult; + else + Projectile.velocity *= 0.9f; + Projectile.extraUpdates = 3; + } + } + else + { + Projectile.velocity += Projectile.velocity.RotatedBy(0.24f * Projectile.ai[1]) * 0.04f; + Projectile.extraUpdates = 2; + } + + time += (homing ? -1 : 1); } public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - SoundEngine.PlaySound(HitSound, Projectile.Center); - float damageInterpolant = Utils.GetLerpValue(950f, 2000f, hit.Damage, true); - float impactAngularVelocity = MathHelper.Lerp(0.08f, 0.2f, damageInterpolant); - float impactParticleScale = MathHelper.Lerp(0.6f, 1f, damageInterpolant); - impactAngularVelocity *= Main.rand.NextBool().ToDirectionInt() * Main.rand.NextFloat(0.75f, 1.25f); - - Color impactColor = Color.Lerp(Color.Fuchsia, Color.Aqua, Main.rand.NextFloat(0.5f)); - Vector2 impactPoint = Vector2.Lerp(Projectile.Center, target.Center, 0.65f); - Vector2 bloodSpawnPosition = target.Center + Main.rand.NextVector2Circular(target.width, target.height) * 0.04f; - Vector2 splatterDirection = (Projectile.Center - bloodSpawnPosition).SafeNormalize(Vector2.UnitY); - for (int i = 0; i < 3; i++) + target.AddBuff(ModContent.BuffType(), 60); + for (int i = 0; i < 4; i++) { - int sparkLifetime = Main.rand.Next(9, 12); - float sparkScale = Main.rand.NextFloat(0.8f, 1f) + damageInterpolant * 0.85f; - Color sparkColor = Color.Lerp(Color.Fuchsia, Color.Aqua, Main.rand.NextFloat(0.7f)); - sparkColor = Color.Lerp(sparkColor, Color.Fuchsia, Main.rand.NextFloat()); - Vector2 sparkVelocity = splatterDirection.RotatedByRandom(0.6f) * Main.rand.NextFloat(12f, 25f); - sparkVelocity.Y -= 6f; - SparkParticle spark = new SparkParticle(impactPoint, sparkVelocity, true, sparkLifetime, sparkScale, sparkColor); - GeneralParticleHandler.SpawnParticle(spark); + Dust dust = Dust.NewDustPerfect(Projectile.Center, ModContent.DustType(), (Projectile.velocity * 3) * Main.rand.NextFloat(0.3f, 1f), 0, default, Main.rand.NextFloat(0.65f, 1f)); + dust.noGravity = true; + dust.color = Main.rand.NextBool() ? Color.Magenta : Color.Aqua; } - //Create an impact point particle. - ImpactParticle impactParticle = new ImpactParticle(impactPoint, impactAngularVelocity, 20, impactParticleScale, impactColor); - GeneralParticleHandler.SpawnParticle(impactParticle); + + if (target == targeted) + Projectile.Kill(); } + public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => homing ? CalamityUtils.CircularHitboxCollision(Projectile.Center, radius, targetHitbox) : false; } } diff --git a/Projectiles/Melee/GreenWater.cs b/Projectiles/Melee/GreenWater.cs index ed9b0cd04e..8b97207f36 100644 --- a/Projectiles/Melee/GreenWater.cs +++ b/Projectiles/Melee/GreenWater.cs @@ -1,4 +1,6 @@ using System; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Particles; using Microsoft.Xna.Framework; using Terraria; using Terraria.Audio; @@ -12,84 +14,143 @@ namespace CalamityMod.Projectiles.Melee public new string LocalizationCategory => "Projectiles.Melee"; private const int TimeLeft = 300; - - public override void SetStaticDefaults() - { - ProjectileID.Sets.TrailCacheLength[Projectile.type] = 4; - ProjectileID.Sets.TrailingMode[Projectile.type] = 0; - } + public Vector2 storedVel; public override void SetDefaults() { - Projectile.width = 20; - Projectile.height = 20; + Projectile.width = 40; + Projectile.height = 40; Projectile.friendly = true; + Projectile.alpha = 255; Projectile.ignoreWater = true; Projectile.tileCollide = false; Projectile.penetrate = 1; + Projectile.extraUpdates = 2; Projectile.timeLeft = TimeLeft; Projectile.DamageType = DamageClass.Melee; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = 30; } public override void AI() { - if (Projectile.ai[1] == 0f) + Player Owner = Main.player[Projectile.owner]; + + Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver4; + if (Projectile.ai[0] == 0) { - if (Projectile.Center.Y > Projectile.ai[2]) - Projectile.tileCollide = true; + if (Projectile.timeLeft == TimeLeft) + { + storedVel = Projectile.velocity; + Projectile.velocity = -Projectile.velocity; + } + if (Projectile.timeLeft > TimeLeft - 60) + { + Projectile.velocity *= 0.95f; + Projectile.rotation = storedVel.ToRotation() + MathHelper.PiOver4; + } else - Projectile.tileCollide = false; + { + + if (Projectile.timeLeft == TimeLeft - 60) + Projectile.velocity = storedVel; + + NPC target = Projectile.Center.ClosestNPCAt(500); + Vector2 moveToMouse; + if (target != null) + moveToMouse = (target.Center - Projectile.Center).SafeNormalize(Vector2.UnitX); + else + moveToMouse = Vector2.Zero; + + if (Projectile.velocity.Length() < 12 && Projectile.timeLeft > 60) + Projectile.velocity += moveToMouse * 0.2f; + else + Projectile.velocity *= 0.9f; + + if (Main.rand.NextBool(5)) + { + Particle spark = new GlowOrbParticle(Projectile.Center - Projectile.velocity.SafeNormalize(Vector2.UnitX) * 3 + Main.rand.NextVector2Circular(6, 6), -Projectile.velocity * Main.rand.NextFloat(0.2f, 0.6f), true, 13, Main.rand.NextFloat(0.55f, 0.8f), Color.DarkRed * 0.8f, false, false, false); + GeneralParticleHandler.SpawnParticle(spark); + } + } + } + else if (Projectile.ai[0] == 1) + { + NPC target = Projectile.Center.ClosestNPCAt(200); + Vector2 moveToMouse; + if (target != null) + moveToMouse = (target.Center - Projectile.Center).SafeNormalize(Vector2.UnitX); + else + moveToMouse = Vector2.Zero; + + if (Projectile.velocity.Length() < 8 && Projectile.timeLeft > 60) + Projectile.velocity += moveToMouse * 0.1f; + else + Projectile.velocity *= 0.98f; } else { - if (Projectile.Center.Y < Projectile.ai[2]) - Projectile.tileCollide = true; - else - Projectile.tileCollide = false; + Projectile.scale = 1.2f; + // Spawn in a helix-style pattern + float sine = (float)Math.Sin(Projectile.timeLeft * 0.575f / MathHelper.Pi); + + Vector2 offset = Projectile.velocity.SafeNormalize(Vector2.UnitX).RotatedBy(MathHelper.PiOver2) * sine * 8f; + + float fade = Utils.GetLerpValue(255, 0, Projectile.alpha); + SparkParticle orb = new(Projectile.Center + offset, -Projectile.velocity * 0.05f, false, 7, 0.7f, Color.Aqua * 0.6f * fade); + GeneralParticleHandler.SpawnParticle(orb); + + SparkParticle orb2 = new(Projectile.Center - offset, -Projectile.velocity * 0.05f, false, 7, 0.7f, Color.Aqua * 0.6f * fade); + GeneralParticleHandler.SpawnParticle(orb2); + + Dust dust = Dust.NewDustPerfect(Projectile.Center - Projectile.velocity.SafeNormalize(Vector2.UnitX) * 3 + Main.rand.NextVector2Circular(6, 6), 102, (-Projectile.velocity.SafeNormalize(Vector2.UnitX) * 9).RotatedByRandom(0.3f) * Main.rand.NextFloat(0.1f, 0.8f), 180, default, Main.rand.NextFloat(0.8f, 1.4f)); + dust.noGravity = true; + dust.alpha = (int)MathHelper.Clamp(Projectile.alpha, 0, 180); + + if (Projectile.timeLeft > 130) + { + Projectile.alpha = (int)(Utils.Remap(Projectile.timeLeft, 150, 130, 255, 0)); + } } - Lighting.AddLight(Projectile.Center, 0.5f, 0.25f, 0f); - - Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver4; - - if (Projectile.localAI[0] == 0f) + if (Main.rand.NextBool()) { - SoundEngine.PlaySound(SoundID.Item21, Projectile.position); - Projectile.localAI[0] += 1f; + Dust dust = Dust.NewDustPerfect(Projectile.Center - Projectile.velocity.SafeNormalize(Vector2.UnitX) * 3 + Main.rand.NextVector2Circular(6, 6), 5, (-Projectile.velocity.SafeNormalize(Vector2.UnitX) * 4).RotatedByRandom(0.3f) * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.8f, 1.4f)); + dust.noGravity = true; + dust.alpha = (int)MathHelper.Clamp(Projectile.alpha, 0, 100); } - - int blood = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.Blood, 0f, 0f, 100, default, Main.rand.NextFloat(1.6f, 2.4f)); - Main.dust[blood].noGravity = true; - Main.dust[blood].velocity *= 0.5f; - } - - public override bool PreDraw(ref Color lightColor) - { - if (Projectile.timeLeft > TimeLeft - 5) - return false; - - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1); - return false; - } - - public override void OnKill(int timeLeft) - { - SoundEngine.PlaySound(SoundID.NPCDeath12, Projectile.Center); - - for (int i = 4; i < 31; i++) + if (Projectile.timeLeft <= 60) { - float oldXPos = Projectile.oldVelocity.X * (30f / (float)i); - float oldYPos = Projectile.oldVelocity.Y * (30f / (float)i); - int killDust = Dust.NewDust(new Vector2(Projectile.oldPosition.X - oldXPos, Projectile.oldPosition.Y - oldYPos), 8, 8, DustID.Blood, Projectile.oldVelocity.X, Projectile.oldVelocity.Y, 100, default, 1.8f); - Main.dust[killDust].noGravity = true; - Dust dust = Main.dust[killDust]; - dust.velocity *= 0.5f; - killDust = Dust.NewDust(new Vector2(Projectile.oldPosition.X - oldXPos, Projectile.oldPosition.Y - oldYPos), 8, 8, DustID.Blood, Projectile.oldVelocity.X, Projectile.oldVelocity.Y, 100, default, 1.4f); - dust = Main.dust[killDust]; - dust.velocity *= 0.05f; + Projectile.alpha = (int)(Utils.Remap(Projectile.timeLeft, 0, 60, 255, 0)); + } + if (Projectile.timeLeft > TimeLeft - 20) + { + Projectile.alpha = (int)(Utils.Remap(Projectile.timeLeft, TimeLeft, TimeLeft - 20, 255, 0)); } } - - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(BuffID.Venom, 90); + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) + { + if (Projectile.ai[0] == 2) // Water tooth + { + target.AddBuff(BuffID.Wet, 300); + target.AddBuff(ModContent.BuffType(), 300); + } + if (Projectile.ai[0] == 0) // "Jaw" teeth + { + target.AddBuff(ModContent.BuffType(), 180); + } + for (int i = 0; i <= 4; i++) + { + Dust dust = Dust.NewDustPerfect(Projectile.Center, 5, (Projectile.velocity * 2.5f).RotatedByRandom(0.7) * Main.rand.NextFloat(0.1f, 0.8f), 0, default, Main.rand.NextFloat(0.9f, 1.8f)); + dust.noGravity = false; + } + for (int i = 0; i <= 2; i++) + { + Particle spark = new AltSparkParticle(Projectile.Center, (Projectile.velocity * 4.5f).RotatedByRandom(0.7) * Main.rand.NextFloat(0.1f, 0.8f) + new Vector2(0, -2), true, 20, 0.5f, Color.DarkRed * 0.7f); + GeneralParticleHandler.SpawnParticle(spark); + } + SoundStyle sound = new("CalamityMod/Sounds/NPCHit/PerfSmallHit", 3); + SoundEngine.PlaySound(sound with { Volume = 0.5f, Pitch = Main.rand.NextFloat(-0.2f, -0.3f) }, Projectile.Center); + } } } diff --git a/Projectiles/Melee/IceBombFriendly.cs b/Projectiles/Melee/IceBombFriendly.cs index 90414812a7..5bd09ba952 100644 --- a/Projectiles/Melee/IceBombFriendly.cs +++ b/Projectiles/Melee/IceBombFriendly.cs @@ -2,6 +2,7 @@ using CalamityMod.Buffs.StatDebuffs; using CalamityMod.Projectiles.Rogue; using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.Audio; using Terraria.ID; @@ -13,6 +14,8 @@ namespace CalamityMod.Projectiles.Melee { public new string LocalizationCategory => "Projectiles.Melee"; public override string Texture => "CalamityMod/Projectiles/Boss/IceBomb"; + public ref float Timer => ref Projectile.ai[0]; + public const float FormTime = 60f; public override void SetDefaults() { @@ -22,16 +25,28 @@ namespace CalamityMod.Projectiles.Melee Projectile.friendly = true; Projectile.DamageType = DamageClass.Melee; Projectile.penetrate = 1; - Projectile.timeLeft = 180; + Projectile.timeLeft = 120; Projectile.tileCollide = false; } - public override bool? CanDamage() => Projectile.ai[0] >= 120f; + public override bool? CanDamage() => false; public override void AI() { - Projectile.velocity *= 0.98f; + NPC npc = Main.npc[(int)Projectile.ai[1]]; + // Rotate around the hit enemy + if (!npc.active) + Projectile.Kill(); + else + { + Vector2 centerOffset = new Vector2((npc.height < npc.width ? npc.height : npc.width) * 0.7f, 0f); + // Enforce a minimum offset so that it doesn't look weird on small enemies + centerOffset.X = MathHelper.Max(centerOffset.X, 45f); + Projectile.Center = npc.Center + centerOffset.RotatedBy((MathHelper.Pi / 30f * Timer) + (MathHelper.PiOver2 * Projectile.ai[2])); + } + + // Constantly pulse in size and transparency if (Projectile.localAI[0] == 0f) { Projectile.scale += 0.01f; @@ -53,67 +68,48 @@ namespace CalamityMod.Projectiles.Melee } } - if (Projectile.ai[0] < 120f) + // Once out for long enough, materialize + Timer++; + if (Timer == FormTime) { - Projectile.ai[0] += 1f; - if (Projectile.ai[0] == 120f) + for (int i = 0; i < 8; i++) { - for (int i = 0; i < 8; i++) + Dust icyDust = Dust.NewDustDirect(Projectile.position, Projectile.width, Projectile.height, DustID.IceRod, 0f, 0f, 100, default, 2f); + icyDust.velocity *= 3f; + if (Main.rand.NextBool()) { - int icyDust = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.IceRod, 0f, 0f, 100, default, 2f); - Main.dust[icyDust].velocity *= 3f; - if (Main.rand.NextBool()) - { - Main.dust[icyDust].scale = 0.5f; - Main.dust[icyDust].fadeIn = 1f + Main.rand.Next(10) * 0.1f; - } + icyDust.scale = 0.5f; + icyDust.fadeIn = 1f + Main.rand.Next(10) * 0.1f; } - for (int j = 0; j < 14; j++) - { - int icyDust2 = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.IceRod, 0f, 0f, 100, default, 3f); - Main.dust[icyDust2].noGravity = true; - Main.dust[icyDust2].velocity *= 5f; - icyDust2 = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, DustID.IceRod, 0f, 0f, 100, default, 2f); - Main.dust[icyDust2].velocity *= 2f; - } - - Projectile.scale = 1f; - Projectile.ExpandHitboxBy((int)(30f * Projectile.scale)); - SoundEngine.PlaySound(SoundID.Item30, Projectile.Center); } + for (int j = 0; j < 14; j++) + { + Dust icyDust2 = Dust.NewDustDirect(Projectile.position, Projectile.width, Projectile.height, DustID.IceRod, 0f, 0f, 100, default, 3f); + icyDust2.noGravity = true; + icyDust2.velocity *= 5f; + icyDust2 = Dust.NewDustDirect(Projectile.position, Projectile.width, Projectile.height, DustID.IceRod, 0f, 0f, 100, default, 2f); + icyDust2.velocity *= 2f; + } + + Projectile.scale = 1f; + Projectile.ExpandHitboxBy((int)(30f * Projectile.scale)); + SoundEngine.PlaySound(SoundID.Item30, Projectile.Center); } } - public override Color? GetAlpha(Color lightColor) - { - return Main.dayTime ? new Color(50, 50, 255, Projectile.alpha) : new Color(255, 255, 255, Projectile.alpha); - } + public override Color? GetAlpha(Color lightColor) => Main.dayTime ? new Color(50, 50, 255, Projectile.alpha) : new Color(255, 255, 255, Projectile.alpha); public override void OnKill(int timeLeft) { SoundEngine.PlaySound(SoundID.Item27, Projectile.position); - float spread = 90f * 0.0174f; - double startAngle = Math.Atan2(Projectile.velocity.X, Projectile.velocity.Y) - spread / 2; - double deltaAngle = spread / 8f; - double offsetAngle; - int i; if (Projectile.owner == Main.myPlayer) { - for (i = 0; i < 2; i++) + for (int i = 0; i < 4; i++) { - offsetAngle = startAngle + deltaAngle * (i + i * i) / 2f + 32f * i; - int projectile1 = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center.X, Projectile.Center.Y, (float)(Math.Sin(offsetAngle) * 5f), (float)(Math.Cos(offsetAngle) * 5f), ModContent.ProjectileType(), (int)(Projectile.damage * 0.5), 0f, Projectile.owner, 0f, 0f); - if (projectile1.WithinBounds(Main.maxProjectiles)) - { - Main.projectile[projectile1].DamageType = DamageClass.Melee; - Main.projectile[projectile1].penetrate = 2; - } - int projectile2 = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center.X, Projectile.Center.Y, (float)(-Math.Sin(offsetAngle) * 5f), (float)(-Math.Cos(offsetAngle) * 5f), ModContent.ProjectileType(), (int)(Projectile.damage * 0.5), 0f, Projectile.owner, 0f, 0f); - if (projectile2.WithinBounds(Main.maxProjectiles)) - { - Main.projectile[projectile2].DamageType = DamageClass.Melee; - Main.projectile[projectile2].penetrate = 2; - } + Vector2 shardVelocity = -Vector2.UnitY.RotatedByRandom(MathHelper.Pi) * Main.rand.NextFloat(2.25f, 4.5f); + int iceShard = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, shardVelocity, ModContent.ProjectileType(), (int)(Projectile.damage * 0.5), 0f, Projectile.owner, 0f, 0f); + if (iceShard.WithinBounds(Main.maxProjectiles)) + Main.projectile[iceShard].DamageType = DamageClass.Melee; } } @@ -121,9 +117,13 @@ namespace CalamityMod.Projectiles.Melee Dust.NewDust(Projectile.position + Projectile.velocity, Projectile.width, Projectile.height, DustID.IceRod, Projectile.oldVelocity.X * 0.5f, Projectile.oldVelocity.Y * 0.5f); } - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 30); + + public override bool PreDraw(ref Color lightColor) { - target.AddBuff(ModContent.BuffType(), 30); + Texture2D tex = ModContent.Request(Texture).Value; + Main.EntitySpriteDraw(tex, Projectile.Center - Main.screenPosition, null, lightColor, Projectile.rotation, tex.Size() / 2f, Projectile.scale, SpriteEffects.None); + return false; } } } diff --git a/Projectiles/Melee/PwnagehammerEcho.cs b/Projectiles/Melee/PwnagehammerEcho.cs index 47a383bacf..cf48232e18 100644 --- a/Projectiles/Melee/PwnagehammerEcho.cs +++ b/Projectiles/Melee/PwnagehammerEcho.cs @@ -1,6 +1,4 @@ -using System; -using System.IO; -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.Audio; @@ -16,6 +14,7 @@ namespace CalamityMod.Projectiles.Melee public static readonly SoundStyle Kunk = new("CalamityMod/Sounds/Item/TF2PanHit") { Volume = 1.1f }; public int Explodamage = 0; public float speed = 0f; + public NPC targeted; public override void SetStaticDefaults() { ProjectileID.Sets.CultistIsResistantTo[Type] = true; @@ -30,55 +29,57 @@ namespace CalamityMod.Projectiles.Melee Projectile.aiStyle = 0; Projectile.friendly = true; Projectile.DamageType = DamageClass.MeleeNoSpeed; - Projectile.penetrate = 1; + Projectile.penetrate = -1; Projectile.tileCollide = false; Projectile.ignoreWater = true; Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = -1; } public override Color? GetAlpha(Color lightColor) { - return new Color(255, 248, 124, 255); + return new Color(255, 248, 124, 255) with { A = 0 }; } public override void AI() { speed = Projectile.velocity.Length(); Projectile.ai[0] += 1f; - if (Projectile.ai[0] > 55f) - { - CalamityUtils.HomeInOnNPC(Projectile, Projectile.tileCollide, 2000f, speed, 12f); - } if (Projectile.ai[0] < 42f) { Projectile.velocity.Y *= 0.9575f; - Projectile.rotation += MathHelper.ToRadians(Projectile.ai[0] * 0.5f) * Projectile.localAI[0]; + Projectile.velocity.X *= 0.98f; + Projectile.rotation += MathHelper.ToRadians(Projectile.ai[0] * 0.5f) * Projectile.localAI[0] * Projectile.direction; } - else if (Projectile.ai[0] < 44f) + else if (Projectile.ai[0] >= 42f) { + Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver2 * 0.5f; Projectile.extraUpdates = 2; - if (Projectile.ai[1] < 0f) - { - Projectile.Kill(); - return; - } - NPC target = Main.npc[(int)Projectile.ai[1]]; - if (!target.CanBeChasedBy(Projectile, false) || !target.active) - Projectile.Kill(); - else + if (Projectile.ai[1] != -5) + targeted = Main.npc[(int)Projectile.ai[1]]; + if (targeted == null || !targeted.CanBeChasedBy(Projectile, false) || !targeted.active) { - float velConst = 24f; - Projectile.velocity = new Vector2((target.Center.X - Projectile.Center.X) / velConst, (target.Center.Y - Projectile.Center.Y) / velConst); - Projectile.rotation += MathHelper.ToRadians(48f) * Projectile.localAI[0]; + Projectile.ai[1] = -5; + targeted = Projectile.Center.ClosestNPCAt(2000); } + if (targeted != null) + { + Vector2 moveTotarget = (targeted.Center - Projectile.Center).SafeNormalize(Vector2.UnitX); + if (Projectile.velocity.Length() < MathHelper.Clamp(25 - Projectile.ai[0] * 0.1f, 10, 25)) + Projectile.velocity += moveTotarget * (0.35f + Projectile.ai[0] * 0.03f); + else + Projectile.velocity *= 0.9f; + } + else + Projectile.Kill(); } if (Main.rand.NextBool()) { Vector2 offset = new Vector2(7, 0).RotatedByRandom(MathHelper.ToRadians(360f)); Vector2 velOffset = new Vector2(3, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(Projectile.position + offset, DustID.GoldFlame, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(255, 245, 198), 2f); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, DustID.GoldFlame, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(255, 245, 198), 2f); dust.noGravity = true; } @@ -86,7 +87,7 @@ namespace CalamityMod.Projectiles.Melee { Vector2 offset = new Vector2(7, 0).RotatedByRandom(MathHelper.ToRadians(360f)); Vector2 velOffset = new Vector2(3, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(Projectile.position + offset, DustID.GoldFlame, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(255, 245, 198), 2f); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, DustID.GoldFlame, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(255, 245, 198), 2f); dust.noGravity = true; } } @@ -97,29 +98,27 @@ namespace CalamityMod.Projectiles.Melee return false; return null; } - - public override bool CanHitPvp(Player target) => Projectile.ai[0] > 42f; - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - Projectile.localAI[0] = target.whoAmI; + if (target == targeted) + Projectile.Kill(); } public override bool PreKill(int timeLeft) { Player player = Main.player[Projectile.owner]; - float numberOfDusts = 32f; + float numberOfDusts = 45f; float rotFactor = 360f / numberOfDusts; for (int i = 0; i < numberOfDusts; i++) { float rot = MathHelper.ToRadians(i * rotFactor); Vector2 offset = new Vector2(15f, 0).RotatedBy(rot); Vector2 velOffset = new Vector2(12.5f, 0).RotatedBy(rot); - int dust = Dust.NewDust(Projectile.position + offset, Projectile.width, Projectile.height, DustID.Sandnado, velOffset.X, velOffset.Y); - Main.dust[dust].noGravity = true; - Main.dust[dust].velocity = velOffset; - Main.dust[dust].scale = 3f; + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, DustID.Sandnado, velOffset); + dust.noGravity = true; + dust.velocity = velOffset * (i % 2 == 0 ? 0.9f : i % 3 == 0 ? 0.8f : 1f); + dust.scale = 3f; } if (Main.zenithWorld) @@ -135,20 +134,9 @@ namespace CalamityMod.Projectiles.Melee public override bool PreDraw(ref Color lightColor) { - SpriteEffects spriteEffects = SpriteEffects.None; - if (Projectile.spriteDirection == -1) - spriteEffects = SpriteEffects.FlipHorizontally; Texture2D texture = Terraria.GameContent.TextureAssets.Projectile[Projectile.type].Value; - Rectangle sourceRectangle = new Rectangle(0, 0, texture.Width, texture.Height); - Vector2 origin = sourceRectangle.Size() / 2f; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], Color.Gold with { A = 0 } * 0.5f, 1, texture, true, true); - for (int i = 0; i < Projectile.oldPos.Length; i++) - { - float rot = MathHelper.ToRadians(22.5f) * Math.Sign(Projectile.velocity.X); - Vector2 drawPos = Projectile.oldPos[i] - Main.screenPosition + origin + new Vector2(0f, Projectile.gfxOffY); - Color color = Projectile.GetAlpha(lightColor) * ((Projectile.oldPos.Length - i) / (float)Projectile.oldPos.Length); - Main.EntitySpriteDraw(texture, drawPos, new Rectangle?(), color, Projectile.rotation - i * rot, origin, Projectile.scale, spriteEffects, 0); - } return false; } } diff --git a/Projectiles/Melee/PwnagehammerExplosionSmall.cs b/Projectiles/Melee/PwnagehammerExplosionSmall.cs index 04e984ab38..8f69a02068 100644 --- a/Projectiles/Melee/PwnagehammerExplosionSmall.cs +++ b/Projectiles/Melee/PwnagehammerExplosionSmall.cs @@ -1,9 +1,5 @@ -using System; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework; using Terraria; -using Terraria.Audio; -using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Melee @@ -29,7 +25,13 @@ namespace CalamityMod.Projectiles.Melee Projectile.usesLocalNPCImmunity = true; Projectile.localNPCHitCooldown = 10; } - + public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) + { + if (Projectile.numHits > 0) + Projectile.damage = (int)(Projectile.damage * 0.85f); + if (Projectile.damage < 1) + Projectile.damage = 1; + } public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, ExplosionRadius, targetHitbox); } } diff --git a/Projectiles/Melee/PwnagehammerProj.cs b/Projectiles/Melee/PwnagehammerProj.cs index 241777b227..d180d605ef 100644 --- a/Projectiles/Melee/PwnagehammerProj.cs +++ b/Projectiles/Melee/PwnagehammerProj.cs @@ -1,5 +1,4 @@ using System; -using System.IO; using Microsoft.Xna.Framework; using Terraria; using Terraria.Audio; @@ -15,6 +14,7 @@ namespace CalamityMod.Projectiles.Melee public static readonly SoundStyle UseSound = new("CalamityMod/Sounds/Item/PwnagehammerSound") { Volume = 0.35f }; public static readonly SoundStyle UseSoundFunny = new("CalamityMod/Sounds/Item/CalamityBell") { Volume = 1.5f }; public static int HighBong = 0; + public int time = 0; public ref int EmpoweredHammer => ref Main.player[Projectile.owner].Calamity().StellarHammer; public override void SetStaticDefaults() @@ -25,12 +25,13 @@ namespace CalamityMod.Projectiles.Melee public override void SetDefaults() { - Projectile.width = Projectile.height = 40; + Projectile.width = Projectile.height = 66; Projectile.friendly = true; Projectile.timeLeft = 3600; Projectile.DamageType = DamageClass.MeleeNoSpeed; Projectile.usesLocalNPCImmunity = true; Projectile.localNPCHitCooldown = 10; + Projectile.extraUpdates = 1; } public override void AI() @@ -40,25 +41,22 @@ namespace CalamityMod.Projectiles.Melee if (EmpoweredHammer >= 5) EmpoweredHammer = 0; - Projectile.velocity.X *= 0.9511f; - Projectile.velocity.Y += 0.502f; + int falloffTime = 10; + if (time > falloffTime) + Projectile.velocity.X *= 0.9711f; + if (Projectile.velocity.Y < 15 && time > falloffTime) + Projectile.velocity.Y += 0.426f; + if (Projectile.velocity.Y < 5) + Projectile.velocity.Y *= 0.98f; - if (Main.rand.NextBool()) + if (Main.rand.NextBool(3)) { Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, DustID.GoldFlame, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(255, 245, 198), 2f); + Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, DustID.GoldFlame, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(255, 245, 198), 1.5f); dust.noGravity = true; } - - if (Main.rand.NextBool(6)) - { - Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); - Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, DustID.GoldFlame, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100, new Color(255, 245, 198), 2f); - dust.noGravity = true; - } - + time++; } public override bool PreKill(int timeLeft) @@ -71,7 +69,7 @@ namespace CalamityMod.Projectiles.Melee float rot = MathHelper.ToRadians(i * rotFactor); Vector2 offset = new Vector2(9f, 0).RotatedBy(rot); Vector2 velOffset = new Vector2(6f, 0).RotatedBy(rot); - Dust dust = Dust.NewDustPerfect(Projectile.position + offset, 269, new Vector2(velOffset.X, velOffset.Y)); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, 269, new Vector2(velOffset.X, velOffset.Y)); dust.noGravity = true; dust.velocity = velOffset; dust.scale = 2.5f; @@ -104,12 +102,11 @@ namespace CalamityMod.Projectiles.Melee if (EmpoweredHammer >= 3) { Projectile.ai[1] = target.whoAmI; - int hammer = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, new Vector2(0, -15f), ModContent.ProjectileType(), Projectile.damage * 2, Projectile.knockBack * 1.5f, Projectile.owner, 0f, Projectile.ai[1]); + int hammer = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, new Vector2(Projectile.velocity.SafeNormalize(Vector2.UnitX).X * 5, -15f), ModContent.ProjectileType(), Projectile.damage * 2, Projectile.knockBack * 1.5f, Projectile.owner, 0f, Projectile.ai[1]); Main.projectile[hammer].localAI[0] = Math.Sign(Projectile.velocity.X); Main.projectile[hammer].netUpdate = true; EmpoweredHammer = 0; HighBong = 1; - } else { diff --git a/Projectiles/Melee/StellarContemptBlast.cs b/Projectiles/Melee/StellarContemptBlast.cs index 819d4aaaf6..0f27f3d0ff 100644 --- a/Projectiles/Melee/StellarContemptBlast.cs +++ b/Projectiles/Melee/StellarContemptBlast.cs @@ -1,9 +1,6 @@ -using System; +using CalamityMod.Buffs.DamageOverTime; using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; using Terraria; -using Terraria.Audio; -using Terraria.ID; using Terraria.ModLoader; namespace CalamityMod.Projectiles.Melee @@ -29,6 +26,14 @@ namespace CalamityMod.Projectiles.Melee Projectile.usesLocalNPCImmunity = true; Projectile.localNPCHitCooldown = 10; } + public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) + { + target.AddBuff(ModContent.BuffType(), 240); + if (Projectile.numHits > 0) + Projectile.damage = (int)(Projectile.damage * 0.95f); + if (Projectile.damage < 1) + Projectile.damage = 1; + } public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, ExplosionRadius, targetHitbox); } diff --git a/Projectiles/Melee/StellarContemptEcho.cs b/Projectiles/Melee/StellarContemptEcho.cs index 94ef8d23cc..39a9736341 100644 --- a/Projectiles/Melee/StellarContemptEcho.cs +++ b/Projectiles/Melee/StellarContemptEcho.cs @@ -1,5 +1,6 @@ -using System; -using System.IO; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Dusts; +using CalamityMod.Particles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -17,6 +18,7 @@ namespace CalamityMod.Projectiles.Melee public float rotatehammer = 35f; public int ColorAlpha = 225; public float speed = 0f; + public NPC targeted; public override void SetStaticDefaults() { @@ -25,7 +27,6 @@ namespace CalamityMod.Projectiles.Melee ProjectileID.Sets.TrailingMode[Projectile.type] = 0; } - // This is all copied straight from PwnagehammerEcho with some minor edits. public override void SetDefaults() { Projectile.width = 74; @@ -33,21 +34,14 @@ namespace CalamityMod.Projectiles.Melee Projectile.aiStyle = 0; Projectile.friendly = true; Projectile.DamageType = DamageClass.MeleeNoSpeed; - Projectile.penetrate = 1; + Projectile.penetrate = -1; Projectile.tileCollide = false; Projectile.ignoreWater = true; Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = -1; } - - public override Color? GetAlpha(Color lightColor) - { - return new Color(64, 224, 208, ColorAlpha); - } - public override void AI() { - Projectile.scale = 1.8f; - ColorAlpha -= 4; rotatehammer--; Projectile.rotation += MathHelper.ToRadians(rotatehammer) * Projectile.direction; @@ -57,48 +51,57 @@ namespace CalamityMod.Projectiles.Melee Projectile.velocity *= 0.95f; Projectile.rotation += MathHelper.ToRadians(Projectile.ai[0] * 0.5f) * Projectile.localAI[0]; } - else if (Projectile.ai[0] > 42f) + else if (Projectile.ai[0] >= 42f) { - Projectile.extraUpdates = 1; - if (Projectile.ai[1] < 0f) + Projectile.extraUpdates = 5; + if (Projectile.ai[1] != -5) + targeted = Main.npc[(int)Projectile.ai[1]]; + if (targeted == null || !targeted.CanBeChasedBy(Projectile, false) || !targeted.active) { - CalamityUtils.HomeInOnNPC(Projectile, Projectile.tileCollide, 2000f, speed, 12f); - if (Projectile.ai[0] > 80f) - Projectile.Kill(); - return; + Projectile.ai[1] = -5; + targeted = Projectile.Center.ClosestNPCAt(2000); } - - NPC target = Main.npc[(int)Projectile.ai[1]]; - if (!target.CanBeChasedBy(Projectile, false) || !target.active) + if (targeted != null) { - Projectile.Kill(); + float speedMult = 0.85f; + Vector2 moveTotarget = (targeted.Center - Projectile.Center).SafeNormalize(Vector2.UnitX); + if (Projectile.velocity.Length() < MathHelper.Clamp(25 - Projectile.ai[0] * 0.1f, 10, 25) * speedMult) + Projectile.velocity += moveTotarget * (0.35f + Projectile.ai[0] * 0.03f) * speedMult; + else + Projectile.velocity *= 0.9f; } else + Projectile.Kill(); + + if (Main.rand.NextBool(6)) { - float velConst = 7f; - velConst--; - Projectile.velocity = new Vector2((target.Center.X - Projectile.Center.X) / velConst, (target.Center.Y - Projectile.Center.Y) / velConst); - Projectile.rotation += MathHelper.ToRadians(48f) * Projectile.localAI[0]; + Vector2 offset = new Vector2(7, 0).RotatedByRandom(MathHelper.ToRadians(360f)); + Vector2 velOffset = new Vector2(3, 0).RotatedBy(offset.ToRotation()); + Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, ModContent.DustType(), new Vector2(Projectile.velocity.X * 0.5f + velOffset.X, Projectile.velocity.Y * 0.5f + velOffset.Y)); + dust.noGravity = true; + dust.scale = Main.rand.NextFloat(1.5f, 1.9f); + dust.color = Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise; + } + } + if (Projectile.ai[0] == 42f && targeted != null) + { + for (int i = 0; i < 20; i++) + { + Dust dust = Dust.NewDustPerfect(Projectile.Center, 278, ((targeted.Center - Projectile.Center).SafeNormalize(Vector2.UnitX) * 25).RotatedByRandom(0.6f) * Main.rand.NextFloat(0.2f, 1f)); + dust.noGravity = true; + dust.scale = Main.rand.NextFloat(0.8f, 1.9f); + dust.color = Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise; } } - - if (Main.rand.NextBool()) + for (int i = 0; i < 2; i++) { - Vector2 offset = new Vector2(7, 0).RotatedByRandom(MathHelper.ToRadians(360f)); - Vector2 velOffset = new Vector2(3, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, DustID.Terragrim, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100); + Vector2 offset = new Vector2(0, -30).RotatedBy(-MathHelper.PiOver4 * 0.5f).RotatedBy(Projectile.rotation); + Vector2 velOffset = new Vector2(0, -5).RotatedBy(-MathHelper.PiOver4).RotatedBy(Projectile.rotation) * Main.rand.NextFloat(0.5f, 1f); + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset + Main.rand.NextVector2Circular(6, 6), Main.rand.NextBool(3) ? 278 : ModContent.DustType(), velOffset); dust.noGravity = true; - dust.scale = Main.rand.NextFloat(2.2f, 3.6f); - } - - if (Main.rand.NextBool(6)) - { - Vector2 offset = new Vector2(7, 0).RotatedByRandom(MathHelper.ToRadians(360f)); - Vector2 velOffset = new Vector2(3, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, DustID.Vortex, new Vector2(Projectile.velocity.X * 0.5f + velOffset.X, Projectile.velocity.Y * 0.5f + velOffset.Y), 100); - dust.noGravity = true; - dust.scale = Main.rand.NextFloat(2.2f, 3.6f); + dust.scale = Main.rand.NextFloat(0.9f, 1.3f); + dust.color = Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise; } } @@ -109,12 +112,11 @@ namespace CalamityMod.Projectiles.Melee return null; } - - public override bool CanHitPvp(Player target) => Projectile.ai[0] > 42f; - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - Projectile.localAI[0] = target.whoAmI; + target.AddBuff(ModContent.BuffType(), 180); + if (target == targeted) + Projectile.Kill(); } public override bool PreKill(int timeLeft) @@ -134,48 +136,52 @@ namespace CalamityMod.Projectiles.Melee for (int i = 0; i < numberOfDusts; i++) { float rot = MathHelper.ToRadians(i * rotFactor); + float intensity = Main.rand.NextFloat(0.2f, 1f); Vector2 offset = new Vector2(30f, 5.8f).RotatedBy(rot); - Vector2 velOffset = new Vector2(20.8f, 10.5f).RotatedBy(rot); - int dust = Dust.NewDust(Projectile.position + offset, Projectile.width, Projectile.height, DustID.Vortex, velOffset.X, velOffset.Y); - Main.dust[dust].noGravity = true; - Main.dust[dust].velocity = velOffset; - Main.dust[dust].scale = 3.8f; + Vector2 velOffset = new Vector2(40.8f, 10.5f).RotatedBy(rot); + if (i % 2 == 0) + { + Particle orb = new CustomSpark(Projectile.Center + offset, velOffset * intensity * 0.7f, "CalamityMod/Particles/Sparkle", false, (int)(40 * intensity), intensity, Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise, new Vector2(1f, 2f), true, true); + GeneralParticleHandler.SpawnParticle(orb); + } + else + { + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, ModContent.DustType(), velOffset); + dust.noGravity = true; + dust.velocity = velOffset * intensity; + dust.scale = Main.rand.NextFloat(2.1f, 2.8f) * intensity; + dust.color = Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise; + } } - for (int i = 0; i < 88; ++i) + for (int i = 0; i < 40; ++i) { - // Pick a random type of dust. - int dustID; - switch (Main.rand.Next(6)) - { - case 0: - dustID = 229; - break; - case 1: - case 2: - dustID = 156; - break; - default: - dustID = 156; - break; - } - + int dustID = ModContent.DustType(); // Choose a random speed and angle for the dust. - float dustSpeed = Main.rand.NextFloat(6.0f, 29.0f); - float angleRandom = 0.09f; + float dustSpeed = 45; + float intensity = Main.rand.NextFloat(0.5f, 1.5f); Vector2 dustVel = new Vector2(dustSpeed, 0.0f).RotatedBy(Projectile.velocity.ToRotation()); - dustVel = dustVel.RotatedBy(-angleRandom); - dustVel = dustVel.RotatedByRandom(2.0f * angleRandom); + dustVel = dustVel.RotatedByRandom((1.5f - intensity) * 0.4f) * intensity; + // Pick a size for the dust particle. - float scale = Main.rand.NextFloat(2.2f, 4.8f); + float scale = Main.rand.NextFloat(2.8f, 3.5f) - intensity; // Actually spawn the dust. - int idx = Dust.NewDust(Projectile.Center, 1, 1, dustID, dustVel.X, dustVel.Y, 0, default, scale); - Main.dust[idx].noGravity = true; - Main.dust[idx].position = Projectile.Center; + Dust idx = Dust.NewDustPerfect(Projectile.Center, dustID, dustVel, 0, default, scale); + idx.noGravity = true; + idx.position = Projectile.Center; + idx.color = Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise; } + Particle pulse3 = new GlowSparkParticle(Projectile.Center + Projectile.velocity, Projectile.velocity * 2, false, 12, 0.17f, Color.Turquoise, new Vector2(2.5f, 0.7f), true, true, 0.85f); + GeneralParticleHandler.SpawnParticle(pulse3); + + Particle bolt2 = new CustomPulse(Projectile.Center, Vector2.Zero, Color.Turquoise, "CalamityMod/Particles/BloomRing", new Vector2(0.7f, 1), Projectile.velocity.ToRotation(), 0f, 3f, 25); + GeneralParticleHandler.SpawnParticle(bolt2); + Particle bolt3 = new CustomPulse(Projectile.Center, Vector2.Zero, Color.PaleTurquoise, "CalamityMod/Particles/BloomRing", new Vector2(0.4f, 1), Projectile.velocity.ToRotation(), 0f, 4f, 25); + GeneralParticleHandler.SpawnParticle(bolt3); + Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Projectile.velocity * 0f, ModContent.ProjectileType(), Projectile.damage / 2, Projectile.knockBack, Projectile.owner, 0f); return false; @@ -183,23 +189,11 @@ namespace CalamityMod.Projectiles.Melee public override bool PreDraw(ref Color lightColor) { - SpriteEffects spriteEffects = SpriteEffects.None; - if (Projectile.spriteDirection == -1) - spriteEffects = SpriteEffects.FlipHorizontally; - Texture2D texture = Terraria.GameContent.TextureAssets.Projectile[Projectile.type].Value; - Rectangle sourceRectangle = new Rectangle(0, 0, texture.Width + 12, texture.Height + 12); - Vector2 origin = sourceRectangle.Size() / 2f; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], Color.Turquoise with { A = 0 } * 0.5f, 1, texture, true, true); - for (int i = 0; i < Projectile.oldPos.Length; i++) - { - float rot = MathHelper.ToRadians(22.5f) * Math.Sign(Projectile.velocity.X); - Vector2 drawPos = Projectile.oldPos[i] - Main.screenPosition + origin + new Vector2(0f, Projectile.gfxOffY); - Color color = Projectile.GetAlpha(lightColor) * ((Projectile.oldPos.Length - i) / (float)Projectile.oldPos.Length); - Main.EntitySpriteDraw(texture, drawPos, new Rectangle?(), color, Projectile.rotation - i * rot, origin, Projectile.scale, spriteEffects, 0); - } - - return false; + Projectile.DrawProjectileWithBackglow(Color.Turquoise with { A = 0 }, Color.White, 12f * Utils.GetLerpValue(0, 42, Projectile.ai[0], true) , texture); + return true; } } } diff --git a/Projectiles/Melee/StellarContemptHammer.cs b/Projectiles/Melee/StellarContemptHammer.cs index a75123933b..30e8240cd5 100644 --- a/Projectiles/Melee/StellarContemptHammer.cs +++ b/Projectiles/Melee/StellarContemptHammer.cs @@ -1,5 +1,6 @@ using System; using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Dusts; using CalamityMod.Items.Weapons.Melee; using CalamityMod.Particles; using Microsoft.Xna.Framework; @@ -18,12 +19,11 @@ namespace CalamityMod.Projectiles.Melee public static readonly SoundStyle UseSound = new("CalamityMod/Sounds/Item/PwnagehammerSound") { Volume = 0.35f }; public static readonly SoundStyle RedHamSound = new("CalamityMod/Sounds/Item/StellarContemptClone") { Volume = 0.6f }; public static readonly SoundStyle UseSoundFunny = new("CalamityMod/Sounds/Item/CalamityBell") { Volume = 1.5f }; - public ref int EmpoweredHammer => ref Main.player[Projectile.owner].Calamity().StellarHammer; public int returnhammer = 0; public int DustOnce = 1; - public float rotatehammer = 8f; - + public float rotatehammer = 15f; + public int time = 0; public override void SetStaticDefaults() { ProjectileID.Sets.TrailCacheLength[Projectile.type] = 11; @@ -32,8 +32,8 @@ namespace CalamityMod.Projectiles.Melee public override void SetDefaults() { - Projectile.width = 62; - Projectile.height = 62; + Projectile.width = 74; + Projectile.height = 74; Projectile.friendly = true; Projectile.DamageType = DamageClass.MeleeNoSpeed; Projectile.tileCollide = false; @@ -56,53 +56,19 @@ namespace CalamityMod.Projectiles.Melee if (returnhammer == 0) { - Projectile.velocity.X *= 0.981f; - Projectile.velocity.Y += 0.226f; + int falloffTime = 15; + if (time > falloffTime) + Projectile.velocity.X *= 0.967f; + if (Projectile.velocity.Y < 15 && time > falloffTime) + Projectile.velocity.Y += 0.426f; + if (Projectile.velocity.Y < 5) + Projectile.velocity.Y *= 0.98f; } if (returnhammer == 1) { if (EmpoweredHammer == 4) { - if (DustOnce == 1) - { - for (int i = 0; i < 20; ++i) - { - // Pick a random type of dust. - int dustID; - switch (Main.rand.Next(6)) - { - case 0: - dustID = 229; - break; - case 1: - case 2: - dustID = 156; - break; - default: - dustID = 156; - break; - } - - // Choose a random speed and angle for the dust. - float dustSpeed = Main.rand.NextFloat(3.0f, 19.0f); - float angleRandom = 0.09f; - Vector2 dustVel = new Vector2(0.0f, dustSpeed * -1f); - dustVel = dustVel.RotatedBy(-angleRandom); - dustVel = dustVel.RotatedByRandom(2.0f * angleRandom); - - // Pick a size for the dust particle. - float scale = Main.rand.NextFloat(1.7f, 3.8f); - - // Actually spawn the dust. - int idx = Dust.NewDust(Projectile.Center, 1, 1, dustID, dustVel.X, dustVel.Y, 0, default, scale); - Main.dust[idx].noGravity = true; - Main.dust[idx].position = Projectile.Center; - } - - DustOnce = 0; - } - Projectile.velocity.X *= 0.281f; Projectile.velocity.Y -= 0.8f; rotatehammer++; @@ -125,7 +91,7 @@ namespace CalamityMod.Projectiles.Melee if (returnhammer == 2) { Projectile.extraUpdates = 2; - float returnSpeed = StellarContempt.Speed; + float returnSpeed = StellarContempt.Speed * 0.7f; float acceleration = 1.1f; Player owner = Main.player[Projectile.owner]; Vector2 playerCenter = owner.Center; @@ -172,10 +138,11 @@ namespace CalamityMod.Projectiles.Melee for (int i = 0; i < 30; i++) { - Dust fire = Dust.NewDustPerfect(Projectile.Center, 156); + Dust fire = Dust.NewDustPerfect(Projectile.Center, ModContent.DustType()); fire.velocity = Projectile.velocity.SafeNormalize(Vector2.UnitY).RotatedByRandom(0.8f) * new Vector2(4f, 1.25f) * Main.rand.NextFloat(0.9f, 1f); fire.velocity = fire.velocity.RotatedBy(Projectile.rotation - MathHelper.PiOver2); fire.velocity += Projectile.velocity * (EmpoweredHammer * 0.04f); + fire.color = Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise; fire.noGravity = true; fire.scale = Main.rand.NextFloat(0.2f, 0.6f) * EmpoweredHammer; @@ -183,6 +150,7 @@ namespace CalamityMod.Projectiles.Melee fire = Dust.CloneDust(fire); fire.velocity = Main.rand.NextVector2Circular(3f, 3f); fire.velocity += Projectile.velocity * (EmpoweredHammer * 0.04f); + fire.color = Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise; } Projectile.Kill(); @@ -193,10 +161,23 @@ namespace CalamityMod.Projectiles.Melee { if (Projectile.velocity.Y < 0f) { - Particle streak = new ManaDrainStreak(player, Main.rand.NextFloat(0.9f, 1.5f), Main.rand.NextVector2CircularEdge(2f, 2f) * Main.rand.NextFloat(85f, 335f), Main.rand.NextFloat(30f, 44f), Color.PaleTurquoise, Color.Turquoise, Main.rand.Next(15, 30), Projectile.Center); - GeneralParticleHandler.SpawnParticle(streak); + float fade = Utils.GetLerpValue(3, -10, Projectile.velocity.Y, true); + float numberOfDusts = 2f; + float rotFactor = 360f / numberOfDusts; + for (int i = 0; i < numberOfDusts; i++) + { + float rot = MathHelper.ToRadians(i * rotFactor); + Vector2 velOffset = CalamityUtils.RandomVelocity(100f, 70f, 250f, 0.04f); + velOffset *= Main.rand.NextFloat(25, 45) * fade; + Particle energy = new SparkParticle(Projectile.Center + velOffset * 2.5f, -velOffset * Main.rand.NextFloat(0.08f, 0.12f) * 1.5f, false, 14, Main.rand.NextFloat(1.1f, 1.25f) - 0.5f * fade, Color.Turquoise); + GeneralParticleHandler.SpawnParticle(energy); + Dust dust = Dust.NewDustPerfect(Projectile.Center + velOffset * 2.5f, 278, -velOffset * Main.rand.NextFloat(0.08f, 0.12f) * 1.5f, 0, default, Main.rand.NextFloat(0.4f, 0.6f)); + dust.noGravity = true; + dust.color = Color.Turquoise; + dust.velocity += Projectile.velocity; + } + Projectile.velocity.Y += 0.6f; - Projectile.scale += 0.03f; } else { @@ -211,21 +192,15 @@ namespace CalamityMod.Projectiles.Melee } // Spawn dust as the hammer travels. - if (Main.rand.NextBool()) + if (Main.rand.NextBool(3)) { Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, DustID.UltraBrightTorch, new Vector2(Projectile.velocity.X * 0.3f + velOffset.X, Projectile.velocity.Y * 0.3f + velOffset.Y), 100); - dust.noGravity = true; - } - - if (Main.rand.NextBool(6)) - { - Vector2 offset = new Vector2(12, 0).RotatedByRandom(MathHelper.ToRadians(360f)); - Vector2 velOffset = new Vector2(4, 0).RotatedBy(offset.ToRotation()); - Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, DustID.UltraBrightTorch, new Vector2(Projectile.velocity.X * 0.2f + velOffset.X, Projectile.velocity.Y * 0.2f + velOffset.Y), 100); + Dust dust = Dust.NewDustPerfect(new Vector2(Projectile.Center.X, Projectile.Center.Y) + offset, ModContent.DustType(), new Vector2(Projectile.velocity.X * 0.3f + velOffset.X, Projectile.velocity.Y * 0.3f + velOffset.Y)); dust.noGravity = true; + dust.color = Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise; } + time++; } // On hit play GONG and spawn dust. @@ -234,6 +209,8 @@ namespace CalamityMod.Projectiles.Melee Player player = Main.player[Projectile.owner]; if (returnhammer == 0) { + Projectile.ai[1] = target.whoAmI; + if (Main.zenithWorld) SoundEngine.PlaySound(UseSoundFunny with { Pitch = EmpoweredHammer * 0.1f - 0.1f }, Projectile.Center); else @@ -250,29 +227,37 @@ namespace CalamityMod.Projectiles.Melee returnhammer = 1; } - float numberOfDusts = 40f; + float numberOfDusts = MathHelper.Clamp(40 - Projectile.numHits * 5, 6, 40); float rotFactor = 360f / numberOfDusts; for (int i = 0; i < numberOfDusts; i++) { float rot = MathHelper.ToRadians(i * rotFactor); Vector2 offset = new Vector2(4.8f, 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 4.1f)); Vector2 velOffset = new Vector2(4f, 0).RotatedBy(rot * Main.rand.NextFloat(1.1f, 4.1f)); - Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, 229, new Vector2(velOffset.X, velOffset.Y)); - dust.noGravity = true; - dust.velocity = velOffset; - dust.scale = Main.rand.NextFloat(1.5f, 3.2f); - } - SoundEngine.PlaySound(SoundID.Item14 with { Volume = 0.22f }, Projectile.Center); - Projectile.ai[1] = target.whoAmI; + if (i % 3 == 0) + { + Particle orb = new CustomSpark(Projectile.Center + offset, velOffset * Main.rand.NextFloat(1f, 1.5f), "CalamityMod/Particles/Sparkle", false, 25, Main.rand.NextFloat(0.55f, 0.75f), Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise, new Vector2(1f, 2f), true, true); + GeneralParticleHandler.SpawnParticle(orb); + } + else + { + Dust dust = Dust.NewDustPerfect(Projectile.Center + offset, ModContent.DustType(), new Vector2(velOffset.X, velOffset.Y)); + dust.noGravity = true; + dust.velocity = velOffset * Main.rand.NextFloat(0.75f, 1); + dust.scale = Main.rand.NextFloat(0.9f, 1.6f); + dust.color = Main.rand.NextBool(3) ? Color.PaleTurquoise : Color.Turquoise; + } + } } public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) { - if (Projectile.numHits > 0) - Projectile.damage = (int)(Projectile.damage * 0.9f); - if (Projectile.damage < 1) - Projectile.damage = 1; + target.AddBuff(ModContent.BuffType(), 90); + float minMult = 0.7f; + int hitsToMinMult = 10; + float damageMult = Utils.Remap(Projectile.numHits, 0, hitsToMinMult, 1, minMult, true); + modifiers.SourceDamage *= damageMult; } private void SpawnFlares(Vector2 targetPos, int width, int height) @@ -315,7 +300,10 @@ namespace CalamityMod.Projectiles.Melee { int proj = Projectile.NewProjectile(Projectile.GetSource_FromThis(), startPoint, velocity, ProjectileID.LunarFlare, flareDamage, flareKB, Main.myPlayer, 0f, AI1); if (proj.WithinBounds(Main.maxProjectiles)) + { Main.projectile[proj].DamageType = DamageClass.MeleeNoSpeed; + Main.projectile[proj].tileCollide = false; + } } } } diff --git a/Projectiles/Ranged/ArcherfishRing.cs b/Projectiles/Ranged/ArcherfishRing.cs index 5db6f1dd27..72c3133e72 100644 --- a/Projectiles/Ranged/ArcherfishRing.cs +++ b/Projectiles/Ranged/ArcherfishRing.cs @@ -63,8 +63,6 @@ namespace CalamityMod.Projectiles.Ranged { //Audio feedback for hitting the ring SoundEngine.PlaySound(PopSound, Projectile.Center); - - target.AddBuff(BuffID.Wet, 240); } public override bool PreDraw(ref Color lightColor) diff --git a/Projectiles/Ranged/DragonsBreathBurst.cs b/Projectiles/Ranged/DragonsBreathBurst.cs index 202219915f..5370887732 100644 --- a/Projectiles/Ranged/DragonsBreathBurst.cs +++ b/Projectiles/Ranged/DragonsBreathBurst.cs @@ -29,7 +29,7 @@ namespace CalamityMod.Projectiles.Ranged { target.AddBuff(ModContent.BuffType(), 420); if (Projectile.numHits > 0) - Projectile.damage = (int)(Projectile.damage * 0.98f); + Projectile.damage = (int)(Projectile.damage * 0.95f); if (Projectile.damage < 1) Projectile.damage = 1; } diff --git a/Projectiles/Ranged/DragonsBreathHoldout.cs b/Projectiles/Ranged/DragonsBreathHoldout.cs index c9f0e0cf0b..0600bc37de 100644 --- a/Projectiles/Ranged/DragonsBreathHoldout.cs +++ b/Projectiles/Ranged/DragonsBreathHoldout.cs @@ -36,7 +36,7 @@ namespace CalamityMod.Projectiles.Ranged fade = MathHelper.Lerp(fade, 0, 0.25f); if (Time == 0) { - weldingTimer = Owner.itemAnimationMax * 4; + weldingTimer = Owner.itemAnimationMax * 6; } if (firingBeam) { diff --git a/Projectiles/Ranged/HellbornHoldout.cs b/Projectiles/Ranged/HellbornHoldout.cs index 5d41469ad0..12a6cb31e7 100644 --- a/Projectiles/Ranged/HellbornHoldout.cs +++ b/Projectiles/Ranged/HellbornHoldout.cs @@ -201,7 +201,7 @@ namespace CalamityMod.Projectiles.Ranged } public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) { - modifiers.SourceDamage *= 0.08f; + modifiers.SourceDamage *= 0.1f; if (Owner.Calamity().hellbornShots < 8) { Owner.Calamity().hellbornShots++; diff --git a/Projectiles/Ranged/IcicleArrowProj.cs b/Projectiles/Ranged/IcicleArrowProj.cs index 8e49752c80..c67551d894 100644 --- a/Projectiles/Ranged/IcicleArrowProj.cs +++ b/Projectiles/Ranged/IcicleArrowProj.cs @@ -75,8 +75,8 @@ namespace CalamityMod.Projectiles.Ranged Projectile.ExpandHitboxBy(50); setFallingStats = true; } - if (Projectile.Calamity().allProjectilesHome) - Projectile.Calamity().allProjectilesHome = false; // Prevent the icicle effect from breaking with Arterial Assault + if (Projectile.Calamity().conditionalHomingRange > 0f) + Projectile.Calamity().conditionalHomingRange = 0f; // Prevent the icicle effect from breaking with Arterial Assault if (targetDist < 1400f) { @@ -101,8 +101,8 @@ namespace CalamityMod.Projectiles.Ranged public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { target.AddBuff(BuffID.Frostburn2, 180); - if (Projectile.Calamity().allProjectilesHome) - Projectile.Calamity().allProjectilesHome = false; // Prevent the icicle effect from breaking with Arterial Assault + if (Projectile.Calamity().conditionalHomingRange > 0f) + Projectile.Calamity().conditionalHomingRange = 0f; // Prevent the icicle effect from breaking with Arterial Assault if (!falling) { Projectile.localAI[0] = 100; diff --git a/Projectiles/Ranged/MegalodonShot.cs b/Projectiles/Ranged/MegalodonShot.cs new file mode 100644 index 0000000000..9d5fba397e --- /dev/null +++ b/Projectiles/Ranged/MegalodonShot.cs @@ -0,0 +1,65 @@ +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Dusts; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Ranged +{ + public class MegalodonShot : ModProjectile, ILocalizedModType + { + public new string LocalizationCategory => "Projectiles.Ranged"; + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + + public override void SetDefaults() + { + Projectile.width = 8; + Projectile.height = 8; + Projectile.friendly = true; + Projectile.DamageType = DamageClass.Ranged; + Projectile.ignoreWater = true; + Projectile.penetrate = 2; + Projectile.alpha = 255; + Projectile.timeLeft = 600; + Projectile.MaxUpdates = 3; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = -1; + Projectile.Calamity().pointBlankShotDuration = CalamityGlobalProjectile.DefaultPointBlankDuration; + } + + public override void AI() + { + // Bubbles + if (Main.rand.NextBool()) + { + Gore bubble = Gore.NewGorePerfect(Projectile.GetSource_FromAI(), Projectile.position, Projectile.velocity * 0.2f + Main.rand.NextVector2Circular(1f, 1f), 411); + bubble.timeLeft = 9 + Main.rand.Next(7); + bubble.scale = Main.rand.NextFloat(0.6f, 1f); + bubble.type = Main.rand.NextBool(3) ? 412 : 411; + } + + // Water trail + for (int i = 0; i < 6; i++) + { + Dust water = Dust.NewDustDirect(Projectile.position, Projectile.width, Projectile.height, DustID.Wet, 0f, 0f, 100); + water.noGravity = true; + water.velocity = Projectile.velocity * 0.5f; + } + } + + public override void OnKill(int timeLeft) + { + // Bubbles + for (int i = 0; i < 10; i++) + { + Gore bubble = Gore.NewGorePerfect(Projectile.GetSource_FromAI(), Projectile.position, Projectile.velocity.RotatedByRandom(MathHelper.ToRadians(60f)) * 0.3f, 411); + bubble.timeLeft = 9 + Main.rand.Next(7); + bubble.scale = Main.rand.NextFloat(0.6f, 1f); + bubble.type = Main.rand.NextBool(3) ? 412 : 411; + } + } + + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(ModContent.BuffType(), 240); + } +} diff --git a/Projectiles/Ranged/NitroShot.cs b/Projectiles/Ranged/NitroShot.cs index 1efd86ee4b..5496c63ec7 100644 --- a/Projectiles/Ranged/NitroShot.cs +++ b/Projectiles/Ranged/NitroShot.cs @@ -25,6 +25,8 @@ namespace CalamityMod.Projectiles.Ranged Projectile.ignoreWater = true; Projectile.penetrate = 5; Projectile.timeLeft = 600; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = -1; Projectile.Calamity().pointBlankShotDuration = CalamityGlobalProjectile.DefaultPointBlankDuration; } diff --git a/Projectiles/Ranged/SproutingArrowMain.cs b/Projectiles/Ranged/SproutingArrowMain.cs index c67de8f3a6..7067bd665a 100644 --- a/Projectiles/Ranged/SproutingArrowMain.cs +++ b/Projectiles/Ranged/SproutingArrowMain.cs @@ -51,12 +51,12 @@ namespace CalamityMod.Projectiles.Ranged Vector2 vel1 = (Projectile.velocity * 0.4f).RotatedBy(Main.rand.NextFloat(0.015f, 0.04f)); Vector2 vel2 = (Projectile.velocity * 0.4f).RotatedBy(Main.rand.NextFloat(-0.015f, -0.04f)); - int split1 = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, vel1 * Main.rand.NextFloat(0.95f, 1.05f), ModContent.ProjectileType(), (int)(Projectile.damage * 2), 0f, Projectile.owner, 0f, hitDirect ? 1f : 0f); - int split2 = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, vel2 * Main.rand.NextFloat(0.95f, 1.05f), ModContent.ProjectileType(), (int)(Projectile.damage * 2), 0f, Projectile.owner, 0f, hitDirect ? 1f : 0f); - if (Projectile.Calamity().allProjectilesHome) // Allows the split arrows to home when using Arterial Assault as well + Projectile split1 = Projectile.NewProjectileDirect(Projectile.GetSource_FromThis(), Projectile.Center, vel1 * Main.rand.NextFloat(0.95f, 1.05f), ModContent.ProjectileType(), Projectile.damage * 2, 0f, Projectile.owner, 0f, hitDirect ? 1f : 0f); + Projectile split2 = Projectile.NewProjectileDirect(Projectile.GetSource_FromThis(), Projectile.Center, vel2 * Main.rand.NextFloat(0.95f, 1.05f), ModContent.ProjectileType(), Projectile.damage * 2, 0f, Projectile.owner, 0f, hitDirect ? 1f : 0f); + if (Projectile.Calamity().conditionalHomingRange > 0f) // Allows the split arrows to home when using Arterial Assault as well { - Main.projectile[split1].Calamity().allProjectilesHome = true; - Main.projectile[split2].Calamity().allProjectilesHome = true; + split1.Calamity().conditionalHomingRange = Projectile.Calamity().conditionalHomingRange; + split2.Calamity().conditionalHomingRange = Projectile.Calamity().conditionalHomingRange; } PointParticle spark = new PointParticle(Projectile.Center - Projectile.velocity + Projectile.velocity.RotatedBy(2.3f), Projectile.velocity.RotatedBy(2.3f) * 0.5f, false, 5, 1.1f, Color.LimeGreen); diff --git a/Projectiles/Rogue/BrackishFlaskProj.cs b/Projectiles/Rogue/BrackishFlaskProj.cs deleted file mode 100644 index f51c3460b9..0000000000 --- a/Projectiles/Rogue/BrackishFlaskProj.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using Microsoft.Xna.Framework; -using Terraria; -using Terraria.Audio; -using Terraria.ID; -using Terraria.ModLoader; - -namespace CalamityMod.Projectiles.Rogue -{ - public class BrackishFlaskProj : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Rogue"; - public override string Texture => "CalamityMod/Items/Weapons/Rogue/BrackishFlask"; - - public override void SetDefaults() - { - Projectile.width = 24; - Projectile.height = 24; - Projectile.friendly = true; - Projectile.penetrate = 1; - Projectile.aiStyle = ProjAIStyleID.ThrownProjectile; - Projectile.timeLeft = 180; - AIType = ProjectileID.ThrowingKnife; - Projectile.DamageType = RogueDamageClass.Instance; - Projectile.ignoreWater = true; - } - - public override void OnKill(int timeLeft) - { - SoundEngine.PlaySound(SoundID.Item107, Projectile.Center); - int randomDust = Utils.SelectRandom(Main.rand, new int[] - { - 33, - 89 - }); - for (int k = 0; k < 5; k++) - { - Dust.NewDust(Projectile.position + Projectile.velocity, Projectile.width, Projectile.height, randomDust, Projectile.oldVelocity.X, Projectile.oldVelocity.Y); - } - float spread = 45f * 0.0174f; - double startAngle = Math.Atan2(Projectile.velocity.X, Projectile.velocity.Y) - spread / 2; - double deltaAngle = spread / 8f; - double offsetAngle; - if (Projectile.owner == Main.myPlayer) - { - if (Projectile.Calamity().stealthStrike) - { - Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center.X, Projectile.Center.Y, 0f, -32f, ModContent.ProjectileType(), Projectile.damage, Projectile.knockBack, Projectile.owner, 0f, 0f); - } - - Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), Projectile.damage, Projectile.knockBack, Projectile.owner, 0f, 0f); - - for (int i = 0; i < 4; i++) - { - offsetAngle = startAngle + deltaAngle * (i + i * i) / 2f + 32f * i; - Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center.X, Projectile.Center.Y, (float)(Math.Sin(offsetAngle) * 5f), (float)(Math.Cos(offsetAngle) * 5f), ModContent.ProjectileType(), Projectile.damage / 2, Projectile.knockBack * 0.5f, Projectile.owner, 0f, 0f); - Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center.X, Projectile.Center.Y, (float)(-Math.Sin(offsetAngle) * 5f), (float)(-Math.Cos(offsetAngle) * 5f), ModContent.ProjectileType(), Projectile.damage / 2, Projectile.knockBack * 0.5f, Projectile.owner, 1f, 0f); - } - } - } - - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) - { - target.AddBuff(BuffID.Venom, 90); - } - - public override void OnHitPlayer(Player target, Player.HurtInfo info) - { - target.AddBuff(BuffID.Venom, 90); - } - } -} diff --git a/Projectiles/Rogue/BrackishSpear.cs b/Projectiles/Rogue/BrackishSpear.cs deleted file mode 100644 index 00bc4c3b88..0000000000 --- a/Projectiles/Rogue/BrackishSpear.cs +++ /dev/null @@ -1,106 +0,0 @@ -using Microsoft.Xna.Framework; -using Terraria; -using Terraria.ID; -using Terraria.ModLoader; - -namespace CalamityMod.Projectiles.Rogue -{ - public class BrackishSpear : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Rogue"; - public override string Texture => "CalamityMod/Projectiles/Magic/AtlantisSpear"; - - public static int TotalSegments = 12; - - public override void SetDefaults() - { - Projectile.width = Projectile.height = 52; - Projectile.friendly = true; - Projectile.alpha = 255; - Projectile.penetrate = -1; - Projectile.tileCollide = false; - Projectile.ignoreWater = true; - Projectile.DamageType = RogueDamageClass.Instance; - Projectile.usesIDStaticNPCImmunity = true; - Projectile.idStaticNPCHitCooldown = 6; - } - - public override void AI() - { - Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver4; - if (Projectile.ai[1] == 0f) - { - Projectile.alpha -= 100; - if (Projectile.alpha <= 0) - { - Projectile.alpha = 0; - Projectile.ai[1] = 1f; - - // This projectile normally does not move by itself, so this will manually move it one time only - // This is only for the first segment and the on-kill segments - if (Projectile.ai[0] == 0f || Projectile.ai[0] > TotalSegments) - { - Projectile.ai[0]++; - Projectile.position += Projectile.velocity; - } - - // Spawn the next segment - if (Main.myPlayer == Projectile.owner && Projectile.ai[0] < TotalSegments) - { - int nextSegment = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center + Projectile.velocity, Projectile.velocity, Projectile.type, Projectile.damage, Projectile.knockBack, Projectile.owner, Projectile.ai[0] + 1f); - NetMessage.SendData(MessageID.SyncProjectile, -1, -1, null, nextSegment); - } - } - } - else // Begin fading out - { - int AlphaPerFrame = 12; - Projectile.alpha += AlphaPerFrame; - if (Projectile.alpha == AlphaPerFrame * 14) - { - for (int i = 0; i < 8; i++) - { - Dust blue = Dust.NewDustDirect(Projectile.position, Projectile.width, Projectile.height, DustID.UnusedWhiteBluePurple, Projectile.velocity.X * 0.005f, Projectile.velocity.Y * 0.005f, 200, default, 1f); - blue.noGravity = true; - blue.velocity *= 0.5f; - } - } - - if (Projectile.alpha >= 255) - Projectile.Kill(); - } - if (Main.rand.NextBool(4)) - Dust.NewDust(Projectile.position + Projectile.velocity, Projectile.width, Projectile.height, DustID.UnusedWhiteBluePurple, Projectile.velocity.X * 0.005f, Projectile.velocity.Y * 0.005f); - } - - // This is essential for Vilethorn-type projectiles, as velocity is a stored parameter and isn't supposed to actually move the projectile - public override bool ShouldUpdatePosition() => false; - - public override Color? GetAlpha(Color lightColor) => new Color(200, 200, 200, Projectile.alpha); - - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(BuffID.Venom, 90); - - public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(BuffID.Venom, 90); - - public override void OnKill(int timeLeft) - { - for (int k = 0; k < 3; k++) - { - Dust.NewDust(Projectile.position + Projectile.velocity, Projectile.width, Projectile.height, DustID.UnusedWhiteBluePurple, Projectile.oldVelocity.X * 0.005f, Projectile.oldVelocity.Y * 0.005f); - } - - // Prevent recursion: the segments that are being spawned here will deliberately be set higher than total segments - if (Projectile.ai[0] > TotalSegments || Main.myPlayer != Projectile.owner) - return; - - // Spawn two ungrowing segments to either side on death - int numProj = 2; - float rotation = MathHelper.ToRadians(20); - for (int i = 0; i < numProj; i++) - { - Vector2 perturbedSpeed = Projectile.velocity.RotatedBy(MathHelper.Lerp(-rotation, rotation, i / (numProj - 1))); - Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, perturbedSpeed, Projectile.type, Projectile.damage, Projectile.knockBack, Projectile.owner, TotalSegments + 1f); - } - } - } -} diff --git a/Projectiles/Rogue/BrackishWater.cs b/Projectiles/Rogue/BrackishWater.cs deleted file mode 100644 index 0a2ef3f6a7..0000000000 --- a/Projectiles/Rogue/BrackishWater.cs +++ /dev/null @@ -1,63 +0,0 @@ -using Microsoft.Xna.Framework; -using Terraria; -using Terraria.Audio; -using Terraria.ID; -using Terraria.ModLoader; - -namespace CalamityMod.Projectiles.Rogue -{ - public class BrackishWater : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Rogue"; - public override void SetDefaults() - { - Projectile.width = 12; - Projectile.height = 12; - Projectile.friendly = true; - Projectile.ignoreWater = true; - Projectile.penetrate = 1; - Projectile.timeLeft = 60; - Projectile.DamageType = RogueDamageClass.Instance; - } - - public override void AI() - { - Lighting.AddLight(Projectile.Center, (255 - Projectile.alpha) * 0f / 255f, (255 - Projectile.alpha) * 0.25f / 255f, (255 - Projectile.alpha) * 0.5f / 255f); - if (Projectile.localAI[0] == 0f && Projectile.ai[0] == 1f) - { - SoundEngine.PlaySound(SoundID.Item21, Projectile.position); - Projectile.localAI[0] += 1f; - } - if (Projectile.timeLeft % 2 == 0) - { - int randomDust = Utils.SelectRandom(Main.rand, new int[] - { - 33, - 89 - }); - int water = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, randomDust, 0f, 0f, 100, default, 1.2f); - Main.dust[water].noGravity = true; - Main.dust[water].velocity *= 0.5f; - Main.dust[water].velocity += Projectile.velocity * 0.1f; - } - } - - public override void OnKill(int timeLeft) - { - if (Projectile.owner == Main.myPlayer) - { - Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), Projectile.damage, Projectile.knockBack, Projectile.owner, 0f, 0f); - } - } - - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) - { - target.AddBuff(BuffID.Venom, 90); - } - - public override void OnHitPlayer(Player target, Player.HurtInfo info) - { - target.AddBuff(BuffID.Venom, 90); - } - } -} diff --git a/Projectiles/Rogue/BrackishWater.png b/Projectiles/Rogue/BrackishWater.png deleted file mode 100644 index 29d231bf6d..0000000000 Binary files a/Projectiles/Rogue/BrackishWater.png and /dev/null differ diff --git a/Projectiles/Rogue/BrackishWaterBlast.cs b/Projectiles/Rogue/BrackishWaterBlast.cs deleted file mode 100644 index e575a3f54a..0000000000 --- a/Projectiles/Rogue/BrackishWaterBlast.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System; -using Microsoft.Xna.Framework; -using Terraria; -using Terraria.Audio; -using Terraria.ID; -using Terraria.ModLoader; - -namespace CalamityMod.Projectiles.Rogue -{ - public class BrackishWaterBlast : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Rogue"; - public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; - - public override void SetDefaults() - { - Projectile.width = 130; - Projectile.height = 130; - Projectile.friendly = true; - Projectile.ignoreWater = true; - Projectile.tileCollide = false; - Projectile.penetrate = -1; - Projectile.timeLeft = 60; - Projectile.DamageType = RogueDamageClass.Instance; - Projectile.usesIDStaticNPCImmunity = true; - Projectile.idStaticNPCHitCooldown = 6; - } - - public override void AI() - { - Lighting.AddLight(Projectile.Center, (255 - Projectile.alpha) * 0f / 255f, (255 - Projectile.alpha) * 0.5f / 255f, (255 - Projectile.alpha) * 0.75f / 255f); - int randomDust = Utils.SelectRandom(Main.rand, new int[] - { - 33, - 89 - }); - if (Projectile.localAI[0] == 0f) - { - SoundEngine.PlaySound(SoundID.Item21, Projectile.position); - Projectile.localAI[0] += 1f; - } - bool xflag = false; - bool yflag = false; - if (Projectile.velocity.X < 0f && Projectile.position.X < Projectile.ai[0]) - { - xflag = true; - } - if (Projectile.velocity.X > 0f && Projectile.position.X > Projectile.ai[0]) - { - xflag = true; - } - if (Projectile.velocity.Y < 0f && Projectile.position.Y < Projectile.ai[1]) - { - yflag = true; - } - if (Projectile.velocity.Y > 0f && Projectile.position.Y > Projectile.ai[1]) - { - yflag = true; - } - if (xflag && yflag) - { - Projectile.Kill(); - } - float projTimer = 25f; - if (Projectile.ai[0] > 180f) - { - projTimer -= (Projectile.ai[0] - 180f) / 2f; - } - if (projTimer <= 0f) - { - projTimer = 0f; - Projectile.Kill(); - } - projTimer *= 0.7f; - Projectile.ai[0] += 4f; - float timerCompare = 0f; - while (timerCompare < projTimer) - { - float random1 = (float)Main.rand.Next(-10, 11); - float random2 = (float)Main.rand.Next(-10, 11); - float random3 = (float)Main.rand.Next(3, 9); - float randomAdjust = (float)Math.Sqrt((double)(random1 * random1 + random2 * random2)); - randomAdjust = random3 / randomAdjust; - random1 *= randomAdjust; - random2 *= randomAdjust; - int water = Dust.NewDust(Projectile.position, Projectile.width, Projectile.height, randomDust, 0f, 0f, 100, default, 0.5f); - Dust dust = Main.dust[water]; - dust.noGravity = true; - dust.position.X = Projectile.Center.X; - dust.position.Y = Projectile.Center.Y; - dust.position.X += (float)Main.rand.Next(-10, 11); - dust.position.Y += (float)Main.rand.Next(-10, 11); - dust.velocity.X = random1; - dust.velocity.Y = random2; - timerCompare++; - } - } - - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(BuffID.Venom, 90); - - public override void OnHitPlayer(Player target, Player.HurtInfo info) => target.AddBuff(BuffID.Venom, 90); - } -} diff --git a/Projectiles/Rogue/CelestialReaperAfterimage.cs b/Projectiles/Rogue/CelestialReaperAfterimage.cs index 14c91ab91c..34024d6c99 100644 --- a/Projectiles/Rogue/CelestialReaperAfterimage.cs +++ b/Projectiles/Rogue/CelestialReaperAfterimage.cs @@ -16,7 +16,6 @@ namespace CalamityMod.Projectiles.Rogue Projectile.height = 76; Projectile.friendly = true; Projectile.ignoreWater = true; - Projectile.penetrate = 1; Projectile.timeLeft = 51; Projectile.tileCollide = false; Projectile.DamageType = RogueDamageClass.Instance; @@ -32,7 +31,7 @@ namespace CalamityMod.Projectiles.Rogue if (Projectile.timeLeft < 150) { - NPC target = Projectile.Center.ClosestNPCAt(640f); + NPC target = Projectile.Center.ClosestNPCAt(800f); if (target != null) Projectile.velocity = (Projectile.velocity * 20f + Projectile.SafeDirectionTo(target.Center) * 20f) / 21f; } diff --git a/Projectiles/Rogue/CelestialReaperProjectile.cs b/Projectiles/Rogue/CelestialReaperProjectile.cs index a864cf5546..3531a0ba5c 100644 --- a/Projectiles/Rogue/CelestialReaperProjectile.cs +++ b/Projectiles/Rogue/CelestialReaperProjectile.cs @@ -12,6 +12,7 @@ namespace CalamityMod.Projectiles.Rogue public override string Texture => "CalamityMod/Items/Weapons/Rogue/CelestialReaper"; public int HomingCooldown = 0; + public NPC HitTarget; public override void SetStaticDefaults() => ProjectileID.Sets.CultistIsResistantTo[Type] = true; public override void SetDefaults() @@ -37,7 +38,7 @@ namespace CalamityMod.Projectiles.Rogue } else { - NPC target = Projectile.Center.ClosestNPCAt(640f); + NPC target = (HitTarget != null && HitTarget.active) ? HitTarget : Projectile.Center.ClosestNPCAt(800f); if (target != null) Projectile.velocity = (Projectile.velocity * 20f + Projectile.SafeDirectionTo(target.Center) * 20f) / 21f; } @@ -57,13 +58,14 @@ namespace CalamityMod.Projectiles.Rogue } } - // The explicit (bool?) cast is necessary until C# 9.0. How ugly. - public override bool? CanHitNPC(NPC target) => HomingCooldown > 0 ? false : (bool?)null; + public override bool? CanHitNPC(NPC target) => HomingCooldown > 0 ? false : null; public override bool CanHitPvp(Player target) => HomingCooldown <= 0; public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { + if (HitTarget == null || !HitTarget.active) + HitTarget = target; HomingCooldown = 25; Projectile.velocity *= -0.75f; // Bounce off of the enemy. } diff --git a/Projectiles/Rogue/KylieBoomerang.cs b/Projectiles/Rogue/KylieBoomerang.cs index 12d1648a1c..9c54b5bd30 100644 --- a/Projectiles/Rogue/KylieBoomerang.cs +++ b/Projectiles/Rogue/KylieBoomerang.cs @@ -13,16 +13,19 @@ namespace CalamityMod.Projectiles.Rogue public new string LocalizationCategory => "Projectiles.Rogue"; public override string Texture => "CalamityMod/Items/Weapons/Rogue/Kylie"; + public ref float State => ref Projectile.ai[0]; + public ref float Timer => ref Projectile.ai[1]; + //This variable will be used for the stealth strike - public float ReboundTime = 0f; - public float timer = 0f; + public const float ReboundTime = 35f; + public int TileBounceDelay = 0; public override void SetDefaults() { Projectile.friendly = true; Projectile.width = 40; Projectile.height = 40; Projectile.penetrate = -1; - Projectile.timeLeft = 360; + Projectile.timeLeft = 240; Projectile.tileCollide = false; Projectile.usesLocalNPCImmunity = true; Projectile.localNPCHitCooldown = 30; @@ -32,11 +35,11 @@ namespace CalamityMod.Projectiles.Rogue public override void AI() { + Player Owner = Main.player[Projectile.owner]; //Constant rotation Projectile.rotation += 0.2f; - - timer++; + //Dust trail if (Main.rand.NextBool(15)) { @@ -49,88 +52,113 @@ namespace CalamityMod.Projectiles.Rogue Projectile.soundDelay = 15; SoundEngine.PlaySound(SoundID.Item7, Projectile.position); } - //Slopes REEEEEEEEEEEE - if (timer == 3f) - Projectile.tileCollide = true; - //Decide the range of the boomerang depending on stealth + + // If stealth strike, stay close to the player's cursor. if (Projectile.Calamity().stealthStrike) - ReboundTime = 36f; - else - ReboundTime = 55f; - - // ai[0] stores whether the boomerang is returning. If 0, it isn't. If 1, it is. - if (Projectile.ai[0] == 0f) { - Projectile.ai[1] += 1f; - if (Projectile.ai[1] >= ReboundTime) + Projectile.tileCollide = true; + if (TileBounceDelay > 0) + TileBounceDelay--; + + Vector2 mousePos = Owner.Calamity().mouseWorld; + if (Vector2.Distance(Projectile.Center, mousePos) > 115f && TileBounceDelay == 0) { - Projectile.ai[0] = 1f; - Projectile.ai[1] = 0f; - Projectile.netUpdate = true; + float accelerationFactor = 12f; // Higher number = Takes longer to turn around. + Projectile.velocity += (mousePos - Projectile.Center).SafeNormalize(Vector2.UnitX) * Kylie.Speed / accelerationFactor; + if (Projectile.velocity.Length() > Kylie.Speed) + { + Projectile.velocity.Normalize(); + Projectile.velocity *= Kylie.Speed; + } + } + else // Accelerate to top speed if close enough to prevent it staying slow if you move in the cursor while it's slowing down. + { + Projectile.velocity *= 1.1f; + if (Projectile.velocity.Length() > Kylie.Speed) + { + Projectile.velocity.Normalize(); + Projectile.velocity *= Kylie.Speed; + } } } else { - Projectile.tileCollide = false; - float returnSpeed = Kylie.Speed * 1.5f; - float acceleration = 3.2f; - Player owner = Main.player[Projectile.owner]; - - // Delete the boomerang if it's excessively far away. - Vector2 playerCenter = owner.Center; - float xDist = playerCenter.X - Projectile.Center.X; - float yDist = playerCenter.Y - Projectile.Center.Y; - float dist = (float)Math.Sqrt((double)(xDist * xDist + yDist * yDist)); - if (dist > 3000f) - Projectile.Kill(); - - dist = returnSpeed / dist; - xDist *= dist; - yDist *= dist; - - // Home back in on the player. - if (Projectile.velocity.X < xDist) + // State of 0 = Going out. State of 1 = Returning. + if (State == 0f) { - Projectile.velocity.X = Projectile.velocity.X + acceleration; - if (Projectile.velocity.X < 0f && xDist > 0f) - Projectile.velocity.X += acceleration; - } - else if (Projectile.velocity.X > xDist) - { - Projectile.velocity.X = Projectile.velocity.X - acceleration; - if (Projectile.velocity.X > 0f && xDist < 0f) - Projectile.velocity.X -= acceleration; - } - if (Projectile.velocity.Y < yDist) - { - Projectile.velocity.Y = Projectile.velocity.Y + acceleration; - if (Projectile.velocity.Y < 0f && yDist > 0f) - Projectile.velocity.Y += acceleration; - } - else if (Projectile.velocity.Y > yDist) - { - Projectile.velocity.Y = Projectile.velocity.Y - acceleration; - if (Projectile.velocity.Y > 0f && yDist < 0f) - Projectile.velocity.Y -= acceleration; - } + Timer += 1f; + //Slopes REEEEEEEEEEEE + if (Timer == 3f) + Projectile.tileCollide = true; - // Delete the projectile if it touches its owner. - if (Main.myPlayer == Projectile.owner) - if (Projectile.Hitbox.Intersects(owner.Hitbox)) + if (Timer >= ReboundTime) + { + State = 1f; + Timer = 0f; + Projectile.netUpdate = true; + } + } + else + { + Projectile.tileCollide = false; + float returnSpeed = Kylie.Speed * 1.5f; + float acceleration = 3.2f; + Player owner = Main.player[Projectile.owner]; + + // Delete the boomerang if it's excessively far away. + Vector2 playerCenter = owner.Center; + float xDist = playerCenter.X - Projectile.Center.X; + float yDist = playerCenter.Y - Projectile.Center.Y; + float dist = (float)Math.Sqrt((double)(xDist * xDist + yDist * yDist)); + if (dist > 3000f) Projectile.Kill(); + + dist = returnSpeed / dist; + xDist *= dist; + yDist *= dist; + + // Home back in on the player. + if (Projectile.velocity.X < xDist) + { + Projectile.velocity.X = Projectile.velocity.X + acceleration; + if (Projectile.velocity.X < 0f && xDist > 0f) + Projectile.velocity.X += acceleration; + } + else if (Projectile.velocity.X > xDist) + { + Projectile.velocity.X = Projectile.velocity.X - acceleration; + if (Projectile.velocity.X > 0f && xDist < 0f) + Projectile.velocity.X -= acceleration; + } + if (Projectile.velocity.Y < yDist) + { + Projectile.velocity.Y = Projectile.velocity.Y + acceleration; + if (Projectile.velocity.Y < 0f && yDist > 0f) + Projectile.velocity.Y += acceleration; + } + else if (Projectile.velocity.Y > yDist) + { + Projectile.velocity.Y = Projectile.velocity.Y - acceleration; + if (Projectile.velocity.Y > 0f && yDist < 0f) + Projectile.velocity.Y -= acceleration; + } + + + // Delete the projectile if it touches its owner. + if (Main.myPlayer == Projectile.owner) + if (Projectile.Hitbox.Intersects(owner.Hitbox)) + Projectile.Kill(); + } } } - public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) - { - //Start homing at player if you hit an enemy - Projectile.ai[0] = 1; - } + // Return to player after hitting an enemy + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => State = 1f; public override bool OnTileCollide(Vector2 oldVelocity) { - //Bounce off tiles and start homing on player if it hits a tile + //Bounce off tiles and return to player after hitting a tile Collision.HitTiles(Projectile.position + Projectile.velocity, Projectile.velocity, Projectile.width, Projectile.height); SoundEngine.PlaySound(SoundID.Dig, Projectile.position); if (Projectile.velocity.X != oldVelocity.X) @@ -141,9 +169,21 @@ namespace CalamityMod.Projectiles.Rogue { Projectile.velocity.Y = -oldVelocity.Y; } - Projectile.ai[0] = 1; + State = 1f; + if (TileBounceDelay == 0) + TileBounceDelay = 10; return false; + } + // Spawn splinter gores on stealth strike death + public override void OnKill(int timeLeft) + { + if (Projectile.Calamity().stealthStrike) + { + Vector2 splinterVel = Projectile.velocity.RotatedByRandom(MathHelper.Pi / 12f); + Gore.NewGore(Projectile.GetSource_Death(), Projectile.Center, splinterVel, Mod.Find("KylieGore1").Type); + Gore.NewGore(Projectile.GetSource_Death(), Projectile.Center, splinterVel, Mod.Find("KylieGore2").Type); + } } } } diff --git a/Projectiles/Rogue/LeviathanTooth.cs b/Projectiles/Rogue/LeviathanTooth.cs index 8785e9f73e..bc64091280 100644 --- a/Projectiles/Rogue/LeviathanTooth.cs +++ b/Projectiles/Rogue/LeviathanTooth.cs @@ -1,4 +1,5 @@ -using System; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Particles; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -11,101 +12,262 @@ namespace CalamityMod.Projectiles.Rogue public class LeviathanTooth : ModProjectile, ILocalizedModType { public new string LocalizationCategory => "Projectiles.Rogue"; + public ref float time => ref Projectile.ai[0]; + + // Vanilla sticky code is jank, So I did my own (for better or worse) + public NPC chosenTarget; + public bool stuckInTarget = false; + public bool stuckInGround = false; + public bool canDamage = true; + public bool canStick = true; + public Vector2 vibrate = Vector2.Zero; + public int stuckTimer = 120; + public Vector2 placementCenter; + float placementDistance; + Vector2 placementVelocity; + public Vector2 storedVelocity; + public bool collideWithTiles = true; + + public bool jawline = true; // Tooth direction for the stealthstrike + public Vector2 startingVel; + public bool toothDirection = false; + public Vector2 chomp = Vector2.Zero; + public bool chomping = true; public override void SetStaticDefaults() { ProjectileID.Sets.TrailCacheLength[Projectile.type] = 8; - ProjectileID.Sets.TrailingMode[Projectile.type] = 1; + ProjectileID.Sets.TrailingMode[Projectile.type] = 2; } public override void SetDefaults() { - Projectile.width = 10; - Projectile.height = 10; + Projectile.width = 2; + Projectile.height = 2; Projectile.friendly = true; Projectile.ignoreWater = true; Projectile.penetrate = -1; + Projectile.extraUpdates = 2; + Projectile.tileCollide = false; Projectile.timeLeft = 600; Projectile.DamageType = RogueDamageClass.Instance; Projectile.usesLocalNPCImmunity = true; - Projectile.localNPCHitCooldown = 10; + Projectile.localNPCHitCooldown = -1; } public override void AI() { - if (Projectile.ai[0] == 0f) + if (time == 0) { - Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver2; - if (Projectile.timeLeft < 575 && !Projectile.Calamity().stealthStrike) + stuckTimer = Main.rand.Next(100, 120 + 1); + startingVel = Projectile.velocity; + if (Projectile.ai[1] < 4) + toothDirection = Main.rand.NextBool(); + } + if (!stuckInTarget && !stuckInGround) + { + if (!Projectile.Calamity().stealthStrike) { - Projectile.velocity.Y += 0.5f; - if (Projectile.velocity.Y > 16f) + Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver2; + if ((time % 2 == 0 || !canStick) && time > 15) { - Projectile.velocity.Y = 16f; + Dust dust = Dust.NewDustPerfect(Projectile.Center - Projectile.velocity.SafeNormalize(Vector2.UnitX) * 3 + Main.rand.NextVector2Circular(6, 6), 5, (-Projectile.velocity.SafeNormalize(Vector2.UnitX) * 4).RotatedByRandom(0.3f) * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.8f, 1.4f)); + dust.noGravity = true; + } + if (time > 90 && canStick) + { + Projectile.velocity.Y += 0.03f; + if (Projectile.velocity.Y > 0) + Projectile.velocity.X *= 0.99f; } } } - //Sticky Behaviour - Projectile.StickyProjAI(15); + else if (stuckInTarget) + { + float power = 5 * Utils.GetLerpValue(120, 0, stuckTimer, true); + vibrate = Main.rand.NextVector2Circular(power, power); + + Projectile.rotation = (storedVelocity).SafeNormalize(Vector2.UnitX).ToRotation() + MathHelper.PiOver2; + + Vector2 impaleVel = (storedVelocity * 0.5f) * Utils.GetLerpValue(120, 0, stuckTimer, true); + placementCenter = chosenTarget.Center + placementVelocity * placementDistance + impaleVel; + + Projectile.Center = placementCenter; + + stuckTimer--; + if (chosenTarget.life <= 0 || chosenTarget == null) + stuckTimer = 0; + if (stuckTimer == 0) + { + for (int i = 0; i < Main.maxNPCs; i++) + Projectile.localNPCImmunity[i] = 0; + + canDamage = true; + vibrate = Vector2.Zero; + canStick = false; + collideWithTiles = true; + Projectile.velocity = storedVelocity * 1.3f; + stuckInTarget = false; + + for (int i = 0; i <= 7; i++) + { + Dust dust = Dust.NewDustPerfect(Projectile.Center, 5, (storedVelocity * 2.5f).RotatedByRandom(0.7) * Main.rand.NextFloat(0.1f, 0.8f), 0, default, Main.rand.NextFloat(0.9f, 1.8f)); + dust.noGravity = false; + } + for (int i = 0; i <= 3; i++) + { + Particle spark = new AltSparkParticle(Projectile.Center, (storedVelocity * 4.5f).RotatedByRandom(0.7) * Main.rand.NextFloat(0.1f, 0.8f) + new Vector2(0, -2), true, 20, 0.5f, Color.DarkRed * 0.7f); + GeneralParticleHandler.SpawnParticle(spark); + } + SoundStyle sound = new("CalamityMod/Sounds/NPCHit/PerfSmallHit", 3); + SoundEngine.PlaySound(sound with { Volume = 0.5f, Pitch = Main.rand.NextFloat(-0.2f, -0.3f) }, Projectile.Center); + } + + } + if (stuckInGround) + { + Projectile.rotation = storedVelocity.ToRotation() + MathHelper.PiOver2; + } + + if (Projectile.Calamity().stealthStrike) + { + collideWithTiles = false; + if (time > 15 && (Projectile.ai[1] == 4 ? Projectile.timeLeft > 60 : time < 40)) + { + for (int i = 0; i < (Projectile.ai[1] == 4 ? 2 : 1); i++) + { + Dust dust = Dust.NewDustPerfect(Projectile.Center - Projectile.velocity.SafeNormalize(Vector2.UnitX) * 3 + Main.rand.NextVector2Circular(6, 6), 5, (-Projectile.velocity.SafeNormalize(Vector2.UnitX) * 4).RotatedByRandom(0.5f) * Main.rand.NextFloat(0.1f, 0.8f), 100, default, Main.rand.NextFloat(0.8f, 1.6f)); + dust.noGravity = true; + } + } + if (Projectile.ai[1] == 4) + { + Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver4; + int jawDir = jawline ? 1 : -1; + Vector2 spawnPos = Projectile.Center + Projectile.velocity.SafeNormalize(Vector2.UnitX).RotatedBy(MathHelper.ToRadians(90f * jawDir)) * 170; + Vector2 jawVel = Projectile.velocity.SafeNormalize(Vector2.UnitX).RotatedBy(MathHelper.ToRadians(90f * jawDir)) * 17; + if (time > 10 && Projectile.timeLeft >= 60) + { + if (time % 3 == 0) + { + Projectile tooth = Projectile.NewProjectileDirect(Projectile.GetSource_FromThis(), spawnPos, jawVel, ModContent.ProjectileType(), Projectile.damage, Projectile.knockBack / 12, Projectile.owner, 0, 0, Projectile.velocity.X > 0 ? 1 : -1); + tooth.Calamity().stealthStrike = true; + tooth.timeLeft = 120; + tooth.extraUpdates = 0; + tooth.usesIDStaticNPCImmunity = true; + tooth.usesLocalNPCImmunity = false; + tooth.idStaticNPCHitCooldown = 5; + tooth.ai[1] = Main.rand.Next(1, 3 + 1); + jawline = !jawline; + } + if (time % 2 == 0) + { + Particle spark = new AltSparkParticle(Projectile.Center - Projectile.velocity * 0.5f, Projectile.velocity * 0.01f, false, 15, 1f, Color.DarkRed * 0.4f); + GeneralParticleHandler.SpawnParticle(spark); + } + if (Projectile.timeLeft == 60) + Projectile.velocity *= 0.5f; + } + else if (Projectile.timeLeft <= 60) + { + Projectile.alpha = (int)(Utils.Remap(Projectile.timeLeft, 0, 60, 255, 0)); + Projectile.velocity *= 0.95f; + } + } + else + { + Projectile.rotation = startingVel.ToRotation() + MathHelper.ToRadians(270f); + if (Projectile.timeLeft > 90) + { + Projectile.velocity.X = MathHelper.Lerp(Projectile.velocity.X, -startingVel.X * 1.3f, 0.045f); + Projectile.velocity.Y = MathHelper.Lerp(Projectile.velocity.Y, -startingVel.Y * 1.3f, 0.045f); + Projectile.alpha = (int)(Utils.Remap(Projectile.timeLeft, 120, 90, 255, 0)); + } + else + { + Projectile.alpha = (int)(Utils.Remap(Projectile.timeLeft, 0, 30, 255, 0)); + Projectile.velocity *= 0.9f; + } + if (time > 40) + { + if (!chomping) + { + chomp.X = MathHelper.Lerp(chomp.X, startingVel.X * 3, 0.2f); + chomp.Y = MathHelper.Lerp(chomp.Y, startingVel.Y * 3, 0.2f); + } + else + { + chomp.X = MathHelper.Lerp(chomp.X, 0, 0.2f); + chomp.Y = MathHelper.Lerp(chomp.Y, 0, 0.2f); + } + if (time % 18 == 0) + chomping = !chomping; + } + + } + } + time++; + + if (collideWithTiles && Collision.SolidCollision(Projectile.Center, 4, 4)) // Vanilla tile collision messes with velocity so we use this instead + { + canDamage = false; + if (Projectile.timeLeft > 180) + Projectile.timeLeft = 180; + stuckInGround = true; + storedVelocity = Projectile.velocity.SafeNormalize(Vector2.UnitX); + Projectile.velocity = Vector2.Zero; + SoundStyle sound = new("CalamityMod/Sounds/NPCHit/RavagerRockPillarHit1"); + SoundEngine.PlaySound(sound with { Volume = 0.25f, Pitch = Main.rand.NextFloat(-0.3f, -0.6f) }, Projectile.Center); + collideWithTiles = false; + + } + + if (!Projectile.Calamity().stealthStrike) + Projectile.alpha = (int)(Utils.Remap(Projectile.timeLeft, 0, 60, 255, 0)); } - public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) => Projectile.ModifyHitNPCSticky(6); - public override bool? CanDamage() => Projectile.ai[0] == 1f ? false : base.CanDamage(); + public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) + { + if (Projectile.Calamity().stealthStrike) + modifiers.SourceDamage *= Projectile.ai[1] == 4 ? 0.6f : 0.5f; + else + modifiers.SourceDamage *= target == chosenTarget ? 1 : (canStick ? 0.2f : 0.5f); + } + public override bool? CanDamage() => canDamage ? null : false; public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - target.AddBuff(BuffID.Venom, 180); - if (Projectile.Calamity().stealthStrike) + if (target == chosenTarget || Projectile.Calamity().stealthStrike) + target.AddBuff(ModContent.BuffType(), 180); + if (!stuckInTarget && canStick && !Projectile.Calamity().stealthStrike) { - int toothBlast = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), (int)(Projectile.damage * 0.6f), Projectile.knockBack, Projectile.owner, 0f, 0f); - Main.projectile[toothBlast].usesLocalNPCImmunity = true; - Main.projectile[toothBlast].usesIDStaticNPCImmunity = false; - Main.projectile[toothBlast].localNPCHitCooldown = -1; - } - } - - public override void OnHitPlayer(Player target, Player.HurtInfo info) - { - target.AddBuff(BuffID.Venom, 180); - if (Projectile.Calamity().stealthStrike) - { - int toothBlast = Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), (int)(Projectile.damage * 0.6f), Projectile.knockBack, Projectile.owner, 0f, 0f); - Main.projectile[toothBlast].usesLocalNPCImmunity = true; - Main.projectile[toothBlast].usesIDStaticNPCImmunity = false; - Main.projectile[toothBlast].localNPCHitCooldown = -1; + if (Projectile.timeLeft < 400) + Projectile.timeLeft = 400; + collideWithTiles = false; + canDamage = false; + placementDistance = -Vector2.Distance(target.Center, Projectile.Center); + placementVelocity = (target.Center - Projectile.Center).SafeNormalize(Vector2.UnitX); + placementCenter = placementVelocity * (placementDistance * 0.01f); + chosenTarget = target; + stuckInTarget = true; + storedVelocity = Projectile.velocity.SafeNormalize(Vector2.UnitX) * 8; + Projectile.velocity = Vector2.Zero; } } public override bool PreDraw(ref Color lightColor) { Texture2D tex = Terraria.GameContent.TextureAssets.Projectile[Projectile.type].Value; - if (Projectile.Calamity().lineColor == 1) + if (Projectile.ai[1] == 2) tex = ModContent.Request("CalamityMod/Projectiles/Rogue/LeviathanTooth2").Value; - if (Projectile.Calamity().lineColor == 2) + if (Projectile.ai[1] == 3) tex = ModContent.Request("CalamityMod/Projectiles/Rogue/LeviathanTooth3").Value; + if (Projectile.ai[1] == 4) + tex = ModContent.Request("CalamityMod/Projectiles/Melee/GreenWater").Value; - Main.EntitySpriteDraw(tex, Projectile.Center - Main.screenPosition, null, Projectile.GetAlpha(lightColor), Projectile.rotation, tex.Size() / 2f, Projectile.scale, SpriteEffects.None, 0); - if (Projectile.Calamity().stealthStrike) - { - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1, tex); - } + Main.EntitySpriteDraw(tex, Projectile.Center - Main.screenPosition + vibrate + chomp, null, Projectile.GetAlpha(lightColor), Projectile.rotation, tex.Size() / 2f, Projectile.scale, toothDirection ? SpriteEffects.FlipHorizontally : SpriteEffects.None, 0); + return false; } - - public override bool OnTileCollide(Vector2 oldVelocity) - { - Collision.HitTiles(Projectile.position + Projectile.velocity, Projectile.velocity, Projectile.width, Projectile.height); - SoundEngine.PlaySound(SoundID.Dig, Projectile.position); - Projectile.Kill(); - return false; - } - - public override void OnKill(int timeLeft) - { - for (int i = 0; i < 5; i++) - { - int dust = Dust.NewDust(Projectile.Center, 1, 1, DustID.Water, 0, 0, 0, default, 1.5f); - Main.dust[dust].noGravity = true; - } - } + public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, Projectile.Calamity().stealthStrike ? 50 : 18, targetHitbox); } } diff --git a/Projectiles/Rogue/PrismRocket.cs b/Projectiles/Rogue/PrismRocket.cs deleted file mode 100644 index 527961a005..0000000000 --- a/Projectiles/Rogue/PrismRocket.cs +++ /dev/null @@ -1,74 +0,0 @@ -using Microsoft.Xna.Framework; -using Terraria; -using Terraria.ID; -using Terraria.ModLoader; - -namespace CalamityMod.Projectiles.Rogue -{ - public class PrismRocket : ModProjectile, ILocalizedModType - { - public new string LocalizationCategory => "Projectiles.Rogue"; - public float ExponentialAccelerationFactor => Projectile.Calamity().stealthStrike ? 1.027f : 1.015f; - public float MaxHomingSpeed => Projectile.Calamity().stealthStrike ? 26f : 21f; - public const int Lifetime = 150; - - public override void SetStaticDefaults() - { - ProjectileID.Sets.CultistIsResistantTo[Type] = true; - ProjectileID.Sets.TrailingMode[Projectile.type] = 2; - ProjectileID.Sets.TrailCacheLength[Projectile.type] = 20; - } - - public override void SetDefaults() - { - Projectile.width = Projectile.height = 16; - Projectile.friendly = true; - Projectile.DamageType = DamageClass.Melee; - Projectile.penetrate = 1; - Projectile.tileCollide = false; - Projectile.timeLeft = Lifetime; - Projectile.DamageType = RogueDamageClass.Instance; - } - - public override void AI() - { - NPC potentialTarget = Projectile.Center.ClosestNPCAt(800f, true); - if (potentialTarget != null) - AttackTarget(potentialTarget); - - Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver2; - EmitDust(); - } - - public void AttackTarget(NPC target) - { - float newSpeed = Projectile.velocity.Length() * ExponentialAccelerationFactor; - if (newSpeed > MaxHomingSpeed) - newSpeed = MaxHomingSpeed; - - if (!Projectile.WithinRange(target.Center, 30f)) - { - Projectile.velocity = (Projectile.velocity * 5f + Projectile.SafeDirectionTo(target.Center) * newSpeed) / 6f; - Projectile.velocity = Projectile.velocity.ToRotation().AngleTowards(Projectile.AngleTo(target.Center), 0.15f).ToRotationVector2() * newSpeed; - } - } - - public void EmitDust() - { - if (Main.dedServ) - return; - - for (int i = 0; i < 2; i++) - { - if (!Main.rand.NextBool(3)) - continue; - - Dust dust = Dust.NewDustPerfect(Projectile.Center - (Projectile.rotation - MathHelper.PiOver2).ToRotationVector2() * 10f, 261); - dust.color = Color.Cyan; - dust.velocity = Main.rand.NextVector2Unit(); - dust.scale = Main.rand.NextFloat(0.75f, 1.05f); - dust.noGravity = true; - } - } - } -} diff --git a/Projectiles/Rogue/PrismRocket.png b/Projectiles/Rogue/PrismRocket.png deleted file mode 100644 index dd035814fc..0000000000 Binary files a/Projectiles/Rogue/PrismRocket.png and /dev/null differ diff --git a/Projectiles/Rogue/PrismShurikenBlade.cs b/Projectiles/Rogue/PrismShurikenBlade.cs index d6dbc41b11..d535d70023 100644 --- a/Projectiles/Rogue/PrismShurikenBlade.cs +++ b/Projectiles/Rogue/PrismShurikenBlade.cs @@ -1,5 +1,13 @@ -using Microsoft.Xna.Framework; +using System; +using System.Collections.Generic; +using CalamityMod.Particles; +using CalamityMod.Projectiles.Magic; +using CalamityMod.Projectiles.Summon; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using ReLogic.Content; using Terraria; +using Terraria.GameContent; using Terraria.ID; using Terraria.ModLoader; @@ -14,33 +22,45 @@ namespace CalamityMod.Projectiles.Rogue Projectile.width = Projectile.height = 22; Projectile.friendly = true; Projectile.ignoreWater = true; + Projectile.penetrate = -1; Projectile.DamageType = RogueDamageClass.Instance; Projectile.extraUpdates = 1; - Projectile.timeLeft = Projectile.MaxUpdates * 300; + Projectile.usesLocalNPCImmunity = true; + Projectile.tileCollide = false; + Projectile.localNPCHitCooldown = 10; + Projectile.timeLeft = 300; } public override void AI() { - CalamityUtils.HomeInOnNPC(Projectile, false, 850f, 19f, 30f); + if (Projectile.timeLeft <= 260) + CalamityUtils.HomeInOnNPC(Projectile, false, 850f, 19f, 30f); + Projectile.velocity += Projectile.velocity.RotatedBy(MathHelper.ToRadians(90f)) * 0.02f; Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver2; + if (Main.rand.NextBool(4)) + { + List eColors = new List() + { + Color.PaleVioletRed, + Color.Turquoise, + Color.OrangeRed, + Color.GreenYellow + }; + float rate = (Main.GlobalTimeWrappedHourly * 8); + int colorIndex = (int)(rate / 2 % eColors.Count); + Color currentColor = eColors[colorIndex]; + Color nextColor = eColors[(colorIndex + 1) % eColors.Count]; + Color usedColor = Color.Lerp(currentColor, nextColor, rate % 2f > 1f ? 1f : rate % 1f); + Particle smoke = new HeavySmokeParticle(Projectile.Center, Projectile.velocity * Main.rand.NextFloat(-0.2f, -0.6f), usedColor, 40, Main.rand.NextFloat(0.45f, 0.6f), 0.8f, Main.rand.NextFloat(-0.2f, 0.2f), true, required: true); + GeneralParticleHandler.SpawnParticle(smoke); + } } - public override void OnKill(int timeLeft) + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - if (Main.dedServ) - return; - - for (int i = 0; i < 15; i++) + if (Projectile.timeLeft <= 260) { - Vector2 circularOffsetDirection = (MathHelper.TwoPi * i / 15f).ToRotationVector2().RotatedBy(Projectile.velocity.ToRotation() - MathHelper.PiOver2); - Vector2 spawnPosition = Projectile.Center - (Projectile.rotation - MathHelper.PiOver2).ToRotationVector2() * Projectile.height * 1.25f; - spawnPosition += circularOffsetDirection * new Vector2(12f, 7f); - - Dust energy = Dust.NewDustPerfect(spawnPosition, 261); - energy.velocity = circularOffsetDirection * new Vector2(3f, 2f); - energy.color = Color.Cyan; - energy.scale = 0.7f; - energy.noGravity = true; + Projectile.Kill(); } } diff --git a/Projectiles/Rogue/RefractionRotorProjectile.cs b/Projectiles/Rogue/RefractionRotorProjectile.cs index dfc1f380ca..7bafa8c5b8 100644 --- a/Projectiles/Rogue/RefractionRotorProjectile.cs +++ b/Projectiles/Rogue/RefractionRotorProjectile.cs @@ -1,7 +1,15 @@ using System; +using System.Collections.Generic; +using System.Security.AccessControl; +using CalamityMod.Items.Weapons.Rogue; +using CalamityMod.Particles; +using CalamityMod.Projectiles.Rogue; +using CalamityMod.Sounds; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using ReLogic.Content; using Terraria; +using Terraria.Audio; using Terraria.ID; using Terraria.ModLoader; @@ -11,6 +19,7 @@ namespace CalamityMod.Projectiles.Rogue { public new string LocalizationCategory => "Projectiles.Rogue"; public const int EnergyShotCount = 6; + private static float RotationIncrement = 0.5f; public override string Texture => "CalamityMod/Items/Weapons/Rogue/RefractionRotor"; public override void SetStaticDefaults() @@ -24,33 +33,58 @@ namespace CalamityMod.Projectiles.Rogue Projectile.width = 142; Projectile.height = 126; Projectile.friendly = true; - Projectile.penetrate = 10; + Projectile.penetrate = -1; Projectile.timeLeft = 300; Projectile.alpha = 255; + Projectile.MaxUpdates = 2; Projectile.tileCollide = false; Projectile.usesLocalNPCImmunity = true; - Projectile.localNPCHitCooldown = 10; + Projectile.localNPCHitCooldown = 20; Projectile.DamageType = RogueDamageClass.Instance; } public override void AI() { + float spin = Projectile.direction <= 0 ? -0.8f : 0.8f; + Projectile.rotation += spin * RotationIncrement; Projectile.alpha = Utils.Clamp(Projectile.alpha - 18, 0, 255); - Projectile.rotation += Projectile.velocity.Length() * Math.Sign(Projectile.velocity.X) * 0.036f; + if (Projectile.timeLeft == 80) + OnhitGrind(spin); + Projectile.StickyProjAI(80, true); + if (Projectile.Calamity().stealthStrike) + { + CalamityUtils.HomeInOnNPC(Projectile, true, 450f, 24f, 30f); + } } - public override bool? CanDamage() => Projectile.alpha <= 128 ? null : false; + private void OnhitGrind(float spinDir) + { + // Spin extra fast to visually shred the enemy. + Projectile.rotation += spinDir * RotationIncrement * 0.8f; + Projectile.StickyProjAI(12, true); + } public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) { - if (Projectile.timeLeft > 20) - Projectile.timeLeft = 20; + if (Projectile.timeLeft > 80) + Projectile.timeLeft = 80; + Projectile.ModifyHitNPCSticky(10); + Projectile.velocity *= 0.8f; + if (Projectile.soundDelay == 0) + { + SoundEngine.PlaySound(new SoundStyle("CalamityMod/Sounds/Custom/SwiftSlice") { Volume = 0.7f }, Projectile.Center); + Projectile.soundDelay = 10; + } + if (Main.myPlayer == Projectile.owner) + { + int slash = Projectile.NewProjectile(Projectile.GetSource_FromAI(), Projectile.Center, Projectile.velocity * 0.1f, ModContent.ProjectileType(), Projectile.damage, 0f, Projectile.owner, target.whoAmI, Projectile.velocity.ToRotation()); + if (Main.projectile.IndexInRange(slash)) + Main.projectile[slash].timeLeft = 20; + } } - public override void OnKill(int timeLeft) { - // Release a puff of rainbow dust and some blades. - // If this projectile is a stealth strike, don't create the blades as a gore-- create them as a projectile instead. + // Creates an explosion and fan of blades on death if (!Main.dedServ) { for (int i = 0; i < 15; i++) @@ -62,40 +96,18 @@ namespace CalamityMod.Projectiles.Rogue rainbowBurst.fadeIn = Main.rand.NextFloat(0.8f, 1.6f); rainbowBurst.noGravity = true; } - - if (!Projectile.Calamity().stealthStrike) - { - if (Main.netMode != NetmodeID.Server) - { - int goreType = Mod.Find("PrismShurikenBlade").Type; - for (int i = 0; i < 6; i++) - { - Vector2 shootDirection = (MathHelper.TwoPi * i / 6f + Projectile.rotation + MathHelper.PiOver2).ToRotationVector2(); - Vector2 spawnPosition = Projectile.Center + Projectile.Size * 0.5f * Projectile.scale * shootDirection * 0.85f; - if (!WorldGen.SolidTile((int)spawnPosition.X / 16, (int)spawnPosition.Y / 16)) - Gore.NewGorePerfect(Projectile.GetSource_Death(), spawnPosition, Projectile.velocity * 0.5f + shootDirection * 7f, goreType, Projectile.scale); - } - } - } + Particle bolt2 = new CustomPulse(Projectile.Center, Vector2.Zero, Color.DarkRed, "CalamityMod/Particles/ShatteredExplosion", Vector2.One, Main.rand.NextFloat(-10f, 10f), 0f, 0.2f, 25); + GeneralParticleHandler.SpawnParticle(bolt2); + Particle bolt3 = new CustomPulse(Projectile.Center, Vector2.Zero, Color.SkyBlue, "CalamityMod/Particles/ShatteredExplosion", Vector2.One, Main.rand.NextFloat(-10f, 10f), 0f, 0.1f, 21); + GeneralParticleHandler.SpawnParticle(bolt3); + Particle bolt4 = new CustomPulse(Projectile.Center, Vector2.Zero, Color.DarkGreen, "CalamityMod/Particles/ShatteredExplosion", Vector2.One, Main.rand.NextFloat(-10f, 10f), 0f, 0.15f, 19); + GeneralParticleHandler.SpawnParticle(bolt4); } - int shootType = ModContent.ProjectileType(); + int shootType = ModContent.ProjectileType(); if (Main.myPlayer != Projectile.owner) return; - // Release a circle of damaging blades if this projectile is a stealth strike. - if (Projectile.Calamity().stealthStrike) - { - int bladeType = ModContent.ProjectileType(); - int rocketDamage = (int)(Projectile.damage * 0.8); - for (int i = 0; i < 6; i++) - { - Vector2 shootDirection = (MathHelper.TwoPi * i / 6f + Projectile.rotation + MathHelper.PiOver2).ToRotationVector2(); - Vector2 spawnPosition = Projectile.Center + Projectile.Size * 0.5f * Projectile.scale * shootDirection * 0.85f; - Projectile.NewProjectile(Projectile.GetSource_FromThis(), spawnPosition, Projectile.velocity * 0.5f + shootDirection * 7f, bladeType, rocketDamage, Projectile.knockBack, Projectile.owner); - } - } - if (CalamityUtils.CountProjectiles(shootType) > 24) return; @@ -114,6 +126,11 @@ namespace CalamityMod.Projectiles.Rogue Vector2 drawPosition = Projectile.Center - Main.screenPosition + Vector2.UnitY * Projectile.gfxOffY; Vector2 origin = glowmask.Size() * 0.5f; Main.EntitySpriteDraw(glowmask, drawPosition, null, Projectile.GetAlpha(Color.White), Projectile.rotation, origin, Projectile.scale, SpriteEffects.None, 0); + Asset p = ModContent.Request("CalamityMod/Particles/CircularSmearSmokey"); + Asset p2 = ModContent.Request("CalamityMod/Particles/SemiCircularSmearSwipe"); + Vector2 generalDrawPos = Projectile.Center - Main.screenPosition; + Main.EntitySpriteDraw(p2.Value, generalDrawPos, null, (Main.rand.NextBool() ? Color.YellowGreen : Color.Goldenrod) with { A = 0 } * 0.55f, Projectile.rotation * Main.rand.NextFloat(1.6f, 1.7f), p2.Size() * 0.5f, (Main.rand.NextBool() ? 1.6f : 1.4f) * Main.rand.NextFloat(0.8f, 1.15f), SpriteEffects.None); + Main.EntitySpriteDraw(p.Value, generalDrawPos, null, (Main.rand.NextBool() ? Color.OrangeRed : Color.CornflowerBlue) with { A = 0 } * 0.75f, Projectile.rotation * Main.rand.NextFloat(1.2f, 1.3f), p.Size() * 0.5f, Main.rand.NextBool() ? 1.4f : 1.2f, SpriteEffects.None); } } } diff --git a/Projectiles/Rogue/RefractionRotorSlashCreator.cs b/Projectiles/Rogue/RefractionRotorSlashCreator.cs new file mode 100644 index 0000000000..ad9b68446f --- /dev/null +++ b/Projectiles/Rogue/RefractionRotorSlashCreator.cs @@ -0,0 +1,60 @@ +using System; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Rogue +{ + public class RefractionRotorSlashCreator : ModProjectile, ILocalizedModType + { + public new string LocalizationCategory => "Projectiles.Rogue"; + public NPC Target => Main.npc[(int)Projectile.ai[0]]; + public float SlashDirection + { + get + { + if (Projectile.ai[1] > MathHelper.Pi) + return Main.rand.NextFloatDirection(); + return Projectile.ai[1] + Main.rand.NextFloatDirection() * 0.2f; + } + } + + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + + public override void SetDefaults() + { + Projectile.width = 2; + Projectile.height = 2; + Projectile.ignoreWater = false; + Projectile.tileCollide = false; + Projectile.penetrate = -1; + Projectile.timeLeft = 45; + Projectile.MaxUpdates = 2; + Projectile.noEnchantmentVisuals = true; + } + + public override void AI() + { + if (Main.myPlayer == Projectile.owner && Projectile.timeLeft % 20 == 19) + { + float maxOffset = Target.width * 0.4f; + if (maxOffset > 300f) + maxOffset = 300f; + Vector2 baseDirection = Vector2.UnitX; + if (Projectile.timeLeft <= 20) + baseDirection = -Vector2.UnitY; + + Vector2 spawnOffset = SlashDirection.ToRotationVector2(); + spawnOffset *= Main.rand.NextFloatDirection() * maxOffset; + Vector2 sliceVelocity = spawnOffset.SafeNormalize(Vector2.UnitY) * 0.1f; + for (int i = 0; i < 4; i++) + { + Projectile.NewProjectile(Projectile.GetSource_FromAI(), Projectile.Center + spawnOffset, sliceVelocity, ModContent.ProjectileType(), (int)(Projectile.damage * 0.5), 0f, Projectile.owner); + } + } + } + + public override bool? CanDamage() => false; + } +} diff --git a/Projectiles/Rogue/RefractionSlash.cs b/Projectiles/Rogue/RefractionSlash.cs new file mode 100644 index 0000000000..e60cf1910b --- /dev/null +++ b/Projectiles/Rogue/RefractionSlash.cs @@ -0,0 +1,59 @@ +using System; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.Items.Weapons.Rogue; +using CalamityMod.Particles; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Rogue +{ + public class RefractionSlash : ModProjectile, ILocalizedModType + { + public new string LocalizationCategory => "Projectiles.Rogue"; + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + public override void SetDefaults() + { + Projectile.width = 512; + Projectile.height = 24; + Projectile.friendly = true; + Projectile.DamageType = RogueDamageClass.Instance; + Projectile.ignoreWater = true; + Projectile.tileCollide = false; + Projectile.penetrate = 2; + Projectile.Opacity = 1f; + Projectile.timeLeft = 35; + Projectile.MaxUpdates = 2; + Projectile.scale = 0.75f; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = Projectile.MaxUpdates * 12; + Projectile.noEnchantmentVisuals = true; + } + + public override void AI() + { + Projectile.rotation = Projectile.velocity.ToRotation(); + Projectile.Opacity = Projectile.timeLeft / 35f; + if (Projectile.timeLeft == 34) + { + Particle spark2 = new GlowSparkParticle(Projectile.Center, new Vector2(0.1f, 0.1f).RotatedByRandom(100), false, 10, Main.rand.NextFloat(0.05f, 0.09f), (Main.rand.NextBool() ? Color.Cyan : Main.rand.NextBool() ? Color.LimeGreen : Color.PaleVioletRed) * 0.7f, new Vector2(2f, 0.5f), true); + GeneralParticleHandler.SpawnParticle(spark2); + } + } + + public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) + { + return Projectile.RotatingHitboxCollision(targetHitbox.TopLeft(), targetHitbox.Size()); + } + + public override bool ShouldUpdatePosition() => true; + + public override Color? GetAlpha(Color lightColor) => Color.Lerp(Color.Cyan, Color.Lime, Projectile.identity / 7f % 1f) * Projectile.Opacity; + + public override bool PreDraw(ref Color lightColor) + { + return false; + } + } +} diff --git a/Projectiles/Rogue/WhitewaterAura.cs b/Projectiles/Rogue/WhitewaterAura.cs new file mode 100644 index 0000000000..4d19d49999 --- /dev/null +++ b/Projectiles/Rogue/WhitewaterAura.cs @@ -0,0 +1,95 @@ +using System; +using CalamityMod.Buffs.DamageOverTime; +using CalamityMod.CalPlayer; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Rogue +{ + public class WhitewaterAura : ModProjectile, ILocalizedModType + { + public new string LocalizationCategory => "Projectiles.Rogue"; + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + public ref float time => ref Projectile.ai[0]; + public float fade = 0; + public float areaScale = 1; + public override void SetDefaults() + { + Projectile.width = Projectile.height = 5; + Projectile.friendly = true; + Projectile.penetrate = -1; + Projectile.timeLeft = 300; + Projectile.tileCollide = false; + Projectile.ignoreWater = true; + Projectile.DamageType = RogueDamageClass.Instance; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = 7; + } + + public override void AI() + { + Projectile.rotation += Main.rand.NextFloat(0.09f, 0.23f); + areaScale = (Math.Abs((float)Math.Sin(time * 0.175f / MathHelper.Pi)) * 0.05f) + 1; + for (int playerIndex = 0; playerIndex < Main.maxPlayers; playerIndex++) + { + Player player = Main.player[playerIndex]; + float targetDist = Vector2.Distance(player.Center, Projectile.Center); + + if (targetDist < 200f * areaScale && time % 6 == 0) + { + player.statLife += 1; + player.HealEffect(1); + if (player.statLife > player.statLifeMax2) + player.statLife = player.statLifeMax2; + } + } + + if (Projectile.timeLeft < 30) + { + fade = MathHelper.Lerp(fade, 0, 0.12f); + areaScale = MathHelper.Lerp(areaScale, 0, 0.12f); + } + if (time < 30) + fade = MathHelper.Lerp(fade, 1, 0.12f); + else if (Projectile.timeLeft > 30) + { + for (int i = 0; i < 4; i++) + { + Dust dust = Dust.NewDustPerfect(Projectile.Center + Main.rand.NextVector2CircularEdge(200f * areaScale, 200f * areaScale), 66); + dust.scale = Main.rand.NextFloat(0.3f, 0.7f); + dust.velocity = Vector2.One.RotatedByRandom(100) * Main.rand.NextFloat(0.5f, 1f); + dust.color = Color.LightBlue; + dust.noGravity = true; + } + } + time++; + } + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) + { + target.AddBuff(BuffID.Wet, 300); + target.AddBuff(ModContent.BuffType(), 300); + if (target.CanBeMoved(true)) + { + // Launch + Vector2 launchVel = (Projectile.Center - target.Center).SafeNormalize(Vector2.UnitY) * -6; + target.velocity = launchVel * (target.knockBackResist == 0 ? 0.5f : 1f); + } + } + public override bool PreDraw(ref Color lightColor) + { + Texture2D tex = ModContent.Request("CalamityMod/Particles/HighResFoggyCircleHardEdge").Value; + Texture2D tex2 = ModContent.Request("CalamityMod/Particles/SoftRoundExplosion").Value; + Color drawColor2 = Color.LightBlue; + + Main.EntitySpriteDraw(tex, Projectile.Center - Main.screenPosition, null, drawColor2 with { A = 0 }, 0, tex.Size() / 2f, 0.2f * fade * areaScale, SpriteEffects.None, 0); + Main.EntitySpriteDraw(tex2, Projectile.Center - Main.screenPosition, null, drawColor2 with { A = 0 } * 0.3f, Projectile.rotation, tex2.Size() / 2f, 0.2f * fade * areaScale, SpriteEffects.None, 0); + Main.EntitySpriteDraw(tex2, Projectile.Center - Main.screenPosition, null, drawColor2 with { A = 0 } * 0.3f, -Projectile.rotation, tex2.Size() / 2f, 0.2f * fade * areaScale, SpriteEffects.None, 0); + + return false; + } + public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, 200 * areaScale, targetHitbox); + } +} diff --git a/Projectiles/Rogue/WhitewaterProj.cs b/Projectiles/Rogue/WhitewaterProj.cs new file mode 100644 index 0000000000..4815b5e882 --- /dev/null +++ b/Projectiles/Rogue/WhitewaterProj.cs @@ -0,0 +1,240 @@ +using System; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Audio; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Rogue +{ + public class WhitewaterProj : ModProjectile, ILocalizedModType + { + public new string LocalizationCategory => "Projectiles.Rogue"; + public override string Texture => "CalamityMod/Items/Weapons/Rogue/Whitewater"; + public ref float time => ref Projectile.ai[0]; + + public bool returning = false; + public bool empowered = false; + public bool shattered = false; + public int shatterTimer = 230; + public float fade = 0; + public float damageModifier = 1; + public float randSize; + + public int returnTime = 500; + public int becomeEmpoweredTime = 60; + + public override void SetDefaults() + { + Projectile.width = 36; + Projectile.height = 40; + Projectile.friendly = true; + Projectile.penetrate = -1; + Projectile.extraUpdates = 1; + Projectile.tileCollide = false; + Projectile.timeLeft = 800; + Projectile.DamageType = RogueDamageClass.Instance; + Projectile.ignoreWater = true; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = 20; + } + public override void AI() + { + Player Owner = Main.player[Projectile.owner]; + + randSize = Main.rand.NextFloat(0.8f, 1.2f); + Projectile.rotation += 0.02f * Projectile.velocity.Length(); + + if (time >= returnTime) + returning = true; + if (time > becomeEmpoweredTime && time < returnTime && !shattered) + { + fade = MathHelper.Lerp(fade, 1, 0.06f); + empowered = true; + } + else + { + fade = MathHelper.Lerp(fade, 0, 0.07f); + empowered = false; + } + if (empowered) + { + Lighting.AddLight(Projectile.Center, Color.LightBlue.ToVector3() * fade); + if (Main.rand.NextBool(5)) + { + Dust dust = Dust.NewDustPerfect(Projectile.Center + Main.rand.NextVector2Circular(15, 15), 278); + dust.noGravity = true; + dust.scale = Main.rand.NextFloat(0.3f, 0.55f); + dust.velocity = Projectile.velocity * Main.rand.NextFloat(0.2f, 0.4f); + dust.color = Color.LightBlue; + } + } + + if (time > 20 && !returning && !shattered) + { + Vector2 moveToMouse = (Owner.Calamity().mouseWorld - Projectile.Center).SafeNormalize(Vector2.UnitX); + if (Projectile.velocity.Length() < 12) + Projectile.velocity += moveToMouse * ( 1 - (0.85f * Utils.GetLerpValue(returnTime / 2, 0, time, true))); + else + Projectile.velocity *= 0.9f; + } + if (shattered && !returning) + { + fade = MathHelper.Lerp(fade, 1, 0.07f); + Projectile.extraUpdates = 5; + Projectile.velocity = Vector2.Zero; + Projectile.alpha = 255; + randSize = Main.rand.NextFloat(1.8f, 2.2f); + + Projectile.timeLeft++; + time--; + + if (shatterTimer <= 140) + { + if (Main.rand.NextBool(5)) + { + Vector2 vel = (Vector2.One * 19).RotatedByRandom(100) * Main.rand.NextFloat(0.9f, 1.1f); + Dust dust = Dust.NewDustPerfect(Projectile.Center + vel * 3, 66); + dust.noGravity = true; + dust.scale = Main.rand.NextFloat(0.5f, 0.85f); + dust.velocity = -vel * Main.rand.NextFloat(0.2f, 0.4f); + dust.color = Color.LightBlue; + } + } + if (shatterTimer == 230) + { + for (int i = 0; i < 25; i++) + { + Vector2 vel = (Vector2.One * 24).RotatedByRandom(100) * Main.rand.NextFloat(0.9f, 1.1f); + Dust dust = Dust.NewDustPerfect(Projectile.Center, 66); + dust.noGravity = true; + dust.scale = Main.rand.NextFloat(0.5f, 0.85f); + dust.velocity = vel * Main.rand.NextFloat(0.2f, 0.4f); + dust.color = Color.LightBlue; + } + } + shatterTimer--; + if (shatterTimer <= 0) + { + Projectile.alpha = 0; + empowered = false; + returning = true; + } + } + if (returning) + { + Projectile.extraUpdates = 1; + Projectile.alpha = 0; + float returnSpeed = 13; + float acceleration = 1.2f; + Vector2 playerCenter = Owner.Center; + float xDist = playerCenter.X - Projectile.Center.X; + float yDist = playerCenter.Y - Projectile.Center.Y; + float dist = (float)Math.Sqrt(xDist * xDist + yDist * yDist); + dist = returnSpeed / dist; + xDist *= dist; + yDist *= dist; + + if (Projectile.velocity.X < xDist) + { + Projectile.velocity.X = Projectile.velocity.X + acceleration; + if (Projectile.velocity.X < 0f && xDist > 0f) + Projectile.velocity.X += acceleration; + } + else if (Projectile.velocity.X > xDist) + { + Projectile.velocity.X = Projectile.velocity.X - acceleration; + if (Projectile.velocity.X > 0f && xDist < 0f) + Projectile.velocity.X -= acceleration; + } + if (Projectile.velocity.Y < yDist) + { + Projectile.velocity.Y = Projectile.velocity.Y + acceleration; + if (Projectile.velocity.Y < 0f && yDist > 0f) + Projectile.velocity.Y += acceleration; + } + else if (Projectile.velocity.Y > yDist) + { + Projectile.velocity.Y = Projectile.velocity.Y - acceleration; + if (Projectile.velocity.Y > 0f && yDist < 0f) + Projectile.velocity.Y -= acceleration; + } + // Delete the projectile if it touches its owner + if (Main.myPlayer == Projectile.owner) + { + if (Projectile.Hitbox.Intersects(Owner.Hitbox)) + { + Projectile.Kill(); + if (Projectile.Calamity().stealthStrike) + { + for (int x = 0; x < Main.maxProjectiles; x++) + { + Projectile projectile = Main.projectile[x]; + if (projectile.active) + { + if (projectile.type == ModContent.ProjectileType()) + { + if (projectile.timeLeft > 30) + projectile.timeLeft = 30; + } + } + } + Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, Vector2.Zero, ModContent.ProjectileType(), (int)(Projectile.damage * 0.1f), Projectile.knockBack, Projectile.owner, 0f, 0f); + } + } + } + } + time++; + } + public override bool? CanDamage() => (shattered && !returning) ? false : null; + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) + { + if (damageModifier > 0.05f) + damageModifier -= 0.05f; + + if (empowered && !shattered) + { + SoundStyle sound = new("CalamityMod/Sounds/Item/BreakAndReform"); + SoundEngine.PlaySound(sound with { Volume = 0.4f }, Projectile.Center); + + int points = Projectile.Calamity().stealthStrike ? 8 : 4; + float radians = MathHelper.TwoPi / points; + Vector2 spinningPoint = Vector2.Normalize(new Vector2(-1f, -1f)); + for (int k = 0; k < points; k++) + { + Vector2 velocity = spinningPoint.RotatedBy(radians * k).RotatedBy(Projectile.ai[1] == 1 ? MathHelper.ToRadians(45f) : 0) * 4; + + Projectile.NewProjectile(Projectile.GetSource_FromThis(), Projectile.Center, -velocity, ModContent.ProjectileType(), (int)(Projectile.damage * 0.5f), Projectile.knockBack, Projectile.owner, 0f, 0f); + } + shattered = true; + } + } + public override void ModifyHitNPC(NPC target, ref NPC.HitModifiers modifiers) + { + if (Projectile.Calamity().stealthStrike) + modifiers.SourceDamage *= damageModifier; + else // if hitting before being empowered it does less damage, otherwise on the empowered hit it does full damage, but both hits are effected by the damageMult + modifiers.SourceDamage *= (empowered && !returning) ? damageModifier : damageModifier * 0.5f; + } + public override bool PreDraw(ref Color lightColor) + { + Texture2D tex = Terraria.GameContent.TextureAssets.Projectile[Projectile.type].Value; + Texture2D rTexture = ModContent.Request("CalamityMod/Particles/BloomCircle").Value; + Texture2D wTexture = ModContent.Request("CalamityMod/Particles/HalfStar").Value; + Color drawColor2 = Color.LightBlue; + + Main.EntitySpriteDraw(rTexture, Projectile.Center - Main.screenPosition, null, drawColor2 with { A = 0 } * fade * 0.5f, Projectile.rotation, rTexture.Size() * 0.5f, 0.45f * randSize, SpriteEffects.None, 0); + + Main.EntitySpriteDraw(tex, Projectile.Center - Main.screenPosition, null, Projectile.GetAlpha(lightColor), Projectile.rotation, tex.Size() / 2f, Projectile.scale, SpriteEffects.None, 0); + + for (int k = 0; k < 2; k++) + { + float rot = (k == 0 ? MathHelper.ToRadians(90f) : 0) + (Projectile.ai[1] == -1 ? MathHelper.ToRadians(45f) : 0); + Main.EntitySpriteDraw(wTexture, Projectile.Center - Main.screenPosition, null, drawColor2 with { A = 0 } * fade * 0.4f, rot, wTexture.Size() * 0.5f, 1.15f * randSize, SpriteEffects.None, 0); + Main.EntitySpriteDraw(wTexture, Projectile.Center - Main.screenPosition, null, Color.White with { A = 0 } * fade * 0.4f, rot, wTexture.Size() * 0.5f, 0.68f * randSize, SpriteEffects.None, 0); + } + return false; + } + public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, 45, targetHitbox); + } +} diff --git a/Projectiles/Rogue/WhitewaterSpear.cs b/Projectiles/Rogue/WhitewaterSpear.cs new file mode 100644 index 0000000000..dedcc42106 --- /dev/null +++ b/Projectiles/Rogue/WhitewaterSpear.cs @@ -0,0 +1,62 @@ +using CalamityMod.Particles; +using Microsoft.Xna.Framework; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Rogue +{ + public class WhitewaterSpear : ModProjectile, ILocalizedModType + { + public new string LocalizationCategory => "Projectiles.Rogue"; + + public ref float time => ref Projectile.ai[0]; + public Vector2 startVel; + public Vector2 startPos; + public override void SetDefaults() + { + Projectile.width = 14; + Projectile.height = 64; + Projectile.friendly = true; + Projectile.ignoreWater = true; + Projectile.tileCollide = false; + Projectile.penetrate = -1; + Projectile.timeLeft = 230; + Projectile.extraUpdates = 5; + Projectile.DamageType = RogueDamageClass.Instance; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = 25; + } + + public override void AI() + { + Lighting.AddLight(Projectile.Center, Color.LightBlue.ToVector3() * 0.4f); + if (time == 0) + { + startVel = Projectile.velocity; + startPos = Projectile.Center; + } + + if (Projectile.timeLeft % 3 == 0) + { + Particle spark = new SparkParticle(Projectile.Center - Projectile.velocity * 2, -Projectile.velocity * 0.05f, false, 14, 1f, Color.LightBlue * 0.2f); + GeneralParticleHandler.SpawnParticle(spark); + } + + if (time > 80) + { + Projectile.velocity.X = MathHelper.Lerp(Projectile.velocity.X, -startVel.X, 0.02f); + Projectile.velocity.Y = MathHelper.Lerp(Projectile.velocity.Y, -startVel.Y, 0.02f); + } + else + Projectile.velocity *= 0.995f; + + Projectile.rotation = Projectile.velocity.ToRotation() + MathHelper.PiOver2; + time++; + } + + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) => target.AddBuff(BuffID.Wet, 180); + + public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, 15, targetHitbox); + } +} diff --git a/Projectiles/Rogue/WhitewaterSpear.png b/Projectiles/Rogue/WhitewaterSpear.png new file mode 100644 index 0000000000..a50659774e Binary files /dev/null and b/Projectiles/Rogue/WhitewaterSpear.png differ diff --git a/Projectiles/Summon/AureusBomber.cs b/Projectiles/Summon/AureusBomber.cs index 1babe1301f..9bae18cf48 100644 --- a/Projectiles/Summon/AureusBomber.cs +++ b/Projectiles/Summon/AureusBomber.cs @@ -4,6 +4,7 @@ using CalamityMod.Dusts; using Microsoft.Xna.Framework; using Terraria; using Terraria.Audio; +using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.ModLoader; @@ -12,6 +13,7 @@ namespace CalamityMod.Projectiles.Summon public class AureusBomber : ModProjectile, ILocalizedModType { public new string LocalizationCategory => "Projectiles.Summon"; + public Player Owner => Main.player[Projectile.owner]; public override void SetStaticDefaults() { Main.projFrames[Projectile.type] = 3; @@ -254,7 +256,8 @@ namespace CalamityMod.Projectiles.Summon public override bool PreDraw(ref Color lightColor) { - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1); + var dye = Owner?.cMinion ?? 0; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1, armorShaderToUse: dye); return false; } diff --git a/Projectiles/Summon/EndoCooperBody.cs b/Projectiles/Summon/EndoCooperBody.cs index e1b83aa8cb..a2bbd06838 100644 --- a/Projectiles/Summon/EndoCooperBody.cs +++ b/Projectiles/Summon/EndoCooperBody.cs @@ -338,7 +338,8 @@ namespace CalamityMod.Projectiles.Summon public override bool PreDraw(ref Color lightColor) { - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1); + var dye = Main.player[Projectile.owner]?.cMinion ?? 0; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1, armorShaderToUse: dye); return false; } diff --git a/Projectiles/Summon/EndoCooperLimbs.cs b/Projectiles/Summon/EndoCooperLimbs.cs index ba3408aa09..cb9330fbc4 100644 --- a/Projectiles/Summon/EndoCooperLimbs.cs +++ b/Projectiles/Summon/EndoCooperLimbs.cs @@ -129,7 +129,9 @@ namespace CalamityMod.Projectiles.Summon { if (Projectile.ai[0] == 2f) return false; - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1); + + var dye = Main.player[Projectile.owner]?.cMinion ?? 0; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1, armorShaderToUse: dye); return false; } diff --git a/Projectiles/Summon/FlarebatMinion.cs b/Projectiles/Summon/FlarebatMinion.cs new file mode 100644 index 0000000000..ce80cf8fb9 --- /dev/null +++ b/Projectiles/Summon/FlarebatMinion.cs @@ -0,0 +1,215 @@ +using System; +using System.IO; +using CalamityMod.Buffs.Summon; +using CalamityMod.Particles; +using CalamityMod.Projectiles.BaseProjectiles; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Audio; +using Terraria.GameContent; +using Terraria.ID; +using Terraria.ModLoader; +using static Terraria.ModLoader.ModContent; + +namespace CalamityMod.Projectiles.Summon +{ + public class FlarebatMinion : BaseMinionProjectile + { + public override int AssociatedProjectileTypeID => ProjectileType(); + + public override int AssociatedBuffTypeID => BuffType(); + + public override ref bool AssociatedMinionBool => ref ModdedOwner.FlarebatBool; + + public override bool PreHardmodeMinionTileVision => true; + + public override int AnimationFrames => 8; + + private bool SyncedOnSpawn + { + get => Projectile.ai[0] == 1f; + set => Projectile.ai[0] = value.ToInt(); + } + + private Vector2 IdlePosition => Owner.MountedCenter + + -Vector2.UnitY.RotatedBy(MathHelper.ToRadians(15f) * (Owner.ownedProjectileCounts[Type] + Owner.ownedProjectileCounts[ProjectileType()] - 1) - MathHelper.ToRadians(30f) * MinionIndex) * 80f; + + private Action CurrentBehavior; + + [Flags] + private enum AttackBehaviorFlags : byte + { + None = 0, + HasDashed = 1, + HasHitTargetOnDash = 2, + IsReturningToOwner = 4, + } + + private AttackBehaviorFlags AttackState; + + public int MinionIndex; + + public override void SetDefaults() + { + base.SetDefaults(); + (Projectile.width, Projectile.height) = (32, 28); + } + + #region AI + + public override void MinionAI() + { + if (!SyncedOnSpawn) + { + CurrentBehavior = IdleBehavior; + FramesUntilNextAnimationFrame = 3; + SyncedOnSpawn = true; + Projectile.netUpdate = true; + } + + CurrentBehavior.Invoke(); + Projectile.rotation = Projectile.rotation.AngleTowards(MathHelper.ToRadians(Projectile.velocity.X * 3f), 0.2f); + Projectile.spriteDirection = MathF.Sign(Projectile.velocity.X); + + if (!Main.dedServ) + { + if (CurrentBehavior == AttackBehavior || (CurrentBehavior == IdleBehavior && Main.rand.NextBool(10))) + { + Dust ambientDust = Dust.NewDustDirect(Projectile.position, Projectile.width, Projectile.height, DustID.Torch); + ambientDust.noGravity = Main.rand.NextBool(); + ambientDust.noLight = true; + ambientDust.noLightEmittence = true; + } + + Lighting.AddLight(Projectile.Center, Color.OrangeRed.ToVector3() * 0.5f); + } + + } + + private void IdleBehavior() + { + if (Target is not null) + { + CurrentBehavior = AttackBehavior; + Projectile.velocity = Projectile.DirectionTo(Target.Center).RotatedByRandom(MathHelper.PiOver2 * 0.7f) * 10f; + return; + } + + Projectile.velocity = Projectile.DirectionTo(IdlePosition) * Utils.Remap(Projectile.DistanceSQ(IdlePosition), 25600f, 0f, 6f, 0f); + Projectile.MinionAntiClump(); + } + + private void AttackBehavior() + { + if (Target is null) + { + CurrentBehavior = IdleBehavior; + return; + } + + // The first stage is redirecting towards the target. + if (!AttackState.HasFlag(AttackBehaviorFlags.HasDashed) && Vector2.Dot(Projectile.DirectionTo(Target.Center), Projectile.velocity.SafeNormalize(-Vector2.UnitY)) < 0.96f) + { + Projectile.velocity = Projectile.velocity.ToRotation().AngleTowards(Projectile.DirectionTo(Target.Center).ToRotation(), 0.08f).ToRotationVector2() * + Utils.Remap(Projectile.DistanceSQ(Target.Center), 6400f, 0f, 12f, 0f); + } + + // When it's whithin a distnce and it hasn't dashed yet, it'll dash. + else if (!AttackState.HasFlag(AttackBehaviorFlags.HasDashed) && Projectile.DistanceSQ(Target.Center) < 57600f) + { + Projectile.velocity = Projectile.DirectionTo(Target.Center) * 15f; + AttackState |= AttackBehaviorFlags.HasDashed; + Projectile.netUpdate = true; + + if (!Main.dedServ) + { + Particle dashRing = new DirectionalPulseRing( + Projectile.Center, + Projectile.velocity.SafeNormalize(-Vector2.UnitY) * 5f, + Color.OrangeRed, + new Vector2(0.5f, 1f), + Projectile.velocity.ToRotation(), + 0.04f, + 0.4f, + 30); + GeneralParticleHandler.SpawnParticle(dashRing); + + SoundEngine.PlaySound(SoundID.Item1 with { Pitch = 0.5f, PitchVariance = 0.1f, Volume = 0.6f }, Projectile.Center); + } + } + + // The second stage is after the dash. + // If it has hit the target is was supposed to hit or he missed: + // Return to the owner. + if (AttackState.HasFlag(AttackBehaviorFlags.HasDashed) && !AttackState.HasFlag(AttackBehaviorFlags.IsReturningToOwner)) + { + if (Vector2.Dot(Projectile.DirectionTo(Target.Center), Projectile.velocity.SafeNormalize(-Vector2.UnitY)) < 0f || AttackState.HasFlag(AttackBehaviorFlags.HasHitTargetOnDash)) + { + AttackState |= AttackBehaviorFlags.IsReturningToOwner; + Projectile.netUpdate = true; + } + } + + // The minion will redirect towards its idle position. + // When it has arrived to it at a distance, reset the state and start over. + if (AttackState.HasFlag(AttackBehaviorFlags.IsReturningToOwner)) + { + Projectile.velocity = Projectile.velocity.ToRotation().AngleTowards(Projectile.DirectionTo(IdlePosition).ToRotation(), 0.08f).ToRotationVector2() * + Utils.Remap(Projectile.DistanceSQ(IdlePosition), 6400f, 0f, 12f, 0f); + + if (Projectile.DistanceSQ(IdlePosition) < 6400f) + { + AttackState = AttackBehaviorFlags.None; + Projectile.netUpdate = true; + } + } + } + + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) + { + if (AttackState.HasFlag(AttackBehaviorFlags.HasDashed) && !AttackState.HasFlag(AttackBehaviorFlags.HasHitTargetOnDash) && Target == target) + AttackState |= AttackBehaviorFlags.HasHitTargetOnDash; + + target.AddBuff(BuffID.OnFire, 60); + } + + #endregion + + #region Drawing + + public override bool PreDraw(ref Color lightColor) + { + Texture2D texture = TextureAssets.Projectile[Type].Value; + Rectangle frame = texture.Frame(verticalFrames: Main.projFrames[Type], frameY: Projectile.frame); + Main.EntitySpriteDraw( + texture, + Projectile.Center - Main.screenPosition, + frame, + Color.White * 0.6f, + Projectile.rotation, + frame.Size() * 0.5f, + Projectile.scale, + Projectile.spriteDirection == -1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None); + return false; + } + + #endregion + + #region Syncing + + public override void SendExtraAI(BinaryWriter writer) + { + writer.Write7BitEncodedInt(MinionIndex); + writer.Write((byte)AttackState); + } + + public override void ReceiveExtraAI(BinaryReader reader) + { + MinionIndex = reader.Read7BitEncodedInt(); + AttackState = (AttackBehaviorFlags)reader.ReadByte(); + } + + #endregion + } +} diff --git a/Projectiles/Summon/FlarebatMinion.png b/Projectiles/Summon/FlarebatMinion.png new file mode 100644 index 0000000000..2a588918c0 Binary files /dev/null and b/Projectiles/Summon/FlarebatMinion.png differ diff --git a/Projectiles/Summon/FrostbatMinion.cs b/Projectiles/Summon/FrostbatMinion.cs new file mode 100644 index 0000000000..31bc94f634 --- /dev/null +++ b/Projectiles/Summon/FrostbatMinion.cs @@ -0,0 +1,214 @@ +using System; +using System.IO; +using CalamityMod.Buffs.Summon; +using CalamityMod.Particles; +using CalamityMod.Projectiles.BaseProjectiles; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Audio; +using Terraria.GameContent; +using Terraria.GameContent.Biomes; +using Terraria.ID; +using static Terraria.ModLoader.ModContent; + +namespace CalamityMod.Projectiles.Summon +{ + public class FrostbatMinion : BaseMinionProjectile + { + public override int AssociatedProjectileTypeID => ProjectileType(); + + public override int AssociatedBuffTypeID => BuffType(); + + public override ref bool AssociatedMinionBool => ref ModdedOwner.FrostbatBool; + + public override bool PreHardmodeMinionTileVision => true; + + public override int AnimationFrames => 8; + + private bool SyncedOnSpawn + { + get => Projectile.ai[0] == 1f; + set => Projectile.ai[0] = value.ToInt(); + } + + private Vector2 IdlePosition => Owner.MountedCenter + + -Vector2.UnitY.RotatedBy(MathHelper.ToRadians(15f) * (Owner.ownedProjectileCounts[Type] + Owner.ownedProjectileCounts[ProjectileType()] - 1) - MathHelper.ToRadians(30f) * MinionIndex) * 80f; + + private Action CurrentBehavior; + + [Flags] + private enum AttackBehaviorFlags : byte + { + None = 0, + HasDashed = 1, + HasHitTargetOnDash = 2, + IsReturningToOwner = 4, + } + + private AttackBehaviorFlags AttackState; + + public int MinionIndex; + + public override void SetDefaults() + { + base.SetDefaults(); + (Projectile.width, Projectile.height) = (32, 28); + } + + #region AI + + public override void MinionAI() + { + if (!SyncedOnSpawn) + { + CurrentBehavior = IdleBehavior; + FramesUntilNextAnimationFrame = 3; + SyncedOnSpawn = true; + Projectile.netUpdate = true; + } + + CurrentBehavior.Invoke(); + Projectile.rotation = Projectile.rotation.AngleTowards(MathHelper.ToRadians(Projectile.velocity.X * 3f), 0.2f); + Projectile.spriteDirection = MathF.Sign(Projectile.velocity.X); + + if (!Main.dedServ) + { + if (CurrentBehavior == AttackBehavior || (CurrentBehavior == IdleBehavior && Main.rand.NextBool(10))) + { + Dust ambientDust = Dust.NewDustDirect(Projectile.position, Projectile.width, Projectile.height, DustID.IceTorch); + ambientDust.noGravity = Main.rand.NextBool(); + ambientDust.noLight = true; + ambientDust.noLightEmittence = true; + } + + Lighting.AddLight(Projectile.Center, Color.Cyan.ToVector3() * 0.5f); + } + } + + private void IdleBehavior() + { + if (Target is not null) + { + CurrentBehavior = AttackBehavior; + Projectile.velocity = Projectile.DirectionTo(Target.Center).RotatedByRandom(MathHelper.PiOver2 * 0.7f) * 10f; + return; + } + + Projectile.velocity = Projectile.DirectionTo(IdlePosition) * Utils.Remap(Projectile.DistanceSQ(IdlePosition), 25600f, 0f, 6f, 0f); + Projectile.MinionAntiClump(); + } + + private void AttackBehavior() + { + if (Target is null) + { + CurrentBehavior = IdleBehavior; + return; + } + + // The first stage is redirecting towards the target. + if (!AttackState.HasFlag(AttackBehaviorFlags.HasDashed) && Vector2.Dot(Projectile.DirectionTo(Target.Center), Projectile.velocity.SafeNormalize(-Vector2.UnitY)) < 0.96f) + { + Projectile.velocity = Projectile.velocity.ToRotation().AngleTowards(Projectile.DirectionTo(Target.Center).ToRotation(), 0.08f).ToRotationVector2() * + Utils.Remap(Projectile.DistanceSQ(Target.Center), 6400f, 0f, 8f, 0f); + } + + // When it's whithin a distnce and it hasn't dashed yet, it'll dash. + else if (!AttackState.HasFlag(AttackBehaviorFlags.HasDashed) && Projectile.DistanceSQ(Target.Center) < 57600f) + { + Projectile.velocity = CalamityUtils.CalculatePredictiveAimToTarget(Projectile.Center, Target, 18f); + AttackState |= AttackBehaviorFlags.HasDashed; + Projectile.netUpdate = true; + + if (!Main.dedServ) + { + Particle dashRing = new DirectionalPulseRing( + Projectile.Center, + Projectile.velocity.SafeNormalize(-Vector2.UnitY) * 5f, + Color.Cyan, + new Vector2(0.5f, 1f), + Projectile.velocity.ToRotation(), + 0.04f, + 0.4f, + 30); + GeneralParticleHandler.SpawnParticle(dashRing); + + SoundEngine.PlaySound(SoundID.Item1 with { Pitch = 0.5f, PitchVariance = 0.1f, Volume = 0.6f }, Projectile.Center); + } + } + + // The second stage is after the dash. + // If it has hit the target is was supposed to hit or he missed: + // Return to the owner. + if (AttackState.HasFlag(AttackBehaviorFlags.HasDashed) && !AttackState.HasFlag(AttackBehaviorFlags.IsReturningToOwner)) + { + if (Vector2.Dot(Projectile.DirectionTo(Target.Center), Projectile.velocity.SafeNormalize(-Vector2.UnitY)) < 0f || AttackState.HasFlag(AttackBehaviorFlags.HasHitTargetOnDash)) + { + AttackState |= AttackBehaviorFlags.IsReturningToOwner; + Projectile.netUpdate = true; + } + } + + // The minion will redirect towards its idle position. + // When it has arrived to it at a distance, reset the state and start over. + if (AttackState.HasFlag(AttackBehaviorFlags.IsReturningToOwner)) + { + Projectile.velocity = Projectile.velocity.ToRotation().AngleTowards(Projectile.DirectionTo(IdlePosition).ToRotation(), 0.08f).ToRotationVector2() * + Utils.Remap(Projectile.DistanceSQ(IdlePosition), 6400f, 0f, 8f, 0f); + + if (Projectile.DistanceSQ(IdlePosition) < 6400f) + { + AttackState = AttackBehaviorFlags.None; + Projectile.netUpdate = true; + } + } + } + + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) + { + if (AttackState.HasFlag(AttackBehaviorFlags.HasDashed) && !AttackState.HasFlag(AttackBehaviorFlags.HasHitTargetOnDash) && Target == target) + AttackState |= AttackBehaviorFlags.HasHitTargetOnDash; + + target.AddBuff(BuffID.Frostburn, 60); + } + + #endregion + + #region Drawing + + public override bool PreDraw(ref Color lightColor) + { + Texture2D texture = TextureAssets.Projectile[Type].Value; + Rectangle frame = texture.Frame(verticalFrames: Main.projFrames[Type], frameY: Projectile.frame); + Main.EntitySpriteDraw( + texture, + Projectile.Center - Main.screenPosition, + frame, + Color.White * 0.6f, + Projectile.rotation, + frame.Size() * 0.5f, + Projectile.scale, + Projectile.spriteDirection == -1 ? SpriteEffects.FlipHorizontally : SpriteEffects.None); + return false; + } + + #endregion + + #region Syncing + + public override void SendExtraAI(BinaryWriter writer) + { + writer.Write7BitEncodedInt(MinionIndex); + writer.Write((byte)AttackState); + } + + public override void ReceiveExtraAI(BinaryReader reader) + { + MinionIndex = reader.Read7BitEncodedInt(); + AttackState = (AttackBehaviorFlags)reader.ReadByte(); + } + + #endregion + } +} diff --git a/Projectiles/Summon/FrostbatMinion.png b/Projectiles/Summon/FrostbatMinion.png new file mode 100644 index 0000000000..4533ef027e Binary files /dev/null and b/Projectiles/Summon/FrostbatMinion.png differ diff --git a/Projectiles/Summon/Hiveling.cs b/Projectiles/Summon/Hiveling.cs index 6392dae030..975c3bb882 100644 --- a/Projectiles/Summon/Hiveling.cs +++ b/Projectiles/Summon/Hiveling.cs @@ -67,7 +67,8 @@ namespace CalamityMod.Projectiles.Summon public override bool PreDraw(ref Color lightColor) { - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1); + var dye = Main.player[Projectile.owner]?.cMinion ?? 0; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1, armorShaderToUse: dye); return false; } } diff --git a/Projectiles/Summon/LuxorsGiftSummon.cs b/Projectiles/Summon/LuxorsGiftSummon.cs index 044636fc24..b15614439d 100644 --- a/Projectiles/Summon/LuxorsGiftSummon.cs +++ b/Projectiles/Summon/LuxorsGiftSummon.cs @@ -102,7 +102,8 @@ namespace CalamityMod.Projectiles.Summon public override bool PreDraw(ref Color lightColor) { - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 2); + var dye = Main.player[Projectile.owner]?.cMinion ?? 0; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 2, armorShaderToUse: dye); return false; } } diff --git a/Projectiles/Summon/MiniGuardianAttack.cs b/Projectiles/Summon/MiniGuardianAttack.cs index 7618a2ec74..1add2c4813 100644 --- a/Projectiles/Summon/MiniGuardianAttack.cs +++ b/Projectiles/Summon/MiniGuardianAttack.cs @@ -452,7 +452,8 @@ namespace CalamityMod.Projectiles.Summon // Has afterimages if maximum empowerment if (!ForcedVanity && SpawnedFromPSC) { - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1); + var dye = Owner?.cMinion ?? 0; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1, armorShaderToUse: dye); return false; } return true; diff --git a/Projectiles/Summon/MiniGuardianDefense.cs b/Projectiles/Summon/MiniGuardianDefense.cs index ff490d34a0..4df35a04f4 100644 --- a/Projectiles/Summon/MiniGuardianDefense.cs +++ b/Projectiles/Summon/MiniGuardianDefense.cs @@ -282,7 +282,8 @@ namespace CalamityMod.Projectiles.Summon // Has afterimages if maximum empowerment if (SpawnedFromPSC && !ForcedVanity) { - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1); + var dye = Owner?.cMinion ?? 0; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1, armorShaderToUse: dye); return false; } return true; diff --git a/Projectiles/Summon/MiniGuardianHealer.cs b/Projectiles/Summon/MiniGuardianHealer.cs index 4db64bdb9b..c8c3632534 100644 --- a/Projectiles/Summon/MiniGuardianHealer.cs +++ b/Projectiles/Summon/MiniGuardianHealer.cs @@ -329,7 +329,8 @@ namespace CalamityMod.Projectiles.Summon // Has afterimages if maximum empowerment if (SpawnedFromPSC && !ForcedVanity && Owner.Calamity().pscState == (int)ProfanedSoulCrystalState.Empowered) { - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1); + var dye = Owner?.cMinion ?? 0; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, 1, armorShaderToUse: dye); return false; } return true; diff --git a/Projectiles/Summon/MiniGuardianRock.cs b/Projectiles/Summon/MiniGuardianRock.cs index f4030d1c70..be009d6bbe 100644 --- a/Projectiles/Summon/MiniGuardianRock.cs +++ b/Projectiles/Summon/MiniGuardianRock.cs @@ -4,6 +4,8 @@ using CalamityMod.Dusts; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; +using Terraria.DataStructures; +using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.ModLoader; @@ -105,6 +107,7 @@ namespace CalamityMod.Projectiles.Summon public override bool PreDraw(ref Color lightColor) { + var dye = Owner?.cMinion ?? 0; bool psc = Owner.Calamity().profanedCrystalBuffs; int rockType = (int)MathHelper.Clamp(Projectile.ai[2], 1f, 6f); ; Texture2D texture = ModContent.Request("CalamityMod/NPCs/ProfanedGuardians/ProfanedRocks" + rockType.ToString()).Value; @@ -129,12 +132,27 @@ namespace CalamityMod.Projectiles.Summon drawPos = Projectile.oldPos[i] + (Projectile.Size / 2f) - Main.screenPosition + new Vector2(0f, Projectile.gfxOffY); // DO NOT REMOVE THESE "UNNECESSARY" FLOAT CASTS. THIS WILL BREAK THE AFTERIMAGES. Color color = Projectile.GetAlpha(lightColor) * ((float)(Projectile.oldPos.Length - i) / (float)Projectile.oldPos.Length); - Main.spriteBatch.Draw(texture, drawPos, frame, color * mult, Projectile.rotation, drawOrigin, Projectile.scale, SpriteEffects.None, 0f); + color *= mult; + + var drawData = new DrawData(texture, drawPos, frame, color) + { + rotation = Projectile.rotation, + origin = drawOrigin + }; + GameShaders.Armor.Apply(dye, Projectile, drawData); + Main.spriteBatch.Draw(texture, drawPos, frame, color, Projectile.rotation, drawOrigin, Projectile.scale, SpriteEffects.None, 0f); } } else { - Main.spriteBatch.Draw(texture, drawPos, frame, Color.White * mult, Projectile.rotation, drawOrigin, Projectile.scale, SpriteEffects.None, 0f); + var color = Color.White * mult; + var drawData = new DrawData(texture, drawPos, frame, color) + { + rotation = Projectile.rotation, + origin = drawOrigin + }; + GameShaders.Armor.Apply(dye, Projectile, drawData); + Main.spriteBatch.Draw(texture, drawPos, frame, color, Projectile.rotation, drawOrigin, Projectile.scale, SpriteEffects.None, 0f); } return false; diff --git a/Projectiles/Summon/SlimePuppet.cs b/Projectiles/Summon/SlimePuppet.cs index af4fe73953..0272f08163 100644 --- a/Projectiles/Summon/SlimePuppet.cs +++ b/Projectiles/Summon/SlimePuppet.cs @@ -3,8 +3,11 @@ using CalamityMod.Buffs.DamageOverTime; using Microsoft.Xna.Framework; using Terraria; using Terraria.Audio; +using Terraria.DataStructures; +using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.ModLoader; +using static System.Runtime.InteropServices.JavaScript.JSType; namespace CalamityMod.Projectiles.Summon { @@ -101,7 +104,8 @@ namespace CalamityMod.Projectiles.Summon public override bool PreDraw(ref Color lightColor) { - CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor); + var dye = Owner?.cMinion ?? 0; + CalamityUtils.DrawAfterimagesCentered(Projectile, ProjectileID.Sets.TrailingMode[Projectile.type], lightColor, armorShaderToUse: dye); return false; } } diff --git a/Projectiles/Summon/Umbrella/MagicArrow.cs b/Projectiles/Summon/Umbrella/MagicArrow.cs index e0dbdf0aea..428d4e79f8 100644 --- a/Projectiles/Summon/Umbrella/MagicArrow.cs +++ b/Projectiles/Summon/Umbrella/MagicArrow.cs @@ -180,7 +180,8 @@ namespace CalamityMod.Projectiles.Summon.Umbrella } // Draw the bat. - Main.spriteBatch.Draw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, direction, 0); + Main.CurrentDrawnEntityShader = Main.player[Projectile.owner]?.cMinion ?? 0; + Main.EntitySpriteDraw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, direction, 0); return false; } diff --git a/Projectiles/Summon/Umbrella/MagicAxe.cs b/Projectiles/Summon/Umbrella/MagicAxe.cs index c283fd7383..6e5a9657da 100644 --- a/Projectiles/Summon/Umbrella/MagicAxe.cs +++ b/Projectiles/Summon/Umbrella/MagicAxe.cs @@ -265,7 +265,8 @@ namespace CalamityMod.Projectiles.Summon.Umbrella } // Draw the axe. - Main.spriteBatch.Draw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, direction, 0); + Main.CurrentDrawnEntityShader = Main.player[Projectile.owner]?.cMinion ?? 0; + Main.EntitySpriteDraw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, direction, 0); return false; } diff --git a/Projectiles/Summon/Umbrella/MagicHammer.cs b/Projectiles/Summon/Umbrella/MagicHammer.cs index a5fc677445..d38ce96b8d 100644 --- a/Projectiles/Summon/Umbrella/MagicHammer.cs +++ b/Projectiles/Summon/Umbrella/MagicHammer.cs @@ -330,7 +330,8 @@ namespace CalamityMod.Projectiles.Summon.Umbrella } // Draw the hammer. - Main.spriteBatch.Draw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, direction, 0); + Main.CurrentDrawnEntityShader = Main.player[Projectile.owner]?.cMinion ?? 0; + Main.EntitySpriteDraw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, direction, 0); return false; } } diff --git a/Projectiles/Summon/Umbrella/MagicRifle.cs b/Projectiles/Summon/Umbrella/MagicRifle.cs index 5b5e977842..292020898d 100644 --- a/Projectiles/Summon/Umbrella/MagicRifle.cs +++ b/Projectiles/Summon/Umbrella/MagicRifle.cs @@ -300,7 +300,8 @@ namespace CalamityMod.Projectiles.Summon.Umbrella } // Draw the rifle. - Main.spriteBatch.Draw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, direction, 0); + Main.CurrentDrawnEntityShader = Main.player[Projectile.owner]?.cMinion ?? 0; + Main.EntitySpriteDraw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, direction, 0); return false; } } diff --git a/Projectiles/Summon/Umbrella/MagicUmbrella.cs b/Projectiles/Summon/Umbrella/MagicUmbrella.cs index 952850a152..c15f6f8102 100644 --- a/Projectiles/Summon/Umbrella/MagicUmbrella.cs +++ b/Projectiles/Summon/Umbrella/MagicUmbrella.cs @@ -352,7 +352,8 @@ namespace CalamityMod.Projectiles.Summon.Umbrella } // Draw the umbrella. - Main.spriteBatch.Draw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, direction, 0); + Main.CurrentDrawnEntityShader = Main.player[Projectile.owner]?.cMinion ?? 0; + Main.EntitySpriteDraw(texture, drawPosition, frame, Projectile.GetAlpha(lightColor), Projectile.rotation, origin, Projectile.scale, direction, 0); return false; } } diff --git a/Projectiles/Typeless/BossRushEffectThing.cs b/Projectiles/Typeless/BossRushEffectThing.cs index afd9b6d18a..7242715a11 100644 --- a/Projectiles/Typeless/BossRushEffectThing.cs +++ b/Projectiles/Typeless/BossRushEffectThing.cs @@ -1,6 +1,7 @@ using CalamityMod.Enums; using CalamityMod.Events; using CalamityMod.NPCs.ExoMechs; +using CalamityMod.Packets; using CalamityMod.Systems; using Microsoft.Xna.Framework; using Terraria; @@ -70,10 +71,7 @@ namespace CalamityMod.Projectiles.Typeless CalamityNetcode.SyncWorld(); if (Main.netMode == NetmodeID.Server) { - var netMessage = Mod.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.BossRushStage); - netMessage.Write(BossRushEvent.BossRushStage); - netMessage.Send(); + BossRushStagePacket.Send(); } } } diff --git a/Projectiles/Typeless/BossRushEndEffectThing.cs b/Projectiles/Typeless/BossRushEndEffectThing.cs index 879c088d75..14e38d5403 100644 --- a/Projectiles/Typeless/BossRushEndEffectThing.cs +++ b/Projectiles/Typeless/BossRushEndEffectThing.cs @@ -55,7 +55,7 @@ namespace CalamityMod.Projectiles.Typeless foreach (Player p in Main.ActivePlayers) { int rock = Item.NewItem(p.GetSource_Misc("CalamityMod_BossRushRock"), (int)p.position.X, (int)p.position.Y, p.width, p.height, ModContent.ItemType()); - if (Main.netMode == NetmodeID.Server) + if (rock < Main.maxItems && Main.netMode == NetmodeID.Server) { Main.timeItemSlotCannotBeReusedFor[rock] = 54000; NetMessage.SendData(MessageID.InstancedItem, p.whoAmI, -1, null, rock); diff --git a/Projectiles/Typeless/LeviAmberDash.cs b/Projectiles/Typeless/LeviAmberDash.cs index 6f40b18d0a..ceba1eb532 100644 --- a/Projectiles/Typeless/LeviAmberDash.cs +++ b/Projectiles/Typeless/LeviAmberDash.cs @@ -37,8 +37,9 @@ namespace CalamityMod.Projectiles.Typeless { if (target.CanBeMoved(true)) { - target.velocity.Y += -1.8f; - target.velocity.X += 4.2f * Owner.direction; + // Launch + Vector2 launchVel = (Owner.Calamity().mouseWorld - target.Center).SafeNormalize(Vector2.UnitY) * 16; + target.velocity = launchVel; } target.AddBuff(BuffID.Wet, 300); diff --git a/Projectiles/Typeless/VoidofExtinctionCrit.cs b/Projectiles/Typeless/VoidofExtinctionCrit.cs new file mode 100644 index 0000000000..2a2eb12280 --- /dev/null +++ b/Projectiles/Typeless/VoidofExtinctionCrit.cs @@ -0,0 +1,55 @@ +using System; +using CalamityMod.Dusts; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.Audio; +using Terraria.Graphics.Shaders; +using Terraria.ID; +using Terraria.ModLoader; + +namespace CalamityMod.Projectiles.Typeless +{ + public class VoidofExtinctionCrit : ModProjectile, ILocalizedModType + { + public new string LocalizationCategory => "Projectiles.Typeless"; + public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; + public Player Owner => Main.player[Projectile.owner]; + private static float ExplosionRadius = 300f; + + public override void SetDefaults() + { + //These shouldn't matter because its circular + Projectile.width = 300; + Projectile.height = 300; + Projectile.friendly = true; + Projectile.DamageType = AverageDamageClass.Instance; + Projectile.ignoreWater = true; + Projectile.tileCollide = false; + Projectile.penetrate = -1; + Projectile.timeLeft = 2; + Projectile.usesLocalNPCImmunity = true; + Projectile.localNPCHitCooldown = -1; + } + public override void AI() + { + Player player = Main.player[Projectile.owner]; + for (int i = 0; i <= 30; i++) + { + Dust dust = Dust.NewDustPerfect(Projectile.Center, Main.rand.NextBool(4) ? 218 : ModContent.DustType(), new Vector2(5, 5).RotatedByRandom(MathHelper.ToRadians(360)) * Main.rand.NextFloat(1.1f, 2.2f), 0, default, Main.rand.NextFloat(2.8f, 3.4f)); + dust.shader = GameShaders.Armor.GetSecondaryShader(player.cFace, player); + dust.noGravity = true; + } + } + + public override void OnHitNPC(NPC target, NPC.HitInfo hit, int damageDone) + { + target.AddBuff(ModContent.BuffType(), 360); + SoundEngine.PlaySound(SoundID.Item89 with { Volume = 0.5f, PitchVariance = 0.4f }, Projectile.Center); + } + + public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) => CalamityUtils.CircularHitboxCollision(Projectile.Center, ExplosionRadius, targetHitbox); + public override bool? CanDamage() => base.CanDamage(); + public override bool? CanCutTiles() => false; + } +} diff --git a/Sounds/Item/BreakAndReform.ogg b/Sounds/Item/BreakAndReform.ogg new file mode 100644 index 0000000000..30ff43b1c8 Binary files /dev/null and b/Sounds/Item/BreakAndReform.ogg differ diff --git a/Systems/MusicEventSystem.cs b/Systems/MusicEventSystem.cs index 676a712615..1746e62840 100644 --- a/Systems/MusicEventSystem.cs +++ b/Systems/MusicEventSystem.cs @@ -4,6 +4,7 @@ using System.IO; using System.Threading; using CalamityMod.Events; using CalamityMod.NPCs; +using CalamityMod.Packets; using Terraria; using Terraria.ID; using Terraria.ModLoader; @@ -280,40 +281,7 @@ namespace CalamityMod.Systems public static void SendSyncRequest() { - ModPacket packet = CalamityMod.Instance.GetPacket(); - packet.Write((byte)CalamityModMessageType.MusicEventSyncRequest); - packet.Send(); - } - - public static void FulfillSyncRequest(int requester) - { - // Only fulfill requests as the server host - if (!Main.dedServ) - return; - - ModPacket packet = CalamityMod.Instance.GetPacket(); - packet.Write((byte)CalamityModMessageType.MusicEventSyncResponse); - - int trackCount = PlayedEvents.Count; - packet.Write(trackCount); - - for (int i = 0; i < trackCount; i++) - packet.Write(PlayedEvents[i]); - - packet.Send(toClient: requester); - } - - public static void ReceiveSyncResponse(BinaryReader reader) - { - // Only receive info on clients - if (Main.dedServ) - return; - - PlayedEvents.Clear(); - int trackCount = reader.ReadInt32(); - - for (int i = 0; i < trackCount; i++) - PlayedEvents.Add(reader.ReadString()); + MusicEventSyncRequestPacket.Send(); } #endregion diff --git a/Systems/WorldgenManagementSystem.cs b/Systems/WorldgenManagementSystem.cs index 3b53923a31..eb53436d2f 100644 --- a/Systems/WorldgenManagementSystem.cs +++ b/Systems/WorldgenManagementSystem.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using CalamityMod.Items.SummonItems; +using CalamityMod.Items.Weapons.Rogue; using CalamityMod.World; using CalamityMod.World.Minibiomes; using CalamityMod.World.Planets; @@ -136,7 +137,14 @@ namespace CalamityMod.Systems int sunkenSeaX = (GenVars.UndergroundDesertLocation.Left + GenVars.UndergroundDesertLocation.Right) / 2; int sunkenSeaY = Main.maxTilesY / 2; - //place each piece of the sunken sea based on the above positons + SunkenSea.ForLoop = CalamityClientConfig.Instance.SunkenSeaMultiThreading switch + { + 2 => SunkenSea.CSharpParallelFor, + 1 => SunkenSea.ReLogicParallelFor, + _ => SunkenSea.NormalForLoop, + }; + + // place each piece of the sunken sea based on the above positons SunkenSea.PlaceRadiantReefs(sunkenSeaX - 100, sunkenSeaY + 75, true); SunkenSea.PlaceRadiantReefs(sunkenSeaX + 100, sunkenSeaY + 75, false); SunkenSea.PlacePolypForest(sunkenSeaX, sunkenSeaY + 500); @@ -415,6 +423,16 @@ namespace CalamityMod.Systems } } + // Replace Step Stool in surface Chests with Kylie + // Calamity adds a very easy recipe for this so hopefully this isn't a big deal (The 4 unironic Step Stool lovers will be out for my head) + if (isBrownChest) + { + if (chest.item[0].type == ItemID.PortableStool) + { + chest.item[0].SetDefaults(ModContent.ItemType()); + } + } + // Give Dead Man's Chests better loot. if (isDeadManChest) { diff --git a/TileEntities/TEBaseTurret.cs b/TileEntities/TEBaseTurret.cs index cc645762f3..305b23f87e 100644 --- a/TileEntities/TEBaseTurret.cs +++ b/TileEntities/TEBaseTurret.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using CalamityMod.Packets; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; @@ -197,51 +198,19 @@ namespace CalamityMod.TileEntities { if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(); - packet.Write((byte)CalamityModMessageType.Turret); - packet.Write(ID); - packet.Write(FiringTime); - packet.Write(Angle); - packet.WriteVector2(TargetPos); - WriteExtraData(packet); - packet.Send(-1, -1); - } - protected internal static bool ReadSyncPacket(Mod mod, BinaryReader reader) - { - int teID = reader.ReadInt32(); - bool exists = ByID.TryGetValue(teID, out TileEntity te); - - // The rest of the packet must be read even if it turns out the turret doesn't exist for whatever reason. - int firingTime = reader.ReadInt32(); - float angle = reader.ReadSingle(); - Vector2 targetVec = reader.ReadVector2(); - - if (exists && te is TEBaseTurret turret) - { - turret.FiringTime = firingTime; - turret.Angle = angle; - turret.TargetPos = targetVec; - turret.ReadExtraData(mod, reader); - return true; - } - else - { - // Otherwise, discard the fixed extra bytes so the message stream doesn't go haywire. - _ = reader.ReadBytes(NumExtraBytes); - return false; - } + TETurretPacket.Send(this); } // Subclasses cannot override SendSyncPacket, but they can override these functions to sync their own extra data. // Due to the limitations of TML packets, this data must be exactly 16 bytes in size. // The default implementations here write 16 bytes of zeroes and dump all 16 bytes when read. public const int NumExtraBytes = 16; - protected virtual void WriteExtraData(BinaryWriter writer) + public virtual void WriteExtraTurretData(BinaryWriter writer) { writer.Write(0Lu); writer.Write(0Lu); } - protected virtual void ReadExtraData(Mod mod, BinaryReader reader) => _ = reader.ReadBytes(NumExtraBytes); + public virtual void ReadExtraTurretData(BinaryReader reader) => _ = reader.ReadBytes(NumExtraBytes); } } diff --git a/TileEntities/TEChargingStation.cs b/TileEntities/TEChargingStation.cs index 33ec54628d..03b10d8b21 100644 --- a/TileEntities/TEChargingStation.cs +++ b/TileEntities/TEChargingStation.cs @@ -3,6 +3,7 @@ using System.Reflection; using CalamityMod.CalPlayer; using CalamityMod.Items; using CalamityMod.Items.DraedonMisc; +using CalamityMod.Packets; using CalamityMod.Tiles.DraedonStructures; using Microsoft.Xna.Framework; using Terraria; @@ -16,14 +17,16 @@ namespace CalamityMod.TileEntities public class TEChargingStation : ModTileEntity { public Vector2 Center => Position.ToWorldCoordinates(8f * ChargingStation.Width, 8f * ChargingStation.Height); - private short ChargingTimer = 0; - private short _stack = 0; + + internal short Internal_ChargingTimer = 0; + internal short Internal_Stack = 0; + public short CellStack { - get => _stack; + get => Internal_Stack; set { - _stack = value; + Internal_Stack = value; SendSyncPacket(); } } @@ -42,7 +45,7 @@ namespace CalamityMod.TileEntities return modItem.UsesCharge && modItem.Charge < modItem.MaxCharge; } } - public bool CanDoWork => _stack > 0 && PluggedItemCanCharge; + public bool CanDoWork => Internal_Stack > 0 && PluggedItemCanCharge; // Red when not actively charging an item, green when charging public Color LightColor => CanDoWork ? Color.MediumSpringGreen : Color.Red; @@ -59,13 +62,13 @@ namespace CalamityMod.TileEntities bool canWork = CanDoWork; if (!canWork) { - ChargingTimer = 0; + Internal_ChargingTimer = 0; return; } - ++ChargingTimer; + ++Internal_ChargingTimer; - if (ChargingTimer >= ChargingStation.FramesPerChargeAction) + if (Internal_ChargingTimer >= ChargingStation.FramesPerChargeAction) { // Apply charge to the plugged item first, as this doesn't send a sync packet. CalamityGlobalItem modItem = PluggedItem.Calamity(); @@ -80,7 +83,7 @@ namespace CalamityMod.TileEntities // Then decrement the cell stack. With the sync flag set, this will sync both the cell stack and the plugged item. CellStack--; - ChargingTimer = 0; + Internal_ChargingTimer = 0; } } @@ -159,8 +162,8 @@ namespace CalamityMod.TileEntities public override void SaveData(TagCompound tag) { - tag.Add("time", ChargingTimer); - tag.Add("cells", _stack); + tag.Add("time", Internal_ChargingTimer); + tag.Add("cells", Internal_Stack); Item forSaving; if (PluggedItem is null) { @@ -174,23 +177,23 @@ namespace CalamityMod.TileEntities public override void LoadData(TagCompound tag) { - ChargingTimer = tag.GetShort("time"); - _stack = tag.GetShort("cells"); + Internal_ChargingTimer = tag.GetShort("time"); + Internal_Stack = tag.GetShort("cells"); PluggedItem = ItemIO.Load(tag.GetCompound("item")); } public override void NetSend(BinaryWriter writer) { - writer.Write(ChargingTimer); - writer.Write(_stack); - ItemIO.Send(PluggedItem, writer, true); + writer.Write(Internal_ChargingTimer); + writer.Write(Internal_Stack); + ItemIO.Send(PluggedItem, writer, writeStack: true, writeFavorite: true); } public override void NetReceive(BinaryReader reader) { - ChargingTimer = reader.ReadInt16(); - _stack = reader.ReadInt16(); - PluggedItem = ItemIO.Receive(reader, true); + Internal_ChargingTimer = reader.ReadInt16(); + Internal_Stack = reader.ReadInt16(); + PluggedItem = ItemIO.Receive(reader, readStack: true, readFavorite: true); } // This packet may or may not contain the plugged item's charge value. If it doesn't, it contains a dummy value (NaN) instead. @@ -199,102 +202,22 @@ namespace CalamityMod.TileEntities { if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(); - packet.Write((byte)CalamityModMessageType.ChargingStationStandard); - packet.Write(ID); - packet.Write(ChargingTimer); - packet.Write(_stack); // Either write the real charge or garbage data. If garbage data is written it will be ignored on the other end. - CalamityGlobalItem modItem = PluggedItem.IsAir ? null : PluggedItem.Calamity(); - packet.Write(syncItemCharge && modItem != null ? modItem.Charge : float.NaN); - packet.Send(-1, -1); + var modItem = PluggedItem.IsAir ? null : PluggedItem.Calamity(); + var chargeOrNaN = (syncItemCharge && modItem != null) ? modItem.Charge : float.NaN; + TEChargingStationStandardPacket.Send(this, Internal_ChargingTimer, Internal_Stack, chargeOrNaN); // If this flag was set to true, set it to false for any further updates (until it gets set to true again). syncItemCharge = false; } - internal static bool ReadSyncPacket(Mod mod, BinaryReader reader) - { - int teID = reader.ReadInt32(); - bool exists = ByID.TryGetValue(teID, out TileEntity te); - - // The rest of the packet must be read even if it turns out the charging station doesn't exist for whatever reason. - short timer = reader.ReadInt16(); - short cellStack = reader.ReadInt16(); - float chargeOrNaN = reader.ReadSingle(); - - // When a server gets this packet, it immediately sends an equivalent packet to all clients. - if (Main.netMode == NetmodeID.Server) - { - ModPacket packet = mod.GetPacket(); - packet.Write((byte)CalamityModMessageType.ChargingStationStandard); - packet.Write(teID); - packet.Write(timer); - packet.Write(cellStack); - packet.Write(chargeOrNaN); - packet.Send(-1, -1); - } - - if (exists && te is TEChargingStation charger) - { - // Only clients update their timer from this packet. When a server receives this packet it ignores the time variable. - if (Main.netMode == NetmodeID.MultiplayerClient) - charger.ChargingTimer = timer; - charger._stack = cellStack; - - // If the charge value sent is not garbage, then try to apply the new charge to the plugged item. - if (!float.IsNaN(chargeOrNaN)) - { - bool itemExists = charger.PluggedItem != null && !charger.PluggedItem.IsAir; - CalamityGlobalItem modItem = itemExists ? charger.PluggedItem.Calamity() : null; - if (modItem != null && modItem.UsesCharge) - { - if (modItem.Charge != chargeOrNaN && Main.netMode == NetmodeID.MultiplayerClient) - charger.ClientChargingDust = true; - modItem.Charge = chargeOrNaN; - } - } - return true; - } - return false; - } - internal void SendItemSyncPacket() { if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(1024); - packet.Write((byte)CalamityModMessageType.ChargingStationItemChange); - packet.Write(ID); - ItemIO.Send(PluggedItem, packet, true); - packet.Send(-1, -1); - } - internal static bool ReadItemSyncPacket(Mod mod, BinaryReader reader) - { - int teID = reader.ReadInt32(); - bool exists = ByID.TryGetValue(teID, out TileEntity te); - - // The rest of the packet must be read even if it turns out the charging station doesn't exist for whatever reason. - Item thePlug = ItemIO.Receive(reader, true); - - // When a server gets this packet, it immediately sends an equivalent packet to all clients. - if (Main.netMode == NetmodeID.Server) - { - ModPacket packet = mod.GetPacket(); - packet.Write((byte)CalamityModMessageType.ChargingStationItemChange); - packet.Write(teID); - ItemIO.Send(thePlug, packet, true); - packet.Send(-1, -1); - } - - if (exists && te is TEChargingStation charger) - { - charger.PluggedItem = thePlug; - return true; - } - return false; + TEChargingStationItemChangePacket.Send(this, PluggedItem); } } } diff --git a/TileEntities/TECodebreaker.cs b/TileEntities/TECodebreaker.cs index 33daa22b17..dedeb3ed1b 100644 --- a/TileEntities/TECodebreaker.cs +++ b/TileEntities/TECodebreaker.cs @@ -2,6 +2,7 @@ using CalamityMod.CustomRecipes; using CalamityMod.Items.DraedonMisc; using CalamityMod.Items.Materials; +using CalamityMod.Packets; using CalamityMod.Tiles.DraedonSummoner; using Microsoft.Xna.Framework; using Terraria; @@ -175,56 +176,7 @@ namespace CalamityMod.TileEntities if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(); - BitsByte containmentFlagWrapper = new BitsByte(); - containmentFlagWrapper[0] = ContainsDecryptionComputer; - containmentFlagWrapper[1] = ContainsSensorArray; - containmentFlagWrapper[2] = ContainsAdvancedDisplay; - containmentFlagWrapper[3] = ContainsVoltageRegulationSystem; - containmentFlagWrapper[4] = ContainsCoolingCell; - - packet.Write((byte)CalamityModMessageType.UpdateCodebreakerConstituents); - packet.Write(ID); - packet.Write(sender); - packet.Write(containmentFlagWrapper); - packet.Send(-1, sender); - } - - public static void ReadConstituentsUpdateSync(Mod mod, BinaryReader reader) - { - int id = reader.ReadInt32(); - short sender = reader.ReadInt16(); - bool exists = ByID.TryGetValue(id, out TileEntity tileEntity); - - // Continue reading to the end even if a tile entity with the given ID does not exist. - // Not doing this will cause errors/bugs. - BitsByte containmentFlagWrapper = reader.ReadByte(); - bool containsDecryptionComputer = containmentFlagWrapper[0]; - bool containsSensorArray = containmentFlagWrapper[1]; - bool containsAdvancedDisplay = containmentFlagWrapper[2]; - bool containsVoltageRegulationSystem = containmentFlagWrapper[3]; - bool containsCoolingCell = containmentFlagWrapper[4]; - - // After doing reading, check again to see if the tile entity is actually there. - // If it isn't don't bother doing anything else. - if (!exists) - return; - - // Furthermore, verify to ensure that the tile entity is a valid one. - if (!(tileEntity is TECodebreaker codebreakerTileEntity)) - return; - - codebreakerTileEntity.ContainsDecryptionComputer = containsDecryptionComputer; - codebreakerTileEntity.ContainsSensorArray = containsSensorArray; - codebreakerTileEntity.ContainsAdvancedDisplay = containsAdvancedDisplay; - codebreakerTileEntity.ContainsVoltageRegulationSystem = containsVoltageRegulationSystem; - codebreakerTileEntity.ContainsCoolingCell = containsCoolingCell; - - // Send the packet again to the other clients if this packet was received on the server. - // Since ModPackets go solely to the server when sent by a client this is necesssary - // to ensure that all clients are informed of what happened. - if (Main.netMode == NetmodeID.Server) - codebreakerTileEntity.SyncConstituents(sender); + TEUpdateCodebreakerConstituentsPacket.Send(this); } public void SyncContainedStuff() @@ -233,39 +185,7 @@ namespace CalamityMod.TileEntities if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(); - packet.Write((byte)CalamityModMessageType.UpdateCodebreakerContainedStuff); - packet.Write(ID); - packet.Write(InputtedCellCount); - packet.Write(InitialCellCountBeforeDecrypting); - packet.Write(HeldSchematicID); - packet.Write(ContainsBloodSample); - packet.Send(); - } - - public static void ReadContainmentSync(Mod mod, BinaryReader reader) - { - int id = reader.ReadInt32(); - bool exists = ByID.TryGetValue(id, out TileEntity tileEntity); - - // Continue reading to the end even if a tile entity with the given ID does not exist. - // Not doing this will cause errors/bugs. - int cellCount = reader.ReadInt32(); - int cellCountBeforeDecrypting = reader.ReadInt32(); - int schematicID = reader.ReadInt32(); - - // After doing reading, check again to see if the tile entity is actually there. - // If it isn't don't bother doing anything else. - if (!exists) - return; - - // Furthermore, verify to ensure that the tile entity is a valid one. - if (!(tileEntity is TECodebreaker codebreakerTileEntity)) - return; - - codebreakerTileEntity.InputtedCellCount = cellCount; - codebreakerTileEntity.InitialCellCountBeforeDecrypting = cellCountBeforeDecrypting; - codebreakerTileEntity.HeldSchematicID = schematicID; + TEUpdateCodebreakerContainedStuffPacket.Send(this); } public void SyncDecryptCountdown() @@ -274,32 +194,7 @@ namespace CalamityMod.TileEntities if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(); - packet.Write((byte)CalamityModMessageType.UpdateCodebreakerDecryptCountdown); - packet.Write(ID); - packet.Write(DecryptionCountdown); - packet.Send(); - } - - public static void ReadDecryptCountdownSync(Mod mod, BinaryReader reader) - { - int id = reader.ReadInt32(); - bool exists = ByID.TryGetValue(id, out TileEntity tileEntity); - - // Continue reading to the end even if a tile entity with the given ID does not exist. - // Not doing this will cause errors/bugs. - int countdown = reader.ReadInt32(); - - // After doing reading, check again to see if the tile entity is actually there. - // If it isn't don't bother doing anything else. - if (!exists) - return; - - // Furthermore, verify to ensure that the tile entity is a valid one. - if (!(tileEntity is TECodebreaker codebreakerTileEntity)) - return; - - codebreakerTileEntity.DecryptionCountdown = countdown; + TEUpdateCodebreakerDecryptCountdownPacket.Send(this); } public void UpdateTime() diff --git a/TileEntities/TEHostileFireTurret.cs b/TileEntities/TEHostileFireTurret.cs index 5f79addd68..33ae21e7c2 100644 --- a/TileEntities/TEHostileFireTurret.cs +++ b/TileEntities/TEHostileFireTurret.cs @@ -121,13 +121,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_playerTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _playerTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEHostileIceTurret.cs b/TileEntities/TEHostileIceTurret.cs index 17d4fec62d..d1ebcd8a6d 100644 --- a/TileEntities/TEHostileIceTurret.cs +++ b/TileEntities/TEHostileIceTurret.cs @@ -121,13 +121,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_playerTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _playerTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEHostileLabTurret.cs b/TileEntities/TEHostileLabTurret.cs index e56a00222a..d74b9474a4 100644 --- a/TileEntities/TEHostileLabTurret.cs +++ b/TileEntities/TEHostileLabTurret.cs @@ -121,13 +121,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_playerTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _playerTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEHostileLaserTurret.cs b/TileEntities/TEHostileLaserTurret.cs index f6957f917a..f34b471781 100644 --- a/TileEntities/TEHostileLaserTurret.cs +++ b/TileEntities/TEHostileLaserTurret.cs @@ -121,13 +121,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_playerTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _playerTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEHostileOnyxTurret.cs b/TileEntities/TEHostileOnyxTurret.cs index 6443c09f49..78a7fd87e9 100644 --- a/TileEntities/TEHostileOnyxTurret.cs +++ b/TileEntities/TEHostileOnyxTurret.cs @@ -121,13 +121,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_playerTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _playerTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEHostilePlagueTurret.cs b/TileEntities/TEHostilePlagueTurret.cs index b06e3301c5..05cca39c47 100644 --- a/TileEntities/TEHostilePlagueTurret.cs +++ b/TileEntities/TEHostilePlagueTurret.cs @@ -121,13 +121,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_playerTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _playerTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEHostileWaterTurret.cs b/TileEntities/TEHostileWaterTurret.cs index d89dc7c8a0..2b2f0a8923 100644 --- a/TileEntities/TEHostileWaterTurret.cs +++ b/TileEntities/TEHostileWaterTurret.cs @@ -121,13 +121,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_playerTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _playerTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TELabHologramProjector.cs b/TileEntities/TELabHologramProjector.cs index 791cd49489..3d735f3897 100644 --- a/TileEntities/TELabHologramProjector.cs +++ b/TileEntities/TELabHologramProjector.cs @@ -1,6 +1,7 @@ using System.IO; using System.Reflection; using CalamityMod.CalPlayer; +using CalamityMod.Packets; using CalamityMod.Tiles.DraedonStructures; using Microsoft.Xna.Framework; using Terraria; @@ -95,27 +96,8 @@ namespace CalamityMod.TileEntities { if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(); - packet.Write((byte)CalamityModMessageType.LabHologramProjector); - packet.Write(ID); - packet.Write(PoppingUp); - packet.Send(-1, -1); - } - internal static bool ReadSyncPacket(Mod mod, BinaryReader reader) - { - int teID = reader.ReadInt32(); - bool exists = ByID.TryGetValue(teID, out TileEntity te); - - // The rest of the packet must be read even if it turns out the projector doesn't exist for whatever reason. - bool pop = reader.ReadBoolean(); - - if (exists && te is TELabHologramProjector projector) - { - projector.PoppingUp = pop; - return true; - } - return false; + TELabHologramProjectorPacket.Send(this, PoppingUp); } } } diff --git a/TileEntities/TEPlayerFireTurret.cs b/TileEntities/TEPlayerFireTurret.cs index ce3485376e..10feeedd45 100644 --- a/TileEntities/TEPlayerFireTurret.cs +++ b/TileEntities/TEPlayerFireTurret.cs @@ -124,13 +124,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_npcTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _npcTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEPlayerIceTurret.cs b/TileEntities/TEPlayerIceTurret.cs index b391d06346..2678aa9196 100644 --- a/TileEntities/TEPlayerIceTurret.cs +++ b/TileEntities/TEPlayerIceTurret.cs @@ -124,13 +124,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_npcTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _npcTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEPlayerLabTurret.cs b/TileEntities/TEPlayerLabTurret.cs index df9517428b..4e0bb773f1 100644 --- a/TileEntities/TEPlayerLabTurret.cs +++ b/TileEntities/TEPlayerLabTurret.cs @@ -124,13 +124,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_npcTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _npcTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEPlayerLaserTurret .cs b/TileEntities/TEPlayerLaserTurret .cs index 0360e32168..e7f7655804 100644 --- a/TileEntities/TEPlayerLaserTurret .cs +++ b/TileEntities/TEPlayerLaserTurret .cs @@ -124,13 +124,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_npcTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _npcTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEPlayerOnyxTurret.cs b/TileEntities/TEPlayerOnyxTurret.cs index 997b04959c..7cbcd7ae3a 100644 --- a/TileEntities/TEPlayerOnyxTurret.cs +++ b/TileEntities/TEPlayerOnyxTurret.cs @@ -124,13 +124,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_npcTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _npcTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEPlayerPlagueTurret.cs b/TileEntities/TEPlayerPlagueTurret.cs index 764f0c8ed8..7836915e60 100644 --- a/TileEntities/TEPlayerPlagueTurret.cs +++ b/TileEntities/TEPlayerPlagueTurret.cs @@ -105,13 +105,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_npcTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _npcTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEPlayerWaterTurret.cs b/TileEntities/TEPlayerWaterTurret.cs index 924f72e22c..3e389b070b 100644 --- a/TileEntities/TEPlayerWaterTurret.cs +++ b/TileEntities/TEPlayerWaterTurret.cs @@ -124,13 +124,13 @@ namespace CalamityMod.TileEntities // This type of turret syncs extra data: its player target index. // This only takes 2 bytes so a junk array is written for the remainder of the space. private const int BytesUsed = 2; - private static readonly byte[] JunkData = new byte[] { 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - protected override void WriteExtraData(BinaryWriter writer) + private static readonly byte[] JunkData = new byte[NumExtraBytes - BytesUsed]; + public override void WriteExtraTurretData(BinaryWriter writer) { writer.Write((short)_npcTargetIndex); writer.Write(JunkData); } - protected override void ReadExtraData(Mod mod, BinaryReader reader) + public override void ReadExtraTurretData(BinaryReader reader) { _npcTargetIndex = reader.ReadInt16(); _ = reader.ReadBytes(NumExtraBytes - BytesUsed); diff --git a/TileEntities/TEPowerCellFactory.cs b/TileEntities/TEPowerCellFactory.cs index 93bdce0481..fd0dd2161a 100644 --- a/TileEntities/TEPowerCellFactory.cs +++ b/TileEntities/TEPowerCellFactory.cs @@ -2,6 +2,7 @@ using System.Reflection; using CalamityMod.CalPlayer; using CalamityMod.Items.DraedonMisc; +using CalamityMod.Packets; using CalamityMod.Tiles.DraedonStructures; using Microsoft.Xna.Framework; using Terraria; @@ -16,14 +17,15 @@ namespace CalamityMod.TileEntities { public Vector2 Center => Position.ToWorldCoordinates(8f * PowerCellFactory.Width, 8f * PowerCellFactory.Height); public long Time = 0; - private short _stack = 0; + + internal short Stack_Internal = 0; public short CellStack { - get => _stack; + get => Stack_Internal; set { - _stack = value; + Stack_Internal = value; SendSyncPacket(); } } @@ -120,68 +122,33 @@ namespace CalamityMod.TileEntities public override void SaveData(TagCompound tag) { tag["time"] = Time; - tag["cells"] = _stack; + tag["cells"] = Stack_Internal; } public override void LoadData(TagCompound tag) { Time = tag.GetLong("time"); - _stack = tag.GetShort("cells"); + Stack_Internal = tag.GetShort("cells"); } public override void NetSend(BinaryWriter writer) { writer.Write(Time); - writer.Write(_stack); + writer.Write(Stack_Internal); } public override void NetReceive(BinaryReader reader) { Time = reader.ReadInt64(); - _stack = reader.ReadInt16(); + Stack_Internal = reader.ReadInt16(); } private void SendSyncPacket() { if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = Mod.GetPacket(); - packet.Write((byte)CalamityModMessageType.PowerCellFactory); - packet.Write(ID); - packet.Write(Time); - packet.Write(_stack); - packet.Send(-1, -1); - } - internal static bool ReadSyncPacket(Mod mod, BinaryReader reader) - { - int teID = reader.ReadInt32(); - bool exists = ByID.TryGetValue(teID, out TileEntity te); - - // The rest of the packet must be read even if it turns out the factory doesn't exist for whatever reason. - long time = reader.ReadInt64(); - short cellStack = reader.ReadInt16(); - - // When a server gets this packet, it immediately sends an equivalent packet to all clients. - if (Main.netMode == NetmodeID.Server) - { - ModPacket packet = mod.GetPacket(); - packet.Write((byte)CalamityModMessageType.PowerCellFactory); - packet.Write(teID); - packet.Write(time); - packet.Write(cellStack); - packet.Send(-1, -1); - } - - if (exists && te is TEPowerCellFactory factory) - { - // Only clients update their timer from this packet. When a server receives this packet it ignores the time variable. - if (Main.netMode == NetmodeID.MultiplayerClient) - factory.Time = time; - factory._stack = cellStack; - return true; - } - return false; + TEPowerCellFactoryPacket.Send(this, Time, Stack_Internal); } } } diff --git a/UI/DraedonSummoning/CodebreakerUI.cs b/UI/DraedonSummoning/CodebreakerUI.cs index 5468ec11de..df1ef0c32d 100644 --- a/UI/DraedonSummoning/CodebreakerUI.cs +++ b/UI/DraedonSummoning/CodebreakerUI.cs @@ -4,6 +4,7 @@ using System.Text; using CalamityMod.Items.DraedonMisc; using CalamityMod.Items.Materials; using CalamityMod.NPCs.ExoMechs; +using CalamityMod.Packets; using CalamityMod.TileEntities; using CalamityMod.World; using Microsoft.Xna.Framework; @@ -652,12 +653,7 @@ namespace CalamityMod.UI.DraedonSummoning if (Main.netMode != NetmodeID.SinglePlayer) { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.CodebreakerSummonStuff); - netMessage.Write(CalamityWorld.DraedonSummonCountdown); - netMessage.WriteVector2(CalamityWorld.DraedonSummonPosition); - netMessage.Write(CalamityWorld.DraedonMechdusa); - netMessage.Send(); + CodebreakerSummonStuffPacket.Send(); } } } diff --git a/UI/DraedonSummoning/ExoMechSelectionUI.cs b/UI/DraedonSummoning/ExoMechSelectionUI.cs index 464adb2175..2ffc7b2b12 100644 --- a/UI/DraedonSummoning/ExoMechSelectionUI.cs +++ b/UI/DraedonSummoning/ExoMechSelectionUI.cs @@ -1,4 +1,5 @@ using CalamityMod.NPCs.ExoMechs; +using CalamityMod.Packets; using CalamityMod.World; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; @@ -103,10 +104,7 @@ namespace CalamityMod.UI.DraedonSummoning if (Main.netMode != NetmodeID.SinglePlayer) { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.ExoMechSelection); - netMessage.Write((int)CalamityWorld.DraedonMechToSummon); - netMessage.Send(); + ExoMechSelectionPacket.Send(); } } Main.blockMouse = Main.LocalPlayer.mouseInterface = true; diff --git a/UI/FlightBar/FlightBar.cs b/UI/FlightBar/FlightBar.cs index 9ceab28314..a2afefa36f 100644 --- a/UI/FlightBar/FlightBar.cs +++ b/UI/FlightBar/FlightBar.cs @@ -201,7 +201,7 @@ namespace CalamityMod.UI FlightAnimTimer++; if (FlightAnimTimer >= FlightAnimFrameDelay) { - if (FlightAnimFrame >= FlightAnimFrames) + if (FlightAnimFrame >= FlightAnimFrames - 1) // Must be # of frames - 1 or else there is 1 frame of normal border before it cuts to infinite border { FlightAnimFrame = -1; FlightAnimTimer = 0; @@ -237,8 +237,7 @@ namespace CalamityMod.UI Vector2 origin = new Vector2(correctBorder.Width * 0.5f, (correctBorder.Height / FlightAnimFrames) * 0.5f); float xOffset = (correctBorder.Width - flightBarAnimTexture.Width) / 2f; int frameHeight = (flightBarAnimTexture.Height / FlightAnimFrames) - 1; - float yOffset = FlightAnimFrame == 0 ? 0 : ((correctBorder.Height / FlightAnimFrame) - frameHeight) / 2f; - Vector2 sizeDiffOffset = new Vector2(xOffset, yOffset); + Vector2 sizeDiffOffset = new Vector2(xOffset, -37f); Rectangle animCropRect = new Rectangle(0, (frameHeight + 1) * FlightAnimFrame, flightBarAnimTexture.Width, frameHeight); spriteBatch.Draw(flightBarAnimTexture, screenPos + sizeDiffOffset, animCropRect, Color.White, 0f, origin * Main.UIScale, uiScale, SpriteEffects.None, 0); } diff --git a/UI/FlightBar/FlightBarAnim.png b/UI/FlightBar/FlightBarAnim.png index 30f87ea581..82b5ce3a82 100644 Binary files a/UI/FlightBar/FlightBarAnim.png and b/UI/FlightBar/FlightBarAnim.png differ diff --git a/Utilities/DrawingUtils.BatchSetting.cs b/Utilities/DrawingUtils.BatchSetting.cs new file mode 100644 index 0000000000..982e3200d9 --- /dev/null +++ b/Utilities/DrawingUtils.BatchSetting.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework.Graphics; +using Terraria; + +namespace CalamityMod +{ + public class BatchSetting(BlendState blend, SamplerState sampler, DepthStencilState depthStencil, RasterizerState rasterizer) + { + public readonly BlendState blendState = blend; + public readonly SamplerState samplerState = sampler; + public readonly DepthStencilState depthStencilState = depthStencil; + public readonly RasterizerState rasterizerState = rasterizer; + + public static readonly BatchSetting AlphaBlend = new( + BlendState.AlphaBlend, + SamplerState.PointClamp, + DepthStencilState.None, + RasterizerState.CullCounterClockwise + ); + + public static readonly BatchSetting Additive = new( + BlendState.Additive, + SamplerState.PointClamp, + DepthStencilState.None, + RasterizerState.CullCounterClockwise + ); + + public static readonly BatchSetting NonPremultiplied = new( + BlendState.NonPremultiplied, + SamplerState.PointClamp, + DepthStencilState.None, + RasterizerState.CullCounterClockwise + ); + + public static readonly BatchSetting Opaque = new( + BlendState.Opaque, + SamplerState.PointClamp, + DepthStencilState.None, + RasterizerState.CullCounterClockwise + ); + } +} diff --git a/Utilities/DrawingUtils.SpriteBatch.cs b/Utilities/DrawingUtils.SpriteBatch.cs new file mode 100644 index 0000000000..94168b2a8a --- /dev/null +++ b/Utilities/DrawingUtils.SpriteBatch.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; + +namespace CalamityMod +{ + public static partial class CalamityUtils + { + // Cached for efficiency purposes. + private const BindingFlags Bind_Private_Instance = BindingFlags.NonPublic | BindingFlags.Instance; + private static readonly FastField Fld_BeginCalled = new("beginCalled", Bind_Private_Instance); + private static readonly FastField Fld_SortMode = new("sortMode", Bind_Private_Instance); + private static readonly FastField Fld_BlendState = new("blendState", Bind_Private_Instance); + private static readonly FastField Fld_SamplerState = new("samplerState", Bind_Private_Instance); + private static readonly FastField Fld_DepthStencilState = new("depthStencilState", Bind_Private_Instance); + private static readonly FastField Fld_RasterizerState = new("rasterizerState", Bind_Private_Instance); + private static readonly FastField Fld_TransformMatrix = new("transformMatrix", Bind_Private_Instance); + private static readonly FastField Fld_CustomEffect = new("customEffect", Bind_Private_Instance); + + /// + /// Sets a 's arbitrarily. + /// + /// The sprite batch. + /// The blend state to use. + public static void SetBlendState(this SpriteBatch spriteBatch, BlendState blendState) + { + spriteBatch.End(); + spriteBatch.Begin(SpriteSortMode.Immediate, blendState, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Main.GameViewMatrix.TransformationMatrix); + } + + /// + /// Determines if a is in a lock due to a call. + /// + /// The sprite batch to check. + public static bool HasBeginBeenCalled(this SpriteBatch spriteBatch) + { + return Fld_BeginCalled.Get(spriteBatch); + } + + public static void SafeAction(this SpriteBatch spriteBatch, Action action) + { + if (spriteBatch is null) + return; + + if (spriteBatch.HasBeginBeenCalled()) + { + var oldSort = Fld_SortMode.Get(spriteBatch); + var oldBlend = Fld_BlendState.Get(spriteBatch); + var oldSampler = Fld_SamplerState.Get(spriteBatch); + var oldDepths = Fld_DepthStencilState.Get(spriteBatch); + var oldRaster = Fld_RasterizerState.Get(spriteBatch); + var oldEffect = Fld_CustomEffect.Get(spriteBatch); + var oldMtx = Fld_TransformMatrix.Get(spriteBatch); + try + { + action?.Invoke(); + } + finally + { + // If something has started in this block, restore the state to previous one + spriteBatch.TryEnd(); + spriteBatch.TryBegin(oldSort, oldBlend, oldSampler, oldDepths, oldRaster, oldEffect, oldMtx); + } + } + else + { + try + { + action?.Invoke(); + } + finally + { + // Initial State was off, turn off the batching + spriteBatch.TryEnd(); + } + } + } + + /// + /// Starts SpriteBatch then Re-Begin batch with old settings when it's all done + /// + /// + /// + /// + /// + /// + /// + public static void SafeBegin(this SpriteBatch spriteBatch, SpriteSortMode sortMode, + BatchSetting settings, + Effect effect, + Matrix transformMatrix, + Action batchCallback + ) + { + if (spriteBatch is null) + return; + + spriteBatch.SafeAction(() => + { + spriteBatch.TryEnd(); + spriteBatch.TryBegin(sortMode, settings.blendState, settings.samplerState, settings.depthStencilState, settings.rasterizerState, effect, transformMatrix); + batchCallback?.Invoke(); + }); + } + + public static bool TryBegin(this SpriteBatch spriteBatch, SpriteSortMode sortMode, + BlendState blendState, + SamplerState samplerState, + DepthStencilState depthStencilState, + RasterizerState rasterizerState, + Effect effect, + Matrix transformMatrix) + { + if (spriteBatch.HasBeginBeenCalled()) + { + return false; + } + else + { + spriteBatch.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, transformMatrix); + return true; + } + } + + public static bool TryEnd(this SpriteBatch spriteBatch) + { + if (!spriteBatch.HasBeginBeenCalled()) + { + return false; + } + else + { + spriteBatch.End(); + return true; + } + } + } +} diff --git a/Utilities/DrawingUtils.cs b/Utilities/DrawingUtils.cs index 2492e54c54..092f151764 100644 --- a/Utilities/DrawingUtils.cs +++ b/Utilities/DrawingUtils.cs @@ -52,7 +52,7 @@ namespace CalamityMod /// If mode 1 is used, this controls the loop increment. Set it to more than 1 to skip afterimages. /// The texture to draw. Set to null to draw the projectile's own loaded texture. /// If false, the afterimages will be centered on the projectile's position instead of its own center. - public static void DrawAfterimagesCentered(Projectile proj, int mode, Color lightColor, int typeOneIncrement = 1, Texture2D texture = null, bool drawCentered = true, bool shrink = false) + public static void DrawAfterimagesCentered(Projectile proj, int mode, Color lightColor, int typeOneIncrement = 1, Texture2D texture = null, bool drawCentered = true, bool shrink = false, int armorShaderToUse = 0) { if (texture is null) texture = TextureAssets.Projectile[proj.type].Value; @@ -81,12 +81,23 @@ namespace CalamityMod // Standard afterimages. No customizable features other than total afterimage count. // Type 0 afterimages linearly scale down from 100% to 0% opacity. Their color and lighting is equal to the main projectile's. case 0: + + for (int i = 0; i < proj.oldPos.Length; ++i) { Vector2 drawPos = proj.oldPos[i] + centerOffset - Main.screenPosition + new Vector2(0f, proj.gfxOffY); // DO NOT REMOVE THESE "UNNECESSARY" FLOAT CASTS. THIS WILL BREAK THE AFTERIMAGES. float interpolant = ((float)(proj.oldPos.Length - i) / (float)proj.oldPos.Length); Color color = alphaColor * interpolant; + + var drawData = new DrawData(texture, drawPos, rectangle, color) + { + rotation = rotation, + origin = origin, + effect = spriteEffects + }; + + GameShaders.Armor.Apply(armorShaderToUse, proj, drawData); Main.spriteBatch.Draw(texture, drawPos, new Rectangle?(rectangle), color, rotation, origin, shrink ? scale * interpolant : scale, spriteEffects, 0f); } break; @@ -110,6 +121,15 @@ namespace CalamityMod float colorMult = (float)(afterimageCount - k); drawColor *= colorMult / afterimageColorCount; } + + var drawData = new DrawData(texture, drawPos, rectangle, drawColor) + { + rotation = rotation, + origin = origin, + effect = spriteEffects + }; + + GameShaders.Armor.Apply(armorShaderToUse, proj, drawData); Main.spriteBatch.Draw(texture, drawPos, new Rectangle?(rectangle), drawColor, rotation, origin, shrink ? scale * interpolant : scale, spriteEffects, 0f); k += increment; } @@ -128,6 +148,14 @@ namespace CalamityMod float interpolant = ((float)(proj.oldPos.Length - i) / (float)proj.oldPos.Length); Color color = alphaColor * interpolant; + var drawData = new DrawData(texture, drawPos, rectangle, color) + { + rotation = rotation, + origin = origin, + effect = spriteEffects + }; + + GameShaders.Armor.Apply(armorShaderToUse, proj, drawData); Main.spriteBatch.Draw(texture, drawPos, new Rectangle?(rectangle), color, afterimageRot, origin, shrink ? scale * interpolant : scale, sfxForThisAfterimage, 0f); } break; @@ -142,7 +170,10 @@ namespace CalamityMod if (!CalamityClientConfig.Instance.Afterimages || ProjectileID.Sets.TrailCacheLength[proj.type] <= 0 || failedToDrawAfterimages) { Vector2 startPos = drawCentered ? proj.Center : proj.position; - Main.spriteBatch.Draw(texture, startPos - Main.screenPosition + new Vector2(0f, proj.gfxOffY), rectangle, proj.GetAlpha(lightColor), rotation, origin, scale, spriteEffects, 0f); + Vector2 drawPos = startPos - Main.screenPosition + new Vector2(0f, proj.gfxOffY); + var drawData = new DrawData(texture, drawPos, rectangle, proj.GetAlpha(lightColor)); + GameShaders.Armor.Apply(armorShaderToUse, proj, drawData); + Main.spriteBatch.Draw(texture, drawPos, rectangle, proj.GetAlpha(lightColor), rotation, origin, scale, spriteEffects, 0f); } } @@ -327,61 +358,6 @@ namespace CalamityMod projectionMatrix = Matrix.CreateOrthographicOffCenter(0f, width * zoom.X, 0f, height * zoom.Y, 0f, 1f) * zoomScaleMatrix; } - /// - /// Sets a 's arbitrarily. - /// - /// The sprite batch. - /// The blend state to use. - public static void SetBlendState(this SpriteBatch spriteBatch, BlendState blendState) - { - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, blendState, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise, null, Main.GameViewMatrix.TransformationMatrix); - } - - // Cached for efficiency purposes. - internal static readonly FieldInfo BeginCalled = typeof(SpriteBatch).GetField("beginCalled", BindingFlags.NonPublic | BindingFlags.Instance); - - /// - /// Determines if a is in a lock due to a call. - /// - /// The sprite batch to check. - public static bool HasBeginBeenCalled(this SpriteBatch spriteBatch) - { - return (bool)BeginCalled.GetValue(spriteBatch); - } - - public static bool TryBegin(this SpriteBatch spriteBatch, SpriteSortMode sortMode, - BlendState blendState, - SamplerState samplerState, - DepthStencilState depthStencilState, - RasterizerState rasterizerState, - Effect effect, - Matrix transformMatrix) - { - if (spriteBatch.HasBeginBeenCalled()) - { - return false; - } - else - { - spriteBatch.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, transformMatrix); - return true; - } - } - - public static bool TryEnd(this SpriteBatch spriteBatch) - { - if (!spriteBatch.HasBeginBeenCalled()) - { - return false; - } - else - { - spriteBatch.End(); - return true; - } - } - /// /// Draws a line significantly more efficiently than using just one scaled line texture. Positions are automatically converted to screen coordinates. /// diff --git a/Utilities/DropHelper.cs b/Utilities/DropHelper.cs index b137434c5f..03462d29fa 100644 --- a/Utilities/DropHelper.cs +++ b/Utilities/DropHelper.cs @@ -1158,10 +1158,13 @@ namespace CalamityMod { NPC npc = info.npc; int idx = Item.NewItem(npc.GetSource_Loot(), npc.Center, itemId, stack, true, -1); - Main.timeItemSlotCannotBeReusedFor[idx] = protectionTime; - foreach (Player player in Main.ActivePlayers) - NetMessage.SendData(MessageID.InstancedItem, player.whoAmI, -1, null, idx); - Main.item[idx].active = false; + if (idx < Main.maxItems) + { + Main.timeItemSlotCannotBeReusedFor[idx] = protectionTime; + foreach (Player player in Main.ActivePlayers) + NetMessage.SendData(MessageID.InstancedItem, player.whoAmI, -1, null, idx); + Main.item[idx].active = false; + } } // Otherwise just drop the item. diff --git a/Utilities/EntityUtils.cs b/Utilities/EntityUtils.cs index 13a11b4bd1..7899a51477 100644 --- a/Utilities/EntityUtils.cs +++ b/Utilities/EntityUtils.cs @@ -39,6 +39,19 @@ namespace CalamityMod Main.LocalPlayer.GetModPlayer().GeneralScreenShakePower += (intensity * dist); } + /// + /// Check if Entity is null or Inactive (!active) + /// + /// Entity to check + /// true if entity is null or inactive, otherwise false + public static bool IsNullOrInactive(this Entity entity) + { + if (entity is null) return true; + if (!entity.active) return true; + + return false; + } + #region Fallback Method for IndexInRange /// /// Fallback method for Main.npc.IndexInRange which provide accurate range check (0 <= index < Main.maxNPCs) diff --git a/Utilities/MiscUtils.cs b/Utilities/MiscUtils.cs index eb9d1c06fe..9283578090 100644 --- a/Utilities/MiscUtils.cs +++ b/Utilities/MiscUtils.cs @@ -266,33 +266,36 @@ namespace CalamityMod public static void StartSandstorm() { - // If it's not windy enough, make it windy enough for a sandstorm - // 0.6f is the minimum for vanilla but Calamity changes it to 0.2f - // Windy days occur when wind speed is at least 0.5f (0.4f in vanilla) so this should never cause a windy day - float windSpeed = 0f; - if (Main.windSpeedCurrent == 0f) + if (Main.netMode != NetmodeID.MultiplayerClient && !Sandstorm.Happening) { - windSpeed = Main.rand.NextFloat(0.3f, 0.4f) * (Main.rand.Next(0, 2) * 2 - 1); + // If it's not windy enough, make it windy enough for a sandstorm + // 0.6f is the minimum for vanilla but Calamity changes it to 0.2f + // Windy days occur when wind speed is at least 0.5f (0.4f in vanilla) so this should never cause a windy day + float windSpeed = 0f; + if (Main.windSpeedCurrent == 0f) + { + windSpeed = Main.rand.NextFloat(0.3f, 0.4f) * (Main.rand.Next(0, 2) * 2 - 1); + } + else if (Main.windSpeedCurrent < 0.3f && Main.windSpeedCurrent > 0f) + { + windSpeed = Main.rand.NextFloat(0.3f, 0.4f); + } + else if (Main.windSpeedCurrent > -0.3f && Main.windSpeedCurrent < 0f) + { + windSpeed = Main.rand.NextFloat(-0.4f, -0.3f); + } + if (windSpeed != 0f) + { + Main.windSpeedCurrent = windSpeed < 0f ? -0.3f : 0.3f; + Main.windSpeedTarget = windSpeed; + } + Sandstorm.StartSandstorm(); } - else if (Main.windSpeedCurrent < 0.3f && Main.windSpeedCurrent > 0f) - { - windSpeed = Main.rand.NextFloat(0.3f, 0.4f); - } - else if (Main.windSpeedCurrent > -0.3f && Main.windSpeedCurrent < 0f) - { - windSpeed = Main.rand.NextFloat(-0.4f, -0.3f); - } - if (windSpeed != 0f) - { - Main.windSpeedCurrent = windSpeed < 0f ? -0.3f : 0.3f; - Main.windSpeedTarget = windSpeed; - } - Sandstorm.StartSandstorm(); } public static void StopSandstorm() { - if (Main.netMode != NetmodeID.MultiplayerClient) + if (Main.netMode != NetmodeID.MultiplayerClient && Sandstorm.Happening) { Sandstorm.StopSandstorm(); } diff --git a/Utilities/NPCUtils.cs b/Utilities/NPCUtils.cs index ace4d96066..5fa4f373d1 100644 --- a/Utilities/NPCUtils.cs +++ b/Utilities/NPCUtils.cs @@ -13,6 +13,7 @@ using CalamityMod.NPCs.OldDuke; using CalamityMod.NPCs.Providence; using CalamityMod.NPCs.SlimeGod; using CalamityMod.NPCs.Yharon; +using CalamityMod.Packets; using CalamityMod.Projectiles.Boss; using CalamityMod.World; using Microsoft.Xna.Framework; @@ -301,14 +302,7 @@ namespace CalamityMod if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = CalamityMod.Instance.GetPacket(); - packet.Write((byte)CalamityModMessageType.SyncCalamityNPCAIArray); - packet.Write((byte)npc.whoAmI); - - for (int i = 0; i < npc.Calamity().newAI.Length; i++) - packet.Write(npc.Calamity().newAI[i]); - - packet.Send(); + SyncCalamityNPCAIArrayPacket.Send(npc); } /// @@ -321,14 +315,7 @@ namespace CalamityMod if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = CalamityMod.Instance.GetPacket(); - packet.Write((byte)CalamityModMessageType.SyncVanillaNPCLocalAIArray); - packet.Write((byte)npc.whoAmI); - - for (int i = 0; i < NPC.maxAI; i++) - packet.Write(npc.localAI[i]); - - packet.Send(); + SyncVanillaNPCLocalAIArrayPacket.Send(npc); } /// @@ -340,22 +327,12 @@ namespace CalamityMod if (Main.netMode != NetmodeID.MultiplayerClient) return; - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.SyncNPCMotionDataToServer); - netMessage.Write(npc.whoAmI); - netMessage.WriteVector2(npc.Center); - netMessage.WriteVector2(npc.velocity); - netMessage.Send(); + SyncNPCMotionDataToServerPacket.Send(npc); } public static void SyncNPCPosAndRotOnly(this NPC npc) { - ModPacket packet = CalamityMod.Instance.GetPacket(); - packet.Write((byte)CalamityModMessageType.SyncNPCPosAndRotOnly); - packet.Write((byte)npc.whoAmI); - packet.WriteVector2(npc.position); - packet.Write((Half)npc.rotation); - packet.Send(); + SyncNPCPosAndRotOnlyPacket.Send(npc); } /// @@ -368,11 +345,7 @@ namespace CalamityMod if (Main.netMode == NetmodeID.SinglePlayer) return; - ModPacket packet = CalamityMod.Instance.GetPacket(); - packet.Write((byte)CalamityModMessageType.SyncDestroyerLaserColor); - packet.Write((byte)npc.whoAmI); - packet.Write(npc.Calamity().destroyerLaserColor); - packet.Send(); + SyncDestroyerLaserColorPacket.Send(npc); } #endregion diff --git a/Utilities/NetcodeUtils.cs b/Utilities/NetcodeUtils.cs new file mode 100644 index 0000000000..1d39b336ec --- /dev/null +++ b/Utilities/NetcodeUtils.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.CalPlayer; +using CalamityMod.Enums; +using Terraria; +using Terraria.DataStructures; +using Terraria.ModLoader; + +namespace CalamityMod +{ + public static partial class CalamityUtils + { + #region TileEntity RW + public static void WriteTileEntityID(this BinaryWriter writer, TileEntity tileEntity) + { + if (tileEntity is null) + { + writer.Write(int.MaxValue); + return; + } + + if (!TileEntity.ByID.ContainsKey(tileEntity.ID)) + { + writer.Write(int.MaxValue); + return; + } + + writer.Write(tileEntity.ID); + } + + public static TileEntityType ReadTileEntity(this BinaryReader reader) where TileEntityType : TileEntity + => ReadTileEntity(reader) as TileEntityType; + + public static TileEntity ReadTileEntity(this BinaryReader reader) + { + var id = reader.ReadInt32(); + bool exists = TileEntity.ByID.TryGetValue(id, out TileEntity tileEntity); + + return exists ? tileEntity : null; + } + #endregion TileEntity RW + + #region Entity RW + public static void WriteWhoAmI(this BinaryWriter writer, ModPlayer player) => WriteWhoAmI(writer, player?.Player); + public static void WriteWhoAmI(this BinaryWriter writer, Player player) + { + byte whoAmI = (byte)(player?.whoAmI ?? Main.maxPlayers); + writer.Write(whoAmI); + } + + public static void WriteWhoAmI(this BinaryWriter writer, ModNPC npc) => WriteWhoAmI(writer, npc?.NPC); + public static void WriteWhoAmI(this BinaryWriter writer, NPC npc) + { + byte whoAmI = (byte)(npc?.whoAmI ?? Main.maxNPCs); + writer.Write(whoAmI); + } + + public static CalamityPlayer ReadCalamityPlayer(this BinaryReader reader, bool nullOnInactive = true) => ReadPlayer(reader, nullOnInactive)?.Calamity() ?? null; + public static Player ReadPlayer(this BinaryReader reader, bool nullOnInactive = true) + { + int index = reader.ReadByte(); + + if (index >= Main.maxPlayers) + return null; + + var player = Main.player[index]; + + if (nullOnInactive && player.IsNullOrInactive()) + return null; + + return player; + } + + public static NPCType ReadModNPC(this BinaryReader reader, bool nullOnInactive = true) where NPCType : ModNPC => ReadNPC(reader, nullOnInactive)?.ModNPC as NPCType; + public static ModNPC ReadModNPC(this BinaryReader reader, bool nullOnInactive = true) => ReadNPC(reader, nullOnInactive)?.ModNPC ?? null; + public static NPC ReadNPC(this BinaryReader reader, bool nullOnInactive = true) + { + int index = reader.ReadByte(); + + if (index >= Main.maxNPCs) + return null; + + var npc = Main.npc[index]; + + if (nullOnInactive && npc.IsNullOrInactive()) + return null; + + return npc; + } + #endregion Entity RW + } +} diff --git a/Utilities/ProjectileUtils.cs b/Utilities/ProjectileUtils.cs index c253626482..03d5cff92b 100644 --- a/Utilities/ProjectileUtils.cs +++ b/Utilities/ProjectileUtils.cs @@ -674,7 +674,7 @@ namespace CalamityMod return false; } - public static void DrawBackglow(this Projectile projectile, Color backglowColor, float backglowArea, Texture2D? texture = null, Rectangle? frame = null) + public static void DrawBackglow(this Projectile projectile, Color backglowColor, float backglowArea, Texture2D? texture = null, Rectangle? frame = null, SpriteEffects effects = SpriteEffects.None) { texture ??= TextureAssets.Projectile[projectile.type].Value; @@ -687,7 +687,7 @@ namespace CalamityMod for (int i = 0; i < 10; i++) { Vector2 drawOffset = (MathHelper.TwoPi * i / 10f).ToRotationVector2() * backglowArea; - Main.spriteBatch.Draw(texture, drawPosition + drawOffset, frame, backAfterimageColor, projectile.rotation, origin, projectile.scale, 0, 0f); + Main.spriteBatch.Draw(texture, drawPosition + drawOffset, frame, backAfterimageColor, projectile.rotation, origin, projectile.scale, effects, 0f); } } @@ -710,7 +710,7 @@ namespace CalamityMod } } - public static void DrawProjectileWithBackglow(this Projectile projectile, Color backglowColor, Color lightColor, float backglowArea, Texture2D? texture = null, Rectangle? frame = null) + public static void DrawProjectileWithBackglow(this Projectile projectile, Color backglowColor, Color lightColor, float backglowArea, Texture2D? texture = null, Rectangle? frame = null, SpriteEffects effects = SpriteEffects.None) { texture ??= TextureAssets.Projectile[projectile.type].Value; @@ -720,8 +720,8 @@ namespace CalamityMod Vector2 drawPosition = projectile.Center - Main.screenPosition; Vector2 origin = frame.Value.Size() * 0.5f; - projectile.DrawBackglow(backglowColor, backglowArea, texture, frame); - Main.spriteBatch.Draw(texture, drawPosition, frame, projectile.GetAlpha(lightColor), projectile.rotation, origin, projectile.scale, 0, 0f); + projectile.DrawBackglow(backglowColor, backglowArea, texture, frame, effects); + Main.spriteBatch.Draw(texture, drawPosition, frame, projectile.GetAlpha(lightColor), projectile.rotation, origin, projectile.scale, effects, 0f); } public static void DrawStarTrail(this Projectile projectile, Color outer, Color inner, float auraHeight = 10f) diff --git a/Utilities/ReflectionHelper.cs b/Utilities/ReflectionHelper.cs new file mode 100644 index 0000000000..cad3cd63bd --- /dev/null +++ b/Utilities/ReflectionHelper.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Text; +using System.Threading.Tasks; +using Terraria.GameContent; + +namespace CalamityMod +{ + public class FastField(FieldInfo fieldInfo) + { + private Action _Setter = ReflectionHelper.CreateFieldSetter(fieldInfo); + private Func _Getter = ReflectionHelper.CreateFieldGetter(fieldInfo); + + public FastField(string fieldName, BindingFlags flags) : this(typeof(T).GetField(fieldName, flags)) + { + + } + + public ValueType Get(T instance) + { + return _Getter(instance); + } + + public void Set(T instance, ValueType newValue) + { + _Setter(instance, newValue); + } + } + + public static class ReflectionHelper + { + public static Action CreateFieldSetter(FieldInfo fieldInfo) + { + string methodName = fieldInfo.ReflectedType.FullName + ".set_" + fieldInfo.Name; + DynamicMethod setterMethod = new DynamicMethod(methodName, null, [typeof(T), typeof(ValueType)], true); + ILGenerator gen = setterMethod.GetILGenerator(); + + gen.Emit(OpCodes.Ldarg_0); + gen.Emit(OpCodes.Ldarg_1); + gen.Emit(OpCodes.Stfld, fieldInfo); + gen.Emit(OpCodes.Ret); + + return (Action)setterMethod.CreateDelegate(typeof(Action)); + } + + public static Func CreateFieldGetter(FieldInfo fieldInfo) + { + string methodName = fieldInfo.ReflectedType.FullName + ".get_" + fieldInfo.Name; + DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(ValueType), [typeof(T)], true); + ILGenerator gen = getterMethod.GetILGenerator(); + + gen.Emit(OpCodes.Ldarg_0); + gen.Emit(OpCodes.Ldfld, fieldInfo); + gen.Emit(OpCodes.Ret); + + return (Func)getterMethod.CreateDelegate(typeof(Func)); + } + } +} diff --git a/World/Abyss.cs b/World/Abyss.cs index 54b16021f0..7a62816fe9 100644 --- a/World/Abyss.cs +++ b/World/Abyss.cs @@ -11,6 +11,7 @@ using CalamityMod.Items.Weapons.Melee; using CalamityMod.Items.Weapons.Ranged; using CalamityMod.Items.Weapons.Rogue; using CalamityMod.Items.Weapons.Summon; +using CalamityMod.Packets; using CalamityMod.Tiles.Abyss; using CalamityMod.Tiles.Abyss.AbyssAmbient; using CalamityMod.Tiles.FurnitureVoid; @@ -1177,18 +1178,27 @@ namespace CalamityMod.World /// /// Unlocks all abyss chests, automatically synced across the server. - /// Only run initally on the server. + /// It SHOULD only run initally on the server. /// public static void UnlockAllAbyssChests() { - UnlockChests = true; - if (Main.netMode == NetmodeID.Server) { - var netMessage = CalamityMod.Instance.GetPacket(); - netMessage.Write((byte)CalamityModMessageType.UnlockAbyssChests); - netMessage.Send(); + UnlockAbyssChestsPacket.Send(); + DoUnlockAllAbyssChests(); } + else if (Main.netMode == NetmodeID.SinglePlayer) + { + DoUnlockAllAbyssChests(); + } + } + + /// + /// Actually Unlocks all abyss chests, This is NOT synced between clients. Call instead unless you know what you doing. + /// + internal static void DoUnlockAllAbyssChests() + { + UnlockChests = true; for (int c = 0; c < Main.maxChests; c++) { diff --git a/World/SunkenSea.cs b/World/SunkenSea.cs index 00332783da..b8a0091c89 100644 --- a/World/SunkenSea.cs +++ b/World/SunkenSea.cs @@ -1,5 +1,7 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; +using System.Threading.Tasks; using CalamityMod.Tiles.SunkenSea; using CalamityMod.Tiles.SunkenSea.Ambient; using CalamityMod.Walls; @@ -35,6 +37,42 @@ namespace CalamityMod.World convert normal terrain blocks below basalt into basalt BLOTCHES EVERYWHERE */ + + public static void NormalForLoop(int fromInclusive, int toExclusive, int step, Action action) + { + for (int i = fromInclusive; i < toExclusive; i += step) + action.Invoke(i); + } + + public static void ReLogicParallelFor(int fromInclusive, int toExclusive, int step, Action action) + { + FastParallel.For(fromInclusive, toExclusive, (start, end, _) => + { + for (int i = start; i < end; i += step) + action.Invoke(i); + }); + } + + public static void CSharpParallelFor(int fromInclusive, int toExclusive, int step, Action action) + { + var partitioner = Partitioner.Create(fromInclusive, toExclusive, step); + Parallel.ForEach(partitioner, (range, _) => + { + for (int i = range.Item1; i < range.Item2; i += step) + action.Invoke(i); + }); + } + + /// + /// The delegate that describes the method of a type of for loop. + /// + public delegate void ForLoopMethod(int fromInclusive, int toExclusive, int step, Action action); + + /// + /// The current type of for loop used to generate the Sunken Sea. + /// + public static ForLoopMethod ForLoop; + public static void PlaceTimelessShores(int startPosX, int startPosY) { int biomeSize = 250 + (Main.maxTilesX / 180); @@ -52,25 +90,22 @@ namespace CalamityMod.World else return -steepness * x + steepness; } - FastParallel.For(startPosX - biomeSize - 20, startPosX + biomeSize + 20, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize - 20, startPosX + biomeSize + 20, 15, (X) => { - for (int X = start; X <= end; X += 15) - { - float height = MathHelper.Lerp( + float height = MathHelper.Lerp( startPosY + 50, startPosY - 35, trapezoidLateralSteep(Utils.GetLerpValue(startPosX - biomeSize - 20, startPosX + biomeSize + 20, X))); - for (int Y = startPosY + 50; Y >= height; Y -= 10) + for (int Y = startPosY + 50; Y >= height; Y -= 10) + { + ShapeData circle = new ShapeData(); + WorldUtils.Gen(new Point(X, Y), new Shapes.Circle(30), Actions.Chain(new GenAction[] { - ShapeData circle = new ShapeData(); - WorldUtils.Gen(new Point(X, Y), new Shapes.Circle(30), Actions.Chain(new GenAction[] - { //new Modifiers.RadialDither(1, 30).Output(circle), new Modifiers.Blotches().Output(circle), - })); - WorldUtils.Gen(new Point(X, Y), new ModShapes.All(circle), new Actions.SetTile((ushort)ModContent.TileType())); - } + })); + WorldUtils.Gen(new Point(X, Y), new ModShapes.All(circle), new Actions.SetTile((ushort)ModContent.TileType())); } }); @@ -78,99 +113,84 @@ namespace CalamityMod.World // Makes the bottom borders of the Timeless Shores curved downwards. // const int totalCuveDepth = 40; - FastParallel.For(startPosX - biomeSize - 20, startPosX - biomeSize + 200, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize - 20, startPosX - biomeSize + 200, 10, (x) => { - for (int x = start; x <= end; x += 10) - { - int curveDepth = (int)MathHelper.Lerp( + int curveDepth = (int)MathHelper.Lerp( totalCuveDepth, 0f, MathF.Sqrt(Utils.GetLerpValue(startPosX - biomeSize - 17, startPosX - biomeSize + 200, x, true))); - for (int y = startPosY + 50; y <= startPosY + 50 + curveDepth; y += 5) + for (int y = startPosY + 50; y <= startPosY + 50 + curveDepth; y += 5) + { + ShapeData circle = new(); + WorldUtils.Gen(new Point(x, y), new Shapes.Circle(30), Actions.Chain(new GenAction[] { - ShapeData circle = new(); - WorldUtils.Gen(new Point(x, y), new Shapes.Circle(30), Actions.Chain(new GenAction[] - { //new Modifiers.RadialDither(1, 30).Output(circle), new Modifiers.Blotches().Output(circle), - })); - WorldUtils.Gen(new Point(x, y), new ModShapes.All(circle), new Actions.SetTile((ushort)ModContent.TileType())); - } + })); + WorldUtils.Gen(new Point(x, y), new ModShapes.All(circle), new Actions.SetTile((ushort)ModContent.TileType())); } }); - FastParallel.For(startPosX + biomeSize - 200, startPosX + biomeSize + 20, (start, end, _) => + ForLoop.Invoke(startPosX + biomeSize - 200, startPosX + biomeSize + 20, 5, (x) => { - for (int x = start; x <= end; x += 5) - { - int curveDepth = (int)MathHelper.Lerp( + int curveDepth = (int)MathHelper.Lerp( totalCuveDepth, 0f, MathF.Sqrt(Utils.GetLerpValue(startPosX + biomeSize + 20, startPosX + biomeSize - 200, x, true))); - for (int y = startPosY + 50; y <= startPosY + 50 + curveDepth; y += 5) + for (int y = startPosY + 50; y <= startPosY + 50 + curveDepth; y += 5) + { + ShapeData circle = new(); + WorldUtils.Gen(new Point(x, y), new Shapes.Circle(30), Actions.Chain(new GenAction[] { - ShapeData circle = new(); - WorldUtils.Gen(new Point(x, y), new Shapes.Circle(30), Actions.Chain(new GenAction[] - { //new Modifiers.RadialDither(1, 30).Output(circle), new Modifiers.Blotches().Output(circle), - })); - WorldUtils.Gen(new Point(x, y), new ModShapes.All(circle), new Actions.SetTile((ushort)ModContent.TileType())); - } + })); + WorldUtils.Gen(new Point(x, y), new ModShapes.All(circle), new Actions.SetTile((ushort)ModContent.TileType())); } }); //clear a smaller square out of the center where the biomes stuff will be - FastParallel.For(startPosX - biomeSize + 35, startPosX + biomeSize - 35, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize + 35, startPosX + biomeSize - 35, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = startPosY - 65; Y <= startPosY + 50; Y++) { - for (int Y = startPosY - 65; Y <= startPosY + 50; Y++) - { - ShapeData circle = new ShapeData(); - GenAction blotchMod = new Modifiers.Blotches(2, 0.4); + ShapeData circle = new ShapeData(); + GenAction blotchMod = new Modifiers.Blotches(2, 0.4); - WorldUtils.Gen(new Point(X, Y), new Shapes.Circle(WorldGen.genRand.Next(2, 5)), Actions.Chain(new GenAction[] - { + WorldUtils.Gen(new Point(X, Y), new Shapes.Circle(WorldGen.genRand.Next(2, 5)), Actions.Chain(new GenAction[] + { blotchMod.Output(circle) - })); - WorldUtils.Gen(new Point(X, Y), new ModShapes.All(circle), Actions.Chain(new GenAction[] - { + })); + WorldUtils.Gen(new Point(X, Y), new ModShapes.All(circle), Actions.Chain(new GenAction[] + { new Actions.Clear() - })); - } + })); } }); // // Places slopes at the sides of the shores to actually make shores. // - FastParallel.For(startPosX - biomeSize + 20, startPosX - biomeSize + 200, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize + 20, startPosX - biomeSize + 200, 20, (moundX) => { - for (int moundX = start; moundX <= end; moundX += 20) - { - ShapeData mound = new(); - GenAction blotchMod = new Modifiers.Blotches().Output(mound); - int moundY = startPosY + 60; - int moundHeight = (int)MathHelper.Lerp(60f, 5f, MathF.Sqrt(Utils.GetLerpValue(startPosX - biomeSize + 27, startPosX - biomeSize + 200, moundX))); + ShapeData mound = new(); + GenAction blotchMod = new Modifiers.Blotches().Output(mound); + int moundY = startPosY + 60; + int moundHeight = (int)MathHelper.Lerp(60f, 5f, MathF.Sqrt(Utils.GetLerpValue(startPosX - biomeSize + 27, startPosX - biomeSize + 200, moundX))); - WorldUtils.Gen(new Point(moundX, moundY), new Shapes.Mound(30, moundHeight), blotchMod); - WorldUtils.Gen(new Point(moundX, moundY), new ModShapes.All(mound), new Actions.SetTile((ushort)ModContent.TileType())); - } + WorldUtils.Gen(new Point(moundX, moundY), new Shapes.Mound(30, moundHeight), blotchMod); + WorldUtils.Gen(new Point(moundX, moundY), new ModShapes.All(mound), new Actions.SetTile((ushort)ModContent.TileType())); }); - FastParallel.For(startPosX + biomeSize - 200, startPosX + biomeSize - 20, (start, end, _) => + ForLoop.Invoke(startPosX + biomeSize - 200, startPosX + biomeSize - 20, 20, (moundX) => { - for (int moundX = start; moundX <= end; moundX += 20) - { - ShapeData mound = new(); - GenAction blotchMod = new Modifiers.Blotches().Output(mound); - int moundY = startPosY + 60; - int moundHeight = (int)MathHelper.Lerp(60f, 5f, MathF.Sqrt(Utils.GetLerpValue(startPosX + biomeSize - 27, startPosX + biomeSize - 200, moundX))); + ShapeData mound = new(); + GenAction blotchMod = new Modifiers.Blotches().Output(mound); + int moundY = startPosY + 60; + int moundHeight = (int)MathHelper.Lerp(60f, 5f, MathF.Sqrt(Utils.GetLerpValue(startPosX + biomeSize - 27, startPosX + biomeSize - 200, moundX))); - WorldUtils.Gen(new Point(moundX, moundY), new Shapes.Mound(30, moundHeight), blotchMod); - WorldUtils.Gen(new Point(moundX, moundY), new ModShapes.All(mound), new Actions.SetTile((ushort)ModContent.TileType())); - } + WorldUtils.Gen(new Point(moundX, moundY), new Shapes.Mound(30, moundHeight), blotchMod); + WorldUtils.Gen(new Point(moundX, moundY), new ModShapes.All(mound), new Actions.SetTile((ushort)ModContent.TileType())); }); // @@ -179,31 +199,25 @@ namespace CalamityMod.World const int platformSize = 130; const int platformHeight = 35; // Remember that because of Terraria's coordinate system, making it lower actually makes it higher. const int platformDepth = 35; // How deep it goes. Like above, the higher it is, the lower it goes. - FastParallel.For(startPosX - platformSize / 2, startPosX + platformSize / 2, (start, end, _) => + ForLoop.Invoke(startPosX - platformSize / 2, startPosX + platformSize / 2, 5, (platformX) => { - for (int platformX = start; platformX <= end; platformX += 5) - { - // This makes the "stem" of the platform be thinner towards the base and then expand on the top. - int thickness = (int)(MathF.Pow(CalamityUtils.Convert01To010(Utils.GetLerpValue(startPosX - platformSize / 2, startPosX + platformSize / 2, platformX)), 3f) * platformDepth) + platformHeight; + // This makes the "stem" of the platform be thinner towards the base and then expand on the top. + int thickness = (int)(MathF.Pow(CalamityUtils.Convert01To010(Utils.GetLerpValue(startPosX - platformSize / 2, startPosX + platformSize / 2, platformX)), 3f) * platformDepth) + platformHeight; - for (int platformY = startPosY + platformHeight; platformY <= startPosY + thickness; platformY++) + for (int platformY = startPosY + platformHeight; platformY <= startPosY + thickness; platformY++) + { + WorldUtils.Gen(new Point(platformX, platformY), new Shapes.Circle(5), Actions.Chain(new GenAction[] { - WorldUtils.Gen(new Point(platformX, platformY), new Shapes.Circle(5), Actions.Chain(new GenAction[] - { new Actions.Clear(), // Clears all tiles and walls. new Actions.PlaceTile((ushort)ModContent.TileType()) // Places tiles. - })); - } + })); } }); - FastParallel.For(startPosX - platformSize / 2, startPosX + platformSize / 2, (start, end, _) => + ForLoop.Invoke(startPosX - platformSize / 2, startPosX + platformSize / 2, 1, (x) => { - for (int x = start; x <= end; x++) - { - float interpolator = CalamityUtils.Convert01To010(Utils.GetLerpValue(startPosX - platformSize / 2, startPosX + platformSize / 2, x, true)); - int elevation = (int)MathHelper.Lerp(4f, 1f, interpolator); - WorldUtils.Gen(new Point(x, startPosY + platformHeight - 7), new Shapes.Circle(elevation), Actions.Chain(new GenAction[] { new Actions.Clear(), })); - } + float interpolator = CalamityUtils.Convert01To010(Utils.GetLerpValue(startPosX - platformSize / 2, startPosX + platformSize / 2, x, true)); + int elevation = (int)MathHelper.Lerp(4f, 1f, interpolator); + WorldUtils.Gen(new Point(x, startPosY + platformHeight - 7), new Shapes.Circle(elevation), Actions.Chain(new GenAction[] { new Actions.Clear(), })); }); // @@ -213,92 +227,77 @@ namespace CalamityMod.World const int shortestDistanceFromCenter = 35; const int holeStart = 50; const int holeDepth = 35; - FastParallel.For(startPosX - furthestDistanceFromCenter, startPosX - shortestDistanceFromCenter, (start, end, _) => + ForLoop.Invoke(startPosX - furthestDistanceFromCenter, startPosX - shortestDistanceFromCenter, 1, (holeX) => { - for (int holeX = start; holeX <= end; holeX++) + for (int holeY = startPosY + holeStart; holeY <= startPosY + holeStart + holeDepth; holeY += 3) { - for (int holeY = startPosY + holeStart; holeY <= startPosY + holeStart + holeDepth; holeY += 3) + ShapeData circle = new(); + + // As the hole gets deeper, we want the holes to be bigger and more blurry, so it's not so monotonous. + int sizeIncrement = (int)Utils.Remap(holeY, startPosY + holeStart, startPosY + holeStart + holeDepth, 1, 20); + + // may or may not be useful later + //GenAction dither = new Modifiers.RadialDither(2 * sizeIncrement, 5 * sizeIncrement); + + WorldUtils.Gen(new Point(holeX, holeY), new Shapes.Circle(sizeIncrement), Actions.Chain(new GenAction[] { - ShapeData circle = new(); - - // As the hole gets deeper, we want the holes to be bigger and more blurry, so it's not so monotonous. - int sizeIncrement = (int)Utils.Remap(holeY, startPosY + holeStart, startPosY + holeStart + holeDepth, 1, 20); - - // may or may not be useful later - //GenAction dither = new Modifiers.RadialDither(2 * sizeIncrement, 5 * sizeIncrement); - - WorldUtils.Gen(new Point(holeX, holeY), new Shapes.Circle(sizeIncrement), Actions.Chain(new GenAction[] - { new Actions.ClearTile(), // The shape removes tiles. new Actions.SetLiquid() // The shape adds liquid (Default to max water). - })); - } + })); } }); - FastParallel.For(startPosX + shortestDistanceFromCenter, startPosX + furthestDistanceFromCenter, (start, end, _) => + ForLoop.Invoke(startPosX + shortestDistanceFromCenter, startPosX + furthestDistanceFromCenter, 1, (holeX) => { - for (int holeX = start; holeX <= end; holeX++) + for (int holeY = startPosY + holeStart; holeY <= startPosY + holeStart + holeDepth; holeY += 3) { - for (int holeY = startPosY + holeStart; holeY <= startPosY + holeStart + holeDepth; holeY += 3) + ShapeData circle = new(); + + // As the hole gets deeper, we want the holes to be bigger and more blurry, so it's not so monotonous. + int sizeIncrement = (int)Utils.Remap(holeY, startPosY + holeStart, startPosY + holeStart + holeDepth, 1, 20); + + WorldUtils.Gen(new Point(holeX, holeY), new Shapes.Circle(sizeIncrement), Actions.Chain(new GenAction[] { - ShapeData circle = new(); - - // As the hole gets deeper, we want the holes to be bigger and more blurry, so it's not so monotonous. - int sizeIncrement = (int)Utils.Remap(holeY, startPosY + holeStart, startPosY + holeStart + holeDepth, 1, 20); - - WorldUtils.Gen(new Point(holeX, holeY), new Shapes.Circle(sizeIncrement), Actions.Chain(new GenAction[] - { new Actions.ClearTile(), // The shape removes tiles. new Actions.SetLiquid() // The shape adds liquid (Default to max water). - })); - } + })); } }); //place water below the clear barrier for the islands so that theres water inbetween them - FastParallel.For(startPosX - biomeSize + 35, startPosX + biomeSize - 35, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize + 35, startPosX + biomeSize - 35, 1, (WaterX) => { - for (int WaterX = start; WaterX <= end; WaterX++) + for (int WaterY = startPosY + 37; WaterY <= startPosY + 60; WaterY++) { - for (int WaterY = startPosY + 37; WaterY <= startPosY + 60; WaterY++) - { - Main.tile[WaterX, WaterY].Get().LiquidType = LiquidID.Water; - Main.tile[WaterX, WaterY].LiquidAmount = byte.MaxValue; - } + Main.tile[WaterX, WaterY].Get().LiquidType = LiquidID.Water; + Main.tile[WaterX, WaterY].LiquidAmount = byte.MaxValue; } }); //slope tiles - FastParallel.For(startPosX - biomeSize, startPosX + biomeSize, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize, startPosX + biomeSize, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = startPosY - 50; Y <= startPosY + 50; Y++) { - for (int Y = startPosY - 50; Y <= startPosY + 50; Y++) - { - Tile.SmoothSlope(X, Y); - } + Tile.SmoothSlope(X, Y); } }); //place layer of sand on valid runestone blocks - FastParallel.For(startPosX - biomeSize, startPosX + biomeSize, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize, startPosX + biomeSize, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = startPosY - 50; Y <= startPosY + 50; Y++) { - for (int Y = startPosY - 50; Y <= startPosY + 50; Y++) + bool canPlaceSand = false; + + if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y - 2].HasTile && + !Main.tile[X, Y - 3].HasTile && !Main.tile[X, Y - 4].HasTile && !Main.tile[X, Y - 5].HasTile) { - bool canPlaceSand = false; + canPlaceSand = true; + } - if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y - 2].HasTile && - !Main.tile[X, Y - 3].HasTile && !Main.tile[X, Y - 4].HasTile && !Main.tile[X, Y - 5].HasTile) - { - canPlaceSand = true; - } - - if (canPlaceSand) - { - PlaceSand(X, Y, 5, ModContent.TileType()); - } + if (canPlaceSand) + { + PlaceSand(X, Y, 5, ModContent.TileType()); } } }); @@ -306,32 +305,29 @@ namespace CalamityMod.World // // Generates pillars made out of walls at random points in the Timeless Shores. // - FastParallel.For(startPosX - biomeSize, startPosX + biomeSize, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize, startPosX + biomeSize, 100, (wallPillarX) => { - for (int wallPillarX = start; wallPillarX <= end; wallPillarX += 1000) + int randomDisplacementX = WorldGen.genRand.Next(-10, 30); + + for (int wallPillarY = startPosY - 75; wallPillarY <= startPosY + 70; wallPillarY += 10) { - int randomDisplacementX = WorldGen.genRand.Next(-10, 30); + // Along the height of the pillar, it becomes shorter the more closer to the center we get. + int pillarWidth = (int)(CalamityUtils.Convert01To010(Utils.GetLerpValue(startPosY - 75, startPosY + 50, wallPillarY)) * 25); - for (int wallPillarY = startPosY - 75; wallPillarY <= startPosY + 70; wallPillarY += 10) + ShapeData rectangle = new ShapeData(); + GenAction blotchFilter = new Modifiers.Blotches(2, 0.4); + GenAction ditherFilter = new Modifiers.Dither(Math.Min(Utils.GetLerpValue(startPosY + 40, startPosY + 70, wallPillarY) + 0.25, 1)); + + WorldUtils.Gen(new Point(randomDisplacementX + wallPillarX + pillarWidth / 2, wallPillarY), new Shapes.Rectangle(25 - pillarWidth + 3, 12), Actions.Chain(new GenAction[] { - // Along the height of the pillar, it becomes shorter the more closer to the center we get. - int pillarWidth = (int)(CalamityUtils.Convert01To010(Utils.GetLerpValue(startPosY - 75, startPosY + 50, wallPillarY)) * 25); - - ShapeData rectangle = new ShapeData(); - GenAction blotchFilter = new Modifiers.Blotches(2, 0.4); - GenAction ditherFilter = new Modifiers.Dither(Math.Min(Utils.GetLerpValue(startPosY + 40, startPosY + 70, wallPillarY) + 0.25, 1)); - - WorldUtils.Gen(new Point(randomDisplacementX + wallPillarX + pillarWidth / 2, wallPillarY), new Shapes.Rectangle(25 - pillarWidth + 3, 12), Actions.Chain(new GenAction[] - { ditherFilter.Output(rectangle), // Applies a dithering filter to the rectangle. blotchFilter.Output(rectangle), // Applies a blotch filter to the rectangle. - })); + })); - WorldUtils.Gen(new Point(randomDisplacementX + wallPillarX + pillarWidth / 2, wallPillarY), new ModShapes.All(rectangle), Actions.Chain(new GenAction[] - { + WorldUtils.Gen(new Point(randomDisplacementX + wallPillarX + pillarWidth / 2, wallPillarY), new ModShapes.All(rectangle), Actions.Chain(new GenAction[] + { new Actions.PlaceWall((ushort)ModContent.WallType()) // The shape places walls. - })); - } + })); } }); @@ -339,56 +335,53 @@ namespace CalamityMod.World // Makes the transition area to the Timeless Shores. // Replaces tiles, walls, and places some water spots. // - FastParallel.For(startPosX - biomeSize - 25, startPosX + biomeSize + 25, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize - 25, startPosX + biomeSize + 25, 20, (x) => { - for (int x = start; x <= end; x += 20) + for (int y = startPosY - 70; y >= startPosY - 200; y -= 15) { - for (int y = startPosY - 70; y >= startPosY - 200; y -= 15) - { - float interpolator = Utils.GetLerpValue(startPosY - 90, startPosY - 150, y, true); - float ditherStrength = MathHelper.Lerp(0f, 0.95f, interpolator); + float interpolator = Utils.GetLerpValue(startPosY - 90, startPosY - 150, y, true); + float ditherStrength = MathHelper.Lerp(0f, 0.95f, interpolator); - WorldUtils.Gen(new Point(x, y), new Shapes.Circle(15), Actions.Chain(new GenAction[] - { + WorldUtils.Gen(new Point(x, y), new Shapes.Circle(15), Actions.Chain(new GenAction[] + { new Modifiers.OnlyTiles(TileID.Sand, TileID.HardenedSand), new Modifiers.Dither(ditherStrength + 0.2f), new Actions.ClearTile(), new Actions.PlaceTile((ushort)ModContent.TileType()), - })); - // changing these makes the walls dither higher up than tiles, to prevent the biome from changing earlier than expected. still looks nice imo :) - interpolator = Utils.GetLerpValue(startPosY - 90, startPosY - 200, y, true); - ditherStrength = MathHelper.Lerp(0f, 0.95f, interpolator); + })); + // changing these makes the walls dither higher up than tiles, to prevent the biome from changing earlier than expected. still looks nice imo :) + interpolator = Utils.GetLerpValue(startPosY - 90, startPosY - 200, y, true); + ditherStrength = MathHelper.Lerp(0f, 0.95f, interpolator); - WorldUtils.Gen(new Point(x, y), new Shapes.Circle(15), Actions.Chain(new GenAction[] - { + WorldUtils.Gen(new Point(x, y), new Shapes.Circle(15), Actions.Chain(new GenAction[] + { new Modifiers.OnlyWalls(WallID.Sandstone, WallID.HardenedSand), new Modifiers.Dither(ditherStrength), new Actions.ClearWall(), new Actions.PlaceWall((ushort)ModContent.WallType()), - })); + })); - // i forgot to change this one. :peepotired: - interpolator = Utils.GetLerpValue(startPosY - 90, startPosY - 150, y, true); - ditherStrength = MathHelper.Lerp(0f, 0.95f, interpolator); - WorldUtils.Gen(new Point(x, y), new Shapes.Circle(15), Actions.Chain(new GenAction[] - { + // i forgot to change this one. :peepotired: + interpolator = Utils.GetLerpValue(startPosY - 90, startPosY - 150, y, true); + ditherStrength = MathHelper.Lerp(0f, 0.95f, interpolator); + WorldUtils.Gen(new Point(x, y), new Shapes.Circle(15), Actions.Chain(new GenAction[] + { new Modifiers.OnlyTiles(TileID.Sandstone), new Modifiers.Dither(ditherStrength), new Actions.ClearTile(), new Actions.PlaceTile((ushort)ModContent.TileType()), - })); + })); - if (Main.tile[x, y].Get().LiquidType == LiquidID.Lava) - WorldUtils.Gen(new Point(x, y), new Shapes.Rectangle(5, 5), new Actions.SetLiquid(LiquidID.Lava, 0)); + if (Main.tile[x, y].Get().LiquidType == LiquidID.Lava) + WorldUtils.Gen(new Point(x, y), new Shapes.Rectangle(5, 5), new Actions.SetLiquid(LiquidID.Lava, 0)); - if (WorldGen.genRand.NextBool(5) && y < startPosY - 100) + if (WorldGen.genRand.NextBool(5) && y < startPosY - 100) + { + WorldUtils.Gen(new Point(x, y), new Shapes.Circle(WorldGen.genRand.Next(5, 7)), Actions.Chain(new GenAction[] { - WorldUtils.Gen(new Point(x, y), new Shapes.Circle(WorldGen.genRand.Next(5, 7)), Actions.Chain(new GenAction[] - { new Modifiers.IsNotSolid().Output(new()), new Actions.SetLiquid(), - })); - } + })); } } }); @@ -419,56 +412,53 @@ namespace CalamityMod.World Vector2 bottomFoci = center + fociOffset; //first, place a basalt barrier on the left and right of the biome - FastParallel.For(origin.X - biomeSize - 3, origin.X + biomeSize + 3, (start, end, _) => + ForLoop.Invoke(origin.X - biomeSize - 3, origin.X + biomeSize + 3, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) { - for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) + if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, Y < origin.Y)) { - if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, Y < origin.Y)) + float percent = dist / constant; + float blurPercent = 0.99f; + + if (percent > blurPercent) { - float percent = dist / constant; - float blurPercent = 0.99f; - - if (percent > blurPercent) + if (Y > origin.Y - 60) { - if (Y > origin.Y - 60) + if (LeftSideBarrier) { - if (LeftSideBarrier) + if (X <= origin.X && Main.tile[X - 40, Y - 25].TileType != ModContent.TileType()) { - if (X <= origin.X && Main.tile[X - 40, Y - 25].TileType != ModContent.TileType()) - { - ShapeData circle = new ShapeData(); - GenAction blotchMod = new Modifiers.Blotches(2, 0.4); + ShapeData circle = new ShapeData(); + GenAction blotchMod = new Modifiers.Blotches(2, 0.4); - WorldUtils.Gen(new Point(X - 40, Y - 25), new Shapes.Circle(60), Actions.Chain(new GenAction[] - { + WorldUtils.Gen(new Point(X - 40, Y - 25), new Shapes.Circle(60), Actions.Chain(new GenAction[] + { blotchMod.Output(circle) - })); - WorldUtils.Gen(new Point(X - 40, Y - 25), new ModShapes.All(circle), Actions.Chain(new GenAction[] - { + })); + WorldUtils.Gen(new Point(X - 40, Y - 25), new ModShapes.All(circle), Actions.Chain(new GenAction[] + { new Actions.Clear(), new Actions.PlaceTile((ushort)ModContent.TileType()) - })); - } + })); } - else + } + else + { + if (X >= origin.X && Main.tile[X + 40, Y - 25].TileType != ModContent.TileType()) { - if (X >= origin.X && Main.tile[X + 40, Y - 25].TileType != ModContent.TileType()) - { - ShapeData circle = new ShapeData(); - GenAction blotchMod = new Modifiers.Blotches(2, 0.4); + ShapeData circle = new ShapeData(); + GenAction blotchMod = new Modifiers.Blotches(2, 0.4); - WorldUtils.Gen(new Point(X + 40, Y - 25), new Shapes.Circle(60), Actions.Chain(new GenAction[] - { + WorldUtils.Gen(new Point(X + 40, Y - 25), new Shapes.Circle(60), Actions.Chain(new GenAction[] + { blotchMod.Output(circle) - })); - WorldUtils.Gen(new Point(X + 40, Y - 25), new ModShapes.All(circle), Actions.Chain(new GenAction[] - { + })); + WorldUtils.Gen(new Point(X + 40, Y - 25), new ModShapes.All(circle), Actions.Chain(new GenAction[] + { new Actions.Clear(), new Actions.PlaceTile((ushort)ModContent.TileType()) - })); - } + })); } } } @@ -535,97 +525,88 @@ namespace CalamityMod.World } //cleanup - FastParallel.For(origin.X - biomeSize - 3, origin.X + biomeSize + 3, (start, end, _) => + ForLoop.Invoke(origin.X - biomeSize - 3, origin.X + biomeSize + 3, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) { - for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) + if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, Y < origin.Y)) { - if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, Y < origin.Y)) + //clean tiles that are sticking out (aka tiles only attached to one tile on one side) + bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; + bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + + if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) { - //clean tiles that are sticking out (aka tiles only attached to one tile on one side) - bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; - bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + WorldGen.KillTile(X, Y); + } - if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) - { - WorldGen.KillTile(X, Y); - } - - //kill random single floating tiles - if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) - { - WorldGen.KillTile(X, Y); - } + //kill random single floating tiles + if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) + { + WorldGen.KillTile(X, Y); } } } }); //place layer of sand blocks on valid surfaces - FastParallel.For(origin.X - biomeSize - 3, origin.X + biomeSize + 3, (start, end, _) => + ForLoop.Invoke(origin.X - biomeSize - 3, origin.X + biomeSize + 3, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) { - for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) + if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, Y < origin.Y)) { - if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, Y < origin.Y)) + bool canPlaceSand = false; + + //place sand clumps on top of exposed shellstone + if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y - 2].HasTile && + !Main.tile[X, Y - 3].HasTile && !Main.tile[X, Y - 4].HasTile && !Main.tile[X, Y - 5].HasTile) { - bool canPlaceSand = false; + canPlaceSand = true; + } - //place sand clumps on top of exposed shellstone - if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y - 2].HasTile && - !Main.tile[X, Y - 3].HasTile && !Main.tile[X, Y - 4].HasTile && !Main.tile[X, Y - 5].HasTile) - { - canPlaceSand = true; - } - - if (canPlaceSand) - { - PlaceSand(X, Y, 5, ModContent.TileType()); - } + if (canPlaceSand) + { + PlaceSand(X, Y, 5, ModContent.TileType()); } } } }); //cleanup again - FastParallel.For(origin.X - biomeSize - 3, origin.X + biomeSize + 3, (start, end, _) => + ForLoop.Invoke(origin.X - biomeSize - 3, origin.X + biomeSize + 3, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) { - for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) + if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, Y < origin.Y)) { - if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, Y < origin.Y)) + //clean tiles that are sticking out (aka tiles only attached to one tile on one side) + bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; + bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + + if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) { - //clean tiles that are sticking out (aka tiles only attached to one tile on one side) - bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; - bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; - - if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) - { - WorldGen.KillTile(X, Y); - } - - //kill random single floating tiles - if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) - { - WorldGen.KillTile(X, Y); - } - - //if any sand is floating, put tiles below it - if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y + 1].HasTile) - { - WorldGen.PlaceTile(X, Y + 1, (ushort)ModContent.TileType()); - Main.tile[X, Y].TileType = (ushort)ModContent.TileType(); - } - - Tile.SmoothSlope(X, Y); + WorldGen.KillTile(X, Y); } + + //kill random single floating tiles + if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) + { + WorldGen.KillTile(X, Y); + } + + //if any sand is floating, put tiles below it + if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y + 1].HasTile) + { + WorldGen.PlaceTile(X, Y + 1, (ushort)ModContent.TileType()); + Main.tile[X, Y].TileType = (ushort)ModContent.TileType(); + } + + Tile.SmoothSlope(X, Y); } } }); @@ -726,97 +707,88 @@ namespace CalamityMod.World } //cleanup - FastParallel.For(origin.X - biomeSize - 3, origin.X + biomeSize + 3, (start, end, _) => + ForLoop.Invoke(origin.X - biomeSize - 3, origin.X + biomeSize + 3, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) { - for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) + if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, false, Y > origin.Y)) { - if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, false, Y > origin.Y)) + //clean tiles that are sticking out (aka tiles only attached to one tile on one side) + bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; + bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + + if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) { - //clean tiles that are sticking out (aka tiles only attached to one tile on one side) - bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; - bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + WorldGen.KillTile(X, Y); + } - if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) - { - WorldGen.KillTile(X, Y); - } - - //kill random single floating tiles - if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) - { - WorldGen.KillTile(X, Y); - } + //kill random single floating tiles + if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) + { + WorldGen.KillTile(X, Y); } } } }); //place extra tiles - FastParallel.For(origin.X - biomeSize - 3, origin.X + biomeSize + 3, (start, end, _) => + ForLoop.Invoke(origin.X - biomeSize - 3, origin.X + biomeSize + 3, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 20; Y <= origin.Y + verticalRadius + 20; Y++) { - for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 20; Y <= origin.Y + verticalRadius + 20; Y++) + if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, false, Y > origin.Y)) { - if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, false, Y > origin.Y)) + bool canPlaceSand = false; + + //place sand clumps on top of exposed limestone + if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y - 2].HasTile && + !Main.tile[X, Y - 3].HasTile && !Main.tile[X, Y - 4].HasTile && !Main.tile[X, Y - 5].HasTile) { - bool canPlaceSand = false; + canPlaceSand = true; + } - //place sand clumps on top of exposed limestone - if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y - 2].HasTile && - !Main.tile[X, Y - 3].HasTile && !Main.tile[X, Y - 4].HasTile && !Main.tile[X, Y - 5].HasTile) - { - canPlaceSand = true; - } - - if (canPlaceSand) - { - PlaceSand(X, Y, 5, ModContent.TileType()); - } + if (canPlaceSand) + { + PlaceSand(X, Y, 5, ModContent.TileType()); } } } }); //cleanup again - FastParallel.For(origin.X - biomeSize - 3, origin.X + biomeSize + 3, (start, end, _) => + ForLoop.Invoke(origin.X - biomeSize - 3, origin.X + biomeSize + 3, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) { - for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) + if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, false, Y > origin.Y)) { - if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, false, Y > origin.Y)) + //clean tiles that are sticking out (aka tiles only attached to one tile on one side) + bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; + bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + + if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) { - //clean tiles that are sticking out (aka tiles only attached to one tile on one side) - bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; - bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; - - if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) - { - WorldGen.KillTile(X, Y); - } - - //kill random single floating tiles - if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) - { - WorldGen.KillTile(X, Y); - } - - //if any sand is floating, put tiles below it - if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y + 1].HasTile) - { - WorldGen.PlaceTile(X, Y + 1, (ushort)ModContent.TileType()); - Main.tile[X, Y].TileType = (ushort)ModContent.TileType(); - } - - Tile.SmoothSlope(X, Y); + WorldGen.KillTile(X, Y); } + + //kill random single floating tiles + if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) + { + WorldGen.KillTile(X, Y); + } + + //if any sand is floating, put tiles below it + if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y + 1].HasTile) + { + WorldGen.PlaceTile(X, Y + 1, (ushort)ModContent.TileType()); + Main.tile[X, Y].TileType = (ushort)ModContent.TileType(); + } + + Tile.SmoothSlope(X, Y); } } }); @@ -846,34 +818,31 @@ namespace CalamityMod.World Vector2 bottomFoci = center + fociOffset; //place another barrier so the gleaming burrows doesnt just burst into the gully - FastParallel.For(origin.X - biomeSize - 3, origin.X + biomeSize + 3, (start, end, _) => + ForLoop.Invoke(origin.X - biomeSize - 3, origin.X + biomeSize + 3, 10, (X) => { - for (int X = start; X <= end; X += 10) + for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y += 2) { - for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y += 2) + if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, true)) { - if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, true)) + float percent = dist / constant; + float blurPercent = 0.98f; + + if (percent > blurPercent) { - float percent = dist / constant; - float blurPercent = 0.98f; - - if (percent > blurPercent) + if (Y > origin.Y - 10) { - if (Y > origin.Y - 10) - { - ShapeData circle = new ShapeData(); - GenAction blotchMod = new Modifiers.Blotches(10, 0.4); + ShapeData circle = new ShapeData(); + GenAction blotchMod = new Modifiers.Blotches(10, 0.4); - WorldUtils.Gen(new Point(X, Y - 10), new Shapes.Circle(20), Actions.Chain(new GenAction[] - { + WorldUtils.Gen(new Point(X, Y - 10), new Shapes.Circle(20), Actions.Chain(new GenAction[] + { blotchMod.Output(circle) - })); - WorldUtils.Gen(new Point(X, Y - 10), new ModShapes.All(circle), Actions.Chain(new GenAction[] - { + })); + WorldUtils.Gen(new Point(X, Y - 10), new ModShapes.All(circle), Actions.Chain(new GenAction[] + { new Actions.Clear(), new Actions.PlaceTile((ushort)ModContent.TileType()) - })); - } + })); } } } @@ -957,56 +926,50 @@ namespace CalamityMod.World } //cleanup the perlin caves - FastParallel.For(origin.X - biomeSize - 3, origin.X + biomeSize + 3, (start, end, _) => + ForLoop.Invoke(origin.X - biomeSize - 3, origin.X + biomeSize + 3, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) { - for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) + if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, true)) { - if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, true)) + //clean tiles that are sticking out (aka tiles only attached to one tile on one side) + bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; + bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + + if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) { - //clean tiles that are sticking out (aka tiles only attached to one tile on one side) - bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; - bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + WorldGen.KillTile(X, Y); + } - if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) - { - WorldGen.KillTile(X, Y); - } - - //kill random single floating tiles - if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) - { - WorldGen.KillTile(X, Y); - } + //kill random single floating tiles + if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) + { + WorldGen.KillTile(X, Y); } } } }); //place extra tiles - FastParallel.For(origin.X - biomeSize - 3, origin.X + biomeSize + 3, (start, end, _) => + ForLoop.Invoke(origin.X - biomeSize - 3, origin.X + biomeSize + 3, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) { - for (int Y = (int)(origin.Y - verticalRadius * 0.4f) - 3; Y <= origin.Y + verticalRadius + 3; Y++) + if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, true)) { - if (CheckInBiomeArea(new Point(X, Y), topFoci, bottomFoci, constant, center, out float dist, true)) + bool canPlaceSand = false; + + //place sand clumps on top of exposed navystone + if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y - 2].HasTile && !Main.tile[X, Y - 3].HasTile) { - bool canPlaceSand = false; + canPlaceSand = true; + } - //place sand clumps on top of exposed navystone - if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y - 2].HasTile && !Main.tile[X, Y - 3].HasTile) - { - canPlaceSand = true; - } - - if (canPlaceSand) - { - PlaceSand(X, Y, 4, ModContent.TileType()); - } + if (canPlaceSand) + { + PlaceSand(X, Y, 4, ModContent.TileType()); } } } @@ -1098,41 +1061,35 @@ namespace CalamityMod.World } //place blocks of basalt all the way down to hell, here it just places one block and wall so it doesnt hurt preformance - FastParallel.For(startPosX - biomeSize - 25, startPosX + biomeSize + 25, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize - 25, startPosX + biomeSize + 25, 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = startPosY - 30; Y <= Main.maxTilesY - 200; Y++) { - for (int Y = startPosY - 30; Y <= Main.maxTilesY - 200; Y++) - { - Main.tile[X, Y].ClearEverything(); - WorldGen.PlaceTile(X, Y, (ushort)ModContent.TileType()); - WorldGen.PlaceWall(X, Y, WallID.LavaUnsafe1); - } + Main.tile[X, Y].ClearEverything(); + WorldGen.PlaceTile(X, Y, (ushort)ModContent.TileType()); + WorldGen.PlaceWall(X, Y, WallID.LavaUnsafe1); } }); //place another wall of circles along the bottom of the biome so it doesnt just end unnaturally - FastParallel.For(startPosX - biomeSize, startPosX + biomeSize, (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize, startPosX + biomeSize, 20, (X) => { - for (int X = start; X <= end; X += 20) + int Y = Main.maxTilesY - 250; + + ShapeData circle = new ShapeData(); + GenAction blotchMod = new Modifiers.Blotches(2, 0.4); + + WorldUtils.Gen(new Point(X, Y), new Shapes.Circle(25), Actions.Chain(new GenAction[] { - int Y = Main.maxTilesY - 250; - - ShapeData circle = new ShapeData(); - GenAction blotchMod = new Modifiers.Blotches(2, 0.4); - - WorldUtils.Gen(new Point(X, Y), new Shapes.Circle(25), Actions.Chain(new GenAction[] - { blotchMod.Output(circle) - })); + })); - WorldUtils.Gen(new Point(X, Y), new ModShapes.All(circle), Actions.Chain(new GenAction[] - { + WorldUtils.Gen(new Point(X, Y), new ModShapes.All(circle), Actions.Chain(new GenAction[] + { new Actions.Clear(), new Actions.PlaceTile((ushort)ModContent.TileType()), new Actions.PlaceWall(WallID.LavaUnsafe1) - })); - } + })); }); //place caverns and lava @@ -1160,58 +1117,52 @@ namespace CalamityMod.World } //place sand blocks - FastParallel.For(startPosX - biomeSize - (Main.maxTilesX / 25), startPosX + biomeSize + (Main.maxTilesX / 25), (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize - (Main.maxTilesX / 25), startPosX + biomeSize + (Main.maxTilesX / 25), 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = startPosY; Y <= Main.maxTilesY - 210; Y++) { - for (int Y = startPosY; Y <= Main.maxTilesY - 210; Y++) + bool canPlaceSand = false; + + //place sand clumps on top of exposed basalt + if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y - 2].HasTile) { - bool canPlaceSand = false; + canPlaceSand = true; + } - //place sand clumps on top of exposed basalt - if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y - 2].HasTile) - { - canPlaceSand = true; - } - - if (canPlaceSand) - { - PlaceSand(X, Y, 3, ModContent.TileType()); - } + if (canPlaceSand) + { + PlaceSand(X, Y, 3, ModContent.TileType()); } } }); //cleanup - FastParallel.For(startPosX - biomeSize - (Main.maxTilesX / 25), startPosX + biomeSize + (Main.maxTilesX / 25), (start, end, _) => + ForLoop.Invoke(startPosX - biomeSize - (Main.maxTilesX / 25), startPosX + biomeSize + (Main.maxTilesX / 25), 1, (X) => { - for (int X = start; X <= end; X++) + for (int Y = startPosY; Y <= Main.maxTilesY - 210; Y++) { - for (int Y = startPosY; Y <= Main.maxTilesY - 210; Y++) + //clean tiles that are sticking out (aka tiles only attached to one tile on one side) + bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; + bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + + if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) { - //clean tiles that are sticking out (aka tiles only attached to one tile on one side) - bool OnlyRight = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile; - bool OnlyLeft = !Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyDown = !Main.tile[X, Y - 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; - bool OnlyUp = !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile; + WorldGen.KillTile(X, Y); + } - if (OnlyRight || OnlyLeft || OnlyDown || OnlyUp) - { - WorldGen.KillTile(X, Y); - } + //kill random single floating tiles + if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) + { + WorldGen.KillTile(X, Y); + } - //kill random single floating tiles - if (!Main.tile[X, Y - 1].HasTile && !Main.tile[X, Y + 1].HasTile && !Main.tile[X - 1, Y].HasTile && !Main.tile[X + 1, Y].HasTile) - { - WorldGen.KillTile(X, Y); - } - - //if any sand is floating, put tiles below it - if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y + 1].HasTile) - { - WorldGen.PlaceTile(X, Y + 1, (ushort)ModContent.TileType()); - Main.tile[X, Y].TileType = (ushort)ModContent.TileType(); - } + //if any sand is floating, put tiles below it + if (Main.tile[X, Y].TileType == ModContent.TileType() && !Main.tile[X, Y + 1].HasTile) + { + WorldGen.PlaceTile(X, Y + 1, (ushort)ModContent.TileType()); + Main.tile[X, Y].TileType = (ushort)ModContent.TileType(); } } }); @@ -1571,26 +1522,23 @@ namespace CalamityMod.World getAttachedPoints(x, y - 1, points); } - FastParallel.For(20, Main.maxTilesX - 20, (start, end, _) => + ForLoop.Invoke(20, Main.maxTilesX - 20, 1, (x) => { - for (int x = start; x < end; x++) + for (int y = 20; y < Main.maxTilesY - 20; y++) { - for (int y = 20; y < Main.maxTilesY - 20; y++) - { - List chunkPoints = new(); - getAttachedPoints(x, y, chunkPoints); + List chunkPoints = new(); + getAttachedPoints(x, y, chunkPoints); - int cutoffLimit = 75; - if (chunkPoints.Count >= 1 && chunkPoints.Count < cutoffLimit) + int cutoffLimit = 75; + if (chunkPoints.Count >= 1 && chunkPoints.Count < cutoffLimit) + { + foreach (Point p in chunkPoints) { - foreach (Point p in chunkPoints) + WorldUtils.Gen(p, new Shapes.Rectangle(1, 1), Actions.Chain(new GenAction[] { - WorldUtils.Gen(p, new Shapes.Rectangle(1, 1), Actions.Chain(new GenAction[] - { new Actions.ClearTile(true), new Actions.SetLiquid() - })); - } + })); } } }