using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; namespace CalamityMod.Graphics { /// /// 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 { private RenderTarget2D target; public readonly RenderTargetCreationCondition CreationCondition; public readonly bool ShouldResetUponScreenResize; public readonly bool ShouldAutoDispose; public bool WaitingForFirstInitialization { get; private set; } = true; public bool IsUninitialized => target is null || target.IsDisposed; public bool IsDisposed { get; private set; } /// /// The actual instance that the wrapper contains. /// public RenderTarget2D Target { get { if (IsUninitialized) { target = CreationCondition(Main.screenWidth, Main.screenHeight); WaitingForFirstInitialization = false; IsDisposed = false; } TimeSinceLastAccessed = 0; return target; } 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; } }