diff --git a/Backgrounds/SunkenSeaBurrowsBG.cs b/Backgrounds/SunkenSeaBurrowsBG.cs index 4c80584980..b8de0ce754 100644 --- a/Backgrounds/SunkenSeaBurrowsBG.cs +++ b/Backgrounds/SunkenSeaBurrowsBG.cs @@ -1,5 +1,6 @@ using CalamityMod.Graphics; using CalamityMod.Systems.Graphic; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; @@ -12,7 +13,7 @@ namespace CalamityMod.Backgrounds { public class SunkenSeaBurrowsBG : ModSystem { - private static ManagedRenderTarget WaterDistortionTarget; + private static RenderTargetLease WaterDistortionTarget; private static bool CurrentlyRendering { get; set; } @@ -26,7 +27,7 @@ namespace CalamityMod.Backgrounds GeneralDrawLayerSystem.OnPrepareDraw += DrawToTarget; On_Main.DrawBackgroundBlackFill += On_Main_DrawBackgroundBlackFill; - Main.QueueMainThreadAction(() => WaterDistortionTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget)); + Main.QueueMainThreadAction(() => WaterDistortionTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice)); } public override void Unload() @@ -139,18 +140,19 @@ namespace CalamityMod.Backgrounds } CurrentlyRendering = true; - WaterDistortionTarget.SwapTo(); - // 13MAY2025: fryzahh: Note that when other Sunken Sea backgrounds are implemented they should use this same system. - // Leaving this here for other programmers, in case I don't get to doing this myself. - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, CalamityUtils.BackgroundMatrix); + using (WaterDistortionTarget.Scope(clearColor: Color.Transparent)) + { + // 13MAY2025: fryzahh: Note that when other Sunken Sea backgrounds are implemented they should use this same system. + // Leaving this here for other programmers, in case I don't get to doing this myself. + Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, CalamityUtils.BackgroundMatrix); - DrawShoresBG(); - DrawBurrowsBG(); + DrawShoresBG(); + DrawBurrowsBG(); - Main.spriteBatch.End(); + Main.spriteBatch.End(); + } - Main.graphics.GraphicsDevice.SetRenderTarget(null); CurrentlyRendering = false; } diff --git a/Buffs/DamageOverTime/MiracleBlight.cs b/Buffs/DamageOverTime/MiracleBlight.cs index bc2f149418..448b4616a7 100644 --- a/Buffs/DamageOverTime/MiracleBlight.cs +++ b/Buffs/DamageOverTime/MiracleBlight.cs @@ -1,8 +1,16 @@ -using CalamityMod.DataStructures; +using System.Collections.Generic; +using CalamityMod.DataStructures; +using CalamityMod.NPCs; +using CalamityMod.NPCs.ExoMechs.Ares; using CalamityMod.Particles; +using CalamityMod.Utilities.Daybreak; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using ReLogic.Content; using Terraria; using Terraria.DataStructures; +using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.ModLoader; @@ -14,6 +22,33 @@ namespace CalamityMod.Buffs.DamageOverTime { EnemyLostRegen = 3000 }; + + public static Asset ShaderTexture => field ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Neurons"); + + public static List ExcludedNPCsForShader => new() + { + // TODO: Remove this list if possible + + // List the reason why the NPC(s) are excluded :) + + // The particle sets break with the visuals and this is the easiest way to fix this that isn't stupidly complex. + ModContent.NPCType(), + ModContent.NPCType(), + ModContent.NPCType(), + ModContent.NPCType(), + ModContent.NPCType(), + + // Breaks with being behind tiles, and causes a funny interaction where his head goes behind his neck. + NPCID.MoonLordCore, + NPCID.MoonLordHand, + NPCID.MoonLordHead + }; + + public override void Load() + { + On_Main.DrawNPC += DrawForNPC; + } + public override void SetStaticDefaults() { Main.debuff[Type] = true; @@ -96,5 +131,44 @@ namespace CalamityMod.Buffs.DamageOverTime GeneralParticleHandler.SpawnParticle(exoEnergy); } } + + private static void DrawForNPC(On_Main.orig_DrawNPC orig, Main self, int iNPCIndex, bool behindTiles) + { + var npc = Main.npc[iNPCIndex]; + + if (!CalamityDrawParameterNPC.DrawingMiracleBlight[npc.whoAmI]) + { + orig(self, iNPCIndex, behindTiles); + return; + } + + if (ExcludedNPCsForShader.Contains(npc.type)) + { + orig(self, iNPCIndex, behindTiles); + return; + } + + using (Main.spriteBatch.Scope()) + { + using var lease = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); + using (lease.Scope(clearColor: Color.Transparent)) + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.Transform); + orig(self, iNPCIndex, behindTiles); + Main.spriteBatch.End(); + } + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise); + + var blightShader = GameShaders.Misc["CalamityMod:MiracleBlight"]; + blightShader.UseImage1(ShaderTexture); + blightShader.UseOpacity(0.7f); + blightShader.Apply(); + + Main.spriteBatch.Draw(lease.Target, Vector2.Zero, Color.White); + + Main.spriteBatch.End(); + } + } } } diff --git a/CalPlayer/CalamityPlayer.cs b/CalPlayer/CalamityPlayer.cs index a7288b9d19..58706ed603 100644 --- a/CalPlayer/CalamityPlayer.cs +++ b/CalPlayer/CalamityPlayer.cs @@ -957,8 +957,6 @@ namespace CalamityMod.CalPlayer public int PurityHealSlowdownFrames = 0; public bool harpyRing = false; public bool angelTreads = false; - /// Counter variable used for automatically re-engaging Vortex armor's stealth with Vortex Booster. - public int vortexBoosterStealthDelay = 0; /// Makes Flesh Knuckles and its upgrades increase the player's max health. public bool fleshKnuckles = false; public bool ironBoots = false; @@ -3361,7 +3359,6 @@ namespace CalamityMod.CalPlayer persecutedEnchantSummonTimer = 0; momentumCapacitorTime = 0; momentumCapacitorBoost = 0f; - vortexBoosterStealthDelay = 0; LungingDown = false; chaliceBleedoutBuffer = 0D; @@ -4413,6 +4410,7 @@ namespace CalamityMod.CalPlayer } #endregion + #region OnExtraJumpStarted public override void OnExtraJumpStarted(ExtraJump jump, ref bool playSound) { if (rainSet && Player.whoAmI == Main.myPlayer) @@ -4420,6 +4418,7 @@ namespace CalamityMod.CalPlayer RainArmorSetChange.SpawnRainArmorJump(Player); } } + #endregion #region PreUpdateMovement public override void PreUpdateMovement() diff --git a/CalPlayer/CalamityPlayerDashEffects.cs b/CalPlayer/CalamityPlayerDashEffects.cs index a28bf6750e..865f7c97e3 100644 --- a/CalPlayer/CalamityPlayerDashEffects.cs +++ b/CalPlayer/CalamityPlayerDashEffects.cs @@ -158,9 +158,6 @@ namespace CalamityMod.CalPlayer if (HasCustomDash) { - // Vortex Booster automatically re-engages Vortex armor's stealth after a delay when dashing - if (Player.wingsLogic == (int)VanillaWingID.WingsVortex && Player.vortexStealthActive) - vortexBoosterStealthDelay = 60; Player.vortexStealthActive = false; // Decide the player's facing direction. diff --git a/CalPlayer/CalamityPlayerLifeRegen.cs b/CalPlayer/CalamityPlayerLifeRegen.cs index c2c772885e..45c25d2761 100644 --- a/CalPlayer/CalamityPlayerLifeRegen.cs +++ b/CalPlayer/CalamityPlayerLifeRegen.cs @@ -579,7 +579,7 @@ namespace CalamityMod.CalPlayer if (silvaSet) Player.lifeRegen += SilvaArmor.SetBonusRegenBoost; - if (phantomicHeartRegen <= 720 && phantomicHeartRegen >= 600) + if (phantomicHeartRegen > 0 && phantomicHeartRegen < 1000) { Player.lifeRegen += PhantomicArtifact.RegenBoost; if (Main.rand.NextBool()) diff --git a/CalPlayer/CalamityPlayerMiscEffects.cs b/CalPlayer/CalamityPlayerMiscEffects.cs index 2ff23e9c0b..669cd5159f 100644 --- a/CalPlayer/CalamityPlayerMiscEffects.cs +++ b/CalPlayer/CalamityPlayerMiscEffects.cs @@ -388,6 +388,13 @@ namespace CalamityMod.CalPlayer Lighting.AddLight(Player.Center, Color.MediumOrchid.ToVector3()); } + // Restore flight time during Vortex stealth with Vortex Booster + if (Player.vortexStealthActive && Player.wingsLogic == (int)VanillaWingID.WingsVortex) + { + if (Player.wingTime > 0 && Player.miscCounter % 3 == 0) + Player.wingTime++; + } + if (Player.HeldItem.type == ModContent.ItemType() && darklightEnergy > 0) { if (darklightEnergy == Lucrecia.MaxEnergy && !darklightEnergyPaused) @@ -2317,12 +2324,6 @@ namespace CalamityMod.CalPlayer hurtSoundTimer--; if (wingProjectileCooldown > 0) wingProjectileCooldown--; - if (vortexBoosterStealthDelay > 0) - { - vortexBoosterStealthDelay--; - if (vortexBoosterStealthDelay == 1 && Player.setVortex) - Player.vortexStealthActive = true; - } if (hallowedRuneCooldown > 0) hallowedRuneCooldown--; if (sulphurBubbleCooldown > 0) diff --git a/CalPlayer/CalamityPlayerOnHit.cs b/CalPlayer/CalamityPlayerOnHit.cs index a23e27a813..ebb43fc131 100644 --- a/CalPlayer/CalamityPlayerOnHit.cs +++ b/CalPlayer/CalamityPlayerOnHit.cs @@ -890,8 +890,6 @@ namespace CalamityMod.CalPlayer { var source = proj.GetSource_FromThis(); - if (npcCheck) - { if (phantomicArtifact) { int restoreBuff = BuffType(); @@ -903,10 +901,10 @@ namespace CalamityMod.CalPlayer empowerBuff, shieldBuff }); - Player.AddBuff(buffType, 60); + Player.AddBuff(buffType, 120); if (buffType == restoreBuff) { - if (phantomicHeartRegen == 1000 && Player.ownedProjectileCounts[ProjectileType()] == 0 && Main.rand.NextBool(20)) + if (phantomicHeartRegen == 1000 && Player.ownedProjectileCounts[ProjectileType()] == 0) { Vector2 target = proj.Center; target.Y += Main.rand.Next(-50, 50); @@ -916,10 +914,10 @@ namespace CalamityMod.CalPlayer } else if (buffType == empowerBuff) { - if (Player.ownedProjectileCounts[ProjectileType()] < 3 && Main.rand.NextBool(10)) + if (Player.ownedProjectileCounts[ProjectileType()] < 3 && Main.rand.NextBool(4)) { int damage = (int)Player.GetTotalDamage().ApplyTo(100); - Projectile.NewProjectile(source, proj.position, proj.velocity, ProjectileType(), damage, 1f, Player.whoAmI); + Projectile.NewProjectile(source, Player.Center, new Vector2(Player.velocity.X,Player.velocity.Y-10).RotatedByRandom(0.3f), ProjectileType(), damage, 1f, Player.whoAmI); } } else @@ -936,7 +934,7 @@ namespace CalamityMod.CalPlayer BuffType(), BuffType() }); - Player.AddBuff(buffType, 60); + Player.AddBuff(buffType, 120); } else if (sGlyph) { @@ -946,9 +944,8 @@ namespace CalamityMod.CalPlayer BuffType(), BuffType() }); - Player.AddBuff(buffType, 60); + Player.AddBuff(buffType, 120); } - } // Fearmonger set gains regen duration when any minion lands any hit if (fearmongerSet) @@ -1003,10 +1000,13 @@ namespace CalamityMod.CalPlayer if (hallowedRuneCooldown <= 0) { hallowedRuneCooldown = 180; - Vector2 spawnPosition = position - new Vector2(0f, 920f).RotatedByRandom(0.3f); + for (var i = 0; i < 3; i++) + { + Vector2 spawnPosition = position - new Vector2(0f, 920f).RotatedByRandom(0.3f); float speed = Main.rand.NextFloat(17f, 23f); int hallowedDamage = (int)Player.GetTotalDamage().ApplyTo(50); - Projectile.NewProjectile(source, spawnPosition, Vector2.Normalize(position - spawnPosition) * speed, ProjectileType(), hallowedDamage, 3f, proj.owner); + Projectile.NewProjectile(source, spawnPosition, Vector2.Normalize(position - spawnPosition) * speed, ProjectileType(), hallowedDamage, 3f, proj.owner); + } } } } diff --git a/CalamityNetcode.cs b/CalamityNetcode.cs index bfffa1013f..33c5e2f016 100644 --- a/CalamityNetcode.cs +++ b/CalamityNetcode.cs @@ -209,6 +209,8 @@ namespace CalamityMod WantToRefundReforges, // Player Draw Effect Parameters - SyncPlayerDrawParameter + SyncPlayerDrawParameter, + + DialogueDisplayStart, } } diff --git a/Dialogues/DialogueLoader.cs b/Dialogues/DialogueLoader.cs new file mode 100644 index 0000000000..60b906a873 --- /dev/null +++ b/Dialogues/DialogueLoader.cs @@ -0,0 +1,302 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using CalamityMod.UI.DialogueDisplay; +using CalamityMod.Utilities; +using MonoMod.Cil; +using Terraria; +using Terraria.Localization; +using Terraria.ModLoader; + +namespace CalamityMod.Dialogues; + +internal record DialogueTextDataEntry( + Mod ProviderMod, + string FilePath, + string DialogueKey, + DialogueTextData Data + ); + +internal partial class DialogueLoader : ModSystem +{ + private const string DialogueFilePrefix = "Dialogue."; + + private static readonly Dictionary _DialogueLookup = []; + private static readonly Dictionary _Watchers = []; + + public override void Load() + { + _DialogueLookup.Clear(); + + var method = typeof(LocalizationLoader).GetMethod(nameof(LocalizationLoader.ExtractLocalizationFiles), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + if (method != null) + { + MonoModHooks.Modify(method, ExtractDialogueFilesPatch); + } + } + + public override void PostSetupContent() + { + foreach (var mod in ModLoader.Mods) + { + if (mod.File == null) + continue; + + var path = mod.SourceFolder; + if (!Directory.Exists(path)) + continue; + + var watcher = new MainThreadedFileSystemWatcher() + { + Path = path, + Filter = "*.json", + FileNameFilter = CalamityDialogueFileRegex(), + NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite, + IncludeSubdirectories = true + }; + watcher.Changed += (arg) => + { + HandleFileUpdate(mod, arg.FullPath); + }; + watcher.Renamed += (arg) => + { + HandleFileUpdate(mod, arg.FullPath); + }; + watcher.EnableRaisingEvents = true; + _Watchers[mod] = watcher; + } + } + + public override void Unload() + { + _DialogueLookup.Clear(); + + foreach (var watcher in _Watchers.Values) + { + watcher.EnableRaisingEvents = false; + watcher.Dispose(); + } + + _Watchers.Clear(); + } + + private static void ExtractDialogueFilesPatch(ILContext il) + { + var cursor = new ILCursor(il); + + int pathLdloc = -1; + int modLdloc = -1; + if (!cursor.TryGotoNext(MoveType.After, + i => i.MatchLdloc(out modLdloc), // Mod mod + i => i.MatchLdloc(out pathLdloc), // string path + i => i.MatchCallOrCallvirt(out _), // GameCulture ActiveCulture + i => i.MatchCallOrCallvirt(typeof(LocalizationLoader), nameof(LocalizationLoader.UpdateLocalizationFilesForMod)))) + { + CalamityMod.Log.ILFailure("Force Extract Dialogue Files", $"Unable to locate {nameof(LocalizationLoader.UpdateLocalizationFilesForMod)} call"); + } + + if (modLdloc == -1) + { + CalamityMod.Log.ILFailure("Force Extract Dialogue Files", $"Unable to locate ldloc index for mod"); + } + + if (pathLdloc == -1) + { + CalamityMod.Log.ILFailure("Force Extract Dialogue Files", $"Unable to locate ldloc index for path"); + } + + cursor.EmitLdloc(modLdloc); + cursor.EmitLdloc(pathLdloc); + cursor.EmitDelegate((Mod mod, string basePath) => + { + foreach (var entry in GetDialogueTextEntries(mod, GameCulture.DefaultCulture, skipDeserializeData: true)) + { + try + { + var destFilePath = Path.Combine(basePath, entry.FilePath); + var destDir = Path.GetDirectoryName(destFilePath); + if (!Directory.Exists(destDir)) Directory.CreateDirectory(destDir); + + using var stream = mod.File.GetStream(entry.FilePath); + using var fileStream = File.OpenWrite(destFilePath); + using var writer = new StreamWriter(fileStream, Encoding.UTF8); + using var reader = new StreamReader(stream, Encoding.UTF8); + writer.Write(reader.ReadToEnd()); + } + catch (Exception e) + { + CalamityMod.Log.Error($"Error while exporting DialogueTextData entry ({mod.Name}::{entry.FilePath}): {e}"); + } + } + }); + } + + public static bool TryGetDialogue(string dialogueKey, out DialogueTextData data) + { + if (_DialogueLookup.TryGetValue(dialogueKey, out var entry)) + { + data = entry.Data; + return true; + } + + data = null; + return false; + } + + public override void OnLocalizationsLoaded() + { + _DialogueLookup.Clear(); + + // Mods should be sorted by dependency order. + foreach (var entry in GetDialogueTextEntiresForAllMods(GameCulture.DefaultCulture)) + { + if (_DialogueLookup.TryGetValue(entry.DialogueKey, out var oldEntry)) + { + if (entry.Data.Revision != oldEntry.Data.Revision) + { + CalamityMod.Log.Warn($"Dialogue Localization was detected but revision mismatches. This will not be applied! : '{entry.ProviderMod.Name}::{entry.FilePath}'"); + continue; + } + } + + _DialogueLookup[entry.DialogueKey] = entry; + } + + var activeCulture = LanguageManager.Instance.ActiveCulture; + if (activeCulture == GameCulture.DefaultCulture) + return; + + foreach (var entry in GetDialogueTextEntiresForAllMods(activeCulture)) + { + var mod = entry.ProviderMod; + + if (!_DialogueLookup.TryGetValue(entry.DialogueKey, out var oldEntry)) + { + CalamityMod.Log.Warn($"Dialogue Localization was detected but original Dialogue file does not exist. This will not be applied! : '{mod.Name}::{entry.FilePath}'"); + continue; + } + + // Skip if entry is from same file. + if (oldEntry.ProviderMod == entry.ProviderMod && oldEntry.FilePath == entry.FilePath) + { + continue; + } + + if (oldEntry.Data.Revision != entry.Data.Revision) + { + CalamityMod.Log.Warn($"Dialogue Localization was detected but revision mismatches. This will not be applied! : '{mod.Name}::{entry.FilePath}'"); + continue; + } + + _DialogueLookup[entry.DialogueKey] = entry; + } + } + + private static void HandleFileUpdate(Mod mod, string filePath) + { + if (!TryGetDialogueFileInfo(filePath, out _, out _, out var dialogueKey)) + return; + + if (!_DialogueLookup.TryGetValue(dialogueKey, out var existingEntry)) + return; + + if (existingEntry.ProviderMod != mod) + return; + + try + { + using var stream = new StreamReader(File.OpenRead(filePath), Encoding.UTF8); + _DialogueLookup[dialogueKey] = existingEntry with + { + Data = JsonSerializer.Deserialize(stream.BaseStream) + }; + + var hotreloadedMessage = $"Dialogue entry has been hot reloaded: '{dialogueKey}', from source: '{filePath}'"; + CalamityMod.Log.Info(hotreloadedMessage); + if (!Main.gameMenu) Main.NewText(hotreloadedMessage); + } + catch (Exception e) + { + CalamityMod.Log.Error($"Error while hot reloading DialogueTextData entry ({filePath}): {e}"); + } + } + + private static IEnumerable GetDialogueTextEntiresForAllMods(GameCulture targetCulture, bool skipDeserializeData = false) + { + return ModLoader.Mods + .Where(mod => mod.File != null) + .SelectMany(mod => GetDialogueTextEntries(mod, targetCulture, skipDeserializeData)); + } + + private static IEnumerable GetDialogueTextEntries(Mod mod, GameCulture targetCulture, bool skipDeserializeData = false) + { + if (mod == null) + yield break; + + if (mod.File == null) + yield break; + + foreach (var file in mod.File) + { + if (!TryGetDialogueFileInfo(file.Name, out var culture, out var prefix, out var dialogueKey)) + continue; + + if (culture != targetCulture) + continue; + + DialogueTextData data = null; + if (!skipDeserializeData) + { + try + { + using var stream = new StreamReader(mod.File.GetStream(file), Encoding.UTF8); + data = JsonSerializer.Deserialize(stream.BaseStream); + } + catch (Exception e) + { + CalamityMod.Log.Error($"Error while reading DialogueTextData entry ({mod.Name}::{file.Name}): {e}"); + } + } + + if (data != null || skipDeserializeData) + { + yield return new DialogueTextDataEntry(mod, file.Name, dialogueKey, data); + } + } + } + + private static bool TryGetDialogueFileInfo(string filePath, out GameCulture culture, out string prefix, out string dialogueKey) + { + if (!Path.GetExtension(filePath).Equals(".json", StringComparison.InvariantCultureIgnoreCase)) + goto EXIT_INVALID; + + if (!LocalizationLoader.TryGetCultureAndPrefixFromPath(filePath, out culture, out prefix)) + goto EXIT_INVALID; + + string fileName = Path.GetFileNameWithoutExtension(filePath); + if (fileName.StartsWith($"{prefix}_{DialogueFilePrefix}", StringComparison.InvariantCultureIgnoreCase)) + { + dialogueKey = fileName[$"{prefix}_{DialogueFilePrefix}".Length..]; + return true; + } + else if (fileName.StartsWith(DialogueFilePrefix, StringComparison.InvariantCultureIgnoreCase)) + { + dialogueKey = fileName[DialogueFilePrefix.Length..]; + return true; + } + +EXIT_INVALID: + culture = null; + prefix = null; + dialogueKey = null; + return false; + } + + [GeneratedRegex(@"Dialogue\..+?\.jsonc?$", RegexOptions.IgnoreCase)] + private static partial Regex CalamityDialogueFileRegex(); +} diff --git a/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Death.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Death.json new file mode 100644 index 0000000000..3e92c78a0f --- /dev/null +++ b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Death.json @@ -0,0 +1,54 @@ +{ + "Revision": 1, + "DefaultColor": "6383FF", + "DefaultSpeaker": "DevourerOfGods", + "AlignType": 1, + "TextDelay": 2, + "BasePunctuationDelay": { + "Delay": 10, + "ForceSet": false, + "Locks": false + }, + "PunctuationDelayCap": 30, + "PunctuationDelays": { + "!": { + "Delay": 20, + "ForceSet": true, + "Locks": true + }, + "?": { + "Delay": 20, + "ForceSet": true, + "Locks": true + } + }, + "Pages": [ + { + "TextDelay": 0, + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Tasteless [Pause(0.25)]slop.]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Delicious... A feast worthy of a god!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):And [Shaking:STAY] dead!]]" + ] + }, + { + "TextDelay": 0, + "Lines": [ + "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):WEAK.]]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:PATHETIC.] ALL THAT RUNNING JUST TO DIE TO A [Shaking:SINGLE TOUCH?!]]]" + ] + } + ] +} diff --git a/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Head.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Head.json new file mode 100644 index 0000000000..93da2b43ff --- /dev/null +++ b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Head.json @@ -0,0 +1,95 @@ +{ + "Revision": 1, + "DefaultColor": "6383FF", + "DefaultSpeaker": "DevourerOfGods", + "AlignType": 1, + "TextDelay": 2, + "BasePunctuationDelay": { + "Delay": 10, + "ForceSet": false, + "Locks": false + }, + "PunctuationDelayCap": 30, + "PunctuationDelays": { + "!": { + "Delay": 20, + "ForceSet": true, + "Locks": true + }, + "?": { + "Delay": 20, + "ForceSet": true, + "Locks": true + } + }, + "Pages": [ + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Fall to your knees, worm!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Let's see how much longer you'll last...]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Getting tired yet?]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You'll fall, just like the others!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Give up! It'll be easier for both of us!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Let me end you already!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):This is starting to get ridiculous...!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):How are you doing this?!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Are you playing me for a fool?!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Why won't you [Shaking:DIE?!]]]" + ] + }, + { + "TextDelay": 0, + "Lines": [ + "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):FALL!]]]" + ] + }, + { + "TextDelay": 0, + "Lines": [ + "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):BEGON!]]]" + ] + }, + { + "TextDelay": 0, + "Lines": [ + "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):DIE!]]]" + ] + } + ] +} diff --git a/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Phases.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Phases.json new file mode 100644 index 0000000000..3ae52d8b17 --- /dev/null +++ b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Phases.json @@ -0,0 +1,48 @@ +{ + "Revision": 1, + "DefaultColor": "6383FF", + "DefaultSpeaker": "DevourerOfGods", + "AlignType": 1, + "TextDelay": 2, + "BasePunctuationDelay": { + "Delay": 10, + "ForceSet": false, + "Locks": false + }, + "PunctuationDelayCap": 30, + "PunctuationDelays": { + "!": { + "Delay": 20, + "ForceSet": true, + "Locks": true + }, + "?": { + "Delay": 20, + "ForceSet": true, + "Locks": true + } + }, + "Pages": [ + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You are no god...]]", + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):But I shall feast upon your essence regardless!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You've done better than most, but don't get cocky!]]" + ] + }, + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):It's not over yet, kid!]]" + ] + }, + { + "Lines": [ + "[Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:[Scale(1.5):A]]][Colors(2, 0.5, FF00FF, 00FFFF):[Shaking(5):[Scale(2): [Pause(0.33)]GOD]]][Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:[Scale(1.5): DOES NOT FEAR]]][Colors(2, 0.5, FF00FF, 00FFFF):[Shaking(5):[Scale(2): [Pause(0.33)]DEATH!]]]" + ] + } + ] +} \ No newline at end of file diff --git a/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Running.json b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Running.json new file mode 100644 index 0000000000..de35cd7052 --- /dev/null +++ b/Dialogues/en-US/Dialogue.Mods.CalamityMod.DevourerOfGods.Running.json @@ -0,0 +1,37 @@ +{ + "Revision": 1, + "DefaultColor": "6383FF", + "DefaultSpeaker": "DevourerOfGods", + "AlignType": 1, + "TextDelay": 2, + "BasePunctuationDelay": { + "Delay": 10, + "ForceSet": false, + "Locks": false + }, + "PunctuationDelayCap": 30, + "PunctuationDelays": { + "!": { + "Delay": 20, + "ForceSet": true, + "Locks": true + }, + "?": { + "Delay": 20, + "ForceSet": true, + "Locks": true + } + }, + "Pages": [ + { + "Lines": [ + "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You can't run forever!]]" + ] + }, + { + "Lines": [ + "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):WHAT'S THE PROBLEM?! CAN'T RUN ANYMORE?!]]]" + ] + } + ] +} diff --git a/FluidSimulation/FluidField.cs b/FluidSimulation/FluidField.cs index 465a2f9de7..213307ced2 100644 --- a/FluidSimulation/FluidField.cs +++ b/FluidSimulation/FluidField.cs @@ -1,6 +1,7 @@ using System; using CalamityMod.Effects; using CalamityMod.Graphics; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -12,11 +13,11 @@ namespace CalamityMod.FluidSimulation // Please do not change this system too much without contacting me first. -Dominic public class FluidField : IDisposable { - internal ManagedRenderTarget TemporaryAuxilaryTarget; + internal RenderTargetLease TemporaryAuxilaryTarget; - internal ManagedRenderTarget DivergenceField; + internal RenderTargetLease DivergenceField; - internal ManagedRenderTarget DivergencePoissonField; + internal RenderTargetLease DivergencePoissonField; internal FluidFieldState VelocityField; @@ -24,7 +25,7 @@ namespace CalamityMod.FluidSimulation internal FluidFieldState ColorField; - internal ManagedRenderTarget OutputTarget; + internal RenderTargetLease OutputTarget; public float Viscosity; @@ -71,8 +72,7 @@ namespace CalamityMod.FluidSimulation } // A surface format of Vector4 is used here to allow for both 0-1 ranged colors and other things at the same time. - public RenderTarget2D FluidCreateCondition(int screen, int height) => - new(Main.instance.GraphicsDevice, Size, Size, true, SurfaceFormat.Vector4, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); + public static RenderTargetDescriptor FluidDescriptor => new RenderTargetDescriptor(SurfaceFormat.Vector4, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents, true); internal FluidField(int size, float scale, float viscosity, float diffusionFactor, float dissipationFactor) { @@ -86,31 +86,31 @@ namespace CalamityMod.FluidSimulation DensityField = new(size); ColorField = new(size); - TemporaryAuxilaryTarget = new(false, FluidCreateCondition, false); + TemporaryAuxilaryTarget = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, FluidDescriptor); - DivergenceField = new(false, FluidCreateCondition, false); - DivergencePoissonField = new(false, FluidCreateCondition, false); + DivergenceField = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, FluidDescriptor); + DivergencePoissonField = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, FluidDescriptor); - OutputTarget = new(false, FluidCreateCondition, false); + OutputTarget = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, FluidDescriptor); } internal void ApplyThingToTarget(RenderTarget2D currentField, Action shaderPreparationsAction) { - Main.instance.GraphicsDevice.SetRenderTarget(TemporaryAuxilaryTarget); - Main.instance.GraphicsDevice.Clear(Color.Transparent); + using (TemporaryAuxilaryTarget.Scope(clearColor: Color.Transparent)) + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); + shaderPreparationsAction(); + Main.spriteBatch.Draw(currentField, currentField.Bounds, Color.White); + Main.spriteBatch.End(); + } - shaderPreparationsAction(); - Main.spriteBatch.Draw(currentField, currentField.Bounds, Color.White); - Main.spriteBatch.End(); - - currentField.CopyContentsFrom(TemporaryAuxilaryTarget); + currentField.CopyContentsFrom(TemporaryAuxilaryTarget.Target); } internal void FlushQueueToTarget(FluidFieldState field) { - ApplyThingToTarget(field.NextState, () => + ApplyThingToTarget(field.NextState.Target, () => { int batchIndex = 0; int pixelCount = field.PendingChanges.Count; @@ -167,9 +167,9 @@ namespace CalamityMod.FluidSimulation internal void CalculateDiffusion(float diffusionFactor, FluidFieldState field, bool colors = false) { diffusionFactor *= DeltaTime * Size; - ApplyThingToTarget(field.NextState, () => + ApplyThingToTarget(field.NextState.Target, () => { - Main.instance.GraphicsDevice.Textures[1] = field.PreviousState; + Main.instance.GraphicsDevice.Textures[1] = field.PreviousState.Target; CalamityShaders.FluidShaders.Value.Parameters["size"].SetValue(Size); CalamityShaders.FluidShaders.Value.Parameters["diffusionFactor"].SetValue(diffusionFactor); CalamityShaders.FluidShaders.Value.Parameters["handlingColors"].SetValue(colors); @@ -194,7 +194,7 @@ namespace CalamityMod.FluidSimulation internal void ClearDivergence(RenderTarget2D velocities) { // Calculate divergence. - ApplyThingToTarget(DivergenceField, () => + ApplyThingToTarget(DivergenceField.Target, () => { Main.instance.GraphicsDevice.Textures[2] = velocities; CalamityShaders.FluidShaders.Value.Parameters["size"].SetValue(Size); @@ -202,16 +202,15 @@ namespace CalamityMod.FluidSimulation }); // Clear the Poisson values and then calculate them, for use in the divergence clearance pass. - Main.instance.GraphicsDevice.SetRenderTarget(DivergencePoissonField); - Main.instance.GraphicsDevice.Clear(Color.Transparent); + using (DivergencePoissonField.Scope(clearColor: Color.Transparent)) { } for (int i = 0; i < GaussSeidelIterations; i++) { - ApplyThingToTarget(DivergencePoissonField, () => + ApplyThingToTarget(DivergencePoissonField.Target, () => { - Main.instance.GraphicsDevice.Textures[1] = DivergencePoissonField; + Main.instance.GraphicsDevice.Textures[1] = DivergencePoissonField.Target; Main.instance.GraphicsDevice.Textures[2] = velocities; - Main.instance.GraphicsDevice.Textures[4] = DivergenceField; + Main.instance.GraphicsDevice.Textures[4] = DivergenceField.Target; CalamityShaders.FluidShaders.Value.Parameters["size"].SetValue(Size); CalamityShaders.FluidShaders.Value.CurrentTechnique.Passes["PerformPoissonIterationPass"].Apply(); }); @@ -220,7 +219,7 @@ namespace CalamityMod.FluidSimulation ApplyThingToTarget(velocities, () => { Main.instance.GraphicsDevice.Textures[1] = velocities; - Main.instance.GraphicsDevice.Textures[3] = DivergencePoissonField; + Main.instance.GraphicsDevice.Textures[3] = DivergencePoissonField.Target; CalamityShaders.FluidShaders.Value.CurrentTechnique.Passes["ClearDivergencePass"].Apply(); }); } @@ -255,36 +254,34 @@ namespace CalamityMod.FluidSimulation { CalculateDiffusion(Viscosity, VelocityField); if (!ShouldSkipDivergenceClearingStep) - ClearDivergence(VelocityField.NextState); + ClearDivergence(VelocityField.NextState.Target); - CalculateAdvection(VelocityField.NextState, VelocityField.PreviousState, VelocityField.PreviousState); + CalculateAdvection(VelocityField.NextState.Target, VelocityField.PreviousState.Target, VelocityField.PreviousState.Target); if (!ShouldSkipDivergenceClearingStep) - ClearDivergence(VelocityField.NextState); + ClearDivergence(VelocityField.NextState.Target); } internal void UpdateDensityFields() { CalculateDiffusion(DiffusionFactor, DensityField); DensityField.SwapState(); - CalculateAdvection(DensityField.PreviousState, DensityField.NextState, VelocityField.NextState); + CalculateAdvection(DensityField.PreviousState.Target, DensityField.NextState.Target, VelocityField.NextState.Target); CalculateDiffusion(DiffusionFactor, ColorField, true); ColorField.SwapState(); - CalculateAdvection(ColorField.PreviousState, ColorField.NextState, VelocityField.NextState, true); + CalculateAdvection(ColorField.PreviousState.Target, ColorField.NextState.Target, VelocityField.NextState.Target, true); } public void UpdateOutputTarget() { - Main.instance.GraphicsDevice.SetRenderTarget(OutputTarget); - Main.instance.GraphicsDevice.Clear(Color.Transparent); - - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); - Main.instance.GraphicsDevice.Textures[5] = ColorField.NextState; - CalamityShaders.FluidShaders.Value.CurrentTechnique.Passes["DrawFluidPass"].Apply(); - Main.spriteBatch.Draw(DensityField.NextState, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, 1f, 0, 0f); - Main.spriteBatch.End(); - - Main.instance.GraphicsDevice.SetRenderTarget(null); + using (OutputTarget.Scope(clearColor: Color.Transparent)) + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); + Main.instance.GraphicsDevice.Textures[5] = ColorField.NextState.Target; + CalamityShaders.FluidShaders.Value.CurrentTechnique.Passes["DrawFluidPass"].Apply(); + Main.spriteBatch.Draw(DensityField.NextState.Target, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, 1f, 0, 0f); + Main.spriteBatch.End(); + } } public void Dispose() @@ -321,9 +318,9 @@ namespace CalamityMod.FluidSimulation Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, Main.Rasterizer, null, drawPerspective); - shaderPreparations?.Invoke(OutputTarget); + shaderPreparations?.Invoke(OutputTarget.Target); - Main.spriteBatch.Draw(OutputTarget, drawPosition, null, Color.White, 0f, OutputTarget.Size * 0.5f, Scale, 0, 0f); + Main.spriteBatch.Draw(OutputTarget.Target, drawPosition, null, Color.White, 0f, OutputTarget.Target.Size() * 0.5f, Scale, 0, 0f); Main.spriteBatch.End(); if (needsToCallEnd) diff --git a/FluidSimulation/FluidFieldState.cs b/FluidSimulation/FluidFieldState.cs index 3036565049..0e9da15fbb 100644 --- a/FluidSimulation/FluidFieldState.cs +++ b/FluidSimulation/FluidFieldState.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using CalamityMod.Graphics; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -8,9 +9,9 @@ namespace CalamityMod.FluidSimulation // Calculations for these are done primarily on the GPU in shaders for performance-sake. public class FluidFieldState { - public ManagedRenderTarget PreviousState; + public RenderTargetLease PreviousState; - public ManagedRenderTarget NextState; + public RenderTargetLease NextState; public Queue PendingChanges = new(); @@ -20,9 +21,6 @@ namespace CalamityMod.FluidSimulation public void SwapState() => Utils.Swap(ref PreviousState, ref NextState); - public RenderTarget2D FieldColorCreateCondition(int screen, int height) => - new(Main.instance.GraphicsDevice, Size, Size, true, FieldContents, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents); - public FluidFieldState(int size, SurfaceFormat fieldContents = SurfaceFormat.Color) { if (Main.dedServ) @@ -31,8 +29,9 @@ namespace CalamityMod.FluidSimulation Size = size; FieldContents = fieldContents; - PreviousState = new(false, FieldColorCreateCondition, false); - NextState = new(false, FieldColorCreateCondition, false); + var descriptor = new RenderTargetDescriptor(FieldContents, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents, true); + PreviousState = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, descriptor); + NextState = RenderTargetPool.Shared.Rent(Main.instance.GraphicsDevice, Size, Size, descriptor); } } } diff --git a/Graphics/ManagedRenderTarget.cs b/Graphics/ManagedRenderTarget.cs index f69b815ca7..47f563979f 100644 --- a/Graphics/ManagedRenderTarget.cs +++ b/Graphics/ManagedRenderTarget.cs @@ -1,114 +1,138 @@ using System; +using System.Collections.Generic; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; -namespace CalamityMod.Graphics +namespace CalamityMod.Graphics; + +internal sealed class ManagedRenderTargetPool : RenderTargetPool { - /// - /// Wrapper class for that safely handles resizing, unloading and auto-disposal if not currently in use to save - /// on GPU memory. - /// - public class ManagedRenderTarget : IDisposable + public new static ManagedRenderTargetPool Shared { get; } = new(); + + private static readonly List managedTargets = []; + + public override RenderTargetLease Rent(GraphicsDevice device, int width, int height, RenderTargetDescriptor descriptor) { - private RenderTarget2D target; + throw new InvalidOperationException("ManagedRenderTargetPool does not support directly leasing targets"); + } - public readonly RenderTargetCreationCondition CreationCondition; + public RenderTargetLease Register(ManagedRenderTarget managedTarget) + { + managedTargets.Add(managedTarget); + return new RenderTargetLease(managedTarget.CreationCondition(Main.screenWidth, Main.screenHeight), this); + } - public readonly bool ShouldResetUponScreenResize; + public override void Return(RenderTargetLease lease) + { + lease.Target.Dispose(); + } - public readonly bool ShouldAutoDispose; - - public bool WaitingForFirstInitialization + public void Return(ManagedRenderTarget managedRt, bool preserveCollection) + { + if (!preserveCollection) { - get; - private set; - } = true; - - public bool IsUninitialized => target is null || target.IsDisposed; - - public bool IsDisposed - { - get; - private set; + _ = managedTargets.Remove(managedRt); } - /// - /// The actual instance that the wrapper contains. - /// - public RenderTarget2D Target + Return(managedRt.lease); + } + + public override void Dispose() + { + foreach (var target in managedTargets) { - get + target.Dispose(preserveCollection: true); + } + + managedTargets.Clear(); + } + + internal void ResizeTargets() + { + foreach (var target in managedTargets) + { + if (target.ShouldResetUponScreenResize) { - if (IsUninitialized) - { - target = CreationCondition(Main.screenWidth, Main.screenHeight); - WaitingForFirstInitialization = false; - IsDisposed = false; - } - - TimeSinceLastAccessed = 0; - return target; + target.lease.Target.Dispose(); + target.lease.Target = target.CreationCondition(Main.screenWidth, Main.screenHeight); } - private set => target = value; } - - public int Width => Target.Width; - - public int Height => Target.Height; - - public Vector2 Size => new(Width, Height); - - /// - /// How many frames since this target has been gotten. Used to dispose of unused targets for the sake of performance. - /// - public int TimeSinceLastAccessed; - - public delegate RenderTarget2D RenderTargetCreationCondition(int screenWidth, int screenHeight); - - // For some reason, adding more arguments to this constructor causes really low end pcs to crash in FNA. I cannot figure out why, so do not use them. - public static RenderTarget2D CreateScreenSizedTarget(int screenWidth, int screenHeight) => new(Main.instance.GraphicsDevice, screenWidth, screenHeight); - - public ManagedRenderTarget(bool shouldResetUponScreenResize, RenderTargetCreationCondition creationCondition, bool shouldAutoDispose = true) - { - ShouldResetUponScreenResize = shouldResetUponScreenResize; - CreationCondition = creationCondition; - ShouldAutoDispose = shouldAutoDispose; - RenderTargetManager.ManagedTargets.Add(this); - } - - /// - /// Sets the current render target to the provided one. - /// - /// The render target to swap to - /// The color to clear the screen with. Transparent by default - public void SwapTo(Color? flushColor = null) => Target.SwapTo(flushColor); - - /// - /// Automatically called by , do not call! - /// - public void Dispose() - { - if (IsDisposed) - return; - - IsDisposed = true; - target?.Dispose(); - GC.SuppressFinalize(this); - } - - /// - /// Automatically called by , do not call! - /// - public void Recreate(int screenWidth, int screenHeight) - { - Dispose(); - IsDisposed = false; - - target = CreationCondition(screenWidth, screenHeight); - TimeSinceLastAccessed = 0; - } - - public static implicit operator RenderTarget2D(ManagedRenderTarget target) => target.Target; } } + +[Obsolete("ManagedRenderTarget is obsolete; developers should use RenderTarget2Ds and RenderTargetLeases")] +public class ManagedRenderTarget : IDisposable +{ + internal RenderTargetLease lease; + + public readonly RenderTargetCreationCondition CreationCondition; + + public readonly bool ShouldResetUponScreenResize; + + public readonly bool ShouldAutoDispose; + + public bool WaitingForFirstInitialization => false; + + public bool IsUninitialized => false; + + public bool IsDisposed + { + get; + private set; + } + + /// + /// The actual instance that the wrapper contains. + /// + public RenderTarget2D Target => lease.Target; + + public int Width => Target.Width; + + public int Height => Target.Height; + + public Vector2 Size => new(Width, Height); + + public int TimeSinceLastAccessed; + + public delegate RenderTarget2D RenderTargetCreationCondition(int screenWidth, int screenHeight); + + [Obsolete("use ScreenspaceTargetPool")] + public static RenderTarget2D CreateScreenSizedTarget(int screenWidth, int screenHeight) => new(Main.instance.GraphicsDevice, screenWidth, screenHeight); + + public ManagedRenderTarget(bool shouldResetUponScreenResize, RenderTargetCreationCondition creationCondition, bool shouldAutoDispose = true) + { + ShouldResetUponScreenResize = shouldResetUponScreenResize; + CreationCondition = creationCondition; + ShouldAutoDispose = shouldAutoDispose; + lease = ManagedRenderTargetPool.Shared.Register(this); + } + + /// + /// Sets the current render target to the provided one. + /// + /// The render target to swap to + /// The color to clear the screen with. Transparent by default + [Obsolete("Use RenderTargetScope")] + public void SwapTo(Color? flushColor = null) => Target.SwapTo(flushColor); + + public void Dispose() + { + Dispose(preserveCollection: false); + } + + public void Dispose(bool preserveCollection) + { + if (IsDisposed) + return; + + IsDisposed = true; + ManagedRenderTargetPool.Shared.Return(this, preserveCollection); + } + + // Does nothing + public void Recreate(int screenWidth, int screenHeight) { } + + public static implicit operator RenderTarget2D(ManagedRenderTarget target) => target.Target; +} diff --git a/Graphics/Metaballs/DoGDistortionMetaball.cs b/Graphics/Metaballs/DoGDistortionMetaball.cs index 260f13a4a1..0c23deb9ae 100644 --- a/Graphics/Metaballs/DoGDistortionMetaball.cs +++ b/Graphics/Metaballs/DoGDistortionMetaball.cs @@ -74,7 +74,7 @@ namespace CalamityMod.Graphics.Metaballs metaballShader.Value.Parameters["edgeColor"]?.SetValue(EdgeColor.ToVector4()); metaballShader.Value.Parameters["singleFrameScreenOffset"]?.SetValue((Main.screenLastPosition - Main.screenPosition) / screenSize); - gd.Textures[1] = DoGVisualsManager.DistortionForegroundContentsTarget; + gd.Textures[1] = DoGVisualsManager.DistortionForegroundContentsTarget.Target; gd.SamplerStates[1] = SamplerState.LinearWrap; metaballShader.Value.CurrentTechnique.Passes[0].Apply(); diff --git a/Graphics/Metaballs/Metaball.cs b/Graphics/Metaballs/Metaball.cs index 1a75123c45..521eaebab2 100644 --- a/Graphics/Metaballs/Metaball.cs +++ b/Graphics/Metaballs/Metaball.cs @@ -2,6 +2,7 @@ using System.Linq; using CalamityMod.Effects; using CalamityMod.Enums; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -11,7 +12,7 @@ namespace CalamityMod.Graphics.Metaballs { public abstract class Metaball : ModType { - internal List LayerTargets = new(); + internal List LayerTargets = new(); /// /// Required utility that is used to determine whether this metaball has anything to draw.

@@ -145,7 +146,7 @@ namespace CalamityMod.Graphics.Metaballs // Load render targets. int layerCount = Layers.Count(); for (int i = 0; i < layerCount; i++) - LayerTargets.Add(new(true, ManagedRenderTarget.CreateScreenSizedTarget)); + LayerTargets.Add(ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice)); }); } diff --git a/Graphics/Metaballs/MetaballManager.cs b/Graphics/Metaballs/MetaballManager.cs index c33bb5f83f..a051f064c8 100644 --- a/Graphics/Metaballs/MetaballManager.cs +++ b/Graphics/Metaballs/MetaballManager.cs @@ -2,6 +2,7 @@ using System.Linq; using CalamityMod.Enums; using CalamityMod.Systems.Graphic; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -70,20 +71,19 @@ namespace CalamityMod.Graphics.Metaballs metaball.PrepareSpriteBatch(Main.spriteBatch); // Draw the raw contents of the metaball to each of its render targets. - foreach (ManagedRenderTarget target in metaball.LayerTargets) + foreach (var target in metaball.LayerTargets) { - gd.SetRenderTarget(target); - gd.Clear(Color.Transparent); - metaball.DrawInstances(); + using (target.Scope(clearColor: Color.Transparent)) + { + metaball.DrawInstances(); - // Flush metaball contents to its render target and reset the sprite batch for the next iteration. - Main.spriteBatch.End(); - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, Main.Rasterizer, null, Main.Transform); + // Flush metaball contents to its render target and reset the sprite batch for the next iteration. + Main.spriteBatch.End(); + Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, Main.Rasterizer, null, Main.Transform); + } } } - // Return to the backbuffer and end the sprite batch. - gd.SetRenderTarget(null); Main.spriteBatch.End(); } @@ -110,7 +110,7 @@ namespace CalamityMod.Graphics.Metaballs metaball.PrepareShaderForTarget(i); // Draw the metaball's raw contents with the shader. - Main.spriteBatch.Draw(metaball.LayerTargets[i], Vector2.Zero, Color.White); + Main.spriteBatch.Draw(metaball.LayerTargets[i].Target, Vector2.Zero, Color.White); } } diff --git a/Graphics/Primitives/PrimitivePixelationSystem.cs b/Graphics/Primitives/PrimitivePixelationSystem.cs index 3fa1d49fbc..582591c4a0 100644 --- a/Graphics/Primitives/PrimitivePixelationSystem.cs +++ b/Graphics/Primitives/PrimitivePixelationSystem.cs @@ -2,6 +2,7 @@ using System.Linq; using CalamityMod.Enums; using CalamityMod.Systems.Graphic; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -12,25 +13,23 @@ namespace CalamityMod.Graphics.Primitives public class PrimitivePixelationSystem : ModSystem { #region Fields/Properties - private static ManagedRenderTarget PixelationTarget_BeforeAllTiles; + private static RenderTargetLease PixelationTarget_BeforeAllTiles; - private static ManagedRenderTarget PixelationTarget_BeforeSolidTiles; + private static RenderTargetLease PixelationTarget_BeforeSolidTiles; - private static ManagedRenderTarget PixelationTarget_BeforeNPCs; + private static RenderTargetLease PixelationTarget_BeforeNPCs; - private static ManagedRenderTarget PixelationTarget_AfterNPCs; + private static RenderTargetLease PixelationTarget_AfterNPCs; - private static ManagedRenderTarget PixelationTarget_BeforeProjectiles; + private static RenderTargetLease PixelationTarget_BeforeProjectiles; - private static ManagedRenderTarget PixelationTarget_AfterProjectiles; + private static RenderTargetLease PixelationTarget_AfterProjectiles; - private static ManagedRenderTarget PixelationTarget_AfterPlayers; + private static RenderTargetLease PixelationTarget_AfterPlayers; - private static ManagedRenderTarget PixelationTarget_AfterDusts; + private static RenderTargetLease PixelationTarget_AfterDusts; - private static ManagedRenderTarget PixelationTarget_AfterEverything; - - private static RenderTarget2D CreatePixelTarget(int width, int height) => new(Main.instance.GraphicsDevice, width / 2, height / 2); + private static RenderTargetLease PixelationTarget_AfterEverything; /// /// Whether the system is currently rendering any primitives. @@ -50,15 +49,15 @@ namespace CalamityMod.Graphics.Primitives Main.QueueMainThreadAction(() => { - PixelationTarget_BeforeAllTiles = new(true, CreatePixelTarget); - PixelationTarget_BeforeSolidTiles = new(true, CreatePixelTarget); - PixelationTarget_BeforeNPCs = new(true, CreatePixelTarget); - PixelationTarget_AfterNPCs = new(true, CreatePixelTarget); - PixelationTarget_BeforeProjectiles = new(true, CreatePixelTarget); - PixelationTarget_AfterProjectiles = new(true, CreatePixelTarget); - PixelationTarget_AfterPlayers = new(true, CreatePixelTarget); - PixelationTarget_AfterDusts = new(true, CreatePixelTarget); - PixelationTarget_AfterEverything = new(true, CreatePixelTarget); + PixelationTarget_BeforeAllTiles = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_BeforeSolidTiles = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_BeforeNPCs = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_AfterNPCs = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_BeforeProjectiles = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_AfterProjectiles = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_AfterPlayers = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_AfterDusts = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); + PixelationTarget_AfterEverything = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => (w / 2, h / 2)); }); GeneralDrawLayerSystem.OnDrawLayer += DrawTargetScaled; @@ -156,17 +155,15 @@ namespace CalamityMod.Graphics.Primitives CurrentlyRendering = true; - DrawPrimsToRenderTarget(PixelationTarget_BeforeAllTiles, GeneralDrawLayer.BeforeAllTiles, beforeAllTiles); - DrawPrimsToRenderTarget(PixelationTarget_BeforeSolidTiles, GeneralDrawLayer.BeforeSolidTiles, beforeSolidTiles); - DrawPrimsToRenderTarget(PixelationTarget_BeforeNPCs, GeneralDrawLayer.BeforeNPCs, beforeNPCs); - DrawPrimsToRenderTarget(PixelationTarget_AfterNPCs, GeneralDrawLayer.AfterNPCs, afterNPCs); - DrawPrimsToRenderTarget(PixelationTarget_BeforeProjectiles, GeneralDrawLayer.BeforeProjectiles, beforeProjectiles); - DrawPrimsToRenderTarget(PixelationTarget_AfterProjectiles, GeneralDrawLayer.AfterProjectiles, afterProjectiles); - DrawPrimsToRenderTarget(PixelationTarget_AfterPlayers, GeneralDrawLayer.AfterPlayers, afterPlayers); - DrawPrimsToRenderTarget(PixelationTarget_AfterDusts, GeneralDrawLayer.AfterDusts, afterDusts); - DrawPrimsToRenderTarget(PixelationTarget_AfterEverything, GeneralDrawLayer.AfterEverything, afterEverything); - - Main.instance.GraphicsDevice.SetRenderTarget(null); + DrawPrimsToRenderTarget(PixelationTarget_BeforeAllTiles.Target, GeneralDrawLayer.BeforeAllTiles, beforeAllTiles); + DrawPrimsToRenderTarget(PixelationTarget_BeforeSolidTiles.Target, GeneralDrawLayer.BeforeSolidTiles, beforeSolidTiles); + DrawPrimsToRenderTarget(PixelationTarget_BeforeNPCs.Target, GeneralDrawLayer.BeforeNPCs, beforeNPCs); + DrawPrimsToRenderTarget(PixelationTarget_AfterNPCs.Target, GeneralDrawLayer.AfterNPCs, afterNPCs); + DrawPrimsToRenderTarget(PixelationTarget_BeforeProjectiles.Target, GeneralDrawLayer.BeforeProjectiles, beforeProjectiles); + DrawPrimsToRenderTarget(PixelationTarget_AfterProjectiles.Target, GeneralDrawLayer.AfterProjectiles, afterProjectiles); + DrawPrimsToRenderTarget(PixelationTarget_AfterPlayers.Target, GeneralDrawLayer.AfterPlayers, afterPlayers); + DrawPrimsToRenderTarget(PixelationTarget_AfterDusts.Target, GeneralDrawLayer.AfterDusts, afterDusts); + DrawPrimsToRenderTarget(PixelationTarget_AfterEverything.Target, GeneralDrawLayer.AfterEverything, afterEverything); CurrentlyRendering = false; } @@ -174,16 +171,18 @@ namespace CalamityMod.Graphics.Primitives private static void DrawPrimsToRenderTarget(RenderTarget2D renderTarget, GeneralDrawLayer layer, List pixelPrimitives) { // Swap to the target regardless, in order to clear any leftover content from last frame. Not doing this results in the final frame lingering once it stops rendering. - renderTarget.SwapTo(); - if (pixelPrimitives.Any()) + using (renderTarget.Scope(clearColor: Color.Transparent)) { - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null); + if (pixelPrimitives.Any()) + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null); - foreach (var pixelPrimitiveDrawer in pixelPrimitives) - pixelPrimitiveDrawer.RenderPixelatedPrimitives(Main.spriteBatch, layer); + foreach (var pixelPrimitiveDrawer in pixelPrimitives) + pixelPrimitiveDrawer.RenderPixelatedPrimitives(Main.spriteBatch, layer); - Main.spriteBatch.End(); + Main.spriteBatch.End(); + } } } #endregion @@ -200,15 +199,15 @@ namespace CalamityMod.Graphics.Primitives { return drawLayer switch { - GeneralDrawLayer.BeforeAllTiles => PixelationTarget_BeforeAllTiles, - GeneralDrawLayer.BeforeSolidTiles => PixelationTarget_BeforeSolidTiles, - GeneralDrawLayer.BeforeNPCs => PixelationTarget_BeforeNPCs, - GeneralDrawLayer.AfterNPCs => PixelationTarget_AfterNPCs, - GeneralDrawLayer.BeforeProjectiles => PixelationTarget_BeforeProjectiles, - GeneralDrawLayer.AfterProjectiles => PixelationTarget_AfterProjectiles, - GeneralDrawLayer.AfterPlayers => PixelationTarget_AfterPlayers, - GeneralDrawLayer.AfterDusts => PixelationTarget_AfterDusts, - _ => PixelationTarget_AfterEverything + GeneralDrawLayer.BeforeAllTiles => PixelationTarget_BeforeAllTiles.Target, + GeneralDrawLayer.BeforeSolidTiles => PixelationTarget_BeforeSolidTiles.Target, + GeneralDrawLayer.BeforeNPCs => PixelationTarget_BeforeNPCs.Target, + GeneralDrawLayer.AfterNPCs => PixelationTarget_AfterNPCs.Target, + GeneralDrawLayer.BeforeProjectiles => PixelationTarget_BeforeProjectiles.Target, + GeneralDrawLayer.AfterProjectiles => PixelationTarget_AfterProjectiles.Target, + GeneralDrawLayer.AfterPlayers => PixelationTarget_AfterPlayers.Target, + GeneralDrawLayer.AfterDusts => PixelationTarget_AfterDusts.Target, + _ => PixelationTarget_AfterEverything.Target }; } #endregion diff --git a/Graphics/RenderTargetManager.cs b/Graphics/RenderTargetManager.cs index 56b673c968..52dd844c8c 100644 --- a/Graphics/RenderTargetManager.cs +++ b/Graphics/RenderTargetManager.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.ModLoader; @@ -8,10 +9,9 @@ namespace CalamityMod.Graphics /// /// Manager class that handles all created instances of /// + [Obsolete("ManagedRenderTarget is obsolete; developers should use RenderTarget2Ds and RenderTargetLeases")] public class RenderTargetManager : ModSystem { - internal static List ManagedTargets { get; } = []; - public delegate void RenderTargetUpdateDelegate(); /// @@ -24,64 +24,19 @@ namespace CalamityMod.Graphics /// public const int TimeBeforeAutoDispose = 600; - internal static void ResetTargetSizes(Vector2 screenSize) - { - foreach (ManagedRenderTarget target in ManagedTargets) - { - // Don't attempt to recreate targets that are already initialized or shouldn't be recreated. - if (target is null || target.IsDisposed || target.WaitingForFirstInitialization) - continue; - - Main.QueueMainThreadAction(() => - { - target.Recreate((int)screenSize.X, (int)screenSize.Y); - }); - } - } - - internal static void DisposeOfTargets() - { - Main.QueueMainThreadAction(() => - { - foreach (ManagedRenderTarget target in ManagedTargets) - target?.Dispose(); - ManagedTargets.Clear(); - }); - } - public override void OnModLoad() { Main.OnPreDraw += HandleTargetUpdateLoop; - Main.OnResolutionChanged += ResetTargetSizes; } public override void OnModUnload() { - DisposeOfTargets(); Main.OnPreDraw -= HandleTargetUpdateLoop; - Main.OnResolutionChanged -= ResetTargetSizes; - - if (RenderTargetUpdateLoopEvent != null) - { - foreach (var subscription in RenderTargetUpdateLoopEvent.GetInvocationList()) - RenderTargetUpdateLoopEvent -= (RenderTargetUpdateDelegate)subscription; - } + RenderTargetUpdateLoopEvent = null; } private void HandleTargetUpdateLoop(GameTime obj) { - // Auto-disposal of targets that havent been used in a while, to stop them hogging GPU memory. - foreach (ManagedRenderTarget target in ManagedTargets) - { - if (target == null || target.IsDisposed || !target.ShouldAutoDispose) - continue; - - if (target.TimeSinceLastAccessed >= TimeBeforeAutoDispose) - target.Dispose(); - else - target.TimeSinceLastAccessed++; - } - RenderTargetUpdateLoopEvent?.Invoke(); } } diff --git a/Graphics/Renderers/BaseRenderer.cs b/Graphics/Renderers/BaseRenderer.cs index cb1e3dc5a8..99e1994015 100644 --- a/Graphics/Renderers/BaseRenderer.cs +++ b/Graphics/Renderers/BaseRenderer.cs @@ -1,80 +1,88 @@ using System; using CalamityMod.Enums; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using Terraria; using Terraria.ModLoader; -namespace CalamityMod.Graphics.Renderers +namespace CalamityMod.Graphics.Renderers; + +/// +/// A class to handle drawing a visual effect to a rendertarget, then drawing the target to the screen at selected layer. +/// +[Obsolete("BaseRenderer is obsolete; developers should explore other avenues for rendering")] +public abstract class BaseRenderer : ModType { + #region Fields/Properties /// - /// A class to handle drawing a visual effect to a rendertarget, then drawing the target to the screen at selected layer. + /// The layer that the target should be drawn at. /// - public abstract class BaseRenderer : ModType + public abstract GeneralDrawLayer Layer { get; } + + /// + /// Whether the target should draw and be drawn to this frame. + /// + public abstract bool ShouldDraw { get; } + + /// + /// The target that the visual is drawn to. Automatically handled. + /// + public RenderTargetLease MainTarget { - #region Fields/Properties - /// - /// The layer that the target should be drawn at. - /// - public abstract GeneralDrawLayer Layer { get; } - - /// - /// Whether the target should draw and be drawn to this frame. - /// - public abstract bool ShouldDraw { get; } - - /// - /// The target that the visual is drawn to. Automatically handled. - /// - public ManagedRenderTarget MainTarget - { - get; - private set; - } - #endregion - - #region Methods - protected sealed override void Register() - { - ModTypeLookup.Register(this); - - if (RendererManager.Renderers.Contains(this)) - throw new Exception($"Renderer '{Name}' has already been registered!"); - - RendererManager.Renderers.Add(this); - } - - - public sealed override void SetupContent() => SetStaticDefaults(); - - public sealed override void SetStaticDefaults() => MainTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); - - /// - /// Called from . - /// - public virtual void PreUpdate() - { - - } - - /// - /// Called from . - /// - public virtual void PostUpdate() - { - - } - - /// - /// Draw whatever needed to the target here. - /// - /// - public abstract void DrawToTarget(SpriteBatch spriteBatch); - - /// - /// Draw the target here. By default, just draws the target. - /// - /// - public virtual void DrawTarget(SpriteBatch spriteBatch) => spriteBatch.Draw(MainTarget, Vector2.Zero, Color.White); - #endregion + get; + private set; } + #endregion + + #region Methods + protected sealed override void Register() + { + ModTypeLookup.Register(this); + + if (RendererManager.Renderers.Contains(this)) + throw new Exception($"Renderer '{Name}' has already been registered!"); + + RendererManager.Renderers.Add(this); + } + + + public sealed override void SetupContent() => SetStaticDefaults(); + + public sealed override void SetStaticDefaults() + { + Main.QueueMainThreadAction(() => + { + MainTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); + }); + } + + /// + /// Called from . + /// + public virtual void PreUpdate() + { + + } + + /// + /// Called from . + /// + public virtual void PostUpdate() + { + + } + + /// + /// Draw whatever needed to the target here. + /// + /// + public abstract void DrawToTarget(SpriteBatch spriteBatch); + + /// + /// Draw the target here. By default, just draws the target. + /// + /// + public virtual void DrawTarget(SpriteBatch spriteBatch) => spriteBatch.Draw(MainTarget.Target, Vector2.Zero, Color.White); + #endregion } diff --git a/Graphics/Renderers/CalamityRenderers/DeerclopsShadowRenderer.cs b/Graphics/Renderers/CalamityRenderers/DeerclopsShadowRenderer.cs deleted file mode 100644 index c2adc4bbac..0000000000 --- a/Graphics/Renderers/CalamityRenderers/DeerclopsShadowRenderer.cs +++ /dev/null @@ -1,76 +0,0 @@ -using CalamityMod.Enums; -using CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Terraria; -using Terraria.GameContent; -using Terraria.Graphics.Shaders; - -namespace CalamityMod.Graphics.Renderers.CalamityRenderers -{ - public class DeerclopsShadowRenderer : BaseRenderer - { - #region Fields/Properties - - public override GeneralDrawLayer Layer => GeneralDrawLayer.AfterEverything; - - public static NPC Deerclops => Main.npc[NPC.deerclopsBoss]; - - // Should only draw if not in the main menu, deerclops is active or the border is fading post-death, - // It's rev+ and the boolean for drawing the border is true. - public override bool ShouldDraw => !Main.gameMenu && DeerclopsAI.borderScalar > 0f && DeerclopsAI.shouldDrawEnrageBorder; - #endregion - - #region Methods - public override void DrawToTarget(SpriteBatch spriteBatch) - { - bool shouldDraw; - var deerclopsInactive = false; - if (NPC.deerclopsBoss >= 0 && NPC.deerclopsBoss.WithinBounds(Main.npc.Length)) - { - shouldDraw = Deerclops.HasValidTarget; - } - else - { - shouldDraw = DeerclopsAI.borderScalar > 0f; - deerclopsInactive = true; - } - - if (shouldDraw) - { - var minRadius = DeerclopsAI.innerBorder; - var maxRadius = DeerclopsAI.outerBorder; - - // Begin drawing the shadow - var blackTile = TextureAssets.MagicPixel; - - var shader = GameShaders.Misc["CalamityMod:DeerclopsShadowShader"].Shader; - shader.Parameters["minRadius"].SetValue(minRadius); - shader.Parameters["maxRadius"].SetValue(maxRadius); - shader.Parameters["anchorPoint"].SetValue(DeerclopsAI.lastDeerclopsPosition); - shader.Parameters["screenPosition"].SetValue(Main.screenPosition); - shader.Parameters["screenSize"].SetValue(Main.ScreenSize.ToVector2()); - shader.Parameters["maxOpacity"].SetValue(DeerclopsAI.borderScalar); - - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, shader, Main.Transform); - - Rectangle rekt = new(Main.screenWidth / 2, Main.screenHeight / 2, Main.screenWidth, Main.screenHeight); - spriteBatch.Draw(blackTile.Value, rekt, null, default, 0f, blackTile.Value.Size() * 0.5f, 0, 0f); - - // Shadow drawing complete - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise); - } - - if (deerclopsInactive) - { - // Push the border away and fade out when deerclops is deadge - DeerclopsAI.borderScalar = MathHelper.Clamp(DeerclopsAI.borderScalar - 0.015f, 0f, 1f); - DeerclopsAI.innerBorder += 30f; - DeerclopsAI.outerBorder += 30f; - } - } - #endregion - } -} diff --git a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs index 799922dd00..60479a2908 100644 --- a/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs +++ b/Graphics/Renderers/CalamityRenderers/DyeableShadersRenderer.cs @@ -3,6 +3,7 @@ using System.Linq; using CalamityMod.DataStructures; using CalamityMod.Enums; using CalamityMod.Utilities.Daybreak; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -14,7 +15,7 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers public class DyeableShadersRenderer : BaseRenderer { #region Fields/Properties - public static Dictionary Targets + public static Dictionary Targets { get; private set; @@ -131,7 +132,7 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers { // If it doesn't have a dictonary entry, create one. if (!Targets.ContainsKey(renderer)) - Main.QueueMainThreadAction(() => Targets[renderer] = new(true, ManagedRenderTarget.CreateScreenSizedTarget)); + Main.QueueMainThreadAction(() => Targets[renderer] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice)); }); // Mark this item as drawable this frame. @@ -164,8 +165,10 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers continue; // Swap to the assosiated target and call the interface method. - target.SwapTo(); - renderer.DrawDyeableShader(spriteBatch); + using (target.Scope(clearColor: Color.Transparent)) + { + renderer.DrawDyeableShader(spriteBatch); + } } } @@ -188,10 +191,10 @@ namespace CalamityMod.Graphics.Renderers.CalamityRenderers // If it is dyeable, and a dye exists, apply it. This has null safety, as dyeShader can be null here. if (renderer.ShaderIsDyeable && Dyes.TryGetValue(renderer, out var dyeID) && dyeID > 0) - GameShaders.Armor.Apply(dyeID, null, new(target, Vector2.Zero, new Rectangle(0, 0, target.Width, target.Height), Color.White)); + GameShaders.Armor.Apply(dyeID, null, new(target.Target, Vector2.Zero, new Rectangle(0, 0, target.Target.Width, target.Target.Height), Color.White)); // Draw the assosiated target that has been drawn to. - spriteBatch.Draw(target, Vector2.Zero, Color.White with { A = 0 }); + spriteBatch.Draw(target.Target, Vector2.Zero, Color.White with { A = 0 }); } spriteBatch.End(); diff --git a/Graphics/Renderers/CalamityRenderers/HolyInfernoRenderer.cs b/Graphics/Renderers/CalamityRenderers/HolyInfernoRenderer.cs deleted file mode 100644 index 583d13f806..0000000000 --- a/Graphics/Renderers/CalamityRenderers/HolyInfernoRenderer.cs +++ /dev/null @@ -1,97 +0,0 @@ -using CalamityMod.Enums; -using CalamityMod.NPCs; -using CalamityMod.NPCs.Providence; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Terraria; -using Terraria.GameContent; -using Terraria.Graphics.Shaders; -using Terraria.ModLoader; - -namespace CalamityMod.Graphics.Renderers.CalamityRenderers -{ - public class HolyInfernoRenderer : BaseRenderer - { - #region Fields/Properties - - public override GeneralDrawLayer Layer => GeneralDrawLayer.BeforeAllTiles; - - public static Providence Provi - { - get - { - if (!Main.npc.IndexInRange(CalamityGlobalNPC.holyBoss)) - return null; - if (Main.npc[CalamityGlobalNPC.holyBoss].type != ModContent.NPCType()) - return null; - - if (Main.npc[CalamityGlobalNPC.holyBoss].ModNPC is not null && - Main.npc[CalamityGlobalNPC.holyBoss].ModNPC is Providence provi) - return provi; - - return null; - } - } - - //Should only draw if not in the main menu, provi is active and the boolean for drawing the border is true. - public override bool ShouldDraw => !Main.gameMenu && CalamityGlobalNPC.holyBoss != -1 && - Main.npc[CalamityGlobalNPC.holyBoss].active && Providence.shouldDrawInfernoBorder; - #endregion - - #region Methods - public override void DrawToTarget(SpriteBatch spriteBatch) - { - var npc = Main.npc[CalamityGlobalNPC.holyBoss]; - var borderDistance = Providence.borderRadius; - if (!npc.HasValidTarget) - return; - - var target = Main.LocalPlayer; - var holyInfernoIntensity = target.Calamity().holyInfernoFadeIntensity; - var prov = Provi; - if (prov == null) - return; - - //Begin drawing the inferno - var blackTile = TextureAssets.MagicPixel; - var diagonalNoise = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/HarshNoise"); - var upwardPerlinNoise = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Perlin"); - var upwardNoise = ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/MeltyNoise"); - - var maxOpacity = 1f; - if (prov.Dying) - { - //Death animation timer ends at 345f. - maxOpacity = MathHelper.Lerp(1f, 0f, Utils.GetLerpValue(0f, 344f, prov.DeathAnimationTimer)); - } - - var shader = GameShaders.Misc["CalamityMod:HolyInfernoShader"].Shader; - shader.Parameters["colorMult"].SetValue(prov.hasBeenGivenFullPower ? 7.65f : 7.35f); //I want you to know it took considerable restraint to deliberately misspell colour. - shader.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly); - shader.Parameters["radius"].SetValue(borderDistance); - shader.Parameters["anchorPoint"].SetValue(npc.Center); - shader.Parameters["screenPosition"].SetValue(Main.screenPosition); - shader.Parameters["screenSize"].SetValue(Main.ScreenSize.ToVector2()); - shader.Parameters["burnIntensity"].SetValue(holyInfernoIntensity); - shader.Parameters["playerPosition"].SetValue(target.Center); - shader.Parameters["maxOpacity"].SetValue(maxOpacity); - shader.Parameters["day"].SetValue(!prov.hasBeenGivenFullPower); - - spriteBatch.GraphicsDevice.Textures[1] = diagonalNoise.Value; - spriteBatch.GraphicsDevice.Textures[2] = upwardNoise.Value; - spriteBatch.GraphicsDevice.Textures[3] = upwardPerlinNoise.Value; - - //Manual end begin for the sampler state - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, SamplerState.LinearWrap, DepthStencilState.None, Main.Rasterizer, shader, Main.Transform); - - Rectangle rekt = new(Main.screenWidth / 2, Main.screenHeight / 2, Main.screenWidth, Main.screenHeight); - spriteBatch.Draw(blackTile.Value, rekt, null, default, 0f, blackTile.Value.Size() * 0.5f, 0, 0f); - - //Inferno drawing complete - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise); - } - #endregion - } -} diff --git a/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs b/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs deleted file mode 100644 index 330a07e939..0000000000 --- a/Graphics/Renderers/CalamityRenderers/MiracleBlightRenderer.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System.Collections.Generic; -using CalamityMod.Enums; -using CalamityMod.NPCs; -using CalamityMod.NPCs.ExoMechs.Ares; -using Microsoft.Xna.Framework; -using Microsoft.Xna.Framework.Graphics; -using Terraria; -using Terraria.Graphics.Shaders; -using Terraria.ID; -using Terraria.ModLoader; - -namespace CalamityMod.Graphics.Renderers.CalamityRenderers -{ - public class MiracleBlightRenderer : BaseRenderer - { - #region Fields/Properties - /// - /// Add NPCs to this if they break with the miracle blight shader. - /// - public static List ExcludedNPCs => new() - { - // List the reason why the NPC(s) are excluded :) - - // The particle sets break with the visuals and this is the easiest way to fix this that isn't stupidly complex. - ModContent.NPCType(), - ModContent.NPCType(), - ModContent.NPCType(), - ModContent.NPCType(), - ModContent.NPCType(), - - // Breaks with being behind tiles, and causes a funny interaction where his head goes behind his neck. - NPCID.MoonLordCore, - NPCID.MoonLordHand, - NPCID.MoonLordHead - }; - - /// - /// Used to determine whether the npc should return true in predraw or not, for exclusively drawing to the drawer target. - /// - public static bool ActuallyDoPreDraw - { - get; - private set; - } - - public override GeneralDrawLayer Layer => GeneralDrawLayer.AfterNPCs; - - // Unsure whether its more performant to always draw, or to check if any NPC actually has the debuff. - public override bool ShouldDraw => true; - #endregion - - #region Methods - /// - /// Checks if the provided npc is eligible to be drawn with the miracle blight visual effect. - /// - /// The NPC to check - /// If the NPC is eligible - public static bool ValidToDraw(NPC npc) - { - // Do not draw inactive npcs, or ones with weird MP types less than or equal to 0. - if (!npc.active || npc.type <= NPCID.None) - return false; - - if (!CalamityDrawParameterNPC.DrawingMiracleBlight[npc.whoAmI]) - return false; - - return true; - } - - public override void DrawToTarget(SpriteBatch spriteBatch) - { - // Indicate that NPCs with miracle blight should draw. - ActuallyDoPreDraw = true; - - // Draw every npc to a single target that should have the miracle blight visual. - foreach (NPC npc in Main.ActiveNPCs) - { - // Extra check to ensure that index errors will not occur. If not in range, something has gone wrong and the loop should terminate. - if (!Main.npc.IndexInRange(npc.whoAmI)) - break; - - if (ValidToDraw(npc)) - Main.instance.DrawNPC(npc.whoAmI, npc.behindTiles); - } - - // Indicate that NPCs with miracle blight should no longer draw. - ActuallyDoPreDraw = false; - } - - public override void DrawTarget(SpriteBatch spriteBatch) - { - // Apply the shader and draw the target. - var blightShader = GameShaders.Misc["CalamityMod:MiracleBlight"]; - blightShader.SetShaderTexture(ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Neurons"), 1); - blightShader.UseOpacity(0.7f); - blightShader.Apply(); - - spriteBatch.Draw(MainTarget, Vector2.Zero, Color.White); - - spriteBatch.End(); - spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, RasterizerState.CullCounterClockwise); - } - #endregion - } -} diff --git a/Graphics/Renderers/RendererManager.cs b/Graphics/Renderers/RendererManager.cs index 9665bab61b..225e743a61 100644 --- a/Graphics/Renderers/RendererManager.cs +++ b/Graphics/Renderers/RendererManager.cs @@ -3,6 +3,7 @@ using System.Linq; using CalamityMod.Enums; using CalamityMod.Systems.Graphic; using CalamityMod.Utilities.Daybreak; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -93,9 +94,8 @@ namespace CalamityMod.Graphics.Renderers continue; using (Main.spriteBatch.Scope()) + using (renderer.MainTarget.Scope(clearColor: Color.Transparent)) { - Main.instance.GraphicsDevice.SetRenderTarget(renderer.MainTarget); - Main.instance.GraphicsDevice.Clear(Color.Transparent); Main.spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.AlphaBlend, @@ -109,8 +109,6 @@ namespace CalamityMod.Graphics.Renderers Main.spriteBatch.End(); } } - - Main.instance.GraphicsDevice.SetRenderTarget(null); } #endregion } diff --git a/ILEditing/BalancingILChanges.cs b/ILEditing/BalancingILChanges.cs index 326f96bd78..8807cc2714 100644 --- a/ILEditing/BalancingILChanges.cs +++ b/ILEditing/BalancingILChanges.cs @@ -497,7 +497,7 @@ namespace CalamityMod.ILEditing } #endregion - #region SoC Buffs & Vortex Booster Keeping Stealth + #region Shield of Cthulhu Buffs private static void DashMovementEdits(On_Player.orig_DashMovement orig, Player self) { //This is a modified version of Vanilla's Shield of Cthulhu dash collision checks @@ -562,16 +562,7 @@ namespace CalamityMod.ILEditing } } } - - // Allows for Vortex Booster to automatically re-engage Vortex armor's stealth after a delay when dashing - bool vortexStealth = self.vortexStealthActive; orig(self); - - if (self.wingsLogic == (int)VanillaWingID.WingsVortex) - { - if (vortexStealth && !self.vortexStealthActive) - self.Calamity().vortexBoosterStealthDelay = 60; - } } #endregion @@ -601,9 +592,9 @@ namespace CalamityMod.ILEditing cursor.Emit(OpCodes.Ldc_I4, (int)VanillaWingID.WingsStardust); cursor.Emit(OpCodes.Bne_Un, label); - cursor.Emit(OpCodes.Ldc_R4, 900f); + cursor.Emit(OpCodes.Ldc_R4, 960f); cursor.Emit(OpCodes.Stloc, 4); - cursor.Emit(OpCodes.Ldc_R4, 900f); + cursor.Emit(OpCodes.Ldc_R4, 960f); cursor.Emit(OpCodes.Stloc, 5); cursor.MarkLabel(label); @@ -623,26 +614,18 @@ namespace CalamityMod.ILEditing } #endregion - #region Solar Wings Change to Solar Flare Armor Dash - private static void SolarWingsDashChange(ILContext il) + #region Solar Wings Change to Solar Flare Armor + private static bool SolarWingsDashChange(On_Player.orig_ConsumeSolarFlare orig, Player self) { - // Make Solar Wings always allow using Solar Flare armor's dash. - var cursor = new ILCursor(il); - - // Genuinely how the fuck is this the only OR opcode in the entire method - if (!cursor.TryGotoNext(MoveType.After, i => i.MatchOr())) + // Solar Wings restore flight time when Solar Flare armor's shield explodes + // This can trigger from either ramming enemies or taking damage + if (orig(self)) { - LogFailure("Solar Dash Change", "Could not locate the OR opcode."); - return; + if (self.wingsLogic == (int)VanillaWingID.WingsSolar) + self.wingTime += 60; + return true; } - - // Add an additional check for if the player is wearing Solar Wings. - cursor.Emit(OpCodes.Ldarg_0); - cursor.Emit(OpCodes.Ldfld, typeof(Player).GetField("wingsLogic")); - cursor.Emit(OpCodes.Ldc_I4, (int)VanillaWingID.WingsSolar); - cursor.EmitCeq(); - // Then OR it. - cursor.EmitOr(); + return false; } #endregion diff --git a/ILEditing/ILChangesLoading.cs b/ILEditing/ILChangesLoading.cs index 94d6162c6f..ab581d62db 100644 --- a/ILEditing/ILChangesLoading.cs +++ b/ILEditing/ILChangesLoading.cs @@ -107,7 +107,7 @@ namespace CalamityMod.ILEditing IL_Projectile.Damage += VanillaBossResistChanges; IL_Projectile.AI_099_2 += LimitTerrarianProjectiles; IL_Projectile.AI_120_StardustGuardian += StardustGuardianAttackBuffs; - IL_Player.UpdateArmorSets += SolarWingsDashChange; + On_Player.ConsumeSolarFlare += SolarWingsDashChange; IL_Player.UpdateBuffs += UpdateBuffsBalancingChanges; IL_Player.ApplyVanillaHurtEffectModifiers += RemoveBeetleAndSolarFlareMultiplicativeDR; diff --git a/Items/CalamityGlobalItem.cs b/Items/CalamityGlobalItem.cs index 6da5842d68..8209aa18b2 100644 --- a/Items/CalamityGlobalItem.cs +++ b/Items/CalamityGlobalItem.cs @@ -1476,9 +1476,9 @@ namespace CalamityMod.Items if (player.Calamity().reaverExplore) grabRange += ReaverHeadExplore.SetBonusGrabRangeBoost; - // Nebula boosters have greater pickup range while using Nebula Mantle. - if (player.wingsLogic == (int)VanillaWingID.WingsNebula && ItemID.Sets.NebulaPickup[item.type]) - grabRange *= 2; + // Nebula boosters have greater pickup range while hovering with Nebula Mantle. + if (player.wingsLogic == (int)VanillaWingID.WingsNebula && player.wingTime > 0f && player.controlJump && player.TryingToHoverDown && ItemID.Sets.NebulaPickup[item.type]) + grabRange *= 3; } #endregion diff --git a/Items/SummonItems/CosmicWorm.cs b/Items/SummonItems/CosmicWorm.cs index cc2aa24914..2c7bbb1321 100644 --- a/Items/SummonItems/CosmicWorm.cs +++ b/Items/SummonItems/CosmicWorm.cs @@ -2,12 +2,8 @@ using CalamityMod.Items.Materials; using CalamityMod.NPCs.DevourerofGods; using CalamityMod.Rarities; -using CalamityMod.UI.DialogueDisplay; -using CalamityMod.UI.DialogueDisplay.DisplayEffects; -using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; -using Terraria.Localization; using Terraria.ModLoader; namespace CalamityMod.Items.SummonItems @@ -47,23 +43,7 @@ namespace CalamityMod.Items.SummonItems if (Main.dedServ) return true; - string key = "Mods.CalamityMod.Status.Boss.DoGSpawn"; - string spawnText = Language.GetTextValue(key); - Color messageColor = Color.Cyan; - Main.NewText(spawnText, messageColor); - /* - var subtitleID = CombatText.NewText(player.Hitbox, messageColor, spawnText, true); - if (subtitleID < Main.maxCombatText) - { - var localPlayer = Main.LocalPlayer.Calamity(); - localPlayer.subtitletext = Main.combatText[subtitleID]; - localPlayer.subtitleColors = [Color.Cyan, Color.Fuchsia]; - } - */ - NPC n = CalamityUtils.SpawnBossOnPosUsingItem(player, (int)player.Center.X, (int)player.Center.Y - 1600, DevourerofGodsHead.SpawnSound); - - DialogueDisplaySystem.StartDialogue("DevourerOfGods.Phases", n, 0, 120, false, new BossText()); return true; } diff --git a/Items/Weapons/DraedonsArsenal/PhalanxSurge.cs b/Items/Weapons/DraedonsArsenal/PhalanxSurge.cs index 00ab2ba3b1..aae000f87b 100644 --- a/Items/Weapons/DraedonsArsenal/PhalanxSurge.cs +++ b/Items/Weapons/DraedonsArsenal/PhalanxSurge.cs @@ -28,7 +28,7 @@ namespace CalamityMod.Items.Weapons.DraedonsArsenal Item.width = 64; Item.height = 36; Item.DamageType = DamageClass.Ranged; - Item.damage = 150; + Item.damage = 175; Item.knockBack = 4f; Item.useTime = 30; Item.useAnimation = 30; diff --git a/Localization/en-US/Mods.CalamityMod.Dialogue.DevourerOfGods.hjson b/Localization/en-US/Mods.CalamityMod.Dialogue.DevourerOfGods.hjson deleted file mode 100644 index e55d20782c..0000000000 --- a/Localization/en-US/Mods.CalamityMod.Dialogue.DevourerOfGods.hjson +++ /dev/null @@ -1,271 +0,0 @@ -Phases: - ''' - { - "DefaultColor": "6383FF", - "DefaultSpeaker": "DevourerOfGods", - "AlignType": 1, - - "TextDelay": 2, - "BasePunctuationDelay": { - "Delay": 10, - "ForceSet": false, - "Locks": false - }, - "PunctuationDelayCap": 30, - "PunctuationDelays": { - "!": { - "Delay": 20, - "ForceSet": true, - "Locks": true - }, - "?": { - "Delay": 20, - "ForceSet": true, - "Locks": true - } - }, - - "Pages": [ - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You are no god...]]", - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):But I shall feast upon your essence regardless!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You've done better than most, but don't get cocky!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):It's not over yet, kid!]]" - ] - }, - - { - "Lines": [ - "[Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:[Scale(1.5):A]]][Colors(2, 0.5, FF00FF, 00FFFF):[Shaking(5):[Scale(2): [Pause(0.33)]GOD]]][Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:[Scale(1.5): DOES NOT FEAR]]][Colors(2, 0.5, FF00FF, 00FFFF):[Shaking(5):[Scale(2): [Pause(0.33)]DEATH!]]]" - ] - } - ] - } - ''' -Death: - ''' - { - "DefaultColor": "6383FF", - "DefaultSpeaker": "DevourerOfGods", - "AlignType": 1, - - "TextDelay": 2, - "BasePunctuationDelay": { - "Delay": 10, - "ForceSet": false, - "Locks": false - }, - "PunctuationDelayCap": 30, - "PunctuationDelays": { - "!": { - "Delay": 20, - "ForceSet": true, - "Locks": true - }, - "?": { - "Delay": 20, - "ForceSet": true, - "Locks": true - } - }, - - "Pages": [ - { - "TextDelay": 0, - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Tasteless [Pause(0.25)]slop.]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Delicious... A feast worthy of a god!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):And [Shaking:STAY] dead!]]" - ] - }, - - { - "TextDelay": 0, - "Lines": [ - "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):WEAK.]]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):[Shaking:PATHETIC.] ALL THAT RUNNING JUST TO DIE TO A [Shaking:SINGLE TOUCH?!]]]" - ] - } - ] - } - ''' -Head: - ''' - { - "DefaultColor": "6383FF", - "DefaultSpeaker": "DevourerOfGods", - "AlignType": 1, - - "TextDelay": 2, - "BasePunctuationDelay": { - "Delay": 10, - "ForceSet": false, - "Locks": false - }, - "PunctuationDelayCap": 30, - "PunctuationDelays": { - "!": { - "Delay": 20, - "ForceSet": true, - "Locks": true - }, - "?": { - "Delay": 20, - "ForceSet": true, - "Locks": true - } - }, - - "Pages": [ - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Fall to your knees, worm!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Let's see how much longer you'll last...]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Getting tired yet?]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You'll fall, just like the others!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Give up! It'll be easier for both of us!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Let me end you already!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):This is starting to get ridiculous...!]]" - ] - - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):How are you doing this?!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Are you playing me for a fool?!]]" - ] - }, - - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):Why won't you [Shaking:DIE?!]]]" - ] - }, - - { - "TextDelay": 0, - "Lines": [ - "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):FALL!]]]" - ] - }, - - { - "TextDelay": 0, - "Lines": [ - "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):BEGON!]]]" - ] - }, - - { - "TextDelay": 0, - "Lines": [ - "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):DIE!]]]" - ] - } - ] - } - ''' -Running: - ''' - { - "DefaultColor": "6383FF", - "DefaultSpeaker": "DevourerOfGods", - "AlignType": 1, - - "TextDelay": 2, - "BasePunctuationDelay": { - "Delay": 10, - "ForceSet": false, - "Locks": false - }, - "PunctuationDelayCap": 30, - "PunctuationDelays": { - "!": { - "Delay": 20, - "ForceSet": true, - "Locks": true - }, - "?": { - "Delay": 20, - "ForceSet": true, - "Locks": true - } - }, - - "Pages": [ - { - "Lines": [ - "[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):You can't run forever!]]" - ] - }, - - { - "Lines": [ - "[Shaking:[Scale(1.5):[Colors(2, 0.5, 00FFFF, FF00FF):WHAT'S THE PROBLEM?! CAN'T RUN ANYMORE?!]]]" - ] - } - ] - } - ''' diff --git a/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson b/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson index 7980d02bad..d4b0bc310e 100644 --- a/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson +++ b/Localization/en-US/Mods.CalamityMod.Items.Placeables.hjson @@ -887,7 +887,7 @@ CalamityCanvas2024: { ForgivenessPainting: { DisplayName: Forgiveness - Tooltip: D. User + Tooltip: "'D. User'" } ThankYouPainting: { diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Magic.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Magic.hjson index 69f3dd2b41..d3e6a71128 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Magic.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Magic.hjson @@ -8,6 +8,7 @@ AerSigilBlast.DisplayName: Aer Blast AerSigilFeather.DisplayName: Aer Feather AerSigilMissile.DisplayName: Aer Missile AetherBeam.DisplayName: Aether Beam +AlphaDraconisStar.DisplayName: Shooting Star AnahitasArpeggioNote.DisplayName: Anahita's Song Ancient2.DisplayName: Ancient Dust ApoctosisBlast.DisplayName: Apoctosis Blast @@ -48,8 +49,6 @@ CauldronProjSmall.DisplayName: Smaullerdron ChronoIcicleLarge.DisplayName: Chrono Icicle ChronoIcicleSmall.DisplayName: Chrono Icicle ChronomancersScytheHoldout.DisplayName: Chronomancer's Scythe -AlphaDraconisStar.DisplayName: Shooting Star -DracoConstellation.DisplayName: Draco ClimaxBeam.DisplayName: Voltaic Bolt ClimaxProj.DisplayName: Voltaic Orb CoralSpike.DisplayName: Coral Spike @@ -59,9 +58,9 @@ CosmicTentacle.DisplayName: Dark Tentacle CryoBlast.DisplayName: Cryo Blast DarkSparkBeam.DisplayName: Dark Spark Beam DarkSparkPrism.DisplayName: Dark Crystal -HyperdeathRiftScepterBeam.DisplayName: Hyperdeath Rift Ripper DeathValleyDusterProjectile.DisplayName: Death Valley Duster DeathhailBeam.DisplayName: Deathhail Beam +DracoConstellation.DisplayName: Draco EelDrop.DisplayName: Acid Eel Drop EidolicWailSoundwave.DisplayName: Eidolic Wail EldritchTentacle.DisplayName: Eldritch Tentacle @@ -101,6 +100,7 @@ HellfireExplosionFriendly.DisplayName: Explosion HellwingBat.DisplayName: Ashen Hellwing HolyFlame.DisplayName: Holy Flame HolyLaser.DisplayName: Holy Laser +HyperdeathRiftScepterBeam.DisplayName: Hyperdeath Rift Ripper IceBarrageMain.DisplayName: Ice Barrage IceBlock.DisplayName: Ice Barrage Block IceBlockIcicle.DisplayName: Ice Barrage Icicle diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson index 75f83a8570..46c00c7e4c 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Melee.hjson @@ -226,6 +226,7 @@ SanguineFury.DisplayName: Sanguine Fury SanguineFuryDash.DisplayName: Shredding Lunge SanguineFuryWheel.DisplayName: Sanguine Bladewheel ScorcherExplosion.DisplayName: Scorching Crystal Blast +ScorpiusConstellation.DisplayName: Scorpius Constellation ScourgeoftheCosmosMini.DisplayName: Miniature Cosmic Scourge ScourgeoftheCosmosProj.DisplayName: Cosmic Scourge SeashineSwordProj.DisplayName: Seashine Beam diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson index 25463e2e9c..68ef53fa50 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Ranged.hjson @@ -97,6 +97,7 @@ FungiOrb2.DisplayName: Fungi Orb GemTechGreenFlechette.DisplayName: Gem Tech Flechette GodSlayerSlugProj.DisplayName: God Slayer Slug HalleysComet.DisplayName: Halley's Comet +HalleysStarburst.DisplayName: Halley's Starburst HandheldTankShell.DisplayName: Tank Shell HeavenlyGaleProj.DisplayName: Heavenly Gale HellbornProj.DisplayName: Hell-born Gunblast @@ -265,4 +266,3 @@ WaterSpout.DisplayName: Spout WildfireBloomFire.DisplayName: Wildfire Fire WildfireBloomFlare.DisplayName: Wildfire Flare WulfrumScrapBullet.DisplayName: High Speed Scrap -HalleysStarburst.DisplayName: Halleys Starburst diff --git a/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson b/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson index a1dbce0c4e..b5832cd29c 100644 --- a/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson +++ b/Localization/en-US/Mods.CalamityMod.Projectiles.Rogue.hjson @@ -165,6 +165,7 @@ LostSoulFriendly.DisplayName: Lost Soul LuminousShard.DisplayName: Stardust Shard LunarKunaiProj.DisplayName: Lunar Kunai LuxorsGiftRogue.DisplayName: Luxor's Rogue +LyraConstellation.DisplayName: Lyra Constellation MalachiteBolt.DisplayName: Malachite MalachiteProj.DisplayName: Malachite MalachiteStealth.DisplayName: Malachite @@ -183,9 +184,6 @@ NanoblackSplit.DisplayName: Nanoblack Blade NanoblackStealthSplit.DisplayName: Nanoblack Afterimage NastyChollaBol.DisplayName: Nasty Cholla NastyChollaNeedle.DisplayName: Cactus Needle -VegaProjectile.DisplayName: Vega -VegaSpark.DisplayName: Vega Spark -VegaStar.DisplayName: Vega Star OrichalcumSpikedGemstoneProjectile.DisplayName: Orichalcum Gemstone PalladiumJavelinProjectile.DisplayName: Palladium Javelin PartisanExplosion.DisplayName: Profaned Explosion @@ -316,6 +314,9 @@ ValariBoomerang.DisplayName: Frostcrush Valari Valaricicle.DisplayName: Valaricicle Valaricicle2.DisplayName: Valaricicle ValedictionBoomerang.DisplayName: Valediction +VegaProjectile.DisplayName: Vega +VegaSpark.DisplayName: Vega Spark +VegaStar.DisplayName: Vega Star VeneratedKnife.DisplayName: Venerated Knife WaveSkipperProjectile.DisplayName: Wave Skipper WebBallBol.DisplayName: Web Ball @@ -326,5 +327,3 @@ WrathwingCinder.DisplayName: Wrathwing Eruption WrathwingFireball.DisplayName: Wrathwing Fireball WrathwingSpear.DisplayName: Wrathwing WulfrumKnifeProj.DisplayName: Wulfrum Knife -LyraConstellation.DisplayName: Lyra Constellation -ScorpiusConstellation.DisplayName: Scorpius Constellation diff --git a/Localization/en-US/Mods.CalamityMod.UI.WindowTitle.hjson b/Localization/en-US/Mods.CalamityMod.UI.WindowTitle.hjson index e211a8ab7b..b6aef90746 100644 --- a/Localization/en-US/Mods.CalamityMod.UI.WindowTitle.hjson +++ b/Localization/en-US/Mods.CalamityMod.UI.WindowTitle.hjson @@ -40,3 +40,4 @@ 39: Terraria: Code merged without looking 40: Terraria: Endless Calamity 41: Terraria: Throwing is dead, long live rogue +42: Terraria: A Quick One Before the Nameless Serpent Devours Azafure diff --git a/Localization/en-US/Mods.CalamityMod.Vanilla.Wings.hjson b/Localization/en-US/Mods.CalamityMod.Vanilla.Wings.hjson index 40f7b60eda..2a9963a8f4 100644 --- a/Localization/en-US/Mods.CalamityMod.Vanilla.Wings.hjson +++ b/Localization/en-US/Mods.CalamityMod.Vanilla.Wings.hjson @@ -4,7 +4,11 @@ DemonWings: Increases fall speed FestiveWings: Spawns ornaments which restore flight time FinWings: Allows quick travel in water TatteredFairyWings: Leaves a trail of flight draining fairy dust -WingsNebula: Increases the pickup range of Nebula armor's nebula boosters -WingsSolar: Allows Solar Flare armor's dash to be used without any charges -WingsStardust: Greatly increases Stardust armor's stardust guardian damage and attack range -WingsVortex: Vortex armor's stealth ability is automatically reactivated 1 second after dashing +WingsNebula: Greatly increases the pickup range of Nebula armor's nebula boosters while hovering +WingsSolar: Solar Flare armor's shield restores flight time whenever a charge is consumed +WingsStardust: + ''' + Greatly increases Stardust armor's stardust guardian attack range + Stardust guardian damage increases the lower your flight time + ''' +WingsVortex: Vortex armor's stealth gradually restores flight time while activated diff --git a/NPCs/CalamityGlobalNPC.cs b/NPCs/CalamityGlobalNPC.cs index e4e7727b4e..e631afec11 100644 --- a/NPCs/CalamityGlobalNPC.cs +++ b/NPCs/CalamityGlobalNPC.cs @@ -12,7 +12,6 @@ using CalamityMod.DataStructures; using CalamityMod.Dusts; using CalamityMod.Events; using CalamityMod.Graphics.Metaballs; -using CalamityMod.Graphics.Renderers.CalamityRenderers; using CalamityMod.Items.Accessories; using CalamityMod.Items.Accessories.Vanity; using CalamityMod.Items.Armor.PlagueReaper; @@ -5321,10 +5320,6 @@ namespace CalamityMod.NPCs } else ManaBurnFireDrawer = null; - - // Only draw the NPC if told to by the miracle blight drawer. - if (MiracleBlightRenderer.ValidToDraw(npc)) - return MiracleBlightRenderer.ActuallyDoPreDraw; } if (Main.zenithWorld) diff --git a/NPCs/CalamityGlobalTownNPC.cs b/NPCs/CalamityGlobalTownNPC.cs index e36dae3423..111783f008 100644 --- a/NPCs/CalamityGlobalTownNPC.cs +++ b/NPCs/CalamityGlobalTownNPC.cs @@ -894,7 +894,7 @@ namespace CalamityMod.NPCs #region NPC Chat public override void GetChat(NPC npc, ref string chat) { - int permadong = NPC.FindFirstNPC(NPCType()); + int permafrost = NPC.FindFirstNPC(NPCType()); int seahorse = NPC.FindFirstNPC(NPCType()); int thief = NPC.FindFirstNPC(NPCType()); int angelstatue = NPC.FindFirstNPC(NPCID.Merchant); @@ -958,8 +958,8 @@ namespace CalamityMod.NPCs break; case NPCID.DyeTrader: - if (Main.rand.NextBool(5) && permadong != -1) - chat = CalamityUtils.GetText("Vanilla.DyeTraderChat.Archmage").Format(Main.npc[permadong].GivenName); + if (Main.rand.NextBool(5) && permafrost != -1) + chat = CalamityUtils.GetText("Vanilla.DyeTraderChat.Archmage").Format(Main.npc[permafrost].GivenName); else if (Main.rand.NextBool(5)) chat = CalamityUtils.GetTextValue("Vanilla.DyeTraderChat.Normal"); break; @@ -1009,8 +1009,8 @@ namespace CalamityMod.NPCs chat = CalamityUtils.GetTextValue("Vanilla.PainterChat.Crimson"); if (Main.rand.NextBool(4) && Main.LocalPlayer.ZoneSnow) { - if (Main.rand.NextBool() && permadong != -1) - chat = CalamityUtils.GetText("Vanilla.PainterChat.Archmage").Format(Main.npc[permadong].GivenName); + if (Main.rand.NextBool() && permafrost != -1) + chat = CalamityUtils.GetText("Vanilla.PainterChat.Archmage").Format(Main.npc[permafrost].GivenName); else chat = CalamityUtils.GetTextValue("Vanilla.PainterChat.Tundra"); } diff --git a/NPCs/CalamityVanillaAIOverrideNPC.cs b/NPCs/CalamityVanillaAIOverrideNPC.cs index 49fb2963e2..353c355c11 100644 --- a/NPCs/CalamityVanillaAIOverrideNPC.cs +++ b/NPCs/CalamityVanillaAIOverrideNPC.cs @@ -921,12 +921,14 @@ public sealed partial class CalamityVanillaAIOverrideNPC : GlobalNPC result &= GlobalPreAI(npc); if (AIOverride != null) { + result &= AIOverride.AI(Mod); + if (AIOverride.DisableMultiplayerSmoothing) { npc.netOffset = Vector2.Zero; + if (AIOverride.EnableMultiplayerSmoothingAheadOfAI) + AIOverride.DisableMultiplayerSmoothing = false; } - - result &= AIOverride.AI(Mod); } return result; } diff --git a/NPCs/DevourerofGods/DevourerofGodsHead.cs b/NPCs/DevourerofGods/DevourerofGodsHead.cs index 08de745aa7..cd2714ad1d 100644 --- a/NPCs/DevourerofGods/DevourerofGodsHead.cs +++ b/NPCs/DevourerofGods/DevourerofGodsHead.cs @@ -4,7 +4,6 @@ using System.IO; using CalamityMod.Buffs.StatDebuffs; using CalamityMod.Dusts; using CalamityMod.Events; -using CalamityMod.Graphics.Renderers.CalamityRenderers; using CalamityMod.Items.Armor.Vanity; using CalamityMod.Items.LoreItems; using CalamityMod.Items.Materials; @@ -33,6 +32,7 @@ using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; using Terraria; using Terraria.Audio; +using Terraria.DataStructures; using Terraria.GameContent; using Terraria.GameContent.Bestiary; using Terraria.GameContent.Events; @@ -304,6 +304,15 @@ namespace CalamityMod.NPCs.DevourerofGods rotation = NPC.rotation; } + public override void OnSpawn(IEntitySource source) + { + string key = "Mods.CalamityMod.Status.Boss.DoGSpawn"; + Color messageColor = Color.Cyan; + CalamityUtils.BroadcastLocalizedText(key, messageColor); + + DialogueDisplaySystem.StartDialogue("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 0, 120, false, new BossText()); + } + public override void SendExtraAI(BinaryWriter writer) { bool wasDyingBefore = Dying; @@ -634,7 +643,7 @@ namespace CalamityMod.NPCs.DevourerofGods player.Calamity().subtitletext = Main.combatText[ctid]; player.Calamity().subtitleColors = new Color[] { Color.Cyan, Color.Fuchsia }; */ - DialogueDisplaySystem.StartDialogue("DevourerOfGods.Phases", NPC, 2, 120, false, new BossText()); + DialogueDisplaySystem.StartDialogue("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 2, 120, false, new BossText()); } } @@ -811,7 +820,7 @@ namespace CalamityMod.NPCs.DevourerofGods player.Calamity().subtitletext = Main.combatText[ctid]; player.Calamity().subtitleColors = new Color[] { Color.Cyan, Color.Fuchsia }; */ - DialogueDisplaySystem.StartDialogue("DevourerOfGods.Phases", NPC, 3, 120, false, new BossText()); + DialogueDisplaySystem.StartDialogue("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 3, 120, false, new BossText()); } spawnedGuardians3 = true; @@ -1474,7 +1483,7 @@ namespace CalamityMod.NPCs.DevourerofGods player.Calamity().subtitletext = Main.combatText[ctid]; player.Calamity().subtitleColors = new Color[] { Color.Cyan, Color.Fuchsia }; */ - DialogueDisplaySystem.StartDialogue("DevourerOfGods.Phases", NPC, 1, 120, false, new BossText()); + DialogueDisplaySystem.StartDialogue("Mods.CalamityMod.DevourerOfGods.Phases", NPC, 1, 120, false, new BossText()); } NPC.TargetClosest(); @@ -2860,7 +2869,7 @@ namespace CalamityMod.NPCs.DevourerofGods target.Calamity().dogTextCooldown = 60; */ - DialogueDisplaySystem.StartDialogue(DialogueGroup, NPC, DialogueIndex, 60, false, new BossText()); + DialogueDisplaySystem.StartDialogueOnClient(DialogueGroup, NPC, DialogueIndex, 60, false, new BossText()); } target.Calamity().DoGHeadHitCounter++; } diff --git a/NPCs/Providence/Providence.cs b/NPCs/Providence/Providence.cs index 5cd463ed36..172e2d814e 100644 --- a/NPCs/Providence/Providence.cs +++ b/NPCs/Providence/Providence.cs @@ -28,6 +28,7 @@ using CalamityMod.Particles; using CalamityMod.Projectiles.Boss; using CalamityMod.Projectiles.Summon; using CalamityMod.Projectiles.Typeless; +using CalamityMod.Systems.Graphic; using CalamityMod.Tiles.Ores; using CalamityMod.Utilities.Daybreak; using CalamityMod.World; @@ -41,6 +42,7 @@ using Terraria.DataStructures; using Terraria.GameContent; using Terraria.GameContent.Bestiary; using Terraria.GameContent.ItemDropRules; +using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.Localization; using Terraria.ModLoader; @@ -249,6 +251,16 @@ namespace CalamityMod.NPCs.Providence public static int StarHeal = Main.expertMode ? 50 : 35; // HolyLight + public override void Load() + { + GeneralDrawLayerSystem.OnBeforeAllTiles += DrawHolyInferno; + } + + public override void Unload() + { + GeneralDrawLayerSystem.OnBeforeAllTiles -= DrawHolyInferno; + } + public override void SetDefaults() { NPC.npcSlots = 36f; @@ -2516,6 +2528,64 @@ namespace CalamityMod.NPCs.Providence } } + private static Asset DiagonalNoise => field ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/HarshNoise"); + private static Asset UpwardPerlinNoise => field ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/Perlin"); + private static Asset UpwardNoise => field ??= ModContent.Request("CalamityMod/ExtraTextures/GreyscaleGradients/MeltyNoise"); + + private static void DrawHolyInferno() + { + if (Main.gameMenu || !shouldDrawInfernoBorder) + return; + + if (CalamityGlobalNPC.holyBoss == -1) + return; + + var npc = Main.npc[CalamityGlobalNPC.holyBoss]; + var borderDistance = borderRadius; + if (!npc.active || !npc.HasValidTarget) + return; + + var target = Main.LocalPlayer; + var holyInfernoIntensity = target.Calamity().holyInfernoFadeIntensity; + var prov = npc.ModNPC(); + if (prov == null) + return; + + //Begin drawing the inferno + var blackTile = TextureAssets.MagicPixel; + + var maxOpacity = 1f; + if (prov.Dying) + { + //Death animation timer ends at 345f. + maxOpacity = MathHelper.Lerp(1f, 0f, Utils.GetLerpValue(0f, 344f, prov.DeathAnimationTimer)); + } + + var shader = GameShaders.Misc["CalamityMod:HolyInfernoShader"].Shader; + shader.Parameters["colorMult"].SetValue(prov.hasBeenGivenFullPower ? 7.65f : 7.35f); //I want you to know it took considerable restraint to deliberately misspell colour. + shader.Parameters["time"].SetValue(Main.GlobalTimeWrappedHourly); + shader.Parameters["radius"].SetValue(borderDistance); + shader.Parameters["anchorPoint"].SetValue(npc.Center); + shader.Parameters["screenPosition"].SetValue(Main.screenPosition); + shader.Parameters["screenSize"].SetValue(Main.ScreenSize.ToVector2()); + shader.Parameters["burnIntensity"].SetValue(holyInfernoIntensity); + shader.Parameters["playerPosition"].SetValue(target.Center); + shader.Parameters["maxOpacity"].SetValue(maxOpacity); + shader.Parameters["day"].SetValue(!prov.hasBeenGivenFullPower); + + Main.spriteBatch.GraphicsDevice.Textures[1] = DiagonalNoise.Value; + Main.spriteBatch.GraphicsDevice.Textures[2] = UpwardNoise.Value; + Main.spriteBatch.GraphicsDevice.Textures[3] = UpwardPerlinNoise.Value; + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, SamplerState.LinearWrap, DepthStencilState.None, Main.Rasterizer, shader, Main.Transform); + + Rectangle rekt = new(Main.screenWidth / 2, Main.screenHeight / 2, Main.screenWidth, Main.screenHeight); + Main.spriteBatch.Draw(blackTile.Value, rekt, null, default, 0f, blackTile.Value.Size() * 0.5f, 0, 0f); + + //Inferno drawing complete + Main.spriteBatch.End(); + } + public override bool? DrawHealthBar(byte hbPosition, ref float scale, ref Vector2 position) { scale = 2f; diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs index 25068326cc..6f210adc67 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainIllusion.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -30,6 +31,8 @@ public class BrainIllusion : ModNPC, ILocalizedModType ref float TeleportTime => ref NPC.ai[3]; + private Vector2 OldPos = Vector2.zeroVector; + public override void SetStaticDefaults() { this.HideFromBestiary(); @@ -92,16 +95,17 @@ public class BrainIllusion : ModNPC, ILocalizedModType { if (Time == 30) { - NPC.oldPos[0] = NPC.Center; + OldPos = NPC.Center; TeleportTime = 0; AttackValue = 0; NPC.Opacity = 1f; + NPC.netUpdate = true; } if (Time < 60) { float lerp = (Time - 30) / 30f; float circleDist = MathHelper.Lerp(BrainOfCthulhuAI.IllusionDashTeleportDistance, BrainOfCthulhuAI.IllusionDashCloseInDistance, CalamityUtils.SineInOutEasing(lerp, 1)); - NPC.Center = Vector2.Lerp(NPC.oldPos[0], target.Center + (Angle.ToRotationVector2() * circleDist), lerp); + NPC.Center = Vector2.Lerp(OldPos, target.Center + (Angle.ToRotationVector2() * circleDist), lerp); Angle += MathHelper.Lerp(0f, BrainOfCthulhuAI.IllusionDashStartingSpinSpeed, CalamityUtils.SineInEasing(lerp, 1)); } else if (Time <= 60f + BrainOfCthulhuAI.IllusionDashSpinDuration) @@ -133,6 +137,16 @@ public class BrainIllusion : ModNPC, ILocalizedModType Time++; } + public override void SendExtraAI(BinaryWriter writer) + { + writer.WritePackedWorldPosition(OldPos); + } + + public override void ReceiveExtraAI(BinaryReader reader) + { + OldPos = reader.ReadPackedWorldPosition(); + } + public override void FindFrame(int frameHeight) { NPC.frameCounter += 1.0; diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs index 1aba67f9bc..dd315cab0b 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuAI.cs @@ -10,8 +10,10 @@ using CalamityMod.Particles; using CalamityMod.Projectiles.Boss.BrainOfCthulhu; using CalamityMod.Utilities.Daybreak; using CalamityMod.World; +using Microsoft.CodeAnalysis; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Graphics.PackedVector; using ReLogic.Content; using Terraria; using Terraria.Audio; @@ -44,6 +46,8 @@ public class BrainOfCthulhuAI : VanillaAIOverride #region Balancing Values + internal static int BrainIllusionDamage => 15; + #region Projectile Damage Values internal static int BloodShotDamage => 12; // 48 internal static int BloodScytheDamage => 12; // 48 @@ -199,10 +203,10 @@ public class BrainOfCthulhuAI : VanillaAIOverride #endregion - internal enum BrainAIState + internal enum BrainAIState : byte { //Spawn Animation - UndergroundSpawnAnimation = -2, + UndergroundSpawnAnimation, SurfaceSpawnAnimation, //Phase 1 Phase1Idle, @@ -246,7 +250,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride internal bool AttackFlag = false; internal Vector2 AttackPosition = Vector2.Zero; internal List availableAttacks = []; - internal List AttackList = []; + internal List AttackList = []; private Player Target => Main.player[NPC.target]; @@ -263,10 +267,11 @@ public class BrainOfCthulhuAI : VanillaAIOverride private static float CreeperAmountRatio => NPC.CountNPCS(NPCID.Creeper) / (float)GetBrainOfCthuluCreepersCountRevDeath(); + public override bool EnableMultiplayerSmoothingAheadOfAI => true; + public override void SetDefaults(Mod mod) { - DisableMultiplayerSmoothing = true; - + NPC.damage = NPC.defDamage = 36; // 64 (1.8x expert scaling) BoCDrawOffset = Vector2.Zero; ShieldOpacity = 1f; ShieldScale = 1f; @@ -290,8 +295,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride public override void OnSpawn(Mod mod) { - DisableMultiplayerSmoothing = true; - if (NPC.target < 0 || NPC.target == Main.maxPlayers || Main.player[NPC.target].dead || !Main.player[NPC.target].active) { // Ignore tank players, target low HP players, Brain is smart @@ -304,6 +307,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride bool onSurface = target.Center.Y / 16 < Main.worldSurface; NPC.Center = target.Center + Vector2.UnitY * (onSurface ? 900 : -900); + DisableMultiplayerSmoothing = true; NPC.dontTakeDamage = true; AIState = onSurface ? BrainAIState.SurfaceSpawnAnimation : BrainAIState.UndergroundSpawnAnimation; @@ -337,13 +341,11 @@ public class BrainOfCthulhuAI : VanillaAIOverride else NPC.defense = (int)(NPC.defDefense * Phase1DefenseMultiplier); - if (AIState < 0) + if (AIState <= BrainAIState.SurfaceSpawnAnimation) NPC.damage = 0; else NPC.damage = NPC.defDamage; - bool death = CalamityWorld.death || BossRushEvent.BossRushActive; - #region Targeting if (NPC.target < 0 || NPC.target == Main.maxPlayers || Main.player[NPC.target].dead || !Main.player[NPC.target].active) { @@ -395,7 +397,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride #endregion #region Forced State Changes - if (!phase2 && CreeperHPRatio == 0f && AIState != BrainAIState.Stunned && AIState >= 0) + if (!phase2 && CreeperHPRatio == 0f && AIState != BrainAIState.Stunned && AIState >= BrainAIState.Phase1Idle) { AIState = BrainAIState.Stunned; Time = 0; @@ -617,27 +619,28 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (AttackCounter < GetBrainOfCthuluCreepersCountRevDeath()) { if (SpawnTime == 0) + { NPC.Center = Target.Center + Vector2.UnitY * (AIState == BrainAIState.UndergroundSpawnAnimation ? -900 : 900); + DisableMultiplayerSmoothing = true; + } if (SpawnDelay <= 0) { - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } - bool targetLeft = AttackCounter % 2 == 0; List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && n.AIOverride().CreeperID % 2 == (targetLeft ? 0 : 1)).ToList(); - int rand; if (creepers.Count > 0) + { rand = Main.rand.Next(creepers.Count); + foreach (NPC creeper in creepers) + creeper.netUpdate = true; + } else { creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1).ToList(); + foreach (NPC creeper in creepers) + creeper.netUpdate = true; rand = Main.rand.Next(creepers.Count); } @@ -721,12 +724,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride creep.AIOverride().Time = -1; NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } } #endregion @@ -814,7 +811,22 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (Time <= 60) { if (Time == 0) + { SoundEngine.PlaySound(Roar, NPC.Center); + + foreach(NPC creeper in Main.ActiveNPCs) + { + if (creeper.type != NPCID.Creeper) + continue; + + CreeperAI ai = creeper.AIOverride(); + Vector2 dir = Vector2.UnitX.RotatedBy(Main.rand.NextFloat(-MathHelper.TwoPi / 3f, MathHelper.TwoPi / 3f)) * (ai.evenID ? -1 : 1); + ai.AttackAngle = dir.ToRotation(); + float rayDist = CalamityUtils.PreciseDistanceToTileCollisionHit(NPC.Center, ai.AttackAngle, 800, 4); + ai.AttackPosition = NPC.Center + (dir * (rayDist - 64)); + creeper.netUpdate = true; + } + } if (Time < 30) { BrainOfCthulhuSystem.ScreenBlurStrength = 0.5f; @@ -1133,7 +1145,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (AttackFlag || Npc.AIOverride().CreeperID % 2 == 0! ^ useEven) { - AttackList.Add(Npc.whoAmI); + AttackList.Add((byte)Npc.whoAmI); //Npc.AIOverride().Time = 0; anyActivated = true; } @@ -1145,7 +1157,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (Npc.type != NPCID.Creeper) continue; - AttackList.Add(Npc.whoAmI); + AttackList.Add((byte)Npc.whoAmI); //Npc.AIOverride().Time = 0; } @@ -1233,7 +1245,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (Time > delay) { - foreach (NPC creeper in Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && !AttackList.Contains(n.whoAmI))) + foreach (NPC creeper in Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && !AttackList.Contains((byte)n.whoAmI))) creeper.position += NPC.velocity; int crushCount; @@ -1252,7 +1264,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (Time < delay + attackDur && Time % attackDelay == 0) { - List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && !AttackList.Contains(n.whoAmI)).ToList(); + List creepers = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && n.AIOverride().Time == -1 && !AttackList.Contains((byte)n.whoAmI)).ToList(); if (creepers.Count > 1) { float rotation; @@ -1268,15 +1280,17 @@ public class BrainOfCthulhuAI : VanillaAIOverride int rand = Main.rand.Next(creepers.Count); NPC first = creepers[rand]; + first.netUpdate = true; CreeperAI creeper1 = first.AIOverride(); - AttackList.Add(first.whoAmI); + AttackList.Add((byte)first.whoAmI); //creeper1.Time = 0; creeper1.AttackAngle = rotation; creepers.RemoveAt(rand); NPC second = creepers[Main.rand.Next(creepers.Count)]; + second.netUpdate = true; CreeperAI creeper2 = second.AIOverride(); - AttackList.Add(second.whoAmI); + AttackList.Add((byte)second.whoAmI); //creeper2.Time = 0; creeper2.AttackAngle = rotation + MathHelper.Pi; @@ -1285,12 +1299,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride } NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } } if (Time > delay + attackDur + attackDelay) @@ -1298,8 +1306,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride Time = 0; AIState = BrainAIState.Phase1Idle; AttackList.Clear(); - //foreach (NPC creep in Main.npc.Where(n => n.active && n.type == NPCID.Creeper)) - // creep.AIOverride().Time = -1; } } } @@ -1319,13 +1325,19 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (Time == 0) { AttackSign = Main.rand.NextBool() ? -1 : 1; + AttackPosition = Target.Center; NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } + } + + if (Time < OrbitSetupDuration) + { + AttackPosition = Target.Center; + } + else + { + float prox = Target.DistanceSQ(AttackPosition); + if (prox > 65536) //256^2 + AttackPosition += Target.DirectionFrom(AttackPosition) * (((float)Math.Sqrt(prox) - 256) / 16f); } if (Time >= OrbitDuration + 30) @@ -1350,36 +1362,23 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (rand >= creepers.Count) rand -= creepers.Count; NPC creeper = creepers[rand]; - AttackList.Add(creeper.whoAmI); + AttackList.Add((byte)creeper.whoAmI); //creeper.AIOverride().Time = 0; rand += (int)Math.Round(creepers.Count / (float)OrbitAttackParticipantCount); } NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } } } } private void CreeperSpiral() { - if (Time == 0) { AttackSign = Main.rand.NextBool() ? -1 : 1; AttackRotation = 0; NPC.netUpdate = true; - foreach (NPC creeper in Main.ActiveNPCs) - { - if (creeper.type != NPCID.Creeper) - continue; - creeper.netUpdate = true; - } } float startTimePerRev = MathHelper.Lerp(StartingTimePerRevolutionMax, StartingTimePerRevolutionMin, 1 - CreeperAmountRatio); float endTimePerRev = MathHelper.Lerp(EndingTimePerRevolutionMax, EndingTimePerRevolutionMin, 1 - CreeperAmountRatio); @@ -1569,6 +1568,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride { Vector2 start = NPC.Center; NPC.Center = endPoint; + DisableMultiplayerSmoothing = true; AttackFlag = true; NPC.netUpdate = true; } @@ -1719,6 +1719,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride float waveValue = Time * MathHelper.Pi / BloodshotRate; Vector2 goalPos = Target.Center + new Vector2((float)Math.Cos(waveValue) * HoverDistance.X * AttackSign, (float)(-0.5f * Math.Cos(2 * waveValue) + 0.5f) * -HoverDistance.Y); NPC.velocity = Vector2.Zero; + DisableMultiplayerSmoothing = true; if (Time < 30f) NPC.Center = Vector2.Lerp(AttackPosition, goalPos, CalamityUtils.SineOutEasing(Time / 30f, 1)); else @@ -1833,6 +1834,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride { Vector2 start = NPC.Center; NPC.Center = endPoint; + DisableMultiplayerSmoothing = true; AttackFlag = true; NPC.netUpdate = true; } @@ -2099,9 +2101,12 @@ public class BrainOfCthulhuAI : VanillaAIOverride float rot = AttackRotation + (CalamityWorld.death ? MathHelper.PiOver4 : MathHelper.PiOver2) * i; Vector2 spawnPos = AttackPosition + (rot.ToRotationVector2() * IllusionDashTeleportDistance); if (i == 0) + { NPC.Center = spawnPos; + DisableMultiplayerSmoothing = true; + } else if (Main.netMode != NetmodeID.MultiplayerClient) - NPC.NewNPCDirect(NPC.GetSource_FromThis(), spawnPos, ModContent.NPCType(), 0, 15, 30, rot).netUpdate = true; + NPC.NewNPCDirect(NPC.GetSource_FromThis(), spawnPos, ModContent.NPCType(), 0, BrainIllusionDamage, 30, rot).netUpdate = true; } NPC.netUpdate = true; @@ -2140,11 +2145,12 @@ public class BrainOfCthulhuAI : VanillaAIOverride float circleDist = MathHelper.Lerp(IllusionDashTeleportDistance, IllusionDashCloseInDistance, CalamityUtils.SineOutEasing(lerp, 1)); NPC.Center = Vector2.Lerp(AttackPosition, Target.Center + (AttackRotation.ToRotationVector2() * circleDist), lerp); AttackRotation += MathHelper.Lerp(0f, IllusionDashStartingSpinSpeed, CalamityUtils.SineInEasing(lerp, 1)); + DisableMultiplayerSmoothing = true; } else if (startTime <= 30 + IllusionDashSpinDuration) { NPC.Center = Target.Center + AttackRotation.ToRotationVector2() * IllusionDashCloseInDistance; - + DisableMultiplayerSmoothing = true; AttackRotation += MathHelper.Lerp(IllusionDashStartingSpinSpeed, 0f, CalamityUtils.SineOutEasing((startTime - 30) / (float)IllusionDashSpinDuration, 1)); } else if (startTime < 30 + IllusionDashSpinDuration + 30) @@ -2198,6 +2204,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride { AttackFlag = true; NPC.Center = endPoint; + DisableMultiplayerSmoothing = true; } else { @@ -2284,13 +2291,6 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (AttackCounter == 0) { NPC.ShowNameOnHover = true; - foreach (NPC npc in Main.npc) - { - if (npc.type != ModContent.NPCType()) - continue; - npc.ModNPC().BeenHit = true; - } - NPC.velocity = NPC.DirectionFrom(Target.Center) * 8f; } else @@ -2316,7 +2316,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride if (p.Distance(NPC.Center) > DespawnRange) continue; - AttackList.Add(p.whoAmI); + AttackList.Add((byte)p.whoAmI); } foreach (NPC n in Main.ActiveNPCs) @@ -2379,6 +2379,7 @@ public class BrainOfCthulhuAI : VanillaAIOverride NPC.Center = AttackPosition + Vector2.UnitX.RotatedBy(AttackRotation) * (baseDist + (circleDist * ((float)Math.Sin(-AttackTime * MathHelper.TwoPi / FalseBrain.TimeDivisor) / 2f + 0.5f))); NPC.Center += Vector2.UnitX.RotatedBy(AttackRotation + MathHelper.PiOver2) * (90 * (float)Math.Cos(AttackTime * MathHelper.TwoPi / FalseBrain.TimeDivisor)); NPC.Opacity = 1f; + DisableMultiplayerSmoothing = true; AttackCounter = 0; } } @@ -2515,13 +2516,19 @@ public class BrainOfCthulhuAI : VanillaAIOverride public override void SendExtraAI(BitWriter bitWriter, BinaryWriter binaryWriter) { - binaryWriter.Write((int)PreviousAttack); + binaryWriter.Write((byte)PreviousAttack); - binaryWriter.Write(TeleportTime); - binaryWriter.Write(TeleportDuration); + if (AIState == BrainAIState.Stunned || AIState >= BrainAIState.Phase2TransitionClosed) + { + binaryWriter.Write(TeleportTime); + binaryWriter.Write(TeleportDuration); + } - binaryWriter.Write(SpawnTime); - binaryWriter.Write(SpawnDelay); + if (AIState <= BrainAIState.SurfaceSpawnAnimation) + { + binaryWriter.Write(SpawnTime); + binaryWriter.Write(SpawnDelay); + } binaryWriter.Write(CachedRatio); @@ -2531,26 +2538,31 @@ public class BrainOfCthulhuAI : VanillaAIOverride binaryWriter.Write(AttackTime); binaryWriter.Write(AttackCounter); - binaryWriter.WritePackedVector2(AttackPosition); + binaryWriter.WritePackedWorldPosition(AttackPosition); - binaryWriter.Write(availableAttacks.Count); - for (int i = 0; i < availableAttacks.Count; i++) - binaryWriter.Write((int)availableAttacks[i]); + binaryWriter.Write((byte)availableAttacks.Count); - binaryWriter.Write(AttackList.Count); - for (int i = 0; i < AttackList.Count; i++) - binaryWriter.Write(AttackList[i]); + binaryWriter.Write(availableAttacks.Select(e => (byte)e).ToArray()); + + binaryWriter.Write((byte)AttackList.Count); + binaryWriter.Write(AttackList.ToArray()); } public override void ReceiveExtraAI(BitReader bitReader, BinaryReader binaryReader) { - PreviousAttack = (BrainAIState)binaryReader.ReadInt32(); + PreviousAttack = (BrainAIState)binaryReader.ReadByte(); - TeleportTime = binaryReader.ReadSingle(); - TeleportDuration = binaryReader.ReadSingle(); + if (AIState == BrainAIState.Stunned || AIState >= BrainAIState.Phase2TransitionClosed) + { + TeleportTime = binaryReader.ReadSingle(); + TeleportDuration = binaryReader.ReadSingle(); + } - SpawnTime = binaryReader.ReadSingle(); - SpawnDelay = binaryReader.ReadInt32(); + if (AIState <= BrainAIState.SurfaceSpawnAnimation) + { + SpawnTime = binaryReader.ReadSingle(); + SpawnDelay = binaryReader.ReadInt32(); + } CachedRatio = binaryReader.ReadSingle(); @@ -2560,17 +2572,13 @@ public class BrainOfCthulhuAI : VanillaAIOverride AttackTime = binaryReader.ReadSingle(); AttackCounter = binaryReader.ReadInt32(); - AttackPosition = binaryReader.ReadPackedVector2(); + AttackPosition = binaryReader.ReadPackedWorldPosition(); - int availableLength = binaryReader.ReadInt32(); - availableAttacks.Clear(); - for (int i = 0; i < availableLength; i++) - availableAttacks.Add((BrainAIState)binaryReader.ReadInt32()); + int availableLength = binaryReader.ReadByte(); + availableAttacks = binaryReader.ReadBytes(availableLength).Select(e => (BrainAIState)e).ToList(); - int attackLength = binaryReader.ReadInt32(); - AttackList.Clear(); - for (int i = 0; i < attackLength; i++) - AttackList.Add(binaryReader.ReadSingle()); + byte attackLength = binaryReader.ReadByte(); + AttackList = binaryReader.ReadBytes(attackLength).ToList(); } public override bool? CanBeHitByProjectile(Mod mod, Projectile projectile) @@ -2606,17 +2614,18 @@ public class BrainOfCthulhuAI : VanillaAIOverride AIState = BrainAIState.DeathAnimation; ResetAttackValues(); Time = 0; + NPC.netUpdate = true; return; } if (AIState == BrainAIState.IllusionTrick && Time < 960) + { AttackFlag = true; + NPC.netUpdate = true; + } } - public override bool PreKill(Mod mod) - { - return AIState == BrainAIState.DeathAnimation && !NPC.dontTakeDamage; - } + public override bool PreKill(Mod mod) => AIState == BrainAIState.DeathAnimation && !NPC.dontTakeDamage; public override void FindFrame(Mod mod, int frameHeight) { diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs index 90abd9d40a..a4cc06eb76 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/BrainOfCthulhuSystem.cs @@ -48,13 +48,12 @@ public class BrainOfCthulhuSystem : ModSystem { orig(self); - if (NPC.crimsonBoss == -1 || !CalamityWorld.revenge) + if (NPC.crimsonBoss == -1 || !CalamityWorld.revenge || !Main.npc[NPC.crimsonBoss].active || !Main.npc[NPC.crimsonBoss].TryGetAIOverride(out var brainAI)) return; if (previousMusic < 0 || previousMusic >= Main.musicFade.Length) return; - var brainAI = Main.npc[NPC.crimsonBoss].AIOverride(); // The last part leaves one frame at the end of the spawn animation where the boss music starts playing, so that it can be instantly maxed out if (brainAI.AIState < 0 && (brainAI.Time - Math.Abs(brainAI.SpawnTime) < 420)) { diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs index 049c25e75c..f3b605ad05 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/CreeperAI.cs @@ -46,7 +46,7 @@ public class CreeperAI : VanillaAIOverride float bossCounter => bocAI.Time; - bool evenID => CreeperID % 2 == 0; + internal bool evenID => CreeperID % 2 == 0; int creeperCount { @@ -65,6 +65,13 @@ public class CreeperAI : VanillaAIOverride bool useBossAIState = true; + public override bool EnableMultiplayerSmoothingAheadOfAI => true; + + public override void SetDefaults(Mod mod) + { + NPC.damage = NPC.defDamage = 36; // 64 (1.8x expert scaling) + } + public override bool AI(Mod mod) { #region Despawn @@ -213,29 +220,18 @@ public class CreeperAI : VanillaAIOverride private void TelekineticOnslaught() { - if (Time == 0 || AttackPosition == Vector2.Zero) - { - Vector2 dir = Vector2.UnitX.RotatedBy(Main.rand.NextFloat(-MathHelper.TwoPi / 3f, MathHelper.TwoPi / 3f)) * (evenID ? -1 : 1); - AttackAngle = dir.ToRotation(); - float rayDist = CalamityUtils.PreciseDistanceToTileCollisionHit(brain.Center, AttackAngle, 800, 4); - AttackPosition = (dir * (rayDist - 64)); - NPC.netUpdate = true; - } - if (Time > 0) { - Vector2 goalLocation = brain.Center + AttackPosition; - - if (WorldGen.SolidOrSlopedTile(goalLocation.ToTileCoordinates().X, goalLocation.ToTileCoordinates().Y)) + Point tileCoords = AttackPosition.ToTileCoordinates(); + if (WorldGen.SolidOrSlopedTile(tileCoords.X, tileCoords.Y)) { float rayDist = CalamityUtils.PreciseDistanceToTileCollisionHit(brain.Center, AttackAngle, 800, 4); - AttackPosition = (AttackAngle.ToRotationVector2() * (rayDist - 64)); - goalLocation = brain.Center + AttackPosition; + AttackPosition = brain.Center + (AttackAngle.ToRotationVector2() * (rayDist - 64)); } - if (NPC.DistanceSQ(goalLocation) > 4096) + if (NPC.DistanceSQ(AttackPosition) > 4096) { - NPC.velocity += NPC.DirectionTo(goalLocation); + NPC.velocity += NPC.DirectionTo(AttackPosition); NPC.velocity = NPC.velocity.ClampMagnitude(0f, 10f); } else @@ -259,7 +255,7 @@ public class CreeperAI : VanillaAIOverride AIState = CreeperAIState.Idle; } - if (brain.AIOverride().AttackList.Contains(NPC.whoAmI)) + if (brain.AIOverride().AttackList.Contains((byte)NPC.whoAmI)) { if (Time < 0) Time = 0; @@ -329,6 +325,7 @@ public class CreeperAI : VanillaAIOverride goalLocation.X += MathHelper.Lerp(0f, 900f, CalamityUtils.SineInOutEasing(MathHelper.Clamp((Time - (brain.AIOverride().SwipeDelay + 5)) / 55f, 0f, 1f), 1)) * (handSide == -1 ? 1 : -1); NPC.Center = Vector2.Lerp(NPC.Center, goalLocation, MathHelper.Clamp((Time - brain.AIOverride().SwipeDelay) / 10f, 0f, 1f)); + DisableMultiplayerSmoothing = true; } Time++; @@ -337,10 +334,14 @@ public class CreeperAI : VanillaAIOverride private void CreeperSwings() { - if (brain.AIOverride().AttackList.Contains(NPC.whoAmI)) + if (brain.AIOverride().AttackList.Contains((byte)NPC.whoAmI)) { if (Time < 0) + { Time = 0; + NPC.netUpdate = true; + AttackPosition = NPC.Center; + } } else { @@ -370,12 +371,11 @@ public class CreeperAI : VanillaAIOverride if (Time <= positioningTime) { - if (AttackPosition == Vector2.Zero) - AttackPosition = NPC.Center; Vector2 goalPosition = sharedTarget.Center - dashDir * 128; goalPosition += dashDir.RotatedBy(MathHelper.PiOver2) * 16; NPC.Center = Vector2.Lerp(AttackPosition, goalPosition, CalamityUtils.SineOutEasing(MathHelper.Clamp(Time / (float)LightSwipeTravelTime, 0f, 1f), 1)); NPC.velocity = Vector2.Zero; + DisableMultiplayerSmoothing = true; } else { @@ -404,7 +404,7 @@ public class CreeperAI : VanillaAIOverride { NPC.damage = 0; Time = -1; - brain.AIOverride().AttackList.Remove(NPC.whoAmI); + brain.AIOverride().AttackList.Remove((byte)NPC.whoAmI); AttackPosition = Vector2.Zero; ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0f); return; @@ -423,6 +423,7 @@ public class CreeperAI : VanillaAIOverride Vector2 goalPosition = sharedTarget.Center - dashDir * 128; NPC.Center = Vector2.Lerp(AttackPosition, goalPosition, CalamityUtils.SineOutEasing(MathHelper.Clamp(Time / (float)StrongSwipeTravelTime, 0f, 1f), 1)); NPC.velocity = Vector2.Zero; + DisableMultiplayerSmoothing = true; } else { @@ -452,6 +453,7 @@ public class CreeperAI : VanillaAIOverride float moveDist = 196; NPC.Center = Vector2.Lerp(AttackPosition, AttackPosition + dashDir * moveDist, (Time - (positioningTime + reelbackTime)) / swingTime); NPC.velocity = Vector2.Zero; + DisableMultiplayerSmoothing = true; if (Time == (positioningTime + reelbackTime + swingTime)) { SoundEngine.PlaySound(SoundID.DD2_MonkStaffGroundImpact, NPC.Center); @@ -481,7 +483,7 @@ public class CreeperAI : VanillaAIOverride { NPC.damage = 0; Time = -1; - brain.AIOverride().AttackList.Remove(NPC.whoAmI); + brain.AIOverride().AttackList.Remove((byte)NPC.whoAmI); AttackPosition = Vector2.Zero; ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 0.5f); return; @@ -500,13 +502,17 @@ public class CreeperAI : VanillaAIOverride { CachedValue1 = MathHelper.TwoPi / creeperCount * localCreeperID; AttackAngle = 0; + NPC.netUpdate = true; } float dist = OrbitStandardRadius + ((float)Math.Sin((CachedValue1 * 7) + bossCounter / 20f) * 24); - if (brain.AIOverride().AttackList.Contains(NPC.whoAmI)) + if (brain.AIOverride().AttackList.Contains((byte)NPC.whoAmI)) { if (Time < 0) + { Time = 0; + NPC.netUpdate = true; + } } else { @@ -528,7 +534,7 @@ public class CreeperAI : VanillaAIOverride if (Time > OrbitAttackInterval) { Time = -2; - brain.AIOverride().AttackList.Remove(NPC.whoAmI); + brain.AIOverride().AttackList.Remove((byte)NPC.whoAmI); } } ConnectionOpacity = BringOpacityTo(ConnectionOpacity, 1f, 0.1f); @@ -540,38 +546,21 @@ public class CreeperAI : VanillaAIOverride float slowDown = (1 - MathHelper.Clamp((bossCounter - OrbitDuration) / 30f, 0f, 1f)); AttackAngle += (BaseRotationSpeed * (MathHelper.Lerp(1f, 0.5f, CreeperAmountRatio) + (bocAI.OnSecondCreeperPhase ? 1f : 0.5f))) * slowDown * bocAI.AttackSign; Vector2 rotation = Vector2.UnitX.RotatedBy(CachedValue1 + AttackAngle) * dist; - Player target = Main.player[brain.target]; if (bossCounter < OrbitSetupDuration) { NPC.damage = 0; - + if (bossCounter == 0) AttackPosition = NPC.Center; - Vector2 goalLocation = target.Center + rotation; - if (bossCounter < OrbitSetupDuration) - NPC.Center = Vector2.Lerp(AttackPosition, goalLocation, CalamityUtils.SineOutEasing(bossCounter / OrbitSetupDuration, 1)); - else - NPC.Center = goalLocation; + NPC.Center = Vector2.Lerp(AttackPosition, bocAI.AttackPosition + rotation, CalamityUtils.SineOutEasing(bossCounter / OrbitSetupDuration, 1)); + DisableMultiplayerSmoothing = true; } else { NPC.damage = NPC.defDamage; - - if (bossCounter <= OrbitSetupDuration + 10) - { - float lerp = CalamityUtils.SineOutEasing((bossCounter - OrbitSetupDuration) / 10f, 1); - AttackPosition = Vector2.Lerp(target.Center, AttackPosition, lerp); - } - else - { - float prox = target.Distance(AttackPosition); - if (prox > 256) - AttackPosition += target.DirectionFrom(AttackPosition) * ((prox - 256) / 16f); - } - - Vector2 goalLocation = AttackPosition + rotation; - NPC.Center = goalLocation; + NPC.Center = bocAI.AttackPosition + rotation; + DisableMultiplayerSmoothing = true; } } @@ -581,11 +570,12 @@ public class CreeperAI : VanillaAIOverride if (bossCounter == 0) { - AttackPosition = Vector2.Zero; + AttackPosition = NPC.Center; List myGroup = Main.npc.Where(n => n.active && n.type == NPCID.Creeper && (n.ai[0] % TendrilCount) + 1 == tendrilID).ToList(); CachedValue1 = myGroup.IndexOf(NPC); CachedValue2 = myGroup.Count; AttackAngle = 0; + NPC.netUpdate = true; } int index = (int)CachedValue1; @@ -606,6 +596,7 @@ public class CreeperAI : VanillaAIOverride if (bossCounter >= SpiralSetupTime) { NPC.Center = position; + DisableMultiplayerSmoothing = true; NPC.damage = NPC.defDamage; NPC.knockBackResist = 0f; @@ -616,11 +607,10 @@ public class CreeperAI : VanillaAIOverride NPC.velocity *= 0.66f; else { - if (AttackPosition == Vector2.Zero) - AttackPosition = NPC.Center; NPC.velocity = Vector2.Zero; float lerp = (bossCounter - (SpiralSetupTime / 10f)) / (float)(SpiralSetupTime * 0.9f); NPC.Center = Vector2.Lerp(AttackPosition, position, CalamityUtils.SineInOutEasing(MathHelper.Clamp(lerp, 0f, 1f), 1)); + DisableMultiplayerSmoothing = true; } } @@ -703,8 +693,7 @@ public class CreeperAI : VanillaAIOverride binaryWriter.Write(CachedValue2); binaryWriter.Write(PartnerIndex); - binaryWriter.WritePackedVector2(AttackPosition); - + binaryWriter.WritePackedWorldPosition(AttackPosition); } public override void ReceiveExtraAI(BitReader bitReader, BinaryReader binaryReader) @@ -713,7 +702,7 @@ public class CreeperAI : VanillaAIOverride CachedValue2 = binaryReader.ReadInt32(); PartnerIndex = binaryReader.ReadInt32(); - AttackPosition = binaryReader.ReadPackedVector2(); + AttackPosition = binaryReader.ReadPackedWorldPosition(); } public override void HitEffect(Mod mod, NPC.HitInfo hit) diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs index 3fadf10671..5e7beed8f4 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/BrainOfCthulhu/FalseBrain.cs @@ -70,6 +70,9 @@ public class FalseBrain : ModNPC, ILocalizedModType NPC brain = Main.npc[NPC.crimsonBoss]; NPC.GivenName = brain.GivenOrTypeName + $": {brain.life}/{brain.lifeMax}"; + if (brain.AIOverride().AttackFlag) + BeenHit = true; + if (BeenHit) { NPC.dontTakeDamage = true; diff --git a/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs b/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs index f43a9e772c..44d52c8a76 100644 --- a/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs +++ b/NPCs/VanillaNPCAIOverrides/Bosses/DeerclopsAI.cs @@ -1,12 +1,16 @@ using System; using CalamityMod.Events; +using CalamityMod.Systems.Graphic; using CalamityMod.World; using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.Audio; using Terraria.DataStructures; using Terraria.Enums; +using Terraria.GameContent; using Terraria.Graphics.CameraModifiers; +using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.ModLoader; @@ -31,6 +35,67 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides.Bosses public static int IceSpikeDamage = 16; // 64 (buffed from 52) public static int HandDamage = 13; // 52 (buffed from 40) + public override void Load() + { + GeneralDrawLayerSystem.OnAfterEverything += DrawDeerclopsShadow; + } + + public override void Unload() + { + GeneralDrawLayerSystem.OnAfterEverything -= DrawDeerclopsShadow; + } + + private static void DrawDeerclopsShadow() + { + if (Main.gameMenu) + return; + + bool shouldDraw; + var deerclopsInactive = false; + if (NPC.deerclopsBoss >= 0 && NPC.deerclopsBoss.WithinBounds(Main.npc.Length)) + { + shouldDraw = Main.npc[NPC.deerclopsBoss].HasValidTarget; + } + else + { + shouldDraw = borderScalar > 0f; + deerclopsInactive = true; + } + + if (shouldDraw) + { + var minRadius = innerBorder; + var maxRadius = outerBorder; + + // Begin drawing the shadow + var blackTile = TextureAssets.MagicPixel; + + var shader = GameShaders.Misc["CalamityMod:DeerclopsShadowShader"].Shader; + shader.Parameters["minRadius"].SetValue(minRadius); + shader.Parameters["maxRadius"].SetValue(maxRadius); + shader.Parameters["anchorPoint"].SetValue(lastDeerclopsPosition); + shader.Parameters["screenPosition"].SetValue(Main.screenPosition); + shader.Parameters["screenSize"].SetValue(Main.ScreenSize.ToVector2()); + shader.Parameters["maxOpacity"].SetValue(borderScalar); + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, shader, Main.Transform); + + Rectangle rekt = new(Main.screenWidth / 2, Main.screenHeight / 2, Main.screenWidth, Main.screenHeight); + Main.spriteBatch.Draw(blackTile.Value, rekt, null, default, 0f, blackTile.Value.Size() * 0.5f, 0, 0f); + + // Shadow drawing complete + Main.spriteBatch.End(); + } + + if (deerclopsInactive) + { + // Push the border away and fade out when deerclops is deadge + borderScalar = MathHelper.Clamp(borderScalar - 0.015f, 0f, 1f); + innerBorder += 30f; + outerBorder += 30f; + } + } + public override bool AI(Mod mod) { CalamityGlobalNPC calamityGlobalNPC = NPC.Calamity(); diff --git a/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs b/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs index f3317441c4..13fb90fdc4 100644 --- a/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs +++ b/NPCs/VanillaNPCAIOverrides/VanillaAIOverride.cs @@ -4,7 +4,6 @@ using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ModLoader; using Terraria.ModLoader.IO; -using Terraria.WorldBuilding; namespace CalamityMod.NPCs.VanillaNPCAIOverrides { @@ -12,17 +11,23 @@ namespace CalamityMod.NPCs.VanillaNPCAIOverrides { public NPC NPC { get; set; } public bool DisableMultiplayerSmoothing { get; set; } + public virtual bool EnableMultiplayerSmoothingAheadOfAI => false; - public void Load(Mod mod) + void ILoadable.Load(Mod mod) { CalamityVanillaAIOverrideNPC.RegisterNetID(this); + Load(); } - public void Unload() + void ILoadable.Unload() { - + Unload(); } + public virtual void Load() { } + + public virtual void Unload() { } + public abstract bool AI(Mod mod); public virtual void SetDefaults(Mod mod) { } diff --git a/Packets/StartDialogueDisplayPacket.cs b/Packets/StartDialogueDisplayPacket.cs new file mode 100644 index 0000000000..a96cbdd738 --- /dev/null +++ b/Packets/StartDialogueDisplayPacket.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CalamityMod.Items.Weapons.Ranged; +using CalamityMod.Systems; +using CalamityMod.UI.DialogueDisplay.DisplayEffects; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; +using Terraria.ID; +using Terraria.ModLoader.IO; +using Terraria.Net; +using static CalamityMod.UI.DialogueDisplay.DialogueDisplaySystem; + +namespace CalamityMod.Packets +{ + internal sealed class StartDialogueDisplayPacket : CalamityPacket + { + public static StartDialogueDisplayPacket Instance { get; private set; } + + public override byte MessageType => (byte)CalamityModMessageType.DialogueDisplayStart; + + public static void Send(string name, bool progressDialogue, Vector2 position, int index, int uptime, DisplayEffectID effect, float wrapWidth, int toClient = -1, int ignoreClient = -1) + { + // Only Server should send Reponse to Clients + if (!Main.dedServ) + return; + + var packet = Instance.CreateBasePacket(); + + packet.Write(name); + packet.WriteFlags(progressDialogue, false); + packet.WritePackedVector2(position); + packet.Write(index); + packet.Write(uptime); + packet.Write((byte)effect); + packet.Write(wrapWidth); + + packet.Send(toClient, ignoreClient); + } + + public enum EntityType : byte + { + NPC, + Player, + Projectile + } + + public static void Send(string name, bool progressDialogue, EntityType type, int entity, int index, int uptime, DisplayEffectID effect, float wrapWidth, int toClient = -1, int ignoreClient = -1) + { + // Only Server should send Reponse to Clients + if (!Main.dedServ) + return; + + var packet = Instance.CreateBasePacket(); + + packet.Write(name); + packet.WriteFlags(progressDialogue, true); + packet.Write((byte)type); + packet.Write(entity); + packet.Write(index); + packet.Write(uptime); + packet.Write((byte)effect); + packet.Write(wrapWidth); + + packet.Send(toClient, ignoreClient); + } + + public override void HandlePacket(in BinaryReader packet, int sender) + { + // Only receive info as clients + + string name = packet.ReadString(); + packet.ReadFlags(out bool progressDialogue, out bool hasEntity); + + int entity = -1; + Vector2 pos = Vector2.zeroVector; + EntityType type = EntityType.NPC; + if (hasEntity) + { + type = (EntityType)packet.ReadByte(); + entity = packet.ReadInt32(); + } + else + pos = packet.ReadPackedVector2(); + + int index = packet.ReadInt32(); + int uptime = packet.ReadInt32(); + byte effect = packet.ReadByte(); + float wrapWidth = packet.ReadSingle(); + + if (Main.netMode != NetmodeID.MultiplayerClient) + return; + + DisplayEffect de = GetEffect((DisplayEffectID)effect); + + if (hasEntity) + { + Entity e = type switch + { + EntityType.NPC => Main.npc[entity], + EntityType.Player => Main.player[entity], + EntityType.Projectile => Main.projectile.FirstOrDefault(p => p.identity == entity), + _ => null + }; + + StartDialogueOnClient(name, e, index, uptime, progressDialogue, de, wrapWidth); + } + else + StartDialogueOnClient(name, pos, index, uptime, progressDialogue, de, wrapWidth); + + } + } + +} diff --git a/Particles/DeathAshParticle.cs b/Particles/DeathAshParticle.cs index f600b156ca..98d0553b5d 100644 --- a/Particles/DeathAshParticle.cs +++ b/Particles/DeathAshParticle.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using CalamityMod.Graphics; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -10,7 +11,7 @@ namespace CalamityMod.Particles { public class DeathAshParticle { - internal static Dictionary PendingNPCsToDraw = new(); + internal static Dictionary PendingNPCsToDraw = new(); internal static BasicEffect basicShader = null; internal static VertexPositionColorTexture[] VertexCache = new VertexPositionColorTexture[PrimitiveBatchSize * 4]; internal static short[] IndexCache = new short[PrimitiveBatchSize * 6]; @@ -65,23 +66,22 @@ namespace CalamityMod.Particles Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); // Draw the NPC to the temporary render target so that all of its drawcode is localized, and then get the colors from the results. - Main.instance.GraphicsDevice.SetRenderTarget(PendingNPCsToDraw[npc]); - Main.instance.GraphicsDevice.Clear(Color.Transparent); - - Vector2 oldPosition = npc.position; - npc.oldPos = new Vector2[npc.oldPos.Length]; - npc.position = Main.screenPosition + new Vector2(Main.screenWidth, Main.screenHeight) * 0.5f; - try + using (PendingNPCsToDraw[npc].Scope(clearColor: Color.Transparent)) { - Main.instance.DrawNPC(npc.whoAmI, true); - } - catch { } - npc.position = oldPosition; - npc.Opacity = 0f; + Vector2 oldPosition = npc.position; + npc.oldPos = new Vector2[npc.oldPos.Length]; + npc.position = Main.screenPosition + new Vector2(Main.screenWidth, Main.screenHeight) * 0.5f; + try + { + Main.instance.DrawNPC(npc.whoAmI, true); + } + catch { } + npc.position = oldPosition; + npc.Opacity = 0f; - Main.spriteBatch.End(); + Main.spriteBatch.End(); + } } - Main.instance.GraphicsDevice.SetRenderTarget(null); } public static void CreateAshesFromNPC(NPC npc, Vector2 velocityOverride) @@ -91,7 +91,7 @@ namespace CalamityMod.Particles return; VelOverride = velocityOverride; - PendingNPCsToDraw[npc] = new(true, ManagedRenderTarget.CreateScreenSizedTarget); + PendingNPCsToDraw[npc] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); } public static Dictionary GetColorCacheFromTexture(Texture2D texture, Rectangle? frame = null, bool pruneForEfficency = false) diff --git a/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs b/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs index 0676297cc8..7c69c9d96e 100644 --- a/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs +++ b/Projectiles/Boss/BrainOfCthulhu/TelekineticEnemyGrab.cs @@ -180,24 +180,26 @@ public class TelekineticEnemyGrab : ModProjectile, ILocalizedModType { writer.Write(throwSign); - writer.WritePackedVector2(throwPos); + writer.WriteVector2(throwPos); - writer.WritePackedVector2(holdPos); + writer.WriteVector2(holdPos); } public override void ReceiveExtraAI(BinaryReader reader) { throwSign = reader.ReadInt32(); - throwPos = reader.ReadPackedVector2(); + throwPos = reader.ReadVector2(); - holdPos = reader.ReadPackedVector2(); + holdPos = reader.ReadVector2(); } - public override bool OnTileCollide(Vector2 oldVelocity) + public override bool OnTileCollide(Vector2 oldVelocity) => true; + + public override void OnKill(int timeLeft) { Vector2 velocity = Projectile.velocity.RotatedBy(MathHelper.Pi) / 8f; - Vector2 pos = Projectile.Center; + Vector2 pos = Projectile.Center + Projectile.velocity; switch (enemyID) { @@ -236,8 +238,6 @@ public class TelekineticEnemyGrab : ModProjectile, ILocalizedModType SoundEngine.PlaySound(SoundID.NPCDeath2 with { Volume = 0.175f }, pos); break; } - - return true; } bool evenRed = false; diff --git a/Projectiles/CalamityGlobalProjectile.cs b/Projectiles/CalamityGlobalProjectile.cs index cfecfd5dbf..e4204140f9 100644 --- a/Projectiles/CalamityGlobalProjectile.cs +++ b/Projectiles/CalamityGlobalProjectile.cs @@ -4542,8 +4542,8 @@ namespace CalamityMod.Projectiles } // Stardust Wings buff the Stardust Guardian's damage - if (player.wingsLogic == (int)VanillaWingID.WingsStardust && projectile.type == ProjectileID.StardustGuardian) - modifiers.SourceDamage *= 2f; + if (player.wingsLogic == (int)VanillaWingID.WingsStardust && player.wingTime > 0f && projectile.type == ProjectileID.StardustGuardian) + modifiers.SourceDamage *= MathF.Max(1f, MathHelper.Lerp(4f, 1f, player.wingTime / (float)player.wingTimeMax)); // If applicable, use ricoshot bonus damage if (totalRicoshotDamageBonus > 0f) diff --git a/Projectiles/Healing/PhantomicHeart.cs b/Projectiles/Healing/PhantomicHeart.cs index ea6c6c6de7..6a5c000682 100644 --- a/Projectiles/Healing/PhantomicHeart.cs +++ b/Projectiles/Healing/PhantomicHeart.cs @@ -25,6 +25,7 @@ namespace CalamityMod.Projectiles.Healing Projectile.width = 28; Projectile.height = 42; Projectile.friendly = true; + Projectile.tileCollide = false; Projectile.alpha = 20; Projectile.penetrate = -1; Projectile.timeLeft = 600; @@ -68,7 +69,7 @@ namespace CalamityMod.Projectiles.Healing if (player.whoAmI == Main.myPlayer) { CalamityPlayer calPlayer = player.Calamity(); - calPlayer.phantomicHeartRegen = 720; + calPlayer.phantomicHeartRegen = 600; Projectile.Kill(); } } diff --git a/Projectiles/Melee/ScorpiusConstellation.cs b/Projectiles/Melee/ScorpiusConstellation.cs index e79122c6fa..b7bc4ae366 100644 --- a/Projectiles/Melee/ScorpiusConstellation.cs +++ b/Projectiles/Melee/ScorpiusConstellation.cs @@ -14,7 +14,7 @@ namespace CalamityMod.Projectiles.Melee { public class ScorpiusConstellation : ModProjectile, ILocalizedModType { - public new string LocalizationCategory => "Projectiles.Rogue"; + public new string LocalizationCategory => "Projectiles.Melee"; public override string Texture => "CalamityMod/Projectiles/InvisibleProj"; public static int lifetime = 150; diff --git a/Projectiles/Summon/HallowedStarSummon.cs b/Projectiles/Summon/HallowedStarSummon.cs index 7875876023..12f84ae24b 100644 --- a/Projectiles/Summon/HallowedStarSummon.cs +++ b/Projectiles/Summon/HallowedStarSummon.cs @@ -29,6 +29,8 @@ namespace CalamityMod.Projectiles.Summon Projectile.penetrate = 1; Projectile.tileCollide = false; Projectile.DamageType = DamageClass.Summon; + Projectile.extraUpdates = 4; + Projectile.stopsDealingDamageAfterPenetrateHits = true; } public override void AI() diff --git a/Projectiles/Summon/PhantomicDagger.cs b/Projectiles/Summon/PhantomicDagger.cs index 114b11ab6c..8831c83389 100644 --- a/Projectiles/Summon/PhantomicDagger.cs +++ b/Projectiles/Summon/PhantomicDagger.cs @@ -57,11 +57,6 @@ namespace CalamityMod.Projectiles.Summon if (target.defense > 999 || target.Calamity().DR >= 0.95f || target.Calamity().unbreakableDR) return; - int cap = 3; - float capDamageFactor = 0.05f; - int excessCount = Main.player[Projectile.owner].ownedProjectileCounts[Type] - cap; - modifiers.SourceDamage *= MathHelper.Clamp(1f - (capDamageFactor * excessCount), 0f, 1f); - // Bypass a portion of the target's DR float maxDRPenetration = 1.05f; // 5% extra damage modifiers.FinalDamage *= MathHelper.Clamp(1f / (1f - target.Calamity().DR), 1f, maxDRPenetration); @@ -111,16 +106,15 @@ namespace CalamityMod.Projectiles.Summon } if (Projectile.alpha != 0) { - Projectile.rotation -= 0.25f; - Projectile.velocity.X *= 0.985f; - Projectile.velocity.Y *= 0.985f; + Projectile.rotation -= 6f * (MathF.Pow(Projectile.Opacity,2f)); + Projectile.velocity *= MathHelper.Lerp(1, 0.9f, Projectile.Opacity); if (Projectile.alpha < 3) { Projectile.alpha = 0; homing = true; } else - Projectile.alpha -= 3; + Projectile.alpha -= 2; } else { @@ -139,8 +133,8 @@ namespace CalamityMod.Projectiles.Summon targetDist = projVel / targetDist; targetXDist *= targetDist; targetYDist *= targetDist; - Projectile.velocity.X = (Projectile.velocity.X * 25f + targetXDist) / 26f; - Projectile.velocity.Y = (Projectile.velocity.Y * 25f + targetYDist) / 26f; + Projectile.velocity.X = (Projectile.velocity.X * 2f + targetXDist) / 3f; + Projectile.velocity.Y = (Projectile.velocity.Y * 2f + targetYDist) / 3f; } else { diff --git a/Skies/DoGSky.cs b/Skies/DoGSky.cs index f6d728e352..34f3f33673 100644 --- a/Skies/DoGSky.cs +++ b/Skies/DoGSky.cs @@ -415,8 +415,8 @@ namespace CalamityMod.Skies { // Impose the distortion rift contents onto the primitives via shader. var metaballShader = CalamityShaders.MetaballEdgeShader; - Texture2D distortionRiftContents = DoGVisualsManager.DistortionRiftBackgroundContentsTarget; - Texture2D distortionRift = DoGVisualsManager.DistortionRiftPrimitivesTarget; + Texture2D distortionRiftContents = DoGVisualsManager.DistortionRiftBackgroundContentsTarget.Target; + Texture2D distortionRift = DoGVisualsManager.DistortionRiftPrimitivesTarget.Target; Vector2 screenSize = new(Main.screenWidth, Main.screenHeight); diff --git a/Systems/Graphic/DoGVisualsManager.cs b/Systems/Graphic/DoGVisualsManager.cs index 2dde39a0fe..fc913ca06a 100644 --- a/Systems/Graphic/DoGVisualsManager.cs +++ b/Systems/Graphic/DoGVisualsManager.cs @@ -1,14 +1,15 @@ -using CalamityMod.Effects; +using System.Linq; +using CalamityMod.Effects; using CalamityMod.Graphics; +using CalamityMod.Graphics.Metaballs; using CalamityMod.Skies; -using Microsoft.Xna.Framework.Graphics; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Graphics; +using Terraria; using Terraria.GameContent; using Terraria.Graphics.Effects; -using Terraria; using Terraria.ModLoader; -using CalamityMod.Graphics.Metaballs; -using System.Linq; namespace CalamityMod.Systems.Graphic { @@ -35,17 +36,17 @@ namespace CalamityMod.Systems.Graphic /// /// The actual effects and contents seen inside the rift in the background of DoG's fight. /// - public static ManagedRenderTarget DistortionRiftBackgroundContentsTarget { get; private set; } + public static RenderTargetLease DistortionRiftBackgroundContentsTarget { get; private set; } /// /// The primitives used to make up the shape of the rift seen in the background of DoG's fight. /// - public static ManagedRenderTarget DistortionRiftPrimitivesTarget { get; private set; } + public static RenderTargetLease DistortionRiftPrimitivesTarget { get; private set; } /// /// The actual effects and contents seen inside of certain attacks used by DoG. Also used for DoG's distortion metaballs. /// - public static ManagedRenderTarget DistortionForegroundContentsTarget { get; private set; } + public static RenderTargetLease DistortionForegroundContentsTarget { get; private set; } public override void OnModLoad() { @@ -62,9 +63,9 @@ namespace CalamityMod.Systems.Graphic Main.QueueMainThreadAction(() => { - DistortionRiftBackgroundContentsTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); - DistortionRiftPrimitivesTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); - DistortionForegroundContentsTarget = new(true, ManagedRenderTarget.CreateScreenSizedTarget); + DistortionRiftBackgroundContentsTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); + DistortionRiftPrimitivesTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); + DistortionForegroundContentsTarget = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice); }); RenderTargetManager.RenderTargetUpdateLoopEvent += PrepareTargets; } @@ -158,29 +159,31 @@ namespace CalamityMod.Systems.Graphic if (ShouldDrawToBackgroundTargets) { // Draw the background which'll be displayed inside the rift onto a render target. - DistortionRiftBackgroundContentsTarget.SwapTo(); - DrawDistortionRiftBackground(); + using (DistortionRiftBackgroundContentsTarget.Scope(clearColor: Color.Transparent)) + { + DrawDistortionRiftBackground(); + } - Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, Main.Rasterizer, null, CalamityUtils.BackgroundMatrix); + using (DistortionRiftPrimitivesTarget.Scope(clearColor: Color.Transparent)) + { + Main.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, Main.Rasterizer, null, CalamityUtils.BackgroundMatrix); - // Draw the primitives which comprise the rift to another render target. - DistortionRiftPrimitivesTarget.SwapTo(); - if (SkyManager.Instance["CalamityMod:DevourerofGodsHead"].IsActive()) - (SkyManager.Instance["CalamityMod:DevourerofGodsHead"] as DoGSky).DrawRiftToRenderTarget(); + // Draw the primitives which comprise the rift to another render target. + if (SkyManager.Instance["CalamityMod:DevourerofGodsHead"].IsActive()) + (SkyManager.Instance["CalamityMod:DevourerofGodsHead"] as DoGSky).DrawRiftToRenderTarget(); - Main.spriteBatch.End(); + Main.spriteBatch.End(); + } } if (ShouldDrawToForegroundTarget) { // Draw the background which'll be displayed for all distortion-related effects done in the foreground (same layer as the player). - DistortionForegroundContentsTarget.SwapTo(); - DrawDistortionForeground(); + using (DistortionForegroundContentsTarget.Scope(clearColor: Color.Transparent)) + { + DrawDistortionForeground(); + } } - - // Reset the current render target at the end of the method once any targets are being drawn to. - if (ShouldDrawToForegroundTarget || ShouldDrawToBackgroundTargets) - Main.instance.GraphicsDevice.SetRenderTarget(null); } #region Distortion Background Drawing diff --git a/Systems/Graphic/LiquidSystem/ModLavaStyleSystem_RT.cs b/Systems/Graphic/LiquidSystem/ModLavaStyleSystem_RT.cs index 167bbece0d..4fdf3ee22e 100644 --- a/Systems/Graphic/LiquidSystem/ModLavaStyleSystem_RT.cs +++ b/Systems/Graphic/LiquidSystem/ModLavaStyleSystem_RT.cs @@ -1,4 +1,5 @@ -using Microsoft.Xna.Framework; +using CalamityMod.Utilities.Daybreak.Buffers; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; using Terraria; @@ -58,32 +59,33 @@ namespace CalamityMod.Systems.Graphic.LiquidSystem if (!Initialized || !TextureArrayReady || Main.gameMenu) return; - var graphicsDevice = Main.instance.GraphicsDevice; - graphicsDevice.SetRenderTarget(LavaRT); - graphicsDevice.Clear(Color.Transparent); - Begin(); - DrawTextures(Textures); - End(); + using (LavaRT.Scope(clearColor: Color.Transparent)) + { + Begin(); + DrawTextures(Textures); + End(); + } - graphicsDevice.SetRenderTarget(LavaBlockRT); - graphicsDevice.Clear(Color.Transparent); - Begin(); - DrawTextures(BlockTextures); - End(); + using (LavaBlockRT.Scope(clearColor: Color.Transparent)) + { + Begin(); + DrawTextures(BlockTextures); + End(); + } - graphicsDevice.SetRenderTarget(LavaSlopeRT); - graphicsDevice.Clear(Color.Transparent); - Begin(); - DrawTextures(SlopeTextures); - End(); + using (LavaSlopeRT.Scope(clearColor: Color.Transparent)) + { + Begin(); + DrawTextures(SlopeTextures); + End(); + } - graphicsDevice.SetRenderTarget(LavaWaterfallRT); - graphicsDevice.Clear(Color.Transparent); - Begin(); - DrawTextures(WaterfallTextures); - End(); - - graphicsDevice.SetRenderTarget(null); + using (LavaWaterfallRT.Scope(clearColor: Color.Transparent)) + { + Begin(); + DrawTextures(WaterfallTextures); + End(); + } } private static readonly BlendState ActualAdditive = new() diff --git a/Systems/Graphic/PixelationSystem/PixelationManager.cs b/Systems/Graphic/PixelationSystem/PixelationManager.cs index 151add53f1..a1f47dea93 100644 --- a/Systems/Graphic/PixelationSystem/PixelationManager.cs +++ b/Systems/Graphic/PixelationSystem/PixelationManager.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using CalamityMod.Enums; using CalamityMod.Graphics; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -12,15 +13,15 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem { public class PixelationManager : ModSystem { - private static Dictionary PixelTargets_BeforeAllTiles; - private static Dictionary PixelTargets_BeforeSolidTiles; - private static Dictionary PixelTargets_BeforeNPCs; - private static Dictionary PixelTargets_AfterNPCs; - private static Dictionary PixelTargets_BeforeProjectiles; - private static Dictionary PixelTargets_AfterProjectiles; - private static Dictionary PixelTargets_AfterPlayers; - private static Dictionary PixelTargets_AfterDusts; - private static Dictionary PixelTargets_AfterEverything; + private static Dictionary PixelTargets_BeforeAllTiles; + private static Dictionary PixelTargets_BeforeSolidTiles; + private static Dictionary PixelTargets_BeforeNPCs; + private static Dictionary PixelTargets_AfterNPCs; + private static Dictionary PixelTargets_BeforeProjectiles; + private static Dictionary PixelTargets_AfterProjectiles; + private static Dictionary PixelTargets_AfterPlayers; + private static Dictionary PixelTargets_AfterDusts; + private static Dictionary PixelTargets_AfterEverything; private static List ActivePixelatedDrawers_BeforeAllTiles; private static List ActivePixelatedDrawers_BeforeSolidTiles; @@ -51,11 +52,6 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem } } - /// - /// Creates a render target at a ratio of the screen's current dimensions based on . - /// - internal static RenderTarget2D CreatePixelTarget(int width, int height) => new(Main.graphics.GraphicsDevice, (int)(width * PixelationResolution), (int)(height * PixelationResolution)); - public override void Load() { if (Main.dedServ) @@ -163,28 +159,27 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem DrawCollectionsToTarget(PixelTargets_AfterPlayers, PixelationMatrix, ActivePixelatedDrawers_AfterPlayers); DrawCollectionsToTarget(PixelTargets_AfterDusts, PixelationMatrix, ActivePixelatedDrawers_AfterDusts); DrawCollectionsToTarget(PixelTargets_AfterEverything, PixelationMatrix, ActivePixelatedDrawers_AfterEverything); - - Main.graphics.GraphicsDevice.SetRenderTarget(null); } } - private static void DrawCollectionsToTarget(Dictionary targetCollection, Matrix pixelationMatrix, List drawerCollection) + private static void DrawCollectionsToTarget(Dictionary targetCollection, Matrix pixelationMatrix, List drawerCollection) { foreach (var blendStateTargetPair in targetCollection) { - blendStateTargetPair.Value.SwapTo(); - - Main.spriteBatch.Begin(default, blendStateTargetPair.Key, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, pixelationMatrix); - - // Select only drawers who match this target's BlendState. - var drawersByBlendState = drawerCollection.Where(d => d.DefaultBlendState == blendStateTargetPair.Key).ToList(); - if (drawersByBlendState.Count > 0) + using (blendStateTargetPair.Value.Scope(clearColor: Color.Transparent)) { - foreach (PixelatedDrawer drawer in drawersByBlendState) - drawer.DrawAction.Invoke(pixelationMatrix); - } + Main.spriteBatch.Begin(default, blendStateTargetPair.Key, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, pixelationMatrix); - Main.spriteBatch.End(); + // Select only drawers who match this target's BlendState. + var drawersByBlendState = drawerCollection.Where(d => d.DefaultBlendState == blendStateTargetPair.Key).ToList(); + if (drawersByBlendState.Count > 0) + { + foreach (PixelatedDrawer drawer in drawersByBlendState) + drawer.DrawAction.Invoke(pixelationMatrix); + } + + Main.spriteBatch.End(); + } } drawerCollection.Clear(); @@ -198,7 +193,7 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem Main.spriteBatch.Begin(default, keyValuePair.Key, SamplerState.PointClamp, DepthStencilState.None, Main.Rasterizer, null, Main.GameViewMatrix.TransformationMatrix); float targetScale = 1f / PixelationResolution; - Main.spriteBatch.Draw(keyValuePair.Value, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, targetScale, SpriteEffects.None, 0f); + Main.spriteBatch.Draw(keyValuePair.Value.Target, Vector2.Zero, null, Color.White, 0f, Vector2.Zero, targetScale, SpriteEffects.None, 0f); Main.spriteBatch.End(); } } @@ -221,9 +216,9 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem return drawerCollection; } - private static Dictionary ReturnAssociatedTargetCollection(GeneralDrawLayer drawLayer) + private static Dictionary ReturnAssociatedTargetCollection(GeneralDrawLayer drawLayer) { - Dictionary targetCollection = drawLayer switch + Dictionary targetCollection = drawLayer switch { GeneralDrawLayer.BeforeAllTiles => PixelTargets_BeforeAllTiles, GeneralDrawLayer.BeforeSolidTiles => PixelTargets_BeforeSolidTiles, @@ -245,47 +240,47 @@ namespace CalamityMod.Systems.Graphic.PixelationSystem { case GeneralDrawLayer.BeforeAllTiles: if (!PixelTargets_BeforeAllTiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeAllTiles[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_BeforeAllTiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.BeforeSolidTiles: if (!PixelTargets_BeforeSolidTiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeSolidTiles[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_BeforeSolidTiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.BeforeNPCs: if (!PixelTargets_BeforeNPCs.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeNPCs[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_BeforeNPCs[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.AfterNPCs: if (!PixelTargets_AfterNPCs.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterNPCs[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_AfterNPCs[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.BeforeProjectiles: if (!PixelTargets_BeforeProjectiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_BeforeProjectiles[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_BeforeProjectiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.AfterProjectiles: if (!PixelTargets_AfterProjectiles.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterProjectiles[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_AfterProjectiles[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.AfterPlayers: if (!PixelTargets_AfterPlayers.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterPlayers[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_AfterPlayers[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.AfterDusts: if (!PixelTargets_AfterDusts.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterDusts[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_AfterDusts[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; case GeneralDrawLayer.AfterEverything: if (!PixelTargets_AfterEverything.ContainsKey(blendState)) - Main.QueueMainThreadAction(() => PixelTargets_AfterEverything[blendState] = new(true, CreatePixelTarget)); + Main.QueueMainThreadAction(() => PixelTargets_AfterEverything[blendState] = ScreenspaceTargetPool.Shared.Rent(Main.instance.GraphicsDevice, (w, h) => ((int)(w * PixelationResolution), (int)(h * PixelationResolution)))); break; } } diff --git a/Systems/Mechanic/DifficultyModeSystem.cs b/Systems/Mechanic/DifficultyModeSystem.cs index 87bdaaea6f..72ddc7fa36 100644 --- a/Systems/Mechanic/DifficultyModeSystem.cs +++ b/Systems/Mechanic/DifficultyModeSystem.cs @@ -59,7 +59,7 @@ namespace CalamityMod.Systems case GameModeID.Normal: { // vanilla game mode in classic, but cal difficulty >= expert - if (GetCurrentDifficulty == ModContent.GetInstance() || GetCurrentDifficulty == ModContent.GetInstance()) + if (GetCurrentDifficulty.CountAs() || GetCurrentDifficulty.CountAs()) { ModeIndicatorUI.SwitchToDifficulty(ModContent.GetInstance(), broadcast: true); } @@ -68,7 +68,7 @@ namespace CalamityMod.Systems case GameModeID.Expert: { // if death was activated, change it to revengence - if (GetCurrentDifficulty == ModContent.GetInstance()) + if (GetCurrentDifficulty.CountAs()) { ModeIndicatorUI.SwitchToDifficulty(ModContent.GetInstance(), broadcast: true); } @@ -77,7 +77,7 @@ namespace CalamityMod.Systems case GameModeID.Master: { // if revengence and master both activated, change it to death - if (GetCurrentDifficulty != ModContent.GetInstance() && CalamityWorld.revenge) + if (!GetCurrentDifficulty.CountAs() && CalamityWorld.revenge) { ModeIndicatorUI.SwitchToDifficulty(ModContent.GetInstance(), broadcast: true); } @@ -241,6 +241,7 @@ namespace CalamityMod.Systems // This is registered in DifficultyModeSystem.OnModLoad // Note that DifficultyModeSystem.Load can't ensure system is loaded after all modes } + public abstract bool Enabled { get; set; @@ -271,6 +272,16 @@ namespace CalamityMod.Systems public virtual bool RequiresDifficulty(DifficultyMode mode) => false; public virtual int[] FavoredDifficultyAtTier(int tier) => [0]; + + public virtual bool IsBasedOn(DifficultyMode mode) => false; + + public bool CountAs() where Difficulty : DifficultyMode => CountAs(ModContent.GetInstance()); + public bool CountAs(DifficultyMode mode) + { + if (mode == this) return true; + if (IsBasedOn(mode)) return true; + return false; + } } public class NoDifficulty : DifficultyMode diff --git a/Systems/TileMerging/TileBlendTexture_Baking.cs b/Systems/TileMerging/TileBlendTexture_Baking.cs index de51103d63..a40a39dc52 100644 --- a/Systems/TileMerging/TileBlendTexture_Baking.cs +++ b/Systems/TileMerging/TileBlendTexture_Baking.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; @@ -62,20 +63,17 @@ namespace CalamityMod.Systems var renderTarget = BakedBlendTexture; if (renderTarget != null && !renderTarget.IsDisposed && !renderTarget.IsContentLost) { - graphicsDevice.SetRenderTarget(renderTarget); - if (_ShouldClearRT) + using (renderTarget.Scope(clearColor: _ShouldClearRT ? Color.Transparent : null)) { - graphicsDevice.Clear(Color.Transparent); _ShouldClearRT = false; + + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone); + + BakeBlendTextureCache(v); + + Main.spriteBatch.End(); } - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.None, RasterizerState.CullNone); - - BakeBlendTextureCache(v); - - Main.spriteBatch.End(); - graphicsDevice.SetRenderTarget(null); - _RequestedVariants[variant] = false; _IsBaked[variant] = true; } diff --git a/UI/DialogueDisplay/DialogueDisplayUI.cs b/UI/DialogueDisplay/DialogueDisplayUI.cs index 4bf1265e07..153eac8d15 100644 --- a/UI/DialogueDisplay/DialogueDisplayUI.cs +++ b/UI/DialogueDisplay/DialogueDisplayUI.cs @@ -1,27 +1,25 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.IO; using System.Linq; -using System.Text.Json; using System.Text.Json.Serialization; +using CalamityMod.Dialogues; +using CalamityMod.Packets; using CalamityMod.UI.DialogueDisplay.DialogueEvents; using CalamityMod.UI.DialogueDisplay.DisplayEffects; using CalamityMod.UI.DialogueDisplay.TextEffects; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -using Microsoft.Xna.Framework.Input; using ReLogic.Content; using ReLogic.Graphics; using Terraria; using Terraria.Audio; using Terraria.GameContent; using Terraria.ID; -using Terraria.Localization; using Terraria.ModLoader; using Terraria.UI; using Terraria.UI.Chat; -using static System.Runtime.InteropServices.JavaScript.JSType; +using static CalamityMod.Packets.StartDialogueDisplayPacket; using static ReLogic.Graphics.DynamicSpriteFont; namespace CalamityMod.UI.DialogueDisplay @@ -63,8 +61,13 @@ namespace CalamityMod.UI.DialogueDisplay { if (dialog.entity.active) dialog.ui.Position = dialog.entity.Center; - else + else if (ui.DisplayEffects.DespawnWithAttachedNPC) dialog.ui.ClosingDialogue = true; + else + { + dialog.ui.Position = dialog.entity.Center; + dialog.entity = null; + } } if (dialog.upTime != -1) @@ -528,7 +531,7 @@ namespace CalamityMod.UI.DialogueDisplay foreach (string s in returnString) storedLen += s.Length; - Pauses.Add(index - storedLen - 1, Params[0]); + Pauses.Add(index - storedLen - 1, Params[0]); } else { @@ -911,6 +914,43 @@ namespace CalamityMod.UI.DialogueDisplay internal static UserInterface UI; + public enum DisplayEffectID + { + Invalid = -1, + None, + AlwaysOnScreen, + BossText, + Built, + WhisperingPearls + } + + public static DisplayEffectID GetID(object obj) + { + if (obj is not DisplayEffect) + return DisplayEffectID.Invalid; + + return obj switch + { + AlwaysOnScreen => DisplayEffectID.AlwaysOnScreen, + BossText => DisplayEffectID.BossText, + BuiltEffect => DisplayEffectID.Built, + WhisperingPearlEffects => DisplayEffectID.WhisperingPearls, + _ => DisplayEffectID.None + }; + } + + public static DisplayEffect GetEffect(DisplayEffectID id) + { + return id switch + { + DisplayEffectID.AlwaysOnScreen => new AlwaysOnScreen(), + DisplayEffectID.BossText => new BossText(), + DisplayEffectID.Built => new BuiltEffect(), + DisplayEffectID.WhisperingPearls => new WhisperingPearlEffects(), + _ => new DisplayEffect() + }; + } + public override void Load() { if (!Main.dedServ) @@ -940,15 +980,6 @@ namespace CalamityMod.UI.DialogueDisplay UI?.Update(gameTime); } - public static DialogueTextData Deserialize(string name) - { - string json = Language.GetTextValue("Mods.CalamityMod.Dialogue." + name); - - DialogueTextData data = JsonSerializer.Deserialize(json); - - return data; - } - public static Color GetColorFromHex(string hex) { System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml('#' + hex); @@ -963,8 +994,8 @@ namespace CalamityMod.UI.DialogueDisplay /// public static int GetSlot(string name) { - foreach(var pair in DialogueDisplayUI.Dialogues) - if(pair.Value.name == name) + foreach (var pair in DialogueDisplayUI.Dialogues) + if (pair.Value.name == name) return pair.Key; return -1; } @@ -1009,13 +1040,35 @@ namespace CalamityMod.UI.DialogueDisplay ///
/// The name of the dialogue's localization key /// The position of the text in the world - public static int StartDialogue(string name, Vector2 startPosition, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1) + public static int StartDialogue(string name, Vector2 startPosition, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1, int toClient = -1, int ignoreClient = -1) { + if (Main.dedServ) + { + StartDialogueDisplayPacket.Send(name, progressDialogue, startPosition, startIndex, Uptime, GetID(effects), wrapWidth, toClient, ignoreClient); + return -1; + } + else if (Main.netMode == NetmodeID.SinglePlayer) + { + return StartDialogueOnClient(name, startPosition, startIndex, Uptime, progressDialogue, effects, wrapWidth); + } + + return -1; + } + + public static int StartDialogueOnClient(string name, Vector2 startPosition, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1) + { + if (Main.dedServ) + return -1; + UI ??= new(); State ??= new(); effects ??= new DisplayEffect(); - DialogueTextData textData = Deserialize(name); + if (!DialogueLoader.TryGetDialogue(name, out var textData)) + { + CalamityMod.Log.Error($"Unable to find Dialogue Data for given name: '{name}'"); + return -1; + } if (startIndex >= textData.PageCount) startIndex = textData.PageCount - 1; @@ -1048,13 +1101,35 @@ namespace CalamityMod.UI.DialogueDisplay /// The name of the dialogue's localization key /// The entity this dialogue will appear with /// The entity this dialogue will appear with - public static int StartDialogue(string name, Entity entity, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1) + public static int StartDialogue(string name, Entity entity, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1, int toClient = -1, int ignoreClient = -1) { + if (Main.dedServ) + { + StartDialogueDisplayPacket.Send(name, progressDialogue, entity is NPC ? EntityType.NPC : entity is Player ? EntityType.Player : EntityType.Projectile, entity is Projectile p ? p.identity : entity.whoAmI, startIndex, Uptime, GetID(effects), wrapWidth, toClient, ignoreClient); + return -1; + } + else if (Main.netMode == NetmodeID.SinglePlayer) + { + return StartDialogueOnClient(name, entity, startIndex, Uptime, progressDialogue, effects, wrapWidth); + } + + return -1; + } + + public static int StartDialogueOnClient(string name, Entity entity, int startIndex = 0, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1) + { + if (Main.dedServ) + return -1; + UI ??= new(); State ??= new(); effects ??= new DisplayEffect(); - DialogueTextData textData = Deserialize(name); + if (!DialogueLoader.TryGetDialogue(name, out var textData)) + { + CalamityMod.Log.Error($"Unable to find Dialogue Data for given name: '{name}'"); + return -1; + } if (startIndex >= textData.PageCount) startIndex = textData.PageCount - 1; @@ -1120,6 +1195,11 @@ namespace CalamityMod.UI.DialogueDisplay public int PunctuationDelayCap { get; init; } public Dictionary PunctuationDelays { get; init; } + /// + /// Only used for DialogueLoader + /// + public int Revision { get; init; } + [JsonConstructor] public DialogueTextData(DialoguePage[] Pages, int Page = 0, string DefaultColor = null, string DefaultSpeaker = null, int DefaultScale = 1, Alignment AlignType = 0, int TextDelay = 3, PunctuationData BasePunctuationDelay = null, int PunctuationDelayCap = 60, Dictionary PunctuationDelays = null) { diff --git a/UI/DialogueDisplay/DisplayEffects/BossText.cs b/UI/DialogueDisplay/DisplayEffects/BossText.cs index 69dde0be01..1085ad8e35 100644 --- a/UI/DialogueDisplay/DisplayEffects/BossText.cs +++ b/UI/DialogueDisplay/DisplayEffects/BossText.cs @@ -7,9 +7,10 @@ namespace CalamityMod.UI.DialogueDisplay.DisplayEffects { public class BossText : DisplayEffect { - Vector2 lastPosition = Vector2.Zero; public override bool FadeWhenTooFar => false; + public override bool DespawnWithAttachedNPC => false; + public override Vector2 TextOffsetFromStart(Vector2 startPos, Vector2 textSize) { Vector2 playerPos = Main.LocalPlayer.Center; diff --git a/UI/DialogueDisplay/DisplayEffects/DisplayEffect.cs b/UI/DialogueDisplay/DisplayEffects/DisplayEffect.cs index d4cb2b60d3..109c2cb7f8 100644 --- a/UI/DialogueDisplay/DisplayEffects/DisplayEffect.cs +++ b/UI/DialogueDisplay/DisplayEffects/DisplayEffect.cs @@ -9,6 +9,8 @@ namespace CalamityMod.UI.DialogueDisplay.DisplayEffects public virtual bool FadeWhenTooFar => true; + public virtual bool DespawnWithAttachedNPC => true; + public virtual float FadeBuffer => 150f; public virtual float FadeDistance => 150f; diff --git a/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs b/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs index 4d4abc310e..5639dba82e 100644 --- a/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs +++ b/Utilities/Daybreak/Buffers/BuffersLoadingSystem.cs @@ -1,3 +1,4 @@ +using CalamityMod.Graphics; using Terraria; using Terraria.ModLoader; @@ -44,6 +45,7 @@ public class BuffersLoadingSystem : ModSystem // Dispose shared pools. RenderTargetPool.Shared.Dispose(); ScreenspaceTargetPool.Shared.Dispose(); + ManagedRenderTargetPool.Shared.Dispose(); } ); } @@ -62,5 +64,6 @@ public class BuffersLoadingSystem : ModSystem orig(self); ScreenspaceTargetPool.Shared.ResizeCachedTargets(self.GraphicsDevice); + ManagedRenderTargetPool.Shared.ResizeTargets(); } } diff --git a/Utilities/DrawingUtils.cs b/Utilities/DrawingUtils.cs index 362d3fc71e..0fc90e184c 100644 --- a/Utilities/DrawingUtils.cs +++ b/Utilities/DrawingUtils.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; +using CalamityMod.Utilities.Daybreak.Buffers; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; @@ -356,16 +357,14 @@ namespace CalamityMod /// public static void CopyContentsFrom(this RenderTarget2D to, RenderTarget2D from) { - Main.instance.GraphicsDevice.SetRenderTarget(to); - Main.instance.GraphicsDevice.Clear(Color.Transparent); + using (to.Scope(clearColor: Color.Transparent)) + { + Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); + Main.spriteBatch.Draw(from, Vector2.Zero, null, Color.White); + Main.spriteBatch.End(); + } - Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, Main.DefaultSamplerState, DepthStencilState.None, Main.Rasterizer, null, Matrix.Identity); - Main.spriteBatch.Draw(from, Vector2.Zero, null, Color.White); - Main.spriteBatch.End(); - - Main.instance.GraphicsDevice.SetRenderTarget(from); - Main.instance.GraphicsDevice.Clear(Color.Transparent); - Main.instance.GraphicsDevice.SetRenderTarget(null); + using (from.Scope(clearColor: Color.Transparent)) { } } /// @@ -818,6 +817,7 @@ namespace CalamityMod /// /// The render target to swap to /// The color to clear the screen with. Transparent by default + [Obsolete("Use RenderTargetScope")] public static void SwapTo(this RenderTarget2D target, Color? flushColor = null) { // If we are in the menu, a server, or any of these are null, return. diff --git a/Utilities/MainThreadedFileSystemWatcher.cs b/Utilities/MainThreadedFileSystemWatcher.cs new file mode 100644 index 0000000000..a605e9e674 --- /dev/null +++ b/Utilities/MainThreadedFileSystemWatcher.cs @@ -0,0 +1,179 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Text.RegularExpressions; +using Terraria; +using Terraria.ModLoader; + +namespace CalamityMod.Utilities; + +internal sealed class MainThreadedFileSystemWatcher : IDisposable +{ + public string Path + { + get => _FSW.Path; + set => _FSW.Path = value; + } + + public string Filter + { + get => _FSW.Filter; + set => _FSW.Filter = value; + } + + public Collection Filters + { + get => _FSW.Filters; + } + + public NotifyFilters NotifyFilter + { + get => _FSW.NotifyFilter; + set => _FSW.NotifyFilter = value; + } + + public bool IncludeSubdirectories + { + get => _FSW.IncludeSubdirectories; + set => _FSW.IncludeSubdirectories = value; + } + + public bool EnableRaisingEvents + { + get => _FSW.EnableRaisingEvents; + set => _FSW.EnableRaisingEvents = value; + } + + public Regex FileNameFilter { get; set; } = null; + + public event Action Changed; + public event Action Renamed; + + private Dictionary _ChangedQueue = []; + private Dictionary _RenamedQueue = []; + + private FileSystemWatcher _FSW; + private bool _HasQueueInFrame = false; + private bool _Disposed; + + public MainThreadedFileSystemWatcher() + { + _FSW = new(); + _FSW.Changed += (o, arg) => + { + if (FileNameFilter != null && !FileNameFilter.IsMatch(System.IO.Path.GetFileName(arg.Name))) + return; + + lock (_ChangedQueue) + { + _ChangedQueue[arg.FullPath] = arg; + _HasQueueInFrame = true; + } + }; + + _FSW.Renamed += (o, arg) => + { + if (FileNameFilter != null && !FileNameFilter.IsMatch(System.IO.Path.GetFileName(arg.Name))) + return; + + lock (_RenamedQueue) + { + _RenamedQueue[arg.FullPath] = arg; + _HasQueueInFrame = true; + } + }; + + MainThreadedFileSystemWatcherSystem.Register(this); + } + + private void Dispose(bool disposing) + { + if (!_Disposed) + { + if (disposing) + { + _FSW?.Dispose(); + } + + _FSW = null; + _Disposed = true; + _ChangedQueue?.Clear(); + _RenamedQueue?.Clear(); + _ChangedQueue = null; + _RenamedQueue = null; + _HasQueueInFrame = false; + MainThreadedFileSystemWatcherSystem.Unregister(this); + } + } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + private sealed class MainThreadedFileSystemWatcherSystem : ILoadable + { + private static MainThreadedFileSystemWatcher[] _Watchers = []; + private static HashSet _WatchersList = []; + + public static void Register(MainThreadedFileSystemWatcher watcher) + { + _WatchersList.Add(watcher); + _Watchers = [.. _WatchersList]; + } + + public static void Unregister(MainThreadedFileSystemWatcher watcher) + { + _WatchersList.Remove(watcher); + _Watchers = [.. _WatchersList]; + } + + void ILoadable.Load(Mod mod) + { + Main.OnTickForThirdPartySoftwareOnly += Tick; + } + + void ILoadable.Unload() + { + Main.OnTickForThirdPartySoftwareOnly -= Tick; + _WatchersList?.Clear(); + _Watchers = []; + } + + private void Tick() + { + foreach (var watcher in _Watchers) + { + if (!watcher._HasQueueInFrame) + continue; + + HandleQueuedEvents(watcher); + } + } + + private static void HandleQueuedEvents(MainThreadedFileSystemWatcher watcher) + { + lock (watcher._ChangedQueue) + { + foreach (var changed in watcher._ChangedQueue.Values) + { + watcher.Changed?.Invoke(changed); + } + watcher._ChangedQueue.Clear(); + } + + lock (watcher._RenamedQueue) + { + foreach (var renamed in watcher._RenamedQueue.Values) + { + watcher.Renamed?.Invoke(renamed); + } + watcher._RenamedQueue.Clear(); + } + + watcher._HasQueueInFrame = false; + } + } +}