Merge pull request #613 from Sergio0694/dev/remove-metaprogramming

Remove shader metaprogramming and dynamic compilation (DX12)
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-10-13 19:45:32 +02:00
コミット bbdacca5cf
100ファイル変更
+244 -1852

検索条件に一致するファイルはありません

+1
ファイルの表示
@@ -81,6 +81,7 @@ internal static partial class BlasHelpers
/// Kernel for <see cref="FullyConnectedForwardGpu"/>.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
public readonly partial struct FullyConnectedForwardKernel : IComputeShader
{
private readonly int n;
-1
ファイルの表示
@@ -28,7 +28,6 @@
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
</ItemGroup>
</Project>
+1
ファイルの表示
@@ -109,6 +109,7 @@ public partial class DispatchingBenchmark : IDisposable
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct TestShader : IComputeShader
{
private readonly ReadWriteBuffer<float> buffer;
-1
ファイルの表示
@@ -19,7 +19,6 @@
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
</ItemGroup>
</Project>
+4
ファイルの表示
@@ -314,6 +314,7 @@ public sealed partial class HlslBokehBlurProcessor
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
{
private readonly IReadWriteNormalizedTexture2D<float4> source;
@@ -351,6 +352,7 @@ public sealed partial class HlslBokehBlurProcessor
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
{
private readonly float z;
@@ -390,6 +392,7 @@ public sealed partial class HlslBokehBlurProcessor
/// Kernel for the gamma highlight pass.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct GammaHighlightProcessor : IComputeShader
{
private readonly IReadWriteNormalizedTexture2D<float4> source;
@@ -414,6 +417,7 @@ public sealed partial class HlslBokehBlurProcessor
/// Kernel for the inverse gamma highlight pass.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader
{
private readonly ReadWriteTexture2D<float4> source;
@@ -118,6 +118,7 @@ public sealed partial class HlslGaussianBlurProcessor
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
{
private readonly IReadWriteNormalizedTexture2D<float4> source;
@@ -150,6 +151,7 @@ public sealed partial class HlslGaussianBlurProcessor
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
{
private readonly IReadWriteNormalizedTexture2D<float4> source;
@@ -8,7 +8,6 @@
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
</ItemGroup>
</Project>
+1
ファイルの表示
@@ -4,6 +4,7 @@ namespace ComputeSharp.Sample.FSharp.Shaders;
/// A sample shader thaat just multiplies items in a buffer by two.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct MultiplyByTwo : IComputeShader
{
private readonly ReadWriteBuffer<float> buffer;
-1
ファイルの表示
@@ -19,7 +19,6 @@
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\ComputeSharp.Sample.FSharp.Shaders\ComputeSharp.Sample.FSharp.Shaders.csproj" />
</ItemGroup>
-1
ファイルの表示
@@ -10,7 +10,6 @@
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
</ItemGroup>
</Project>
+1
ファイルの表示
@@ -24,6 +24,7 @@ Formatting.PrintMatrix(array, 10, 10, "AFTER");
/// The sample kernel that multiples all items by two.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct MultiplyByTwo : IComputeShader
{
private readonly ReadWriteBuffer<float> buffer;
-1
ファイルの表示
@@ -10,7 +10,6 @@
<OutputType Condition="'$(CI_RUNNER_SAMPLES_INTEGRATION_TESTS)' != 'true'">WinExe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<Platforms>x64;ARM64</Platforms>
<DefineConstants>$(DefineConstants);SAMPLE_APP</DefineConstants>
<NoWarn>$(NoWarn);CA1416</NoWarn>
<AssemblyName>computesharp.cli</AssemblyName>
-2
ファイルの表示
@@ -7,9 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct ColorfulInfinity : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct ContouredLayers : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct ExtrudedTruchetPattern : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -7,9 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct FourColorGradient : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -7,9 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct FractalTiling : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -5,9 +5,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// Ported from <see href="https://www.shadertoy.com/new"/>.
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct HelloWorld : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>Created by Syntopia.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct MengerJourney : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>Created by whisky_shusuky.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct Octagrams : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -7,9 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct ProteanClouds : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -7,9 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct PyramidPattern : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct TerracedHills : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct TriangleGridContouring : IPixelShader<float4>
{
/// <summary>
-2
ファイルの表示
@@ -6,9 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
#if SAMPLE_APP
[EmbeddedBytecode(DispatchAxis.XY)]
#endif
internal readonly partial struct TwoTiledTruchet : IPixelShader<float4>
{
/// <summary>
-1
ファイルの表示
@@ -10,7 +10,6 @@
<PublishProfile>win10-$(Platform).pubxml</PublishProfile>
<UseWinUI>true</UseWinUI>
<EnableMsixTooling>true</EnableMsixTooling>
<DefineConstants>$(DefineConstants);SAMPLE_APP</DefineConstants>
</PropertyGroup>
<ItemGroup>
-1
ファイルの表示
@@ -3,7 +3,6 @@
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Platforms>x64;ARM64</Platforms>
<DefineConstants>$(DefineConstants);SAMPLE_APP</DefineConstants>
<NoWarn>$(NoWarn);CA1416;IDE0210</NoWarn>
</PropertyGroup>
-39
ファイルの表示
@@ -1,39 +0,0 @@
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace ComputeSharp.Extensions;
/// <summary>
/// A <see langword="class"/> that provides extension methods for the <see cref="MethodInfo"/> type.
/// </summary>
internal static class MethodInfoExtensions
{
/// <summary>
/// Gets a fully qualified name for the input method, including parameters.
/// </summary>
/// <param name="method">The input <see cref="MethodInfo"/> instance.</param>
/// <returns>A fully qualified name for <paramref name="method"/>, including parameters.</returns>
public static string GetFullyQualifiedName(this MethodInfo method)
{
string parameters = string.Join(", ", method.GetParameters().Select(static p => p.ParameterType.FullName));
// Fixup the method name for static local functions in global statements. This only needs to
// be done when the method is in a type with fully qualified name "Program", as that's the only
// case where it might happen. If the declaring type has a name, it can't be that for sure.
(string declaringType, string methodName) = (method.DeclaringType!.FullName!, method.Name) switch
{
("Program", var name) => ("Program", Regex.Replace(name, @"<<Main>\$>g__(\w+)\|\d+_\d+", static m => m.Groups[1].Value)),
(var type, var name) => (type, name)
};
if (method.IsGenericMethod)
{
string arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName));
return $"{declaringType}.{methodName}<{arguments}>({parameters})";
}
return $"{declaringType}.{methodName}({parameters})";
}
}
-21
ファイルの表示
@@ -1,21 +0,0 @@
using System;
using System.ComponentModel;
namespace ComputeSharp;
/// <summary>
/// An attribute that indicates that a method will be indirectly used in a compute shader.
/// This method is necessary for methods that are captured and used within a given shader
/// through a <see cref="Delegate"/> field (of some custom type). In order to be processed
/// 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.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete(
"This API (and shader metaprogramming in general) is being removed in a future version of ComputeSharp. " +
"If you're relying on this functionality, consider manually implementing different shader variants. " +
"It is possible to still reuse code by moving it to helper methods that are used by multiple shaders.")]
public sealed class ShaderMethodAttribute : Attribute
{
}
@@ -1,93 +0,0 @@
using System;
using System.Collections.Generic;
namespace ComputeSharp.__Internals;
/// <inheritdoc/>
partial class ShaderMethodSourceAttribute : Attribute
{
/// <summary>
/// Appends the mapped source code for the current method.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
/// <param name="mapping">The mapping of already discovered constant names.</param>
public void AppendConstants(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
{
foreach (KeyValuePair<string, string> constant in this.constants)
{
if (mapping.Add(constant.Key))
{
builder.Append('\n');
builder.Append("#define ");
builder.Append(constant.Key);
builder.Append(' ');
builder.Append(constant.Value);
builder.Append('\n');
}
}
}
/// <summary>
/// Appends the discovered types for the current method.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
/// <param name="mapping">The mapping of already discovered type names.</param>
public void AppendTypes(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
{
foreach (KeyValuePair<string, string> type in this.types)
{
if (mapping.Add(type.Key))
{
builder.Append('\n');
builder.Append(type.Value);
builder.Append('\n');
}
}
}
/// <summary>
/// Appends the discovered forward declarations for the current method.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
/// <param name="mapping">The mapping of already discovered type names.</param>
public void AppendForwardDeclarations(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
{
foreach (KeyValuePair<string, string> method in this.methods)
{
if (mapping.Add(method.Key))
{
builder.Append('\n');
builder.Append(method.Key);
builder.Append('\n');
}
}
}
/// <summary>
/// Appends the discovered methods for the current method.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
/// <param name="mapping">The mapping of already discovered type names.</param>
public void AppendMethods(ref ArrayPoolStringBuilder builder, HashSet<string> mapping)
{
foreach (KeyValuePair<string, string> method in this.methods)
{
if (mapping.Remove(method.Key))
{
builder.Append('\n');
builder.Append(method.Value);
builder.Append('\n');
}
}
}
/// <summary>
/// Appends the mapped source code for the current method.
/// </summary>
/// <param name="builder">The target <see cref="ArrayPoolStringBuilder"/> instance to write to.</param>
/// <param name="name">The name to bind the method to.</param>
public void AppendMappedInvokeMethod(ref ArrayPoolStringBuilder builder, string name)
{
builder.Append(this.invokeMethod.Replace(InvokeMethodIdentifier, name));
}
}
-113
ファイルの表示
@@ -1,113 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using ComputeSharp.Extensions;
#pragma warning disable IDE0052
namespace ComputeSharp.__Internals;
/// <summary>
/// An attribute that contains info on a processed shader method that can be executed within a shader.
/// Instances of this attribute are generated from method annotated with <see cref="ShaderMethodAttribute"/>.
/// </summary>
/// <remarks>This attribute is not meant to be directly used by applications using ComputeSharp.</remarks>
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This attribute is not intended to be used directly by user code")]
public sealed partial class ShaderMethodSourceAttribute : Attribute
{
/// <summary>
/// The identifier for the invoke method, for late binding.
/// </summary>
internal const string InvokeMethodIdentifier = "__<NAME>__";
/// <summary>
/// The fully qualified name of the current method.
/// </summary>
private readonly string methodName;
/// <summary>
/// The source code for the target entry point method.
/// </summary>
private readonly string invokeMethod;
/// <summary>
/// The collection of custom types.
/// </summary>
private readonly Dictionary<string, string> types;
/// <summary>
/// The collection of processed methods.
/// </summary>
private readonly Dictionary<string, string> methods;
/// <summary>
/// The collection of discovered constants.
/// </summary>
private readonly Dictionary<string, string> constants;
/// <summary>
/// Creates a new <see cref="ShaderMethodSourceAttribute"/> instance with the specified parameters.
/// </summary>
/// <param name="methodName">The fully qualified name of the current method.</param>
/// <param name="invokeMethod">The source code for the target entry point method.</param>
/// <param name="types">The collection of custom types.</param>
/// <param name="methods">The collection of processed methods.</param>
/// <param name="constants">The collection of discovered constants.</param>
public ShaderMethodSourceAttribute(string methodName, string invokeMethod, object[] types, object[] methods, object[] constants)
{
this.methodName = methodName;
this.invokeMethod = invokeMethod;
this.types = types.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
this.methods = methods.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
this.constants = constants.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
}
/// <summary>
/// Gets the associated <see cref="ShaderMethodSourceAttribute"/> instance for a specified delegate.
/// </summary>
/// <param name="function">The input <see cref="Delegate"/> instance to get info for.</param>
/// <param name="name">The name of the shader field containing <paramref name="function"/>.</param>
/// <returns>The associated <see cref="ShaderMethodSourceAttribute"/> instance for the given delegate.</returns>
public static ShaderMethodSourceAttribute GetForDelegate(Delegate function, string name)
{
if (!function.Method.IsStatic)
{
return ThrowArgumentExceptionForNonStaticMethod(name);
}
IEnumerable<ShaderMethodSourceAttribute> attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes<ShaderMethodSourceAttribute>();
string methodName = function.Method.GetFullyQualifiedName();
foreach (ShaderMethodSourceAttribute attribute in attributes)
{
if (attribute.methodName.Equals(methodName))
{
return attribute;
}
}
return ThrowArgumentExceptionForMissingShaderMethodAttribute(name);
}
/// <summary>
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> is not static.
/// </summary>
/// <param name="name">The name of the shader field containing the invalid method.</param>
private static ShaderMethodSourceAttribute ThrowArgumentExceptionForNonStaticMethod(string name)
{
throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a non static method (only static methods are supported for captured delegates).", name);
}
/// <summary>
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> doesn't have <see cref="ShaderMethodAttribute"/> applied to it.
/// </summary>
/// <param name="name">The name of the shader field containing the invalid method.</param>
private static ShaderMethodSourceAttribute ThrowArgumentExceptionForMissingShaderMethodAttribute(string name)
{
throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a method without the [ShaderMethod] attribute applied to it.", name);
}
}
+3 -5
ファイルの表示
@@ -104,11 +104,9 @@ public static class ReflectionServices
private static unsafe ShaderInfo GetNonGenericShaderInfo<T>(in T shader)
where T : struct, IShader
{
Unsafe.AsRef(in shader).BuildHlslSource(out ArrayPoolStringBuilder shaderSource, 1, 1, 1);
Unsafe.AsRef(in shader).BuildHlslSource(out string hlslSource);
using ComPtr<IDxcBlob> dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(shaderSource.WrittenSpan);
shaderSource.Dispose();
using ComPtr<IDxcBlob> dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(hlslSource);
using ComPtr<IDxcUtils> dxcUtils = default;
@@ -134,7 +132,7 @@ public static class ReflectionServices
return new(
CompilerVersion: new string(d3D12ShaderDescription.Creator),
HlslSource: shaderSource.WrittenSpan.ToString(),
HlslSource: hlslSource,
ConstantBufferCount: d3D12ShaderDescription.ConstantBuffers,
BoundResourceCount: d3D12ShaderDescription.BoundResources,
InstructionCount: d3D12ShaderDescription.InstructionCount,
-38
ファイルの表示
@@ -1,38 +0,0 @@
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
namespace ComputeSharp.__Internals;
/// <summary>
/// A <see langword="class"/> that uses the DXC APIs to compile compute shaders.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This type is not intended to be used directly by user code")]
public static class ShaderCompiler
{
/// <summary>
/// Compiles a new HLSL shader from the input source code.
/// </summary>
/// <typeparam name="TLoader">The type of bytecode loader being used.</typeparam>
/// <typeparam name="T">The type of shader being dispatched.</typeparam>
/// <param name="loader">The <typeparamref name="TLoader"/> instance to use to load the bytecode.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="shader">The input <typeparamref name="T"/> instance representing the compute shader to run.</param>
public static unsafe void LoadDynamicBytecode<TLoader, T>(ref TLoader loader, int threadsX, int threadsY, int threadsZ, in T shader)
where TLoader : struct, IBytecodeLoader
where T : struct, IShader
{
Unsafe.AsRef(in shader).BuildHlslSource(out ArrayPoolStringBuilder builder, threadsX, threadsY, threadsZ);
using ComPtr<IDxcBlob> dxcBlobBytecode = Shaders.Translation.ShaderCompiler.Instance.Compile(builder.WrittenSpan);
builder.Dispose();
loader.LoadDynamicBytecode((IntPtr)dxcBlobBytecode.Get());
}
}
-1
ファイルの表示
@@ -49,7 +49,6 @@ CMPS0039 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Ser
CMPS0040 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0041 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
-3
ファイルの表示
@@ -57,9 +57,6 @@
<!-- ComputeSharp APIs -->
<Compile Include="..\ComputeSharp\Core\Attributes\EmbeddedBytecodeAttribute.cs" Link="ComputeSharp\Core\Attributes\EmbeddedBytecodeAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\GroupSharedAttribute.cs" Link="ComputeSharp\Core\Attributes\GroupSharedAttribute.cs" />
<Compile Include="..\ComputeSharp.Dynamic\Attributes\ShaderMethodAttribute.cs" Link="ComputeSharp\Core\Attributes\ShaderMethodAttribute.cs" />
<Compile Include="..\ComputeSharp.Dynamic\Attributes\__Internals\ShaderMethodSourceAttribute.cs" Link="ComputeSharp\Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" />
<Compile Include="..\ComputeSharp.Dynamic\Attributes\Extensions\MethodInfoExtensions.cs" Link="ComputeSharp\Extensions\MethodInfoExtensions.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\DispatchAxis.cs" Link="ComputeSharp\Core\Dispatch\DispatchAxis.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\DispatchSize.cs" Link="ComputeSharp\Core\Dispatch\DispatchSize.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\GridIds.cs" Link="ComputeSharp\Core\Dispatch\GridIds.cs" />
-16
ファイルの表示
@@ -586,22 +586,6 @@ partial class DiagnosticDescriptors
description: "A shader type cannot implement more than one shader interface.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a dynamic shader annotated as an embedded bytecode.
/// <para>
/// Format: <c>"The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor EmbeddedBytecodeWithDynamicShader = new DiagnosticDescriptor(
id: "CMPS0043",
title: "Embedded bytecode for dynamic shader",
messageFormat: "The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)",
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A shader type cannot be precompiled if it captures one or more delegate values.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an embedded bytecode shader with invalid thread ids values.
/// <para>
-41
ファイルの表示
@@ -1,41 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators.Helpers;
/// <summary>
/// A class containing additional factory methods for constructing syntax nodes, tokens and trivia.
/// </summary>
internal static class SyntaxFactoryHelper
{
/// <summary>
/// Creates an <see cref="object"/>[] array expression with the nested groups in the input sequence.
/// <para>
/// That it, it applies the following transformation:
/// <code>
/// { ("K1", "V1"), ("K2", "V2") } => new object[] { new string[] { "K1", "V1" }, new string[] { "K2", "V2" } }
/// </code>
/// </para>
/// </summary>
/// <param name="groups">The input sequence of <see cref="string"/> groups.</param>
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B)> groups)
{
return
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ObjectKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(groups.Select(static group =>
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
.AddExpressions(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.A)),
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(group.B))))).ToArray()));
}
}
+9 -251
ファイルの表示
@@ -1,6 +1,3 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGenerators.Models;
@@ -23,21 +20,18 @@ partial class IShaderGenerator
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslSource</c> method.
/// </summary>
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <param name="hierarchyDepth">The depth of the hierarchy for this type (used to calculate the right indentation).</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslSource</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, bool supportsDynamicShaders, int hierarchyDepth)
public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth)
{
// Generate the necessary body statements depending on whether dynamic shaders are supported
ImmutableArray<StatementSyntax> bodyStatements = supportsDynamicShaders
? GenerateRenderMethodBody(hlslSourceInfo, hierarchyDepth)
: GenerateEmptyMethodBody();
// The indentation level is the current depth + 2 (the method, and the return expression)
SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSourceInfo.HlslSource, hierarchyDepth + 2);
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ)
// readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out string hlslSource)
// {
// <BODY>
// hlslSource = <HLSL_SOURCE>;
// }
return
MethodDeclaration(
@@ -46,249 +40,13 @@ partial class IShaderGenerator
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddParameterListParameters(
Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")),
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.WithBody(Block(bodyStatements));
}
/// <summary>
/// Produces the series of statements for the empty fallback method.
/// </summary>
/// <returns>A series of statements for when dynamic shaders are not supported.</returns>
private static ImmutableArray<StatementSyntax> GenerateEmptyMethodBody()
{
// builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(0);
return
ImmutableArray.Create<StatementSyntax>(
Parameter(Identifier("hlslSource")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(PredefinedType(Token(SyntaxKind.StringKeyword))))
.WithBody(Block(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("builder"),
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"),
IdentifierName("Create")))
.AddArgumentListArguments(
Argument(LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0)))))));
}
/// <summary>
/// Produces the series of statements to build the current HLSL source.
/// </summary>
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
/// <param name="hierarchyDepth">The depth of the hierarchy for this type (used to calculate the right indentation).</param>
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static ImmutableArray<StatementSyntax> GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth)
{
using ImmutableArrayBuilder<StatementSyntax> statements = new();
StringBuilder textBuilder = new();
int capturedDelegates = 0;
int prologueStatements = 0;
int sizeHint = 64;
void AppendLF()
{
_ = textBuilder.Append('\n');
}
void AppendLine(string text)
{
_ = textBuilder.Append(text);
}
void AppendParsedStatement(string text)
{
FlushText();
statements.Add(ParseStatement(text));
}
void FlushText()
{
if (textBuilder.Length > 0)
{
string hlslSource = textBuilder.ToString();
_ = textBuilder.Append(hlslSource);
sizeHint += textBuilder.Length;
// The indentation level is the current depth + 2 (the method, and the return expression)
SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSource, hierarchyDepth + 2);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression)))));
_ = textBuilder.Clear();
}
}
// Declare the hashsets to track imported members and types from delegates, if needed
if (!hlslSourceInfo.Delegates.IsEmpty)
{
void DeclareMapping(int index, string name, IEnumerable<string> items)
{
// global::System.Collections.Generic.HashSet<string> <NAME> = new();
statements.Insert(index,
LocalDeclarationStatement(VariableDeclaration(
GenericName(Identifier("global::System.Collections.Generic.HashSet"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword))))
.AddVariables(
VariableDeclarator(Identifier(name))
.WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))));
prologueStatements++;
// <NAME>.Add("<ITEM>");
foreach (string item in items)
{
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(name),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))))));
prologueStatements++;
}
}
DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes);
DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants);
DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures);
// Go through all existing delegate fields, if any
foreach (string fieldName in hlslSourceInfo.Delegates)
{
// global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __<DELEGATE_NAME>Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(<DELEGATE_NAME>, "<DELEGATE_NAME>");
statements.Add(
LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"))
.AddVariables(
VariableDeclarator(Identifier($"__{fieldName}Attribute"))
.WithInitializer(
EqualsValueClause(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"),
IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate))))
.AddArgumentListArguments(
Argument(IdentifierName(fieldName)),
Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName)))))))));
capturedDelegates++;
prologueStatements++;
}
}
// Header and thread ids
AppendLine(hlslSourceInfo.HeaderAndThreadsX);
AppendParsedStatement("builder.Append(threadsX);");
AppendLine(hlslSourceInfo.ThreadsY);
AppendParsedStatement("builder.Append(threadsY);");
AppendLine(hlslSourceInfo.ThreadsZ);
AppendParsedStatement("builder.Append(threadsZ);");
// Define declarations
AppendLine(hlslSourceInfo.Defines);
// Defines from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
}
// Static fields and declared types
AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes);
// Declared types from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
}
// Captured variables
AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations);
// Forward declarations from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);");
}
// Remove all forward declarations from methods that are embedded into the shader.
// This is necessary to avoid duplicate definitions from methods from delegates.
if (capturedDelegates > 0)
{
// <NAME>.Add("<ITEM>");
foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures)
{
FlushText();
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("__methodNames"),
IdentifierName("Remove")))
.AddArgumentListArguments(Argument(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
}
}
// Captured methods
AppendLine(hlslSourceInfo.CapturedMethods);
// Captured methods from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
}
// Captured delegate methods
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendLF();
AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
AppendLF();
}
// Entry point
AppendLine(hlslSourceInfo.EntryPoint);
FlushText();
// builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(<SIZE_HINT>);
statements.Insert(
prologueStatements,
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("builder"),
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"),
IdentifierName("Create")))
.AddArgumentListArguments(
Argument(LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(sizeHint)))))));
return statements.ToImmutable();
IdentifierName("hlslSource"),
LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression)))));
}
}
}
+18 -63
ファイルの表示
@@ -15,8 +15,6 @@ using Microsoft.CodeAnalysis.CSharp.Syntax;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
@@ -34,12 +32,16 @@ partial class IShaderGenerator
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="threadIds">The info on the shader thread count size to use.</param>
/// <param name="isImplicitTextureUsed">Indicates whether the current shader uses an implicit texture.</param>
/// <returns>The resulting info on the processed shader.</returns>
public static HlslShaderSourceInfo GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
Compilation compilation,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol)
INamedTypeSymbol structDeclarationSymbol,
ThreadIdsInfo threadIds,
out bool isImplicitTextureUsed)
{
// Detect invalid properties
DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol);
@@ -62,7 +64,6 @@ partial class IShaderGenerator
bool isComputeShader = pixelShaderSymbol is null;
string? implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
(ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, ImmutableArray<(string Name, string HlslType)> valueFields) = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader);
ImmutableArray<string> delegateInstanceFields = GetDispatchId.GetInfo(structDeclarationSymbol);
ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes);
(string entryPoint, ImmutableArray<(string Signature, string Definition)> processedMethods, bool isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, isComputeShader);
(string, string)? implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
@@ -72,13 +73,16 @@ partial class IShaderGenerator
ImmutableArray<(string Name, string Definition)> declaredTypes = GetDeclaredTypes(diagnostics, structDeclarationSymbol, discoveredTypes, instanceMethods);
ImmutableArray<(string Name, string Value)> definedConstants = GetDefinedConstants(constantDefinitions);
// Check whether an implicit texture is used in the shader
isImplicitTextureUsed = implicitTextureType is not null;
// Get the HLSL source data with the intermediate info
return GetHlslSourceInfo(
threadIds,
definedConstants,
declaredTypes,
resourceFields,
valueFields,
delegateInstanceFields,
staticFields,
sharedBuffers,
processedMethods,
@@ -423,7 +427,7 @@ partial class IShaderGenerator
/// </summary>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of discovered constants to declare in the shader.</returns>
internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
private static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary<IFieldSymbol, string> constantDefinitions)
{
using ImmutableArrayBuilder<(string, string)> builder = new();
@@ -446,7 +450,7 @@ partial class IShaderGenerator
/// <param name="types">The sequence of discovered custom types.</param>
/// <param name="instanceMethods">The collection of discovered instance methods for custom struct types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
private static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
ISymbol sourceSymbol,
IEnumerable<INamedTypeSymbol> types,
@@ -540,11 +544,11 @@ partial class IShaderGenerator
/// <summary>
/// Produces the series of statements to build the current HLSL source.
/// </summary>
/// <param name="threadIds">The info on the shader thread count size to use.</param>
/// <param name="definedConstants">The sequence of defined constants for the shader.</param>
/// <param name="declaredTypes">The sequence of declared types used by the shader.</param>
/// <param name="resourceFields">The sequence of resource instance fields for the current shader.</param>
/// <param name="valueFields">The sequence of value instance fields for the current shader.</param>
/// <param name="delegateInstanceFields">The sequence of delegate fields for the current shader.</param>
/// <param name="staticFields">The sequence of static fields referenced by the shader.</param>
/// <param name="sharedBuffers">The sequence of shared buffers declared by the shader.</param>
/// <param name="processedMethods">The sequence of processed methods used by the shader.</param>
@@ -554,11 +558,11 @@ partial class IShaderGenerator
/// <param name="executeMethod">The body of the entry point of the shader.</param>
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static HlslShaderSourceInfo GetHlslSourceInfo(
ThreadIdsInfo threadIds,
ImmutableArray<(string Name, string Value)> definedConstants,
ImmutableArray<(string Name, string Definition)> declaredTypes,
ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields,
ImmutableArray<(string Name, string HlslType)> valueFields,
ImmutableArray<string> delegateInstanceFields,
ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers,
ImmutableArray<(string Signature, string Definition)> processedMethods,
@@ -610,20 +614,11 @@ partial class IShaderGenerator
// Group size constants
AppendLF();
AppendLine("#define __GroupSize__get_X ");
string headerAndThreadsX = FlushText();
AppendLF();
AppendLineAndLF(threadIds.X.ToString());
AppendLine("#define __GroupSize__get_Y ");
string threadsY = FlushText();
AppendLF();
AppendLineAndLF(threadIds.Y.ToString());
AppendLine("#define __GroupSize__get_Z ");
string threadsZ = FlushText();
AppendLF();
AppendLineAndLF(threadIds.Z.ToString());
// Define declarations
foreach ((string name, string value) in definedConstants)
@@ -631,8 +626,6 @@ partial class IShaderGenerator
AppendLineAndLF($"#define {name} {value}");
}
string defines = FlushText();
// Static fields
if (staticFields.Any())
{
@@ -658,8 +651,6 @@ partial class IShaderGenerator
AppendLineAndLF(typeDefinition);
}
string staticFieldsAndDeclaredTypes = FlushText();
// Captured variables
AppendLF();
AppendLineAndLF("cbuffer _ : register(b0)");
@@ -737,8 +728,6 @@ partial class IShaderGenerator
AppendLineAndLF(forwardDeclaration);
}
string capturedFieldsAndResourcesAndForwardDeclarations = FlushText();
// Captured methods
foreach ((string _, string method) in processedMethods)
{
@@ -746,48 +735,14 @@ partial class IShaderGenerator
AppendLineAndLF(method);
}
string capturedMethods = FlushText();
// Entry point
AppendLF();
AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
AppendLineAndLF(executeMethod);
string entryPoint = FlushText();
string hlslSource = FlushText();
return new(
headerAndThreadsX,
threadsY,
threadsZ,
defines,
staticFieldsAndDeclaredTypes,
capturedFieldsAndResourcesAndForwardDeclarations,
capturedMethods,
entryPoint,
implicitTextureType,
isSamplerUsed,
declaredTypes.Select(static t => t.Name).ToImmutableArray(),
definedConstants.Select(static c => c.Name).ToImmutableArray(),
processedMethods.Select(static m => m.Signature).ToImmutableArray(),
delegateInstanceFields);
}
/// <summary>
/// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks).
/// </summary>
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
/// <returns>The non dynamic HLSL source code.</returns>
public static string GetNonDynamicHlslSource(HlslShaderSourceInfo hlslSourceInfo)
{
return
hlslSourceInfo.HeaderAndThreadsX + "<THREADSX>" +
hlslSourceInfo.ThreadsY + "<THREADSY>" +
hlslSourceInfo.ThreadsZ + "<THREADSZ>" +
hlslSourceInfo.Defines +
hlslSourceInfo.StaticFieldsAndDeclaredTypes +
hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations +
hlslSourceInfo.CapturedMethods +
hlslSourceInfo.EntryPoint;
return new(hlslSource, isSamplerUsed);
}
}
}
@@ -1,97 +0,0 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.__Internals;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
partial class IShaderGenerator
{
/// <inheritdoc/>
partial class GetDispatchId
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
/// </summary>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(ImmutableArray<string> delegateFieldNames)
{
// This code produces a method declaration as follows:
//
// readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId()
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("GetDispatchId"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.WithBody(GetShaderHashCodeBody(delegateFieldNames));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// </summary>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray<string> delegateFieldNames)
{
if (delegateFieldNames.Length == 0)
{
// return 0;
return
Block(ReturnStatement(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))));
}
List<StatementSyntax> blockStatements = new(4)
{
// global::System.HashCode hashCode = default;
LocalDeclarationStatement(
VariableDeclaration(IdentifierName("global::System.HashCode"))
.AddVariables(
VariableDeclarator(Identifier("hashCode"))
.WithInitializer(EqualsValueClause(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword))))))
};
foreach (string fieldName in delegateFieldNames)
{
// hashCode.Add(delegateField.Method);
blockStatements.Add(ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(fieldName),
IdentifierName("Method"))))));
}
// return hashCode.ToHashCode();
blockStatements.Add(ReturnStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("ToHashCode")))));
return Block(blockStatements);
}
}
}
-31
ファイルの表示
@@ -1,31 +0,0 @@
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
partial class IShaderGenerator
{
/// <summary>
/// A helper with all logic to generate the <c>GetDispatchId</c> method.
/// </summary>
private static partial class GetDispatchId
{
/// <summary>
/// Extracts the names of all instance fields of a <see cref="System.Delegate"/> type.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The names of all <see cref="System.Delegate"/> instance fields within <paramref name="structDeclarationSymbol"/>.</returns>
public static ImmutableArray<string> GetInfo(INamedTypeSymbol structDeclarationSymbol)
{
return
structDeclarationSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(static member => member is { Type: INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }, IsImplicitlyDeclared: false })
.Select(static member => member.Name)
.ToImmutableArray();
}
}
}
+6 -78
ファイルの表示
@@ -23,12 +23,11 @@ partial class IShaderGenerator
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
/// </summary>
/// <param name="bytecodeInfo">The input <see cref="EmbeddedBytecodeInfo"/> instance.</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslSource</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, bool supportsDynamicShaders, out Func<SyntaxNode, SourceText> fixup)
public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func<SyntaxNode, SourceText> fixup)
{
BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, supportsDynamicShaders, out string? bytecodeLiterals);
BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
if (bytecodeLiterals is not null)
{
@@ -66,25 +65,16 @@ partial class IShaderGenerator
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// </summary>
/// <param name="bytecodeInfo">The input <see cref="EmbeddedBytecodeInfo"/> instance.</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <param name="bytecodeLiterals">The resulting bytecode literals to insert into the final source code.</param>
/// <returns>The <see cref="BlockSyntax"/> instance trying to retrieve the precompiled shader.</returns>
private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, bool supportsDynamicShaders, out string? bytecodeLiterals)
private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
{
if (bytecodeInfo.Bytecode.IsEmpty)
{
bytecodeLiterals = null;
if (supportsDynamicShaders)
{
// Return the dynamic compilation path
return Block(GetDynamicCompilationStatement());
}
else
{
// Faulting path
return Block(GetDynamicCompilationFaultingBlock());
}
// Faulting path
return Block();
}
bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan());
@@ -142,70 +132,8 @@ partial class IShaderGenerator
IdentifierName("LoadEmbeddedBytecode")))
.AddArgumentListArguments(Argument(IdentifierName("bytecode"))))));
// If dynamic shaders are supported, return the combined block
if (supportsDynamicShaders)
{
return Block(embeddedBranch.WithElse(ElseClause(Block(GetDynamicCompilationStatement()))));
}
// If there is no dynamic shader support, add the faulting path after the branch
return Block(embeddedBranch.WithElse(ElseClause(Block(GetDynamicCompilationFaultingBlock()))));
}
/// <summary>
/// The cached tree of dynamic statements.
/// </summary>
private static StatementSyntax? dynamicStatement;
/// <summary>
/// Returns the <see cref="StatementSyntax"/> instance to create a new dynamic shader.
/// </summary>
/// <returns>The <see cref="StatementSyntax"/> instance to create a new dynamic shader.</returns>
private static StatementSyntax GetDynamicCompilationStatement()
{
// This code produces a method declaration as follows:
//
// ComputeSharp.__Internals.ShaderCompiler.LoadDynamicBytecode(ref loader, threadsX, threadsY, threadsZ, in this);
return dynamicStatement ??=
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("ComputeSharp.__Internals.ShaderCompiler"),
IdentifierName("LoadDynamicBytecode")))
.AddArgumentListArguments(
Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)),
Argument(IdentifierName("threadsX")),
Argument(IdentifierName("threadsY")),
Argument(IdentifierName("threadsZ")),
Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword))));
}
/// <summary>
/// The cached tree of dynamic fault statement.
/// </summary>
private static ExpressionStatementSyntax? dynamicFaultStatement;
/// <summary>
/// Returns a <see cref="ExpressionStatementSyntax"/> instances to perform a faulting call to <c>LoadDynamicBytecode(IntPtr)</c>.
/// </summary>
/// <returns>A <see cref="ExpressionStatementSyntax"/> instances to perform a faulting call to <c>LoadDynamicBytecode(IntPtr)</c>.</returns>
private static ExpressionStatementSyntax GetDynamicCompilationFaultingBlock()
{
// This code produces a faulting call as follows:
//
// loader.LoadDynamicBytecode(default);
return dynamicFaultStatement ??=
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadDynamicBytecode")))
.AddArgumentListArguments(
Argument(LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword)))));
return Block(embeddedBranch.WithElse(ElseClause(Block())));
}
}
}
+1 -14
ファイルの表示
@@ -36,23 +36,18 @@ partial class IShaderGenerator
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <returns>The thread ids for the precompiled shader, if available.</returns>
public static ThreadIdsInfo GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
bool supportsDynamicShaders)
{
// Try to get the attribute that controls shader precompilation (has to be present when ComputeSharp.Dynamic is not referenced)
if (!structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName(typeof(EmbeddedBytecodeAttribute).FullName, out AttributeData? attribute))
{
// Emit the diagnostics if dynamic shaders are not supported
if (!supportsDynamicShaders)
{
diagnostics.Add(MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported, structDeclarationSymbol, structDeclarationSymbol);
}
diagnostics.Add(MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported, structDeclarationSymbol, structDeclarationSymbol);
return new(true, 0, 0, 0);
}
@@ -107,14 +102,6 @@ partial class IShaderGenerator
threadsZ = explicitThreadsZ;
}
// If the current shader is dynamic, emit a diagnostic error
if (isDynamicShader)
{
diagnostics.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol);
return new(true, 0, 0, 0);
}
// Ensure the bytecode generation is disabled if any errors are present. This step is done last to ensure that
// all available diagnostics are still emitted correctly before reaching this point, instead of being disabled.
if (diagnostics.Count > 0)
-11
ファイルの表示
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.Linq;
using ComputeSharp.SourceGeneration.Models;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
@@ -45,16 +44,6 @@ partial class IShaderGenerator
return null;
}
/// <summary>
/// Checks whether dynamic shaders are supported in a given compilation.
/// </summary>
/// <param name="compilation">The <see cref="Compilation"/> instance currently in use.</param>
/// <returns>Whether dynamic shaders are supported in the input compilation.</returns>
private static bool IsDynamicCompilationSupported(Compilation compilation)
{
return compilation.ReferencedAssemblyNames.Any(static identity => identity.Name is "ComputeSharp.Dynamic");
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
/// </summary>
+23 -49
ファイルの表示
@@ -22,11 +22,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Check whether or not dynamic shaders are supported
IncrementalValueProvider<bool> supportsDynamicShaders =
context.CompilationProvider
.Select(static (compilation, _) => IsDynamicCompilationSupported(compilation));
// Discover all shader types and extract all the necessary info from each of them
IncrementalValuesProvider<ShaderInfo> shaderInfoWithErrors =
context.SyntaxProvider
@@ -56,11 +51,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = new();
// GetDispatchId() info
ImmutableArray<string> dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol);
token.ThrowIfCancellationRequested();
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
diagnostics,
@@ -71,36 +61,36 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
token.ThrowIfCancellationRequested();
// TryGetBytecode() info
ThreadIdsInfo threadIds = LoadBytecode.GetInfo(
diagnostics,
typeSymbol,
false);
token.ThrowIfCancellationRequested();
// BuildHlslSource() info
HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo(
diagnostics,
context.SemanticModel.Compilation,
typeDeclaration,
typeSymbol);
typeSymbol,
threadIds,
out bool isImplicitTextureUsed);
token.ThrowIfCancellationRequested();
// GetDispatchMetadata() info
DispatchMetadataInfo dispatchMetadataInfo = LoadDispatchMetadata.GetInfo(
root32BitConstantCount,
hlslSourceInfo.ImplicitTextureType is not null,
isImplicitTextureUsed,
hlslSourceInfo.IsSamplerUsed,
fieldInfos);
token.ThrowIfCancellationRequested();
// TryGetBytecode() info
ThreadIdsInfo threadIds = LoadBytecode.GetInfo(
diagnostics,
typeSymbol,
!hlslSourceInfo.Delegates.IsEmpty,
IsDynamicCompilationSupported(context.SemanticModel.Compilation));
token.ThrowIfCancellationRequested();
return new ShaderInfo(
Hierarchy: HierarchyInfo.From(typeSymbol),
DispatchId: new DispatchIdInfo(dispatchIdInfo),
DispatchData: new DispatchDataInfo(
shaderType,
fieldInfos,
@@ -118,20 +108,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
shaderInfoWithErrors
.Select(static (item, _) => item.Diagnostcs));
// Get the GetDispatchId() info (hierarchy and dispatch id info)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo DispatchId)> dispatchIdInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.DispatchId));
// Generate the GetDispatchId() methods
context.RegisterSourceOutput(dispatchIdInfo, static (context, item) =>
{
MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.DispatchId.Delegates);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getDispatchIdMethod, addSkipLocalsInitAttribute: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetDispatchId)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the LoadDispatchData() info (hierarchy and dispatch data info)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo DispatchData)> dispatchDataInfo =
shaderInfoWithErrors
@@ -151,18 +127,17 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
});
// Get the BuildHlslSource info (hierarchy, HLSL source and parsing options)
IncrementalValuesProvider<((HierarchyInfo Hierarchy, HlslShaderSourceInfo HlslShaderSource) Left, bool SupportsDynamicShaders)> hlslSourceInfo =
IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo HlslShaderSource)> hlslSourceInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource))
.Combine(supportsDynamicShaders);
.Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource));
// Generate the BuildHlslSource() methods
context.RegisterSourceOutput(hlslSourceInfo, static (context, item) =>
{
MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Left.HlslShaderSource, item.SupportsDynamicShaders, item.Left.Hierarchy.Hierarchy.Length);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, addSkipLocalsInitAttribute: true);
MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.HlslShaderSource, item.Hierarchy.Hierarchy.Length);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, addSkipLocalsInitAttribute: true);
context.AddSource($"{item.Left.Hierarchy.FullyQualifiedMetadataName}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the LoadDispatchMetadata() info (hierarchy and dispatch metadata info)
@@ -182,7 +157,7 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
// Transform the raw HLSL source to compile (this step aggregates the HLSL source to ensure compilation is only done for actual HLSL changes)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo =
shaderInfoWithErrors
.Select(static (item, token) => (item.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.HlslShaderSource), item.ThreadIds));
.Select(static (item, token) => (item.Hierarchy, item.HlslShaderSource.HlslSource, item.ThreadIds));
// Compile the requested shader bytecodes
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
@@ -219,19 +194,18 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
context.ReportDiagnostics(embeddedBytecodeDiagnostics);
// Get the TryGetBytecode() info (hierarchy and compiled bytecode)
IncrementalValuesProvider<((HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode) Info, bool SupportsDynamicShaders)> embeddedBytecodeInfo =
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode)> embeddedBytecodeInfo =
embeddedBytecodeWithErrors
.Select(static (item, token) => (item.Hierarchy, item.EmbeddedBytecode))
.Combine(supportsDynamicShaders);
.Select(static (item, token) => (item.Hierarchy, item.EmbeddedBytecode));
// Generate the TryGetBytecode() methods
context.RegisterSourceOutput(embeddedBytecodeInfo, static (context, item) =>
{
MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.Info.EmbeddedBytecode, item.SupportsDynamicShaders, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, tryGetBytecodeMethod, addSkipLocalsInitAttribute: false);
MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.EmbeddedBytecode, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, addSkipLocalsInitAttribute: false);
SourceText text = fixup(compilationUnit);
context.AddSource($"{item.Info.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text);
});
}
}
-9
ファイルの表示
@@ -1,9 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a shader dispatch id.
/// </summary>
/// <param name="Delegates">The list of delegate field names for the shader.</param>
internal sealed record DispatchIdInfo(EquatableArray<string> Delegates);
-18
ファイルの表示
@@ -1,18 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL method.
/// </summary>
/// <param name="MetadataName">The metadata name for the method.</param>
/// <param name="EntryPoint">The meethod entry point.</param>
/// <param name="DefinedTypes">The discovered declared types.</param>
/// <param name="DefinedConstants">The discovered defined constants.</param>
/// <param name="DependentMethods">The dependent captured methods.</param>
internal sealed record HlslMethodSourceInfo(
string MetadataName,
string EntryPoint,
EquatableArray<(string Name, string Definition)> DefinedTypes,
EquatableArray<(string Name, string Value)> DefinedConstants,
EquatableArray<(string Signature, string Definition)> DependentMethods);
+2 -30
ファイルの表示
@@ -1,36 +1,8 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL shader.
/// </summary>
/// <param name="HeaderAndThreadsX">The shader generated header and <c>threadsX</c> count declaration.</param>
/// <param name="ThreadsY">The <c>threadsY</c> count declaration.</param>
/// <param name="ThreadsZ">The <c>threadsZ</c> count declaration.</param>
/// <param name="Defines">The define statements, if any.</param>
/// <param name="StaticFieldsAndDeclaredTypes">The static fields and declared types, if any.</param>
/// <param name="CapturedFieldsAndResourcesAndForwardDeclarations">The captured fields, and method forward declarations.</param>
/// <param name="CapturedMethods">The captured method implementations.</param>
/// <param name="EntryPoint">The shader entry point.</param>
/// <param name="ImplicitTextureType">The type of the implicit texture type, if any.</param>
/// <param name="HlslSource">The HLSL source for the shader.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
/// <param name="DefinedTypes">The names of declared types.</param>
/// <param name="DefinedConstants">The names of defined constants.</param>
/// <param name="MethodSignatures">The signatures for captured methods.</param>
/// <param name="Delegates">The list of delegate fields.</param>
internal sealed record HlslShaderSourceInfo(
string HeaderAndThreadsX,
string ThreadsY,
string ThreadsZ,
string Defines,
string StaticFieldsAndDeclaredTypes,
string CapturedFieldsAndResourcesAndForwardDeclarations,
string CapturedMethods,
string EntryPoint,
string? ImplicitTextureType,
bool IsSamplerUsed,
EquatableArray<string> DefinedTypes,
EquatableArray<string> DefinedConstants,
EquatableArray<string> MethodSignatures,
EquatableArray<string> Delegates);
internal sealed record HlslShaderSourceInfo(string HlslSource, bool IsSamplerUsed);
-2
ファイルの表示
@@ -7,7 +7,6 @@ namespace ComputeSharp.SourceGenerators.Models;
/// A model representing all necessary info for a full generation pass for a shader.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="DispatchId">The gathered dispatch id for the shader type.</param>
/// <param name="DispatchData">The gathered shader dispatch data.</param>
/// <param name="DispatchMetadata">The gathered shader dispatch metadata.</param>
/// <param name="HlslShaderSource">The processed HLSL source for the shader.</param>
@@ -15,7 +14,6 @@ namespace ComputeSharp.SourceGenerators.Models;
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record ShaderInfo(
HierarchyInfo Hierarchy,
DispatchIdInfo DispatchId,
DispatchDataInfo DispatchData,
DispatchMetadataInfo DispatchMetadata,
HlslShaderSourceInfo HlslShaderSource,
-11
ファイルの表示
@@ -1,11 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing all necessary info for a full generation pass for a shader method.
/// </summary>
/// <param name="HlslMethodSource">The processed HLSL source for the shader method.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record ShaderMethodInfo(HlslMethodSourceInfo HlslMethodSource, EquatableArray<DiagnosticInfo> Diagnostcs);
-190
ファイルの表示
@@ -1,190 +0,0 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
using ComputeSharp.SourceGeneration.SyntaxRewriters;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <summary>
/// A source generator for processing static methods referenced from compute shaders.
/// </summary>
[Generator(LanguageNames.CSharp)]
public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Get all declared methods (including global function declarations) with the [ShaderMethod] attribute, and their info
IncrementalValuesProvider<ShaderMethodInfo> methodInfoWithErrors =
context.SyntaxProvider
.ForAttributeWithMetadataName(
typeof(ShaderMethodAttribute).FullName,
static (node, _) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } or LocalFunctionStatementSyntax { Parent: GlobalStatementSyntax { Parent: CompilationUnitSyntax } },
static (context, token) =>
{
HlslMethodSourceInfo hlslMethodSourceInfo = Execute.GetData(
context.SemanticModel.Compilation,
(CSharpSyntaxNode)context.TargetNode,
(IMethodSymbol)context.TargetSymbol,
out ImmutableArray<DiagnosticInfo> diagnostics);
return new ShaderMethodInfo(hlslMethodSourceInfo, diagnostics);
});
// Output the diagnostics, if any
context.ReportDiagnostics(
methodInfoWithErrors
.Select(static (item, _) => item.Diagnostcs));
// Generate the [ShaderMethodSource] attributes
context.RegisterSourceOutput(methodInfoWithErrors, static (context, item) =>
{
CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item.HlslMethodSource);
string filename = item.HlslMethodSource.MetadataName.Replace('`', '-').Replace('+', '.');
context.AddSource($"{filename}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
}
/// <summary>
/// A helper with all logic to generate the attribute declarations.
/// </summary>
private static class Execute
{
/// <summary>
/// Processes a given target method.
/// </summary>
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> or <see cref="LocalFunctionStatementSyntax"/> node to process.</param>
/// <param name="methodSymbol">The <see cref="IMethodSymbol"/> instance for the current method.</param>
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
public static HlslMethodSourceInfo GetData(
Compilation compilation,
CSharpSyntaxNode methodDeclaration,
IMethodSymbol methodSymbol,
out ImmutableArray<DiagnosticInfo> diagnostics)
{
using ImmutableArrayBuilder<DiagnosticInfo> builder = new();
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default); // Unused in this generator
// Explore the syntax tree and extract the processed info
SemanticModelProvider semanticModel = new(compilation);
(string entryPoint, ImmutableArray<(string Signature, string Definition)> dependentMethods) = GetProcessedMethods(builder, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions);
ImmutableArray<(string Name, string Definition)> definedTypes = IShaderGenerator.BuildHlslSource.GetDeclaredTypes(builder, methodSymbol, discoveredTypes, instanceMethods);
ImmutableArray<(string Name, string Value)> definedConstants = IShaderGenerator.BuildHlslSource.GetDefinedConstants(constantDefinitions);
diagnostics = builder.ToImmutable();
return new(
methodSymbol.GetFullyQualifiedMetadataName(includeParameters: true),
entryPoint,
definedTypes,
definedConstants,
dependentMethods);
}
/// <summary>
/// Gets a sequence of processed methods from a target method declaration.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> or <see cref="LocalFunctionStatementSyntax"/> instance for the current method.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the method to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
CSharpSyntaxNode methodDeclaration,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
Dictionary<IMethodSymbol, MethodDeclarationSyntax> instanceMethods = new(SymbolEqualityComparer.Default);
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, diagnostics);
// Process the possible syntax nodes
SyntaxNode visitedMethod = methodDeclaration switch
{
MethodDeclarationSyntax methodDeclarationSyntax => shaderSourceRewriter.Visit(methodDeclarationSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)),
LocalFunctionStatementSyntax functionStatementSyntax => shaderSourceRewriter.Visit(functionStatementSyntax)!.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier)),
_ => throw new ArgumentException("Invalid method declaration syntax node type.")
};
// Rewrite the method syntax tree
string targetMethod = visitedMethod
.WithoutTrivia()
.NormalizeWhitespace(eol: "\n")
.ToFullString();
using ImmutableArrayBuilder<(string, string)> methods = new();
// Emit the extracted local functions
foreach (KeyValuePair<string, LocalFunctionStatementSyntax> localFunction in shaderSourceRewriter.LocalFunctions)
{
methods.Add((
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
}
// Emit the discovered static methods
foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values)
{
methods.Add((
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
return (targetMethod, methods.ToImmutable());
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance with the processed attribute.
/// </summary>
/// <param name="methodSourceInfo">The input <see cref="HlslMethodSourceInfo"/> instance to use.</param>
public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo)
{
// This produces an assembly attribute declaration as follows:
//
// // <auto-generated/>
// #pragma warning disable
// [assembly: global::ComputeSharp.ShaderMethodSourceAttribute(<ARGUMENTS>)]
return
CompilationUnit().AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.MetadataName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.EntryPoint))),
AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedTypes)),
AttributeArgument(NestedArrayExpression(methodSourceInfo.DependentMethods)),
AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedConstants)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithOpenBracketToken(Token(TriviaList(
Comment("// <auto-generated/>"),
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
SyntaxKind.OpenBracketToken,
TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace(eol: "\n");
}
}
}
-8
ファイルの表示
@@ -10,14 +10,6 @@ namespace ComputeSharp.__Internals;
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IBytecodeLoader
{
/// <summary>
/// Loads a dynamic shader bytecode.
/// </summary>
/// <param name="handle">An opaque handle to the shader bytecode.</param>
/// <exception cref="InvalidOperationException">Thrown if the shader has already been initialized.</exception>
/// <exception cref="NotSupportedException">Thrown if <paramref name="handle"/> is <see langword="null"/> (indicating an unsupported configuration).</exception>
void LoadDynamicBytecode(IntPtr handle);
/// <summary>
/// Loads the embedded shader bytecode for the shader being dispatched.
/// </summary>
+2 -13
ファイルの表示
@@ -10,14 +10,6 @@ namespace ComputeSharp.__Internals;
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IShader
{
/// <summary>
/// Gets a unique dispatch identifier for the shader.
/// </summary>
/// <returns>The unique dispatch identifier for the shader.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be used directly by user code")]
int GetDispatchId();
/// <summary>
/// Loads the dispatch data for the shader.
/// </summary>
@@ -46,13 +38,10 @@ public interface IShader
/// <summary>
/// Builds the HLSL source code for the current shader instance.
/// </summary>
/// <param name="builder">The resulting <see cref="ArrayPoolStringBuilder"/> instance containing the HLSL source.</param>
/// <param name="threadsX">The number of threads in each thread group for the X axis.</param>
/// <param name="threadsY">The number of threads in each thread group for the Y axis.</param>
/// <param name="threadsZ">The number of threads in each thread group for the Z axis.</param>
/// <param name="hlslSource">The resulting HLSL source.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is not intended to be called directly by user code")]
void BuildHlslSource(out ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ);
void BuildHlslSource(out string hlslSource);
/// <summary>
/// Loads the bytecode for the current shader.
+2 -12
ファイルの表示
@@ -2,7 +2,6 @@ using System;
using System.Runtime.CompilerServices;
using ComputeSharp.__Internals;
using ComputeSharp.Shaders.Models;
using TerraFX.Interop.DirectX;
#pragma warning disable CS0618
@@ -22,24 +21,15 @@ internal struct ShaderBytecodeLoader : IBytecodeLoader
/// Gets the current cached shader instance.
/// </summary>
/// <returns>The current <see cref="ICachedShader"/> instance.</returns>
/// <exception cref="InvalidOperationException">Thrown if the shader has not been initialized.</exception>
/// <exception cref="NotSupportedException">Thrown if the HLSL bytecode is not available.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly ICachedShader GetCachedShader()
{
default(InvalidOperationException).ThrowIf(this.cachedShader is null);
default(NotSupportedException).ThrowIf(this.cachedShader is null);
return this.cachedShader;
}
/// <inheritdoc/>
public unsafe void LoadDynamicBytecode(IntPtr handle)
{
default(InvalidOperationException).ThrowIf(this.cachedShader is not null);
default(NotSupportedException).ThrowIf(handle == IntPtr.Zero);
this.cachedShader = new ICachedShader.Dynamic((IDxcBlob*)handle);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void LoadEmbeddedBytecode(ReadOnlySpan<byte> bytecode)
-163
ファイルの表示
@@ -1,163 +0,0 @@
using System;
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace ComputeSharp.__Internals;
/// <summary>
/// A helper type that implements a pooled buffer writer for <see cref="char"/> values.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This type is not intended to be used directly by user code")]
[DebuggerTypeProxy(typeof(DebugView))]
public ref struct ArrayPoolStringBuilder
{
/// <summary>
/// The underlying <see cref="char"/> array.
/// </summary>
private char[] array;
/// <summary>
/// The starting offset within <see cref="array"/>.
/// </summary>
private int index;
/// <summary>
/// Creates a new <see cref="ArrayPoolStringBuilder"/> instance ready to use.
/// </summary>
/// <param name="sizeHint">The size hint for the internal buffer to allocate.</param>
/// <returns>A new <see cref="ArrayPoolStringBuilder"/> instance with default values.</returns>
public static ArrayPoolStringBuilder Create(int sizeHint)
{
ArrayPoolStringBuilder builder;
builder.array = ArrayPool<char>.Shared.Rent(sizeHint);
builder.index = 0;
return builder;
}
/// <summary>
/// Gets the data written to the underlying buffer so far, as a <see cref="ReadOnlySpan{T}"/>.
/// </summary>
[UnscopedRef]
public readonly ReadOnlySpan<char> WrittenSpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new(this.array, 0, this.index);
}
/// <summary>
/// Appends the input character to the current buffer.
/// </summary>
/// <param name="value">The input character to write.</param>
public void Append(char value)
{
EnsureCapacity(1);
this.array[this.index++] = value;
}
/// <summary>
/// Appends the input sequence of characters to the current buffer.
/// </summary>
/// <param name="value">The input characters to write.</param>
public void Append(string value)
{
EnsureCapacity(value.Length);
#if NET6_0_OR_GREATER
value.CopyTo(this.array.AsSpan(this.index));
#else
value.AsSpan().CopyTo(this.array.AsSpan(this.index));
#endif
this.index += value.Length;
}
/// <summary>
/// Appends the text representation of the input value to the current buffer.
/// </summary>
/// <param name="value">The input value to write.</param>
public void Append(int value)
{
#if NET6_0_OR_GREATER
int charsWritten;
while (!value.TryFormat(this.array.AsSpan(this.index), out charsWritten))
{
EnsureCapacity(10);
}
this.index += charsWritten;
#else
Append(value.ToString());
#endif
}
/// <summary>
/// Ensures that <see cref="array"/> has enough free space to contain a given number of new items.
/// </summary>
/// <param name="requestedSize">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureCapacity(int requestedSize)
{
if (requestedSize > this.array.Length - this.index)
{
ResizeBuffer(requestedSize);
}
}
/// <summary>
/// Resizes <see cref="array"/> to ensure it can fit the specified number of new items.
/// </summary>
/// <param name="sizeHint">The minimum number of items to ensure space for in <see cref="array"/>.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void ResizeBuffer(int sizeHint)
{
int minimumSize = this.index + sizeHint;
// Rent a new array with the specified size, and copy as many items from the current array
// as possible to the new array. This mirrors the behavior of the Array.Resize API from
// the BCL: if the new size is greater than the length of the current array, copy all the
// items from the original array into the new one. Otherwise, copy as many items as possible,
// until the new array is completely filled, and ignore the remaining items in the first array.
char[] newArray = ArrayPool<char>.Shared.Rent(minimumSize);
int itemsToCopy = Math.Min(this.array.Length, minimumSize);
Array.Copy(this.array, 0, newArray, 0, itemsToCopy);
ArrayPool<char>.Shared.Return(this.array);
this.array = newArray;
}
/// <inheritdoc/>
public readonly void Dispose()
{
ArrayPool<char>.Shared.Return(this.array);
}
/// <summary>
/// A debug proxy used for displaying debug info.
/// </summary>
internal sealed class DebugView
{
/// <summary>
/// Initializes a new instance of the <see cref="DebugView"/> class with the specified parameters.
/// </summary>
/// <param name="builder">The input <see cref="ArrayPoolStringBuilder"/> instance to display.</param>
public DebugView(ArrayPoolStringBuilder builder)
{
Text = builder.WrittenSpan.ToString();
}
/// <summary>
/// Gets the text to display for the current instance.
/// </summary>
public string Text { get; }
}
}
+1 -1
ファイルの表示
@@ -35,7 +35,7 @@ internal static class PipelineDataLoader<T>
/// <returns>The <see cref="PipelineData"/> instance for a given shader.</returns>
public static unsafe PipelineData GetPipelineData(GraphicsDevice device, int threadsX, int threadsY, int threadsZ, ref T shader)
{
ShaderKey key = new(shader.GetDispatchId(), threadsX, threadsY, threadsZ);
ShaderKey key = new(threadsX, threadsY, threadsZ);
lock (ShadersCache)
{
+2 -10
ファイルの表示
@@ -8,11 +8,6 @@ namespace ComputeSharp.Shaders.Models;
/// </summary>
internal readonly struct ShaderKey : IEquatable<ShaderKey>
{
/// <summary>
/// The hashcode of the current shader type.
/// </summary>
private readonly int id;
/// <summary>
/// The number of iterations to run on the X axis.
/// </summary>
@@ -31,14 +26,12 @@ internal readonly struct ShaderKey : IEquatable<ShaderKey>
/// <summary>
/// Creates a new <see cref="ShaderKey"/> instance with the specified parameters.
/// </summary>
/// <param name="id">The hashcode of the current shader type.</param>
/// <param name="threadsX">The number of iterations to run on the X axis.</param>
/// <param name="threadsY">The number of iterations to run on the Y axis.</param>
/// <param name="threadsZ">The number of iterations to run on the Z axis.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ShaderKey(int id, int threadsX, int threadsY, int threadsZ)
public ShaderKey(int threadsX, int threadsY, int threadsZ)
{
this.id = id;
this.threadsX = threadsX;
this.threadsY = threadsY;
this.threadsZ = threadsZ;
@@ -49,7 +42,6 @@ internal readonly struct ShaderKey : IEquatable<ShaderKey>
public bool Equals(ShaderKey other)
{
return
this.id == other.id &&
this.threadsX == other.threadsX &&
this.threadsY == other.threadsY &&
this.threadsZ == other.threadsZ;
@@ -65,6 +57,6 @@ internal readonly struct ShaderKey : IEquatable<ShaderKey>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
return HashCode.Combine(this.id, this.threadsX, this.threadsY, this.threadsZ);
return HashCode.Combine(this.threadsX, this.threadsY, this.threadsZ);
}
}
+9 -4
ファイルの表示
@@ -1,13 +1,10 @@
using System.Diagnostics;
using System.Linq;
#if NET6_0_OR_GREATER
using System.Runtime.Versioning;
#endif
using ComputeSharp;
using ComputeSharp.Interop;
#if NET6_0_OR_GREATER
[assembly: SupportedOSPlatform("windows6.2")]
#endif
float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray();
@@ -26,10 +23,18 @@ for (int i = 0; i < array.Length; i++)
Trace.Assert(result[i] == array[i] * 2);
}
// Also get the shader info (this requires DXC to be present)
ShaderInfo shaderInfo = ReflectionServices.GetShaderInfo<MultiplyByTwo>();
// Validate a couple properties as a sanity check
Trace.Assert(shaderInfo.HlslSource is { Length: > 0 });
Trace.Assert(shaderInfo.BoundResourceCount == 2);
/// <summary>
/// A sample kernel that requires dynamic compilation, as it's not precompiled.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct MultiplyByTwo : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
@@ -10,7 +10,6 @@
<ProjectReference Include="..\..\src\ComputeSharp.Core\ComputeSharp.Core.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Core.SourceGenerators\ComputeSharp.Core.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.Dynamic\ComputeSharp.Dynamic.csproj" />
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" PrivateAssets="contentfiles;build" />
</ItemGroup>
</Project>
+9 -8
ファイルの表示
@@ -5,11 +5,11 @@ float[] numbers = Enumerable.Range(0, 128).Select(i => (float)i).ToArray();
using GraphicsDevice device = GraphicsDevice.GetDefault();
using ReadWriteBuffer<float> buffer = device.AllocateReadWriteBuffer(numbers);
device.For(buffer.Length, new ApplyFunctionShader(buffer, AddHalf));
device.For(buffer.Length, new ApplyFunctionShader(buffer));
foreach (ref float number in numbers.AsSpan())
{
number = AddHalf(number);
number = ApplyFunctionShader.AddHalf(number);
}
float[] result = buffer.ToArray();
@@ -21,18 +21,19 @@ if (!numbers.SequenceEqual(result))
Console.WriteLine("Test passed successfully!");
// See https://github.com/Sergio0694/ComputeSharp/issues/374
[ShaderMethod]
static float AddHalf(float input) => input + 0.5f;
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct ApplyFunctionShader : IComputeShader
{
private readonly ReadWriteBuffer<float> sourceTexture;
private readonly Func<float, float> func;
public static float AddHalf(float input)
{
return input + 0.5f;
}
public void Execute()
{
this.sourceTexture[ThreadIds.X] = this.func(this.sourceTexture[ThreadIds.X]);
this.sourceTexture[ThreadIds.X] = AddHalf(this.sourceTexture[ThreadIds.X]);
}
}
+7
ファイルの表示
@@ -11,6 +11,7 @@ namespace ComputeSharp.Tests.Internals;
public partial class ShaderDataLoaderTests
{
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public partial struct CapturedResourceShader : IComputeShader
{
public ReadWriteBuffer<float> _;
@@ -39,6 +40,7 @@ public partial class ShaderDataLoaderTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public partial struct MultipleResourcesAndPrimitivesShader : IComputeShader
{
public ReadWriteBuffer<float> _0;
@@ -76,6 +78,7 @@ public partial class ShaderDataLoaderTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public partial struct ScalarAndVectorTypesShader : IComputeShader
{
public ReadWriteBuffer<float> _;
@@ -127,6 +130,7 @@ public partial class ShaderDataLoaderTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public partial struct ScalarVectorAndMatrixTypesShader : IComputeShader
{
public ReadWriteBuffer<float> _;
@@ -213,6 +217,7 @@ public partial class ShaderDataLoaderTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public partial struct FlatCustomTypeShader : IComputeShader
{
public ReadWriteBuffer<float> _0;
@@ -305,6 +310,7 @@ public partial class ShaderDataLoaderTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public partial struct NestedCustomTypesShader : IComputeShader
{
public ReadWriteBuffer<float> _0;
@@ -397,6 +403,7 @@ public partial class ShaderDataLoaderTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public partial struct AmbiguousNamesShader : IComputeShader
{
public ReadWriteBuffer<float> a;
-78
ファイルの表示
@@ -1,78 +0,0 @@
using System;
using ComputeSharp.__Internals;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable CS0618
namespace ComputeSharp.Tests.Internals;
[TestClass]
[TestCategory("ShaderHashCode")]
public partial class ShaderHashCodeTests
{
public partial struct Shader1 : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
public void Execute()
{
this.B[0] = this.A;
}
}
[TestMethod]
public void ShaderWithNoCapturedDelegates()
{
float value = 10;
using ReadWriteBuffer<float> buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer<float>(1);
Shader1 shader1 = new() { A = value, B = buffer };
int hash1 = ((IShader)shader1).GetDispatchId();
int hash2 = ((IShader)shader1).GetDispatchId();
Assert.IsTrue(hash1 == hash2);
Shader1 shader2 = new() { A = value, B = buffer };
int hash3 = ((IShader)shader2).GetDispatchId();
Assert.IsTrue(hash1 == hash3);
}
public partial struct Shader2 : IComputeShader
{
public float A;
public ReadWriteBuffer<float> B;
public Func<float, float> F;
public void Execute()
{
this.B[0] = this.F(this.A);
}
}
[TestMethod]
public void ShaderWithCapturedDelegates()
{
Func<float, float> f = static x => x * x;
using ReadWriteBuffer<float> buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer<float>(1);
Shader2 shader1 = new() { A = 1, B = buffer, F = f };
int hash1 = ((IShader)shader1).GetDispatchId();
int hash2 = ((IShader)shader1).GetDispatchId();
Assert.IsTrue(hash1 == hash2);
f = static x => x + 1;
Shader2 shader2 = new() { A = 1, B = buffer, F = f };
int hash3 = ((IShader)shader2).GetDispatchId();
Assert.IsFalse(hash1 == hash3);
}
}
@@ -26,7 +26,7 @@ public class DynamicNativeLibrariesResolverTests : NativeLibrariesResolverTestsB
}
string coreProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.csproj");
string projectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.csproj");
string projectPath = Path.Combine(path, "src", "ComputeSharp", "ComputeSharp.csproj");
string dynamicProjectPath = Path.Combine(path, "src", "ComputeSharp.Dynamic", "ComputeSharp.Dynamic.csproj");
Process.Start("dotnet", $"pack {coreProjectPath} -c Release").WaitForExit();
+1 -1
ファイルの表示
@@ -26,7 +26,7 @@ public class PixNativeLibrariesResolverTests : NativeLibrariesResolverTestsBase
}
string coreProjectPath = Path.Combine(path, "src", "ComputeSharp.Core", "ComputeSharp.Core.csproj");
string projectPath = Path.Combine(path, "src", "ComputeSharp.Package", "ComputeSharp.Package.csproj");
string projectPath = Path.Combine(path, "src", "ComputeSharp", "ComputeSharp.csproj");
string pixProjectPath = Path.Combine(path, "src", "ComputeSharp.Pix", "ComputeSharp.Pix.csproj");
// Run dotnet pack and on the packaging projects, to ensure the local NuGet packages are available
-35
ファイルの表示
@@ -1481,41 +1481,6 @@ public class DiagnosticsTests
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0042", "CMPS0047");
}
[TestMethod]
public void EmbeddedBytecodeWithDynamicShader()
{
const string source = """
using System;
using ComputeSharp;
namespace ComputeSharp
{
public interface IComputeShader { }
public class ReadWriteBuffer<T> { }
public class EmbeddedBytecodeAttribute : Attribute
{
public EmbeddedBytecodeAttribute(int threadsX, int threadsY, int threadsZ) { }
}
}
namespace MyFancyApp.Sample
{
[EmbeddedBytecode(8, 8, 1)]
public struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
public Action action;
public void Execute()
{
}
}
}
""";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0043");
}
[TestMethod]
[DataRow(-1, 1, 1)]
[DataRow(1, -1, 1)]
+4
ファイルの表示
@@ -278,6 +278,7 @@ public partial class BufferTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ConstantBufferKernel : IComputeShader
{
public readonly ConstantBuffer<int> source;
@@ -306,6 +307,7 @@ public partial class BufferTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyBufferKernel : IComputeShader
{
public readonly ReadOnlyBuffer<int> source;
@@ -334,6 +336,7 @@ public partial class BufferTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteBufferKernel : IComputeShader
{
public readonly ReadWriteBuffer<int> source;
@@ -369,6 +372,7 @@ public partial class BufferTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct DoublePrecisionSupportShader : IComputeShader
{
public readonly ReadWriteBuffer<double> buffer;
+12
ファイルの表示
@@ -1294,6 +1294,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct OffsetComputeShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
@@ -1307,6 +1308,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct ClearPixelShader : IPixelShader<float4>
{
/// <inheritdoc/>
@@ -1317,6 +1319,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct ColorPixelShader : IPixelShader<float4>
{
public readonly float4 color;
@@ -1329,6 +1332,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct LinearSampling2DPixelShader : IPixelShader<float4>
{
public readonly IReadOnlyTexture2D<float4> source;
@@ -1341,6 +1345,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct LinearSampling3DComputeShader : IComputeShader
{
public readonly IReadOnlyTexture3D<float4> source;
@@ -1359,6 +1364,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct LinearSamplingFromNormalized2DPixelShader : IPixelShader<float4>
{
public readonly IReadOnlyNormalizedTexture2D<float4> source;
@@ -1371,6 +1377,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct CopyToOutputPixelShader : IPixelShader<float4>
{
public readonly IReadOnlyNormalizedTexture2D<float4> source;
@@ -1383,6 +1390,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct InvertPixelShader : IPixelShader<float4>
{
public readonly IReadWriteNormalizedTexture2D<float4> source;
@@ -1395,6 +1403,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct LinearSamplingFromNormalized3DComputeShader : IComputeShader
{
public readonly IReadOnlyNormalizedTexture3D<float4> source;
@@ -1413,6 +1422,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct Dotted2DPixelShader : IComputeShader
{
public readonly IReadWriteNormalizedTexture2D<float4> source;
@@ -1441,6 +1451,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct Dotted3DPixelShader : IComputeShader
{
public readonly IReadWriteNormalizedTexture3D<float4> source;
@@ -1469,6 +1480,7 @@ public partial class ComputeContextTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct ConvertToNonNormalized2DShader : IComputeShader
{
public readonly IReadOnlyNormalizedTexture2D<float4> source;
+9
ファイルの表示
@@ -57,6 +57,7 @@ public partial class DispatchTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct ThreadIdsShader : IComputeShader
{
public readonly ReadWriteTexture3D<int4> buffer;
@@ -111,6 +112,7 @@ public partial class DispatchTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct ThreadIdsNormalizedShader : IComputeShader
{
public readonly ReadWriteTexture3D<float4> buffer;
@@ -172,6 +174,7 @@ public partial class DispatchTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct GroupIdsShader : IComputeShader
{
public readonly ReadWriteTexture3D<int4> buffer;
@@ -202,6 +205,7 @@ public partial class DispatchTests
}
[AutoConstructor]
[EmbeddedBytecode(4, 15, 7)]
internal readonly partial struct GroupSizeShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
@@ -234,6 +238,7 @@ public partial class DispatchTests
}
[AutoConstructor]
[EmbeddedBytecode(32, 1, 1)]
internal readonly partial struct GridIdsShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
@@ -265,6 +270,7 @@ public partial class DispatchTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct DispatchSizeShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
@@ -304,6 +310,7 @@ public partial class DispatchTests
}
}
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct DispatchPixelShader : IPixelShader<float4>
{
public float4 Execute()
@@ -333,6 +340,7 @@ public partial class DispatchTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct FixedGroupSharedPixelShader : IComputeShader
{
private readonly ReadWriteBuffer<int> buffer;
@@ -376,6 +384,7 @@ public partial class DispatchTests
}
[AutoConstructor]
[EmbeddedBytecode(32, 1, 1)]
internal readonly partial struct DynamicGroupSharedPixelShader : IComputeShader
{
private readonly ReadWriteBuffer<int> buffer;
+1
ファイルの表示
@@ -35,6 +35,7 @@ public partial class IPixelShaderTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct EarlyReturnShader : IPixelShader<float4>
{
public float4 Execute()
+1
ファイルの表示
@@ -73,6 +73,7 @@ public partial class InitializationTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct SampleShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
-251
ファイルの表示
@@ -1,251 +0,0 @@
using System;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable IDE0062
namespace ComputeSharp.Tests;
[TestClass]
[TestCategory("Metaprogramming")]
public partial class MetaprogrammingTests
{
[AutoConstructor]
internal readonly partial struct ActivationWithDelegateShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public readonly Func<int, int> activation;
public void Execute()
{
this.buffer[ThreadIds.X] = this.activation(ThreadIds.X);
}
}
public static class Activations
{
[ShaderMethod]
public static int Square(int x)
{
return x * x;
}
[ShaderMethod]
public static int AddOne(int x)
{
return x + 1;
}
// Missing attribute
public static int Identity(int x)
{
return x;
}
[ShaderMethod]
public static int FunctionWithConstants(int x)
{
return (int)(x + FourAndAHalf);
}
[ShaderMethod]
public static Position FunctionWithTypes(int x)
{
Point point = default;
point.A = x;
point.B = x * x;
Position position = default;
position.X = point.A;
position.Y = point.B;
return position;
}
public struct Point
{
public int A;
public int B;
}
[ShaderMethod]
public static int FunctionWithLocalFunctionAndStaticMethod(int x)
{
static int AddTwo(int x) => x + 2;
return Square(3 + AddOne(x) + AddTwo(x));
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void ActivationWithDelegate(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Square));
int[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.Square(i));
}
device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.AddOne));
result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.AddOne(i));
}
}
[CombinatorialTestMethod]
[AllDevices]
[ExpectedException(typeof(ArgumentException))]
public unsafe void DelegateWithMissingAttributeOnMethod(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Identity));
}
[CombinatorialTestMethod]
[AllDevices]
[ExpectedException(typeof(ArgumentException))]
public unsafe void DelegateWrappingNonStaticMethod(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
[ShaderMethod]
int Dummy(int x) => x;
device.Get().For(100, new ActivationWithDelegateShader(buffer, Dummy));
}
[AutoConstructor]
internal readonly partial struct ActivationWithMultipleDelegatesShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public readonly Func<int, int> f1;
public readonly Func<int, int> f2;
public void Execute()
{
this.buffer[ThreadIds.X] = this.f2(this.f1(ThreadIds.X));
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void ActivationWithMultipleDelegates(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new ActivationWithMultipleDelegatesShader(buffer, Activations.Square, Activations.AddOne));
int[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.AddOne(Activations.Square(i)));
}
}
public const float FourAndAHalf = 4.5f;
public const int MagicNumber = 42;
[AutoConstructor]
internal readonly partial struct DelegateWithConstantsShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public readonly Func<int, int> activation;
public void Execute()
{
this.buffer[ThreadIds.X] = MagicNumber + this.activation(ThreadIds.X);
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void DelegateWithConstants(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new DelegateWithConstantsShader(buffer, Activations.FunctionWithConstants));
int[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], MagicNumber + Activations.FunctionWithConstants(i));
}
}
public struct Position
{
public int X;
public int Y;
}
[AutoConstructor]
internal readonly partial struct DelegateWithTypesShader : IComputeShader
{
public readonly ReadWriteBuffer<Position> buffer;
public readonly Func<int, Position> activation;
public void Execute()
{
this.buffer[ThreadIds.X] = this.activation(ThreadIds.X);
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void DelegateWithTypes(Device device)
{
using ReadWriteBuffer<Position> buffer = device.Get().AllocateReadWriteBuffer<Position>(100);
device.Get().For(100, new DelegateWithTypesShader(buffer, Activations.FunctionWithTypes));
Position[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i].X, Activations.FunctionWithTypes(i).X);
Assert.AreEqual(result[i].Y, Activations.FunctionWithTypes(i).Y);
}
}
[AutoConstructor]
internal readonly partial struct DelegateWithLocalFunctionsAndStaticMethodsShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public readonly Func<int, int> activation;
public void Execute()
{
this.buffer[ThreadIds.X] = Activations.AddOne(ThreadIds.X) + this.activation(ThreadIds.X);
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void DelegateWithLocalFunctionsAndStaticMethods(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new DelegateWithLocalFunctionsAndStaticMethodsShader(buffer, Activations.FunctionWithLocalFunctionAndStaticMethod));
int[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.AddOne(i) + Activations.FunctionWithLocalFunctionAndStaticMethod(i));
}
}
}
+24 -1
ファイルの表示
@@ -1,4 +1,4 @@
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
@@ -29,6 +29,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyBuffer_T1_AsReadOnlyBufferShader : IComputeShader
{
public readonly ReadOnlyBuffer<float> source;
@@ -61,6 +62,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteBuffer_T1_AsReadWriteBufferShader : IComputeShader
{
public readonly ReadWriteBuffer<float> source;
@@ -93,6 +95,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyTexture1D_T1_AsReadOnlyTexture1DShader : IComputeShader
{
public readonly ReadOnlyTexture1D<float> source;
@@ -125,6 +128,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture1D_T1_AsReadWriteTexture1DShader : IComputeShader
{
public readonly ReadWriteTexture1D<float> source;
@@ -161,6 +165,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture1D_T1_AsIReadOnlyTexture1DShader : IComputeShader
{
public readonly IReadOnlyTexture1D<float> source;
@@ -193,6 +198,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyTexture1D_T2_AsReadOnlyTexture1DShader : IComputeShader
{
public readonly ReadOnlyTexture1D<Rgba32, float4> source;
@@ -225,6 +231,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyTexture1D_T2_AsIReadOnlyNormalizedTexture1DShader : IComputeShader
{
public readonly IReadOnlyNormalizedTexture1D<float4> source;
@@ -257,6 +264,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture1D_T2_AsReadWriteTexture1DShader : IComputeShader
{
public readonly ReadWriteTexture1D<Rgba32, float4> source;
@@ -289,6 +297,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture1D_T2_AsIReadWriteNormalizedTexture1DShader : IComputeShader
{
public readonly IReadWriteNormalizedTexture1D<float4> source;
@@ -321,6 +330,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyTexture2D_T1_AsReadOnlyTexture2DShader : IComputeShader
{
public readonly ReadOnlyTexture2D<float> source;
@@ -354,6 +364,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture2D_T1_AsReadWriteTexture2DShader : IComputeShader
{
public readonly ReadWriteTexture2D<float> source;
@@ -391,6 +402,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture2D_T1_AsIReadOnlyTexture2DShader : IComputeShader
{
public readonly IReadOnlyTexture2D<float> source;
@@ -424,6 +436,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyTexture2D_T2_AsReadOnlyTexture2DShader : IComputeShader
{
public readonly ReadOnlyTexture2D<Rgba32, float4> source;
@@ -457,6 +470,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyTexture2D_T2_AsIReadOnlyNormalizedTexture2DShader : IComputeShader
{
public readonly IReadOnlyNormalizedTexture2D<float4> source;
@@ -490,6 +504,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture2D_T2_AsReadWriteTexture2DShader : IComputeShader
{
public readonly ReadWriteTexture2D<Rgba32, float4> source;
@@ -523,6 +538,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture2D_T2_AsIReadWriteNormalizedTexture2DShader : IComputeShader
{
public readonly IReadWriteNormalizedTexture2D<float4> source;
@@ -556,6 +572,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyTexture3D_T1_AsReadOnlyTexture3DShader : IComputeShader
{
public readonly ReadOnlyTexture3D<float> source;
@@ -590,6 +607,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture3D_T1_AsReadWriteTexture3DShader : IComputeShader
{
public readonly ReadWriteTexture3D<float> source;
@@ -628,6 +646,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture3D_T1_AsIReadOnlyTexture3DShader : IComputeShader
{
public readonly IReadOnlyTexture3D<float> source;
@@ -662,6 +681,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyTexture3D_T2_AsReadOnlyTexture3DShader : IComputeShader
{
public readonly ReadOnlyTexture3D<Rgba32, float4> source;
@@ -696,6 +716,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyTexture3D_T2_AsIReadOnlyNormalizedTexture3DShader : IComputeShader
{
public readonly IReadOnlyNormalizedTexture3D<float4> source;
@@ -730,6 +751,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture3D_T2_AsReadWriteTexture3DShader : IComputeShader
{
public readonly ReadWriteTexture3D<Rgba32, float4> source;
@@ -764,6 +786,7 @@ public partial class ResourceDimensionsTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture3D_T2_AsIReadWriteNormalizedTexture3DShader : IComputeShader
{
public readonly IReadWriteNormalizedTexture3D<float4> source;
+2 -1
ファイルの表示
@@ -1,4 +1,4 @@
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text.RegularExpressions" #>
@@ -132,6 +132,7 @@ foreach (var pair in typesMap)
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct <#=testMethodName#>Shader : IComputeShader
{
public readonly <#=shaderResourceType#> source;
+17
ファイルの表示
@@ -18,6 +18,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct ReservedKeywordsShader : IComputeShader
{
public readonly ReadWriteBuffer<float> row_major;
@@ -53,6 +54,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct ReservedKeywordsInCustomTypesShader : IComputeShader
{
public readonly ReadWriteBuffer<float> row_major;
@@ -80,6 +82,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct ReservedKeywordsFromHlslTypesAndBuiltInValuesShader : IComputeShader
{
public readonly ReadWriteBuffer<float> fragmentKeyword;
@@ -158,6 +161,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct SpecialTypeAsReturnTypeShader : IComputeShader
{
public readonly ReadWriteBuffer<float2> buffer;
@@ -179,6 +183,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct LocalFunctionInExternalMethodsShader : IComputeShader
{
public readonly ReadWriteBuffer<float2> buffer;
@@ -210,6 +215,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct CapturedNestedStructTypeShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
@@ -229,6 +235,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct ExternalStructTypeShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
@@ -250,6 +257,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct OutOfOrderMethodsShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
@@ -285,6 +293,7 @@ namespace ComputeSharp.Tests
Assert.AreEqual(info.BoundResourceCount, 2u);
}
[EmbeddedBytecode(DispatchAxis.XY)]
public readonly partial struct StatelessPixelShader : IPixelShader<float4>
{
/// <inheritdoc/>
@@ -295,6 +304,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct LoopWithVarCounterShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
@@ -324,6 +334,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct DoublePrecisionSupportShader : IComputeShader
{
public readonly ReadWriteBuffer<double> buffer;
@@ -343,6 +354,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct FieldAccessWithThisExpressionShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
@@ -369,6 +381,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ComputeShaderWithInheritedShaderInterfaceShader : IMyBaseShader
{
int IMyBaseShader.A => 42;
@@ -402,6 +415,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct PixelShaderWithInheritedShaderInterfaceShader : IMyBaseShader<float4>
{
int IMyBaseShader<float4>.A => 42;
@@ -450,6 +464,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct StructInstanceMethodsShader : IComputeShader
{
public readonly MyStructTypeA a;
@@ -483,6 +498,7 @@ namespace ComputeSharp.Tests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct PixelShaderWithScopedParameterInMethodsShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
@@ -520,6 +536,7 @@ namespace ExternalNamespace
public partial class ShaderCompilerTestsInExternalNamespace
{
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct UserDefinedTypeShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
+4
ファイルの表示
@@ -31,6 +31,7 @@ public partial class ShaderMembersTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct StaticConstantsShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
@@ -70,6 +71,7 @@ public partial class ShaderMembersTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct GlobalVariableShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
@@ -104,6 +106,7 @@ public partial class ShaderMembersTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct BoolInstanceFieldsShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
@@ -167,6 +170,7 @@ public partial class ShaderMembersTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct BoolInstanceFieldInCustomStructShader : IComputeShader
{
public readonly ReadWriteBuffer<Int2AndBoolField> buffer;
+12
ファイルの表示
@@ -52,6 +52,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct NanAndInfiniteShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer1;
@@ -112,6 +113,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ModAndComparisonOperatorsShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
@@ -173,6 +175,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct BitwiseOperatorsShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
@@ -225,6 +228,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct BooleanOperatorsShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
@@ -274,6 +278,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ToBooleanConversionIntrinsicsShader : IComputeShader
{
public readonly ReadOnlyBuffer<float> buffer1;
@@ -357,6 +362,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct FromBooleanConversionIntrinsicsShader : IComputeShader
{
public readonly ReadOnlyBuffer<int> source;
@@ -439,6 +445,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ConstantsInShaderConstantFieldsShader : IComputeShader
{
public const float rot_angle = (float)(137.2 / 180.0 * Math.PI);
@@ -516,6 +523,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct DoubleConstantsInShaderConstantFieldsShader : IComputeShader
{
public const float DoubleToFloatConstant = (float)(1 / 255.0);
@@ -622,6 +630,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct GlslStyleMulOperatorsShader : IComputeShader
{
public readonly ReadOnlyBuffer<float> source1;
@@ -762,6 +771,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct CustomStructTypeShader : IComputeShader
{
public readonly ReadWriteBuffer<CustomStructType> source;
@@ -799,6 +809,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct MiscHlslIntrinsicsShader : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer1;
@@ -841,6 +852,7 @@ public partial class ShaderRewriterTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadonlyModifierInMethodsShader : IComputeShader
{
private readonly ReadWriteBuffer<int> buffer;
+1
ファイルの表示
@@ -9,6 +9,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct ColorfulInfinity : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct ContouredLayers : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct ExtrudedTruchetPattern : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -9,6 +9,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct FourColorGradient : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -9,6 +9,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct FractalTiling : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -7,6 +7,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// Ported from <see href="https://www.shadertoy.com/new"/>.
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct HelloWorld : IPixelShader<float4>
{
/// <summary>
+1
ファイルの表示
@@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>Created by Syntopia.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct MengerJourney : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>Created by whisky_shusuky.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct Octagrams : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -9,6 +9,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct ProteanClouds : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -9,6 +9,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct PyramidPattern : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -6,6 +6,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct TerracedHills : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct TriangleGridContouring : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -8,6 +8,7 @@ namespace ComputeSharp.SwapChain.Shaders.Compute;
/// <para>Created by Shane.</para>
/// </summary>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct TwoTiledTruchet : IComputeShader
{
/// <summary>
+1
ファイルの表示
@@ -89,6 +89,7 @@ partial class Texture1DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
public readonly partial struct SamplingComputeShader : IComputeShader
{
public readonly IReadOnlyNormalizedTexture1D<float4> source;
+8 -1
ファイルの表示
@@ -1,4 +1,4 @@
using System;
using System;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
@@ -69,6 +69,7 @@ partial class Texture1DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader
{
public readonly ReadOnlyTexture1D<Bgra32, Float4> source;
@@ -81,6 +82,7 @@ partial class Texture1DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct Shader_Unorm_R16_float : IComputeShader
{
public readonly ReadOnlyTexture1D<R16, float> source;
@@ -93,6 +95,7 @@ partial class Texture1DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct Shader_Unorm_R8_float : IComputeShader
{
public readonly ReadOnlyTexture1D<R8, float> source;
@@ -105,6 +108,7 @@ partial class Texture1DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader
{
public readonly ReadOnlyTexture1D<Rg16, Float2> source;
@@ -117,6 +121,7 @@ partial class Texture1DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader
{
public readonly ReadOnlyTexture1D<Rg32, Float2> source;
@@ -129,6 +134,7 @@ partial class Texture1DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader
{
public readonly ReadOnlyTexture1D<Rgba32, Float4> source;
@@ -141,6 +147,7 @@ partial class Texture1DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader
{
public readonly ReadOnlyTexture1D<Rgba64, Float4> source;
+2 -1
ファイルの表示
@@ -1,4 +1,4 @@
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
@@ -65,6 +65,7 @@ foreach (var (t, tPixel) in EnumerateTypes())
#>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader
{
public readonly ReadOnlyTexture1D<<#=t#>, <#=tPixel#>> source;
+2
ファイルの表示
@@ -363,6 +363,7 @@ public partial class Texture1DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadOnlyTexture1DKernel : IComputeShader
{
public readonly ReadOnlyTexture1D<int> source;
@@ -393,6 +394,7 @@ public partial class Texture1DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.X)]
internal readonly partial struct ReadWriteTexture1DKernel : IComputeShader
{
public readonly ReadWriteTexture1D<int> source;
+2
ファイルの表示
@@ -72,6 +72,7 @@ partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
public readonly partial struct SamplingComputeShader : IComputeShader
{
public readonly IReadOnlyNormalizedTexture2D<float4> source;
@@ -105,6 +106,7 @@ partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
public readonly partial struct SamplingPixelShader : IPixelShader<float4>
{
public readonly IReadOnlyNormalizedTexture2D<float4> texture;
+8 -1
ファイルの表示
@@ -1,4 +1,4 @@
using System;
using System;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
@@ -69,6 +69,7 @@ partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader
{
public readonly ReadOnlyTexture2D<Bgra32, Float4> source;
@@ -81,6 +82,7 @@ partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct Shader_Unorm_R16_float : IComputeShader
{
public readonly ReadOnlyTexture2D<R16, float> source;
@@ -93,6 +95,7 @@ partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct Shader_Unorm_R8_float : IComputeShader
{
public readonly ReadOnlyTexture2D<R8, float> source;
@@ -105,6 +108,7 @@ partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rg16, Float2> source;
@@ -117,6 +121,7 @@ partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rg32, Float2> source;
@@ -129,6 +134,7 @@ partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rgba32, Float4> source;
@@ -141,6 +147,7 @@ partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rgba64, Float4> source;
+2 -1
ファイルの表示
@@ -1,4 +1,4 @@
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
@@ -65,6 +65,7 @@ foreach (var (t, tPixel) in EnumerateTypes())
#>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader
{
public readonly ReadOnlyTexture2D<<#=t#>, <#=tPixel#>> source;
+2
ファイルの表示
@@ -428,6 +428,7 @@ public partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct ReadOnlyTexture2DKernel : IComputeShader
{
public readonly ReadOnlyTexture2D<int> source;
@@ -458,6 +459,7 @@ public partial class Texture2DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XY)]
internal readonly partial struct ReadWriteTexture2DKernel : IComputeShader
{
public readonly ReadWriteTexture2D<int> source;
+8 -1
ファイルの表示
@@ -1,4 +1,4 @@
using System;
using System;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
@@ -69,6 +69,7 @@ partial class Texture3DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader
{
public readonly ReadOnlyTexture3D<Bgra32, Float4> source;
@@ -81,6 +82,7 @@ partial class Texture3DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct Shader_Unorm_R16_float : IComputeShader
{
public readonly ReadOnlyTexture3D<R16, float> source;
@@ -93,6 +95,7 @@ partial class Texture3DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct Shader_Unorm_R8_float : IComputeShader
{
public readonly ReadOnlyTexture3D<R8, float> source;
@@ -105,6 +108,7 @@ partial class Texture3DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rg16, Float2> source;
@@ -117,6 +121,7 @@ partial class Texture3DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rg32, Float2> source;
@@ -129,6 +134,7 @@ partial class Texture3DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rgba32, Float4> source;
@@ -141,6 +147,7 @@ partial class Texture3DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rgba64, Float4> source;
+2 -1
ファイルの表示
@@ -1,4 +1,4 @@
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
@@ -65,6 +65,7 @@ foreach (var (t, tPixel) in EnumerateTypes())
#>
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader
{
public readonly ReadOnlyTexture3D<<#=t#>, <#=tPixel#>> source;
+2
ファイルの表示
@@ -533,6 +533,7 @@ public partial class Texture3DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct ReadOnlyTexture3DKernel : IComputeShader
{
public readonly ReadOnlyTexture3D<int> source;
@@ -563,6 +564,7 @@ public partial class Texture3DTests
}
[AutoConstructor]
[EmbeddedBytecode(DispatchAxis.XYZ)]
internal readonly partial struct ReadWriteTexture3DKernel : IComputeShader
{
public readonly ReadWriteTexture3D<int> source;