Merge pull request #122 from Sergio0694/feature/texture-sampled-indexers
Pixel shaders, texture sampling
このコミットが含まれているのは:
67ファイル変更
+3092
-253
検索条件に一致するファイルはありません
@@ -6,12 +6,12 @@ using FX = TerraFX.Interop.Windows;
|
||||
namespace ComputeSharp.SwapChain.Backend
|
||||
{
|
||||
internal sealed class SwapChainApplication<T> : Win32Application
|
||||
where T : struct, IComputeShader
|
||||
where T : struct, IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="Func{T1, T2, TResult}"/> instance used to create shaders to run.
|
||||
/// The <see cref="Func{T1, TResult}"/> instance used to create shaders to run.
|
||||
/// </summary>
|
||||
private readonly Func<IReadWriteTexture2D<Float4>, TimeSpan, T> shaderFactory;
|
||||
private readonly Func<TimeSpan, T> shaderFactory;
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="ID3D12Device"/> pointer for the device currently in use.
|
||||
@@ -76,8 +76,8 @@ namespace ComputeSharp.SwapChain.Backend
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="SwapChainApplication"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="shaderFactory">The <see cref="Func{T1, T2, TResult}"/> instance used to create shaders to run.</param>
|
||||
public SwapChainApplication(Func<IReadWriteTexture2D<Float4>, TimeSpan, T> shaderFactory)
|
||||
/// <param name="shaderFactory">The <see cref="Func{T1, TResult}"/> instance used to create shaders to run.</param>
|
||||
public SwapChainApplication(Func<TimeSpan, T> 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<ID3D12Resource> d3D12Resource = default;
|
||||
|
||||
// Get the underlying ID3D12Resource pointer for the texture
|
||||
_ = InteropServices.TryGetID3D12Resource(this.texture, FX.__uuidof<ID3D12Resource>(), (void**)d3D12Resource.GetAddressOf());
|
||||
_ = InteropServices.TryGetID3D12Resource(this.texture!, FX.__uuidof<ID3D12Resource>(), (void**)d3D12Resource.GetAddressOf());
|
||||
|
||||
// Get the target back buffer to update
|
||||
ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ComputeSharp\ComputeSharp.csproj" />
|
||||
<ProjectReference Include="..\..\src\ComputeSharp.SourceGenerators\ComputeSharp.SourceGenerators.csproj"
|
||||
@@ -13,4 +17,10 @@
|
||||
PrivateAssets="contentfiles;build" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="Textures\RustyMetal.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// A texture for <c>\Textures\RustyMetal.png</c>.
|
||||
/// </summary>
|
||||
private static readonly IReadOnlyTexture2D<Float4> RustyMetal = LoadTexture();
|
||||
|
||||
/// <summary>
|
||||
/// The mapping of available samples to choose from.
|
||||
/// </summary>
|
||||
private static readonly Win32Application[] Samples = new Win32Application[]
|
||||
{
|
||||
new SwapChainApplication<ColorfulInfinity>(static (texture, time) => new(texture, (float)time.TotalSeconds)),
|
||||
new SwapChainApplication<FractalTiling>(static (texture, time) => new(texture, (float)time.TotalSeconds)),
|
||||
new SwapChainApplication<TwoTiledTruchet>(static (texture, time) => new(texture, (float)time.TotalSeconds)),
|
||||
new SwapChainApplication<MengerJourney>(static (texture, time) => new(texture, (float)time.TotalSeconds)),
|
||||
new SwapChainApplication<Octagrams>(static (texture, time) => new(texture, (float)time.TotalSeconds)),
|
||||
new SwapChainApplication<ProteanClouds>(static (texture, time) => new(texture, (float)time.TotalSeconds)),
|
||||
new SwapChainApplication<ExtrudedTruchetPattern>(static (texture, time) => new(texture, (float)time.TotalSeconds)),
|
||||
new SwapChainApplication<PyramidPattern>(static (texture, time) => new(texture, (float)time.TotalSeconds)),
|
||||
new SwapChainApplication<TriangleGridContouring>(static (texture, time) => new(texture, (float)time.TotalSeconds))
|
||||
new SwapChainApplication<ColorfulInfinity>(static time => new((float)time.TotalSeconds)),
|
||||
new SwapChainApplication<FractalTiling>(static time => new((float)time.TotalSeconds)),
|
||||
new SwapChainApplication<TwoTiledTruchet>(static time => new((float)time.TotalSeconds)),
|
||||
new SwapChainApplication<MengerJourney>(static time => new((float)time.TotalSeconds)),
|
||||
new SwapChainApplication<Octagrams>(static time => new((float)time.TotalSeconds)),
|
||||
new SwapChainApplication<ProteanClouds>(static time => new((float)time.TotalSeconds)),
|
||||
new SwapChainApplication<ExtrudedTruchetPattern>(static time => new((float)time.TotalSeconds)),
|
||||
new SwapChainApplication<PyramidPattern>(static time => new((float)time.TotalSeconds)),
|
||||
new SwapChainApplication<TriangleGridContouring>(static time => new((float)time.TotalSeconds)),
|
||||
new SwapChainApplication<ContouredLayers>(static time => new((float)time.TotalSeconds, RustyMetal))
|
||||
};
|
||||
|
||||
static void Main()
|
||||
@@ -47,5 +60,26 @@ namespace ComputeSharp.SwapChain
|
||||
|
||||
Win32ApplicationRunner.Run(Samples[index]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allocates a new <see cref="ReadOnlyTexture2D{T, TPixel}"/> instance with the specified texture data.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the texture to load.</param>
|
||||
/// <returns>A texture with the data from the image at the specified name.</returns>
|
||||
[Pure]
|
||||
private static ReadOnlyTexture2D<Rgba32, Float4> LoadTexture([CallerMemberName] string name = null!)
|
||||
{
|
||||
string filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Textures", $"{name}.png");
|
||||
|
||||
using Image<ImageSharpRgba32> image = Image.Load<ImageSharpRgba32>(filename);
|
||||
|
||||
ReadOnlyTexture2D<Rgba32, Float4> texture = Gpu.Default.AllocateReadOnlyTexture2D<Rgba32, Float4>(image.Width, image.Height);
|
||||
|
||||
image.TryGetSinglePixelSpan(out Span<ImageSharpRgba32> span);
|
||||
|
||||
texture.CopyFrom(MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(span));
|
||||
|
||||
return texture;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,8 @@
|
||||
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ColorfulInfinity : IComputeShader
|
||||
internal readonly partial struct ColorfulInfinity : IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
@@ -49,7 +44,7 @@
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders
|
||||
{
|
||||
/// <summary>
|
||||
/// Constructing some concise contoured layers, then applying various edge and shading effects to produce some faux depth.
|
||||
/// Ported from <see href="https://www.shadertoy.com/view/3lj3zt"/>.
|
||||
/// <para>Created by Shane.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ContouredLayers : IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The current time Hlsl.Since the start of the application.
|
||||
/// </summary>
|
||||
public readonly float time;
|
||||
|
||||
/// <summary>
|
||||
/// The background texture to sample.
|
||||
/// </summary>
|
||||
public readonly IReadOnlyTexture2D<Float4> 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;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,8 @@
|
||||
/// <para>Created by Shane.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ExtrudedTruchetPattern : IComputeShader
|
||||
internal readonly partial struct ExtrudedTruchetPattern : IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
@@ -180,7 +175,7 @@
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,20 +7,15 @@
|
||||
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct FractalTiling : IComputeShader
|
||||
internal readonly partial struct FractalTiling : IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
public readonly float time;
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,8 @@
|
||||
/// <para>Created by Syntopia.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct MengerJourney : IComputeShader
|
||||
internal readonly partial struct MengerJourney : IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
@@ -153,7 +148,7 @@
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,8 @@
|
||||
/// <para>Created by whisky_shusuky.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct Octagrams : IComputeShader
|
||||
internal readonly partial struct Octagrams : IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
@@ -88,7 +83,7 @@
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,8 @@
|
||||
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ProteanClouds : IComputeShader
|
||||
internal readonly partial struct ProteanClouds : IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time Hlsl.Since the start of the application.
|
||||
/// </summary>
|
||||
@@ -131,7 +126,7 @@
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,8 @@
|
||||
/// <para>Created by Shane.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct PyramidPattern : IComputeShader
|
||||
internal readonly partial struct PyramidPattern : IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time Hlsl.Since the start of the application.
|
||||
/// </summary>
|
||||
@@ -135,7 +130,7 @@
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,8 @@
|
||||
/// <para>Created by Shane.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct TriangleGridContouring : IComputeShader
|
||||
internal readonly partial struct TriangleGridContouring : IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time Hlsl.Since the start of the application.
|
||||
/// </summary>
|
||||
@@ -268,7 +263,7 @@
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,13 +6,8 @@
|
||||
/// <para>Created by Shane.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct TwoTiledTruchet : IComputeShader
|
||||
internal readonly partial struct TwoTiledTruchet : IPixelShader<Float4>
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
@@ -114,7 +109,7 @@
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 1.9 MiB |
@@ -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)
|
||||
@@ -29,6 +29,7 @@
|
||||
<Compile Include="..\ComputeSharp\Core\Extensions\MethodInfoExtensions.cs" Link="Core\Extensions\MethodInfoExtensions.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Helpers\AlignmentHelper.cs" Link="Core\Helpers\AlignmentHelper.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Interfaces\IComputeShader.cs" Link="Core\Interfaces\IComputeShader.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Interfaces\IPixelShader{TPixel}.cs" Link="Core\Interfaces\IPixelShader{TPixel}.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Intrinsics\Attributes\HlslIntrinsicNameAttribute.cs" Link="Core\Intrinsics\Attributes\HlslIntrinsicNameAttribute.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Intrinsics\Hlsl.cs" Link="Core\Intrinsics\Hlsl.cs" />
|
||||
<Compile Include="..\ComputeSharp\Core\Intrinsics\Hlsl.g.cs" Link="Core\Intrinsics\Hlsl.g.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");
|
||||
|
||||
/// <summary>
|
||||
/// Gets a <see cref="DiagnosticDescriptor"/> for a type implementing multiple shader interfaces.
|
||||
/// <para>
|
||||
/// Format: <c>"The shader of type {0} cannot implement more than one shader interface"</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ namespace ComputeSharp.SourceGenerators.Helpers
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="values">The input sequence of <see cref="string"/> instances.</param>
|
||||
/// <returns>An <see cref="ArrayCreationExpression"/> instance with the described contents.</returns>
|
||||
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
|
||||
[Pure]
|
||||
public static ArrayCreationExpressionSyntax ArrayExpression(IEnumerable<string> values)
|
||||
{
|
||||
@@ -44,7 +44,7 @@ namespace ComputeSharp.SourceGenerators.Helpers
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="values">The input sequence of <see cref="string"/> groups.</param>
|
||||
/// <returns>An <see cref="ArrayCreationExpression"/> instance with the described contents.</returns>
|
||||
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
|
||||
[Pure]
|
||||
public static ArrayCreationExpressionSyntax NestedArrayExpression(IEnumerable<IEnumerable<string?>> groups)
|
||||
{
|
||||
@@ -71,7 +71,7 @@ namespace ComputeSharp.SourceGenerators.Helpers
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="values">The input sequence of <see cref="string"/> groups.</param>
|
||||
/// <returns>An <see cref="ArrayCreationExpression"/> instance with the described contents.</returns>
|
||||
/// <returns>An <see cref="ArrayCreationExpressionSyntax"/> instance with the described contents.</returns>
|
||||
[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()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a <see cref="string"/>[]? array expression from the given tuple instance.
|
||||
/// <para>
|
||||
/// That it, it applies the following transformation:
|
||||
/// <code>
|
||||
/// null => null
|
||||
/// ("S1", "S2") => new string[] { "S1", "S2" }
|
||||
/// </code>
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <param name="values">The input tuple instance.</param>
|
||||
/// <returns>An <see cref="ExpressionSyntax"/> instance with the described contents.</returns>
|
||||
[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<ExpressionSyntax>(OmittedArraySizeExpression()))))
|
||||
.WithInitializer(InitializerExpression(SyntaxKind.ArrayInitializerExpression)
|
||||
.AddExpressions(
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.First)),
|
||||
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(values.Value.Second))));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<byte>) }))
|
||||
{
|
||||
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
|
||||
}
|
||||
|
||||
@@ -154,9 +154,11 @@ namespace ComputeSharp.SourceGenerators
|
||||
{
|
||||
List<StatementSyntax> statements = new();
|
||||
|
||||
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
|
||||
var isComputeShader = pixelShaderSymbol is null;
|
||||
int
|
||||
resourceOffset = 0,
|
||||
rawDataOffset = sizeof(int) * 3;
|
||||
rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
|
||||
|
||||
AppendFields(structDeclarationSymbol, Array.Empty<string>(), ref resourceOffset, ref rawDataOffset, statements);
|
||||
|
||||
|
||||
@@ -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<byte>) }))
|
||||
{
|
||||
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
|
||||
}
|
||||
|
||||
@@ -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<byte>) }))
|
||||
{
|
||||
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
|
||||
}
|
||||
|
||||
@@ -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<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
|
||||
Dictionary<IFieldSymbol, string> 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<byte>) }) > 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<byte>) });
|
||||
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
|
||||
/// <param name="context">The current generator context in use.</param>
|
||||
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
|
||||
/// <param name="types">The collection of currently discovered types.</param>
|
||||
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
|
||||
/// <returns>A sequence of captured fields in <paramref name="structDeclarationSymbol"/>.</returns>
|
||||
[Pure]
|
||||
private static IEnumerable<IEnumerable<string>> GetProcessedFields(
|
||||
GeneratorExecutionContext context,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
ICollection<INamedTypeSymbol> types)
|
||||
ICollection<INamedTypeSymbol> 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
|
||||
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
|
||||
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
|
||||
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
|
||||
/// <param name="isComputeShader">Indicates whether or not <paramref name="structDeclarationSymbol"/> represents a compute shader.</param>
|
||||
/// <returns>A sequence of processed methods in <paramref name="structDeclaration"/>, and the entry point.</returns>
|
||||
[Pure]
|
||||
private static (string EntryPoint, IEnumerable<string> Methods, IEnumerable<string> Declarations) GetProcessedMethods(
|
||||
private static (string EntryPoint, IEnumerable<string> Methods, IEnumerable<string> Declarations, bool IsSamplerUser) GetProcessedMethods(
|
||||
GeneratorExecutionContext context,
|
||||
StructDeclarationSyntax structDeclaration,
|
||||
INamedTypeSymbol structDeclarationSymbol,
|
||||
SemanticModelProvider semanticModel,
|
||||
ICollection<INamedTypeSymbol> discoveredTypes,
|
||||
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions)
|
||||
IDictionary<IFieldSymbol, string> constantDefinitions,
|
||||
bool isComputeShader)
|
||||
{
|
||||
// Find all declared methods in the type
|
||||
ImmutableArray<MethodDeclarationSyntax> methodDeclarations = (
|
||||
@@ -323,15 +340,22 @@ namespace ComputeSharp.SourceGenerators
|
||||
string? entryPoint = null;
|
||||
List<string> methods = new();
|
||||
List<string> 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<byte>.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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -33,6 +33,21 @@ namespace ComputeSharp.SourceGenerators.Mappings
|
||||
[$"ComputeSharp.IReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The mapping of supported known samplers to HLSL resource type names.
|
||||
/// </summary>
|
||||
private static readonly IReadOnlyDictionary<string, string?> KnownResourceSamplers = new Dictionary<string, string?>
|
||||
{
|
||||
[$"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
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The mapping of supported known size accessors for HLSL resource types.
|
||||
/// </summary>
|
||||
@@ -389,6 +404,18 @@ namespace ComputeSharp.SourceGenerators.Mappings
|
||||
return KnownResourceIndexers.TryGetValue(name, out mapped);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the mapped HLSL-compatible sampler resource type name for the input indexer name.
|
||||
/// </summary>
|
||||
/// <param name="name">The input fully qualified indexer name.</param>
|
||||
/// <param name="mapped">The mapped type name, if one is found.</param>
|
||||
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader for the given sampler.</returns>
|
||||
[Pure]
|
||||
public static bool TryGetMappedResourceSamplerAccessType(string name, out string? mapped)
|
||||
{
|
||||
return KnownResourceSamplers.TryGetValue(name, out mapped);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get the mapped HLSL-compatible indexer vector type name for the input indexer name.
|
||||
/// </summary>
|
||||
|
||||
@@ -265,6 +265,26 @@ namespace ComputeSharp.SourceGenerators.Mappings
|
||||
return typeName.ToHlslIdentifierName();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapped HLSL-compatible type name for the output texture of a pixel shader.
|
||||
/// </summary>
|
||||
/// <param name="typeSymbol">The pixel shader type to map.</param>
|
||||
/// <returns>The HLSL-compatible type name that can be used in an HLSL shader.</returns>
|
||||
[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<unorm {mappedElementType}>";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapped HLSL-compatible type name for the input element type symbol.
|
||||
/// </summary>
|
||||
|
||||
@@ -8,22 +8,22 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
|
||||
/// <summary>
|
||||
/// A custom <see cref="CSharpSyntaxRewriter"/> type that does postprocessing fixups on the shader main method.
|
||||
/// </summary>
|
||||
internal sealed class ExecuteMethodRewriter : CSharpSyntaxRewriter
|
||||
internal abstract class ExecuteMethodRewriter : CSharpSyntaxRewriter
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="ShaderSourceRewriter"/> instance used to process the input tree.
|
||||
/// </summary>
|
||||
private readonly ShaderSourceRewriter shaderSourceRewriter;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ExecuteMethodRewriter"/> instance with the specified parameters.
|
||||
/// Creates a new <see cref="Compute"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter"/> instance used to process the input tree.</param>
|
||||
public ExecuteMethodRewriter(ShaderSourceRewriter shaderSourceRewriter)
|
||||
{
|
||||
this.shaderSourceRewriter = shaderSourceRewriter;
|
||||
ShaderSourceRewriter = shaderSourceRewriter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the <see cref="ShaderSourceRewriter"/> instance used to process the input tree.
|
||||
/// </summary>
|
||||
protected ShaderSourceRewriter ShaderSourceRewriter { get; }
|
||||
|
||||
/// <inheritdoc cref="CSharpSyntaxRewriter.Visit(SyntaxNode?)"/>
|
||||
public TNode? Visit<TNode>(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;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node)
|
||||
/// <summary>
|
||||
/// A custom <see cref="ExecuteMethodRewriter"/> type specialized for compute shaders.
|
||||
/// </summary>
|
||||
public sealed class Compute : ExecuteMethodRewriter
|
||||
{
|
||||
var updatedNode = ((MethodDeclarationSyntax)base.VisitMethodDeclaration(node)!).WithModifiers(TokenList());
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="Compute"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter"/> instance used to process the input tree.</param>
|
||||
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)
|
||||
// {
|
||||
// <body>
|
||||
// }
|
||||
var rangeCheckExpression =
|
||||
BinaryExpression(SyntaxKind.LogicalAndExpression,
|
||||
/// <inheritdoc/>
|
||||
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)
|
||||
// {
|
||||
// <body>
|
||||
// }
|
||||
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!)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A custom <see cref="ExecuteMethodRewriter"/> type specialized for compute shaders.
|
||||
/// </summary>
|
||||
public sealed class Pixel : ExecuteMethodRewriter
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="Pixel"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="shaderSourceRewriter">The <see cref="ShaderSourceRewriter"/> instance used to process the input tree.</param>
|
||||
public Pixel(ShaderSourceRewriter shaderSourceRewriter)
|
||||
: base(shaderSourceRewriter)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override SyntaxNode? VisitReturnStatement(ReturnStatementSyntax node)
|
||||
{
|
||||
var updatedNode = (ReturnStatementSyntax)base.VisitReturnStatement(node)!;
|
||||
|
||||
// __outputTexture[ThreadIds.xy] = <RETURN_EXPRESSION>;
|
||||
return
|
||||
ExpressionStatement(
|
||||
AssignmentExpression(
|
||||
SyntaxKind.SimpleAssignmentExpression,
|
||||
ElementAccessExpression(IdentifierName("__outputTexture"))
|
||||
.AddArgumentListArguments(
|
||||
Argument(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("ThreadIds"),
|
||||
IdentifierName("xy")))),
|
||||
updatedNode.Expression!));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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!)));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,26 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
|
||||
/// </summary>
|
||||
internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="SemanticModelProvider"/> instance with semantic info on the target syntax tree.
|
||||
/// </summary>
|
||||
protected readonly SemanticModelProvider SemanticModel;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of discovered custom types.
|
||||
/// </summary>
|
||||
protected readonly ICollection<INamedTypeSymbol> DiscoveredTypes;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of discovered constant definitions.
|
||||
/// </summary>
|
||||
protected readonly IDictionary<IFieldSymbol, string> ConstantDefinitions;
|
||||
|
||||
/// <summary>
|
||||
/// The current generator context in use.
|
||||
/// </summary>
|
||||
protected readonly GeneratorExecutionContext Context;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="HlslSourceRewriter"/> instance with the specified parameters.
|
||||
/// </summary>
|
||||
@@ -41,24 +61,9 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <see cref="SemanticModelProvider"/> instance with semantic info on the target syntax tree.
|
||||
/// Gets whether or not the shader uses a texture sampler at least once.
|
||||
/// </summary>
|
||||
protected readonly SemanticModelProvider SemanticModel;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of discovered custom types.
|
||||
/// </summary>
|
||||
protected readonly ICollection<INamedTypeSymbol> DiscoveredTypes;
|
||||
|
||||
/// <summary>
|
||||
/// The collection of discovered constant definitions.
|
||||
/// </summary>
|
||||
protected readonly IDictionary<IFieldSymbol, string> ConstantDefinitions;
|
||||
|
||||
/// <summary>
|
||||
/// The current generator context in use.
|
||||
/// </summary>
|
||||
protected readonly GeneratorExecutionContext Context;
|
||||
public bool IsSamplerUsed { get; private set; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
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))
|
||||
|
||||
@@ -22,6 +22,8 @@ namespace ComputeSharp.__Internals
|
||||
/// </summary>
|
||||
/// <param name="shaderType">The type of the current shader.</param>
|
||||
/// <param name="types">The collection of custom types.</param>
|
||||
/// <param name="implicitTextureField">The implicit texture field info, if present.</param>
|
||||
/// <param name="implicitSamplerFields">The implicit texture sampler field info, if present.</param>
|
||||
/// <param name="fields">The mapped collection of shader fields.</param>
|
||||
/// <param name="forwardDeclarations">The forward declarations for static methods.</param>
|
||||
/// <param name="executeMethod">The source code for the <see cref="IComputeShader.Execute"/> method.</param>
|
||||
@@ -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<string[]>().ToDictionary(static arg => arg[0], static arg => (arg[1], arg[2]));
|
||||
ForwardDeclarations = forwardDeclarations;
|
||||
ExecuteMethod = executeMethod;
|
||||
@@ -61,6 +67,16 @@ namespace ComputeSharp.__Internals
|
||||
/// </summary>
|
||||
internal IReadOnlyCollection<string> Types { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapping for the implicit texture field, if the shader is a pixel shader.
|
||||
/// </summary>
|
||||
internal (string Name, string Type)? ImplicitTextureField { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapping for the implicit sampler field, if necessary.
|
||||
/// </summary>
|
||||
internal (string Name, string Type)? ImplicitSamplerField { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the mapping of field names.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace ComputeSharp
|
||||
{
|
||||
/// <summary>
|
||||
/// An <see langword="interface"/> representing a pixel shader.
|
||||
/// </summary>
|
||||
public interface IPixelShader<TPixel>
|
||||
where TPixel : unmanaged
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes the current pixel shader.
|
||||
/// </summary>
|
||||
/// <returns>The pixel value for the current invocation.</returns>
|
||||
TPixel Execute();
|
||||
}
|
||||
}
|
||||
@@ -1131,5 +1131,34 @@ namespace ComputeSharp
|
||||
{
|
||||
ShaderRunner<T>.Run(device, x, y, z, threadsX, threadsY, threadsZ, in shader);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
|
||||
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
|
||||
/// <param name="texture">The target texture to apply the pixel shader to.</param>
|
||||
public static void ForEach<T, TPixel>(this GraphicsDevice device, IReadWriteTexture2D<TPixel> texture)
|
||||
where T : struct, IPixelShader<TPixel>
|
||||
where TPixel : unmanaged
|
||||
{
|
||||
ShaderRunner<T>.Run(device, texture, default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of pixel shader to run.</typeparam>
|
||||
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
|
||||
/// <param name="texture">The target texture to apply the pixel shader to.</param>
|
||||
/// <param name="shader">The input <typeparamref name="T"/> instance representing the pixel shader to run.</param>
|
||||
public static void ForEach<T, TPixel>(this GraphicsDevice device, IReadWriteTexture2D<TPixel> texture, in T shader)
|
||||
where T : struct, IPixelShader<TPixel>
|
||||
where TPixel : unmanaged
|
||||
{
|
||||
ShaderRunner<T>.Run(device, texture, in shader);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,5 +32,20 @@
|
||||
/// <param name="xy">The coordinates of the value to get.</param>
|
||||
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
|
||||
TPixel this[Int2 xy] { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a single <typeparamref name="TPixel"/> value from the current readonly texture with linear sampling.
|
||||
/// </summary>
|
||||
/// <param name="u">The horizontal normalized offset of the value to get.</param>
|
||||
/// <param name="v">The vertical normalized offset of the value to get.</param>
|
||||
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
|
||||
TPixel this[float u, float v] { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a single <typeparamref name="TPixel"/> value from the current readonly texture with linear sampling.
|
||||
/// </summary>
|
||||
/// <param name="uv">The normalized coordinates of the value to get.</param>
|
||||
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
|
||||
TPixel this[Float2 uv] { get; }
|
||||
}
|
||||
}
|
||||
@@ -38,5 +38,21 @@
|
||||
/// <param name="xyz">The coordinates of the value to get.</param>
|
||||
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
|
||||
TPixel this[Int3 xyz] { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a single <typeparamref name="TPixel"/> value from the current readonly texture with linear sampling.
|
||||
/// </summary>
|
||||
/// <param name="u">The horizontal normalized offset of the value to get.</param>
|
||||
/// <param name="v">The vertical normalized offset of the value to get.</param>
|
||||
/// <param name="w">The depthwise normalized offset of the value to get.</param>
|
||||
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
|
||||
TPixel this[float u, float v, float w] { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a single <typeparamref name="TPixel"/> value from the current readonly texture with linear sampling.
|
||||
/// </summary>
|
||||
/// <param name="uvw">The normalized coordinates of the value to get.</param>
|
||||
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
|
||||
TPixel this[Float3 uvw] { get; }
|
||||
}
|
||||
}
|
||||
@@ -39,10 +39,16 @@ namespace ComputeSharp
|
||||
/// <inheritdoc/>
|
||||
public TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture2D<T,TPixel>)}[{typeof(Int2)}]");
|
||||
|
||||
/// <inheritdoc/>
|
||||
public TPixel this[float u, float v] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture2D<T, TPixel>)}[{typeof(float)}, {typeof(float)}]");
|
||||
|
||||
/// <inheritdoc/>
|
||||
public TPixel this[Float2 uv] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture2D<T, TPixel>)}[{typeof(Float2)}]");
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override string ToString()
|
||||
{
|
||||
return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)},{typeof(TPixel)}>[{Width}, {Height}]";
|
||||
return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)}, {typeof(TPixel)}>[{Width}, {Height}]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,10 +40,16 @@ namespace ComputeSharp
|
||||
/// <inheritdoc/>
|
||||
public TPixel this[Int3 xyz] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture3D<T, TPixel>)}[{typeof(Int3)}]");
|
||||
|
||||
/// <inheritdoc/>
|
||||
public TPixel this[float u, float v, float w] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture3D<T, TPixel>)}[{typeof(float)}, {typeof(float)}, {typeof(float)}]");
|
||||
|
||||
/// <inheritdoc/>
|
||||
public TPixel this[Float3 uvw] => throw new InvalidExecutionContextException($"{typeof(ReadOnlyTexture3D<T, TPixel>)}[{typeof(Float3)}]");
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override string ToString()
|
||||
{
|
||||
return $"ComputeSharp.ReadOnlyTexture3D<{typeof(T)},{nameof(TPixel)}>[{Width}, {Height}, {Depth}]";
|
||||
return $"ComputeSharp.ReadOnlyTexture3D<{typeof(T)}, {nameof(TPixel)}>[{Width}, {Height}, {Depth}]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ namespace ComputeSharp
|
||||
/// <inheritdoc/>
|
||||
public override string ToString()
|
||||
{
|
||||
return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)},{typeof(TPixel)}>[{Width}, {Height}]";
|
||||
return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)}, {typeof(TPixel)}>[{Width}, {Height}]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ namespace ComputeSharp
|
||||
/// <inheritdoc/>
|
||||
public override string ToString()
|
||||
{
|
||||
return $"ComputeSharp.ReadWriteTexture3D<{typeof(T)},{nameof(TPixel)}>[{Width}, {Height}, {Depth}]";
|
||||
return $"ComputeSharp.ReadWriteTexture3D<{typeof(T)}, {nameof(TPixel)}>[{Width}, {Height}, {Depth}]";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
/// <param name="d3D12Device">The target <see cref="ID3D12Device"/> to use to create the root signature.</param>
|
||||
/// <param name="d3D12Root32BitConstantsCount">The number of 32 bit root constants to load.</param>
|
||||
/// <param name="d3D12DescriptorRanges1">The input descriptor ranges for the signature to create.</param>
|
||||
/// <param name="isStaticSamplerUsed">Indicates whether or not a static sampler is used.</param>
|
||||
/// <returns>A pointer to the newly allocated <see cref="ID3D12RootSignature"/> instance.</returns>
|
||||
/// <exception cref="Exception">Thrown when the creation of the root signature fails.</exception>
|
||||
public static ComPtr<ID3D12RootSignature> CreateRootSignature(
|
||||
this ref ID3D12Device d3D12Device,
|
||||
int d3D12Root32BitConstantsCount,
|
||||
ReadOnlySpan<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1)
|
||||
ReadOnlySpan<D3D12_DESCRIPTOR_RANGE1> d3D12DescriptorRanges1,
|
||||
bool isStaticSamplerUsed)
|
||||
{
|
||||
using ComPtr<ID3DBlob> d3D3Blob = default;
|
||||
using ComPtr<ID3DBlob> 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.
|
||||
|
||||
@@ -14,13 +14,13 @@ namespace ComputeSharp.Interop
|
||||
public static class ReflectionServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the shader info associated with a given shader.
|
||||
/// Gets the shader info associated with a given compute shader.
|
||||
/// <para>
|
||||
/// 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 <see cref="Delegate"/>-s.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of shader to retrieve info for.</typeparam>
|
||||
/// <typeparam name="T">The type of compute shader to retrieve info for.</typeparam>
|
||||
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
|
||||
/// <remarks>
|
||||
/// 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<T>(out ShaderInfo shaderInfo)
|
||||
where T : struct, IComputeShader
|
||||
{
|
||||
GetShaderInfo(default(T), out shaderInfo);
|
||||
GetNonGenericShaderInfo(default(T), out shaderInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shader info associated with a given shader.
|
||||
/// Gets the shader info associated with a given compute shader.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of shader to retrieve info for.</typeparam>
|
||||
/// <param name="shader">The input shader to retrieve info for.</param>
|
||||
/// <typeparam name="T">The type of compute shader to retrieve info for.</typeparam>
|
||||
/// <param name="shader">The input compute shader to retrieve info for.</param>
|
||||
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
|
||||
/// <remarks>
|
||||
/// 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
|
||||
/// </remarks>
|
||||
public static unsafe void GetShaderInfo<T>(in T shader, out ShaderInfo shaderInfo)
|
||||
where T : struct, IComputeShader
|
||||
{
|
||||
GetNonGenericShaderInfo(in shader, out shaderInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shader info associated with a given pixel shader.
|
||||
/// <para>
|
||||
/// 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 <see cref="Delegate"/>-s.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of pixel shader to retrieve info for.</typeparam>
|
||||
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
|
||||
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public static void GetShaderInfo<T, TPixel>(out ShaderInfo shaderInfo)
|
||||
where T : struct, IPixelShader<TPixel>
|
||||
where TPixel : unmanaged
|
||||
{
|
||||
GetNonGenericShaderInfo(default(T), out shaderInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shader info associated with a given pixel shader.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of pixel shader to retrieve info for.</typeparam>
|
||||
/// <typeparam name="TPixel">The type of pixels being processed by the shader.</typeparam>
|
||||
/// <param name="shader">The input pixel shader to retrieve info for.</param>
|
||||
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public static unsafe void GetShaderInfo<T, TPixel>(in T shader, out ShaderInfo shaderInfo)
|
||||
where T : struct, IPixelShader<TPixel>
|
||||
where TPixel : unmanaged
|
||||
{
|
||||
GetNonGenericShaderInfo(in shader, out shaderInfo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the shader info associated with a given shader of any type.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of shader to retrieve info for.</typeparam>
|
||||
/// <param name="shader">The input shader to retrieve info for.</param>
|
||||
/// <param name="shaderInfo">The resulting <see cref="ShaderInfo"/> instance.</param>
|
||||
private static unsafe void GetNonGenericShaderInfo<T>(in T shader, out ShaderInfo shaderInfo)
|
||||
where T : struct
|
||||
{
|
||||
ShaderLoader<T> shaderLoader = ShaderLoader<T>.Load(in shader);
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -1,37 +1,43 @@
|
||||
#pragma warning disable CS1572, CS1573
|
||||
|
||||
namespace ComputeSharp.Shaders.Renderer.Models
|
||||
namespace ComputeSharp.Shaders.Renderer.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// A model that contains info on a shader typed resource field.
|
||||
/// A model that contains info on a shader resource field.
|
||||
/// </summary>
|
||||
/// <param name="FieldType">The type of the current field in the HLSL shader.</param>
|
||||
/// <param name="FieldName">The name to use for the current field.</param>
|
||||
/// <param name="BufferIndex">The register index to bind the resource to.</param>
|
||||
internal abstract record HlslResourceInfo(string FieldType, string FieldName, int BufferIndex)
|
||||
/// <param name="RegisterIndex">The register index to bind the resource to.</param>
|
||||
internal abstract record HlslResourceInfo(string FieldType, string FieldName, int RegisterIndex)
|
||||
: CapturedFieldInfo(FieldType, FieldName)
|
||||
{
|
||||
/// <summary>
|
||||
/// A model that represents a captured constant buffer in a shader.
|
||||
/// </summary>
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// A model that represents a captured readonly typed resource in a shader.
|
||||
/// Maps to either <see cref="ComputeSharp.ReadOnlyBuffer{T}"/> or <see cref="ComputeSharp.ReadOnlyTexture2D{T}"/>.
|
||||
/// </summary>
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// A model that represents a captured writeable buffer in a shader.
|
||||
/// Maps to either <see cref="ComputeSharp.ReadWriteBuffer{T}"/> or <see cref="ComputeSharp.ReadWriteTexture2D{T}"/>.
|
||||
/// </summary>
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// A model that represents a captured sampler in a shader.
|
||||
/// This resource type doesn't have a mapping to a public API.
|
||||
/// </summary>
|
||||
/// <inheritdoc/>
|
||||
public sealed record Sampler(string FieldType, string FieldName, int RegisterIndex)
|
||||
: HlslResourceInfo(FieldType, FieldName, RegisterIndex);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
@@ -20,7 +23,7 @@ namespace ComputeSharp.Shaders
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader to run.</typeparam>
|
||||
internal static class ShaderRunner<T>
|
||||
where T : struct, IComputeShader
|
||||
where T : struct
|
||||
{
|
||||
/// <summary>
|
||||
/// The mapping used to cache and reuse compiled shaders.
|
||||
@@ -175,6 +178,86 @@ namespace ComputeSharp.Shaders
|
||||
commandList.ExecuteAndWaitForCompletion();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
|
||||
/// </summary>
|
||||
/// <param name="device">The <see cref="GraphicsDevice"/> to use to run the shader.</param>
|
||||
/// <param name="texture">The target texture to invoke the pixel shader upon.</param>
|
||||
/// <param name="shader">The input <typeparamref name="T"/> instance representing the pixel shader to run.</param>
|
||||
public static unsafe void Run<TPixel>(GraphicsDevice device, IReadWriteTexture2D<TPixel> 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<T> 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<D3D12_GPU_DESCRIPTOR_HANDLE> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads a shader with the specified parameters.
|
||||
/// </summary>
|
||||
@@ -208,7 +291,7 @@ namespace ComputeSharp.Shaders
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static unsafe void CreatePipelineData(GraphicsDevice device, in CachedShader<T> shaderData, out PipelineData pipelineData)
|
||||
{
|
||||
using ComPtr<ID3D12RootSignature> d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1);
|
||||
using ComPtr<ID3D12RootSignature> d3D12RootSignature = device.D3D12Device->CreateRootSignature(shaderData.Loader.D3D12Root32BitConstantsCount, shaderData.Loader.D3D12DescriptorRanges1, shaderData.Loader.IsStaticSamplerUsed);
|
||||
using ComPtr<ID3D12PipelineState> d3D12PipelineState = device.D3D12Device->CreateComputePipelineState(d3D12RootSignature.Get(), shaderData.Bytecode.D3D12ShaderBytecode);
|
||||
|
||||
pipelineData = new PipelineData(d3D12RootSignature.Get(), d3D12PipelineState.Get());
|
||||
|
||||
@@ -13,6 +13,11 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
string EntryPoint { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether or not the current shader is a compute shader (and not a pixel shader).
|
||||
/// </summary>
|
||||
bool IsComputeShader { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of <see cref="Renderer.Models.HlslResourceInfo"/> items for the shader fields.
|
||||
/// </summary>
|
||||
|
||||
@@ -9,7 +9,7 @@ namespace ComputeSharp.Shaders.Translation.Models
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader in use.</typeparam>
|
||||
internal readonly struct CachedShader<T>
|
||||
where T : struct, IComputeShader
|
||||
where T : struct
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="ShaderLoader{T}"/> instance with the shader metadata.
|
||||
|
||||
@@ -15,7 +15,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
|
||||
private static class TypeInfo<T>
|
||||
where T : struct, IComputeShader
|
||||
where T : struct
|
||||
{
|
||||
/// <summary>
|
||||
/// 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<T>(in T shader)
|
||||
where T : struct, IComputeShader
|
||||
where T : struct
|
||||
{
|
||||
int hash = TypeInfo<T>.Id;
|
||||
|
||||
@@ -70,6 +70,6 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// <param name="shader">The compute shader instance to use to compute the final hash value.</param>
|
||||
/// <returns>The final hash value for the input closure.</returns>
|
||||
private delegate int Hasher<T>(int hash, in T shader)
|
||||
where T : struct, IComputeShader;
|
||||
where T : struct;
|
||||
}
|
||||
}
|
||||
@@ -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<byte, int>(ref r1) = x;
|
||||
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 1) = y;
|
||||
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
|
||||
|
||||
if (IsComputeShader)
|
||||
{
|
||||
Unsafe.Add(ref Unsafe.As<byte, int>(ref r1), 2) = z;
|
||||
}
|
||||
|
||||
// Invoke the dynamic method to extract the captured data
|
||||
int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1);
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of compute shader currently in use.</typeparam>
|
||||
internal sealed partial class ShaderLoader<T> : IShaderLoader
|
||||
where T : struct, IComputeShader
|
||||
where T : struct
|
||||
{
|
||||
/// <summary>
|
||||
/// The associated <see cref="IComputeShaderSourceAttribute"/> instance for the current shader type.
|
||||
@@ -45,6 +45,11 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// </summary>
|
||||
private uint readWriteBuffersCount;
|
||||
|
||||
/// <summary>
|
||||
/// The number of samplers to define in the shader.
|
||||
/// </summary>
|
||||
private uint samplersCount;
|
||||
|
||||
/// <summary>
|
||||
/// The array of <see cref="D3D12_DESCRIPTOR_RANGE1"/> items that are required to load the captured values.
|
||||
/// </summary>
|
||||
@@ -98,6 +103,14 @@ namespace ComputeSharp.Shaders.Translation
|
||||
/// <inheritdoc/>
|
||||
public string EntryPoint { get; private set; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool IsComputeShader { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether or not the current shader requires access to a static sampler.
|
||||
/// </summary>
|
||||
public bool IsStaticSamplerUsed { get; private set; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
public IReadOnlyList<HlslResourceInfo> HlslResourceInfo => this.hlslResourceInfo;
|
||||
|
||||
@@ -174,12 +187,43 @@ namespace ComputeSharp.Shaders.Translation
|
||||
BindingFlags.Public |
|
||||
BindingFlags.NonPublic).ToArray();
|
||||
|
||||
if (shaderFields.Count == 0)
|
||||
List<D3D12_DESCRIPTOR_RANGE1> 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<D3D12_DESCRIPTOR_RANGE1> 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)
|
||||
|
||||
@@ -1370,6 +1370,31 @@ namespace ComputeSharp.Tests.SourceGenerators
|
||||
VerifyGeneratedDiagnostics<IComputeShaderDataLoaderGenerator>(source, "CMPS0046");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MultipleShaderTypes()
|
||||
{
|
||||
string source = @"
|
||||
using ComputeSharp;
|
||||
|
||||
namespace ComputeSharp
|
||||
{
|
||||
public interface IComputeShader { }
|
||||
public interface IPixelShader<TPixel> { }
|
||||
}
|
||||
|
||||
namespace MyFancyApp.Sample
|
||||
{
|
||||
public struct MyShader : IComputeShader, IPixelShader<Float4>
|
||||
{
|
||||
public void Execute()
|
||||
{
|
||||
}
|
||||
}
|
||||
}";
|
||||
|
||||
VerifyGeneratedDiagnostics<IComputeShaderSourceGenerator>(source, "CMPS0047");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies the output of a source generator.
|
||||
/// </summary>
|
||||
|
||||
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 1.3 MiB |
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 2.3 MiB |
@@ -27,22 +27,30 @@
|
||||
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Processors\HlslBokehBlurProcessor{TPixel}.cs" Link="Imaging\Processors\HlslBokehBlurProcessor{TPixel}.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Processors\HlslGaussianBlurProcessor.cs" Link="Imaging\Processors\HlslGaussianBlurProcessor.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.ImageProcessing\Processors\HlslGaussianBlurProcessor{TPixel}.cs" Link="Imaging\Processors\HlslGaussianBlurProcessor{TPixel}.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\ColorfulInfinity.cs" Link="Shaders\ColorfulInfinity.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\ExtrudedTruchetPattern.cs" Link="Shaders\ExtrudedTruchetPattern.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\FractalTiling.cs" Link="Shaders\FractalTiling.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\MengerJourney.cs" Link="Shaders\MengerJourney.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\TwoTiledTruchet.cs" Link="Shaders\TwoTiledTruchet.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\Octagrams.cs" Link="Shaders\Octagrams.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\ProteanClouds.cs" Link="Shaders\ProteanClouds.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\PyramidPattern.cs" Link="Shaders\PyramidPattern.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\TriangleGridContouring.cs" Link="Shaders\TriangleGridContouring.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\ColorfulInfinity.cs" Link="Shaders\Pixel\ColorfulInfinity.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\ContouredLayers.cs" Link="Shaders\Pixel\ContouredLayers.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\ExtrudedTruchetPattern.cs" Link="Shaders\Pixel\ExtrudedTruchetPattern.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\FractalTiling.cs" Link="Shaders\Pixel\FractalTiling.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\MengerJourney.cs" Link="Shaders\Pixel\MengerJourney.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\TwoTiledTruchet.cs" Link="Shaders\Pixel\TwoTiledTruchet.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\Octagrams.cs" Link="Shaders\Pixel\Octagrams.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\ProteanClouds.cs" Link="Shaders\Pixel\ProteanClouds.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\PyramidPattern.cs" Link="Shaders\Pixel\PyramidPattern.cs" />
|
||||
<Compile Include="..\..\samples\ComputeSharp.SwapChain\Shaders\TriangleGridContouring.cs" Link="Shaders\Pixel\TriangleGridContouring.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\..\samples\ComputeSharp.ImageProcessing\city.jpg" Link="Imaging\city.jpg" CopyToOutputDirectory="PreserveNewest" />
|
||||
<None Include="..\..\samples\ComputeSharp.ImageProcessing\city.jpg" Link="Imaging\city.jpg" CopyToOutputDirectory="PreserveNewest" />
|
||||
<None Include="..\..\samples\ComputeSharp.SwapChain\Textures\RustyMetal.png" Link="Shaders\Textures\RustyMetal.png" CopyToOutputDirectory="PreserveNewest" />
|
||||
<None Update="Assets/CityAfter1024x1024Sampling.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\ColorfulInfinity.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\ContouredLayers.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Include="Assets\ExtrudedTruchetPattern.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
|
||||
@@ -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<Rgba32, Float4> texture = device.Get().AllocateReadWriteTexture2D<Rgba32, Float4>(256, 256);
|
||||
|
||||
device.Get().ForEach<DispatchPixelShader, Float4>(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<Float4>
|
||||
{
|
||||
public Float4 Execute()
|
||||
{
|
||||
return new(
|
||||
(float)ThreadIds.X / DispatchSize.X,
|
||||
(float)ThreadIds.Y / DispatchSize.Y,
|
||||
1,
|
||||
1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ using ComputeSharp.Resources;
|
||||
namespace ComputeSharp.Tests.Extensions
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper class for testing <see cref="Buffer{T}"/> APIs.
|
||||
/// A helper class for testing resource types.
|
||||
/// </summary>
|
||||
public static class GraphicsDeviceExtensions
|
||||
{
|
||||
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper class for loading images into resources.
|
||||
/// </summary>
|
||||
public static class ImagingExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Allocates a new <see cref="ReadOnlyTexture2D{T, TPixel}"/> instance with the specified texture data.
|
||||
/// </summary>
|
||||
/// <param name="device">The target <see cref="GraphicsDevice"/> instance to allocate the texture for.</param>
|
||||
/// <param name="path">The path of the texture to load.</param>
|
||||
/// <returns>A texture with the data from the image at the specified path.</returns>
|
||||
[Pure]
|
||||
public static ReadOnlyTexture2D<Rgba32, Float4> LoadTexture(this GraphicsDevice device, string path)
|
||||
{
|
||||
using Image<ImageSharpRgba32> image = Image.Load<ImageSharpRgba32>(path);
|
||||
|
||||
Assert.IsTrue(image.TryGetSinglePixelSpan(out Span<ImageSharpRgba32> span));
|
||||
|
||||
Span<Rgba32> pixels = MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(span);
|
||||
|
||||
return device.AllocateReadOnlyTexture2D<Rgba32, Float4>(pixels, image.Width, image.Height);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="Image{TPixel}"/> instance with the specified texture data.
|
||||
/// </summary>
|
||||
/// <param name="texture">The source <see cref="ReadWriteTexture2D{T, TPixel}"/> instance to read data from.</param>
|
||||
/// <returns>An image with the data from the input texture.</returns>
|
||||
[Pure]
|
||||
public static Image<ImageSharpRgba32> ToImage(this ReadWriteTexture2D<Rgba32, Float4> texture)
|
||||
{
|
||||
Image<ImageSharpRgba32> image = new(texture.Width, texture.Height);
|
||||
|
||||
Assert.IsTrue(image.TryGetSinglePixelSpan(out Span<ImageSharpRgba32> span));
|
||||
|
||||
Span<Rgba32> pixels = MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(span);
|
||||
|
||||
texture.CopyTo(pixels);
|
||||
|
||||
return image;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,11 +75,22 @@ namespace ComputeSharp.Tests
|
||||
/// <param name="expectedPath">The path to the reference image.</param>
|
||||
/// <param name="actualPath">The path to the expected image.</param>
|
||||
/// <param name="threshold">The allowed difference threshold for the normalized delta.</param>
|
||||
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<ImageSharpRgba32>(expectedPath);
|
||||
using var actual = Image.Load<ImageSharpRgba32>(actualPath);
|
||||
|
||||
AssertEqual(expected, actual, threshold);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that two images are equal.
|
||||
/// </summary>
|
||||
/// <param name="expected">The reference image.</param>
|
||||
/// <param name="actual">The expected image.</param>
|
||||
/// <param name="threshold">The allowed difference threshold for the normalized delta.</param>
|
||||
public static void AssertEqual(Image<ImageSharpRgba32> expected, Image<ImageSharpRgba32> actual, float threshold)
|
||||
{
|
||||
if (expected.Size() != actual.Size())
|
||||
{
|
||||
Assert.Fail($"The input images have different sizes: {expected.Size()} and {actual.Size()}");
|
||||
|
||||
@@ -122,7 +122,7 @@ namespace ComputeSharp.Tests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OutOfOrderMethods_Ok()
|
||||
public void OutOfOrderMethods()
|
||||
{
|
||||
ReflectionServices.GetShaderInfo<OutOfOrderMethodsShader>(out var info);
|
||||
}
|
||||
@@ -153,5 +153,23 @@ namespace ComputeSharp.Tests
|
||||
buffer[ThreadIds.X] = ExternalStructType.Sum(type);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void PixelShader()
|
||||
{
|
||||
ReflectionServices.GetShaderInfo<StatelessPixelShader, Float4>(out var info);
|
||||
|
||||
Assert.AreEqual(info.TextureStoreInstructionCount, 1u);
|
||||
Assert.AreEqual(info.BoundResourceCount, 2u);
|
||||
}
|
||||
|
||||
public readonly partial struct StatelessPixelShader : IPixelShader<Float4>
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public Float4 Execute()
|
||||
{
|
||||
return new(1, 1, 1, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders.Compute
|
||||
{
|
||||
/// <summary>
|
||||
/// A shader creating an abstract and colorful animation.
|
||||
/// Ported from <see href="https://www.shadertoy.com/view/WtjyzR"/>.
|
||||
/// <para>Created by Benoit Marini.</para>
|
||||
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ColorfulInfinity : IComputeShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
public readonly float time;
|
||||
|
||||
/// <summary>
|
||||
/// The total number of layers for the final animation.
|
||||
/// </summary>
|
||||
private const float NumberOfLayers = 16.0f;
|
||||
|
||||
/// <summary>
|
||||
/// The number of iterations to calculate a texel value.
|
||||
/// </summary>
|
||||
private const int NumberOfIterations = 23;
|
||||
|
||||
/// <summary>
|
||||
/// Makes some magic happen.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders.Compute
|
||||
{
|
||||
/// <summary>
|
||||
/// Constructing some concise contoured layers, then applying various edge and shading effects to produce some faux depth.
|
||||
/// Ported from <see href="https://www.shadertoy.com/view/3lj3zt"/>.
|
||||
/// <para>Created by Shane.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ContouredLayers : IComputeShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> destination;
|
||||
|
||||
/// <summary>
|
||||
/// The current time Hlsl.Since the start of the application.
|
||||
/// </summary>
|
||||
public readonly float time;
|
||||
|
||||
/// <summary>
|
||||
/// The sampling texture.
|
||||
/// </summary>
|
||||
public readonly IReadOnlyTexture2D<Float4> 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;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders.Compute
|
||||
{
|
||||
/// <summary>
|
||||
/// A basic extruded square grid-based blobby Truchet pattern.
|
||||
/// Ported from <see href="https://www.shadertoy.com/view/ttVBzd"/>.
|
||||
/// <para>Created by Shane.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ExtrudedTruchetPattern : IComputeShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
public readonly float time;
|
||||
|
||||
/// <summary>
|
||||
/// Curve shape - Round: 0, Semi-round: 1, Octagonal: 2, Superellipse: 3, Straight: 4.
|
||||
/// </summary>
|
||||
private static readonly int SHAPE = 0;
|
||||
|
||||
/// <summary>
|
||||
/// Object ID: Either the back plane or the metaballs.
|
||||
/// </summary>
|
||||
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)));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders.Compute
|
||||
{
|
||||
/// <summary>
|
||||
/// A shader creating a fractal tiling animation.
|
||||
/// Ported from <see href="https://www.shadertoy.com/view/Ml2GWy"/>.
|
||||
/// <para>Created by Inigo Quilez.</para>
|
||||
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct FractalTiling : IComputeShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
public readonly float time;
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders.Compute
|
||||
{
|
||||
/// <summary>
|
||||
/// A shader creating a flythrough in a Menger system.
|
||||
/// Ported from <see href="https://www.shadertoy.com/view/Mdf3z7"/>.
|
||||
/// <para>Created by Syntopia.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct MengerJourney : IComputeShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// Rotates a given <see cref="Float2"/> value by a specified amount.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the light at a specified normal and starting color.
|
||||
/// Uses two light sources and no specular lights.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DE: Infinitely tiled Menger IFS.
|
||||
/// For more info on KIFS, see <a href="http://www.fractalforums.com/3d-fractal-generation/kaleidoscopic-%28escape-time-ifs%29/"/>
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the finite difference normal at a given position.
|
||||
/// </summary>
|
||||
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)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a ray march operation on a specific position.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders.Compute
|
||||
{
|
||||
/// <summary>
|
||||
/// A shader creating an octagram animation, inspired by arabesque.
|
||||
/// Ported from <see href="https://www.shadertoy.com/view/tlVGDt"/>.
|
||||
/// <para>Created by whisky_shusuky.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct Octagrams : IComputeShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders.Compute
|
||||
{
|
||||
/// <summary>
|
||||
/// Fully procedural 3D animated volume with three evaluations per step (for shading).
|
||||
/// Ported from <see href="https://www.shadertoy.com/view/3l23Rh"/>.
|
||||
/// <para>Created by nimitz (twitter: @stormoid).</para>
|
||||
/// <para>License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct ProteanClouds : IComputeShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time Hlsl.Since the start of the application.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders.Compute
|
||||
{
|
||||
/// <summary>
|
||||
/// 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 <see href="https://www.shadertoy.com/view/wlscWX"/>.
|
||||
/// <para>Created by Shane.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct PyramidPattern : IComputeShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time Hlsl.Since the start of the application.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders.Compute
|
||||
{
|
||||
/// <summary>
|
||||
/// Utilizing a 2D simplex grid to construct the isolines of a noise function.
|
||||
/// Ported from <see href="https://www.shadertoy.com/view/WtfGDX"/>.
|
||||
/// <para>Created by Shane.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct TriangleGridContouring : IComputeShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time Hlsl.Since the start of the application.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
namespace ComputeSharp.SwapChain.Shaders.Compute
|
||||
{
|
||||
/// <summary>
|
||||
/// A shader creating an animated two-tiles Truchet arrangement.
|
||||
/// Ported from <see href="https://www.shadertoy.com/view/tsSfWK"/>.
|
||||
/// <para>Created by Shane.</para>
|
||||
/// </summary>
|
||||
[AutoConstructor]
|
||||
internal readonly partial struct TwoTiledTruchet : IComputeShader
|
||||
{
|
||||
/// <summary>
|
||||
/// The target texture.
|
||||
/// </summary>
|
||||
public readonly IReadWriteTexture2D<Float4> texture;
|
||||
|
||||
/// <summary>
|
||||
/// The current time since the start of the application.
|
||||
/// </summary>
|
||||
public readonly float time;
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the Truchet distance field.
|
||||
/// </summary>
|
||||
/// <param name="p">The input value to compute the distance field for.</param>
|
||||
/// <param name="ang">The resulting Truchet angle.</param>
|
||||
/// <returns>The distance field for the input value.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Rgba32, Float4> background = device.Get().LoadTexture(filename);
|
||||
|
||||
RunAndCompareShader(
|
||||
device,
|
||||
shaderType,
|
||||
texture => new SwapChain.Shaders.Compute.ContouredLayers(texture, 0, background),
|
||||
texture => new ContouredLayers(0, background),
|
||||
0.0007f);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -84,14 +120,13 @@ namespace ComputeSharp.Tests
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of shader to test.</typeparam>
|
||||
/// <param name="device">The device to use.</param>
|
||||
/// <param name="factory">A producer to create an instance of the shader to run.</param>
|
||||
/// <param name="shaderType">The type of shader being executed.</param>
|
||||
/// <param name="delta">The comparison delta.</param>
|
||||
private static void RunAndCompareShader<T>(Device device, Func<ReadWriteTexture2D<Rgba32, Float4>, 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<Rgba32, Float4> texture = device.Get().AllocateReadWriteTexture2D<Rgba32, Float4>(imageInfo.Width, imageInfo.Height))
|
||||
{
|
||||
device.Get().For(texture.Width, texture.Height, factory(texture));
|
||||
if (shaderType.IsAssignableTo(typeof(IComputeShader)))
|
||||
{
|
||||
static void RunComputeShader<T>(ReadWriteTexture2D<Rgba32, Float4> texture)
|
||||
where T : struct, IComputeShader
|
||||
{
|
||||
texture.GraphicsDevice.For(texture.Width, texture.Height, (T)Activator.CreateInstance(typeof(T), texture, 0f)!);
|
||||
}
|
||||
|
||||
var action = new Action<ReadWriteTexture2D<Rgba32, Float4>>(RunComputeShader<SwapChain.Shaders.Compute.ColorfulInfinity>);
|
||||
|
||||
action.Method.GetGenericMethodDefinition().MakeGenericMethod(shaderType).Invoke(null, new[] { texture });
|
||||
}
|
||||
else
|
||||
{
|
||||
static void RunPixelShader<T>(ReadWriteTexture2D<Rgba32, Float4> texture)
|
||||
where T : struct, IPixelShader<Float4>
|
||||
{
|
||||
texture.GraphicsDevice.ForEach(texture, (T)Activator.CreateInstance(typeof(T), 0f)!);
|
||||
}
|
||||
|
||||
var action = new Action<ReadWriteTexture2D<Rgba32, Float4>>(RunPixelShader<ColorfulInfinity>);
|
||||
|
||||
action.Method.GetGenericMethodDefinition().MakeGenericMethod(shaderType).Invoke(null, new[] { texture });
|
||||
}
|
||||
|
||||
_ = image.TryGetSinglePixelSpan(out Span<ImageSharpRgba32> span);
|
||||
|
||||
texture.CopyTo(MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes a given test for a specified shader.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of shader to test.</typeparam>
|
||||
/// <param name="device">The device to use.</param>
|
||||
/// <param name="shaderType">The type of shader being executed.</param>
|
||||
/// <param name="computeFactory">The factory of compute shaders.</param>
|
||||
/// <param name="pixelFactory">The factory of pixel shaders.</param>
|
||||
/// <param name="delta">The comparison delta.</param>
|
||||
private static void RunAndCompareShader<TCompute, TPixel>(
|
||||
Device device,
|
||||
Type shaderType,
|
||||
Func<ReadWriteTexture2D<Rgba32, Float4>, TCompute> computeFactory,
|
||||
Func<ReadWriteTexture2D<Rgba32, Float4>, TPixel> pixelFactory,
|
||||
float delta)
|
||||
where TCompute : struct, IComputeShader
|
||||
where TPixel : struct, IPixelShader<Float4>
|
||||
{
|
||||
_ = device.Get();
|
||||
|
||||
string expectedPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Assets", $"{shaderType.Name}.png");
|
||||
|
||||
IImageInfo imageInfo = Image.Identify(expectedPath);
|
||||
|
||||
using Image<ImageSharpRgba32> image = new(imageInfo.Width, imageInfo.Height);
|
||||
|
||||
using (ReadWriteTexture2D<Rgba32, Float4> texture = device.Get().AllocateReadWriteTexture2D<Rgba32, Float4>(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<ImageSharpRgba32> span);
|
||||
|
||||
texture.CopyTo(MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(span));
|
||||
}
|
||||
|
||||
string actualPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Shaders", $"{shaderType.Name}.png");
|
||||
|
||||
_ = Directory.CreateDirectory(Path.GetDirectoryName(actualPath)!);
|
||||
|
||||
|
||||
@@ -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<ImageSharpRgba32>(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png"));
|
||||
|
||||
using ReadOnlyTexture2D<Rgba32, Float4> source = device.Get().LoadTexture(Path.Combine(imagingPath, "city.jpg"));
|
||||
using ReadWriteTexture2D<Rgba32, Float4> destination = device.Get().AllocateReadWriteTexture2D<Rgba32, Float4>(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<Float4> source;
|
||||
public readonly IReadWriteTexture2D<Float4> 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<ImageSharpRgba32>(Path.Combine(assetsPath, "CityAfter1024x1024Sampling.png"));
|
||||
|
||||
using ReadOnlyTexture2D<Rgba32, Float4> source = device.Get().LoadTexture(Path.Combine(imagingPath, "city.jpg"));
|
||||
using ReadWriteTexture2D<Rgba32, Float4> destination = device.Get().AllocateReadWriteTexture2D<Rgba32, Float4>(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<Float4>
|
||||
{
|
||||
public readonly IReadOnlyTexture2D<Float4> texture;
|
||||
|
||||
public Float4 Execute()
|
||||
{
|
||||
return texture[ThreadIds.Normalized.XY];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
新しいイシューから参照
ユーザーをブロックする