Merge pull request #87 from Sergio0694/feature/hlsl-codegen-GetDimensions

Added support for resource dimensions in HLSL
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2021-01-09 22:34:01 +01:00
コミット 30fb7f448c
5ファイル変更
+142 -188

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

+32 -116
ファイルの表示
@@ -1,7 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
@@ -257,61 +256,38 @@ namespace ComputeSharp.BokehBlur.Processors
Span<Rgba32> span = MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(pixelSpan);
using ReadWriteTexture2D<Rgba32, Vector4> sourceTexture = Gpu.Default.AllocateReadWriteTexture2D<Rgba32, Vector4>(span, source.Width, source.Height);
using ReadWriteTexture2D<Vector4> processingTexture = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadWriteTexture2D<Vector4> realTexture = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadWriteTexture2D<Vector4> imaginaryTexture = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadOnlyBuffer<Complex64> kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer<Complex64>(KernelSize);
using ReadWriteTexture2D<Rgba32, Vector4> texture = Gpu.Default.AllocateReadWriteTexture2D<Rgba32, Vector4>(span, source.Width, source.Height);
using ReadWriteTexture2D<Vector4> temporary = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadWriteTexture2D<Vector4> reals = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadWriteTexture2D<Vector4> imaginaries = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadOnlyBuffer<Complex64> kernel = Gpu.Default.AllocateReadOnlyBuffer<Complex64>(KernelSize);
// Preliminary gamma highlight pass
ApplyGammaHighlight(sourceTexture);
ref Vector4 param0 = ref MemoryMarshal.GetArrayDataReference(KernelParameters);
Gpu.Default.For<GammaHighlightProcessor>(source.Height, new(texture));
// Perform two 1D convolutions for each component in the current instance
for (int j = 0; j < Kernels.Length; j++)
{
kernelBuffer.SetData(Kernels[j]);
Vector4 parameters = Unsafe.Add(ref param0, j);
Vector4 parameters = KernelParameters[j];
ApplyVerticalConvolution(sourceTexture, realTexture, imaginaryTexture, kernelBuffer);
ApplyHorizontalConvolutionAndAccumulatePartials(realTexture, imaginaryTexture, processingTexture, kernelBuffer, parameters.Z, parameters.W);
kernel.SetData(Kernels[j]);
Gpu.Default.For<VerticalConvolutionProcessor>(
source.Width,
source.Height,
new(texture, reals, imaginaries, kernel));
Gpu.Default.For<HorizontalConvolutionAndAccumulatePartialsProcessor>(
source.Width,
source.Height,
new(parameters.Z, parameters.W, reals, imaginaries, temporary, kernel));
}
// Apply the inverse gamma exposure pass
ApplyInverseGammaExposure(processingTexture, sourceTexture);
Gpu.Default.For<InverseGammaHighlightProcessor>(source.Height, new(temporary, texture));
// Write the final pixel data
sourceTexture.GetData(span);
}
/// <summary>
/// Performs a vertical 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="source">The source <see cref="IReadOnlyTexture2D{TPixel}"/> to read data from.</param>
/// <param name="reals">The target <see cref="ReadWriteTexture2D{T}"/> to write the real results to.</param>
/// <param name="imaginaries">The target <see cref="ReadWriteTexture2D{T}"/> to write the imaginary results to.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyVerticalConvolution(
IReadWriteTexture2D<Vector4> source,
ReadWriteTexture2D<Vector4> reals,
ReadWriteTexture2D<Vector4> imaginaries,
ReadOnlyBuffer<Complex64> kernel)
{
int height = Source.Height;
int width = Source.Width;
VerticalConvolutionProcessor shader = new(
maxY: height - 1,
maxX: width - 1,
kernelLength: kernel.Length,
source,
reals,
imaginaries,
kernel);
Gpu.Default.For(width, height, in shader);
texture.GetData(span);
}
/// <summary>
@@ -320,10 +296,6 @@ namespace ComputeSharp.BokehBlur.Processors
[AutoConstructor]
internal partial struct VerticalConvolutionProcessor : IComputeShader
{
public int maxY;
public int maxX;
public int kernelLength;
public IReadWriteTexture2D<Vector4> source;
public ReadWriteTexture2D<Vector4> reals;
public ReadWriteTexture2D<Vector4> imaginaries;
@@ -334,13 +306,15 @@ namespace ComputeSharp.BokehBlur.Processors
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int maxY = source.Height;
int maxX = source.Width;
int kernelLength = kernel.Length;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
int offsetX = Hlsl.Clamp(ids.X, 0, maxX);
Vector4 color = source[offsetX, offsetY];
Complex64 factors = kernel[i];
@@ -353,49 +327,12 @@ namespace ComputeSharp.BokehBlur.Processors
}
}
/// <summary>
/// Performs an horizontal 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="reals">The source <see cref="ReadWriteTexture2D{T}"/> to read the real results from.</param>
/// <param name="imaginaries">The source <see cref="ReadWriteTexture2D{T}"/> to read the imaginary results from.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
/// <param name="z">The weight factor for the real component of the complex pixel values.</param>
/// <param name="w">The weight factor for the imaginary component of the complex pixel values.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyHorizontalConvolutionAndAccumulatePartials(
ReadWriteTexture2D<Vector4> reals,
ReadWriteTexture2D<Vector4> imaginaries,
ReadWriteTexture2D<Vector4> target,
ReadOnlyBuffer<Complex64> kernel,
float z,
float w)
{
int height = Source.Height;
int width = Source.Width;
HorizontalConvolutionAndAccumulatePartialsProcessor shader = new(
maxY: height - 1,
maxX: width - 1,
kernelLength: kernel.Length,
z,
w,
reals,
imaginaries,
target,
kernel);
Gpu.Default.For(width, height, in shader);
}
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
{
public int maxY;
public int maxX;
public int kernelLength;
public float z;
public float w;
@@ -409,13 +346,15 @@ namespace ComputeSharp.BokehBlur.Processors
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int maxY = target.Height;
int maxX = target.Width;
int kernelLength = kernel.Length;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
int offsetX = Hlsl.Clamp(ids.X + i - radiusX, 0, maxX);
Vector4 sourceReal = reals[offsetX, offsetY];
Vector4 sourceImaginary = imaginaries[offsetX, offsetY];
Complex64 factors = kernel[i];
@@ -428,29 +367,19 @@ namespace ComputeSharp.BokehBlur.Processors
}
}
/// <summary>
/// Applies the gamma highlight pass to compute the final pixel values for a target image.
/// </summary>
/// <param name="source">The source <see cref="IReadWriteTexture2D{TPixel}"/> instance to modify.</param>
[Pure]
private void ApplyGammaHighlight(IReadWriteTexture2D<Vector4> source)
{
Gpu.Default.For(source.Height, new GammaHighlightProcessor(source.Width, source));
}
/// <summary>
/// Kernel for the gamma highlight pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct GammaHighlightProcessor : IComputeShader
{
public readonly int width;
public readonly IReadWriteTexture2D<Vector4> source;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
int width = source.Width;
for (int i = 0; i < width; i++)
{
Float4 v = source[i, ids.X];
@@ -462,33 +391,20 @@ namespace ComputeSharp.BokehBlur.Processors
}
}
/// <summary>
/// Applies the inverse gamma highlight pass to compute the final pixel values for a target image.
/// </summary>
/// <param name="source">The source <see cref="ReadWriteTexture2D{T}"/> instance to read from.</param>
/// <param name="target">The target <see cref="IReadWriteTexture2D{TPixel}"/> instance to write to.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyInverseGammaExposure(
ReadWriteTexture2D<Vector4> source,
IReadWriteTexture2D<Vector4> target)
{
Gpu.Default.For(source.Height, new InverseGammaHighlightProcessor(source.Width, source, target));
}
/// <summary>
/// Kernel for the inverse gamma highlight pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader
{
public readonly int width;
public readonly ReadWriteTexture2D<Vector4> source;
public readonly IReadWriteTexture2D<Vector4> target;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
int width = source.Width;
for (int i = 0; i < width; i++)
{
Float4 v = source[i, ids.X];
+10 -66
ファイルの表示
@@ -98,48 +98,18 @@ namespace ComputeSharp.BokehBlur.Processors
using ReadWriteTexture2D<Vector4> firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadOnlyBuffer<float> kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel);
ApplyVerticalConvolution(sourceTexture, firstPassTexture, kernelBuffer);
ApplyHorizontalConvolution(firstPassTexture, sourceTexture, kernelBuffer);
Gpu.Default.For<VerticalConvolutionProcessor>(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer));
Gpu.Default.For<HorizontalConvolutionProcessor>(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer));
sourceTexture.GetData(span);
}
/// <summary>
/// Performs a vertical 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="source">The source <see cref="IReadWriteTexture2D{TPixel}"/> to read data from.</param>
/// <param name="target">The target <see cref="ReadWriteTexture2D{T}"/> to write the results to.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyVerticalConvolution(
IReadWriteTexture2D<Vector4> source,
ReadWriteTexture2D<Vector4> target,
ReadOnlyBuffer<float> kernel)
{
int height = Source.Height;
int width = Source.Width;
VerticalConvolutionProcessor shader = new(
maxY: height - 1,
maxX: width - 1,
kernel.Length,
source,
target,
kernel);
Gpu.Default.For(width, height, in shader);
}
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
{
public readonly int maxY;
public readonly int maxX;
public readonly int kernelLength;
public readonly IReadWriteTexture2D<Vector4> source;
public readonly ReadWriteTexture2D<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
@@ -148,13 +118,15 @@ namespace ComputeSharp.BokehBlur.Processors
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int maxY = source.Height - 1;
int maxX = source.Width - 1;
int kernelLength = kernel.Length;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
int offsetX = Hlsl.Clamp(ids.X, 0, maxX);
Vector4 color = source[offsetX, offsetY];
result += kernel[i] * color;
@@ -164,42 +136,12 @@ namespace ComputeSharp.BokehBlur.Processors
}
}
/// <summary>
/// Performs an horizontal 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="source">The source <see cref="ReadWriteTexture2D{T}"/> to read data from.</param>
/// <param name="target">The target <see cref="IReadWriteTexture2D{TPixel}"/> to write the results to.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyHorizontalConvolution(
ReadWriteTexture2D<Vector4> source,
IReadWriteTexture2D<Vector4> target,
ReadOnlyBuffer<float> kernel)
{
int height = Source.Height;
int width = Source.Width;
HorizontalConvolutionProcessor shader = new(
maxY: height - 1,
maxX: width - 1,
kernel.Length,
source,
target,
kernel);
Gpu.Default.For(width, height, in shader);
}
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
{
public readonly int maxY;
public readonly int maxX;
public readonly int kernelLength;
public readonly ReadWriteTexture2D<Vector4> source;
public readonly IReadWriteTexture2D<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
@@ -208,13 +150,15 @@ namespace ComputeSharp.BokehBlur.Processors
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int maxY = source.Height - 1;
int maxX = source.Width - 1;
int kernelLength = kernel.Length;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
int offsetX = Hlsl.Clamp(ids.X + i - radiusX, 0, maxX);
Vector4 color = source[offsetX, offsetY];
result += kernel[i] * color;
+5 -5
ファイルの表示
@@ -78,7 +78,7 @@ namespace ComputeSharp.SourceGenerators
var processedMembers = GetProcessedMembers(structDeclarationSymbol, discoveredTypes).ToArray();
var (entryPoint, localFunctions) = GetProcessedMethods(structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods);
var processedTypes = GetProcessedTypes(discoveredTypes).ToArray();
var processedMethods = localFunctions.Concat(staticMethods.Values.Select(static method => method.ToFullString())).ToArray();
var processedMethods = localFunctions.Concat(staticMethods.Values).Select(static method => method.NormalizeWhitespace().ToFullString()).ToArray();
// Create the compilation unit with the source attribute
var source =
@@ -140,7 +140,7 @@ namespace ComputeSharp.SourceGenerators
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
[Pure]
private static (string EntryPoint, IEnumerable<string> Methods) GetProcessedMethods(
private static (string EntryPoint, IEnumerable<SyntaxNode> Methods) GetProcessedMethods(
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
SemanticModel semanticModel,
@@ -154,7 +154,7 @@ namespace ComputeSharp.SourceGenerators
select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray();
string? entryPoint = null;
List<string> methods = new();
List<SyntaxNode> methods = new();
foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations)
{
@@ -177,12 +177,12 @@ namespace ComputeSharp.SourceGenerators
entryPoint = processedMethod.NormalizeWhitespace().ToFullString();
}
else methods.Add(processedMethod.NormalizeWhitespace().ToFullString());
else methods.Add(processedMethod);
// Emit the extracted local functions
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
{
methods.Add(localFunction.Value.NormalizeWhitespace().ToFullString());
methods.Add(localFunction.Value);
}
}
+44
ファイルの表示
@@ -31,6 +31,29 @@ namespace ComputeSharp.SourceGenerators.Mappings
[$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
};
/// <summary>
/// The mapping of supported known size accessors for HLSL resource types.
/// </summary>
private static readonly IReadOnlyDictionary<string, (int Rank, int Axis)> KnownSizeAccessors = new Dictionary<string, (int, int)>
{
["ComputeSharp.Resources.Buffer`1.Length"] = (2, 0),
["ComputeSharp.Resources.Texture2D`1.Width"] = (2, 0),
["ComputeSharp.Resources.Texture2D`1.Height"] = (2, 1),
["ComputeSharp.Resources.Texture3D`1.Width"] = (3, 0),
["ComputeSharp.Resources.Texture3D`1.Height"] = (3, 1),
["ComputeSharp.Resources.Texture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadOnlyTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadOnlyTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadOnlyTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadOnlyTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadOnlyTexture3D`1.Depth"] = (3, 2),
["ComputeSharp.IReadWriteTexture2D`1.Width"] = (2, 0),
["ComputeSharp.IReadWriteTexture2D`1.Height"] = (2, 1),
["ComputeSharp.IReadWriteTexture3D`1.Width"] = (3, 0),
["ComputeSharp.IReadWriteTexture3D`1.Height"] = (3, 1),
["ComputeSharp.IReadWriteTexture3D`1.Depth"] = (3, 2)
};
/// <summary>
/// The mapping of supported known members to HLSL names.
/// </summary>
@@ -193,5 +216,26 @@ namespace ComputeSharp.SourceGenerators.Mappings
{
return KnownIndexers.TryGetValue(name, out mapped);
}
/// <summary>
/// Tries to get the mapped HLSL-compatible indexer vector type name for the input indexer name.
/// </summary>
/// <param name="name">The input fully qualified indexer name.</param>
/// <param name="mapped">The mapped type name, if one is found.</param>
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given indexer.</returns>
[Pure]
public static bool TryGetAccessorRankAndAxis(string name, out int rank, out int axis)
{
if (KnownSizeAccessors.TryGetValue(name, out var info))
{
(rank, axis) = info;
return true;
}
(rank, axis) = default((int, int));
return false;
}
}
}
+51 -1
ファイルの表示
@@ -306,7 +306,57 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
true => ParseExpression(mapping!),
false => updatedNode.WithName(IdentifierName(mapping!))
};
}
}
// If the current member access is an access to any of the size properties in the available
// resource types (either buffer or texture types), then rewrite the subtree to transform the
// property access into an invocation of an autogenerated static helper method to get the target
// dimension for the buffer in use. The helper method is added to the list of static helpers.
if (operation is IPropertyReferenceOperation propertyOperation &&
HlslKnownMembers.TryGetAccessorRankAndAxis(propertyOperation.Property.GetFullMetadataName(), out int rank, out int axis))
{
IMethodSymbol key = propertyOperation.Property.GetMethod!;
if (!this.staticMethods.TryGetValue(key, out MethodDeclarationSyntax? methodSyntax))
{
INamedTypeSymbol resourceType = (INamedTypeSymbol)this.semanticModel.GetTypeInfo(node.Expression).Type!;
string resourceName = HlslKnownTypes.GetMappedName(resourceType);
// Create a static method to get a specified dimension for a target resource type.
// The method will automatically create the necessary number of temporary variables
// depending on the rank of the input resource (eg. 2 for Texture2D<T> resources).
// For instance, this code will generate the following tree for Texture2D<float>.Width:
//
// static int __get_Dimension0(Texture2D<float> texture)
// {
// uint _0, _1;
// texture.GetDimensions(_0, _1);
//
// return _0;
// }
methodSyntax =
MethodDeclaration(PredefinedType(Token(SyntaxKind.IntKeyword)), $"__get_Dimension{axis}")
.AddModifiers(Token(SyntaxKind.StaticKeyword))
.AddParameterListParameters(
Parameter(Identifier("resource"))
.WithType(IdentifierName(resourceName)))
.WithBody(Block(
LocalDeclarationStatement(
VariableDeclaration(PredefinedType(Token(SyntaxKind.UIntKeyword)))
.AddVariables(Enumerable.Range(0, rank).Select(static i => VariableDeclarator(Identifier("_" + i))).ToArray())),
ExpressionStatement(
InvocationExpression(MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("resource"),
IdentifierName("GetDimensions")))
.AddArgumentListArguments(Enumerable.Range(0, rank).Select(static i => Argument(IdentifierName("_" + i))).ToArray())),
ReturnStatement(IdentifierName("_" + axis))));
this.staticMethods.Add(key, methodSyntax);
}
return InvocationExpression(IdentifierName(methodSyntax.Identifier)).AddArgumentListArguments(Argument(updatedNode.Expression));
}
}
return updatedNode;