diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index 6578e44d..23c797b5 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -24,9 +24,9 @@ - Hlsl.Void.tt True True + Hlsl.Void.tt True @@ -137,8 +137,8 @@ - Hlsl.Void.g.cs TextTemplatingFileGenerator + Hlsl.Void.g.cs TextTemplatingFileGenerator diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs index b55de47e..ad3f07cf 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs @@ -101,7 +101,7 @@ partial class ID2D1ShaderGenerator HashSet resourceTextureIndices = new(resourceTextureInfos.Where(info => info.Index.HasValue).Select(info => info.Index!.Value)); // All input description indices must be unique - if (resourceTextureIndices.Count != resourceTextureInfos.Count) + if (resourceTextureIndices.Count != resourceTextureInfos.Count(info => info.Index.HasValue)) { diagnostics.Add(RepeatedD2DResourceTextureIndices, structDeclarationSymbol, structDeclarationSymbol); } diff --git a/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj index 76c8e66e..3125ca55 100644 --- a/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj +++ b/src/ComputeSharp.D2D1/ComputeSharp.D2D1.csproj @@ -21,6 +21,24 @@ + + + + + + + True + True + PixelShaderEffect.Properties.tt + + + + + TextTemplatingFileGenerator + PixelShaderEffect.Properties.g.cs + + + true diff --git a/src/ComputeSharp.D2D1/Helpers/ThrowHelper.cs b/src/ComputeSharp.D2D1/Helpers/ThrowHelper.cs index 36fd8f77..288452c9 100644 --- a/src/ComputeSharp.D2D1/Helpers/ThrowHelper.cs +++ b/src/ComputeSharp.D2D1/Helpers/ThrowHelper.cs @@ -34,6 +34,18 @@ internal static class ThrowHelper throw new ArgumentException(message, name); } + /// + /// Throws a new . + /// + /// The argument name. + /// The message to include in the exception. + /// Thrown with the specified parameters. + [DoesNotReturn] + public static void ThrowArgumentNullException(string? name, string? message) + { + throw new ArgumentNullException(name, message); + } + /// /// Throws a new . /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ExtendMode.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ExtendMode.cs new file mode 100644 index 00000000..0ecb3e2b --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ExtendMode.cs @@ -0,0 +1,28 @@ +using static TerraFX.Interop.DirectX.D2D1_EXTEND_MODE; + +namespace ComputeSharp.D2D1; + +/// +/// Specifies how a brush paints areas outside of its normal content area. +/// +/// +/// This type exposes the available values in . +/// +public enum D2D1ExtendMode +{ + /// + /// Repeat the edge pixels of the brush's content for all regions outside the normal content area. + /// + Clamp = (int)D2D1_EXTEND_MODE_CLAMP, + + /// + /// Repeat the brush's content. + /// + Wrap = (int)D2D1_EXTEND_MODE_WRAP, + + /// + /// The same as , except that alternate tiles of the brush's + /// content are flipped (the brush's normal content is drawn untransformed). + /// + Mirror = (int)D2D1_EXTEND_MODE_MIRROR +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs index 83149d16..99015f4e 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs @@ -337,10 +337,16 @@ public static class D2D1PixelShader /// The type of D2D1 pixel shader to set the constant buffer for. /// The input D2D1 pixel shader to set the contant buffer for. /// A pointer to the ID2D1DrawInfo instance to use. + /// Thrown if is . /// For more info, see . public static unsafe void SetConstantBufferForD2D1DrawInfo(in T shader, void* d2D1DrawInfo) where T : unmanaged, ID2D1PixelShader { + if (d2D1DrawInfo is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1DrawInfo), "The input ID2D1DrawInfo object cannot be null."); + } + D2D1DrawInfoDispatchDataLoader dataLoader = new((ID2D1DrawInfo*)d2D1DrawInfo); Unsafe.AsRef(in shader).LoadDispatchData(ref dataLoader); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs index 3c1c813e..e83187bb 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffect.cs @@ -1,14 +1,12 @@ using System; using System.Globalization; using System.Runtime.CompilerServices; -#if !NET6_0_OR_GREATER -using System.Runtime.InteropServices; -#endif using System.Text; using ComputeSharp.D2D1.Extensions; using ComputeSharp.D2D1.Helpers; using ComputeSharp.D2D1.Interop.Effects; using ComputeSharp.D2D1.Shaders.Interop.Buffers; +using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; using ComputeSharp.D2D1.Shaders.Loaders; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -28,11 +26,17 @@ public static unsafe class D2D1PixelShaderEffect /// The type of D2D1 pixel shader to register. /// A pointer to the ID2D1Factory1 instance to use. /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// Thrown if is . /// Thrown if an effect is registered multiple times with different properties. /// For more info, see . - public static unsafe void RegisterForD2D1Factory1(void* d2D1Factory1, out Guid effectId) + public static void RegisterForD2D1Factory1(void* d2D1Factory1, out Guid effectId) where T : unmanaged, ID2D1PixelShader { + if (d2D1Factory1 is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1Factory1), "The input ID2D1Factory1 object cannot be null."); + } + RegisterForD2D1Factory1(d2D1Factory1, null, out effectId); } @@ -43,12 +47,18 @@ public static unsafe class D2D1PixelShaderEffect /// The type of implementation to register. /// A pointer to the ID2D1Factory1 instance to use. /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// Thrown if is . /// Thrown if an effect is registered multiple times with different properties. /// For more info, see . - public static unsafe void RegisterForD2D1Factory1(void* d2D1Factory1, out Guid effectId) + public static void RegisterForD2D1Factory1(void* d2D1Factory1, out Guid effectId) where T : unmanaged, ID2D1PixelShader where TMapper : class, ID2D1TransformMapper, new() { + if (d2D1Factory1 is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1Factory1), "The input ID2D1Factory1 object cannot be null."); + } + RegisterForD2D1Factory1(d2D1Factory1, static () => new TMapper(), out effectId); } @@ -59,11 +69,17 @@ public static unsafe class D2D1PixelShaderEffect /// A pointer to the ID2D1Factory1 instance to use. /// An optional factory of instances to use for the transform. /// The of the registered effect, which can be used to call ID2D1DeviceContext::CreateEffect. + /// Thrown if is . /// Thrown if an effect is registered multiple times with different properties. /// For more info, see . - public static unsafe void RegisterForD2D1Factory1(void* d2D1Factory1, Func>? mapperFactory, out Guid effectId) + public static void RegisterForD2D1Factory1(void* d2D1Factory1, Func>? mapperFactory, out Guid effectId) where T : unmanaged, ID2D1PixelShader { + if (d2D1Factory1 is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1Factory1), "The input ID2D1Factory1 object cannot be null."); + } + effectId = default; PixelShaderEffect.For.Initialize(mapperFactory); @@ -91,30 +107,134 @@ public static unsafe class D2D1PixelShaderEffect + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + "; fixed (char* pXml = xml) - fixed (char* pPropertyName = "Buffer") + fixed (char* pBufferPropertyName = "Buffer") + fixed (char* pResourceTextureManager0PropertyName = "ResourceTextureManager0") + fixed (char* pResourceTextureManager1PropertyName = "ResourceTextureManager1") + fixed (char* pResourceTextureManager2PropertyName = "ResourceTextureManager2") + fixed (char* pResourceTextureManager3PropertyName = "ResourceTextureManager3") + fixed (char* pResourceTextureManager4PropertyName = "ResourceTextureManager4") + fixed (char* pResourceTextureManager5PropertyName = "ResourceTextureManager5") + fixed (char* pResourceTextureManager6PropertyName = "ResourceTextureManager6") + fixed (char* pResourceTextureManager7PropertyName = "ResourceTextureManager7") + fixed (char* pResourceTextureManager8PropertyName = "ResourceTextureManager8") + fixed (char* pResourceTextureManager9PropertyName = "ResourceTextureManager9") + fixed (char* pResourceTextureManager10PropertyName = "ResourceTextureManager10") + fixed (char* pResourceTextureManager11PropertyName = "ResourceTextureManager11") + fixed (char* pResourceTextureManager12PropertyName = "ResourceTextureManager12") + fixed (char* pResourceTextureManager13PropertyName = "ResourceTextureManager13") + fixed (char* pResourceTextureManager14PropertyName = "ResourceTextureManager14") + fixed (char* pResourceTextureManager15PropertyName = "ResourceTextureManager15") { // Prepare the effect binding functions - D2D1_PROPERTY_BINDING d2D1PropertyBinding; - d2D1PropertyBinding.propertyName = (ushort*)pPropertyName; - d2D1PropertyBinding.getFunction = - (delegate* unmanaged[Stdcall]) -#if NET6_0_OR_GREATER - (delegate* unmanaged) - &PixelShaderEffect.GetConstantBuffer; -#else - (void*)Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.GetConstantBufferWrapper); -#endif - d2D1PropertyBinding.setFunction = - (delegate* unmanaged[Stdcall]) -#if NET6_0_OR_GREATER - (delegate* unmanaged) - &PixelShaderEffect.SetConstantBuffer; -#else - (void*)Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.SetConstantBufferWrapper); -#endif + D2D1_PROPERTY_BINDING* d2D1PropertyBinding = stackalloc D2D1_PROPERTY_BINDING[17]; + + // Property names + d2D1PropertyBinding[0].propertyName = (ushort*)pBufferPropertyName; + d2D1PropertyBinding[1].propertyName = (ushort*)pResourceTextureManager0PropertyName; + d2D1PropertyBinding[2].propertyName = (ushort*)pResourceTextureManager1PropertyName; + d2D1PropertyBinding[3].propertyName = (ushort*)pResourceTextureManager2PropertyName; + d2D1PropertyBinding[4].propertyName = (ushort*)pResourceTextureManager3PropertyName; + d2D1PropertyBinding[5].propertyName = (ushort*)pResourceTextureManager4PropertyName; + d2D1PropertyBinding[6].propertyName = (ushort*)pResourceTextureManager5PropertyName; + d2D1PropertyBinding[7].propertyName = (ushort*)pResourceTextureManager6PropertyName; + d2D1PropertyBinding[8].propertyName = (ushort*)pResourceTextureManager7PropertyName; + d2D1PropertyBinding[9].propertyName = (ushort*)pResourceTextureManager8PropertyName; + d2D1PropertyBinding[10].propertyName = (ushort*)pResourceTextureManager9PropertyName; + d2D1PropertyBinding[11].propertyName = (ushort*)pResourceTextureManager10PropertyName; + d2D1PropertyBinding[12].propertyName = (ushort*)pResourceTextureManager11PropertyName; + d2D1PropertyBinding[13].propertyName = (ushort*)pResourceTextureManager12PropertyName; + d2D1PropertyBinding[14].propertyName = (ushort*)pResourceTextureManager13PropertyName; + d2D1PropertyBinding[15].propertyName = (ushort*)pResourceTextureManager14PropertyName; + d2D1PropertyBinding[16].propertyName = (ushort*)pResourceTextureManager15PropertyName; + + // Property getters + d2D1PropertyBinding[0].getFunction = PixelShaderEffect.GetConstantBuffer; + d2D1PropertyBinding[1].getFunction = PixelShaderEffect.GetResourceTextureManager0; + d2D1PropertyBinding[2].getFunction = PixelShaderEffect.GetResourceTextureManager1; + d2D1PropertyBinding[3].getFunction = PixelShaderEffect.GetResourceTextureManager2; + d2D1PropertyBinding[4].getFunction = PixelShaderEffect.GetResourceTextureManager3; + d2D1PropertyBinding[5].getFunction = PixelShaderEffect.GetResourceTextureManager4; + d2D1PropertyBinding[6].getFunction = PixelShaderEffect.GetResourceTextureManager5; + d2D1PropertyBinding[7].getFunction = PixelShaderEffect.GetResourceTextureManager6; + d2D1PropertyBinding[8].getFunction = PixelShaderEffect.GetResourceTextureManager7; + d2D1PropertyBinding[9].getFunction = PixelShaderEffect.GetResourceTextureManager8; + d2D1PropertyBinding[10].getFunction = PixelShaderEffect.GetResourceTextureManager9; + d2D1PropertyBinding[11].getFunction = PixelShaderEffect.GetResourceTextureManager10; + d2D1PropertyBinding[12].getFunction = PixelShaderEffect.GetResourceTextureManager11; + d2D1PropertyBinding[13].getFunction = PixelShaderEffect.GetResourceTextureManager12; + d2D1PropertyBinding[14].getFunction = PixelShaderEffect.GetResourceTextureManager13; + d2D1PropertyBinding[15].getFunction = PixelShaderEffect.GetResourceTextureManager14; + d2D1PropertyBinding[16].getFunction = PixelShaderEffect.GetResourceTextureManager15; + + // Property setters + d2D1PropertyBinding[0].setFunction = PixelShaderEffect.SetConstantBuffer; + d2D1PropertyBinding[1].setFunction = PixelShaderEffect.SetResourceTextureManager0; + d2D1PropertyBinding[2].setFunction = PixelShaderEffect.SetResourceTextureManager1; + d2D1PropertyBinding[3].setFunction = PixelShaderEffect.SetResourceTextureManager2; + d2D1PropertyBinding[4].setFunction = PixelShaderEffect.SetResourceTextureManager3; + d2D1PropertyBinding[5].setFunction = PixelShaderEffect.SetResourceTextureManager4; + d2D1PropertyBinding[6].setFunction = PixelShaderEffect.SetResourceTextureManager5; + d2D1PropertyBinding[7].setFunction = PixelShaderEffect.SetResourceTextureManager6; + d2D1PropertyBinding[8].setFunction = PixelShaderEffect.SetResourceTextureManager7; + d2D1PropertyBinding[9].setFunction = PixelShaderEffect.SetResourceTextureManager8; + d2D1PropertyBinding[10].setFunction = PixelShaderEffect.SetResourceTextureManager9; + d2D1PropertyBinding[11].setFunction = PixelShaderEffect.SetResourceTextureManager10; + d2D1PropertyBinding[12].setFunction = PixelShaderEffect.SetResourceTextureManager11; + d2D1PropertyBinding[13].setFunction = PixelShaderEffect.SetResourceTextureManager12; + d2D1PropertyBinding[14].setFunction = PixelShaderEffect.SetResourceTextureManager13; + d2D1PropertyBinding[15].setFunction = PixelShaderEffect.SetResourceTextureManager14; + d2D1PropertyBinding[16].setFunction = PixelShaderEffect.SetResourceTextureManager15; fixed (Guid* pGuid = &PixelShaderEffect.For.Id) { @@ -122,8 +242,8 @@ public static unsafe class D2D1PixelShaderEffect ((ID2D1Factory1*)d2D1Factory1)->RegisterEffectFromString( classId: pGuid, propertyXml: (ushort*)pXml, - bindings: &d2D1PropertyBinding, - bindingsCount: 1, + bindings: d2D1PropertyBinding, + bindingsCount: 17, effectFactory: PixelShaderEffect.For.Factory).Assert(); } @@ -139,7 +259,7 @@ public static unsafe class D2D1PixelShaderEffect /// A blob containing serialized information that can be used to register an effect. /// Thrown if an effect is registered multiple times with different properties. /// For more info and for details on the binary format, see . - public static unsafe ReadOnlyMemory GetRegistrationBlob(out Guid effectId) + public static ReadOnlyMemory GetRegistrationBlob(out Guid effectId) where T : unmanaged, ID2D1PixelShader { return GetRegistrationBlob(null, out effectId); @@ -154,7 +274,7 @@ public static unsafe class D2D1PixelShaderEffect /// A blob containing serialized information that can be used to register an effect. /// Thrown if an effect is registered multiple times with different properties. /// For more info and for details on the binary format, see . - public static unsafe ReadOnlyMemory GetRegistrationBlob(out Guid effectId) + public static ReadOnlyMemory GetRegistrationBlob(out Guid effectId) where T : unmanaged, ID2D1PixelShader where TMapper : class, ID2D1TransformMapper, new() { @@ -201,7 +321,7 @@ public static unsafe class D2D1PixelShaderEffect /// For more info, see . /// /// - public static unsafe ReadOnlyMemory GetRegistrationBlob(Func>? mapperFactory, out Guid effectId) + public static ReadOnlyMemory GetRegistrationBlob(Func>? mapperFactory, out Guid effectId) where T : unmanaged, ID2D1PixelShader { effectId = default; @@ -243,26 +363,129 @@ public static unsafe class D2D1PixelShaderEffect + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + "); // Null terminator for the text writer.Write((byte)'\0'); - // Property accessors -#if NET6_0_OR_GREATER - nint getBufferPointer = (nint)(delegate* unmanaged)&PixelShaderEffect.GetConstantBuffer; - nint setBufferPointer = (nint)(delegate* unmanaged)&PixelShaderEffect.SetConstantBuffer; -#else - nint getBufferPointer = Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.GetConstantBufferWrapper); - nint setBufferPointer = Marshal.GetFunctionPointerForDelegate(PixelShaderEffect.SetConstantBufferWrapper); -#endif - // Bindings - writer.Write(1); + writer.Write(17); writer.WriteAsUtf8("Buffer"); writer.Write((byte)'\0'); - writer.Write(getBufferPointer); - writer.Write(setBufferPointer); + writer.Write((nint)PixelShaderEffect.GetConstantBuffer); + writer.Write((nint)PixelShaderEffect.SetConstantBuffer); + writer.WriteAsUtf8("ResourceTextureManager0"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager0); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager0); + writer.WriteAsUtf8("ResourceTextureManager1"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager1); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager1); + writer.WriteAsUtf8("ResourceTextureManager2"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager2); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager2); + writer.WriteAsUtf8("ResourceTextureManager3"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager3); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager3); + writer.WriteAsUtf8("ResourceTextureManager4"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager4); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager4); + writer.WriteAsUtf8("ResourceTextureManager5"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager5); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager5); + writer.WriteAsUtf8("ResourceTextureManager6"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager6); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager6); + writer.WriteAsUtf8("ResourceTextureManager7"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager7); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager7); + writer.WriteAsUtf8("ResourceTextureManager8"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager8); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager8); + writer.WriteAsUtf8("ResourceTextureManager9"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager9); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager9); + writer.WriteAsUtf8("ResourceTextureManager10"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager10); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager10); + writer.WriteAsUtf8("ResourceTextureManager11"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager11); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager11); + writer.WriteAsUtf8("ResourceTextureManager12"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager12); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager12); + writer.WriteAsUtf8("ResourceTextureManager13"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager13); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager13); + writer.WriteAsUtf8("ResourceTextureManager14"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager14); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager14); + writer.WriteAsUtf8("ResourceTextureManager15"); + writer.Write((byte)'\0'); + writer.Write((nint)PixelShaderEffect.GetResourceTextureManager15); + writer.Write((nint)PixelShaderEffect.SetResourceTextureManager15); // Effect factory writer.Write((nint)PixelShaderEffect.For.Factory); @@ -278,15 +501,26 @@ public static unsafe class D2D1PixelShaderEffect /// The type of D2D1 pixel shader to create an effect for. /// A pointer to the ID2D1DeviceContext instance to use. /// A pointer to the resulting ID2D1Effect* pointer to produce. + /// Thrown if or are . /// /// Thrown if this method is called before initializing a shader effect for the shader type . /// To do so, make sure to call either (or an overload), or /// to use (or an overload), and use that blob to register an effect. /// /// For more info, see . - public static unsafe void CreateFromD2D1DeviceContext(void* d2D1DeviceContext, void** d2D1Effect) + public static void CreateFromD2D1DeviceContext(void* d2D1DeviceContext, void** d2D1Effect) where T : unmanaged, ID2D1PixelShader { + if (d2D1DeviceContext is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1DeviceContext), "The input ID2D1DeviceContext object cannot be null."); + } + + if (d2D1Effect is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1Effect), "The pointer to the target ID2D1Effect result cannot be null."); + } + if (!PixelShaderEffect.For.TryGetId(out Guid id)) { ThrowHelper.ThrowInvalidOperationException("The effect for the input shader type has not been initialized yet."); @@ -303,12 +537,76 @@ public static unsafe class D2D1PixelShaderEffect /// The type of D2D1 pixel shader to set the constant buffer for. /// The input D2D1 pixel shader to set the contant buffer for. /// A pointer to the ID2D1Effect instance to use. + /// Thrown if is . /// For more info, see . - public static unsafe void SetConstantBufferForD2D1Effect(in T shader, void* d2D1Effect) + public static void SetConstantBufferForD2D1Effect(in T shader, void* d2D1Effect) where T : unmanaged, ID2D1PixelShader { + if (d2D1Effect is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1Effect), "The input ID2D1DeviceContext object cannot be null."); + } + D2D1EffectDispatchDataLoader dataLoader = new((ID2D1Effect*)d2D1Effect); Unsafe.AsRef(in shader).LoadDispatchData(ref dataLoader); } + + /// + /// Sets the resource texture manager from an input D2D1 effect, by calling ID2D1Effect::SetValue. + /// + /// A pointer to the ID2D1Effect instance to use. + /// The input ID2D1ResourceTextureManager object (see ). + /// The index of the resource texture to assign the resource texture manager to. + /// Thrown if or are . + /// For more info, see . + public static void SetResourceTextureManagerForD2D1Effect(void* d2D1Effect, void* resourceTextureManager, int resourceTextureIndex) + { + if (d2D1Effect is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1Effect), "The input ID2D1Effect object cannot be null."); + } + + if (resourceTextureManager is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(resourceTextureManager), "The input ID2D1ResourceTextureManager object cannot be null."); + } + + ((ID2D1Effect*)d2D1Effect)->SetValue( + index: D2D1PixelShaderEffectProperty.ResourceTextureManager0 + (uint)resourceTextureIndex, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_IUNKNOWN, + data: (byte*)&resourceTextureManager, + dataSize: (uint)sizeof(void*)).Assert(); + } + + /// + /// Sets the resource texture manager from an input D2D1 effect, by calling ID2D1Effect::SetValue. + /// + /// A pointer to the ID2D1Effect instance to use. + /// The input instance.. + /// The index of the resource texture to assign the resource texture manager to. + /// Thrown if or are . + /// For more info, see . + public static void SetResourceTextureManagerForD2D1Effect(void* d2D1Effect, D2D1ResourceTextureManager resourceTextureManager, int resourceTextureIndex) + { + if (d2D1Effect is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(d2D1Effect), "The input ID2D1Effect object cannot be null."); + } + + if (resourceTextureManager is null) + { + ThrowHelper.ThrowArgumentNullException(nameof(resourceTextureManager), "The input D2D1ResourceTextureManager object cannot be null."); + } + + using ComPtr resourceTextureManager2 = default; + + resourceTextureManager.GetD2D1ResourceTextureManager(resourceTextureManager2.GetAddressOf()); + + ((ID2D1Effect*)d2D1Effect)->SetValue( + index: D2D1PixelShaderEffectProperty.ResourceTextureManager0 + (uint)resourceTextureIndex, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_IUNKNOWN, + data: (byte*)resourceTextureManager2.GetAddressOf(), + dataSize: (uint)sizeof(void*)).Assert(); + } } diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffectProperty.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffectProperty.cs index de30340b..dbf89f8d 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffectProperty.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShaderEffectProperty.cs @@ -7,7 +7,7 @@ public static class D2D1PixelShaderEffectProperty { /// - /// The index for the constant buffer property of a object. + /// The index for the constant buffer property of a object. /// /// /// The value to set for this property can be retrieved with . @@ -16,4 +16,100 @@ public static class D2D1PixelShaderEffectProperty /// For more info, see . /// public const uint ConstantBuffer = 0; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 0. + /// + /// For more info, see . + public const uint ResourceTextureManager0 = 1; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 1. + /// + /// For more info, see . + public const uint ResourceTextureManager1 = 2; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 2. + /// + /// For more info, see . + public const uint ResourceTextureManager2 = 3; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 3. + /// + /// For more info, see . + public const uint ResourceTextureManager3 = 4; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 4. + /// + /// For more info, see . + public const uint ResourceTextureManager4 = 5; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 5. + /// + /// For more info, see . + public const uint ResourceTextureManager5 = 6; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 6. + /// + /// For more info, see . + public const uint ResourceTextureManager6 = 7; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 7. + /// + /// For more info, see . + public const uint ResourceTextureManager7 = 8; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 8. + /// + /// For more info, see . + public const uint ResourceTextureManager8 = 9; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 9. + /// + /// For more info, see . + public const uint ResourceTextureManager9 = 10; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 10. + /// + /// For more info, see . + public const uint ResourceTextureManager10 = 11; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 11. + /// + /// For more info, see . + public const uint ResourceTextureManager11 = 12; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 12. + /// + /// For more info, see . + public const uint ResourceTextureManager12 = 13; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 13. + /// + /// For more info, see . + public const uint ResourceTextureManager13 = 14; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 14. + /// + /// For more info, see . + public const uint ResourceTextureManager14 = 15; + + /// + /// The index for the ID2D1ResourceTextureManager instance for the resource texture at index 15. + /// + /// For more info, see . + public const uint ResourceTextureManager15 = 16; } diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureManager.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureManager.cs new file mode 100644 index 00000000..8710954a --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureManager.cs @@ -0,0 +1,491 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Interop; + +/// +/// Provides an ID2D1ResourceTextureManager implementation, which can be used to manage resources in +/// an effect created with and share them across multiple effect instances. +/// +/// +/// +/// The built-in ID2D1EffectImpl +/// implementation provided by (which makes it possible to register and create +/// ID2D1Effect +/// instances that can be used to run D2D1 pixel shaders) uses resource texture manager objects to handle resource textures. +/// +/// +/// These managers are COM objects implementing the following interface: +/// +/// [uuid(3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64)] +/// interface ID2D1ResourceTextureManager : IUnknown +/// { +/// HRESULT Initialize( +/// [in, optional] const GUID *resourceId, +/// [in] const D2D1_RESOURCE_TEXTURE_PROPERTIES *resourceTextureProperties, +/// [in, optional] const BYTE *data, +/// [in, optional] const UINT32 *strides, +/// UINT32 dataSize); +/// +/// HRESULT Update( +/// [in, optional] const UINT32 *minimumExtents, +/// [in, optional] const UINT32 *maximimumExtents, +/// [in] const UINT32 *strides, +/// UINT32 dimensions, +/// [in] const BYTE *data, +/// UINT32 dataCount); +/// }; +/// +/// +/// +/// These can be used to create resource textures, pass them to effects, and also share resources among different effects. +/// +/// +/// For details of how these work, Initialize maps to +/// ID2D1EffectContext::CreateResourceTexture, +/// whereas Update maps to ID2D1ResourceTexture::Update. +/// The same behavior and parameters as those methods is used. +/// +/// +/// This interface is implemented by ComputeSharp.D2D1, and it can be used through the APIs in . +/// That is, is first used to create an ID2D1ResourceTextureManager instance. Then, +/// can be used to initialize the resource texture held by the manager. The manager can also be assigned to an effect at any time, +/// using the available property indices from . To update texture data after its initial +/// creation, can be used. +/// +/// +/// An RCW (runtime callable wrapper, see ), +/// is also available for all of these APIs, implemented by the same . In this case, the constructor can +/// be used to create and initialize an instance (equivalent to calling and ), and then +/// is available for texture data updates. +/// The instance implements , which can be used in advanced scenarios to retrieve the underlying COM object. +/// +/// +/// The ID2D1ResourceTextureManager contract allows callers to create a resource texture at any time even before the effect +/// has been initialized and the manager assigned to it. In that case, the manager will buffer the data internally, and will defer +/// the creation of the actual resource texture until it's possible for it to do so, at which point it will also free the buffer. +/// +/// +/// If implementing a custom resource manager is needed, in order for external implementations to be accepted by the effect objects +/// created by , the ID2D1ResourceTextureManagerInternal interface also needs to be implemented: +/// +/// [uuid(5CBB1024-8EA1-4689-81BF-8AD190B5EF5D)] +/// interface ID2D1ResourceTextureManager : IUnknown +/// { +/// HRESULT Initialize( +/// [in] ID2D1EffectContext *effectContext, +/// [in, optional] const UINT32 *dimensions); +/// +/// HRESULT GetResourceTexture([out] ID2D1ResourceTexture **resourceTexture); +/// }; +/// +/// +/// +/// Note that due to the fact ID2D1EffectContext +/// and ID2D1ResourceTexture are not thread safe, +/// they are only safe to use without additional synchronization when Initialize and GetResourceTexture are called. This happens from the internal +/// ID2D1EffectImpl object, which is invoked by D2D, which will handle +/// taking the necessary lock before invoking these APIs. Due to the fact the context has to be stored internally, custom implementations have to make sure to retrieve the +/// right ID2D1Multithread instance from the effect context and use that to synchronize all accesses to those two objects from all APIs (including those exposed by +/// ID2D1ResourceTextureManager). The built-in implementation of these two interfaces provided by takes care of all this. +/// +/// +/// The dimensions parameter in ID2D1ResourceTextureManager::Initialize is optional, and can be passed by an ID2D1Effect +/// when initializing an input resurce texture manager, if the dimensions of the resource texture at the target index are known in advance. +/// This can allow the manager to perform additional validation when the resource texture is initialized. Not providing a value is not an +/// error, but if a resource texture with invalid size is used the effect might fail to render later on and be more difficult to troubleshoot. +/// +/// +public sealed unsafe class D2D1ResourceTextureManager : ICustomQueryInterface +{ + /// + /// The object wrapped by the current instance. + /// + private readonly D2D1ResourceTextureManagerImpl* d2D1ResourceManagerImpl; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The extents of the resource to create. + /// The buffer precision for the resource to create. + /// The channel depth for the resource to create. + /// The filter for the resource to create. + /// The extend modes for the resource to create. + /// Thrown if creating or initializing the instance failed. + public D2D1ResourceTextureManager( + ReadOnlySpan extents, + D2D1BufferPrecision bufferPrecision, + D2D1ChannelDepth channelDepth, + D2D1Filter filter, + ReadOnlySpan extendModes) + : this( + null, + extents, + bufferPrecision, + channelDepth, + filter, + extendModes, + ReadOnlySpan.Empty, + ReadOnlySpan.Empty) + { + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The resource id for the resource to create. + /// The extents of the resource to create. + /// The buffer precision for the resource to create. + /// The channel depth for the resource to create. + /// The filter for the resource to create. + /// The extend modes for the resource to create. + /// Thrown if creating or initializing the instance failed. + public D2D1ResourceTextureManager( + Guid resourceId, + ReadOnlySpan extents, + D2D1BufferPrecision bufferPrecision, + D2D1ChannelDepth channelDepth, + D2D1Filter filter, + ReadOnlySpan extendModes) + : this( + &resourceId, + extents, + bufferPrecision, + channelDepth, + filter, + extendModes, + ReadOnlySpan.Empty, + ReadOnlySpan.Empty) + { + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The extents of the resource to create. + /// The buffer precision for the resource to create. + /// The channel depth for the resource to create. + /// The filter for the resource to create. + /// The extend modes for the resource to create. + /// The data to load in the resource to create. + /// The strides for the data supplied for the resource to create. + /// Thrown if creating or initializing the instance failed. + public D2D1ResourceTextureManager( + ReadOnlySpan extents, + D2D1BufferPrecision bufferPrecision, + D2D1ChannelDepth channelDepth, + D2D1Filter filter, + ReadOnlySpan extendModes, + ReadOnlySpan data, + ReadOnlySpan strides) + : this( + null, + extents, + bufferPrecision, + channelDepth, + filter, + extendModes, + data, + strides) + { + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The resource id for the resource to create. + /// The extents of the resource to create. + /// The buffer precision for the resource to create. + /// The channel depth for the resource to create. + /// The filter for the resource to create. + /// The extend modes for the resource to create. + /// The data to load in the resource to create. + /// The strides for the data supplied for the resource to create. + /// Thrown if creating or initializing the instance failed. + public D2D1ResourceTextureManager( + Guid resourceId, + ReadOnlySpan extents, + D2D1BufferPrecision bufferPrecision, + D2D1ChannelDepth channelDepth, + D2D1Filter filter, + ReadOnlySpan extendModes, + ReadOnlySpan data, + ReadOnlySpan strides) + : this( + &resourceId, + extents, + bufferPrecision, + channelDepth, + filter, + extendModes, + data, + strides) + { + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The resource id for the resource to create. + /// The extents of the resource to create. + /// The buffer precision for the resource to create. + /// The channel depth for the resource to create. + /// The filter for the resource to create. + /// The extend modes for the resource to create. + /// The data to load in the resource to create. + /// The strides for the data supplied for the resource to create. + /// Thrown if creating or initializing the instance failed. + private D2D1ResourceTextureManager( + Guid* resourceId, + ReadOnlySpan extents, + D2D1BufferPrecision bufferPrecision, + D2D1ChannelDepth channelDepth, + D2D1Filter filter, + ReadOnlySpan extendModes, + ReadOnlySpan data, + ReadOnlySpan strides) + { + // Manually validate the parameters here to ensure the native objects wouldn't try + // to read out of bounds and potentially AV. For those cases, we just throw here. + if (extents.Length == 0 || + extendModes.Length == 0 || + extents.Length != extendModes.Length || + (data.Length > 0 && strides.Length != extents.Length - 1)) + { + GC.SuppressFinalize(this); + + Marshal.ThrowExceptionForHR(E.E_INVALIDARG); + } + + fixed (D2D1ResourceTextureManagerImpl** d2D1ResourceManagerImpl = &this.d2D1ResourceManagerImpl) + { + D2D1ResourceTextureManagerImpl.Factory(d2D1ResourceManagerImpl); + } + + fixed (uint* pExtents = extents) + fixed (D2D1ExtendMode* pExtendModes = extendModes) + fixed (byte* pData = data) + fixed (uint* pStrides = strides) + { + D2D1_RESOURCE_TEXTURE_PROPERTIES d2D1ResourceTextureProperties; + d2D1ResourceTextureProperties.extents = pExtents; + d2D1ResourceTextureProperties.dimensions = (uint)extents.Length; + d2D1ResourceTextureProperties.bufferPrecision = (D2D1_BUFFER_PRECISION)bufferPrecision; + d2D1ResourceTextureProperties.channelDepth = (D2D1_CHANNEL_DEPTH)channelDepth; + d2D1ResourceTextureProperties.filter = (D2D1_FILTER)filter; + d2D1ResourceTextureProperties.extendModes = (D2D1_EXTEND_MODE*)pExtendModes; + + int hresult = D2D1ResourceTextureManagerImpl.Initialize( + @this: this.d2D1ResourceManagerImpl, + resourceId: resourceId, + resourceTextureProperties: &d2D1ResourceTextureProperties, + data: pData, + strides: pStrides, + dataSize: (uint)data.Length); + + Marshal.ThrowExceptionForHR(hresult); + } + } + + /// + /// Releases the underlying ID2D1ResourceTextureManager object. + /// + ~D2D1ResourceTextureManager() + { + if (this.d2D1ResourceManagerImpl is not null) + { + this.d2D1ResourceManagerImpl->Release(); + } + } + + /// + /// Updates the specific resource texture inside the specific range or box using the supplied data. + /// + /// The "left" extent of the updates if specified. If , the entire texture is updated. + /// The "right" extent of the updates if specified. If , the entire texture is updated. + /// The stride to advance through the input data, according to dimension. + /// The data to be placed into the resource texture. + public void Update( + ReadOnlySpan minimumExtents, + ReadOnlySpan maximimumExtents, + ReadOnlySpan strides, + ReadOnlySpan data) + { + fixed (uint* pMinimumExtents = minimumExtents) + fixed (uint* pMaximumExtents = maximimumExtents) + fixed (uint* pStrides = strides) + fixed (byte* pData = data) + { + int dimensions = strides.Length + 1; + + // Ensure that if the extents are not null, their length is correct. This is again to + // avoid the native method assuming they'd be longer than they are and causing an AV. + if (pMinimumExtents is not null && + pMaximumExtents is not null && + (minimumExtents.Length != dimensions || maximimumExtents.Length != dimensions)) + { + Marshal.ThrowExceptionForHR(E.E_INVALIDARG); + } + + int hresult = D2D1ResourceTextureManagerImpl.Update( + @this: this.d2D1ResourceManagerImpl, + minimumExtents: pMinimumExtents, + maximimumExtents: pMaximumExtents, + strides: pStrides, + dimensions: (uint)dimensions, + data: pData, + dataCount: (uint)data.Length); + + GC.KeepAlive(this); + + Marshal.ThrowExceptionForHR(hresult); + } + } + + /// + /// Gets the underlying object. + /// + /// The underlying object. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void GetD2D1ResourceTextureManager(ID2D1ResourceTextureManager** resourceTextureManager) + { + _ = this.d2D1ResourceManagerImpl->AddRef(); + + *resourceTextureManager = (ID2D1ResourceTextureManager*)this.d2D1ResourceManagerImpl; + + GC.KeepAlive(this); + } + + /// + CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) + { + fixed (Guid* pIid = &iid) + fixed (IntPtr* pPpv = &ppv) + { + int hresult = this.d2D1ResourceManagerImpl->QueryInterface(pIid, (void**)pPpv); + + GC.KeepAlive(this); + + return hresult switch + { + S.S_OK => CustomQueryInterfaceResult.Handled, + _ => CustomQueryInterfaceResult.Failed + }; + } + } + + /// + /// Creates a new ID2D1ResourceTextureManager instance. + /// + /// A pointer to the resulting ID2D1ResourceTextureManager instance. + public static void Create(void** resourceTextureManager) + { + D2D1ResourceTextureManagerImpl.Factory((D2D1ResourceTextureManagerImpl**)resourceTextureManager); + } + + /// + /// Initializes a given ID2D1ResourceTextureManager instance. + /// + /// A pointer to the ID2D1ResourceTextureManager instance to use. + /// The resource id for the resource to create. + /// The extents of the resource to create. + /// The buffer precision for the resource to create. + /// The channel depth for the resource to create. + /// The filter for the resource to create. + /// The extend modes for the resource to create. + /// The data to load in the resource to create. + /// The strides for the data supplied for the resource to create. + /// + /// Depending on internal state, might immediately create the resource + /// texture, or it might buffer the data internally and then create the resource texture at a later time. + /// + public static void Initialize( + void* resourceTextureManager, + Guid resourceId, + ReadOnlySpan extents, + D2D1BufferPrecision bufferPrecision, + D2D1ChannelDepth channelDepth, + D2D1Filter filter, + ReadOnlySpan extendModes, + ReadOnlySpan data, + ReadOnlySpan strides) + { + // Validate parameters early from here too to avoid AVs in the native method + if (extents.Length == 0 || + extendModes.Length == 0 || + extents.Length != extendModes.Length || + (data.Length > 0 && strides.Length != extents.Length - 1)) + { + Marshal.ThrowExceptionForHR(E.E_INVALIDARG); + } + + fixed (uint* pExtents = extents) + fixed (D2D1ExtendMode* pExtendModes = extendModes) + fixed (byte* pData = data) + fixed (uint* pStrides = strides) + { + D2D1_RESOURCE_TEXTURE_PROPERTIES d2D1ResourceTextureProperties; + d2D1ResourceTextureProperties.extents = pExtents; + d2D1ResourceTextureProperties.dimensions = (uint)extents.Length; + d2D1ResourceTextureProperties.bufferPrecision = (D2D1_BUFFER_PRECISION)bufferPrecision; + d2D1ResourceTextureProperties.channelDepth = (D2D1_CHANNEL_DEPTH)channelDepth; + d2D1ResourceTextureProperties.filter = (D2D1_FILTER)filter; + d2D1ResourceTextureProperties.extendModes = (D2D1_EXTEND_MODE*)pExtendModes; + + int hresult = ((ID2D1ResourceTextureManager*)resourceTextureManager)->Initialize( + resourceId: &resourceId, + resourceTextureProperties: &d2D1ResourceTextureProperties, + data: pData, + strides: pStrides, + dataSize: (uint)data.Length); + + Marshal.ThrowExceptionForHR(hresult); + } + } + + /// + /// Updates the data in a given ID2D1ResourceTextureManager instance. + /// + /// A pointer to the ID2D1ResourceTextureManager instance to use. + /// The "left" extent of the updates if specified (if empty, the entire texture is updated). + /// The "right" extent of the updates if specified (if empty, the entire texture is updated). + /// The stride to advance through the input data. + /// The data to be placed into the resource texture. + public static void Update( + void* resourceTextureManager, + ReadOnlySpan minimumExtents, + ReadOnlySpan maximimumExtents, + ReadOnlySpan strides, + ReadOnlySpan data) + { + fixed (uint* pMinimumExtents = minimumExtents) + fixed (uint* pMaximumExtents = maximimumExtents) + fixed (uint* pStrides = strides) + fixed (byte* pData = data) + { + int dimensions = strides.Length + 1; + + // Same validation as in the Update instance method above + if (pMinimumExtents is not null && + pMaximumExtents is not null && + (minimumExtents.Length != dimensions || maximimumExtents.Length != dimensions)) + { + Marshal.ThrowExceptionForHR(E.E_INVALIDARG); + } + + int hresult = ((ID2D1ResourceTextureManager*)resourceTextureManager)->Update( + minimumExtents: pMinimumExtents, + maximimumExtents: pMaximumExtents, + strides: pStrides, + dimensions: (uint)dimensions, + data: pData, + dataCount: (uint)data.Length); + + Marshal.ThrowExceptionForHR(hresult); + } + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderCompiler.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderCompiler.cs index 8e3f9ae9..fdf1d322 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderCompiler.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ShaderCompiler.cs @@ -37,10 +37,13 @@ public static class D2D1ShaderCompiler int sourceWrittenBytes = Encoding.ASCII.GetBytes(hlslSource, sourceBuffer); // Encode the entry point to ASCII - int maxEntryPointLength = Encoding.ASCII.GetMaxByteCount(entryPoint.Length); + int maxEntryPointLength = Encoding.ASCII.GetMaxByteCount(entryPoint.Length) + 1; byte[] entryPointBuffer = ArrayPool.Shared.Rent(maxEntryPointLength); int entryPointWrittenBytes = Encoding.ASCII.GetBytes(entryPoint, entryPointBuffer); + // The entry point has to be null-terminated + entryPointBuffer[entryPointWrittenBytes] = (byte)'\0'; + ReadOnlySpan sourceAscii = sourceBuffer.AsSpan(0, sourceWrittenBytes); ReadOnlySpan entryPointAscii = entryPointBuffer.AsSpan(0, entryPointWrittenBytes); @@ -56,7 +59,7 @@ public static class D2D1ShaderCompiler /// Compiles a new HLSL shader from the input source code. /// /// The HLSL source code to compile (in ASCII). - /// The entry point of the shader being compiled (in ASCII). + /// The entry point of the shader being compiled (in ASCII, null-terminated). /// The shader profile to use to compile the shader. /// The compiler options to use to compile the shader. /// The bytecode for the compiled shader. diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs index 5098a14e..593091a6 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.For{T}.cs @@ -44,6 +44,11 @@ internal unsafe partial struct PixelShaderEffect /// private static Guid shaderId; + /// + /// The size of the constant buffer for the shader. + /// + private static int constantBufferSize; + /// /// The number of inputs for the shader. /// @@ -89,6 +94,16 @@ internal unsafe partial struct PixelShaderEffect /// private static D2D1ChannelDepth channelDepth; + /// + /// The number of available resource texture descriptions. + /// + private static int resourceTextureDescriptionCount; + + /// + /// The buffer with the available resource texture descriptions for the shader. + /// + private static D2D1ResourceTextureDescription* resourceTextureDescriptions; + /// /// The factory of instances to use for each created effect. /// @@ -119,9 +134,7 @@ internal unsafe partial struct PixelShaderEffect { // Load all shader properties Guid shaderId = typeof(T).GUID; - ReadOnlyMemory bytecodeInfo = D2D1PixelShader.LoadBytecode(); - int bytecodeSize = bytecodeInfo.Length; - byte* bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), bytecodeSize); + int constantBufferSize = D2D1PixelShader.GetConstantBufferSize(); D2D1BufferPrecision bufferPrecision = D2D1PixelShader.GetOutputBufferPrecision(); D2D1ChannelDepth channelDepth = D2D1PixelShader.GetOutputBufferChannelDepth(); D2D1PixelOptions pixelOptions = D2D1PixelShader.GetPixelOptions(); @@ -142,11 +155,23 @@ internal unsafe partial struct PixelShaderEffect inputDescriptionsInfo.Span.CopyTo(new Span(inputDescriptions, inputDescriptionCount)); + // Prepare the resource texture descriptions + ReadOnlyMemory resourceTextureDescriptionsInfo = D2D1PixelShader.GetResourceTextureDescriptions(); + int resourceTextureDescriptionCount = resourceTextureDescriptionsInfo.Length; + D2D1ResourceTextureDescription* resourceTextureDescriptions = (D2D1ResourceTextureDescription*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), sizeof(D2D1ResourceTextureDescription) * resourceTextureDescriptionCount); + + resourceTextureDescriptionsInfo.Span.CopyTo(new Span(resourceTextureDescriptions, resourceTextureDescriptionCount)); + // Copy the bytecode to the target buffer + ReadOnlyMemory bytecodeInfo = D2D1PixelShader.LoadBytecode(); + int bytecodeSize = bytecodeInfo.Length; + byte* bytecode = (byte*)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(For), bytecodeSize); + bytecodeInfo.Span.CopyTo(new Span(bytecode, bytecodeSize)); // Set the shared state and mark the type as initialized For.shaderId = shaderId; + For.constantBufferSize = constantBufferSize; For.inputCount = inputCount; For.inputTypes = inputTypes; For.inputDescriptionCount = inputDescriptionCount; @@ -156,6 +181,8 @@ internal unsafe partial struct PixelShaderEffect For.bytecodeSize = bytecodeSize; For.bufferPrecision = bufferPrecision; For.channelDepth = channelDepth; + For.resourceTextureDescriptionCount = resourceTextureDescriptionCount; + For.resourceTextureDescriptions = resourceTextureDescriptions; For.d2D1DrawTransformMapperFactory = d2D1DrawTransformMapperFactory; isInitialized = true; @@ -231,6 +258,7 @@ internal unsafe partial struct PixelShaderEffect return PixelShaderEffect.Factory( shaderId, + constantBufferSize, inputCount, inputTypes, inputDescriptionCount, @@ -240,6 +268,8 @@ internal unsafe partial struct PixelShaderEffect bytecodeSize, bufferPrecision, channelDepth, + resourceTextureDescriptionCount, + resourceTextureDescriptions, d2D1TransformMapper, effectImpl); } diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs index e3e3d1f3..0509e163 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ID2D1EffectImplMethods.cs @@ -1,6 +1,7 @@ using System; using System.Runtime.InteropServices; using ComputeSharp.D2D1.Extensions; +using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; #if !NET6_0_OR_GREATER @@ -128,11 +129,27 @@ internal unsafe partial struct PixelShaderEffect } } + // If loading the bytecode succeeded, set the transform node if (Windows.SUCCEEDED(hresult)) { hresult = transformGraph->SetSingleTransformNode((ID2D1TransformNode*)&@this->lpVtblForID2D1DrawTransform); } + // If the transform node was set, also store the effect context + if (Windows.SUCCEEDED(hresult)) + { + // Free the previous ID2D1EffectContext object, if present + if (@this->d2D1EffectContext is not null) + { + _ = @this->d2D1EffectContext->Release(); + } + + // Store the new ID2D1EffectContext object + _ = effectContext->AddRef(); + + @this->d2D1EffectContext = effectContext; + } + return hresult; } @@ -140,14 +157,72 @@ internal unsafe partial struct PixelShaderEffect [UnmanagedCallersOnly] public static int PrepareForRender(PixelShaderEffect* @this, D2D1_CHANGE_TYPE changeType) { + int hresult = S.S_OK; + + // Validate the constant buffer + if (@this->constantBufferSize > 0 && + @this->constantBuffer is null) + { + return E.E_NOT_VALID_STATE; + } + + // First, set the constant buffer, if available if (@this->constantBuffer is not null) { - return @this->d2D1DrawInfo->SetPixelShaderConstantBuffer( + hresult = @this->d2D1DrawInfo->SetPixelShaderConstantBuffer( buffer: @this->constantBuffer, bufferCount: (uint)@this->constantBufferSize); } - return S.S_OK; + if (Windows.SUCCEEDED(hresult)) + { + foreach (ref readonly D2D1ResourceTextureDescription resourceTextureDescription in new ReadOnlySpan(@this->resourceTextureDescriptions, @this->resourceTextureDescriptionCount)) + { + using ComPtr resourceTextureManager = @this->resourceTextureManagerBuffer[resourceTextureDescription.Index]; + + // If the current resource texture manager is not set, we cannot render, as there's an unbound resource texture + if (resourceTextureManager.Get() is null) + { + hresult = E.E_NOT_VALID_STATE; + + break; + } + + using ComPtr resourceTextureManagerInternal = default; + + // Get the ID2D1ResourceTextureManagerInternal object + hresult = resourceTextureManager.CopyTo(resourceTextureManagerInternal.GetAddressOf()); + + // This cast should always succeed, as when an input resource texture managers is set it's + // also checked for ID2D1ResourceTextureManagerInternal, but still validate for good measure. + if (!Windows.SUCCEEDED(hresult)) + { + break; + } + + using ComPtr d2D1ResourceTexture = default; + + // Try to get the ID2D1ResourceTexture from the manager + hresult = resourceTextureManagerInternal.Get()->GetResourceTexture(d2D1ResourceTexture.GetAddressOf()); + + if (!Windows.SUCCEEDED(hresult)) + { + break; + } + + // Set the ID2D1ResourceTexture object to the current index in the ID2D1DrawInfo object in use + hresult = @this->d2D1DrawInfo->SetResourceTexture( + textureIndex: (uint)resourceTextureDescription.Index, + resourceTexture: d2D1ResourceTexture.Get()); + + if (!Windows.SUCCEEDED(hresult)) + { + break; + } + } + } + + return hresult; } /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs new file mode 100644 index 00000000..856bb492 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.cs @@ -0,0 +1,279 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +unsafe partial struct PixelShaderEffect +{ +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int PropertyGetFunctionDelegate(IUnknown* effect, byte* data, uint dataSize, uint* actualSize); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int PropertySetFunctionDelegate(IUnknown* effect, byte* data, uint dataSize); + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetConstantBufferWrapper = GetConstantBufferImpl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetConstantBufferWrapper = SetConstantBufferImpl; +#endif + + /// + /// Gets the get accessor for the constant buffer. + /// + public static delegate* unmanaged[Stdcall] GetConstantBuffer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetConstantBufferImpl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetConstantBufferWrapper); +#endif + } + } + + /// + /// Gets the set accessor for the constant buffer. + /// + public static delegate* unmanaged[Stdcall] SetConstantBuffer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetConstantBufferImpl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetConstantBufferWrapper); +#endif + } + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetConstantBufferImpl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + PixelShaderEffect* @this = (PixelShaderEffect*)effect; + + // This is a call likely from ID2D1Effect::GetValueSize, to query the property size + if (data is null && + dataSize == 0 && + actualSize is not null) + { + *actualSize = (uint)@this->constantBufferSize; + + return S.S_FALSE; + } + + if (data is null) + { + return E.E_POINTER; + } + + if (dataSize < @this->constantBufferSize) + { + return E.E_NOT_SUFFICIENT_BUFFER; + } + + if (@this->constantBuffer is null) + { + return E.E_NOT_VALID_STATE; + } + + uint writtenBytes = 0; + + if (@this->constantBufferSize > 0) + { + Buffer.MemoryCopy(@this->constantBuffer, data, dataSize, @this->constantBufferSize); + + writtenBytes = (uint)@this->constantBufferSize; + } + + if (actualSize is not null) + { + *actualSize = writtenBytes; + } + + return S.S_OK; + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetConstantBufferImpl(IUnknown* effect, byte* data, uint dataSize) + { + if (data is null) + { + return E.E_POINTER; + } + + PixelShaderEffect* @this = (PixelShaderEffect*)effect; + + if (dataSize != (uint)@this->constantBufferSize) + { + return E.E_INVALIDARG; + } + + if (@this->constantBuffer is not null) + { + NativeMemory.Free(@this->constantBuffer); + } + + void* buffer = NativeMemory.Alloc(dataSize); + + Buffer.MemoryCopy(data, buffer, dataSize, dataSize); + + @this->constantBuffer = (byte*)buffer; + + return S.S_OK; + } + + /// + /// Gets the resource texture manager for a given index. + /// + /// The index of the resource texture to get the manager for. + /// A pointer to a variable that stores the data that this function retrieves on the property. + /// The number of bytes in the property to retrieve. + /// A optional pointer to a variable that stores the actual number of bytes retrieved on the property. + /// The for the operation. + private int GetResourceTextureManagerAtIndex(int resourceTextureIndex, byte* data, uint dataSize, uint* actualSize) + { + if (!IsResourceTextureManagerIndexValid(resourceTextureIndex, out _)) + { + return E.E_INVALIDARG; + } + + if (data is null) + { + return E.E_POINTER; + } + + if (dataSize < sizeof(void*)) + { + return E.E_INVALIDARG; + } + + using ComPtr resourceTextureManager = this.resourceTextureManagerBuffer[resourceTextureIndex]; + + resourceTextureManager.CopyTo((ID2D1ResourceTextureManager**)data); + + if (actualSize is not null) + { + *actualSize = (uint)sizeof(void*); + } + + return S.S_OK; + } + + /// + /// Sets the resource texture manager for a given index. + /// + /// The index of the resource texture to set the manager for. + /// A pointer to the data to be set on the property. + /// The number of bytes in the property set by the function. + /// The for the operation. + private int SetResourceTextureManagerAtIndex(int resourceTextureIndex, byte* data, uint dataSize) + { + if (!IsResourceTextureManagerIndexValid(resourceTextureIndex, out uint dimensions)) + { + return E.E_INVALIDARG; + } + + if (data is null) + { + return E.E_POINTER; + } + + void* value = *(void**)data; + + if (value is null) + { + return E.E_POINTER; + } + + if (dataSize != (uint)sizeof(void*)) + { + return E.E_INVALIDARG; + } + + using ComPtr unknown = (IUnknown*)value; + using ComPtr resourceTextureManager = default; + + // Check that the input object implements ID2D1ResourceTextureManager + int result = unknown.CopyTo(resourceTextureManager.GetAddressOf()); + + if (result != S.S_OK) + { + return result; + } + + using ComPtr resourceTextureManagerInternal = default; + + // Then, also check that it implements ID2D1ResourceTextureManagerInternal + result = unknown.CopyTo(resourceTextureManagerInternal.GetAddressOf()); + + if (result != S.S_OK) + { + return result; + } + + // Initialize the resource texture manager, if an effect context is available + if (this.d2D1EffectContext is not null) + { + result = resourceTextureManagerInternal.Get()->Initialize(this.d2D1EffectContext, &dimensions); + + // ID2D1ResourceTextureManager::Initialize should generally return either S_OK for first + // initialization, S_FALSE if an ID2D1EffectContext is already present (which is allowed, to + // enable sharing resource texture managers across different source textures and effects), or + // E_INVALIDARG if the manager has already been initialized through the public interface, + // and the stored dimensions for that don't match the ones for this resource texture index. + if (!Windows.SUCCEEDED(result)) + { + return result; + } + } + + // Store the resource texture manager into the buffer + this.resourceTextureManagerBuffer[resourceTextureIndex] = resourceTextureManager.Detach(); + + return S.S_OK; + } + + /// + /// Checks whether a given index for a resource texture manager is valid for the current effect. + /// + /// The index of the resource texture to validate. + /// The number of dimensions for the resource texture at the gven index. + /// Whether or not is valid for the current effect. + private bool IsResourceTextureManagerIndexValid(int resourceTextureIndex, out uint dimensions) + { + foreach (ref readonly D2D1ResourceTextureDescription resourceTextureDescription in new ReadOnlySpan(this.resourceTextureDescriptions, this.resourceTextureDescriptionCount)) + { + if (resourceTextureDescription.Index == resourceTextureIndex) + { + dimensions = (uint)resourceTextureDescription.Dimensions; + + return true; + } + } + + dimensions = 0; + + return false; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.g.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.g.cs new file mode 100644 index 00000000..320d425d --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.g.cs @@ -0,0 +1,898 @@ +using System.Runtime.CompilerServices; +#if !NET6_OR_GREATER +using System.Runtime.InteropServices; +#endif +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +unsafe partial struct PixelShaderEffect +{ +#if !NET6_0_OR_GREATER + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager0Wrapper = GetResourceTextureManager0Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager0Wrapper = SetResourceTextureManager0Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager1Wrapper = GetResourceTextureManager1Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager1Wrapper = SetResourceTextureManager1Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager2Wrapper = GetResourceTextureManager2Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager2Wrapper = SetResourceTextureManager2Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager3Wrapper = GetResourceTextureManager3Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager3Wrapper = SetResourceTextureManager3Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager4Wrapper = GetResourceTextureManager4Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager4Wrapper = SetResourceTextureManager4Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager5Wrapper = GetResourceTextureManager5Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager5Wrapper = SetResourceTextureManager5Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager6Wrapper = GetResourceTextureManager6Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager6Wrapper = SetResourceTextureManager6Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager7Wrapper = GetResourceTextureManager7Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager7Wrapper = SetResourceTextureManager7Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager8Wrapper = GetResourceTextureManager8Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager8Wrapper = SetResourceTextureManager8Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager9Wrapper = GetResourceTextureManager9Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager9Wrapper = SetResourceTextureManager9Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager10Wrapper = GetResourceTextureManager10Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager10Wrapper = SetResourceTextureManager10Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager11Wrapper = GetResourceTextureManager11Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager11Wrapper = SetResourceTextureManager11Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager12Wrapper = GetResourceTextureManager12Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager12Wrapper = SetResourceTextureManager12Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager13Wrapper = GetResourceTextureManager13Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager13Wrapper = SetResourceTextureManager13Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager14Wrapper = GetResourceTextureManager14Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager14Wrapper = SetResourceTextureManager14Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager15Wrapper = GetResourceTextureManager15Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager15Wrapper = SetResourceTextureManager15Impl; +#endif + + /// + /// Gets the get accessor for the resource manager at index 0. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager0 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager0Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager0Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 0. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager0 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager0Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager0Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 1. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager1 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager1Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager1Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 1. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager1 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager1Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager1Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 2. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager2Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager2Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 2. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager2Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager2Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 3. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager3Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager3Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 3. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager3Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager3Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 4. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager4Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager4Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 4. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager4Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager4Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 5. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager5Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager5Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 5. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager5Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager5Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 6. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager6 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager6Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager6Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 6. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager6 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager6Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager6Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 7. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager7 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager7Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager7Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 7. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager7 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager7Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager7Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 8. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager8 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager8Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager8Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 8. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager8 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager8Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager8Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 9. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager9 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager9Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager9Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 9. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager9 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager9Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager9Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 10. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager10 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager10Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager10Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 10. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager10 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager10Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager10Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 11. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager11 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager11Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager11Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 11. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager11 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager11Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager11Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 12. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager12 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager12Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager12Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 12. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager12 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager12Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager12Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 13. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager13 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager13Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager13Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 13. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager13 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager13Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager13Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 14. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager14 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager14Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager14Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 14. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager14 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager14Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager14Wrapper); +#endif + } + } + + /// + /// Gets the get accessor for the resource manager at index 15. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager15 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager15Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager15Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index 15. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager15 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager15Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager15Wrapper); +#endif + } + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager0Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(0, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager0Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(0, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager1Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(1, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager1Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(1, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager2Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(2, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager2Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(2, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager3Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(3, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager3Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(3, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager4Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(4, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager4Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(4, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager5Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(5, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager5Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(5, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager6Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(6, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager6Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(6, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager7Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(7, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager7Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(7, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager8Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(8, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager8Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(8, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager9Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(9, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager9Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(9, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager10Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(10, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager10Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(10, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager11Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(11, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager11Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(11, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager12Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(12, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager12Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(12, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager13Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(13, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager13Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(13, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager14Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(14, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager14Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(14, data, dataSize); + } + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager15Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(15, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager15Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(15, data, dataSize); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.tt b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.tt new file mode 100644 index 00000000..87261660 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.Properties.tt @@ -0,0 +1,98 @@ +<#@ template debug="false" hostspecific="false" language="C#" #> +<#@ assembly name="System.Core" #> +<#@ output extension=".g.cs"#> +using System.Runtime.CompilerServices; +#if !NET6_OR_GREATER +using System.Runtime.InteropServices; +#endif +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +unsafe partial struct PixelShaderEffect +{ +#if !NET6_0_OR_GREATER +<# +for (int i = 0; i < 16; i++) +{ +#> + /// + /// A cached instance wrapping . + /// + private static readonly PropertyGetFunctionDelegate GetResourceTextureManager<#=i#>Wrapper = GetResourceTextureManager<#=i#>Impl; + + /// + /// A cached instance wrapping . + /// + private static readonly PropertySetFunctionDelegate SetResourceTextureManager<#=i#>Wrapper = SetResourceTextureManager<#=i#>Impl; +<# + if (i < 15) WriteLine(""); +} +#> +#endif + +<# +for (int i = 0; i < 16; i++) +{ +#> + /// + /// Gets the get accessor for the resource manager at index <#=i#>. + /// + public static delegate* unmanaged[Stdcall] GetResourceTextureManager<#=i#> + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &GetResourceTextureManager<#=i#>Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(GetResourceTextureManager<#=i#>Wrapper); +#endif + } + } + + /// + /// Gets the set accessor for the resource manager at index <#=i#>. + /// + public static delegate* unmanaged[Stdcall] SetResourceTextureManager<#=i#> + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { +#if NET6_0_OR_GREATER + return &SetResourceTextureManager<#=i#>Impl; +#else + return (delegate* unmanaged[Stdcall])(void*)Marshal.GetFunctionPointerForDelegate(SetResourceTextureManager<#=i#>Wrapper); +#endif + } + } + +<# +} +#> +<# +for (int i = 0; i < 16; i++) +{ +#> + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int GetResourceTextureManager<#=i#>Impl(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) + { + return ((PixelShaderEffect*)effect)->GetResourceTextureManagerAtIndex(<#=i#>, data, dataSize, actualSize); + } + + /// + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int SetResourceTextureManager<#=i#>Impl(IUnknown* effect, byte* data, uint dataSize) + { + return ((PixelShaderEffect*)effect)->SetResourceTextureManagerAtIndex(<#=i#>, data, dataSize); + } +<# +} +#> +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ResourceTextureManagerBuffer.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ResourceTextureManagerBuffer.cs new file mode 100644 index 00000000..6d11ba20 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.ResourceTextureManagerBuffer.cs @@ -0,0 +1,123 @@ +using System; +using System.Runtime.CompilerServices; +using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; + +#pragma warning disable CS0649 + +namespace ComputeSharp.D2D1.Interop.Effects; + +/// +partial struct PixelShaderEffect +{ + /// + /// A buffer of 16 objects. + /// + private unsafe struct ResourceTextureManagerBuffer + { + /// + /// The pointer to the instance at index 0. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager0; + + /// + /// The pointer to the instance at index 1. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager1; + + /// + /// The pointer to the instance at index 2. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager2; + + /// + /// The pointer to the instance at index 3. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager3; + + /// + /// The pointer to the instance at index 4. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager4; + + /// + /// The pointer to the instance at index 5. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager5; + + /// + /// The pointer to the instance at index 6. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager6; + + /// + /// The pointer to the instance at index 7. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager7; + + /// + /// The pointer to the instance at index 8. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager8; + + /// + /// The pointer to the instance at index 9. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager9; + + /// + /// The pointer to the instance at index 10. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager10; + + /// + /// The pointer to the instance at index 11. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager11; + + /// + /// The pointer to the instance at index 12. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager12; + + /// + /// The pointer to the instance at index 13. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager13; + + /// + /// The pointer to the instance at index 14. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager14; + + /// + /// The pointer to the instance at index 15. + /// + public ID2D1ResourceTextureManager* ResourceTextureManager15; + + /// + /// Gets a to the pointer at a given index. + /// + /// The index of the instance to retrieve. + /// A to the pointer at a given index. + public ref ID2D1ResourceTextureManager* this[int index] + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + ID2D1ResourceTextureManager** @this = (ID2D1ResourceTextureManager**)Unsafe.AsPointer(ref this); + + return ref @this[index]; + } + } + + /// + /// Gets a with the items in the current instance. + /// + /// A with the items in the current instance. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Span AsSpan() + { + return new((ID2D1ResourceTextureManager**)Unsafe.AsPointer(ref this), 16); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs index fb99a9e7..249f0544 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/PixelShaderEffect.cs @@ -2,13 +2,13 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; +using ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; #if NET6_0_OR_GREATER using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; #else using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; -using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; #endif namespace ComputeSharp.D2D1.Interop.Effects; @@ -38,24 +38,6 @@ internal unsafe partial struct PixelShaderEffect /// [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint ReleaseDelegate(PixelShaderEffect* @this); - - /// - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - public delegate int GetConstantBufferDelegate(IUnknown* effect, byte* data, uint dataSize, uint* actualSize); - - /// - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - public delegate int SetConstantBufferDelegate(IUnknown* effect, byte* data, uint dataSize); - - /// - /// A cached instance wrapping . - /// - public static readonly GetConstantBufferDelegate GetConstantBufferWrapper = GetConstantBuffer; - - /// - /// A cached instance wrapping . - /// - public static readonly SetConstantBufferDelegate SetConstantBufferWrapper = SetConstantBuffer; #endif /// @@ -132,21 +114,21 @@ internal unsafe partial struct PixelShaderEffect /// private volatile int referenceCount; + /// + /// The for the shader. + /// + private Guid shaderId; + /// /// The constant buffer data, if set. /// private byte* constantBuffer; /// - /// The size of , if set. + /// The size of . /// private int constantBufferSize; - /// - /// The for the shader. - /// - private Guid shaderId; - /// /// The number of inputs for the shader. /// @@ -200,6 +182,19 @@ internal unsafe partial struct PixelShaderEffect /// private D2D1ChannelDepth channelDepth; + /// + /// The number of available resource texture descriptions. + /// + private int resourceTextureDescriptionCount; + + /// + /// The buffer with the available resource texture descriptions for the shader. + /// + /// + /// This buffer is also shared among effect instances, like . + /// + private D2D1ResourceTextureDescription* resourceTextureDescriptions; + /// /// The handle for the instance in use, if any. /// @@ -210,10 +205,21 @@ internal unsafe partial struct PixelShaderEffect /// private ID2D1DrawInfo* d2D1DrawInfo; + /// + /// The instance currently in use. + /// + private ID2D1EffectContext* d2D1EffectContext; + + /// + /// The resource texture managers for the current instance. + /// + private ResourceTextureManagerBuffer resourceTextureManagerBuffer; + /// /// The factory method for . /// /// The for the shader. + /// The size of the constant buffer for the shader. /// The number of inputs for the shader. /// The buffer with the types of inputs for the shader. /// The number of available input descriptions. @@ -223,11 +229,14 @@ internal unsafe partial struct PixelShaderEffect /// The size of . /// The buffer precision for the resulting output buffer. /// The channel depth for the resulting output buffer. + /// The number of available resource texture descriptions. + /// The buffer with the available resource texture descriptions for the shader. /// The instance to use for the effect. /// The resulting effect instance. /// This always returns 0. private static int Factory( Guid shaderId, + int constantBufferSize, int inputCount, D2D1PixelShaderInputType* inputTypes, int inputDescriptionCount, @@ -237,6 +246,8 @@ internal unsafe partial struct PixelShaderEffect int bytecodeSize, D2D1BufferPrecision bufferPrecision, D2D1ChannelDepth channelDepth, + int resourceTextureDescriptionCount, + D2D1ResourceTextureDescription* resourceTextureDescriptions, D2D1TransformMapper? d2D1TransformMapper, IUnknown** effectImpl) { @@ -259,6 +270,8 @@ internal unsafe partial struct PixelShaderEffect @this->lpVtblForID2D1DrawTransform = VtblForID2D1DrawTransform; @this->referenceCount = 1; @this->shaderId = shaderId; + @this->constantBuffer = null; + @this->constantBufferSize = constantBufferSize; @this->inputCount = inputCount; @this->inputTypes = inputTypes; @this->inputDescriptionCount = inputDescriptionCount; @@ -268,56 +281,19 @@ internal unsafe partial struct PixelShaderEffect @this->bytecodeSize = bytecodeSize; @this->bufferPrecision = bufferPrecision; @this->channelDepth = channelDepth; + @this->resourceTextureDescriptionCount = resourceTextureDescriptionCount; + @this->resourceTextureDescriptions = resourceTextureDescriptions; @this->d2D1TransformMapperHandle = GCHandle.Alloc(d2D1TransformMapper); + @this->d2D1DrawInfo = null; + @this->d2D1EffectContext = null; + + @this->resourceTextureManagerBuffer.AsSpan().Clear(); *effectImpl = (IUnknown*)@this; return S.S_OK; } - /// - [UnmanagedCallersOnly] - public static int GetConstantBuffer(IUnknown* effect, byte* data, uint dataSize, uint* actualSize) - { - PixelShaderEffect* @this = (PixelShaderEffect*)effect; - - if (@this->constantBufferSize == 0) - { - *actualSize = 0; - } - else - { - int bytesToCopy = Math.Min((int)dataSize, @this->constantBufferSize); - - Buffer.MemoryCopy(@this->constantBuffer, data, dataSize, bytesToCopy); - - *actualSize = (uint)bytesToCopy; - } - - return S.S_OK; - } - - /// - [UnmanagedCallersOnly] - public static int SetConstantBuffer(IUnknown* effect, byte* data, uint dataSize) - { - PixelShaderEffect* @this = (PixelShaderEffect*)effect; - - if (@this->constantBuffer is not null) - { - NativeMemory.Free(@this->constantBuffer); - } - - void* buffer = NativeMemory.Alloc(dataSize); - - Buffer.MemoryCopy(data, buffer, dataSize, dataSize); - - @this->constantBuffer = (byte*)buffer; - @this->constantBufferSize = (int)dataSize; - - return S.S_OK; - } - /// private int QueryInterface(Guid* riid, void** ppvObject) { @@ -379,6 +355,23 @@ internal unsafe partial struct PixelShaderEffect _ = this.d2D1DrawInfo->Release(); } + if (this.d2D1EffectContext is not null) + { + _ = this.d2D1EffectContext->Release(); + } + + // Use the list of resource texture descriptions to see the indices that might have accepted a resource texture manager. + // Then, retrieve all of them and release the ones that had been assigned (from one of the property bindings). + foreach (ref readonly D2D1ResourceTextureDescription resourceTextureDescription in new ReadOnlySpan(this.resourceTextureDescriptions, this.resourceTextureDescriptionCount)) + { + ID2D1ResourceTextureManager* resourceTextureManager = resourceTextureManagerBuffer[resourceTextureDescription.Index]; + + if (resourceTextureManager is not null) + { + _ = ((IUnknown*)resourceTextureManager)->Release(); + } + } + NativeMemory.Free(Unsafe.AsPointer(ref this)); } diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs new file mode 100644 index 00000000..89fc5479 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManager.cs @@ -0,0 +1,688 @@ +using System; +using System.Runtime.InteropServices; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; + +/// +unsafe partial struct D2D1ResourceTextureManagerImpl +{ + /// + public static int Initialize( + D2D1ResourceTextureManagerImpl* @this, + Guid* resourceId, + D2D1_RESOURCE_TEXTURE_PROPERTIES* resourceTextureProperties, + byte* data, + uint* strides, + uint dataSize) + { + lock (@this->lockHandle.Target!) + { + // If the method has already been called, fail + if (@this->d2D1ResourceTexture is not null || + @this->data is not null) + { + return E.E_NOT_VALID_STATE; + } + + // If the manager has been assigned to an effect and the dimensions are available, validate them. + // Check and ignore if the input properties are null (validation for that is done afterwards). + if (@this->expectedDimensions != 0 && + resourceTextureProperties is not null && + resourceTextureProperties->dimensions != @this->expectedDimensions) + { + return E.E_INVALIDARG; + } + + // If the method has already been called, just forward the call + if (@this->d2D1EffectContext is not null) + { + @this->d2D1Multithread->Enter(); + + // Create the resource after taking a D2D lock + int hresult = @this->d2D1EffectContext->CreateResourceTexture( + resourceId: resourceId, + resourceTextureProperties: resourceTextureProperties, + data: data, + strides: strides, + dataSize: dataSize, + resourceTexture: &@this->d2D1ResourceTexture); + + @this->d2D1Multithread->Leave(); + + return hresult; + } + + // Initialize into a staging buffer + return ID2D1ResourceTextureManagerMethods.InitializeWithStagingBuffer( + @this: @this, + resourceId: resourceId, + resourceTextureProperties: resourceTextureProperties, + data: data, + strides: strides, + dataSize: dataSize); + } + } + + /// + public static int Update( + D2D1ResourceTextureManagerImpl* @this, + uint* minimumExtents, + uint* maximimumExtents, + uint* strides, + uint dimensions, + byte* data, + uint dataCount) + { + lock (@this->lockHandle.Target!) + { + if (@this->d2D1ResourceTexture is null && + @this->data is null) + { + return E.E_NOT_VALID_STATE; + } + + // If a resource texture already exists, just forward the call + if (@this->d2D1ResourceTexture is not null) + { + @this->d2D1Multithread->Enter(); + + // Take a D2D lock here too to ensure thread safety + int hresult = @this->d2D1ResourceTexture->Update( + minimumExtents: minimumExtents, + maximimumExtents: maximimumExtents, + strides: strides, + dimensions: dimensions, + data: data, + dataCount: dataCount); + + @this->d2D1Multithread->Leave(); + + return hresult; + } + + // Otherwise update the staging buffer + return ID2D1ResourceTextureManagerMethods.UpdateWithStagingBuffer( + @this: @this, + minimumExtents: minimumExtents, + maximimumExtents: maximimumExtents, + strides: strides, + dimensions: dimensions, + data: data, + dataCount: dataCount); + } + } + + /// + /// The implementation for ID2D1ResourceTextureManager. + /// + private static class ID2D1ResourceTextureManagerMethods + { +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int InitializeDelegate( + D2D1ResourceTextureManagerImpl* @this, + Guid* resourceId, + D2D1_RESOURCE_TEXTURE_PROPERTIES* resourceTextureProperties, + byte* data, + uint* strides, + uint dataSize); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int UpdateDelegate( + D2D1ResourceTextureManagerImpl* @this, + uint* minimumExtents, + uint* maximimumExtents, + uint* strides, + uint dimensions, + byte* data, + uint dataCount); + + /// + /// A cached instance wrapping . + /// + public static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface; + + /// + /// A cached instance wrapping . + /// + public static readonly AddRefDelegate AddRefWrapper = AddRef; + + /// + /// A cached instance wrapping . + /// + public static readonly ReleaseDelegate ReleaseWrapper = Release; + + /// + /// A cached instance wrapping . + /// + public static readonly InitializeDelegate InitializeWrapper = Initialize; + + /// + /// A cached instance wrapping . + /// + public static readonly UpdateDelegate UpdateWrapper = Update; +#endif + + /// + [UnmanagedCallersOnly] + public static int QueryInterface(D2D1ResourceTextureManagerImpl* @this, Guid* riid, void** ppvObject) + { + return @this->QueryInterface(riid, ppvObject); + } + + /// + [UnmanagedCallersOnly] + public static uint AddRef(D2D1ResourceTextureManagerImpl* @this) + { + return @this->AddRef(); + } + + /// + [UnmanagedCallersOnly] + public static uint Release(D2D1ResourceTextureManagerImpl* @this) + { + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + public static int Initialize( + D2D1ResourceTextureManagerImpl* @this, + Guid* resourceId, + D2D1_RESOURCE_TEXTURE_PROPERTIES* resourceTextureProperties, + byte* data, + uint* strides, + uint dataSize) + { + return D2D1ResourceTextureManagerImpl.Initialize( + @this, + resourceId, + resourceTextureProperties, + data, + strides, + dataSize); + } + + /// + [UnmanagedCallersOnly] + public static int Update( + D2D1ResourceTextureManagerImpl* @this, + uint* minimumExtents, + uint* maximimumExtents, + uint* strides, + uint dimensions, + byte* data, + uint dataCount) + { + return D2D1ResourceTextureManagerImpl.Update( + @this, + minimumExtents, + maximimumExtents, + strides, + dimensions, + data, + dataCount); + } + + /// + public static int InitializeWithStagingBuffer( + D2D1ResourceTextureManagerImpl* @this, + Guid* resourceId, + D2D1_RESOURCE_TEXTURE_PROPERTIES* resourceTextureProperties, + byte* data, + uint* strides, + uint dataSize) + { + // Return E_POINTER if any input pointer is null. In particular, the data pointer + // must not be null if the data size is not 0, and the strides pointer must not be + // null if some data is supplied, and the number of dimensions is greater than 1. + if (resourceTextureProperties is null || + (dataSize > 0 && data is null) || + resourceTextureProperties->extents is null || + resourceTextureProperties->extendModes is null || + (resourceTextureProperties->dimensions > 1 && dataSize > 0 && strides is null)) + { + return E.E_POINTER; + } + + // Textures can only have between 1 and 3 dimensions + if (resourceTextureProperties->dimensions is 0 or > 3) + { + return E.E_INVALIDARG; + } + + // No extent can be 0 + foreach (uint extent in new ReadOnlySpan(resourceTextureProperties->extents, (int)resourceTextureProperties->dimensions)) + { + if (extent == 0) + { + return E.E_INVALIDARG; + } + } + + // The buffer precision can't be unknown, and the channel depth must be explicit + if (resourceTextureProperties->bufferPrecision == D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_UNKNOWN || + resourceTextureProperties->channelDepth == D2D1_CHANNEL_DEPTH.D2D1_CHANNEL_DEPTH_DEFAULT) + { + return E.E_INVALIDARG; + } + + // Validate the data size + if (dataSize > 0) + { + uint elementSizeInBytes = GetElementSizeInBytes( + resourceTextureProperties->bufferPrecision, + resourceTextureProperties->channelDepth); + + int hresult = ValidateDataAndStrides( + elementSizeInBytes, + resourceTextureProperties->extents, + resourceTextureProperties->dimensions, + strides, + dataSize); + + if (hresult != S.S_OK) + { + return hresult; + } + } + + // Allocate a buffer for the resource id, if there is one + if (resourceId is not null) + { + try + { + @this->resourceId = (Guid*)NativeMemory.Alloc((nuint)sizeof(Guid)); + } + catch (OutOfMemoryException) + { + return E.E_OUTOFMEMORY; + } + + *@this->resourceId = *resourceId; + } + + uint* extents; + + // Allocate a buffer for the extents (one per dimension) + try + { + extents = (uint*)NativeMemory.Alloc(sizeof(uint) * resourceTextureProperties->dimensions); + } + catch (OutOfMemoryException) + { + return E.E_OUTOFMEMORY; + } + + D2D1_EXTEND_MODE* extendModes; + + // Allocate a buffer for the extend modes (one per dimension) + try + { + extendModes = (D2D1_EXTEND_MODE*)NativeMemory.Alloc(sizeof(D2D1_EXTEND_MODE) * resourceTextureProperties->dimensions); + } + catch (OutOfMemoryException) + { + return E.E_OUTOFMEMORY; + } + + // Copy the extents into the buffer + Buffer.MemoryCopy( + source: resourceTextureProperties->extents, + destination: extents, + destinationSizeInBytes: sizeof(uint) * resourceTextureProperties->dimensions, + sourceBytesToCopy: sizeof(uint) * resourceTextureProperties->dimensions); + + // Copy the extend modes into the buffer + Buffer.MemoryCopy( + source: resourceTextureProperties->extendModes, + destination: extendModes, + destinationSizeInBytes: sizeof(D2D1_EXTEND_MODE) * resourceTextureProperties->dimensions, + sourceBytesToCopy: sizeof(D2D1_EXTEND_MODE) * resourceTextureProperties->dimensions); + + // Initialize the other resource texture properties + @this->resourceTextureProperties.extents = extents; + @this->resourceTextureProperties.dimensions = resourceTextureProperties->dimensions; + @this->resourceTextureProperties.bufferPrecision = resourceTextureProperties->bufferPrecision; + @this->resourceTextureProperties.channelDepth = resourceTextureProperties->channelDepth; + @this->resourceTextureProperties.filter = resourceTextureProperties->filter; + @this->resourceTextureProperties.extendModes = extendModes; + + // Initialize the staging buffer and optional strides + return InitializeStagingBufferAndStrides( + @this: @this, + dimensions: resourceTextureProperties->dimensions, + data: data, + strides: strides, + dataSize: dataSize); + } + + /// + public static int UpdateWithStagingBuffer( + D2D1ResourceTextureManagerImpl* @this, + uint* minimumExtents, + uint* maximimumExtents, + uint* strides, + uint dimensions, + byte* data, + uint dataCount) + { + // Either both extents are available, or none is, and the other values must not be null + if (minimumExtents is null && maximimumExtents is not null || + minimumExtents is not null && maximimumExtents is null || + (dimensions > 1 && strides is null) || + data is null) + { + return E.E_POINTER; + } + + // The dimensions must match the currently stored texture data + if (dimensions != @this->resourceTextureProperties.dimensions) + { + return E.E_INVALIDARG; + } + + // If the update extents are specified, check that the targets are all greater than the starting extents. + if (minimumExtents is not null) + { + for (int i = 0; i < (int)dimensions; i++) + { + if (maximimumExtents[i] <= minimumExtents[i]) + { + return E.E_INVALIDARG; + } + } + } + + uint elementSizeInBytes = GetElementSizeInBytes( + @this->resourceTextureProperties.bufferPrecision, + @this->resourceTextureProperties.channelDepth); + + // Calculate the extents of the buffer, based on the delta between the input extents. + // If no extents range is provided, it means that the entire resource texture is updated. + uint* updateExtents = stackalloc uint[3]; + + if (minimumExtents is not null) + { + updateExtents[0] = maximimumExtents[0] - minimumExtents[0]; + updateExtents[1] = dimensions > 1 ? (maximimumExtents[1] - minimumExtents[1]) : 1; + updateExtents[2] = dimensions > 2 ? (maximimumExtents[2] - minimumExtents[2]) : 1; + + // Validate that the requested extent is not greater than the corresponding dimension + for (int i = 0; i < (int)dimensions; i++) + { + if (updateExtents[i] > @this->resourceTextureProperties.extents[i]) + { + return E.E_INVALIDARG; + } + } + } + else + { + Buffer.MemoryCopy( + source: @this->resourceTextureProperties.extents, + destination: updateExtents, + destinationSizeInBytes: dimensions * sizeof(uint), + sourceBytesToCopy: dimensions * sizeof(uint)); + } + + // Validate that the provided buffer is valid for the update range + int hresult = ValidateDataAndStrides( + elementSizeInBytes, + updateExtents, + dimensions, + strides, + dataCount); + + if (hresult != S.S_OK) + { + return hresult; + } + + // If the texture hasn't been allocated yet, do that now. This is only + // valid if the whole texture is being updated (as it's being initialized). + if (@this->data is null) + { + if (minimumExtents is not null) + { + // If explicit extents are passed, they must match the resource texture size + for (int i = 0; i < (int)dimensions; i++) + { + if (updateExtents[i] != @this->resourceTextureProperties.extents[i]) + { + return E.E_INVALIDARG; + } + } + } + + // This is a full update with no existing resource, so just initialize the buffer from scratch + return InitializeStagingBufferAndStrides( + @this: @this, + dimensions: dimensions, + data: data, + strides: strides, + dataSize: dataCount); + } + + // Precalculate the byte size of each row update + uint rowUpdateSizeInBytes = updateExtents[0] * elementSizeInBytes; + + for (int z = 0; z < updateExtents[2]; z++) + { + // Calculate the starting position in the source and destination buffers. + // - The source advances by the 2D slice stride for each iteration. + // - The destination does the same, but it also starts at the given initial offset. + // This pointer is aligned to the start of a row in the offset 2D plane after this. + byte* sourceDataPlane = + data + + (dimensions > 2 ? z * strides[1] : 0); + byte* destinationDataPlane = + @this->data + + (dimensions > 2 ? minimumExtents[2] * @this->strides[1] + z * @this->strides[1] : 0) + + (dimensions > 1 ? minimumExtents[1] * @this->strides[0] : 0); + + for (int y = 0; y < updateExtents[1]; y++) + { + // Shift the source ahead to get to the start of the current row. The destination + // is also shifted ahead by the current row, plus the target initial element offset. + byte* sourceDataRow = sourceDataPlane + (dimensions > 1 ? y * strides[0] : 0); + byte* destinationDataRow = + destinationDataPlane + + (dimensions > 1 ? y * @this->strides[0] : 0) + + (minimumExtents[0] * elementSizeInBytes); + + Buffer.MemoryCopy( + source: sourceDataRow, + destination: destinationDataRow, + destinationSizeInBytes: rowUpdateSizeInBytes, + sourceBytesToCopy: rowUpdateSizeInBytes); + } + } + + return S.S_OK; + } + + /// + /// Gets the element size of each item in the resource texture, in bytes. + /// + /// The precision of the resource texture. + /// The number of channels in the resource texture. + /// Tthe element size of each item in the resource texture, in bytes. + private static uint GetElementSizeInBytes(D2D1_BUFFER_PRECISION bufferPrecision, D2D1_CHANNEL_DEPTH channelDepth) + { + uint channelSizeInBytes = bufferPrecision switch + { + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM => 1, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB => 1, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_UNORM => 2, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_16BPC_FLOAT => 2, + D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT => 4, + _ => 0 + }; + + return channelDepth switch + { + D2D1_CHANNEL_DEPTH.D2D1_CHANNEL_DEPTH_1 => channelSizeInBytes, + D2D1_CHANNEL_DEPTH.D2D1_CHANNEL_DEPTH_4 => channelSizeInBytes * 4, + _ => 0 + }; + } + + /// + /// Validates the data and strides for a call to or . + /// + /// The element size in bytes. + /// The extents of the resource table in each dimension. + /// The number of dimensions in the resource texture. + /// The stride to advance through the input data, according to dimension. + /// The size of the data buffer to be used to update the resource texture. + /// The for the validation. + private static int ValidateDataAndStrides( + uint elementSizeInBytes, + uint* extents, + uint dimensions, + uint* strides, + uint dataSize) + { + uint extent0SizeInBytes; + + try + { + extent0SizeInBytes = checked(extents[0] * elementSizeInBytes); + } + catch (OverflowException) + { + return E.E_INVALIDARG; + } + + // For 1D textures, the row byte size must match the data size (no strides to consider) + if (dimensions == 1) + { + if (extent0SizeInBytes != dataSize) + { + return E.E_NOT_SUFFICIENT_BUFFER; + } + } + else + { + // Validate the 0th stride is not smaller than the byte size of each row + if (extent0SizeInBytes > strides[0]) + { + return E.E_INVALIDARG; + } + + uint extent01SizeInBytes; + + try + { + extent01SizeInBytes = checked((extents[1] - 1) * strides[0] + extent0SizeInBytes); + } + catch (OverflowException) + { + return E.E_INVALIDARG; + } + + // For 2D textures, the size must match the rows * stride, plus the byte size of the last row (no trailing padding) + if (dimensions == 2) + { + if (extent01SizeInBytes != dataSize) + { + return E.E_NOT_SUFFICIENT_BUFFER; + } + } + else + { + // Validate the 1th stride is not smaller than the byte size of a 2D slice, with padding + if (extent01SizeInBytes > strides[1]) + { + return E.E_INVALIDARG; + } + + uint extent012SizeInBytes; + + try + { + extent012SizeInBytes = (extents[2] - 1) * strides[1] + extent01SizeInBytes; + } + catch (OverflowException) + { + return E.E_INVALIDARG; + } + + if (extent012SizeInBytes != dataSize) + { + return E.E_NOT_SUFFICIENT_BUFFER; + } + } + } + + return S.S_OK; + } + + /// + /// Initializes the staging buffer and optional strides with pre-validated data. + /// + /// The current object. + /// The number of dimensions in the resource texture. This must match the number used to load the texture. + /// The data to be placed into the resource texture. + /// The stride to advance through the input data, according to dimension. + /// The size of the data buffer to be used to update the resource texture. + /// The for the operation. + /// + /// This method is invoked with pre-validated data and doesn't check the input arguments. + /// This method is invoked either when initializing the texture, or when doing a full update with no existing texture. + /// + private static int InitializeStagingBufferAndStrides( + D2D1ResourceTextureManagerImpl* @this, + uint dimensions, + byte* data, + uint* strides, + uint dataSize) + { + // Allocate the data buffer (this is the one most likely to potentially throw) + if (dataSize > 0) + { + try + { + @this->data = (byte*)NativeMemory.Alloc(dataSize); + } + catch (OutOfMemoryException) + { + return E.E_OUTOFMEMORY; + } + + Buffer.MemoryCopy(data, @this->data, dataSize, dataSize); + + @this->dataSize = dataSize; + } + + // If there are strides (ie. the texture has dimension greater than 1), initialize them as well + if (strides is not null) + { + try + { + @this->strides = (uint*)NativeMemory.Alloc(sizeof(uint) * (dimensions - 1)); + } + catch (OutOfMemoryException) + { + return E.E_OUTOFMEMORY; + } + + Buffer.MemoryCopy( + source: strides, + destination: @this->strides, + destinationSizeInBytes: sizeof(uint) * (dimensions - 1), + sourceBytesToCopy: sizeof(uint) * (dimensions - 1)); + } + + return S.S_OK; + } + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs new file mode 100644 index 00000000..f9fc316e --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.ID2D1ResourceTextureManagerInternal.cs @@ -0,0 +1,202 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Shaders.Interop.Extensions; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if !NET6_0_OR_GREATER +using UnmanagedCallersOnlyAttribute = ComputeSharp.NetStandard.System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute; +#endif + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; + +/// +partial struct D2D1ResourceTextureManagerImpl +{ + /// + /// The implementation for ID2D1ResourceTextureManagerInternal. + /// + private unsafe static class ID2D1ResourceTextureManagerInternalMethods + { +#if !NET6_0_OR_GREATER + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int InitializeDelegate(D2D1ResourceTextureManagerImpl* @this, ID2D1EffectContext* effectContext, uint* dimensions); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int GetResourceTextureDelegate(D2D1ResourceTextureManagerImpl* @this, ID2D1ResourceTexture** resourceTexture); + + /// + /// A cached instance wrapping . + /// + public static readonly QueryInterfaceDelegate QueryInterfaceWrapper = QueryInterface; + + /// + /// A cached instance wrapping . + /// + public static readonly AddRefDelegate AddRefWrapper = AddRef; + + /// + /// A cached instance wrapping . + /// + public static readonly ReleaseDelegate ReleaseWrapper = Release; + + /// + /// A cached instance wrapping . + /// + public static readonly InitializeDelegate InitializeWrapper = Initialize; + + /// + /// A cached instance wrapping . + /// + public static readonly GetResourceTextureDelegate GetResourceTextureWrapper = GetResourceTexture; +#endif + + /// + [UnmanagedCallersOnly] + public static int QueryInterface(D2D1ResourceTextureManagerImpl* @this, Guid* riid, void** ppvObject) + { + @this = (D2D1ResourceTextureManagerImpl*)&((void**)@this)[-1]; + + return @this->QueryInterface(riid, ppvObject); + } + + /// + [UnmanagedCallersOnly] + public static uint AddRef(D2D1ResourceTextureManagerImpl* @this) + { + @this = (D2D1ResourceTextureManagerImpl*)&((void**)@this)[-1]; + + return @this->AddRef(); + } + + /// + [UnmanagedCallersOnly] + public static uint Release(D2D1ResourceTextureManagerImpl* @this) + { + @this = (D2D1ResourceTextureManagerImpl*)&((void**)@this)[-1]; + + return @this->Release(); + } + + /// + [UnmanagedCallersOnly] + public static int Initialize(D2D1ResourceTextureManagerImpl* @this, ID2D1EffectContext* effectContext, uint* dimensions) + { + @this = (D2D1ResourceTextureManagerImpl*)&((void**)@this)[-1]; + + if (effectContext is null) + { + return E.E_POINTER; + } + + lock (@this->lockHandle.Target!) + { + // If the dimensions are available, validate them + if (dimensions is not null) + { + uint expectedDimensions = *dimensions; + + if (@this->resourceTextureProperties.extents is not null && + @this->resourceTextureProperties.dimensions != expectedDimensions) + { + return E.E_INVALIDARG; + } + + @this->expectedDimensions = expectedDimensions; + } + + // If this is the first time the method is called, just store the context. + // Before doing so, get an ID2D1Multithread instance, to ensure thread safety. + // For additional info, see docs on ID2D1EffectFactoryExtensions.GetD2D1Multithread. + if (@this->d2D1EffectContext is null) + { + using ComPtr d2D1Multithread = default; + + int hresult = effectContext->GetD2D1Multithread(d2D1Multithread.GetAddressOf()); + + // If an ID2D1Multithread object is available, we can safely store the context + if (Windows.SUCCEEDED(hresult)) + { + _ = effectContext->AddRef(); + + @this->d2D1EffectContext = effectContext; + @this->d2D1Multithread = d2D1Multithread.Detach(); + } + + return hresult; + } + + // Otherwise, just do nothing and return S_FALSE. This allows an existing resource texture + // manager to be shared across effects. If the resource cannot be shared, it will just + // return an error when effect is actually set, with ID2D1DrawInfo::SetResourceTexture. + return S.S_FALSE; + } + } + + /// + [UnmanagedCallersOnly] + public static int GetResourceTexture(D2D1ResourceTextureManagerImpl* @this, ID2D1ResourceTexture** resourceTexture) + { + @this = (D2D1ResourceTextureManagerImpl*)&((void**)@this)[-1]; + + if (*resourceTexture is not null) + { + return E.E_POINTER; + } + + lock (@this->lockHandle.Target!) + { + // If the effect context is null, it means Initialize has not been called yet + if (@this->d2D1EffectContext is null) + { + return E.E_NOT_VALID_STATE; + } + + // If the texture has already been created, just return it + if (@this->d2D1ResourceTexture is not null) + { + @this->d2D1ResourceTexture->AddRef(); + + *resourceTexture = @this->d2D1ResourceTexture; + + return S.S_OK; + } + + // If the data is null at this point, it means CreateResourceTexture has not been called yet + if (@this->data is null) + { + return E.E_NOT_VALID_STATE; + } + + // Create the resource now, as it hasn't been created yet + int result = @this->d2D1EffectContext->CreateResourceTexture( + resourceId: @this->resourceId, + resourceTextureProperties: &@this->resourceTextureProperties, + data: @this->data, + strides: @this->strides, + dataSize: @this->dataSize, + resourceTexture: resourceTexture); + + // If creation was successful, release the buffered data. Going forwards, + // the resource texture will be used directly for all updates requested. + if (result == S.S_OK) + { + NativeMemory.Free(@this->resourceTextureProperties.extents); + NativeMemory.Free(@this->resourceTextureProperties.extendModes); + NativeMemory.Free(@this->data); + NativeMemory.Free(@this->strides); + + // Reset the stored pointers to avoid double frees from Release() + @this->resourceTextureProperties.extents = null; + @this->resourceTextureProperties.extendModes = null; + @this->data = null; + @this->strides = null; + } + + return result; + } + } + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs new file mode 100644 index 00000000..a10c9b3f --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/D2D1ResourceTextureManagerImpl.cs @@ -0,0 +1,281 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; +#if NET6_0_OR_GREATER +using RuntimeHelpers = System.Runtime.CompilerServices.RuntimeHelpers; +#else +using RuntimeHelpers = ComputeSharp.D2D1.NetStandard.System.Runtime.CompilerServices.RuntimeHelpers; +#endif + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; + +/// +/// An implementation of the ID2D1ResourceTextureManager and ID2D1ResourceTextureManagerInternal interfaces. +/// +internal unsafe partial struct D2D1ResourceTextureManagerImpl +{ + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int QueryInterfaceDelegate(D2D1ResourceTextureManagerImpl* @this, Guid* riid, void** ppvObject); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint AddRefDelegate(D2D1ResourceTextureManagerImpl* @this); + + /// + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint ReleaseDelegate(D2D1ResourceTextureManagerImpl* @this); + + /// + /// The shared vtable pointer for instance, for ID2D1ResourceTextureManager. + /// + private static readonly void** VtblForID2D1ResourceTextureManager; + + /// + /// The shared vtable pointer for instance, for ID2D1ResourceTextureManagerInternal. + /// + private static readonly void** VtblForID2D1ResourceTextureManagerInternal; + + /// + /// Initializes the shared state for . + /// + static D2D1ResourceTextureManagerImpl() + { + void** lpVtbl = (void**)RuntimeHelpers.AllocateTypeAssociatedMemory(typeof(D2D1ResourceTextureManagerImpl), sizeof(void*) * 10); + + // ID2D1ResourceTextureManager +#if NET6_0_OR_GREATER + lpVtbl[0] = (delegate* unmanaged)&ID2D1ResourceTextureManagerMethods.QueryInterface; + lpVtbl[1] = (delegate* unmanaged)&ID2D1ResourceTextureManagerMethods.AddRef; + lpVtbl[2] = (delegate* unmanaged)&ID2D1ResourceTextureManagerMethods.Release; + lpVtbl[3] = (delegate* unmanaged)&ID2D1ResourceTextureManagerMethods.Initialize; + lpVtbl[4] = (delegate* unmanaged)&ID2D1ResourceTextureManagerMethods.Update; +#else + lpVtbl[0] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1ResourceTextureManagerMethods.QueryInterfaceWrapper); + lpVtbl[1] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1ResourceTextureManagerMethods.AddRefWrapper); + lpVtbl[2] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1ResourceTextureManagerMethods.ReleaseWrapper); + lpVtbl[3] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1ResourceTextureManagerMethods.InitializeWrapper); + lpVtbl[4] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1ResourceTextureManagerMethods.UpdateWrapper); +#endif + + // ID2D1ResourceTextureManagerInternal +#if NET6_0_OR_GREATER + lpVtbl[5 + 0] = (delegate* unmanaged)&ID2D1ResourceTextureManagerInternalMethods.QueryInterface; + lpVtbl[5 + 1] = (delegate* unmanaged)&ID2D1ResourceTextureManagerInternalMethods.AddRef; + lpVtbl[5 + 2] = (delegate* unmanaged)&ID2D1ResourceTextureManagerInternalMethods.Release; + lpVtbl[5 + 3] = (delegate* unmanaged)&ID2D1ResourceTextureManagerInternalMethods.Initialize; + lpVtbl[5 + 4] = (delegate* unmanaged)&ID2D1ResourceTextureManagerInternalMethods.GetResourceTexture; +#else + lpVtbl[5 + 0] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1ResourceTextureManagerInternalMethods.QueryInterfaceWrapper); + lpVtbl[5 + 1] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1ResourceTextureManagerInternalMethods.AddRefWrapper); + lpVtbl[5 + 2] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1ResourceTextureManagerInternalMethods.ReleaseWrapper); + lpVtbl[5 + 3] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1ResourceTextureManagerInternalMethods.InitializeWrapper); + lpVtbl[5 + 4] = (void*)Marshal.GetFunctionPointerForDelegate(ID2D1ResourceTextureManagerInternalMethods.GetResourceTextureWrapper); +#endif + + VtblForID2D1ResourceTextureManager = lpVtbl; + VtblForID2D1ResourceTextureManagerInternal = &lpVtbl[5]; + } + + /// + /// The vtable pointer for the current instance, for ID2D1ResourceTextureManager. + /// + private void** lpVtblForID2D1ResourceTextureManager; + + /// + /// The vtable pointer for the current instance, for ID2D1ResourceTextureManagerInternal. + /// + private void** lpVtblForID2D1ResourceTextureManagerInternal; + + /// + /// The current reference count for the object (from IUnknown). + /// + private volatile int referenceCount; + + /// + /// The object currently wrapped by the current instance. + /// + private ID2D1EffectContext* d2D1EffectContext; + + /// + /// The instance used to lock accesses to and . + /// + private ID2D1Multithread* d2D1Multithread; + + /// + /// The object, if one was created already. + /// + private ID2D1ResourceTexture* d2D1ResourceTexture; + + /// + /// The to identify the resource, if available. + /// + private Guid* resourceId; + + /// + /// The for the resource texture. + /// + /// + /// If is , it has not been set. + /// + private D2D1_RESOURCE_TEXTURE_PROPERTIES resourceTextureProperties; + + /// + /// The texture data, if available. + /// + /// + /// Once the texture has been created, this will no longer be necessary. + /// + private byte* data; + + /// + /// An optional pointer to the stride to advance through the resource texture, according to dimension. + /// + private uint* strides; + + /// + /// The size, in bytes, of the data. + /// + private uint dataSize; + + /// + /// A to a dummy to use for locking. + /// + private GCHandle lockHandle; + + /// + /// The expected dimensions for the slot the manager has been assigned to in an effect. + /// + /// If 0, it has not been set, so it can be ignored. + private uint expectedDimensions; + + /// + /// The factory method for instances. + /// + /// The resulting resource texture manager instance. + public static void Factory(D2D1ResourceTextureManagerImpl** resourceTextureManager) + { + D2D1ResourceTextureManagerImpl* @this = (D2D1ResourceTextureManagerImpl*)NativeMemory.Alloc((nuint)sizeof(D2D1ResourceTextureManagerImpl)); + + *@this = default; + + @this->lpVtblForID2D1ResourceTextureManager = VtblForID2D1ResourceTextureManager; + @this->lpVtblForID2D1ResourceTextureManagerInternal = VtblForID2D1ResourceTextureManagerInternal; + @this->referenceCount = 1; + @this->d2D1EffectContext = null; + @this->d2D1Multithread = null; + @this->d2D1ResourceTexture = null; + @this->resourceId = null; + @this->resourceTextureProperties = default; + @this->data = null; + @this->strides = null; + @this->dataSize = 0; + @this->lockHandle = GCHandle.Alloc(new object()); + @this->expectedDimensions = 0; + + *resourceTextureManager = @this; + } + + /// + public int QueryInterface(Guid* riid, void** ppvObject) + { + if (ppvObject is null) + { + return E.E_POINTER; + } + + // ID2D1ResourceTextureManager + if (riid->Equals(Windows.__uuidof()) || + riid->Equals(ID2D1ResourceTextureManager.Guid)) + { + _ = Interlocked.Increment(ref this.referenceCount); + + *ppvObject = Unsafe.AsPointer(ref this); + + return S.S_OK; + } + + // ID2D1ResourceTextureManagerInternal + if (riid->Equals(ID2D1ResourceTextureManagerInternal.Guid)) + { + _ = Interlocked.Increment(ref this.referenceCount); + + *ppvObject = (void**)Unsafe.AsPointer(ref this) + 1; + + return S.S_OK; + } + + *ppvObject = null; + + return E.E_NOINTERFACE; + } + + /// + public uint AddRef() + { + return (uint)Interlocked.Increment(ref this.referenceCount); + } + + /// + public uint Release() + { + uint referenceCount = (uint)Interlocked.Decrement(ref this.referenceCount); + + if (referenceCount == 0) + { + lock (this.lockHandle.Target!) + { + // Also synchronize on the ID2D1Multithread instance before touching D2D objects + if (this.d2D1Multithread is not null) + { + // Enter the lock, and then free the effect context. That is guaranteed to + // not be null here, as it is only ever set if ID2D1Multithread is retrieved. + this.d2D1Multithread->Enter(); + this.d2D1EffectContext->Release(); + + // Release the resource too if it has been created + if (this.d2D1ResourceTexture is not null) + { + this.d2D1ResourceTexture->Release(); + } + + this.d2D1Multithread->Leave(); + } + + if (this.resourceId is not null) + { + NativeMemory.Free(this.resourceId); + } + + if (this.resourceTextureProperties.extents is not null) + { + NativeMemory.Free(this.resourceTextureProperties.extents); + } + + if (this.resourceTextureProperties.extendModes is not null) + { + NativeMemory.Free(this.resourceTextureProperties.extendModes); + } + + if (this.data is not null) + { + NativeMemory.Free(this.data); + } + + if (this.strides is not null) + { + NativeMemory.Free(this.strides); + } + } + + this.lockHandle.Free(); + + NativeMemory.Free(Unsafe.AsPointer(ref this)); + } + + return referenceCount; + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManager.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManager.cs new file mode 100644 index 00000000..690f7db6 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManager.cs @@ -0,0 +1,101 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; + +/// +/// The resource texture manager type to use with built-in effects. +/// +[Guid("3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64")] +internal unsafe struct ID2D1ResourceTextureManager +{ + /// + /// Gets the for ID2D1ResourceTextureManager (3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64). + /// + public static ref readonly Guid Guid + { + get + { + ReadOnlySpan data = new byte[] { + 0xE4, 0xC7, 0x4F, 0x3C, + 0x19, 0xA4, + 0xCA, 0x46, + 0xB5, 0xF6, + 0x66, + 0xEB, + 0x4F, + 0xF1, + 0x8D, + 0x64 + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + + /// + /// The vtable for the current instance. + /// + private readonly void** lpVtbl; + + /// + /// Creates or finds the given resource texture, depending on whether a resource id is specified. + /// It also optionally initializes the texture with the specified data. + /// + /// An optional pointer to the unique id that identifies the resource texture. + /// The properties used to create the resource texture. + /// The optional data to be loaded into the resource texture. + /// An optional pointer to the stride to advance through the resource texture, according to dimension. + /// The size, in bytes, of the data. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Initialize( + Guid* resourceId, + D2D1_RESOURCE_TEXTURE_PROPERTIES* resourceTextureProperties, + byte* data, + uint* strides, + uint dataSize) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])( + (ID2D1ResourceTextureManager*)Unsafe.AsPointer(ref this), + resourceId, + resourceTextureProperties, + data, + strides, + dataSize); + } + + /// + /// Updates the specific resource texture inside the specific range or box using the supplied data. + /// + /// The "left" extent of the updates if specified. If , the entire texture is updated. + /// The "right" extent of the updates if specified. If , the entire texture is updated. + /// The stride to advance through the input data, according to dimension. + /// The number of dimensions in the resource texture. This must match the number used to load the texture. + /// The data to be placed into the resource texture. + /// The size of the data buffer to be used to update the resource texture. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Update( + uint* minimumExtents, + uint* maximimumExtents, + uint* strides, + uint dimensions, + byte* data, + uint dataCount) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[4])( + (ID2D1ResourceTextureManager*)Unsafe.AsPointer(ref this), + minimumExtents, + maximimumExtents, + strides, + dimensions, + data, + dataCount); + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManagerInternal.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManagerInternal.cs new file mode 100644 index 00000000..ac43cacb --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Effects/ResourceManagers/ID2D1ResourceTextureManagerInternal.cs @@ -0,0 +1,73 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ComputeSharp.D2D1.Shaders.Interop.Effects.ResourceManagers; + +/// +/// The internal resource texture manager type to use with built-in effects. +/// +[Guid("5CBB1024-8EA1-4689-81BF-8AD190B5EF5D")] +internal unsafe struct ID2D1ResourceTextureManagerInternal +{ + /// + /// Gets the for ID2D1ResourceTextureManagerInternal (5CBB1024-8EA1-4689-81BF-8AD190B5EF5D). + /// + public static ref readonly Guid Guid + { + get + { + ReadOnlySpan data = new byte[] { + 0x24, 0x10, 0xBB, 0x5C, + 0xA1, 0x8E, + 0x89, 0x46, + 0x81, 0xBF, + 0x8A, + 0xD1, + 0x90, + 0xB5, + 0xEF, + 0x5D + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + + /// + /// The vtable for the current instance. + /// + private readonly void** lpVtbl; + + /// + /// Sets the for the current ID2D1ResourceTextureManagerInternal instance. + /// + /// The input for the manager. + /// A pointer to an optional amount of dimensions for the target resource texture, for validation. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int Initialize(ID2D1EffectContext* effectContext, uint* dimensions) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[3])( + (ID2D1ResourceTextureManagerInternal*)Unsafe.AsPointer(ref this), + effectContext, + dimensions); + } + + /// + /// Gets the instance held by the manager. + /// + /// The resulting instance. + /// An for the operation. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public int GetResourceTexture(ID2D1ResourceTexture** resourceTexture) + { + return ((delegate* unmanaged[Stdcall])this.lpVtbl[4])( + (ID2D1ResourceTextureManagerInternal*)Unsafe.AsPointer(ref this), + resourceTexture); + } +} diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/Extensions/ID2D1EffectContextExtensions.cs b/src/ComputeSharp.D2D1/Shaders/Interop/Extensions/ID2D1EffectContextExtensions.cs new file mode 100644 index 00000000..17b5dde6 --- /dev/null +++ b/src/ComputeSharp.D2D1/Shaders/Interop/Extensions/ID2D1EffectContextExtensions.cs @@ -0,0 +1,66 @@ +using System; +using System.Runtime.CompilerServices; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Shaders.Interop.Extensions; + +/// +/// Extensions for the type. +/// +internal static class ID2D1EffectContextExtensions +{ + /// + /// Gets an from an input object. + /// + /// The input instance. + /// The resulting object. + /// The for the operation + /// + /// + /// The object is not thread-safe, so it cannot be used concurrently + /// when outside of a scenario where D2D has explicitly called into user code (eg. in the public APIs + /// from . To avoid issues, it is necessary to lock with the same lock + /// used by D2D when using any public API on from other callsites. + /// The same goes for any type out of d2d1effectauthor.h, such as . + /// + /// + /// To lock, the object can be used. To retrieve this, a + /// instance is needed. This cannot be retrieved directly from an , but this + /// can be used to create any instance (such as a flood effect, which is fairly cheap). + /// From that, can be used to get an object. + /// The fact implements this interface is mentioned in the docs, + /// see . + /// + /// + /// From the , an can be retrieved. Finally, this can + /// be cast to , which can then be kept and used to synchronize later calls. + /// + /// + public static unsafe int GetD2D1Multithread(this ref ID2D1EffectContext effectContext, ID2D1Multithread** multithread) + { + using ComPtr floodEffect = default; + + int hresult = effectContext.CreateEffect( + effectId: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_D2D1Flood)), + effect: (void**)floodEffect.GetAddressOf()); + + if (Windows.SUCCEEDED(hresult)) + { + using ComPtr d2D1Image = default; + + hresult = floodEffect.CopyTo(d2D1Image.GetAddressOf()); + + if (Windows.SUCCEEDED(hresult)) + { + using ComPtr d2D1Factory = default; + + d2D1Image.Get()->GetFactory(d2D1Factory.GetAddressOf()); + + hresult = d2D1Factory.CopyTo(multithread); + } + } + + return hresult; + } +} diff --git a/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/UnmanagedCallersOnlyAttribute.cs b/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/UnmanagedCallersOnlyAttribute.cs index b35b322b..0f25befe 100644 --- a/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/UnmanagedCallersOnlyAttribute.cs +++ b/src/ComputeSharp.NetStandard/System/Runtime/InteropServices/UnmanagedCallersOnlyAttribute.cs @@ -3,6 +3,8 @@ using System; +#pragma warning disable CS0649 + namespace ComputeSharp.NetStandard.System.Runtime.InteropServices; // This cannot be in System.Runtime.InteropServices, or Roslyn will recognize it /// @@ -14,4 +16,16 @@ namespace ComputeSharp.NetStandard.System.Runtime.InteropServices; // This canno [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class UnmanagedCallersOnlyAttribute : Attribute { + /// + /// Optional. If omitted, the runtime will use the default platform calling convention. + /// + /// + /// Supplied types must be from the official "System.Runtime.CompilerServices" namespace and be of the form "CallConvXXX". + /// + public Type[]? CallConvs; + + /// + /// Optional. If omitted, no named export is emitted during compilation. + /// + public string? EntryPoint; } \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1/D2D1_EXTEND_MODE.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1/D2D1_EXTEND_MODE.cs new file mode 100644 index 00000000..3697bb0b --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1/D2D1_EXTEND_MODE.cs @@ -0,0 +1,18 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +namespace TerraFX.Interop.DirectX +{ + internal enum D2D1_EXTEND_MODE : uint + { + D2D1_EXTEND_MODE_CLAMP = 0, + + D2D1_EXTEND_MODE_WRAP = 1, + + D2D1_EXTEND_MODE_MIRROR = 2, + + D2D1_EXTEND_MODE_FORCE_DWORD = 0xffffffff, + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1/ID2D1Factory.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1/ID2D1Factory.cs new file mode 100644 index 00000000..e690fd2f --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1/ID2D1Factory.cs @@ -0,0 +1,20 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.InteropServices; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("06152247-6F50-465A-9245-118BFD3B6007")] + [NativeTypeName("struct ID2D1Factory : IUnknown")] + [NativeInheritance("IUnknown")] + internal unsafe partial struct ID2D1Factory + { + public void** lpVtbl; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1/ID2D1Image.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1/ID2D1Image.cs new file mode 100644 index 00000000..bfa830c6 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1/ID2D1Image.cs @@ -0,0 +1,55 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("65019F75-8DA2-497C-B32C-DFA34E48EDE6")] + [NativeTypeName("struct ID2D1Image : ID2D1Resource")] + [NativeInheritance("ID2D1Resource")] + internal unsafe partial struct ID2D1Image + { + public void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[0]))((ID2D1Image*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[1]))((ID2D1Image*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[2]))((ID2D1Image*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + public void GetFactory(ID2D1Factory** factory) + { + ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID2D1Image*)Unsafe.AsPointer(ref this), factory); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs index e7c40874..993104bc 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/D2D1_PROPERTY_TYPE.cs @@ -7,6 +7,7 @@ namespace TerraFX.Interop.DirectX { internal enum D2D1_PROPERTY_TYPE : uint { - D2D1_PROPERTY_TYPE_BLOB = 9 + D2D1_PROPERTY_TYPE_BLOB = 9, + D2D1_PROPERTY_TYPE_IUNKNOWN = 10 } } \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Multithread.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Multithread.cs new file mode 100644 index 00000000..93cc3351 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1_1/ID2D1Multithread.cs @@ -0,0 +1,62 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1_1.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("31E6E7BC-E0FF-4D46-8C64-A0A8C41C15D3")] + [NativeTypeName("struct ID2D1Multithread : IUnknown")] + [NativeInheritance("IUnknown")] + internal unsafe partial struct ID2D1Multithread + { + public void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[0]))((ID2D1Multithread*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[1]))((ID2D1Multithread*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[2]))((ID2D1Multithread*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(4)] + public void Enter() + { + ((delegate* unmanaged[Stdcall])(lpVtbl[4]))((ID2D1Multithread*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(5)] + public void Leave() + { + ((delegate* unmanaged[Stdcall])(lpVtbl[5]))((ID2D1Multithread*)Unsafe.AsPointer(ref this)); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_PROPERTY_BINDING.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_PROPERTY_BINDING.cs index 260517aa..fdd86e4a 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_PROPERTY_BINDING.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_PROPERTY_BINDING.cs @@ -5,7 +5,9 @@ #pragma warning disable CS0649 +#if NET6_0_OR_GREATER using TerraFX.Interop.Windows; +#endif namespace TerraFX.Interop.DirectX { @@ -15,9 +17,17 @@ namespace TerraFX.Interop.DirectX public ushort* propertyName; [NativeTypeName("PD2D1_PROPERTY_SET_FUNCTION")] - public delegate* unmanaged[Stdcall] setFunction; +#if NET6_0_OR_GREATER + public delegate* unmanaged[Stdcall] setFunction; +#else + public void* setFunction; +#endif [NativeTypeName("PD2D1_PROPERTY_GET_FUNCTION")] - public delegate* unmanaged[Stdcall] getFunction; +#if NET6_0_OR_GREATER + public delegate* unmanaged[Stdcall] getFunction; +#else + public void* getFunction; +#endif } } \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_RESOURCE_TEXTURE_PROPERTIES.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_RESOURCE_TEXTURE_PROPERTIES.cs new file mode 100644 index 00000000..3671d592 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/D2D1_RESOURCE_TEXTURE_PROPERTIES.cs @@ -0,0 +1,27 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + internal unsafe partial struct D2D1_RESOURCE_TEXTURE_PROPERTIES + { + [NativeTypeName("const UINT32 *")] + public uint* extents; + + [NativeTypeName("UINT32")] + public uint dimensions; + + public D2D1_BUFFER_PRECISION bufferPrecision; + + public D2D1_CHANNEL_DEPTH channelDepth; + + public D2D1_FILTER filter; + + [NativeTypeName("const D2D1_EXTEND_MODE *")] + public D2D1_EXTEND_MODE* extendModes; + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs index f1412941..73ff14e9 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1DrawInfo.cs @@ -57,6 +57,13 @@ namespace TerraFX.Interop.DirectX return ((delegate* unmanaged[Stdcall])(lpVtbl[7]))((ID2D1DrawInfo*)Unsafe.AsPointer(ref this), buffer, bufferCount); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(8)] + public HRESULT SetResourceTexture([NativeTypeName("UINT32")] uint textureIndex, ID2D1ResourceTexture* resourceTexture) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[8]))((ID2D1DrawInfo*)Unsafe.AsPointer(ref this), textureIndex, resourceTexture); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(10)] public HRESULT SetPixelShader([NativeTypeName("const GUID &")] Guid* shaderId, D2D1_PIXEL_OPTIONS pixelOptions = D2D1_PIXEL_OPTIONS_NONE) diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1EffectContext.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1EffectContext.cs index ab8361cd..e9d47721 100644 --- a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1EffectContext.cs +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1EffectContext.cs @@ -19,6 +19,29 @@ namespace TerraFX.Interop.DirectX { public void** lpVtbl; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[0]))((IUnknown*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[1]))((IUnknown*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[2]))((IUnknown*)Unsafe.AsPointer(ref this)); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(4)] public HRESULT CreateEffect([NativeTypeName("const IID &")] Guid* effectId, void** effect) @@ -40,6 +63,13 @@ namespace TerraFX.Interop.DirectX return ((delegate* unmanaged[Stdcall])(lpVtbl[14]))((ID2D1EffectContext*)Unsafe.AsPointer(ref this), shaderId); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(15)] + public HRESULT CreateResourceTexture([NativeTypeName("const GUID *")] Guid* resourceId, [NativeTypeName("const D2D1_RESOURCE_TEXTURE_PROPERTIES *")] D2D1_RESOURCE_TEXTURE_PROPERTIES* resourceTextureProperties, [NativeTypeName("const BYTE *")] byte* data, [NativeTypeName("const UINT32 *")] uint* strides, [NativeTypeName("UINT32")] uint dataSize, ID2D1ResourceTexture** resourceTexture) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[15]))((ID2D1EffectContext*)Unsafe.AsPointer(ref this), resourceId, resourceTextureProperties, data, strides, dataSize, resourceTexture); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] [VtblIndex(22)] public HRESULT CheckFeatureSupport(D2D1_FEATURE feature, void* featureSupportData, [NativeTypeName("UINT32")] uint featureSupportDataSize) diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1ResourceTexture.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1ResourceTexture.cs new file mode 100644 index 00000000..c3aa978a --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effectauthor/ID2D1ResourceTexture.cs @@ -0,0 +1,55 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effectauthor.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace TerraFX.Interop.DirectX +{ + [Guid("688D15C3-02B0-438D-B13A-D1B44C32C39A")] + [NativeTypeName("struct ID2D1ResourceTexture : IUnknown")] + [NativeInheritance("IUnknown")] + internal unsafe partial struct ID2D1ResourceTexture + { + public void** lpVtbl; + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(0)] + public HRESULT QueryInterface([NativeTypeName("const IID &")] Guid* riid, void** ppvObject) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[0]))((ID2D1ResourceTexture*)Unsafe.AsPointer(ref this), riid, ppvObject); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(1)] + [return: NativeTypeName("ULONG")] + public uint AddRef() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[1]))((ID2D1ResourceTexture*)Unsafe.AsPointer(ref this)); + } + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(2)] + [return: NativeTypeName("ULONG")] + public uint Release() + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[2]))((ID2D1ResourceTexture*)Unsafe.AsPointer(ref this)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [VtblIndex(3)] + public HRESULT Update([NativeTypeName("const UINT32 *")] uint* minimumExtents, [NativeTypeName("const UINT32 *")] uint* maximimumExtents, [NativeTypeName("const UINT32 *")] uint* strides, [NativeTypeName("UINT32")] uint dimensions, [NativeTypeName("const BYTE *")] byte* data, [NativeTypeName("UINT32")] uint dataCount) + { + return ((delegate* unmanaged[Stdcall])(lpVtbl[3]))((ID2D1ResourceTexture*)Unsafe.AsPointer(ref this), minimumExtents, maximimumExtents, strides, dimensions, data, dataCount); + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/CLSID.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/CLSID.cs new file mode 100644 index 00000000..e63a48c6 --- /dev/null +++ b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d2d1effects/CLSID.cs @@ -0,0 +1,38 @@ +// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. + +// Ported from um/d2d1effects.h in the Windows SDK for Windows 10.0.22000.0 +// Original source is Copyright © Microsoft. All rights reserved. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace TerraFX.Interop.Windows +{ + internal static partial class CLSID + { + [NativeTypeName("const GUID")] + public static ref readonly Guid CLSID_D2D1Flood + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + ReadOnlySpan data = new byte[] { + 0x20, 0x3C, 0xC2, 0x61, + 0x69, 0xAE, + 0x8E, 0x4D, + 0x94, + 0xCF, + 0x50, + 0x07, + 0x8D, + 0xF6, + 0x38, + 0xF2 + }; + + return ref Unsafe.As(ref MemoryMarshal.GetReference(data)); + } + } + } +} \ No newline at end of file diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shadeer/D3D11_SHADER_DESC.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shader/D3D11_SHADER_DESC.cs similarity index 100% rename from src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shadeer/D3D11_SHADER_DESC.cs rename to src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shader/D3D11_SHADER_DESC.cs diff --git a/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shadeer/ID3D11ShaderReflection.cs b/src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shader/ID3D11ShaderReflection.cs similarity index 100% rename from src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shadeer/ID3D11ShaderReflection.cs rename to src/TerraFX.Interop.Windows.D2D1/DirectX/um/d3d11shader/ID3D11ShaderReflection.cs diff --git a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems index 130071e2..f607566b 100644 --- a/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems +++ b/src/TerraFX.Interop.Windows.D2D1/TerraFX.Interop.Windows.D2D1.projitems @@ -17,21 +17,28 @@ + + + + + + + - + @@ -41,7 +48,7 @@ - + diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs index a8da79de..e8227e77 100644 --- a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/E.cs @@ -7,6 +7,12 @@ namespace TerraFX.Interop.Windows { internal static class E { + [NativeTypeName("#define E_NOT_VALID_STATE HRESULT_FROM_WIN32(ERROR_INVALID_STATE)")] + public const int E_NOT_VALID_STATE = -2147019873; + + [NativeTypeName("#define E_NOT_SUFFICIENT_BUFFER HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)")] + public const int E_NOT_SUFFICIENT_BUFFER = -2147024774; + [NativeTypeName("#define E_NOTIMPL _HRESULT_TYPEDEF_(0x80004001L)")] public const int E_NOTIMPL = unchecked((int)(0x80004001)); diff --git a/src/TerraFX.Interop.Windows/Windows/shared/winerror/S.cs b/src/TerraFX.Interop.Windows/Windows/shared/winerror/S.cs index 04be0f93..ed02e8c5 100644 --- a/src/TerraFX.Interop.Windows/Windows/shared/winerror/S.cs +++ b/src/TerraFX.Interop.Windows/Windows/shared/winerror/S.cs @@ -12,11 +12,5 @@ namespace TerraFX.Interop.Windows [NativeTypeName("#define S_FALSE ((HRESULT)1L)")] public const int S_FALSE = ((int)(1)); - - [NativeTypeName("#define S_STORE_LAUNCHED_FOR_REMEDIATION _HRESULT_TYPEDEF_(0x00270258L)")] - public const int S_STORE_LAUNCHED_FOR_REMEDIATION = ((int)(0x00270258)); - - [NativeTypeName("#define S_APPLICATION_ACTIVATION_ERROR_HANDLED_BY_DIALOG _HRESULT_TYPEDEF_(0x00270259L)")] - public const int S_APPLICATION_ACTIVATION_ERROR_HANDLED_BY_DIALOG = ((int)(0x00270259)); } } diff --git a/tests/ComputeSharp.D2D1.Tests/Assets/WallpapersStack.png b/tests/ComputeSharp.D2D1.Tests/Assets/WallpapersStack.png new file mode 100644 index 00000000..c13f05e6 Binary files /dev/null and b/tests/ComputeSharp.D2D1.Tests/Assets/WallpapersStack.png differ diff --git a/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj b/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj index a650719c..2b8891a6 100644 --- a/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj +++ b/tests/ComputeSharp.D2D1.Tests/ComputeSharp.D2D1.Tests.csproj @@ -38,6 +38,21 @@ PreserveNewest + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + PreserveNewest diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs new file mode 100644 index 00000000..6d2c504b --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderEffectTests.cs @@ -0,0 +1,160 @@ +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Tests.Effects; +using ComputeSharp.D2D1.Tests.Helpers; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.Tests; + +[TestClass] +[TestCategory("D2D1PixelShaderEffect")] +public partial class D2D1PixelShaderEffectTests +{ + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void RegisterForD2D1Factory1_NullD2D1Factory1() + { + D2D1PixelShaderEffect.RegisterForD2D1Factory1(null, out _); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void RegisterForD2D1Factory1_WithTransformMapper_NullD2D1Factory1() + { + D2D1PixelShaderEffect.RegisterForD2D1Factory1(null, out _); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void RegisterForD2D1Factory1_WithTransformMapperFactory_NullD2D1Factory1() + { + D2D1PixelShaderEffect.RegisterForD2D1Factory1(null, () => new PixelateEffect(), out _); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void CreateFromD2D1DeviceContext_NullD2D1DeviceContext() + { + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(null, (void**)1); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void CreateFromD2D1DeviceContext_NullD2D1Effect() + { + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext((void*)1, null); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void SetConstantBufferForD2D1Effect_NullD2D1Effect() + { + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(default, null); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void SetResourceTextureManagerForD2D1Effect_NullD2D1Effect() + { + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(null, (void*)1, 0); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void SetResourceTextureManagerForD2D1Effect_NullD2D1ResourceTextureManager() + { + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect((void*)1, (void*)null, 0); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void SetResourceTextureManagerForD2D1Effect_RCW_NullD2D1Effect() + { + D2D1ResourceTextureManager resourceTextureManager = new( + extents: stackalloc uint[] { 64 }, + bufferPrecision: D2D1BufferPrecision.UInt8Normalized, + channelDepth: D2D1ChannelDepth.One, + filter: D2D1Filter.MinLinearMagMipPoint, + extendModes: stackalloc D2D1ExtendMode[] { D2D1ExtendMode.Clamp }); + + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(null, resourceTextureManager, 0); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void SetResourceTextureManagerForD2D1Effect_RCW_NullD2D1ResourceTextureManager() + { + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect((void*)1, (D2D1ResourceTextureManager)null!, 0); + } + + [TestMethod] + [ExpectedException(typeof(Win32Exception))] + public unsafe void NullConstantBuffer_DrawImageFails() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), 128, 128); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + } + + [D2DInputCount(0)] + [D2DRequiresScenePosition] + [AutoConstructor] + private partial struct NullConstantBufferShader : ID2D1PixelShader + { + private float dummy; + + public float4 Execute() + { + return dummy; + } + } + + [TestMethod] + public unsafe void GetValueSize_ConstantBuffer() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + uint size = d2D1Effect.Get()->GetValueSize(D2D1PixelShaderEffectProperty.ConstantBuffer); + + Assert.AreEqual(D2D1PixelShader.GetConstantBufferSize(), (int)size); + } + + [D2DInputCount(0)] + [D2DRequiresScenePosition] + [AutoConstructor] + private partial struct ConstantBufferSizeTestShader : ID2D1PixelShader + { + private float a; + private float b; + private float3 c; + private int d; + private int e; + + public float4 Execute() + { + return a + b + c.X + d + e; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs index 3028574b..a0375100 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs @@ -559,4 +559,11 @@ public partial class D2D1PixelShaderTests return 0; } } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)] + public unsafe void SetConstantBufferForD2D1DrawInfo_NullD2D1DrawInfo() + { + D2D1PixelShader.SetConstantBufferForD2D1DrawInfo(default, null); + } } \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs new file mode 100644 index 00000000..780f7541 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/D2D1ResourceTextureManagerTests.cs @@ -0,0 +1,688 @@ +using System; +using System.ComponentModel; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.Tests.Helpers; +using ComputeSharp.Tests.Helpers; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#pragma warning disable CS0649 + +namespace ComputeSharp.D2D1.Tests; + +[TestClass] +[TestCategory("D2D1ResourceTextureManager")] +public partial class D2D1ResourceTextureManagerTests +{ + [TestMethod] + public unsafe void VerifyInterfaces() + { + using ComPtr resourceTextureManager = default; + + D2D1ResourceTextureManager.Create((void**)resourceTextureManager.GetAddressOf()); + + Assert.IsTrue(resourceTextureManager.Get() is not null); + + _ = resourceTextureManager.Get()->AddRef(); + + Assert.AreEqual(1u, resourceTextureManager.Get()->Release()); + + using ComPtr unknown = default; + using ComPtr resourceTextureManager2 = default; + using ComPtr resourceTextureManagerInternal = default; + + Guid uuidOfIUnknown = typeof(IUnknown).GUID; + Guid uuidOfResourceTextureManager = new("3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64"); + Guid uuidOfResourceTextureManagerInternal = new("5CBB1024-8EA1-4689-81BF-8AD190B5EF5D"); + + // The object implements IUnknown and the two resource texture manager interfaces + Assert.AreEqual(0, (int)resourceTextureManager.AsIID(&uuidOfIUnknown, &unknown)); + Assert.AreEqual(0, (int)resourceTextureManager.AsIID(&uuidOfResourceTextureManager, &resourceTextureManager2)); + Assert.AreEqual(0, (int)resourceTextureManager.AsIID(&uuidOfResourceTextureManagerInternal, &resourceTextureManagerInternal)); + + Assert.IsTrue(unknown.Get() is not null); + Assert.IsTrue(resourceTextureManager2.Get() is not null); + Assert.IsTrue(resourceTextureManagerInternal.Get() is not null); + + using ComPtr garbage = default; + + Guid uuidOfGarbage = Guid.NewGuid(); + + // Any other random QueryInterface should fail + Assert.AreEqual(E.E_NOINTERFACE, (int)resourceTextureManager.AsIID(&uuidOfGarbage, &garbage)); + + Assert.IsTrue(garbage.Get() is null); + } + + [TestMethod] + public unsafe void VerifyInterfaces_RCW() + { + D2D1ResourceTextureManager resourceTextureManager = new( + extents: stackalloc uint[] { 64 }, + bufferPrecision: D2D1BufferPrecision.UInt8Normalized, + channelDepth: D2D1ChannelDepth.Four, + filter: D2D1Filter.MinLinearMagMipPoint, + extendModes: stackalloc D2D1ExtendMode[] { D2D1ExtendMode.Clamp }); + + using ComPtr unknown = default; + using ComPtr resourceTextureManager2 = default; + using ComPtr resourceTextureManagerInternal = default; + + Guid uuidOfIUnknown = typeof(IUnknown).GUID; + Guid uuidOfResourceTextureManager = new("3C4FC7E4-A419-46CA-B5F6-66EB4FF18D64"); + Guid uuidOfResourceTextureManagerInternal = new("5CBB1024-8EA1-4689-81BF-8AD190B5EF5D"); + + // The object implements IUnknown and the two resource texture manager interfaces + Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)resourceTextureManager).GetInterface(ref uuidOfIUnknown, out *(IntPtr*)unknown.GetAddressOf())); + Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)resourceTextureManager).GetInterface(ref uuidOfResourceTextureManager, out *(IntPtr*)resourceTextureManager2.GetAddressOf())); + Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)resourceTextureManager).GetInterface(ref uuidOfResourceTextureManagerInternal, out *(IntPtr*)resourceTextureManagerInternal.GetAddressOf())); + + Assert.IsTrue(unknown.Get() is not null); + Assert.IsTrue(resourceTextureManager2.Get() is not null); + Assert.IsTrue(resourceTextureManagerInternal.Get() is not null); + + using ComPtr garbage = default; + + Guid uuidOfGarbage = Guid.NewGuid(); + + // Any other random QueryInterface should fail + Assert.AreEqual(CustomQueryInterfaceResult.Failed, ((ICustomQueryInterface)resourceTextureManager).GetInterface(ref uuidOfGarbage, out *(IntPtr*)garbage.GetAddressOf())); + + Assert.IsTrue(garbage.Get() is null); + } + + [TestMethod] + public unsafe void LoadPixelsFromResourceTexture2D_CreateAfterGettingEffectContext() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(default(IndexFrom2DResourceTextureShader), d2D1Effect.Get()); + + using ComPtr resourceTextureManager = default; + + D2D1ResourceTextureManager.Create((void**)resourceTextureManager.GetAddressOf()); + + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager.Get(), 0); + + string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; + string expectedPath = Path.Combine(assemblyPath, "Assets", "Landscape.png"); + + using Image expected = Image.Load(expectedPath); + + if (!expected.DangerousTryGetSinglePixelMemory(out Memory pixels)) + { + Assert.Inconclusive(); + } + + D2D1ResourceTextureManager.Initialize( + resourceTextureManager: resourceTextureManager.Get(), + resourceId: Guid.NewGuid(), + extents: stackalloc[] { (uint)expected.Width, (uint)expected.Height }, + bufferPrecision: D2D1BufferPrecision.UInt8Normalized, + channelDepth: D2D1ChannelDepth.Four, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp }, + data: MemoryMarshal.AsBytes(pixels.Span), + strides: stackalloc[] { (uint)(sizeof(Rgba32) * expected.Width) }); + + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)expected.Width, (uint)expected.Height); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + string destinationPath = Path.Combine(assemblyPath, "temp", "IndexedFromResourceTexture2D_After.png"); + + _ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!); + + ImageHelper.SaveBitmapToFile(destinationPath, (uint)expected.Width, (uint)expected.Height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + + TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); + } + + [TestMethod] + public unsafe void LoadPixelsFromResourceTexture2D_CreateBeforeGettingEffectContext() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(default(IndexFrom2DResourceTextureShader), d2D1Effect.Get()); + + using ComPtr resourceTextureManager = default; + + D2D1ResourceTextureManager.Create((void**)resourceTextureManager.GetAddressOf()); + + string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; + string expectedPath = Path.Combine(assemblyPath, "Assets", "Landscape.png"); + + using Image expected = Image.Load(expectedPath); + + if (!expected.DangerousTryGetSinglePixelMemory(out Memory pixels)) + { + Assert.Inconclusive(); + } + + D2D1ResourceTextureManager.Initialize( + resourceTextureManager: resourceTextureManager.Get(), + resourceId: Guid.NewGuid(), + extents: stackalloc[] { (uint)expected.Width, (uint)expected.Height }, + bufferPrecision: D2D1BufferPrecision.UInt8Normalized, + channelDepth: D2D1ChannelDepth.Four, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp }, + data: MemoryMarshal.AsBytes(pixels.Span), + strides: stackalloc[] { (uint)(sizeof(Rgba32) * expected.Width) }); + + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager.Get(), 0); + + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)expected.Width, (uint)expected.Height); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + string destinationPath = Path.Combine(assemblyPath, "temp", "IndexedFromResourceTexture2D_Before.png"); + + _ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!); + + ImageHelper.SaveBitmapToFile(destinationPath, (uint)expected.Width, (uint)expected.Height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + + TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); + } + + [TestMethod] + public unsafe void LoadPixelsFromResourceTexture2D_CreateBeforeGettingEffectContext_RCW() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(default(IndexFrom2DResourceTextureShader), d2D1Effect.Get()); + + string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; + string expectedPath = Path.Combine(assemblyPath, "Assets", "Landscape.png"); + + using Image expected = Image.Load(expectedPath); + + if (!expected.DangerousTryGetSinglePixelMemory(out Memory pixels)) + { + Assert.Inconclusive(); + } + + D2D1ResourceTextureManager resourceTextureManager = new( + resourceId: Guid.NewGuid(), + extents: stackalloc[] { (uint)expected.Width, (uint)expected.Height }, + bufferPrecision: D2D1BufferPrecision.UInt8Normalized, + channelDepth: D2D1ChannelDepth.Four, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp }, + data: MemoryMarshal.AsBytes(pixels.Span), + strides: stackalloc[] { (uint)(sizeof(Rgba32) * expected.Width) }); + + using ComPtr unknown = default; + + Guid uuidOfIUnknown = typeof(IUnknown).GUID; + + Assert.AreEqual(CustomQueryInterfaceResult.Handled, ((ICustomQueryInterface)resourceTextureManager).GetInterface(ref uuidOfIUnknown, out *(IntPtr*)unknown.GetAddressOf())); + + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), unknown.Get(), 0); + + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)expected.Width, (uint)expected.Height); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + string destinationPath = Path.Combine(assemblyPath, "temp", "IndexedFromResourceTexture2D_Before.png"); + + _ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!); + + ImageHelper.SaveBitmapToFile(destinationPath, (uint)expected.Width, (uint)expected.Height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + + TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); + } + + [D2DInputCount(0)] + [D2DRequiresScenePosition] + private partial struct IndexFrom2DResourceTextureShader : ID2D1PixelShader + { + [D2DResourceTextureIndex(0)] + private D2D1ResourceTexture2D source; + + public float4 Execute() + { + int2 xy = (int2)D2D.GetScenePosition().XY; + + return this.source[xy]; + } + } + + [TestMethod] + public unsafe void LoadPixelsFromResourceTexture3D() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; + string expectedPath = Path.Combine(assemblyPath, "Assets", "WallpapersStack.png"); + + using Image expected = Image.Load(expectedPath); + + if (!expected.DangerousTryGetSinglePixelMemory(out Memory pixels)) + { + Assert.Inconclusive(); + } + + IndexFrom3DResourceTextureShader shader = new(expected.Height / 4); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + + using ComPtr resourceTextureManager = default; + + D2D1ResourceTextureManager.Create((void**)resourceTextureManager.GetAddressOf()); + + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager.Get(), 0); + + D2D1ResourceTextureManager.Initialize( + resourceTextureManager: resourceTextureManager.Get(), + resourceId: Guid.NewGuid(), + extents: stackalloc[] { (uint)expected.Width, (uint)(expected.Height / 4), 4u }, + bufferPrecision: D2D1BufferPrecision.UInt8Normalized, + channelDepth: D2D1ChannelDepth.Four, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp }, + data: MemoryMarshal.AsBytes(pixels.Span), + strides: stackalloc[] { (uint)(sizeof(Rgba32) * expected.Width), (uint)(sizeof(Rgba32) * expected.Width * (expected.Height / 4)) }); + + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)expected.Width, (uint)expected.Height); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + string destinationPath = Path.Combine(assemblyPath, "temp", "IndexedFromResourceTexture3D.png"); + + _ = Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)!); + + ImageHelper.SaveBitmapToFile(destinationPath, (uint)expected.Width, (uint)expected.Height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + + TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); + } + + [D2DInputCount(0)] + [D2DRequiresScenePosition] + [AutoConstructor] + private partial struct IndexFrom3DResourceTextureShader : ID2D1PixelShader + { + private int height; + + [D2DResourceTextureIndex(0)] + private D2D1ResourceTexture3D source; + + public float4 Execute() + { + int2 xy = (int2)D2D.GetScenePosition().XY; + + int x = xy.X; + int y = (int)((uint)xy.Y % (uint)height); + int z = (int)((uint)xy.Y / (uint)height); + + return this.source[x, y, z]; + } + } + + [TestMethod] + [DataRow(128, 0, 26)] + [DataRow(128, 0, 67)] + [DataRow(128, 0, 128)] + [DataRow(128, 32, 64)] + [DataRow(1024, 311, 489)] + [DataRow(1024, 907, 117)] + public unsafe void UpdateResourceTexture1D(int width, int startOffset, int updateLength) + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + CopyFromResourceTexture1DShader shader = new(width); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + + byte[] texture = new byte[width]; + + D2D1ResourceTextureManager resourceTextureManager = new( + extents: stackalloc[] { (uint)width }, + bufferPrecision: D2D1BufferPrecision.UInt8Normalized, + channelDepth: D2D1ChannelDepth.One, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp }, + data: texture, + strides: null); + + byte[] data = RandomNumberGenerator.GetBytes(updateLength); + + resourceTextureManager.Update( + minimumExtents: stackalloc uint[] { (uint)startOffset }, + maximimumExtents: stackalloc uint[] { (uint)(startOffset + updateLength) }, + strides: ReadOnlySpan.Empty, + data: data); + + data.CopyTo(texture.AsSpan(startOffset)); + + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, 0); + + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)width, 1); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + byte[] resultingBytes = new byte[width]; + int i = 0; + + foreach (Bgra32 pixel in new ReadOnlySpan(d2D1MappedRect.bits, width)) + { + resultingBytes[i++] = pixel.B; + } + + Assert.IsTrue(texture.AsSpan().SequenceEqual(resultingBytes)); + } + + [D2DInputCount(0)] + [D2DRequiresScenePosition] + [AutoConstructor] + private partial struct CopyFromResourceTexture1DShader : ID2D1PixelShader + { + private int width; + + [D2DResourceTextureIndex(0)] + private D2D1ResourceTexture1D source; + + public float4 Execute() + { + int2 xy = (int2)D2D.GetScenePosition().XY; + + return this.source[xy.X]; + } + } + + [TestMethod] + [DataRow(64, 64, 0, 0, 64, 64)] + [DataRow(64, 64, 32, 32, 32, 32)] + [DataRow(64, 64, 12, 33, 43, 22)] + [DataRow(512, 768, 245, 111, 255, 461)] + [DataRow(1024, 2048, 11, 899, 512, 342)] + public unsafe void UpdateResourceTexture2D( + int width, + int height, + int startOffsetX, + int startOffsetY, + int updateLengthX, + int updateLengthY) + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + CopyFromResourceTexture2DShader shader = new(width, height); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + + byte[] texture = new byte[width * height]; + + D2D1ResourceTextureManager resourceTextureManager = new( + extents: stackalloc[] { (uint)width, (uint)height }, + bufferPrecision: D2D1BufferPrecision.UInt8Normalized, + channelDepth: D2D1ChannelDepth.One, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp }, + data: texture, + strides: stackalloc uint[] { (uint)width }); + + byte[] data = RandomNumberGenerator.GetBytes(updateLengthX * updateLengthY); + + resourceTextureManager.Update( + minimumExtents: stackalloc uint[] { (uint)startOffsetX, (uint)startOffsetY }, + maximimumExtents: stackalloc uint[] { (uint)(startOffsetX + updateLengthX), (uint)(startOffsetY + updateLengthY) }, + strides: stackalloc uint[] { (uint)updateLengthX }, + data: data); + + for (int y = 0; y < updateLengthY; y++) + { + ReadOnlySpan source = data.AsSpan(y * updateLengthX, updateLengthX); + Span destination = texture.AsSpan(startOffsetY * width + y * width + startOffsetX, updateLengthX); + + source.CopyTo(destination); + } + + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, 0); + + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)width, (uint)height); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + byte[] resultingBytes = new byte[width * height]; + int i = 0; + + for (int y = 0; y < height; y++) + { + foreach (Bgra32 pixel in new ReadOnlySpan(d2D1MappedRect.bits + d2D1MappedRect.pitch * y, width)) + { + resultingBytes[i++] = pixel.B; + } + } + + Assert.IsTrue(texture.AsSpan().SequenceEqual(resultingBytes)); + } + + [D2DInputCount(0)] + [D2DRequiresScenePosition] + [AutoConstructor] + private partial struct CopyFromResourceTexture2DShader : ID2D1PixelShader + { + private int width; + private int height; + + [D2DResourceTextureIndex(0)] + private D2D1ResourceTexture2D source; + + public float4 Execute() + { + int2 xy = (int2)D2D.GetScenePosition().XY; + + return this.source[xy]; + } + } + + [TestMethod] + [DataRow(64, 64, 3, 0, 0, 0, 64, 64, 3)] + [DataRow(64, 64, 3, 10, 22, 1, 44, 33, 1)] + [DataRow(64, 64, 3, 10, 22, 1, 44, 33, 2)] + [DataRow(64, 64, 3, 10, 22, 0, 44, 33, 2)] + [DataRow(512, 512, 6, 245, 0, 2, 188, 1, 4)] + [DataRow(512, 512, 6, 245, 0, 2, 188, 467, 3)] + [DataRow(512, 512, 6, 245, 113, 1, 256, 322, 2)] + public unsafe void UpdateResourceTexture3D( + int width, + int height, + int depth, + int startOffsetX, + int startOffsetY, + int startOffsetZ, + int updateLengthX, + int updateLengthY, + int updateLengthZ) + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + CopyFromResourceTexture3DShader shader = new(width, height, depth); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); + + byte[] texture = new byte[width * height * depth]; + + D2D1ResourceTextureManager resourceTextureManager = new( + extents: stackalloc[] { (uint)width, (uint)height, (uint)depth }, + bufferPrecision: D2D1BufferPrecision.UInt8Normalized, + channelDepth: D2D1ChannelDepth.One, + filter: D2D1Filter.MinMagMipPoint, + extendModes: stackalloc[] { D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp, D2D1ExtendMode.Clamp }, + data: texture, + strides: stackalloc uint[] { (uint)width, (uint)(width * height) }); + + byte[] data = RandomNumberGenerator.GetBytes(updateLengthX * updateLengthY * updateLengthZ); + + resourceTextureManager.Update( + minimumExtents: stackalloc uint[] { (uint)startOffsetX, (uint)startOffsetY, (uint)startOffsetZ }, + maximimumExtents: stackalloc uint[] { (uint)(startOffsetX + updateLengthX), (uint)(startOffsetY + updateLengthY), (uint)(startOffsetZ + updateLengthZ) }, + strides: stackalloc uint[] { (uint)updateLengthX, (uint)(updateLengthX * updateLengthY) }, + data: data); + + for (int z = 0; z < updateLengthZ; z++) + { + for (int y = 0; y < updateLengthY; y++) + { + ReadOnlySpan source = data.AsSpan(z * updateLengthX * updateLengthY + y * updateLengthX, updateLengthX); + Span destination = texture.AsSpan((startOffsetZ + z) * (width * height) + (startOffsetY + y) * width + startOffsetX, updateLengthX); + + source.CopyTo(destination); + } + } + + D2D1PixelShaderEffect.SetResourceTextureManagerForD2D1Effect(d2D1Effect.Get(), resourceTextureManager, 0); + + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), (uint)width, (uint)(height * depth)); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + + using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); + + byte[] resultingBytes = new byte[width * height * depth]; + int i = 0; + + for (int y = 0; y < height * depth; y++) + { + foreach (Bgra32 pixel in new ReadOnlySpan(d2D1MappedRect.bits + d2D1MappedRect.pitch * y, width)) + { + resultingBytes[i++] = pixel.B; + } + } + + Assert.IsTrue(texture.AsSpan().SequenceEqual(resultingBytes)); + } + + [D2DInputCount(0)] + [D2DRequiresScenePosition] + [AutoConstructor] + private partial struct CopyFromResourceTexture3DShader : ID2D1PixelShader + { + private int width; + private int height; + private int depth; + + [D2DResourceTextureIndex(0)] + private D2D1ResourceTexture3D source; + + public float4 Execute() + { + int2 xy = (int2)D2D.GetScenePosition().XY; + + int x = xy.X; + int y = (int)((uint)xy.Y % (uint)this.height); + int z = (int)((uint)xy.Y / (uint)this.height); + + return this.source[x, y, z]; + } + } + + [TestMethod] + [ExpectedException(typeof(Win32Exception))] + public unsafe void NullResourceTexture_DrawImageFails() + { + using ComPtr d2D1Factory2 = D2D1Helper.CreateD2D1Factory2(); + using ComPtr d2D1Device = D2D1Helper.CreateD2D1Device(d2D1Factory2.Get()); + using ComPtr d2D1DeviceContext = D2D1Helper.CreateD2D1DeviceContext(d2D1Device.Get()); + + D2D1PixelShaderEffect.RegisterForD2D1Factory1(d2D1Factory2.Get(), null, out _); + + using ComPtr d2D1Effect = default; + + D2D1PixelShaderEffect.CreateFromD2D1DeviceContext(d2D1DeviceContext.Get(), (void**)d2D1Effect.GetAddressOf()); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(default(NullResourceTextureShader), d2D1Effect.Get()); + + using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), 128, 128); + + D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); + } + + [D2DInputCount(0)] + [D2DRequiresScenePosition] + private partial struct NullResourceTextureShader : ID2D1PixelShader + { + [D2DResourceTextureIndex(0)] + private D2D1ResourceTexture2D source; + + public float4 Execute() + { + return source[0, 0]; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs b/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs index 02a5da36..8a25a156 100644 --- a/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/EndToEndTests.cs @@ -1,10 +1,5 @@ -using System; -using System.IO; -using System.Reflection; -using System.Runtime.CompilerServices; -using ComputeSharp.D2D1.Tests.Effects; +using ComputeSharp.D2D1.Tests.Effects; using ComputeSharp.D2D1.Tests.Helpers; -using ComputeSharp.Tests.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; using SixLabors.ImageSharp; @@ -23,19 +18,19 @@ public class EndToEndTests [TestMethod] public unsafe void Invert() { - RunAndCompareShader(new InvertEffect(), null, "Landscape.png", "Landscape_Inverted.png"); + D2D1TestRunner.RunAndCompareShader(new InvertEffect(), null, "Landscape.png", "Landscape_Inverted.png"); } [TestMethod] public unsafe void InvertWithThreshold() { - RunAndCompareShader(new InvertWithThresholdEffect(1), null, "Landscape.png", "Landscape_Inverted.png"); + D2D1TestRunner.RunAndCompareShader(new InvertWithThresholdEffect(1), null, "Landscape.png", "Landscape_Inverted.png"); } [TestMethod] public unsafe void Pixelate() { - RunAndCompareShader( + D2D1TestRunner.RunAndCompareShader( new PixelateEffect.Shader(new PixelateEffect.Shader.Constants(1280, 840, 16)), static () => new PixelateEffect(), "Landscape.png", @@ -45,88 +40,12 @@ public class EndToEndTests [TestMethod] public unsafe void ZonePlate() { - RunAndCompareShader(new ZonePlateEffect(1280, 720, 800), null, 1280, 720, "ZonePlate.png"); + D2D1TestRunner.RunAndCompareShader(new ZonePlateEffect(1280, 720, 800), null, 1280, 720, "ZonePlate.png"); } [TestMethod] public unsafe void CheckerboardClip() { - RunAndCompareShader(new CheckerboardClipEffect(1280, 840, 32), null, "Landscape.png", "Landscape_CheckerboardClip.png"); - } - - /// - /// Executes a pixel shader and compares the expected results. - /// - /// The type of pixel shader to run. - /// A custom factory for the effect. - /// The name of the source image. - /// The name of the expected result image. - /// The name of the destination image to save results to. - /// The shader to run. - private static void RunAndCompareShader( - in T shader, - Func>? transformMapperFactory, - string originalFileName, - string expectedFileName, - [CallerMemberName] string destinationFileName = "") - where T : unmanaged, ID2D1PixelShader - { - string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); - string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp"); - - _ = Directory.CreateDirectory(temporaryPath); - - string originalPath = Path.Combine(assetsPath, originalFileName); - string expectedPath = Path.Combine(assetsPath, expectedFileName); - string destinationPath = Path.Combine(temporaryPath, $"{destinationFileName}.png"); - - // Run the shader - D2D1TestRunner.ExecutePixelShaderAndCompareResults( - in shader, - transformMapperFactory, - originalPath, - destinationPath); - - // Compare the results - TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); - } - - /// - /// Executes a pixel shader and compares the expected results. - /// - /// The type of pixel shader to run. - /// A custom factory for the effect. - /// The resulting width. - /// The resulting height. - /// The name of the expected result image. - /// The name of the destination image to save results to. - /// The shader to run. - private static void RunAndCompareShader( - in T shader, - Func>? transformMapperFactory, - int width, - int height, - string expectedFileName, - [CallerMemberName] string destinationFileName = "") - where T : unmanaged, ID2D1PixelShader - { - string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); - string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp"); - - _ = Directory.CreateDirectory(temporaryPath); - - string expectedPath = Path.Combine(assetsPath, expectedFileName); - string destinationPath = Path.Combine(temporaryPath, $"{destinationFileName}.png"); - - // Run the shader - D2D1TestRunner.ExecutePixelShaderAndCompareResults( - in shader, - transformMapperFactory, - width, - height, - destinationPath); - - // Compare the results - TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); + D2D1TestRunner.RunAndCompareShader(new CheckerboardClipEffect(1280, 840, 32), null, "Landscape.png", "Landscape_CheckerboardClip.png"); } } \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1Helper.cs b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1Helper.cs index 5a6b2ded..0195201e 100644 --- a/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1Helper.cs +++ b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1Helper.cs @@ -1,4 +1,5 @@ -using ComputeSharp.D2D1.Tests.Extensions; +using System; +using ComputeSharp.D2D1.Tests.Extensions; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -100,17 +101,40 @@ internal static class D2D1Helper /// Creates an instance. /// /// The input instance to use to create the bitmap source. - /// The input to use to create the bitmap source. + /// The loaded pixel data. + /// The width of the bitmap. + /// The height of the bitmap. /// The input to set the source for. /// A new instance. - public static unsafe ComPtr CreateD2D1BitmapAndSetAsSource(ID2D1DeviceContext* d2D1DeviceContext, IWICBitmap* wicBitmap, ID2D1Effect* d2D1Effect) + public static unsafe ComPtr CreateD2D1BitmapAndSetAsSource( + ID2D1DeviceContext* d2D1DeviceContext, + ReadOnlyMemory pixels, + uint width, + uint height, + ID2D1Effect* d2D1Effect) { using ComPtr d2D1BitmapSource = default; - // Create a source D2D1 bitmap from the WIC bitmap - d2D1DeviceContext->CreateBitmapFromWicBitmap( - wicBitmapSource: (IWICBitmapSource*)wicBitmap, - bitmap: d2D1BitmapSource.GetAddressOf()).Assert(); + D2D_SIZE_U d2DSize = default; + d2DSize.width = width; + d2DSize.height = height; + + D2D1_BITMAP_PROPERTIES d2DBitmapProperties = default; + d2DBitmapProperties.pixelFormat.format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM; + d2DBitmapProperties.pixelFormat.alphaMode = D2D1_ALPHA_MODE.D2D1_ALPHA_MODE_PREMULTIPLIED; + d2DBitmapProperties.dpiX = 96; + d2DBitmapProperties.dpiY = 96; + + fixed (byte* p = pixels.Span) + { + // Create a source D2D1 bitmap from the image data + d2D1DeviceContext->CreateBitmap( + size: d2DSize, + srcData: p, + pitch: width * 4, + bitmapProperties: &d2DBitmapProperties, + bitmap: d2D1BitmapSource.GetAddressOf()).Assert(); + } d2D1Effect->SetInput(0, (ID2D1Image*)d2D1BitmapSource.Get()); diff --git a/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs index 65de58db..dfe1d5e9 100644 --- a/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs +++ b/tests/ComputeSharp.D2D1.Tests/Helpers/D2D1TestRunner.cs @@ -1,5 +1,9 @@ using System; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; using ComputeSharp.D2D1.Interop; +using ComputeSharp.Tests.Helpers; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; @@ -10,6 +14,82 @@ namespace ComputeSharp.D2D1.Tests.Helpers; /// internal static class D2D1TestRunner { + /// + /// Executes a pixel shader and compares the expected results. + /// + /// The type of pixel shader to run. + /// A custom factory for the effect. + /// The name of the source image. + /// The name of the expected result image. + /// The name of the destination image to save results to. + /// The shader to run. + public static void RunAndCompareShader( + in T shader, + Func>? transformMapperFactory, + string originalFileName, + string expectedFileName, + [CallerMemberName] string destinationFileName = "") + where T : unmanaged, ID2D1PixelShader + { + string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); + string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp"); + + _ = Directory.CreateDirectory(temporaryPath); + + string originalPath = Path.Combine(assetsPath, originalFileName); + string expectedPath = Path.Combine(assetsPath, expectedFileName); + string destinationPath = Path.Combine(temporaryPath, $"{destinationFileName}.png"); + + // Run the shader + ExecutePixelShaderAndSaveToFile( + in shader, + transformMapperFactory, + originalPath, + destinationPath); + + // Compare the results + TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); + } + + /// + /// Executes a pixel shader and compares the expected results. + /// + /// The type of pixel shader to run. + /// A custom factory for the effect. + /// The resulting width. + /// The resulting height. + /// The name of the expected result image. + /// The name of the destination image to save results to. + /// The shader to run. + public static void RunAndCompareShader( + in T shader, + Func>? transformMapperFactory, + int width, + int height, + string expectedFileName, + [CallerMemberName] string destinationFileName = "") + where T : unmanaged, ID2D1PixelShader + { + string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); + string temporaryPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "temp"); + + _ = Directory.CreateDirectory(temporaryPath); + + string expectedPath = Path.Combine(assetsPath, expectedFileName); + string destinationPath = Path.Combine(temporaryPath, $"{destinationFileName}.png"); + + // Run the shader + ExecutePixelShaderAndSaveToFile( + in shader, + transformMapperFactory, + width, + height, + destinationPath); + + // Compare the results + TolerantImageComparer.AssertEqual(destinationPath, expectedPath, 0.00001f); + } + /// /// Executes a pixel shader to produce an image. /// @@ -18,7 +98,7 @@ internal static class D2D1TestRunner /// A custom factory for the effect. /// The source path for the image to run the shader on. /// The destination path for the result. - public static unsafe void ExecutePixelShaderAndCompareResults( + public static unsafe void ExecutePixelShaderAndSaveToFile( in T shader, Func>? transformMapperFactory, string sourcePath, @@ -37,8 +117,9 @@ internal static class D2D1TestRunner D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(in shader, d2D1Effect.Get()); - using ComPtr wicBitmap = WICHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height); - using ComPtr d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), wicBitmap.Get(), d2D1Effect.Get()); + ReadOnlyMemory pixels = ImageHelper.LoadBitmapFromFile(sourcePath, out uint width, out uint height); + + using ComPtr d2D1BitmapSource = D2D1Helper.CreateD2D1BitmapAndSetAsSource(d2D1DeviceContext.Get(), pixels, width, height, d2D1Effect.Get()); using ComPtr d2D1BitmapTarget = D2D1Helper.CreateD2D1BitmapAndSetAsTarget(d2D1DeviceContext.Get(), width, height); D2D1Helper.DrawEffect(d2D1DeviceContext.Get(), d2D1Effect.Get()); @@ -46,7 +127,7 @@ internal static class D2D1TestRunner using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); // Save the image - WICHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + ImageHelper.SaveBitmapToFile(destinationPath, width, height, d2D1MappedRect.pitch, d2D1MappedRect.bits); } /// @@ -58,7 +139,7 @@ internal static class D2D1TestRunner /// The resulting height. /// A custom factory for the effect. /// The destination path for the result. - public static unsafe void ExecutePixelShaderAndCompareResults( + public static unsafe void ExecutePixelShaderAndSaveToFile( in T shader, Func>? transformMapperFactory, int width, @@ -85,6 +166,6 @@ internal static class D2D1TestRunner using ComPtr d2D1Bitmap1Buffer = D2D1Helper.CreateD2D1Bitmap1Buffer(d2D1DeviceContext.Get(), d2D1BitmapTarget.Get(), out D2D1_MAPPED_RECT d2D1MappedRect); // Save the image - WICHelper.SaveBitmapToFile(destinationPath, (uint)width, (uint)height, d2D1MappedRect.pitch, d2D1MappedRect.bits); + ImageHelper.SaveBitmapToFile(destinationPath, (uint)width, (uint)height, d2D1MappedRect.pitch, d2D1MappedRect.bits); } } diff --git a/tests/ComputeSharp.D2D1.Tests/Helpers/ImageHelper.cs b/tests/ComputeSharp.D2D1.Tests/Helpers/ImageHelper.cs new file mode 100644 index 00000000..d5489726 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Tests/Helpers/ImageHelper.cs @@ -0,0 +1,63 @@ +using System; +using System.Buffers; +using System.Runtime.InteropServices; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; + +namespace ComputeSharp.D2D1.Tests.Helpers; + +/// +/// A with helpers to load and save images. +/// +internal static class ImageHelper +{ + /// + /// Loads a instance from a given path. + /// + /// The path to load the image from. + /// The resulting image width. + /// The resulting image height. + /// The resulting instance. + public static unsafe ReadOnlyMemory LoadBitmapFromFile(string filename, out uint width, out uint height) + { + using Image image = Image.Load(filename); + + width = (uint)image.Width; + height = (uint)image.Height; + + if (!image.DangerousTryGetSinglePixelMemory(out Memory memory)) + { + Assert.Inconclusive(); + } + + return MemoryMarshal.AsBytes(memory.Span).ToArray(); + } + + /// + /// Saves a given image buffer to a target path. + /// + /// The path to save the image to. + /// The image width. + /// The image height. + /// The image stride in bytes. + /// The image pixel buffer. + public static unsafe void SaveBitmapToFile(string filename, uint width, uint height, uint strideInBytes, byte* buffer) + { + byte[] pixelData = ArrayPool.Shared.Rent((int)width * (int)height * sizeof(Bgra32)); + + for (int i = 0; i < (int)height; i++) + { + ReadOnlySpan source = new(buffer + i * (int)strideInBytes, (int)width * sizeof(Bgra32)); + + source.CopyTo(pixelData.AsSpan(i * (int)width * sizeof(Bgra32))); + } + + using (Image image = Image.WrapMemory(pixelData, (int)width, (int)height)) + { + image.Save(filename); + } + + ArrayPool.Shared.Return(pixelData); + } +} diff --git a/tests/ComputeSharp.D2D1.Tests/Helpers/WICHelper.cs b/tests/ComputeSharp.D2D1.Tests/Helpers/WICHelper.cs deleted file mode 100644 index 34b2e0af..00000000 --- a/tests/ComputeSharp.D2D1.Tests/Helpers/WICHelper.cs +++ /dev/null @@ -1,203 +0,0 @@ -using System; -using System.Runtime.CompilerServices; -using ComputeSharp.D2D1.Tests.Extensions; -using TerraFX.Interop.Windows; - -namespace ComputeSharp.D2D1.Tests.Helpers; - -/// -/// A that uses the WIC APIs to load and decode images. -/// -internal static class WICHelper -{ - /// - /// Loads an instance from a given path. - /// - /// The path to load the image from. - /// The resulting image width. - /// The resulting image height. - /// The resulting instance. - public static unsafe ComPtr LoadBitmapFromFile(string filename, out uint width, out uint height) - { - using ComPtr wicImagingFactory2 = default; - - // Create a Windows Imaging Component (WIC) factory - Windows.CoCreateInstance( - rclsid: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_WICImagingFactory2)), - pUnkOuter: null, - dwClsContext: (uint)CLSCTX.CLSCTX_INPROC_SERVER, - riid: Windows.__uuidof(), - ppv: (void**)wicImagingFactory2.GetAddressOf()).Assert(); - - using ComPtr wicBitmapDecoder = default; - - // Get the bitmap decoder for the target file - fixed (char* p = filename) - { - wicImagingFactory2.Get()->CreateDecoderFromFilename( - wzFilename: (ushort*)p, - pguidVendor: null, - dwDesiredAccess: Windows.GENERIC_READ, - metadataOptions: WICDecodeOptions.WICDecodeMetadataCacheOnDemand, - ppIDecoder: 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(); - - fixed (uint* widthPtr = &width) - fixed (uint* heightPtr = &height) - { - // Extract the image size info - wicBitmapFrameDecode.Get()->GetSize(widthPtr, heightPtr).Assert(); - } - - Guid wicTargetPixelFormatGuid = GUID.GUID_WICPixelFormat32bppPBGRA; - Guid wicActualPixelFormatGuid; - - // Get the current and target pixel format info - wicBitmapFrameDecode.Get()->GetPixelFormat(&wicActualPixelFormatGuid).Assert(); - - using ComPtr wicBitmap = default; - - // Create the target bitmap - wicImagingFactory2.Get()->CreateBitmap( - uiWidth: width, - uiHeight: height, - pixelFormat: &wicTargetPixelFormatGuid, - option: WICBitmapCreateCacheOption.WICBitmapCacheOnLoad, - ppIBitmap: wicBitmap.GetAddressOf()).Assert(); - - WICRect wicRect; - wicRect.X = 0; - wicRect.Y = 0; - wicRect.Width = (int)width; - wicRect.Height = (int)height; - - using (ComPtr wicBitmapLock = default) - { - // Lock the bitmap - wicBitmap.Get()->Lock( - prcLock: &wicRect, - flags: (uint)WICBitmapLockFlags.WICBitmapLockWrite, - ppILock: wicBitmapLock.GetAddressOf()).Assert(); - - uint wicBitmapStride; - - // Get the stride - wicBitmapLock.Get()->GetStride(&wicBitmapStride).Assert(); - - uint wicBitmapSize; - byte* wicBitmapPointer; - - // Get the bitmap size and pointer - wicBitmapLock.Get()->GetDataPointer(&wicBitmapSize, &wicBitmapPointer).Assert(); - - // Check if a pixel format conversion is needed - if (wicTargetPixelFormatGuid == wicActualPixelFormatGuid) - { - // No conversion is needed, just copy the pixels directly - wicBitmapFrameDecode.Get()->CopyPixels( - prc: &wicRect, - cbStride: wicBitmapStride, - cbBufferSize: wicBitmapSize, - pbBuffer: wicBitmapPointer).Assert(); - } - else - { - using ComPtr wicFormatConverter = default; - - // Create a format converter - wicImagingFactory2.Get()->CreateFormatConverter(wicFormatConverter.GetAddressOf()).Assert(); - - // Get a format converter to decode the pixel data - wicFormatConverter.Get()->Initialize( - pISource: (IWICBitmapSource*)wicBitmapFrameDecode.Get(), - dstFormat: &wicTargetPixelFormatGuid, - dither: WICBitmapDitherType.WICBitmapDitherTypeNone, - pIPalette: null, - alphaThresholdPercent: 0, - paletteTranslate: WICBitmapPaletteType.WICBitmapPaletteTypeCustom).Assert(); - - // Decode the pixel data into the upload buffer - wicFormatConverter.Get()->CopyPixels( - prc: &wicRect, - cbStride: wicBitmapStride, - cbBufferSize: wicBitmapSize, - pbBuffer: wicBitmapPointer).Assert(); - } - } - - return wicBitmap.Move(); - } - - /// - /// Saves a given image buffer to a target path. - /// - /// The path to save the image to. - /// The image width. - /// The image height. - /// The image stride in bytes. - /// The image pixel buffer. - public static unsafe void SaveBitmapToFile(string filename, uint width, uint height, uint strideInBytes, byte* buffer) - { - using ComPtr wicImagingFactory2 = default; - - // Create a Windows Imaging Component (WIC) factory - Windows.CoCreateInstance( - rclsid: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in CLSID.CLSID_WICImagingFactory2)), - pUnkOuter: null, - dwClsContext: (uint)CLSCTX.CLSCTX_INPROC_SERVER, - riid: Windows.__uuidof(), - ppv: (void**)wicImagingFactory2.GetAddressOf()).Assert(); - - using ComPtr wicBitmapEncoder = default; - - // Create the image encoder - wicImagingFactory2.Get()->CreateEncoder( - guidContainerFormat: (Guid*)Unsafe.AsPointer(ref Unsafe.AsRef(in GUID.GUID_ContainerFormatPng)), - pguidVendor: null, - ppIEncoder: wicBitmapEncoder.GetAddressOf()).Assert(); - - using ComPtr wicStream = default; - - // Create and initialize a stream to the target file - wicImagingFactory2.Get()->CreateStream(wicStream.GetAddressOf()).Assert(); - - fixed (char* p = filename) - { - // Initialize the stream to the target file - wicStream.Get()->InitializeFromFilename((ushort*)p, Windows.GENERIC_WRITE); - } - - // Initialize the encoder - wicBitmapEncoder.Get()->Initialize( - pIStream: (IStream*)wicStream.Get(), - cacheOption: WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache).Assert(); - - using ComPtr wicBitmapFrameEncode = default; - - // Create the image frame and initialize it - wicBitmapEncoder.Get()->CreateNewFrame(wicBitmapFrameEncode.GetAddressOf(), null).Assert(); - - Guid wicTargetPixelFormatGuid = GUID.GUID_WICPixelFormat32bppPBGRA; - - // Set the encoding properties - wicBitmapFrameEncode.Get()->Initialize(null).Assert(); - wicBitmapFrameEncode.Get()->SetSize(width, height).Assert(); - wicBitmapFrameEncode.Get()->SetPixelFormat(&wicTargetPixelFormatGuid).Assert(); - - // Encode the target image - wicBitmapFrameEncode.Get()->WritePixels( - lineCount: height, - cbStride: strideInBytes, - cbBufferSize: strideInBytes * height, - pbPixels: buffer).Assert(); - - // Flush the changes - wicBitmapFrameEncode.Get()->Commit(); - wicBitmapEncoder.Get()->Commit(); - } -}