Merge pull request #31 from Sergio0694/bugfix_handle-reserved-keywords
Bokeh blur sample, bug fixes
このコミットが含まれているのは:
9ファイル変更
+254
-10
検索条件に一致するファイルはありません
@@ -328,3 +328,6 @@ ASALocalRun/
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Sample bokeh blur image
|
||||
**/*_bokeh.jpg
|
||||
@@ -0,0 +1,26 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp3.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="city.jpg" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="city.jpg">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.0-beta0006" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,140 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Tasks;
|
||||
using ComputeSharp.Graphics.Buffers;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Advanced;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using Vector4 = System.Numerics.Vector4;
|
||||
|
||||
namespace ComputeSharp.BokehBlur
|
||||
{
|
||||
class Program
|
||||
{
|
||||
/// <summary>
|
||||
/// The radius of the bokeh blur effect to apply
|
||||
/// </summary>
|
||||
private const int Radius = 48;
|
||||
|
||||
/// <summary>
|
||||
/// The gamma exposure value to use when applying the effect
|
||||
/// </summary>
|
||||
private const float Gamma = 3;
|
||||
|
||||
static void Main()
|
||||
{
|
||||
// Load the input image
|
||||
Console.WriteLine(">> Loading image");
|
||||
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "city.jpg");
|
||||
using Image<Rgba32> image = Image.Load(path);
|
||||
var (height, width) = (image.Height, image.Width);
|
||||
|
||||
// Get the vector buffer
|
||||
Console.WriteLine(">> Getting pixel data");
|
||||
Vector4[] vectorArray = new Vector4[height * width];
|
||||
|
||||
// Populate the buffer
|
||||
Parallel.For(0, height, i =>
|
||||
{
|
||||
ref Rgba32 rPixel = ref image.GetPixelRowSpan(i).GetPinnableReference();
|
||||
ref Vector4 r4 = ref vectorArray[i * width];
|
||||
|
||||
for (int j = 0; j < width; j++)
|
||||
{
|
||||
Vector4 v4 = Unsafe.Add(ref rPixel, j).ToVector4();
|
||||
v4.X = MathF.Pow(v4.X, Gamma);
|
||||
v4.Y = MathF.Pow(v4.Y, Gamma);
|
||||
v4.Z = MathF.Pow(v4.Z, Gamma);
|
||||
Unsafe.Add(ref r4, j) = v4;
|
||||
}
|
||||
});
|
||||
|
||||
Console.WriteLine(">> Creating kernel");
|
||||
int diameter = Radius * 2 + 1;
|
||||
float[] kernel = new float[diameter * diameter];
|
||||
int ones = 0;
|
||||
for (int i = 0; i < diameter; i++)
|
||||
{
|
||||
for (int j = 0; j < diameter; j++)
|
||||
{
|
||||
if (MathF.Sqrt(MathF.Pow(j - Radius, 2) + MathF.Pow(i - Radius, 2)) - 0.1f <= Radius)
|
||||
{
|
||||
kernel[i * diameter + j] = 1;
|
||||
ones++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine(">> Normalizing kernel");
|
||||
for (int i = 0; i < diameter; i++)
|
||||
for (int j = 0; j < diameter; j++)
|
||||
kernel[i * diameter + j] /= ones;
|
||||
|
||||
// Apply the effect
|
||||
Console.WriteLine(">> Applying effect");
|
||||
using ReadOnlyBuffer<Vector4> image_gpu = Gpu.Default.AllocateReadOnlyBuffer(vectorArray);
|
||||
using ReadOnlyBuffer<float> kernel_gpu = Gpu.Default.AllocateReadOnlyBuffer(kernel);
|
||||
using ReadWriteBuffer<Vector4> result_gpu = Gpu.Default.AllocateReadWriteBuffer<Vector4>(vectorArray.Length);
|
||||
Gpu.Default.For(height, width, id =>
|
||||
{
|
||||
Vector4 total = Vector4.Zero;
|
||||
|
||||
for (int y = -Radius; y <= Radius; y++)
|
||||
{
|
||||
for (int x = -Radius; x <= Radius; x++)
|
||||
{
|
||||
int iy = (int)id.X + y;
|
||||
int jx = (int)id.Y + x;
|
||||
|
||||
if (iy < 0) iy = -iy;
|
||||
else if (iy > height) iy = 2 * height - iy;
|
||||
if (jx < 0) jx = -jx;
|
||||
else if (jx > width) jx = 2 * width - jx;
|
||||
|
||||
int ki = Radius - y;
|
||||
int kj = Radius - x;
|
||||
|
||||
total += image_gpu[(uint)(iy * width + jx)] * kernel_gpu[(uint)(ki * diameter + kj)];
|
||||
}
|
||||
}
|
||||
|
||||
result_gpu[(uint)(id.X * width + id.Y)] = total;
|
||||
});
|
||||
|
||||
// Copy data back
|
||||
Console.WriteLine(">> Copying data back");
|
||||
result_gpu.GetData(vectorArray);
|
||||
|
||||
// Copy the modified image back
|
||||
Console.WriteLine(">> Storing pixel data");
|
||||
Parallel.For(0, height, i =>
|
||||
{
|
||||
ref Rgba32 rPixel = ref image.GetPixelRowSpan(i).GetPinnableReference();
|
||||
ref Vector4 r4 = ref vectorArray[i * width];
|
||||
Vector4 low = Vector4.Zero;
|
||||
Vector4 high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
|
||||
float invGamma = 1 / Gamma;
|
||||
|
||||
for (int j = 0; j < width; j++)
|
||||
{
|
||||
Vector4 v4 = Unsafe.Add(ref r4, j);
|
||||
Vector4 clamp = Vector4.Clamp(v4, low, high);
|
||||
v4.X = MathF.Pow(clamp.X, invGamma);
|
||||
v4.Y = MathF.Pow(clamp.Y, invGamma);
|
||||
v4.Z = MathF.Pow(clamp.Z, invGamma);
|
||||
|
||||
Unsafe.Add(ref rPixel, j).FromVector4(v4);
|
||||
}
|
||||
});
|
||||
|
||||
// Save the resulting image
|
||||
Console.WriteLine(">> Saving to disk");
|
||||
string targetPath = Path.Combine(
|
||||
Path.GetRelativePath(Path.GetDirectoryName(path), @"..\..\..\"),
|
||||
$"{Path.GetFileNameWithoutExtension(path)}_bokeh{Path.GetExtension(path)}");
|
||||
image.Save(targetPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 1.3 MiB |
@@ -0,0 +1,64 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace ComputeSharp.Shaders.Mappings
|
||||
{
|
||||
/// <summary>
|
||||
/// A <see langword="class"/> that contains and maps known HLSL method names to common .NET method
|
||||
/// </summary>
|
||||
internal static class HlslKnownKeywords
|
||||
{
|
||||
/// <summary>
|
||||
/// The mapping of supported known methods to HLSL methods
|
||||
/// </summary>
|
||||
private static readonly IReadOnlyCollection<string> KnownKeywords = new[]
|
||||
{
|
||||
"asm", "asm_fragment", "cbuffer", "centroid", "column_major",
|
||||
"compile", "discard", "dword", "export", "fxgroup", "groupshared",
|
||||
"half", "inline", "inout", "line", "lineadj", "linear", "matrix",
|
||||
"nointerpolation", "noperspective", "NULL", "packoffset", "pass",
|
||||
"pixelfragment", "point", "precise", "register", "row_major", "sample",
|
||||
"sampler", "shared", "snorm", "stateblock", "stateblock_state", "tbuffer",
|
||||
"technique", "typedef", "triangle", "triangleadj", "uniform", "unorm",
|
||||
"unsigned", "vector", "vertexfragment", "zero"
|
||||
};
|
||||
|
||||
private static Regex _KeywordsRegex;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="Regex"/> to use to match variable names
|
||||
/// </summary>
|
||||
private static Regex KeywordsRegex
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_KeywordsRegex == null)
|
||||
{
|
||||
string
|
||||
keywords = string.Join("|", KnownKeywords),
|
||||
pattern = $@"(?<![A-Za-z])(?:{keywords})(?!\w)";
|
||||
_KeywordsRegex = new Regex(pattern, RegexOptions.Compiled);
|
||||
}
|
||||
|
||||
return _KeywordsRegex;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapped HLSL-compatible variable name for the input identifier name
|
||||
/// </summary>
|
||||
/// <param name="name">The input variable name to map</param>
|
||||
/// <returns>The HLSL-compatible variable name name that can be used in an HLSL shader</returns>
|
||||
[Pure]
|
||||
public static string GetMappedName(string name) => KeywordsRegex.IsMatch(name) ? $"_{name}" : name;
|
||||
|
||||
/// <summary>
|
||||
/// Processes an input text and replaces all the occurrences of reserved keywords
|
||||
/// </summary>
|
||||
/// <param name="text">The input text to process</param>
|
||||
/// <returns>A valid shader body source code that can be used in HLSL</returns>
|
||||
[Pure]
|
||||
public static string GetMappedText(string text) => KeywordsRegex.Replace(text, m => $"_{m.Value}");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using ComputeSharp.Graphics;
|
||||
using ComputeSharp.Graphics.Buffers.Abstract;
|
||||
using ComputeSharp.Graphics.Buffers.Extensions;
|
||||
@@ -40,7 +41,7 @@ namespace ComputeSharp.Shaders
|
||||
/// <summary>
|
||||
/// The mapping used to cache and reuse compiled shaders
|
||||
/// </summary>
|
||||
private static readonly Dictionary<(Type type, int ThreadsX, int ThreadsY, int ThreadsZ), (ShaderLoader Loader, ShaderBytecode Bytecode)> ShadersCache = new Dictionary<(Type, int, int, int), (ShaderLoader, ShaderBytecode)>();
|
||||
private static readonly Dictionary<(MethodInfo Method, int ThreadsX, int ThreadsY, int ThreadsZ), (ShaderLoader Loader, ShaderBytecode Bytecode)> ShadersCache = new Dictionary<(MethodInfo, int, int, int), (ShaderLoader, ShaderBytecode)>();
|
||||
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters
|
||||
@@ -66,7 +67,7 @@ namespace ComputeSharp.Shaders
|
||||
groupsZ = z / threadsZ + (z % threadsZ == 0 ? 0 : 1);
|
||||
|
||||
// Try to get the cache shader
|
||||
var key = (action.Method.DeclaringType, threadsX, threadsY, threadsZ);
|
||||
var key = (action.Method, threadsX, threadsY, threadsZ);
|
||||
if (!ShadersCache.TryGetValue(key, out var shaderData))
|
||||
{
|
||||
// Load the input shader
|
||||
|
||||
@@ -107,7 +107,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// <summary>
|
||||
/// A <see cref="Regex"/> used to preprocess the entry point declaration for both lambda expressions and local methods
|
||||
/// </summary>
|
||||
private static readonly Regex LambdaMethodDeclarationRegex = new Regex(@"(private|internal) void <\w+>[\w_|]+(?=\()", RegexOptions.Compiled);
|
||||
private static readonly Regex LambdaMethodDeclarationRegex = new Regex(@"(?:private|internal) void <\w+>[\w_|]+(?=\()", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// Decompiles a target method and returns its <see cref="SyntaxTree"/> and <see cref="SemanticModel"/> info
|
||||
@@ -134,7 +134,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
string
|
||||
sourceCode = decompiler.DecompileAsString(typeHandle),
|
||||
typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Shader"),
|
||||
methodFixedCode = LambdaMethodDeclarationRegex.Replace(typeFixedCode, "internal void Main");
|
||||
methodFixedCode = LambdaMethodDeclarationRegex.Replace(typeFixedCode, m => $"// {m.Value}{Environment.NewLine} internal void Main");
|
||||
|
||||
// Workaround for some local methods not being decompiled correctly
|
||||
if (!methodFixedCode.Contains("internal void Main"))
|
||||
@@ -142,7 +142,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
EntityHandle methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException();
|
||||
string
|
||||
methodOnlySourceCode = decompiler.DecompileAsString(methodHandle),
|
||||
methodOnlyFixedSourceCode = LambdaMethodDeclarationRegex.Replace(methodOnlySourceCode, "internal void Main"),
|
||||
methodOnlyFixedSourceCode = LambdaMethodDeclarationRegex.Replace(methodOnlySourceCode, m => $"// {m.Value}{Environment.NewLine} internal void Main"),
|
||||
methodOnlyIndentedSourceCode = $" {methodOnlyFixedSourceCode.Replace(Environment.NewLine, $"{Environment.NewLine} ")}";
|
||||
|
||||
int lastClosedBracketsIndex = methodFixedCode.LastIndexOf('}');
|
||||
@@ -153,7 +153,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(methodFixedCode);
|
||||
|
||||
// Get the root node to return
|
||||
rootNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
|
||||
rootNode = syntaxTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(node => node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name));
|
||||
|
||||
// Update the incremental compilation and retrieve the syntax tree for the method
|
||||
_Compilation = _Compilation.AddSyntaxTrees(syntaxTree);
|
||||
|
||||
@@ -157,7 +157,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
private void LoadFieldInfo(ReadableMember memberInfo, string? name = null)
|
||||
{
|
||||
Type fieldType = memberInfo.MemberType;
|
||||
string fieldName = name ?? memberInfo.Name;
|
||||
string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name);
|
||||
|
||||
// Constant buffer
|
||||
if (HlslKnownTypes.IsConstantBufferType(fieldType))
|
||||
@@ -199,7 +199,6 @@ namespace ComputeSharp.Shaders.Translation
|
||||
string typeName = HlslKnownTypes.GetMappedName(fieldType);
|
||||
_FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName));
|
||||
}
|
||||
else throw new NotSupportedException($"Unsupported field of type {fieldType.FullName}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -227,7 +226,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
// Additional preprocessing
|
||||
MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
|
||||
MethodBody = MethodBody.TrimEnd('\n', '\r', ' ');
|
||||
MethodBody = Regex.Replace(MethodBody, @"(?<!A-Za-z)vector(?!\w)", "_vector"); // The decompiler can name a local Vector[2,3,4] variable as "vector"
|
||||
MethodBody = HlslKnownKeywords.GetMappedText(MethodBody);
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -24,7 +24,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests", "..\te
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.Internals", "..\tests\ComputeSharp.Tests.Internals\ComputeSharp.Tests.Internals.csproj", "{E889E6D6-A814-4950-AAC1-68F1ECFC5BD6}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Benchmark", "..\samples\ComputeSharp.Benchmark\ComputeSharp.Benchmark.csproj", "{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Benchmark", "..\samples\ComputeSharp.Benchmark\ComputeSharp.Benchmark.csproj", "{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.BokehBlur", "..\samples\ComputeSharp.BokehBlur\ComputeSharp.BokehBlur.csproj", "{524CC5DD-1DEE-4A30-9515-AB90965E5207}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@@ -90,6 +92,14 @@ Global
|
||||
{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF}.Release|x64.Build.0 = Release|Any CPU
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207}.Release|x64.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -99,6 +109,7 @@ Global
|
||||
{E91F4D24-922A-4921-A8D7-9C45A143C45D} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
|
||||
{E889E6D6-A814-4950-AAC1-68F1ECFC5BD6} = {F8EFBB27-4EE2-4463-A75B-7EFDFB55D0F7}
|
||||
{34AFE6E6-9A4C-4C3F-AE69-DD3693086DAF} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
|
||||
{524CC5DD-1DEE-4A30-9515-AB90965E5207} = {0ED8F632-5E17-46BE-8CC3-B14A82D4AEB1}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {4664C5E3-0340-4E22-BCFD-98AAEDF5F2DC}
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする