diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index 35b382fa..cae3f955 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -71,7 +71,7 @@ jobs: path: artifacts\*.nupkg if-no-files-found: error - # Run all unit tests referencing the ComputeSharp project directly + # Run all unit tests referencing the ComputeSharp projects directly run-tests: needs: [build-solution] strategy: @@ -122,6 +122,32 @@ jobs: - name: Run ComputeSharp.D2D1.Tests.AssemblyLevelAttributes run: dotnet test tests\ComputeSharp.D2D1.Tests.AssemblyLevelAttributes\ComputeSharp.D2D1.Tests.AssemblyLevelAttributes.csproj -c Release -f ${{matrix.framework}} -v n -l "console;verbosity=detailed" + # Run all UWP tests (separately, as they need VS Test) + run-tests-uwp: + needs: [build-solution] + strategy: + matrix: + configuration: [Debug, Release] + runs-on: windows-2022 + steps: + - name: Git checkout + uses: actions/checkout@v3 + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.1 + + # Build the D2D1 UWP unit tests (need to restore and build separately for it to build correctly) + - name: Build ComputeSharp.D2D1.Uwp.Tests + run: > + msbuild tests\ComputeSharp.D2D1.Uwp.Tests\ComputeSharp.D2D1.Uwp.Tests.csproj -t:restore /p:Configuration=${{matrix.configuration}} /p:Platform=x64; + msbuild tests\ComputeSharp.D2D1.Uwp.Tests\ComputeSharp.D2D1.Uwp.Tests.csproj -t:build /p:Configuration=${{matrix.configuration}} /p:Platform=x64 + + # Run the D2D1 UWP unit tests with VS Test (need to use vswhere to find the VS Test runner) + - name: Run ComputeSharp.D2D1.Uwp.Tests + run: > + $vs_path = vswhere -latest -products * -requires Microsoft.VisualStudio.Workload.ManagedDesktop -requiresAny -property installationPath; + $vstest_path = join-path $vs_path 'Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe'; + & $vstest_path /Platform:x64 /framework:frameworkuap10 tests\ComputeSharp.D2D1.Uwp.Tests\bin\x64\${{matrix.configuration}}\ComputeSharp.D2D1.Uwp.Tests.build.appxrecipe + # Run all the local samples to ensure they build and run with no errors run-samples: needs: [build-solution] @@ -255,7 +281,7 @@ jobs: # Publish the packages to GitHub packages publish-nightlies-github: - needs: [run-tests, run-samples, run-samples-aot, verify-packages] + needs: [run-tests, run-tests-uwp, run-samples, run-samples-aot, verify-packages] runs-on: windows-2022 if: ${{github.event_name == 'push'}} steps: @@ -267,7 +293,7 @@ jobs: # Publish the packages to Azure DevOps publish-nightlies-azure-devops: - needs: [run-tests, run-samples, run-samples-aot, verify-packages] + needs: [run-tests, run-tests-uwp, run-samples, run-samples-aot, verify-packages] runs-on: windows-2022 if: ${{github.event_name == 'push'}} steps: diff --git a/ComputeSharp.sln b/ComputeSharp.sln index 97cfd4ee..b39cce02 100644 --- a/ComputeSharp.sln +++ b/ComputeSharp.sln @@ -150,6 +150,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Assets", "Assets", "{345F62 assets\icon_highres.png = assets\icon_highres.png EndProjectSection EndProject +Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.D2D1.UI.Tests", "tests\ComputeSharp.D2D1.UI.Tests\ComputeSharp.D2D1.UI.Tests.shproj", "{346AEB10-A4EA-427E-8578-F60915DB3053}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.D2D1.Uwp.Tests", "tests\ComputeSharp.D2D1.Uwp.Tests\ComputeSharp.D2D1.Uwp.Tests.csproj", "{4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -414,6 +418,18 @@ Global {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|ARM64.Build.0 = Release|ARM64 {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|x64.ActiveCfg = Release|x64 {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A}.Release|x64.Build.0 = Release|x64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|ARM64.Build.0 = Debug|ARM64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|x64.ActiveCfg = Debug|x64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|x64.Build.0 = Debug|x64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Debug|x64.Deploy.0 = Debug|x64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|ARM64.ActiveCfg = Release|ARM64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|ARM64.Build.0 = Release|ARM64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|ARM64.Deploy.0 = Release|ARM64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|x64.ActiveCfg = Release|x64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|x64.Build.0 = Release|x64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3}.Release|x64.Deploy.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -451,6 +467,8 @@ Global {568E7009-5C13-4153-9C94-0AC7A3E6883C} = {1A9C4108-F61A-4ABE-B5CF-F524521EAE2D} {B54B6DCA-6EAB-46A8-83D3-15154659F47F} = {1A9C4108-F61A-4ABE-B5CF-F524521EAE2D} {9EA5AE9D-C39A-4F43-B03E-0A848EA2558A} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1} + {346AEB10-A4EA-427E-8578-F60915DB3053} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC} @@ -464,6 +482,11 @@ Global src\TerraFX.Interop.Windows.Dynamic\TerraFX.Interop.Windows.Dynamic.projitems*{158f984d-cd96-4062-bd02-2268946031a0}*SharedItemsImports = 13 samples\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems*{209c95a3-fa53-431b-b688-3299ca6c29d2}*SharedItemsImports = 5 src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{314eb353-e7e3-4146-8111-685cc83ec1de}*SharedItemsImports = 5 + tests\ComputeSharp.D2D1.UI.Tests\ComputeSharp.D2D1.UI.Tests.projitems*{346aeb10-a4ea-427e-8578-f60915db3053}*SharedItemsImports = 13 + samples\ComputeSharp.SwapChain.Shaders.D2D1.Shared\ComputeSharp.SwapChain.Shaders.D2D1.Shared.projitems*{4d4bb2f6-5653-4db5-a8dd-90d58d8fe4d3}*SharedItemsImports = 4 + src\ComputeSharp.NetStandard\ComputeSharp.NetStandard.projitems*{4d4bb2f6-5653-4db5-a8dd-90d58d8fe4d3}*SharedItemsImports = 4 + src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{4d4bb2f6-5653-4db5-a8dd-90d58d8fe4d3}*SharedItemsImports = 4 + tests\ComputeSharp.D2D1.UI.Tests\ComputeSharp.D2D1.UI.Tests.projitems*{4d4bb2f6-5653-4db5-a8dd-90d58d8fe4d3}*SharedItemsImports = 4 src\TerraFX.Interop.Windows.D2D1\TerraFX.Interop.Windows.D2D1.projitems*{4d7d9ba8-a821-4b1c-9ee2-cbcf5849906e}*SharedItemsImports = 5 src\TerraFX.Interop.Windows\TerraFX.Interop.Windows.projitems*{514ff00e-bbf0-4d55-a47c-eeeb6208adce}*SharedItemsImports = 13 src\ComputeSharp.SourceGeneration\ComputeSharp.SourceGeneration.projitems*{51d5a422-d3a5-4c4d-8a6d-a048940bf279}*SharedItemsImports = 13 diff --git a/src/ComputeSharp.D2D1.UI/CanvasEffect.cs b/src/ComputeSharp.D2D1.UI/CanvasEffect.cs index efef99d5..898aa459 100644 --- a/src/ComputeSharp.D2D1.UI/CanvasEffect.cs +++ b/src/ComputeSharp.D2D1.UI/CanvasEffect.cs @@ -124,14 +124,12 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I this.canvasImage?.Dispose(); this.canvasImage = null; - this.isInvalidated = false; - } - else - { - // Otherwise, just mark the internal state as not being valid anymore. The next - // time the image is requested, the effect graph will be configured if needed. - this.isInvalidated = true; } + + // For both invalidation types, always mark the internal state as not being valid anymore. + // The next time the image is requested, the effect graph will be configured if needed. + // This matches the default value for the field (which is needed for the first realization). + this.isInvalidated = true; } } diff --git a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs index d6c49f69..a894c2f2 100644 --- a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs +++ b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ICanvasEffectFactoryNative.cs @@ -124,7 +124,7 @@ unsafe partial class PixelShaderEffect { *wrapper = null; - return E.E_INVALIDARG; + return D2DERR.D2DERR_WRONG_FACTORY; } } @@ -139,7 +139,7 @@ unsafe partial class PixelShaderEffect // Register the new wrapper for the input resource. This has to be done manually in this // case, as the effect is not being realized through the usual path from GetD2DImage. - ResourceManager.RegisterWrapper((IUnknown*)resource, this); + ResourceManager.RegisterWrapper((IUnknown*)resource, @this); // Unwrap the PixelShaderEffect and return its CCW to the caller RcwMarshaller.GetNativeObject(@this, wrapper); diff --git a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.Interop.cs b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.Interop.cs index 30546024..bc5e4f2f 100644 --- a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.Interop.cs +++ b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.Interop.cs @@ -1,3 +1,4 @@ +using System; using ComputeSharp.D2D1.Interop; #if WINDOWS_UWP using ComputeSharp.D2D1.Uwp.Extensions; @@ -92,6 +93,9 @@ unsafe partial class PixelShaderEffect } else { + // If the effect is not realized, manually ensure the transform isn't null + default(ArgumentNullException).ThrowIfNull(value); + this.transformMapper = value; } } @@ -196,7 +200,7 @@ unsafe partial class PixelShaderEffect }; // Map from D2D1_BUFFER_PRECISION to CanvasBufferPrecision, and return null for D2D1_BUFFER_PRECISION_UNKNOWN - return this.d2D1BufferPrecision switch + return d2D1BufferPrecision switch { D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM => CanvasBufferPrecision.Precision8UIntNormalized, D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB => CanvasBufferPrecision.Precision8UIntNormalizedSrgb, diff --git a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ReferenceTracking.cs b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ReferenceTracking.cs index dd5695ee..97ce8fa2 100644 --- a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ReferenceTracking.cs +++ b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.ReferenceTracking.cs @@ -1,6 +1,12 @@ using System; using ComputeSharp.Interop; using System.Runtime.CompilerServices; +#if WINDOWS_UWP +using ComputeSharp.D2D1.Uwp.Helpers; +#else +using ComputeSharp.D2D1.WinUI.Helpers; +#endif +using TerraFX.Interop.Windows; #if WINDOWS_UWP namespace ComputeSharp.D2D1.Uwp; @@ -41,15 +47,27 @@ partial class PixelShaderEffect } /// - void IReferenceTrackedObject.DangerousOnDispose() + unsafe void IReferenceTrackedObject.DangerousOnDispose() { + // When the effect is disposed, we also unregister it from the resource manager cache. This + // is analogous to what is done when manually unrealizing the effect (eg. when using a new + // device. Without this call, the resource manager would keep registered effects alive for + // the entire process duration, even if their original wrappers are gone (ie. collected). + if (this.d2D1Effect.Get() is not null) + { + ResourceManager.UnregisterWrapper((IUnknown*)this.d2D1Effect.Get()); + } + + // Release the native D2D objects that were set during realization this.canvasDevice.Dispose(); this.d2D1RealizationDevice.Dispose(); this.d2D1Effect.Dispose(); - // Also release all native resources for the used sources. - // The transform mapper and resource texture managers don't - // need to be disposed, as those could be shared between effects. + // Also release all native resources for the used sources. The transform mapper and + // resource texture managers don't need to be disposed, as those could be shared + // between effects. Note that SourceReference.Dispose() will only release the native + // resources (ie. D2D images and effects), but it will not also dispose the managed + // wrappers (ie. IGraphicsEffectSource objects), as those can be shared as well. for (int i = 0; i < Sources.Count; i++) { Sources.Storage[i].Dispose(); diff --git a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs index 542a9408..472a86b8 100644 --- a/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs +++ b/src/TerraFX.Interop.Windows.D2D1/Windows/shared/winerror/D2DERR.cs @@ -7,12 +7,15 @@ namespace TerraFX.Interop.DirectX; internal static partial class D2DERR { - [NativeTypeName("#define D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES _HRESULT_TYPEDEF_(0x88990026L)")] - public const int D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES = unchecked((int)(0x88990026)); + [NativeTypeName("#define D2DERR_WRONG_FACTORY _HRESULT_TYPEDEF_(0x88990012L)")] + public const int D2DERR_WRONG_FACTORY = unchecked((int)(0x88990012)); [NativeTypeName("#define D2DERR_CYCLIC_GRAPH _HRESULT_TYPEDEF_(0x88990020L)")] public const int D2DERR_CYCLIC_GRAPH = unchecked((int)(0x88990020)); + [NativeTypeName("#define D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES _HRESULT_TYPEDEF_(0x88990026L)")] + public const int D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES = unchecked((int)(0x88990026)); + [NativeTypeName("#define D2DERR_EFFECT_IS_NOT_REGISTERED _HRESULT_TYPEDEF_(0x88990028L)")] public const int D2DERR_EFFECT_IS_NOT_REGISTERED = unchecked((int)(0x88990028)); } \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.UI.Tests/CanvasEffectTests.cs b/tests/ComputeSharp.D2D1.UI.Tests/CanvasEffectTests.cs new file mode 100644 index 00000000..21a57cb2 --- /dev/null +++ b/tests/ComputeSharp.D2D1.UI.Tests/CanvasEffectTests.cs @@ -0,0 +1,121 @@ +using ComputeSharp.D2D1.Uwp; +using Microsoft.Graphics.Canvas; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +#nullable enable + +namespace ComputeSharp.D2D1.UI.Tests; + +[TestClass] +[TestCategory("CanvasEffect")] +public partial class CanvasEffectTests +{ + [TestMethod] + public unsafe void CanvasEffect_IsRealizedAndInvalidatedCorrectly() + { + EffectWithNoInputs effect = new(); + + try + { + using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f)) + using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession()) + { + drawingSession.DrawImage(effect); + } + + Assert.AreEqual(effect.NumberOfBuildEffectGraphCalls, 1); + Assert.AreEqual(effect.NumberOfConfigureEffectGraphCalls, 1); + Assert.AreEqual(effect.NumberOfDisposeCalls, 0); + + effect.Value = 42; + + using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f)) + using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession()) + { + drawingSession.DrawImage(effect); + } + + Assert.AreEqual(effect.NumberOfBuildEffectGraphCalls, 1); + Assert.AreEqual(effect.NumberOfConfigureEffectGraphCalls, 2); + Assert.AreEqual(effect.NumberOfDisposeCalls, 0); + + effect.ValueWithReload = 123; + + using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f)) + using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession()) + { + drawingSession.DrawImage(effect); + } + + Assert.AreEqual(effect.NumberOfBuildEffectGraphCalls, 2); + Assert.AreEqual(effect.NumberOfConfigureEffectGraphCalls, 3); + Assert.AreEqual(effect.NumberOfDisposeCalls, 0); + } + finally + { + effect.Dispose(); + + Assert.AreEqual(effect.NumberOfDisposeCalls, 1); + } + } + + private sealed class EffectWithNoInputs : CanvasEffect + { + private PixelShaderEffect? effect; + + private int value; + + public int Value + { + get => this.value; + set => SetAndInvalidateEffectGraph(ref this.value, value); + } + + public int ValueWithReload + { + get => this.value; + set => SetAndInvalidateEffectGraph(ref this.value, value, InvalidationType.Creation); + } + + public int NumberOfBuildEffectGraphCalls { get; private set; } + + public int NumberOfConfigureEffectGraphCalls { get; private set; } + + public int NumberOfDisposeCalls { get; private set; } + + protected override ICanvasImage BuildEffectGraph() + { + NumberOfBuildEffectGraphCalls++; + + return this.effect = new PixelShaderEffect(); + } + + protected override void ConfigureEffectGraph() + { + NumberOfConfigureEffectGraphCalls++; + + this.effect!.ConstantBuffer = new ShaderWithNoInputs(this.value); + } + + protected override void Dispose(bool disposing) + { + NumberOfDisposeCalls++; + + base.Dispose(disposing); + + this.effect?.Dispose(); + } + } + + [D2DInputCount(0)] + [AutoConstructor] + private partial struct ShaderWithNoInputs : ID2D1PixelShader + { + public int Value; + + public float4 Execute() + { + return default; + } + } +} diff --git a/tests/ComputeSharp.D2D1.UI.Tests/ComputeSharp.D2D1.UI.Tests.projitems b/tests/ComputeSharp.D2D1.UI.Tests/ComputeSharp.D2D1.UI.Tests.projitems new file mode 100644 index 00000000..826aaefe --- /dev/null +++ b/tests/ComputeSharp.D2D1.UI.Tests/ComputeSharp.D2D1.UI.Tests.projitems @@ -0,0 +1,18 @@ + + + + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) + true + 346aeb10-a4ea-427e-8578-f60915db3053 + + + ComputeSharp.D2D1.UI.Tests + + + + + + + + + \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.UI.Tests/ComputeSharp.D2D1.UI.Tests.shproj b/tests/ComputeSharp.D2D1.UI.Tests/ComputeSharp.D2D1.UI.Tests.shproj new file mode 100644 index 00000000..9abf6f55 --- /dev/null +++ b/tests/ComputeSharp.D2D1.UI.Tests/ComputeSharp.D2D1.UI.Tests.shproj @@ -0,0 +1,13 @@ + + + + 346aeb10-a4ea-427e-8578-f60915db3053 + 14.0 + + + + + + + + diff --git a/tests/ComputeSharp.D2D1.UI.Tests/Helpers/TolerantImageComparer.cs b/tests/ComputeSharp.D2D1.UI.Tests/Helpers/TolerantImageComparer.cs new file mode 100644 index 00000000..60cb3c99 --- /dev/null +++ b/tests/ComputeSharp.D2D1.UI.Tests/Helpers/TolerantImageComparer.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Text; +using System.Runtime.CompilerServices; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.Graphics.Canvas; +using Color = Windows.UI.Color; + +namespace ComputeSharp.D2D1.UI.Tests.Helpers; + +/// +/// An tolerant image comparer type, inspired from ImageSharp. +/// +internal static class TolerantImageComparer +{ + /// + /// Asserts that two images are equal. + /// + /// The reference image. + /// The expected image. + /// The allowed difference threshold for the normalized delta. + public static void AssertEqual(CanvasBitmap expected, CanvasBitmap actual, float threshold) + { + if (expected.SizeInPixels.Width != actual.SizeInPixels.Width || + expected.SizeInPixels.Height != actual.SizeInPixels.Height) + { + Assert.Fail($"The input images have different sizes: {expected.SizeInPixels} and {actual.SizeInPixels}"); + } + + Color[] expectedColors = expected.GetPixelColors(); + Color[] actualColors = actual.GetPixelColors(); + + float totalDifference = 0F; + + List differences = new(20); + + for (int i = 0; i < expectedColors.Length; i++) + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static int GetManhattanDistanceInRgbaSpace(ref Color a, ref Color b) + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static int Diff(ushort a, ushort b) => Math.Abs(a - b); + + return Diff(a.R, b.R) + Diff(a.G, b.G) + Diff(a.B, b.B) + Diff(a.A, b.A); + } + + int d = GetManhattanDistanceInRgbaSpace(ref expectedColors[i], ref actualColors[i]); + + if (d > 0) + { + if (differences.Count < 20) + { + int offsetY = (int)(i / expected.SizeInPixels.Width); + int offsetX = (int)(i % expected.SizeInPixels.Width); + + PixelDifference diff = new(new Point(offsetX, offsetY), expectedColors[i], actualColors[i]); + + differences.Add(diff); + } + + totalDifference += d; + } + } + + float normalizedDifference = totalDifference / (actual.SizeInPixels.Width * (float)actual.SizeInPixels.Height); + + normalizedDifference /= 4F * 65535F; + + if (normalizedDifference > threshold) + { + StringBuilder builder = new(); + + _ = builder.AppendLine($"The input images don't match. Normalized delta: {normalizedDifference}%"); + _ = builder.AppendLine($"First {differences.Count} pixel deltas:"); + + foreach (PixelDifference delta in differences) + { + _ = builder.AppendLine(delta.ToString()); + } + + Assert.Fail(builder.ToString()); + } + } + + /// + /// A simple model repressenting info about a difference between two pixels. + /// + private readonly struct PixelDifference + { + public PixelDifference(Point position, Color expected, Color actual) + { + this.Position = position; + this.RedDifference = actual.R - expected.R; + this.GreenDifference = actual.G - expected.G; + this.BlueDifference = actual.B - expected.B; + this.AlphaDifference = actual.A - expected.A; + } + + public readonly Point Position; + + public readonly int RedDifference; + + public readonly int GreenDifference; + + public readonly int BlueDifference; + + public readonly int AlphaDifference; + + /// + public override string ToString() + { + return $"[delta({this.RedDifference},{this.GreenDifference},{this.BlueDifference},{this.AlphaDifference}) @ ({this.Position.X},{this.Position.Y})]"; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.UI.Tests/Helpers/Win2DHelper.cs b/tests/ComputeSharp.D2D1.UI.Tests/Helpers/Win2DHelper.cs new file mode 100644 index 00000000..653fbfbd --- /dev/null +++ b/tests/ComputeSharp.D2D1.UI.Tests/Helpers/Win2DHelper.cs @@ -0,0 +1,119 @@ +using System; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.WindowsRuntime; +using Microsoft.Graphics.Canvas; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +#nullable enable + +namespace ComputeSharp.D2D1.UI.Tests.Helpers; + +/// +/// A helper type to marshal managed objects in unit tests. +/// +internal static class Win2DHelper +{ + /// + /// Gets the managed wrapper for a given object. + /// + /// The input object to get a wrapper for. + /// The realization instance to use. + /// The resulting managed wrapper for . + public static unsafe object GetOrCreate(ID2D1Image* d2D1Image, CanvasDevice? canvasDevice = null) + { + IActivationFactory activationFactory = WindowsRuntimeMarshal.GetActivationFactory(typeof(CanvasDevice)); + + using ComPtr activationFactoryUnknown = default; + + activationFactoryUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(activationFactory)); + + using ComPtr canvasFactoryNativeUnknown = default; + + Guid uuidOfCanvasFactoryNativeUnknown = new("695C440D-04B3-4EDD-BFD9-63E51E9F7202"); + + //Get the ICanvasFactoryNative object + int hresult = activationFactoryUnknown.CopyTo(&uuidOfCanvasFactoryNativeUnknown, (void**)canvasFactoryNativeUnknown.GetAddressOf()); + + Marshal.ThrowExceptionForHR(hresult); + + using ComPtr canvasDeviceUnknown = default; + + if (canvasDevice is not null) + { + canvasDeviceUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(canvasDevice)); + } + + using ComPtr canvasDeviceInterfaceUnknown = default; + + if (canvasDevice is not null) + { + Guid uuidOfCanvasDeviceInterface = new("A27F0B5D-EC2C-4D4F-948F-0AA1E95E33E6"); + + // Get the ICanvasDevice object (as an IUnknown* as well) + hresult = canvasDeviceUnknown.CopyTo(&uuidOfCanvasDeviceInterface, (void**)canvasDeviceInterfaceUnknown.GetAddressOf()); + } + + using ComPtr wrapperUnknown = default; + + // Invoke GetOrCreate to get the inspectable wrapper + hresult = ((delegate* unmanaged[Stdcall])(*(void***)canvasFactoryNativeUnknown.Get())[6])( + canvasFactoryNativeUnknown.Get(), + canvasDeviceInterfaceUnknown.Get(), + (IUnknown*)d2D1Image, + 0, + wrapperUnknown.GetAddressOf()); + + Marshal.ThrowExceptionForHR(hresult); + + // Get or create a managed object for the native object + return Marshal.GetObjectForIUnknown((IntPtr)wrapperUnknown.Get()); + } + + /// + /// Gets the D2D image from a given object. + /// + /// The input object. + /// The realization instance to use. + /// The resulting object. + public static unsafe void GetD2DImage(ICanvasImage canvasImage, CanvasDevice canvasDevice, ID2D1Image** d2D1Image) + { + using ComPtr effectUnknown = default; + + effectUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(canvasImage)); + + using ComPtr canvasImageInteropUnknown = default; + + Guid uuidOfCanvasImageInterop = new("E042D1F7-F9AD-4479-A713-67627EA31863"); + + // Get the ICanvasImageInterop object (as an IUnknown*) + int hresult = effectUnknown.CopyTo(&uuidOfCanvasImageInterop, (void**)canvasImageInteropUnknown.GetAddressOf()); + + Marshal.ThrowExceptionForHR(hresult); + + using ComPtr canvasDeviceUnknown = default; + + canvasDeviceUnknown.Attach((IUnknown*)Marshal.GetIUnknownForObject(canvasDevice)); + + using ComPtr canvasDeviceInterfaceUnknown = default; + + Guid uuidOfCanvasDeviceInterface = new("A27F0B5D-EC2C-4D4F-948F-0AA1E95E33E6"); + + // Get the ICanvasDevice object (as an IUnknown* as well) + hresult = canvasDeviceUnknown.CopyTo(&uuidOfCanvasDeviceInterface, (void**)canvasDeviceInterfaceUnknown.GetAddressOf()); + + Marshal.ThrowExceptionForHR(hresult); + + // Invoke GetD2DImage (passing NEVER_INSERT_DPI_COMPENSATION | MINIMAL_REALIZATION | ALLOW_NULL_EFFECT_INPUTS) + hresult = ((delegate* unmanaged[Stdcall])(*(void***)canvasImageInteropUnknown.Get())[4])( + canvasImageInteropUnknown.Get(), + canvasDeviceInterfaceUnknown.Get(), + null, + 4 | 8 | 16, + 0, + null, + d2D1Image); + + Marshal.ThrowExceptionForHR(hresult); + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.UI.Tests/PixelShaderEffectTests.cs b/tests/ComputeSharp.D2D1.UI.Tests/PixelShaderEffectTests.cs new file mode 100644 index 00000000..d1ca0216 --- /dev/null +++ b/tests/ComputeSharp.D2D1.UI.Tests/PixelShaderEffectTests.cs @@ -0,0 +1,514 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.D2D1.Interop; +using ComputeSharp.D2D1.UI.Tests.Helpers; +using ComputeSharp.D2D1.Uwp; +using Microsoft.Graphics.Canvas; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.UI.Tests; + +[TestClass] +[TestCategory("PixelShaderEffect")] +public partial class PixelShaderEffectTests +{ + [TestMethod] + public unsafe void ConstantBuffer_IsInitiallySetToDefault() + { + using PixelShaderEffect effect = new(); + + ShaderWithSomeProperties shader = effect.ConstantBuffer; + ShaderWithSomeProperties defaultShader = default; + + ReadOnlySpan actual = new(&shader, sizeof(ShaderWithSomeProperties)); + ReadOnlySpan expected = new(&defaultShader, sizeof(ShaderWithSomeProperties)); + + // The default constant buffer is set to 0, and it can be retrieved correctly + Assert.IsTrue(actual.SequenceEqual(expected)); + } + + [TestMethod] + public unsafe void ConstantBuffer_RoundTripsCorrectly() + { + ShaderWithSomeProperties shader = new( + A: 3.14f, + B: 123456, + C: new int2(111, -222), + D: new uint2x2(8888, 123456, 98765, 192837465), + E: new float2(-3.14f, 6.28f)); + + using PixelShaderEffect effect = new() { ConstantBuffer = shader }; + + ShaderWithSomeProperties roundTripShader = effect.ConstantBuffer; + + ReadOnlySpan expected = new(&shader, sizeof(ShaderWithSomeProperties)); + ReadOnlySpan actual = new(&roundTripShader, sizeof(ShaderWithSomeProperties)); + + // The resulting constant buffer matches the source, when the effect is not realized + Assert.IsTrue(actual.SequenceEqual(expected)); + + // Draw the effect, to force realization + using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f)) + using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession()) + { + drawingSession.DrawImage(effect); + } + + roundTripShader = effect.ConstantBuffer; + actual = new(&roundTripShader, sizeof(ShaderWithSomeProperties)); + + // The shader also matches when retrieving it through the realized effect + Assert.IsTrue(actual.SequenceEqual(expected)); + + // Draw the effect on a different device (this forces it to unrealize and re-realize). + // This also acts as a unit test for the device changed logic, since that's used here. + using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f)) + using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession()) + { + drawingSession.DrawImage(effect); + } + + roundTripShader = effect.ConstantBuffer; + actual = new(&roundTripShader, sizeof(ShaderWithSomeProperties)); + + // The shader also matches when retrieving it through the realized effect + Assert.IsTrue(actual.SequenceEqual(expected)); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentOutOfRangeException))] + public void SourcesOutOfRange_ThrowsArgumentOutOfRangeException() + { + using PixelShaderEffect effect0 = new(); + + _ = Assert.ThrowsException(() => effect0.Sources[0] = null); + _ = Assert.ThrowsException(() => effect0.Sources[1] = null); + + using PixelShaderEffect effect1 = new(); + + effect1.Sources[0] = null; + + _ = Assert.ThrowsException(() => effect1.Sources[1] = null); + _ = Assert.ThrowsException(() => effect1.Sources[2] = null); + + using PixelShaderEffect effect2 = new(); + + effect2.Sources[0] = null; + effect2.Sources[1] = null; + + _ = Assert.ThrowsException(() => effect2.Sources[2] = null); + _ = Assert.ThrowsException(() => effect2.Sources[3] = null); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void NullTransformMapper_UnrealizedEffect_ThrowsArgumentNullException() + { + using PixelShaderEffect effect = new(); + + effect.TransformMapper = null!; + } + + [TestMethod] + [ExpectedException(typeof(ArgumentNullException))] + public void NullTransformMapper_RealizedEffect_ThrowsArgumentNullException() + { + using PixelShaderEffect effect = new(); + + using (CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f)) + using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession()) + { + drawingSession.DrawImage(effect); + } + + effect.TransformMapper = null!; + } + + [TestMethod] + [ExpectedException(typeof(Exception), AllowDerivedTypes = true)] + public unsafe void GraphCycle_IsDetectedCorrectly() + { + using PixelShaderEffect effect1 = new(); + using PixelShaderEffect effect2 = new(); + using PixelShaderEffect effect3 = new(); + using PixelShaderEffect effect4 = new(); + using PixelShaderEffect effect5 = new(); + using PixelShaderEffect effect6 = new(); + using PixelShaderEffect effect7 = new(); + + // Build a graph with a cycle in it: + // + // ┌───┐ ┌───┐ ┌───┐ + // │ 1 ├──►│ 2 ├──►│ 3 ├──────────┐ + // └───┘ └───┘ └───┘ ▼ + // ┌───┐ ┌───┐ ▲ │ ┌───┐ ┌───┐ + // │ 7 ├──►│ 6 ├─┘ └─►│ 4 ├──►│ 5 │ + // └───┘ └───┘ └───┘ └───┘ + // ▲ │ + // └─────────────────┘ + // + // The cycle is 4 -> 6 -> 2 -> 3 -> 4. + effect2.Sources[0] = effect1; + effect2.Sources[1] = effect6; + effect3.Sources[0] = effect2; + effect4.Sources[0] = effect3; + effect5.Sources[0] = effect3; + effect5.Sources[1] = effect4; + effect6.Sources[0] = effect4; + effect6.Sources[1] = effect7; + + using ComPtr d2D1Image = default; + + // Realize the effect for it to detect a graph cycle. We specifically don't want to draw + // the effect, because in that case we'd still get an exception from D2D, even if the + // effect from ComputeSharp failed to detect a graph cycle. We want to make sure the + // detection and subsequent error is coming from our wrapper, not from D2D's logic. + Win2DHelper.GetD2DImage(effect5, new CanvasDevice(), d2D1Image.GetAddressOf()); + } + + [TestMethod] + public unsafe void Interop_EffectPropertiesAreForwardedCorrectly() + { + ShaderWithSomePropertiesAndInputs shader = new(-1234567); + + using PixelShaderEffect effect0 = new(); + using PixelShaderEffect effect1 = new() + { + ConstantBuffer = shader, + CacheOutput = true, + BufferPrecision = CanvasBufferPrecision.Precision32Float, + Sources = { [0] = effect0 } + }; + + CanvasDevice canvasDevice = new(); + + using ComPtr d2D1Image = default; + + // Realize the effect and get the D2D effect (this will also apply all local properties) + Win2DHelper.GetD2DImage(effect1, canvasDevice, d2D1Image.GetAddressOf()); + + using ComPtr d2D1Effect = default; + + Marshal.ThrowExceptionForHR(d2D1Image.CopyTo(d2D1Effect.GetAddressOf())); + + int constantBufferDataSize = D2D1PixelShader.GetConstantBufferSize(); + byte* constantBufferData = stackalloc byte[constantBufferDataSize]; + + int hresult = d2D1Effect.Get()->GetValue( + index: D2D1PixelShaderEffectProperty.ConstantBuffer, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BLOB, + data: constantBufferData, + dataSize: (uint)constantBufferDataSize); + + Marshal.ThrowExceptionForHR(hresult); + + ReadOnlyMemory expectedConstantBufferData = D2D1PixelShader.GetConstantBuffer(in shader); + + Assert.IsTrue(expectedConstantBufferData.Span.SequenceEqual(new ReadOnlySpan(constantBufferData, constantBufferDataSize))); + + int cacheOutput; + + hresult = d2D1Effect.Get()->GetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, + data: (byte*)&cacheOutput, + dataSize: sizeof(int)); + + Marshal.ThrowExceptionForHR(hresult); + + Assert.AreEqual(1, cacheOutput); + + D2D1_BUFFER_PRECISION d2D1BufferPrecision; + + hresult = d2D1Effect.Get()->GetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&d2D1BufferPrecision, + dataSize: sizeof(D2D1_BUFFER_PRECISION)); + + Marshal.ThrowExceptionForHR(hresult); + + Assert.AreEqual(D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT, d2D1BufferPrecision); + + using ComPtr d2D1Image1 = default; + using ComPtr d2D1Image2 = default; + + Win2DHelper.GetD2DImage(effect0, canvasDevice, d2D1Image1.GetAddressOf()); + + d2D1Effect.Get()->GetInput(0, d2D1Image2.GetAddressOf()); + + using ComPtr d2D1Image1Unknown = default; + using ComPtr d2D1Image2Unknown = default; + + Marshal.ThrowExceptionForHR(d2D1Image1.CopyTo(d2D1Image1Unknown.GetAddressOf())); + Marshal.ThrowExceptionForHR(d2D1Image2.CopyTo(d2D1Image2Unknown.GetAddressOf())); + + // The image from the effect input should be the same retrieved from the original source wrapper + Assert.IsTrue(d2D1Image1Unknown.Get() == d2D1Image2Unknown.Get()); + } + + [TestMethod] + public unsafe void Interop_EffectPropertiesAreUpdatedFromNativeEffectCorrectly() + { + ShaderWithSomePropertiesAndInputs shader = new(-1234567); + + using PixelShaderEffect effect0 = new(); + using PixelShaderEffect effect1 = new(); + + CanvasDevice canvasDevice = new(); + + using ComPtr d2D1Image0 = default; + using ComPtr d2D1Image1 = default; + + // Realize the effects and get the D2D effects + Win2DHelper.GetD2DImage(effect0, canvasDevice, d2D1Image0.GetAddressOf()); + Win2DHelper.GetD2DImage(effect1, canvasDevice, d2D1Image1.GetAddressOf()); + + using ComPtr d2D1Effect = default; + + Marshal.ThrowExceptionForHR(d2D1Image1.CopyTo(d2D1Effect.GetAddressOf())); + + D2D1PixelShaderEffect.SetConstantBufferForD2D1Effect(d2D1Effect.Get(), in shader); + + int cacheOutput = 1; + + int hresult = d2D1Effect.Get()->SetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_CACHED, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BOOL, + data: (byte*)&cacheOutput, + dataSize: sizeof(int)); + + Marshal.ThrowExceptionForHR(hresult); + + Assert.AreEqual(1, cacheOutput); + + D2D1_BUFFER_PRECISION d2D1BufferPrecision = D2D1_BUFFER_PRECISION.D2D1_BUFFER_PRECISION_32BPC_FLOAT; + + hresult = d2D1Effect.Get()->SetValue( + index: (uint)D2D1_PROPERTY.D2D1_PROPERTY_PRECISION, + type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_UNKNOWN, + data: (byte*)&d2D1BufferPrecision, + dataSize: sizeof(D2D1_BUFFER_PRECISION)); + + Marshal.ThrowExceptionForHR(hresult); + + d2D1Effect.Get()->SetInput(0, d2D1Image0.Get()); + + Assert.AreEqual(shader.Number, effect1.ConstantBuffer.Number); + Assert.IsTrue(effect1.CacheOutput); + Assert.AreEqual(CanvasBufferPrecision.Precision32Float, effect1.BufferPrecision); + Assert.AreSame(effect0, effect1.Sources[0]); + } + + [TestMethod] + public unsafe void Interop_IsWrapperRegisteredCorrectly() + { + using PixelShaderEffect effect = new(); + + using ComPtr d2D1Image = default; + + Win2DHelper.GetD2DImage(effect, new CanvasDevice(), d2D1Image.GetAddressOf()); + + object wrapper = Win2DHelper.GetOrCreate(d2D1Image.Get()); + + Assert.AreSame(effect, wrapper); + } + + [TestMethod] + public unsafe void Interop_IsWrapperUnregisteredCorrectly_FromExplicitDispose() + { + using ComPtr d2D1Image = default; + + PixelShaderEffect effect = new(); + CanvasDevice canvasDevice = new(); + + try + { + Win2DHelper.GetD2DImage(effect, canvasDevice, d2D1Image.GetAddressOf()); + } + finally + { + effect.Dispose(); + } + + object wrapper = Win2DHelper.GetOrCreate(d2D1Image.Get(), canvasDevice); + + Assert.IsTrue(wrapper is PixelShaderEffect); + Assert.AreNotSame(effect, wrapper); + + // Ensure the new wrapper is disposed as well + using PixelShaderEffect _ = (PixelShaderEffect)wrapper; + } + + [TestMethod] + [ExpectedException(typeof(Exception), AllowDerivedTypes = true)] + public unsafe void Interop_IsWrapperUnregisteredCorrectly_FromExplicitDispose_FailsWithNoDevice() + { + using ComPtr d2D1Image = default; + + using (PixelShaderEffect effect = new()) + { + Win2DHelper.GetD2DImage(effect, new CanvasDevice(), d2D1Image.GetAddressOf()); + } + + _ = Win2DHelper.GetOrCreate(d2D1Image.Get()); + } + + [TestMethod] + [ExpectedException(typeof(Exception), AllowDerivedTypes = true)] + public unsafe void Interop_IsWrapperUnregisteredCorrectly_FromFinalizer_FailsWithNoDevice() + { + using ComPtr d2D1Image = default; + + [MethodImpl(MethodImplOptions.NoInlining)] + static void Test(ID2D1Image** d2D1Image) + { + PixelShaderEffect effect = new(); + + Win2DHelper.GetD2DImage(effect, new CanvasDevice(), d2D1Image); + } + + Test(d2D1Image.GetAddressOf()); + + GC.Collect(); + GC.WaitForPendingFinalizers(); + + _ = Win2DHelper.GetOrCreate(d2D1Image.Get()); + } + + [TestMethod] + public unsafe void Interop_IsWrapperFactoryRegisteredCorrectlyAndWorking() + { + using PixelShaderEffect effect = new(); + + CanvasDevice canvasDevice1 = new(); + CanvasDevice canvasDevice2 = new(); + + using ComPtr d2D1Image1 = default; + using ComPtr d2D1Image2 = default; + + Win2DHelper.GetD2DImage(effect, canvasDevice1, d2D1Image1.GetAddressOf()); + Win2DHelper.GetD2DImage(effect, canvasDevice2, d2D1Image2.GetAddressOf()); + + // The first resource is orphaned, so a new wrapper will be created + object wrapper1 = Win2DHelper.GetOrCreate(d2D1Image1.Get(), canvasDevice1); + + Assert.IsTrue(wrapper1 is PixelShaderEffect); + Assert.AreNotSame(wrapper1, effect); + + // Property dispose the new wrapper as well + using PixelShaderEffect _ = (PixelShaderEffect)wrapper1; + + // Getting the same wrapper again should return the newly created one + object wrapper1FromCache = Win2DHelper.GetOrCreate(d2D1Image1.Get(), canvasDevice1); + + Assert.AreSame(wrapper1, wrapper1FromCache); + + using ComPtr d2D1Image1FromNewWrapper = default; + + // Get the realized image from the newly created wrapper + Win2DHelper.GetD2DImage((ICanvasImage)wrapper1, canvasDevice1, d2D1Image1FromNewWrapper.GetAddressOf()); + + using ComPtr d2D1Image1Unknown = default; + using ComPtr d2D1Image1FromNewWrapperUnknown = default; + + Marshal.ThrowExceptionForHR(d2D1Image1.CopyTo(d2D1Image1Unknown.GetAddressOf())); + Marshal.ThrowExceptionForHR(d2D1Image1FromNewWrapper.CopyTo(d2D1Image1FromNewWrapperUnknown.GetAddressOf())); + + // The retrieved image should be the same one the new wrapper was created from + Assert.IsTrue(d2D1Image1Unknown.Get() == d2D1Image1FromNewWrapperUnknown.Get()); + + // The second resource is currently registered, so it returns the local wrapper + object wrapper2 = Win2DHelper.GetOrCreate(d2D1Image2.Get()); + + Assert.AreSame(effect, wrapper2); + } + + [TestMethod] + public unsafe void Interop_WrapperFactoryDetectsMismatchedDevices() + { + using PixelShaderEffect effect = new(); + + CanvasDevice canvasDevice1 = new(); + CanvasDevice canvasDevice2 = new(); + + using ComPtr d2D1Image1 = default; + using ComPtr d2D1Image2 = default; + + Win2DHelper.GetD2DImage(effect, canvasDevice1, d2D1Image1.GetAddressOf()); + Win2DHelper.GetD2DImage(effect, canvasDevice2, d2D1Image2.GetAddressOf()); + + // The factory should detect we're passing an incompatible device for the resource + try + { + _ = Win2DHelper.GetOrCreate(d2D1Image1.Get(), canvasDevice2); + + Assert.Fail(); + } + catch (Exception e) + { + Assert.AreEqual(e.HResult, D2DERR.D2DERR_WRONG_FACTORY); + } + } + + [D2DInputCount(0)] + [AutoConstructor] + private partial struct ShaderWithSomeProperties : ID2D1PixelShader + { + public float A; + public int B; + public int2 C; + public uint2x2 D; + public float2 E; + + public float4 Execute() + { + return default; + } + } + + [D2DInputCount(1)] + [AutoConstructor] + private partial struct ShaderWithSomePropertiesAndInputs : ID2D1PixelShader + { + public int Number; + + public float4 Execute() + { + return D2D.GetInput(0); + } + } + + [D2DInputCount(0)] + private partial struct ShaderWith0Inputs : ID2D1PixelShader + { + public float4 Execute() + { + return default; + } + } + + [D2DInputCount(1)] + [D2DInputSimple(0)] + private partial struct ShaderWith1Input : ID2D1PixelShader + { + public float4 Execute() + { + return D2D.GetInput(0); + } + } + + [D2DInputCount(2)] + [D2DInputSimple(0)] + [D2DInputSimple(1)] + private partial struct ShaderWith2Inputs : ID2D1PixelShader + { + public float4 Execute() + { + return D2D.GetInput(0) + D2D.GetInput(1); + } + } +} diff --git a/tests/ComputeSharp.D2D1.UI.Tests/ShadersTests.cs b/tests/ComputeSharp.D2D1.UI.Tests/ShadersTests.cs new file mode 100644 index 00000000..374fb3ad --- /dev/null +++ b/tests/ComputeSharp.D2D1.UI.Tests/ShadersTests.cs @@ -0,0 +1,144 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using ComputeSharp.D2D1.UI.Tests.Helpers; +using ComputeSharp.D2D1.Uwp; +using ComputeSharp.SwapChain.Shaders.D2D1; +using Microsoft.Graphics.Canvas; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Windows.Storage; +using Windows.UI; + +#nullable enable + +namespace ComputeSharp.D2D1.UI.Tests; + +[TestClass] +[TestCategory("Shaders")] +public class ShadersTests +{ + [TestMethod] + [DataRow(WrapperType.PixelShaderEffect)] + [DataRow(WrapperType.CanvasEffect)] + public async Task HelloWorld(WrapperType wrapperType) + { + await RunTestAsync(wrapperType); + } + + [TestMethod] + [DataRow(WrapperType.PixelShaderEffect)] + [DataRow(WrapperType.CanvasEffect)] + public async Task ColorfulInfinity(WrapperType wrapperType) + { + await RunTestAsync(wrapperType); + } + + [TestMethod] + [DataRow(WrapperType.PixelShaderEffect)] + [DataRow(WrapperType.CanvasEffect)] + public async Task FractalTiling(WrapperType wrapperType) + { + await RunTestAsync(wrapperType); + } + + [TestMethod] + [DataRow(WrapperType.PixelShaderEffect)] + [DataRow(WrapperType.CanvasEffect)] + public async Task MengerJourney(WrapperType wrapperType) + { + await RunTestAsync(wrapperType, 0.000011f); + } + + [TestMethod] + [DataRow(WrapperType.PixelShaderEffect)] + [DataRow(WrapperType.CanvasEffect)] + public async Task Octagrams(WrapperType wrapperType) + { + await RunTestAsync(wrapperType); + } + + [TestMethod] + [DataRow(WrapperType.PixelShaderEffect)] + [DataRow(WrapperType.CanvasEffect)] + public async Task ProteanClouds(WrapperType wrapperType) + { + await RunTestAsync(wrapperType); + } + + [TestMethod] + [DataRow(WrapperType.PixelShaderEffect)] + [DataRow(WrapperType.CanvasEffect)] + public async Task TerracedHills(WrapperType wrapperType) + { + await RunTestAsync(wrapperType, 0.000026f); + } + + private static async Task RunTestAsync(WrapperType wrapperType, float threshold = 0.00001f) + where T : unmanaged, ID2D1PixelShader + { + T shader = (T)Activator.CreateInstance(typeof(T), 0f, new int2(1280, 720))!; + + // Either create the effect directly, or a canvas effect + using ICanvasImage canvasImage = wrapperType switch + { + WrapperType.PixelShaderEffect => new PixelShaderEffect() { ConstantBuffer = shader }, + _ => new TestCanvasEffect { ConstantBuffer = shader } + }; + + Color[] pixelColors; + + using CanvasDevice canvasDevice = new(); + + // Compute the resulting image + using (CanvasRenderTarget renderTarget = new(canvasDevice, 1280, 720, 96.0f)) + { + // Draw the shader on the render target + using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession()) + { + drawingSession.DrawImage(canvasImage); + } + + // Get the BGRA32 pixel data from the render target + pixelColors = renderTarget.GetPixelColors(); + } + + StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/Shaders/{typeof(T).Name}.png")); + + // Retrieve the expected image + using Stream stream = await imageFile.OpenStreamForReadAsync(); + using CanvasBitmap expected = await CanvasBitmap.LoadAsync(canvasDevice, stream.AsRandomAccessStream()); + using CanvasBitmap actual = CanvasBitmap.CreateFromColors(canvasDevice, pixelColors, 1280, 720); + + TolerantImageComparer.AssertEqual(expected, actual, threshold); + } + + private sealed class TestCanvasEffect : CanvasEffect + where T : unmanaged, ID2D1PixelShader + { + private PixelShaderEffect? effect; + + private T constantBuffer; + + public T ConstantBuffer + { + get => this.constantBuffer; + set => SetAndInvalidateEffectGraph(ref this.constantBuffer, value); + } + + protected override ICanvasImage BuildEffectGraph() + { + return this.effect = new PixelShaderEffect(); + } + + protected override void ConfigureEffectGraph() + { + this.effect!.ConstantBuffer = this.constantBuffer; + } + } + + public enum WrapperType + { + PixelShaderEffect, + CanvasEffect + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/LockScreenLogo.scale-200.png b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/LockScreenLogo.scale-200.png new file mode 100644 index 00000000..735f57ad Binary files /dev/null and b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/LockScreenLogo.scale-200.png differ diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/SplashScreen.scale-200.png b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/SplashScreen.scale-200.png new file mode 100644 index 00000000..023e7f1f Binary files /dev/null and b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/SplashScreen.scale-200.png differ diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Square150x150Logo.scale-200.png b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Square150x150Logo.scale-200.png new file mode 100644 index 00000000..af49fec1 Binary files /dev/null and b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Square150x150Logo.scale-200.png differ diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Square44x44Logo.scale-200.png b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Square44x44Logo.scale-200.png new file mode 100644 index 00000000..ce342a2e Binary files /dev/null and b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Square44x44Logo.scale-200.png differ diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Square44x44Logo.targetsize-24_altform-unplated.png b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Square44x44Logo.targetsize-24_altform-unplated.png new file mode 100644 index 00000000..f6c02ce9 Binary files /dev/null and b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Square44x44Logo.targetsize-24_altform-unplated.png differ diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/StoreLogo.png b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/StoreLogo.png new file mode 100644 index 00000000..7385b56c Binary files /dev/null and b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/StoreLogo.png differ diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Wide310x150Logo.scale-200.png b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Wide310x150Logo.scale-200.png new file mode 100644 index 00000000..288995b3 Binary files /dev/null and b/tests/ComputeSharp.D2D1.Uwp.Tests/Assets/Wide310x150Logo.scale-200.png differ diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/ComputeSharp.D2D1.Uwp.Tests.csproj b/tests/ComputeSharp.D2D1.Uwp.Tests/ComputeSharp.D2D1.Uwp.Tests.csproj new file mode 100644 index 00000000..041635c7 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Uwp.Tests/ComputeSharp.D2D1.Uwp.Tests.csproj @@ -0,0 +1,160 @@ + + + + + Debug + x64 + {4D4BB2F6-5653-4DB5-A8DD-90D58D8FE4D3} + AppContainerExe + Properties + ComputeSharp.D2D1.Uwp.Tests + ComputeSharp.D2D1.Uwp.Tests + en-US + UAP + 10.0.22621.0 + 10.0.17763.0 + 14 + 512 + {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + $(VisualStudioVersion) + false + + + true + bin\ARM64\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + $(NoWarn);2008 + full + ARM64 + false + prompt + true + true + + + bin\ARM64\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + $(NoWarn);2008 + pdbonly + ARM64 + false + prompt + true + true + + + true + bin\x64\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + $(NoWarn);2008 + full + x64 + false + prompt + true + + + bin\x64\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + $(NoWarn);2008 + pdbonly + x64 + false + prompt + true + true + + + PackageReference + + + + + + + + UnitTestApp.xaml + + + + + MSBuild:Compile + Designer + + + + + Designer + + + + + Assets\Shaders\ColorfulInfinity.png + PreserveNewest + + + Assets\Shaders\FractalTiling.png + PreserveNewest + + + Assets\Shaders\HelloWorld.png + PreserveNewest + + + Assets\Shaders\MengerJourney.png + PreserveNewest + + + Assets\Shaders\Octagrams.png + PreserveNewest + + + Assets\Shaders\ProteanClouds.png + PreserveNewest + + + Assets\Shaders\TerracedHills.png + PreserveNewest + + + + + + + + + + + + + 6.2.14 + + + 2.2.7 + + + 2.2.7 + + + 1.13.1 + all + + + + + + + + + + + + + + + 14.0 + + + \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/Package.appxmanifest b/tests/ComputeSharp.D2D1.Uwp.Tests/Package.appxmanifest new file mode 100644 index 00000000..24fb011e --- /dev/null +++ b/tests/ComputeSharp.D2D1.Uwp.Tests/Package.appxmanifest @@ -0,0 +1,44 @@ + + + + + + + + + ComputeSharp.D2D1.Uwp.Tests + sergiopedri + Assets\StoreLogo.png + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/Properties/AssemblyInfo.cs b/tests/ComputeSharp.D2D1.Uwp.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..8fb8814e --- /dev/null +++ b/tests/ComputeSharp.D2D1.Uwp.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,16 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("ComputeSharp.D2D1.Uwp.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ComputeSharp.D2D1.Uwp.Tests")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: AssemblyMetadata("TargetPlatform","UAP")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: ComVisible(false)] \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/Properties/Default.rd.xml b/tests/ComputeSharp.D2D1.Uwp.Tests/Properties/Default.rd.xml new file mode 100644 index 00000000..922d306f --- /dev/null +++ b/tests/ComputeSharp.D2D1.Uwp.Tests/Properties/Default.rd.xml @@ -0,0 +1,22 @@ + + + + + + + \ No newline at end of file diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/UnitTestApp.xaml b/tests/ComputeSharp.D2D1.Uwp.Tests/UnitTestApp.xaml new file mode 100644 index 00000000..606340e6 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Uwp.Tests/UnitTestApp.xaml @@ -0,0 +1,4 @@ + diff --git a/tests/ComputeSharp.D2D1.Uwp.Tests/UnitTestApp.xaml.cs b/tests/ComputeSharp.D2D1.Uwp.Tests/UnitTestApp.xaml.cs new file mode 100644 index 00000000..0f6c05d2 --- /dev/null +++ b/tests/ComputeSharp.D2D1.Uwp.Tests/UnitTestApp.xaml.cs @@ -0,0 +1,31 @@ +using Windows.ApplicationModel.Activation; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; + +namespace ComputeSharp.D2D1.Uwp.Tests; + +/// +/// Provides application-specific behavior to supplement the default Application class. +/// +public sealed partial class App : Application +{ + /// + /// Creates a new instance. + /// + public App() + { + InitializeComponent(); + } + + /// + protected override void OnLaunched(LaunchActivatedEventArgs e) + { + Window.Current.Content ??= new Frame(); + + Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.CreateDefaultUI(); + + Window.Current.Activate(); + + Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.Run(e.Arguments); + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Helpers/TolerantImageComparer.cs b/tests/ComputeSharp.Tests/Helpers/TolerantImageComparer.cs index 97ed11aa..078c4777 100644 --- a/tests/ComputeSharp.Tests/Helpers/TolerantImageComparer.cs +++ b/tests/ComputeSharp.Tests/Helpers/TolerantImageComparer.cs @@ -85,6 +85,7 @@ internal static class TolerantImageComparer if (differences.Count < 20) { PixelDifference diff = new(new Point(x, y), aBuffer[x], bBuffer[x]); + differences.Add(diff); } @@ -94,11 +95,13 @@ internal static class TolerantImageComparer } float normalizedDifference = totalDifference / (actual.Width * (float)actual.Height); + normalizedDifference /= 4F * 65535F; if (normalizedDifference > threshold) { StringBuilder builder = new(); + _ = builder.AppendLine($"The input images don't match. Normalized delta: {normalizedDifference}%"); _ = builder.AppendLine($"First {differences.Count} pixel deltas:"); diff --git a/tests/Directory.Build.props b/tests/Directory.Build.props index d3430177..7fe8533e 100644 --- a/tests/Directory.Build.props +++ b/tests/Directory.Build.props @@ -6,6 +6,9 @@ false + + $(NoWarn);CS0649 + $(NoWarn);CS1591