diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs index 18c54fb3..8220fc1a 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.Resources.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics.Contracts; +using System.IO; using ComputeSharp.__Internals; using ComputeSharp.Graphics.Helpers; using ComputeSharp.Resources; @@ -1133,6 +1134,30 @@ public static partial class GraphicsDeviceExtensions return texture; } + /// + /// Loads a new readonly 2D texture with the contents of the specified stream. + /// + /// 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 stream with the image data to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadOnlyTexture2D LoadReadOnlyTexture2D(this GraphicsDevice device, Stream stream) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + Guard.IsNotNull(stream, nameof(stream)); + + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, stream); + + ReadOnlyTexture2D texture = device.AllocateReadOnlyTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; + } + /// /// Loads a new writeable 2D texture with the contents of the specified file. /// @@ -1194,4 +1219,28 @@ public static partial class GraphicsDeviceExtensions return texture; } + + /// + /// Loads a new writeable 2D texture with the contents of the specified stream. + /// + /// 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 stream with the image data to load and decode into the texture. + /// A instance with the contents of the specified file. + [Pure] + public static ReadWriteTexture2D LoadReadWriteTexture2D(this GraphicsDevice device, Stream stream) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + Guard.IsNotNull(stream, nameof(stream)); + + using UploadTexture2D upload = WICHelper.Instance.LoadTexture(device, stream); + + ReadWriteTexture2D texture = device.AllocateReadWriteTexture2D(upload.Width, upload.Height); + + upload.CopyTo(texture); + + return texture; + } } diff --git a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs index 1090d5bb..c66b9a10 100644 --- a/src/ComputeSharp/Graphics/Helpers/WICHelper.cs +++ b/src/ComputeSharp/Graphics/Helpers/WICHelper.cs @@ -1,7 +1,9 @@ using System; using System.Diagnostics.Contracts; +using System.IO; using System.Runtime.CompilerServices; using ComputeSharp.Core.Extensions; +using ComputeSharp.Graphics.Extensions; using TerraFX.Interop.Windows; #pragma warning disable CA1416 @@ -106,6 +108,110 @@ internal sealed unsafe class WICHelper } } + /// + /// Loads an from a specified stream. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The stream with the image data to load and decode into the texture. + /// An instance with the contents of the specified file. + [Pure] + public UploadTexture2D LoadTexture(GraphicsDevice device, Stream stream) + where T : unmanaged + { + using ComPtr wicBitmapDecoder = default; + using ComPtr wicStream = default; + + this.wicImagingFactory2.Get()->CreateStream(wicStream.GetAddressOf()).Assert(); + + wicStream.Get()->InitializeFromStream(stream).Assert(); + + this.wicImagingFactory2.Get()->CreateDecoderFromStream( + (IStream*)wicStream.Get(), + null, + WICDecodeOptions.WICDecodeMetadataCacheOnDemand, + wicBitmapDecoder.GetAddressOf()).Assert(); + + return LoadTexture(device, wicBitmapDecoder.Get()); + } + + /// + /// Loads an from a specified object. + /// + /// The type of items to store in the texture. + /// The instance to use to allocate the texture. + /// The object in use. + /// An instance with the contents of the specified file. + [Pure] + private UploadTexture2D LoadTexture(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder) + where T : unmanaged + { + using ComPtr wicBitmapFrameDecode = default; + + // Get the first frame of the loaded image (if more are present, they will be ignored) + wicBitmapDecoder->GetFrame(0, wicBitmapFrameDecode.GetAddressOf()).Assert(); + + uint width; + uint height; + + // Extract the image size info + wicBitmapFrameDecode.Get()->GetSize(&width, &height).Assert(); + + Guid wicTargetPixelFormatGuid = WICFormatHelper.GetForType(); + Guid wicActualPixelFormatGuid; + + // Get the current and target pixel format info + wicBitmapFrameDecode.Get()->GetPixelFormat(&wicActualPixelFormatGuid).Assert(); + + // If the current pixel format is the same as the target one, we can just read the + // decoded pixel data directly. Otherwise, we need a pixel format conversion step. + if (wicTargetPixelFormatGuid == wicActualPixelFormatGuid) + { + // Allocate an upload texture to transfer the decoded pixel data + UploadTexture2D upload = device.AllocateUploadTexture2D((int)width, (int)height); + + T* data = upload.View.DangerousGetAddressAndByteStride(out int strideInBytes); + + // Copy the decoded pixels directly from the loaded image + wicBitmapFrameDecode.Get()->CopyPixels( + prc: null, + cbStride: (uint)strideInBytes, + cbBufferSize: (uint)strideInBytes * height, + pbBuffer: (byte*)data).Assert(); + + return upload; + } + else + { + using ComPtr wicFormatConverter = default; + + this.wicImagingFactory2.Get()->CreateFormatConverter(wicFormatConverter.GetAddressOf()).Assert(); + + // Get a format converter to decode the pixel data + wicFormatConverter.Get()->Initialize( + (IWICBitmapSource*)wicBitmapFrameDecode.Get(), + &wicTargetPixelFormatGuid, + WICBitmapDitherType.WICBitmapDitherTypeNone, + null, + 0, + WICBitmapPaletteType.WICBitmapPaletteTypeMedianCut).Assert(); + + // Allocate an upload texture to transfer the converted pixel data + 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(); + + return upload; + } + } + /// /// Saves a texture to a specified file. /// @@ -205,81 +311,4 @@ internal sealed unsafe class WICHelper wicBitmapFrameEncode.Get()->Commit(); wicBitmapEncoder.Get()->Commit(); } - - /// - /// Loads an from a specified object. - /// - /// The type of items to store in the texture. - /// The instance to use to allocate the texture. - /// The object in use. - /// An instance with the contents of the specified file. - [Pure] - private UploadTexture2D LoadTexture(GraphicsDevice device, IWICBitmapDecoder* wicBitmapDecoder) - where T : unmanaged - { - using ComPtr wicBitmapFrameDecode = default; - - // Get the first frame of the loaded image (if more are present, they will be ignored) - wicBitmapDecoder->GetFrame(0, wicBitmapFrameDecode.GetAddressOf()).Assert(); - - uint width; - uint height; - - // Extract the image size info - wicBitmapFrameDecode.Get()->GetSize(&width, &height).Assert(); - - Guid wicTargetPixelFormatGuid = WICFormatHelper.GetForType(); - Guid wicActualPixelFormatGuid; - - // Get the current and target pixel format info - wicBitmapFrameDecode.Get()->GetPixelFormat(&wicActualPixelFormatGuid).Assert(); - - // If the current pixel format is the same as the target one, we can just read the - // decoded pixel data directly. Otherwise, we need a pixel format conversion step. - if (wicTargetPixelFormatGuid == wicActualPixelFormatGuid) - { - // Allocate an upload texture to transfer the decoded pixel data - UploadTexture2D upload = device.AllocateUploadTexture2D((int)width, (int)height); - - T* data = upload.View.DangerousGetAddressAndByteStride(out int strideInBytes); - - // Copy the decoded pixels directly from the loaded image - wicBitmapFrameDecode.Get()->CopyPixels( - prc: null, - cbStride: (uint)strideInBytes, - cbBufferSize: (uint)strideInBytes * height, - pbBuffer: (byte*)data).Assert(); - - return upload; - } - else - { - using ComPtr wicFormatConverter = default; - - this.wicImagingFactory2.Get()->CreateFormatConverter(wicFormatConverter.GetAddressOf()).Assert(); - - // Get a format converter to decode the pixel data - wicFormatConverter.Get()->Initialize( - (IWICBitmapSource*)wicBitmapFrameDecode.Get(), - &wicTargetPixelFormatGuid, - WICBitmapDitherType.WICBitmapDitherTypeNone, - null, - 0, - WICBitmapPaletteType.WICBitmapPaletteTypeMedianCut).Assert(); - - // Allocate an upload texture to transfer the converted pixel data - 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(); - - return upload; - } - } } diff --git a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs index 003cbbb3..4214b6aa 100644 --- a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics.Contracts; +using System.IO; using ComputeSharp.__Internals; using ComputeSharp.Resources; @@ -335,14 +336,14 @@ public static class GraphicsDeviceExtensions } /// - /// Loads a new readonly 2D texture with the contents of the specified file. + /// Loads 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 type of texture to allocate. /// The buffer with the image data to load and decode into the texture. - /// A instance with the contents of the specified file. + /// A instance with the contents of the specified buffer. [Pure] public static Texture2D LoadTexture2D(this GraphicsDevice device, Type type, byte[] buffer) where T : unmanaged, IUnorm @@ -356,6 +357,28 @@ public static class GraphicsDeviceExtensions }; } + /// + /// Loads a new readonly 2D texture with the contents of the specified stream. + /// + /// 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 type of texture to allocate. + /// The stream with the image data to load and decode into the texture. + /// A instance with the contents of the specified stream. + [Pure] + public static Texture2D LoadTexture2D(this GraphicsDevice device, Type type, Stream stream) + where T : unmanaged, IUnorm + where TPixel : unmanaged + { + return type switch + { + _ when type == typeof(ReadOnlyTexture2D<,>) => device.LoadReadOnlyTexture2D(stream), + _ when type == typeof(ReadWriteTexture2D<,>) => device.LoadReadWriteTexture2D(stream), + _ => throw new ArgumentException($"Invalid type: {type}", nameof(type)) + }; + } + /// /// Saves a texture to a specified file. /// diff --git a/tests/ComputeSharp.Tests/ImagingTests.cs b/tests/ComputeSharp.Tests/ImagingTests.cs index dc42f0a7..f89ef461 100644 --- a/tests/ComputeSharp.Tests/ImagingTests.cs +++ b/tests/ComputeSharp.Tests/ImagingTests.cs @@ -111,6 +111,24 @@ public class ImagingTests TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); } + [CombinatorialTestMethod] + [AllDevices] + [Resource(typeof(ReadOnlyTexture2D<,>))] + [Resource(typeof(ReadWriteTexture2D<,>))] + public void LoadAsRgba32FromStream(Device device, Type textureType) + { + string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg"); + + using Stream stream = File.OpenRead(path); + + using Texture2D texture = device.Get().LoadTexture2D(textureType, stream); + + using Image loaded = texture.ToImage(); + using Image original = Image.Load(path); + + TolerantImageComparer.AssertEqual(original, loaded, 0.0000032f); + } + [CombinatorialTestMethod] [Device(Device.Warp)] [Resource(typeof(ReadOnlyTexture2D<,>))] @@ -121,6 +139,16 @@ public class ImagingTests using Texture2D texture = device.Get().LoadTexture2D(textureType, typeof(string), null!); } + [CombinatorialTestMethod] + [Device(Device.Warp)] + [Resource(typeof(ReadOnlyTexture2D<,>))] + [Resource(typeof(ReadWriteTexture2D<,>))] + [ExpectedException(typeof(ArgumentNullException))] + public void LoadAsRgba32_WithNullStream(Device device, Type textureType) + { + using Texture2D texture = device.Get().LoadTexture2D(textureType, (Stream)null!); + } + [CombinatorialTestMethod] [AllDevices] [Resource(typeof(ReadOnlyTexture2D<,>))]