diff --git a/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/PixelShaderEffect.cs b/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/PixelShaderEffect.cs index e0257d28..125c6e68 100644 --- a/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/PixelShaderEffect.cs +++ b/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/PixelShaderEffect.cs @@ -5,7 +5,6 @@ using ComputeSharp.D2D1.Uwp; #else using ComputeSharp.D2D1.WinUI; #endif -using Microsoft.Graphics.Canvas; #nullable enable @@ -65,16 +64,16 @@ public abstract class PixelShaderEffect : CanvasEffect public sealed class For : PixelShaderEffect where T : unmanaged, ID2D1PixelShader { + /// + /// The node in use. + /// + private static readonly EffectNode> Effect = new(); + /// /// The factory to use. /// private readonly Factory factory; - /// - /// The instance in use. - /// - private PixelShaderEffect? effect; - /// /// Creates a new instance with the specified parameters. /// @@ -85,28 +84,15 @@ public abstract class PixelShaderEffect : CanvasEffect } /// - protected override ICanvasImage BuildEffectGraph() + protected override void BuildEffectGraph(EffectGraph effectGraph) { - this.effect = new PixelShaderEffect(); - - return this.effect; + effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect()); } /// - protected override void ConfigureEffectGraph() + protected override void ConfigureEffectGraph(EffectGraph effectGraph) { - this.effect!.ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight); - } - - /// - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - if (disposing) - { - this.effect?.Dispose(); - } + effectGraph.GetNode(Effect).ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight); } /// diff --git a/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/D2D1ContouredLayersRunner.cs b/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/D2D1ContouredLayersRunner.cs index 9707c246..863c2c2e 100644 --- a/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/D2D1ContouredLayersRunner.cs +++ b/samples/ComputeSharp.SwapChain.Core.Shared/Shaders/Runners/D2D1ContouredLayersRunner.cs @@ -8,7 +8,6 @@ using ComputeSharp.D2D1.Uwp; using ComputeSharp.D2D1.WinUI; #endif using ComputeSharp.SwapChain.Shaders.D2D1; -using Microsoft.Graphics.Canvas; using Windows.ApplicationModel; #nullable enable @@ -21,12 +20,12 @@ namespace ComputeSharp.SwapChain.Core.Shaders.Runners; public sealed class D2D1ContouredLayersEffect : PixelShaderEffect { /// - /// The reusable instance to use to render frames. + /// The reusable node to use to render frames. /// - private PixelShaderEffect? pixelShaderEffect; + private static readonly EffectNode> PixelShaderEffect = new(); /// - protected override unsafe ICanvasImage BuildEffectGraph() + protected override unsafe void BuildEffectGraph(EffectGraph effectGraph) { string filename = Path.Combine(Package.Current.InstalledLocation.Path, "Assets", "Textures", "RustyMetal.png"); @@ -56,25 +55,15 @@ public sealed class D2D1ContouredLayersEffect : PixelShaderEffect strides: stackalloc uint[] { (uint)strideInBytes }); // Create the new pixel shader effect - this.pixelShaderEffect = new PixelShaderEffect() { ResourceTextureManagers = { [0] = resourceTextureManager } }; + PixelShaderEffect pixelShaderEffect = new() { ResourceTextureManagers = { [0] = resourceTextureManager } }; - return this.pixelShaderEffect; + // Register the pixel shader effect as the output node in the effect graph + effectGraph.RegisterOutputNode(PixelShaderEffect, pixelShaderEffect); } /// - protected override void ConfigureEffectGraph() + protected override void ConfigureEffectGraph(EffectGraph effectGraph) { - this.pixelShaderEffect!.ConstantBuffer = new ContouredLayers((float)ElapsedTime.TotalSeconds, new int2(ScreenWidth, ScreenHeight)); - } - - /// - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - if (disposing) - { - this.pixelShaderEffect?.Dispose(); - } + effectGraph.GetNode(PixelShaderEffect).ConstantBuffer = new ContouredLayers((float)ElapsedTime.TotalSeconds, new int2(ScreenWidth, ScreenHeight)); } } \ No newline at end of file diff --git a/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/PixelShaderEffect.cs b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/PixelShaderEffect.cs index 44175d6a..65fd73ff 100644 --- a/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/PixelShaderEffect.cs +++ b/samples/ComputeSharp.SwapChain.D2D1.Cli/Backend/PixelShaderEffect.cs @@ -59,16 +59,16 @@ internal abstract class PixelShaderEffect : CanvasEffect public sealed class For : PixelShaderEffect where T : unmanaged, ID2D1PixelShader { + /// + /// The node in use. + /// + private static readonly EffectNode> Effect = new(); + /// /// The factory to use. /// private readonly Factory factory; - /// - /// The instance in use. - /// - private PixelShaderEffect? effect; - /// /// Creates a new instance with the specified parameters. /// @@ -79,28 +79,15 @@ internal abstract class PixelShaderEffect : CanvasEffect } /// - protected override ICanvasImage BuildEffectGraph() + protected override void BuildEffectGraph(EffectGraph effectGraph) { - this.effect = new PixelShaderEffect(); - - return this.effect; + effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect()); } /// - protected override void ConfigureEffectGraph() + protected override void ConfigureEffectGraph(EffectGraph effectGraph) { - this.effect!.ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight); - } - - /// - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - if (disposing) - { - this.effect?.Dispose(); - } + effectGraph.GetNode(Effect).ConstantBuffer = this.factory(ElapsedTime, ScreenWidth, ScreenHeight); } /// diff --git a/src/ComputeSharp.Core/Polyfills/InvalidOperationExceptionExtensions.cs b/src/ComputeSharp.Core/Polyfills/InvalidOperationExceptionExtensions.cs index 38a6cd11..c5f082c6 100644 --- a/src/ComputeSharp.Core/Polyfills/InvalidOperationExceptionExtensions.cs +++ b/src/ComputeSharp.Core/Polyfills/InvalidOperationExceptionExtensions.cs @@ -36,7 +36,22 @@ internal static class InvalidOperationExceptionExtensions } /// - /// Throws an for a given parameter name. + /// Throws an if is . + /// + /// Dummy value to invoke the extension upon (always pass . + /// The condition to decide whether to throw the exception. + /// The message to include in the exception. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ThrowIf(this InvalidOperationException? _, [DoesNotReturnIf(true)] bool condition, string message) + { + if (condition) + { + Throw(message); + } + } + + /// + /// Throws an . /// /// Always thrown with no parameters. [DoesNotReturn] @@ -44,4 +59,15 @@ internal static class InvalidOperationExceptionExtensions { throw new InvalidOperationException(); } + + /// + /// Throws an with a given message. + /// + /// The message to include in the exception. + /// Always thrown with no parameters. + [DoesNotReturn] + private static void Throw(string message) + { + throw new InvalidOperationException(message); + } } diff --git a/src/ComputeSharp.D2D1.UI/CanvasEffect.EffectGraph.cs b/src/ComputeSharp.D2D1.UI/CanvasEffect.EffectGraph.cs new file mode 100644 index 00000000..9af0f2a7 --- /dev/null +++ b/src/ComputeSharp.D2D1.UI/CanvasEffect.EffectGraph.cs @@ -0,0 +1,265 @@ +using System; +using System.Runtime.CompilerServices; +using Microsoft.Graphics.Canvas; + +#if WINDOWS_UWP +namespace ComputeSharp.D2D1.Uwp; +#else +namespace ComputeSharp.D2D1.WinUI; +#endif + +/// +partial class CanvasEffect +{ + /// + /// An object representing an effect graph being built or configured. + /// + protected readonly ref struct EffectGraph + { + /// + ///The owning instance. + /// + private readonly CanvasEffect owner; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The owning instance. + internal EffectGraph(CanvasEffect owner) + { + this.owner = owner; + } + + /// + /// Gets a previously registered object associated with a given effect graph node. + /// + /// The instance to use to lookup the object to retrieve. + /// The object associated with in the effect graph. + /// Thrown if is . + /// Thrown if is not currently registered in the effect graph. + /// Thrown if the current instance is not valid. + public ICanvasImage GetNode(IEffectNode effectNode) + { + default(ArgumentNullException).ThrowIfNull(effectNode); + default(InvalidOperationException).ThrowIf(this.owner is null); + + // Try to get the canvas image associated with the input effect node marker. + // This must have been previously registered in a call to BuildEffectGraph. + if (!this.owner.transformNodes.TryGetValue(effectNode, out ICanvasImage? canvasImage)) + { + default(ArgumentException).Throw(nameof(effectNode), "The specified node is not registered in the effect graph."); + } + + return canvasImage; + } + + /// + /// Gets a previously registered object (an instance) associated with a given effect graph node. + /// + /// The type of object to retrieve. + /// The instance to use to lookup the object to retrieve. + /// The object associated with in the effect graph. + /// Thrown if is . + /// Thrown if is not currently registered in the effect graph. + /// Thrown if the current instance is not valid. + public T GetNode(IEffectNode effectNode) + where T : class, ICanvasImage + { + default(ArgumentNullException).ThrowIfNull(effectNode); + default(InvalidOperationException).ThrowIf(this.owner is null); + + // Retrieve the registered canvas image, same as above + if (!this.owner.transformNodes.TryGetValue(effectNode, out ICanvasImage? canvasImage)) + { + default(ArgumentException).Throw(nameof(effectNode), "The specified node is not registered in the effect graph."); + } + + // Return the T node (we can skip the expensive cast since this is guaranteed to be valid). + // This is because EffectNode being registered can only associate T instances with them. + return Unsafe.As(canvasImage); + } + + /// + /// Registers an object in the effect graph. + /// + /// The object to register in the effect graph. + /// Thrown if is . + /// + /// Thrown if the current instance is not valid or if the effect graph does not support modifications at this time. + /// + /// + /// + /// + /// This method can be used when doesn't need to be retrieved from , ie. + /// when it has no properties that the current effect instance will need to mutate over it. Using this method still allows the effect to + /// correctly track the image ownership, so that it can be disposed when the current effect instance is disposed. + /// + /// + /// If performing lookups on is required, use the overload. + /// + /// + public void RegisterNode(ICanvasImage canvasImage) + { + default(ArgumentNullException).ThrowIfNull(canvasImage); + default(InvalidOperationException).ThrowIf(this.owner is null); + default(InvalidOperationException).ThrowIf(this.owner.invalidationType != InvalidationType.Creation, "The effect graph cannot be modified after its creation."); + + // Use a new dummy object as key to register the anonymous effect node. This is cheaper than having to maintain a different + // data structure (eg. a HashSet instance) just to hold the anonymous effects that may be registered. This way, + // the same dictionary can be reused for all kinds of effect nodes instead. Anonymous effects are generally a nicher scenario. + _ = this.owner.transformNodes.TryAdd(new object(), canvasImage); + } + + /// + /// Registers an object in the effect graph, associated with a given instance. + /// + /// The type of object to register. + /// The instance to use to register . + /// The object to register in the effect graph. + /// Thrown if or are . + /// + /// Thrown if the current instance is not valid or if the effect graph does not support modifications at this time. + /// + /// Thrown if is already registered in the effect graph. + /// + /// This method can only be called from an value being passed to . If this + /// method is called from within , it will fail, as the effect graph cannot be mutated from there. + /// + public void RegisterNode(EffectNode effectNode, T canvasImage) + where T : class, ICanvasImage + { + default(ArgumentNullException).ThrowIfNull(effectNode); + default(ArgumentNullException).ThrowIfNull(canvasImage); + default(InvalidOperationException).ThrowIf(this.owner is null); + default(InvalidOperationException).ThrowIf(this.owner.invalidationType != InvalidationType.Creation, "The effect graph cannot be modified after its creation."); + + // Try to add the new canvas image associated with the input effect node marker. + // This must not have been previously added from another RegisterNode call. + if (!this.owner.transformNodes.TryAdd(effectNode, canvasImage)) + { + default(ArgumentException).Throw(nameof(effectNode), "The specified node is already registered in the effect graph."); + } + } + + /// + /// Registers an object in the effect graph, and marks it as the output node for the effect graph being built. + /// + /// + /// + /// + /// This method can be used when doesn't need to be retrieved from , ie. + /// when it has no properties that the current effect instance will need to mutate over it. Using this method still allows the effect to + /// correctly track the image ownership, so that it can be disposed when the current effect instance is disposed. + /// + /// + /// If performing lookups on is required, use the overload. + /// + /// + /// + public void RegisterOutputNode(ICanvasImage canvasImage) + { + default(ArgumentNullException).ThrowIfNull(canvasImage); + default(InvalidOperationException).ThrowIf(this.owner is null); + default(InvalidOperationException).ThrowIf(this.owner.invalidationType != InvalidationType.Creation, "The effect graph cannot be modified after its creation."); + + // Register the anonymous effect node with a dummy object, same as above + _ = this.owner.transformNodes.TryAdd(new object(), canvasImage); + + // Store the anonymous output node for later use + this.owner.canvasImage = canvasImage; + } + + /// + /// Registers an object in the effect graph, associated with a given instance. + /// Additionally, it also marks the input object as the output node for the effect graph being built. + /// + /// + public void RegisterOutputNode(EffectNode effectNode, T canvasImage) + where T : class, ICanvasImage + { + default(ArgumentNullException).ThrowIfNull(effectNode); + default(ArgumentNullException).ThrowIfNull(canvasImage); + default(InvalidOperationException).ThrowIf(this.owner is null); + default(InvalidOperationException).ThrowIf(this.owner.invalidationType != InvalidationType.Creation, "The effect graph cannot be modified after its creation."); + + // Try to add the output node as in the method above (but with an extra check before doing so) + if (!this.owner.transformNodes.TryAdd(effectNode, canvasImage)) + { + default(ArgumentException).Throw(nameof(effectNode), "The specified node is already registered in the effect graph."); + } + + // Store the output node for later use + this.owner.canvasImage = canvasImage; + } + + /// + /// Sets a previously registered instance as the output node for the effect graph. + /// + /// The instance to set as output node for the effect graph. + /// Thrown if is . + /// Thrown if the current instance is not valid. + /// Thrown if is not registered in the effect graph. + /// + /// This method can be called from both and . It can be used for + /// efficiently changing the output node of a graph, without having to rebuild it. For instance, this can be used for effects that + /// have multiple paths that can be taken for their inputs, depending on the value of some property describing the effect behavior. + /// + public void SetOutputNode(IEffectNode effectNode) + { + default(ArgumentNullException).ThrowIfNull(effectNode); + default(InvalidOperationException).ThrowIf(this.owner is null); + + // Get the canvas image for the registered effect node (which has to exist at this point) + if (!this.owner.transformNodes.TryGetValue(effectNode, out ICanvasImage? canvasImage)) + { + default(ArgumentException).Throw(nameof(effectNode), "The specified output node is not registered in the effect graph."); + } + + // Store the new output node + this.owner.canvasImage = canvasImage; + } + } + + /// + /// A marker interface for an effect node that was registered from an value. + /// + /// + /// + /// This interface allows using and in more scenarios, + /// including where the concrete type of the image being used (eg. to set the output node) is not known (or needed) by the caller. + /// + /// + /// This interface only implemented by and it's not meant to be implemented by external types. + /// + /// + protected interface IEffectNode + { + } + + /// + /// A marker interface for a generic effect node that was registered from an value. + /// + /// The covariant type of associated with the current effect node. + /// + /// + /// This interface allows using and in more scenarios, + /// including with ternary expressions returning multiple concrete instances with a common image type. + /// + /// + /// This interface only implemented by and it's not meant to be implemented by external types. + /// + /// + protected interface IEffectNode : IEffectNode + where T : ICanvasImage + { + } + + /// + /// A marker type for an effect node that can be registered and retrieved from an value. + /// + /// The type of associated with the current effect node. + protected sealed class EffectNode : IEffectNode + where T : class, ICanvasImage + { + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.UI/CanvasEffect.Interop.cs b/src/ComputeSharp.D2D1.UI/CanvasEffect.Interop.cs index e3a6ea74..29bc06f4 100644 --- a/src/ComputeSharp.D2D1.UI/CanvasEffect.Interop.cs +++ b/src/ComputeSharp.D2D1.UI/CanvasEffect.Interop.cs @@ -69,20 +69,55 @@ unsafe partial class CanvasEffect [MemberNotNull(nameof(canvasImage))] private ICanvasImage GetCanvasImage() { - lock (this.lockObject) + lock (this.transformNodes) { default(ObjectDisposedException).ThrowIf(this.isDisposed, this); - this.canvasImage ??= BuildEffectGraph(); - - if (this.isInvalidated) + // Build the effect graph (the output node might not have been set yet) + if (this.invalidationType == InvalidationType.Creation) { - ConfigureEffectGraph(); + DisposeEffectGraph(); + BuildEffectGraph(new EffectGraph(this)); - this.isInvalidated = false; + // We successfully got past the effect graph creation, so update the current + // invalidation state. This ensures that even if the configuration failed, the + // next time the effect is drawn again the graph won't be created again too. + this.invalidationType = InvalidationType.Update; } + // Configure the effect graph, if the effect is invalidated + if (this.invalidationType == InvalidationType.Update) + { + ConfigureEffectGraph(new EffectGraph(this)); + + // The effect graph is now ready to go: no further work will be done before drawing + // unless it is explicitly invalidated again, using either creation or update mode. + this.invalidationType = default; + } + + // At this point, there must be an output canvas image being set. + // If not, it means a derived type has forgot to set an output node. + default(InvalidOperationException).ThrowIf(this.canvasImage is null, "No output node is set in the effect graph."); + return this.canvasImage; } } + + /// + /// Disposes and clears the current effect graph, if any. + /// + private void DisposeEffectGraph() + { + // Dispose all registered canvas images + foreach (ICanvasImage canvasImage in this.transformNodes.Values) + { + canvasImage.Dispose(); + } + + // Also clear the current effect graph. Note that the canvas image used as output + // node for the effect graph does not need to be explicitly disposed here, as that + // object is guaranteed to have been part of the dictionary of transform nodes. + this.transformNodes.Clear(); + this.canvasImage = null; + } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.UI/CanvasEffect.cs b/src/ComputeSharp.D2D1.UI/CanvasEffect.cs index 898aa459..c9cdbf63 100644 --- a/src/ComputeSharp.D2D1.UI/CanvasEffect.cs +++ b/src/ComputeSharp.D2D1.UI/CanvasEffect.cs @@ -16,9 +16,12 @@ namespace ComputeSharp.D2D1.WinUI; public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.Interface { /// - /// Lock object used to synchronize calls to APIs. + /// The mapping of registered transform nodes for the current effect graph. /// - private readonly object lockObject = new(); + /// + /// When not empty (ie. when an effect graph has been built), this will always also include . + /// + private readonly Dictionary transformNodes = new(); /// /// The current cached result for , if available. @@ -26,13 +29,9 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I private ICanvasImage? canvasImage; /// - /// Indicates whether the current state has been invalidated (requiring to be called). + /// Indicates the current invalidation state for the effect graph (which controls the logic in ). /// - /// - /// This is initially so that will always be called when - /// first creating the image, even if the effect has not bee invalidated. This ensures default parameters are set. - /// - private bool isInvalidated = true; + private InvalidationType invalidationType = InvalidationType.Creation; /// /// Indicates whether the effect is disposed. @@ -40,10 +39,10 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I private bool isDisposed; /// - /// Builds the effect graph for the current instance, and returns an object - /// representing the output node of the graph. This image will then be passed to Win2D to perform the actual drawing, when needed. + /// Builds the effect graph for the current instance, and configures all effect nodes, as well as the output + /// node for the graph. That instance will then be passed to Win2D to perform the actual drawing, when needed. /// - /// The resulting object representing the output node of the effect graph. + /// The input value to use to build the effect graph. /// /// /// This method is called once before the current effect is drawn, and the resulting image is automatically cached and reused. @@ -74,29 +73,33 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I /// /// Create an instance of all necessary nodes in the effect graph. /// Connect the effect nodes as needed to build the connected graph. - /// Save all effects that can be configured as instance fields in the effect type. - /// Return the instance for the output node of the graph. + /// Register all effects as effect nodes in the graph, including the output node. /// /// /// - /// This method should never be called directly. It is automatically invoked when an is needed. + /// For convenience, it is recommended to store all necessary objects in + /// fields, so they can easily be accessed from and . + /// + /// + /// This method should never be called directly. It is automatically invoked when an effect graph is needed. /// /// - protected abstract ICanvasImage BuildEffectGraph(); + protected abstract void BuildEffectGraph(EffectGraph effectGraph); /// /// Configures the current effect graph whenever it is invalidated. /// + /// The input value to use to configure the effect graph. /// /// /// This method is guaranteed to be called after has been invoked already. As such, any instance /// fields that are set by can be assumed to never be when this method runs. /// /// - /// This method should never be called directly. It is used internally to configure the current instance. + /// This method should never be called directly. It is used internally to configure the current effect graph. /// /// - protected abstract void ConfigureEffectGraph(); + protected abstract void ConfigureEffectGraph(EffectGraph effectGraph); /// /// Invalidates the last returned result from . @@ -116,20 +119,15 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I /// protected void InvalidateEffectGraph(InvalidationType invalidationType = InvalidationType.Update) { - lock (this.lockObject) + lock (this.transformNodes) { - // If the effect graph should be created again, dispose the image and throw it away - if (invalidationType == InvalidationType.Creation) - { - this.canvasImage?.Dispose(); - - this.canvasImage = null; - } - - // 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; + // This method only updates the invalidation type. The next time the effect is drawn, + // the current graph (if existing) will be disposed automatically before building a + // new one. If the invalidation mode just needs an update, no disposal will happen. + // The new invalidation type is always set to the maximum between the current one and + // the requested one. This means that eg. if the current invalidation type is creation, + // and a property only needing an update is set, the creation request will persist. + this.invalidationType = (InvalidationType)Math.Max((byte)this.invalidationType, (byte)invalidationType); } } @@ -191,10 +189,9 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I // the lock itself might have already been collected by the time this code runs, which would lead the lock // statement to throw a NullReferenceException. So if a finalizer is running, just let objects be collected // on their own. This is fine here since there are no unmanaged references to free, but just managed wrappers. - lock (this.lockObject) + lock (this.transformNodes) { - this.canvasImage?.Dispose(); - this.canvasImage = null; + DisposeEffectGraph(); } } @@ -212,17 +209,8 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I /// /// Indicates the invalidation type to request when invoking and related methods. /// - protected enum InvalidationType + protected enum InvalidationType : byte { - /// - /// Fully invalidates the effect graph, causing it to be created again the next time it is needed. - /// - /// - /// This will cause the last returned instance to be disposed and discarded, - /// and to be called again the next time the effect is used for drawing. - /// - Creation, - /// /// Invalidates the state of the effect graph, causing it to be configured again the next time it is used. /// @@ -236,6 +224,15 @@ public abstract partial class CanvasEffect : ICanvasImage, ICanvasImageInterop.I /// This is much less expensive than creating the effect graph again, and should be preferred if possible. /// /// - Update + Update, + + /// + /// Fully invalidates the effect graph, causing it to be created again the next time it is needed. + /// + /// + /// This will cause the last returned instance to be disposed and discarded, + /// and to be called again the next time the effect is used for drawing. + /// + Creation } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.UI/ComputeSharp.D2D1.UI.projitems b/src/ComputeSharp.D2D1.UI/ComputeSharp.D2D1.UI.projitems index 2bdd3aaf..16149cbc 100644 --- a/src/ComputeSharp.D2D1.UI/ComputeSharp.D2D1.UI.projitems +++ b/src/ComputeSharp.D2D1.UI/ComputeSharp.D2D1.UI.projitems @@ -26,6 +26,7 @@ + diff --git a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs index 94dbdfad..1a1630ad 100644 --- a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs +++ b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.ResourceTextureManagerCollection.cs @@ -92,7 +92,7 @@ partial class PixelShaderEffect internal static ImmutableArray Indices { get; } = GetIndices(); /// - /// The owning instance. + /// Gets the owning instance. /// internal PixelShaderEffect Owner { get; } diff --git a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.SourceCollection.cs b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.SourceCollection.cs index 8fe5889b..69c3369d 100644 --- a/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.SourceCollection.cs +++ b/src/ComputeSharp.D2D1.UI/PixelShaderEffect{T}.Properties.SourceCollection.cs @@ -78,7 +78,7 @@ partial class PixelShaderEffect } /// - /// The owning instance. + /// Gets the owning instance. /// internal PixelShaderEffect Owner { get; } diff --git a/tests/ComputeSharp.D2D1.UI.Tests/CanvasEffectTests.cs b/tests/ComputeSharp.D2D1.UI.Tests/CanvasEffectTests.cs index 1f293ee2..6bdccd44 100644 --- a/tests/ComputeSharp.D2D1.UI.Tests/CanvasEffectTests.cs +++ b/tests/ComputeSharp.D2D1.UI.Tests/CanvasEffectTests.cs @@ -1,10 +1,22 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Numerics; +using System.Threading.Tasks; +using ComputeSharp.D2D1.UI.Tests.Helpers; #if WINDOWS_UWP using ComputeSharp.D2D1.Uwp; #else using ComputeSharp.D2D1.WinUI; #endif +using ComputeSharp.SwapChain.Shaders.D2D1; using Microsoft.Graphics.Canvas; +using Microsoft.Graphics.Canvas.Effects; using Microsoft.VisualStudio.TestTools.UnitTesting; +using TerraFX.Interop.Windows; +using Windows.Foundation; +using Windows.Storage; +using Windows.UI; #nullable enable @@ -15,7 +27,7 @@ namespace ComputeSharp.D2D1.UI.Tests; public partial class CanvasEffectTests { [TestMethod] - public unsafe void CanvasEffect_IsRealizedAndInvalidatedCorrectly() + public void CanvasEffect_IsRealizedAndInvalidatedCorrectly() { EffectWithNoInputs effect = new(); @@ -63,9 +75,315 @@ public partial class CanvasEffectTests } } + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void CanvasEffect_EffectSettingNotRegisteredOutputNode() + { + EffectSettingNotRegisteredOutputNode effect = new(); + + try + { + using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f); + using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession(); + + drawingSession.DrawImage(effect); + } + catch + { + Assert.IsTrue(effect.WasConfigureEffectGraphCalled); + + throw; + } + } + + [TestMethod] + [ExpectedException(typeof(InvalidOperationException))] + public void CanvasEffect_EffectNotRegisteringAnOutputNode() + { + EffectNotRegisteringAnOutputNode effect = new(); + + try + { + using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f); + using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession(); + + drawingSession.DrawImage(effect); + } + catch + { + Assert.IsTrue(effect.WasConfigureEffectGraphCalled); + + throw; + } + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void CanvasEffect_EffectRegisteringNodesMultipleTimes1() + { + EffectRegisteringNodesMultipleTimes1 effect = new(); + + using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f); + using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession(); + + drawingSession.DrawImage(effect); + } + + [TestMethod] + [ExpectedException(typeof(ArgumentException))] + public void CanvasEffect_EffectRegisteringNodesMultipleTimes2() + { + EffectRegisteringNodesMultipleTimes2 effect = new(); + + using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f); + using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession(); + + drawingSession.DrawImage(effect); + } + + [TestMethod] + public void CanvasEffect_EffectRegisteringNullObjects() + { + EffectRegisteringNullObjects effect = new(); + + using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f); + using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession(); + + drawingSession.DrawImage(effect); + } + + [TestMethod] + public void CanvasEffect_EffectConfiguringGraphIncorrectly() + { + EffectConfiguringGraphIncorrectly effect = new(); + + using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f); + using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession(); + + drawingSession.DrawImage(effect); + } + + [TestMethod] + public void CanvasEffect_EffectOnlyUsingAnonymousNodes() + { + EffectOnlyUsingAnonymousNodes effect = new(); + + using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f); + using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession(); + + drawingSession.DrawImage(effect); + } + + [TestMethod] + public void CanvasEffect_EffectUsingEffectGraphInInvalidState() + { + EffectUsingEffectGraphInInvalidState effect = new(); + + using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f); + using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession(); + + drawingSession.DrawImage(effect); + } + + [TestMethod] + public async Task CanvasEffect_PixelShaderSwitchEffect() + { + PixelShaderSwitchEffect effect = new(); + + async Task TestAsync(string shaderName) + { + Color[] pixelColors; + + using CanvasDevice canvasDevice = new(); + + // Same logic as in the shader tests + using (CanvasRenderTarget renderTarget = new(canvasDevice, 1280, 720, 96.0f)) + { + using (CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession()) + { + drawingSession.DrawImage(effect); + } + + pixelColors = renderTarget.GetPixelColors(); + } + + StorageFile imageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Assets/Shaders/{shaderName}.png")); + + 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: 0.00001f); + } + + // Every time the effect is re-drawn, a different shader is set as the output node + await TestAsync(nameof(HelloWorld)); + await TestAsync(nameof(ColorfulInfinity)); + await TestAsync(nameof(FractalTiling)); + await TestAsync(nameof(Octagrams)); + await TestAsync(nameof(ProteanClouds)); + } + + [TestMethod] + public void CanvasEffect_EffectTestingDisposal() + { + EffectTestingDisposal effect = new(); + + using CanvasRenderTarget renderTarget = new(new CanvasDevice(), 128, 128, 96.0f); + using CanvasDrawingSession drawingSession = renderTarget.CreateDrawingSession(); + + // Force creating the graph (the drawing fails because the effects are dummies) + try + { + drawingSession.DrawImage(effect); + } + catch (Exception e) when (e.HResult == E.E_FAIL) + { + } + + Assert.AreEqual(1, effect.Effects1.Count); + Assert.AreEqual(1, effect.Effects2.Count); + Assert.AreEqual(1, effect.Effects3.Count); + Assert.AreEqual(0, effect.Effects1[0].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects2[0].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects3[0].NumberOfDisposeCalls); + + effect.InvalidateCreation(); + + // Effects aren't disposed yet until we redraw + Assert.AreEqual(1, effect.Effects1.Count); + Assert.AreEqual(1, effect.Effects2.Count); + Assert.AreEqual(1, effect.Effects3.Count); + Assert.AreEqual(0, effect.Effects1[0].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects2[0].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects3[0].NumberOfDisposeCalls); + + // Redraw, which builds a new effect graph and disposes the old one + try + { + drawingSession.DrawImage(effect); + } + catch (Exception e) when (e.HResult == E.E_FAIL) + { + } + + Assert.AreEqual(2, effect.Effects1.Count); + Assert.AreEqual(2, effect.Effects2.Count); + Assert.AreEqual(2, effect.Effects3.Count); + Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls); + + // Redrawing now doesn't change anything + try + { + drawingSession.DrawImage(effect); + } + catch (Exception e) when (e.HResult == E.E_FAIL) + { + } + + Assert.AreEqual(2, effect.Effects1.Count); + Assert.AreEqual(2, effect.Effects2.Count); + Assert.AreEqual(2, effect.Effects3.Count); + Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls); + + effect.InvalidateUpdate(); + + // Invalidating with update mode also doesn't do anything here + Assert.AreEqual(2, effect.Effects1.Count); + Assert.AreEqual(2, effect.Effects2.Count); + Assert.AreEqual(2, effect.Effects3.Count); + Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls); + + // Redraw, and also verify the disposal state wasn't changed + try + { + drawingSession.DrawImage(effect); + } + catch (Exception e) when (e.HResult == E.E_FAIL) + { + } + + Assert.AreEqual(2, effect.Effects1.Count); + Assert.AreEqual(2, effect.Effects2.Count); + Assert.AreEqual(2, effect.Effects3.Count); + Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls); + + // Verify that invalidating with update after creation is ignored + effect.InvalidateCreation(); + effect.InvalidateUpdate(); + + Assert.AreEqual(2, effect.Effects1.Count); + Assert.AreEqual(2, effect.Effects2.Count); + Assert.AreEqual(2, effect.Effects3.Count); + Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects1[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects2[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects3[1].NumberOfDisposeCalls); + + // Redraw, disposing the old graph once again + try + { + drawingSession.DrawImage(effect); + } + catch (Exception e) when (e.HResult == E.E_FAIL) + { + } + + Assert.AreEqual(3, effect.Effects1.Count); + Assert.AreEqual(3, effect.Effects2.Count); + Assert.AreEqual(3, effect.Effects3.Count); + Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects1[1].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects2[1].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects3[1].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects1[2].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects2[2].NumberOfDisposeCalls); + Assert.AreEqual(0, effect.Effects3[2].NumberOfDisposeCalls); + + // Finally dispose the effect + effect.Dispose(); + + Assert.AreEqual(3, effect.Effects1.Count); + Assert.AreEqual(3, effect.Effects2.Count); + Assert.AreEqual(3, effect.Effects3.Count); + Assert.AreEqual(1, effect.Effects1[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects2[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects3[0].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects1[1].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects2[1].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects3[1].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects1[2].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects2[2].NumberOfDisposeCalls); + Assert.AreEqual(1, effect.Effects3[2].NumberOfDisposeCalls); + } + private sealed class EffectWithNoInputs : CanvasEffect { - private PixelShaderEffect? effect; + private static readonly EffectNode> Effect = new(); private int value; @@ -87,18 +405,21 @@ public partial class CanvasEffectTests public int NumberOfDisposeCalls { get; private set; } - protected override ICanvasImage BuildEffectGraph() + protected override void BuildEffectGraph(EffectGraph effectGraph) { NumberOfBuildEffectGraphCalls++; - return this.effect = new PixelShaderEffect(); + effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect()); } - protected override void ConfigureEffectGraph() + protected override void ConfigureEffectGraph(EffectGraph effectGraph) { NumberOfConfigureEffectGraphCalls++; - this.effect!.ConstantBuffer = new ShaderWithNoInputs(this.value); + effectGraph.GetNode(Effect).ConstantBuffer = new ShaderWithNoInputs(this.value); + + // Also test the non-generic overload + Assert.IsTrue(effectGraph.GetNode((IEffectNode)Effect) is PixelShaderEffect); } protected override void Dispose(bool disposing) @@ -106,8 +427,273 @@ public partial class CanvasEffectTests NumberOfDisposeCalls++; base.Dispose(disposing); + } + } - this.effect?.Dispose(); + private sealed class EffectSettingNotRegisteredOutputNode : CanvasEffect + { + public bool WasConfigureEffectGraphCalled { get; private set; } + + protected override void BuildEffectGraph(EffectGraph effectGraph) + { + effectGraph.RegisterOutputNode(new EffectNode(), new ColorSourceEffect()); + effectGraph.RegisterOutputNode(new EffectNode(), new ColorSourceEffect()); + } + + protected override void ConfigureEffectGraph(EffectGraph effectGraph) + { + WasConfigureEffectGraphCalled = true; + + effectGraph.SetOutputNode(new EffectNode()); + } + } + + private sealed class EffectNotRegisteringAnOutputNode : CanvasEffect + { + public bool WasConfigureEffectGraphCalled { get; private set; } + + protected override void BuildEffectGraph(EffectGraph effectGraph) + { + effectGraph.RegisterNode(new ColorSourceEffect()); + effectGraph.RegisterNode(new EffectNode(), new ColorSourceEffect()); + effectGraph.RegisterNode(new EffectNode(), new ColorSourceEffect()); + } + + protected override void ConfigureEffectGraph(EffectGraph effectGraph) + { + WasConfigureEffectGraphCalled = true; + } + } + + private sealed class EffectRegisteringNodesMultipleTimes1 : CanvasEffect + { + protected override void BuildEffectGraph(EffectGraph effectGraph) + { + EffectNode node = new(); + + effectGraph.RegisterNode(node, new ColorSourceEffect()); + effectGraph.RegisterOutputNode(node, new ColorSourceEffect()); + } + + protected override void ConfigureEffectGraph(EffectGraph effectGraph) + { + Assert.Fail(); + } + } + + private sealed class EffectRegisteringNodesMultipleTimes2 : CanvasEffect + { + protected override void BuildEffectGraph(EffectGraph effectGraph) + { + EffectNode node = new(); + + effectGraph.RegisterNode(node, new ColorSourceEffect()); + effectGraph.RegisterNode(node, new ColorSourceEffect()); + effectGraph.RegisterOutputNode(new EffectNode(), new ColorSourceEffect()); + } + + protected override void ConfigureEffectGraph(EffectGraph effectGraph) + { + Assert.Fail(); + } + } + + private sealed class EffectRegisteringNullObjects : CanvasEffect + { + protected override unsafe void BuildEffectGraph(EffectGraph effectGraph) + { + // Verify that if the effect graph is invalid, arguments are validated first + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterNode(null!)); + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterNode(null!, new ColorSourceEffect())); + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterNode(new EffectNode(), null!)); + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterNode(null!, (ColorSourceEffect?)null!)); + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterOutputNode(null!)); + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterOutputNode(null!, new ColorSourceEffect())); + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterOutputNode(new EffectNode(), null!)); + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterOutputNode(null!, (ColorSourceEffect)null!)); + + void* ptr = &effectGraph; + + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).RegisterNode(null!)); + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).RegisterNode(null!, new ColorSourceEffect())); + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).RegisterNode(new EffectNode(), null!)); + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).RegisterNode(null!, (ColorSourceEffect?)null!)); + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).RegisterOutputNode(null!)); + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).RegisterOutputNode(null!, new ColorSourceEffect())); + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).RegisterOutputNode(new EffectNode(), null!)); + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).RegisterOutputNode(null!, (ColorSourceEffect)null!)); + + effectGraph.RegisterOutputNode(new EffectNode(), new ColorSourceEffect()); + } + + protected override void ConfigureEffectGraph(EffectGraph effectGraph) + { + } + } + + private sealed class EffectConfiguringGraphIncorrectly : CanvasEffect + { + private static readonly EffectNode EffectNode1 = new(); + private static readonly EffectNode EffectNode2 = new(); + private static readonly EffectNode EffectNode3 = new(); +#pragma warning disable CA2213 + private readonly ColorSourceEffect effect1 = new(); + private readonly ColorSourceEffect effect2 = new(); + private readonly ColorSourceEffect effect3 = new(); +#pragma warning restore CA2213 + + protected override void BuildEffectGraph(EffectGraph effectGraph) + { + effectGraph.RegisterNode(EffectNode1, this.effect1); + effectGraph.RegisterNode(EffectNode2, this.effect2); + effectGraph.RegisterOutputNode(EffectNode3, this.effect3); + } + + protected override unsafe void ConfigureEffectGraph(EffectGraph effectGraph) + { + void* ptr = &effectGraph; + + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).GetNode((EffectNode)null!)); + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).GetNode(new EffectNode())); + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).RegisterNode(new EffectNode(), new ColorSourceEffect())); + _ = Assert.ThrowsException(() => (*(EffectGraph*)ptr).RegisterOutputNode(new EffectNode(), new ColorSourceEffect())); + + Assert.AreSame(effectGraph.GetNode(EffectNode1), this.effect1); + Assert.AreSame(effectGraph.GetNode(EffectNode2), this.effect2); + Assert.AreSame(effectGraph.GetNode(EffectNode3), this.effect3); + } + } + + private sealed class EffectOnlyUsingAnonymousNodes : CanvasEffect + { + protected override void BuildEffectGraph(EffectGraph effectGraph) + { + effectGraph.RegisterNode(new ColorSourceEffect()); + effectGraph.RegisterNode(new ColorSourceEffect()); + effectGraph.RegisterOutputNode(new ColorSourceEffect()); + } + + protected override void ConfigureEffectGraph(EffectGraph effectGraph) + { + } + } + + private sealed class EffectUsingEffectGraphInInvalidState : CanvasEffect + { + protected override void BuildEffectGraph(EffectGraph effectGraph) + { + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterNode(new ColorSourceEffect())); + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterNode(new EffectNode(), new ColorSourceEffect())); + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterOutputNode(new ColorSourceEffect())); + _ = Assert.ThrowsException(() => default(EffectGraph).RegisterOutputNode(new EffectNode(), new ColorSourceEffect())); + + effectGraph.RegisterOutputNode(new EffectNode(), new ColorSourceEffect()); + } + + protected override void ConfigureEffectGraph(EffectGraph effectGraph) + { + _ = Assert.ThrowsException(() => default(EffectGraph).GetNode(new EffectNode())); + } + } + + private sealed class PixelShaderSwitchEffect : CanvasEffect + { + private static readonly EffectNode> HelloWorldNode = new(); + private static readonly EffectNode> ColorfulInfinityNode = new(); + private static readonly EffectNode> FractalTilingNode = new(); + private static readonly EffectNode> OctagramsNode = new(); + private static readonly EffectNode> ProteanCloudsNode = new(); + + private int step; + + protected override void BuildEffectGraph(EffectGraph effectGraph) + { + effectGraph.RegisterNode(HelloWorldNode, new PixelShaderEffect { ConstantBuffer = new HelloWorld(0, new int2(1280, 720)) }); + effectGraph.RegisterNode(ColorfulInfinityNode, new PixelShaderEffect { ConstantBuffer = new ColorfulInfinity(0, new int2(1280, 720)) }); + effectGraph.RegisterNode(FractalTilingNode, new PixelShaderEffect { ConstantBuffer = new FractalTiling(0, new int2(1280, 720)) }); + effectGraph.RegisterNode(OctagramsNode, new PixelShaderEffect { ConstantBuffer = new Octagrams(0, new int2(1280, 720)) }); + effectGraph.RegisterNode(ProteanCloudsNode, new PixelShaderEffect { ConstantBuffer = new ProteanClouds(0, new int2(1280, 720)) }); + effectGraph.SetOutputNode(HelloWorldNode); + } + + protected override void ConfigureEffectGraph(EffectGraph effectGraph) + { + switch (this.step++) + { + case 0: break; + case 1: + effectGraph.SetOutputNode(ColorfulInfinityNode); + break; + case 2: + effectGraph.SetOutputNode(FractalTilingNode); + break; + case 3 or 4: + // Test the overload which is non-generic, allowing ternary expressions too + effectGraph.SetOutputNode(this.step == 4 ? OctagramsNode : ProteanCloudsNode); + break; + default: + Assert.Fail(); + break; + } + } + } + + private sealed class EffectTestingDisposal : CanvasEffect + { + private static readonly EffectNode EffectNode1 = new(); + private static readonly EffectNode EffectNode2 = new(); + private static readonly EffectNode EffectNode3 = new(); + public readonly List Effects1 = new(); + public readonly List Effects2 = new(); + public readonly List Effects3 = new(); + + public void InvalidateCreation() + { + InvalidateEffectGraph(InvalidationType.Creation); + } + + public void InvalidateUpdate() + { + InvalidateEffectGraph(InvalidationType.Update); + } + + protected override void BuildEffectGraph(EffectGraph effectGraph) + { + this.Effects1.Add(new DummyCanvasImageTrackingDisposal()); + this.Effects2.Add(new DummyCanvasImageTrackingDisposal()); + this.Effects3.Add(new DummyCanvasImageTrackingDisposal()); + + effectGraph.RegisterNode(EffectNode1, this.Effects1[^1]); + effectGraph.RegisterNode(EffectNode2, this.Effects2[^1]); + effectGraph.RegisterOutputNode(EffectNode3, this.Effects3[^1]); + } + + protected override void ConfigureEffectGraph(EffectGraph effectGraph) + { + } + } + + private sealed class DummyCanvasImageTrackingDisposal : ICanvasImage + { + public int NumberOfDisposeCalls { get; private set; } + + public Rect GetBounds(ICanvasResourceCreator resourceCreator) + { + Assert.Fail(); + + return default; + } + + public Rect GetBounds(ICanvasResourceCreator resourceCreator, Matrix3x2 transform) + { + Assert.Fail(); + + return default; + } + + public void Dispose() + { + NumberOfDisposeCalls++; } } diff --git a/tests/ComputeSharp.D2D1.UI.Tests/ShadersTests.cs b/tests/ComputeSharp.D2D1.UI.Tests/ShadersTests.cs index 071527b3..9a4a8b86 100644 --- a/tests/ComputeSharp.D2D1.UI.Tests/ShadersTests.cs +++ b/tests/ComputeSharp.D2D1.UI.Tests/ShadersTests.cs @@ -120,7 +120,7 @@ public class ShadersTests private sealed class TestCanvasEffect : CanvasEffect where T : unmanaged, ID2D1PixelShader { - private PixelShaderEffect? effect; + private static readonly EffectNode> Effect = new(); private T constantBuffer; @@ -130,21 +130,14 @@ public class ShadersTests set => SetAndInvalidateEffectGraph(ref this.constantBuffer, value); } - protected override ICanvasImage BuildEffectGraph() + protected override void BuildEffectGraph(EffectGraph effectGraph) { - return this.effect = new PixelShaderEffect(); + effectGraph.RegisterOutputNode(Effect, new PixelShaderEffect()); } - protected override void ConfigureEffectGraph() + protected override void ConfigureEffectGraph(EffectGraph effectGraph) { - this.effect!.ConstantBuffer = this.constantBuffer; - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - this.effect?.Dispose(); + effectGraph.GetNode(Effect).ConstantBuffer = this.constantBuffer; } }