From 95ef4571b03ebb30425819a9b1b90de87140a0f6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 22:34:58 +0100 Subject: [PATCH 01/61] Added more shared properties to .props file --- src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj | 1 - src/ComputeSharp/ComputeSharp.csproj | 2 -- src/Directory.Build.props | 2 ++ 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index 4c325294..f06c8d8c 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -2,7 +2,6 @@ net5.0 - true diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 9d310d55..958bf173 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -2,8 +2,6 @@ net5.0 - 9.0 - true diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 84867398..33aa3d0d 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,5 +1,7 @@ + true + 9.0 enable From c188aaa9f3a6c98380111a3d2171ffc337c193bf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 22:35:17 +0100 Subject: [PATCH 02/61] Removed unnecessary .Core dependency on .NET 5 --- src/ComputeSharp.Core/ComputeSharp.Core.csproj | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index e7c12eb8..a76d03f4 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -2,11 +2,10 @@ netstandard2.0;net5.0 - true - 9.0 - + + From 2b1e88fbd84a80c6a6f3795615ab7e2c305d88ed Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 22:35:48 +0100 Subject: [PATCH 03/61] Added .Graphics support for .NET Standard 2.0 --- nuget.config | 1 + .../Buffers/Abstract/Buffer{T}.cs | 12 +- .../Buffers/Views/BufferDebugView{T}.cs | 8 +- .../Interop/ID3D12CommandAllocatorPool.cs | 3 + .../ID3D12DescriptorHandleAllocator.cs | 7 +- .../ComputeSharp.Graphics.csproj | 10 +- .../Properties/Polyfills.cs | 122 ++++++++++++++++++ 7 files changed, 153 insertions(+), 10 deletions(-) create mode 100644 src/ComputeSharp.Graphics/Properties/Polyfills.cs diff --git a/nuget.config b/nuget.config index e71007c9..4f62278c 100644 --- a/nuget.config +++ b/nuget.config @@ -5,5 +5,6 @@ + diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs index 106501bc..b4bb2c61 100644 --- a/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs @@ -1,6 +1,5 @@ using System.Buffers; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Buffers.Enums; using ComputeSharp.Graphics.Extensions; @@ -8,6 +7,11 @@ using ComputeSharp.Graphics.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; +#if NET5_0 +using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal; +#else +using MemoryMarshal = ComputeSharp.System.Runtime.InteropServices.MemoryMarshal; +#endif namespace ComputeSharp.Graphics.Buffers.Abstract { @@ -138,9 +142,11 @@ namespace ComputeSharp.Graphics.Buffers.Abstract try { - source.GetData(ref MemoryMarshal.GetArrayDataReference(array), source.Length, 0); + ref T r0 = ref MemoryMarshal.GetArrayDataReference(array); - SetData(ref MemoryMarshal.GetArrayDataReference(array), source.Length, 0); + source.GetData(ref r0, source.Length, 0); + + SetData(ref r0, source.Length, 0); } finally { diff --git a/src/ComputeSharp.Graphics/Buffers/Views/BufferDebugView{T}.cs b/src/ComputeSharp.Graphics/Buffers/Views/BufferDebugView{T}.cs index 59950292..9325d70e 100644 --- a/src/ComputeSharp.Graphics/Buffers/Views/BufferDebugView{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/Views/BufferDebugView{T}.cs @@ -1,6 +1,10 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; using ComputeSharp.Graphics.Buffers.Abstract; +#if NET5_0 +using GC = System.GC; +#else +using GC = ComputeSharp.System.GC; +#endif namespace ComputeSharp.Graphics.Buffers.Views { diff --git a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12CommandAllocatorPool.cs b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12CommandAllocatorPool.cs index 85461480..fe88514c 100644 --- a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12CommandAllocatorPool.cs +++ b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12CommandAllocatorPool.cs @@ -2,6 +2,9 @@ using System.Collections.Generic; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Extensions; +#if NETSTANDARD2_0 +using ComputeSharp.System.Collections.Generic; +#endif using TerraFX.Interop; namespace ComputeSharp.Graphics.Commands.Interop diff --git a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs index fc8e03f4..e53489c2 100644 --- a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs +++ b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs @@ -1,8 +1,11 @@ -using ComputeSharp.Graphics.Extensions; +using System; +using ComputeSharp.Graphics.Extensions; using Microsoft.Toolkit.Diagnostics; -using System; using TerraFX.Interop; using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_TYPE; +#if NETSTANDARD2_0 +using GC = ComputeSharp.System.GC; +#endif namespace ComputeSharp.Graphics.Commands.Interop { diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index 8c720d45..3d2eefe6 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -1,13 +1,17 @@  - net5.0 - true + netstandard2.0;net5.0 - + + + + + + diff --git a/src/ComputeSharp.Graphics/Properties/Polyfills.cs b/src/ComputeSharp.Graphics/Properties/Polyfills.cs new file mode 100644 index 00000000..d9c2c634 --- /dev/null +++ b/src/ComputeSharp.Graphics/Properties/Polyfills.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace ComputeSharp +{ + namespace System + { + /// + /// A polyfill class for the type. + /// + internal static class GC + { + /// + /// Allocates an array while skipping zero-initialization, if possible. + /// + /// Specifies the type of the array element. + /// Specifies the length of the array. + /// Specifies whether the allocated array must be pinned. + /// An array object with uninitialized memory, if possible. + public static T[] AllocateUninitializedArray(int length, bool pinned = false) + { + return new T[length]; + } + } + + namespace Collections.Generic + { + /// + /// Extensions for the type. + /// + internal static class QueueExtensions + { + /// + /// Removes the object at the beginning of the instance and copies it to the result parameter. + /// + /// The type of values in the input . + /// The input . + /// The removed object. + /// Whether or not the object was successfully removed. + public static bool TryDequeue(this Queue queue, out T? result) + { + if (queue.Count > 0) + { + result = queue.Dequeue(); + + return true; + } + + result = default; + + return false; + } + } + } + + namespace Runtime.InteropServices + { + /// + /// A polyfill class for the type. + /// + internal static class MemoryMarshal + { + /// + /// Returns a reference to the 0th element of array. If the array is empty, returns + /// a reference to where the 0th element would have been stored. Such a reference + /// may be used for pinning but must never be dereferenced. + /// + /// The type of the array elements. + /// The array to analyze. + /// Reference to the 0th element in array. + public static ref T GetArrayDataReference(T[] array) + { + IntPtr offset = TypeInfo.ArrayDataByteOffset; + RawObjectData rawObject = Unsafe.As(array)!; + ref byte r0 = ref rawObject.Data; + ref byte r1 = ref Unsafe.AddByteOffset(ref r0, offset); + ref T r2 = ref Unsafe.As(ref r1); + + return ref r2; + } + + /// + /// A private generic class to preload type info for arbitrary runtime types. + /// + /// The type to load info for. + private static class TypeInfo + { + /// + /// The byte offset to the first element in a SZ array. + /// + public static readonly IntPtr ArrayDataByteOffset = MeasureArrayDataByteOffset(); + + /// + /// Computes the value for . + /// + /// The value of for the current runtime. + private static IntPtr MeasureArrayDataByteOffset() + { + T[] array = new T[1]; + RawObjectData rawObject = Unsafe.As(array)!; + ref byte r0 = ref rawObject.Data; + ref byte r1 = ref Unsafe.As(ref array[0]); + + return Unsafe.ByteOffset(ref r0, ref r1); + } + } + + /// + /// Mapping type for a raw object. + /// + [StructLayout(LayoutKind.Explicit)] + private sealed class RawObjectData + { + [FieldOffset(0)] + public byte Data; + } + } + } + } +} From e27547fb43d73db7d973e49bc8b32b06d21986e4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 00:15:32 +0100 Subject: [PATCH 04/61] Minor code tweaks --- .../Interop/ID3D12CommandAllocatorPool.cs | 3 - .../Properties/Polyfills.cs | 67 ++++++++++--------- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12CommandAllocatorPool.cs b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12CommandAllocatorPool.cs index fe88514c..85461480 100644 --- a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12CommandAllocatorPool.cs +++ b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12CommandAllocatorPool.cs @@ -2,9 +2,6 @@ using System.Collections.Generic; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Extensions; -#if NETSTANDARD2_0 -using ComputeSharp.System.Collections.Generic; -#endif using TerraFX.Interop; namespace ComputeSharp.Graphics.Commands.Interop diff --git a/src/ComputeSharp.Graphics/Properties/Polyfills.cs b/src/ComputeSharp.Graphics/Properties/Polyfills.cs index d9c2c634..1e457f1a 100644 --- a/src/ComputeSharp.Graphics/Properties/Polyfills.cs +++ b/src/ComputeSharp.Graphics/Properties/Polyfills.cs @@ -1,5 +1,6 @@ -using System; -using System.Collections.Generic; +#if NETSTANDARD2_0 + +using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -25,36 +26,6 @@ namespace ComputeSharp } } - namespace Collections.Generic - { - /// - /// Extensions for the type. - /// - internal static class QueueExtensions - { - /// - /// Removes the object at the beginning of the instance and copies it to the result parameter. - /// - /// The type of values in the input . - /// The input . - /// The removed object. - /// Whether or not the object was successfully removed. - public static bool TryDequeue(this Queue queue, out T? result) - { - if (queue.Count > 0) - { - result = queue.Dequeue(); - - return true; - } - - result = default; - - return false; - } - } - } - namespace Runtime.InteropServices { /// @@ -120,3 +91,35 @@ namespace ComputeSharp } } } + +namespace System.Collections.Generic +{ + /// + /// Extensions for the type. + /// + internal static class QueueExtensions + { + /// + /// Removes the object at the beginning of the instance and copies it to the result parameter. + /// + /// The type of values in the input . + /// The input . + /// The removed object. + /// Whether or not the object was successfully removed. + public static bool TryDequeue(this Queue queue, out T? result) + { + if (queue.Count > 0) + { + result = queue.Dequeue(); + + return true; + } + + result = default; + + return false; + } + } +} + +#endif From 880f501b55b0e84a5446e73726ff9904abefc384 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 00:53:44 +0100 Subject: [PATCH 05/61] Added .Shaders support for .NET Standard 2.0 --- .../ComputeSharp.Shaders.csproj | 2 +- .../Properties/Polyfills.cs | 37 +++++++++++ .../Renderer/HlslShaderRenderer.cs | 8 +-- .../Translation/Models/DispatchData.cs | 12 ++++ .../ShaderCompiler.LibraryLoading.cs | 66 +++++++++++++++++++ .../Translation/ShaderCompiler.cs | 65 +----------------- .../ShaderLoader{T}.DispatchData.cs | 6 +- .../Translation/ShaderLoader{T}.cs | 40 +++++------ 8 files changed, 146 insertions(+), 90 deletions(-) create mode 100644 src/ComputeSharp.Shaders/Properties/Polyfills.cs create mode 100644 src/ComputeSharp.Shaders/Translation/ShaderCompiler.LibraryLoading.cs diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index f06c8d8c..f2204371 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -1,7 +1,7 @@  - net5.0 + netstandard2.0;net5.0 diff --git a/src/ComputeSharp.Shaders/Properties/Polyfills.cs b/src/ComputeSharp.Shaders/Properties/Polyfills.cs new file mode 100644 index 00000000..227d8a84 --- /dev/null +++ b/src/ComputeSharp.Shaders/Properties/Polyfills.cs @@ -0,0 +1,37 @@ +#if NETSTANDARD2_0 + +using System.ComponentModel; + +namespace System.Runtime.CompilerServices +{ + /// + /// Reserved to be used by the compiler for tracking metadata. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + internal static class IsExternalInit + { + } +} + +namespace System.Reflection +{ + /// + /// Extensions for the type. + /// + internal static class MethodInfoExtensions + { + /// + /// Creates a delegate of type T from a given method. + /// + /// The type of delegate to create. + /// The input . + /// The delegate for this method. + public static T CreateDelegate(this MethodInfo method) + where T : Delegate + { + return (T)method.CreateDelegate(typeof(T)); + } + } +} + +#endif diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index 72ee091e..a1a69c70 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -163,11 +163,11 @@ namespace ComputeSharp.Shaders.Renderer /// Appends the input sequence of characters to the current buffer. /// /// The input characters to write. - public void Append(ReadOnlySpan value) + public void Append(string value) { EnsureCapacity(value.Length); - value.CopyTo(this.array.AsSpan(this.index)); + value.AsSpan().CopyTo(this.array.AsSpan(this.index)); this.index += value.Length; } @@ -186,11 +186,11 @@ namespace ComputeSharp.Shaders.Renderer /// Appends the input sequence of characters to the current buffer, with a trailing new line. /// /// The input characters to write. - public void AppendLine(ReadOnlySpan value) + public void AppendLine(string value) { EnsureCapacity(value.Length + 1); - value.CopyTo(this.array.AsSpan(this.index)); + value.AsSpan().CopyTo(this.array.AsSpan(this.index)); this.index += value.Length; diff --git a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs index ca016a1c..fac76157 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs @@ -54,10 +54,16 @@ namespace ComputeSharp.Shaders.Translation.Models [MethodImpl(MethodImplOptions.AggressiveInlining)] get { +#if NET5_0 ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As(ref r0); return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount); +#else + Span span = this.resourcesArray.AsSpan(0, this.resourcesCount); + + return MemoryMarshal.Cast(span); +#endif } } @@ -69,11 +75,17 @@ namespace ComputeSharp.Shaders.Translation.Models [MethodImpl(MethodImplOptions.AggressiveInlining)] get { +#if NET5_0 ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray); ref Int4 r1 = ref Unsafe.As(ref r0); int length = (int)((uint)this.variablesByteSize / (uint)sizeof(Int4)); return MemoryMarshal.CreateReadOnlySpan(ref r1, length); +#else + Span span = this.variablesArray.AsSpan(0, this.variablesByteSize); + + return MemoryMarshal.Cast(span); +#endif } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.LibraryLoading.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.LibraryLoading.cs new file mode 100644 index 00000000..9b860505 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.LibraryLoading.cs @@ -0,0 +1,66 @@ +#if NET5_0 +using System; +using System.IO; +using System.Runtime.InteropServices; +using FX = TerraFX.Interop.Windows; +#endif + +namespace ComputeSharp.Shaders.Translation +{ + /// + internal static unsafe partial class ShaderCompiler + { + /// + /// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries. + /// + private static void InitializeDxcLibrariesLoading() + { +#if NET5_0 + // Test whether the native libraries are present in the same folder of the executable + // (which is the case when the program was built with a runtime identifier), or whether + // they are in the "runtimes\win-x64\native" folder in the executable directory. + string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native"); + bool isNuGetRuntimeLibrariesDirectoryPresent = Directory.Exists(nugetNativeLibsPath); + + // Register a custom library resolver for the two DXC libraries. We need to either manually load the two + // libraries from the NuGet directory, if an RID is not in use, or we need to ensure that dxil.dll is + // loaded correctly in case the program was executed with the host being in another directory. + // This happens when doing eg. "dotnet bin\Debug\net5.0\MyApp.dll", which would crash at runtime. + FX.ResolveLibrary += (libraryName, assembly, searchPath) => + { + if (libraryName is not "dxcompiler") return IntPtr.Zero; + + if (isNuGetRuntimeLibrariesDirectoryPresent) + { + string + dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxcompiler.dll"), + dxilPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxil.dll"); + + // Load DXIL first so that DXC doesn't fail to load it, and then DXIL, both from the NuGet path + if (NativeLibrary.TryLoad(dxilPath, out _) && NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle)) + { + return handle; + } + } + else + { + // Even when the two libraries are correctly copied next to the executable in use, we load them + // manually to ensure the operation is successful. This is to avoid failures in cases such as when + // doing "dotnet bin\MyApp.dll", ie. when the host is in another path than the executable in use. + // This is probably because DXIL is a native dependency for DXC, but the way Windows loads these + // libraries doesn't take into account the .NET concepts of "app directory": neither the current "bin" + // directory nor the "process directory", which is "C:\Program Files\dotnet", actually contain the + // native library we need, hence the runtime crash. Manually loading the library this way solves this. + if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) && + NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle)) + { + return handle; + } + } + + return IntPtr.Zero; + }; +#endif + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index 78c5b1ea..dedc20a0 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -1,10 +1,6 @@ using System; -using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; -using System.IO; -using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; using TerraFX.Interop; @@ -15,7 +11,7 @@ namespace ComputeSharp.Shaders.Translation /// /// A that uses the DXC APIs to compile compute shaders. /// - internal static unsafe class ShaderCompiler + internal static unsafe partial class ShaderCompiler { /// /// The instance to use to create the bytecode for HLSL sources. @@ -56,64 +52,6 @@ namespace ComputeSharp.Shaders.Translation DxcIncludeHandler = dxcIncludeHandler.Move(); } - /// - /// Initializes the DLL resolvers for the dxcompiler.dll and dxil.dll libraries. - /// - private static void InitializeDxcLibrariesLoading() - { - // Test whether the native libraries are present in the same folder of the executable - // (which is the case when the program was built with a runtime identifier), or whether - // they are in the "runtimes\win-x64\native" folder in the executable directory. - string nugetNativeLibsPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native"); - bool isNuGetRuntimeLibrariesDirectoryPresent = Directory.Exists(nugetNativeLibsPath); - - // Register a custom library resolver for the two DXC libraries. We need to either manually load the two - // libraries from the NuGet directory, if an RID is not in use, or we need to ensure that dxil.dll is - // loaded correctly in case the program was executed with the host being in another directory. - // This happens when doing eg. "dotnet bin\Debug\net5.0\MyApp.dll", which would crash at runtime. - FX.ResolveLibrary += (n, a, s) => ResolveLibrary(n, a, s, isNuGetRuntimeLibrariesDirectoryPresent); - } - - /// - /// A custom resolver to override the default library resolution behavior for the DXC and DXIL libraries. - /// This either loads the libraries from the NuGet directory, or just ensures that DXIL is always loaded. - /// - /// - private static IntPtr ResolveLibrary(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool isNuGetRuntimeLibrariesDirectoryPresent) - { - if (libraryName is not "dxcompiler") return IntPtr.Zero; - - if (isNuGetRuntimeLibrariesDirectoryPresent) - { - string - dxcompilerPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxcompiler.dll"), - dxilPath = Path.Combine(AppContext.BaseDirectory, @"runtimes\win-x64\native\dxil.dll"); - - // Load DXIL first so that DXC doesn't fail to load it, and then DXIL, both from the NuGet path - if (NativeLibrary.TryLoad(dxilPath, out _) && NativeLibrary.TryLoad(dxcompilerPath, out IntPtr handle)) - { - return handle; - } - } - else - { - // Even when the two libraries are correctly copied next to the executable in use, we load them - // manually to ensure the operation is successful. This is to avoid failures in cases such as when - // doing "dotnet bin\MyApp.dll", ie. when the host is in another path than the executable in use. - // This is probably because DXIL is a native dependency for DXC, but the way Windows loads these - // libraries doesn't take into account the .NET concepts of "app directory": neither the current "bin" - // directory nor the "process directory", which is "C:\Program Files\dotnet", actually contain the - // native library we need, hence the runtime crash. Manually loading the library this way solves this. - if (NativeLibrary.TryLoad("dxil", assembly, searchPath, out _) && - NativeLibrary.TryLoad("dxcompiler", assembly, searchPath, out IntPtr handle)) - { - return handle; - } - } - - return IntPtr.Zero; - } - /// /// Compiles a new HLSL shader from the input source code. /// @@ -175,7 +113,6 @@ namespace ComputeSharp.Shaders.Translation /// /// The input (faulting) operation. /// This method always throws and never actually returs. - [DoesNotReturn] [MethodImpl(MethodImplOptions.NoInlining)] private static ComPtr ThrowHslsCompilationException(IDxcOperationResult* dxcOperationResult) { diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs index 270c40e1..76fe2554 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs @@ -4,10 +4,14 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using ComputeSharp.Graphics; using ComputeSharp.Shaders.Translation.Models; using TerraFX.Interop; +#if NET5_0 +using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal; +#else +using MemoryMarshal = ComputeSharp.System.Runtime.InteropServices.MemoryMarshal; +#endif namespace ComputeSharp.Shaders.Translation { diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 92ee855b..11ac00bd 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; -using System.Runtime.InteropServices; using ComputeSharp.__Internals; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Renderer.Models; @@ -43,9 +42,9 @@ namespace ComputeSharp.Shaders.Translation private uint readWriteBuffersCount; /// - /// The of items that are required to load the captured values. + /// The array of items that are required to load the captured values. /// - private readonly List d3D12DescriptorRanges1 = new(); + private D3D12_DESCRIPTOR_RANGE1[] d3D12DescriptorRanges1; /// /// The with the items for the shader fields. @@ -79,7 +78,7 @@ namespace ComputeSharp.Shaders.Translation /// public ReadOnlySpan D3D12DescriptorRanges1 { - get => CollectionsMarshal.AsSpan(this.d3D12DescriptorRanges1); + get => this.d3D12DescriptorRanges1; } /// @@ -107,12 +106,10 @@ namespace ComputeSharp.Shaders.Translation { ShaderLoader @this = new(); - // Reading members through reflection requires an object parameter, - // so here we're just boxing the input shader once to avoid allocating - // it multiple times in the managed heap while processing the shader. - object box = shader; + // Reading members through reflection requires an object parameter, so here we're just boxing + // the input shader once to avoid allocating it multiple times while processing the shader. + @this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader); - @this.LoadFieldsInfo(box); @this.LoadMethodMetadata(); @this.InitializeDispatchDataLoader(); @@ -123,7 +120,8 @@ namespace ComputeSharp.Shaders.Translation /// Loads the fields info for the current shader being loaded. /// /// The boxed instance to use to build the shader. - private void LoadFieldsInfo(object shader) + /// The array of items that are required to load the captured values. + private D3D12_DESCRIPTOR_RANGE1[] LoadFieldsInfo(object shader) { IReadOnlyList shaderFields = typeof(T).GetFields( BindingFlags.Instance | @@ -135,51 +133,53 @@ namespace ComputeSharp.Shaders.Translation ThrowHelper.ThrowInvalidOperationException("The shader body must contain at least one field"); } + List d3D12DescriptorRanges1 = new(); + // Descriptor for the buffer for captured scalar/vector variables D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount++); - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); + d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); // Inspect the captured fields foreach (FieldInfo fieldInfo in shaderFields) { - LoadFieldInfo(shader, fieldInfo); + LoadFieldInfo(shader, fieldInfo, d3D12DescriptorRanges1); } + + return d3D12DescriptorRanges1.ToArray(); } /// /// Loads a specified and adds it to the shader model. /// /// The boxed instance to use to build the shader. - /// The target to load. - private void LoadFieldInfo(object shader, FieldInfo fieldInfo) + /// The target to load. + /// The list of discovered values. + private void LoadFieldInfo(object shader, FieldInfo fieldInfo, List d3D12DescriptorRanges1) { Type fieldType = fieldInfo.FieldType; (string hlslName, string hlslType) = Attribute.Fields[fieldInfo.Name]; if (HlslKnownTypes.IsConstantBufferType(fieldType)) { - D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount); + d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount)); - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); this.totalResourceCount++; } else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) { - D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount); + d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, this.readOnlyBuffersCount)); - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); this.totalResourceCount++; } else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) { - D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount); + d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount)); - this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); this.totalResourceCount++; From 955f6be4f921d2c1bc63c1091de1c31c94fd7ab9 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 01:01:57 +0100 Subject: [PATCH 06/61] Added main support for .NET Standard 2.0 --- src/ComputeSharp/ComputeSharp.csproj | 2 +- .../Extensions/Buffers/BufferExtensions.cs | 5 +++++ .../Extensions/Buffers/Texture2DExtensions.cs | 12 ++++++++++++ .../Extensions/Buffers/Texture3DExtensions.cs | 10 ++++++++++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 958bf173..31d48cef 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -1,7 +1,7 @@  - net5.0 + netstandard2.0;net5.0 diff --git a/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs b/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs index 95ddd2f5..32c9e32e 100644 --- a/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs @@ -3,6 +3,11 @@ using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using ComputeSharp.Graphics.Buffers.Abstract; using Microsoft.Toolkit.Diagnostics; +#if NET5_0 +using GC = System.GC; +#else +using GC = ComputeSharp.System.GC; +#endif namespace ComputeSharp { diff --git a/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs b/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs index 4c1b03e2..00ec659c 100644 --- a/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs @@ -55,6 +55,7 @@ namespace ComputeSharp texture.GetData(destination.AsSpan(), 0, 0, texture.Width, texture.Height); } +#if NET5_0 /// /// Reads the contents of the specified range from the current instance and writes them into a target array. /// @@ -68,6 +69,7 @@ namespace ComputeSharp { texture.GetData(destination.AsSpan(), x, y); } +#endif /// /// Reads the contents of the specified range from the current instance and writes them into a target array. @@ -98,6 +100,7 @@ namespace ComputeSharp texture.GetData(destination.AsSpan(offset), 0, 0, texture.Width, texture.Height); } +#if NET5_0 /// /// Reads the contents of the specified range from the current instance and writes them into a target array. /// @@ -112,6 +115,7 @@ namespace ComputeSharp { texture.GetData(destination.AsSpan(offset), x, y); } +#endif /// /// Reads the contents of the specified range from the current instance and writes them into a target array. @@ -143,6 +147,7 @@ namespace ComputeSharp texture.GetData(destination, 0, 0, texture.Width, texture.Height); } +#if NET5_0 /// /// Reads the contents of the specified range from the current instance and writes them into a target . /// @@ -159,6 +164,7 @@ namespace ComputeSharp texture.GetData(destination, offsetX, offsetY, width, height); } +#endif /// /// Reads the contents of the specified range from the current instance and writes them into a target . @@ -203,6 +209,7 @@ namespace ComputeSharp texture.SetData(source.AsSpan(), 0, 0, texture.Width, texture.Height); } +#if NET5_0 /// /// Writes the contents of a given array to a specified area of the current instance. /// @@ -216,6 +223,7 @@ namespace ComputeSharp { texture.SetData(source.AsSpan(), x, y); } +#endif /// /// Writes the contents of a given array to a specified area of the current instance. @@ -233,6 +241,7 @@ namespace ComputeSharp texture.SetData(source.AsSpan(), x, y, width, height); } +#if NET5_0 /// /// Writes the contents of a given array to a specified area of the current instance. /// @@ -247,6 +256,7 @@ namespace ComputeSharp { texture.SetData(source.AsSpan(offset), x, y); } +#endif /// /// Writes the contents of a given array to a specified area of the current instance. @@ -278,6 +288,7 @@ namespace ComputeSharp texture.SetData(source, 0, 0, texture.Width, texture.Height); } +#if NET5_0 /// /// Writes the contents of a given to a specified area of the current instance. /// @@ -294,6 +305,7 @@ namespace ComputeSharp texture.SetData(source, offsetX, offsetY, width, height); } +#endif /// /// Writes the contents of a given to a specified area of the current instance. diff --git a/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs b/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs index 850378a5..8666780e 100644 --- a/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs @@ -66,6 +66,7 @@ namespace ComputeSharp texture.GetData(destination.AsSpan(offset), 0, 0, 0, texture.Width, texture.Height, texture.Depth); } +#if NET5_0 /// /// Reads the contents of the specified range from the current instance and writes them into a target array. /// @@ -81,6 +82,7 @@ namespace ComputeSharp { texture.GetData(destination.AsSpan(offset), x, y, z); } +#endif /// /// Reads the contents of the specified range from the current instance and writes them into a target array. @@ -113,6 +115,7 @@ namespace ComputeSharp texture.GetData(destination, 0, 0, 0, texture.Width, texture.Height, texture.Depth); } +#if NET5_0 /// /// Reads the contents of the specified range from the current instance and writes them into a target . /// @@ -131,6 +134,7 @@ namespace ComputeSharp texture.GetData(destination, offsetX, offsetY, offsetZ, width, height, depth); } +#endif /// /// Reads the contents of the specified range from the current instance and writes them into a target . @@ -182,6 +186,7 @@ namespace ComputeSharp texture.SetData(source.AsSpan(), 0, 0, 0, texture.Width, texture.Height, texture.Depth); } +#if NET5_0 /// /// Writes the contents of a given array to a specified area of the current instance. /// @@ -196,6 +201,7 @@ namespace ComputeSharp { texture.SetData(source.AsSpan(), x, y, z); } +#endif /// /// Writes the contents of a given array to a specified area of the current instance. @@ -215,6 +221,7 @@ namespace ComputeSharp texture.SetData(source.AsSpan(), x, y, z, width, height, depth); } +#if NET5_0 /// /// Writes the contents of a given array to a specified area of the current instance. /// @@ -230,6 +237,7 @@ namespace ComputeSharp { texture.SetData(source.AsSpan(offset), x, y, z); } +#endif /// /// Writes the contents of a given array to a specified area of the current instance. @@ -263,6 +271,7 @@ namespace ComputeSharp texture.SetData(source, 0, 0, 0, texture.Width, texture.Height, texture.Depth); } +#if NET5_0 /// /// Writes the contents of a given to a specified area of the current instance. /// @@ -281,6 +290,7 @@ namespace ComputeSharp texture.SetData(source, offsetX, offsetY, offsetZ, width, height, depth); } +#endif /// /// Writes the contents of a given to a specified area of the current instance. From 334a71eb0e073fad9f303d72c2b479ef98aa1ead Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 13:30:25 +0100 Subject: [PATCH 07/61] Added missing analyzers to internal test project --- .../ComputeSharp.Tests.Internals.csproj | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj index 5fd0b827..9baa5c40 100644 --- a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj +++ b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj @@ -13,6 +13,10 @@ + From 10bab42c3aa03e2d75da5f17134d6c688e21bec8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 13:34:58 +0100 Subject: [PATCH 08/61] Enabled .NET Core 2.1 tests --- .../ComputeSharp.Tests.Internals.csproj | 3 ++- tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj index 9baa5c40..80cda974 100644 --- a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj +++ b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj @@ -1,8 +1,9 @@  - net5.0 + netcoreapp2.1;net5.0 false + 9.0 diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj index aae52469..ee76bc48 100644 --- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj +++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj @@ -1,8 +1,9 @@  - net5.0 + netcoreapp2.1;net5.0 false + 9.0 From d088fae2e54e0bd134944bb02858649d328b65d6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 14:14:25 +0100 Subject: [PATCH 09/61] Removed unnecessary code --- .../Extensions/TypeExtensions.cs | 50 ------------------- 1 file changed, 50 deletions(-) delete mode 100644 src/ComputeSharp.Graphics/Extensions/TypeExtensions.cs diff --git a/src/ComputeSharp.Graphics/Extensions/TypeExtensions.cs b/src/ComputeSharp.Graphics/Extensions/TypeExtensions.cs deleted file mode 100644 index 427c418c..00000000 --- a/src/ComputeSharp.Graphics/Extensions/TypeExtensions.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; - -namespace ComputeSharp.Graphics.Extensions -{ - /// - /// A that provides extension methods for the type. - /// - internal static class TypeExtensions - { - /// - /// The mapping of supported known types to display string. - /// - private static readonly IReadOnlyDictionary KnownTypes = new Dictionary - { - [typeof(bool)] = "bool", - [typeof(int)] = "int", - [typeof(uint)] = "uint", - [typeof(float)] = "float", - [typeof(double)] = "double" - }; - - /// - /// Gets a friendly display for the input type. - /// - /// The input type to analyze. - [Pure] - public static string ToFriendlyString(this Type type) - { - // Array types of arbitrary rank - if (type.IsArray) - { - int rank = type.GetArrayRank(); - return $"{type.GetElementType()!.ToFriendlyString()}[{new string(Enumerable.Repeat(',', rank - 1).ToArray())}]"; - } - - // Non generic types - string? name; - if (type.GetGenericArguments().Length == 0) return KnownTypes.TryGetValue(type, out name) ? name : type.Name; - - // Generic types - Type[] genericArguments = type.GetGenericArguments(); - string typeDefeninition = KnownTypes.TryGetValue(type, out name) ? name : type.Name; - string polishedName = typeDefeninition.Substring(0, typeDefeninition.IndexOf("`")); - return $"{polishedName}<{string.Join(",", genericArguments.Select(ToFriendlyString))}>"; - } - } -} From 8658cd85e8afacf4204368b8de603d73cf6159ff Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 14:18:10 +0100 Subject: [PATCH 10/61] Minor code tweaks --- .../Commands/CommandList.cs | 2 +- .../Extensions/ComPtrExtensions.cs | 22 +------------------ .../Translation/ShaderCompiler.cs | 2 +- 3 files changed, 3 insertions(+), 23 deletions(-) diff --git a/src/ComputeSharp.Graphics/Commands/CommandList.cs b/src/ComputeSharp.Graphics/Commands/CommandList.cs index 13bc89bc..3b30eca0 100644 --- a/src/ComputeSharp.Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp.Graphics/Commands/CommandList.cs @@ -75,7 +75,7 @@ namespace ComputeSharp.Graphics.Commands [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly ID3D12CommandList** GetD3D12CommandListAddressOf() { - return this.d3D12GraphicsCommandList.Upcast().GetAddressOf(); + return (ID3D12CommandList**)this.d3D12GraphicsCommandList.GetAddressOf(); } /// diff --git a/src/ComputeSharp.Graphics/Extensions/ComPtrExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ComPtrExtensions.cs index c21a29bb..7388fdb8 100644 --- a/src/ComputeSharp.Graphics/Extensions/ComPtrExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ComPtrExtensions.cs @@ -7,7 +7,7 @@ namespace ComputeSharp.Core.Extensions /// /// Helper methods for working with the type. /// - public static class ComPtrExtensions + internal static class ComPtrExtensions { /// /// Reinterprets the current instance as one of type . @@ -59,25 +59,5 @@ namespace ComputeSharp.Core.Extensions return copy; } - - /// - /// Upcasts the current instance as a base type. - /// - /// The type of the current instance. - /// The type to cast the input instance to. - /// The input instance to upcast. - /// A instance of type . - /// - /// This method is meant to be used in a chained expression and it does not increment the reference - /// count for the input pointer. Do not expose the return value of this extension to consumers. - /// - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe ref readonly ComPtr Upcast(this in ComPtr ptr) - where T : unmanaged - where U : unmanaged - { - return ref Unsafe.As, ComPtr>(ref Unsafe.AsRef(in ptr)); - } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs index dedc20a0..321e4548 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderCompiler.cs @@ -81,7 +81,7 @@ namespace ComputeSharp.Shaders.Translation fixed (char* optimization = "-O3") { DxcCompiler.Get()->Compile( - dxcBlobEncoding.Upcast().Get(), + (IDxcBlob*)dxcBlobEncoding.Get(), (ushort*)shaderName, (ushort*)entryPoint, (ushort*)shaderProfile, From 7e44eb5f7463ccb450cc978481a5c19717e41fc0 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 14:28:44 +0100 Subject: [PATCH 11/61] Moved resource types to \Resources directory --- .../{Buffers => Resources}/Abstract/Buffer{T}.cs | 0 .../{Buffers => Resources}/Abstract/StructuredBuffer{T}.cs | 0 .../{Buffers => Resources}/Abstract/Texture2D{T}.cs | 0 .../{Buffers => Resources}/Abstract/Texture3D{T}.cs | 0 .../{Buffers => Resources}/ConstantBuffer{T}.cs | 0 .../{Buffers => Resources}/Enums/ResourceType.cs | 0 .../{Buffers => Resources}/Interop/ID3D12ResourceMap.cs | 0 .../{Buffers => Resources}/ReadOnlyBuffer{T}.cs | 0 .../{Buffers => Resources}/ReadOnlyTexture2D{T,TPixel}.cs | 0 .../{Buffers => Resources}/ReadOnlyTexture2D{T}.cs | 0 .../{Buffers => Resources}/ReadOnlyTexture3D{T,TPixel}.cs | 0 .../{Buffers => Resources}/ReadOnlyTexture3D{T}.cs | 0 .../{Buffers => Resources}/ReadWriteBuffer{T}.cs | 0 .../{Buffers => Resources}/ReadWriteTexture2D{T,TPixel}.cs | 0 .../{Buffers => Resources}/ReadWriteTexture2D{T}.cs | 0 .../{Buffers => Resources}/ReadWriteTexture3D{T,TPixel}.cs | 0 .../{Buffers => Resources}/ReadWriteTexture3D{T}.cs | 0 .../{Buffers => Resources}/Views/BufferDebugView{T}.cs | 0 .../{Buffers => Resources}/Views/Texture2DDebugView{T}.cs | 0 .../{Buffers => Resources}/Views/Texture3DDebugView{T}.cs | 0 20 files changed, 0 insertions(+), 0 deletions(-) rename src/ComputeSharp.Graphics/{Buffers => Resources}/Abstract/Buffer{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/Abstract/StructuredBuffer{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/Abstract/Texture2D{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/Abstract/Texture3D{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ConstantBuffer{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/Enums/ResourceType.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/Interop/ID3D12ResourceMap.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ReadOnlyBuffer{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ReadOnlyTexture2D{T,TPixel}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ReadOnlyTexture2D{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ReadOnlyTexture3D{T,TPixel}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ReadOnlyTexture3D{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ReadWriteBuffer{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ReadWriteTexture2D{T,TPixel}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ReadWriteTexture2D{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ReadWriteTexture3D{T,TPixel}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/ReadWriteTexture3D{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/Views/BufferDebugView{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/Views/Texture2DDebugView{T}.cs (100%) rename src/ComputeSharp.Graphics/{Buffers => Resources}/Views/Texture3DDebugView{T}.cs (100%) diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/Abstract/Buffer{T}.cs rename to src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/StructuredBuffer{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/Abstract/StructuredBuffer{T}.cs rename to src/ComputeSharp.Graphics/Resources/Abstract/StructuredBuffer{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/Abstract/Texture2D{T}.cs rename to src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Abstract/Texture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/Abstract/Texture3D{T}.cs rename to src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs rename to src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Enums/ResourceType.cs b/src/ComputeSharp.Graphics/Resources/Enums/ResourceType.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/Enums/ResourceType.cs rename to src/ComputeSharp.Graphics/Resources/Enums/ResourceType.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Interop/ID3D12ResourceMap.cs b/src/ComputeSharp.Graphics/Resources/Interop/ID3D12ResourceMap.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/Interop/ID3D12ResourceMap.cs rename to src/ComputeSharp.Graphics/Resources/Interop/ID3D12ResourceMap.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ReadOnlyBuffer{T}.cs rename to src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T,TPixel}.cs rename to src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture2D{T}.cs rename to src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T,TPixel}.cs rename to src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ReadOnlyTexture3D{T}.cs rename to src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteBuffer{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ReadWriteBuffer{T}.cs rename to src/ComputeSharp.Graphics/Resources/ReadWriteBuffer{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T,TPixel}.cs rename to src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ReadWriteTexture2D{T}.cs rename to src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T,TPixel}.cs rename to src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/ReadWriteTexture3D{T}.cs rename to src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Views/BufferDebugView{T}.cs b/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/Views/BufferDebugView{T}.cs rename to src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Views/Texture2DDebugView{T}.cs b/src/ComputeSharp.Graphics/Resources/Views/Texture2DDebugView{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/Views/Texture2DDebugView{T}.cs rename to src/ComputeSharp.Graphics/Resources/Views/Texture2DDebugView{T}.cs diff --git a/src/ComputeSharp.Graphics/Buffers/Views/Texture3DDebugView{T}.cs b/src/ComputeSharp.Graphics/Resources/Views/Texture3DDebugView{T}.cs similarity index 100% rename from src/ComputeSharp.Graphics/Buffers/Views/Texture3DDebugView{T}.cs rename to src/ComputeSharp.Graphics/Resources/Views/Texture3DDebugView{T}.cs From 374acb06dbc56fe6507a117f158551c6fcde806a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 30 Dec 2020 22:42:52 +0100 Subject: [PATCH 12/61] Improved namespaces for public buffer types --- src/ComputeSharp.Graphics/Commands/PipelineData.cs | 2 +- .../Exceptions/GraphicsDeviceMismatchException.cs | 5 ++--- .../Extensions/ID3D12DeviceExtensions.cs | 2 +- .../Extensions/ID3D12ResourceExtensions.cs | 2 +- src/ComputeSharp.Graphics/GraphicsDevice.cs | 4 ++-- src/ComputeSharp.Graphics/GraphicsDeviceInfo.cs | 2 +- .../Helpers/DeviceHelper.Enumerator.cs | 2 +- .../Helpers/__Internals/GraphicsResourceHelper.cs | 3 +-- src/ComputeSharp.Graphics/Interop/NativeObject.cs | 2 +- src/ComputeSharp.Graphics/Luid.cs | 2 +- .../Resources/Abstract/Buffer{T}.cs | 6 +++--- .../Resources/Abstract/StructuredBuffer{T}.cs | 8 ++++---- .../Resources/Abstract/Texture2D{T}.cs | 8 ++++---- .../Resources/Abstract/Texture3D{T}.cs | 8 ++++---- src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs | 9 ++++----- .../Resources/Enums/ResourceType.cs | 2 +- .../Resources/Interop/ID3D12ResourceMap.cs | 2 +- src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs | 7 +++---- .../Resources/ReadOnlyTexture2D{T}.cs | 7 +++---- .../Resources/ReadOnlyTexture3D{T}.cs | 7 +++---- .../Resources/ReadWriteBuffer{T}.cs | 7 +++---- .../Resources/ReadWriteTexture2D{T}.cs | 7 +++---- .../Resources/ReadWriteTexture3D{T}.cs | 7 +++---- .../Resources/Views/BufferDebugView{T}.cs | 3 +-- .../Resources/Views/Texture2DDebugView{T}.cs | 3 +-- .../Resources/Views/Texture3DDebugView{T}.cs | 3 +-- .../Translation/Interop/IDxcBlobObject.cs | 2 +- .../IComputeShaderDataLoaderGenerator.cs | 2 +- src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs | 2 +- .../Extensions/Buffers/Texture2DExtensions.cs | 2 +- .../Extensions/Buffers/Texture3DExtensions.cs | 2 +- src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs | 1 + tests/ComputeSharp.Tests/BufferTests.cs | 2 +- .../Extensions/GraphicsDeviceExtensions.cs | 1 + tests/ComputeSharp.Tests/Texture2DTests.cs | 2 +- tests/ComputeSharp.Tests/Texture3DTests.cs | 2 +- 36 files changed, 64 insertions(+), 74 deletions(-) diff --git a/src/ComputeSharp.Graphics/Commands/PipelineData.cs b/src/ComputeSharp.Graphics/Commands/PipelineData.cs index 346daef9..d25c1fe0 100644 --- a/src/ComputeSharp.Graphics/Commands/PipelineData.cs +++ b/src/ComputeSharp.Graphics/Commands/PipelineData.cs @@ -1,4 +1,4 @@ -using ComputeSharp.Graphics.Interop; +using ComputeSharp.Interop; using TerraFX.Interop; namespace ComputeSharp.Graphics.Commands diff --git a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs index 6790ec38..2706fc13 100644 --- a/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs +++ b/src/ComputeSharp.Graphics/Exceptions/GraphicsDeviceMismatchException.cs @@ -1,9 +1,8 @@ using System; using System.Diagnostics.Contracts; using System.Text; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Interop; +using ComputeSharp.Interop; +using ComputeSharp.Resources; namespace ComputeSharp.Exceptions { diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs index 239e2369..ae2e91e9 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs @@ -1,7 +1,6 @@ using System; using System.Diagnostics.Contracts; using ComputeSharp.Core.Extensions; -using ComputeSharp.Graphics.Buffers.Enums; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_QUEUE_FLAGS; @@ -19,6 +18,7 @@ using static TerraFX.Interop.D3D12_RESOURCE_STATES; using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; using FX = TerraFX.Interop.Windows; +using ComputeSharp.Graphics.Resources.Enums; namespace ComputeSharp.Graphics.Extensions { diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12ResourceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12ResourceExtensions.cs index 5fc2c29e..c6afd4bd 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12ResourceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12ResourceExtensions.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.CompilerServices; using ComputeSharp.Core.Extensions; -using ComputeSharp.Graphics.Buffers.Interop; +using ComputeSharp.Graphics.Resources.Interop; using TerraFX.Interop; namespace ComputeSharp.Graphics.Extensions diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index ff2dfd47..824becaf 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -6,7 +6,7 @@ using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Commands.Interop; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; -using ComputeSharp.Graphics.Interop; +using ComputeSharp.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; @@ -14,7 +14,7 @@ using static TerraFX.Interop.D3D12_FEATURE; using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; using static TerraFX.Interop.DXGI_ADAPTER_FLAG; -namespace ComputeSharp.Graphics +namespace ComputeSharp { /// /// A that represents a DX12-compatible GPU device that can be used to run compute shaders. diff --git a/src/ComputeSharp.Graphics/GraphicsDeviceInfo.cs b/src/ComputeSharp.Graphics/GraphicsDeviceInfo.cs index ad07c130..71a5c06a 100644 --- a/src/ComputeSharp.Graphics/GraphicsDeviceInfo.cs +++ b/src/ComputeSharp.Graphics/GraphicsDeviceInfo.cs @@ -1,7 +1,7 @@ using TerraFX.Interop; using static TerraFX.Interop.DXGI_ADAPTER_FLAG; -namespace ComputeSharp.Graphics +namespace ComputeSharp { /// /// A type containing info on a given DX12.0 device that can be used. diff --git a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.Enumerator.cs b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.Enumerator.cs index 81a3e914..8fe0dd92 100644 --- a/src/ComputeSharp.Graphics/Helpers/DeviceHelper.Enumerator.cs +++ b/src/ComputeSharp.Graphics/Helpers/DeviceHelper.Enumerator.cs @@ -2,7 +2,7 @@ using System.Collections; using System.Collections.Generic; using ComputeSharp.Core.Extensions; -using ComputeSharp.Graphics.Interop; +using ComputeSharp.Interop; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; using HRESULT = System.Int32; diff --git a/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index cf210dd2..03a2c82f 100644 --- a/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -1,8 +1,7 @@ using System; using System.ComponentModel; using System.Runtime.CompilerServices; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; using TerraFX.Interop; namespace ComputeSharp.__Internals diff --git a/src/ComputeSharp.Graphics/Interop/NativeObject.cs b/src/ComputeSharp.Graphics/Interop/NativeObject.cs index c0b4c75e..10bdb1cd 100644 --- a/src/ComputeSharp.Graphics/Interop/NativeObject.cs +++ b/src/ComputeSharp.Graphics/Interop/NativeObject.cs @@ -1,7 +1,7 @@ using System; using System.Runtime.CompilerServices; -namespace ComputeSharp.Graphics.Interop +namespace ComputeSharp.Interop { /// /// Base class for a class. diff --git a/src/ComputeSharp.Graphics/Luid.cs b/src/ComputeSharp.Graphics/Luid.cs index 5057f388..f28d1089 100644 --- a/src/ComputeSharp.Graphics/Luid.cs +++ b/src/ComputeSharp.Graphics/Luid.cs @@ -3,7 +3,7 @@ using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using TerraFX.Interop; -namespace ComputeSharp.Graphics +namespace ComputeSharp { /// /// A locally unique identifier for a graphics device. diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs index b4bb2c61..76fd6afd 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs @@ -1,9 +1,9 @@ using System.Buffers; using System.Runtime.CompilerServices; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics.Buffers.Enums; using ComputeSharp.Graphics.Extensions; -using ComputeSharp.Graphics.Interop; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; @@ -13,7 +13,7 @@ using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal; using MemoryMarshal = ComputeSharp.System.Runtime.InteropServices.MemoryMarshal; #endif -namespace ComputeSharp.Graphics.Buffers.Abstract +namespace ComputeSharp.Resources { /// /// A representing a typed buffer stored on GPU memory. diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/StructuredBuffer{T}.cs index 2ede7c03..ab650ac7 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/StructuredBuffer{T}.cs @@ -1,13 +1,13 @@ -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Interop; -using ComputeSharp.Graphics.Commands; +using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Graphics.Resources.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; -namespace ComputeSharp.Graphics.Buffers.Abstract +namespace ComputeSharp.Resources { /// /// A representing a typed structured buffer stored on GPU memory. diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs index ffeec2e7..30e2a48f 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs @@ -1,11 +1,11 @@ using System.Runtime.CompilerServices; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Interop; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; -using ComputeSharp.Graphics.Interop; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Graphics.Resources.Interop; +using ComputeSharp.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; @@ -15,7 +15,7 @@ using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; using FX = TerraFX.Interop.Windows; -namespace ComputeSharp.Graphics.Buffers.Abstract +namespace ComputeSharp.Resources { /// /// A representing a typed 2D texture stored on GPU memory. diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs index 95600e7f..9d262a7c 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs @@ -1,11 +1,11 @@ using System.Runtime.CompilerServices; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Interop; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; -using ComputeSharp.Graphics.Interop; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Graphics.Resources.Interop; +using ComputeSharp.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; @@ -15,7 +15,7 @@ using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; using FX = TerraFX.Interop.Windows; -namespace ComputeSharp.Graphics.Buffers.Abstract +namespace ComputeSharp.Resources { /// /// A representing a typed 3D texture stored on GPU memory. diff --git a/src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs index fe2ef679..24ce2bfb 100644 --- a/src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs @@ -3,14 +3,13 @@ using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Core.Helpers; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Interop; -using ComputeSharp.Graphics.Buffers.Views; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Helpers; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Graphics.Resources.Interop; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; using Microsoft.Toolkit.Diagnostics; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; using FX = TerraFX.Interop.Windows; diff --git a/src/ComputeSharp.Graphics/Resources/Enums/ResourceType.cs b/src/ComputeSharp.Graphics/Resources/Enums/ResourceType.cs index 8ddddb8d..99505b8b 100644 --- a/src/ComputeSharp.Graphics/Resources/Enums/ResourceType.cs +++ b/src/ComputeSharp.Graphics/Resources/Enums/ResourceType.cs @@ -1,4 +1,4 @@ -namespace ComputeSharp.Graphics.Buffers.Enums +namespace ComputeSharp.Graphics.Resources.Enums { /// /// An that indicates the type of a given HLSL resource. diff --git a/src/ComputeSharp.Graphics/Resources/Interop/ID3D12ResourceMap.cs b/src/ComputeSharp.Graphics/Resources/Interop/ID3D12ResourceMap.cs index bd9d70f9..d6cb938b 100644 --- a/src/ComputeSharp.Graphics/Resources/Interop/ID3D12ResourceMap.cs +++ b/src/ComputeSharp.Graphics/Resources/Interop/ID3D12ResourceMap.cs @@ -3,7 +3,7 @@ using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Extensions; using TerraFX.Interop; -namespace ComputeSharp.Graphics.Buffers.Interop +namespace ComputeSharp.Graphics.Resources.Interop { /// /// A type representing a mapped memory resource. diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs index 296df86e..785dcd56 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs @@ -1,9 +1,8 @@ using System.Diagnostics; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Views; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; namespace ComputeSharp { diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs index 36b930ef..3d94f2f0 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs @@ -1,9 +1,8 @@ using System.Diagnostics; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Views; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; namespace ComputeSharp { diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs index 306b0d19..044a069a 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs @@ -1,9 +1,8 @@ using System.Diagnostics; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Views; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; namespace ComputeSharp { diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteBuffer{T}.cs index 28c65443..1ea2cfd4 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteBuffer{T}.cs @@ -1,9 +1,8 @@ using System.Diagnostics; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Views; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; namespace ComputeSharp { diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs index 1b75ce5b..bbf43edc 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs @@ -1,9 +1,8 @@ using System.Diagnostics; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Views; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; namespace ComputeSharp { diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs index 8ee45602..631d72bf 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs @@ -1,9 +1,8 @@ using System.Diagnostics; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Views; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; namespace ComputeSharp { diff --git a/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs b/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs index 9325d70e..fb4da827 100644 --- a/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs @@ -1,12 +1,11 @@ using System.Diagnostics; -using ComputeSharp.Graphics.Buffers.Abstract; #if NET5_0 using GC = System.GC; #else using GC = ComputeSharp.System.GC; #endif -namespace ComputeSharp.Graphics.Buffers.Views +namespace ComputeSharp.Resources.Views { /// /// A debug proxy used to display items in a instance. diff --git a/src/ComputeSharp.Graphics/Resources/Views/Texture2DDebugView{T}.cs b/src/ComputeSharp.Graphics/Resources/Views/Texture2DDebugView{T}.cs index def44462..ad4f4951 100644 --- a/src/ComputeSharp.Graphics/Resources/Views/Texture2DDebugView{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Views/Texture2DDebugView{T}.cs @@ -1,7 +1,6 @@ using System.Diagnostics; -using ComputeSharp.Graphics.Buffers.Abstract; -namespace ComputeSharp.Graphics.Buffers.Views +namespace ComputeSharp.Resources.Views { /// /// A debug proxy used to display items in a instance. diff --git a/src/ComputeSharp.Graphics/Resources/Views/Texture3DDebugView{T}.cs b/src/ComputeSharp.Graphics/Resources/Views/Texture3DDebugView{T}.cs index d4e43269..cdd8b3d2 100644 --- a/src/ComputeSharp.Graphics/Resources/Views/Texture3DDebugView{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Views/Texture3DDebugView{T}.cs @@ -1,7 +1,6 @@ using System.Diagnostics; -using ComputeSharp.Graphics.Buffers.Abstract; -namespace ComputeSharp.Graphics.Buffers.Views +namespace ComputeSharp.Resources.Views { /// /// A debug proxy used to display items in a instance. diff --git a/src/ComputeSharp.Shaders/Translation/Interop/IDxcBlobObject.cs b/src/ComputeSharp.Shaders/Translation/Interop/IDxcBlobObject.cs index bb5efd3e..eb3cd02e 100644 --- a/src/ComputeSharp.Shaders/Translation/Interop/IDxcBlobObject.cs +++ b/src/ComputeSharp.Shaders/Translation/Interop/IDxcBlobObject.cs @@ -1,4 +1,4 @@ -using ComputeSharp.Graphics.Interop; +using ComputeSharp.Interop; using TerraFX.Interop; namespace ComputeSharp.Shaders.Translation.Interop diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index bc1b3312..1d1e59ec 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -97,7 +97,7 @@ namespace ComputeSharp.SourceGenerators Literal("This method is not intended to be called directly by user code"))))))).AddModifiers( Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( - Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.Graphics.GraphicsDevice")), + Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.GraphicsDevice")), Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType), Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))), Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) diff --git a/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs b/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs index 32c9e32e..2732e4d8 100644 --- a/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs @@ -1,7 +1,7 @@ using System; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; using Microsoft.Toolkit.Diagnostics; #if NET5_0 using GC = System.GC; diff --git a/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs b/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs index 00ec659c..50ee8172 100644 --- a/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs @@ -1,7 +1,7 @@ using System; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; using Microsoft.Toolkit.Diagnostics; namespace ComputeSharp diff --git a/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs b/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs index 8666780e..3e0ccfe6 100644 --- a/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs @@ -1,7 +1,7 @@ using System; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; using Microsoft.Toolkit.Diagnostics; namespace ComputeSharp diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index c0533982..38296899 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -3,6 +3,7 @@ using System.Diagnostics.Contracts; using ComputeSharp.__Internals; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; using ComputeSharp.Shaders; #pragma warning disable CS0618 diff --git a/tests/ComputeSharp.Tests/BufferTests.cs b/tests/ComputeSharp.Tests/BufferTests.cs index 30f97b6e..55e49552 100644 --- a/tests/ComputeSharp.Tests/BufferTests.cs +++ b/tests/ComputeSharp.Tests/BufferTests.cs @@ -1,6 +1,6 @@ using System; using System.Linq; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs index f4005f85..b75c16b7 100644 --- a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs @@ -3,6 +3,7 @@ using System.Diagnostics.Contracts; using ComputeSharp.__Internals; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; #pragma warning disable CS0618 diff --git a/tests/ComputeSharp.Tests/Texture2DTests.cs b/tests/ComputeSharp.Tests/Texture2DTests.cs index d9ce8fa5..4a6806e8 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.cs @@ -1,6 +1,6 @@ using System; using System.Linq; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; using ComputeSharp.Tests.Extensions; using Microsoft.Toolkit.HighPerformance.Memory; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/tests/ComputeSharp.Tests/Texture3DTests.cs b/tests/ComputeSharp.Tests/Texture3DTests.cs index 5b771f42..d69d4335 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.cs @@ -1,6 +1,6 @@ using System; using System.Linq; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; using ComputeSharp.Tests.Extensions; using Microsoft.Toolkit.HighPerformance.Extensions; using Microsoft.Toolkit.HighPerformance.Memory; From 6748ec03dba4c65d9439cce3268c0f5f7e2fc3f4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 21:54:59 +0100 Subject: [PATCH 13/61] Fixed some merge issues --- src/ComputeSharp.Core/PixelTypes/Rg16.cs | 2 +- .../Resources/ReadOnlyTexture2D{T,TPixel}.cs | 7 +++---- .../Resources/ReadOnlyTexture3D{T,TPixel}.cs | 7 +++---- .../Resources/ReadWriteTexture2D{T,TPixel}.cs | 7 +++---- .../Resources/ReadWriteTexture3D{T,TPixel}.cs | 7 +++---- src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs | 2 -- .../Extensions/GraphicsDeviceExtensions.cs | 2 -- tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs | 2 +- tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs | 2 +- 9 files changed, 15 insertions(+), 23 deletions(-) diff --git a/src/ComputeSharp.Core/PixelTypes/Rg16.cs b/src/ComputeSharp.Core/PixelTypes/Rg16.cs index cf294abb..dd3b6ce9 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rg16.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rg16.cs @@ -73,7 +73,7 @@ namespace ComputeSharp public static bool operator !=(Rg16 left, Rg16 right) => !left.Equals(right); /// - public override readonly bool Equals(object obj) => obj is Rg16 rgba32 && Equals(rgba32); + public override readonly bool Equals(object? obj) => obj is Rg16 rgba32 && Equals(rgba32); /// [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs index ad66a8a2..b6a6f190 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs @@ -1,10 +1,9 @@ using System.Diagnostics; using ComputeSharp.__Internals; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Views; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; #pragma warning disable CS0618 diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs index 35d64c8e..2580c375 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs @@ -1,10 +1,9 @@ using System.Diagnostics; using ComputeSharp.__Internals; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Views; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; #pragma warning disable CS0618 diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs index ca284d79..c1e586d0 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs @@ -1,10 +1,9 @@ using System.Diagnostics; using ComputeSharp.__Internals; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Views; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; #pragma warning disable CS0618 diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs index 32acd100..03dc47c5 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs @@ -1,10 +1,9 @@ using System.Diagnostics; using ComputeSharp.__Internals; using ComputeSharp.Exceptions; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Enums; -using ComputeSharp.Graphics.Buffers.Views; +using ComputeSharp.Graphics.Resources.Enums; +using ComputeSharp.Resources; +using ComputeSharp.Resources.Views; #pragma warning disable CS0618 diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index 38296899..60492b1b 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -1,8 +1,6 @@ using System; using System.Diagnostics.Contracts; using ComputeSharp.__Internals; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Resources; using ComputeSharp.Shaders; diff --git a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs index b75c16b7..e7e704e4 100644 --- a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs @@ -1,8 +1,6 @@ using System; using System.Diagnostics.Contracts; using ComputeSharp.__Internals; -using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Resources; #pragma warning disable CS0618 diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs index 78efd8c9..e7cd0d74 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs @@ -2,7 +2,7 @@ using System; using System.Numerics; using System.Reflection; using ComputeSharp.__Internals; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs index 673f6f77..c4c9e3b4 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.cs @@ -2,7 +2,7 @@ using System; using System.Numerics; using System.Reflection; using ComputeSharp.__Internals; -using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Resources; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; From cc53717a9c42854ed09cb7d3d86f8ce2ddc896d2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 5 Jan 2021 22:19:30 +0100 Subject: [PATCH 14/61] Fixed build errors, minor code tweaks --- .../Blas/BlasHelpers.cs | 1 - .../ID3D12DescriptorHandleAllocator.cs | 2 +- .../UnsupportedTextureTypeException.cs | 1 - .../Properties/Polyfills.cs | 138 +++++++++--------- .../Resources/Abstract/Buffer{T}.cs | 2 +- .../Resources/Views/BufferDebugView{T}.cs | 2 +- src/ComputeSharp.Shaders/ShaderRunner{T}.cs | 1 - .../Translation/Models/CachedShader{T}.cs | 1 - .../ShaderLoader{T}.DispatchData.cs | 3 +- .../Extensions/Buffers/BufferExtensions.cs | 2 +- src/ComputeSharp/Gpu.cs | 1 - .../ComputeSharp.Tests/InitializationTests.cs | 1 - 12 files changed, 71 insertions(+), 84 deletions(-) diff --git a/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs index 6634e708..687f86bb 100644 --- a/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs +++ b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs @@ -1,6 +1,5 @@ using System.Runtime.CompilerServices; using System.Threading.Tasks; -using ComputeSharp.Graphics; namespace ComputeSharp.Benchmark.Blas { diff --git a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs index e53489c2..f41b8007 100644 --- a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs +++ b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs @@ -4,7 +4,7 @@ using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_TYPE; #if NETSTANDARD2_0 -using GC = ComputeSharp.System.GC; +using GC = Polyfills.GC; #endif namespace ComputeSharp.Graphics.Commands.Interop diff --git a/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs b/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs index e7f1e242..511ce147 100644 --- a/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs +++ b/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs @@ -1,7 +1,6 @@ using System; using System.Diagnostics.Contracts; using System.Text; -using ComputeSharp.Graphics; using Microsoft.Toolkit.Diagnostics; namespace ComputeSharp.Exceptions diff --git a/src/ComputeSharp.Graphics/Properties/Polyfills.cs b/src/ComputeSharp.Graphics/Properties/Polyfills.cs index 1e457f1a..cfd91f55 100644 --- a/src/ComputeSharp.Graphics/Properties/Polyfills.cs +++ b/src/ComputeSharp.Graphics/Properties/Polyfills.cs @@ -4,90 +4,84 @@ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -namespace ComputeSharp +namespace Polyfills { - namespace System + /// + /// A polyfill class for the type. + /// + internal static class GC { /// - /// A polyfill class for the type. + /// Allocates an array while skipping zero-initialization, if possible. /// - internal static class GC + /// Specifies the type of the array element. + /// Specifies the length of the array. + /// Specifies whether the allocated array must be pinned. + /// An array object with uninitialized memory, if possible. + public static T[] AllocateUninitializedArray(int length, bool pinned = false) + { + return new T[length]; + } + } + + /// + /// A polyfill class for the type. + /// + internal static class MemoryMarshal + { + /// + /// Returns a reference to the 0th element of array. If the array is empty, returns + /// a reference to where the 0th element would have been stored. Such a reference + /// may be used for pinning but must never be dereferenced. + /// + /// The type of the array elements. + /// The array to analyze. + /// Reference to the 0th element in array. + public static ref T GetArrayDataReference(T[] array) + { + IntPtr offset = TypeInfo.ArrayDataByteOffset; + RawObjectData rawObject = Unsafe.As(array)!; + ref byte r0 = ref rawObject.Data; + ref byte r1 = ref Unsafe.AddByteOffset(ref r0, offset); + ref T r2 = ref Unsafe.As(ref r1); + + return ref r2; + } + + /// + /// A private generic class to preload type info for arbitrary runtime types. + /// + /// The type to load info for. + private static class TypeInfo { /// - /// Allocates an array while skipping zero-initialization, if possible. + /// The byte offset to the first element in a SZ array. /// - /// Specifies the type of the array element. - /// Specifies the length of the array. - /// Specifies whether the allocated array must be pinned. - /// An array object with uninitialized memory, if possible. - public static T[] AllocateUninitializedArray(int length, bool pinned = false) + public static readonly IntPtr ArrayDataByteOffset = MeasureArrayDataByteOffset(); + + /// + /// Computes the value for . + /// + /// The value of for the current runtime. + private static IntPtr MeasureArrayDataByteOffset() { - return new T[length]; + T[] array = new T[1]; + RawObjectData rawObject = Unsafe.As(array)!; + ref byte r0 = ref rawObject.Data; + ref byte r1 = ref Unsafe.As(ref array[0]); + + return Unsafe.ByteOffset(ref r0, ref r1); } } - namespace Runtime.InteropServices + /// + /// Mapping type for a raw object. + /// + [StructLayout(LayoutKind.Explicit)] + private sealed class RawObjectData { - /// - /// A polyfill class for the type. - /// - internal static class MemoryMarshal - { - /// - /// Returns a reference to the 0th element of array. If the array is empty, returns - /// a reference to where the 0th element would have been stored. Such a reference - /// may be used for pinning but must never be dereferenced. - /// - /// The type of the array elements. - /// The array to analyze. - /// Reference to the 0th element in array. - public static ref T GetArrayDataReference(T[] array) - { - IntPtr offset = TypeInfo.ArrayDataByteOffset; - RawObjectData rawObject = Unsafe.As(array)!; - ref byte r0 = ref rawObject.Data; - ref byte r1 = ref Unsafe.AddByteOffset(ref r0, offset); - ref T r2 = ref Unsafe.As(ref r1); - - return ref r2; - } - - /// - /// A private generic class to preload type info for arbitrary runtime types. - /// - /// The type to load info for. - private static class TypeInfo - { - /// - /// The byte offset to the first element in a SZ array. - /// - public static readonly IntPtr ArrayDataByteOffset = MeasureArrayDataByteOffset(); - - /// - /// Computes the value for . - /// - /// The value of for the current runtime. - private static IntPtr MeasureArrayDataByteOffset() - { - T[] array = new T[1]; - RawObjectData rawObject = Unsafe.As(array)!; - ref byte r0 = ref rawObject.Data; - ref byte r1 = ref Unsafe.As(ref array[0]); - - return Unsafe.ByteOffset(ref r0, ref r1); - } - } - - /// - /// Mapping type for a raw object. - /// - [StructLayout(LayoutKind.Explicit)] - private sealed class RawObjectData - { - [FieldOffset(0)] - public byte Data; - } - } + [FieldOffset(0)] + public byte Data; } } } diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs index 76fd6afd..d8434aa6 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs @@ -10,7 +10,7 @@ using FX = TerraFX.Interop.Windows; #if NET5_0 using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal; #else -using MemoryMarshal = ComputeSharp.System.Runtime.InteropServices.MemoryMarshal; +using MemoryMarshal = Polyfills.MemoryMarshal; #endif namespace ComputeSharp.Resources diff --git a/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs b/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs index fb4da827..bd78980e 100644 --- a/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs @@ -2,7 +2,7 @@ #if NET5_0 using GC = System.GC; #else -using GC = ComputeSharp.System.GC; +using GC = Polyfills.GC; #endif namespace ComputeSharp.Resources.Views diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs index 3ceb999b..04683a7f 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -4,7 +4,6 @@ using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.Core.Extensions; -using ComputeSharp.Graphics; using ComputeSharp.Graphics.Commands; using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Renderer; diff --git a/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs b/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs index 9c65823a..da4de180 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/CachedShader{T}.cs @@ -1,5 +1,4 @@ using System.Runtime.CompilerServices; -using ComputeSharp.Graphics; using ComputeSharp.Graphics.Commands; using ComputeSharp.Shaders.Translation.Interop; diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs index 76fe2554..db6b8bef 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs @@ -4,13 +4,12 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; -using ComputeSharp.Graphics; using ComputeSharp.Shaders.Translation.Models; using TerraFX.Interop; #if NET5_0 using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal; #else -using MemoryMarshal = ComputeSharp.System.Runtime.InteropServices.MemoryMarshal; +using MemoryMarshal = Polyfills.MemoryMarshal; #endif namespace ComputeSharp.Shaders.Translation diff --git a/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs b/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs index 2732e4d8..a838cc5b 100644 --- a/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs @@ -6,7 +6,7 @@ using Microsoft.Toolkit.Diagnostics; #if NET5_0 using GC = System.GC; #else -using GC = ComputeSharp.System.GC; +using GC = Polyfills.GC; #endif namespace ComputeSharp diff --git a/src/ComputeSharp/Gpu.cs b/src/ComputeSharp/Gpu.cs index c138b30b..affd1d93 100644 --- a/src/ComputeSharp/Gpu.cs +++ b/src/ComputeSharp/Gpu.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Diagnostics.Contracts; -using ComputeSharp.Graphics; using ComputeSharp.Graphics.Helpers; namespace ComputeSharp diff --git a/tests/ComputeSharp.Tests/InitializationTests.cs b/tests/ComputeSharp.Tests/InitializationTests.cs index 586b5b4e..661896e0 100644 --- a/tests/ComputeSharp.Tests/InitializationTests.cs +++ b/tests/ComputeSharp.Tests/InitializationTests.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using ComputeSharp.Graphics; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.Tests From 7c156a2dab2aa4a26eafb23c313cf7bea649e823 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Jan 2021 00:05:36 +0100 Subject: [PATCH 15/61] Minor code tweaks --- .../Extensions/ID3D12DeviceExtensions.cs | 2 +- .../Extensions/ID3D12GraphicsCommandListExtensions.cs | 1 - src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs | 2 +- src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs | 4 ++-- src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs | 4 ++-- .../ComputeSharp.SourceGenerators.csproj | 2 -- 6 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs index ae2e91e9..6d177f7c 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.Contracts; using ComputeSharp.Core.Extensions; +using ComputeSharp.Graphics.Resources.Enums; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_QUEUE_FLAGS; @@ -18,7 +19,6 @@ using static TerraFX.Interop.D3D12_RESOURCE_STATES; using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; using FX = TerraFX.Interop.Windows; -using ComputeSharp.Graphics.Resources.Enums; namespace ComputeSharp.Graphics.Extensions { diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12GraphicsCommandListExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12GraphicsCommandListExtensions.cs index a228f3ed..bdd20afa 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12GraphicsCommandListExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12GraphicsCommandListExtensions.cs @@ -17,7 +17,6 @@ namespace ComputeSharp.Graphics.Extensions /// The depthwise offset in the destination texture. /// The source (a buffer) to read from. /// The value describing . - public static void CopyTextureRegion( this ref ID3D12GraphicsCommandList d3D12GraphicsCommandList, ID3D12Resource* d3D12ResourceDestination, diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs index d8434aa6..0bab9ab9 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs @@ -87,7 +87,7 @@ namespace ComputeSharp.Resources } /// - /// Gets the associated with the current instance. + /// Gets the associated with the current instance. /// public GraphicsDevice GraphicsDevice { get; } diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs index 30e2a48f..89434f8f 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs @@ -53,7 +53,7 @@ namespace ComputeSharp.Resources /// /// Creates a new instance with the specified parameters. /// - /// The associated with the current instance. + /// The associated with the current instance. /// The height of the texture. /// The width of the texture. /// The resource type for the current texture. @@ -99,7 +99,7 @@ namespace ComputeSharp.Resources } /// - /// Gets the associated with the current instance. + /// Gets the associated with the current instance. /// public GraphicsDevice GraphicsDevice { get; } diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs index 9d262a7c..da06d3fb 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs @@ -53,7 +53,7 @@ namespace ComputeSharp.Resources /// /// Creates a new instance with the specified parameters. /// - /// The associated with the current instance. + /// The associated with the current instance. /// The height of the texture. /// The width of the texture. /// The depth of the texture. @@ -103,7 +103,7 @@ namespace ComputeSharp.Resources } /// - /// Gets the associated with the current instance. + /// Gets the associated with the current instance. /// public GraphicsDevice GraphicsDevice { get; } diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 03fb352f..14f36b67 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -2,8 +2,6 @@ netstandard2.0 - true - 9.0 From a126052185e100f5c9a3fd23bd057cc0d0592292 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Jan 2021 00:05:45 +0100 Subject: [PATCH 16/61] Removed unnecessary NuGet package --- src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index 3d2eefe6..e52ebdb8 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -8,11 +8,6 @@ - - - - - From c2f6e81e76d8dce07260caf3633a0c747fb24168 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Jan 2021 16:09:36 +0100 Subject: [PATCH 17/61] Added unorm texture interface types --- .../Interfaces/IReadOnlyTexture2D{TPixel}.cs | 26 ++++++++++++++++++ .../Interfaces/IReadOnlyTexture3D{TPixel}.cs | 27 +++++++++++++++++++ .../Interfaces/IReadWriteTexture2D{TPixel}.cs | 26 ++++++++++++++++++ .../Interfaces/IReadWriteTexture3D{TPixel}.cs | 27 +++++++++++++++++++ .../Resources/ReadOnlyTexture2D{T,TPixel}.cs | 15 +++-------- .../Resources/ReadOnlyTexture3D{T,TPixel}.cs | 16 +++-------- .../Resources/ReadWriteTexture2D{T,TPixel}.cs | 15 +++-------- .../Resources/ReadWriteTexture3D{T,TPixel}.cs | 16 +++-------- 8 files changed, 118 insertions(+), 50 deletions(-) create mode 100644 src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs create mode 100644 src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs create mode 100644 src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs create mode 100644 src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs diff --git a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs new file mode 100644 index 00000000..b03ba5c9 --- /dev/null +++ b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs @@ -0,0 +1,26 @@ +namespace ComputeSharp +{ + /// + /// An interface representing a typed readonly 2D texture containing normalized pixel data stored on GPU memory. + /// This interface can only be used to wrap instances. + /// + /// The type of normalized pixels used on the GPU side. + public interface IReadOnlyTexture2D + where TPixel : unmanaged + { + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public TPixel this[int x, int y] { get; } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public TPixel this[Int2 xy] { get; } + } +} diff --git a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs new file mode 100644 index 00000000..a718f10f --- /dev/null +++ b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs @@ -0,0 +1,27 @@ +namespace ComputeSharp +{ + /// + /// An interface representing a typed readonly 3D texture containing normalized pixel data stored on GPU memory. + /// This interface can only be used to wrap instances. + /// + /// The type of normalized pixels used on the GPU side. + public interface IReadOnlyTexture3D + where TPixel : unmanaged + { + /// + /// Gets a single value from the current readonly texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// The depthwise offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public TPixel this[int x, int y, int z] { get; } + + /// + /// Gets a single value from the current readonly texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public TPixel this[Int3 xyz] { get; } + } +} diff --git a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs new file mode 100644 index 00000000..62cd23f9 --- /dev/null +++ b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs @@ -0,0 +1,26 @@ +namespace ComputeSharp +{ + /// + /// An interface representing a typed writeable 2D texture containing normalized pixel data stored on GPU memory. + /// This interface can only be used to wrap instances. + /// + /// The type of normalized pixels used on the GPU side. + public interface IReadWriteTexture2D + where TPixel : unmanaged + { + /// + /// Gets a single value from the current writeable texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref TPixel this[int x, int y] { get; } + + /// + /// Gets or sets a single value from the current writeable texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref TPixel this[Int2 xy] { get; } + } +} diff --git a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs new file mode 100644 index 00000000..7e04187e --- /dev/null +++ b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs @@ -0,0 +1,27 @@ +namespace ComputeSharp +{ + /// + /// An interface representing a typed writeable 2D texture containing normalized pixel data stored on GPU memory. + /// This interface can only be used to wrap instances. + /// + /// The type of normalized pixels used on the GPU side. + public interface IReadWriteTexture3D + where TPixel : unmanaged + { + /// + /// Gets a single value from the current writeable texture. + /// + /// The horizontal offset of the value to get. + /// The vertical offset of the value to get. + /// The depthwise offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref TPixel this[int x, int y, int z] { get; } + + /// + /// Gets a single value from the current writeable texture. + /// + /// The coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + public ref TPixel this[Int3 xyz] { get; } + } +} diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs index b6a6f190..e2a1ab08 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs @@ -16,7 +16,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. [DebuggerTypeProxy(typeof(Texture2DDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] - public sealed class ReadOnlyTexture2D : Texture2D + public sealed class ReadOnlyTexture2D : Texture2D, IReadOnlyTexture2D where T : unmanaged, IUnorm where TPixel : unmanaged { @@ -31,19 +31,10 @@ namespace ComputeSharp { } - /// - /// Gets a single value from the current readonly texture. - /// - /// The horizontal offset of the value to get. - /// The vertical offset of the value to get. - /// This API can only be used from a compute shader, and will always throw if used anywhere else. + /// public TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D)}[int,int]"); - /// - /// Gets a single value from the current readonly texture. - /// - /// The coordinates of the value to get. - /// This API can only be used from a compute shader, and will always throw if used anywhere else. + /// public TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D)}[Int2]"); /// diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs index 2580c375..07d4d98a 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs @@ -16,7 +16,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. [DebuggerTypeProxy(typeof(Texture3DDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] - public sealed class ReadOnlyTexture3D : Texture3D + public sealed class ReadOnlyTexture3D : Texture3D, IReadOnlyTexture3D where T : unmanaged, IUnorm where TPixel : unmanaged { @@ -32,20 +32,10 @@ namespace ComputeSharp { } - /// - /// Gets a single value from the current readonly texture. - /// - /// The horizontal offset of the value to get. - /// The vertical offset of the value to get. - /// The depthwise offset of the value to get. - /// This API can only be used from a compute shader, and will always throw if used anywhere else. + /// public TPixel this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D)}[int,int,int]"); - /// - /// Gets a single value from the current readonly texture. - /// - /// The coordinates of the value to get. - /// This API can only be used from a compute shader, and will always throw if used anywhere else. + /// public TPixel this[Int3 xyz] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D)}[Int3]"); /// diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs index c1e586d0..28366eb3 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs @@ -16,7 +16,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. [DebuggerTypeProxy(typeof(Texture2DDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] - public sealed class ReadWriteTexture2D : Texture2D + public sealed class ReadWriteTexture2D : Texture2D, IReadWriteTexture2D where T : unmanaged, IUnorm where TPixel : unmanaged { @@ -31,19 +31,10 @@ namespace ComputeSharp { } - /// - /// Gets a single value from the current writeable texture. - /// - /// The horizontal offset of the value to get. - /// The vertical offset of the value to get. - /// This API can only be used from a compute shader, and will always throw if used anywhere else. + /// public ref TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture2D)}[int,int]"); - /// - /// Gets or sets a single value from the current writeable texture. - /// - /// The coordinates of the value to get. - /// This API can only be used from a compute shader, and will always throw if used anywhere else. + /// public ref TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture2D)}[Int2]"); /// diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs index 03dc47c5..7a0caaa2 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs @@ -16,7 +16,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. [DebuggerTypeProxy(typeof(Texture3DDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] - public sealed class ReadWriteTexture3D : Texture3D + public sealed class ReadWriteTexture3D : Texture3D, IReadWriteTexture3D where T : unmanaged, IUnorm where TPixel : unmanaged { @@ -32,20 +32,10 @@ namespace ComputeSharp { } - /// - /// Gets a single value from the current writeable texture. - /// - /// The horizontal offset of the value to get. - /// The vertical offset of the value to get. - /// The depthwise offset of the value to get. - /// This API can only be used from a compute shader, and will always throw if used anywhere else. + /// public ref TPixel this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture3D)}[int,int,int]"); - /// - /// Gets a single value from the current writeable texture. - /// - /// The coordinates of the value to get. - /// This API can only be used from a compute shader, and will always throw if used anywhere else. + /// public ref TPixel this[Int3 xyz] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture3D)}[Int3]"); /// From 226481aff6920ef3b7b79d5b880f1df68531e084 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Jan 2021 16:15:10 +0100 Subject: [PATCH 18/61] Tweaked visibility of some resource fields --- src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs | 2 +- src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs | 2 +- src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs index 0bab9ab9..85085968 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs @@ -30,7 +30,7 @@ namespace ComputeSharp.Resources /// /// The instance for the current resource. /// - internal readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle; + private readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle; /// /// The instance for the current resource. diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs index 89434f8f..b2cf57b9 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs @@ -32,7 +32,7 @@ namespace ComputeSharp.Resources /// /// The instance for the current resource. /// - internal readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle; + private readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle; /// /// The instance for the current resource. diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs index da06d3fb..cc6a528c 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs @@ -32,7 +32,7 @@ namespace ComputeSharp.Resources /// /// The instance for the current resource. /// - internal readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle; + private readonly D3D12_CPU_DESCRIPTOR_HANDLE D3D12CpuDescriptorHandle; /// /// The instance for the current resource. From 958fa15a11d5572e6964229f43e8eb1ddd5a0dc4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Jan 2021 17:28:55 +0100 Subject: [PATCH 19/61] Added dispatch helpers for normalized texture interfaces --- .../Commands/CommandList.cs | 2 +- .../__Internals/GraphicsResourceHelper.cs | 136 ++++++++++++++++-- .../Resources/Abstract/Texture2D{T}.cs | 14 +- .../Resources/Abstract/Texture3D{T}.cs | 14 +- .../Mappings/HlslKnownKeywords.cs | 2 +- 5 files changed, 152 insertions(+), 16 deletions(-) diff --git a/src/ComputeSharp.Graphics/Commands/CommandList.cs b/src/ComputeSharp.Graphics/Commands/CommandList.cs index 3b30eca0..f75edc4f 100644 --- a/src/ComputeSharp.Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp.Graphics/Commands/CommandList.cs @@ -9,7 +9,7 @@ using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; namespace ComputeSharp.Graphics.Commands { /// - /// A command list to set and execute operaations on the GPU. + /// A command list to set and execute operations on the GPU. /// internal unsafe ref struct CommandList { diff --git a/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index 03a2c82f..9abde184 100644 --- a/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -2,6 +2,7 @@ using System.ComponentModel; using System.Runtime.CompilerServices; using ComputeSharp.Resources; +using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; namespace ComputeSharp.__Internals @@ -13,11 +14,26 @@ namespace ComputeSharp.__Internals [Obsolete("This type is not intended to be used directly by user code")] public static class GraphicsResourceHelper { + /// + /// An interface for non-generic graphics resource types. + /// + internal interface IGraphicsResource + { + /// + /// Validates the given resource for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The target instance in use. + /// The GPU descriptor handle for the resource. + D3D12_GPU_DESCRIPTOR_HANDLE ValidateAndGetGpuDescriptorHandle(GraphicsDevice device); + } + /// /// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle. /// + /// The type of values stored in the input buffer. /// The input instance to check. /// The target instance in use. + /// The GPU descriptor handle for the buffer. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -31,37 +47,133 @@ namespace ComputeSharp.__Internals } /// - /// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle. + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. /// - /// The input instance to check. + /// The type of values stored in the input texture. + /// The input instance to check. /// The target instance in use. + /// The GPU descriptor handle for the texture. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ulong ValidateAndGetGpuDescriptorHandle(Texture2D buffer, GraphicsDevice device) + public static ulong ValidateAndGetGpuDescriptorHandle(Texture2D texture, GraphicsDevice device) where T : unmanaged { - buffer.ThrowIfDisposed(); - buffer.ThrowIfDeviceMismatch(device); + texture.ThrowIfDisposed(); + texture.ThrowIfDeviceMismatch(device); - return Unsafe.As(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle)); + return Unsafe.As(ref Unsafe.AsRef(in texture.D3D12GpuDescriptorHandle)); } /// - /// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle. + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. /// - /// The input instance to check. + /// The type of normalized values stored in the input texture. + /// The input instance to check. /// The target instance in use. + /// The GPU descriptor handle for the texture. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ulong ValidateAndGetGpuDescriptorHandle(Texture3D buffer, GraphicsDevice device) + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture2D texture, GraphicsDevice device) + where TPixel : unmanaged + { + if (texture is IGraphicsResource resource) + { + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = resource.ValidateAndGetGpuDescriptorHandle(device); + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + return ThrowHelper.ThrowArgumentException("The input texture is not a valid instance"); + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of normalized values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteTexture2D texture, GraphicsDevice device) + where TPixel : unmanaged + { + if (texture is IGraphicsResource resource) + { + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = resource.ValidateAndGetGpuDescriptorHandle(device); + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + return ThrowHelper.ThrowArgumentException("The input texture is not a valid instance"); + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ValidateAndGetGpuDescriptorHandle(Texture3D texture, GraphicsDevice device) where T : unmanaged { - buffer.ThrowIfDisposed(); - buffer.ThrowIfDeviceMismatch(device); + texture.ThrowIfDisposed(); + texture.ThrowIfDeviceMismatch(device); - return Unsafe.As(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle)); + return Unsafe.As(ref Unsafe.AsRef(in texture.D3D12GpuDescriptorHandle)); + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of normalized values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadOnlyTexture3D texture, GraphicsDevice device) + where TPixel : unmanaged + { + if (texture is IGraphicsResource resource) + { + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = resource.ValidateAndGetGpuDescriptorHandle(device); + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + return ThrowHelper.ThrowArgumentException("The input texture is not a valid instance"); + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of normalized values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe ulong ValidateAndGetGpuDescriptorHandle(IReadWriteTexture3D texture, GraphicsDevice device) + where TPixel : unmanaged + { + if (texture is IGraphicsResource resource) + { + D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle = resource.ValidateAndGetGpuDescriptorHandle(device); + + return *(ulong*)&d3D12GpuDescriptorHandle; + } + + return ThrowHelper.ThrowArgumentException("The input texture is not a valid instance"); } } } diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs index b2cf57b9..6ea4d30e 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs @@ -1,4 +1,5 @@ using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; @@ -15,13 +16,15 @@ using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; using FX = TerraFX.Interop.Windows; +#pragma warning disable CS0618 + namespace ComputeSharp.Resources { /// /// A representing a typed 2D texture stored on GPU memory. /// /// The type of items stored on the texture. - public unsafe abstract class Texture2D : NativeObject + public unsafe abstract class Texture2D : NativeObject, GraphicsResourceHelper.IGraphicsResource where T : unmanaged { /// @@ -281,5 +284,14 @@ namespace ComputeSharp.Resources GraphicsDeviceMismatchException.Throw(this, device); } } + + /// + D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) + { + ThrowIfDisposed(); + ThrowIfDeviceMismatch(device); + + return D3D12GpuDescriptorHandle; + } } } diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs index cc6a528c..207afc44 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs @@ -1,4 +1,5 @@ using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Commands; using ComputeSharp.Graphics.Extensions; @@ -15,13 +16,15 @@ using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; using FX = TerraFX.Interop.Windows; +#pragma warning disable CS0618 + namespace ComputeSharp.Resources { /// /// A representing a typed 3D texture stored on GPU memory. /// /// The type of items stored on the texture. - public unsafe abstract class Texture3D : NativeObject + public unsafe abstract class Texture3D : NativeObject, GraphicsResourceHelper.IGraphicsResource where T : unmanaged { /// @@ -304,5 +307,14 @@ namespace ComputeSharp.Resources GraphicsDeviceMismatchException.Throw(this, device); } } + + /// + D3D12_GPU_DESCRIPTOR_HANDLE GraphicsResourceHelper.IGraphicsResource.ValidateAndGetGpuDescriptorHandle(GraphicsDevice device) + { + ThrowIfDisposed(); + ThrowIfDeviceMismatch(device); + + return D3D12GpuDescriptorHandle; + } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownKeywords.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownKeywords.cs index 750ce0e5..c8f03de0 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownKeywords.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownKeywords.cs @@ -28,7 +28,7 @@ namespace ComputeSharp.SourceGenerators.Mappings /// Tries to get the mapped HLSL-compatible identifier name for the input identifier name. /// /// The input identifier name. - /// The mapped identifier name, if aa replacement is needed. + /// The mapped identifier name, if a replacement is needed. /// The HLSL-compatible identifier name that can be used in an HLSL shader. [Pure] public static bool TryGetMappedName(string name, out string? mapped) From 2c90b7a92ccdb290a7507bd5a4fdc5e47c31952f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Jan 2021 18:01:03 +0100 Subject: [PATCH 20/61] Implemented source generator support for interfaces --- .../__Internals/GraphicsResourceHelper.cs | 46 +++++++++++++++++-- .../Translation/Mappings/HlslKnownTypes.cs | 8 +++- .../Mappings/HlslKnownMembers.cs | 6 ++- .../Mappings/HlslKnownTypes.cs | 8 ++++ 4 files changed, 61 insertions(+), 7 deletions(-) diff --git a/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index 9abde184..fdf9a066 100644 --- a/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -50,13 +50,32 @@ namespace ComputeSharp.__Internals /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. /// /// The type of values stored in the input texture. - /// The input instance to check. + /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ulong ValidateAndGetGpuDescriptorHandle(Texture2D texture, GraphicsDevice device) + public static ulong ValidateAndGetGpuDescriptorHandle(ReadOnlyTexture2D texture, GraphicsDevice device) + where T : unmanaged + { + texture.ThrowIfDisposed(); + texture.ThrowIfDeviceMismatch(device); + + return Unsafe.As(ref Unsafe.AsRef(in texture.D3D12GpuDescriptorHandle)); + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ValidateAndGetGpuDescriptorHandle(ReadWriteTexture2D texture, GraphicsDevice device) where T : unmanaged { texture.ThrowIfDisposed(); @@ -115,13 +134,32 @@ namespace ComputeSharp.__Internals /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. /// /// The type of values stored in the input texture. - /// The input instance to check. + /// The input instance to check. /// The target instance in use. /// The GPU descriptor handle for the texture. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static ulong ValidateAndGetGpuDescriptorHandle(Texture3D texture, GraphicsDevice device) + public static ulong ValidateAndGetGpuDescriptorHandle(ReadOnlyTexture3D texture, GraphicsDevice device) + where T : unmanaged + { + texture.ThrowIfDisposed(); + texture.ThrowIfDeviceMismatch(device); + + return Unsafe.As(ref Unsafe.AsRef(in texture.D3D12GpuDescriptorHandle)); + } + + /// + /// Validates the given texture for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The type of values stored in the input texture. + /// The input instance to check. + /// The target instance in use. + /// The GPU descriptor handle for the texture. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ValidateAndGetGpuDescriptorHandle(ReadWriteTexture3D texture, GraphicsDevice device) where T : unmanaged { texture.ThrowIfDisposed(); diff --git a/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs index b2c84d86..5776c971 100644 --- a/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.Shaders/Translation/Mappings/HlslKnownTypes.cs @@ -79,7 +79,9 @@ namespace ComputeSharp.Shaders.Mappings genericType == typeof(ReadOnlyTexture2D<>) || genericType == typeof(ReadOnlyTexture2D<,>) || genericType == typeof(ReadOnlyTexture3D<>) || - genericType == typeof(ReadOnlyTexture3D<,>); + genericType == typeof(ReadOnlyTexture3D<,>) || + genericType == typeof(IReadOnlyTexture2D<>) || + genericType == typeof(IReadOnlyTexture3D<>); } /// @@ -99,7 +101,9 @@ namespace ComputeSharp.Shaders.Mappings genericType == typeof(ReadWriteTexture2D<>) || genericType == typeof(ReadWriteTexture2D<,>) || genericType == typeof(ReadWriteTexture3D<>) || - genericType == typeof(ReadWriteTexture3D<,>); + genericType == typeof(ReadWriteTexture3D<,>) || + genericType == typeof(IReadWriteTexture2D<>) || + genericType == typeof(IReadWriteTexture3D<>); ; } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index e3751ef4..45200de1 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -21,10 +21,14 @@ namespace ComputeSharp.SourceGenerators.Mappings [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", + [$"ComputeSharp.IReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2", [$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", [$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", - [$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" + [$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3", + [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" }; /// diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 2bc27d99..22aefe96 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -78,6 +78,10 @@ namespace ComputeSharp.SourceGenerators.Mappings case "ComputeSharp.ReadOnlyTexture3D`2": case "ComputeSharp.ReadWriteTexture3D`1": case "ComputeSharp.ReadWriteTexture3D`2": + case "ComputeSharp.IReadOnlyTexture2D`1": + case "ComputeSharp.IReadWriteTexture2D`1": + case "ComputeSharp.IReadOnlyTexture3D`1": + case "ComputeSharp.IReadWriteTexture3D`1": return true; default: return false; }; @@ -134,6 +138,10 @@ namespace ComputeSharp.SourceGenerators.Mappings "ComputeSharp.ReadOnlyTexture3D`2" => $"Texture3D", "ComputeSharp.ReadWriteTexture3D`1" => $"RWTexture3D<{mapped}>", "ComputeSharp.ReadWriteTexture3D`2" => $"RWTexture3D", + "ComputeSharp.IReadOnlyTexture2D`1" => $"Texture2D", + "ComputeSharp.IReadWriteTexture2D`1" => $"RWTexture2D", + "ComputeSharp.IReadOnlyTexture3D`1" => $"Texture3D", + "ComputeSharp.IReadWriteTexture3D`1" => $"RWTexture3D", _ => throw new ArgumentException() }; } From da339566cca5b88371f689fb0b27cecb85e512a2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Jan 2021 18:14:37 +0100 Subject: [PATCH 21/61] Added size properties to texture interfaces --- .../Interfaces/IReadOnlyTexture2D{TPixel}.cs | 10 ++++++++++ .../Interfaces/IReadOnlyTexture3D{TPixel}.cs | 15 +++++++++++++++ .../Interfaces/IReadWriteTexture2D{TPixel}.cs | 10 ++++++++++ .../Interfaces/IReadWriteTexture3D{TPixel}.cs | 15 +++++++++++++++ 4 files changed, 50 insertions(+) diff --git a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs index b03ba5c9..e2d18faf 100644 --- a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs @@ -8,6 +8,16 @@ public interface IReadOnlyTexture2D where TPixel : unmanaged { + /// + /// Gets the width of the current texture. + /// + public int Width { get; } + + /// + /// Gets the height of the current texture. + /// + public int Height { get; } + /// /// Gets a single value from the current readonly texture. /// diff --git a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs index a718f10f..df101b43 100644 --- a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs @@ -8,6 +8,21 @@ public interface IReadOnlyTexture3D where TPixel : unmanaged { + /// + /// Gets the width of the current texture. + /// + public int Width { get; } + + /// + /// Gets the height of the current texture. + /// + public int Height { get; } + + /// + /// Gets the depth of the current texture. + /// + public int Depth { get; } + /// /// Gets a single value from the current readonly texture. /// diff --git a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs index 62cd23f9..dede8cfb 100644 --- a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture2D{TPixel}.cs @@ -8,6 +8,16 @@ public interface IReadWriteTexture2D where TPixel : unmanaged { + /// + /// Gets the width of the current texture. + /// + public int Width { get; } + + /// + /// Gets the height of the current texture. + /// + public int Height { get; } + /// /// Gets a single value from the current writeable texture. /// diff --git a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs index 7e04187e..6bbfb12a 100644 --- a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadWriteTexture3D{TPixel}.cs @@ -8,6 +8,21 @@ public interface IReadWriteTexture3D where TPixel : unmanaged { + /// + /// Gets the width of the current texture. + /// + public int Width { get; } + + /// + /// Gets the height of the current texture. + /// + public int Height { get; } + + /// + /// Gets the depth of the current texture. + /// + public int Depth { get; } + /// /// Gets a single value from the current writeable texture. /// From f702a1a7374abba88ddb2764dcd171b196616671 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 6 Jan 2021 18:14:50 +0100 Subject: [PATCH 22/61] Refactored image samples to texture interfaces --- .../HlslBokehBlurProcessor{TPixel}.cs | 18 +++++++++--------- .../HlslGaussianBlurProcessor{TPixel}.cs | 12 ++++++------ 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index 25d0d23b..7fb37dd0 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -288,13 +288,13 @@ namespace ComputeSharp.BokehBlur.Processors /// /// Performs a vertical 1D complex convolution with the specified parameters. /// - /// The source to read data from. + /// The source to read data from. /// The target to write the real results to. /// The target to write the imaginary results to. /// The with the values for the current complex kernel. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyVerticalConvolution( - ReadWriteTexture2D source, + IReadWriteTexture2D source, ReadWriteTexture2D reals, ReadWriteTexture2D imaginaries, ReadOnlyBuffer kernel) @@ -324,7 +324,7 @@ namespace ComputeSharp.BokehBlur.Processors public int maxX; public int kernelLength; - public ReadWriteTexture2D source; + public IReadWriteTexture2D source; public ReadWriteTexture2D reals; public ReadWriteTexture2D imaginaries; public ReadOnlyBuffer kernel; @@ -431,9 +431,9 @@ namespace ComputeSharp.BokehBlur.Processors /// /// Applies the gamma highlight pass to compute the final pixel values for a target image. /// - /// The source instance to modify. + /// The source instance to modify. [Pure] - private void ApplyGammaHighlight(ReadWriteTexture2D source) + private void ApplyGammaHighlight(IReadWriteTexture2D source) { Gpu.Default.For(source.Height, new GammaHighlightProcessor(source.Width, source)); } @@ -446,7 +446,7 @@ namespace ComputeSharp.BokehBlur.Processors { public readonly int width; - public readonly ReadWriteTexture2D source; + public readonly IReadWriteTexture2D source; /// public void Execute(ThreadIds ids) @@ -466,11 +466,11 @@ namespace ComputeSharp.BokehBlur.Processors /// Applies the inverse gamma highlight pass to compute the final pixel values for a target image. /// /// The source instance to read from. - /// The target instance to write to. + /// The target instance to write to. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyInverseGammaExposure( ReadWriteTexture2D source, - ReadWriteTexture2D target) + IReadWriteTexture2D target) { Gpu.Default.For(source.Height, new InverseGammaHighlightProcessor(source.Width, source, target)); } @@ -484,7 +484,7 @@ namespace ComputeSharp.BokehBlur.Processors public readonly int width; public readonly ReadWriteTexture2D source; - public readonly ReadWriteTexture2D target; + public readonly IReadWriteTexture2D target; /// public void Execute(ThreadIds ids) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 5f1fa2f5..bc72a6a8 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -107,12 +107,12 @@ namespace ComputeSharp.BokehBlur.Processors /// /// Performs a vertical 1D complex convolution with the specified parameters. /// - /// The source to read data from. + /// The source to read data from. /// The target to write the results to. /// The with the values for the current complex kernel. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyVerticalConvolution( - ReadWriteTexture2D source, + IReadWriteTexture2D source, ReadWriteTexture2D target, ReadOnlyBuffer kernel) { @@ -140,7 +140,7 @@ namespace ComputeSharp.BokehBlur.Processors public readonly int maxX; public readonly int kernelLength; - public readonly ReadWriteTexture2D source; + public readonly IReadWriteTexture2D source; public readonly ReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; @@ -168,12 +168,12 @@ namespace ComputeSharp.BokehBlur.Processors /// Performs an horizontal 1D complex convolution with the specified parameters. /// /// The source to read data from. - /// The target to write the results to. + /// The target to write the results to. /// The with the values for the current complex kernel. [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ApplyHorizontalConvolution( ReadWriteTexture2D source, - ReadWriteTexture2D target, + IReadWriteTexture2D target, ReadOnlyBuffer kernel) { int height = Source.Height; @@ -201,7 +201,7 @@ namespace ComputeSharp.BokehBlur.Processors public readonly int kernelLength; public readonly ReadWriteTexture2D source; - public readonly ReadWriteTexture2D target; + public readonly IReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; /// From deae3e57bec9a568d3175e38f25dcc65388d9125 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Jan 2021 00:10:11 +0100 Subject: [PATCH 23/61] Minor code tweaks --- .../IComputeShaderSourceGenerator.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index fa51f8ba..88c6e92c 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -78,7 +78,7 @@ namespace ComputeSharp.SourceGenerators var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); - var processedMethods = localFunctions.Concat(staticMethods.Values.Select(static method => method.ToFullString())).ToArray(); + var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.ToFullString()).ToArray(); // Create the compilation unit with the source attribute var source = @@ -140,7 +140,7 @@ namespace ComputeSharp.SourceGenerators /// The set of discovered and processed static methods. /// A sequence of processed methods in , and the entry point. [Pure] - private static (string EntryPoint, IEnumerable Methods) GetProcessedMethods( + private static (string EntryPoint, IEnumerable Methods) GetProcessedMethods( StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModel semanticModel, @@ -154,7 +154,7 @@ namespace ComputeSharp.SourceGenerators select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); string? entryPoint = null; - List methods = new(); + List methods = new(); foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { @@ -177,12 +177,12 @@ namespace ComputeSharp.SourceGenerators entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); } - else methods.Add(processedMethod.NormalizeWhitespace().ToFullString()); + else methods.Add(processedMethod); // Emit the extracted local functions foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString()); + methods.Add(localFunction.Value); } } From b26fda5e8fbfd8baddeb9fee98d5383b48d3b3a1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Jan 2021 18:22:08 +0100 Subject: [PATCH 24/61] Added template method for GetDimensions(...) --- .../IComputeShaderSourceGenerator.cs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 88c6e92c..fb7f8dcb 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -226,6 +226,48 @@ namespace ComputeSharp.SourceGenerators .ToFullString(); } } + + /// + /// Creates a method to get a specific dimension size for a specified resource type. + /// + /// The input resource type (without generic parameters). + /// The type of items in the input resource. + /// The rank of the resource (must be 2 for structured buffers). + /// The target axis to get the dimension for. + /// A instance with the requested tree. + internal static MethodDeclarationSyntax CreateResourceDimensionAccessorMethod(string resourceType, string itemType, int rank, int axis) + { + // Create a static method to get a specified dimension for a target resource type. + // The method will automatically create the necessary number of temporary variables + // depending on the rank of the input resource (eg. 2 for Texture2D resources). + // For instance, this code will generate the following tree for Texture2D.Width: + // + // static int __get_Dimension0(Texture2D texture) + // { + // uint a, b; + // texture.GetDimensions(a, b); + // + // return a; + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .AddParameterListParameters( + Parameter(Identifier("resource")) + .WithType(GenericName(Identifier(resourceType)) + .AddTypeArgumentListArguments(IdentifierName(itemType)))) + .WithBody(Block( + LocalDeclarationStatement( + VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier(('a' + i).ToString()))).ToArray())), + ExpressionStatement( + InvocationExpression(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("resource"), + IdentifierName("GetDimensions"))) + .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName(('a' + i).ToString()))).ToArray())), + ReturnStatement(IdentifierName(('a' + axis).ToString())))); + } } } From e67d1161f3fc129c2f0c2246436bead4c256ed2c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Jan 2021 19:38:27 +0100 Subject: [PATCH 25/61] Implemented support for GetDimensions properties --- .../IComputeShaderSourceGenerator.cs | 44 +------------- .../Mappings/HlslKnownMembers.cs | 44 ++++++++++++++ .../SyntaxRewriters/ShaderSourceRewriter.cs | 58 ++++++++++++++++++- 3 files changed, 102 insertions(+), 44 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index fb7f8dcb..3aa284ea 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -78,7 +78,7 @@ namespace ComputeSharp.SourceGenerators var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); - var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.ToFullString()).ToArray(); + var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); // Create the compilation unit with the source attribute var source = @@ -226,48 +226,6 @@ namespace ComputeSharp.SourceGenerators .ToFullString(); } } - - /// - /// Creates a method to get a specific dimension size for a specified resource type. - /// - /// The input resource type (without generic parameters). - /// The type of items in the input resource. - /// The rank of the resource (must be 2 for structured buffers). - /// The target axis to get the dimension for. - /// A instance with the requested tree. - internal static MethodDeclarationSyntax CreateResourceDimensionAccessorMethod(string resourceType, string itemType, int rank, int axis) - { - // Create a static method to get a specified dimension for a target resource type. - // The method will automatically create the necessary number of temporary variables - // depending on the rank of the input resource (eg. 2 for Texture2D resources). - // For instance, this code will generate the following tree for Texture2D.Width: - // - // static int __get_Dimension0(Texture2D texture) - // { - // uint a, b; - // texture.GetDimensions(a, b); - // - // return a; - // } - return - MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") - .AddModifiers(Token(SyntaxKind.StaticKeyword)) - .AddParameterListParameters( - Parameter(Identifier("resource")) - .WithType(GenericName(Identifier(resourceType)) - .AddTypeArgumentListArguments(IdentifierName(itemType)))) - .WithBody(Block( - LocalDeclarationStatement( - VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier(('a' + i).ToString()))).ToArray())), - ExpressionStatement( - InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("resource"), - IdentifierName("GetDimensions"))) - .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName(('a' + i).ToString()))).ToArray())), - ReturnStatement(IdentifierName(('a' + axis).ToString())))); - } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index 45200de1..c2c58e37 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -31,6 +31,29 @@ namespace ComputeSharp.SourceGenerators.Mappings [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" }; + /// + /// The mapping of supported known size accessors for HLSL resource types. + /// + private static readonly IReadOnlyDictionary KnownSizeAccessors = new Dictionary + { + ["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0), + ["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0), + ["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1), + ["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0), + ["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1), + ["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2), + ["ComputeSharp.IReadWriteTexture2D`1.Width"] = (2, 0), + ["ComputeSharp.IReadWriteTexture2D`1.Height"] = (2, 1), + ["ComputeSharp.IReadWriteTexture3D`1.Width"] = (3, 0), + ["ComputeSharp.IReadWriteTexture3D`1.Height"] = (3, 1), + ["ComputeSharp.IReadWriteTexture3D`1.Depth"] = (3, 2) + }; + /// /// The mapping of supported known members to HLSL names. /// @@ -193,5 +216,26 @@ namespace ComputeSharp.SourceGenerators.Mappings { return KnownIndexers.TryGetValue(name, out mapped); } + + /// + /// Tries to get the mapped HLSL-compatible indexer vector type name for the input indexer name. + /// + /// The input fully qualified indexer name. + /// The mapped type name, if one is found. + /// The HLSL-compatible type name that can be used in an HLSL shader for the given indexer. + [Pure] + public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis) + { + if (KnownSizeAccessors.TryGetValue(name, out var info)) + { + (rank, axis) = info; + + return true; + } + + (rank, axis) = default((int, int)); + + return false; + } } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 0f089902..0c2e392d 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -306,7 +306,23 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters true => ParseExpression(mapping!), false => updatedNode.WithName(IdentifierName(mapping!)) }; - } + } + + // If the current member access is an access to any of the size properties in the available + // resource types (either buffer or texture types), then rewrite the subtree to transform the + // property access into an invocation of an autogenerated static helper method to get the target + // dimension for the buffer in use. The helper method is added to the list of static helpers. + if (operation is IPropertyReferenceOperation propertyOperation && + HlslKnownMembers.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) + { + INamedTypeSymbol resourceType = (INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Expression).Type!; + string resourceName = HlslKnownTypes.GetMappedName(resourceType); + MethodDeclarationSyntax methodSyntax = CreateResourceDimensionAccessorMethod(resourceName, rank, axis); + + this.staticMethods.Add(propertyOperation.Property.GetMethod!, methodSyntax); + + return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); + } } return updatedNode; @@ -416,5 +432,45 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedToken.WithoutTrivia(); } + + /// + /// Creates a method to get a specific dimension size for a specified resource type. + /// + /// The input resource type. + /// The rank of the resource (must be 2 for structured buffers). + /// The target axis to get the dimension for. + /// A instance with the requested tree. + private static MethodDeclarationSyntax CreateResourceDimensionAccessorMethod(string resourceType, int rank, int axis) + { + // Create a static method to get a specified dimension for a target resource type. + // The method will automatically create the necessary number of temporary variables + // depending on the rank of the input resource (eg. 2 for Texture2D resources). + // For instance, this code will generate the following tree for Texture2D.Width: + // + // static int __get_Dimension0(Texture2D texture) + // { + // uint _0, _1; + // texture.GetDimensions(_0, _1); + // + // return _0; + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .AddParameterListParameters( + Parameter(Identifier("resource")) + .WithType(IdentifierName(resourceType))) + .WithBody(Block( + LocalDeclarationStatement( + VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), + ExpressionStatement( + InvocationExpression(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("resource"), + IdentifierName("GetDimensions"))) + .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), + ReturnStatement(IdentifierName("_" + axis)))); + } } } From 81d04db13c46d5cd6747d91fc29a42931479c844 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Jan 2021 19:43:48 +0100 Subject: [PATCH 26/61] Minor code refactoring, skipped repeated initialization --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 82 +++++++++---------- 1 file changed, 38 insertions(+), 44 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 0c2e392d..d110eb45 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -315,11 +315,45 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (operation is IPropertyReferenceOperation propertyOperation && HlslKnownMembers.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis)) { - INamedTypeSymbol resourceType = (INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Expression).Type!; - string resourceName = HlslKnownTypes.GetMappedName(resourceType); - MethodDeclarationSyntax methodSyntax = CreateResourceDimensionAccessorMethod(resourceName, rank, axis); + IMethodSymbol key = propertyOperation.Property.GetMethod!; - this.staticMethods.Add(propertyOperation.Property.GetMethod!, methodSyntax); + if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax)) + { + INamedTypeSymbol resourceType = (INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Expression).Type!; + string resourceName = HlslKnownTypes.GetMappedName(resourceType); + + // Create a static method to get a specified dimension for a target resource type. + // The method will automatically create the necessary number of temporary variables + // depending on the rank of the input resource (eg. 2 for Texture2D resources). + // For instance, this code will generate the following tree for Texture2D.Width: + // + // static int __get_Dimension0(Texture2D texture) + // { + // uint _0, _1; + // texture.GetDimensions(_0, _1); + // + // return _0; + // } + methodSyntax = + MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") + .AddModifiers(Token(SyntaxKind.StaticKeyword)) + .AddParameterListParameters( + Parameter(Identifier("resource")) + .WithType(IdentifierName(resourceName))) + .WithBody(Block( + LocalDeclarationStatement( + VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) + .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), + ExpressionStatement( + InvocationExpression(MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("resource"), + IdentifierName("GetDimensions"))) + .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), + ReturnStatement(IdentifierName("_" + axis)))); + + this.staticMethods.Add(key, methodSyntax); + } return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression)); } @@ -432,45 +466,5 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedToken.WithoutTrivia(); } - - /// - /// Creates a method to get a specific dimension size for a specified resource type. - /// - /// The input resource type. - /// The rank of the resource (must be 2 for structured buffers). - /// The target axis to get the dimension for. - /// A instance with the requested tree. - private static MethodDeclarationSyntax CreateResourceDimensionAccessorMethod(string resourceType, int rank, int axis) - { - // Create a static method to get a specified dimension for a target resource type. - // The method will automatically create the necessary number of temporary variables - // depending on the rank of the input resource (eg. 2 for Texture2D resources). - // For instance, this code will generate the following tree for Texture2D.Width: - // - // static int __get_Dimension0(Texture2D texture) - // { - // uint _0, _1; - // texture.GetDimensions(_0, _1); - // - // return _0; - // } - return - MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}") - .AddModifiers(Token(SyntaxKind.StaticKeyword)) - .AddParameterListParameters( - Parameter(Identifier("resource")) - .WithType(IdentifierName(resourceType))) - .WithBody(Block( - LocalDeclarationStatement( - VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())), - ExpressionStatement( - InvocationExpression(MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("resource"), - IdentifierName("GetDimensions"))) - .AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())), - ReturnStatement(IdentifierName("_" + axis)))); - } } } From 97722027e4cc606b7f72424b2c91ffa7a681014f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 9 Jan 2021 20:05:54 +0100 Subject: [PATCH 27/61] Code refactorings to image processing sample --- .../HlslBokehBlurProcessor{TPixel}.cs | 148 ++++-------------- .../HlslGaussianBlurProcessor{TPixel}.cs | 76 ++------- 2 files changed, 42 insertions(+), 182 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index 7fb37dd0..5ac36156 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Diagnostics.Contracts; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -257,61 +256,38 @@ namespace ComputeSharp.BokehBlur.Processors Span span = MemoryMarshal.Cast(pixelSpan); - using ReadWriteTexture2D sourceTexture = Gpu.Default.AllocateReadWriteTexture2D(span, source.Width, source.Height); - using ReadWriteTexture2D processingTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); - using ReadWriteTexture2D realTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); - using ReadWriteTexture2D imaginaryTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); - using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); + using ReadWriteTexture2D texture = Gpu.Default.AllocateReadWriteTexture2D(span, source.Width, source.Height); + using ReadWriteTexture2D temporary = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D reals = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D imaginaries = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadOnlyBuffer kernel = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); // Preliminary gamma highlight pass - ApplyGammaHighlight(sourceTexture); - - ref Vector4 param0 = ref MemoryMarshal.GetArrayDataReference(KernelParameters); + Gpu.Default.For(source.Height, new(texture)); // Perform two 1D convolutions for each component in the current instance for (int j = 0; j < Kernels.Length; j++) { - kernelBuffer.SetData(Kernels[j]); - Vector4 parameters = Unsafe.Add(ref param0, j); + Vector4 parameters = KernelParameters[j]; - ApplyVerticalConvolution(sourceTexture, realTexture, imaginaryTexture, kernelBuffer); - ApplyHorizontalConvolutionAndAccumulatePartials(realTexture, imaginaryTexture, processingTexture, kernelBuffer, parameters.Z, parameters.W); + kernel.SetData(Kernels[j]); + + Gpu.Default.For( + source.Width, + source.Height, + new(texture, reals, imaginaries, kernel)); + + Gpu.Default.For( + source.Width, + source.Height, + new(parameters.Z, parameters.W, reals, imaginaries, temporary, kernel)); } // Apply the inverse gamma exposure pass - ApplyInverseGammaExposure(processingTexture, sourceTexture); + Gpu.Default.For(source.Height, new(temporary, texture)); // Write the final pixel data - sourceTexture.GetData(span); - } - - /// - /// Performs a vertical 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the real results to. - /// The target to write the imaginary results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyVerticalConvolution( - IReadWriteTexture2D source, - ReadWriteTexture2D reals, - ReadWriteTexture2D imaginaries, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; - - VerticalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernelLength: kernel.Length, - source, - reals, - imaginaries, - kernel); - - Gpu.Default.For(width, height, in shader); + texture.GetData(span); } /// @@ -320,10 +296,6 @@ namespace ComputeSharp.BokehBlur.Processors [AutoConstructor] internal partial struct VerticalConvolutionProcessor : IComputeShader { - public int maxY; - public int maxX; - public int kernelLength; - public IReadWriteTexture2D source; public ReadWriteTexture2D reals; public ReadWriteTexture2D imaginaries; @@ -334,13 +306,15 @@ namespace ComputeSharp.BokehBlur.Processors { Vector4 real = Vector4.Zero; Vector4 imaginary = Vector4.Zero; + int maxY = source.Height; + int maxX = source.Width; + int kernelLength = kernel.Length; int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; for (int i = 0; i < kernelLength; i++) { int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + int offsetX = Hlsl.Clamp(ids.X, 0, maxX); Vector4 color = source[offsetX, offsetY]; Complex64 factors = kernel[i]; @@ -353,49 +327,12 @@ namespace ComputeSharp.BokehBlur.Processors } } - /// - /// Performs an horizontal 1D complex convolution with the specified parameters. - /// - /// The source to read the real results from. - /// The source to read the imaginary results from. - /// The with the values for the current complex kernel. - /// The weight factor for the real component of the complex pixel values. - /// The weight factor for the imaginary component of the complex pixel values. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyHorizontalConvolutionAndAccumulatePartials( - ReadWriteTexture2D reals, - ReadWriteTexture2D imaginaries, - ReadWriteTexture2D target, - ReadOnlyBuffer kernel, - float z, - float w) - { - int height = Source.Height; - int width = Source.Width; - - HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernelLength: kernel.Length, - z, - w, - reals, - imaginaries, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - /// /// Kernel for the horizontal convolution pass. /// [AutoConstructor] internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader { - public int maxY; - public int maxX; - public int kernelLength; public float z; public float w; @@ -409,13 +346,15 @@ namespace ComputeSharp.BokehBlur.Processors { Vector4 real = Vector4.Zero; Vector4 imaginary = Vector4.Zero; + int maxY = target.Height; + int maxX = target.Width; + int kernelLength = kernel.Length; int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); for (int i = 0; i < kernelLength; i++) { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + int offsetX = Hlsl.Clamp(ids.X + i - radiusX, 0, maxX); Vector4 sourceReal = reals[offsetX, offsetY]; Vector4 sourceImaginary = imaginaries[offsetX, offsetY]; Complex64 factors = kernel[i]; @@ -428,29 +367,19 @@ namespace ComputeSharp.BokehBlur.Processors } } - /// - /// Applies the gamma highlight pass to compute the final pixel values for a target image. - /// - /// The source instance to modify. - [Pure] - private void ApplyGammaHighlight(IReadWriteTexture2D source) - { - Gpu.Default.For(source.Height, new GammaHighlightProcessor(source.Width, source)); - } - /// /// Kernel for the gamma highlight pass. /// [AutoConstructor] internal readonly partial struct GammaHighlightProcessor : IComputeShader { - public readonly int width; - public readonly IReadWriteTexture2D source; /// public void Execute(ThreadIds ids) { + int width = source.Width; + for (int i = 0; i < width; i++) { Float4 v = source[i, ids.X]; @@ -462,33 +391,20 @@ namespace ComputeSharp.BokehBlur.Processors } } - /// - /// Applies the inverse gamma highlight pass to compute the final pixel values for a target image. - /// - /// The source instance to read from. - /// The target instance to write to. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyInverseGammaExposure( - ReadWriteTexture2D source, - IReadWriteTexture2D target) - { - Gpu.Default.For(source.Height, new InverseGammaHighlightProcessor(source.Width, source, target)); - } - /// /// Kernel for the inverse gamma highlight pass. /// [AutoConstructor] internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader { - public readonly int width; - public readonly ReadWriteTexture2D source; public readonly IReadWriteTexture2D target; /// public void Execute(ThreadIds ids) { + int width = source.Width; + for (int i = 0; i < width; i++) { Float4 v = source[i, ids.X]; diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index bc72a6a8..0aad185e 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -98,48 +98,18 @@ namespace ComputeSharp.BokehBlur.Processors using ReadWriteTexture2D firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); - ApplyVerticalConvolution(sourceTexture, firstPassTexture, kernelBuffer); - ApplyHorizontalConvolution(firstPassTexture, sourceTexture, kernelBuffer); + Gpu.Default.For(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer)); + Gpu.Default.For(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer)); sourceTexture.GetData(span); } - /// - /// Performs a vertical 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyVerticalConvolution( - IReadWriteTexture2D source, - ReadWriteTexture2D target, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; - - VerticalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernel.Length, - source, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - /// /// Kernel for the vertical convolution pass. /// [AutoConstructor] internal readonly partial struct VerticalConvolutionProcessor : IComputeShader { - public readonly int maxY; - public readonly int maxX; - public readonly int kernelLength; - public readonly IReadWriteTexture2D source; public readonly ReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; @@ -148,13 +118,15 @@ namespace ComputeSharp.BokehBlur.Processors public void Execute(ThreadIds ids) { Vector4 result = Vector4.Zero; + int maxY = source.Height - 1; + int maxX = source.Width - 1; + int kernelLength = kernel.Length; int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; for (int i = 0; i < kernelLength; i++) { int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + int offsetX = Hlsl.Clamp(ids.X, 0, maxX); Vector4 color = source[offsetX, offsetY]; result += kernel[i] * color; @@ -164,42 +136,12 @@ namespace ComputeSharp.BokehBlur.Processors } } - /// - /// Performs an horizontal 1D complex convolution with the specified parameters. - /// - /// The source to read data from. - /// The target to write the results to. - /// The with the values for the current complex kernel. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ApplyHorizontalConvolution( - ReadWriteTexture2D source, - IReadWriteTexture2D target, - ReadOnlyBuffer kernel) - { - int height = Source.Height; - int width = Source.Width; - - HorizontalConvolutionProcessor shader = new( - maxY: height - 1, - maxX: width - 1, - kernel.Length, - source, - target, - kernel); - - Gpu.Default.For(width, height, in shader); - } - /// /// Kernel for the horizontal convolution pass. /// [AutoConstructor] internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader { - public readonly int maxY; - public readonly int maxX; - public readonly int kernelLength; - public readonly ReadWriteTexture2D source; public readonly IReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; @@ -208,13 +150,15 @@ namespace ComputeSharp.BokehBlur.Processors public void Execute(ThreadIds ids) { Vector4 result = Vector4.Zero; + int maxY = source.Height - 1; + int maxX = source.Width - 1; + int kernelLength = kernel.Length; int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); for (int i = 0; i < kernelLength; i++) { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + int offsetX = Hlsl.Clamp(ids.X + i - radiusX, 0, maxX); Vector4 color = source[offsetX, offsetY]; result += kernel[i] * color; From 3daafd3e16533f6ab9ca65d6802e4570b524a557 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 10 Jan 2021 18:37:13 +0100 Subject: [PATCH 28/61] Fixed handling of constants in source generators --- .../AutoConstructorGenerator.cs | 9 ++++----- .../IComputeShaderDataLoaderGenerator.cs | 2 ++ 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs index b82df4d0..40ebf95d 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs @@ -42,12 +42,11 @@ namespace ComputeSharp.SourceGenerators var structName = structDeclaration.Identifier.Text; var structModifiers = structDeclaration.Modifiers; var fields = ( - from fieldDeclaration in structDeclaration.Members.OfType() - let fieldType = fieldDeclaration.Declaration.Type - let typeName = semanticModel.GetTypeInfo(fieldType).Type!.ToDisplayString() + from fieldSymbol in structDeclarationSymbol.GetMembers().OfType() + where !fieldSymbol.IsConst + let typeName = fieldSymbol.Type!.ToDisplayString() let fieldFullType = ParseTypeName(typeName) - from fieldVariable in fieldDeclaration.Declaration.Variables - select (Type: fieldFullType, fieldVariable.Identifier)).ToImmutableArray(); + select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray(); // Create the constructor declaration for the type. This will // produce a constructor with simple initialization of all variables: diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 1d1e59ec..2922aa8a 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -141,6 +141,8 @@ namespace ComputeSharp.SourceGenerators } else if (HlslKnownTypes.IsScalarOrVectorType(typeName)) { + if (fieldSymbol.IsConst) continue; + var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); // Calculate the right offset with 16-bytes padding (HLSL constant buffer). From 27438f7a695ebb5357a05918fa3c4bbef2fbc43c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 10 Jan 2021 22:33:13 +0100 Subject: [PATCH 29/61] Implemented support for local shader constants --- .../IComputeShaderSourceAttribute.cs | 15 ++++++- .../Renderer/HlslShaderRenderer.cs | 16 ++++++-- .../Translation/IShaderLoader.cs | 5 +++ .../Translation/ShaderLoader{T}.cs | 39 +++++++++++++------ .../IComputeShaderSourceGenerator.cs | 38 ++++++++++++++++-- .../ShaderMethodSourceGenerator.cs | 2 +- .../SyntaxRewriters/ShaderSourceRewriter.cs | 32 +++++++++++++-- 7 files changed, 123 insertions(+), 24 deletions(-) diff --git a/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs index 163d3d5d..91c92c52 100644 --- a/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs @@ -24,13 +24,21 @@ namespace ComputeSharp.__Internals /// The mapped collection of shader fields. /// The source code for the method. /// The collection of processed methods. - public IComputeShaderSourceAttribute(string shaderTypeName, string[] types, object[] args, string executeMethod, string[] methods) + /// The collection of discovered constants. + public IComputeShaderSourceAttribute( + string shaderTypeName, + string[] types, + object[] args, + string executeMethod, + string[] methods, + object[] constants) { ShaderTypeName = shaderTypeName; Types = types; Fields = args.Cast().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2])); ExecuteMethod = executeMethod; Methods = methods; + Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); } /// @@ -58,6 +66,11 @@ namespace ComputeSharp.__Internals /// internal IReadOnlyCollection Methods { get; } + /// + /// Gets the collection of discovered constants. + /// + internal IReadOnlyDictionary Constants { get; } + /// /// Gets the associated instance for a specified type. /// diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index a1a69c70..6ee1583f 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -31,17 +31,27 @@ namespace ComputeSharp.Shaders.Renderer builder.AppendLine("// AUTO GENERATED"); builder.AppendLine("// ================================================"); builder.AppendLine("// This shader was created by ComputeSharp."); - builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); + builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); + builder.AppendLine(); + + // Constants + foreach (var constant in info.ConstantsInfo) + { + builder.Append("#define "); + builder.Append(constant.Key); + builder.Append(' '); + builder.AppendLine(constant.Value); + builder.AppendLine(); + } // Declared types foreach (var type in info.DeclaredTypes) { - builder.AppendLine(); builder.AppendLine(type); + builder.AppendLine(); } // Captured variables - builder.AppendLine(); builder.AppendLine("cbuffer _ : register(b0)"); builder.AppendLine('{'); builder.AppendLine(" uint __x;"); diff --git a/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs index 1a8b5be0..bf21f77e 100644 --- a/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs @@ -28,6 +28,11 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyCollection MethodsInfo { get; } + /// + /// Gets the collection of constants to be declared in the shader. + /// + public IReadOnlyDictionary ConstantsInfo { get; } + /// /// Gets the collection of declared types for the shader. /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 11ac00bd..6f3c62b0 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -61,6 +61,11 @@ namespace ComputeSharp.Shaders.Translation /// private readonly List methodsInfo = new(); + /// + /// The with the discovered constants for the shader. + /// + private readonly Dictionary constantsInfo = new(); + /// /// The with the collected declared types for the shader. /// @@ -93,6 +98,9 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyCollection MethodsInfo => this.methodsInfo; + /// + public IReadOnlyDictionary ConstantsInfo => this.constantsInfo; + /// public IReadOnlyCollection DeclaredTypes => this.declaredTypes; @@ -106,16 +114,34 @@ namespace ComputeSharp.Shaders.Translation { ShaderLoader @this = new(); + @this.LoadMethodMetadata(); + // Reading members through reflection requires an object parameter, so here we're just boxing // the input shader once to avoid allocating it multiple times while processing the shader. @this.d3D12DescriptorRanges1 = @this.LoadFieldsInfo(shader); - @this.LoadMethodMetadata(); @this.InitializeDispatchDataLoader(); return @this; } + /// + /// Loads the metadata info for the current shader. + /// + private void LoadMethodMetadata() + { + EntryPoint = Attribute.ExecuteMethod; + + this.methodsInfo.AddRange(Attribute.Methods); + + foreach (var pair in Attribute.Constants) + { + this.constantsInfo.Add(pair.Key, pair.Value); + } + + this.declaredTypes.AddRange(Attribute.Types); + } + /// /// Loads the fields info for the current shader being loaded. /// @@ -200,16 +226,5 @@ namespace ComputeSharp.Shaders.Translation } else ThrowHelper.ThrowArgumentException("Invalid captured variable"); } - - /// - /// Loads the metadata info for the current shader. - /// - private void LoadMethodMetadata() - { - EntryPoint = Attribute.ExecuteMethod; - - this.methodsInfo.AddRange(Attribute.Methods); - this.declaredTypes.AddRange(Attribute.Types); - } } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 3aa284ea..fe67c4ef 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -45,6 +45,7 @@ namespace ComputeSharp.SourceGenerators // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Helper that converts a sequence of string sequences into a nested array expression. // That is, this applies the following transformation: @@ -76,9 +77,10 @@ namespace ComputeSharp.SourceGenerators // Explore the syntax tree and extract the processed info var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods); + var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); + var processedConstants = GetProcessedConstants(structDeclarationSymbol, constantDefinitions); // Create the compilation unit with the source attribute var source = @@ -90,7 +92,8 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(ArrayExpression(processedTypes)), AttributeArgument(NestedArrayExpression(processedMembers)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))), - AttributeArgument(ArrayExpression(processedMethods))))) + AttributeArgument(ArrayExpression(processedMethods)), + AttributeArgument(NestedArrayExpression(processedConstants))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() @@ -138,6 +141,7 @@ namespace ComputeSharp.SourceGenerators /// The instance for the type to process. /// The collection of currently discovered types. /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. /// A sequence of processed methods in , and the entry point. [Pure] private static (string EntryPoint, IEnumerable Methods) GetProcessedMethods( @@ -145,7 +149,8 @@ namespace ComputeSharp.SourceGenerators INamedTypeSymbol structDeclarationSymbol, SemanticModel semanticModel, ICollection discoveredTypes, - IDictionary staticMethods) + IDictionary staticMethods, + IDictionary constantDefinitions) { // Find all declared methods in the type ImmutableArray methodDeclarations = ( @@ -159,7 +164,7 @@ namespace ComputeSharp.SourceGenerators foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { IMethodSymbol methodDeclarationSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration)!; - ShaderSourceRewriter shaderSourceRewriter = new(structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods); + ShaderSourceRewriter shaderSourceRewriter = new(structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); // Rewrite the method syntax tree var processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); @@ -189,6 +194,31 @@ namespace ComputeSharp.SourceGenerators return (entryPoint!, methods); } + /// + /// Gets a sequence of discovered constants. + /// + /// The type symbol for the shader type. + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + [Pure] + private static IEnumerable> GetProcessedConstants(INamedTypeSymbol structDeclarationSymbol, IReadOnlyDictionary constantDefinitions) + { + foreach (var constant in constantDefinitions) + { + if (SymbolEqualityComparer.Default.Equals(structDeclarationSymbol, constant.Key.ContainingSymbol)) + { + yield return new string[] { constant.Key.Name, constant.Value }; + } + else + { + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).GetFullMetadataName().Replace(".", "__"); + var constantName = $"{ownerTypeName}__{constant.Key.Name}"; + + yield return new string[] { constantName, constant.Value }; + } + } + } + /// /// Gets the sequence of processed discovered custom types. /// diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 7ce2bf63..3d39992e 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -96,7 +96,7 @@ namespace ComputeSharp.SourceGenerators ICollection discoveredTypes, IDictionary staticMethods) { - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods); + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, null); // TODO: implement constant support // Rewrite the method syntax tree var processedMethod = shaderSourceRewriter diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index d110eb45..fc4022a9 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -37,6 +37,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// private readonly IDictionary staticMethods; + /// + /// The collection of discovered constant definitions. + /// + private readonly IDictionary constantDefinitions; + /// /// The collection of processed local functions in the current tree. /// @@ -59,16 +64,19 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// The instance for the target syntax tree. /// The set of discovered custom types. /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. public ShaderSourceRewriter( INamedTypeSymbol shaderType, SemanticModel semanticModel, ICollection discoveredTypes, - IDictionary staticMethods) + IDictionary staticMethods, + IDictionary constantDefinitions) { this.shaderType = shaderType; this.semanticModel = semanticModel; this.discoveredTypes = discoveredTypes; this.staticMethods = staticMethods; + this.constantDefinitions = constantDefinitions; this.localFunctions = new(); this.implicitVariables = new(); } @@ -79,14 +87,17 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// The instance for the target syntax tree. /// The set of discovered custom types. /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. public ShaderSourceRewriter( SemanticModel semanticModel, ICollection discoveredTypes, - IDictionary staticMethods) + IDictionary staticMethods, + IDictionary constantDefinitions) { this.semanticModel = semanticModel; this.discoveredTypes = discoveredTypes; this.staticMethods = staticMethods; + this.constantDefinitions = constantDefinitions; this.implicitVariables = new(); this.localFunctions = new(); } @@ -398,7 +409,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (!this.staticMethods.ContainsKey(method)) { - ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods); + ShaderSourceRewriter shaderSourceRewriter = new(this.semanticModel, this.discoveredTypes, this.staticMethods, this.constantDefinitions); MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax(), processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace().WithoutTrivia(); @@ -452,6 +463,21 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode; } + /// + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + { + var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; + + if (this.semanticModel.GetOperation(node) is IFieldReferenceOperation operation && + operation.Field.IsConst && + !this.constantDefinitions.ContainsKey(operation.Field)) + { + this.constantDefinitions.Add(operation.Field, operation.Field.ConstantValue!.ToString()); + } + + return updatedNode; + } + /// public override SyntaxToken VisitToken(SyntaxToken token) { From ad58397e1d12958f4c62d1469abdbb2d04ae8d7c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 10 Jan 2021 22:49:36 +0100 Subject: [PATCH 30/61] Fixed handling of constants in parent type hierarchy --- .../Renderer/HlslShaderRenderer.cs | 18 +++++++++++------- .../IComputeShaderSourceGenerator.cs | 18 +++++------------- .../SyntaxRewriters/ShaderSourceRewriter.cs | 5 +++++ 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index 6ee1583f..b3066e31 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -32,26 +32,30 @@ namespace ComputeSharp.Shaders.Renderer builder.AppendLine("// ================================================"); builder.AppendLine("// This shader was created by ComputeSharp."); builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); - builder.AppendLine(); // Constants - foreach (var constant in info.ConstantsInfo) + if (info.ConstantsInfo.Count > 0) { - builder.Append("#define "); - builder.Append(constant.Key); - builder.Append(' '); - builder.AppendLine(constant.Value); builder.AppendLine(); + + foreach (var constant in info.ConstantsInfo) + { + builder.Append("#define "); + builder.Append(constant.Key); + builder.Append(' '); + builder.AppendLine(constant.Value); + } } // Declared types foreach (var type in info.DeclaredTypes) { - builder.AppendLine(type); builder.AppendLine(); + builder.AppendLine(type); } // Captured variables + builder.AppendLine(); builder.AppendLine("cbuffer _ : register(b0)"); builder.AppendLine('{'); builder.AppendLine(" uint __x;"); diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index fe67c4ef..5e96e74c 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -80,7 +80,7 @@ namespace ComputeSharp.SourceGenerators var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); - var processedConstants = GetProcessedConstants(structDeclarationSymbol, constantDefinitions); + var processedConstants = GetProcessedConstants(constantDefinitions); // Create the compilation unit with the source attribute var source = @@ -197,25 +197,17 @@ namespace ComputeSharp.SourceGenerators /// /// Gets a sequence of discovered constants. /// - /// The type symbol for the shader type. /// The collection of discovered constant definitions. /// A sequence of discovered constants to declare in the shader. [Pure] - private static IEnumerable> GetProcessedConstants(INamedTypeSymbol structDeclarationSymbol, IReadOnlyDictionary constantDefinitions) + private static IEnumerable> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) { foreach (var constant in constantDefinitions) { - if (SymbolEqualityComparer.Default.Equals(structDeclarationSymbol, constant.Key.ContainingSymbol)) - { - yield return new string[] { constant.Key.Name, constant.Value }; - } - else - { - var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).GetFullMetadataName().Replace(".", "__"); - var constantName = $"{ownerTypeName}__{constant.Key.Name}"; + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().Replace(".", "__"); + var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - yield return new string[] { constantName, constant.Value }; - } + yield return new string[] { constantName, constant.Value }; } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index fc4022a9..6580be03 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -473,6 +473,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters !this.constantDefinitions.ContainsKey(operation.Field)) { this.constantDefinitions.Add(operation.Field, operation.Field.ConstantValue!.ToString()); + + var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__"); + var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; + + return IdentifierName(constantName); } return updatedNode; From 4b5c422bc3c05332104e727ba91958a41b6cd69a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 11 Jan 2021 13:38:03 +0100 Subject: [PATCH 31/61] Implemented constant support for member accesses --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 6580be03..80112469 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -293,14 +293,15 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && this.semanticModel.GetOperation(node) is IMemberReferenceOperation operation) { - // If the current member access is to a constant, hardcode the value in HLSL - if (operation.ConstantValue is { HasValue: true } and { Value: object value }) + // If the member access is a constant, track it and replace the tree with the processed constant name + if (operation is IFieldReferenceOperation fieldOperation && fieldOperation.Field.IsConst) { - return ParseExpression(value switch - { - IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), - _ => value.ToString() - }); + this.constantDefinitions[fieldOperation.Field] = fieldOperation.Field.ConstantValue!.ToString(); + + var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__"); + var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; + + return IdentifierName(constantName); } // If the current member access is a field or property access, check the lookup table @@ -468,11 +469,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; - if (this.semanticModel.GetOperation(node) is IFieldReferenceOperation operation && - operation.Field.IsConst && - !this.constantDefinitions.ContainsKey(operation.Field)) + if (this.semanticModel.GetOperation(node) is IFieldReferenceOperation operation && operation.Field.IsConst) { - this.constantDefinitions.Add(operation.Field, operation.Field.ConstantValue!.ToString()); + this.constantDefinitions[operation.Field] = operation.Field.ConstantValue!.ToString(); var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__"); var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; From 075c7cdf9a75584b67c9ef7667f443561c1f2506 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 11 Jan 2021 14:01:33 +0100 Subject: [PATCH 32/61] Implemented constant support for methods, code refactoring --- .../ShaderMethodSourceAttribute.cs | 10 ++- .../Translation/ShaderLoader{T}.cs | 8 ++- .../Helpers/SyntaxFactoryHelper.cs | 61 +++++++++++++++++++ .../IComputeShaderSourceGenerator.cs | 31 +--------- .../ShaderMethodSourceGenerator.cs | 27 +++----- 5 files changed, 88 insertions(+), 49 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs diff --git a/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs index 195ea4d2..97104dfd 100644 --- a/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; +using System.Linq; using System.Reflection; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; @@ -35,13 +36,15 @@ namespace ComputeSharp.__Internals /// The collection of custom types. /// The source code for the target entry point method. /// The collection of processed methods. - public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods) + /// The collection of discovered constants. + public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods, object[] constants) { this.invokeMethod = invokeMethod; MethodName = methodName; Types = types; Methods = methods; + Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); } /// @@ -59,6 +62,11 @@ namespace ComputeSharp.__Internals /// internal IReadOnlyCollection Methods { get; } + /// + /// Gets the collection of discovered constants. + /// + internal IReadOnlyDictionary Constants { get; } + /// /// Gets the mapped source code for the current method. /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 6f3c62b0..12606154 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -132,14 +132,13 @@ namespace ComputeSharp.Shaders.Translation { EntryPoint = Attribute.ExecuteMethod; + this.declaredTypes.AddRange(Attribute.Types); this.methodsInfo.AddRange(Attribute.Methods); foreach (var pair in Attribute.Constants) { this.constantsInfo.Add(pair.Key, pair.Value); } - - this.declaredTypes.AddRange(Attribute.Types); } /// @@ -223,6 +222,11 @@ namespace ComputeSharp.Shaders.Translation this.declaredTypes.AddRange(methodSource.Types); this.methodsInfo.Add(methodSource.GetMappedInvokeMethod(hlslName)); this.methodsInfo.AddRange(methodSource.Methods); + + foreach (var pair in methodSource.Constants) + { + this.constantsInfo[pair.Key] = pair.Value; + } } else ThrowHelper.ThrowArgumentException("Invalid captured variable"); } diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs new file mode 100644 index 00000000..5fb2c00a --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Linq; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators.Helpers +{ + /// + /// A class containing additional factory methods for constructing syntax nodes, tokens and trivia. + /// + internal static class SyntaxFactoryHelper + { + /// + /// Creates a [] array expression from the given sequence of instances. + /// + /// That it, it applies the following transformation: + /// + /// { "S1", "S2" } => new string[] { "S1", "S2" } + /// + /// + /// + /// The input sequence of instances. + /// An instance with the described contents. + [Pure] + public static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values) + { + return + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray())); + } + + /// + /// Creates an [] array expression with the nested groups in the input sequence. + /// + /// That it, it applies the following transformation: + /// + /// { ("K1", "V1"), ("K2", "V2") } => new object[] { new[] { "K1", "V1" }, new[] { "K2", "V2" } } + /// + /// + /// + /// The input sequence of groups. + /// An instance with the described contents. + [Pure] + public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable> groups) + { + return + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions(groups.Select(static group => + ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions( + group.Select(static item => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))).ToArray()))).ToArray())); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 5e96e74c..c1b061a3 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -12,6 +12,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; #pragma warning disable CS0618 @@ -47,34 +48,6 @@ namespace ComputeSharp.SourceGenerators Dictionary staticMethods = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - // Helper that converts a sequence of string sequences into a nested array expression. - // That is, this applies the following transformation: - // - { ("K1", "V1"), ("K2", "V2") } => new object[] { new[] { "K1", "V1" }, new[] { "K2", "V2" } } - static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable> groups) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(groups.Select(static group => - ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions( - group.Select(static item => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))).ToArray()))).ToArray())); - } - - // Helper that converts a sequence of strings into an array expression. - // That is, this applies the following transformation: - // - { "S1", "S2" } => new string[] { "S1", "S2" } - static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray())); - } - // Explore the syntax tree and extract the processed info var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); @@ -200,7 +173,7 @@ namespace ComputeSharp.SourceGenerators /// The collection of discovered constant definitions. /// A sequence of discovered constants to declare in the shader. [Pure] - private static IEnumerable> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) + internal static IEnumerable> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) { foreach (var constant in constantDefinitions) { diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 3d39992e..6d817f4b 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -11,6 +11,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; #pragma warning disable CS0618 @@ -44,23 +45,12 @@ namespace ComputeSharp.SourceGenerators // We need to sets to track all discovered custom types and static methods HashSet discoveredTypes = new(SymbolEqualityComparer.Default); Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); // Explore the syntax tree and extract the processed info - var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods); + var (invokeMethod, processedMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = IComputeShaderSourceGenerator.GetProcessedTypes(discoveredTypes).ToArray(); - - // Helper that converts a sequence of strings into an array expression. - // That is, this applies the following transformation: - // - { "S1", "S2" } => new string[] { "S1", "S2" } - static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values) - { - return - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) - .AddExpressions(values.Select(static value => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(value))).ToArray())); - } + var processedConstants = IComputeShaderSourceGenerator.GetProcessedConstants(constantDefinitions); // Create the compilation unit with the source attribute var source = @@ -70,7 +60,8 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))), AttributeArgument(ArrayExpression(processedTypes)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))), - AttributeArgument(ArrayExpression(processedMethods))))) + AttributeArgument(ArrayExpression(processedMethods)), + AttributeArgument(NestedArrayExpression(processedConstants))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() @@ -88,15 +79,17 @@ namespace ComputeSharp.SourceGenerators /// The instance for the method to process. /// The collection of currently discovered types. /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. /// A sequence of processed methods in . [Pure] private static (string InvokeMethod, IEnumerable Methods) GetProcessedMethods( MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel, ICollection discoveredTypes, - IDictionary staticMethods) + IDictionary staticMethods, + IDictionary constantDefinitions) { - ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, null); // TODO: implement constant support + ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions); // Rewrite the method syntax tree var processedMethod = shaderSourceRewriter From d6228da210a53684ba70ae41c4211644920fa9db Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 11 Jan 2021 18:08:25 +0100 Subject: [PATCH 33/61] Added GroupSharedAttribute type --- .../Attributes/AutoConstructorAttribute.cs | 2 +- .../Attributes/GroupSharedAttribute.cs | 46 +++++++++++++++++++ .../Attributes/ShaderMethodAttribute.cs | 2 +- 3 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 src/ComputeSharp.Core/Attributes/GroupSharedAttribute.cs diff --git a/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs b/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs index bd4dc3e7..c5db9978 100644 --- a/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/AutoConstructorAttribute.cs @@ -5,7 +5,7 @@ namespace ComputeSharp /// /// An attribute that indicates that a target shader type should get an automatic constructor for all fields. /// - [AttributeUsage(AttributeTargets.Struct)] + [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] public sealed class AutoConstructorAttribute : Attribute { } diff --git a/src/ComputeSharp.Core/Attributes/GroupSharedAttribute.cs b/src/ComputeSharp.Core/Attributes/GroupSharedAttribute.cs new file mode 100644 index 00000000..06f561ba --- /dev/null +++ b/src/ComputeSharp.Core/Attributes/GroupSharedAttribute.cs @@ -0,0 +1,46 @@ +using System; + +namespace ComputeSharp +{ + /// + /// An attribute that indicates that an array static field in a shader type will be shared in a thread group. + /// + /// This attribute can be used to declare fields as follows: + /// + /// struct MyShader : IComputeShader + /// { + /// [GroupShared(32)] + /// static float[] MyBuffer; + /// } + /// + /// + /// The buffer shouldn't be manually initialized, as each shader invocation will automatically receive the + /// right buffer in use for the thread group it belongs to. If there is an assignment for the field, it + /// will just be ignored in the shader. Additionally, buffer types are not allowed as array items. + /// + [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] + public sealed class GroupSharedAttribute : Attribute + { + /// + /// Creates a new instance with the specified parameters. + /// + public GroupSharedAttribute() + { + } + + /// + /// Creates a new instance with the specified parameters. + /// + /// The size of the shared buffer to declare. + public GroupSharedAttribute(int size) + { + Size = size; + } + + /// + /// Gets the size of the shared buffer being declared. + /// If , the thread group size will be used. + /// + public int? Size { get; } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs b/src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs index 9eae4f37..d644045c 100644 --- a/src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/ShaderMethodAttribute.cs @@ -9,7 +9,7 @@ namespace ComputeSharp /// correctly, wrapped methods need to have this attribute manually applied to them. /// Methods also need to be static, though this can only be tested at runtime. /// - [AttributeUsage(AttributeTargets.Method)] + [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public sealed class ShaderMethodAttribute : Attribute { } From 80fd4d96e08350400454f7150a265feb08bf997f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 11 Jan 2021 20:27:14 +0100 Subject: [PATCH 34/61] Added parsing method for static buffer fields --- .../ComputeSharp.SourceGenerators.csproj | 1 + .../IComputeShaderSourceGenerator.cs | 32 +++++++++++++++++++ .../Mappings/HlslKnownTypes.cs | 18 +++++++++++ 3 files changed, 51 insertions(+) diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 14f36b67..91506957 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -14,6 +14,7 @@ and to match members based on full name, so the types being in the generator assembly are not an issue.--> + diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index c1b061a3..fd39af43 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -88,6 +88,8 @@ namespace ComputeSharp.SourceGenerators { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { + if (fieldSymbol.IsStatic) continue; + INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; string typeName = HlslKnownTypes.GetMappedName(typeSymbol); @@ -106,6 +108,36 @@ namespace ComputeSharp.SourceGenerators } } + /// + /// Gets a sequence of captured members and their mapped names. + /// + /// The input instance to process. + /// The collection of currently discovered types. + /// A sequence of captured members in . + [Pure] + private static IEnumerable> GetGroupSharedMembers(INamedTypeSymbol structDeclarationSymbol, ICollection types) + { + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (!fieldSymbol.IsStatic) continue; + + AttributeData attribute = fieldSymbol.GetAttributes().First(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; + IArrayTypeSymbol typeSymbol = (IArrayTypeSymbol)fieldSymbol.Type; + + string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + yield return new[] + { + mapping ?? fieldSymbol.Name, + typeName, + bufferSize?.ToString() ?? "-1" + }; + } + } + /// /// Gets a sequence of processed methods declared within a given type. /// diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 22aefe96..04ed2673 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -149,6 +149,24 @@ namespace ComputeSharp.SourceGenerators.Mappings return KnownTypes[typeName]; } + /// + /// Gets the mapped HLSL-compatible type name for the input element type symbol. + /// + /// The input type to map. + /// The HLSL-compatible type name that can be used in an HLSL shader. + [Pure] + public static string GetMappedElementName(IArrayTypeSymbol typeSymbol) + { + string elementTypeName = ((INamedTypeSymbol)typeSymbol.ElementType).GetFullMetadataName(); + + if (KnownTypes.TryGetValue(elementTypeName, out string? mapped)) + { + return mapped; + } + + return elementTypeName.Replace(".", "__"); + } + /// /// Gets the mapped HLSL-compatible type name for the input type name. /// From 67d1d92cae3abf9c06cbcf4aa480a0a934c4fd2d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 12 Jan 2021 16:22:23 +0100 Subject: [PATCH 35/61] Added source generator support for shared buffers --- .../IComputeShaderSourceAttribute.cs | 10 +++++- .../AutoConstructorGenerator.cs | 2 +- .../Helpers/SyntaxFactoryHelper.cs | 32 +++++++++++++++++++ .../IComputeShaderDataLoaderGenerator.cs | 2 ++ .../IComputeShaderHashCodeGenerator.cs | 2 ++ .../IComputeShaderSourceGenerator.cs | 15 ++++----- 6 files changed, 53 insertions(+), 10 deletions(-) diff --git a/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs index 91c92c52..7cd9407c 100644 --- a/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs @@ -25,13 +25,15 @@ namespace ComputeSharp.__Internals /// The source code for the method. /// The collection of processed methods. /// The collection of discovered constants. + /// The collection of group shared buffers public IComputeShaderSourceAttribute( string shaderTypeName, string[] types, object[] args, string executeMethod, string[] methods, - object[] constants) + object[] constants, + object[] sharedBuffers) { ShaderTypeName = shaderTypeName; Types = types; @@ -39,6 +41,7 @@ namespace ComputeSharp.__Internals ExecuteMethod = executeMethod; Methods = methods; Constants = constants.Cast().ToDictionary(static c => c[0], static c => c[1]); + SharedBuffers = sharedBuffers.Cast().ToDictionary(static t => (string)t[0], static t => ((string)t[1], (int?)t[2])); } /// @@ -71,6 +74,11 @@ namespace ComputeSharp.__Internals /// internal IReadOnlyDictionary Constants { get; } + /// + /// Gets the collection of discovered constants. + /// + internal IReadOnlyDictionary SharedBuffers { get; } + /// /// Gets the associated instance for a specified type. /// diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs index 40ebf95d..7111ff4b 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs @@ -43,7 +43,7 @@ namespace ComputeSharp.SourceGenerators var structModifiers = structDeclaration.Modifiers; var fields = ( from fieldSymbol in structDeclarationSymbol.GetMembers().OfType() - where !fieldSymbol.IsConst + where !fieldSymbol.IsConst && !fieldSymbol.IsStatic let typeName = fieldSymbol.Type!.ToDisplayString() let fieldFullType = ParseTypeName(typeName) select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray(); diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs index 5fb2c00a..894f6630 100644 --- a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs +++ b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs @@ -57,5 +57,37 @@ namespace ComputeSharp.SourceGenerators.Helpers ImplicitArrayCreationExpression(InitializerExpression(SyntaxKind.ArrayInitializerExpression).AddExpressions( group.Select(static item => LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))).ToArray()))).ToArray())); } + + /// + /// Creates an [] array expression with the nested groups in the input sequence. + /// + /// That it, it applies the following transformation: + /// + /// { ("K1", "V1", I1), ("K2", "V2", null) } => new object[] { new object[] { "K1", "V1", I1 }, new object[] { "K2", "V2", null } } + /// + /// + /// + /// The input sequence of groups. + /// An instance with the described contents. + [Pure] + public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B, int? C)> groups) + { + return + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions(groups.Select(static group => + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)), + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B)), + group.C is int i + ? LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(i)) + : LiteralExpression(SyntaxKind.NullLiteralExpression)))).ToArray())); + } } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 2922aa8a..834fb2d9 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -128,6 +128,8 @@ namespace ComputeSharp.SourceGenerators foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { + if (fieldSymbol.IsStatic) continue; + INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; string typeName = typeSymbol.GetFullMetadataName(); diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index ae194820..127677c7 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -120,6 +120,8 @@ namespace ComputeSharp.SourceGenerators { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { + if (fieldSymbol.IsStatic) continue; + INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; if (typeSymbol.TypeKind != TypeKind.Delegate) continue; diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index fd39af43..93f2d6a7 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -50,6 +50,7 @@ namespace ComputeSharp.SourceGenerators // Explore the syntax tree and extract the processed info var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); + var sharedBuffers = GetGroupSharedMembers(structDeclarationSymbol, discoveredTypes).ToArray(); var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray(); @@ -66,7 +67,8 @@ namespace ComputeSharp.SourceGenerators AttributeArgument(NestedArrayExpression(processedMembers)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))), AttributeArgument(ArrayExpression(processedMethods)), - AttributeArgument(NestedArrayExpression(processedConstants))))) + AttributeArgument(NestedArrayExpression(processedConstants)), + AttributeArgument(NestedArrayExpression(sharedBuffers))))) .WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList())) .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)))) .NormalizeWhitespace() @@ -115,7 +117,7 @@ namespace ComputeSharp.SourceGenerators /// The collection of currently discovered types. /// A sequence of captured members in . [Pure] - private static IEnumerable> GetGroupSharedMembers(INamedTypeSymbol structDeclarationSymbol, ICollection types) + private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers(INamedTypeSymbol structDeclarationSymbol, ICollection types) { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -129,12 +131,9 @@ namespace ComputeSharp.SourceGenerators _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - yield return new[] - { - mapping ?? fieldSymbol.Name, - typeName, - bufferSize?.ToString() ?? "-1" - }; + yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize); + + types.Add((INamedTypeSymbol)typeSymbol.ElementType); } } From a0265d9f9301b102dd9c81d1655ec23431fc5758 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 12 Jan 2021 16:22:38 +0100 Subject: [PATCH 36/61] Implemented shared buffer shader generation --- .../Renderer/HlslShaderRenderer.cs | 16 ++++++++++++++++ .../Translation/IShaderLoader.cs | 17 +++++++++++------ .../Translation/ShaderLoader{T}.cs | 4 ++++ 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index b3066e31..337325d7 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -114,6 +114,22 @@ namespace ComputeSharp.Shaders.Renderer } } + // Shared buffers + foreach (var buffer in info.SharedBuffers) + { + builder.AppendLine(); + builder.Append("groupshared "); + builder.Append(buffer.Value.Type); + builder.Append(' '); + builder.Append(buffer.Key); + builder.Append('['); + + if (buffer.Value.Count is int count) builder.Append(count.ToString()); + else builder.Append((threadsX * threadsY * threadsZ).ToString()); + + builder.AppendLine("];"); + } + // Captured methods foreach (var function in info.MethodsInfo) { diff --git a/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs index bf21f77e..0ff336a8 100644 --- a/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/IShaderLoader.cs @@ -11,31 +11,36 @@ namespace ComputeSharp.Shaders.Translation /// /// Gets the generated source code for the method in the current shader. /// - public string EntryPoint { get; } + string EntryPoint { get; } /// /// Gets the collection of items for the shader fields. /// - public IReadOnlyList HlslResourceInfo { get; } + IReadOnlyList HlslResourceInfo { get; } /// /// Gets the collection of items for the shader fields. /// - public IReadOnlyList FieldsInfo { get; } + IReadOnlyList FieldsInfo { get; } /// /// Gets the collection of methods to be used in the shader. /// - public IReadOnlyCollection MethodsInfo { get; } + IReadOnlyCollection MethodsInfo { get; } /// /// Gets the collection of constants to be declared in the shader. /// - public IReadOnlyDictionary ConstantsInfo { get; } + IReadOnlyDictionary ConstantsInfo { get; } /// /// Gets the collection of declared types for the shader. /// - public IReadOnlyCollection DeclaredTypes { get; } + IReadOnlyCollection DeclaredTypes { get; } + + /// + /// Gets the collection of discovered constants. + /// + IReadOnlyDictionary SharedBuffers { get; } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 12606154..af601973 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -104,6 +104,9 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyCollection DeclaredTypes => this.declaredTypes; + /// + public IReadOnlyDictionary SharedBuffers { get; private set; } + /// /// Loads and processes an input shadeer. /// @@ -131,6 +134,7 @@ namespace ComputeSharp.Shaders.Translation private void LoadMethodMetadata() { EntryPoint = Attribute.ExecuteMethod; + SharedBuffers = Attribute.SharedBuffers; this.declaredTypes.AddRange(Attribute.Types); this.methodsInfo.AddRange(Attribute.Methods); From bbc8832023b106588a89808cd8f4076eb3318b89 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 12 Jan 2021 18:09:55 +0100 Subject: [PATCH 37/61] Added thread group synchronization intrinsics --- src/ComputeSharp.Core/Intrinsics/Hlsl.cs | 46 ++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs index c58a3301..3d757637 100644 --- a/src/ComputeSharp.Core/Intrinsics/Hlsl.cs +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs @@ -153,6 +153,28 @@ namespace ComputeSharp [Pure] public static bool All(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(All)}({nameof(Float4)})"); + /// + /// Blocks execution of all threads in a group until all memory accesses have been completed. + /// + /// + /// A memory barrier guarantees that outstanding memory operations have completed. + /// Threads are synchronized at GroupSync barriers. + /// This may stall a thread or threads if memory operations are in progress. + /// + [PreserveMemberName] + public static void AllMemoryBarrier() => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(AllMemoryBarrier)}()"); + + /// + /// Blocks execution of all threads in a group until all memory accesses have been completed and all threads in the group have reached this call. + /// + /// + /// A memory barrier guarantees that outstanding memory operations have completed. + /// Threads are synchronized at GroupSync barriers. + /// This may stall a thread or threads if memory operations are in progress. + /// + [PreserveMemberName] + public static void AllMemoryBarrierWithGroupSync() => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(AllMemoryBarrierWithGroupSync)}()"); + /// /// Determines if any components of the specified value are non-zero. /// @@ -616,6 +638,18 @@ namespace ComputeSharp [Pure] public static Float3 Degrees(Float4 x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Degrees)}({nameof(Float4)})"); + /// + /// Blocks execution of all threads in a group until all device memory accesses have been completed. + /// + [PreserveMemberName] + public static void DeviceMemoryBarrier() => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(DeviceMemoryBarrier)}()"); + + /// + /// Blocks execution of all threads in a group until all device memory accesses have been completed and all threads in the group have reached this call. + /// + [PreserveMemberName] + public static void DeviceMemoryBarrierWithGroupSync() => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(DeviceMemoryBarrierWithGroupSync)}()"); + /// /// Returns a distance scalar between two values. /// @@ -870,6 +904,18 @@ namespace ComputeSharp [Pure] public static Float4 Frexp(Float4 x, out Float4 exp) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(Frexp)}({nameof(Float4)},{nameof(Float4)})"); + /// + /// Blocks execution of all threads in a group until all group shared accesses have been completed. + /// + [PreserveMemberName] + public static void GroupMemoryBarrier() => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(GroupMemoryBarrier)}()"); + + /// + /// Blocks execution of all threads in a group until all group shared accesses have been completed and all threads in the group have reached this call. + /// + [PreserveMemberName] + public static void GroupMemoryBarrierWithGroupSync() => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(GroupMemoryBarrierWithGroupSync)}()"); + /// /// Performs a guaranteed atomic add of a value to a destination. /// From c6aa194749b7372e446c4851425b2b22bfddb5b8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 13 Jan 2021 19:07:53 +0100 Subject: [PATCH 38/61] Switched ThreadIds to static type --- .../Interfaces/IComputeShader.cs | 3 +- src/ComputeSharp.Core/Primitives/ThreadIds.cs | 82 +++++++++---------- .../IComputeShaderSourceGenerator.cs | 9 +- .../Mappings/HlslKnownMembers.cs | 9 ++ .../Mappings/HlslKnownTypes.cs | 16 ++-- .../SyntaxRewriters/ExecuteMethodRewriter.cs | 32 ++------ 6 files changed, 73 insertions(+), 78 deletions(-) diff --git a/src/ComputeSharp.Core/Interfaces/IComputeShader.cs b/src/ComputeSharp.Core/Interfaces/IComputeShader.cs index 66f145dd..37f5396d 100644 --- a/src/ComputeSharp.Core/Interfaces/IComputeShader.cs +++ b/src/ComputeSharp.Core/Interfaces/IComputeShader.cs @@ -8,7 +8,6 @@ /// /// Executes the current compute shader. /// - /// The value with the current execution indices. - void Execute(ThreadIds ids); + void Execute(); } } diff --git a/src/ComputeSharp.Core/Primitives/ThreadIds.cs b/src/ComputeSharp.Core/Primitives/ThreadIds.cs index 69f58032..175d5f5a 100644 --- a/src/ComputeSharp.Core/Primitives/ThreadIds.cs +++ b/src/ComputeSharp.Core/Primitives/ThreadIds.cs @@ -3,203 +3,203 @@ namespace ComputeSharp { /// - /// A that indicates the ids of a given GPU thread running a compute shader. + /// A that indicates the ids of a given GPU thread running a compute shader. /// - public readonly ref struct ThreadIds + public static class ThreadIds { /// /// Gets the X id of the current thread. /// - public int X => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(X)}"); + public static int X => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(X)}"); /// /// Gets the Y id of the current thread. /// - public int Y => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(Y)}"); + public static int Y => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(Y)}"); /// /// Gets the Z id of the current thread. /// - public int Z => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(Z)}"); + public static int Z => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(Z)}"); /// /// Gets an value with the value for all components. /// - public Int2 XX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XX)}"); + public static Int2 XX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XX)}"); /// /// Gets or sets an value with the and values. /// - public Int2 XY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XY)}"); + public static Int2 XY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XY)}"); /// /// Gets or sets an value with the and values. /// - public Int2 XZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XZ)}"); + public static Int2 XZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XZ)}"); /// /// Gets or sets an value with the and values. /// - public Int2 YX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YX)}"); + public static Int2 YX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YX)}"); /// /// Gets an value with the value for all components. /// - public Int2 YY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YY)}"); + public static Int2 YY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YY)}"); /// /// Gets or sets an value with the and values. /// - public Int2 YZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YZ)}"); + public static Int2 YZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YZ)}"); /// /// Gets or sets an value with the and values. /// - public Int2 ZX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZX)}"); + public static Int2 ZX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZX)}"); /// /// Gets or sets an value with the and values. /// - public Int2 ZY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZY)}"); + public static Int2 ZY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZY)}"); /// /// Gets an value with the value for all components. /// - public Int2 ZZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZZ)}"); + public static Int2 ZZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZZ)}"); /// /// Gets an value with the value for all components. /// - public Int3 XXX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XXX)}"); + public static Int3 XXX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XXX)}"); /// /// Gets an value with the , and values. /// - public Int3 XXY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XXY)}"); + public static Int3 XXY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XXY)}"); /// /// Gets an value with the , and values. /// - public Int3 XXZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XXZ)}"); + public static Int3 XXZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XXZ)}"); /// /// Gets an value with the , and values. /// - public Int3 XYX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XYX)}"); + public static Int3 XYX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XYX)}"); /// /// Gets an value with the , and values. /// - public Int3 XYY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XYY)}"); + public static Int3 XYY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XYY)}"); /// /// Gets or sets an value with the , and values. /// - public Int3 XYZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XYZ)}"); + public static Int3 XYZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XYZ)}"); /// /// Gets an value with the , and values. /// - public Int3 XZX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XZX)}"); + public static Int3 XZX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XZX)}"); /// /// Gets or sets an value with the , and values. /// - public Int3 XZY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XZY)}"); + public static Int3 XZY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XZY)}"); /// /// Gets an value with the , and values. /// - public Int3 XZZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XZZ)}"); + public static Int3 XZZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(XZZ)}"); /// /// Gets an value with the , and values. /// - public Int3 YXX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YXX)}"); + public static Int3 YXX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YXX)}"); /// /// Gets an value with the , and values. /// - public Int3 YXY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YXY)}"); + public static Int3 YXY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YXY)}"); /// /// Gets or sets an value with the , and values. /// - public Int3 YXZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YXZ)}"); + public static Int3 YXZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YXZ)}"); /// /// Gets an value with the , and values. /// - public Int3 YYX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YYX)}"); + public static Int3 YYX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YYX)}"); /// /// Gets an value with the value for all components. /// - public Int3 YYY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YYY)}"); + public static Int3 YYY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YYY)}"); /// /// Gets an value with the , and values. /// - public Int3 YYZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YYZ)}"); + public static Int3 YYZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YYZ)}"); /// /// Gets or sets an value with the , and values. /// - public Int3 YZX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YZX)}"); + public static Int3 YZX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YZX)}"); /// /// Gets an value with the , and values. /// - public Int3 YZY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YZY)}"); + public static Int3 YZY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YZY)}"); /// /// Gets an value with the , and values. /// - public Int3 YZZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YZZ)}"); + public static Int3 YZZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(YZZ)}"); /// /// Gets an value with the , and values. /// - public Int3 ZXX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZXX)}"); + public static Int3 ZXX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZXX)}"); /// /// Gets or sets an value with the , and values. /// - public Int3 ZXY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZXY)}"); + public static Int3 ZXY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZXY)}"); /// /// Gets an value with the , and values. /// - public Int3 ZXZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZXZ)}"); + public static Int3 ZXZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZXZ)}"); /// /// Gets or sets an value with the , and values. /// - public Int3 ZYX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZYX)}"); + public static Int3 ZYX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZYX)}"); /// /// Gets an value with the , and values. /// - public Int3 ZYY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZYY)}"); + public static Int3 ZYY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZYY)}"); /// /// Gets an value with the , and values. /// - public Int3 ZYZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZYZ)}"); + public static Int3 ZYZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZYZ)}"); /// /// Gets an value with the , and values. /// - public Int3 ZZX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZZX)}"); + public static Int3 ZZX => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZZX)}"); /// /// Gets an value with the , and values. /// - public Int3 ZZY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZZY)}"); + public static Int3 ZZY => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZZY)}"); /// /// Gets an value with the value for all components. /// - public Int3 ZZZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZZZ)}"); + public static Int3 ZZZ => throw new InvalidExecutionContextException($"{nameof(ThreadIds)}.{nameof(ZZZ)}"); } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 93f2d6a7..7e5787bc 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -171,18 +171,15 @@ namespace ComputeSharp.SourceGenerators ShaderSourceRewriter shaderSourceRewriter = new(structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); // Rewrite the method syntax tree - var processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); // If the method is the shader entry point, do additional processing if (methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && methodDeclarationSymbol.ReturnsVoid && methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 1 && - methodDeclarationSymbol.Parameters[0].Type.ToDisplayString() == typeof(ThreadIds).FullName) + methodDeclarationSymbol.Parameters.Length == 0) { - var parameterName = methodDeclarationSymbol.Parameters[0].Name; - - processedMethod = new ExecuteMethodRewriter(parameterName).Visit(processedMethod)!; + processedMethod = new ExecuteMethodRewriter().Visit(processedMethod)!; entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index c2c58e37..ddd54ccd 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -190,6 +190,15 @@ namespace ComputeSharp.SourceGenerators.Mappings knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Property.Name.ToLower()}"); } + // Programmatically load mappings for the dispatch types + foreach (var item in + from type in HlslKnownTypes.HlslDispatchTypes + from property in type.GetProperties(BindingFlags.Static | BindingFlags.Public) + select (Type: type, Property: property)) + { + knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Type.Name}.{item.Property.Name.ToLower()}"); + } + return knownMembers; } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 04ed2673..b01f4e15 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -41,8 +41,7 @@ namespace ComputeSharp.SourceGenerators.Mappings [typeof(double).FullName] = "double", [typeof(Double2).FullName] = "double2", [typeof(Double3).FullName] = "double3", - [typeof(Double4).FullName] = "double4", - [typeof(ThreadIds).FullName] = "int3" + [typeof(Double4).FullName] = "double4" }; /// @@ -50,7 +49,6 @@ namespace ComputeSharp.SourceGenerators.Mappings /// public static IReadOnlyCollection HlslMappedVectorTypes { get; } = new[] { - typeof(ThreadIds), typeof(Bool2), typeof(Bool3), typeof(Bool4), typeof(Int2), typeof(Int3), typeof(Int4), typeof(UInt2), typeof(UInt3), typeof(UInt4), @@ -58,6 +56,14 @@ namespace ComputeSharp.SourceGenerators.Mappings typeof(Double2), typeof(Double3), typeof(Double4) }; + /// + /// Gets the known HLSL dispatch types. + /// + public static IReadOnlyCollection HlslDispatchTypes { get; } = new[] + { + typeof(ThreadIds) + }; + /// /// Checks whether or not a given type name matches a typed resource type. /// @@ -94,9 +100,7 @@ namespace ComputeSharp.SourceGenerators.Mappings /// Whether or not represents a typed resource type. public static bool IsScalarOrVectorType(string typeName) { - return - KnownTypes.ContainsKey(typeName) && - typeName != typeof(ThreadIds).FullName; + return KnownTypes.ContainsKey(typeName); } /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs index 63245d3b..70c4f77a 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs @@ -10,20 +10,6 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// internal sealed class ExecuteMethodRewriter : CSharpSyntaxRewriter { - /// - /// The identifier name for the input parameter. - /// - private readonly string threadIdsIdentifier; - - /// - /// Creates a new instance with the specified parameters. - /// - /// The identifier name for the input parameter. - public ExecuteMethodRewriter(string threadIdsIdentifier) - { - this.threadIdsIdentifier = threadIdsIdentifier; - } - /// public TNode? Visit(TNode? node) where TNode : SyntaxNode @@ -32,11 +18,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters } /// - public override SyntaxNode VisitParameter(ParameterSyntax node) + public override SyntaxNode? VisitParameterList(ParameterListSyntax node) { - var updatedNode = (ParameterSyntax)base.VisitParameter(node)!; + var updatedNode = (ParameterListSyntax)base.VisitParameterList(node)!; - return updatedNode.WithIdentifier(Identifier($"{updatedNode.Identifier.Text} : SV_DispatchThreadId")); + return updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID"))); } /// @@ -48,9 +34,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters // check to ensure that invocation outside of the requested range are discarded. // The following snippet creates this prologue before the user provided body: // - // if (ids.X < __x && - // ids.Y < __y && - // ids.Z < __z) + // if (ThreadIds.x < __x && + // ThreadIds.y < __y && + // ThreadIds.z < __z) // { // // } @@ -60,19 +46,19 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters BinaryExpression(SyntaxKind.LessThanExpression, MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(this.threadIdsIdentifier), + IdentifierName(nameof(ThreadIds)), IdentifierName("x")), IdentifierName("__x")), BinaryExpression(SyntaxKind.LessThanExpression, MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(this.threadIdsIdentifier), + IdentifierName(nameof(ThreadIds)), IdentifierName("y")), IdentifierName("__y"))), BinaryExpression(SyntaxKind.LessThanExpression, MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(this.threadIdsIdentifier), + IdentifierName(nameof(ThreadIds)), IdentifierName("z")), IdentifierName("__z"))); From 126f40e1c5571b6d9e86ccb3495a8681d460b24c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 13 Jan 2021 19:10:04 +0100 Subject: [PATCH 39/61] Fixed sample files --- .../Blas/BlasHelpers.cs | 8 ++--- .../HlslBokehBlurProcessor{TPixel}.cs | 30 +++++++++---------- .../HlslGaussianBlurProcessor{TPixel}.cs | 16 +++++----- samples/ComputeSharp.Sample.Shared/Program.cs | 4 +-- 4 files changed, 29 insertions(+), 29 deletions(-) diff --git a/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs index 687f86bb..d1e3df0a 100644 --- a/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs +++ b/samples/ComputeSharp.Benchmark/Blas/BlasHelpers.cs @@ -92,17 +92,17 @@ namespace ComputeSharp.Benchmark.Blas public readonly ReadWriteBuffer y; /// - public void Execute(ThreadIds ids) + public void Execute() { - int x_offset = ids.X * n * p + ids.Y * m; + int x_offset = ThreadIds.X * n * p + ThreadIds.Y * m; float result = 0f; for (int k = 0; k < m; k++) { - result += x[x_offset + k] * w[k * p + ids.Z]; + result += x[x_offset + k] * w[k * p + ThreadIds.Z]; } - y[ids.X * n * p + ids.Y * p + ids.Z] = result + b[ids.Z]; + y[ThreadIds.X * n * p + ThreadIds.Y * p + ThreadIds.Z] = result + b[ThreadIds.Z]; } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index 5ac36156..9ae94951 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -302,7 +302,7 @@ namespace ComputeSharp.BokehBlur.Processors public ReadOnlyBuffer kernel; /// - public void Execute(ThreadIds ids) + public void Execute() { Vector4 real = Vector4.Zero; Vector4 imaginary = Vector4.Zero; @@ -313,8 +313,8 @@ namespace ComputeSharp.BokehBlur.Processors for (int i = 0; i < kernelLength; i++) { - int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(ids.X, 0, maxX); + int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX); Vector4 color = source[offsetX, offsetY]; Complex64 factors = kernel[i]; @@ -322,8 +322,8 @@ namespace ComputeSharp.BokehBlur.Processors imaginary += factors.Imaginary * color; } - reals[ids.XY] = real; - imaginaries[ids.XY] = imaginary; + reals[ThreadIds.XY] = real; + imaginaries[ThreadIds.XY] = imaginary; } } @@ -342,7 +342,7 @@ namespace ComputeSharp.BokehBlur.Processors public ReadOnlyBuffer kernel; /// - public void Execute(ThreadIds ids) + public void Execute() { Vector4 real = Vector4.Zero; Vector4 imaginary = Vector4.Zero; @@ -350,11 +350,11 @@ namespace ComputeSharp.BokehBlur.Processors int maxX = target.Width; int kernelLength = kernel.Length; int radiusX = kernelLength >> 1; - int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); + int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY); for (int i = 0; i < kernelLength; i++) { - int offsetX = Hlsl.Clamp(ids.X + i - radiusX, 0, maxX); + int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX); Vector4 sourceReal = reals[offsetX, offsetY]; Vector4 sourceImaginary = imaginaries[offsetX, offsetY]; Complex64 factors = kernel[i]; @@ -363,7 +363,7 @@ namespace ComputeSharp.BokehBlur.Processors imaginary += factors.Real * sourceImaginary + factors.Imaginary * sourceReal; } - target[ids.XY] += real * z + imaginary * w; + target[ThreadIds.XY] += real * z + imaginary * w; } } @@ -376,17 +376,17 @@ namespace ComputeSharp.BokehBlur.Processors public readonly IReadWriteTexture2D source; /// - public void Execute(ThreadIds ids) + public void Execute() { int width = source.Width; for (int i = 0; i < width; i++) { - Float4 v = source[i, ids.X]; + Float4 v = source[i, ThreadIds.X]; v.XYZ = v.XYZ * v.XYZ * v.XYZ; - source[i, ids.X] = v; + source[i, ThreadIds.X] = v; } } } @@ -401,18 +401,18 @@ namespace ComputeSharp.BokehBlur.Processors public readonly IReadWriteTexture2D target; /// - public void Execute(ThreadIds ids) + public void Execute() { int width = source.Width; for (int i = 0; i < width; i++) { - Float4 v = source[i, ids.X]; + Float4 v = source[i, ThreadIds.X]; v.XYZ = Hlsl.Clamp(v.XYZ, 0, float.MaxValue); v.XYZ = Hlsl.Pow(v.XYZ, 1 / 3f); - target[i, ids.X] = v; + target[i, ThreadIds.X] = v; } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 0aad185e..3126f2d4 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -115,7 +115,7 @@ namespace ComputeSharp.BokehBlur.Processors public readonly ReadOnlyBuffer kernel; /// - public void Execute(ThreadIds ids) + public void Execute() { Vector4 result = Vector4.Zero; int maxY = source.Height - 1; @@ -125,14 +125,14 @@ namespace ComputeSharp.BokehBlur.Processors for (int i = 0; i < kernelLength; i++) { - int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(ids.X, 0, maxX); + int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX); Vector4 color = source[offsetX, offsetY]; result += kernel[i] * color; } - target[ids.XY] = result; + target[ThreadIds.XY] = result; } } @@ -147,24 +147,24 @@ namespace ComputeSharp.BokehBlur.Processors public readonly ReadOnlyBuffer kernel; /// - public void Execute(ThreadIds ids) + public void Execute() { Vector4 result = Vector4.Zero; int maxY = source.Height - 1; int maxX = source.Width - 1; int kernelLength = kernel.Length; int radiusX = kernelLength >> 1; - int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); + int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY); for (int i = 0; i < kernelLength; i++) { - int offsetX = Hlsl.Clamp(ids.X + i - radiusX, 0, maxX); + int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX); Vector4 color = source[offsetX, offsetY]; result += kernel[i] * color; } - target[ids.XY] = result; + target[ThreadIds.XY] = result; } } } diff --git a/samples/ComputeSharp.Sample.Shared/Program.cs b/samples/ComputeSharp.Sample.Shared/Program.cs index b56d467d..e20ef49d 100644 --- a/samples/ComputeSharp.Sample.Shared/Program.cs +++ b/samples/ComputeSharp.Sample.Shared/Program.cs @@ -47,9 +47,9 @@ namespace ComputeSharp.Sample public readonly ReadWriteBuffer buffer; /// - public void Execute(ThreadIds ids) + public void Execute() { - buffer[ids.X] *= 2; + buffer[ThreadIds.X] *= 2; } } From 437d4a0688becd5ad1c9db18e568786743410846 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 13 Jan 2021 19:30:59 +0100 Subject: [PATCH 40/61] Added GroupIds class --- src/ComputeSharp.Core/Dispatch/GroupIds.cs | 210 ++++++++++++++++++ .../{Primitives => Dispatch}/ThreadIds.cs | 0 .../ComputeSharp.SourceGenerators.csproj | 3 +- .../Mappings/HlslKnownMembers.cs | 14 +- .../Mappings/HlslKnownTypes.cs | 2 +- .../SyntaxRewriters/ExecuteMethodRewriter.cs | 5 +- 6 files changed, 230 insertions(+), 4 deletions(-) create mode 100644 src/ComputeSharp.Core/Dispatch/GroupIds.cs rename src/ComputeSharp.Core/{Primitives => Dispatch}/ThreadIds.cs (100%) diff --git a/src/ComputeSharp.Core/Dispatch/GroupIds.cs b/src/ComputeSharp.Core/Dispatch/GroupIds.cs new file mode 100644 index 00000000..c871eb06 --- /dev/null +++ b/src/ComputeSharp.Core/Dispatch/GroupIds.cs @@ -0,0 +1,210 @@ +using ComputeSharp.Exceptions; + +namespace ComputeSharp +{ + /// + /// A that indicates the ids of a given GPU thread running a compute shader within aa dispatch group. + /// + public static class GroupIds + { + /// + /// Gets the flattened index of the current thread with respect to the dispatch group. + /// + public static int Index => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(Index)}"); + + /// + /// Gets the X id of the current thread with respect to the dispatch group. + /// + public static int X => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(X)}"); + + /// + /// Gets the Y id of the current thread with respect to the dispatch group. + /// + public static int Y => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(Y)}"); + + /// + /// Gets the Z id of the current thread with respect to the dispatch group. + /// + public static int Z => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(Z)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int2 XX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XX)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 XY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XY)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 XZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XZ)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 YX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YX)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int2 YY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YY)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 YZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YZ)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 ZX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZX)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 ZY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZY)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int2 ZZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZZ)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int3 XXX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XXX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XXY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XXY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XXZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XXZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XYX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XYX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XYY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XYY)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 XYZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XYZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XZX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XZX)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 XZY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XZY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XZZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(XZZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YXX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YXX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YXY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YXY)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 YXZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YXZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YYX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YYX)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int3 YYY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YYY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YYZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YYZ)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 YZX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YZX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YZY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YZY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YZZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(YZZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZXX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZXX)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 ZXY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZXY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZXZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZXZ)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 ZYX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZYX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZYY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZYY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZYZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZYZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZZX => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZZX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZZY => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZZY)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int3 ZZZ => throw new InvalidExecutionContextException($"{nameof(GroupIds)}.{nameof(ZZZ)}"); + } +} diff --git a/src/ComputeSharp.Core/Primitives/ThreadIds.cs b/src/ComputeSharp.Core/Dispatch/ThreadIds.cs similarity index 100% rename from src/ComputeSharp.Core/Primitives/ThreadIds.cs rename to src/ComputeSharp.Core/Dispatch/ThreadIds.cs diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 91506957..d007ccd6 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -18,6 +18,8 @@ + + @@ -38,7 +40,6 @@ - diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index ddd54ccd..ccf68a33 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -190,13 +190,25 @@ namespace ComputeSharp.SourceGenerators.Mappings knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Property.Name.ToLower()}"); } + // Store GroupIds.Index for a quicker comparison afterwards + PropertyInfo groupindexProperty = typeof(GroupIds).GetProperty(nameof(GroupIds.Index), BindingFlags.Static | BindingFlags.Public); + // Programmatically load mappings for the dispatch types foreach (var item in from type in HlslKnownTypes.HlslDispatchTypes from property in type.GetProperties(BindingFlags.Static | BindingFlags.Public) select (Type: type, Property: property)) { - knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Type.Name}.{item.Property.Name.ToLower()}"); + if (item.Property == groupindexProperty) + { + // The thread group index is a standalone parameter, so if this property is used, we + // just map the access directly to that implicit and hidden parameter name instead. + knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"__{nameof(GroupIds)}__get_Index"); + } + else + { + knownMembers.Add($"{item.Type.FullName}{Type.Delimiter}{item.Property.Name}", $"{item.Type.Name}.{item.Property.Name.ToLower()}"); + } } return knownMembers; diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index b01f4e15..041a3bb0 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -61,7 +61,7 @@ namespace ComputeSharp.SourceGenerators.Mappings /// public static IReadOnlyCollection HlslDispatchTypes { get; } = new[] { - typeof(ThreadIds) + typeof(ThreadIds), typeof(GroupIds) }; /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs index 70c4f77a..58908f46 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs @@ -22,7 +22,10 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (ParameterListSyntax)base.VisitParameterList(node)!; - return updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID"))); + return updatedNode.AddParameters( + Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID")), + Parameter(Identifier($"uint3 {nameof(GroupIds)} : SV_GroupThreadID")), + Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex"))); } /// From 073cfa64ab0a378e3a2ae5bb57e7e51875b69e8b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 13 Jan 2021 19:35:04 +0100 Subject: [PATCH 41/61] Added WarpIds type --- src/ComputeSharp.Core/Dispatch/WarpIds.cs | 205 ++++++++++++++++++ .../ComputeSharp.SourceGenerators.csproj | 1 + .../Mappings/HlslKnownTypes.cs | 4 +- .../SyntaxRewriters/ExecuteMethodRewriter.cs | 3 +- .../SyntaxRewriters/ShaderSourceRewriter.cs | 1 - 5 files changed, 211 insertions(+), 3 deletions(-) create mode 100644 src/ComputeSharp.Core/Dispatch/WarpIds.cs diff --git a/src/ComputeSharp.Core/Dispatch/WarpIds.cs b/src/ComputeSharp.Core/Dispatch/WarpIds.cs new file mode 100644 index 00000000..2c02cdbb --- /dev/null +++ b/src/ComputeSharp.Core/Dispatch/WarpIds.cs @@ -0,0 +1,205 @@ +using ComputeSharp.Exceptions; + +namespace ComputeSharp +{ + /// + /// A that indicates the ids of a given dispatch warp (a group of threads). + /// + public static class WarpIds + { + /// + /// Gets the X id of the current thread with respect to the dispatch group. + /// + public static int X => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(X)}"); + + /// + /// Gets the Y id of the current thread with respect to the dispatch group. + /// + public static int Y => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(Y)}"); + + /// + /// Gets the Z id of the current thread with respect to the dispatch group. + /// + public static int Z => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(Z)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int2 XX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XX)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 XY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XY)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 XZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XZ)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 YX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YX)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int2 YY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YY)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 YZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YZ)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 ZX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZX)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 ZY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZY)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int2 ZZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZZ)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int3 XXX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XXX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XXY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XXY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XXZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XXZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XYX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XYX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XYY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XYY)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 XYZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XYZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XZX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XZX)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 XZY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XZY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XZZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(XZZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YXX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YXX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YXY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YXY)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 YXZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YXZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YYX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YYX)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int3 YYY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YYY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YYZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YYZ)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 YZX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YZX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YZY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YZY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YZZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(YZZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZXX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZXX)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 ZXY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZXY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZXZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZXZ)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 ZYX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZYX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZYY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZYY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZYZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZYZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZZX => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZZX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZZY => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZZY)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int3 ZZZ => throw new InvalidExecutionContextException($"{nameof(WarpIds)}.{nameof(ZZZ)}"); + } +} diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index d007ccd6..e40e29f9 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -20,6 +20,7 @@ + diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 041a3bb0..c6716afd 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -61,7 +61,9 @@ namespace ComputeSharp.SourceGenerators.Mappings /// public static IReadOnlyCollection HlslDispatchTypes { get; } = new[] { - typeof(ThreadIds), typeof(GroupIds) + typeof(ThreadIds), + typeof(GroupIds), + typeof(WarpIds) }; /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs index 58908f46..bdfce306 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs @@ -25,7 +25,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode.AddParameters( Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID")), Parameter(Identifier($"uint3 {nameof(GroupIds)} : SV_GroupThreadID")), - Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex"))); + Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex")), + Parameter(Identifier($"uint3 {nameof(WarpIds)} : SV_GroupID"))); } /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 80112469..fe593c2a 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; From 602ca37516ef0fca497df225c519a6359e59ea03 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 13 Jan 2021 20:05:09 +0100 Subject: [PATCH 42/61] Optimized shader dispatch parameter declarations --- .../IComputeShaderSourceGenerator.cs | 2 +- .../SyntaxRewriters/ExecuteMethodRewriter.cs | 37 ++++++++++++++++--- .../SyntaxRewriters/ShaderSourceRewriter.cs | 30 ++++++++++++++- 3 files changed, 61 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 7e5787bc..05ec04c3 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -179,7 +179,7 @@ namespace ComputeSharp.SourceGenerators methodDeclarationSymbol.TypeParameters.Length == 0 && methodDeclarationSymbol.Parameters.Length == 0) { - processedMethod = new ExecuteMethodRewriter().Visit(processedMethod)!; + processedMethod = new ExecuteMethodRewriter(shaderSourceRewriter).Visit(processedMethod)!; entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs index bdfce306..ad67c0b3 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs @@ -10,6 +10,20 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// internal sealed class ExecuteMethodRewriter : CSharpSyntaxRewriter { + /// + /// The instance used to process the input tree. + /// + private readonly ShaderSourceRewriter shaderSourceRewriter; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance used to process the input tree. + public ExecuteMethodRewriter(ShaderSourceRewriter shaderSourceRewriter) + { + this.shaderSourceRewriter = shaderSourceRewriter; + } + /// public TNode? Visit(TNode? node) where TNode : SyntaxNode @@ -22,11 +36,24 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { var updatedNode = (ParameterListSyntax)base.VisitParameterList(node)!; - return updatedNode.AddParameters( - Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID")), - Parameter(Identifier($"uint3 {nameof(GroupIds)} : SV_GroupThreadID")), - Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex")), - Parameter(Identifier($"uint3 {nameof(WarpIds)} : SV_GroupID"))); + updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID"))); + + if (this.shaderSourceRewriter.IsGroupIdsUsed) + { + updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GroupIds)} : SV_GroupThreadID"))); + } + + if (this.shaderSourceRewriter.IsGroupIdsIndexUsed) + { + updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex"))); + } + + if (this.shaderSourceRewriter.IsWarpIdsUsed) + { + updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(WarpIds)} : SV_GroupID"))); + } + + return updatedNode; } /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index fe593c2a..289f14ac 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -106,6 +106,21 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// public IReadOnlyDictionary LocalFunctions => this.localFunctions; + /// + /// Gets whether or not the shader uses at least once (except ). + /// + public bool IsGroupIdsUsed { get; private set; } + + /// + /// Gets whether or not the shader uses at least once. + /// + public bool IsWarpIdsUsed { get; set; } + /// public MethodDeclarationSyntax? Visit(MethodDeclarationSyntax? node) { @@ -307,11 +322,22 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters // to see if the member should be rewritten for HLSL compliance, and rewrite if needed. if (HlslKnownMembers.TryGetMappedName(operation.Member.ToDisplayString(), out string? mapping)) { + // Mark which dispatch properties have been used, to optimize the declaration afterwards + if (operation.Member.IsStatic) + { + string typeName = operation.Member.ContainingType.GetFullMetadataName(); + + if (mapping == $"__{nameof(GroupIds)}__get_Index") IsGroupIdsIndexUsed = true; + else if (typeName == typeof(GroupIds).FullName) IsGroupIdsUsed = true; + else if (typeName == typeof(WarpIds).FullName) IsWarpIdsUsed = true; + } + // Static and instance members are handled differently, with static members being // converted into a literal expression, and instance getting an updated identifier. - // For instance, consider these two cases: + // For instance, consider these three cases: // - Vector3.One (static) => float3(1.0f, 1.0f, 1.0f) - // - ThredIds.X (instance) => [arg].x + // - ThreadIds.X (custom) => ThreadIds.x + // - uint3.X (instance) => [arg].x return operation.Member.IsStatic switch { true => ParseExpression(mapping!), From 6338f2511eb0b5e98898a977f0a9112fff997cf8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 13 Jan 2021 20:09:52 +0100 Subject: [PATCH 43/61] Updated unit tests with new code changes --- .../ShaderHashCodeTests.cs | 4 +- tests/ComputeSharp.Tests/BufferTests.cs | 12 ++--- .../ComputeSharp.Tests/InitializationTests.cs | 4 +- .../Texture2DTests.Pixels.g.cs | 48 +++++++++---------- .../Texture2DTests.Pixels.tt | 4 +- tests/ComputeSharp.Tests/Texture2DTests.cs | 8 ++-- .../Texture3DTests.Pixels.g.cs | 48 +++++++++---------- .../Texture3DTests.Pixels.tt | 4 +- tests/ComputeSharp.Tests/Texture3DTests.cs | 8 ++-- 9 files changed, 70 insertions(+), 70 deletions(-) diff --git a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs index 498695ea..dfe219e2 100644 --- a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs +++ b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs @@ -13,7 +13,7 @@ namespace ComputeSharp.Tests.Internals public float A; public ReadWriteBuffer B; - public void Execute(ThreadIds ids) + public void Execute() { B[0] = A; } @@ -46,7 +46,7 @@ namespace ComputeSharp.Tests.Internals public ReadWriteBuffer B; public Func F; - public void Execute(ThreadIds ids) + public void Execute() { B[0] = F(A); } diff --git a/tests/ComputeSharp.Tests/BufferTests.cs b/tests/ComputeSharp.Tests/BufferTests.cs index 55e49552..e8dcc321 100644 --- a/tests/ComputeSharp.Tests/BufferTests.cs +++ b/tests/ComputeSharp.Tests/BufferTests.cs @@ -223,9 +223,9 @@ namespace ComputeSharp.Tests public readonly ConstantBuffer source; public readonly ReadWriteBuffer destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.X] = source[ids.X]; + destination[ThreadIds.X] = source[ThreadIds.X]; } } @@ -250,9 +250,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyBuffer source; public readonly ReadWriteBuffer destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.X] = source[ids.X]; + destination[ThreadIds.X] = source[ThreadIds.X]; } } @@ -277,9 +277,9 @@ namespace ComputeSharp.Tests public readonly ReadWriteBuffer source; public readonly ReadWriteBuffer destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.X] = source[ids.X]; + destination[ThreadIds.X] = source[ThreadIds.X]; } } } diff --git a/tests/ComputeSharp.Tests/InitializationTests.cs b/tests/ComputeSharp.Tests/InitializationTests.cs index 661896e0..4e7e8589 100644 --- a/tests/ComputeSharp.Tests/InitializationTests.cs +++ b/tests/ComputeSharp.Tests/InitializationTests.cs @@ -86,9 +86,9 @@ namespace ComputeSharp.Tests { public readonly ReadWriteBuffer buffer; - public void Execute(ThreadIds ids) + public void Execute() { - buffer[ids.X] = ids.X; + buffer[ThreadIds.X] = ThreadIds.X; } } } diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs index 08039596..f914c901 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.g.cs @@ -113,9 +113,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -125,9 +125,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -137,9 +137,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -149,9 +149,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -161,9 +161,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -173,9 +173,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -185,9 +185,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -197,9 +197,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -209,9 +209,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -221,9 +221,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -233,9 +233,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } @@ -245,9 +245,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } } diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt index 33775291..991ce833 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.tt @@ -69,9 +69,9 @@ foreach (var (t, tPixel) in EnumerateTypes()) public readonly ReadOnlyTexture2D<<#=t#>, <#=tPixel#>> source; public readonly ReadWriteTexture2D<<#=t#>, <#=tPixel#>> destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2; + destination[ThreadIds.XY] = (source[ThreadIds.XY] + destination[ThreadIds.XY]) / 2; } } <# diff --git a/tests/ComputeSharp.Tests/Texture2DTests.cs b/tests/ComputeSharp.Tests/Texture2DTests.cs index 4a6806e8..77991cfe 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.cs @@ -159,9 +159,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture2D source; public readonly ReadWriteBuffer destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.Y * 32 + ids.X] = source[ids.XY]; + destination[ThreadIds.Y * 32 + ThreadIds.X] = source[ThreadIds.XY]; } } @@ -188,9 +188,9 @@ namespace ComputeSharp.Tests public readonly ReadWriteTexture2D source; public readonly ReadWriteTexture2D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XY] = source[ids.XY]; + destination[ThreadIds.XY] = source[ThreadIds.XY]; } } } diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs index 3c1e4955..debd29cf 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.g.cs @@ -113,9 +113,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -125,9 +125,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -137,9 +137,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -149,9 +149,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -161,9 +161,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -173,9 +173,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -185,9 +185,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -197,9 +197,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -209,9 +209,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -221,9 +221,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -233,9 +233,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } @@ -245,9 +245,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } } diff --git a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt index d72edd3c..57be04b8 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt +++ b/tests/ComputeSharp.Tests/Texture3DTests.Pixels.tt @@ -69,9 +69,9 @@ foreach (var (t, tPixel) in EnumerateTypes()) public readonly ReadOnlyTexture3D<<#=t#>, <#=tPixel#>> source; public readonly ReadWriteTexture3D<<#=t#>, <#=tPixel#>> destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2; + destination[ThreadIds.XYZ] = (source[ThreadIds.XYZ] + destination[ThreadIds.XYZ]) / 2; } } <# diff --git a/tests/ComputeSharp.Tests/Texture3DTests.cs b/tests/ComputeSharp.Tests/Texture3DTests.cs index d69d4335..b2adb7e0 100644 --- a/tests/ComputeSharp.Tests/Texture3DTests.cs +++ b/tests/ComputeSharp.Tests/Texture3DTests.cs @@ -193,9 +193,9 @@ namespace ComputeSharp.Tests public readonly ReadOnlyTexture3D source; public readonly ReadWriteBuffer destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.Z * 32 * 32 + ids.Y * 32 + ids.X] = source[ids.XYZ]; + destination[ThreadIds.Z * 32 * 32 + ThreadIds.Y * 32 + ThreadIds.X] = source[ThreadIds.XYZ]; } } @@ -222,9 +222,9 @@ namespace ComputeSharp.Tests public readonly ReadWriteTexture3D source; public readonly ReadWriteTexture3D destination; - public void Execute(ThreadIds ids) + public void Execute() { - destination[ids.XYZ] = source[ids.XYZ]; + destination[ThreadIds.XYZ] = source[ThreadIds.XYZ]; } } } From b340dc633d31a2ea383726013e2906a7d1e92fb3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Jan 2021 14:42:48 +0100 Subject: [PATCH 44/61] Fixed some XML docs --- .../__Internals/ShaderMethodSourceAttribute.cs | 6 +++--- src/ComputeSharp.Core/PixelTypes/Rg16.cs | 4 ++-- src/ComputeSharp.Core/PixelTypes/Rg32.cs | 4 ++-- src/ComputeSharp.Core/Primitives/Float/Float3.cs | 4 ++-- src/ComputeSharp.Core/Primitives/Float/Float4.cs | 4 ++-- .../Commands/CommandList.cs | 3 ++- .../Interop/ID3D12DescriptorHandleAllocator.cs | 4 ++-- .../Commands/PipelineData.cs | 7 +++---- .../Extensions/ID3D12DeviceExtensions.cs | 1 + src/ComputeSharp.Graphics/GraphicsDevice.cs | 10 +++++----- src/ComputeSharp.Graphics/GraphicsDeviceInfo.cs | 2 +- .../Helpers/MemoryHelper.cs | 2 -- .../Interfaces/IReadOnlyTexture3D{TPixel}.cs | 2 +- .../Resources/ReadOnlyTexture3D{T}.cs | 2 +- .../Renderer/HlslShaderRenderer.cs | 4 ++-- .../Renderer/Models/HlslResourceInfo.cs | 1 + .../Translation/ShaderLoader{T}.cs | 4 ++-- .../Extensions/Buffers/BufferExtensions.cs | 2 +- .../Extensions/Buffers/Texture2DExtensions.cs | 6 +++--- .../Extensions/Buffers/Texture3DExtensions.cs | 10 +++++----- .../Extensions/GraphicsDeviceExtensions.cs | 16 ++++++++-------- 21 files changed, 49 insertions(+), 49 deletions(-) diff --git a/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs index 97104dfd..8d0bbce3 100644 --- a/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -79,10 +79,10 @@ namespace ComputeSharp.__Internals } /// - /// Gets the associated instance for a specified type. + /// Gets the associated instance for a specified delegate. /// - /// The shader type to get the attribute for. - /// The associated instance for type . + /// The input instance to get info for. + /// The associated instance for the given delegate. [Pure] internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function) { diff --git a/src/ComputeSharp.Core/PixelTypes/Rg16.cs b/src/ComputeSharp.Core/PixelTypes/Rg16.cs index dd3b6ce9..5da5ce6d 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rg16.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rg16.cs @@ -30,8 +30,8 @@ namespace ComputeSharp /// /// Initializes a new instance of the struct. /// - /// The x-component - /// The y-component + /// The red component. + /// The green component. public Rg16(byte r, byte g) { R = r; diff --git a/src/ComputeSharp.Core/PixelTypes/Rg32.cs b/src/ComputeSharp.Core/PixelTypes/Rg32.cs index 10f5a7c1..8d0e39ba 100644 --- a/src/ComputeSharp.Core/PixelTypes/Rg32.cs +++ b/src/ComputeSharp.Core/PixelTypes/Rg32.cs @@ -30,8 +30,8 @@ namespace ComputeSharp /// /// Initializes a new instance of the struct. /// - /// The x-component - /// The y-component + /// The red component. + /// The green component. public Rg32(ushort r, ushort g) { R = r; diff --git a/src/ComputeSharp.Core/Primitives/Float/Float3.cs b/src/ComputeSharp.Core/Primitives/Float/Float3.cs index eeeea995..4c1893c6 100644 --- a/src/ComputeSharp.Core/Primitives/Float/Float3.cs +++ b/src/ComputeSharp.Core/Primitives/Float/Float3.cs @@ -567,13 +567,13 @@ namespace ComputeSharp /// /// Casts a value to a one. /// - /// The input value to cast. + /// The input value to cast. public static unsafe implicit operator Vector3(Float3 xyz) => *(Vector3*)&xyz; /// /// Casts a value to a one. /// - /// The input value to cast. + /// The input value to cast. public static unsafe implicit operator Float3(Vector3 xyz) => *(Float3*)&xyz; /// diff --git a/src/ComputeSharp.Core/Primitives/Float/Float4.cs b/src/ComputeSharp.Core/Primitives/Float/Float4.cs index 5b7904a6..f6192624 100644 --- a/src/ComputeSharp.Core/Primitives/Float/Float4.cs +++ b/src/ComputeSharp.Core/Primitives/Float/Float4.cs @@ -3972,13 +3972,13 @@ namespace ComputeSharp /// /// Casts a value to a one. /// - /// The input value to cast. + /// The input value to cast. public static unsafe implicit operator Vector4(Float4 xyzw) => *(Vector4*)&xyzw; /// /// Casts a value to a one. /// - /// The input value to cast. + /// The input value to cast. public static unsafe implicit operator Float4(Vector4 xyzw) => *(Float4*)&xyzw; /// diff --git a/src/ComputeSharp.Graphics/Commands/CommandList.cs b/src/ComputeSharp.Graphics/Commands/CommandList.cs index f75edc4f..58bd809a 100644 --- a/src/ComputeSharp.Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp.Graphics/Commands/CommandList.cs @@ -120,6 +120,7 @@ namespace ComputeSharp.Graphics.Commands /// The source (a texture) to read from. /// The horizontal offset in the destination texture. /// The vertical offset in the destination texture. + /// The depthwise offset in the destination texture. /// The width of the memory area to read from. /// The height of the memory area to read from. /// The depth of the memory area to read from. @@ -166,7 +167,7 @@ namespace ComputeSharp.Graphics.Commands /// /// Sets a given object ready to be executed. /// - /// The input to setup. + /// The input to setup. public readonly void SetPipelineData(PipelineData pipelineData) { this.d3D12GraphicsCommandList.Get()->SetComputeRootSignature(pipelineData.D3D12RootSignature); diff --git a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs index f41b8007..5b869e48 100644 --- a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs +++ b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs @@ -79,7 +79,7 @@ namespace ComputeSharp.Graphics.Commands.Interop /// Rents a new CPU and GPU handle pair to use in a memory buffer. /// /// The resulting value. - /// The resulting value. + /// The resulting value. public void Rent( out D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, out D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle) @@ -106,7 +106,7 @@ namespace ComputeSharp.Graphics.Commands.Interop /// Returns a CPU and GPU handle pair for later use. /// /// The returned value. - /// The returned value. + /// The returned value. public void Return( D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle) diff --git a/src/ComputeSharp.Graphics/Commands/PipelineData.cs b/src/ComputeSharp.Graphics/Commands/PipelineData.cs index d25c1fe0..be6ad0eb 100644 --- a/src/ComputeSharp.Graphics/Commands/PipelineData.cs +++ b/src/ComputeSharp.Graphics/Commands/PipelineData.cs @@ -19,11 +19,10 @@ namespace ComputeSharp.Graphics.Commands private ComPtr d3D12PipelineState; /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// - /// The to use. - /// The value for the current shader. - /// The bytecode for the compute shader to run. + /// The value for the current shader. + /// The compiled pipeline state to reuse for the current shader. public PipelineData(ComPtr d3D12RootSignature, ComPtr d3D12PipelineState) { this.d3D12RootSignature = d3D12RootSignature; diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs index 6d177f7c..971f3db3 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs @@ -423,6 +423,7 @@ namespace ComputeSharp.Graphics.Extensions /// /// The target to use to create the command list. /// The type of command list to create. + /// The command allocator to use to create the command list. /// A pointer to the newly allocated instance. /// Thrown when the creation of the command list fails. public static ComPtr CreateCommandList( diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index 824becaf..600ded21 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -152,11 +152,11 @@ namespace ComputeSharp internal bool IsCacheCoherentUMA { get; } /// - /// Checks whether the current device supports the creation of + /// Checks whether the current device supports the creation of /// resources for a specified type . /// /// The type of values to check support for. - /// Whether instances can be created by the current device. + /// Whether instances can be created by the current device. [Pure] public bool IsTexture2DSupportedForType() where T : unmanaged @@ -167,11 +167,11 @@ namespace ComputeSharp } /// - /// Checks whether the current device supports the creation of + /// Checks whether the current device supports the creation of /// resources for a specified type . /// /// The type of values to check support for. - /// Whether instances can be created by the current device. + /// Whether instances can be created by the current device. [Pure] public bool IsTexture3DSupportedForType() where T : unmanaged @@ -181,7 +181,7 @@ namespace ComputeSharp return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D); } - /// + /// internal void RentShaderResourceViewDescriptorHandles( out D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, out D3D12_GPU_DESCRIPTOR_HANDLE d3D12GpuDescriptorHandle) diff --git a/src/ComputeSharp.Graphics/GraphicsDeviceInfo.cs b/src/ComputeSharp.Graphics/GraphicsDeviceInfo.cs index 71a5c06a..5c4b7f48 100644 --- a/src/ComputeSharp.Graphics/GraphicsDeviceInfo.cs +++ b/src/ComputeSharp.Graphics/GraphicsDeviceInfo.cs @@ -11,7 +11,7 @@ namespace ComputeSharp /// /// Creates a new instance with the specified parameters. /// - /// The available info for the associate device. + /// The available info for the associated device. internal unsafe GraphicsDeviceInfo(DXGI_ADAPTER_DESC1* dxgiDescription1) { Luid = Luid.FromLUID(dxgiDescription1->AdapterLuid); diff --git a/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs b/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs index 4842f413..4a30f2b8 100644 --- a/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/MemoryHelper.cs @@ -174,7 +174,6 @@ namespace ComputeSharp.Graphics.Helpers /// Copies the content of a source memory area to the 3D area pointed by an input pointer. /// The destination memory area has padding in each row, while the source does not. /// - /// The type of values to read. /// The source memory area to read from. /// The pointer that indicates the 3D memory area to write to. /// The height of the 3D memory area to write to. @@ -219,7 +218,6 @@ namespace ComputeSharp.Graphics.Helpers /// Copies a 3D memory area pointed by a pointer value to a target memory area. /// The source memory area has padding in each row, while the target does not. /// - /// The type of values to read. /// The pointer that indicates the memory area to read from. /// The height of the 3D memory area to read. /// The depth of the 3D memory area to read. diff --git a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs index df101b43..74725b0a 100644 --- a/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs @@ -28,7 +28,7 @@ /// /// The horizontal offset of the value to get. /// The vertical offset of the value to get. - /// The depthwise offset of the value to get. + /// The depthwise offset of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. public TPixel this[int x, int y, int z] { get; } diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs index 044a069a..7dc1995e 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs @@ -32,7 +32,7 @@ namespace ComputeSharp /// /// The horizontal offset of the value to get. /// The vertical offset of the value to get. - /// The depthwise offset of the value to get. + /// The depthwise offset of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. public T this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D)}[int,int,int]"); diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index 337325d7..3c2731b6 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -251,7 +251,7 @@ namespace ComputeSharp.Shaders.Renderer /// /// Ensures that has enough free space to contain a given number of new items. /// - /// The minimum number of items to ensure space for in . + /// The minimum number of items to ensure space for in . [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnsureCapacity(int requestedSize) { @@ -297,7 +297,7 @@ namespace ComputeSharp.Shaders.Renderer internal sealed class DebugView { /// - /// Initializes a new instance of the class with the specified parameters. + /// Initializes a new instance of the class with the specified parameters. /// /// The input instance to display. public DebugView(ArrayPoolStringBuilder builder) diff --git a/src/ComputeSharp.Shaders/Renderer/Models/HlslResourceInfo.cs b/src/ComputeSharp.Shaders/Renderer/Models/HlslResourceInfo.cs index f89cb615..cbde91bb 100644 --- a/src/ComputeSharp.Shaders/Renderer/Models/HlslResourceInfo.cs +++ b/src/ComputeSharp.Shaders/Renderer/Models/HlslResourceInfo.cs @@ -5,6 +5,7 @@ /// /// The type of the current field in the HLSL shader. /// The name to use for the current field. + /// The register index to bind the resource to. internal abstract record HlslResourceInfo(string FieldType, string FieldName, int BufferIndex) : CapturedFieldInfo(FieldType, FieldName) { diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index af601973..1d6f6257 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -111,7 +111,7 @@ namespace ComputeSharp.Shaders.Translation /// Loads and processes an input shadeer. /// /// The instance to use to build the shader. - /// A new instance representing the input shader. + /// A new instance representing the input shader. [Pure] public static ShaderLoader Load(in T shader) { @@ -179,7 +179,7 @@ namespace ComputeSharp.Shaders.Translation } /// - /// Loads a specified and adds it to the shader model. + /// Loads a specified and adds it to the shader model. /// /// The boxed instance to use to build the shader. /// The target to load. diff --git a/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs b/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs index a838cc5b..256c57a2 100644 --- a/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs @@ -68,7 +68,7 @@ namespace ComputeSharp /// The type of items stored on the buffer. /// The input instance to read data from. /// The input array to write data to. - /// The starting offset within to write data to. + /// The starting offset within to write data to. /// The offset to start reading data from. /// The number of items to read. public static void GetData(this Buffer buffer, T[] destination, int destinationOffset, int bufferOffset, int count) diff --git a/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs b/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs index 50ee8172..ae58b6b7 100644 --- a/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/Texture2DExtensions.cs @@ -93,7 +93,7 @@ namespace ComputeSharp /// The type of items stored on the texture. /// The input instance to read data from. /// The input array to write data to. - /// The starting offset within to write data to. + /// The starting offset within to write data to. public static void GetData(this Texture2D texture, T[] destination, int offset) where T : unmanaged { @@ -107,7 +107,7 @@ namespace ComputeSharp /// The type of items stored on the texture. /// The input instance to read data from. /// The input array to write data to. - /// The starting offset within to write data to. + /// The starting offset within to write data to. /// The horizontal range of items to copy. /// The vertical range of items to copy. public static void GetData(this Texture2D texture, T[] destination, int offset, Range x, Range y) @@ -123,7 +123,7 @@ namespace ComputeSharp /// The type of items stored on the texture. /// The input instance to read data from. /// The input array to write data to. - /// The starting offset within to write data to. + /// The starting offset within to write data to. /// The horizontal offset in the source texture. /// The vertical offset in the source texture. /// The width of the memory area to copy. diff --git a/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs b/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs index 3e0ccfe6..6c16d91a 100644 --- a/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/Texture3DExtensions.cs @@ -41,7 +41,7 @@ namespace ComputeSharp /// The input array to write data to. /// /// The input 3D array needs to have each 2D plane stacked on the depth axis. That is, the expected - /// layout of the input array has to be [, , ]. + /// layout of the input array has to be of shape [depth, height, width]. /// public static void GetData(this Texture3D texture, T[,,] destination) where T : unmanaged @@ -59,7 +59,7 @@ namespace ComputeSharp /// The type of items stored on the texture. /// The input instance to read data from. /// The input array to write data to. - /// The starting offset within to write data to. + /// The starting offset within to write data to. public static void GetData(this Texture3D texture, T[] destination, int offset) where T : unmanaged { @@ -73,7 +73,7 @@ namespace ComputeSharp /// The type of items stored on the texture. /// The input instance to read data from. /// The input array to write data to. - /// The starting offset within to write data to. + /// The starting offset within to write data to. /// The horizontal range of items to copy. /// The vertical range of items to copy. /// The depthwise range of items to copy. @@ -90,7 +90,7 @@ namespace ComputeSharp /// The type of items stored on the texture. /// The input instance to read data from. /// The input array to write data to. - /// The starting offset within to write data to. + /// The starting offset within to write data to. /// The horizontal offset in the source texture. /// The vertical offset in the source texture. /// The depthwise offset in the source texture. @@ -162,7 +162,7 @@ namespace ComputeSharp /// The input array to read data from. /// /// The source 3D array needs to have each 2D plane stacked on the depth axis. That is, the expected - /// layout of the input array has to be [, , ]. + /// layout of the input array has to be of shape [depth, height, width]. /// public static void SetData(this Texture3D texture, T[,,] source) where T : unmanaged diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index 60492b1b..078e2ca4 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -178,7 +178,7 @@ namespace ComputeSharp /// The type of items to store in the texture. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// The starting offset within to read data from. + /// The starting offset within to read data from. /// The width of the texture. /// The height of the texture. /// A instance with the contents of the input array. @@ -269,7 +269,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// The starting offset within to read data from. + /// The starting offset within to read data from. /// The width of the texture. /// The height of the texture. /// A instance with the contents of the input array. @@ -362,7 +362,7 @@ namespace ComputeSharp /// The type of items to store in the texture. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// The starting offset within to read data from. + /// The starting offset within to read data from. /// The width of the texture. /// The height of the texture. /// The depth of the texture. @@ -461,7 +461,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// The starting offset within to read data from. + /// The starting offset within to read data from. /// The width of the texture. /// The height of the texture. /// The depth of the texture. @@ -622,7 +622,7 @@ namespace ComputeSharp /// The type of items to store in the texture. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// The starting offset within to read data from. + /// The starting offset within to read data from. /// The width of the texture. /// The height of the texture. /// A instance with the contents of the input array. @@ -713,7 +713,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// The starting offset within to read data from. + /// The starting offset within to read data from. /// The width of the texture. /// The height of the texture. /// A instance with the contents of the input array. @@ -806,7 +806,7 @@ namespace ComputeSharp /// The type of items to store in the texture. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// The starting offset within to read data from. + /// The starting offset within to read data from. /// The width of the texture. /// The height of the texture. /// The depth of the texture. @@ -905,7 +905,7 @@ namespace ComputeSharp /// The type of pixels used on the GPU side. /// The instance to use to allocate the texture. /// The input array with the data to copy on the allocated texture. - /// The starting offset within to read data from. + /// The starting offset within to read data from. /// The width of the texture. /// The height of the texture. /// The depth of the texture. From 929f4b400369c1a1a05142a08e79372b7350da6a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Jan 2021 14:58:30 +0100 Subject: [PATCH 45/61] Enabled XML docs files for public projects --- .gitignore | 5 ++++- src/ComputeSharp.Core/ComputeSharp.Core.csproj | 2 ++ src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj | 6 ++++-- src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj | 2 ++ src/ComputeSharp/ComputeSharp.csproj | 2 ++ 5 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index fd8f3e38..b266c367 100644 --- a/.gitignore +++ b/.gitignore @@ -330,4 +330,7 @@ ASALocalRun/ .mfractor/ # Sample images -**/city_*.jpg +samples/**/city_*.jpg + +# XML docs files +src/**/ComputeSharp*.xml \ No newline at end of file diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index a76d03f4..4df5b272 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -2,6 +2,8 @@ netstandard2.0;net5.0 + bin\Release + ComputeSharp.Core.xml diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index e52ebdb8..96c738d6 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -2,11 +2,13 @@ netstandard2.0;net5.0 + bin\Release + ComputeSharp.Graphics.xml - - + + diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index f2204371..a0ee85cf 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -2,6 +2,8 @@ netstandard2.0;net5.0 + bin\Release + ComputeSharp.Shaders.xml diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 31d48cef..8f1cc533 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -2,6 +2,8 @@ netstandard2.0;net5.0 + bin\Release + ComputeSharp.xml From d01e9fbcdc643028281f9fdf5ec59e83060321ec Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Jan 2021 17:21:49 +0100 Subject: [PATCH 46/61] Added ThreadIds and GroupIds unit tests --- tests/ComputeSharp.Tests/DispatchTests.cs | 83 +++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 tests/ComputeSharp.Tests/DispatchTests.cs diff --git a/tests/ComputeSharp.Tests/DispatchTests.cs b/tests/ComputeSharp.Tests/DispatchTests.cs new file mode 100644 index 00000000..10e2d5a1 --- /dev/null +++ b/tests/ComputeSharp.Tests/DispatchTests.cs @@ -0,0 +1,83 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests +{ + [TestClass] + [TestCategory("Dispatch")] + public partial class DispatchTests + { + [TestMethod] + public void Verify_ThreadIds() + { + using ReadWriteTexture3D buffer = Gpu.Default.AllocateReadWriteTexture3D(50, 50, 50); + + Gpu.Default.For(buffer.Width, buffer.Height, buffer.Depth, new ThreadIdsShader(buffer)); + + Int4[,,] data = buffer.GetData(); + + for (int z = 0; z < 50; z++) + { + for (int x = 0; x < 50; x++) + { + for (int y = 0; y < 50; y++) + { + Int4 value = data[z, y, x]; + + Assert.AreEqual(x, value.X); + Assert.AreEqual(y, value.Y); + Assert.AreEqual(z, value.Z); + } + } + } + } + + [AutoConstructor] + internal readonly partial struct ThreadIdsShader : IComputeShader + { + public readonly ReadWriteTexture3D buffer; + + public void Execute() + { + buffer[ThreadIds.XYZ].XYZ = ThreadIds.XYZ; + } + } + + [TestMethod] + public void Verify_GroupIds() + { + using ReadWriteTexture3D buffer = Gpu.Default.AllocateReadWriteTexture3D(50, 50, 50); + + Gpu.Default.For(buffer.Width, buffer.Height, buffer.Depth, 4, 4, 4, new GroupIdsShader(buffer)); + + Int4[,,] data = buffer.GetData(); + + for (int z = 0; z < 50; z++) + { + for (int x = 0; x < 50; x++) + { + for (int y = 0; y < 50; y++) + { + Int4 value = data[z, y, x]; + + Assert.AreEqual(x % 4, value.X); + Assert.AreEqual(y % 4, value.Y); + Assert.AreEqual(z % 4, value.Z); + Assert.AreEqual(value.Z * 4 * 4 + value.Y * 4 + value.X, value.W); + } + } + } + } + + [AutoConstructor] + internal readonly partial struct GroupIdsShader : IComputeShader + { + public readonly ReadWriteTexture3D buffer; + + public void Execute() + { + buffer[ThreadIds.XYZ].XYZ = GroupIds.XYZ; + buffer[ThreadIds.XYZ].W = GroupIds.Index; + } + } + } +} From 417d0af5762dce370c946cabcada550551cdb218 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Jan 2021 17:53:54 +0100 Subject: [PATCH 47/61] Added GroupSize type --- src/ComputeSharp.Core/Dispatch/GroupIds.cs | 2 +- src/ComputeSharp.Core/Dispatch/GroupSize.cs | 210 ++++++++++++++++++ .../Renderer/HlslShaderRenderer.cs | 19 +- .../ComputeSharp.SourceGenerators.csproj | 3 +- .../Mappings/HlslKnownMembers.cs | 22 ++ 5 files changed, 246 insertions(+), 10 deletions(-) create mode 100644 src/ComputeSharp.Core/Dispatch/GroupSize.cs diff --git a/src/ComputeSharp.Core/Dispatch/GroupIds.cs b/src/ComputeSharp.Core/Dispatch/GroupIds.cs index c871eb06..18473a80 100644 --- a/src/ComputeSharp.Core/Dispatch/GroupIds.cs +++ b/src/ComputeSharp.Core/Dispatch/GroupIds.cs @@ -3,7 +3,7 @@ namespace ComputeSharp { /// - /// A that indicates the ids of a given GPU thread running a compute shader within aa dispatch group. + /// A that indicates the ids of a given GPU thread running a compute shader within a dispatch group. /// public static class GroupIds { diff --git a/src/ComputeSharp.Core/Dispatch/GroupSize.cs b/src/ComputeSharp.Core/Dispatch/GroupSize.cs new file mode 100644 index 00000000..0b4973c8 --- /dev/null +++ b/src/ComputeSharp.Core/Dispatch/GroupSize.cs @@ -0,0 +1,210 @@ +using ComputeSharp.Exceptions; + +namespace ComputeSharp +{ + /// + /// A that indicates the size info of a given GPU thread group running a compute shader within. + /// + public static class GroupSize + { + /// + /// Gets the total size of the current thread group. + /// + public static int Count => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(Count)}"); + + /// + /// Gets the size of the X axis of the current thread group. + /// + public static int X => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(X)}"); + + /// + /// Gets the size of the Y axis of the current thread group. + /// + public static int Y => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(Y)}"); + + /// + /// Gets the size of the Z axis of the current thread group. + /// + public static int Z => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(Z)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int2 XX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XX)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 XY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XY)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 XZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XZ)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 YX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YX)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int2 YY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YY)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 YZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YZ)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 ZX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZX)}"); + + /// + /// Gets or sets an value with the and values. + /// + public static Int2 ZY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZY)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int2 ZZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZZ)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int3 XXX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XXX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XXY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XXY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XXZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XXZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XYX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XYX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XYY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XYY)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 XYZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XYZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XZX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XZX)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 XZY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XZY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 XZZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(XZZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YXX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YXX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YXY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YXY)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 YXZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YXZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YYX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YYX)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int3 YYY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YYY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YYZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YYZ)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 YZX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YZX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YZY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YZY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 YZZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(YZZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZXX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZXX)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 ZXY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZXY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZXZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZXZ)}"); + + /// + /// Gets or sets an value with the , and values. + /// + public static Int3 ZYX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZYX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZYY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZYY)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZYZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZYZ)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZZX => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZZX)}"); + + /// + /// Gets an value with the , and values. + /// + public static Int3 ZZY => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZZY)}"); + + /// + /// Gets an value with the value for all components. + /// + public static Int3 ZZZ => throw new InvalidExecutionContextException($"{nameof(GroupSize)}.{nameof(ZZZ)}"); + } +} diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index 3c2731b6..882d5298 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -33,7 +33,16 @@ namespace ComputeSharp.Shaders.Renderer builder.AppendLine("// This shader was created by ComputeSharp."); builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); - // Constants + // Group size constants + builder.AppendLine(); + builder.Append("#define __GroupSize__get_X "); + builder.AppendLine(threadsX.ToString()); + builder.Append("#define __GroupSize__get_Y "); + builder.AppendLine(threadsY.ToString()); + builder.Append("#define __GroupSize__get_Z "); + builder.AppendLine(threadsZ.ToString()); + + // User defined onstants if (info.ConstantsInfo.Count > 0) { builder.AppendLine(); @@ -139,13 +148,7 @@ namespace ComputeSharp.Shaders.Renderer // Entry point builder.AppendLine(); - builder.Append("[NumThreads("); - builder.Append(threadsX.ToString()); - builder.Append(", "); - builder.Append(threadsY.ToString()); - builder.Append(", "); - builder.Append(threadsZ.ToString()); - builder.AppendLine(")]"); + builder.AppendLine("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); builder.AppendLine(info.EntryPoint); return builder; diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index e40e29f9..c49ab22a 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -18,8 +18,9 @@ - + + diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index ccf68a33..707abb64 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -211,6 +211,28 @@ namespace ComputeSharp.SourceGenerators.Mappings } } + // Programmatically load mappings for the group size + foreach (var property in typeof(GroupSize).GetProperties(BindingFlags.Static | BindingFlags.Public)) + { + string key = $"{typeof(GroupSize).FullName}{Type.Delimiter}{property.Name}"; + + switch (property.Name) + { + case nameof(GroupSize.Count): + knownMembers.Add(key, "__GroupSize__get_X * __GroupSize__get_Y * __GroupSize__get_Z"); + break; + case string name when name.Length == 1: + knownMembers.Add(key, $"__GroupSize__get_{name}"); + break; + case string name when name.Length == 1: + knownMembers.Add(key, $"__GroupSize__get_{name[0]} * __GroupSize__get_{name[1]}"); + break; + case string name when name.Length == 1: + knownMembers.Add(key, $"__GroupSize__get_{name[0]} * __GroupSize__get_{name[1]} * __GroupSize__get_{name[2]}"); + break; + } + } + return knownMembers; } From 736e52c09f9092c9c81c5ad38649b8cd017f41d3 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 14 Jan 2021 17:54:03 +0100 Subject: [PATCH 48/61] Added GroupSize unit tests --- tests/ComputeSharp.Tests/DispatchTests.cs | 29 +++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/ComputeSharp.Tests/DispatchTests.cs b/tests/ComputeSharp.Tests/DispatchTests.cs index 10e2d5a1..39f74221 100644 --- a/tests/ComputeSharp.Tests/DispatchTests.cs +++ b/tests/ComputeSharp.Tests/DispatchTests.cs @@ -79,5 +79,34 @@ namespace ComputeSharp.Tests buffer[ThreadIds.XYZ].W = GroupIds.Index; } } + + [TestMethod] + public void Verify_GroupSize() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(32); + + Gpu.Default.For(1, 1, 1, 4, 15, 7, new GroupSizeShader(buffer)); + + int[] data = buffer.GetData(); + + Assert.AreEqual(4, data[0]); + Assert.AreEqual(15, data[1]); + Assert.AreEqual(7, data[2]); + Assert.AreEqual(4 * 15 * 7, data[3]); + } + + [AutoConstructor] + internal readonly partial struct GroupSizeShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + + public void Execute() + { + buffer[0] = GroupSize.X; + buffer[1] = GroupSize.Y; + buffer[2] = GroupSize.Z; + buffer[3] = GroupSize.Count; + } + } } } From 7629dee8c00c6b390a991e2bac1eba6f806cab2e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Jan 2021 20:16:48 +0100 Subject: [PATCH 49/61] Added more texture type validation APIs --- .../UnsupportedTextureTypeException.cs | 6 +-- .../Extensions/ID3D12DeviceExtensions.cs | 2 +- src/ComputeSharp.Graphics/GraphicsDevice.cs | 50 ++++++++++++++++--- .../Resources/Abstract/Texture2D{T}.cs | 6 +-- .../Resources/Abstract/Texture3D{T}.cs | 6 +-- .../Resources/ReadOnlyTexture2D{T,TPixel}.cs | 3 +- .../Resources/ReadOnlyTexture2D{T}.cs | 3 +- .../Resources/ReadOnlyTexture3D{T,TPixel}.cs | 3 +- .../Resources/ReadOnlyTexture3D{T}.cs | 3 +- .../Resources/ReadWriteTexture2D{T,TPixel}.cs | 3 +- .../Resources/ReadWriteTexture2D{T}.cs | 3 +- .../Resources/ReadWriteTexture3D{T,TPixel}.cs | 3 +- .../Resources/ReadWriteTexture3D{T}.cs | 3 +- 13 files changed, 68 insertions(+), 26 deletions(-) diff --git a/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs b/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs index 511ce147..1b100ced 100644 --- a/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs +++ b/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs @@ -35,12 +35,12 @@ namespace ComputeSharp.Exceptions builder.AppendLine(rank switch { - 2 => $"{nameof(GraphicsDevice.IsTexture2DSupportedForType)}().", - 3 => $"{nameof(GraphicsDevice.IsTexture3DSupportedForType)}().", + 2 => $"{nameof(GraphicsDevice.IsReadOnlyTexture2DSupportedForType)}() or {nameof(GraphicsDevice.IsReadWriteTexture2DSupportedForType)}().", + 3 => $"{nameof(GraphicsDevice.IsReadOnlyTexture3DSupportedForType)}() or {nameof(GraphicsDevice.IsReadWriteTexture3DSupportedForType)}().", _ => ThrowHelper.ThrowArgumentException("Invalid texture rank") }); - builder.AppendLine($"As a possible workaround on older devices, consider using a texture type of lower rank, or a linear buffer."); + builder.AppendLine("As a possible workaround on older devices, consider using a texture type of lower rank, or a linear buffer."); builder.ToString(); return new(builder.ToString()); diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs index 971f3db3..0b621f4a 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs @@ -505,7 +505,7 @@ namespace ComputeSharp.Graphics.Extensions d3D12Device.CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &d3D12FeatureDataFormatSupport, (uint)sizeof(D3D12_FEATURE_DATA_FORMAT_SUPPORT)).Assert(); - return (d3D12FeatureDataFormatSupport.Support1 & d3D12FormatSupport1) != 0; + return (d3D12FeatureDataFormatSupport.Support1 & d3D12FormatSupport1) == d3D12FormatSupport1; } } } diff --git a/src/ComputeSharp.Graphics/GraphicsDevice.cs b/src/ComputeSharp.Graphics/GraphicsDevice.cs index 600ded21..b2c12d7e 100644 --- a/src/ComputeSharp.Graphics/GraphicsDevice.cs +++ b/src/ComputeSharp.Graphics/GraphicsDevice.cs @@ -152,13 +152,13 @@ namespace ComputeSharp internal bool IsCacheCoherentUMA { get; } /// - /// Checks whether the current device supports the creation of - /// resources for a specified type . + /// Checks whether the current device supports the creation of + /// resources for a specified type . /// /// The type of values to check support for. - /// Whether instances can be created by the current device. + /// Whether instances can be created by the current device. [Pure] - public bool IsTexture2DSupportedForType() + public bool IsReadOnlyTexture2DSupportedForType() where T : unmanaged { ThrowIfDisposed(); @@ -167,13 +167,30 @@ namespace ComputeSharp } /// - /// Checks whether the current device supports the creation of - /// resources for a specified type . + /// Checks whether the current device supports the creation of + /// resources for a specified type . /// /// The type of values to check support for. - /// Whether instances can be created by the current device. + /// Whether instances can be created by the current device. [Pure] - public bool IsTexture3DSupportedForType() + public bool IsReadWriteTexture2DSupportedForType() + where T : unmanaged + { + ThrowIfDisposed(); + + return this.d3D12Device.Get()->IsDxgiFormatSupported( + DXGIFormatHelper.GetForType(), + D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); + } + + /// + /// Checks whether the current device supports the creation of + /// resources for a specified type . + /// + /// The type of values to check support for. + /// Whether instances can be created by the current device. + [Pure] + public bool IsReadOnlyTexture3DSupportedForType() where T : unmanaged { ThrowIfDisposed(); @@ -181,6 +198,23 @@ namespace ComputeSharp return this.d3D12Device.Get()->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE3D); } + /// + /// Checks whether the current device supports the creation of + /// resources for a specified type . + /// + /// The type of values to check support for. + /// Whether instances can be created by the current device. + [Pure] + public bool IsReadWriteTexture3DSupportedForType() + where T : unmanaged + { + ThrowIfDisposed(); + + return this.d3D12Device.Get()->IsDxgiFormatSupported( + DXGIFormatHelper.GetForType(), + D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW); + } + /// internal void RentShaderResourceViewDescriptorHandles( out D3D12_CPU_DESCRIPTOR_HANDLE d3D12CpuDescriptorHandle, diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs index 6ea4d30e..8780a646 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs @@ -10,7 +10,6 @@ using ComputeSharp.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; -using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; using static TerraFX.Interop.D3D12_RESOURCE_STATES; using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; @@ -60,14 +59,15 @@ namespace ComputeSharp.Resources /// The height of the texture. /// The width of the texture. /// The resource type for the current texture. - private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType) + /// The format support for the current texture type. + private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { device.ThrowIfDisposed(); Guard.IsBetweenOrEqualTo(width, 1, FX.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION, nameof(width)); Guard.IsBetweenOrEqualTo(height, 1, FX.D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION, nameof(height)); - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D)) + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) { UnsupportedTextureTypeException.ThrowForTexture2D(); } diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs index 207afc44..fa5a08c7 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs @@ -10,7 +10,6 @@ using ComputeSharp.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; -using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; using static TerraFX.Interop.D3D12_RESOURCE_STATES; using static TerraFX.Interop.D3D12_SRV_DIMENSION; using static TerraFX.Interop.D3D12_UAV_DIMENSION; @@ -61,7 +60,8 @@ namespace ComputeSharp.Resources /// The width of the texture. /// The depth of the texture. /// The resource type for the current texture. - private protected Texture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType) + /// The format support for the current texture type. + private protected Texture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { device.ThrowIfDisposed(); @@ -69,7 +69,7 @@ namespace ComputeSharp.Resources Guard.IsBetweenOrEqualTo(height, 1, FX.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION, nameof(height)); Guard.IsBetweenOrEqualTo(depth, 1, FX.D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION, nameof(depth)); - if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), D3D12_FORMAT_SUPPORT1_TEXTURE2D)) + if (!device.D3D12Device->IsDxgiFormatSupported(DXGIFormatHelper.GetForType(), d3D12FormatSupport)) { UnsupportedTextureTypeException.ThrowForTexture2D(); } diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs index e2a1ab08..e4709634 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs @@ -4,6 +4,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Resources; using ComputeSharp.Resources.Views; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; #pragma warning disable CS0618 @@ -27,7 +28,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height) - : base(device, width, height, ResourceType.ReadOnly) + : base(device, width, height, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE2D) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs index 3d94f2f0..564d6453 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs @@ -3,6 +3,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Resources; using ComputeSharp.Resources.Views; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; namespace ComputeSharp { @@ -22,7 +23,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height) - : base(device, width, height, ResourceType.ReadOnly) + : base(device, width, height, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE2D) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs index 07d4d98a..6b632835 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs @@ -4,6 +4,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Resources; using ComputeSharp.Resources.Views; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; #pragma warning disable CS0618 @@ -28,7 +29,7 @@ namespace ComputeSharp /// The height of the texture. /// The depth of the texture. internal ReadOnlyTexture3D(GraphicsDevice device, int width, int height, int depth) - : base(device, width, height, depth, ResourceType.ReadOnly) + : base(device, width, height, depth, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE3D) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs index 7dc1995e..089a0f5d 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs @@ -3,6 +3,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Resources; using ComputeSharp.Resources.Views; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; namespace ComputeSharp { @@ -23,7 +24,7 @@ namespace ComputeSharp /// The height of the texture. /// The depth of the texture. internal ReadOnlyTexture3D(GraphicsDevice device, int width, int height, int depth) - : base(device, width, height, depth, ResourceType.ReadOnly) + : base(device, width, height, depth, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE3D) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs index 28366eb3..d120a371 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs @@ -4,6 +4,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Resources; using ComputeSharp.Resources.Views; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; #pragma warning disable CS0618 @@ -27,7 +28,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. internal ReadWriteTexture2D(GraphicsDevice device, int width, int height) - : base(device, width, height, ResourceType.ReadWrite) + : base(device, width, height, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs index bbf43edc..b8e83351 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs @@ -3,6 +3,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Resources; using ComputeSharp.Resources.Views; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; namespace ComputeSharp { @@ -22,7 +23,7 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. internal ReadWriteTexture2D(GraphicsDevice device, int width, int height) - : base(device, width, height, ResourceType.ReadWrite) + : base(device, width, height, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs index 7a0caaa2..ce4026bd 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs @@ -4,6 +4,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Resources; using ComputeSharp.Resources.Views; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; #pragma warning disable CS0618 @@ -28,7 +29,7 @@ namespace ComputeSharp /// The height of the texture. /// The depth of the texture. internal ReadWriteTexture3D(GraphicsDevice device, int width, int height, int depth) - : base(device, width, height, depth, ResourceType.ReadWrite) + : base(device, width, height, depth, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs index 631d72bf..1a4b88e1 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs @@ -3,6 +3,7 @@ using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Resources.Enums; using ComputeSharp.Resources; using ComputeSharp.Resources.Views; +using static TerraFX.Interop.D3D12_FORMAT_SUPPORT1; namespace ComputeSharp { @@ -23,7 +24,7 @@ namespace ComputeSharp /// The height of the texture. /// The depth of the texture. internal ReadWriteTexture3D(GraphicsDevice device, int width, int height, int depth) - : base(device, width, height, depth, ResourceType.ReadWrite) + : base(device, width, height, depth, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) { } From 95c9d336d3c99d6d03e6242177aeefbeef753dd0 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Jan 2021 20:22:32 +0100 Subject: [PATCH 50/61] Tweaked an exception message --- .../Exceptions/UnsupportedTextureTypeException.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs b/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs index 1b100ced..d2dbc529 100644 --- a/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs +++ b/src/ComputeSharp.Graphics/Exceptions/UnsupportedTextureTypeException.cs @@ -35,12 +35,12 @@ namespace ComputeSharp.Exceptions builder.AppendLine(rank switch { - 2 => $"{nameof(GraphicsDevice.IsReadOnlyTexture2DSupportedForType)}() or {nameof(GraphicsDevice.IsReadWriteTexture2DSupportedForType)}().", - 3 => $"{nameof(GraphicsDevice.IsReadOnlyTexture3DSupportedForType)}() or {nameof(GraphicsDevice.IsReadWriteTexture3DSupportedForType)}().", + 2 => $"{nameof(GraphicsDevice.IsReadOnlyTexture2DSupportedForType)}() or {nameof(GraphicsDevice)}.{nameof(GraphicsDevice.IsReadWriteTexture2DSupportedForType)}().", + 3 => $"{nameof(GraphicsDevice.IsReadOnlyTexture3DSupportedForType)}() or {nameof(GraphicsDevice)}.{nameof(GraphicsDevice.IsReadWriteTexture3DSupportedForType)}().", _ => ThrowHelper.ThrowArgumentException("Invalid texture rank") }); - builder.AppendLine("As a possible workaround on older devices, consider using a texture type of lower rank, or a linear buffer."); + builder.Append("As a possible workaround on older devices, consider using a texture type of lower rank, or a linear buffer."); builder.ToString(); return new(builder.ToString()); From 45f5959bb878d2f3e6208b27f01655477abb0de4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Jan 2021 20:48:48 +0100 Subject: [PATCH 51/61] Fixed HLSL formatting of floating point constants --- .../SyntaxRewriters/ShaderSourceRewriter.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 289f14ac..5c40b29d 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; @@ -310,7 +311,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters // If the member access is a constant, track it and replace the tree with the processed constant name if (operation is IFieldReferenceOperation fieldOperation && fieldOperation.Field.IsConst) { - this.constantDefinitions[fieldOperation.Field] = fieldOperation.Field.ConstantValue!.ToString(); + this.constantDefinitions[fieldOperation.Field] = ((IFormattable)fieldOperation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); var ownerTypeName = ((INamedTypeSymbol)fieldOperation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__"); var constantName = $"__{ownerTypeName}__{fieldOperation.Field.Name}"; @@ -496,7 +497,7 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters if (this.semanticModel.GetOperation(node) is IFieldReferenceOperation operation && operation.Field.IsConst) { - this.constantDefinitions[operation.Field] = operation.Field.ConstantValue!.ToString(); + this.constantDefinitions[operation.Field] = ((IFormattable)operation.Field.ConstantValue!).ToString(null, CultureInfo.InvariantCulture); var ownerTypeName = ((INamedTypeSymbol)operation.Field.ContainingSymbol).ToDisplayString().Replace(".", "__"); var constantName = $"__{ownerTypeName}__{operation.Field.Name}"; From 3e2d956e7e6e865e98a5a48706f160225d73967f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 15 Jan 2021 20:49:00 +0100 Subject: [PATCH 52/61] Minor formatting tweaks to HLSL shaders --- .../Renderer/HlslShaderRenderer.cs | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs index 882d5298..e2bd3929 100644 --- a/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp.Shaders/Renderer/HlslShaderRenderer.cs @@ -43,17 +43,12 @@ namespace ComputeSharp.Shaders.Renderer builder.AppendLine(threadsZ.ToString()); // User defined onstants - if (info.ConstantsInfo.Count > 0) + foreach (var constant in info.ConstantsInfo) { - builder.AppendLine(); - - foreach (var constant in info.ConstantsInfo) - { - builder.Append("#define "); - builder.Append(constant.Key); - builder.Append(' '); - builder.AppendLine(constant.Value); - } + builder.Append("#define "); + builder.Append(constant.Key); + builder.Append(' '); + builder.AppendLine(constant.Value); } // Declared types From 97a2bbc69beac292bf146f64ac6064f5776a5c5c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 16 Jan 2021 16:05:41 +0100 Subject: [PATCH 53/61] Speedup to gaussian blur sample --- .../Processors/HlslGaussianBlurProcessor{TPixel}.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 3126f2d4..9a8721a6 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -95,7 +95,7 @@ namespace ComputeSharp.BokehBlur.Processors Span span = MemoryMarshal.Cast(pixelSpan); using ReadWriteTexture2D sourceTexture = Gpu.Default.AllocateReadWriteTexture2D(span, source.Width, source.Height); - using ReadWriteTexture2D firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); using ReadOnlyBuffer kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel); Gpu.Default.For(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer)); @@ -111,7 +111,7 @@ namespace ComputeSharp.BokehBlur.Processors internal readonly partial struct VerticalConvolutionProcessor : IComputeShader { public readonly IReadWriteTexture2D source; - public readonly ReadWriteTexture2D target; + public readonly IReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; /// @@ -142,7 +142,7 @@ namespace ComputeSharp.BokehBlur.Processors [AutoConstructor] internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader { - public readonly ReadWriteTexture2D source; + public readonly IReadWriteTexture2D source; public readonly IReadWriteTexture2D target; public readonly ReadOnlyBuffer kernel; From 052e50a8d29c16583db523d72066e4ca967bee4d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 16 Jan 2021 17:23:54 +0100 Subject: [PATCH 54/61] Added AllocationMode option to create resources --- .../HlslBokehBlurProcessor{TPixel}.cs | 2 +- .../Extensions/ID3D12DeviceExtensions.cs | 15 ++- .../Resources/Abstract/Buffer{T}.cs | 5 +- .../Resources/Abstract/StructuredBuffer{T}.cs | 9 +- .../Resources/Abstract/Texture2D{T}.cs | 8 +- .../Resources/Abstract/Texture3D{T}.cs | 8 +- .../Resources/ConstantBuffer{T}.cs | 5 +- .../Resources/Enums/AllocationMode.cs | 20 ++++ .../Resources/ReadOnlyBuffer{T}.cs | 5 +- .../Resources/ReadOnlyTexture2D{T,TPixel}.cs | 5 +- .../Resources/ReadOnlyTexture2D{T}.cs | 5 +- .../Resources/ReadOnlyTexture3D{T,TPixel}.cs | 5 +- .../Resources/ReadOnlyTexture3D{T}.cs | 5 +- .../Resources/ReadWriteBuffer{T}.cs | 5 +- .../Resources/ReadWriteTexture2D{T,TPixel}.cs | 5 +- .../Resources/ReadWriteTexture2D{T}.cs | 5 +- .../Resources/ReadWriteTexture3D{T,TPixel}.cs | 5 +- .../Resources/ReadWriteTexture3D{T}.cs | 5 +- src/ComputeSharp.Shaders/ShaderRunner{T}.cs | 2 +- .../Extensions/GraphicsDeviceExtensions.cs | 99 ++++++++++--------- 20 files changed, 140 insertions(+), 83 deletions(-) create mode 100644 src/ComputeSharp.Graphics/Resources/Enums/AllocationMode.cs diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index 9ae94951..864389ed 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -257,7 +257,7 @@ namespace ComputeSharp.BokehBlur.Processors Span span = MemoryMarshal.Cast(pixelSpan); using ReadWriteTexture2D texture = Gpu.Default.AllocateReadWriteTexture2D(span, source.Width, source.Height); - using ReadWriteTexture2D temporary = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); + using ReadWriteTexture2D temporary = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height, AllocationMode.Clear); using ReadWriteTexture2D reals = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); using ReadWriteTexture2D imaginaries = Gpu.Default.AllocateReadWriteTexture2D(source.Width, source.Height); using ReadOnlyBuffer kernel = Gpu.Default.AllocateReadOnlyBuffer(KernelSize); diff --git a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs index 0b621f4a..96570d5b 100644 --- a/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Graphics/Extensions/ID3D12DeviceExtensions.cs @@ -101,15 +101,18 @@ namespace ComputeSharp.Graphics.Extensions /// /// The instance in use. /// The resource type currently in use. + /// The allocation mode to use for the new resource. /// The size in bytes of the current buffer. /// Indicates whether or not the current device has a cache coherent UMA architecture. /// An reference for the current buffer. public static ComPtr CreateCommittedResource( this ref ID3D12Device d3D12Device, ResourceType resourceType, + AllocationMode allocationMode, ulong sizeInBytes, bool isCacheCoherentUMA) { + D3D12_HEAP_FLAGS d3D12HeapFlags = allocationMode == AllocationMode.Default ? D3D12_HEAP_FLAG_CREATE_NOT_ZEROED : D3D12_HEAP_FLAG_NONE; (D3D12_HEAP_TYPE d3D12HeapType, D3D12_RESOURCE_FLAGS d3D12ResourceFlags, D3D12_RESOURCE_STATES d3D12ResourceStates) = resourceType switch @@ -145,7 +148,7 @@ namespace ComputeSharp.Graphics.Extensions d3D12Device.CreateCommittedResource( &d3D12HeapProperties, - D3D12_HEAP_FLAG_NONE, + d3D12HeapFlags, &d3D12ResourceDescription, d3D12ResourceStates, null, @@ -160,6 +163,7 @@ namespace ComputeSharp.Graphics.Extensions /// /// The instance in use. /// The resource type currently in use. + /// The allocation mode to use for the new resource. /// The value to use. /// The width of the texture resource. /// The height of the texture resource. @@ -169,12 +173,14 @@ namespace ComputeSharp.Graphics.Extensions public static ComPtr CreateCommittedResource( this ref ID3D12Device d3D12Device, ResourceType resourceType, + AllocationMode allocationMode, DXGI_FORMAT dxgiFormat, uint width, uint height, bool isCacheCoherentUMA, out D3D12_RESOURCE_STATES d3D12ResourceStates) { + D3D12_HEAP_FLAGS d3D12HeapFlags = allocationMode == AllocationMode.Default ? D3D12_HEAP_FLAG_CREATE_NOT_ZEROED : D3D12_HEAP_FLAG_NONE; D3D12_RESOURCE_FLAGS d3D12ResourceFlags; (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch @@ -207,7 +213,7 @@ namespace ComputeSharp.Graphics.Extensions d3D12Device.CreateCommittedResource( &d3D12HeapProperties, - D3D12_HEAP_FLAG_NONE, + d3D12HeapFlags, &d3D12ResourceDescription, d3D12ResourceStates, null, @@ -222,6 +228,7 @@ namespace ComputeSharp.Graphics.Extensions /// /// The instance in use. /// The resource type currently in use. + /// The allocation mode to use for the new resource. /// The value to use. /// The width of the texture resource. /// The height of the texture resource. @@ -232,6 +239,7 @@ namespace ComputeSharp.Graphics.Extensions public static ComPtr CreateCommittedResource( this ref ID3D12Device d3D12Device, ResourceType resourceType, + AllocationMode allocationMode, DXGI_FORMAT dxgiFormat, uint width, uint height, @@ -239,6 +247,7 @@ namespace ComputeSharp.Graphics.Extensions bool isCacheCoherentUMA, out D3D12_RESOURCE_STATES d3D12ResourceStates) { + D3D12_HEAP_FLAGS d3D12HeapFlags = allocationMode == AllocationMode.Default ? D3D12_HEAP_FLAG_CREATE_NOT_ZEROED : D3D12_HEAP_FLAG_NONE; D3D12_RESOURCE_FLAGS d3D12ResourceFlags; (d3D12ResourceFlags, d3D12ResourceStates) = resourceType switch @@ -271,7 +280,7 @@ namespace ComputeSharp.Graphics.Extensions d3D12Device.CreateCommittedResource( &d3D12HeapProperties, - D3D12_HEAP_FLAG_NONE, + d3D12HeapFlags, &d3D12ResourceDescription, d3D12ResourceStates, null, diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs index 85085968..7cacdccd 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs @@ -50,7 +50,8 @@ namespace ComputeSharp.Resources /// The number of items to store in the current buffer. /// The size in bytes of each buffer item (including padding, if any). /// The resource type for the current buffer. - private protected Buffer(GraphicsDevice device, int length, uint elementSizeInBytes, ResourceType resourceType) + /// The allocation mode to use for the new resource. + private protected Buffer(GraphicsDevice device, int length, uint elementSizeInBytes, ResourceType resourceType, AllocationMode allocationMode) { device.ThrowIfDisposed(); @@ -68,7 +69,7 @@ namespace ComputeSharp.Resources GraphicsDevice = device; Length = length; - this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, (ulong)SizeInBytes, device.IsCacheCoherentUMA); + this.d3D12Resource = device.D3D12Device->CreateCommittedResource(resourceType, allocationMode, (ulong)SizeInBytes, device.IsCacheCoherentUMA); device.RentShaderResourceViewDescriptorHandles(out D3D12CpuDescriptorHandle, out D3D12GpuDescriptorHandle); diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/StructuredBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/StructuredBuffer{T}.cs index ab650ac7..e47ea518 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/StructuredBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/StructuredBuffer{T}.cs @@ -22,8 +22,9 @@ namespace ComputeSharp.Resources /// The associated with the current instance. /// The number of items to store in the current buffer. /// The buffer type for the current buffer. - private protected unsafe StructuredBuffer(GraphicsDevice device, int length, ResourceType resourceType) - : base(device, length, (uint)sizeof(T), resourceType) + /// The allocation mode to use for the new resource. + private protected unsafe StructuredBuffer(GraphicsDevice device, int length, ResourceType resourceType, AllocationMode allocationMode) + : base(device, length, (uint)sizeof(T), resourceType, allocationMode) { } @@ -57,7 +58,7 @@ namespace ComputeSharp.Resources byteOffset = (nint)offset * sizeof(T), byteSize = size * sizeof(T); - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.ReadBack, (ulong)byteSize, false); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.ReadBack, AllocationMode.Default, (ulong)byteSize, false); using (CommandList copyCommandList = new(GraphicsDevice, D3D12_COMMAND_LIST_TYPE_COPY)) { @@ -109,7 +110,7 @@ namespace ComputeSharp.Resources byteOffset = (nint)offset * sizeof(T), byteSize = size * sizeof(T); - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.Upload, (ulong)byteSize, false); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.Upload, AllocationMode.Default, (ulong)byteSize, false); using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) fixed (void* sourcePointer = &source) diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs index 8780a646..3b36a343 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs @@ -59,8 +59,9 @@ namespace ComputeSharp.Resources /// The height of the texture. /// The width of the texture. /// The resource type for the current texture. + /// The allocation mode to use for the new resource. /// The format support for the current texture type. - private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) + private protected Texture2D(GraphicsDevice device, int width, int height, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { device.ThrowIfDisposed(); @@ -78,6 +79,7 @@ namespace ComputeSharp.Resources this.d3D12Resource = device.D3D12Device->CreateCommittedResource( resourceType, + allocationMode, DXGIFormatHelper.GetForType(), (uint)width, (uint)height, @@ -152,7 +154,7 @@ namespace ComputeSharp.Resources out ulong rowSizeInBytes, out ulong totalSizeInBytes); - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.ReadBack, totalSizeInBytes, GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.ReadBack, AllocationMode.Default, totalSizeInBytes, GraphicsDevice.IsCacheCoherentUMA); using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) { @@ -224,7 +226,7 @@ namespace ComputeSharp.Resources out ulong rowSizeInBytes, out ulong totalSizeInBytes); - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.Upload, totalSizeInBytes, GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.Upload, AllocationMode.Default, totalSizeInBytes, GraphicsDevice.IsCacheCoherentUMA); using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) fixed (void* sourcePointer = &source) diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs index fa5a08c7..35ae7c08 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs @@ -60,8 +60,9 @@ namespace ComputeSharp.Resources /// The width of the texture. /// The depth of the texture. /// The resource type for the current texture. + /// The allocation mode to use for the new resource. /// The format support for the current texture type. - private protected Texture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) + private protected Texture3D(GraphicsDevice device, int width, int height, int depth, ResourceType resourceType, AllocationMode allocationMode, D3D12_FORMAT_SUPPORT1 d3D12FormatSupport) { device.ThrowIfDisposed(); @@ -81,6 +82,7 @@ namespace ComputeSharp.Resources this.d3D12Resource = device.D3D12Device->CreateCommittedResource( resourceType, + allocationMode, DXGIFormatHelper.GetForType(), (uint)width, (uint)height, @@ -166,7 +168,7 @@ namespace ComputeSharp.Resources out ulong rowSizeInBytes, out ulong totalSizeInBytes); - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.ReadBack, totalSizeInBytes, GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.ReadBack, AllocationMode.Default, totalSizeInBytes, GraphicsDevice.IsCacheCoherentUMA); using (CommandList copyCommandList = new(GraphicsDevice, this.d3D12CommandListType)) { @@ -245,7 +247,7 @@ namespace ComputeSharp.Resources out ulong rowSizeInBytes, out ulong totalSizeInBytes); - using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.Upload, totalSizeInBytes, GraphicsDevice.IsCacheCoherentUMA); + using ComPtr d3D12Resource = GraphicsDevice.D3D12Device->CreateCommittedResource(ResourceType.Upload, AllocationMode.Default, totalSizeInBytes, GraphicsDevice.IsCacheCoherentUMA); using (ID3D12ResourceMap resource = d3D12Resource.Get()->Map()) fixed (void* sourcePointer = &source) diff --git a/src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs index 24ce2bfb..a4200c3e 100644 --- a/src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ConstantBuffer{T}.cs @@ -35,8 +35,9 @@ namespace ComputeSharp /// /// The associated with the current instance. /// The number of items to store in the current buffer. - internal ConstantBuffer(GraphicsDevice device, int length) - : base(device, length, (uint)GetPaddedSize(), ResourceType.Constant) + /// The allocation mode to use for the new resource. + internal ConstantBuffer(GraphicsDevice device, int length, AllocationMode allocationMode) + : base(device, length, (uint)GetPaddedSize(), ResourceType.Constant, allocationMode) { } diff --git a/src/ComputeSharp.Graphics/Resources/Enums/AllocationMode.cs b/src/ComputeSharp.Graphics/Resources/Enums/AllocationMode.cs new file mode 100644 index 00000000..4f2e508b --- /dev/null +++ b/src/ComputeSharp.Graphics/Resources/Enums/AllocationMode.cs @@ -0,0 +1,20 @@ +namespace ComputeSharp +{ + /// + /// An that indicates a mode to use when allocating resources. + /// + public enum AllocationMode + { + /// + /// The default allocation mode for graphics resources. Allocated buffers are not explicitly cleared when created. + /// They can still be cleared for security reasons in some situations, but this step will be skipped whenever possible. + /// As such, always make sure not to read directly to buffers created this way before writing data to them first. + /// + Default, + + /// + /// Clear allocated buffers when creating them. + /// + Clear + } +} diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs index 785dcd56..2d902880 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyBuffer{T}.cs @@ -20,8 +20,9 @@ namespace ComputeSharp /// /// The associated with the current instance. /// The number of items to store in the current buffer. - internal ReadOnlyBuffer(GraphicsDevice device, int length) - : base(device, length, ResourceType.ReadOnly) + /// The allocation mode to use for the new resource. + internal ReadOnlyBuffer(GraphicsDevice device, int length, AllocationMode allocationMode) + : base(device, length, ResourceType.ReadOnly, allocationMode) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs index e4709634..7ebb1b17 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs @@ -27,8 +27,9 @@ namespace ComputeSharp /// The associated with the current instance. /// The width of the texture. /// The height of the texture. - internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height) - : base(device, width, height, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE2D) + /// The allocation mode to use for the new resource. + internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height, AllocationMode allocationMode) + : base(device, width, height, ResourceType.ReadOnly, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE2D) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs index 564d6453..4e86b8ca 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture2D{T}.cs @@ -22,8 +22,9 @@ namespace ComputeSharp /// The associated with the current instance. /// The width of the texture. /// The height of the texture. - internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height) - : base(device, width, height, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE2D) + /// The allocation mode to use for the new resource. + internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height, AllocationMode allocationMode) + : base(device, width, height, ResourceType.ReadOnly, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE2D) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs index 6b632835..76bd6395 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs @@ -28,8 +28,9 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - internal ReadOnlyTexture3D(GraphicsDevice device, int width, int height, int depth) - : base(device, width, height, depth, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE3D) + /// The allocation mode to use for the new resource. + internal ReadOnlyTexture3D(GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode) + : base(device, width, height, depth, ResourceType.ReadOnly, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE3D) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs index 089a0f5d..29c12680 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadOnlyTexture3D{T}.cs @@ -23,8 +23,9 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - internal ReadOnlyTexture3D(GraphicsDevice device, int width, int height, int depth) - : base(device, width, height, depth, ResourceType.ReadOnly, D3D12_FORMAT_SUPPORT1_TEXTURE3D) + /// The allocation mode to use for the new resource. + internal ReadOnlyTexture3D(GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode) + : base(device, width, height, depth, ResourceType.ReadOnly, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE3D) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteBuffer{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteBuffer{T}.cs index 1ea2cfd4..4fd28bb1 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteBuffer{T}.cs @@ -20,8 +20,9 @@ namespace ComputeSharp /// /// The associated with the current instance. /// The number of items to store in the current buffer. - internal ReadWriteBuffer(GraphicsDevice device, int length) - : base(device, length, ResourceType.ReadWrite) + /// The allocation mode to use for the new resource. + internal ReadWriteBuffer(GraphicsDevice device, int length, AllocationMode allocationMode) + : base(device, length, ResourceType.ReadWrite, allocationMode) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs index d120a371..61ff5f9e 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs @@ -27,8 +27,9 @@ namespace ComputeSharp /// The associated with the current instance. /// The width of the texture. /// The height of the texture. - internal ReadWriteTexture2D(GraphicsDevice device, int width, int height) - : base(device, width, height, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) + /// The allocation mode to use for the new resource. + internal ReadWriteTexture2D(GraphicsDevice device, int width, int height, AllocationMode allocationMode) + : base(device, width, height, ResourceType.ReadWrite, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs index b8e83351..a3037378 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture2D{T}.cs @@ -22,8 +22,9 @@ namespace ComputeSharp /// The associated with the current instance. /// The width of the texture. /// The height of the texture. - internal ReadWriteTexture2D(GraphicsDevice device, int width, int height) - : base(device, width, height, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) + /// The allocation mode to use for the new resource. + internal ReadWriteTexture2D(GraphicsDevice device, int width, int height, AllocationMode allocationMode) + : base(device, width, height, ResourceType.ReadWrite, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs index ce4026bd..157d98d7 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs @@ -28,8 +28,9 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - internal ReadWriteTexture3D(GraphicsDevice device, int width, int height, int depth) - : base(device, width, height, depth, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) + /// The allocation mode to use for the new resource. + internal ReadWriteTexture3D(GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode) + : base(device, width, height, depth, ResourceType.ReadWrite, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) { } diff --git a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs index 1a4b88e1..e13bcf0d 100644 --- a/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/ReadWriteTexture3D{T}.cs @@ -23,8 +23,9 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. - internal ReadWriteTexture3D(GraphicsDevice device, int width, int height, int depth) - : base(device, width, height, depth, ResourceType.ReadWrite, D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) + /// The allocation mode to use for the new resource. + internal ReadWriteTexture3D(GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode) + : base(device, width, height, depth, ResourceType.ReadWrite, allocationMode, D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) { } diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs index 04683a7f..57accca0 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -37,7 +37,7 @@ namespace ComputeSharp.Shaders { ConditionalWeakTable> map = variablesBuffers ??= new(); - return map.GetValue(device, static gpu => new(gpu, 256)); + return map.GetValue(device, static gpu => new(gpu, 256, AllocationMode.Default)); } } diff --git a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs index 078e2ca4..fdb156ba 100644 --- a/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Extensions/GraphicsDeviceExtensions.cs @@ -19,12 +19,13 @@ namespace ComputeSharp /// The type of items to store in the buffer. /// The instance to use to allocate the buffer. /// The length of the buffer to allocate. + /// The allocation mode to use for the new resource. /// A zeroed instance of size . [Pure] - public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, int length) + public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, int length, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged { - return new(device, length); + return new(device, length, allocationMode); } /// @@ -52,7 +53,7 @@ namespace ComputeSharp public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, ReadOnlySpan span) where T : unmanaged { - ConstantBuffer buffer = new(device, span.Length); + ConstantBuffer buffer = new(device, span.Length, AllocationMode.Default); buffer.SetData(span); @@ -70,7 +71,7 @@ namespace ComputeSharp public static ConstantBuffer AllocateConstantBuffer(this GraphicsDevice device, Buffer buffer) where T : unmanaged { - ConstantBuffer constantBuffer = new(device, buffer.Length); + ConstantBuffer constantBuffer = new(device, buffer.Length, AllocationMode.Default); constantBuffer.SetData(buffer); @@ -83,12 +84,13 @@ namespace ComputeSharp /// The type of items to store in the buffer. /// The instance to use to allocate the buffer. /// The length of the buffer to allocate. + /// The allocation mode to use for the new resource. /// A zeroed instance of size . [Pure] - public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, int length) + public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, int length, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged { - return new(device, length); + return new(device, length, allocationMode); } /// @@ -116,7 +118,7 @@ namespace ComputeSharp public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, ReadOnlySpan span) where T : unmanaged { - ReadOnlyBuffer buffer = new(device, span.Length); + ReadOnlyBuffer buffer = new(device, span.Length, AllocationMode.Default); buffer.SetData(span); @@ -134,7 +136,7 @@ namespace ComputeSharp public static ReadOnlyBuffer AllocateReadOnlyBuffer(this GraphicsDevice device, Buffer buffer) where T : unmanaged { - ReadOnlyBuffer readWriteBuffer = new(device, buffer.Length); + ReadOnlyBuffer readWriteBuffer = new(device, buffer.Length, AllocationMode.Default); readWriteBuffer.SetData(buffer); @@ -148,12 +150,13 @@ namespace ComputeSharp /// The instance to use to allocate the texture. /// The width of the texture. /// The height of the texture. + /// The allocation mode to use for the new resource. /// A zeroed instance of size [, ]. [Pure] - public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, int width, int height) + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, int width, int height, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged { - return new(device, width, height); + return new(device, width, height, allocationMode); } /// @@ -200,7 +203,7 @@ namespace ComputeSharp public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, T[,] array) where T : unmanaged { - ReadOnlyTexture2D texture = new(device, array.GetLength(1), array.GetLength(0)); + ReadOnlyTexture2D texture = new(device, array.GetLength(1), array.GetLength(0), AllocationMode.Default); texture.SetData(array); @@ -220,7 +223,7 @@ namespace ComputeSharp public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, ReadOnlySpan span, int width, int height) where T : unmanaged { - ReadOnlyTexture2D texture = new(device, width, height); + ReadOnlyTexture2D texture = new(device, width, height, AllocationMode.Default); texture.SetData(span); @@ -235,13 +238,14 @@ namespace ComputeSharp /// The instance to use to allocate the texture. /// The width of the texture. /// The height of the texture. + /// The allocation mode to use for the new resource. /// A zeroed instance of size [, ]. [Pure] - public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, int width, int height) + public static ReadOnlyTexture2D AllocateReadOnlyTexture2D(this GraphicsDevice device, int width, int height, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm where TPixel : unmanaged { - return new(device, width, height); + return new(device, width, height, allocationMode); } /// @@ -294,7 +298,7 @@ namespace ComputeSharp where T : unmanaged, IUnorm where TPixel : unmanaged { - ReadOnlyTexture2D texture = new(device, array.GetLength(1), array.GetLength(0)); + ReadOnlyTexture2D texture = new(device, array.GetLength(1), array.GetLength(0), AllocationMode.Default); texture.SetData(array); @@ -316,7 +320,7 @@ namespace ComputeSharp where T : unmanaged, IUnorm where TPixel : unmanaged { - ReadOnlyTexture2D texture = new(device, width, height); + ReadOnlyTexture2D texture = new(device, width, height, AllocationMode.Default); texture.SetData(span); @@ -331,12 +335,13 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. + /// The allocation mode to use for the new resource. /// A zeroed instance of size [, , ]. [Pure] - public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, int width, int height, int depth) + public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged { - return new(device, width, height, depth); + return new(device, width, height, depth, allocationMode); } /// @@ -389,7 +394,7 @@ namespace ComputeSharp public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, T[,,] array) where T : unmanaged { - ReadOnlyTexture3D texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0)); + ReadOnlyTexture3D texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0), AllocationMode.Default); texture.SetData(array); @@ -410,7 +415,7 @@ namespace ComputeSharp public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, ReadOnlySpan span, int width, int height, int depth) where T : unmanaged { - ReadOnlyTexture3D texture = new(device, width, height, depth); + ReadOnlyTexture3D texture = new(device, width, height, depth, AllocationMode.Default); texture.SetData(span); @@ -426,13 +431,14 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. + /// The allocation mode to use for the new resource. /// A zeroed instance of size [, , ]. [Pure] - public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, int width, int height, int depth) + public static ReadOnlyTexture3D AllocateReadOnlyTexture3D(this GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm where TPixel : unmanaged { - return new(device, width, height, depth); + return new(device, width, height, depth, allocationMode); } /// @@ -491,7 +497,7 @@ namespace ComputeSharp where T : unmanaged, IUnorm where TPixel : unmanaged { - ReadOnlyTexture3D texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0)); + ReadOnlyTexture3D texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0), AllocationMode.Default); texture.SetData(array); @@ -514,7 +520,7 @@ namespace ComputeSharp where T : unmanaged, IUnorm where TPixel : unmanaged { - ReadOnlyTexture3D texture = new(device, width, height, depth); + ReadOnlyTexture3D texture = new(device, width, height, depth, AllocationMode.Default); texture.SetData(span); @@ -527,12 +533,13 @@ namespace ComputeSharp /// The type of items to store in the buffer. /// The instance to use to allocate the buffer. /// The length of the buffer to allocate. + /// The allocation mode to use for the new resource. /// A zeroed instance of size . [Pure] - public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, int length) + public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, int length, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged { - return new(device, length); + return new(device, length, allocationMode); } /// @@ -560,7 +567,7 @@ namespace ComputeSharp public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, ReadOnlySpan span) where T : unmanaged { - ReadWriteBuffer buffer = new(device, span.Length); + ReadWriteBuffer buffer = new(device, span.Length, AllocationMode.Default); buffer.SetData(span); @@ -578,7 +585,7 @@ namespace ComputeSharp public static ReadWriteBuffer AllocateReadWriteBuffer(this GraphicsDevice device, Buffer buffer) where T : unmanaged { - ReadWriteBuffer readWriteBuffer = new(device, buffer.Length); + ReadWriteBuffer readWriteBuffer = new(device, buffer.Length, AllocationMode.Default); readWriteBuffer.SetData(buffer); @@ -592,12 +599,13 @@ namespace ComputeSharp /// The instance to use to allocate the texture. /// The width of the texture. /// The height of the texture. + /// The allocation mode to use for the new resource. /// A zeroed instance of size [, ]. [Pure] - public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, int width, int height) + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, int width, int height, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged { - return new(device, width, height); + return new(device, width, height, allocationMode); } /// @@ -644,7 +652,7 @@ namespace ComputeSharp public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, T[,] array) where T : unmanaged { - ReadWriteTexture2D texture = new(device, array.GetLength(1), array.GetLength(0)); + ReadWriteTexture2D texture = new(device, array.GetLength(1), array.GetLength(0), AllocationMode.Default); texture.SetData(array); @@ -664,7 +672,7 @@ namespace ComputeSharp public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, ReadOnlySpan span, int width, int height) where T : unmanaged { - ReadWriteTexture2D texture = new(device, width, height); + ReadWriteTexture2D texture = new(device, width, height, AllocationMode.Default); texture.SetData(span); @@ -679,13 +687,14 @@ namespace ComputeSharp /// The instance to use to allocate the texture. /// The width of the texture. /// The height of the texture. + /// The allocation mode to use for the new resource. /// A zeroed instance of size [, ]. [Pure] - public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, int width, int height) + public static ReadWriteTexture2D AllocateReadWriteTexture2D(this GraphicsDevice device, int width, int height, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm where TPixel : unmanaged { - return new(device, width, height); + return new(device, width, height, allocationMode); } /// @@ -738,7 +747,7 @@ namespace ComputeSharp where T : unmanaged, IUnorm where TPixel : unmanaged { - ReadWriteTexture2D texture = new(device, array.GetLength(1), array.GetLength(0)); + ReadWriteTexture2D texture = new(device, array.GetLength(1), array.GetLength(0), AllocationMode.Default); texture.SetData(array); @@ -760,7 +769,7 @@ namespace ComputeSharp where T : unmanaged, IUnorm where TPixel : unmanaged { - ReadWriteTexture2D texture = new(device, width, height); + ReadWriteTexture2D texture = new(device, width, height, AllocationMode.Default); texture.SetData(span); @@ -775,12 +784,13 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. + /// The allocation mode to use for the new resource. /// A zeroed instance of size [, ]. [Pure] - public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, int width, int height, int depth) + public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged { - return new(device, width, height, depth); + return new(device, width, height, depth, allocationMode); } /// @@ -833,7 +843,7 @@ namespace ComputeSharp public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, T[,,] array) where T : unmanaged { - ReadWriteTexture3D texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0)); + ReadWriteTexture3D texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0), AllocationMode.Default); texture.SetData(array); @@ -854,7 +864,7 @@ namespace ComputeSharp public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, ReadOnlySpan span, int width, int height, int depth) where T : unmanaged { - ReadWriteTexture3D texture = new(device, width, height, depth); + ReadWriteTexture3D texture = new(device, width, height, depth, AllocationMode.Default); texture.SetData(span); @@ -870,13 +880,14 @@ namespace ComputeSharp /// The width of the texture. /// The height of the texture. /// The depth of the texture. + /// The allocation mode to use for the new resource. /// A zeroed instance of size [, ]. [Pure] - public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, int width, int height, int depth) + public static ReadWriteTexture3D AllocateReadWriteTexture3D(this GraphicsDevice device, int width, int height, int depth, AllocationMode allocationMode = AllocationMode.Default) where T : unmanaged, IUnorm where TPixel : unmanaged { - return new(device, width, height, depth); + return new(device, width, height, depth, allocationMode); } /// @@ -935,7 +946,7 @@ namespace ComputeSharp where T : unmanaged, IUnorm where TPixel : unmanaged { - ReadWriteTexture3D texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0)); + ReadWriteTexture3D texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0), AllocationMode.Default); texture.SetData(array); @@ -958,7 +969,7 @@ namespace ComputeSharp where T : unmanaged, IUnorm where TPixel : unmanaged { - ReadWriteTexture3D texture = new(device, width, height, depth); + ReadWriteTexture3D texture = new(device, width, height, depth, AllocationMode.Default); texture.SetData(span); From 2f6bf05c1b1b8da1df6c2507244f0233042ce129 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 16 Jan 2021 17:24:05 +0100 Subject: [PATCH 55/61] Minor improvement to a benchmark --- samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs index 870b1966..a27608c6 100644 --- a/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Blas/BlasBenchmark.cs @@ -153,7 +153,7 @@ namespace ComputeSharp.Benchmark.Blas using ReadOnlyBuffer x = Gpu.Default.AllocateReadOnlyBuffer(X); using ReadOnlyBuffer w = Gpu.Default.AllocateReadOnlyBuffer(W); using ReadOnlyBuffer b = Gpu.Default.AllocateReadOnlyBuffer(B); - using ReadWriteBuffer y = Gpu.Default.AllocateReadWriteBuffer(Y); + using ReadWriteBuffer y = Gpu.Default.AllocateReadWriteBuffer(Y.Length); BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, x, w, b, y); From 1ed6a4921004bbb973da158c24f8f593290d7355 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Jan 2021 15:34:08 +0100 Subject: [PATCH 56/61] Initial switch to root constants for cbuffer resource --- .../Commands/CommandList.cs | 12 ++++++ .../Extensions/ID3D12DeviceExtensions.cs | 10 +++-- src/ComputeSharp.Shaders/ShaderRunner{T}.cs | 39 ++----------------- .../Translation/Models/DispatchData.cs | 8 ++-- .../ShaderLoader{T}.DispatchData.cs | 2 +- .../Translation/ShaderLoader{T}.cs | 5 --- .../IComputeShaderDataLoaderGenerator.cs | 6 --- 7 files changed, 28 insertions(+), 54 deletions(-) diff --git a/src/ComputeSharp.Graphics/Commands/CommandList.cs b/src/ComputeSharp.Graphics/Commands/CommandList.cs index 58bd809a..3514e5d4 100644 --- a/src/ComputeSharp.Graphics/Commands/CommandList.cs +++ b/src/ComputeSharp.Graphics/Commands/CommandList.cs @@ -154,6 +154,18 @@ namespace ComputeSharp.Graphics.Commands this.d3D12GraphicsCommandList.Get()->ResourceBarrier(1, &d3D12ResourceBarrier); } + /// + /// Binds an input constant buffer to the first root parameter. + /// + /// The input buffer with the constant data to bind. + public readonly unsafe void SetComputeRoot32BitConstants(ReadOnlySpan data) + { + fixed (uint* p = data) + { + this.d3D12GraphicsCommandList.Get()->SetComputeRoot32BitConstants(0, (uint)data.Length, p, 0); + } + } + /// /// Binds an input value to a specified root parameter. /// diff --git a/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs index 88f88aac..da70278e 100644 --- a/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs @@ -28,18 +28,22 @@ namespace ComputeSharp.Shaders.Extensions fixed (D3D12_DESCRIPTOR_RANGE1* d3D12DescriptorRange1 = d3D12DescriptorRanges1) { - D3D12_ROOT_PARAMETER1* d3D12RootParameters1 = stackalloc D3D12_ROOT_PARAMETER1[d3D12DescriptorRanges1.Length]; + D3D12_ROOT_PARAMETER1* d3D12RootParameters1 = stackalloc D3D12_ROOT_PARAMETER1[d3D12DescriptorRanges1.Length + 1]; + + // The initial constant buffer is initialized with 32 bit root constants. + // This avoids having to manage an extra buffer for each shader dispatch. + D3D12_ROOT_PARAMETER1.InitAsConstants(out *d3D12RootParameters1, 3, 0); // TODO: fix length // Pack each descriptor range into a root parameter with that single range as content for (int i = 0; i < d3D12DescriptorRanges1.Length; i++) { - D3D12_ROOT_PARAMETER1.InitAsDescriptorTable(out d3D12RootParameters1[i], 1, d3D12DescriptorRange1 + i); + D3D12_ROOT_PARAMETER1.InitAsDescriptorTable(out d3D12RootParameters1[i + 1], 1, d3D12DescriptorRange1 + i); } // Root signature description wrapping the packed collection of root parameters D3D12_VERSIONED_ROOT_SIGNATURE_DESC.Init_1_1( out D3D12_VERSIONED_ROOT_SIGNATURE_DESC d3D12VersionedRootSignatureDescription, - (uint)d3D12DescriptorRanges1.Length, + (uint)d3D12DescriptorRanges1.Length + 1, d3D12RootParameters1); // Serialize the root signature from the data just computed. When this is done diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs index 57accca0..891b1d50 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -15,32 +15,6 @@ using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; namespace ComputeSharp.Shaders { - /// - /// A with helper methods to support . - /// This type is primarily needed to avoid having fields being repeated per generic instantiation. - /// - internal static class ShaderRunner - { - /// - /// A thread-safe map of reusable GPU buffers for captured locals. - /// - [ThreadStatic] - private static ConditionalWeakTable>? variablesBuffers; - - /// - /// Gets the reusable instance for a shader invocation. - /// - /// The to use to run the shader. - /// The reusable instance to populate. - [Pure] - public static ConstantBuffer GetVariablesBuffer(GraphicsDevice device) - { - ConditionalWeakTable> map = variablesBuffers ??= new(); - - return map.GetValue(device, static gpu => new(gpu, 256, AllocationMode.Default)); - } - } - /// /// A responsible for performing all the necessary operations to compile and run a compute shader. /// @@ -126,22 +100,17 @@ namespace ComputeSharp.Shaders // Extract the dispatch data for the shader invocation using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, z); - // Load the captured buffers + // Initialize the loop targets and the captured values + commandList.SetComputeRoot32BitConstants(dispatchData.Variables); + ReadOnlySpan resources = dispatchData.Resources; for (int i = 0; i < resources.Length; i++) { + // Load the captured buffers commandList.SetComputeRootDescriptorTable(i + 1, resources[i]); } - // Initialize the loop targets and the captured values - ConstantBuffer variablesBuffer = ShaderRunner.GetVariablesBuffer(device); - ReadOnlySpan variables = dispatchData.Variables; - - variablesBuffer.SetData(ref MemoryMarshal.GetReference(variables), variables.Length, 0); - - commandList.SetComputeRootDescriptorTable(0, variablesBuffer.D3D12GpuDescriptorHandle); - // Calculate the dispatch values int groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1), diff --git a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs index fac76157..c47050ba 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs @@ -70,21 +70,21 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// Gets a with the padded data representing all the captured variables. /// - public unsafe ReadOnlySpan Variables + public unsafe ReadOnlySpan Variables { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { #if NET5_0 ref byte r0 = ref MemoryMarshal.GetArrayDataReference(this.variablesArray); - ref Int4 r1 = ref Unsafe.As(ref r0); - int length = (int)((uint)this.variablesByteSize / (uint)sizeof(Int4)); + ref uint r1 = ref Unsafe.As(ref r0); + int length = (int)((uint)this.variablesByteSize / sizeof(uint)); return MemoryMarshal.CreateReadOnlySpan(ref r1, length); #else Span span = this.variablesArray.AsSpan(0, this.variablesByteSize); - return MemoryMarshal.Cast(span); + return MemoryMarshal.Cast(span); #endif } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs index db6b8bef..11d015ef 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs @@ -58,7 +58,7 @@ namespace ComputeSharp.Shaders.Translation { // Resources and variables buffers ulong[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); - byte[] variables = ArrayPool.Shared.Rent(4096); + byte[] variables = ArrayPool.Shared.Rent(256); ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources); ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 1d6f6257..22422117 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -164,11 +164,6 @@ namespace ComputeSharp.Shaders.Translation List d3D12DescriptorRanges1 = new(); - // Descriptor for the buffer for captured scalar/vector variables - D3D12_DESCRIPTOR_RANGE1 d3D12DescriptorRange1 = new(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, this.constantBuffersCount++); - - d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); - // Inspect the captured fields foreach (FieldInfo fieldInfo in shaderFields) { diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 834fb2d9..97a13f72 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -163,12 +163,6 @@ namespace ComputeSharp.SourceGenerators } } - // After all the captured fields have been processed, ansure the reported byte size for - // the local variables is padded to the standard alignment for constant buffers. This is - // necessary to enable loading all the dispatch data after reinterpreting it to a sequence - // of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds. - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - yield return ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset))); } } From 47a5101d7775afaf43ba125219ae38bb7052ed4c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Jan 2021 15:59:35 +0100 Subject: [PATCH 57/61] Fixed root signature initialization with root constant count --- .../ComputeRoot32BitConstantsAttribute.cs | 29 ++++++++++++++ .../IComputeShaderSourceAttribute.cs | 2 +- .../Extensions/ID3D12DeviceExtensions.cs | 4 +- src/ComputeSharp.Shaders/ShaderRunner{T}.cs | 2 +- .../ShaderLoader{T}.DispatchData.cs | 7 ++++ .../Translation/ShaderLoader{T}.cs | 5 +++ .../ComputeSharp.SourceGenerators.csproj | 1 + .../IComputeShaderDataLoaderGenerator.cs | 39 +++++++++++++++---- 8 files changed, 78 insertions(+), 11 deletions(-) create mode 100644 src/ComputeSharp.Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs diff --git a/src/ComputeSharp.Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs new file mode 100644 index 00000000..3277c05b --- /dev/null +++ b/src/ComputeSharp.Core/Attributes/__Internals/ComputeRoot32BitConstantsAttribute.cs @@ -0,0 +1,29 @@ +using System; +using System.ComponentModel; + +namespace ComputeSharp.__Internals +{ + /// + /// An attribute that contains info on the number of 32 bit constants for a given shader. + /// + /// This attribute is not meant to be directly used by applications using ComputeSharp. + [AttributeUsage(AttributeTargets.ReturnValue, AllowMultiple = false)] + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This attribute is not intended to be used directly by user code")] + public sealed class ComputeRoot32BitConstantsAttribute : Attribute + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The number of 32 bit constants for the annotated method. + public ComputeRoot32BitConstantsAttribute(int count) + { + Count = count; + } + + /// + /// Gets the number of 32 bit constants for the annotated method. + /// + internal int Count { get; } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs index 7cd9407c..ce076d16 100644 --- a/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs @@ -25,7 +25,7 @@ namespace ComputeSharp.__Internals /// The source code for the method. /// The collection of processed methods. /// The collection of discovered constants. - /// The collection of group shared buffers + /// The collection of group shared buffers. public IComputeShaderSourceAttribute( string shaderTypeName, string[] types, diff --git a/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs index da70278e..fe254f94 100644 --- a/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/ID3D12DeviceExtensions.cs @@ -15,11 +15,13 @@ namespace ComputeSharp.Shaders.Extensions /// Creates a new for a given device. /// /// The target to use to create the root signature. + /// The number of 32 bit root constants to load. /// The input descriptor ranges for the signature to create. /// A pointer to the newly allocated instance. /// Thrown when the creation of the root signature fails. public static ComPtr CreateRootSignature( this ref ID3D12Device d3D12Device, + int d3D12Root32BitConstantsCount, ReadOnlySpan d3D12DescriptorRanges1) { using ComPtr d3D3Blob = default; @@ -32,7 +34,7 @@ namespace ComputeSharp.Shaders.Extensions // The initial constant buffer is initialized with 32 bit root constants. // This avoids having to manage an extra buffer for each shader dispatch. - D3D12_ROOT_PARAMETER1.InitAsConstants(out *d3D12RootParameters1, 3, 0); // TODO: fix length + D3D12_ROOT_PARAMETER1.InitAsConstants(out *d3D12RootParameters1, (uint)d3D12Root32BitConstantsCount, 0); // Pack each descriptor range into a root parameter with that single range as content for (int i = 0; i < d3D12DescriptorRanges1.Length; i++) diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs index 891b1d50..2bdeef32 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -155,7 +155,7 @@ namespace ComputeSharp.Shaders [MethodImpl(MethodImplOptions.NoInlining)] private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader shaderData, out PipelineData pipelineData) { - using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12DescriptorRanges1); + using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1); using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.Bytecode.D3D12ShaderBytecode); pipelineData = new PipelineData(d3D12RootSignature.Move(), d3D12PipelineState.Move()); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs index 11d015ef..faddec59 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; +using ComputeSharp.__Internals; using ComputeSharp.Shaders.Translation.Models; using TerraFX.Interop; #if NET5_0 @@ -12,6 +13,8 @@ using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal; using MemoryMarshal = Polyfills.MemoryMarshal; #endif +#pragma warning disable CS0618 + namespace ComputeSharp.Shaders.Translation { /// @@ -84,6 +87,10 @@ namespace ComputeSharp.Shaders.Translation Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!; MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!; + // Extract the computed count of 32 bit root constants to load + D3D12Root32BitConstantsCount = ((ComputeRoot32BitConstantsAttribute)method.ReturnTypeCustomAttributes.GetCustomAttributes(false)[0]).Count; + + // Create a delegate from the generated shader data loader this.dispatchDataLoader = method.CreateDelegate(); } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 22422117..b2cdd86d 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -78,6 +78,11 @@ namespace ComputeSharp.Shaders.Translation { } + /// + /// Gets the number of 32 bit constants in the root signature for the shader. + /// + public int D3D12Root32BitConstantsCount { get; private set; } + /// /// Gets a with the loaded items for the shader. /// diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index c49ab22a..724c0a19 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -16,6 +16,7 @@ + diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 97a13f72..028d7ed4 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Text; +using ComputeSharp.__Internals; using ComputeSharp.Core.Helpers; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; @@ -13,6 +14,8 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; +#pragma warning disable CS0618 + namespace ComputeSharp.SourceGenerators { [Generator] @@ -54,7 +57,7 @@ namespace ComputeSharp.SourceGenerators if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); - BlockSyntax block = Block(GetDispatchDataLoadingStatements(structDeclarationSymbol)); + BlockSyntax block = Block(GetDispatchDataLoadingStatements(structDeclarationSymbol, out int root32BitConstantsCount)); // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: @@ -68,6 +71,7 @@ namespace ComputeSharp.SourceGenerators // { // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] // [System.Obsolete("This method is not intended to be called directly by user code")] + // [return: ComputeRoot32BitConstants(42)] // public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1) // { // ... @@ -94,7 +98,13 @@ namespace ComputeSharp.SourceGenerators Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( AttributeArgument(LiteralExpression( SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be called directly by user code"))))))).AddModifiers( + Literal("This method is not intended to be called directly by user code")))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName(nameof(ComputeRoot32BitConstantsAttribute).Replace("Attribute", ""))) + .AddArgumentListArguments(AttributeArgument(LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(root32BitConstantsCount)))))) + .WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.ReturnKeyword)))).AddModifiers( Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.GraphicsDevice")), @@ -118,10 +128,13 @@ namespace ComputeSharp.SourceGenerators /// Gets a sequence of statements to load the dispatch data for a given shader /// /// The input instance to process. + /// The total number of 32 bit root constants to load. /// The sequence of instances to load shader dispatch data. [Pure] - private static IEnumerable GetDispatchDataLoadingStatements(INamedTypeSymbol structDeclarationSymbol) + private static IEnumerable GetDispatchDataLoadingStatements(INamedTypeSymbol structDeclarationSymbol, out int count) { + List statements = new(); + int resourceOffset = 0, rawDataOffset = sizeof(int) * 3; @@ -135,11 +148,11 @@ namespace ComputeSharp.SourceGenerators if (HlslKnownTypes.IsTypedResourceType(typeName)) { - yield return ExpressionStatement( + statements.Add(ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"), - ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)"))); + ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)")))); } else if (HlslKnownTypes.IsScalarOrVectorType(typeName)) { @@ -156,14 +169,24 @@ namespace ComputeSharp.SourceGenerators fieldSize, 16); - yield return ExpressionStatement( - ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})")); + statements.Add(ExpressionStatement( + ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})"))); rawDataOffset += fieldSize; } } - yield return ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset))); + // After all the captured fields have been processed, ansure the reported byte size for + // the local variables is padded to a multiple of a 32 bit value. This is necessary to + // enable loading all the dispatch data after reinterpreting it to a sequence of values + // of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds. + rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int)); + + statements.Add(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset)))); + + count = rawDataOffset / sizeof(int); + + return statements; } } } From 0150402e7fd20858b9186d8ff447039a244ee7b1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 17 Jan 2021 16:50:24 +0100 Subject: [PATCH 58/61] Removed unnecessary using directives --- src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs | 1 - src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs | 1 - src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs | 1 - src/ComputeSharp.Shaders/ShaderRunner{T}.cs | 2 -- 4 files changed, 5 deletions(-) diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs index 7cacdccd..e75240ac 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs @@ -35,7 +35,6 @@ namespace ComputeSharp.Resources /// /// The instance for the current resource. /// - /// This field is dynamically accessed when loading shader dispatch data. internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle; /// diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs index 3b36a343..c4a349c3 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture2D{T}.cs @@ -39,7 +39,6 @@ namespace ComputeSharp.Resources /// /// The instance for the current resource. /// - /// This field is dynamically accessed when loading shader dispatch data. internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle; /// diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs index 35ae7c08..2d0a59ac 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Texture3D{T}.cs @@ -39,7 +39,6 @@ namespace ComputeSharp.Resources /// /// The instance for the current resource. /// - /// This field is dynamically accessed when loading shader dispatch data. internal readonly D3D12_GPU_DESCRIPTOR_HANDLE D3D12GpuDescriptorHandle; /// diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs index 2bdeef32..5a1198c7 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using ComputeSharp.Core.Extensions; using ComputeSharp.Graphics.Commands; using ComputeSharp.Shaders.Extensions; From a855f3a26417a4e71f54fc818dc0ef7d69c0fc50 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 29 Jan 2021 16:20:59 +0100 Subject: [PATCH 59/61] =?UTF-8?q?Removed=20.NET=20Standard=202.0=20target?= =?UTF-8?q?=20(=F0=9F=98=A2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ComputeSharp.Core.csproj | 8 +- .../ID3D12DescriptorHandleAllocator.cs | 3 - .../ComputeSharp.Graphics.csproj | 2 +- .../Properties/Polyfills.cs | 119 ------------------ .../Resources/Abstract/Buffer{T}.cs | 6 +- .../Resources/Views/BufferDebugView{T}.cs | 8 +- .../ComputeSharp.Shaders.csproj | 2 +- .../Properties/Polyfills.cs | 37 ------ .../ShaderLoader{T}.DispatchData.cs | 6 +- src/ComputeSharp/ComputeSharp.csproj | 2 +- .../Extensions/Buffers/BufferExtensions.cs | 5 - .../ComputeSharp.Tests.Internals.csproj | 2 +- .../ComputeSharp.Tests.csproj | 2 +- 13 files changed, 10 insertions(+), 192 deletions(-) delete mode 100644 src/ComputeSharp.Graphics/Properties/Polyfills.cs delete mode 100644 src/ComputeSharp.Shaders/Properties/Polyfills.cs diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index 4df5b272..40f1ef7d 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -1,15 +1,9 @@  - netstandard2.0;net5.0 + net5.0 bin\Release ComputeSharp.Core.xml - - - - - - diff --git a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs index 5b869e48..e0b0c05b 100644 --- a/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs +++ b/src/ComputeSharp.Graphics/Commands/Interop/ID3D12DescriptorHandleAllocator.cs @@ -3,9 +3,6 @@ using ComputeSharp.Graphics.Extensions; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using static TerraFX.Interop.D3D12_DESCRIPTOR_HEAP_TYPE; -#if NETSTANDARD2_0 -using GC = Polyfills.GC; -#endif namespace ComputeSharp.Graphics.Commands.Interop { diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index 96c738d6..c0bde5ee 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -1,7 +1,7 @@  - netstandard2.0;net5.0 + net5.0 bin\Release ComputeSharp.Graphics.xml diff --git a/src/ComputeSharp.Graphics/Properties/Polyfills.cs b/src/ComputeSharp.Graphics/Properties/Polyfills.cs deleted file mode 100644 index cfd91f55..00000000 --- a/src/ComputeSharp.Graphics/Properties/Polyfills.cs +++ /dev/null @@ -1,119 +0,0 @@ -#if NETSTANDARD2_0 - -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace Polyfills -{ - /// - /// A polyfill class for the type. - /// - internal static class GC - { - /// - /// Allocates an array while skipping zero-initialization, if possible. - /// - /// Specifies the type of the array element. - /// Specifies the length of the array. - /// Specifies whether the allocated array must be pinned. - /// An array object with uninitialized memory, if possible. - public static T[] AllocateUninitializedArray(int length, bool pinned = false) - { - return new T[length]; - } - } - - /// - /// A polyfill class for the type. - /// - internal static class MemoryMarshal - { - /// - /// Returns a reference to the 0th element of array. If the array is empty, returns - /// a reference to where the 0th element would have been stored. Such a reference - /// may be used for pinning but must never be dereferenced. - /// - /// The type of the array elements. - /// The array to analyze. - /// Reference to the 0th element in array. - public static ref T GetArrayDataReference(T[] array) - { - IntPtr offset = TypeInfo.ArrayDataByteOffset; - RawObjectData rawObject = Unsafe.As(array)!; - ref byte r0 = ref rawObject.Data; - ref byte r1 = ref Unsafe.AddByteOffset(ref r0, offset); - ref T r2 = ref Unsafe.As(ref r1); - - return ref r2; - } - - /// - /// A private generic class to preload type info for arbitrary runtime types. - /// - /// The type to load info for. - private static class TypeInfo - { - /// - /// The byte offset to the first element in a SZ array. - /// - public static readonly IntPtr ArrayDataByteOffset = MeasureArrayDataByteOffset(); - - /// - /// Computes the value for . - /// - /// The value of for the current runtime. - private static IntPtr MeasureArrayDataByteOffset() - { - T[] array = new T[1]; - RawObjectData rawObject = Unsafe.As(array)!; - ref byte r0 = ref rawObject.Data; - ref byte r1 = ref Unsafe.As(ref array[0]); - - return Unsafe.ByteOffset(ref r0, ref r1); - } - } - - /// - /// Mapping type for a raw object. - /// - [StructLayout(LayoutKind.Explicit)] - private sealed class RawObjectData - { - [FieldOffset(0)] - public byte Data; - } - } -} - -namespace System.Collections.Generic -{ - /// - /// Extensions for the type. - /// - internal static class QueueExtensions - { - /// - /// Removes the object at the beginning of the instance and copies it to the result parameter. - /// - /// The type of values in the input . - /// The input . - /// The removed object. - /// Whether or not the object was successfully removed. - public static bool TryDequeue(this Queue queue, out T? result) - { - if (queue.Count > 0) - { - result = queue.Dequeue(); - - return true; - } - - result = default; - - return false; - } - } -} - -#endif diff --git a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs index e75240ac..744e26ed 100644 --- a/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Abstract/Buffer{T}.cs @@ -1,5 +1,6 @@ using System.Buffers; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using ComputeSharp.Exceptions; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Graphics.Resources.Enums; @@ -7,11 +8,6 @@ using ComputeSharp.Interop; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; -#if NET5_0 -using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal; -#else -using MemoryMarshal = Polyfills.MemoryMarshal; -#endif namespace ComputeSharp.Resources { diff --git a/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs b/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs index bd78980e..2df6d818 100644 --- a/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs +++ b/src/ComputeSharp.Graphics/Resources/Views/BufferDebugView{T}.cs @@ -1,9 +1,5 @@ -using System.Diagnostics; -#if NET5_0 -using GC = System.GC; -#else -using GC = Polyfills.GC; -#endif +using System; +using System.Diagnostics; namespace ComputeSharp.Resources.Views { diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index a0ee85cf..fbf12c54 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -1,7 +1,7 @@  - netstandard2.0;net5.0 + net5.0 bin\Release ComputeSharp.Shaders.xml diff --git a/src/ComputeSharp.Shaders/Properties/Polyfills.cs b/src/ComputeSharp.Shaders/Properties/Polyfills.cs deleted file mode 100644 index 227d8a84..00000000 --- a/src/ComputeSharp.Shaders/Properties/Polyfills.cs +++ /dev/null @@ -1,37 +0,0 @@ -#if NETSTANDARD2_0 - -using System.ComponentModel; - -namespace System.Runtime.CompilerServices -{ - /// - /// Reserved to be used by the compiler for tracking metadata. - /// - [EditorBrowsable(EditorBrowsableState.Never)] - internal static class IsExternalInit - { - } -} - -namespace System.Reflection -{ - /// - /// Extensions for the type. - /// - internal static class MethodInfoExtensions - { - /// - /// Creates a delegate of type T from a given method. - /// - /// The type of delegate to create. - /// The input . - /// The delegate for this method. - public static T CreateDelegate(this MethodInfo method) - where T : Delegate - { - return (T)method.CreateDelegate(typeof(T)); - } - } -} - -#endif diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs index faddec59..2922a85f 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs @@ -4,14 +4,10 @@ using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using ComputeSharp.__Internals; using ComputeSharp.Shaders.Translation.Models; using TerraFX.Interop; -#if NET5_0 -using MemoryMarshal = System.Runtime.InteropServices.MemoryMarshal; -#else -using MemoryMarshal = Polyfills.MemoryMarshal; -#endif #pragma warning disable CS0618 diff --git a/src/ComputeSharp/ComputeSharp.csproj b/src/ComputeSharp/ComputeSharp.csproj index 8f1cc533..c9ab3f20 100644 --- a/src/ComputeSharp/ComputeSharp.csproj +++ b/src/ComputeSharp/ComputeSharp.csproj @@ -1,7 +1,7 @@  - netstandard2.0;net5.0 + net5.0 bin\Release ComputeSharp.xml diff --git a/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs b/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs index 256c57a2..5fe675bc 100644 --- a/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs +++ b/src/ComputeSharp/Extensions/Buffers/BufferExtensions.cs @@ -3,11 +3,6 @@ using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using ComputeSharp.Resources; using Microsoft.Toolkit.Diagnostics; -#if NET5_0 -using GC = System.GC; -#else -using GC = Polyfills.GC; -#endif namespace ComputeSharp { diff --git a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj index 80cda974..0f9fc9f1 100644 --- a/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj +++ b/tests/ComputeSharp.Tests.Internals/ComputeSharp.Tests.Internals.csproj @@ -1,7 +1,7 @@  - netcoreapp2.1;net5.0 + net5.0 false 9.0 diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj index ee76bc48..dcb51fa4 100644 --- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj +++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.1;net5.0 + net5.0 false 9.0 From 0086e44a8c6c83ccae12ed5af817fbe093e57e7d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 29 Jan 2021 16:27:24 +0100 Subject: [PATCH 60/61] Updated package and assembly info --- src/ComputeSharp.Core/ComputeSharp.Core.csproj | 1 + src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj | 1 + src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj | 4 ++-- src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj | 1 + .../ComputeSharp.SourceGenerators.csproj | 4 +--- src/ComputeSharp/ComputeSharp.csproj | 1 + src/Directory.Build.props | 3 +++ 7 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.Core/ComputeSharp.Core.csproj b/src/ComputeSharp.Core/ComputeSharp.Core.csproj index 40f1ef7d..b2374d22 100644 --- a/src/ComputeSharp.Core/ComputeSharp.Core.csproj +++ b/src/ComputeSharp.Core/ComputeSharp.Core.csproj @@ -4,6 +4,7 @@ net5.0 bin\Release ComputeSharp.Core.xml + ComputeSharp.Core diff --git a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj index c0bde5ee..203d2f59 100644 --- a/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj +++ b/src/ComputeSharp.Graphics/ComputeSharp.Graphics.csproj @@ -4,6 +4,7 @@ net5.0 bin\Release ComputeSharp.Graphics.xml + ComputeSharp.Graphics diff --git a/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj b/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj index d14cc0c8..20cce1e3 100644 --- a/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj +++ b/src/ComputeSharp.Package/ComputeSharp.Package.msbuildproj @@ -5,14 +5,14 @@ ComputeSharp - A .NET 5 library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders + A library to run C# code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders New interlocked intrinsics APIs, performance and memory optimizations 2.0.0 https://github.com/Sergio0694/ComputeSharp.git https://github.com/Sergio0694/ComputeSharp Sergio Pedri Sergio Pedri - Copyright (c) 2020 Sergio Pedri + Copyright (c) 2021 Sergio Pedri MIT false https://i.imgur.com/ntvmD6P.png diff --git a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj index fbf12c54..f22b6583 100644 --- a/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj +++ b/src/ComputeSharp.Shaders/ComputeSharp.Shaders.csproj @@ -4,6 +4,7 @@ net5.0 bin\Release ComputeSharp.Shaders.xml + ComputeSharp.Shaders diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 724c0a19..109a36c2 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -2,11 +2,9 @@ netstandard2.0 - - - analyzers\dotnet\cs false + ComputeSharp.SourceGenerators