From 8d5b3c739a49b31ad5e2aa7a6177a50c37b853a4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 19 Aug 2022 01:51:37 +0200 Subject: [PATCH 1/9] Add initial draft port of bokeh blur effect to D2D1 --- .../Effects/BokehBlurEffect.cs | 548 ++++++++++++++++++ .../ComputeSharp.D2D1.Tests/EndToEndTests.cs | 18 +- 2 files changed, 565 insertions(+), 1 deletion(-) create mode 100644 tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs new file mode 100644 index 00000000..cabfaffd --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs @@ -0,0 +1,548 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1; +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Tests.Extensions; +using ComputeSharp.D2D1.Tests.Helpers; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.BokehBlur.Processors; + +/// +/// A bokeh blur effect, using linearly separable convolutions in the complex space for better efficiency. +/// +public sealed partial class BokehBlurEffect +{ + /// + /// The kernel radius. + /// + private readonly int Radius; + + /// + /// The maximum size of the kernel in either direction. + /// + private readonly int KernelSize; + + /// + /// The number of components to use when applying the bokeh blur. + /// + private readonly int ComponentsCount; + + /// + /// The kernel parameters to use for the current instance (a: X, b: Y, A: Z, B: W) + /// + private readonly Vector4[] KernelParameters; + + /// + /// The kernel components for the current instance. + /// + private readonly (float[] Real, float[] Imaginary)[] Kernels; + + /// + /// The scaling factor for kernel values. + /// + private readonly float KernelsScale; + + /// + /// The mapping of initialized complex kernels and parameters, to speed up the initialization of new instances. + /// + private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, (float[] Real, float[] Imaginary)[] Kernels)> Cache = new(); + + /// + /// Initializes a new instance of the class. + /// + /// The size of the area to sample. + /// The number of components to use to approximate the original 2D bokeh blur convolution kernel. + public BokehBlurEffect(int radius, int componentsCount) + { + Radius = radius; + KernelSize = Radius * 2 + 1; + ComponentsCount = componentsCount; + + // Reuse the initialized values from the cache, if possible + var parameters = (Radius, ComponentsCount); + if (Cache.TryGetValue(parameters, out var info)) + { + KernelParameters = info.Parameters; + KernelsScale = info.Scale; + Kernels = info.Kernels; + } + else + { + // Initialize the complex kernels and parameters with the current arguments + (KernelParameters, KernelsScale) = GetParameters(); + var kernels = CreateComplexKernels(); + + NormalizeKernels(kernels, KernelParameters); + + Kernels = ConvertKernelsToStructureOfArrays(kernels); + + // Store them in the cache for future use + Cache.TryAdd(parameters, (KernelParameters, KernelsScale, Kernels)); + } + } + + /// + /// Gets the kernel scales to adjust the component values in each kernel. + /// + private static IReadOnlyList KernelScales { get; } = new[] { 1.4f, 1.2f, 1.2f, 1.2f, 1.2f, 1.2f }; + + /// + /// Gets the available bokeh blur kernel parameters. + /// + private static IReadOnlyList KernelComponents { get; } = new[] + { + // 1 component + new[] { new Vector4(0.862325f, 1.624835f, 0.767583f, 1.862321f) }, + + // 2 components + new[] + { + new Vector4(0.886528f, 5.268909f, 0.411259f, -0.548794f), + new Vector4(1.960518f, 1.558213f, 0.513282f, 4.56111f) + }, + + // 3 components + new[] + { + new Vector4(2.17649f, 5.043495f, 1.621035f, -2.105439f), + new Vector4(1.019306f, 9.027613f, -0.28086f, -0.162882f), + new Vector4(2.81511f, 1.597273f, -0.366471f, 10.300301f) + }, + + // 4 components + new[] + { + new Vector4(4.338459f, 1.553635f, -5.767909f, 46.164397f), + new Vector4(3.839993f, 4.693183f, 9.795391f, -15.227561f), + new Vector4(2.791880f, 8.178137f, -3.048324f, 0.302959f), + new Vector4(1.342190f, 12.328289f, 0.010001f, 0.244650f) + }, + + // 5 components + new[] + { + new Vector4(4.892608f, 1.685979f, -22.356787f, 85.91246f), + new Vector4(4.71187f, 4.998496f, 35.918936f, -28.875618f), + new Vector4(4.052795f, 8.244168f, -13.212253f, -1.578428f), + new Vector4(2.929212f, 11.900859f, 0.507991f, 1.816328f), + new Vector4(1.512961f, 16.116382f, 0.138051f, -0.01f) + }, + + // 6 components + new[] + { + new Vector4(5.143778f, 2.079813f, -82.326596f, 111.231024f), + new Vector4(5.612426f, 6.153387f, 113.878661f, 58.004879f), + new Vector4(5.982921f, 9.802895f, 39.479083f, -162.028887f), + new Vector4(6.505167f, 11.059237f, -71.286026f, 95.027069f), + new Vector4(3.869579f, 14.81052f, 1.405746f, -3.704914f), + new Vector4(2.201904f, 19.032909f, -0.152784f, -0.107988f) + } + }; + + /// + /// Gets the kernel parameters and scaling factor for the current count value in the current instance. + /// + private (Vector4[] Parameters, float Scale) GetParameters() + { + // Prepare the kernel components + int index = Math.Max(0, Math.Min(ComponentsCount - 1, KernelComponents.Count)); + + return (KernelComponents[index], KernelScales[index]); + } + + /// + /// Creates the collection of complex 1D kernels with the specified parameters. + /// + private Complex64[][] CreateComplexKernels() + { + var kernels = new Complex64[KernelParameters.Length][]; + ref Vector4 baseRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan()); + + for (int i = 0; i < KernelParameters.Length; i++) + { + ref Vector4 paramsRef = ref Unsafe.Add(ref baseRef, i); + + kernels[i] = CreateComplex1DKernel(paramsRef.X, paramsRef.Y); + } + + return kernels; + } + + /// + /// Creates a complex 1D kernel with the specified parameters. + /// + /// The exponential parameter for each complex component. + /// The angle component for each complex component. + private Complex64[] CreateComplex1DKernel(float a, float b) + { + var kernel = new Complex64[KernelSize]; + ref Complex64 baseRef = ref MemoryMarshal.GetReference(kernel.AsSpan()); + int r = Radius; + int n = -r; + + for (int i = 0; i < KernelSize; i++, n++) + { + // Incrementally compute the range values + float value = n * KernelsScale * (1f / r); + + value *= value; + + // Fill in the complex kernel values + Unsafe.Add(ref baseRef, i) = new Complex64( + (float)(Math.Exp(-a * value) * Math.Cos(b * value)), + (float)(Math.Exp(-a * value) * Math.Sin(b * value))); + } + + return kernel; + } + + /// + /// Normalizes the kernels with respect to A * real + B * imaginary. + /// + /// The input kernels to normalize. + /// The kernel parameters to use to normalize the kernels. + private static void NormalizeKernels(Complex64[][] kernels, Vector4[] kernelParameters) + { + // Calculate the complex weighted sum + float total = 0; + Span kernelsSpan = kernels.AsSpan(); + ref Complex64[] baseKernelsRef = ref MemoryMarshal.GetReference(kernelsSpan); + ref Vector4 baseParamsRef = ref MemoryMarshal.GetReference(kernelParameters.AsSpan()); + + for (int i = 0; i < kernelParameters.Length; i++) + { + ref Complex64[] kernelRef = ref Unsafe.Add(ref baseKernelsRef, i); + int length = kernelRef.Length; + ref Complex64 valueRef = ref kernelRef[0]; + ref Vector4 paramsRef = ref Unsafe.Add(ref baseParamsRef, i); + + for (int j = 0; j < length; j++) + { + for (int k = 0; k < length; k++) + { + ref Complex64 jRef = ref Unsafe.Add(ref valueRef, j); + ref Complex64 kRef = ref Unsafe.Add(ref valueRef, k); + + total += + paramsRef.Z * (jRef.Real * kRef.Real - jRef.Imaginary * kRef.Imaginary) + + paramsRef.W * (jRef.Real * kRef.Imaginary + jRef.Imaginary * kRef.Real); + } + } + } + + // Normalize the kernels + float scalar = 1f / (float)Math.Sqrt(total); + + for (int i = 0; i < kernelsSpan.Length; i++) + { + ref Complex64[] kernelsRef = ref Unsafe.Add(ref baseKernelsRef, i); + int length = kernelsRef.Length; + ref Complex64 valueRef = ref kernelsRef[0]; + + for (int j = 0; j < length; j++) + { + Unsafe.Add(ref valueRef, j) *= scalar; + } + } + } + + /// + /// Converts the kernels into structure of arrays. + /// + /// The input kernels to convert. + private static (float[] Real, float[] Imaginary)[] ConvertKernelsToStructureOfArrays(Complex64[][] kernels) + { + var structureOfArrayKernels = new (float[] Real, float[] Imaginary)[kernels.Length]; + + for (int i = 0; i < kernels.Length; i++) + { + Complex64[] kernel = kernels[i]; + var real = new float[kernel.Length]; + var imaginary = new float[kernel.Length]; + + for (int j = 0; j < kernel.Length; j++) + { + real[j] = kernel[j].Real; + imaginary[j] = kernel[j].Imaginary; + } + + structureOfArrayKernels[i] = (real, imaginary); + } + + return structureOfArrayKernels; + } + + /// + /// Applies the effect on an image loaded from a given path and writes the result to the output path. + /// + /// The source path for the image to run the effect on. + /// The destination path for the result. + public unsafe void ApplyEffect(string sourcePath, string destinationPath) + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + // Register all necessary effects + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); + + using ComPtr verticalConvolutionEffectForReals = default; + using ComPtr verticalConvolutionEffectForImaginaries = default; + using ComPtr horizontalConvolutionEffect = default; + using ComPtr gammaExposureEffect = default; + using ComPtr inverseGammaExposureEffect = default; + + // Create an instance of each effect + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectForReals.GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectForImaginaries.GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)horizontalConvolutionEffect.GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)gammaExposureEffect.GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)inverseGammaExposureEffect.GetAddressOf()); + + ReadOnlyMemory pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height); + + // Load the source bitmap and create a destination bitmap + using ComPtr d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, gammaExposureEffect.Get()); + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height); + + // Create the resource texture for the real kernel + D2D1ResourceTextureManager kernelReals = new( + extents: stackalloc uint[] { (uint)KernelSize }, + bufferPrecision: D2D1BufferPrecision.Float32, + channelDepth: D2D1ChannelDepth.One, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp }, + data: MemoryMarshal.AsBytes(Kernels[0].Real.AsSpan()), + strides: ReadOnlySpan.Empty); + + // Also create the one for the imaginary kernel + D2D1ResourceTextureManager kernelImaginary = new( + extents: stackalloc uint[] { (uint)KernelSize }, + bufferPrecision: D2D1BufferPrecision.Float32, + channelDepth: D2D1ChannelDepth.One, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp }, + data: MemoryMarshal.AsBytes(Kernels[0].Imaginary.AsSpan()), + strides: ReadOnlySpan.Empty); + + // Assign the resource textures + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(verticalConvolutionEffectForReals.Get(), kernelReals, 1); + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(verticalConvolutionEffectForImaginaries.Get(), kernelImaginary, 1); + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(horizontalConvolutionEffect.Get(), kernelReals, 2); + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(horizontalConvolutionEffect.Get(), kernelImaginary, 3); + + // Set the constant buffers + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution((int)width, (int)height), verticalConvolutionEffectForReals.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution((int)width, (int)height), verticalConvolutionEffectForImaginaries.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new HorizontalConvolutionAndAccumulatePartials((int)width, (int)height, KernelParameters[0].Z, KernelParameters[0].W), horizontalConvolutionEffect.Get()); + + // Build the effect graph: + // + // [INPUT] ---> [GAMMA EXPOSURE] ---> [VERTICAL REAL] ------ + // \ \ + // -----------> [VERTICAL IMAGINARY] ----> [HORIZONTAL] ---> [INVERSE GAMMA EXPOSURE] ---> [OUTPUT] + verticalConvolutionEffectForReals.Get()->SetInputEffect(0, gammaExposureEffect.Get()); + verticalConvolutionEffectForImaginaries.Get()->SetInputEffect(0, gammaExposureEffect.Get()); + horizontalConvolutionEffect.Get()->SetInputEffect(0, verticalConvolutionEffectForReals.Get()); + horizontalConvolutionEffect.Get()->SetInputEffect(1, verticalConvolutionEffectForImaginaries.Get()); + inverseGammaExposureEffect.Get()->SetInputEffect(0, horizontalConvolutionEffect.Get()); + + d2D1DeviceContext.Get()->BeginDraw(); + + // Draw the final result + d2D1DeviceContext.Get()->DrawImage( + effect: inverseGammaExposureEffect.Get(), + targetOffset: null, + imageRectangle: null, + interpolationMode: D2D1_INTERPOLATION_MODE.D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR, + compositeMode: D2D1_COMPOSITE_MODE.D2D1_COMPOSITE_MODE_SOURCE_COPY); + + d2D1DeviceContext.Get()->EndDraw().Assert(); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + _ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!); + + ImageHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + } + + /// + /// Kernel for the vertical convolution pass for real or imaginary components. + /// + [D2DInputCount(1)] + [D2DInputComplex(0)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] + [D2DRequiresScenePosition] + [AutoConstructor] + internal partial struct VerticalConvolution : ID2D1PixelShader + { + private readonly int width; + private readonly int height; + + [D2DResourceTextureIndex(1)] + private readonly D2D1ResourceTexture1D kernel; + + /// + public float4 Execute() + { + int2 position = (int2)D2D.GetScenePosition().XY; + float4 result = float4.Zero; + int maxY = this.height; + int maxX = this.width; + int kernelLength = this.kernel.Width; + int radiusY = kernelLength >> 1; + int offsetX = Hlsl.Clamp(position.X, 0, maxX); + + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(position.Y + i - radiusY, 0, maxY); + float2 uv = new((float)offsetX / maxX, (float)offsetY / maxY); + float4 color = D2D.SampleInputAtPosition(0, uv); + float factor = this.kernel[i]; + + result += factor * color; + } + + return result; + } + } + + /// + /// Kernel for the horizontal convolution pass. + /// + [D2DInputCount(2)] + [D2DInputComplex(0)] + [D2DInputComplex(1)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] + [D2DRequiresScenePosition] + [AutoConstructor] + internal partial struct HorizontalConvolutionAndAccumulatePartials : ID2D1PixelShader + { + private readonly int width; + private readonly int height; + private readonly float z; + private readonly float w; + + [D2DResourceTextureIndex(2)] + private readonly D2D1ResourceTexture1D kernelReals; + + [D2DResourceTextureIndex(3)] + private readonly D2D1ResourceTexture1D kernelImaginaries; + + /// + public float4 Execute() + { + int2 position = (int2)D2D.GetScenePosition().XY; + float4 real = float4.Zero; + float4 imaginary = float4.Zero; + int maxY = this.width; + int maxX = this.width; + int kernelLength = this.kernelReals.Width; + int radiusX = kernelLength >> 1; + int offsetY = Hlsl.Clamp(position.Y, 0, maxY); + + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(position.X + i - radiusX, 0, maxX); + float2 uv = new((float)offsetX / maxX, (float)offsetY / maxY); + float4 sourceReal = D2D.SampleInputAtPosition(0, uv); + float4 sourceImaginary = D2D.SampleInputAtPosition(1, uv); + float realFactor = kernelReals[i]; + float imaginaryFactor = kernelImaginaries[i]; + + real += realFactor * sourceReal - imaginaryFactor * sourceImaginary; + imaginary += realFactor * sourceImaginary + imaginaryFactor * sourceReal; + } + + return real * z + imaginary * w; + } + } + + /// + /// Kernel for the gamma highlight pass. + /// + [D2DInputCount(1)] + [D2DInputSimple(0)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] + [AutoConstructor] + internal readonly partial struct GammaHighlight : ID2D1PixelShader + { + /// + public float4 Execute() + { + float4 pixel = D2D.GetInput(0); + + pixel.XYZ = pixel.XYZ * pixel.XYZ * pixel.XYZ; + + return pixel; + } + } + + /// + /// Kernel for the inverse gamma highlight pass. + /// + [D2DInputCount(1)] + [D2DInputSimple(0)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] + [AutoConstructor] + internal readonly partial struct InverseGammaHighlight : ID2D1PixelShader + { + /// + public float4 Execute() + { + float4 pixel = D2D.GetInput(0); + + pixel = Hlsl.Clamp(pixel, 0, float.MaxValue); + pixel.XYZ = Hlsl.Pow(pixel.XYZ, 1 / 3f); + + return pixel; + } + } + + /// + /// Represents a complex number, where the real and imaginary parts are stored as values. + /// + private readonly struct Complex64 + { + /// + /// The real part of the complex number. + /// + public readonly float Real; + + /// + /// The imaginary part of the complex number. + /// + public readonly float Imaginary; + + /// + /// Initializes a new instance of the struct. + /// + /// The real part in the complex number. + /// The imaginary part in the complex number. + public Complex64(float real, float imaginary) + { + this.Real = real; + this.Imaginary = imaginary; + } + + /// + /// Performs the multiplication operation between a instance and a scalar. + /// + /// The value to multiply. + /// The scalar to use to multiply the value. + /// The result. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Complex64 operator *(Complex64 value, float scalar) => new(value.Real * scalar, value.Imaginary * scalar); + } +} diff --git a/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs b/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs index 8a25a156..514cffa9 100644 --- a/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs @@ -1,4 +1,7 @@ -using ComputeSharp.D2D1.Tests.Effects; +using System.IO; +using System.Reflection; +using ComputeSharp.BokehBlur.Processors; +using ComputeSharp.D2D1.Tests.Effects; using ComputeSharp.D2D1.Tests.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; @@ -48,4 +51,17 @@ public class EndToEndTests { D2D1TestRunner.RunAndCompareShader(new CheckerboardClipEffect(1280, 840, 32), null, "Landscape.png", "Landscape_CheckerboardClip.png"); } + + [TestMethod] + public void BokehBlur() + { + BokehBlurEffect bokehBlurEffect = new(32, 1); + + string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); + string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp"); + + bokehBlurEffect.ApplyEffect( + Path.Combine(assetsPath, "Landscape.png"), + Path.Combine(temporaryPath, "Landscape_BokehBlur.png")); + } } \ No newline at end of file From 65c0c8df9529611a1f58f7cec227b547e30e5c10 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 19 Aug 2022 02:39:36 +0200 Subject: [PATCH 2/9] Add transform mappers for convolution effects --- .../Effects/BokehBlurEffect.cs | 204 +++++++++++------- 1 file changed, 130 insertions(+), 74 deletions(-) diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs index cabfaffd..124d6715 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Drawing; using System.IO; using System.Numerics; using System.Runtime.CompilerServices; @@ -292,8 +293,8 @@ public sealed partial class BokehBlurEffect using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); // Register all necessary effects - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); - D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), static () => new VerticalConvolution(), out _); + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), static () => new HorizontalConvolutionAndAccumulatePartials(), out _); D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); @@ -304,9 +305,9 @@ public sealed partial class BokehBlurEffect using ComPtr inverseGammaExposureEffect = default; // Create an instance of each effect - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectForReals.GetAddressOf()); - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectForImaginaries.GetAddressOf()); - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)horizontalConvolutionEffect.GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectForReals.GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectForImaginaries.GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)horizontalConvolutionEffect.GetAddressOf()); D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)gammaExposureEffect.GetAddressOf()); D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)inverseGammaExposureEffect.GetAddressOf()); @@ -343,9 +344,9 @@ public sealed partial class BokehBlurEffect D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(horizontalConvolutionEffect.Get(), kernelImaginary, 3); // Set the constant buffers - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution((int)width, (int)height), verticalConvolutionEffectForReals.Get()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution((int)width, (int)height), verticalConvolutionEffectForImaginaries.Get()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new HorizontalConvolutionAndAccumulatePartials((int)width, (int)height, KernelParameters[0].Z, KernelParameters[0].W), horizontalConvolutionEffect.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)width, (int)height), verticalConvolutionEffectForReals.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)width, (int)height), verticalConvolutionEffectForImaginaries.Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new HorizontalConvolutionAndAccumulatePartials.Shader((int)width, (int)height, KernelParameters[0].Z, KernelParameters[0].W), horizontalConvolutionEffect.Get()); // Build the effect graph: // @@ -378,94 +379,147 @@ public sealed partial class BokehBlurEffect } /// - /// Kernel for the vertical convolution pass for real or imaginary components. + /// The vertical convolution shader and transform. /// - [D2DInputCount(1)] - [D2DInputComplex(0)] - [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] - [D2DRequiresScenePosition] - [AutoConstructor] - internal partial struct VerticalConvolution : ID2D1PixelShader + private sealed partial class VerticalConvolution : ID2D1TransformMapper { - private readonly int width; - private readonly int height; - - [D2DResourceTextureIndex(1)] - private readonly D2D1ResourceTexture1D kernel; + /// + public void MapInputsToOutput(in Shader shader, ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput) + { + output = Rectangle.Inflate(inputs[0], 0, 100); + opaqueOutput = Rectangle.Empty; + } /// - public float4 Execute() + public void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput) { - int2 position = (int2)D2D.GetScenePosition().XY; - float4 result = float4.Zero; - int maxY = this.height; - int maxX = this.width; - int kernelLength = this.kernel.Width; - int radiusY = kernelLength >> 1; - int offsetX = Hlsl.Clamp(position.X, 0, maxX); + invalidOutput = invalidInput; + } - for (int i = 0; i < kernelLength; i++) + /// + public void MapOutputToInputs(in Rectangle output, Span inputs) + { + inputs.Fill(output); + } + + /// + /// Kernel for the vertical convolution pass for real or imaginary components. + /// + [D2DInputCount(1)] + [D2DInputComplex(0)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] + [D2DRequiresScenePosition] + [AutoConstructor] + public partial struct Shader : ID2D1PixelShader + { + private readonly int width; + private readonly int height; + + [D2DResourceTextureIndex(1)] + private readonly D2D1ResourceTexture1D kernel; + + /// + public float4 Execute() { - int offsetY = Hlsl.Clamp(position.Y + i - radiusY, 0, maxY); - float2 uv = new((float)offsetX / maxX, (float)offsetY / maxY); - float4 color = D2D.SampleInputAtPosition(0, uv); - float factor = this.kernel[i]; + int2 position = (int2)D2D.GetScenePosition().XY; + float4 result = float4.Zero; + int maxY = this.height; + int maxX = this.width; + int kernelLength = this.kernel.Width; + int radiusY = kernelLength >> 1; + int offsetX = Hlsl.Clamp(position.X, 0, maxX); - result += factor * color; + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(position.Y + i - radiusY, 0, maxY); + float2 uv = new((float)offsetX / maxX, (float)offsetY / maxY); + float4 color = D2D.SampleInputAtPosition(0, uv); + float factor = this.kernel[i]; + + result += factor * color; + } + + return result; } - - return result; } } /// - /// Kernel for the horizontal convolution pass. + /// The horizontal convolutin and partial accumulation effect and transform. /// - [D2DInputCount(2)] - [D2DInputComplex(0)] - [D2DInputComplex(1)] - [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] - [D2DRequiresScenePosition] - [AutoConstructor] - internal partial struct HorizontalConvolutionAndAccumulatePartials : ID2D1PixelShader + private sealed partial class HorizontalConvolutionAndAccumulatePartials : ID2D1TransformMapper { - private readonly int width; - private readonly int height; - private readonly float z; - private readonly float w; - - [D2DResourceTextureIndex(2)] - private readonly D2D1ResourceTexture1D kernelReals; - - [D2DResourceTextureIndex(3)] - private readonly D2D1ResourceTexture1D kernelImaginaries; + /// + public void MapInputsToOutput(in Shader shader, ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput) + { + output = Rectangle.Inflate(inputs[0], 100, 0); + opaqueOutput = Rectangle.Empty; + } /// - public float4 Execute() + public void MapInvalidOutput(int inputIndex, Rectangle invalidInput, out Rectangle invalidOutput) { - int2 position = (int2)D2D.GetScenePosition().XY; - float4 real = float4.Zero; - float4 imaginary = float4.Zero; - int maxY = this.width; - int maxX = this.width; - int kernelLength = this.kernelReals.Width; - int radiusX = kernelLength >> 1; - int offsetY = Hlsl.Clamp(position.Y, 0, maxY); + invalidOutput = invalidInput; + } - for (int i = 0; i < kernelLength; i++) + /// + public void MapOutputToInputs(in Rectangle output, Span inputs) + { + inputs.Fill(output); + } + + /// + /// Kernel for the horizontal convolution pass. + /// + [D2DInputCount(2)] + [D2DInputComplex(0)] + [D2DInputComplex(1)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + [D2DInputDescription(1, D2D1Filter.MinMagMipPoint)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] + [D2DRequiresScenePosition] + [AutoConstructor] + public partial struct Shader : ID2D1PixelShader + { + private readonly int width; + private readonly int height; + private readonly float z; + private readonly float w; + + [D2DResourceTextureIndex(2)] + private readonly D2D1ResourceTexture1D kernelReals; + + [D2DResourceTextureIndex(3)] + private readonly D2D1ResourceTexture1D kernelImaginaries; + + /// + public float4 Execute() { - int offsetX = Hlsl.Clamp(position.X + i - radiusX, 0, maxX); - float2 uv = new((float)offsetX / maxX, (float)offsetY / maxY); - float4 sourceReal = D2D.SampleInputAtPosition(0, uv); - float4 sourceImaginary = D2D.SampleInputAtPosition(1, uv); - float realFactor = kernelReals[i]; - float imaginaryFactor = kernelImaginaries[i]; + int2 position = (int2)D2D.GetScenePosition().XY; + float4 real = float4.Zero; + float4 imaginary = float4.Zero; + int maxY = this.width; + int maxX = this.width; + int kernelLength = this.kernelReals.Width; + int radiusX = kernelLength >> 1; + int offsetY = Hlsl.Clamp(position.Y, 0, maxY); - real += realFactor * sourceReal - imaginaryFactor * sourceImaginary; - imaginary += realFactor * sourceImaginary + imaginaryFactor * sourceReal; + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(position.X + i - radiusX, 0, maxX); + float2 uv = new((float)offsetX / maxX, (float)offsetY / maxY); + float4 sourceReal = D2D.SampleInputAtPosition(0, uv); + float4 sourceImaginary = D2D.SampleInputAtPosition(1, uv); + float realFactor = kernelReals[i]; + float imaginaryFactor = kernelImaginaries[i]; + + real += realFactor * sourceReal - imaginaryFactor * sourceImaginary; + imaginary += realFactor * sourceImaginary + imaginaryFactor * sourceReal; + } + + return real * z + imaginary * w; } - - return real * z + imaginary * w; } } @@ -474,6 +528,7 @@ public sealed partial class BokehBlurEffect /// [D2DInputCount(1)] [D2DInputSimple(0)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] [AutoConstructor] internal readonly partial struct GammaHighlight : ID2D1PixelShader @@ -494,6 +549,7 @@ public sealed partial class BokehBlurEffect /// [D2DInputCount(1)] [D2DInputSimple(0)] + [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] [AutoConstructor] internal readonly partial struct InverseGammaHighlight : ID2D1PixelShader From 1db6b075bc8aab32be5fdf1953596807b75dbc27 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 19 Aug 2022 03:41:26 +0200 Subject: [PATCH 3/9] Fix sampling in bokeh blur shaders --- tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs index 124d6715..49d6652a 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs @@ -434,7 +434,7 @@ public sealed partial class BokehBlurEffect { int offsetY = Hlsl.Clamp(position.Y + i - radiusY, 0, maxY); float2 uv = new((float)offsetX / maxX, (float)offsetY / maxY); - float4 color = D2D.SampleInputAtPosition(0, uv); + float4 color = D2D.SampleInput(0, uv); float factor = this.kernel[i]; result += factor * color; @@ -509,8 +509,8 @@ public sealed partial class BokehBlurEffect { int offsetX = Hlsl.Clamp(position.X + i - radiusX, 0, maxX); float2 uv = new((float)offsetX / maxX, (float)offsetY / maxY); - float4 sourceReal = D2D.SampleInputAtPosition(0, uv); - float4 sourceImaginary = D2D.SampleInputAtPosition(1, uv); + float4 sourceReal = D2D.SampleInput(0, uv); + float4 sourceImaginary = D2D.SampleInput(1, uv); float realFactor = kernelReals[i]; float imaginaryFactor = kernelImaginaries[i]; From 233ae99ec90dd5033bff8d8fa87831028f099236 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 19 Aug 2022 03:59:08 +0200 Subject: [PATCH 4/9] First attempt to support multiple components --- .../Effects/BokehBlurEffect.cs | 190 ++++++++++++------ 1 file changed, 128 insertions(+), 62 deletions(-) diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs index 49d6652a..a24b77fb 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs @@ -298,84 +298,150 @@ public sealed partial class BokehBlurEffect D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), out _); - using ComPtr verticalConvolutionEffectForReals = default; - using ComPtr verticalConvolutionEffectForImaginaries = default; - using ComPtr horizontalConvolutionEffect = default; + int numberOfComponents = KernelParameters.Length; + using ComPtr gammaExposureEffect = default; using ComPtr inverseGammaExposureEffect = default; + using ComPtr compositeEffect = default; + Span> verticalConvolutionEffectsForReals = stackalloc ComPtr[numberOfComponents]; + Span> verticalConvolutionEffectsForImaginaries = stackalloc ComPtr[numberOfComponents]; + Span> horizontalConvolutionEffects = stackalloc ComPtr[numberOfComponents]; - // Create an instance of each effect - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectForReals.GetAddressOf()); - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectForImaginaries.GetAddressOf()); - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)horizontalConvolutionEffect.GetAddressOf()); - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)gammaExposureEffect.GetAddressOf()); - D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)inverseGammaExposureEffect.GetAddressOf()); + try + { + // Create an instance of each effect + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)gammaExposureEffect.GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)inverseGammaExposureEffect.GetAddressOf()); - ReadOnlyMemory pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height); + for (int i = 0; i < numberOfComponents; i++) + { + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectsForReals[i].GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)verticalConvolutionEffectsForImaginaries[i].GetAddressOf()); + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)horizontalConvolutionEffects[i].GetAddressOf()); + } - // Load the source bitmap and create a destination bitmap - using ComPtr d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, gammaExposureEffect.Get()); - using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height); + // If partials need to be summed, also create the composite effect + if (numberOfComponents > 1) + { + d2D1DeviceContext.Get()->CreateEffect( + effectId: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_D2D1Composite)), + effect: compositeEffect.GetAddressOf()).Assert(); - // Create the resource texture for the real kernel - D2D1ResourceTextureManager kernelReals = new( - extents: stackalloc uint[] { (uint)KernelSize }, - bufferPrecision: D2D1BufferPrecision.Float32, - channelDepth: D2D1ChannelDepth.One, - filter: D2D1Filter.MinMagMipPoint, - extendModes: stackalloc[] { D2D1ExtendMode.Clamp }, - data: MemoryMarshal.AsBytes(Kernels[0].Real.AsSpan()), - strides: ReadOnlySpan.Empty); + D2D1_COMPOSITE_MODE d2D1CompositeMode = D2D1_COMPOSITE_MODE.D2D1_COMPOSITE_MODE_PLUS; - // Also create the one for the imaginary kernel - D2D1ResourceTextureManager kernelImaginary = new( - extents: stackalloc uint[] { (uint)KernelSize }, - bufferPrecision: D2D1BufferPrecision.Float32, - channelDepth: D2D1ChannelDepth.One, - filter: D2D1Filter.MinMagMipPoint, - extendModes: stackalloc[] { D2D1ExtendMode.Clamp }, - data: MemoryMarshal.AsBytes(Kernels[0].Imaginary.AsSpan()), - strides: ReadOnlySpan.Empty); + // Set the mode to plus + compositeEffect.Get()->SetValue((uint)D2D1_COMPOSITE_PROP.D2D1_COMPOSITE_PROP_MODE, (byte*)&d2D1CompositeMode, sizeof(D2D1_COMPOSITE_MODE)).Assert(); + } - // Assign the resource textures - D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(verticalConvolutionEffectForReals.Get(), kernelReals, 1); - D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(verticalConvolutionEffectForImaginaries.Get(), kernelImaginary, 1); - D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(horizontalConvolutionEffect.Get(), kernelReals, 2); - D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(horizontalConvolutionEffect.Get(), kernelImaginary, 3); + ReadOnlyMemory pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height); - // Set the constant buffers - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)width, (int)height), verticalConvolutionEffectForReals.Get()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)width, (int)height), verticalConvolutionEffectForImaginaries.Get()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new HorizontalConvolutionAndAccumulatePartials.Shader((int)width, (int)height, KernelParameters[0].Z, KernelParameters[0].W), horizontalConvolutionEffect.Get()); + // Load the source bitmap and create a destination bitmap + using ComPtr d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, gammaExposureEffect.Get()); + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height); - // Build the effect graph: - // - // [INPUT] ---> [GAMMA EXPOSURE] ---> [VERTICAL REAL] ------ - // \ \ - // -----------> [VERTICAL IMAGINARY] ----> [HORIZONTAL] ---> [INVERSE GAMMA EXPOSURE] ---> [OUTPUT] - verticalConvolutionEffectForReals.Get()->SetInputEffect(0, gammaExposureEffect.Get()); - verticalConvolutionEffectForImaginaries.Get()->SetInputEffect(0, gammaExposureEffect.Get()); - horizontalConvolutionEffect.Get()->SetInputEffect(0, verticalConvolutionEffectForReals.Get()); - horizontalConvolutionEffect.Get()->SetInputEffect(1, verticalConvolutionEffectForImaginaries.Get()); - inverseGammaExposureEffect.Get()->SetInputEffect(0, horizontalConvolutionEffect.Get()); + (D2D1ResourceTextureManager Reals, D2D1ResourceTextureManager Imaginaries)[] kernels = new (D2D1ResourceTextureManager, D2D1ResourceTextureManager)[numberOfComponents]; + uint kernelSize = (uint)KernelSize; - d2D1DeviceContext.Get()->BeginDraw(); + for (int i = 0; i < numberOfComponents; i++) + { + // Create the resource texture for the real kernel + D2D1ResourceTextureManager kernelReals = new( + extents: new Span(&kernelSize, 1), + bufferPrecision: D2D1BufferPrecision.Float32, + channelDepth: D2D1ChannelDepth.One, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp }, + data: MemoryMarshal.AsBytes(Kernels[i].Real.AsSpan()), + strides: ReadOnlySpan.Empty); - // Draw the final result - d2D1DeviceContext.Get()->DrawImage( - effect: inverseGammaExposureEffect.Get(), - targetOffset: null, - imageRectangle: null, - interpolationMode: D2D1_INTERPOLATION_MODE.D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR, - compositeMode: D2D1_COMPOSITE_MODE.D2D1_COMPOSITE_MODE_SOURCE_COPY); + // Also create the one for the imaginary kernel + D2D1ResourceTextureManager kernelImaginary = new( + extents: new Span(&kernelSize, 1), + bufferPrecision: D2D1BufferPrecision.Float32, + channelDepth: D2D1ChannelDepth.One, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp }, + data: MemoryMarshal.AsBytes(Kernels[i].Imaginary.AsSpan()), + strides: ReadOnlySpan.Empty); - d2D1DeviceContext.Get()->EndDraw().Assert(); + kernels[i] = (kernelReals, kernelImaginary); + } - using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + // Assign the resource textures + for (int i = 0; i < numberOfComponents; i++) + { + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(verticalConvolutionEffectsForReals[i].Get(), kernels[i].Reals, 1); + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(verticalConvolutionEffectsForImaginaries[i].Get(), kernels[i].Imaginaries, 1); + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(horizontalConvolutionEffects[i].Get(), kernels[i].Reals, 2); + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(horizontalConvolutionEffects[i].Get(), kernels[i].Imaginaries, 3); + } - _ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!); + // Set the constant buffers + for (int i = 0; i < numberOfComponents; i++) + { + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)width, (int)height), verticalConvolutionEffectsForReals[i].Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)width, (int)height), verticalConvolutionEffectsForImaginaries[i].Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new HorizontalConvolutionAndAccumulatePartials.Shader((int)width, (int)height, KernelParameters[i].Z, KernelParameters[i].W), horizontalConvolutionEffects[i].Get()); + } - ImageHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + // Build the effect graph: + // + // [INPUT] ---> [GAMMA EXPOSURE] ---> [VERTICAL REAL] ------ + // \ \ + // -----------> [VERTICAL IMAGINARY] ----> [HORIZONTAL] ---> [INVERSE GAMMA EXPOSURE] ---> [OUTPUT] + for (int i = 0; i < numberOfComponents; i++) + { + verticalConvolutionEffectsForReals[i].Get()->SetInputEffect(0, gammaExposureEffect.Get()); + verticalConvolutionEffectsForImaginaries[i].Get()->SetInputEffect(0, gammaExposureEffect.Get()); + horizontalConvolutionEffects[i].Get()->SetInputEffect(0, verticalConvolutionEffectsForReals[i].Get()); + horizontalConvolutionEffects[i].Get()->SetInputEffect(1, verticalConvolutionEffectsForImaginaries[i].Get()); + } + + // Connect to the output node + if (numberOfComponents == 1) + { + inverseGammaExposureEffect.Get()->SetInputEffect(0, horizontalConvolutionEffects[0].Get()); + } + else + { + compositeEffect.Get()->SetInputCount((uint)numberOfComponents); + + // Aggregate all partial results with the composite effect + for (int i = 0; i < numberOfComponents; i++) + { + compositeEffect.Get()->SetInputEffect((uint)i, horizontalConvolutionEffects[i].Get()); + } + + inverseGammaExposureEffect.Get()->SetInputEffect(0, compositeEffect.Get()); + } + + d2D1DeviceContext.Get()->BeginDraw(); + + // Draw the final result + d2D1DeviceContext.Get()->DrawImage( + effect: inverseGammaExposureEffect.Get(), + targetOffset: null, + imageRectangle: null, + interpolationMode: D2D1_INTERPOLATION_MODE.D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR, + compositeMode: D2D1_COMPOSITE_MODE.D2D1_COMPOSITE_MODE_SOURCE_COPY); + + d2D1DeviceContext.Get()->EndDraw().Assert(); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + _ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!); + + ImageHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + } + finally + { + for (int i = 0; i < numberOfComponents; i++) + { + verticalConvolutionEffectsForReals[i].Dispose(); + verticalConvolutionEffectsForImaginaries[i].Dispose(); + horizontalConvolutionEffects[i].Dispose(); + } + } } /// From 84da270ae81ba45ed6a99bd2c47871c6a4dda515 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 19 Aug 2022 04:17:45 +0200 Subject: [PATCH 5/9] Increase channel precision to 32 bits to fix banding --- tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs | 9 +++++++++ tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs | 2 +- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs index a24b77fb..2de73bc0 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs @@ -327,6 +327,11 @@ public sealed partial class BokehBlurEffect effectId: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_D2D1Composite)), effect: compositeEffect.GetAddressOf()).Assert(); + D2D1_BUFFER_PRECISION d2D1BufferPrecision = D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT; + + // Set the channel precision to 32 bits manually to avoid banding + compositeEffect.Get()->SetValue((uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, (byte*)&d2D1BufferPrecision, sizeof(D2D1_BUFFER_PRECISION)).Assert(); + D2D1_COMPOSITE_MODE d2D1CompositeMode = D2D1_COMPOSITE_MODE.D2D1_COMPOSITE_MODE_PLUS; // Set the mode to plus @@ -474,6 +479,7 @@ public sealed partial class BokehBlurEffect [D2DInputCount(1)] [D2DInputComplex(0)] [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + [D2DOutputBuffer(D2D1BufferPrecision.Float32, D2D1ChannelDepth.Four)] [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] [D2DRequiresScenePosition] [AutoConstructor] @@ -543,6 +549,7 @@ public sealed partial class BokehBlurEffect [D2DInputComplex(1)] [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] [D2DInputDescription(1, D2D1Filter.MinMagMipPoint)] + [D2DOutputBuffer(D2D1BufferPrecision.Float32, D2D1ChannelDepth.Four)] [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] [D2DRequiresScenePosition] [AutoConstructor] @@ -595,6 +602,7 @@ public sealed partial class BokehBlurEffect [D2DInputCount(1)] [D2DInputSimple(0)] [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + [D2DOutputBuffer(D2D1BufferPrecision.Float32, D2D1ChannelDepth.Four)] [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] [AutoConstructor] internal readonly partial struct GammaHighlight : ID2D1PixelShader @@ -616,6 +624,7 @@ public sealed partial class BokehBlurEffect [D2DInputCount(1)] [D2DInputSimple(0)] [D2DInputDescription(0, D2D1Filter.MinMagMipPoint)] + [D2DOutputBuffer(D2D1BufferPrecision.Float32, D2D1ChannelDepth.Four)] [D2DShaderProfile(D2D1ShaderProfile.PixelShader50)] [AutoConstructor] internal readonly partial struct InverseGammaHighlight : ID2D1PixelShader diff --git a/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs b/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs index 514cffa9..619e57c0 100644 --- a/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs @@ -55,7 +55,7 @@ public class EndToEndTests [TestMethod] public void BokehBlur() { - BokehBlurEffect bokehBlurEffect = new(32, 1); + BokehBlurEffect bokehBlurEffect = new(32, 3); string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp"); From 5dd39fb9cc6af05ebb67738ab739e4e5f29766b5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 19 Aug 2022 12:40:56 +0200 Subject: [PATCH 6/9] Fix D2D1 bokeh blur effect transforms --- .../Effects/BokehBlurEffect.cs | 68 ++++++++++--------- 1 file changed, 36 insertions(+), 32 deletions(-) diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs index 2de73bc0..c2df970b 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs @@ -384,9 +384,9 @@ public sealed partial class BokehBlurEffect // Set the constant buffers for (int i = 0; i < numberOfComponents; i++) { - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)width, (int)height), verticalConvolutionEffectsForReals[i].Get()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)width, (int)height), verticalConvolutionEffectsForImaginaries[i].Get()); - D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new HorizontalConvolutionAndAccumulatePartials.Shader((int)width, (int)height, KernelParameters[i].Z, KernelParameters[i].W), horizontalConvolutionEffects[i].Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)kernelSize), verticalConvolutionEffectsForReals[i].Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new VerticalConvolution.Shader((int)kernelSize), verticalConvolutionEffectsForImaginaries[i].Get()); + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(new HorizontalConvolutionAndAccumulatePartials.Shader((int)kernelSize, KernelParameters[i].Z, KernelParameters[i].W), horizontalConvolutionEffects[i].Get()); } // Build the effect graph: @@ -454,10 +454,17 @@ public sealed partial class BokehBlurEffect /// private sealed partial class VerticalConvolution : ID2D1TransformMapper { + /// + /// The length of the convolution kernel. + /// + private int kernelLength; + /// public void MapInputsToOutput(in Shader shader, ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput) { - output = Rectangle.Inflate(inputs[0], 0, 100); + this.kernelLength = shader.kernelLength; + + output = inputs[0]; opaqueOutput = Rectangle.Empty; } @@ -470,7 +477,9 @@ public sealed partial class BokehBlurEffect /// public void MapOutputToInputs(in Rectangle output, Span inputs) { - inputs.Fill(output); + Rectangle input = Rectangle.Inflate(output, 0, this.kernelLength); + + inputs.Fill(input); } /// @@ -485,8 +494,7 @@ public sealed partial class BokehBlurEffect [AutoConstructor] public partial struct Shader : ID2D1PixelShader { - private readonly int width; - private readonly int height; + public readonly int kernelLength; [D2DResourceTextureIndex(1)] private readonly D2D1ResourceTexture1D kernel; @@ -494,19 +502,13 @@ public sealed partial class BokehBlurEffect /// public float4 Execute() { - int2 position = (int2)D2D.GetScenePosition().XY; float4 result = float4.Zero; - int maxY = this.height; - int maxX = this.width; - int kernelLength = this.kernel.Width; - int radiusY = kernelLength >> 1; - int offsetX = Hlsl.Clamp(position.X, 0, maxX); + int length = this.kernelLength; + int radiusY = length >> 1; - for (int i = 0; i < kernelLength; i++) + for (int i = 0; i < length; i++) { - int offsetY = Hlsl.Clamp(position.Y + i - radiusY, 0, maxY); - float2 uv = new((float)offsetX / maxX, (float)offsetY / maxY); - float4 color = D2D.SampleInput(0, uv); + float4 color = D2D.SampleInputAtOffset(0, new float2(0, i - radiusY)); float factor = this.kernel[i]; result += factor * color; @@ -522,10 +524,17 @@ public sealed partial class BokehBlurEffect /// private sealed partial class HorizontalConvolutionAndAccumulatePartials : ID2D1TransformMapper { + /// + /// The length of the convolution kernel. + /// + private int kernelLength; + /// public void MapInputsToOutput(in Shader shader, ReadOnlySpan inputs, ReadOnlySpan opaqueInputs, out Rectangle output, out Rectangle opaqueOutput) { - output = Rectangle.Inflate(inputs[0], 100, 0); + this.kernelLength = shader.kernelLength; + + output = inputs[0]; opaqueOutput = Rectangle.Empty; } @@ -538,7 +547,9 @@ public sealed partial class BokehBlurEffect /// public void MapOutputToInputs(in Rectangle output, Span inputs) { - inputs.Fill(output); + Rectangle input = Rectangle.Inflate(output, this.kernelLength, 0); + + inputs.Fill(input); } /// @@ -555,8 +566,7 @@ public sealed partial class BokehBlurEffect [AutoConstructor] public partial struct Shader : ID2D1PixelShader { - private readonly int width; - private readonly int height; + public readonly int kernelLength; private readonly float z; private readonly float w; @@ -569,21 +579,15 @@ public sealed partial class BokehBlurEffect /// public float4 Execute() { - int2 position = (int2)D2D.GetScenePosition().XY; float4 real = float4.Zero; float4 imaginary = float4.Zero; - int maxY = this.width; - int maxX = this.width; - int kernelLength = this.kernelReals.Width; - int radiusX = kernelLength >> 1; - int offsetY = Hlsl.Clamp(position.Y, 0, maxY); + int length = this.kernelLength; + int radiusX = length >> 1; - for (int i = 0; i < kernelLength; i++) + for (int i = 0; i < length; i++) { - int offsetX = Hlsl.Clamp(position.X + i - radiusX, 0, maxX); - float2 uv = new((float)offsetX / maxX, (float)offsetY / maxY); - float4 sourceReal = D2D.SampleInput(0, uv); - float4 sourceImaginary = D2D.SampleInput(1, uv); + float4 sourceReal = D2D.SampleInputAtOffset(0, new float2(i - radiusX, 0)); + float4 sourceImaginary = D2D.SampleInputAtOffset(1, new float2(i - radiusX, 0)); float realFactor = kernelReals[i]; float imaginaryFactor = kernelImaginaries[i]; From ca9aef9b9b6d6ea9e942522dadf8b6a32fb6e255 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 19 Aug 2022 19:34:08 +0200 Subject: [PATCH 7/9] Add border effect to fix edge clamping --- .../Effects/BokehBlurEffect.cs | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs index c2df970b..810cb67d 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs @@ -303,6 +303,8 @@ public sealed partial class BokehBlurEffect using ComPtr gammaExposureEffect = default; using ComPtr inverseGammaExposureEffect = default; using ComPtr compositeEffect = default; + using ComPtr borderEffect = default; + Span> verticalConvolutionEffectsForReals = stackalloc ComPtr[numberOfComponents]; Span> verticalConvolutionEffectsForImaginaries = stackalloc ComPtr[numberOfComponents]; Span> horizontalConvolutionEffects = stackalloc ComPtr[numberOfComponents]; @@ -320,6 +322,17 @@ public sealed partial class BokehBlurEffect D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)horizontalConvolutionEffects[i].GetAddressOf()); } + // Create the border effect to clamp the input image + d2D1DeviceContext.Get()->CreateEffect( + effectId: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_D2D1Border)), + effect: borderEffect.GetAddressOf()).Assert(); + + D2D1_BORDER_EDGE_MODE d2D1BorderEdgeMode = D2D1_BORDER_EDGE_MODE.D2D1_BORDER_EDGE_MODE_CLAMP; + + // Set the border mode to clamp on both axes + borderEffect.Get()->SetValue((uint)D2D1_BORDER_PROP.D2D1_BORDER_PROP_EDGE_MODE_X, (byte*)&d2D1BorderEdgeMode, sizeof(D2D1_BORDER_EDGE_MODE)).Assert(); + borderEffect.Get()->SetValue((uint)D2D1_BORDER_PROP.D2D1_BORDER_PROP_EDGE_MODE_Y, (byte*)&d2D1BorderEdgeMode, sizeof(D2D1_BORDER_EDGE_MODE)).Assert(); + // If partials need to be summed, also create the composite effect if (numberOfComponents > 1) { @@ -391,13 +404,15 @@ public sealed partial class BokehBlurEffect // Build the effect graph: // - // [INPUT] ---> [GAMMA EXPOSURE] ---> [VERTICAL REAL] ------ - // \ \ - // -----------> [VERTICAL IMAGINARY] ----> [HORIZONTAL] ---> [INVERSE GAMMA EXPOSURE] ---> [OUTPUT] + // [INPUT] ---> [BORDER] --> [GAMMA EXPOSURE] ---> [VERTICAL REAL] ---- + // \ \ + // -----> [VERTICAL IMAGINARY] ----> [HORIZONTAL] ---> [INVERSE GAMMA EXPOSURE] ---> [OUTPUT] + borderEffect.Get()->SetInputEffect(0, gammaExposureEffect.Get()); + for (int i = 0; i < numberOfComponents; i++) { - verticalConvolutionEffectsForReals[i].Get()->SetInputEffect(0, gammaExposureEffect.Get()); - verticalConvolutionEffectsForImaginaries[i].Get()->SetInputEffect(0, gammaExposureEffect.Get()); + verticalConvolutionEffectsForReals[i].Get()->SetInputEffect(0, borderEffect.Get()); + verticalConvolutionEffectsForImaginaries[i].Get()->SetInputEffect(0, borderEffect.Get()); horizontalConvolutionEffects[i].Get()->SetInputEffect(0, verticalConvolutionEffectsForReals[i].Get()); horizontalConvolutionEffects[i].Get()->SetInputEffect(1, verticalConvolutionEffectsForImaginaries[i].Get()); } From bef0c333f7b2006a2c0c5234e5d49d9bd8c9b8e9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 20 Aug 2022 00:44:29 +0200 Subject: [PATCH 8/9] Fix color banding issue in D2D1 bokeh blur --- .../ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs index 810cb67d..bcecb144 100644 --- a/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs +++ b/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs @@ -292,6 +292,16 @@ public sealed partial class BokehBlurEffect using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + D2D1_RENDERING_CONTROLS d2D1RenderingControls = default; + + d2D1DeviceContext.Get()->GetRenderingControls(&d2D1RenderingControls); + + // Set the buffer precision for the whole context to 32 bits per channel. This avoids + // color banding issues due to intermediate buffers clamping to just 8 bits per channel. + d2D1RenderingControls.bufferPrecision = D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT; + + d2D1DeviceContext.Get()->SetRenderingControls(&d2D1RenderingControls); + // Register all necessary effects D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), static () => new VerticalConvolution(), out _); D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), static () => new HorizontalConvolutionAndAccumulatePartials(), out _); From ff9fa35989ee4cf00364f6adefdea6fcc80288a9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 20 Aug 2022 00:44:45 +0200 Subject: [PATCH 9/9] Enable proper D2D1 bokeh blur unit tests --- .../ComputeSharp.D2D1.Tests.csproj | 3 +++ .../ComputeSharp.D2D1.Tests/EndToEndTests.cs | 27 ++++++++++++++----- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj b/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj index dbe90541..09b62fe1 100644 --- a/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj +++ b/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj @@ -50,6 +50,9 @@ PreserveNewest + + PreserveNewest + diff --git a/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs b/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs index 619e57c0..b6bcd911 100644 --- a/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs @@ -3,8 +3,11 @@ using System.Reflection; using ComputeSharp.BokehBlur.Processors; using ComputeSharp.D2D1.Tests.Effects; using ComputeSharp.D2D1.Tests.Helpers; +using ComputeSharp.Tests.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; namespace ComputeSharp.D2D1.Tests; @@ -53,15 +56,27 @@ public class EndToEndTests } [TestMethod] - public void BokehBlur() + [DataRow(8, 1, "Landscape")] + [DataRow(32, 3, "Landscape")] + [DataRow(80, 1, "City")] + [DataRow(80, 2, "City")] + public void BokehBlur(int radius, int numberOfComponents, string filename) { - BokehBlurEffect bokehBlurEffect = new(32, 3); - string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp"); + string sourcePath = Path.Combine(assetsPath, Path.ChangeExtension(filename, "png")); + string destinationPathForCpu = Path.Combine(temporaryPath, Path.ChangeExtension($"{filename}_{radius}_{numberOfComponents}_cpu", "png")); + string destinationPathForGpu = Path.Combine(temporaryPath, Path.ChangeExtension($"{filename}_{radius}_{numberOfComponents}_gpu", "png")); - bokehBlurEffect.ApplyEffect( - Path.Combine(assetsPath, "Landscape.png"), - Path.Combine(temporaryPath, "Landscape_BokehBlur.png")); + _ = Directory.CreateDirectory(temporaryPath); + + using Image original = Image.Load(sourcePath); + using Image cpu = original.Clone(c => c.BokehBlur(radius, numberOfComponents, 3)); + + cpu.SaveAsPng(destinationPathForCpu); + + new BokehBlurEffect(radius, numberOfComponents).ApplyEffect(sourcePath, destinationPathForGpu); + + TolerantImageComparer.AssertEqual(destinationPathForCpu, destinationPathForGpu, 0.00002f); } } \ No newline at end of file