From 903ae95f16d25573adb67b939ef59ea89537cb9f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 11 May 2021 22:32:56 +0200 Subject: [PATCH 1/7] Added draft of internal WIC decoder helpers --- .../Graphics/Helpers/WICFormatHelper.cs | 33 +++++ .../Graphics/Helpers/WICHelper.cs | 123 ++++++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs create mode 100644 src/ComputeSharp/Graphics/Helpers/WICHelper.cs diff --git a/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs new file mode 100644 index 00000000..fe65f07b --- /dev/null +++ b/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs @@ -0,0 +1,33 @@ +using System; +using System.Diagnostics.Contracts; +using System.Runtime.CompilerServices; +using Microsoft.Toolkit.Diagnostics; +using FX = TerraFX.Interop.Windows; + +namespace ComputeSharp.Graphics.Helpers +{ + /// + /// A helper type with utility methods for WIC formats. + /// + internal static class WICFormatHelper + { + /// + /// Gets the appropriate WIC format value for the input type argument. + /// + /// The input type argument to get the corresponding WIC format . + /// The WIC format value corresponding to . + /// Thrown when the input type is not supported. + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Guid GetForType() + where T : unmanaged + { + if (typeof(T) == typeof(Bgra32)) return FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba32)) return FX.GUID_WICPixelFormat32bppRGBA; + else if (typeof(T) == typeof(Rgba64)) return FX.GUID_WICPixelFormat64bppRGBA; + else if (typeof(T) == typeof(R8)) return FX.GUID_WICPixelFormat8bppGray; + else if (typeof(T) == typeof(R16)) return FX.GUID_WICPixelFormat16bppGray; + else return ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + } +} diff --git a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs new file mode 100644 index 00000000..97ebeb9d --- /dev/null +++ b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs @@ -0,0 +1,123 @@ +using System; +using System.Diagnostics.Contracts; +using ComputeSharp.__Internals; +using ComputeSharp.Core.Extensions; +using TerraFX.Interop; +using FX = TerraFX.Interop.Windows; + +#pragma warning disable CS0618 + +namespace ComputeSharp.Graphics.Helpers +{ + /// + /// A that uses the WIC APIs to load and decode images. + /// + internal sealed unsafe class WICHelper + { + /// + /// The instance to use to create decoders. + /// + private readonly ComPtr wicImagingFactory2; + + /// + /// Creates a new instance. + /// + private WICHelper() + { + using ComPtr wicImagingFactory2 = default; + Guid wicImagingFactor2Clsid = FX.CLSID_WICImagingFactory2; + + FX.CoCreateInstance( + &wicImagingFactor2Clsid, + null, + (uint)CLSCTX.CLSCTX_INPROC_SERVER, + FX.__uuidof(), + wicImagingFactory2.GetVoidAddressOf()).Assert(); + + this.wicImagingFactory2 = wicImagingFactory2.Move(); + } + + /// + /// Destroys the current instance. + /// + ~WICHelper() + { + this.wicImagingFactory2.Dispose(); + } + + /// + /// Gets a instance to use. + /// + public static WICHelper Instance { get; } = new(); + + /// + /// Loads a from a specified file. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The filename of the image file to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public ReadOnlyTexture2D LoadTexture(GraphicsDevice device, ReadOnlySpan filename) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + using ComPtr wicBitmapDecoder = default; + + // Get the bitmap decoder for the target file + fixed (char* p = filename) + { + this.wicImagingFactory2.Get()->CreateDecoderFromFilename( + (ushort*)p, + null, + FX.GENERIC_READ, + WICDecodeOptions.WICDecodeMetadataCacheOnDemand, + wicBitmapDecoder.GetAddressOf()).Assert(); + } + + using ComPtr wicBitmapFrameDecode = default; + + // Get the first frame of the loaded image (if more are present, they will be ignored) + wicBitmapDecoder.Get()->GetFrame(0, wicBitmapFrameDecode.GetAddressOf()).Assert(); + + using ComPtr wicFormatConverter = default; + Guid wicPixelFormatGuid = WICFormatHelper.GetForType(); + + this.wicImagingFactory2.Get()->CreateFormatConverter(wicFormatConverter.GetAddressOf()).Assert(); + + // Get a format converter to decode the pixel data + wicFormatConverter.Get()->Initialize( + (IWICBitmapSource*)wicBitmapFrameDecode.Get(), + &wicPixelFormatGuid, + WICBitmapDitherType.WICBitmapDitherTypeNone, + null, + 0, + WICBitmapPaletteType.WICBitmapPaletteTypeMedianCut).Assert(); + + uint width, height; + + // Extract the image size info + wicFormatConverter.Get()->GetSize(&width, &height).Assert(); + + // Allocate an upload texture to transfer the decoded pixel data + using UploadTexture2D upload = device.AllocateUploadTexture2D((int)width, (int)height); + + T* data = upload.View.DangerousGetAddressAndByteStride(out int strideInBytes); + + // Decode the pixel data into the upload buffer + wicFormatConverter.Get()->CopyPixels( + prc: null, + cbStride: (uint)strideInBytes, + cbBufferSize: (uint)strideInBytes * height, + pbBuffer: (byte*)data).Assert(); + + // Create the final texture to return + ReadOnlyTexture2D texture = device.AllocateReadOnlyTexture2D((int)width, (int)height); + + upload.CopyTo(texture); + + return texture; + } + } +} From 41d4ae683f14d21144c779c36d4bf96d72b9948d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 11 May 2021 23:00:54 +0200 Subject: [PATCH 2/7] Added new extension to load a texture from an image --- .../Extensions/GraphicsDeviceExtensions.cs | 57 ++++++++++++------- .../Resources/ReadOnlyTexture2D{T,TPixel}.cs | 2 +- .../Resources/ReadOnlyTexture3D{T,TPixel}.cs | 2 +- .../Resources/ReadWriteTexture2D{T,TPixel}.cs | 2 +- .../Resources/ReadWriteTexture3D{T,TPixel}.cs | 2 +- 5 files changed, 41 insertions(+), 24 deletions(-) diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs index 57592daf..6ea3e81d 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.Contracts; using ComputeSharp.__Internals; +using ComputeSharp.Graphics.Helpers; using ComputeSharp.Resources; using ComputeSharp.Shaders; @@ -239,7 +240,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The allocation mode to use for the new resource. - /// A zeroed instance of size [, ]. + /// A zeroed instance of size [, ]. [Pure] public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, int width, int height, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm @@ -257,7 +258,7 @@ namespace ComputeSharp /// The input array with the data to copy on the allocated texture. /// The width of the texture. /// The height of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[] source, int width, int height) where T : unmanaged, IUnorm @@ -276,7 +277,7 @@ namespace ComputeSharp /// The starting offset within to read data from. /// The width of the texture. /// The height of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[] source, int offset, int width, int height) where T : unmanaged, IUnorm @@ -292,7 +293,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// A read write instance with the contents of the input array. + /// A read write instance with the contents of the input array. [Pure] public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[,] source) where T : unmanaged, IUnorm @@ -314,7 +315,7 @@ namespace ComputeSharp /// The input with the data to copy on the allocated texture. /// The width of the texture. /// The height of the texture. - /// A instance with the contents of the input . + /// A instance with the contents of the input . [Pure] public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, ReadOnlySpan source, int width, int height) where T : unmanaged, IUnorm @@ -327,6 +328,22 @@ namespace ComputeSharp return texture; } + /// + /// Allocates a new readonly 2D texture with the contents of the specified file. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The filename of the image file to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, ReadOnlySpan filename) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return WICHelper.Instance.LoadTexture(device, filename); + } + /// /// Allocates a new readonly 3D texture with the specified parameters. /// @@ -432,7 +449,7 @@ namespace ComputeSharp /// The height of the texture. /// The depth of the texture. /// The allocation mode to use for the new resource. - /// A zeroed instance of size [, , ]. + /// A zeroed instance of size [, , ]. [Pure] public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm @@ -451,7 +468,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, T[] source, int width, int height, int depth) where T : unmanaged, IUnorm @@ -471,7 +488,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, T[] source, int offset, int width, int height, int depth) where T : unmanaged, IUnorm @@ -487,7 +504,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// A read write instance with the contents of the input array. + /// A read write instance with the contents of the input array. /// /// The source 3D array needs to have each 2D plane stacked on the depth axis. /// That is, the expected layout of the input array has to be [depth, height, width]. @@ -514,7 +531,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input . + /// A instance with the contents of the input . [Pure] public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, ReadOnlySpan source, int width, int height, int depth) where T : unmanaged, IUnorm @@ -688,7 +705,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The allocation mode to use for the new resource. - /// A zeroed instance of size [, ]. + /// A zeroed instance of size [, ]. [Pure] public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, int width, int height, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm @@ -706,7 +723,7 @@ namespace ComputeSharp /// The input array with the data to copy on the allocated texture. /// The width of the texture. /// The height of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[] source, int width, int height) where T : unmanaged, IUnorm @@ -725,7 +742,7 @@ namespace ComputeSharp /// The starting offset within to read data from. /// The width of the texture. /// The height of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[] source, int offset, int width, int height) where T : unmanaged, IUnorm @@ -741,7 +758,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// A read write instance with the contents of the input array. + /// A read write instance with the contents of the input array. [Pure] public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[,] source) where T : unmanaged, IUnorm @@ -763,7 +780,7 @@ namespace ComputeSharp /// The input with the data to copy on the allocated texture. /// The width of the texture. /// The height of the texture. - /// A instance with the contents of the input . + /// A instance with the contents of the input . [Pure] public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, ReadOnlySpan source, int width, int height) where T : unmanaged, IUnorm @@ -881,7 +898,7 @@ namespace ComputeSharp /// The height of the texture. /// The depth of the texture. /// The allocation mode to use for the new resource. - /// A instance of size [, , ]. + /// A instance of size [, , ]. [Pure] public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm @@ -900,7 +917,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, T[] source, int width, int height, int depth) where T : unmanaged, IUnorm @@ -920,7 +937,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input array. + /// A instance with the contents of the input array. [Pure] public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, T[] source, int offset, int width, int height, int depth) where T : unmanaged, IUnorm @@ -936,7 +953,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// A read write instance with the contents of the input array. + /// A read write instance with the contents of the input array. /// /// The source 3D array needs to have each 2D plane stacked on the depth axis. /// That is, the expected layout of the input array has to be [depth, height, width]. @@ -963,7 +980,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - /// A instance with the contents of the input . + /// A instance with the contents of the input . [Pure] public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, ReadOnlySpan source, int width, int height, int depth) where T : unmanaged, IUnorm diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs index 42b5c06b..984ba086 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs @@ -22,7 +22,7 @@ namespace ComputeSharp where TPixel : unmanaged { /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. /// The width of the texture. diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs index 2871cfd0..f29774ce 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs @@ -22,7 +22,7 @@ namespace ComputeSharp where TPixel : unmanaged { /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. /// The width of the texture. diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs index 84acb879..caa6def5 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs @@ -22,7 +22,7 @@ namespace ComputeSharp where TPixel : unmanaged { /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. /// The width of the texture. diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs index cb452315..19d2fe45 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs @@ -22,7 +22,7 @@ namespace ComputeSharp where TPixel : unmanaged { /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The associated with the current instance. /// The width of the texture. From d1a2c667dddf3d91396ed589f6de60fef56e6c7f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 11 May 2021 23:01:13 +0200 Subject: [PATCH 3/7] Updated sample and tests to use new texture loading APIs --- .../ComputeSharp.SwapChain.csproj | 4 ---- samples/ComputeSharp.SwapChain/Program.cs | 13 +------------ src/Directory.Build.props | 2 +- .../Extensions/ImagingExtensions.cs | 18 ------------------ tests/ComputeSharp.Tests/ShadersTests.cs | 2 +- .../Texture2DTests.Pixels.cs | 8 ++++---- 6 files changed, 7 insertions(+), 40 deletions(-) diff --git a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj index 9f8fe3d7..248e0cad 100644 --- a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj +++ b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj @@ -5,10 +5,6 @@ net5.0 - - - - image = Image.Load(filename); - - ReadOnlyTexture2D texture = Gpu.Default.AllocateReadOnlyTexture2D(image.Width, image.Height); - - image.TryGetSinglePixelSpan(out Span span); - - texture.CopyFrom(MemoryMarshal.Cast(span)); - - return texture; + return Gpu.Default.AllocateReadOnlyTexture2D(filename); } } } diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 398a1fa7..91228da0 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -4,7 +4,7 @@ - + diff --git a/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs b/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs index 6994ab4c..0fea45d9 100644 --- a/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs @@ -12,24 +12,6 @@ namespace ComputeSharp.Tests.Extensions /// public static class ImagingExtensions { - /// - /// Allocates a new instance with the specified texture data. - /// - /// The target instance to allocate the texture for. - /// The path of the texture to load. - /// A texture with the data from the image at the specified path. - [Pure] - public static ReadOnlyTexture2D LoadTexture(this GraphicsDevice device, string path) - { - using Image image = Image.Load(path); - - Assert.IsTrue(image.TryGetSinglePixelSpan(out Span span)); - - Span pixels = MemoryMarshal.Cast(span); - - return device.AllocateReadOnlyTexture2D(pixels, image.Width, image.Height); - } - /// /// Creates a new instance with the specified texture data. /// diff --git a/tests/ComputeSharp.Tests/ShadersTests.cs b/tests/ComputeSharp.Tests/ShadersTests.cs index 075e7ffa..2a3bdf14 100644 --- a/tests/ComputeSharp.Tests/ShadersTests.cs +++ b/tests/ComputeSharp.Tests/ShadersTests.cs @@ -105,7 +105,7 @@ namespace ComputeSharp.Tests { string filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Shaders", "Textures", "RustyMetal.png"); - using ReadOnlyTexture2D background = device.Get().LoadTexture(filename); + using ReadOnlyTexture2D background = device.Get().AllocateReadOnlyTexture2D(filename); RunAndCompareShader( device, diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs index 294dd521..0c0fec91 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs @@ -76,14 +76,14 @@ namespace ComputeSharp.Tests using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png")); - using ReadOnlyTexture2D source = device.Get().LoadTexture(Path.Combine(imagingPath, "city.jpg")); + using ReadOnlyTexture2D source = device.Get().AllocateReadOnlyTexture2D(Path.Combine(imagingPath, "city.jpg")); using ReadWriteTexture2D destination = device.Get().AllocateReadWriteTexture2D(sampled.Width, sampled.Height); device.Get().For(sampled.Width, sampled.Height, new SamplingComputeShader(source, destination)); using var processed = destination.ToImage(); - ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.00000086f); + ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.0000017f); } [AutoConstructor] @@ -109,14 +109,14 @@ namespace ComputeSharp.Tests using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png")); - using ReadOnlyTexture2D source = device.Get().LoadTexture(Path.Combine(imagingPath, "city.jpg")); + using ReadOnlyTexture2D source = device.Get().AllocateReadOnlyTexture2D(Path.Combine(imagingPath, "city.jpg")); using ReadWriteTexture2D destination = device.Get().AllocateReadWriteTexture2D(sampled.Width, sampled.Height); device.Get().ForEach(destination, new SamplingPixelShader(source)); using var processed = destination.ToImage(); - ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.00000086f); + ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.0000017f); } [AutoConstructor] From ec647da78b87481a10e3849c9bb349f3076d1751 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 11 May 2021 23:13:04 +0200 Subject: [PATCH 4/7] Added unit test for WIC image loader --- .../Extensions/ImagingExtensions.cs | 19 ++++++ .../ImageProcessingTests.cs | 63 +++++++++++++++++++ tests/ComputeSharp.Tests/ImagingTests.cs | 47 +++----------- 3 files changed, 89 insertions(+), 40 deletions(-) create mode 100644 tests/ComputeSharp.Tests/ImageProcessingTests.cs diff --git a/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs b/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs index 0fea45d9..ab357a2e 100644 --- a/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs @@ -12,6 +12,25 @@ namespace ComputeSharp.Tests.Extensions /// public static class ImagingExtensions { + /// + /// Creates a new instance with the specified texture data. + /// + /// The source instance to read data from. + /// An image with the data from the input texture. + [Pure] + public static Image ToImage(this ReadOnlyTexture2D texture) + { + Image image = new(texture.Width, texture.Height); + + Assert.IsTrue(image.TryGetSinglePixelSpan(out Span span)); + + Span pixels = MemoryMarshal.Cast(span); + + texture.CopyTo(pixels); + + return image; + } + /// /// Creates a new instance with the specified texture data. /// diff --git a/tests/ComputeSharp.Tests/ImageProcessingTests.cs b/tests/ComputeSharp.Tests/ImageProcessingTests.cs new file mode 100644 index 00000000..409ea4b0 --- /dev/null +++ b/tests/ComputeSharp.Tests/ImageProcessingTests.cs @@ -0,0 +1,63 @@ +using System.IO; +using System.Reflection; +using ComputeSharp.BokehBlur.Processors; +using ComputeSharp.Tests.Attributes; +using ComputeSharp.Tests.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Processing; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; + +namespace ComputeSharp.Tests +{ + [TestClass] + [TestCategory("ImageProcessing")] + public class ImageProcessingTests + { + [CombinatorialTestMethod] + [AllDevices] + public void BokehBlur(Device device) + { + // Early test to ensure the device is available. This saves time when running the + // unit test if the target device is not available, as we skip the preprocessing. + _ = device.Get(); + + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + + using var original = Image.Load(Path.Combine(path, "city.jpg")); + using var cpu = original.Clone(c => c.BokehBlur(80, 2, 3)); + using var gpu = original.Clone(c => c.ApplyProcessor(new HlslBokehBlurProcessor(device.Get(), 80, 2))); + + string + expectedPath = Path.Combine(path, "city_bokeh_cpu.jpg"), + actualPath = Path.Combine(path, "city_bokeh_gpu.jpg"); + + cpu.Save(expectedPath); + gpu.Save(actualPath); + + ImagingTests.TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.000009f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void GaussianBlur(Device device) + { + _ = device.Get(); + + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + + using var original = Image.Load(Path.Combine(path, "city.jpg")); + using var cpu = original.Clone(c => c.GaussianBlur(30f)); + using var gpu = original.Clone(c => c.ApplyProcessor(new HlslGaussianBlurProcessor(device.Get(), 90))); + + string + expectedPath = Path.Combine(path, "city_gaussian_cpu.jpg"), + actualPath = Path.Combine(path, "city_gaussian_gpu.jpg"); + + cpu.Save(expectedPath); + gpu.Save(actualPath); + + ImagingTests.TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.000003f); + } + } +} diff --git a/tests/ComputeSharp.Tests/ImagingTests.cs b/tests/ComputeSharp.Tests/ImagingTests.cs index 97ffe400..14f2764b 100644 --- a/tests/ComputeSharp.Tests/ImagingTests.cs +++ b/tests/ComputeSharp.Tests/ImagingTests.cs @@ -4,13 +4,12 @@ using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; -using ComputeSharp.BokehBlur.Processors; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Processing; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; +using ImageSharpBgra32 = SixLabors.ImageSharp.PixelFormats.Bgra32; namespace ComputeSharp.Tests { @@ -20,48 +19,16 @@ namespace ComputeSharp.Tests { [CombinatorialTestMethod] [AllDevices] - public void BokehBlur(Device device) + public void LoadImageAsRgba32(Device device) { - // Early test to ensure the device is available. This saves time when running the - // unit test if the target device is not available, as we skip the preprocessing. - _ = device.Get(); + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); - string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + using ReadOnlyTexture2D texture = Gpu.Default.AllocateReadOnlyTexture2D(path); - using var original = Image.Load(Path.Combine(path, "city.jpg")); - using var cpu = original.Clone(c => c.BokehBlur(80, 2, 3)); - using var gpu = original.Clone(c => c.ApplyProcessor(new HlslBokehBlurProcessor(device.Get(), 80, 2))); + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); - string - expectedPath = Path.Combine(path, "city_bokeh_cpu.jpg"), - actualPath = Path.Combine(path, "city_bokeh_gpu.jpg"); - - cpu.Save(expectedPath); - gpu.Save(actualPath); - - TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.000009f); - } - - [CombinatorialTestMethod] - [AllDevices] - public void GaussianBlur(Device device) - { - _ = device.Get(); - - string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); - - using var original = Image.Load(Path.Combine(path, "city.jpg")); - using var cpu = original.Clone(c => c.GaussianBlur(30f)); - using var gpu = original.Clone(c => c.ApplyProcessor(new HlslGaussianBlurProcessor(device.Get(), 90))); - - string - expectedPath = Path.Combine(path, "city_gaussian_cpu.jpg"), - actualPath = Path.Combine(path, "city_gaussian_gpu.jpg"); - - cpu.Save(expectedPath); - gpu.Save(actualPath); - - TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.000003f); + TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); } /// From c66ac3fe199e19c90b3bbd885d6f8e914ad29f8f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 11 May 2021 23:24:24 +0200 Subject: [PATCH 5/7] Added extension to load a texture from a buffer --- .../Extensions/GraphicsDeviceExtensions.cs | 16 ++++++ .../Graphics/Helpers/WICHelper.cs | 51 ++++++++++++++++++- tests/ComputeSharp.Tests/ImagingTests.cs | 21 ++++++-- 3 files changed, 84 insertions(+), 4 deletions(-) diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs index 6ea3e81d..16378891 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs @@ -344,6 +344,22 @@ namespace ComputeSharp return WICHelper.Instance.LoadTexture(device, filename); } + /// + /// Allocates a new readonly 2D texture with the contents of the specified buffer. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The buffer with the image data to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, ReadOnlySpan span) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return WICHelper.Instance.LoadTexture(device, span); + } + /// /// Allocates a new readonly 3D texture with the specified parameters. /// diff --git a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs index 97ebeb9d..61cee873 100644 --- a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs @@ -76,10 +76,59 @@ namespace ComputeSharp.Graphics.Helpers wicBitmapDecoder.GetAddressOf()).Assert(); } + return LoadTexture(device, wicBitmapDecoder.Get()); + } + + /// + /// Loads a from a specified buffer. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The buffer with the image data to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public ReadOnlyTexture2D LoadTexture(GraphicsDevice device, ReadOnlySpan span) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + using ComPtr wicBitmapDecoder = default; + using ComPtr wicStream = default; + + // Get the bitmap decoder for the target buffer + fixed (byte* p = span) + { + this.wicImagingFactory2.Get()->CreateStream(wicStream.GetAddressOf()).Assert(); + + wicStream.Get()->InitializeFromMemory(p, (uint)span.Length).Assert(); + + this.wicImagingFactory2.Get()->CreateDecoderFromStream( + (IStream*)wicStream.Get(), + null, + WICDecodeOptions.WICDecodeMetadataCacheOnDemand, + wicBitmapDecoder.GetAddressOf()).Assert(); + + return LoadTexture(device, wicBitmapDecoder.Get()); + } + } + + /// + /// Loads a from a specified object. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The object in use. + /// A instance with the contents of the specified file. + [Pure] + public ReadOnlyTexture2D LoadTexture(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { using ComPtr wicBitmapFrameDecode = default; // Get the first frame of the loaded image (if more are present, they will be ignored) - wicBitmapDecoder.Get()->GetFrame(0, wicBitmapFrameDecode.GetAddressOf()).Assert(); + wicBitmapDecoder->GetFrame(0, wicBitmapFrameDecode.GetAddressOf()).Assert(); using ComPtr wicFormatConverter = default; Guid wicPixelFormatGuid = WICFormatHelper.GetForType(); diff --git a/tests/ComputeSharp.Tests/ImagingTests.cs b/tests/ComputeSharp.Tests/ImagingTests.cs index 14f2764b..752a2cb6 100644 --- a/tests/ComputeSharp.Tests/ImagingTests.cs +++ b/tests/ComputeSharp.Tests/ImagingTests.cs @@ -9,7 +9,6 @@ using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; -using ImageSharpBgra32 = SixLabors.ImageSharp.PixelFormats.Bgra32; namespace ComputeSharp.Tests { @@ -19,11 +18,27 @@ namespace ComputeSharp.Tests { [CombinatorialTestMethod] [AllDevices] - public void LoadImageAsRgba32(Device device) + public void LoadAsRgba32FromFile(Device device) { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); - using ReadOnlyTexture2D texture = Gpu.Default.AllocateReadOnlyTexture2D(path); + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(path); + + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); + + TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void LoadAsRgba32FromBuffer(Device device) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); + + byte[] buffer = File.ReadAllBytes(path); + + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(buffer); using Image loaded = texture.ToImage(); using Image original = Image.Load(path); From f31ac94bf964cbc89c5dc8c61e6edc419da838df Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 12 May 2021 11:17:00 +0200 Subject: [PATCH 6/7] Added extensions to save textures to files --- .../Extensions/ReadBackTexture2DExtensions.cs | 23 ++++ .../Extensions/Texture2DExtensions.cs | 17 +++ .../Graphics/Helpers/WICFormatHelper.cs | 99 +++++++++++++++++ .../Graphics/Helpers/WICHelper.cs | 102 +++++++++++++++++- tests/ComputeSharp.Tests/ImagingTests.cs | 54 ++++++++++ 5 files changed, 294 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs diff --git a/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs new file mode 100644 index 00000000..83b075cf --- /dev/null +++ b/src/ComputeSharp/Graphics/Extensions/ReadBackTexture2DExtensions.cs @@ -0,0 +1,23 @@ +using System; +using ComputeSharp.Graphics.Helpers; + +namespace ComputeSharp +{ + /// + /// A that contains extension methods for the type. + /// + public static class ReadBackTexture2DExtensions + { + /// + /// Saves a texture to a specified file. + /// + /// The type of items to store in the texture. + /// The texture to save to an image. + /// The filename of the image file to save. + public static void Save(this ReadBackTexture2D texture, ReadOnlySpan filename) + where T : unmanaged + { + WICHelper.Instance.SaveTexture(texture.View, filename); + } + } +} diff --git a/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs b/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs index db6722f8..e1e2b755 100644 --- a/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/Texture2DExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; +using ComputeSharp.Graphics.Helpers; using ComputeSharp.Resources; using Microsoft.Toolkit.Diagnostics; @@ -338,5 +339,21 @@ namespace ComputeSharp { texture.CopyFrom(ref MemoryMarshal.GetReference(source), source.Length, x, y, width, height); } + + /// + /// Saves a texture to a specified file. + /// + /// The type of items to store in the texture. + /// The texture to save to an image. + /// The filename of the image file to save. + public static void Save(this Texture2D texture, ReadOnlySpan filename) + where T : unmanaged + { + using ReadBackTexture2D readback = texture.GraphicsDevice.AllocateReadBackTexture2D(texture.Width, texture.Height); + + texture.CopyTo(readback); + + WICHelper.Instance.SaveTexture(readback.View, filename); + } } } diff --git a/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs index fe65f07b..19b5716e 100644 --- a/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/WICFormatHelper.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics.Contracts; +using System.IO; using System.Runtime.CompilerServices; using Microsoft.Toolkit.Diagnostics; using FX = TerraFX.Interop.Windows; @@ -29,5 +30,103 @@ namespace ComputeSharp.Graphics.Helpers else if (typeof(T) == typeof(R16)) return FX.GUID_WICPixelFormat16bppGray; else return ThrowHelper.ThrowArgumentException("Invalid texture type"); } + + /// + /// Gets the appropriate WIC format value for the input type argument. + /// + /// The input type argument to get the corresponding WIC format . + /// The WIC format value corresponding to . + /// Thrown when the input type is not supported. + [Pure] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool TryGetIntermediateFormatForType(Guid containerFormat, out Guid intermediateFormat) + where T : unmanaged + { + if (containerFormat == FX.GUID_ContainerFormatBmp) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(R8)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatPng) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = default; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat8bppGray; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatJpeg) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = FX.GUID_WICPixelFormat24bppBGR; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat8bppGray; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatWmp) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = default; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = default; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatTiff) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = default; + else if (typeof(T) == typeof(R8)) intermediateFormat = default; + else if (typeof(T) == typeof(R16)) intermediateFormat = default; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else if (containerFormat == FX.GUID_ContainerFormatDds) + { + if (typeof(T) == typeof(Bgra32)) intermediateFormat = default; + else if (typeof(T) == typeof(Rgba32)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(Rgba64)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(R8)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else if (typeof(T) == typeof(R16)) intermediateFormat = FX.GUID_WICPixelFormat32bppBGRA; + else intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid texture type"); + } + else + { + intermediateFormat = ThrowHelper.ThrowArgumentException("Invalid container format"); + } + + return intermediateFormat != default; + } + + /// + /// Gets the appropriate WIC container format value for the input filename. + /// + /// The target filename to get the container format for. + /// The WIC format container value matching . + /// Thrown when the input filename doesn't have a valid file extension. + [Pure] + public static Guid GetForFilename(ReadOnlySpan filename) + { + switch (Path.GetExtension(filename).ToString()) + { + case ".bmp": return FX.GUID_ContainerFormatBmp; + case ".png": return FX.GUID_ContainerFormatPng; + case ".jpg": + case ".jpeg": return FX.GUID_ContainerFormatJpeg; + case ".jxr": + case ".hdp": + case ".wdp": + case ".wmp": return FX.GUID_ContainerFormatWmp; + case ".tiff": return FX.GUID_ContainerFormatTiff; + case ".dds": return FX.GUID_ContainerFormatDds; + default: return ThrowHelper.ThrowArgumentException("Invalid filename"); + } + } } } diff --git a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs index 61cee873..83d46a75 100644 --- a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs @@ -112,6 +112,106 @@ namespace ComputeSharp.Graphics.Helpers } } + /// + /// Saves a texture to a specified file. + /// + /// The type of items to store in the texture. + /// The texture data to save to an image. + /// The filename of the image file to save. + public void SaveTexture(TextureView2D texture, ReadOnlySpan filename) + where T : unmanaged + { + using ComPtr wicBitmapEncoder = default; + Guid containerGuid = WICFormatHelper.GetForFilename(filename); + + // Create the image encoder + this.wicImagingFactory2.Get()->CreateEncoder( + &containerGuid, + null, + wicBitmapEncoder.GetAddressOf()).Assert(); + + using ComPtr wicStream = default; + + // Create and initialize a stream to the target file + this.wicImagingFactory2.Get()->CreateStream(wicStream.GetAddressOf()).Assert(); + + fixed (char* p = filename) + { + wicStream.Get()->InitializeFromFilename( + (ushort*)p, + FX.GENERIC_WRITE); + } + + // Initialize the encoder + wicBitmapEncoder.Get()->Initialize( + (IStream*)wicStream.Get(), + WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache).Assert(); + + using ComPtr wicBitmapFrameEncode = default; + + // Create the image frame and initialize it + wicBitmapEncoder.Get()->CreateNewFrame(wicBitmapFrameEncode.GetAddressOf(), null).Assert(); + + wicBitmapFrameEncode.Get()->Initialize(null).Assert(); + wicBitmapFrameEncode.Get()->SetSize((uint)texture.Width, (uint)texture.Height).Assert(); + + // Depending on the target format and the current pixel type, we need to check whether + // an intermediate encoding step is necessary. This is because not all pixel formats + // are directly supported by the native image encoders present in Windows. + if (WICFormatHelper.TryGetIntermediateFormatForType(containerGuid, out Guid intermediateGuid)) + { + T* data = texture.DangerousGetAddressAndByteStride(out int strideInBytes); + + using ComPtr wicBitmap = default; + Guid initialGuid = WICFormatHelper.GetForType(); + + // Create a bitmap wrapping the input texture + this.wicImagingFactory2.Get()->CreateBitmapFromMemory( + (uint)texture.Width, + (uint)texture.Height, + &initialGuid, + (uint)strideInBytes, + (uint)(strideInBytes * texture.Height), + (byte*)data, + wicBitmap.GetAddressOf()).Assert(); + + using ComPtr wicFormatConverter = default; + + this.wicImagingFactory2.Get()->CreateFormatConverter(wicFormatConverter.GetAddressOf()).Assert(); + + // Get a format converter to encode the pixel data + wicFormatConverter.Get()->Initialize( + (IWICBitmapSource*)wicBitmap.Get(), + &intermediateGuid, + WICBitmapDitherType.WICBitmapDitherTypeNone, + null, + 0, + WICBitmapPaletteType.WICBitmapPaletteTypeMedianCut).Assert(); + + // Write the encoded image data to the frame + wicBitmapFrameEncode.Get()->SetPixelFormat(&intermediateGuid).Assert(); + wicBitmapFrameEncode.Get()->WriteSource( + (IWICBitmapSource*)wicBitmap.Get(), + null).Assert(); + } + else + { + T* data = texture.DangerousGetAddressAndByteStride(out int strideInBytes); + Guid initialGuid = WICFormatHelper.GetForType(); + + // Write the image data to the frame + wicBitmapFrameEncode.Get()->SetPixelFormat(&initialGuid).Assert(); + wicBitmapFrameEncode.Get()->WritePixels( + lineCount: (uint)texture.Height, + cbStride: (uint)strideInBytes, + cbBufferSize: (uint)(strideInBytes * texture.Height), + pbPixels: (byte*)data).Assert(); + } + + wicBitmapFrameEncode.Get()->Commit(); + wicBitmapEncoder.Get()->Commit(); + } + /// /// Loads a from a specified object. /// @@ -121,7 +221,7 @@ namespace ComputeSharp.Graphics.Helpers /// The object in use. /// A instance with the contents of the specified file. [Pure] - public ReadOnlyTexture2D LoadTexture(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder) + private ReadOnlyTexture2D LoadTexture(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder) where T : unmanaged, IUnorm where TPixel : unmanaged { diff --git a/tests/ComputeSharp.Tests/ImagingTests.cs b/tests/ComputeSharp.Tests/ImagingTests.cs index 752a2cb6..6e0e7656 100644 --- a/tests/ComputeSharp.Tests/ImagingTests.cs +++ b/tests/ComputeSharp.Tests/ImagingTests.cs @@ -9,6 +9,7 @@ using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; +using ImageSharpL8 = SixLabors.ImageSharp.PixelFormats.L8; namespace ComputeSharp.Tests { @@ -46,6 +47,59 @@ namespace ComputeSharp.Tests TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); } + [CombinatorialTestMethod] + [AllDevices] + public void SaveRgba32AsJpeg(Device device) + { + string + path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), + expectedPath = Path.Combine(path, "city.jpg"), + actualPath = Path.Combine(path, "city_rgba32_saved.jpg"); + + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(expectedPath); + + texture.Save(actualPath); + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void SaveBgra32AsJpeg(Device device) + { + string + path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), + expectedPath = Path.Combine(path, "city.jpg"), + actualPath = Path.Combine(path, "city_bgra32_saved.jpg"); + + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(expectedPath); + + texture.Save(actualPath); + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00001023f); + } + + [CombinatorialTestMethod] + [AllDevices] + public void SaveR8AsJpeg(Device device) + { + string + path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"), + sourcePath = Path.Combine(path, "city.jpg"), + expectedPath = Path.Combine(path, "city_r8_reference.jpg"), + actualPath = Path.Combine(path, "city_r8_saved.jpg"); + + using ReadOnlyTexture2D texture = device.Get().AllocateReadOnlyTexture2D(sourcePath); + + texture.Save(actualPath); + + using Image original = Image.Load(sourcePath); + + original.Save(expectedPath); + + TolerantImageComparer.AssertEqual(expectedPath, actualPath, 0.00004037f); + } + /// /// An tolerant image comparer type, from ImageSharp. /// From 94632776992740684ee08457491eb7e15d0471f6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 12 May 2021 11:24:29 +0200 Subject: [PATCH 7/7] Added extensions to load writeable textures from data --- .../Extensions/GraphicsDeviceExtensions.cs | 60 ++++++++++++++++++- .../Graphics/Helpers/WICHelper.cs | 46 +++++--------- 2 files changed, 74 insertions(+), 32 deletions(-) diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs index 16378891..6d65673e 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs @@ -341,7 +341,13 @@ namespace ComputeSharp where T : unmanaged, IUnorm where TPixel : unmanaged { - return WICHelper.Instance.LoadTexture(device, filename); + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, filename); + + ReadOnlyTexture2D texture = device.AllocateReadOnlyTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; } /// @@ -357,7 +363,13 @@ namespace ComputeSharp where T : unmanaged, IUnorm where TPixel : unmanaged { - return WICHelper.Instance.LoadTexture(device, span); + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, span); + + ReadOnlyTexture2D texture = device.AllocateReadOnlyTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; } /// @@ -809,6 +821,50 @@ namespace ComputeSharp return texture; } + /// + /// Allocates a new writeable 2D texture with the contents of the specified file. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The filename of the image file to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, ReadOnlySpan filename) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, filename); + + ReadWriteTexture2D texture = device.AllocateReadWriteTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; + } + + /// + /// Allocates a new writeable 2D texture with the contents of the specified buffer. + /// + /// The type of items to store in the texture. + /// The type of pixels used on the GPU side. + /// The instance to use to allocate the texture. + /// The buffer with the image data to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, ReadOnlySpan span) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, span); + + ReadWriteTexture2D texture = device.AllocateReadWriteTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; + } + /// /// Allocates a new writeable 3D texture with the specified parameters. /// diff --git a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs index 83d46a75..7bde9bf5 100644 --- a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs @@ -1,12 +1,9 @@ using System; using System.Diagnostics.Contracts; -using ComputeSharp.__Internals; using ComputeSharp.Core.Extensions; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; -#pragma warning disable CS0618 - namespace ComputeSharp.Graphics.Helpers { /// @@ -51,17 +48,15 @@ namespace ComputeSharp.Graphics.Helpers public static WICHelper Instance { get; } = new(); /// - /// Loads a from a specified file. + /// Loads an from a specified file. /// /// The type of items to store in the texture. - /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The filename of the image file to load and decode into the texture. - /// A instance with the contents of the specified file. + /// An instance with the contents of the specified file. [Pure] - public ReadOnlyTexture2D LoadTexture(GraphicsDevice device, ReadOnlySpan filename) - where T : unmanaged, IUnorm - where TPixel : unmanaged + public UploadTexture2D LoadTexture(GraphicsDevice device, ReadOnlySpan filename) + where T : unmanaged { using ComPtr wicBitmapDecoder = default; @@ -76,21 +71,19 @@ namespace ComputeSharp.Graphics.Helpers wicBitmapDecoder.GetAddressOf()).Assert(); } - return LoadTexture(device, wicBitmapDecoder.Get()); + return LoadTexture(device, wicBitmapDecoder.Get()); } /// - /// Loads a from a specified buffer. + /// Loads an from a specified buffer. /// /// The type of items to store in the texture. - /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The buffer with the image data to load and decode into the texture. - /// A instance with the contents of the specified file. + /// An instance with the contents of the specified file. [Pure] - public ReadOnlyTexture2D LoadTexture(GraphicsDevice device, ReadOnlySpan span) - where T : unmanaged, IUnorm - where TPixel : unmanaged + public UploadTexture2D LoadTexture(GraphicsDevice device, ReadOnlySpan span) + where T : unmanaged { using ComPtr wicBitmapDecoder = default; using ComPtr wicStream = default; @@ -108,7 +101,7 @@ namespace ComputeSharp.Graphics.Helpers WICDecodeOptions.WICDecodeMetadataCacheOnDemand, wicBitmapDecoder.GetAddressOf()).Assert(); - return LoadTexture(device, wicBitmapDecoder.Get()); + return LoadTexture(device, wicBitmapDecoder.Get()); } } @@ -213,17 +206,15 @@ namespace ComputeSharp.Graphics.Helpers } /// - /// Loads a from a specified object. + /// Loads an from a specified object. /// /// The type of items to store in the texture. - /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The object in use. - /// A instance with the contents of the specified file. + /// An instance with the contents of the specified file. [Pure] - private ReadOnlyTexture2D LoadTexture(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder) - where T : unmanaged, IUnorm - where TPixel : unmanaged + private UploadTexture2D LoadTexture(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder) + where T : unmanaged { using ComPtr wicBitmapFrameDecode = default; @@ -250,7 +241,7 @@ namespace ComputeSharp.Graphics.Helpers wicFormatConverter.Get()->GetSize(&width, &height).Assert(); // Allocate an upload texture to transfer the decoded pixel data - using UploadTexture2D upload = device.AllocateUploadTexture2D((int)width, (int)height); + UploadTexture2D upload = device.AllocateUploadTexture2D((int)width, (int)height); T* data = upload.View.DangerousGetAddressAndByteStride(out int strideInBytes); @@ -261,12 +252,7 @@ namespace ComputeSharp.Graphics.Helpers cbBufferSize: (uint)strideInBytes * height, pbBuffer: (byte*)data).Assert(); - // Create the final texture to return - ReadOnlyTexture2D texture = device.AllocateReadOnlyTexture2D((int)width, (int)height); - - upload.CopyTo(texture); - - return texture; + return upload; } } }