summaryrefslogtreecommitdiff
path: root/src/SMAPI.Mods.ErrorHandler/Patches/SpriteBatchValidationPatches.cs
blob: 0211cfb12c9f1bbd856422e8533feb50d88a614f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#if HARMONY_2
using HarmonyLib;
#else
using Harmony;
#endif
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI.Framework.Patching;

namespace StardewModdingAPI.Mods.ErrorHandler.Patches
{
    /// <summary>Harmony patch for <see cref="SpriteBatch"/> to validate textures earlier.</summary>
    /// <remarks>Patch methods must be static for Harmony to work correctly. See the Harmony documentation before renaming patch arguments.</remarks>
    [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Argument names are defined by Harmony and methods are named for clarity.")]
    [SuppressMessage("ReSharper", "IdentifierTypo", Justification = "Argument names are defined by Harmony and methods are named for clarity.")]
    internal class SpriteBatchValidationPatches : IHarmonyPatch
    {
        /*********
        ** Accessors
        *********/
        /// <inheritdoc />
        public string Name => nameof(SpriteBatchValidationPatches);


        /*********
        ** Public methods
        *********/
        /// <inheritdoc />
#if HARMONY_2
        public void Apply(Harmony harmony)
#else
        public void Apply(HarmonyInstance harmony)
#endif
        {
            harmony.Patch(
#if SMAPI_FOR_WINDOWS
                original: AccessTools.Method(typeof(SpriteBatch), "InternalDraw"),
#else
                original: AccessTools.Method(typeof(SpriteBatch), "CheckValid", new[] { typeof(Texture2D) }),
#endif
                postfix: new HarmonyMethod(this.GetType(), nameof(SpriteBatchValidationPatches.After_SpriteBatch_CheckValid))
            );
        }


        /*********
        ** Private methods
        *********/
#if SMAPI_FOR_WINDOWS
        /// <summary>The method to call instead of <see cref="SpriteBatch.InternalDraw"/>.</summary>
        /// <param name="texture">The texture to validate.</param>
#else
        /// <summary>The method to call instead of <see cref="SpriteBatch.CheckValid"/>.</summary>
        /// <param name="texture">The texture to validate.</param>
#endif
        private static void After_SpriteBatch_CheckValid(Texture2D texture)
        {
            if (texture?.IsDisposed == true)
                throw new ObjectDisposedException("Cannot draw this texture because it's disposed.");
        }
    }
}