diff --git a/nuget.config b/nuget.config index a06b48ea..e71007c9 100644 --- a/nuget.config +++ b/nuget.config @@ -4,5 +4,6 @@ + diff --git a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj index e95049bf..4a6eded4 100644 --- a/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj +++ b/samples/ComputeSharp.Benchmark/ComputeSharp.Benchmark.csproj @@ -19,8 +19,8 @@ - - + + diff --git a/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs b/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs index aa4d4873..e518da56 100644 --- a/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Imaging/ImagingBenchmark.cs @@ -65,7 +65,7 @@ namespace ComputeSharp.Benchmark.Imaging [BenchmarkCategory("BOKEH")] public void Bokeh_Gpu() { - this.image.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2, 3))); + this.image.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2))); } /// diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs index 84e05a55..e9bd5cfe 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs @@ -1,7 +1,10 @@ using System.Numerics; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Diagnostics; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.BokehBlur.Processors { @@ -20,27 +23,23 @@ namespace ComputeSharp.BokehBlur.Processors /// public const int DefaultComponents = 2; - /// - /// The default gamma used by the parameterless constructor. - /// - public const float DefaultGamma = 3f; - /// /// Initializes a new instance of the class. /// - public HlslBokehBlurProcessor() : this(DefaultRadius, DefaultComponents, DefaultGamma) { } + public HlslBokehBlurProcessor() + : this(DefaultRadius, DefaultComponents) + { + } /// /// 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. - /// The gamma highlight factor to use to further process the image. - public HlslBokehBlurProcessor(int radius, int components, float gamma) + public HlslBokehBlurProcessor(int radius, int components) { Radius = radius; Components = components; - Gamma = gamma; } /// @@ -53,16 +52,18 @@ namespace ComputeSharp.BokehBlur.Processors /// public int Components { get; } - /// - /// Gets the gamma highlight factor to use when applying the effect. - /// - public float Gamma { get; } - /// public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle) where TPixel : unmanaged, IPixel { - return new HlslBokehBlurProcessor(this, configuration, source, sourceRectangle); + if (typeof(TPixel) != typeof(ImageSharpRgba32)) + { + ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format"); + } + + var processor = new Implementation(this, configuration, Unsafe.As>(source), sourceRectangle); + + return Unsafe.As>(processor); } /// diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index bbc41abb..f35defb8 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -10,446 +10,446 @@ using SixLabors.ImageSharp; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.BokehBlur.Processors { - /// - /// Applies bokeh blur processing to the image. - /// - /// The pixel format. - /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve. - public sealed partial class HlslBokehBlurProcessor : ImageProcessor - where TPixel : unmanaged, IPixel + /// + public sealed partial class HlslBokehBlurProcessor { /// - /// The kernel radius. + /// Applies bokeh blur processing to the image. /// - private readonly int Radius; - - /// - /// The gamma highlight factor to use when applying the effect. - /// - private readonly float Gamma; - - /// - /// 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 Complex64[][] 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, Complex64[][] Kernels)> Cache = new(); - - /// - /// Initializes a new instance of the class. - /// - /// The defining the processor parameters. - /// The configuration which allows altering default behaviour or extending the library. - /// The source instance to modify. - /// The source that indicates the area to edit. - public HlslBokehBlurProcessor(HlslBokehBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle) - : base(configuration, source, sourceRectangle) + /// This processor is based on the code from Mike Pound, see github.com/mikepound/convolve. + public sealed partial class Implementation : ImageProcessor { - Radius = definition.Radius; - KernelSize = Radius * 2 + 1; - ComponentsCount = definition.Components; - Gamma = definition.Gamma; + /// + /// The kernel radius. + /// + private readonly int Radius; - // Reuse the initialized values from the cache, if possible - var parameters = (Radius, ComponentsCount); - if (Cache.TryGetValue(parameters, out var info)) + /// + /// 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 Complex64[][] 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, Complex64[][] Kernels)> Cache = new(); + + /// + /// Initializes a new instance of the class. + /// + /// The defining the processor parameters. + /// The configuration which allows altering default behaviour or extending the library. + /// The source instance to modify. + /// The source that indicates the area to edit. + public Implementation(HlslBokehBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle) + : base(configuration, source, sourceRectangle) { - KernelParameters = info.Parameters; - KernelsScale = info.Scale; - Kernels = info.Kernels; - } - else - { - // Initialize the complex kernels and parameters with the current arguments - (KernelParameters, KernelsScale) = GetParameters(); - Kernels = CreateComplexKernels(); - NormalizeKernels(); + Radius = definition.Radius; + KernelSize = Radius * 2 + 1; + ComponentsCount = definition.Components; - // 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, 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( - MathF.Exp(-a * value) * MathF.Cos(b * value), - MathF.Exp(-a * value) * MathF.Sin(b * value)); - } - - return kernel; - } - - /// - /// Normalizes the kernels with respect to A * real + B * imaginary. - /// - private void NormalizeKernels() - { - // 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++) + // Reuse the initialized values from the cache, if possible + var parameters = (Radius, ComponentsCount); + if (Cache.TryGetValue(parameters, out var info)) { - for (int k = 0; k < length; k++) + KernelParameters = info.Parameters; + KernelsScale = info.Scale; + Kernels = info.Kernels; + } + else + { + // Initialize the complex kernels and parameters with the current arguments + (KernelParameters, KernelsScale) = GetParameters(); + Kernels = CreateComplexKernels(); + NormalizeKernels(); + + // 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, 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( + MathF.Exp(-a * value) * MathF.Cos(b * value), + MathF.Exp(-a * value) * MathF.Sin(b * value)); + } + + return kernel; + } + + /// + /// Normalizes the kernels with respect to A * real + B * imaginary. + /// + private void NormalizeKernels() + { + // 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++) { - 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); + 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 / MathF.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; } } } - // Normalize the kernels - float scalar = 1f / MathF.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; - } - } - } - - /// - protected override void OnFrameApply(ImageFrame source) - { - foreach (Memory memory in source.GetPixelMemoryGroup()) - { - // Preliminary gamma highlight pass - using IMemoryOwner source4 = GetExposedVector4Buffer(memory); - - using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); - using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); - using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); - - ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters - - // Perform two 1D convolutions for each component in the current instance - for (int j = 0; j < Kernels.Length; j++) - { - kernelBuffer.SetData(Kernels[j]); - Vector4 parameters = Unsafe.Add(ref param0, j); - - ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); - ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W); - } - - // Apply the inverse gamma exposure pass - processingBuffer.GetData(source4.Memory.Span); - - // Write the final pixel data - ApplyInverseGammaExposure(source4.Memory, memory); - } - } - - /// - /// Performs a vertical 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyVerticalConvolution( - ReadOnlyBuffer source, - ReadWriteBuffer target, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; - - HlslBokehBlurProcessor.VerticalConvolutionProcessor shader = new( - width, - maxY: height - 1, - maxX: width - 1, - kernelLength: kernel.Length, - source, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - - /// - /// Performs an horizontal 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - /// The weight factor for the real component of the complex pixel values. - /// The weight factor for the imaginary component of the complex pixel values. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyHorizontalConvolutionAndAccumulatePartials( - ReadWriteBuffer source, - ReadWriteBuffer target, - ReadOnlyBuffer kernel, - float z, - float w) - { - int height = Source.Height; - int width = Source.Width; - - HlslBokehBlurProcessor.HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( - width, - maxY: height - 1, - maxX: width - 1, - kernelLength: kernel.Length, - z, - w, - source, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - - /// - /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. - /// - /// The source image. - [Pure] - private IMemoryOwner GetExposedVector4Buffer(Memory source) - { - IMemoryOwner target = Configuration.MemoryAllocator.Allocate(source.Length); - - float exp = Gamma; - int width = Source.Width; - int height = source.Length / width; - - ParallelRowIterator.IterateRows( - Configuration, - new Rectangle(0, 0, width, height), - new GetExposedVector4BufferProcessor(width, exp, source, target.Memory, Configuration)); - - return target; - } - - /// - /// The processor for . - /// - [AutoConstructor] - private readonly partial struct GetExposedVector4BufferProcessor : IRowOperation - { - private readonly int width; - private readonly float exp; - - private readonly Memory source; - private readonly Memory target; - private readonly Configuration configuration; - /// - public void Invoke(int y) + protected override void OnFrameApply(ImageFrame source) { - int offset = y * width; - - Span rowTPixel = source.Span.Slice(offset, width); - Span rowVector4 = target.Span.Slice(offset, width); - - PixelOperations.Instance.ToVector4(configuration, rowTPixel, rowVector4); - - foreach (ref Vector4 v in rowVector4) + foreach (Memory memory in source.GetPixelMemoryGroup()) { - v.X = MathF.Pow(v.X, exp); - v.Y = MathF.Pow(v.Y, exp); - v.Z = MathF.Pow(v.Z, exp); + // Preliminary gamma highlight pass + using IMemoryOwner source4 = GetExposedVector4Buffer(memory); + + using ReadOnlyBuffer sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer(source4.Memory.Span); + using ReadWriteBuffer processingBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); + using ReadWriteBuffer firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer(sourceBuffer.Length); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); + + ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters + + // Perform two 1D convolutions for each component in the current instance + for (int j = 0; j < Kernels.Length; j++) + { + kernelBuffer.SetData(Kernels[j]); + Vector4 parameters = Unsafe.Add(ref param0, j); + + ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer); + ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W); + } + + // Apply the inverse gamma exposure pass + processingBuffer.GetData(source4.Memory.Span); + + // Write the final pixel data + ApplyInverseGammaExposure(source4.Memory, memory); } } - } - /// - /// Applies the inverse gamma exposure pass to compute the final pixel values for a target image. - /// - /// The source buffer to read from. - /// The target image. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyInverseGammaExposure(Memory source, Memory target) - { - int width = Source.Width; - int height = source.Length / width; - float expGamma = 1 / Gamma; - - ParallelRowIterator.IterateRows( - Configuration, - new Rectangle(0, 0, width, height), - new ApplyInverseGammaExposureProcessor(width, expGamma, source, target, Configuration)); - } - - /// - /// The processor for . - /// - [AutoConstructor] - private readonly partial struct ApplyInverseGammaExposureProcessor : IRowOperation - { - private readonly int width; - private readonly float exp; - - private readonly Memory source; - private readonly Memory target; - private readonly Configuration configuration; - - /// - public void Invoke(int y) + /// + /// Performs a vertical 1D complex convolution with the specified parameters. + /// + /// The source to read data from. + /// The target to write the results to. + /// The with the values for the current complex kernel. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyVerticalConvolution( + ReadOnlyBuffer source, + ReadWriteBuffer target, + ReadOnlyBuffer kernel) { - int offset = y * width; + int height = Source.Height; + int width = Source.Width; - Span rowVector4 = source.Span.Slice(offset, width); - Span rowTPixel = target.Span.Slice(offset, width); + VerticalConvolutionProcessor shader = new( + width, + maxY: height - 1, + maxX: width - 1, + kernelLength: kernel.Length, + source, + target, + kernel); - Vector4 low = Vector4.Zero; - var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + Gpu.Default.For(width, height, in shader); + } - foreach (ref Vector4 v in rowVector4) + /// + /// Performs an horizontal 1D complex convolution with the specified parameters. + /// + /// The source to read data from. + /// The target to write the results to. + /// The with the values for the current complex kernel. + /// The weight factor for the real component of the complex pixel values. + /// The weight factor for the imaginary component of the complex pixel values. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyHorizontalConvolutionAndAccumulatePartials( + ReadWriteBuffer source, + ReadWriteBuffer target, + ReadOnlyBuffer kernel, + float z, + float w) + { + int height = Source.Height; + int width = Source.Width; + + HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( + width, + maxY: height - 1, + maxX: width - 1, + kernelLength: kernel.Length, + z, + w, + source, + target, + kernel); + + Gpu.Default.For(width, height, in shader); + } + + /// + /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. + /// + /// The source image. + [Pure] + private IMemoryOwner GetExposedVector4Buffer(Memory source) + { + IMemoryOwner target = Configuration.MemoryAllocator.Allocate(source.Length); + + int width = Source.Width; + int height = source.Length / width; + + ParallelRowIterator.IterateRows( + Configuration, + new Rectangle(0, 0, width, height), + new GetExposedVector4BufferProcessor(width, source, target.Memory, Configuration)); + + return target; + } + + /// + /// The processor for . + /// + [AutoConstructor] + private readonly partial struct GetExposedVector4BufferProcessor : IRowOperation + { + private readonly int width; + + private readonly Memory source; + private readonly Memory target; + private readonly Configuration configuration; + + /// + public void Invoke(int y) { - var clamp = Vector4.Clamp(v, low, high); - v.X = MathF.Pow(clamp.X, exp); - v.Y = MathF.Pow(clamp.Y, exp); - v.Z = MathF.Pow(clamp.Z, exp); - } + int offset = y * width; - PixelOperations.Instance.FromVector4Destructive(configuration, rowVector4, rowTPixel); + Span rowTPixel = source.Span.Slice(offset, width); + Span rowVector4 = target.Span.Slice(offset, width); + + PixelOperations.Instance.ToVector4(configuration, rowTPixel, rowVector4); + + foreach (ref Vector4 v in rowVector4) + { + Vector4 pixel = v; + float alpha = pixel.W; + + pixel = pixel * pixel * pixel; + pixel.W = alpha; + + v = pixel; + } + } + } + + /// + /// Applies the inverse gamma exposure pass to compute the final pixel values for a target image. + /// + /// The source buffer to read from. + /// The target image. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyInverseGammaExposure(Memory source, Memory target) + { + int width = Source.Width; + int height = source.Length / width; + + ParallelRowIterator.IterateRows( + Configuration, + new Rectangle(0, 0, width, height), + new ApplyInverseGammaExposureProcessor(width, source, target, Configuration)); + } + + /// + /// The processor for . + /// + [AutoConstructor] + private readonly partial struct ApplyInverseGammaExposureProcessor : IRowOperation + { + private readonly int width; + + private readonly Memory source; + private readonly Memory target; + private readonly Configuration configuration; + + /// + public void Invoke(int y) + { + int offset = y * width; + + Span rowVector4 = source.Span.Slice(offset, width); + Span rowTPixel = target.Span.Slice(offset, width); + + Vector4 low = Vector4.Zero; + var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + + foreach (ref Vector4 v in rowVector4) + { + var clamp = Vector4.Clamp(v, low, high); + + clamp.X = MathF.Pow(clamp.X, 1 / 3f); + clamp.Y = MathF.Pow(clamp.Y, 1 / 3f); + clamp.Z = MathF.Pow(clamp.Z, 1 / 3f); + + v = clamp; + } + + PixelOperations.Instance.FromVector4Destructive(configuration, rowVector4, rowTPixel); + } } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs index 8bdfa0ef..962db9cf 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs @@ -1,7 +1,9 @@ -using System.Numerics; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Diagnostics; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.BokehBlur.Processors { @@ -51,76 +53,14 @@ namespace ComputeSharp.BokehBlur.Processors public IImageProcessor CreatePixelSpecificProcessor(Configuration configuration, Image source, Rectangle sourceRectangle) where TPixel : unmanaged, IPixel { - return new HlslGaussianBlurProcessor(this, configuration, source, sourceRectangle); - } - - /// - /// Kernel for the vertical convolution pass. - /// - [AutoConstructor] - internal readonly partial struct VerticalConvolutionProcessor : IComputeShader - { - public readonly int maxY; - public readonly int maxX; - public readonly int kernelLength; - - public readonly ReadWriteTexture2D source; - public readonly ReadWriteTexture2D target; - public readonly ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) + if (typeof(TPixel) != typeof(ImageSharpRgba32)) { - Vector4 result = Vector4.Zero; - int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - - for (int i = 0; i < kernelLength; i++) - { - int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); - Vector4 color = source[offsetX, offsetY]; - - result += kernel[i] * color; - } - - target[ids.XY] = result; + ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format"); } - } - /// - /// Kernel for the horizontal convolution pass. - /// - [AutoConstructor] - internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader - { - public readonly int maxY; - public readonly int maxX; - public readonly int kernelLength; + var processor = new Implementation(this, configuration, Unsafe.As>(source), sourceRectangle); - public readonly ReadWriteTexture2D source; - public readonly ReadWriteTexture2D target; - public readonly ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 result = Vector4.Zero; - int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); - int offsetXY; - - for (int i = 0; i < kernelLength; i++) - { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); - Vector4 color = source[offsetX, offsetY]; - - result += kernel[i] * color; - } - - target[ids.XY] = result; - } + return Unsafe.As>(processor); } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index f9529bf2..5f1fa2f5 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -4,158 +4,225 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Toolkit.Diagnostics; using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.BokehBlur.Processors { - /// - /// Applies Gaussian blur processing to an image. - /// - /// The pixel format. - internal sealed class HlslGaussianBlurProcessor : ImageProcessor - where TPixel : unmanaged, IPixel + /// + public sealed partial class HlslGaussianBlurProcessor { /// - /// The 1D kernel to apply. + /// Applies Gaussian blur processing to an image. /// - private readonly float[] Kernel; - - /// - /// Initializes a new instance of the class. - /// - /// The defining the processor parameters. - /// The configuration which allows altering default behaviour or extending the library. - /// The source for the current processor instance. - /// The source area to process for the current processor instance. - public HlslGaussianBlurProcessor(HlslGaussianBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle) - : base(configuration, source, sourceRectangle) + internal sealed partial class Implementation : ImageProcessor { - int kernelSize = definition.Radius * 2 + 1; - Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma); - } + /// + /// The 1D kernel to apply. + /// + private readonly float[] Kernel; - /// - /// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function. - /// - private static float[] CreateGaussianBlurKernel(int size, float weight) - { - float[] kernel = new float[size]; - ref float rKernel = ref kernel[0]; - - float sum = 0F; - float midpoint = (size - 1) / 2F; - - for (int i = 0; i < size; i++) + /// + /// Initializes a new instance of the class. + /// + /// The defining the processor parameters. + /// The configuration which allows altering default behaviour or extending the library. + /// The source for the current processor instance. + /// The source area to process for the current processor instance. + public Implementation(HlslGaussianBlurProcessor definition, Configuration configuration, Image source, Rectangle sourceRectangle) + : base(configuration, source, sourceRectangle) { - float x = i - midpoint; - float gx = Gaussian(x, weight); - sum += gx; - Unsafe.Add(ref rKernel, i) = gx; + int kernelSize = definition.Radius * 2 + 1; + Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma); } - // Normalize kernel so that the sum of all weights equals 1 - for (int i = 0; i < size; i++) + /// + /// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function. + /// + private static float[] CreateGaussianBlurKernel(int size, float weight) { - Unsafe.Add(ref rKernel, i) /= sum; + float[] kernel = new float[size]; + ref float rKernel = ref kernel[0]; + + float sum = 0F; + float midpoint = (size - 1) / 2F; + + for (int i = 0; i < size; i++) + { + float x = i - midpoint; + float gx = Gaussian(x, weight); + sum += gx; + Unsafe.Add(ref rKernel, i) = gx; + } + + // Normalize kernel so that the sum of all weights equals 1 + for (int i = 0; i < size; i++) + { + Unsafe.Add(ref rKernel, i) /= sum; + } + + return kernel; } - return kernel; - } - - /// - /// Implementation of 1D Gaussian G(x) function. - /// - /// The x provided to G(x) - /// The spread of the blur. - /// The Gaussian G(x) - private static float Gaussian(float x, float sigma) - { - const float Numerator = 1.0f; - float denominator = MathF.Sqrt(2 * MathF.PI) * sigma; - - float exponentNumerator = -x * x; - float exponentDenominator = 2 * sigma * sigma; - - float left = Numerator / denominator; - float right = MathF.Exp(exponentNumerator / exponentDenominator); - - return left * right; - } - - /// - protected override void OnFrameApply(ImageFrame source) - { - ImageFrame frame = (ImageFrame)(object)source; - - if (!frame.TryGetSinglePixelSpan(out Span pixelSpan)) + /// + /// Implementation of 1D Gaussian G(x) function. + /// + /// The x provided to G(x) + /// The spread of the blur. + /// The Gaussian G(x) + private static float Gaussian(float x, float sigma) { - ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory"); + const float Numerator = 1.0f; + float denominator = MathF.Sqrt(2 * MathF.PI) * sigma; + + float exponentNumerator = -x * x; + float exponentDenominator = 2 * sigma * sigma; + + float left = Numerator / denominator; + float right = MathF.Exp(exponentNumerator / exponentDenominator); + + return left * right; } - Span span = MemoryMarshal.Cast(pixelSpan); + /// + protected override void OnFrameApply(ImageFrame source) + { + if (!source.TryGetSinglePixelSpan(out Span pixelSpan)) + { + ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory"); + } - using ReadWriteTexture2D sourceTexture = Gpu.Default.AllocateReadWriteTexture2D(span, frame.Width, frame.Height); - using ReadWriteTexture2D firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D(frame.Width, frame.Height); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); + Span span = MemoryMarshal.Cast(pixelSpan); - ApplyVerticalConvolution(sourceTexture, firstPassTexture, kernelBuffer); - ApplyHorizontalConvolution(firstPassTexture, sourceTexture, kernelBuffer); + using ReadWriteTexture2D sourceTexture = Gpu.Default.AllocateReadWriteTexture2D(span, source.Width, source.Height); + using ReadWriteTexture2D firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); - sourceTexture.GetData(span); - } + ApplyVerticalConvolution(sourceTexture, firstPassTexture, kernelBuffer); + ApplyHorizontalConvolution(firstPassTexture, sourceTexture, kernelBuffer); - /// - /// Performs a vertical 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyVerticalConvolution( - ReadWriteTexture2D source, - ReadWriteTexture2D target, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; + sourceTexture.GetData(span); + } - HlslGaussianBlurProcessor.VerticalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernel.Length, - source, - target, - kernel); + /// + /// Performs a vertical 1D complex convolution with the specified parameters. + /// + /// The source to read data from. + /// The target to write the results to. + /// The with the values for the current complex kernel. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyVerticalConvolution( + ReadWriteTexture2D source, + ReadWriteTexture2D target, + ReadOnlyBuffer kernel) + { + int height = Source.Height; + int width = Source.Width; - Gpu.Default.For(width, height, in shader); - } + VerticalConvolutionProcessor shader = new( + maxY: height - 1, + maxX: width - 1, + kernel.Length, + source, + target, + kernel); - /// - /// Performs an horizontal 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyHorizontalConvolution( - ReadWriteTexture2D source, - ReadWriteTexture2D target, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; + Gpu.Default.For(width, height, in shader); + } - HlslGaussianBlurProcessor.HorizontalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernel.Length, - source, - target, - kernel); + /// + /// Kernel for the vertical convolution pass. + /// + [AutoConstructor] + internal readonly partial struct VerticalConvolutionProcessor : IComputeShader + { + public readonly int maxY; + public readonly int maxX; + public readonly int kernelLength; - Gpu.Default.For(width, height, in shader); + public readonly ReadWriteTexture2D source; + public readonly ReadWriteTexture2D target; + public readonly ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 result = Vector4.Zero; + int radiusY = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + Vector4 color = source[offsetX, offsetY]; + + result += kernel[i] * color; + } + + target[ids.XY] = result; + } + } + + /// + /// Performs an horizontal 1D complex convolution with the specified parameters. + /// + /// The source to read data from. + /// The target to write the results to. + /// The with the values for the current complex kernel. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ApplyHorizontalConvolution( + ReadWriteTexture2D source, + ReadWriteTexture2D target, + ReadOnlyBuffer kernel) + { + int height = Source.Height; + int width = Source.Width; + + HorizontalConvolutionProcessor shader = new( + maxY: height - 1, + maxX: width - 1, + kernel.Length, + source, + target, + kernel); + + Gpu.Default.For(width, height, in shader); + } + + /// + /// Kernel for the horizontal convolution pass. + /// + [AutoConstructor] + internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader + { + public readonly int maxY; + public readonly int maxX; + public readonly int kernelLength; + + public readonly ReadWriteTexture2D source; + public readonly ReadWriteTexture2D target; + public readonly ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 result = Vector4.Zero; + int radiusX = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); + + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + Vector4 color = source[offsetX, offsetY]; + + result += kernel[i] * color; + } + + target[ids.XY] = result; + } + } } } } diff --git a/samples/ComputeSharp.ImageProcessing/Program.cs b/samples/ComputeSharp.ImageProcessing/Program.cs index 34af8cb3..9924b200 100644 --- a/samples/ComputeSharp.ImageProcessing/Program.cs +++ b/samples/ComputeSharp.ImageProcessing/Program.cs @@ -20,7 +20,7 @@ namespace ComputeSharp.ImageProcessing // Apply a series of processors and save the results foreach (var effect in new (string Name, IImageProcessor Processor)[] { - ("bokeh", new HlslBokehBlurProcessor(80, 2, 3)), + ("bokeh", new HlslBokehBlurProcessor(80, 2)), ("gaussian", new HlslGaussianBlurProcessor(80)) }) {