using ADOFAIRenderer.Core;
using HarmonyLib;
using UnityEngine;
namespace ADOFAIRenderer.Patch.Game;
///
/// Makes the game's bloom compute its blur size as if the frame were 720 pixels high
/// ("High-Resolution Bloom Correction" option).
///
/// Patched member: VideoBloom.OnRenderImage(RenderTexture source, RenderTexture destination). The game scales the
/// frame down to a bloom buffer 198 pixels high (scale = 198 / source.height) and sets the blur radius in bloom
/// buffer pixels to KernelSize * MediumKernelScale * scale (and KernelSize * LargeKernelScale * scale).
/// BloomBlit turns the radius into the number of 5-tap blur passes and the blend amount of the last pass.
///
///
/// While the render is active () and AdvancedConfig.HighResBloomCorrection is
/// enabled, the prefix multiplies KernelSize by source.height / 720 for the duration of the call, so the
/// radius equals KernelSize * MediumKernelScale * 198 / 720 and the blur passes on the bloom buffer are the same
/// as in a 720p frame. The finalizer restores the original KernelSize. The bloom buffer size and the downscale
/// from the source frame keep the game's behavior.
///
///
[HarmonyPatch(typeof(VideoBloom))]
public class VideoBloomPatch
{
/// Frame height in pixels the blur size is computed for.
private const float ReferenceHeight = 720f;
/// Prefix of VideoBloom.OnRenderImage.
/// The bloom component on the game camera.
/// The camera frame; its height selects the multiplier.
/// Original KernelSize, or null when it was not changed.
[HarmonyPrefix]
[HarmonyPatch("OnRenderImage")]
// ReSharper disable InconsistentNaming
public static void ScaleKernelSize(VideoBloom __instance, RenderTexture source, out float? __state)
// ReSharper restore InconsistentNaming
{
__state = null;
if (!source || !RenderManager.IsActive || !RenderManager.Instance.Configuration.AdvancedConfig.HighResBloomCorrection)
return;
__state = __instance.KernelSize;
__instance.KernelSize *= source.height / ReferenceHeight;
}
/// Finalizer of VideoBloom.OnRenderImage: restores KernelSize when the prefix changed it.
/// The bloom component on the game camera.
/// Original KernelSize stored by the prefix, or null.
[HarmonyFinalizer]
[HarmonyPatch("OnRenderImage")]
// ReSharper disable InconsistentNaming
public static void RestoreKernelSize(VideoBloom __instance, float? __state)
// ReSharper restore InconsistentNaming
{
if (__state.HasValue) __instance.KernelSize = __state.Value;
}
}