diff --git a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs index 2fd92fa0..26f4f0cf 100644 --- a/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs +++ b/samples/ComputeSharp.SwapChain/Backend/SwapChainApplication{T}.cs @@ -6,12 +6,12 @@ using FX = TerraFX.Interop.Windows; namespace ComputeSharp.SwapChain.Backend { internal sealed class SwapChainApplication : Win32Application - where T : struct, IComputeShader + where T : struct, IPixelShader { /// - /// The instance used to create shaders to run. + /// The instance used to create shaders to run. /// - private readonly Func, TimeSpan, T> shaderFactory; + private readonly Func shaderFactory; /// /// The pointer for the device currently in use. @@ -76,8 +76,8 @@ namespace ComputeSharp.SwapChain.Backend /// /// Creates a new instance with the specified parameters. /// - /// The instance used to create shaders to run. - public SwapChainApplication(Func, TimeSpan, T> shaderFactory) + /// The instance used to create shaders to run. + public SwapChainApplication(Func shaderFactory) { this.shaderFactory = shaderFactory; } @@ -231,12 +231,12 @@ namespace ComputeSharp.SwapChain.Backend } // Generate the new frame - Gpu.Default.For(this.texture!.Width, this.texture.Height, this.shaderFactory(this.texture, time)); + Gpu.Default.ForEach(this.texture!, this.shaderFactory(time)); using ComPtr d3D12Resource = default; // Get the underlying ID3D12Resource pointer for the texture - _ = InteropServices.TryGetID3D12Resource(this.texture, FX.__uuidof(), (void**)d3D12Resource.GetAddressOf()); + _ = InteropServices.TryGetID3D12Resource(this.texture!, FX.__uuidof(), (void**)d3D12Resource.GetAddressOf()); // Get the target back buffer to update ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch diff --git a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj index 44b2ad45..9f8fe3d7 100644 --- a/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj +++ b/samples/ComputeSharp.SwapChain/ComputeSharp.SwapChain.csproj @@ -5,6 +5,10 @@ net5.0 + + + + + + + PreserveNewest + + + diff --git a/samples/ComputeSharp.SwapChain/Program.cs b/samples/ComputeSharp.SwapChain/Program.cs index 2ab00306..c976ee4d 100644 --- a/samples/ComputeSharp.SwapChain/Program.cs +++ b/samples/ComputeSharp.SwapChain/Program.cs @@ -1,25 +1,38 @@ using System; +using System.Diagnostics.Contracts; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using ComputeSharp.SwapChain.Backend; using ComputeSharp.SwapChain.Shaders; +using SixLabors.ImageSharp; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; namespace ComputeSharp.SwapChain { class Program { + /// + /// A texture for \Textures\RustyMetal.png. + /// + private static readonly IReadOnlyTexture2D RustyMetal = LoadTexture(); + /// /// The mapping of available samples to choose from. /// private static readonly Win32Application[] Samples = new Win32Application[] { - new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), - new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), - new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), - new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), - new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), - new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), - new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), - new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)), - new SwapChainApplication(static (texture, time) => new(texture, (float)time.TotalSeconds)) + new SwapChainApplication(static time => new((float)time.TotalSeconds)), + new SwapChainApplication(static time => new((float)time.TotalSeconds)), + new SwapChainApplication(static time => new((float)time.TotalSeconds)), + new SwapChainApplication(static time => new((float)time.TotalSeconds)), + new SwapChainApplication(static time => new((float)time.TotalSeconds)), + new SwapChainApplication(static time => new((float)time.TotalSeconds)), + new SwapChainApplication(static time => new((float)time.TotalSeconds)), + new SwapChainApplication(static time => new((float)time.TotalSeconds)), + new SwapChainApplication(static time => new((float)time.TotalSeconds)), + new SwapChainApplication(static time => new((float)time.TotalSeconds, RustyMetal)) }; static void Main() @@ -47,5 +60,26 @@ namespace ComputeSharp.SwapChain Win32ApplicationRunner.Run(Samples[index]); } + + /// + /// Allocates a new instance with the specified texture data. + /// + /// The name of the texture to load. + /// A texture with the data from the image at the specified name. + [Pure] + private static ReadOnlyTexture2D LoadTexture([CallerMemberName] string name = null!) + { + string filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Textures", $"{name}.png"); + + using Image image = Image.Load(filename); + + ReadOnlyTexture2D texture = Gpu.Default.AllocateReadOnlyTexture2D(image.Width, image.Height); + + image.TryGetSinglePixelSpan(out Span span); + + texture.CopyFrom(MemoryMarshal.Cast(span)); + + return texture; + } } } diff --git a/samples/ComputeSharp.SwapChain/Shaders/ColorfulInfinity.cs b/samples/ComputeSharp.SwapChain/Shaders/ColorfulInfinity.cs index 034330fa..267c2d55 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/ColorfulInfinity.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/ColorfulInfinity.cs @@ -7,13 +7,8 @@ /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] - internal readonly partial struct ColorfulInfinity : IComputeShader + internal readonly partial struct ColorfulInfinity : IPixelShader { - /// - /// The target texture. - /// - public readonly IReadWriteTexture2D texture; - /// /// The current time since the start of the application. /// @@ -49,7 +44,7 @@ } /// - public void Execute() + public Float4 Execute() { Float2 uv = (ThreadIds.XY - (Float2)DispatchSize.XY * 0.5f) / DispatchSize.Y; Float3 col = 0; @@ -68,9 +63,7 @@ col *= new Float3(2, 1.0f, 2.0f); col = Hlsl.Pow(col, 0.5f); - Float4 color = new(col.X, col.Y, col.Z, 1.0f); - - texture[ThreadIds.XY] = color; + return new(col.X, col.Y, col.Z, 1.0f); } } } diff --git a/samples/ComputeSharp.SwapChain/Shaders/ContouredLayers.cs b/samples/ComputeSharp.SwapChain/Shaders/ContouredLayers.cs new file mode 100644 index 00000000..b0a6fde4 --- /dev/null +++ b/samples/ComputeSharp.SwapChain/Shaders/ContouredLayers.cs @@ -0,0 +1,197 @@ +namespace ComputeSharp.SwapChain.Shaders +{ + /// + /// Constructing some concise contoured layers, then applying various edge and shading effects to produce some faux depth. + /// Ported from . + /// Created by Shane. + /// + [AutoConstructor] + internal readonly partial struct ContouredLayers : IPixelShader + { + /// + /// The current time Hlsl.Since the start of the application. + /// + public readonly float time; + + /// + /// The background texture to sample. + /// + public readonly IReadOnlyTexture2D texture; + + // Float3 to float hash. + private static float Hash21(Float2 p) + { + return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new Float2(41, 289))) * 45758.5453f); + } + + // Float2 to Float2 hash. + private Float2 Hash22(Float2 p) + { + float n = Hlsl.Sin(Hlsl.Dot(p, new Float2(1, 113))); + + p = Hlsl.Frac(new Float2(262144, 32768) * n); + + return Hlsl.Sin(p * 6.2831853f + time); + } + + // Float2 to Float2 hash. + private static Float2 Hash22B(Float2 p) + { + float n = Hlsl.Sin(Hlsl.Dot(p, new Float2(41, 289))); + + return Hlsl.Frac(new Float2(262144, 32768) * n) * 2.0f - 1.0f; + } + + // Smooth 2D noise + private static float Noise2D(Float2 p) + { + Float2 i = Hlsl.Floor(p); + + p -= i; + + Float4 v = default; + + v.X = Hlsl.Dot(Hash22B(i), p); + v.Y = Hlsl.Dot(Hash22B(i + Float2.UnitX), p - Float2.UnitX); + v.Z = Hlsl.Dot(Hash22B(i + Float2.UnitY), p - Float2.UnitY); + v.W = Hlsl.Dot(Hash22B(i + 1.0f), p - 1.0f); + + p = p * p * (3.0f - 2.0f * p); + + return Hlsl.Lerp(Hlsl.Lerp(v.X, v.Y, p.X), Hlsl.Lerp(v.Z, v.W, p.X), p.Y); + } + + // Based on IQ's gradient noise formula. + private float Noise2D3G(Float2 p) + { + Float2 i = Hlsl.Floor(p); + + p -= i; + + Float4 v = default; + + v.X = Hlsl.Dot(Hash22(i), p); + v.Y = Hlsl.Dot(Hash22(i + Float2.UnitX), p - Float2.UnitX); + v.Z = Hlsl.Dot(Hash22(i + Float2.UnitY), p - Float2.UnitY); + v.W = Hlsl.Dot(Hash22(i + 1.0f), p - 1.0f); + + p = p * p * p * (p * (p * 6.0f - 15.0f) + 10.0f); + + return Hlsl.Lerp(Hlsl.Lerp(v.X, v.Y, p.X), Hlsl.Lerp(v.Z, v.W, p.X), p.Y); + } + + // Map function with noise layers + private float MapNoise(Float3 p, float i) + { + return Noise2D3G(p.XY * 3.0f) * 0.66f + Noise2D3G(p.XY * 6.0f) * 0.34f + i / 10.0f * 1.0f - 0.15f; + } + + // 2D derivative function. + private Float3 GetNormal(in Float3 p, float m, float i) + { + Float2 e = new(0.001f, 0); + + return new Float3(m - MapNoise(p - e.XYY, i), m - MapNoise(p - e.YXY, i), 0.0f) / e.X * 1.4142f; + } + + // The map layer and its derivative + private Float4 MapLayer(in Float3 p, float i) + { + Float4 d = default; + + d.X = MapNoise(p, i); + d.YZW = GetNormal(p, d.X, i); + + return d; + } + + // Layer color. Based on the shade, layer number and smoothing factor. + private Float3 GetColor(Float2 p, float sh, float fi) + { + Float3 tx = texture[p + Hash21(new Float2(sh, fi))].XYZ; + + tx *= tx; + + Float3 col; + + col = (Float3)1.0 * (1.0f - 0.75f / (1.0f + sh * sh * 2.0f)); + col = Hlsl.Min(col * tx * 3.0f, 1.0f); + + return col; + } + + // A hatch-like algorithm, or a stipple... or some kind of textured pattern. + private float Hatch(Float2 p, float res) + { + p *= res / 16.0f; + + float hatch = Hlsl.Clamp(Hlsl.Sin((p.X - p.Y) * 3.14159f * 200.0f) * 2.0f + 0.5f, 0.0f, 1.0f); + + float hRnd = Hash21(Hlsl.Floor(p * 6.0f) + 0.73f); + if (hRnd > 0.66f) hatch = hRnd; + + hatch = hatch * 0.75f + 0.5f; + + return hatch; + } + + /// + public Float4 Execute() + { + Float2 fragCoord = new(ThreadIds.X, DispatchSize.Y - ThreadIds.Y); + float res = Hlsl.Min(DispatchSize.Y, 700.0f); + Float2 uv = (fragCoord - (Float2)DispatchSize.XY * 0.5f) / res; + float sf = 1.0f / DispatchSize.Y; + Float3 col = GetColor(uv, 0.0f, 0.0f); + float pL = 0.0f; + float hatch = Hatch(uv, res); + + col *= hatch; + + const int lNum = 5; + float flNum = lNum; + + for (int i = 0; i < lNum; i++) + { + float fi = i; + + hatch = Hatch(uv + Hlsl.Sin(new Float2(41.0f, 289.0f) * (fi + 1.0f)), res); + + Float4 c = MapLayer(new Float3(uv, 1.0f), fi); + Float4 cSh = MapLayer(new Float3(uv - new Float2(0.03f, -0.03f) * ((flNum - fi) / flNum * 0.5f + 0.5f), 1.0f), fi); + float sh = (fi + 1.0f) / (flNum); + Float3 lCol = GetColor(uv, sh, fi + 1.0f); + Float3 ld = Hlsl.Normalize(new Float3(-1, 1, -0.25f)); + Float3 n = Hlsl.Normalize(new Float3(0.0f, 0.0f, -1.0f) + c.YZW); + float diff = Hlsl.Max(Hlsl.Dot(ld, n), 0.0f); + + diff *= 2.5f; + + Float3 eCol = lCol * (diff + 1.0f); + float sfL = sf * Hlsl.Length(c.YZX) * 2.0f; + float sfLSh = sf * Hlsl.Length(cSh.YZX) * 6.0f; + const float shF = 0.5f; + + col = Hlsl.Lerp(col, Float3.Zero, (1.0f - Hlsl.SmoothStep(0.0f, sfLSh, Hlsl.Max(cSh.X, pL))) * shF); + col = Hlsl.Lerp(col, Float3.Zero, (1.0f - Hlsl.SmoothStep(0.0f, sfL * 3.0f, c.X)) * 0.25f); + col = Hlsl.Lerp(col, Float3.Zero, (1.0f - Hlsl.SmoothStep(0.0f, sfL, c.X)) * 0.85f); + col = Hlsl.Lerp(col, eCol * hatch, (1.0f - Hlsl.SmoothStep(0.0f, sfL, c.X + Hlsl.Length(c.YZX) * 0.003f))); + col = Hlsl.Lerp(col, lCol * hatch, (1.0f - Hlsl.SmoothStep(0.0f, sfL, c.X + Hlsl.Length(c.YZX) * 0.006f))); + + pL = c.X; + } + + col *= Hlsl.Lerp(new Float3(1.8f, 1, 0.7f).ZYX, new Float3(1.8f, 1, 0.7f).XZY, Noise2D(uv * 2.0f)); + + Float3 rn3 = Noise2D(uv * DispatchSize.Y / 1.0f + 1.7f) - Noise2D(uv * DispatchSize.Y / 1.0f + 3.4f); + + col *= 0.93f + 0.07f * rn3.XYZ + 0.07f * Hlsl.Dot(rn3, new Float3(0.299f, 0.587f, 0.114f)); + + uv = fragCoord / DispatchSize.XY; + + col *= Hlsl.Pow(16.0f * uv.X * uv.Y * (1.0f - uv.X) * (1.0f - uv.Y), 0.0625f); + + return new Float4(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1); + } + } +} diff --git a/samples/ComputeSharp.SwapChain/Shaders/ExtrudedTruchetPattern.cs b/samples/ComputeSharp.SwapChain/Shaders/ExtrudedTruchetPattern.cs index c0d333f6..a66a3aef 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/ExtrudedTruchetPattern.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/ExtrudedTruchetPattern.cs @@ -6,13 +6,8 @@ /// Created by Shane. /// [AutoConstructor] - internal readonly partial struct ExtrudedTruchetPattern : IComputeShader + internal readonly partial struct ExtrudedTruchetPattern : IPixelShader { - /// - /// The target texture. - /// - public readonly IReadWriteTexture2D texture; - /// /// The current time since the start of the application. /// @@ -180,7 +175,7 @@ } /// - public void Execute() + public Float4 Execute() { Int2 coords = new(ThreadIds.X, DispatchSize.Y - ThreadIds.Y); Float2 u = (coords - (Float2)DispatchSize.XY * 0.5f) / DispatchSize.Y; @@ -292,7 +287,7 @@ c = Hlsl.Sqrt(Hlsl.Max(c, 0)); - texture[ThreadIds.XY] = c; + return c; } } } diff --git a/samples/ComputeSharp.SwapChain/Shaders/FractalTiling.cs b/samples/ComputeSharp.SwapChain/Shaders/FractalTiling.cs index 8831eaec..54b119e9 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/FractalTiling.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/FractalTiling.cs @@ -7,20 +7,15 @@ /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] - internal readonly partial struct FractalTiling : IComputeShader + internal readonly partial struct FractalTiling : IPixelShader { - /// - /// The target texture. - /// - public readonly IReadWriteTexture2D texture; - /// /// The current time since the start of the application. /// public readonly float time; /// - public void Execute() + public Float4 Execute() { Float2 position = ((Float2)(256 * ThreadIds.XY)) / DispatchSize.X + time; Float4 color = 0; @@ -45,7 +40,7 @@ color.XYZ = Hlsl.Pow(color.XYZ, new Float3(0.7f, 0.8f, 0.5f)); color.W = 1.0f; - texture[ThreadIds.XY] = color; + return color; } } } diff --git a/samples/ComputeSharp.SwapChain/Shaders/MengerJourney.cs b/samples/ComputeSharp.SwapChain/Shaders/MengerJourney.cs index 9a594438..e56eb5db 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/MengerJourney.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/MengerJourney.cs @@ -6,13 +6,8 @@ /// Created by Syntopia. /// [AutoConstructor] - internal readonly partial struct MengerJourney : IComputeShader + internal readonly partial struct MengerJourney : IPixelShader { - /// - /// The target texture. - /// - public readonly IReadWriteTexture2D texture; - /// /// The current time since the start of the application. /// @@ -153,7 +148,7 @@ } /// - public void Execute() + public Float4 Execute() { Float3 camPos = 0.5f * time * new Float3(1.0f, 0.0f, 0.0f); Float3 target = camPos + new Float3(1.0f, 0.0f * Hlsl.Cos(time), 0.0f * Hlsl.Sin(0.4f * time)); @@ -169,7 +164,7 @@ Float3 rayDir = Hlsl.Normalize(camDir + (coord.X * camRight + coord.Y * camUp) * FieldOfView); - texture[ThreadIds.XY] = RayMarch(camPos, rayDir, ThreadIds.XY); + return RayMarch(camPos, rayDir, ThreadIds.XY); } } } diff --git a/samples/ComputeSharp.SwapChain/Shaders/Octagrams.cs b/samples/ComputeSharp.SwapChain/Shaders/Octagrams.cs index 4bca70ef..180eb7c3 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/Octagrams.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/Octagrams.cs @@ -6,13 +6,8 @@ /// Created by whisky_shusuky. /// [AutoConstructor] - internal readonly partial struct Octagrams : IComputeShader + internal readonly partial struct Octagrams : IPixelShader { - /// - /// The target texture. - /// - public readonly IReadWriteTexture2D texture; - /// /// The current time since the start of the application. /// @@ -88,7 +83,7 @@ } /// - public void Execute() + public Float4 Execute() { Float2 p = ((Float2)ThreadIds.XY * 2.0f - DispatchSize.XY) / Hlsl.Min(DispatchSize.X, DispatchSize.Y); Float3 ro = new(0.0f, -0.2f, time * 4.0f); @@ -122,7 +117,7 @@ Float3 col = ac * 0.02f + new Float3(0.0f, 0.2f * Hlsl.Abs(Hlsl.Sin(time)), 0.5f + Hlsl.Sin(time) * 0.2f); Float4 color = new(col, 1.0f - t * (0.02f + 0.02f * Hlsl.Sin(time))); - texture[ThreadIds.XY] = color; + return color; } } } diff --git a/samples/ComputeSharp.SwapChain/Shaders/ProteanClouds.cs b/samples/ComputeSharp.SwapChain/Shaders/ProteanClouds.cs index 5a4f4bc9..1374106c 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/ProteanClouds.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/ProteanClouds.cs @@ -7,13 +7,8 @@ /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. /// [AutoConstructor] - internal readonly partial struct ProteanClouds : IComputeShader + internal readonly partial struct ProteanClouds : IPixelShader { - /// - /// The target texture. - /// - public readonly IReadWriteTexture2D texture; - /// /// The current time Hlsl.Since the start of the application. /// @@ -131,7 +126,7 @@ } /// - public void Execute() + public Float4 Execute() { Float2 q = (Float2)ThreadIds.XY / DispatchSize.XY; Float2 p = (ThreadIds.XY - 0.5f * (Float2)DispatchSize.XY) / DispatchSize.Y; @@ -167,7 +162,7 @@ col = Hlsl.Pow(col, new Float3(0.55f, 0.65f, 0.6f)) * new Float3(1.0f, 0.97f, 0.9f); col *= Hlsl.Pow(16.0f * q.X * q.Y * (1.0f - q.X) * (1.0f - q.Y), 0.12f) * 0.7f + 0.3f; - texture[ThreadIds.XY] = new Float4(col, 1.0f); + return new(col, 1.0f); } } } diff --git a/samples/ComputeSharp.SwapChain/Shaders/PyramidPattern.cs b/samples/ComputeSharp.SwapChain/Shaders/PyramidPattern.cs index 8ce8d1b7..7f807140 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/PyramidPattern.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/PyramidPattern.cs @@ -7,13 +7,8 @@ /// Created by Shane. /// [AutoConstructor] - internal readonly partial struct PyramidPattern : IComputeShader + internal readonly partial struct PyramidPattern : IPixelShader { - /// - /// The target texture. - /// - public readonly IReadWriteTexture2D texture; - /// /// The current time Hlsl.Since the start of the application. /// @@ -135,7 +130,7 @@ } /// - public void Execute() + public Float4 Execute() { Int2 coordinate = new(ThreadIds.X, DispatchSize.Y - ThreadIds.Y); float iRes = Hlsl.Min(DispatchSize.Y, 800.0f); @@ -175,9 +170,7 @@ col *= hatch * 0.5f + 0.7f; - Float4 color = new(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1); - - texture[ThreadIds.XY] = color; + return new(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1); } } } diff --git a/samples/ComputeSharp.SwapChain/Shaders/TriangleGridContouring.cs b/samples/ComputeSharp.SwapChain/Shaders/TriangleGridContouring.cs index 122facb9..0d4dc01c 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/TriangleGridContouring.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/TriangleGridContouring.cs @@ -6,13 +6,8 @@ /// Created by Shane. /// [AutoConstructor] - internal readonly partial struct TriangleGridContouring : IComputeShader + internal readonly partial struct TriangleGridContouring : IPixelShader { - /// - /// The target texture. - /// - public readonly IReadWriteTexture2D texture; - /// /// The current time Hlsl.Since the start of the application. /// @@ -268,7 +263,7 @@ } /// - public void Execute() + public Float4 Execute() { Int2 coordinate = new(ThreadIds.X, DispatchSize.Y - ThreadIds.Y); Float2 uv = (coordinate - (Float2)DispatchSize.XY * 0.5f) / Hlsl.Min(650.0f, DispatchSize.Y); @@ -278,9 +273,7 @@ uv = coordinate / (Float2)DispatchSize.XY; col *= Hlsl.Pow(16.0f * uv.X * uv.Y * (1.0f - uv.X) * (1.0f - uv.Y), 0.0625f) + 0.1f; - Float4 color = new(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1); - - texture[ThreadIds.XY] = color; + return new(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1); } } } diff --git a/samples/ComputeSharp.SwapChain/Shaders/TwoTiledTruchet.cs b/samples/ComputeSharp.SwapChain/Shaders/TwoTiledTruchet.cs index d1d90f34..90cf73e1 100644 --- a/samples/ComputeSharp.SwapChain/Shaders/TwoTiledTruchet.cs +++ b/samples/ComputeSharp.SwapChain/Shaders/TwoTiledTruchet.cs @@ -6,13 +6,8 @@ /// Created by Shane. /// [AutoConstructor] - internal readonly partial struct TwoTiledTruchet : IComputeShader + internal readonly partial struct TwoTiledTruchet : IPixelShader { - /// - /// The target texture. - /// - public readonly IReadWriteTexture2D texture; - /// /// The current time since the start of the application. /// @@ -114,7 +109,7 @@ } /// - public void Execute() + public Float4 Execute() { Float2 uv = (ThreadIds.XY - (Float2)DispatchSize.XY * 0.5f) / DispatchSize.Y; float gSc = 7.0f; @@ -143,7 +138,7 @@ Float3 rgb = Hlsl.Sqrt(Hlsl.Max(col, 0.0f)); Float4 color = new(rgb.X, rgb.Y, rgb.Z, 1.0f); - texture[ThreadIds.XY] = color; + return color; } } } diff --git a/samples/ComputeSharp.SwapChain/Textures/RustyMetal.png b/samples/ComputeSharp.SwapChain/Textures/RustyMetal.png new file mode 100644 index 00000000..bab629b5 Binary files /dev/null and b/samples/ComputeSharp.SwapChain/Textures/RustyMetal.png differ diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index bdbc1087..8ab9597d 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -53,3 +53,4 @@ CMPS0043 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, CMPS0044 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0045 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPS0046 | ComputeSharp.IComputeShader | Error | IComputeShaderDataLoaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPS0047 | ComputeSharp.IComputeShader | Error | IComputeShaderSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 0530ae6d..3e2dcc6f 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -29,6 +29,7 @@ + diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 03ca810a..caf8bc94 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -646,5 +646,21 @@ namespace ComputeSharp.SourceGenerators.Diagnostics isEnabledByDefault: true, description: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources.", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a type implementing multiple shader interfaces. + /// + /// Format: "The shader of type {0} cannot implement more than one shader interface". + /// + /// + public static readonly DiagnosticDescriptor MultipleShaderTypesImplemented = new( + id: "CMPS0047", + title: "Multiple shader implementations for type declaration", + messageFormat: $"The shader of type {{0}} cannot implement more than one shader interface", + category: typeof(IComputeShaderSourceGenerator).FullName, + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A shader type cannot implement more than one shader interface.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } } diff --git a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs index e582b220..e90839c0 100644 --- a/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs +++ b/src/ComputeSharp.SourceGenerators/Helpers/SyntaxFactoryHelper.cs @@ -22,7 +22,7 @@ namespace ComputeSharp.SourceGenerators.Helpers /// /// /// The input sequence of instances. - /// An instance with the described contents. + /// An instance with the described contents. [Pure] public static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable values) { @@ -44,7 +44,7 @@ namespace ComputeSharp.SourceGenerators.Helpers /// /// /// The input sequence of groups. - /// An instance with the described contents. + /// An instance with the described contents. [Pure] public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable> groups) { @@ -71,7 +71,7 @@ namespace ComputeSharp.SourceGenerators.Helpers /// /// /// The input sequence of groups. - /// An instance with the described contents. + /// An instance with the described contents. [Pure] public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<(string A, string B, int? C)> groups) { @@ -92,5 +92,35 @@ namespace ComputeSharp.SourceGenerators.Helpers ? LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(i)) : LiteralExpression(SyntaxKind.NullLiteralExpression)))).ToArray())); } + + /// + /// Creates a []? array expression from the given tuple instance. + /// + /// That it, it applies the following transformation: + /// + /// null => null + /// ("S1", "S2") => new string[] { "S1", "S2" } + /// + /// + /// + /// The input tuple instance. + /// An instance with the described contents. + [Pure] + public static ExpressionSyntax ArrayExpression((string First, string Second)? values) + { + if (values is null) + { + return LiteralExpression(SyntaxKind.NullLiteralExpression); + } + + return + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.StringKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.First)), + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.Second)))); + } } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs index a16456be..b426151e 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.SyntaxReceiver.cs @@ -29,7 +29,9 @@ namespace ComputeSharp.SourceGenerators { if (context.Node is StructDeclarationSyntax structDeclaration && context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && - structSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) + structSymbol.Interfaces.Any(static interfaceSymbol => + interfaceSymbol.Name == nameof(IComputeShader) || + interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })) { this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 3477badd..5dffbd96 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -154,9 +154,11 @@ namespace ComputeSharp.SourceGenerators { List statements = new(); + var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); + var isComputeShader = pixelShaderSymbol is null; int resourceOffset = 0, - rawDataOffset = sizeof(int) * 3; + rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); AppendFields(structDeclarationSymbol, Array.Empty(), ref resourceOffset, ref rawDataOffset, statements); diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs index c8ae8f9c..2e58a0cb 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.SyntaxReceiver.cs @@ -29,7 +29,9 @@ namespace ComputeSharp.SourceGenerators { if (context.Node is StructDeclarationSyntax structDeclaration && context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && - structSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) + structSymbol.Interfaces.Any(static interfaceSymbol => + interfaceSymbol.Name == nameof(IComputeShader) || + interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })) { this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs index 7b3ad917..a4d2182b 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.SyntaxReceiver.cs @@ -29,7 +29,9 @@ namespace ComputeSharp.SourceGenerators { if (context.Node is StructDeclarationSyntax structDeclaration && context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol && - structSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) + structSymbol.Interfaces.Any(static interfaceSymbol => + interfaceSymbol.Name == nameof(IComputeShader) || + interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })) { this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index 597434d3..37362f1b 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -6,6 +6,7 @@ using System.Text; using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Helpers; using ComputeSharp.SourceGenerators.Mappings; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; @@ -15,7 +16,6 @@ using Microsoft.CodeAnalysis.Text; using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -using ComputeSharp.SourceGenerators.Helpers; #pragma warning disable CS0618 @@ -74,10 +74,20 @@ namespace ComputeSharp.SourceGenerators Dictionary staticMethods = new(SymbolEqualityComparer.Default); Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + // A given type can only represent a single shader type + if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) + { + context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); + } + // Explore the syntax tree and extract the processed info - var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes).ToArray(); + var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); + var isComputeShader = pixelShaderSymbol is null; + var implicitTextureField = isComputeShader ? default((string, string)?) : (HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!), "__outputTexture"); + var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, processedMethods, forwardDeclarations) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions); + var (entryPoint, processedMethods, forwardDeclarations, isSamplerUsed) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedConstants = GetProcessedConstants(constantDefinitions); var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); @@ -90,6 +100,8 @@ namespace ComputeSharp.SourceGenerators Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments( AttributeArgument(TypeOfExpression(IdentifierName(structDeclarationSymbol.ToDisplayString()))), AttributeArgument(ArrayExpression(processedTypes)), + AttributeArgument(ArrayExpression(implicitTextureField)), + AttributeArgument(ArrayExpression(implicitSamplerField)), AttributeArgument(NestedArrayExpression(processedMembers)), AttributeArgument(ArrayExpression(forwardDeclarations)), AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(entryPoint))), @@ -112,12 +124,14 @@ namespace ComputeSharp.SourceGenerators /// The current generator context in use. /// The input instance to process. /// The collection of currently discovered types. + /// Indicates whether or not represents a compute shader. /// A sequence of captured fields in . [Pure] private static IEnumerable> GetProcessedFields( GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, - ICollection types) + ICollection types, + bool isComputeShader) { bool hlslResourceFound = false; @@ -176,7 +190,8 @@ namespace ComputeSharp.SourceGenerators yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName }; } - if (!hlslResourceFound) + // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource + if (!hlslResourceFound && isComputeShader) { context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); } @@ -303,16 +318,18 @@ namespace ComputeSharp.SourceGenerators /// The collection of currently discovered types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. + /// Indicates whether or not represents a compute shader. /// A sequence of processed methods in , and the entry point. [Pure] - private static (string EntryPoint, IEnumerable Methods, IEnumerable Declarations) GetProcessedMethods( + private static (string EntryPoint, IEnumerable Methods, IEnumerable Declarations, bool IsSamplerUser) GetProcessedMethods( GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, - IDictionary constantDefinitions) + IDictionary constantDefinitions, + bool isComputeShader) { // Find all declared methods in the type ImmutableArray methodDeclarations = ( @@ -323,15 +340,22 @@ namespace ComputeSharp.SourceGenerators string? entryPoint = null; List methods = new(); List declarations = new(); + bool isSamplerUsed = false; foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) { IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; bool isShaderEntryPoint = - methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && - methodDeclarationSymbol.ReturnsVoid && - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0; + (isComputeShader && + methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && + methodDeclarationSymbol.ReturnsVoid && + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0) || + (!isComputeShader && + methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && + methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0); // Create the source rewriter for the current method ShaderSourceRewriter shaderSourceRewriter = new( @@ -346,6 +370,9 @@ namespace ComputeSharp.SourceGenerators // Rewrite the method syntax tree MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); + // Track the implicit sampler, if used + isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; + // Emit the extracted local functions first foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { @@ -356,7 +383,11 @@ namespace ComputeSharp.SourceGenerators // If the method is the shader entry point, do additional processing if (isShaderEntryPoint) { - processedMethod = new ExecuteMethodRewriter(shaderSourceRewriter).Visit(processedMethod)!; + processedMethod = isComputeShader switch + { + true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!, + false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)! + }; entryPoint = processedMethod.NormalizeWhitespace().ToFullString(); } @@ -374,7 +405,7 @@ namespace ComputeSharp.SourceGenerators declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace().ToFullString()); } - return (entryPoint!, methods, declarations); + return (entryPoint!, methods, declarations, isSamplerUsed); } /// diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs index 97011619..75a0095c 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownMembers.cs @@ -33,6 +33,21 @@ namespace ComputeSharp.SourceGenerators.Mappings [$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3" }; + /// + /// The mapping of supported known samplers to HLSL resource type names. + /// + private static readonly IReadOnlyDictionary KnownResourceSamplers = new Dictionary + { + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}]"] = "float2", + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float2).FullName}]"] = null, + [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", + [$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(Float3).FullName}]"] = null, + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(float).FullName}, {typeof(float).FullName}, {typeof(float).FullName}]"] = "float3", + [$"ComputeSharp.IReadOnlyTexture2D`1.this[{typeof(Float3).FullName}]"] = null + }; + /// /// The mapping of supported known size accessors for HLSL resource types. /// @@ -389,6 +404,18 @@ namespace ComputeSharp.SourceGenerators.Mappings return KnownResourceIndexers.TryGetValue(name, out mapped); } + /// + /// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name. + /// + /// The input fully qualified indexer name. + /// The mapped type name, if one is found. + /// The HLSL-compatible type name that can be used in an HLSL shader for the given sampler. + [Pure] + public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped) + { + return KnownResourceSamplers.TryGetValue(name, out mapped); + } + /// /// Tries to get the mapped HLSL-compatible indexer vector type name for the input indexer name. /// diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 812040df..1c7a0751 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -265,6 +265,26 @@ namespace ComputeSharp.SourceGenerators.Mappings return typeName.ToHlslIdentifierName(); } + /// + /// Gets the mapped HLSL-compatible type name for the output texture of a pixel shader. + /// + /// The pixel shader type to map. + /// The HLSL-compatible type name that can be used in an HLSL shader. + [Pure] + public static string GetMappedNameForPixelShaderType(INamedTypeSymbol typeSymbol) + { + string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments.First()).GetFullMetadataName(); + + // If the current type is a custom type, format it as needed + if (!KnownHlslTypes.TryGetValue(genericArgumentName, out string? mappedElementType)) + { + mappedElementType = genericArgumentName.ToHlslIdentifierName(); + } + + // Construct the HLSL type name + return $"RWTexture2D"; + } + /// /// Gets the mapped HLSL-compatible type name for the input element type symbol. /// diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs index 0c9febca..a1943062 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ExecuteMethodRewriter.cs @@ -8,22 +8,22 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// /// A custom type that does postprocessing fixups on the shader main method. /// - internal sealed class ExecuteMethodRewriter : CSharpSyntaxRewriter + internal abstract class ExecuteMethodRewriter : CSharpSyntaxRewriter { /// - /// The instance used to process the input tree. - /// - private readonly ShaderSourceRewriter shaderSourceRewriter; - - /// - /// Creates a new instance with the specified parameters. + /// Creates a new instance with the specified parameters. /// /// The instance used to process the input tree. public ExecuteMethodRewriter(ShaderSourceRewriter shaderSourceRewriter) { - this.shaderSourceRewriter = shaderSourceRewriter; + ShaderSourceRewriter = shaderSourceRewriter; } + /// + /// Gets the instance used to process the input tree. + /// + protected ShaderSourceRewriter ShaderSourceRewriter { get; } + /// public TNode? Visit(TNode? node) where TNode : SyntaxNode @@ -38,17 +38,17 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(ThreadIds)} : SV_DispatchThreadID"))); - if (this.shaderSourceRewriter.IsGroupIdsUsed) + if (ShaderSourceRewriter.IsGroupIdsUsed) { updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GroupIds)} : SV_GroupThreadID"))); } - if (this.shaderSourceRewriter.IsGroupIdsIndexUsed) + if (ShaderSourceRewriter.IsGroupIdsIndexUsed) { updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint __{nameof(GroupIds)}__get_Index : SV_GroupIndex"))); } - if (this.shaderSourceRewriter.IsGridIdsUsed) + if (ShaderSourceRewriter.IsGridIdsUsed) { updatedNode = updatedNode.AddParameters(Parameter(Identifier($"uint3 {nameof(GridIds)} : SV_GroupID"))); } @@ -56,23 +56,106 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode; } - /// - public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + /// + /// A custom type specialized for compute shaders. + /// + public sealed class Compute : ExecuteMethodRewriter { - var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList()); + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance used to process the input tree. + public Compute(ShaderSourceRewriter shaderSourceRewriter) + : base(shaderSourceRewriter) + { + } - // When we're rewriting the main compute shader method, we need to insert a range - // check to ensure that invocation outside of the requested range are discarded. - // The following snippet creates this prologue before the user provided body: - // - // if (ThreadIds.x < __x && - // ThreadIds.y < __y && - // ThreadIds.z < __z) - // { - // - // } - var rangeCheckExpression = - BinaryExpression(SyntaxKind.LogicalAndExpression, + /// + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList()); + + // When we're rewriting the main compute shader method, we need to insert a range + // check to ensure that invocation outside of the requested range are discarded. + // The following snippet creates this prologue before the user provided body: + // + // if (ThreadIds.x < __x && + // ThreadIds.y < __y && + // ThreadIds.z < __z) + // { + // + // } + BinaryExpressionSyntax rangeCheckExpression = + BinaryExpression(SyntaxKind.LogicalAndExpression, + BinaryExpression(SyntaxKind.LogicalAndExpression, + BinaryExpression(SyntaxKind.LessThanExpression, + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ThreadIds)), + IdentifierName("x")), + IdentifierName("__x")), + BinaryExpression(SyntaxKind.LessThanExpression, + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ThreadIds)), + IdentifierName("y")), + IdentifierName("__y"))), + BinaryExpression(SyntaxKind.LessThanExpression, + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ThreadIds)), + IdentifierName("z")), + IdentifierName("__z"))); + + return updatedNode.WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!))); + } + } + + /// + /// A custom type specialized for compute shaders. + /// + public sealed class Pixel : ExecuteMethodRewriter + { + /// + /// Creates a new instance with the specified parameters. + /// + /// The instance used to process the input tree. + public Pixel(ShaderSourceRewriter shaderSourceRewriter) + : base(shaderSourceRewriter) + { + } + + /// + public override SyntaxNode? VisitReturnStatement(ReturnStatementSyntax node) + { + var updatedNode = (ReturnStatementSyntax)base.VisitReturnStatement(node)!; + + // __outputTexture[ThreadIds.xy] = ; + return + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ElementAccessExpression(IdentifierName("__outputTexture")) + .AddArgumentListArguments( + Argument( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("ThreadIds"), + IdentifierName("xy")))), + updatedNode.Expression!)); + } + + /// + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) + { + var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList()); + + // Change the return type to void + updatedNode = updatedNode.WithReturnType(PredefinedType(Token(SyntaxKind.VoidKeyword))); + + // Same as above, but skipping the third check for the Z axis. + // This is because pixel shaders only ever run on 2D textures. + BinaryExpressionSyntax rangeCheckExpression = BinaryExpression(SyntaxKind.LogicalAndExpression, BinaryExpression(SyntaxKind.LessThanExpression, MemberAccessExpression( @@ -85,15 +168,25 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters SyntaxKind.SimpleMemberAccessExpression, IdentifierName(nameof(ThreadIds)), IdentifierName("y")), - IdentifierName("__y"))), - BinaryExpression(SyntaxKind.LessThanExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ThreadIds)), - IdentifierName("z")), - IdentifierName("__z"))); + IdentifierName("__y"))); - return updatedNode.WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!))); + return updatedNode.WithBody(Block(IfStatement(rangeCheckExpression, updatedNode.Body!))); + } + + /// + public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) + { + IdentifierNameSyntax updatedNode = (IdentifierNameSyntax)base.VisitIdentifierName(node)!; + + // Since pixel shaders are only ever executed on 2D textures, the special __z field can + // be removed and replaced with just numeric literal expressions, where the value is 1. + if (updatedNode.Identifier.Text == "__z") + { + return LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)); + } + + return updatedNode; + } } } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index 2156d71c..b52a6974 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -21,6 +21,26 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters /// internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter { + /// + /// The instance with semantic info on the target syntax tree. + /// + protected readonly SemanticModelProvider SemanticModel; + + /// + /// The collection of discovered custom types. + /// + protected readonly ICollection DiscoveredTypes; + + /// + /// The collection of discovered constant definitions. + /// + protected readonly IDictionary ConstantDefinitions; + + /// + /// The current generator context in use. + /// + protected readonly GeneratorExecutionContext Context; + /// /// Creates a new instance with the specified parameters. /// @@ -41,24 +61,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters } /// - /// The instance with semantic info on the target syntax tree. + /// Gets whether or not the shader uses a texture sampler at least once. /// - protected readonly SemanticModelProvider SemanticModel; - - /// - /// The collection of discovered custom types. - /// - protected readonly ICollection DiscoveredTypes; - - /// - /// The collection of discovered constant definitions. - /// - protected readonly IDictionary ConstantDefinitions; - - /// - /// The current generator context in use. - /// - protected readonly GeneratorExecutionContext Context; + public bool IsSamplerUsed { get; private set; } /// public override SyntaxNode VisitCastExpression(CastExpressionSyntax node) @@ -175,7 +180,11 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { string literal = updatedNode.Token.ValueText; - if (!literal.Contains('.')) literal += ".0"; + // If the numeric literal is neither a decimal nor an exponential, add the ".0" suffix + if (literal.IndexOfAny(new[] { '.', 'E' }) == -1) + { + literal += ".0"; + } return updatedNode.WithToken(Literal(literal, 0f)); } @@ -201,8 +210,8 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters { string propertyName = operation.Property.GetFullMetadataName(); - // Rewrite texture resource indices taking vectors into individual indices as per HLSL spec. - // For instance: texture[ThreadIds.XY] will be rewritten as texture[ThreadIds.X, ThreadIds.Y]. + // Rewrite texture resource indices taking individual indices a vector argument, as per HLSL spec. + // For instance: texture[ThreadIds.X, ThreadIds.Y] will be rewritten as texture[int2(ThreadIds.X, ThreadIds.Y)]. if (HlslKnownMembers.TryGetMappedResourceIndexerTypeName(propertyName, out string? mapping)) { var index = InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments)); @@ -210,6 +219,32 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters return updatedNode.WithArgumentList(BracketedArgumentList(SingletonSeparatedList(Argument(index)))); } + // Rewrite texture resource sampled accesses, if needed + if (HlslKnownMembers.TryGetMappedResourceSamplerAccessType(propertyName, out mapping)) + { + IsSamplerUsed = true; + + // Get the syntax for the argument syntax transformation as described above + ArgumentSyntax coordinateSyntax = mapping switch + { + not null => Argument(InvocationExpression(IdentifierName(mapping!), ArgumentList(updatedNode.ArgumentList.Arguments))), + null => updatedNode.ArgumentList.Arguments[0] + }; + + // Transform an indexer syntax into a sampling call with the implicit static linear sampler. + // For instance: texture[uv] will be rewritten as texture.SampleLevel(__sampler, uv, 0). + return + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + updatedNode.Expression, + IdentifierName("SampleLevel"))) + .AddArgumentListArguments( + Argument(IdentifierName("__sampler")), + coordinateSyntax, + Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))); + } + // If the current property is a swizzled matrix indexer, ensure all the arguments are constants, and rewrite // the property access to the corresponding HLSL syntax. For instance, m[M11, M12] will become m._m00_m01. if (HlslKnownMembers.IsKnownMatrixIndexer(propertyName)) diff --git a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs index 22f05618..d33a491b 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs @@ -22,6 +22,8 @@ namespace ComputeSharp.__Internals /// /// The type of the current shader. /// The collection of custom types. + /// The implicit texture field info, if present. + /// The implicit texture sampler field info, if present. /// The mapped collection of shader fields. /// The forward declarations for static methods. /// The source code for the method. @@ -32,6 +34,8 @@ namespace ComputeSharp.__Internals public IComputeShaderSourceAttribute( Type shaderType, string[] types, + string[]? implicitTextureField, + string[]? implicitSamplerFields, object[] fields, string[] forwardDeclarations, string executeMethod, @@ -42,6 +46,8 @@ namespace ComputeSharp.__Internals { ShaderType = shaderType; Types = types; + ImplicitTextureField = implicitTextureField is null ? null : (implicitTextureField[0], implicitTextureField[1]); + ImplicitSamplerField = implicitSamplerFields is null ? null : (implicitSamplerFields[0], implicitSamplerFields[1]); Fields = fields.Cast().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2])); ForwardDeclarations = forwardDeclarations; ExecuteMethod = executeMethod; @@ -61,6 +67,16 @@ namespace ComputeSharp.__Internals /// internal IReadOnlyCollection Types { get; } + /// + /// Gets the mapping for the implicit texture field, if the shader is a pixel shader. + /// + internal (string Name, string Type)? ImplicitTextureField { get; } + + /// + /// Gets the mapping for the implicit sampler field, if necessary. + /// + internal (string Name, string Type)? ImplicitSamplerField { get; } + /// /// Gets the mapping of field names. /// diff --git a/src/ComputeSharp/Core/Interfaces/IPixelShader{TPixel}.cs b/src/ComputeSharp/Core/Interfaces/IPixelShader{TPixel}.cs new file mode 100644 index 00000000..d89d6187 --- /dev/null +++ b/src/ComputeSharp/Core/Interfaces/IPixelShader{TPixel}.cs @@ -0,0 +1,15 @@ +namespace ComputeSharp +{ + /// + /// An representing a pixel shader. + /// + public interface IPixelShader + where TPixel : unmanaged + { + /// + /// Executes the current pixel shader. + /// + /// The pixel value for the current invocation. + TPixel Execute(); + } +} diff --git a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs index 834b2bab..57592daf 100644 --- a/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs +++ b/src/ComputeSharp/Graphics/Extensions/GraphicsDeviceExtensions.cs @@ -1131,5 +1131,34 @@ namespace ComputeSharp { ShaderRunner.Run(device, x, y, z, threadsX, threadsY, threadsZ, in shader); } + + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// + /// The type of pixel shader to run. + /// The type of pixels being processed by the shader. + /// The to use to run the shader. + /// The target texture to apply the pixel shader to. + public static void ForEach(this GraphicsDevice device, IReadWriteTexture2D texture) + where T : struct, IPixelShader + where TPixel : unmanaged + { + ShaderRunner.Run(device, texture, default); + } + + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// + /// The type of pixel shader to run. + /// The type of pixels being processed by the shader. + /// The to use to run the shader. + /// The target texture to apply the pixel shader to. + /// The input instance representing the pixel shader to run. + public static void ForEach(this GraphicsDevice device, IReadWriteTexture2D texture, in T shader) + where T : struct, IPixelShader + where TPixel : unmanaged + { + ShaderRunner.Run(device, texture, in shader); + } } } diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs index d0504e42..c668331f 100644 --- a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture2D{TPixel}.cs @@ -32,5 +32,20 @@ /// The coordinates of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. TPixel this[Int2 xy] { get; } + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The horizontal normalized offset of the value to get. + /// The vertical normalized offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + TPixel this[float u, float v] { get; } + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The normalized coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + TPixel this[Float2 uv] { get; } } } diff --git a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs index 30f1db44..79536de0 100644 --- a/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/Interfaces/IReadOnlyTexture3D{TPixel}.cs @@ -38,5 +38,21 @@ /// The coordinates of the value to get. /// This API can only be used from a compute shader, and will always throw if used anywhere else. TPixel this[Int3 xyz] { get; } + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The horizontal normalized offset of the value to get. + /// The vertical normalized offset of the value to get. + /// The depthwise normalized offset of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + TPixel this[float u, float v, float w] { get; } + + /// + /// Gets a single value from the current readonly texture with linear sampling. + /// + /// The normalized coordinates of the value to get. + /// This API can only be used from a compute shader, and will always throw if used anywhere else. + TPixel this[Float3 uvw] { get; } } } diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs index 47b8b62e..42b5c06b 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture2D{T,TPixel}.cs @@ -39,10 +39,16 @@ namespace ComputeSharp /// public TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture2D)}[{typeof(Int2)}]"); + /// + public TPixel this[float u, float v] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture2D)}[{typeof(float)}, {typeof(float)}]"); + + /// + public TPixel this[Float2 uv] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture2D)}[{typeof(Float2)}]"); + /// public override string ToString() { - return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)},{typeof(TPixel)}>[{Width}, {Height}]"; + return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)}, {typeof(TPixel)}>[{Width}, {Height}]"; } } } diff --git a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs index 95ba8bc7..2871cfd0 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadOnlyTexture3D{T,TPixel}.cs @@ -40,10 +40,16 @@ namespace ComputeSharp /// public TPixel this[Int3 xyz] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture3D)}[{typeof(Int3)}]"); + /// + public TPixel this[float u, float v, float w] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture3D)}[{typeof(float)}, {typeof(float)}, {typeof(float)}]"); + + /// + public TPixel this[Float3 uvw] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture3D)}[{typeof(Float3)}]"); + /// public override string ToString() { - return $"ComputeSharp.ReadOnlyTexture3D<{typeof(T)},{nameof(TPixel)}>[{Width}, {Height}, {Depth}]"; + return $"ComputeSharp.ReadOnlyTexture3D<{typeof(T)}, {nameof(TPixel)}>[{Width}, {Height}, {Depth}]"; } } } diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs index f8238ac1..84acb879 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture2D{T,TPixel}.cs @@ -42,7 +42,7 @@ namespace ComputeSharp /// public override string ToString() { - return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)},{typeof(TPixel)}>[{Width}, {Height}]"; + return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)}, {typeof(TPixel)}>[{Width}, {Height}]"; } } } diff --git a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs index b836afd6..cb452315 100644 --- a/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs +++ b/src/ComputeSharp/Graphics/Resources/ReadWriteTexture3D{T,TPixel}.cs @@ -43,7 +43,7 @@ namespace ComputeSharp /// public override string ToString() { - return $"ComputeSharp.ReadWriteTexture3D<{typeof(T)},{nameof(TPixel)}>[{Width}, {Height}, {Depth}]"; + return $"ComputeSharp.ReadWriteTexture3D<{typeof(T)}, {nameof(TPixel)}>[{Width}, {Height}, {Depth}]"; } } } diff --git a/src/ComputeSharp/Shaders/Extensions/ID3D12DeviceExtensions.cs b/src/ComputeSharp/Shaders/Extensions/ID3D12DeviceExtensions.cs index fe254f94..dedce974 100644 --- a/src/ComputeSharp/Shaders/Extensions/ID3D12DeviceExtensions.cs +++ b/src/ComputeSharp/Shaders/Extensions/ID3D12DeviceExtensions.cs @@ -1,7 +1,10 @@ using System; using ComputeSharp.Core.Extensions; using TerraFX.Interop; +using static TerraFX.Interop.D3D12_COMPARISON_FUNC; +using static TerraFX.Interop.D3D12_FILTER; using static TerraFX.Interop.D3D12_PIPELINE_STATE_FLAGS; +using static TerraFX.Interop.D3D12_TEXTURE_ADDRESS_MODE; using FX = TerraFX.Interop.Windows; namespace ComputeSharp.Shaders.Extensions @@ -17,12 +20,14 @@ namespace ComputeSharp.Shaders.Extensions /// The target to use to create the root signature. /// The number of 32 bit root constants to load. /// The input descriptor ranges for the signature to create. + /// Indicates whether or not a static sampler is used. /// A pointer to the newly allocated instance. /// Thrown when the creation of the root signature fails. public static ComPtr CreateRootSignature( this ref ID3D12Device d3D12Device, int d3D12Root32BitConstantsCount, - ReadOnlySpan d3D12DescriptorRanges1) + ReadOnlySpan d3D12DescriptorRanges1, + bool isStaticSamplerUsed) { using ComPtr d3D3Blob = default; using ComPtr d3D3BlobError = default; @@ -42,11 +47,28 @@ namespace ComputeSharp.Shaders.Extensions D3D12_ROOT_PARAMETER1.InitAsDescriptorTable(out d3D12RootParameters1[i + 1], 1, d3D12DescriptorRange1 + i); } + D3D12_STATIC_SAMPLER_DESC d3D12SamplerDescription; + + // Create the linear static sampler if needed + if (isStaticSamplerUsed) + { + D3D12_STATIC_SAMPLER_DESC.Init( + out d3D12SamplerDescription, + shaderRegister: 0, + filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR, + addressU: D3D12_TEXTURE_ADDRESS_MODE_MIRROR, + addressV: D3D12_TEXTURE_ADDRESS_MODE_MIRROR, + addressW: D3D12_TEXTURE_ADDRESS_MODE_MIRROR, + comparisonFunc: D3D12_COMPARISON_FUNC_NEVER); + } + // Root signature description wrapping the packed collection of root parameters D3D12_VERSIONED_ROOT_SIGNATURE_DESC.Init_1_1( out D3D12_VERSIONED_ROOT_SIGNATURE_DESC d3D12VersionedRootSignatureDescription, - (uint)d3D12DescriptorRanges1.Length + 1, - d3D12RootParameters1); + numParameters: (uint)d3D12DescriptorRanges1.Length + 1, + _pParameters: d3D12RootParameters1, + numStaticSamplers: isStaticSamplerUsed ? 1u : 0u, + _pStaticSamplers: isStaticSamplerUsed ? &d3D12SamplerDescription : null); // Serialize the root signature from the data just computed. When this is done // we just work with the resulting blobs, so the input data can be unpinned. diff --git a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs index c0a04789..3a83b4f0 100644 --- a/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs +++ b/src/ComputeSharp/Shaders/Interop/ReflectionServices.cs @@ -14,13 +14,13 @@ namespace ComputeSharp.Interop public static class ReflectionServices { /// - /// Gets the shader info associated with a given shader. + /// Gets the shader info associated with a given compute shader. /// - /// This overload can be used for simplicity when the shader being inspected does not rely on captured + /// This overload can be used for simplicity when the compute shader being inspected does not rely on captured /// objects to be processed correctly. This is the case when it does not contain any -s. /// /// - /// The type of shader to retrieve info for. + /// The type of compute shader to retrieve info for. /// The resulting instance. /// /// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to @@ -30,14 +30,14 @@ namespace ComputeSharp.Interop public static void GetShaderInfo(out ShaderInfo shaderInfo) where T : struct, IComputeShader { - GetShaderInfo(default(T), out shaderInfo); + GetNonGenericShaderInfo(default(T), out shaderInfo); } /// - /// Gets the shader info associated with a given shader. + /// Gets the shader info associated with a given compute shader. /// - /// The type of shader to retrieve info for. - /// The input shader to retrieve info for. + /// The type of compute shader to retrieve info for. + /// The input compute shader to retrieve info for. /// The resulting instance. /// /// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to @@ -46,6 +46,59 @@ namespace ComputeSharp.Interop /// public static unsafe void GetShaderInfo(in T shader, out ShaderInfo shaderInfo) where T : struct, IComputeShader + { + GetNonGenericShaderInfo(in shader, out shaderInfo); + } + + /// + /// Gets the shader info associated with a given pixel shader. + /// + /// This overload can be used for simplicity when the pixel shader being inspected does not rely on captured + /// objects to be processed correctly. This is the case when it does not contain any -s. + /// + /// + /// The type of pixel shader to retrieve info for. + /// The type of pixels being processed by the shader. + /// The resulting instance. + /// + /// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to + /// avoid having to compiler multiple shaders just to get reflection info for them. When using any of + /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. + /// + public static void GetShaderInfo(out ShaderInfo shaderInfo) + where T : struct, IPixelShader + where TPixel : unmanaged + { + GetNonGenericShaderInfo(default(T), out shaderInfo); + } + + /// + /// Gets the shader info associated with a given pixel shader. + /// + /// The type of pixel shader to retrieve info for. + /// The type of pixels being processed by the shader. + /// The input pixel shader to retrieve info for. + /// The resulting instance. + /// + /// The thread group sizes will always be set to (1, 1, 1) in the returned shader. This is done to + /// avoid having to compiler multiple shaders just to get reflection info for them. When using any of + /// the APIs to dispatch a shader, the thread sizes would actually be set to a proper value insead. + /// + public static unsafe void GetShaderInfo(in T shader, out ShaderInfo shaderInfo) + where T : struct, IPixelShader + where TPixel : unmanaged + { + GetNonGenericShaderInfo(in shader, out shaderInfo); + } + + /// + /// Gets the shader info associated with a given shader of any type. + /// + /// The type of shader to retrieve info for. + /// The input shader to retrieve info for. + /// The resulting instance. + private static unsafe void GetNonGenericShaderInfo(in T shader, out ShaderInfo shaderInfo) + where T : struct { ShaderLoader shaderLoader = ShaderLoader.Load(in shader); diff --git a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs index 89fead55..754709ee 100644 --- a/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs +++ b/src/ComputeSharp/Shaders/Renderer/HlslShaderRenderer.cs @@ -85,7 +85,11 @@ namespace ComputeSharp.Shaders.Renderer builder.AppendLine('{'); builder.AppendLine(" uint __x;"); builder.AppendLine(" uint __y;"); - builder.AppendLine(" uint __z;"); + + if (info.IsComputeShader) + { + builder.AppendLine(" uint __z;"); + } foreach (var local in info.FieldsInfo) { @@ -98,25 +102,25 @@ namespace ComputeSharp.Shaders.Renderer builder.AppendLine('}'); - // Buffers - foreach (var buffer in info.HlslResourceInfo) + // Resources + foreach (var resource in info.HlslResourceInfo) { builder.AppendLine(); - switch (buffer) + switch (resource) { // Constant buffer go to cbuffer fields with a dummy local case HlslResourceInfo.Constant _: builder.Append("cbuffer _"); - builder.Append(buffer.FieldName); + builder.Append(resource.FieldName); builder.Append(" : register(b"); - builder.Append(buffer.BufferIndex.ToString()); + builder.Append(resource.RegisterIndex.ToString()); builder.AppendLine(')'); builder.AppendLine('{'); builder.Append(" "); - builder.Append(buffer.FieldType); + builder.Append(resource.FieldType); builder.Append(' '); - builder.Append(buffer.FieldName); + builder.Append(resource.FieldName); builder.AppendLine("[2];"); builder.AppendLine('}'); break; @@ -128,12 +132,23 @@ namespace ComputeSharp.Shaders.Renderer case HlslResourceInfo.ReadWrite _: registerId = 'u'; StructuredBuffer: - builder.Append(buffer.FieldType); + builder.Append(resource.FieldType); builder.Append(' '); - builder.Append(buffer.FieldName); + builder.Append(resource.FieldName); builder.Append(" : register("); builder.Append(registerId); - builder.Append(buffer.BufferIndex.ToString()); + builder.Append(resource.RegisterIndex.ToString()); + builder.AppendLine(");"); + break; + + // Texture samplers + case HlslResourceInfo.Sampler _: + builder.Append(resource.FieldType); + builder.Append(' '); + builder.Append(resource.FieldName); + builder.Append(" : register("); + builder.Append('s'); + builder.Append(resource.RegisterIndex.ToString()); builder.AppendLine(");"); break; } diff --git a/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs b/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs index 455b287d..af71a082 100644 --- a/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs +++ b/src/ComputeSharp/Shaders/Renderer/Models/HlslResourceInfo.cs @@ -1,37 +1,43 @@ -#pragma warning disable CS1572, CS1573 - -namespace ComputeSharp.Shaders.Renderer.Models +namespace ComputeSharp.Shaders.Renderer.Models { /// - /// A model that contains info on a shader typed resource field. + /// A model that contains info on a shader resource field. /// /// The type of the current field in the HLSL shader. /// The name to use for the current field. - /// The register index to bind the resource to. - internal abstract record HlslResourceInfo(string FieldType, string FieldName, int BufferIndex) + /// The register index to bind the resource to. + internal abstract record HlslResourceInfo(string FieldType, string FieldName, int RegisterIndex) : CapturedFieldInfo(FieldType, FieldName) { /// /// A model that represents a captured constant buffer in a shader. /// /// - public sealed record Constant(string FieldType, string FieldName, int BufferIndex) - : HlslResourceInfo(FieldType, FieldName, BufferIndex); + public sealed record Constant(string FieldType, string FieldName, int RegisterIndex) + : HlslResourceInfo(FieldType, FieldName, RegisterIndex); /// /// A model that represents a captured readonly typed resource in a shader. /// Maps to either or . /// /// - public sealed record ReadOnly(string FieldType, string FieldName, int BufferIndex) - : HlslResourceInfo(FieldType, FieldName, BufferIndex); + public sealed record ReadOnly(string FieldType, string FieldName, int RegisterIndex) + : HlslResourceInfo(FieldType, FieldName, RegisterIndex); /// /// A model that represents a captured writeable buffer in a shader. /// Maps to either or . /// /// - public sealed record ReadWrite(string FieldType, string FieldName, int BufferIndex) - : HlslResourceInfo(FieldType, FieldName, BufferIndex); + public sealed record ReadWrite(string FieldType, string FieldName, int RegisterIndex) + : HlslResourceInfo(FieldType, FieldName, RegisterIndex); + + /// + /// A model that represents a captured sampler in a shader. + /// This resource type doesn't have a mapping to a public API. + /// + /// + public sealed record Sampler(string FieldType, string FieldName, int RegisterIndex) + : HlslResourceInfo(FieldType, FieldName, RegisterIndex); } } diff --git a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs index eb03e3ff..220b2c2c 100644 --- a/src/ComputeSharp/Shaders/ShaderRunner{T}.cs +++ b/src/ComputeSharp/Shaders/ShaderRunner{T}.cs @@ -8,11 +8,14 @@ using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Translation; using ComputeSharp.Shaders.Translation.Interop; using ComputeSharp.Shaders.Translation.Models; +using ComputeSharp.__Internals; using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; using static TerraFX.Interop.D3D12_COMMAND_LIST_TYPE; +#pragma warning disable CS0618 + namespace ComputeSharp.Shaders { /// @@ -20,7 +23,7 @@ namespace ComputeSharp.Shaders /// /// The type of compute shader to run. internal static class ShaderRunner - where T : struct, IComputeShader + where T : struct { /// /// The mapping used to cache and reuse compiled shaders. @@ -175,6 +178,86 @@ namespace ComputeSharp.Shaders commandList.ExecuteAndWaitForCompletion(); } + /// + /// Compiles and runs the input shader on a target instance, with the specified parameters. + /// + /// The to use to run the shader. + /// The target texture to invoke the pixel shader upon. + /// The input instance representing the pixel shader to run. + public static unsafe void Run(GraphicsDevice device, IReadWriteTexture2D texture, in T shader) + where TPixel : unmanaged + { + device.ThrowIfDisposed(); + + // Calculate the dispatch values + int + x = texture.Width, + y = texture.Height, + threadsX = 8, + threadsY = 8, + groupsX = Math.DivRem(x, threadsX, out int modX) + (modX == 0 ? 0 : 1), + groupsY = Math.DivRem(y, threadsY, out int modY) + (modY == 0 ? 0 : 1); + + Guard.IsBetweenOrEqualTo(groupsX, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); + Guard.IsBetweenOrEqualTo(groupsY, 1, FX.D3D11_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, nameof(groupsX)); + + // Create the shader key + ShaderKey key = new(ShaderHashCodeProvider.GetHashCode(in shader), threadsX, threadsY, 1); + CachedShader shaderData; + PipelineData? pipelineData; + + lock (ShadersCache) + { + // Get or preload the shader + if (!ShadersCache.TryGetValue(key, out shaderData)) + { + LoadShader(threadsX, threadsY, 1, in shader, out shaderData); + + // Cache for later use + ShadersCache.Add(key, shaderData); + } + + // Create the reusable pipeline state + if (!shaderData.CachedPipelines.TryGetValue(device, out pipelineData)) + { + CreatePipelineData(device, shaderData, out pipelineData); + } + } + + // Create the commands list and set the pipeline state + using CommandList commandList = new(device, D3D12_COMMAND_LIST_TYPE_COMPUTE); + + commandList.D3D12GraphicsCommandList->SetComputeRootSignature(pipelineData.D3D12RootSignature); + commandList.D3D12GraphicsCommandList->SetPipelineState(pipelineData.D3D12PipelineState); + + // Extract the dispatch data for the shader invocation + using DispatchData dispatchData = shaderData.Loader.GetDispatchData(device, in shader, x, y, 1); + + // Initialize the loop targets and the captured values + commandList.D3D12GraphicsCommandList->SetComputeRoot32BitConstants(dispatchData.Variables); + + // Load the implicit output texture + commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable( + 1, + ((GraphicsResourceHelper.IGraphicsResource)texture).ValidateAndGetGpuDescriptorHandle(device)); + + // Skip the last (missing) resource, as the internal counter is exceeding the number of explicit + // resources that the shader has actually captured (since it includes the target texture too). + // For the same reason, the target root descriptor table index is also offset by 2, as it needs + // to skip not only the constant buffer with capture values, but the implicit texture as well. + ReadOnlySpan resources = dispatchData.Resources[..^1]; + + for (int i = 0; i < resources.Length; i++) + { + // Load the captured buffers + commandList.D3D12GraphicsCommandList->SetComputeRootDescriptorTable((uint)i + 2, resources[i]); + } + + // Dispatch and wait for completion + commandList.D3D12GraphicsCommandList->Dispatch((uint)groupsX, (uint)groupsY, 1); + commandList.ExecuteAndWaitForCompletion(); + } + /// /// Loads a shader with the specified parameters. /// @@ -208,7 +291,7 @@ namespace ComputeSharp.Shaders [MethodImpl(MethodImplOptions.NoInlining)] private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader shaderData, out PipelineData pipelineData) { - using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1); + using ComPtr d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1, shaderData.Loader.IsStaticSamplerUsed); using ComPtr d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.Bytecode.D3D12ShaderBytecode); pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get()); diff --git a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs b/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs index 23438eff..ccbdc33f 100644 --- a/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs +++ b/src/ComputeSharp/Shaders/Translation/IShaderLoader.cs @@ -13,6 +13,11 @@ namespace ComputeSharp.Shaders.Translation /// string EntryPoint { get; } + /// + /// Gets whether or not the current shader is a compute shader (and not a pixel shader). + /// + bool IsComputeShader { get; } + /// /// Gets the collection of items for the shader fields. /// diff --git a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs b/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs index da4de180..39558fb1 100644 --- a/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/Models/CachedShader{T}.cs @@ -9,7 +9,7 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// The type of compute shader in use. internal readonly struct CachedShader - where T : struct, IComputeShader + where T : struct { /// /// The instance with the shader metadata. diff --git a/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs index d6139881..2304eba6 100644 --- a/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp/Shaders/Translation/ShaderHashCodeProvider.cs @@ -15,7 +15,7 @@ namespace ComputeSharp.Shaders.Translation /// /// The type of compute shader currently in use. private static class TypeInfo - where T : struct, IComputeShader + where T : struct { /// /// The id of the compute shader type in use. @@ -51,7 +51,7 @@ namespace ComputeSharp.Shaders.Translation [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetHashCode(in T shader) - where T : struct, IComputeShader + where T : struct { int hash = TypeInfo.Id; @@ -70,6 +70,6 @@ namespace ComputeSharp.Shaders.Translation /// The compute shader instance to use to compute the final hash value. /// The final hash value for the input closure. private delegate int Hasher(int hash, in T shader) - where T : struct, IComputeShader; + where T : struct; } } diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs index 80b0d868..95c80c19 100644 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs +++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.DispatchData.cs @@ -62,10 +62,14 @@ namespace ComputeSharp.Shaders.Translation ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources); ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); - // Set the x, y and z counters + // Set the x, y and (optionally) z counters Unsafe.As(ref r1) = x; Unsafe.Add(ref Unsafe.As(ref r1), 1) = y; - Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; + + if (IsComputeShader) + { + Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; + } // Invoke the dynamic method to extract the captured data int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1); diff --git a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs index 745f53b0..a13586e1 100644 --- a/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp/Shaders/Translation/ShaderLoader{T}.cs @@ -19,7 +19,7 @@ namespace ComputeSharp.Shaders.Translation /// /// The type of compute shader currently in use. internal sealed partial class ShaderLoader : IShaderLoader - where T : struct, IComputeShader + where T : struct { /// /// The associated instance for the current shader type. @@ -45,6 +45,11 @@ namespace ComputeSharp.Shaders.Translation /// private uint readWriteBuffersCount; + /// + /// The number of samplers to define in the shader. + /// + private uint samplersCount; + /// /// The array of items that are required to load the captured values. /// @@ -98,6 +103,14 @@ namespace ComputeSharp.Shaders.Translation /// public string EntryPoint { get; private set; } + /// + public bool IsComputeShader { get; private set; } + + /// + /// Gets whether or not the current shader requires access to a static sampler. + /// + public bool IsStaticSamplerUsed { get; private set; } + /// public IReadOnlyList HlslResourceInfo => this.hlslResourceInfo; @@ -174,12 +187,43 @@ namespace ComputeSharp.Shaders.Translation BindingFlags.Public | BindingFlags.NonPublic).ToArray(); - if (shaderFields.Count == 0) + List d3D12DescriptorRanges1 = new(); + + // Add the implicit texture descriptor if the shader is a pixel shader + foreach (Type interfaceType in typeof(T).GetInterfaces()) + { + if (interfaceType.IsGenericType && + interfaceType.GetGenericTypeDefinition() == typeof(IPixelShader<>)) + { + d3D12DescriptorRanges1.Add(new D3D12_DESCRIPTOR_RANGE1(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, this.readWriteBuffersCount)); + + (string hlslType, string hlslName) = Attribute.ImplicitTextureField!.Value; + + this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); + this.totalResourceCount++; + + break; + } + } + + // Set the current shader type + IsComputeShader = d3D12DescriptorRanges1.Count == 0; + + // Ensure the shader has a valid number of captured resources + if (shaderFields.Count == 0 && d3D12DescriptorRanges1.Count == 0) { ThrowHelper.ThrowInvalidOperationException("The shader body must contain at least one field"); } - List d3D12DescriptorRanges1 = new(); + // Add the implicit sampler descriptor if necessary + if (Attribute.ImplicitSamplerField is not null) + { + (string hlslType, string hlslName) = Attribute.ImplicitSamplerField!.Value; + + this.hlslResourceInfo.Add(new HlslResourceInfo.Sampler(hlslType, hlslName, (int)this.samplersCount++)); + + IsStaticSamplerUsed = true; + } // Inspect the captured fields foreach (FieldInfo fieldInfo in shaderFields) diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 0b1702d7..021a575f 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -1370,6 +1370,31 @@ namespace ComputeSharp.Tests.SourceGenerators VerifyGeneratedDiagnostics(source, "CMPS0046"); } + [TestMethod] + public void MultipleShaderTypes() + { + string source = @" + using ComputeSharp; + + namespace ComputeSharp + { + public interface IComputeShader { } + public interface IPixelShader { } + } + + namespace MyFancyApp.Sample + { + public struct MyShader : IComputeShader, IPixelShader + { + public void Execute() + { + } + } + }"; + + VerifyGeneratedDiagnostics(source, "CMPS0047"); + } + /// /// Verifies the output of a source generator. /// diff --git a/tests/ComputeSharp.Tests/Assets/CityAfter1024x1024Sampling.png b/tests/ComputeSharp.Tests/Assets/CityAfter1024x1024Sampling.png new file mode 100644 index 00000000..0430d2c7 Binary files /dev/null and b/tests/ComputeSharp.Tests/Assets/CityAfter1024x1024Sampling.png differ diff --git a/tests/ComputeSharp.Tests/Assets/ContouredLayers.png b/tests/ComputeSharp.Tests/Assets/ContouredLayers.png new file mode 100644 index 00000000..dd16f502 Binary files /dev/null and b/tests/ComputeSharp.Tests/Assets/ContouredLayers.png differ diff --git a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj index a3d872c5..42a2f615 100644 --- a/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj +++ b/tests/ComputeSharp.Tests/ComputeSharp.Tests.csproj @@ -27,22 +27,30 @@ - - - - - - - - - + + + + + + + + + + - + + + + PreserveNewest + PreserveNewest + + PreserveNewest + PreserveNewest diff --git a/tests/ComputeSharp.Tests/DispatchTests.cs b/tests/ComputeSharp.Tests/DispatchTests.cs index a7a19fc5..7b59d084 100644 --- a/tests/ComputeSharp.Tests/DispatchTests.cs +++ b/tests/ComputeSharp.Tests/DispatchTests.cs @@ -262,5 +262,41 @@ namespace ComputeSharp.Tests buffer[5] = (int)Hlsl.Dot(DispatchSize.XYZ, Float3.One); } } + + [CombinatorialTestMethod] + [AllDevices] + public void Verify_DispatchAsPixelShader(Device device) + { + using ReadWriteTexture2D texture = device.Get().AllocateReadWriteTexture2D(256, 256); + + device.Get().ForEach(texture); + + Rgba32[,] data = texture.ToArray(); + + for (int y = 0; y < texture.Height; y++) + { + for (int x = 0; x < texture.Width; x++) + { + Rgba32 pixel = data[y, x]; + + Assert.AreEqual((float)pixel.R / 255, (float)x / texture.Width, 0.1f); + Assert.AreEqual((float)pixel.G / 255, (float)y / texture.Height, 0.1f); + Assert.AreEqual(pixel.B, 255); + Assert.AreEqual(pixel.A, 255); + } + } + } + + internal readonly partial struct DispatchPixelShader : IPixelShader + { + public Float4 Execute() + { + return new( + (float)ThreadIds.X / DispatchSize.X, + (float)ThreadIds.Y / DispatchSize.Y, + 1, + 1); + } + } } } diff --git a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs index f9e8a0a7..b9736eb0 100644 --- a/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs +++ b/tests/ComputeSharp.Tests/Extensions/GraphicsDeviceExtensions.cs @@ -8,7 +8,7 @@ using ComputeSharp.Resources; namespace ComputeSharp.Tests.Extensions { /// - /// A helper class for testing APIs. + /// A helper class for testing resource types. /// public static class GraphicsDeviceExtensions { diff --git a/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs b/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs new file mode 100644 index 00000000..6994ab4c --- /dev/null +++ b/tests/ComputeSharp.Tests/Extensions/ImagingExtensions.cs @@ -0,0 +1,52 @@ +using System; +using System.Diagnostics.Contracts; +using System.Runtime.InteropServices; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using SixLabors.ImageSharp; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; + +namespace ComputeSharp.Tests.Extensions +{ + /// + /// A helper class for loading images into resources. + /// + public static class ImagingExtensions + { + /// + /// Allocates a new instance with the specified texture data. + /// + /// The target instance to allocate the texture for. + /// The path of the texture to load. + /// A texture with the data from the image at the specified path. + [Pure] + public static ReadOnlyTexture2D LoadTexture(this GraphicsDevice device, string path) + { + using Image image = Image.Load(path); + + Assert.IsTrue(image.TryGetSinglePixelSpan(out Span span)); + + Span pixels = MemoryMarshal.Cast(span); + + return device.AllocateReadOnlyTexture2D(pixels, image.Width, image.Height); + } + + /// + /// Creates a new instance with the specified texture data. + /// + /// The source instance to read data from. + /// An image with the data from the input texture. + [Pure] + public static Image ToImage(this ReadWriteTexture2D texture) + { + Image image = new(texture.Width, texture.Height); + + Assert.IsTrue(image.TryGetSinglePixelSpan(out Span span)); + + Span pixels = MemoryMarshal.Cast(span); + + texture.CopyTo(pixels); + + return image; + } + } +} diff --git a/tests/ComputeSharp.Tests/ImagingTests.cs b/tests/ComputeSharp.Tests/ImagingTests.cs index ef68773d..97ffe400 100644 --- a/tests/ComputeSharp.Tests/ImagingTests.cs +++ b/tests/ComputeSharp.Tests/ImagingTests.cs @@ -75,11 +75,22 @@ namespace ComputeSharp.Tests /// The path to the reference image. /// The path to the expected image. /// The allowed difference threshold for the normalized delta. - public static void AssertEqual(string expectedPath, string actualPath, float threshold) + public static void AssertEqual(string expectedPath, string actualPath, float threshold) { using var expected = Image.Load(expectedPath); using var actual = Image.Load(actualPath); + AssertEqual(expected, actual, threshold); + } + + /// + /// Asserts that two images are equal. + /// + /// The reference image. + /// The expected image. + /// The allowed difference threshold for the normalized delta. + public static void AssertEqual(Image expected, Image actual, float threshold) + { if (expected.Size() != actual.Size()) { Assert.Fail($"The input images have different sizes: {expected.Size()} and {actual.Size()}"); diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index 0bdfd0b4..50e72d30 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -122,7 +122,7 @@ namespace ComputeSharp.Tests } [TestMethod] - public void OutOfOrderMethods_Ok() + public void OutOfOrderMethods() { ReflectionServices.GetShaderInfo(out var info); } @@ -153,5 +153,23 @@ namespace ComputeSharp.Tests buffer[ThreadIds.X] = ExternalStructType.Sum(type); } } + + [TestMethod] + public void PixelShader() + { + ReflectionServices.GetShaderInfo(out var info); + + Assert.AreEqual(info.TextureStoreInstructionCount, 1u); + Assert.AreEqual(info.BoundResourceCount, 2u); + } + + public readonly partial struct StatelessPixelShader : IPixelShader + { + /// + public Float4 Execute() + { + return new(1, 1, 1, 1); + } + } } } diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs new file mode 100644 index 00000000..a617bea6 --- /dev/null +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ColorfulInfinity.cs @@ -0,0 +1,76 @@ +namespace ComputeSharp.SwapChain.Shaders.Compute +{ + /// + /// A shader creating an abstract and colorful animation. + /// Ported from . + /// Created by Benoit Marini. + /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. + /// + [AutoConstructor] + internal readonly partial struct ColorfulInfinity : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + /// + /// The total number of layers for the final animation. + /// + private const float NumberOfLayers = 16.0f; + + /// + /// The number of iterations to calculate a texel value. + /// + private const int NumberOfIterations = 23; + + /// + /// Makes some magic happen. + /// + private Float4 Tex(Float3 p) + { + float t = time + 78.0f; + Float4 o = new(p.X, p.Y, p.Z, 3.0f * Hlsl.Sin(t * 0.1f)); + Float4 dec = + new Float4(1.0f, 0.9f, 0.1f, 0.15f) + + new Float4(0.06f * Hlsl.Cos(t * 0.1f), 0, 0, 0.14f * Hlsl.Cos(t * 0.23f)); + + for (int i = 0; i++ < NumberOfIterations;) + { + o.XZYW = Hlsl.Abs(o / Hlsl.Dot(o, o) - dec); + } + + return o; + } + + /// + public void Execute() + { + Float2 uv = (ThreadIds.XY - (Float2)DispatchSize.XY * 0.5f) / DispatchSize.Y; + Float3 col = 0; + float t = time * 0.3f; + + for (float i = 0.0f; i <= 1.0f; i += 1.0f / NumberOfLayers) + { + float d = Hlsl.Frac(i + t); + float s = Hlsl.Lerp(5.0f, 0.5f, d); + float f = d * Hlsl.SmoothStep(1.0f, 0.9f, d); + + col += Tex(new Float3(uv.X * s, uv.Y * s, i * 4.0f)).XYZ * f; + } + + col /= NumberOfLayers; + col *= new Float3(2, 1.0f, 2.0f); + col = Hlsl.Pow(col, 0.5f); + + Float4 color = new(col.X, col.Y, col.Z, 1.0f); + + texture[ThreadIds.XY] = color; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs new file mode 100644 index 00000000..76dc6a82 --- /dev/null +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ContouredLayers.cs @@ -0,0 +1,202 @@ +namespace ComputeSharp.SwapChain.Shaders.Compute +{ + /// + /// Constructing some concise contoured layers, then applying various edge and shading effects to produce some faux depth. + /// Ported from . + /// Created by Shane. + /// + [AutoConstructor] + internal readonly partial struct ContouredLayers : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D destination; + + /// + /// The current time Hlsl.Since the start of the application. + /// + public readonly float time; + + /// + /// The sampling texture. + /// + public readonly IReadOnlyTexture2D texture; + + // Float3 to float hash. + private static float Hash21(Float2 p) + { + return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new Float2(41, 289))) * 45758.5453f); + } + + // Float2 to Float2 hash. + private Float2 Hash22(Float2 p) + { + float n = Hlsl.Sin(Hlsl.Dot(p, new Float2(1, 113))); + + p = Hlsl.Frac(new Float2(262144, 32768) * n); + + return Hlsl.Sin(p * 6.2831853f + time); + } + + // Float2 to Float2 hash. + private static Float2 Hash22B(Float2 p) + { + float n = Hlsl.Sin(Hlsl.Dot(p, new Float2(41, 289))); + + return Hlsl.Frac(new Float2(262144, 32768) * n) * 2.0f - 1.0f; + } + + // Smooth 2D noise + private static float Noise2D(Float2 p) + { + Float2 i = Hlsl.Floor(p); + + p -= i; + + Float4 v = default; + + v.X = Hlsl.Dot(Hash22B(i), p); + v.Y = Hlsl.Dot(Hash22B(i + Float2.UnitX), p - Float2.UnitX); + v.Z = Hlsl.Dot(Hash22B(i + Float2.UnitY), p - Float2.UnitY); + v.W = Hlsl.Dot(Hash22B(i + 1.0f), p - 1.0f); + + p = p * p * (3.0f - 2.0f * p); + + return Hlsl.Lerp(Hlsl.Lerp(v.X, v.Y, p.X), Hlsl.Lerp(v.Z, v.W, p.X), p.Y); + } + + // Based on IQ's gradient noise formula. + private float Noise2D3G(Float2 p) + { + Float2 i = Hlsl.Floor(p); + + p -= i; + + Float4 v = default; + + v.X = Hlsl.Dot(Hash22(i), p); + v.Y = Hlsl.Dot(Hash22(i + Float2.UnitX), p - Float2.UnitX); + v.Z = Hlsl.Dot(Hash22(i + Float2.UnitY), p - Float2.UnitY); + v.W = Hlsl.Dot(Hash22(i + 1.0f), p - 1.0f); + + p = p * p * p * (p * (p * 6.0f - 15.0f) + 10.0f); + + return Hlsl.Lerp(Hlsl.Lerp(v.X, v.Y, p.X), Hlsl.Lerp(v.Z, v.W, p.X), p.Y); + } + + // Map function with noise layers + private float MapNoise(Float3 p, float i) + { + return Noise2D3G(p.XY * 3.0f) * 0.66f + Noise2D3G(p.XY * 6.0f) * 0.34f + i / 10.0f * 1.0f - 0.15f; + } + + // 2D derivative function. + private Float3 GetNormal(in Float3 p, float m, float i) + { + Float2 e = new(0.001f, 0); + + return new Float3(m - MapNoise(p - e.XYY, i), m - MapNoise(p - e.YXY, i), 0.0f) / e.X * 1.4142f; + } + + // The map layer and its derivative + private Float4 MapLayer(in Float3 p, float i) + { + Float4 d = default; + + d.X = MapNoise(p, i); + d.YZW = GetNormal(p, d.X, i); + + return d; + } + + // Layer color. Based on the shade, layer number and smoothing factor. + private Float3 GetColor(Float2 p, float sh, float fi) + { + Float3 tx = texture[p + Hash21(new Float2(sh, fi))].XYZ; + + tx *= tx; + + Float3 col; + + col = (Float3)1.0 * (1.0f - 0.75f / (1.0f + sh * sh * 2.0f)); + col = Hlsl.Min(col * tx * 3.0f, 1.0f); + + return col; + } + + // A hatch-like algorithm, or a stipple... or some kind of textured pattern. + private float Hatch(Float2 p, float res) + { + p *= res / 16.0f; + + float hatch = Hlsl.Clamp(Hlsl.Sin((p.X - p.Y) * 3.14159f * 200.0f) * 2.0f + 0.5f, 0.0f, 1.0f); + + float hRnd = Hash21(Hlsl.Floor(p * 6.0f) + 0.73f); + if (hRnd > 0.66f) hatch = hRnd; + + hatch = hatch * 0.75f + 0.5f; + + return hatch; + } + + /// + public void Execute() + { + Float2 fragCoord = new(ThreadIds.X, DispatchSize.Y - ThreadIds.Y); + float res = Hlsl.Min(DispatchSize.Y, 700.0f); + Float2 uv = (fragCoord - (Float2)DispatchSize.XY * 0.5f) / res; + float sf = 1.0f / DispatchSize.Y; + Float3 col = GetColor(uv, 0.0f, 0.0f); + float pL = 0.0f; + float hatch = Hatch(uv, res); + + col *= hatch; + + const int lNum = 5; + float flNum = lNum; + + for (int i = 0; i < lNum; i++) + { + float fi = i; + + hatch = Hatch(uv + Hlsl.Sin(new Float2(41.0f, 289.0f) * (fi + 1.0f)), res); + + Float4 c = MapLayer(new Float3(uv, 1.0f), fi); + Float4 cSh = MapLayer(new Float3(uv - new Float2(0.03f, -0.03f) * ((flNum - fi) / flNum * 0.5f + 0.5f), 1.0f), fi); + float sh = (fi + 1.0f) / (flNum); + Float3 lCol = GetColor(uv, sh, fi + 1.0f); + Float3 ld = Hlsl.Normalize(new Float3(-1, 1, -0.25f)); + Float3 n = Hlsl.Normalize(new Float3(0.0f, 0.0f, -1.0f) + c.YZW); + float diff = Hlsl.Max(Hlsl.Dot(ld, n), 0.0f); + + diff *= 2.5f; + + Float3 eCol = lCol * (diff + 1.0f); + float sfL = sf * Hlsl.Length(c.YZX) * 2.0f; + float sfLSh = sf * Hlsl.Length(cSh.YZX) * 6.0f; + const float shF = 0.5f; + + col = Hlsl.Lerp(col, Float3.Zero, (1.0f - Hlsl.SmoothStep(0.0f, sfLSh, Hlsl.Max(cSh.X, pL))) * shF); + col = Hlsl.Lerp(col, Float3.Zero, (1.0f - Hlsl.SmoothStep(0.0f, sfL * 3.0f, c.X)) * 0.25f); + col = Hlsl.Lerp(col, Float3.Zero, (1.0f - Hlsl.SmoothStep(0.0f, sfL, c.X)) * 0.85f); + col = Hlsl.Lerp(col, eCol * hatch, (1.0f - Hlsl.SmoothStep(0.0f, sfL, c.X + Hlsl.Length(c.YZX) * 0.003f))); + col = Hlsl.Lerp(col, lCol * hatch, (1.0f - Hlsl.SmoothStep(0.0f, sfL, c.X + Hlsl.Length(c.YZX) * 0.006f))); + + pL = c.X; + } + + col *= Hlsl.Lerp(new Float3(1.8f, 1, 0.7f).ZYX, new Float3(1.8f, 1, 0.7f).XZY, Noise2D(uv * 2.0f)); + + Float3 rn3 = Noise2D(uv * DispatchSize.Y / 1.0f + 1.7f) - Noise2D(uv * DispatchSize.Y / 1.0f + 3.4f); + + col *= 0.93f + 0.07f * rn3.XYZ + 0.07f * Hlsl.Dot(rn3, new Float3(0.299f, 0.587f, 0.114f)); + + uv = fragCoord / DispatchSize.XY; + + col *= Hlsl.Pow(16.0f * uv.X * uv.Y * (1.0f - uv.X) * (1.0f - uv.Y), 0.0625f); + + destination[ThreadIds.XY] = new Float4(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1); + } + } +} diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs new file mode 100644 index 00000000..46c137e2 --- /dev/null +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ExtrudedTruchetPattern.cs @@ -0,0 +1,298 @@ +namespace ComputeSharp.SwapChain.Shaders.Compute +{ + /// + /// A basic extruded square grid-based blobby Truchet pattern. + /// Ported from . + /// Created by Shane. + /// + [AutoConstructor] + internal readonly partial struct ExtrudedTruchetPattern : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + /// + /// Curve shape - Round: 0, Semi-round: 1, Octagonal: 2, Superellipse: 3, Straight: 4. + /// + private static readonly int SHAPE = 0; + + /// + /// Object ID: Either the back plane or the metaballs. + /// + private static int objID; + + // Standard 2D rotation formula. + private static Float2x2 Rotate2x2(float a) + { + float c = Hlsl.Cos(a), s = Hlsl.Sin(a); + + return new(c, -s, s, c); + } + + // IQ's Float2 to float hash. + private static float Hash21(Float2 p) + { + return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new Float2(27.619f, 57.583f))) * 43758.5453f); + } + + // Various distance metrics. + private static float Distance(Float2 p) + { + if (SHAPE == 0) + { + return Hlsl.Length(p); + } + else p = Hlsl.Abs(p); + + switch (SHAPE) + { + case 1: return Hlsl.Max(Hlsl.Length(p), (p.X + p.Y) * 0.7071f + 0.015f); + case 2: return Hlsl.Max((p.X + p.Y) * 0.7071f, Hlsl.Max(p.X, p.Y)); + case 3: return Hlsl.Pow(Hlsl.Dot(Hlsl.Pow(p, 3), 1), 1.0f / 3.0f); + default: return (p.X + p.Y) * 0.7071f; + } + } + + // GLSL's mod function + private static float Mod(float x, float y) + { + return x - y * Hlsl.Floor(x / y); + } + + // A standard square grid 2D blobby Truchet routine: Render circles + // in opposite corners of a tile, reverse the pattern on alternate + // checker tiles, and randomly rotate. + private static float Truchet(Float2 p) + { + const float sc = 0.5f; + Float2 ip = Hlsl.Floor(p / sc) + 0.5f; + + p -= ip * sc; + + float rnd = Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(ip, new Float2(1, 113))) * 45758.5453f); + + if (rnd < .5) p.Y = -p.Y; + + float d = Hlsl.Min(Distance(p - 0.5f * sc), Distance(p + 0.5f * sc)) - 0.5f * sc; + + if (SHAPE == 4) + { + d += (0.5f - 0.5f / Hlsl.Sqrt(2.0f)) * sc; + } + + if (rnd < 0.5f) d = -d; + if (Mod(ip.X + ip.Y, 2.0f) < 0.5f) d = -d; + + return d - 0.03f; + } + + // The scene's distance function: There'd be faster ways to do this, but it's + // more readable this way. Plus, this is a pretty simple scene, so it's + // efficient enough. + private static float M(Float3 p) + { + float fl = -p.Z; + float obj = Truchet(p.XY); + + obj = Hlsl.Max(obj, Hlsl.Abs(p.Z) - 0.125f) - Hlsl.SmoothStep(0.03f, 0.25f, -obj) * 0.1f; + + float studs = 1e5f; + const float sc = 0.5f; + Float2 q = p.XY + 0.5f * sc; + Float2 iq = Hlsl.Floor(q / sc) + 0.5f; + + q -= iq * sc; + + if (Mod(iq.X + iq.Y, 2.0f) > 0.5f) + { + studs = Hlsl.Max(Hlsl.Length(q) - 0.1f * sc - 0.02f, Hlsl.Abs(p.Z) - 0.26f); + } + + objID = fl < obj && fl < studs ? 0 : obj < studs ? 1 : 2; + + return Hlsl.Min(Hlsl.Min(fl, obj), studs); + } + + // Cheap shadows are hard. In fact, I'd almost say, shadowing particular scenes with limited + // iterations is impossible... However, I'd be very grateful if someone could prove me wrong. :) + private static float SoftShadow(Float3 ro, Float3 lp, Float3 n, float k) + { + const int iter = 24; + + ro += n * 0.0015f; + + Float3 rd = lp - ro; + float shade = 1.0f; + float t = 0; + float end = Hlsl.Max(Hlsl.Length(rd), 0.0001f); + + rd /= end; + + for (int i = 0; i < iter; i++) + { + float d = M(ro + rd * t); + + shade = Hlsl.Min(shade, k * d / t); + t += Hlsl.Clamp(d, 0.01f, 0.25f); + + if (d < 0.0f || t > end) break; + } + + return Hlsl.Max(shade, 0.0f); + } + + + // I keep a collection of occlusion routines... OK, that sounded really nerdy. :) + // Anyway, I like this one. I'm assuHlsl.Ming it's based on IQ's original. + private float CalculateAO(in Float3 p, in Float3 n) + { + float sca = 2.0f, occ = 0.0f; + + for (int i = (int)Hlsl.Min(time, 0f); i < 5; i++) + { + float hr = (i + 1f) * 0.15f / 5.0f; + float d = M(p + n * hr); + occ += (hr - d) * sca; + sca *= 0.7f; + + if (sca > 1e5f) break; + } + + return Hlsl.Clamp(1.0f - occ, 0.0f, 1.0f); + } + + // Standard normal function. + private static Float3 Normal(in Float3 p) + { + Float2 e = new(0.001f, 0); + + return Hlsl.Normalize(new Float3( + M(p + e.XYY) - M(p - e.XYY), + M(p + e.YXY) - M(p - e.YXY), + M(p + e.YYX) - M(p - e.YYX))); + } + + /// + public void Execute() + { + Int2 coords = new(ThreadIds.X, DispatchSize.Y - ThreadIds.Y); + Float2 u = (coords - (Float2)DispatchSize.XY * 0.5f) / DispatchSize.Y; + Float3 + r = Hlsl.Normalize(new Float3(u, 1)), + o = new(0, time / 2.0f, -3), + l = o + new Float3(0.25f, 0.25f, 2.0f); + + r.YZ = Hlsl.Mul(Rotate2x2(0.15f), r.YZ); + r.XZ = Hlsl.Mul(Rotate2x2(-Hlsl.Cos(time * 3.14159f / 32.0f) / 8.0f), r.XZ); + r.XY = Hlsl.Mul(Rotate2x2(Hlsl.Sin(time * 3.14159f / 32.0f) / 8.0f), r.XY); + + float d, t = Hash21(r.XY * 57.0f + Hlsl.Frac(time)) * 0.5f, glow = 0; + + for (int i = 0; i < 96; i++) + { + d = M(o + r * t); + + if (Hlsl.Abs(d) < .001) break; + + t += d * 0.7f; + glow += 0.2f / (1.0f + Hlsl.Abs(d) * 5.0f); + } + + int gObjID = objID; + Float3 p = o + r * t, n = Normal(p); + Float2 uv = p.XY; + float sc = 0.5f; + Float2 iuv = Hlsl.Floor(uv / sc) + 0.5f; + + uv -= iuv * sc; + + Float2 uv2 = p.XY + 0.5f * sc; + Float2 iuv2 = Hlsl.Floor(uv2 / sc) + 0.5f; + + uv2 -= iuv2 * sc; + + float bord = Hlsl.Max(Hlsl.Abs(uv.X), Hlsl.Abs(uv.Y)) - 0.5f * sc; + + bord = Hlsl.Abs(bord) - 0.002f; + d = Truchet(p.XY); + + float lSc = 20.0f; + float pat = (Hlsl.Abs(Hlsl.Frac((uv.X - uv.Y) * lSc - 0.5f) - 0.5f) * 2.0f - 0.5f) / lSc; + float pat2 = (Hlsl.Abs(Hlsl.Frac((uv.X + uv.Y) * lSc + 0.5f) - 0.5f) * 2.0f - 0.5f) / lSc; + float sf = Hlsl.Dot(Hlsl.Sin(p.XY - Hlsl.Cos(p.YX * 2.0f)), 0.5f); + float sf2 = Hlsl.Dot(Hlsl.Sin(p.XY * 1.5f - Hlsl.Cos(p.YX * 3.0f)), 0.5f); + Float4 col1 = Hlsl.Lerp(new Float4(1, 0.75f, 0.6f, 0), new Float4(1, 0.85f, 0.65f, 0), Hlsl.SmoothStep(-0.5f, 0.5f, sf)); + Float4 col2 = Hlsl.Lerp(new Float4(0.4f, 0.7f, 1, 0), new Float4(0.3f, 0.85f, 0.95f, 0), Hlsl.SmoothStep(-0.5f, 0.5f, sf2) * 0.5f); + + col1 = Hlsl.Pow(col1, 1.6f); + col2 = Hlsl.Lerp(col1.ZYXW, Hlsl.Pow(col2, 1.4f), 0.666f); + + Float4 oCol; + + if (gObjID == 0) + { + oCol = Hlsl.Lerp(col2, 0, (1.0f - Hlsl.SmoothStep(0, 0.01f, pat2)) * 0.35f); + oCol = Hlsl.Lerp(oCol, 0, (1.0f - Hlsl.SmoothStep(0, 0.01f, bord)) * 0.8f); + + if (Mod(iuv.X + iuv.Y, 2.0f) > 0.5f) oCol *= 0.8f; + + oCol = Hlsl.Lerp(oCol, 0, (1.0f - Hlsl.SmoothStep(0, 0.01f, d - 0.015f)) * 0.8f); + } + else if (gObjID == 1) + { + oCol = Hlsl.Lerp(1, 0, 1.0f - Hlsl.SmoothStep(0, 0.01f, d + 0.05f)); + Float4 fCol = Hlsl.Lerp(col1, 0, (1.0f - Hlsl.SmoothStep(0, 0.01f, pat)) * 0.35f); + fCol = Hlsl.Lerp(fCol, 0, (1.0f - Hlsl.SmoothStep(0, 0.01f, bord)) * 0.8f); + + if (Mod(iuv.X + iuv.Y, 2.0f) < 0.5f) fCol *= 0.8f; + + oCol = Hlsl.Lerp(oCol, fCol, 1 - Hlsl.SmoothStep(0, 0.01f, d + 0.08f)); + oCol = Hlsl.Lerp(oCol, 0, (1 - Hlsl.SmoothStep(0, 0.01f, Hlsl.Length(uv2) - 0.08f)) * 0.8f); + } + else + { + oCol = col1; + + float ht = 0.26f; + + if (Mod(iuv2.X + iuv2.Y + 1.0f, 2.0f) > 0.5f) + { + float tmp = pat; pat = pat2; pat2 = tmp; + + oCol = col2; + ht = 0.05f; + } + + float mark = Hlsl.Length(uv2); + float markRim = Hlsl.Max(Hlsl.Abs(mark - 0.07f), Hlsl.Abs(p.Z + ht)) - 0.003f; + + oCol = Hlsl.Lerp(oCol, 0, (1 - Hlsl.SmoothStep(0, 0.01f, markRim)) * 0.8f); + oCol = Hlsl.Lerp(oCol, 0, (1 - Hlsl.SmoothStep(0, 0.01f, mark - 0.015f)) * 0.8f); + } + + Float3 ld = l - p; + float lDist = Hlsl.Length(ld); + + ld /= lDist; + + float at = 1.0f / (1.0f + lDist * lDist * 0.125f); + float sh = SoftShadow(p, l, n, 8); + float ao = CalculateAO(p, n); + float df = Hlsl.Max(Hlsl.Dot(n, ld), 0); + float sp = Hlsl.Pow(Hlsl.Max(Hlsl.Dot(Hlsl.Reflect(r, n), ld), 0), 32); + + Float4 c = oCol * (df * sh + sp * sh + 0.5f) * at * ao; + + c = Hlsl.Sqrt(Hlsl.Max(c, 0)); + + texture[ThreadIds.XY] = c; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs b/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs new file mode 100644 index 00000000..00a9298e --- /dev/null +++ b/tests/ComputeSharp.Tests/Shaders/Compute/FractalTiling.cs @@ -0,0 +1,51 @@ +namespace ComputeSharp.SwapChain.Shaders.Compute +{ + /// + /// A shader creating a fractal tiling animation. + /// Ported from . + /// Created by Inigo Quilez. + /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. + /// + [AutoConstructor] + internal readonly partial struct FractalTiling : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + /// + public void Execute() + { + Float2 position = ((Float2)(256 * ThreadIds.XY)) / DispatchSize.X + time; + Float4 color = 0; + + for (int i = 0; i < 6; i++) + { + Float2 a = Hlsl.Floor(position); + Float2 b = Hlsl.Frac(position); + Float4 w = Hlsl.Frac( + (Hlsl.Sin(a.X * 7 + 31.0f * a.Y + 0.01f * time) + + new Float4(0.035f, 0.01f, 0, 0.7f)) + * 13.545317f); + + color.XYZ += w.XYZ * + 2.0f * Hlsl.SmoothStep(0.45f, 0.55f, w.W) * + Hlsl.Sqrt(16.0f * b.X * b.Y * (1.0f - b.X) * (1.0f - b.Y)); + + position /= 2.0f; + color /= 2.0f; + } + + color.XYZ = Hlsl.Pow(color.XYZ, new Float3(0.7f, 0.8f, 0.5f)); + color.W = 1.0f; + + texture[ThreadIds.XY] = color; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs b/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs new file mode 100644 index 00000000..03f3a9a9 --- /dev/null +++ b/tests/ComputeSharp.Tests/Shaders/Compute/MengerJourney.cs @@ -0,0 +1,175 @@ +namespace ComputeSharp.SwapChain.Shaders.Compute +{ + /// + /// A shader creating a flythrough in a Menger system. + /// Ported from . + /// Created by Syntopia. + /// + [AutoConstructor] + internal readonly partial struct MengerJourney : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + private const int MaxSteps = 30; + private const float MinimumDistance = 0.0009f; + private const float NormalDistance = 0.0002f; + private const int Iterations = 7; + private const float Scale = 3.0f; + private const float FieldOfView = 1.0f; + private const float Jitter = 0.05f; + private const float FudgeFactor = 0.7f; + private const float NonLinearPerspective = 2.0f; + private const float Ambient = 0.32184f; + private const float Diffuse = 0.5f; + + private static readonly Float3 LightDir = 1.0f; + private static readonly Float3 LightColor = new(1.0f, 1.0f, 0.858824f); + private static readonly Float3 LightDir2 = new(1.0f, -1.0f, 1.0f); + private static readonly Float3 LightColor2 = new(0, 0.333333f, 1.0f); + private static readonly Float3 Offset = new(0.92858f, 0.92858f, 0.32858f); + + /// + /// Rotates a given value by a specified amount. + /// + private static Float2 Rotate(Float2 v, float a) + { + return new(Hlsl.Cos(a) * v.X + Hlsl.Sin(a) * v.Y, -Hlsl.Sin(a) * v.X + Hlsl.Cos(a) * v.Y); + } + + /// + /// Calculates the light at a specified normal and starting color. + /// Uses two light sources and no specular lights. + /// + private static Float3 GetLight(in Float3 color, in Float3 normal) + { + Float3 lightDir = Hlsl.Normalize(LightDir); + float diffuse = Hlsl.Max(0.0f, Hlsl.Dot(-normal, lightDir)); + + Float3 lightDir2 = Hlsl.Normalize(LightDir2); + float diffuse2 = Hlsl.Max(0.0f, Hlsl.Dot(-normal, lightDir2)); + + return + (diffuse * Diffuse) * (LightColor * color) + + (diffuse2 * Diffuse) * (LightColor2 * color); + } + + /// + /// DE: Infinitely tiled Menger IFS. + /// For more info on KIFS, see + /// + private float DE(Float3 z) + { + // Performs the GLSL mod function. + static Float3 Mod(Float3 x, float y) + { + return x - y * Hlsl.Floor(x / y); + } + + z = Hlsl.Abs(1.0f - Mod(z, 2.0f)); + + float d = 1000.0f; + + for (int n = 0; n < Iterations; n++) + { + z.XY = Rotate(z.XY, 4.0f + 2.0f * Hlsl.Cos(time / 8.0f)); + z = Hlsl.Abs(z); + + if (z.X < z.Y) { z.XY = z.YX; } + if (z.X < z.Z) { z.XZ = z.ZX; } + if (z.Y < z.Z) { z.YZ = z.ZY; } + + z = Scale * z - Offset * (Scale - 1.0f); + + if (z.Z < -0.5f * Offset.Z * (Scale - 1.0)) + { + z.Z += Offset.Z * (Scale - 1.0f); + } + + d = Hlsl.Min(d, Hlsl.Length(z) * Hlsl.Pow(Scale, -n - 1.0f)); + } + + return d - 0.001f; + } + + /// + /// Calculates the finite difference normal at a given position. + /// + private Float3 getNormal(in Float3 pos) + { + Float3 e = new(0.0f, NormalDistance, 0.0f); + + return Hlsl.Normalize(new Float3( + DE(pos + e.YXX) - DE(pos - e.YXX), + DE(pos + e.XYX) - DE(pos - e.XYX), + DE(pos + e.XXY) - DE(pos - e.XXY))); + } + + /// + /// Performs a ray march operation on a specific position. + /// + private Float4 RayMarch(in Float3 from, Float3 dir, in Float2 fragCoord) + { + // Computes a pseudo-random number + static float Rand(Float2 co) + { + return Hlsl.Frac(Hlsl.Cos(Hlsl.Dot(co, new Float2(4.898f, 7.23f))) * 23421.631f); + } + + float totalDistance = Jitter * Rand(fragCoord.XY + time); + Float3 dir2 = dir; + float distance = 0; + int steps = 0; + Float3 pos = 0; + + for (int i = 0; i < MaxSteps; i++) + { + dir.ZY = Rotate(dir2.ZY, totalDistance * Hlsl.Cos(time / 4.0f) * NonLinearPerspective); + pos = from + totalDistance * dir; + distance = DE(pos) * FudgeFactor; + totalDistance += distance; + + if (distance < MinimumDistance) break; + + steps = i; + } + + float smoothStep = steps + distance / MinimumDistance; + float ao = 1.1f - smoothStep / MaxSteps; + Float3 normal = getNormal(pos - dir * NormalDistance * 3.0f); + Float3 color = 1.0f; + Float3 light = GetLight(color, normal); + + color = (color * Ambient + light) * ao; + + return new(color.X, color.Y, color.Z, 1.0f); + } + + /// + public void Execute() + { + Float3 camPos = 0.5f * time * new Float3(1.0f, 0.0f, 0.0f); + Float3 target = camPos + new Float3(1.0f, 0.0f * Hlsl.Cos(time), 0.0f * Hlsl.Sin(0.4f * time)); + Float3 camDir = Hlsl.Normalize(target - camPos); + Float3 camUp = new(0.0f, 1.0f, 0.0f); + + camUp = Hlsl.Normalize(camUp - Hlsl.Dot(camDir, camUp) * camDir); + + Float3 camRight = Hlsl.Normalize(Hlsl.Cross(camDir, camUp)); + Float2 coord = -1.0f + 2.0f * (Float2)ThreadIds.XY / DispatchSize.XY; + + coord.X *= (float)DispatchSize.X / DispatchSize.Y; + + Float3 rayDir = Hlsl.Normalize(camDir + (coord.X * camRight + coord.Y * camUp) * FieldOfView); + + texture[ThreadIds.XY] = RayMarch(camPos, rayDir, ThreadIds.XY); + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs b/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs new file mode 100644 index 00000000..b2d5136a --- /dev/null +++ b/tests/ComputeSharp.Tests/Shaders/Compute/Octagrams.cs @@ -0,0 +1,128 @@ +namespace ComputeSharp.SwapChain.Shaders.Compute +{ + /// + /// A shader creating an octagram animation, inspired by arabesque. + /// Ported from . + /// Created by whisky_shusuky. + /// + [AutoConstructor] + internal readonly partial struct Octagrams : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + private static Float2x2 Rotate(float a) + { + float c = Hlsl.Cos(a), s = Hlsl.Sin(a); + + return new(c, s, -s, c); + } + + private static float Box(Float3 pos, float scale) + { + static float SDBox(Float3 p, Float3 b) + { + Float3 q = Hlsl.Abs(p) - b; + + return Hlsl.Length(Hlsl.Max(q, 0.0f)) + + Hlsl.Min(Hlsl.Max(q.X, Hlsl.Max(q.Y, q.Z)), 0.0f); + } + + pos *= scale; + + float b = SDBox(pos, new(0.4f, 0.4f, 0.1f)) / 1.5f; + + pos.XY *= 5.0f; + pos.Y -= 3.5f; + pos.XY = Hlsl.Mul(pos.XY, Rotate(0.75f)); + + return -b; + } + + private static float BoxSet(Float3 pos, float gTime) + { + Float3 pos_origin = pos; + + pos = pos_origin; + pos.Y += Hlsl.Sin(gTime * 0.4f) * 2.5f; + pos.XY = Hlsl.Mul(pos.XY, Rotate(0.8f)); + + float box1 = Box(pos, 2.0f - Hlsl.Abs(Hlsl.Sin(gTime * 0.4f)) * 1.5f); + + pos = pos_origin; + pos.Y -= Hlsl.Sin(gTime * 0.4f) * 2.5f; + pos.XY = Hlsl.Mul(pos.XY, Rotate(0.8f)); + + float box2 = Box(pos, 2.0f - Hlsl.Abs(Hlsl.Sin(gTime * 0.4f)) * 1.5f); + + pos = pos_origin; + pos.X += Hlsl.Sin(gTime * 0.4f) * 2.5f; + pos.XY = Hlsl.Mul(pos.XY, Rotate(0.8f)); + + float box3 = Box(pos, 2.0f - Hlsl.Abs(Hlsl.Sin(gTime * 0.4f)) * 1.5f); + + pos = pos_origin; + pos.X -= Hlsl.Sin(gTime * 0.4f) * 2.5f; + pos.XY = Hlsl.Mul(pos.XY, Rotate(0.8f)); + + float box4 = Box(pos, 2.0f - Hlsl.Abs(Hlsl.Sin(gTime * 0.4f)) * 1.5f); + + pos = pos_origin; + pos.XY = Hlsl.Mul(pos.XY, Rotate(0.8f)); + + float box5 = Box(pos, 0.5f) * 6.0f; + + pos = pos_origin; + + float box6 = Box(pos, 0.5f) * 6.0f; + float result = Hlsl.Max(Hlsl.Max(Hlsl.Max(Hlsl.Max(Hlsl.Max(box1, box2), box3), box4), box5), box6); + + return result; + } + + /// + public void Execute() + { + Float2 p = ((Float2)ThreadIds.XY * 2.0f - DispatchSize.XY) / Hlsl.Min(DispatchSize.X, DispatchSize.Y); + Float3 ro = new(0.0f, -0.2f, time * 4.0f); + Float3 ray = Hlsl.Normalize(new Float3(p, 1.5f)); + + ray.XY = Hlsl.Mul(ray.XY, Rotate(Hlsl.Sin(time * 0.03f) * 5.0f)); + ray.YZ = Hlsl.Mul(ray.YZ, Rotate(Hlsl.Sin(time * 0.05f) * 0.2f)); + + float t = 0.1f; + float ac = 0.0f; + + for (int i = 0; i < 99; i++) + { + static Float3 Mod(Float3 x, float y) + { + return x - y * Hlsl.Floor(x / y); + } + + Float3 pos = ro + ray * t; + + pos = Mod(pos - 2.0f, 4.0f) - 2.0f; + + float gTime = time - i * 0.01f; + float d = BoxSet(pos, gTime); + + d = Hlsl.Max(Hlsl.Abs(d), 0.01f); + ac += Hlsl.Exp(-d * 23.0f); + t += d * 0.55f; + } + + Float3 col = ac * 0.02f + new Float3(0.0f, 0.2f * Hlsl.Abs(Hlsl.Sin(time)), 0.5f + Hlsl.Sin(time) * 0.2f); + Float4 color = new(col, 1.0f - t * (0.02f + 0.02f * Hlsl.Sin(time))); + + texture[ThreadIds.XY] = color; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs b/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs new file mode 100644 index 00000000..1e39535d --- /dev/null +++ b/tests/ComputeSharp.Tests/Shaders/Compute/ProteanClouds.cs @@ -0,0 +1,173 @@ +namespace ComputeSharp.SwapChain.Shaders.Compute +{ + /// + /// Fully procedural 3D animated volume with three evaluations per step (for shading). + /// Ported from . + /// Created by nimitz (twitter: @stormoid). + /// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. + /// + [AutoConstructor] + internal readonly partial struct ProteanClouds : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time Hlsl.Since the start of the application. + /// + public readonly float time; + + private static readonly Float3x3 m3 = new Float3x3(0.33338f, 0.56034f, -0.71817f, -0.87887f, 0.32651f, -0.15323f, 0.15162f, 0.69596f, 0.61339f) * 1.93f; + + private static Float2x2 Rotate(in float a) + { + float c = Hlsl.Cos(a), s = Hlsl.Sin(a); + + return new(c, s, -s, c); + } + + private static float LinStep(in float mn, in float mx, in float x) + { + return Hlsl.Clamp((x - mn) / (mx - mn), 0.0f, 1.0f); + } + + private static Float2 Disp(float t) + { + return new Float2(Hlsl.Sin(t * 0.22f) * 1.0f, Hlsl.Cos(t * 0.175f) * 1.0f) * 2.0f; + } + + private Float2 Map(Float3 p, float prm1, Float2 bsMo) + { + Float3 p2 = p; + + p2.XY -= Disp(p.Z).XY; + p.XY = Hlsl.Mul(p.XY, Rotate(Hlsl.Sin(p.Z + time) * (0.1f + prm1 * 0.05f) + time * 0.09f)); + + float cl = Hlsl.Dot(p2.XY, p2.XY); + float d = 0.0f; + + p *= 0.61f; + + float z = 1.0f; + float trk = 1.0f; + float dspAmp = 0.1f + prm1 * 0.2f; + + for (int i = 0; i < 5; i++) + { + p += Hlsl.Sin(p.ZXY * 0.75f * trk + time * trk * 0.8f) * dspAmp; + d -= Hlsl.Abs(Hlsl.Dot(Hlsl.Cos(p), Hlsl.Sin(p.YZX)) * z); + z *= 0.57f; + trk *= 1.4f; + + p = Hlsl.Mul(p, m3); + } + + d = Hlsl.Abs(d + prm1 * 3.0f) + prm1 * 0.3f - 2.5f + bsMo.Y; + + return new Float2(d + cl * 0.2f + 0.25f, cl); + } + + private Float4 Render(Float3 ro, Float3 rd, float time, float prm1, Float2 bsMo) + { + Float4 rez = 0; + float t = 1.5f; + float fogT = 0; + + for (int i = 0; i < 130; i++) + { + if (rez.A > 0.99f) break; + + Float3 pos = ro + t * rd; + Float2 mpv = Map(pos, prm1, bsMo); + float den = Hlsl.Clamp(mpv.X - 0.3f, 0.0f, 1.0f) * 1.12f; + float dn = Hlsl.Clamp((mpv.X + 2.0f), 0.0f, 3.0f); + Float4 col = 0f; + + if (mpv.X > 0.6f) + { + + col = new Float4(Hlsl.Sin(new Float3(5.0f, 0.4f, 0.2f) + mpv.Y * 0.1f + Hlsl.Sin(pos.Z * 0.4f) * 0.5f + 1.8f) * 0.5f + 0.5f, 0.08f); + col *= den * den * den; + col.RGB *= LinStep(4.0f, -2.5f, mpv.X) * 2.3f; + + float dif = Hlsl.Clamp((den - Map(pos + 0.8f, prm1, bsMo).X) / 9.0f, 0.001f, 1.0f); + + dif += Hlsl.Clamp((den - Map(pos + 0.35f, prm1, bsMo).X) / 2.5f, 0.001f, 1.0f); + col.XYZ *= den * (new Float3(0.005f, 0.045f, 0.075f) + 1.5f * new Float3(0.033f, 0.07f, 0.03f) * dif); + } + + float fogC = Hlsl.Exp(t * 0.2f - 2.2f); + + col += new Float4(0.06f, 0.11f, 0.11f, 0.1f) * Hlsl.Clamp(fogC - fogT, 0.0f, 1.0f); + fogT = fogC; + rez += col * (1.0f - rez.A); + t += Hlsl.Clamp(0.5f - dn * dn * 0.05f, 0.09f, 0.3f); + } + + return Hlsl.Clamp(rez, 0.0f, 1.0f); + } + + private static float GetSaturation(Float3 c) + { + float mi = Hlsl.Min(Hlsl.Min(c.X, c.Y), c.Z); + float ma = Hlsl.Max(Hlsl.Max(c.X, c.Y), c.Z); + + return (ma - mi) / (ma + (float)1e-7); + } + + private static Float3 ILerp(in Float3 a, in Float3 b, in float x) + { + Float3 ic = Hlsl.Lerp(a, b, x) + new Float3((float)1e-6, 0.0f, 0.0f); + float sd = Hlsl.Abs(GetSaturation(ic) - Hlsl.Lerp(GetSaturation(a), GetSaturation(b), x)); + Float3 dir = Hlsl.Normalize(new Float3(2.0f * ic.X - ic.Y - ic.Z, 2.0f * ic.Y - ic.X - ic.Z, 2.0f * ic.Z - ic.Y - ic.X)); + float lgt = Hlsl.Dot(1.0f, ic); + float ff = Hlsl.Dot(dir, Hlsl.Normalize(ic)); + + ic += 1.5f * dir * sd * ff * lgt; + + return Hlsl.Clamp(ic, 0.0f, 1.0f); + } + + /// + public void Execute() + { + Float2 q = (Float2)ThreadIds.XY / DispatchSize.XY; + Float2 p = (ThreadIds.XY - 0.5f * (Float2)DispatchSize.XY) / DispatchSize.Y; + Float2 bsMo = -0.5f * (Float2)DispatchSize.XY / DispatchSize.Y; + float scaledTime = time * 3.0f; + Float3 ro = new(0, 0, scaledTime); + + ro += new Float3(Hlsl.Sin(time) * 0.5f, Hlsl.Sin(time * 1.0f) * 0.0f, 0); + + float dspAmp = 0.85f; + + ro.XY += Disp(ro.Z) * dspAmp; + + float tgtDst = 3.5f; + Float3 target = Hlsl.Normalize(ro - new Float3(Disp(scaledTime + tgtDst) * dspAmp, scaledTime + tgtDst)); + + ro.X -= bsMo.X * 2.0f; + + Float3 rightdir = Hlsl.Normalize(Hlsl.Cross(target, new Float3(0, 1, 0))); + Float3 updir = Hlsl.Normalize(Hlsl.Cross(rightdir, target)); + + rightdir = Hlsl.Normalize(Hlsl.Cross(updir, target)); + + Float3 rd = Hlsl.Normalize((p.X * rightdir + p.Y * updir) * 1.0f - target); + + rd.XY = Hlsl.Mul(rd.XY, Rotate(-Disp(scaledTime + 3.5f).X * 0.2f + bsMo.X)); + + float prm1 = Hlsl.SmoothStep(-0.4f, 0.4f, Hlsl.Sin(time * 0.3f)); + Float4 scn = Render(ro, rd, scaledTime, prm1, bsMo); + Float3 col = scn.RGB; + + col = ILerp(col.BGR, col.RGB, Hlsl.Clamp(1.0f - prm1, 0.05f, 1.0f)); + col = Hlsl.Pow(col, new Float3(0.55f, 0.65f, 0.6f)) * new Float3(1.0f, 0.97f, 0.9f); + col *= Hlsl.Pow(16.0f * q.X * q.Y * (1.0f - q.X) * (1.0f - q.Y), 0.12f) * 0.7f + 0.3f; + + texture[ThreadIds.XY] = new Float4(col, 1.0f); + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs b/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs new file mode 100644 index 00000000..2a3546b8 --- /dev/null +++ b/tests/ComputeSharp.Tests/Shaders/Compute/PyramidPattern.cs @@ -0,0 +1,183 @@ +namespace ComputeSharp.SwapChain.Shaders.Compute +{ + /// + /// An offset grid of square-based pyramids whose tips have been offset according to an underlying directional noise field. + /// The faux lighting is provided via bump mapping. No raymarching was harmed during the making of this example. + /// Ported from . + /// Created by Shane. + /// + [AutoConstructor] + internal readonly partial struct PyramidPattern : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time Hlsl.Since the start of the application. + /// + public readonly float time; + + // Standard 2D rotation formula. + private static Float2x2 Rotate2x2(in float a) + { + float c = Hlsl.Cos(a), s = Hlsl.Sin(a); + + return new(c, -s, s, c); + } + + // IQ's Float2 to float hash. + private static float Hash21(Float2 p) + { + return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new Float2(27.619f, 57.583f))) * 43758.5453f); + } + + // Float2 to Float2 hash. + private static Float2 Hash22B(Float2 p) + { + float n = Hlsl.Sin(Hlsl.Dot(p, new Float2(41, 289))); + + return Hlsl.Frac(new Float2(262144, 32768) * n) * 2.0f - 1.0f; + } + + // Based on IQ's gradient noise formula. + private static float N2D3G(Float2 p) + { + Float2 i = Hlsl.Floor(p); + + p -= i; + + Float4 v = default; + + v.X = Hlsl.Dot(Hash22B(i), p); + v.Y = Hlsl.Dot(Hash22B(i + Float2.UnitX), p - Float2.UnitX); + v.Z = Hlsl.Dot(Hash22B(i + Float2.UnitY), p - Float2.UnitY); + v.W = Hlsl.Dot(Hash22B(i + 1.0f), p - 1.0f); + + p = p * p * (3.0f - 2.0f * p); + + return Hlsl.Lerp(Hlsl.Lerp(v.X, v.Y, p.X), Hlsl.Lerp(v.Z, v.W, p.X), p.Y); + } + + // Two layers of noise. + private static float FBM(Float2 p) + { + return N2D3G(p) * 0.66f + N2D3G(p * 2.0f) * 0.34f; + } + + // HLSL mod from GLSL + private static float Mod(float x, float y) + { + return x - y * Hlsl.Floor(x / y); + } + + private float BMap(Float2 p) + { + p = Hlsl.Mul(p, Rotate2x2(-3.14159f / 5.0f)); + + if (Mod(Hlsl.Floor(p.Y), 2.0f) < 0.5f) + { + p.X += 0.5f; + } + + Float2 ip = Hlsl.Floor(p); + + p -= ip + 0.5f; + + float ang = -3.14159f * 3.0f / 5.0f + (FBM(ip / 8.0f + time / 3.0f)) * 6.2831f * 2.0f; + + Float2 offs = new Float2(Hlsl.Cos(ang), Hlsl.Sin(ang)) * 0.35f; + + if (p.X < offs.X) p.X = 1.0f - (p.X + 0.5f) / Hlsl.Abs(offs.X + 0.5f); + else p.X = (p.X - offs.X) / (0.5f - offs.X); + + if (p.Y < offs.Y) p.Y = 1.0f - (p.Y + 0.5f) / Hlsl.Abs(offs.Y + 0.5f); + else p.Y = (p.Y - offs.Y) / (0.5f - offs.Y); + + return 1.0f - Hlsl.Max(p.X, p.Y); + } + + + // Standard function-based bump mapping function, with an edge value included for good measure + private Float3 DoBumpMap(in Float2 p, in Float3 n, float bumpfactor, ref float edge) + { + Float2 e = new(0.025f, 0); + + float f = BMap(p); + float fx = BMap(p - e.XY); + float fy = BMap(p - e.YX); + float fx2 = BMap(p + e.XY); + float fy2 = BMap(p + e.YX); + + Float3 grad = (new Float3(fx - fx2, fy - fx2, 0)) / e.X / 2.0f; + + edge = Hlsl.Length(new Float2(fx, fy) + new Float2(fx2, fy2) - f * 2.0f); + edge = Hlsl.SmoothStep(0.0f, 1.0f, edge / e.X); + + grad -= n * Hlsl.Dot(n, grad); + + return Hlsl.Normalize(n + grad * bumpfactor); + } + + + // A hatch-like algorithm, or a stipple... or some kind of textured pattern + private float DoHatch(Float2 p, float res) + { + p *= res / 16.0f; + + float hatch = Hlsl.Clamp(Hlsl.Sin((p.X - p.Y) * 3.14159f * 200.0f) * 2.0f + 0.5f, 0.0f, 1.0f); + + float hRnd = Hash21(Hlsl.Floor(p * 6.0f) + 0.73f); + if (hRnd > 0.66f) hatch = hRnd; + + return hatch; + } + + /// + public void Execute() + { + Int2 coordinate = new(ThreadIds.X, DispatchSize.Y - ThreadIds.Y); + float iRes = Hlsl.Min(DispatchSize.Y, 800.0f); + Float2 uv = (coordinate - (Float2)DispatchSize.XY * 0.5f) / iRes; + Float3 rd = Hlsl.Normalize(new Float3(uv, 0.5f)); + const float gSc = 10.0f; + Float2 p = uv * gSc + new Float2(0, time / 2.0f); + Float2 oP = p; + float m = BMap(p); + Float3 n = new(0, 0, -1); + float + edge = 0.0f, + bumpFactor = 0.25f; + + n = DoBumpMap(p, n, bumpFactor, ref edge); + + Float3 lp = new Float3(-0.0f + Hlsl.Sin(time) * 0.3f, 0.0f + Hlsl.Cos(time * 1.3f) * 0.3f, -1) - new Float3(uv, 0); + float lDist = Hlsl.Max(Hlsl.Length(lp), 0.001f); + Float3 ld = lp / lDist; + float diff = Hlsl.Max(Hlsl.Dot(n, ld), 0.0f); + + diff = Hlsl.Pow(diff, 4.0f); + + float spec = Hlsl.Pow(Hlsl.Max(Hlsl.Dot(Hlsl.Reflect(-ld, n), -rd), 0.0f), 16.0f); + float fre = Hlsl.Min(Hlsl.Pow(Hlsl.Max(1.0f + Hlsl.Dot(n, rd), 0.0f), 4.0f), 3.0f); + Float3 col = 0.15f * (diff + 0.251f + spec * new Float3(1, 0.7f, 0.3f) * 9.0f + fre * new Float3(0.1f, 0.3f, 1) * 12.0f); + float rf = Hlsl.SmoothStep(0.0f, 0.35f, BMap(Hlsl.Reflect(rd, n).XY * 2.0f) * FBM(Hlsl.Reflect(rd, n).XY * 3.0f) + 0.1f); + + col += col * col * rf * rf * new Float3(1, 0.1f, 0.1f) * 15.0f; + + float shade = m * 0.83f + 0.17f; + + col *= shade; + col *= 1.0f - edge * 0.8f; + + float hatch = DoHatch(oP / gSc, iRes); + + col *= hatch * 0.5f + 0.7f; + + Float4 color = new(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1); + + texture[ThreadIds.XY] = color; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs b/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs new file mode 100644 index 00000000..c7f90b44 --- /dev/null +++ b/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs @@ -0,0 +1,286 @@ +namespace ComputeSharp.SwapChain.Shaders.Compute +{ + /// + /// Utilizing a 2D simplex grid to construct the isolines of a noise function. + /// Ported from . + /// Created by Shane. + /// + [AutoConstructor] + internal readonly partial struct TriangleGridContouring : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time Hlsl.Since the start of the application. + /// + public readonly float time; + + // Standard 2D rotation formula. + private static Float2x2 Rotate2x2(in float a) + { + float c = Hlsl.Cos(a), s = Hlsl.Sin(a); + + return new(c, -s, s, c); + } + + // IQ's Float2 to float hash. + private static float Hash21(Float2 p) + { + return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new Float2(27.619f, 57.583f))) * 43758.5453f); + } + + // Float2 to Float2 hash. + private Float2 Hash22(Float2 p) + { + float n = Hlsl.Sin(Hlsl.Dot(p, new Float2(41, 289))); + + p = Hlsl.Frac(new Float2(262144, 32768) * n); + + return Hlsl.Sin(p * 6.2831853f + time); + } + + // Based on IQ's gradient noise formula. + private float N2D3G(Float2 p) + { + Float2 i = Hlsl.Floor(p); + + p -= i; + + Float4 v = default; + + v.X = Hlsl.Dot(Hash22(i), p); + v.Y = Hlsl.Dot(Hash22(i + Float2.UnitX), p - Float2.UnitX); + v.Z = Hlsl.Dot(Hash22(i + Float2.UnitY), p - Float2.UnitY); + v.W = Hlsl.Dot(Hash22(i + 1.0f), p - 1.0f); + + p = p * p * p * (p * (p * 6.0f - 15.0f) + 10.0f); + + return Hlsl.Lerp(Hlsl.Lerp(v.X, v.Y, p.X), Hlsl.Lerp(v.Z, v.W, p.X), p.Y); + } + + + // The isofunction. Just a Hlsl.Single noise function, but it can be more elaborate. + private float IsoFunction(in Float2 p) + { + return N2D3G(p / 4.0f + 0.07f); + } + + // Unsigned distance to the segment joining "a" and "b". + private static float DistLine(Float2 a, Float2 b) + { + b = a - b; + + float h = Hlsl.Clamp(Hlsl.Dot(a, b) / Hlsl.Dot(b, b), 0.0f, 1.0f); + + return Hlsl.Length(a - b * h); + } + + // Based on IQ's signed distance to the segment joining "a" and "b". + private static float distEdge(Float2 a, Float2 b) + { + return Hlsl.Dot((a + b) * 0.5f, Hlsl.Normalize((b - a).YX * new Float2(-1, 1))); + } + + // Interpolating along the edge connecting vertices v1 and v2 with respect to the isovalue. + private static Float2 Interpolate(in Float2 p1, in Float2 p2, float v1, float v2, float isovalue) + { + return Hlsl.Lerp(p1, p2, (isovalue - v1) / (v2 - v1) * 0.75f + 0.25f / 2.0f); + } + + // Isoline function. + private static int IsoLine( + Float3 n3, + Float2 ip0, + Float2 ip1, + Float2 ip2, + float isovalue, + float i, + ref Float2 p0, + ref Float2 p1) + { + p0 = 1e5f; + p1 = 1e5f; + + int iTh = 0; + + if (n3.X > isovalue) iTh += 4; + if (n3.Y > isovalue) iTh += 2; + if (n3.Z > isovalue) iTh += 1; + + if (iTh == 1 || iTh == 6) + { + p0 = Interpolate(ip1, ip2, n3.Y, n3.Z, isovalue); + p1 = Interpolate(ip2, ip0, n3.Z, n3.X, isovalue); + + } + else if (iTh == 2 || iTh == 5) + { + p0 = Interpolate(ip0, ip1, n3.X, n3.Y, isovalue); + p1 = Interpolate(ip1, ip2, n3.Y, n3.Z, isovalue); + + } + else if (iTh == 3 || iTh == 4) + { + p0 = Interpolate(ip0, ip1, n3.X, n3.Y, isovalue); + p1 = Interpolate(ip2, ip0, n3.Z, n3.X, isovalue); + } + + if (iTh >= 4 && iTh <= 6) + { + Float2 tmp = p0; + + p0 = p1; + p1 = tmp; + } + + if (i == 0.0f) + { + Float2 tmp = p0; + + p0 = p1; + p1 = tmp; + } + + return iTh; + } + + private Float3 SimplexContour(Float2 p) + { + const float gSc = 8.0f; + + p *= gSc; + + Float2 oP = p; + + p += new Float2(N2D3G(p * 3.5f), N2D3G(p * 3.5f + 7.3f)) * 0.015f; + + Float2 s = Hlsl.Floor(p + (p.X + p.Y) * 0.36602540378f); + + p -= s - (s.X + s.Y) * 0.211324865f; + + float i = p.X < p.Y ? 1.0f : 0.0f; + Float2 + ioffs = new(1.0f - i, i), + ip0 = 0, + ip1 = ioffs - 0.2113248654f, + ip2 = 0.577350269f, + ctr = (ip0 + ip1 + ip2) / 3.0f; + + ip0 -= ctr; + ip1 -= ctr; + ip2 -= ctr; + p -= ctr; + + Float3 n3 = default; + + n3.X = IsoFunction(s); + n3.Y = IsoFunction(s + ioffs); + n3.Z = IsoFunction(s + 1.0f); + + float + d = 1e5f, + d2 = 1e5f, + d3 = 1e5f, + d4 = 1e5f, + d5 = 1e5f; + + float isovalue = 0; + Float2 p0 = default, p1 = default; + int iTh = IsoLine(n3, ip0, ip1, ip2, isovalue, i, ref p0, ref p1); + + d = Hlsl.Min(d, distEdge(p - p0, p - p1)); + + if (iTh == 7) + { + d = 0; + } + + d3 = Hlsl.Min(d3, DistLine((p - p0), (p - p1))); + d4 = Hlsl.Min(d4, Hlsl.Min(Hlsl.Length(p - p0), Hlsl.Length(p - p1))); + + float tri = Hlsl.Min(Hlsl.Min(DistLine(p - ip0, p - ip1), DistLine(p - ip1, p - ip2)), DistLine(p - ip2, p - ip0)); + + d5 = Hlsl.Min(d5, tri); + d5 = Hlsl.Min(d5, Hlsl.Length(p) - 0.02f); + isovalue = -0.15f; + + int iTh2 = IsoLine(n3, ip0, ip1, ip2, isovalue, i, ref p0, ref p1); + + d2 = Hlsl.Min(d2, distEdge(p - p0, p - p1)); + + float oldD2 = d2; + + if (iTh2 == 7) d2 = 0.0f; + if (iTh == 7) d2 = 1e5f; + + d2 = Hlsl.Max(d2, -d); + d3 = Hlsl.Min(d3, DistLine((p - p0), (p - p1))); + d4 = Hlsl.Min(d4, Hlsl.Min(Hlsl.Length(p - p0), Hlsl.Length(p - p1))); + d4 -= 0.075f; + d3 -= 0.0125f; + d /= gSc; + d2 /= gSc; + d3 /= gSc; + d4 /= gSc; + d5 /= gSc; + + Float3 col = new(1, 0.85f, 0.6f); + float sf = 0.004f; + + if (d > 0.0f && d2 > 0.0f) col = new Float3(1, 1.8f, 3) * 0.45f; + if (d > 0.0f) col = Hlsl.Lerp(col, new Float3(1, 1.85f, 3) * 0.3f, (1.0f - Hlsl.SmoothStep(0.0f, sf, d2 - 0.012f))); + + col = Hlsl.Lerp(col, new Float3(1.1f, 0.85f, 0.6f), (1.0f - Hlsl.SmoothStep(0.0f, sf, d2))); + col = Hlsl.Lerp(col, new Float3(1.5f, 0.9f, 0.6f) * 0.6f, (1.0f - Hlsl.SmoothStep(0.0f, sf, d - 0.012f))); + col = Hlsl.Lerp(col, new Float3(1, 0.8f, 0.6f) * new Float3(0.7f, 1.0f, 0.75f) * 0.95f, (1.0f - Hlsl.SmoothStep(0.0f, sf, d))); + + if (d2 > 0.0f) col *= (Hlsl.Abs(Hlsl.Dot(n3, Float3.One)) * 1.25f + 1.25f) / 2.0f; + else col *= Hlsl.Max(2.0f - (Hlsl.Dot(n3, Float3.One) + 1.45f) / 1.25f, 0.0f); + + float pat = Hlsl.Abs(Hlsl.Frac(tri * 12.5f + 0.4f) - 0.5f) * 2.0f; + + col *= pat * 0.425f + 0.75f; + col = Hlsl.Lerp(col, Float3.Zero, (1.0f - Hlsl.SmoothStep(0.0f, sf, d5)) * 0.95f); + col = Hlsl.Lerp(col, Float3.Zero, (1.0f - Hlsl.SmoothStep(0.0f, sf, d3))); + col = Hlsl.Lerp(col, Float3.Zero, (1.0f - Hlsl.SmoothStep(0.0f, sf, d4))); + col = Hlsl.Lerp(col, Float3.One, (1.0f - Hlsl.SmoothStep(0.0f, sf, d4 + 0.005f))); + + Float2 q = oP * 1.5f; + + col = Hlsl.Min(col, 1.0f); + + float gr = Hlsl.Sqrt(Hlsl.Dot(col, new Float3(0.299f, 0.587f, 0.114f))) * 1.25f; + float ns = (N2D3G(q * 4.0f * new Float2(1.0f / 3.0f, 3)) * 0.64f + N2D3G(q * 8.0f * new Float2(1.0f / 3.0f, 3)) * 0.34f) * 0.5f + 0.5f; + + ns = gr - ns; + q = Hlsl.Mul(q, Rotate2x2(3.14159f / 3.0f)); + + float ns2 = (N2D3G(q * 4.0f * new Float2(1.0f / 3.0f, 3)) * 0.64f + N2D3G(q * 8.0f * new Float2(1.0f / 3.0f, 3)) * 0.34f) * 0.5f + 0.5f; + + ns2 = gr - ns2; + ns = Hlsl.SmoothStep(0.0f, 1.0f, Hlsl.Min(ns, ns2)); + col = Hlsl.Lerp(col, col * (ns + 0.35f), 0.4f); + + return col; + } + + /// + public void Execute() + { + Int2 coordinate = new(ThreadIds.X, DispatchSize.Y - ThreadIds.Y); + Float2 uv = (coordinate - (Float2)DispatchSize.XY * 0.5f) / Hlsl.Min(650.0f, DispatchSize.Y); + Float2 p = Hlsl.Mul(Rotate2x2(3.14159f / 12.0f), uv) + new Float2(0.8660254f, 0.5f) * time / 16.0f; + Float3 col = SimplexContour(p); + + uv = coordinate / (Float2)DispatchSize.XY; + col *= Hlsl.Pow(16.0f * uv.X * uv.Y * (1.0f - uv.X) * (1.0f - uv.Y), 0.0625f) + 0.1f; + + Float4 color = new(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1); + + texture[ThreadIds.XY] = color; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs b/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs new file mode 100644 index 00000000..2edc0590 --- /dev/null +++ b/tests/ComputeSharp.Tests/Shaders/Compute/TwoTiledTruchet.cs @@ -0,0 +1,149 @@ +namespace ComputeSharp.SwapChain.Shaders.Compute +{ + /// + /// A shader creating an animated two-tiles Truchet arrangement. + /// Ported from . + /// Created by Shane. + /// + [AutoConstructor] + internal readonly partial struct TwoTiledTruchet : IComputeShader + { + /// + /// The target texture. + /// + public readonly IReadWriteTexture2D texture; + + /// + /// The current time since the start of the application. + /// + public readonly float time; + + /// + /// Calculates the Truchet distance field. + /// + /// The input value to compute the distance field for. + /// The resulting Truchet angle. + /// The distance field for the input value. + private Float2 DistanceField(Float2 p, out Float2 ang) + { + // Fast hash for a pair of floats + static float Hash21(Float2 p) + { + return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new Float2(27.619f, 57.583f))) * 43758.5453f); + } + + // HLSL's port of the GLSL mod intrinsic + static float Mod(float x, float y) + { + return x - y * Hlsl.Floor(x / y); + } + + Float2 ip2 = Hlsl.Floor(p / 2.0f); + Float2 ip = Hlsl.Floor(p); + float rnd = Hash21(ip); + float rnd3 = Hash21(ip + 0.57f); + Float2 d = 1e5f; + + p -= ip + 0.5f; + + if (Mod(ip2.X + ip2.Y, 2.0f) < 0.5f) + { + d = Hlsl.Abs(p); + ang = p.YX; + + if (Mod(ip.X + 1.0f, 2.0f) < 0.5f) + { + ang.X *= -1.0f; + + } + + if (Mod(ip.Y + 1.0f, 2.0f) > 0.5f) + { + ang.Y *= -1.0f; + } + + if (rnd3 < .5) + { + d = d.YX; + ang = ang.YX; + } + + ang += 0.5f; + ang *= 3.0f; + + } + else + { + if (rnd < .5) + { + p = p.YX * new Float2(1, -1); + } + + d.X = Hlsl.Length(p - 0.5f) - 0.5f; + d.Y = Hlsl.Length(p + 0.5f) - 0.5f; + + d = Hlsl.Abs(d); + + ang = 0; + ang.X = -Hlsl.Atan((p.Y - 0.5f) / (p.X - 0.5f)); + ang.Y = -Hlsl.Atan((p.Y + 0.5f) / (p.X + 0.5f)); + + if (Mod(ip.X + ip.Y, 2.0f) < 0.5f) + { + ang *= -1.0f; + } + + if (rnd < 0.5f) + { + ang *= -1.0f; + } + + if (rnd3 < 0.5f) + { + d = d.YX; + ang = ang.YX; + } + + ang *= 4.0f / 6.2831853f; + ang *= 2.0f; + } + + ang = Hlsl.Frac(ang + time / 4.0f); + + return d; + } + + /// + public void Execute() + { + Float2 uv = (ThreadIds.XY - (Float2)DispatchSize.XY * 0.5f) / DispatchSize.Y; + float gSc = 7.0f; + Float2 p = uv * gSc - new Float2(-1, -0.5f) * time / 2.0f; + float sf = 2.0f / DispatchSize.Y * gSc; + float lSc = 6.0f; + float lw = 1.0f / lSc / gSc; + Float2 d = DistanceField(p, out Float2 ang) - 2.5f / lSc; + Float3 col = new(1.0f, 0.9f, 0.8f); + + for (int i = 0; i < 2; i++) + { + float di = d[i] - lw / 4.0f; + float tracks = Hlsl.Clamp(Hlsl.Sin(ang[i] * 6.2831f + time * 6.0f) * 4.0f, 0.0f, 1.0f); + float gap = 1.0f + lw; + + col = Hlsl.Lerp(col, 0, (1.0f - Hlsl.SmoothStep(0.0f, sf * 6.0f, di)) * 0.35f); + col = Hlsl.Lerp(col, 0, 1.0f - Hlsl.SmoothStep(0.0f, sf, di)); + col = Hlsl.Lerp(col, new(1.0f, 0.9f, 0.8f), 1.0f - Hlsl.SmoothStep(0.0f, sf, di + lw * 2.0f)); + col = Hlsl.Lerp(col, 0, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + gap / lSc)); + col = Hlsl.Lerp(col, 1, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + gap / lSc + lw)); + col = Hlsl.Lerp(col, 0, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + 2.0f * gap / lSc)); + col = Hlsl.Lerp(col, 1 * tracks, 1.0f - Hlsl.SmoothStep(0.0f, sf, di + 2.0f * gap / lSc + lw)); + } + + Float3 rgb = Hlsl.Sqrt(Hlsl.Max(col, 0.0f)); + Float4 color = new(rgb.X, rgb.Y, rgb.Z, 1.0f); + + texture[ThreadIds.XY] = color; + } + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/ShadersTests.cs b/tests/ComputeSharp.Tests/ShadersTests.cs index 929363c8..075e7ffa 100644 --- a/tests/ComputeSharp.Tests/ShadersTests.cs +++ b/tests/ComputeSharp.Tests/ShadersTests.cs @@ -18,65 +18,101 @@ namespace ComputeSharp.Tests { [CombinatorialTestMethod] [AllDevices] - public void ColorfulInfinity(Device device) + [Data(typeof(ColorfulInfinity))] + [Data(typeof(SwapChain.Shaders.Compute.ColorfulInfinity))] + public void ColorfulInfinity(Device device, Type shaderType) { - RunAndCompareShader(device, static texture => new ColorfulInfinity(texture, 0), 0.0000004f); + RunAndCompareShader(device, shaderType, 0.0000004f); } [CombinatorialTestMethod] [AllDevices] - public void FractalTiling(Device device) + [Data(typeof(FractalTiling))] + [Data(typeof(SwapChain.Shaders.Compute.FractalTiling))] + public void FractalTiling(Device device, Type shaderType) { - RunAndCompareShader(device, static texture => new FractalTiling(texture, 0), 0.0000005f); + RunAndCompareShader(device, shaderType, 0.0000005f); } [CombinatorialTestMethod] [AllDevices] - public void MengerJourney(Device device) + [Data(typeof(MengerJourney))] + [Data(typeof(SwapChain.Shaders.Compute.MengerJourney))] + public void MengerJourney(Device device, Type shaderType) { - RunAndCompareShader(device, static texture => new MengerJourney(texture, 0), 0.000011f); + RunAndCompareShader(device, shaderType, 0.000011f); } [CombinatorialTestMethod] [AllDevices] - public void TwoTiledTruchet(Device device) + [Data(typeof(TwoTiledTruchet))] + [Data(typeof(SwapChain.Shaders.Compute.TwoTiledTruchet))] + public void TwoTiledTruchet(Device device, Type shaderType) { - RunAndCompareShader(device, static texture => new TwoTiledTruchet(texture, 0), 0.00032f); + RunAndCompareShader(device, shaderType, 0.00032f); } [CombinatorialTestMethod] [AllDevices] - public void Octagrams(Device device) + [Data(typeof(Octagrams))] + [Data(typeof(SwapChain.Shaders.Compute.Octagrams))] + public void Octagrams(Device device, Type shaderType) { - RunAndCompareShader(device, static texture => new Octagrams(texture, 0), 0.0000006f); + RunAndCompareShader(device, shaderType, 0.0000006f); } [CombinatorialTestMethod] [AllDevices] - public void ProteanClouds(Device device) + [Data(typeof(ProteanClouds))] + [Data(typeof(SwapChain.Shaders.Compute.ProteanClouds))] + public void ProteanClouds(Device device, Type shaderType) { - RunAndCompareShader(device, static texture => new ProteanClouds(texture, 0), 0.0000004f); + RunAndCompareShader(device, shaderType, 0.0000004f); } [CombinatorialTestMethod] [AllDevices] - public void ExtrudedTruchetPattern(Device device) + [Data(typeof(ExtrudedTruchetPattern))] + [Data(typeof(SwapChain.Shaders.Compute.ExtrudedTruchetPattern))] + public void ExtrudedTruchetPattern(Device device, Type shaderType) { - RunAndCompareShader(device, static texture => new ExtrudedTruchetPattern(texture, 0), 0.00011f); + RunAndCompareShader(device, shaderType, 0.00011f); } [CombinatorialTestMethod] [AllDevices] - public void PyramidPattern(Device device) + [Data(typeof(PyramidPattern))] + [Data(typeof(SwapChain.Shaders.Compute.PyramidPattern))] + public void PyramidPattern(Device device, Type shaderType) { - RunAndCompareShader(device, static texture => new PyramidPattern(texture, 0), 0.00021f); + RunAndCompareShader(device, shaderType, 0.00021f); } [CombinatorialTestMethod] [AllDevices] - public void TriangleGridContouring(Device device) + [Data(typeof(TriangleGridContouring))] + [Data(typeof(SwapChain.Shaders.Compute.TriangleGridContouring))] + public void TriangleGridContouring(Device device, Type shaderType) { - RunAndCompareShader(device, static texture => new TriangleGridContouring(texture, 0), 0.0006f); + RunAndCompareShader(device, shaderType, 0.0006f); + } + + [CombinatorialTestMethod] + [AllDevices] + [Data(typeof(ContouredLayers))] + [Data(typeof(SwapChain.Shaders.Compute.ContouredLayers))] + public void ContouredLayers(Device device, Type shaderType) + { + string filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Shaders", "Textures", "RustyMetal.png"); + + using ReadOnlyTexture2D background = device.Get().LoadTexture(filename); + + RunAndCompareShader( + device, + shaderType, + texture => new SwapChain.Shaders.Compute.ContouredLayers(texture, 0, background), + texture => new ContouredLayers(0, background), + 0.0007f); } /// @@ -84,14 +120,13 @@ namespace ComputeSharp.Tests /// /// The type of shader to test. /// The device to use. - /// A producer to create an instance of the shader to run. + /// The type of shader being executed. /// The comparison delta. - private static void RunAndCompareShader(Device device, Func, T> factory, float delta) - where T : struct, IComputeShader + private static void RunAndCompareShader(Device device, Type shaderType, float delta) { _ = device.Get(); - string expectedPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets", $"{typeof(T).Name}.png"); + string expectedPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets", $"{shaderType.Name}.png"); IImageInfo imageInfo = Image.Identify(expectedPath); @@ -99,14 +134,92 @@ namespace ComputeSharp.Tests using (ReadWriteTexture2D texture = device.Get().AllocateReadWriteTexture2D(imageInfo.Width, imageInfo.Height)) { - device.Get().For(texture.Width, texture.Height, factory(texture)); + if (shaderType.IsAssignableTo(typeof(IComputeShader))) + { + static void RunComputeShader(ReadWriteTexture2D texture) + where T : struct, IComputeShader + { + texture.GraphicsDevice.For(texture.Width, texture.Height, (T)Activator.CreateInstance(typeof(T), texture, 0f)!); + } + + var action = new Action>(RunComputeShader); + + action.Method.GetGenericMethodDefinition().MakeGenericMethod(shaderType).Invoke(null, new[] { texture }); + } + else + { + static void RunPixelShader(ReadWriteTexture2D texture) + where T : struct, IPixelShader + { + texture.GraphicsDevice.ForEach(texture, (T)Activator.CreateInstance(typeof(T), 0f)!); + } + + var action = new Action>(RunPixelShader); + + action.Method.GetGenericMethodDefinition().MakeGenericMethod(shaderType).Invoke(null, new[] { texture }); + } _ = image.TryGetSinglePixelSpan(out Span span); texture.CopyTo(MemoryMarshal.Cast(span)); } - string actualPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Shaders", $"{typeof(T).Name}.png"); + string actualPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Shaders", $"{shaderType.Name}.png"); + + _ = Directory.CreateDirectory(Path.GetDirectoryName(actualPath)!); + + image.SaveAsPng(actualPath, new PngEncoder() { CompressionLevel = PngCompressionLevel.BestCompression, ColorType = PngColorType.Rgb }); + + ImagingTests.TolerantImageComparer.AssertEqual(expectedPath, actualPath, delta); + } + + /// + /// Executes a given test for a specified shader. + /// + /// The type of shader to test. + /// The device to use. + /// The type of shader being executed. + /// The factory of compute shaders. + /// The factory of pixel shaders. + /// The comparison delta. + private static void RunAndCompareShader( + Device device, + Type shaderType, + Func, TCompute> computeFactory, + Func, TPixel> pixelFactory, + float delta) + where TCompute : struct, IComputeShader + where TPixel : struct, IPixelShader + { + _ = device.Get(); + + string expectedPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets", $"{shaderType.Name}.png"); + + IImageInfo imageInfo = Image.Identify(expectedPath); + + using Image image = new(imageInfo.Width, imageInfo.Height); + + using (ReadWriteTexture2D texture = device.Get().AllocateReadWriteTexture2D(imageInfo.Width, imageInfo.Height)) + { + if (shaderType.IsAssignableTo(typeof(IComputeShader))) + { + Assert.AreEqual(typeof(TCompute), shaderType); + + texture.GraphicsDevice.For(texture.Width, texture.Height, computeFactory(texture)); + } + else + { + Assert.AreEqual(typeof(TPixel), shaderType); + + texture.GraphicsDevice.ForEach(texture, pixelFactory(texture)); + } + + _ = image.TryGetSinglePixelSpan(out Span span); + + texture.CopyTo(MemoryMarshal.Cast(span)); + } + + string actualPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Shaders", $"{shaderType.Name}.png"); _ = Directory.CreateDirectory(Path.GetDirectoryName(actualPath)!); diff --git a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs index 5eaf8df4..294dd521 100644 --- a/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs +++ b/tests/ComputeSharp.Tests/Texture2DTests.Pixels.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Numerics; using System.Reflection; using ComputeSharp.__Internals; @@ -6,6 +7,8 @@ using ComputeSharp.Resources; using ComputeSharp.Tests.Attributes; using ComputeSharp.Tests.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using SixLabors.ImageSharp; +using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32; #pragma warning disable CS0618 @@ -61,5 +64,70 @@ namespace ComputeSharp.Tests throw e.InnerException; } } + + [CombinatorialTestMethod] + [AllDevices] + public void SampleFromSourceTexture_ComputeShader(Device device) + { + _ = device.Get(); + + string imagingPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); + + using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png")); + + using ReadOnlyTexture2D source = device.Get().LoadTexture(Path.Combine(imagingPath, "city.jpg")); + using ReadWriteTexture2D destination = device.Get().AllocateReadWriteTexture2D(sampled.Width, sampled.Height); + + device.Get().For(sampled.Width, sampled.Height, new SamplingComputeShader(source, destination)); + + using var processed = destination.ToImage(); + + ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.00000086f); + } + + [AutoConstructor] + public readonly partial struct SamplingComputeShader : IComputeShader + { + public readonly IReadOnlyTexture2D source; + public readonly IReadWriteTexture2D destination; + + public void Execute() + { + destination[ThreadIds.XY] = source[ThreadIds.Normalized.XY]; + } + } + + [CombinatorialTestMethod] + [AllDevices] + public void SampleFromSourceTexture_PixelShader(Device device) + { + _ = device.Get(); + + string imagingPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging"); + string assetsPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets"); + + using var sampled = Image.Load(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png")); + + using ReadOnlyTexture2D source = device.Get().LoadTexture(Path.Combine(imagingPath, "city.jpg")); + using ReadWriteTexture2D destination = device.Get().AllocateReadWriteTexture2D(sampled.Width, sampled.Height); + + device.Get().ForEach(destination, new SamplingPixelShader(source)); + + using var processed = destination.ToImage(); + + ImagingTests.TolerantImageComparer.AssertEqual(sampled, processed, 0.00000086f); + } + + [AutoConstructor] + public readonly partial struct SamplingPixelShader : IPixelShader + { + public readonly IReadOnlyTexture2D texture; + + public Float4 Execute() + { + return texture[ThreadIds.Normalized.XY]; + } + } } }