using System; using System.Buffers; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Shaders.Renderer.Models; using ComputeSharp.Shaders.Translation; namespace ComputeSharp.Shaders.Renderer { /// /// A type that renders an HLSL template from the previously loaded shader data. /// internal static class HlslShaderRenderer { /// /// Renders a new HLSL shader source with the given parameters. /// /// The number of threads in each thread group for the X axis. /// The number of threads in each thread group for the Y axis. /// The number of threads in each thread group for the Z axis. /// The input instance with the shader information. /// The source code for the new HLSL shader. [Pure] public static ArrayPoolStringBuilder Render(int threadsX, int threadsY, int threadsZ, IShaderLoader info) { var builder = ArrayPoolStringBuilder.Create(); // Header builder.AppendLine("// ================================================"); builder.AppendLine("// AUTO GENERATED"); builder.AppendLine("// ================================================"); builder.AppendLine("// This shader was created by ComputeSharp."); builder.AppendLine("// See: https://github.com/Sergio0694/ComputeSharp."); // Declared types foreach (var type in info.DeclaredTypes) { builder.AppendLine(); builder.AppendLine(type); } // Captured variables builder.AppendLine(); builder.AppendLine("cbuffer _ : register(b0)"); builder.AppendLine('{'); builder.AppendLine(" uint __x;"); builder.AppendLine(" uint __y;"); builder.AppendLine(" uint __z;"); foreach (var local in info.FieldsInfo) { builder.Append(" "); builder.Append(local.FieldType); builder.Append(' '); builder.Append(local.FieldName); builder.AppendLine(';'); } builder.AppendLine('}'); // Buffers foreach (var buffer in info.HlslResourceInfo) { builder.AppendLine(); switch (buffer) { // Constant buffer go to cbuffer fields with a dummy local case HlslResourceInfo.Constant _: builder.Append("cbuffer _"); builder.Append(buffer.FieldName); builder.Append(" : register(b"); builder.Append(buffer.BufferIndex.ToString()); builder.AppendLine(')'); builder.AppendLine('{'); builder.Append(" "); builder.Append(buffer.FieldType); builder.Append(' '); builder.Append(buffer.FieldName); builder.Append("[2];"); builder.AppendLine('}'); break; // Structured buffer have the same syntax but different id case HlslResourceInfo.ReadOnly _: char registerId = 't'; goto StructuredBuffer; case HlslResourceInfo.ReadWrite _: registerId = 'u'; StructuredBuffer: builder.Append(buffer.FieldType); builder.Append(' '); builder.Append(buffer.FieldName); builder.Append(" : register("); builder.Append(registerId); builder.Append(buffer.BufferIndex.ToString()); builder.AppendLine(");"); break; } } // Captured methods foreach (var function in info.MethodsInfo) { builder.AppendLine(); builder.AppendLine(function); } // Entry point builder.AppendLine(); builder.Append("[NumThreads("); builder.Append(threadsX.ToString()); builder.Append(", "); builder.Append(threadsY.ToString()); builder.Append(", "); builder.Append(threadsZ.ToString()); builder.AppendLine(")]"); builder.AppendLine(info.EntryPoint); return builder; } /// /// A helper type that implements a pooled buffer writer for values. /// [DebuggerTypeProxy(typeof(DebugView))] public ref struct ArrayPoolStringBuilder { /// /// The underlying array. /// private char[] array; /// /// The starting offset within . /// private int index; /// /// Creates a new instance ready to use. /// /// A new instance with default values. [Pure] public static ArrayPoolStringBuilder Create() { ArrayPoolStringBuilder builder; builder.array = ArrayPool.Shared.Rent(1024); builder.index = 0; return builder; } /// public ReadOnlySpan WrittenSpan { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => new(this.array, 0, this.index); } /// /// Appends the input sequence of characters to the current buffer. /// /// The input characters to write. public void Append(ReadOnlySpan value) { EnsureCapacity(value.Length); value.CopyTo(this.array.AsSpan(this.index)); this.index += value.Length; } /// /// Appends a character to the current buffer. /// public void Append(char character) { EnsureCapacity(1); this.array[this.index++] = character; } /// /// Appends the input sequence of characters to the current buffer, with a trailing new line. /// /// The input characters to write. public void AppendLine(ReadOnlySpan value) { EnsureCapacity(value.Length + 1); value.CopyTo(this.array.AsSpan(this.index)); this.index += value.Length; this.array[this.index++] = '\n'; } /// /// Appends a character and a new line to the current buffer. /// public void AppendLine(char character) { EnsureCapacity(2); this.array[this.index++] = character; this.array[this.index++] = '\n'; } /// /// Appends a new line to the current buffer. /// public void AppendLine() { EnsureCapacity(1); this.array[this.index++] = '\n'; } /// /// Ensures that has enough free space to contain a given number of new items. /// /// The minimum number of items to ensure space for in . [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnsureCapacity(int requestedSize) { if (requestedSize > this.array.Length - this.index) { ResizeBuffer(requestedSize); } } /// /// Resizes to ensure it can fit the specified number of new items. /// /// The minimum number of items to ensure space for in . [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.Shared.Rent(minimumSize); int itemsToCopy = Math.Min(this.array.Length, minimumSize); Array.Copy(this.array, 0, newArray, 0, itemsToCopy); ArrayPool.Shared.Return(array); this.array = newArray; } /// public void Dispose() { ArrayPool.Shared.Return(this.array); } /// /// A debug proxy used for displaying debug info. /// internal sealed class DebugView { /// /// Initializes a new instance of the class with the specified parameters. /// /// The input instance to display. public DebugView(ArrayPoolStringBuilder builder) { Text = builder.WrittenSpan.ToString(); } /// /// Gets the text to display for the current instance. /// public string Text { get; } } } } }