diff --git a/samples/ComputeSharp.BokehBlur/Program.cs b/samples/ComputeSharp.BokehBlur/Program.cs index f6274586..52208139 100644 --- a/samples/ComputeSharp.BokehBlur/Program.cs +++ b/samples/ComputeSharp.BokehBlur/Program.cs @@ -79,40 +79,42 @@ namespace ComputeSharp.BokehBlur for (int j = 0; j < diameter; j++) kernel[i * diameter + j] /= ones; - // Apply the effect Console.WriteLine(">> Applying effect"); - using ReadOnlyBuffer image_gpu = Gpu.Default.AllocateReadOnlyBuffer(vectorArray); - using ReadOnlyBuffer kernel_gpu = Gpu.Default.AllocateReadOnlyBuffer(kernel); - using ReadWriteBuffer result_gpu = Gpu.Default.AllocateReadWriteBuffer(vectorArray.Length); - Gpu.Default.For(height, width, id => + using (ReadOnlyBuffer image_gpu = Gpu.Default.AllocateReadOnlyBuffer(vectorArray)) + using (ReadOnlyBuffer kernel_gpu = Gpu.Default.AllocateReadOnlyBuffer(kernel)) + using (ReadWriteBuffer result_gpu = Gpu.Default.AllocateReadWriteBuffer(vectorArray.Length)) { - Vector4 total = Vector4.Zero; - - for (int y = -Radius; y <= Radius; y++) + // Apply the effect + Gpu.Default.For(height, width, id => { - for (int x = -Radius; x <= Radius; x++) + Vector4 total = Vector4.Zero; + + for (int y = -Radius; y <= Radius; y++) { - int iy = (int)id.X + y; - int jx = (int)id.Y + x; + 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; + 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; + int ki = Radius - y; + int kj = Radius - x; - total += image_gpu[(uint)(iy * width + jx)] * kernel_gpu[(uint)(ki * diameter + kj)]; + total += image_gpu[(uint)(iy * width + jx)] * kernel_gpu[(uint)(ki * diameter + kj)]; + } } - } - result_gpu[(uint)(id.X * width + id.Y)] = total; - }); + result_gpu[(uint)(id.X * width + id.Y)] = total; + }); - // Copy data back - Console.WriteLine(">> Copying data back"); - result_gpu.GetData(vectorArray); + // Copy data back + Console.WriteLine(">> Copying data back"); + result_gpu.GetData(vectorArray); + } // Copy the modified image back Console.WriteLine(">> Storing pixel data"); diff --git a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs index ae59e697..3046b64f 100644 --- a/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs +++ b/src/ComputeSharp.Shaders/Translation/MethodDecompiler.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; +using System.Text; using System.Text.RegularExpressions; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.CSharp; @@ -99,6 +100,25 @@ namespace ComputeSharp.Shaders.Translation } } + /// + /// Creates a new instance targeting a given assembly + /// + /// The path of the assembly to decompile + /// A instance that can be used on the targeted assembly + [Pure] + private static CSharpDecompiler CreateDecompiler(string assemblyPath) + { + DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest) + { + ObjectOrCollectionInitializers = false, + UsingDeclarations = false, + CSharpFormattingOptions = { IndentationString = IndentedTextWriter.DefaultTabString } + }; + + UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard"); + return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings); + } + /// /// A used to preprocess the closure type declarations for both lambda expressions and local methods /// @@ -149,8 +169,11 @@ namespace ComputeSharp.Shaders.Translation methodFixedCode = methodFixedCode.Insert(lastClosedBracketsIndex, methodOnlyIndentedSourceCode); } + // Unwrap the nested fields + string unwrappedCode = UnwrapSyntaxTree(methodFixedCode); + // Load the type syntax tree - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(methodFixedCode); + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(unwrappedCode); // Get the root node to return rootNode = syntaxTree.GetRoot().DescendantNodes().OfType().First(node => node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name)); @@ -162,22 +185,75 @@ namespace ComputeSharp.Shaders.Translation } /// - /// Creates a new instance targeting a given assembly + /// A used to find fields that represent nested closure types /// - /// The path of the assembly to decompile - /// A instance that can be used on the targeted assembly - [Pure] - private static CSharpDecompiler CreateDecompiler(string assemblyPath) - { - DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest) - { - ObjectOrCollectionInitializers = false, - UsingDeclarations = false, - CSharpFormattingOptions = { IndentationString = IndentedTextWriter.DefaultTabString } - }; + private static readonly Regex NestedClosureFieldRegex = new Regex(@"(?<=public )((?:\w+\.)+<>[\w_]+) (CS\$<>[\w_]+)(?=;)", RegexOptions.Compiled); - UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard"); - return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings); + /// + /// A used to identify compiler generated fields + /// + private static readonly Regex CompilerGeneratedFieldRegex = new Regex(@"CS\$<>[\w_]+\.", RegexOptions.Compiled); + + /// + /// Unwraps all the nested captured fields in the given source code, moving them to the top level + /// + /// The input source code to process + [Pure] + private string UnwrapSyntaxTree(string source) + { + List parsedFields = new List(); + + // Local function to recursively extract all the nested fields + void ParseNestedFields(string source) + { + // Find the field declarations + Match match = NestedClosureFieldRegex.Match(source); + if (!match.Success) return; + + // Load the nested closure type + string fullname = match.Groups[1].Value.Replace(".<>", "+<>"); // Fullname of a nested type + Type type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(fullname)).First(t => t != null); + + // Decompile the type and get a readable source code + EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(type.MetadataToken) ?? throw new InvalidOperationException(); + CSharpDecompiler decompiler = Decompilers[type.Assembly.Location]; + string + sourceCode = decompiler.DecompileAsString(typeHandle), + typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Scope"); + + // Load the syntax tree and retrieve the list of fields + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(typeFixedCode); + FieldDeclarationSyntax[] fields = syntaxTree.GetRoot().DescendantNodes().OfType().First().ChildNodes().OfType().ToArray(); + + // Add the captured fields + foreach (FieldDeclarationSyntax field in fields) + if (!field.Declaration.Variables.ToFullString().StartsWith("CS$<>")) + parsedFields.Add(field); + + // Explore the new decompiled type + ParseNestedFields(typeFixedCode); + } + + ParseNestedFields(source); + + if (parsedFields.Count > 0) + { + // Build the aggregated string with all the captured fields + StringBuilder builder = new StringBuilder(); + foreach (FieldDeclarationSyntax field in parsedFields) + builder.AppendLine(field.ToFullString()); + string fields = builder.ToString().TrimEnd(' ', '\r', '\n'); + + // Replace the field declarations + Match match = NestedClosureFieldRegex.Match(source); + source = source.Remove(match.Index - 11, match.Length + 12); // leading " public " and trailing ";" + source = source.Insert(match.Index - 11, fields); + + // Adjust the method body to remove references to compiler generated fields + source = CompilerGeneratedFieldRegex.Replace(source, string.Empty); + } + + return source; } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index 669f05c2..5e2f5e4d 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -72,24 +72,46 @@ namespace ComputeSharp.Shaders.Translation /// /// The of instances mapping the captured buffers in the current shader /// - private readonly List _BufferMembers = new List(); + private readonly List<(ReadableMember Member, IEnumerable? Parents)> _BufferMembers = new List<(ReadableMember, IEnumerable?)>(); /// /// Gets the ordered collection of buffers used as fields in the current shader /// /// The to use to build the shader - public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action action) => _BufferMembers.Select((field, i) => (i + 1, (GraphicsResource)field.GetValue(action.Target))); + public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action action) + { + foreach (var (item, i) in _BufferMembers.Select((item, i) => (item, i))) + { + if (item.Parents == null) yield return (i + 1, (GraphicsResource)item.Member.GetValue(action.Target)); + else + { + object target = item.Parents.Aggregate(action.Target, (obj, member) => member.GetValue(obj)); + yield return (i + 1, (GraphicsResource)item.Member.GetValue(target)); + } + } + } /// /// The of instances mapping the captured scalar/vector variables in the current shader /// - private readonly List _VariableMembers = new List(); + private readonly List<(ReadableMember Member, IEnumerable? Parents)> _VariableMembers = new List<(ReadableMember, IEnumerable?)>(); /// /// Gets the collection of values of the captured fields for the current shader /// /// The to use to build the shader - public IEnumerable GetVariables(Action action) => _VariableMembers.Select(field => field.GetValue(action.Target)); + public IEnumerable GetVariables(Action action) + { + foreach (var item in _VariableMembers) + { + if (item.Parents == null) yield return item.Member.GetValue(action.Target); + else + { + object target = item.Parents.Aggregate(action.Target, (obj, member) => member.GetValue(obj)); + yield return item.Member.GetValue(target); + } + } + } private readonly List _BuffersList = new List(); @@ -154,7 +176,8 @@ namespace ComputeSharp.Shaders.Translation /// /// The target to load /// The optional explicit name to use for the field - private void LoadFieldInfo(ReadableMember memberInfo, string? name = null) + /// The list of parent fields to reach the current from a given + private void LoadFieldInfo(ReadableMember memberInfo, string? name = null, IReadOnlyList? parents = null) { Type fieldType = memberInfo.MemberType; string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name); @@ -165,7 +188,7 @@ namespace ComputeSharp.Shaders.Translation DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount)); // Track the buffer field - _BufferMembers.Add(memberInfo); + _BufferMembers.Add((memberInfo, parents)); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); _BuffersList.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, _ConstantBuffersCount++)); @@ -176,7 +199,7 @@ namespace ComputeSharp.Shaders.Translation DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount)); // Track the buffer field - _BufferMembers.Add(memberInfo); + _BufferMembers.Add((memberInfo, parents)); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, _ReadOnlyBuffersCount++)); @@ -187,7 +210,7 @@ namespace ComputeSharp.Shaders.Translation DescriptorRanges.Add(new DescriptorRange(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount)); // Track the buffer field - _BufferMembers.Add(memberInfo); + _BufferMembers.Add((memberInfo, parents)); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, _ReadWriteBuffersCount++)); @@ -195,10 +218,23 @@ namespace ComputeSharp.Shaders.Translation else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { // Register the captured field - _VariableMembers.Add(memberInfo); + _VariableMembers.Add((memberInfo, parents)); string typeName = HlslKnownTypes.GetMappedName(fieldType); _FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); } + else if (fieldType.IsClass && fieldName.StartsWith("CS$<>")) + { + // Captured scope, update the parents list + List updatedParents = parents?.ToList() ?? new List(); + updatedParents.Add(memberInfo); + + // Recurse on the new compiler generated class + IReadOnlyList fields = fieldType.GetFields().ToArray(); + foreach (FieldInfo fieldInfo in fields) + { + LoadFieldInfo(fieldInfo, null, updatedParents); + } + } } ///