Refactored code to use file scoped using declarations

このコミットが含まれているのは:
Sergio Pedri committed 2021-10-30 15:11:43 +02:00
1 親 52ec5a79b0
コミット d5e3114f7c
275ファイル変更
+91970 -92271

検索条件に一致するファイルはありません

+138 -139
ファイルの表示
@@ -3,160 +3,159 @@ using System.Buffers;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
namespace ComputeSharp.Benchmark.Blas
namespace ComputeSharp.Benchmark.Blas;
/// <summary>
/// A <see langword="class"/> that benchmarks the APIs in the <see cref="BlasHelpers"/> class, on both CPU and GPU.
/// </summary>
[SimpleJob(RunStrategy.Monitoring)]
public class BlasBenchmark : IDisposable
{
/// <summary>
/// A <see langword="class"/> that benchmarks the APIs in the <see cref="BlasHelpers"/> class, on both CPU and GPU.
/// The number of samples.
/// </summary>
[SimpleJob(RunStrategy.Monitoring)]
public class BlasBenchmark : IDisposable
private const int C = 128;
/// <summary>
/// The nummber of rows in the <see cref="X"/> matrix.
/// </summary>
private const int N = 512;
/// <summary>
/// The number of columns in the <see cref="X"/> matrix (same as the number of rows in the <see cref="W"/> matrix)
/// </summary>
private const int M = 512;
/// <summary>
/// The number of columns in the <see cref="W"/> matrix.
/// </summary>
private const int P = 256;
/// <summary>
/// The input tensor.
/// </summary>
private float[]? X;
/// <summary>
/// The weights tensor.
/// </summary>
private float[]? W;
/// <summary>
/// The bias tensor.
/// </summary>
private float[]? B;
/// <summary>
/// The result tensor.
/// </summary>
private float[]? Y;
/// <summary>
/// The input tensor (GPU).
/// </summary>
private ReadOnlyBuffer<float>? BufferX;
/// <summary>
/// The weights tensor (GPU).
/// </summary>
private ReadOnlyBuffer<float>? BufferW;
/// <summary>
/// The bias tensor (GPU).
/// </summary>
private ReadOnlyBuffer<float>? BufferB;
/// <summary>
/// The result tensor (GPU).
/// </summary>
private ReadWriteBuffer<float>? BufferY;
/// <summary>
/// A <see cref="System.Random"/> instance to initialize the tensors.
/// </summary>
private readonly Random Random = new Random();
/// <summary>
/// Initial setup for a benchmarking session.
/// </summary>
[GlobalSetup]
public void Setup()
{
/// <summary>
/// The number of samples.
/// </summary>
private const int C = 128;
/// <summary>
/// The nummber of rows in the <see cref="X"/> matrix.
/// </summary>
private const int N = 512;
/// <summary>
/// The number of columns in the <see cref="X"/> matrix (same as the number of rows in the <see cref="W"/> matrix)
/// </summary>
private const int M = 512;
/// <summary>
/// The number of columns in the <see cref="W"/> matrix.
/// </summary>
private const int P = 256;
/// <summary>
/// The input tensor.
/// </summary>
private float[]? X;
/// <summary>
/// The weights tensor.
/// </summary>
private float[]? W;
/// <summary>
/// The bias tensor.
/// </summary>
private float[]? B;
/// <summary>
/// The result tensor.
/// </summary>
private float[]? Y;
/// <summary>
/// The input tensor (GPU).
/// </summary>
private ReadOnlyBuffer<float>? BufferX;
/// <summary>
/// The weights tensor (GPU).
/// </summary>
private ReadOnlyBuffer<float>? BufferW;
/// <summary>
/// The bias tensor (GPU).
/// </summary>
private ReadOnlyBuffer<float>? BufferB;
/// <summary>
/// The result tensor (GPU).
/// </summary>
private ReadWriteBuffer<float>? BufferY;
/// <summary>
/// A <see cref="System.Random"/> instance to initialize the tensors.
/// </summary>
private readonly Random Random = new Random();
/// <summary>
/// Initial setup for a benchmarking session.
/// </summary>
[GlobalSetup]
public void Setup()
// Creates a new random normalized float[] array of a given size
float[] CreateRandomArray(int size)
{
// Creates a new random normalized float[] array of a given size
float[] CreateRandomArray(int size)
float[] array = ArrayPool<float>.Shared.Rent(size);
foreach (ref float x in array.AsSpan())
{
float[] array = ArrayPool<float>.Shared.Rent(size);
foreach (ref float x in array.AsSpan())
{
x = (float)Random.NextDouble();
}
return array;
x = (float)Random.NextDouble();
}
X = CreateRandomArray(C * N * M);
W = CreateRandomArray(M * P);
B = CreateRandomArray(P);
Y = CreateRandomArray(C * N * P);
BufferX = Gpu.Default.AllocateReadOnlyBuffer(X);
BufferW = Gpu.Default.AllocateReadOnlyBuffer(W);
BufferB = Gpu.Default.AllocateReadOnlyBuffer(B);
BufferY = Gpu.Default.AllocateReadWriteBuffer(Y);
Cpu();
GpuWithNoTemporaryBuffers();
GpuWithTemporaryBuffers();
return array;
}
/// <inheritdoc/>
[GlobalCleanup]
public void Dispose()
{
ArrayPool<float>.Shared.Return(X!);
ArrayPool<float>.Shared.Return(W!);
ArrayPool<float>.Shared.Return(B!);
ArrayPool<float>.Shared.Return(Y!);
X = CreateRandomArray(C * N * M);
W = CreateRandomArray(M * P);
B = CreateRandomArray(P);
Y = CreateRandomArray(C * N * P);
BufferX!.Dispose();
BufferW!.Dispose();
BufferB!.Dispose();
BufferY!.Dispose();
}
BufferX = Gpu.Default.AllocateReadOnlyBuffer(X);
BufferW = Gpu.Default.AllocateReadOnlyBuffer(W);
BufferB = Gpu.Default.AllocateReadOnlyBuffer(B);
BufferY = Gpu.Default.AllocateReadWriteBuffer(Y);
/// <summary>
/// Runs a fully connected forward operation on the CPU.
/// </summary>
[Benchmark(Baseline = true)]
public void Cpu()
{
BlasHelpers.FullyConnectedForwardCpu(C, N, M, P, X!, W!, B!, Y!);
}
Cpu();
GpuWithNoTemporaryBuffers();
GpuWithTemporaryBuffers();
}
/// <summary>
/// Runs a fully connected forward operation on the GPU.
/// </summary>
[Benchmark]
public void GpuWithNoTemporaryBuffers()
{
BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, BufferX!, BufferW!, BufferB!, BufferY!);
}
/// <inheritdoc/>
[GlobalCleanup]
public void Dispose()
{
ArrayPool<float>.Shared.Return(X!);
ArrayPool<float>.Shared.Return(W!);
ArrayPool<float>.Shared.Return(B!);
ArrayPool<float>.Shared.Return(Y!);
/// <summary>
/// Runs a fully connected forward operation on the GPU, creating temporary GPU buffers to perform the operations.
/// </summary>
[Benchmark]
public void GpuWithTemporaryBuffers()
{
using ReadOnlyBuffer<float> x = Gpu.Default.AllocateReadOnlyBuffer(X!);
using ReadOnlyBuffer<float> w = Gpu.Default.AllocateReadOnlyBuffer(W!);
using ReadOnlyBuffer<float> b = Gpu.Default.AllocateReadOnlyBuffer(B!);
using ReadWriteBuffer<float> y = Gpu.Default.AllocateReadWriteBuffer<float>(Y!.Length);
BufferX!.Dispose();
BufferW!.Dispose();
BufferB!.Dispose();
BufferY!.Dispose();
}
BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, x, w, b, y);
/// <summary>
/// Runs a fully connected forward operation on the CPU.
/// </summary>
[Benchmark(Baseline = true)]
public void Cpu()
{
BlasHelpers.FullyConnectedForwardCpu(C, N, M, P, X!, W!, B!, Y!);
}
y.CopyTo(Y);
}
/// <summary>
/// Runs a fully connected forward operation on the GPU.
/// </summary>
[Benchmark]
public void GpuWithNoTemporaryBuffers()
{
BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, BufferX!, BufferW!, BufferB!, BufferY!);
}
/// <summary>
/// Runs a fully connected forward operation on the GPU, creating temporary GPU buffers to perform the operations.
/// </summary>
[Benchmark]
public void GpuWithTemporaryBuffers()
{
using ReadOnlyBuffer<float> x = Gpu.Default.AllocateReadOnlyBuffer(X!);
using ReadOnlyBuffer<float> w = Gpu.Default.AllocateReadOnlyBuffer(W!);
using ReadOnlyBuffer<float> b = Gpu.Default.AllocateReadOnlyBuffer(B!);
using ReadWriteBuffer<float> y = Gpu.Default.AllocateReadWriteBuffer<float>(Y!.Length);
BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, x, w, b, y);
y.CopyTo(Y);
}
}
+83 -84
ファイルの表示
@@ -1,109 +1,108 @@
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace ComputeSharp.Benchmark.Blas
namespace ComputeSharp.Benchmark.Blas;
/// <summary>
/// A <see langword="class"/> that contains primitives to run certain operations of a neural network.
/// </summary>
internal static partial class BlasHelpers
{
/// <summary>
/// A <see langword="class"/> that contains primitives to run certain operations of a neural network.
/// Executes the forward pass on a fully connected layer on the CPU.
/// </summary>
internal static partial class BlasHelpers
/// <param name="c">The number of samples in the input tensor.</param>
/// <param name="n">The number of rows in the input matrix.</param>
/// <param name="m">The number of columns in the input matrix.</param>
/// <param name="p">The number of columns in the output matrix.</param>
/// <param name="x">The input tensor.</param>
/// <param name="w">The weights tensor.</param>
/// <param name="b">The bias tensor.</param>
/// <param name="y">The result tensor.</param>
public static void FullyConnectedForwardCpu(int c, int n, int m, int p, float[] x, float[] w, float[] b, float[] y)
{
/// <summary>
/// Executes the forward pass on a fully connected layer on the CPU.
/// </summary>
/// <param name="c">The number of samples in the input tensor.</param>
/// <param name="n">The number of rows in the input matrix.</param>
/// <param name="m">The number of columns in the input matrix.</param>
/// <param name="p">The number of columns in the output matrix.</param>
/// <param name="x">The input tensor.</param>
/// <param name="w">The weights tensor.</param>
/// <param name="b">The bias tensor.</param>
/// <param name="y">The result tensor.</param>
public static void FullyConnectedForwardCpu(int c, int n, int m, int p, float[] x, float[] w, float[] b, float[] y)
void Kernel(int s)
{
void Kernel(int s)
ref float rx = ref x[s * n * m];
ref float rw = ref w[0];
ref float rb = ref b[0];
ref float ry = ref y[s * n * p];
for (int i = 0; i < n; i++)
{
ref float rx = ref x[s * n * m];
ref float rw = ref w[0];
ref float rb = ref b[0];
ref float ry = ref y[s * n * p];
int x_offset = i * m;
int y_offset = i * p;
for (int i = 0; i < n; i++)
for (int j = 0; j < p; j++)
{
int x_offset = i * m;
int y_offset = i * p;
float result = 0f;
for (int j = 0; j < p; j++)
for (int k = 0; k < m; k++)
{
float result = 0f;
for (int k = 0; k < m; k++)
{
result += Unsafe.Add(ref rx, x_offset + k) * Unsafe.Add(ref rw, k * p + j);
}
Unsafe.Add(ref ry, y_offset + j) = result + Unsafe.Add(ref rb, j);
result += Unsafe.Add(ref rx, x_offset + k) * Unsafe.Add(ref rw, k * p + j);
}
Unsafe.Add(ref ry, y_offset + j) = result + Unsafe.Add(ref rb, j);
}
}
Parallel.For(0, c, Kernel);
}
/// <summary>
/// Executes the forward pass on a fully connected layer on the GPU.
/// </summary>
/// <param name="device">The device to run the computation on.</param>
/// <param name="c">The number of samples in the input tensor.</param>
/// <param name="n">The number of rows in the input matrix.</param>
/// <param name="m">The number of columns in the input matrix.</param>
/// <param name="p">The number of columns in the output matrix.</param>
/// <param name="x">The input tensor.</param>
/// <param name="w">The weights tensor.</param>
/// <param name="b">The bias tensor.</param>
/// <param name="y">The result tensor.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void FullyConnectedForwardGpu(
GraphicsDevice device,
int c,
int n,
int m,
int p,
ReadOnlyBuffer<float> x,
ReadOnlyBuffer<float> w,
ReadOnlyBuffer<float> b,
ReadWriteBuffer<float> y)
{
device.For(c, n, p, new FullyConnectedForwardKernel(n, m, p, x, w, b, y));
}
Parallel.For(0, c, Kernel);
}
/// <summary>
/// Kernel for <see cref="FullyConnectedForwardGpu"/>.
/// </summary>
[AutoConstructor]
public readonly partial struct FullyConnectedForwardKernel : IComputeShader
{
public readonly int n;
public readonly int m;
public readonly int p;
public readonly ReadOnlyBuffer<float> x;
public readonly ReadOnlyBuffer<float> w;
public readonly ReadOnlyBuffer<float> b;
public readonly ReadWriteBuffer<float> y;
/// <summary>
/// Executes the forward pass on a fully connected layer on the GPU.
/// </summary>
/// <param name="device">The device to run the computation on.</param>
/// <param name="c">The number of samples in the input tensor.</param>
/// <param name="n">The number of rows in the input matrix.</param>
/// <param name="m">The number of columns in the input matrix.</param>
/// <param name="p">The number of columns in the output matrix.</param>
/// <param name="x">The input tensor.</param>
/// <param name="w">The weights tensor.</param>
/// <param name="b">The bias tensor.</param>
/// <param name="y">The result tensor.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void FullyConnectedForwardGpu(
GraphicsDevice device,
int c,
int n,
int m,
int p,
ReadOnlyBuffer<float> x,
ReadOnlyBuffer<float> w,
ReadOnlyBuffer<float> b,
ReadWriteBuffer<float> y)
{
device.For(c, n, p, new FullyConnectedForwardKernel(n, m, p, x, w, b, y));
}
/// <inheritdoc/>
public void Execute()
/// <summary>
/// Kernel for <see cref="FullyConnectedForwardGpu"/>.
/// </summary>
[AutoConstructor]
public readonly partial struct FullyConnectedForwardKernel : IComputeShader
{
public readonly int n;
public readonly int m;
public readonly int p;
public readonly ReadOnlyBuffer<float> x;
public readonly ReadOnlyBuffer<float> w;
public readonly ReadOnlyBuffer<float> b;
public readonly ReadWriteBuffer<float> y;
/// <inheritdoc/>
public void Execute()
{
int x_offset = ThreadIds.X * n * p + ThreadIds.Y * m;
float result = 0f;
for (int k = 0; k < m; k++)
{
int x_offset = ThreadIds.X * n * p + ThreadIds.Y * m;
float result = 0f;
for (int k = 0; k < m; k++)
{
result += x[x_offset + k] * w[k * p + ThreadIds.Z];
}
y[ThreadIds.X * n * p + ThreadIds.Y * p + ThreadIds.Z] = result + b[ThreadIds.Z];
result += x[x_offset + k] * w[k * p + ThreadIds.Z];
}
y[ThreadIds.X * n * p + ThreadIds.Y * p + ThreadIds.Z] = result + b[ThreadIds.Z];
}
}
}
+65 -66
ファイルの表示
@@ -10,82 +10,81 @@ using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Processors.Convolution;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.Benchmark.Imaging
namespace ComputeSharp.Benchmark.Imaging;
/// <summary>
/// A <see langword="class"/> that benchmarks the image processors against the reference in ImageSharp.
/// </summary>
[SimpleJob(RunStrategy.Monitoring)]
[CategoriesColumn]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
public class ImagingBenchmark : IDisposable
{
/// <summary>
/// A <see langword="class"/> that benchmarks the image processors against the reference in ImageSharp.
/// The loaded image.
/// </summary>
[SimpleJob(RunStrategy.Monitoring)]
[CategoriesColumn]
[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)]
public class ImagingBenchmark : IDisposable
private Image<ImageSharpRgba32>? image;
/// <summary>
/// Initial setup for a benchmarking session.
/// </summary>
[GlobalSetup]
public void Setup()
{
/// <summary>
/// The loaded image.
/// </summary>
private Image<ImageSharpRgba32>? image;
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg");
/// <summary>
/// Initial setup for a benchmarking session.
/// </summary>
[GlobalSetup]
public void Setup()
{
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "Imaging", "city.jpg");
this.image = Image.Load<ImageSharpRgba32>(path);
this.image = Image.Load<ImageSharpRgba32>(path);
Bokeh_Cpu();
Bokeh_Gpu();
Gaussian_Cpu();
Gaussian_Gpu();
}
Bokeh_Cpu();
Bokeh_Gpu();
Gaussian_Cpu();
Gaussian_Gpu();
}
/// <inheritdoc/>
[GlobalCleanup]
public void Dispose()
{
this.image!.Dispose();
}
/// <inheritdoc/>
[GlobalCleanup]
public void Dispose()
{
this.image!.Dispose();
}
/// <summary>
/// Runs a bokeh blur effect on the CPU.
/// </summary>
[Benchmark(Baseline = true)]
[BenchmarkCategory("BOKEH")]
public void Bokeh_Cpu()
{
this.image!.Mutate(c => c.ApplyProcessor(new BokehBlurProcessor(80, 2, 3)));
}
/// <summary>
/// Runs a bokeh blur effect on the CPU.
/// </summary>
[Benchmark(Baseline = true)]
[BenchmarkCategory("BOKEH")]
public void Bokeh_Cpu()
{
this.image!.Mutate(c => c.ApplyProcessor(new BokehBlurProcessor(80, 2, 3)));
}
/// <summary>
/// Runs a bokeh blur effect on the GPU.
/// </summary>
[Benchmark]
[BenchmarkCategory("BOKEH")]
public void Bokeh_Gpu()
{
this.image!.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2)));
}
/// <summary>
/// Runs a bokeh blur effect on the GPU.
/// </summary>
[Benchmark]
[BenchmarkCategory("BOKEH")]
public void Bokeh_Gpu()
{
this.image!.Mutate(c => c.ApplyProcessor(new HlslBokehBlurProcessor(80, 2)));
}
/// <summary>
/// Runs a gaussian blur effect on the CPU.
/// </summary>
[Benchmark(Baseline = true)]
[BenchmarkCategory("GAUSSIAN")]
public void Gaussian_Cpu()
{
this.image!.Mutate(c => c.ApplyProcessor(new GaussianBlurProcessor(80)));
}
/// <summary>
/// Runs a gaussian blur effect on the CPU.
/// </summary>
[Benchmark(Baseline = true)]
[BenchmarkCategory("GAUSSIAN")]
public void Gaussian_Cpu()
{
this.image!.Mutate(c => c.ApplyProcessor(new GaussianBlurProcessor(80)));
}
/// <summary>
/// Runs a gaussian blur effect on the GPU.
/// </summary>
[Benchmark]
[BenchmarkCategory("GAUSSIAN")]
public void Gaussian_Gpu()
{
this.image!.Mutate(c => c.ApplyProcessor(new HlslGaussianBlurProcessor(80)));
}
/// <summary>
/// Runs a gaussian blur effect on the GPU.
/// </summary>
[Benchmark]
[BenchmarkCategory("GAUSSIAN")]
public void Gaussian_Gpu()
{
this.image!.Mutate(c => c.ApplyProcessor(new HlslGaussianBlurProcessor(80)));
}
}
+35 -36
ファイルの表示
@@ -3,44 +3,43 @@
using System.Runtime.CompilerServices;
namespace SixLabors.ImageSharp
namespace SixLabors.ImageSharp;
/// <summary>
/// Represents a complex number, where the real and imaginary parts are stored as <see cref="float"/> values.
/// </summary>
/// <remarks>
/// This is a more efficient version of the <see cref="Complex64"/> type.
/// </remarks>
internal readonly struct Complex64
{
/// <summary>
/// Represents a complex number, where the real and imaginary parts are stored as <see cref="float"/> values.
/// The real part of the complex number.
/// </summary>
/// <remarks>
/// This is a more efficient version of the <see cref="Complex64"/> type.
/// </remarks>
internal readonly struct Complex64
public readonly float Real;
/// <summary>
/// The imaginary part of the complex number.
/// </summary>
public readonly float Imaginary;
/// <summary>
/// Initializes a new instance of the <see cref="Complex64"/> struct.
/// </summary>
/// <param name="real">The real part in the complex number.</param>
/// <param name="imaginary">The imaginary part in the complex number.</param>
public Complex64(float real, float imaginary)
{
/// <summary>
/// The real part of the complex number.
/// </summary>
public readonly float Real;
/// <summary>
/// The imaginary part of the complex number.
/// </summary>
public readonly float Imaginary;
/// <summary>
/// Initializes a new instance of the <see cref="Complex64"/> struct.
/// </summary>
/// <param name="real">The real part in the complex number.</param>
/// <param name="imaginary">The imaginary part in the complex number.</param>
public Complex64(float real, float imaginary)
{
this.Real = real;
this.Imaginary = imaginary;
}
/// <summary>
/// Performs the multiplication operation between a <see cref="Complex64"/> instance and a <see cref="float"/> scalar.
/// </summary>
/// <param name="value">The <see cref="Complex64"/> value to multiply.</param>
/// <param name="scalar">The <see cref="float"/> scalar to use to multiply the <see cref="Complex64"/> value.</param>
/// <returns>The <see cref="Complex64"/> result.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Complex64 operator *(Complex64 value, float scalar) => new Complex64(value.Real * scalar, value.Imaginary * scalar);
this.Real = real;
this.Imaginary = imaginary;
}
}
/// <summary>
/// Performs the multiplication operation between a <see cref="Complex64"/> instance and a <see cref="float"/> scalar.
/// </summary>
/// <param name="value">The <see cref="Complex64"/> value to multiply.</param>
/// <param name="scalar">The <see cref="float"/> scalar to use to multiply the <see cref="Complex64"/> value.</param>
/// <returns>The <see cref="Complex64"/> result.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Complex64 operator *(Complex64 value, float scalar) => new Complex64(value.Real * scalar, value.Imaginary * scalar);
}
+65 -66
ファイルの表示
@@ -5,81 +5,80 @@ using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
namespace ComputeSharp.BokehBlur.Processors;
/// <summary>
/// Applies bokeh blur processing to the image.
/// </summary>
public sealed partial class HlslBokehBlurProcessor : IImageProcessor
{
/// <summary>
/// Applies bokeh blur processing to the image.
/// The default radius used by the parameterless constructor.
/// </summary>
public sealed partial class HlslBokehBlurProcessor : IImageProcessor
public const int DefaultRadius = 32;
/// <summary>
/// The default component count used by the parameterless constructor.
/// </summary>
public const int DefaultComponents = 2;
/// <summary>
/// Initializes a new instance of the <see cref="HlslBokehBlurProcessor"/> class.
/// </summary>
public HlslBokehBlurProcessor()
: this(Gpu.Default, DefaultRadius, DefaultComponents)
{
/// <summary>
/// The default radius used by the parameterless constructor.
/// </summary>
public const int DefaultRadius = 32;
}
/// <summary>
/// The default component count used by the parameterless constructor.
/// </summary>
public const int DefaultComponents = 2;
/// <summary>
/// Initializes a new instance of the <see cref="HlslBokehBlurProcessor"/> class.
/// </summary>
/// <param name="radius">The size of the area to sample.</param>
/// <param name="components">The number of components to use to approximate the original 2D bokeh blur convolution kernel.</param>
public HlslBokehBlurProcessor(int radius, int components)
: this(Gpu.Default, radius, components)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HlslBokehBlurProcessor"/> class.
/// </summary>
public HlslBokehBlurProcessor()
: this(Gpu.Default, DefaultRadius, DefaultComponents)
/// <summary>
/// Initializes a new instance of the <see cref="HlslBokehBlurProcessor"/> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
/// <param name="radius">The size of the area to sample.</param>
/// <param name="components">The number of components to use to approximate the original 2D bokeh blur convolution kernel.</param>
public HlslBokehBlurProcessor(GraphicsDevice device, int radius, int components)
{
GraphicsDevice = device;
Radius = radius;
Components = components;
}
/// <summary>
/// Gets the <see cref="ComputeSharp.GraphicsDevice"/> associated with the current instance.
/// </summary>
public GraphicsDevice GraphicsDevice { get; }
/// <summary>
/// Gets the radius.
/// </summary>
public int Radius { get; }
/// <summary>
/// Gets the number of components.
/// </summary>
public int Components { get; }
/// <inheritdoc/>
public IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
where TPixel : unmanaged, IPixel<TPixel>
{
if (typeof(TPixel) != typeof(ImageSharpRgba32))
{
ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
}
/// <summary>
/// Initializes a new instance of the <see cref="HlslBokehBlurProcessor"/> class.
/// </summary>
/// <param name="radius">The size of the area to sample.</param>
/// <param name="components">The number of components to use to approximate the original 2D bokeh blur convolution kernel.</param>
public HlslBokehBlurProcessor(int radius, int components)
: this(Gpu.Default, radius, components)
{
}
var processor = new Implementation(this, configuration, Unsafe.As<Image<ImageSharpRgba32>>(source), sourceRectangle);
/// <summary>
/// Initializes a new instance of the <see cref="HlslBokehBlurProcessor"/> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
/// <param name="radius">The size of the area to sample.</param>
/// <param name="components">The number of components to use to approximate the original 2D bokeh blur convolution kernel.</param>
public HlslBokehBlurProcessor(GraphicsDevice device, int radius, int components)
{
GraphicsDevice = device;
Radius = radius;
Components = components;
}
/// <summary>
/// Gets the <see cref="ComputeSharp.GraphicsDevice"/> associated with the current instance.
/// </summary>
public GraphicsDevice GraphicsDevice { get; }
/// <summary>
/// Gets the radius.
/// </summary>
public int Radius { get; }
/// <summary>
/// Gets the number of components.
/// </summary>
public int Components { get; }
/// <inheritdoc/>
public IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
where TPixel : unmanaged, IPixel<TPixel>
{
if (typeof(TPixel) != typeof(ImageSharpRgba32))
{
ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
}
var processor = new Implementation(this, configuration, Unsafe.As<Image<ImageSharpRgba32>>(source), sourceRectangle);
return Unsafe.As<IImageProcessor<TPixel>>(processor);
}
return Unsafe.As<IImageProcessor<TPixel>>(processor);
}
}
+366 -367
ファイルの表示
@@ -9,417 +9,416 @@ using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
namespace ComputeSharp.BokehBlur.Processors;
/// <inheritdoc/>
public sealed partial class HlslBokehBlurProcessor
{
/// <inheritdoc/>
public sealed partial class HlslBokehBlurProcessor
/// <summary>
/// Applies bokeh blur processing to the image.
/// </summary>
/// <remarks>This processor is based on the code from Mike Pound, see <a href="https://github.com/mikepound/convolve">github.com/mikepound/convolve</a>.</remarks>
public sealed partial class Implementation : ImageProcessor<ImageSharpRgba32>
{
/// <summary>
/// Applies bokeh blur processing to the image.
/// The <see cref="ComputeSharp.GraphicsDevice"/> instance in use.
/// </summary>
/// <remarks>This processor is based on the code from Mike Pound, see <a href="https://github.com/mikepound/convolve">github.com/mikepound/convolve</a>.</remarks>
public sealed partial class Implementation : ImageProcessor<ImageSharpRgba32>
private readonly GraphicsDevice GraphicsDevice;
/// <summary>
/// The kernel radius.
/// </summary>
private readonly int Radius;
/// <summary>
/// The maximum size of the kernel in either direction.
/// </summary>
private readonly int KernelSize;
/// <summary>
/// The number of components to use when applying the bokeh blur.
/// </summary>
private readonly int ComponentsCount;
/// <summary>
/// The kernel parameters to use for the current instance (a: X, b: Y, A: Z, B: W)
/// </summary>
private readonly Vector4[] KernelParameters;
/// <summary>
/// The kernel components for the current instance.
/// </summary>
private readonly Complex64[][] Kernels;
/// <summary>
/// The scaling factor for kernel values.
/// </summary>
private readonly float KernelsScale;
/// <summary>
/// The mapping of initialized complex kernels and parameters, to speed up the initialization of new <see cref="HlslBokehBlurProcessor{TPixel}"/> instances.
/// </summary>
private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, Complex64[][] Kernels)> Cache = new();
/// <summary>
/// Initializes a new instance of the <see cref="Implementation"/> class.
/// </summary>
/// <param name="definition">The <see cref="HlslBokehBlurProcessor"/> defining the processor parameters.</param>
/// <param name="configuration">The configuration which allows altering default behaviour or extending the library.</param>
/// <param name="source">The source <see cref="Image{TPixel}"/> instance to modify.</param>
/// <param name="sourceRectangle">The source <see cref="Rectangle"/> that indicates the area to edit.</param>
public Implementation(HlslBokehBlurProcessor definition, Configuration configuration, Image<ImageSharpRgba32> source, Rectangle sourceRectangle)
: base(configuration, source, sourceRectangle)
{
/// <summary>
/// The <see cref="ComputeSharp.GraphicsDevice"/> instance in use.
/// </summary>
private readonly GraphicsDevice GraphicsDevice;
GraphicsDevice = definition.GraphicsDevice;
Radius = definition.Radius;
KernelSize = Radius * 2 + 1;
ComponentsCount = definition.Components;
/// <summary>
/// The kernel radius.
/// </summary>
private readonly int Radius;
/// <summary>
/// The maximum size of the kernel in either direction.
/// </summary>
private readonly int KernelSize;
/// <summary>
/// The number of components to use when applying the bokeh blur.
/// </summary>
private readonly int ComponentsCount;
/// <summary>
/// The kernel parameters to use for the current instance (a: X, b: Y, A: Z, B: W)
/// </summary>
private readonly Vector4[] KernelParameters;
/// <summary>
/// The kernel components for the current instance.
/// </summary>
private readonly Complex64[][] Kernels;
/// <summary>
/// The scaling factor for kernel values.
/// </summary>
private readonly float KernelsScale;
/// <summary>
/// The mapping of initialized complex kernels and parameters, to speed up the initialization of new <see cref="HlslBokehBlurProcessor{TPixel}"/> instances.
/// </summary>
private static readonly ConcurrentDictionary<(int Radius, int ComponentsCount), (Vector4[] Parameters, float Scale, Complex64[][] Kernels)> Cache = new();
/// <summary>
/// Initializes a new instance of the <see cref="Implementation"/> class.
/// </summary>
/// <param name="definition">The <see cref="HlslBokehBlurProcessor"/> defining the processor parameters.</param>
/// <param name="configuration">The configuration which allows altering default behaviour or extending the library.</param>
/// <param name="source">The source <see cref="Image{TPixel}"/> instance to modify.</param>
/// <param name="sourceRectangle">The source <see cref="Rectangle"/> that indicates the area to edit.</param>
public Implementation(HlslBokehBlurProcessor definition, Configuration configuration, Image<ImageSharpRgba32> source, Rectangle sourceRectangle)
: base(configuration, source, sourceRectangle)
// Reuse the initialized values from the cache, if possible
var parameters = (Radius, ComponentsCount);
if (Cache.TryGetValue(parameters, out var info))
{
GraphicsDevice = definition.GraphicsDevice;
Radius = definition.Radius;
KernelSize = Radius * 2 + 1;
ComponentsCount = definition.Components;
KernelParameters = info.Parameters;
KernelsScale = info.Scale;
Kernels = info.Kernels;
}
else
{
// Initialize the complex kernels and parameters with the current arguments
(KernelParameters, KernelsScale) = GetParameters();
Kernels = CreateComplexKernels();
NormalizeKernels();
// Reuse the initialized values from the cache, if possible
var parameters = (Radius, ComponentsCount);
if (Cache.TryGetValue(parameters, out var info))
{
KernelParameters = info.Parameters;
KernelsScale = info.Scale;
Kernels = info.Kernels;
}
else
{
// Initialize the complex kernels and parameters with the current arguments
(KernelParameters, KernelsScale) = GetParameters();
Kernels = CreateComplexKernels();
NormalizeKernels();
// Store them in the cache for future use
Cache.TryAdd(parameters, (KernelParameters, KernelsScale, Kernels));
}
}
// Store them in the cache for future use
Cache.TryAdd(parameters, (KernelParameters, KernelsScale, Kernels));
}
/// <summary>
/// Gets the kernel scales to adjust the component values in each kernel.
/// </summary>
private static IReadOnlyList<float> KernelScales { get; } = new[] { 1.4f, 1.2f, 1.2f, 1.2f, 1.2f, 1.2f };
/// <summary>
/// Gets the available bokeh blur kernel parameters.
/// </summary>
private static IReadOnlyList<Vector4[]> KernelComponents { get; } = new[]
{
// 1 component
new[] { new Vector4(0.862325f, 1.624835f, 0.767583f, 1.862321f) },
// 2 components
new[]
{
new Vector4(0.886528f, 5.268909f, 0.411259f, -0.548794f),
new Vector4(1.960518f, 1.558213f, 0.513282f, 4.56111f)
},
// 3 components
new[]
{
new Vector4(2.17649f, 5.043495f, 1.621035f, -2.105439f),
new Vector4(1.019306f, 9.027613f, -0.28086f, -0.162882f),
new Vector4(2.81511f, 1.597273f, -0.366471f, 10.300301f)
},
// 4 components
new[]
{
new Vector4(4.338459f, 1.553635f, -5.767909f, 46.164397f),
new Vector4(3.839993f, 4.693183f, 9.795391f, -15.227561f),
new Vector4(2.791880f, 8.178137f, -3.048324f, 0.302959f),
new Vector4(1.342190f, 12.328289f, 0.010001f, 0.244650f)
},
// 5 components
new[]
{
new Vector4(4.892608f, 1.685979f, -22.356787f, 85.91246f),
new Vector4(4.71187f, 4.998496f, 35.918936f, -28.875618f),
new Vector4(4.052795f, 8.244168f, -13.212253f, -1.578428f),
new Vector4(2.929212f, 11.900859f, 0.507991f, 1.816328f),
new Vector4(1.512961f, 16.116382f, 0.138051f, -0.01f)
},
// 6 components
new[]
{
new Vector4(5.143778f, 2.079813f, -82.326596f, 111.231024f),
new Vector4(5.612426f, 6.153387f, 113.878661f, 58.004879f),
new Vector4(5.982921f, 9.802895f, 39.479083f, -162.028887f),
new Vector4(6.505167f, 11.059237f, -71.286026f, 95.027069f),
new Vector4(3.869579f, 14.81052f, 1.405746f, -3.704914f),
new Vector4(2.201904f, 19.032909f, -0.152784f, -0.107988f)
}
};
/// <summary>
/// Gets the kernel parameters and scaling factor for the current count value in the current instance.
/// </summary>
private (Vector4[] Parameters, float Scale) GetParameters()
{
// Prepare the kernel components
int index = Math.Max(0, Math.Min(ComponentsCount - 1, KernelComponents.Count));
return (KernelComponents[index], KernelScales[index]);
}
/// <summary>
/// Creates the collection of complex 1D kernels with the specified parameters.
/// </summary>
private Complex64[][] CreateComplexKernels()
{
var kernels = new Complex64[KernelParameters.Length][];
ref Vector4 baseRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
for (int i = 0; i < KernelParameters.Length; i++)
{
ref Vector4 paramsRef = ref Unsafe.Add(ref baseRef, i);
kernels[i] = CreateComplex1DKernel(paramsRef.X, paramsRef.Y);
}
/// <summary>
/// Gets the kernel scales to adjust the component values in each kernel.
/// </summary>
private static IReadOnlyList<float> KernelScales { get; } = new[] { 1.4f, 1.2f, 1.2f, 1.2f, 1.2f, 1.2f };
return kernels;
}
/// <summary>
/// Gets the available bokeh blur kernel parameters.
/// </summary>
private static IReadOnlyList<Vector4[]> KernelComponents { get; } = new[]
/// <summary>
/// Creates a complex 1D kernel with the specified parameters.
/// </summary>
/// <param name="a">The exponential parameter for each complex component.</param>
/// <param name="b">The angle component for each complex component.</param>
private Complex64[] CreateComplex1DKernel(float a, float b)
{
var kernel = new Complex64[KernelSize];
ref Complex64 baseRef = ref MemoryMarshal.GetReference(kernel.AsSpan());
int r = Radius, n = -r;
for (int i = 0; i < KernelSize; i++, n++)
{
// 1 component
new[] { new Vector4(0.862325f, 1.624835f, 0.767583f, 1.862321f) },
// Incrementally compute the range values
float value = n * KernelsScale * (1f / r);
value *= value;
// 2 components
new[]
{
new Vector4(0.886528f, 5.268909f, 0.411259f, -0.548794f),
new Vector4(1.960518f, 1.558213f, 0.513282f, 4.56111f)
},
// 3 components
new[]
{
new Vector4(2.17649f, 5.043495f, 1.621035f, -2.105439f),
new Vector4(1.019306f, 9.027613f, -0.28086f, -0.162882f),
new Vector4(2.81511f, 1.597273f, -0.366471f, 10.300301f)
},
// 4 components
new[]
{
new Vector4(4.338459f, 1.553635f, -5.767909f, 46.164397f),
new Vector4(3.839993f, 4.693183f, 9.795391f, -15.227561f),
new Vector4(2.791880f, 8.178137f, -3.048324f, 0.302959f),
new Vector4(1.342190f, 12.328289f, 0.010001f, 0.244650f)
},
// 5 components
new[]
{
new Vector4(4.892608f, 1.685979f, -22.356787f, 85.91246f),
new Vector4(4.71187f, 4.998496f, 35.918936f, -28.875618f),
new Vector4(4.052795f, 8.244168f, -13.212253f, -1.578428f),
new Vector4(2.929212f, 11.900859f, 0.507991f, 1.816328f),
new Vector4(1.512961f, 16.116382f, 0.138051f, -0.01f)
},
// 6 components
new[]
{
new Vector4(5.143778f, 2.079813f, -82.326596f, 111.231024f),
new Vector4(5.612426f, 6.153387f, 113.878661f, 58.004879f),
new Vector4(5.982921f, 9.802895f, 39.479083f, -162.028887f),
new Vector4(6.505167f, 11.059237f, -71.286026f, 95.027069f),
new Vector4(3.869579f, 14.81052f, 1.405746f, -3.704914f),
new Vector4(2.201904f, 19.032909f, -0.152784f, -0.107988f)
}
};
/// <summary>
/// Gets the kernel parameters and scaling factor for the current count value in the current instance.
/// </summary>
private (Vector4[] Parameters, float Scale) GetParameters()
{
// Prepare the kernel components
int index = Math.Max(0, Math.Min(ComponentsCount - 1, KernelComponents.Count));
return (KernelComponents[index], KernelScales[index]);
// Fill in the complex kernel values
Unsafe.Add(ref baseRef, i) = new Complex64(
MathF.Exp(-a * value) * MathF.Cos(b * value),
MathF.Exp(-a * value) * MathF.Sin(b * value));
}
/// <summary>
/// Creates the collection of complex 1D kernels with the specified parameters.
/// </summary>
private Complex64[][] CreateComplexKernels()
return kernel;
}
/// <summary>
/// Normalizes the kernels with respect to A * real + B * imaginary.
/// </summary>
private void NormalizeKernels()
{
// Calculate the complex weighted sum
float total = 0;
Span<Complex64[]> kernelsSpan = Kernels.AsSpan();
ref Complex64[] baseKernelsRef = ref MemoryMarshal.GetReference(kernelsSpan);
ref Vector4 baseParamsRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
for (int i = 0; i < KernelParameters.Length; i++)
{
var kernels = new Complex64[KernelParameters.Length][];
ref Vector4 baseRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
for (int i = 0; i < KernelParameters.Length; i++)
ref Complex64[] kernelRef = ref Unsafe.Add(ref baseKernelsRef, i);
int length = kernelRef.Length;
ref Complex64 valueRef = ref kernelRef[0];
ref Vector4 paramsRef = ref Unsafe.Add(ref baseParamsRef, i);
for (int j = 0; j < length; j++)
{
ref Vector4 paramsRef = ref Unsafe.Add(ref baseRef, i);
kernels[i] = CreateComplex1DKernel(paramsRef.X, paramsRef.Y);
}
return kernels;
}
/// <summary>
/// Creates a complex 1D kernel with the specified parameters.
/// </summary>
/// <param name="a">The exponential parameter for each complex component.</param>
/// <param name="b">The angle component for each complex component.</param>
private Complex64[] CreateComplex1DKernel(float a, float b)
{
var kernel = new Complex64[KernelSize];
ref Complex64 baseRef = ref MemoryMarshal.GetReference(kernel.AsSpan());
int r = Radius, n = -r;
for (int i = 0; i < KernelSize; i++, n++)
{
// Incrementally compute the range values
float value = n * KernelsScale * (1f / r);
value *= value;
// Fill in the complex kernel values
Unsafe.Add(ref baseRef, i) = new Complex64(
MathF.Exp(-a * value) * MathF.Cos(b * value),
MathF.Exp(-a * value) * MathF.Sin(b * value));
}
return kernel;
}
/// <summary>
/// Normalizes the kernels with respect to A * real + B * imaginary.
/// </summary>
private void NormalizeKernels()
{
// Calculate the complex weighted sum
float total = 0;
Span<Complex64[]> kernelsSpan = Kernels.AsSpan();
ref Complex64[] baseKernelsRef = ref MemoryMarshal.GetReference(kernelsSpan);
ref Vector4 baseParamsRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
for (int i = 0; i < KernelParameters.Length; i++)
{
ref Complex64[] kernelRef = ref Unsafe.Add(ref baseKernelsRef, i);
int length = kernelRef.Length;
ref Complex64 valueRef = ref kernelRef[0];
ref Vector4 paramsRef = ref Unsafe.Add(ref baseParamsRef, i);
for (int j = 0; j < length; j++)
for (int k = 0; k < length; k++)
{
for (int k = 0; k < length; k++)
{
ref Complex64 jRef = ref Unsafe.Add(ref valueRef, j);
ref Complex64 kRef = ref Unsafe.Add(ref valueRef, k);
total +=
paramsRef.Z * (jRef.Real * kRef.Real - jRef.Imaginary * kRef.Imaginary)
+ paramsRef.W * (jRef.Real * kRef.Imaginary + jRef.Imaginary * kRef.Real);
}
}
}
// Normalize the kernels
float scalar = 1f / MathF.Sqrt(total);
for (int i = 0; i < kernelsSpan.Length; i++)
{
ref Complex64[] kernelsRef = ref Unsafe.Add(ref baseKernelsRef, i);
int length = kernelsRef.Length;
ref Complex64 valueRef = ref kernelsRef[0];
for (int j = 0; j < length; j++)
{
Unsafe.Add(ref valueRef, j) *= scalar;
ref Complex64 jRef = ref Unsafe.Add(ref valueRef, j);
ref Complex64 kRef = ref Unsafe.Add(ref valueRef, k);
total +=
paramsRef.Z * (jRef.Real * kRef.Real - jRef.Imaginary * kRef.Imaginary)
+ paramsRef.W * (jRef.Real * kRef.Imaginary + jRef.Imaginary * kRef.Real);
}
}
}
// Normalize the kernels
float scalar = 1f / MathF.Sqrt(total);
for (int i = 0; i < kernelsSpan.Length; i++)
{
ref Complex64[] kernelsRef = ref Unsafe.Add(ref baseKernelsRef, i);
int length = kernelsRef.Length;
ref Complex64 valueRef = ref kernelsRef[0];
for (int j = 0; j < length; j++)
{
Unsafe.Add(ref valueRef, j) *= scalar;
}
}
}
/// <inheritdoc/>
protected override void OnFrameApply(ImageFrame<ImageSharpRgba32> source)
{
if (!source.TryGetSinglePixelSpan(out Span<ImageSharpRgba32> pixelSpan))
{
ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
}
Span<Rgba32> span = MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(pixelSpan);
using ReadWriteTexture2D<Rgba32, Vector4> texture = GraphicsDevice.AllocateReadWriteTexture2D<Rgba32, Vector4>(span, source.Width, source.Height);
using ReadWriteTexture2D<Vector4> temporary = GraphicsDevice.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height, AllocationMode.Clear);
using ReadWriteTexture2D<Vector4> reals = GraphicsDevice.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadWriteTexture2D<Vector4> imaginaries = GraphicsDevice.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadOnlyBuffer<Complex64> kernel = GraphicsDevice.AllocateReadOnlyBuffer<Complex64>(KernelSize);
// Preliminary gamma highlight pass
GraphicsDevice.For<GammaHighlightProcessor>(source.Height, new(texture));
// Perform two 1D convolutions for each component in the current instance
for (int j = 0; j < Kernels.Length; j++)
{
Vector4 parameters = KernelParameters[j];
kernel.CopyFrom(Kernels[j]);
GraphicsDevice.For<VerticalConvolutionProcessor>(
source.Width,
source.Height,
new(texture, reals, imaginaries, kernel));
GraphicsDevice.For<HorizontalConvolutionAndAccumulatePartialsProcessor>(
source.Width,
source.Height,
new(parameters.Z, parameters.W, reals, imaginaries, temporary, kernel));
}
// Apply the inverse gamma exposure pass
GraphicsDevice.For<InverseGammaHighlightProcessor>(source.Height, new(temporary, texture));
// Write the final pixel data
texture.CopyTo(span);
}
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct VerticalConvolutionProcessor : IComputeShader
{
public IReadWriteTexture2D<Vector4> source;
public ReadWriteTexture2D<Vector4> reals;
public ReadWriteTexture2D<Vector4> imaginaries;
public ReadOnlyBuffer<Complex64> kernel;
/// <inheritdoc/>
protected override void OnFrameApply(ImageFrame<ImageSharpRgba32> source)
public void Execute()
{
if (!source.TryGetSinglePixelSpan(out Span<ImageSharpRgba32> pixelSpan))
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int maxY = source.Height;
int maxX = source.Width;
int kernelLength = kernel.Length;
int radiusY = kernelLength >> 1;
for (int i = 0; i < kernelLength; i++)
{
ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX);
Vector4 color = source[offsetX, offsetY];
Complex64 factors = kernel[i];
real += factors.Real * color;
imaginary += factors.Imaginary * color;
}
Span<Rgba32> span = MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(pixelSpan);
using ReadWriteTexture2D<Rgba32, Vector4> texture = GraphicsDevice.AllocateReadWriteTexture2D<Rgba32, Vector4>(span, source.Width, source.Height);
using ReadWriteTexture2D<Vector4> temporary = GraphicsDevice.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height, AllocationMode.Clear);
using ReadWriteTexture2D<Vector4> reals = GraphicsDevice.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadWriteTexture2D<Vector4> imaginaries = GraphicsDevice.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadOnlyBuffer<Complex64> kernel = GraphicsDevice.AllocateReadOnlyBuffer<Complex64>(KernelSize);
// Preliminary gamma highlight pass
GraphicsDevice.For<GammaHighlightProcessor>(source.Height, new(texture));
// Perform two 1D convolutions for each component in the current instance
for (int j = 0; j < Kernels.Length; j++)
{
Vector4 parameters = KernelParameters[j];
kernel.CopyFrom(Kernels[j]);
GraphicsDevice.For<VerticalConvolutionProcessor>(
source.Width,
source.Height,
new(texture, reals, imaginaries, kernel));
GraphicsDevice.For<HorizontalConvolutionAndAccumulatePartialsProcessor>(
source.Width,
source.Height,
new(parameters.Z, parameters.W, reals, imaginaries, temporary, kernel));
}
// Apply the inverse gamma exposure pass
GraphicsDevice.For<InverseGammaHighlightProcessor>(source.Height, new(temporary, texture));
// Write the final pixel data
texture.CopyTo(span);
reals[ThreadIds.XY] = real;
imaginaries[ThreadIds.XY] = imaginary;
}
}
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct VerticalConvolutionProcessor : IComputeShader
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
{
public float z;
public float w;
public ReadWriteTexture2D<Vector4> reals;
public ReadWriteTexture2D<Vector4> imaginaries;
public ReadWriteTexture2D<Vector4> target;
public ReadOnlyBuffer<Complex64> kernel;
/// <inheritdoc/>
public void Execute()
{
public IReadWriteTexture2D<Vector4> source;
public ReadWriteTexture2D<Vector4> reals;
public ReadWriteTexture2D<Vector4> imaginaries;
public ReadOnlyBuffer<Complex64> kernel;
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int maxY = target.Height;
int maxX = target.Width;
int kernelLength = kernel.Length;
int radiusX = kernelLength >> 1;
int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY);
/// <inheritdoc/>
public void Execute()
for (int i = 0; i < kernelLength; i++)
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int maxY = source.Height;
int maxX = source.Width;
int kernelLength = kernel.Length;
int radiusY = kernelLength >> 1;
int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX);
Vector4 sourceReal = reals[offsetX, offsetY];
Vector4 sourceImaginary = imaginaries[offsetX, offsetY];
Complex64 factors = kernel[i];
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX);
Vector4 color = source[offsetX, offsetY];
Complex64 factors = kernel[i];
real += factors.Real * sourceReal - factors.Imaginary * sourceImaginary;
imaginary += factors.Real * sourceImaginary + factors.Imaginary * sourceReal;
}
real += factors.Real * color;
imaginary += factors.Imaginary * color;
}
target[ThreadIds.XY] += real * z + imaginary * w;
}
}
reals[ThreadIds.XY] = real;
imaginaries[ThreadIds.XY] = imaginary;
/// <summary>
/// Kernel for the gamma highlight pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct GammaHighlightProcessor : IComputeShader
{
public readonly IReadWriteTexture2D<Vector4> source;
/// <inheritdoc/>
public void Execute()
{
int width = source.Width;
for (int i = 0; i < width; i++)
{
float4 v = source[i, ThreadIds.X];
v.XYZ = v.XYZ * v.XYZ * v.XYZ;
source[i, ThreadIds.X] = v;
}
}
}
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
/// <summary>
/// Kernel for the inverse gamma highlight pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader
{
public readonly ReadWriteTexture2D<Vector4> source;
public readonly IReadWriteTexture2D<Vector4> target;
/// <inheritdoc/>
public void Execute()
{
public float z;
public float w;
int width = source.Width;
public ReadWriteTexture2D<Vector4> reals;
public ReadWriteTexture2D<Vector4> imaginaries;
public ReadWriteTexture2D<Vector4> target;
public ReadOnlyBuffer<Complex64> kernel;
/// <inheritdoc/>
public void Execute()
for (int i = 0; i < width; i++)
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int maxY = target.Height;
int maxX = target.Width;
int kernelLength = kernel.Length;
int radiusX = kernelLength >> 1;
int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY);
float4 v = source[i, ThreadIds.X];
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX);
Vector4 sourceReal = reals[offsetX, offsetY];
Vector4 sourceImaginary = imaginaries[offsetX, offsetY];
Complex64 factors = kernel[i];
v = Hlsl.Clamp(v, 0, float.MaxValue);
v.XYZ = Hlsl.Pow(v.XYZ, 1 / 3f);
real += factors.Real * sourceReal - factors.Imaginary * sourceImaginary;
imaginary += factors.Real * sourceImaginary + factors.Imaginary * sourceReal;
}
target[ThreadIds.XY] += real * z + imaginary * w;
}
}
/// <summary>
/// Kernel for the gamma highlight pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct GammaHighlightProcessor : IComputeShader
{
public readonly IReadWriteTexture2D<Vector4> source;
/// <inheritdoc/>
public void Execute()
{
int width = source.Width;
for (int i = 0; i < width; i++)
{
float4 v = source[i, ThreadIds.X];
v.XYZ = v.XYZ * v.XYZ * v.XYZ;
source[i, ThreadIds.X] = v;
}
}
}
/// <summary>
/// Kernel for the inverse gamma highlight pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader
{
public readonly ReadWriteTexture2D<Vector4> source;
public readonly IReadWriteTexture2D<Vector4> target;
/// <inheritdoc/>
public void Execute()
{
int width = source.Width;
for (int i = 0; i < width; i++)
{
float4 v = source[i, ThreadIds.X];
v = Hlsl.Clamp(v, 0, float.MaxValue);
v.XYZ = Hlsl.Pow(v.XYZ, 1 / 3f);
target[i, ThreadIds.X] = v;
}
target[i, ThreadIds.X] = v;
}
}
}
+70 -71
ファイルの表示
@@ -5,85 +5,84 @@ using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
namespace ComputeSharp.BokehBlur.Processors;
/// <summary>
/// Defines Gaussian blur by a (Sigma, Radius) pair.
/// </summary>
public sealed partial class HlslGaussianBlurProcessor : IImageProcessor
{
/// <summary>
/// Defines Gaussian blur by a (Sigma, Radius) pair.
/// The default value for <see cref="Sigma"/>.
/// </summary>
public sealed partial class HlslGaussianBlurProcessor : IImageProcessor
public const float DefaultSigma = 3f;
/// <summary>
/// Initializes a new instance of the <see cref="HlslGaussianBlurProcessor"/> class.
/// </summary>
public HlslGaussianBlurProcessor()
: this(Gpu.Default, DefaultSigma, 9)
{
/// <summary>
/// The default value for <see cref="Sigma"/>.
/// </summary>
public const float DefaultSigma = 3f;
}
/// <summary>
/// Initializes a new instance of the <see cref="HlslGaussianBlurProcessor"/> class.
/// </summary>
public HlslGaussianBlurProcessor()
: this(Gpu.Default, DefaultSigma, 9)
/// <summary>
/// Initializes a new instance of the <see cref="HlslGaussianBlurProcessor"/> class.
/// </summary>
/// <param name="radius">The radius value representing the size of the area to sample.</param>
public HlslGaussianBlurProcessor(int radius)
: this(Gpu.Default, radius / 3F, radius)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HlslGaussianBlurProcessor"/> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
/// <param name="radius">The radius value representing the size of the area to sample.</param>
public HlslGaussianBlurProcessor(GraphicsDevice device, int radius)
: this(device, radius / 3F, radius)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HlslGaussianBlurProcessor"/> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
/// <param name="sigma"> The sigma value representing the weight of the blur. </param>
/// <param name="radius">The radius value representing the size of the area to sample (this should be at least twice the sigma value)</param>
public HlslGaussianBlurProcessor(GraphicsDevice device, float sigma, int radius)
{
GraphicsDevice = device;
Sigma = sigma;
Radius = radius;
}
/// <summary>
/// The <see cref="ComputeSharp.GraphicsDevice"/> instance in use.
/// </summary>
private readonly GraphicsDevice GraphicsDevice;
/// <summary>
/// Gets the sigma value representing the weight of the blur.
/// </summary>
public float Sigma { get; }
/// <summary>
/// Gets the radius defining the size of the area to sample.
/// </summary>
public int Radius { get; }
/// <inheritdoc />
public IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
where TPixel : unmanaged, IPixel<TPixel>
{
if (typeof(TPixel) != typeof(ImageSharpRgba32))
{
ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
}
/// <summary>
/// Initializes a new instance of the <see cref="HlslGaussianBlurProcessor"/> class.
/// </summary>
/// <param name="radius">The radius value representing the size of the area to sample.</param>
public HlslGaussianBlurProcessor(int radius)
: this(Gpu.Default, radius / 3F, radius)
{
}
var processor = new Implementation(this, configuration, Unsafe.As<Image<ImageSharpRgba32>>(source), sourceRectangle);
/// <summary>
/// Initializes a new instance of the <see cref="HlslGaussianBlurProcessor"/> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
/// <param name="radius">The radius value representing the size of the area to sample.</param>
public HlslGaussianBlurProcessor(GraphicsDevice device, int radius)
: this(device, radius / 3F, radius)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HlslGaussianBlurProcessor"/> class.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
/// <param name="sigma"> The sigma value representing the weight of the blur. </param>
/// <param name="radius">The radius value representing the size of the area to sample (this should be at least twice the sigma value)</param>
public HlslGaussianBlurProcessor(GraphicsDevice device, float sigma, int radius)
{
GraphicsDevice = device;
Sigma = sigma;
Radius = radius;
}
/// <summary>
/// The <see cref="ComputeSharp.GraphicsDevice"/> instance in use.
/// </summary>
private readonly GraphicsDevice GraphicsDevice;
/// <summary>
/// Gets the sigma value representing the weight of the blur.
/// </summary>
public float Sigma { get; }
/// <summary>
/// Gets the radius defining the size of the area to sample.
/// </summary>
public int Radius { get; }
/// <inheritdoc />
public IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
where TPixel : unmanaged, IPixel<TPixel>
{
if (typeof(TPixel) != typeof(ImageSharpRgba32))
{
ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
}
var processor = new Implementation(this, configuration, Unsafe.As<Image<ImageSharpRgba32>>(source), sourceRectangle);
return Unsafe.As<IImageProcessor<TPixel>>(processor);
}
return Unsafe.As<IImageProcessor<TPixel>>(processor);
}
}
+136 -137
ファイルの表示
@@ -7,172 +7,171 @@ using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
namespace ComputeSharp.BokehBlur.Processors;
/// <inheritdoc/>
public sealed partial class HlslGaussianBlurProcessor
{
/// <inheritdoc/>
public sealed partial class HlslGaussianBlurProcessor
/// <summary>
/// Applies Gaussian blur processing to an image.
/// </summary>
internal sealed partial class Implementation : ImageProcessor<ImageSharpRgba32>
{
/// <summary>
/// Applies Gaussian blur processing to an image.
/// The <see cref="ComputeSharp.GraphicsDevice"/> instance in use.
/// </summary>
internal sealed partial class Implementation : ImageProcessor<ImageSharpRgba32>
private readonly GraphicsDevice GraphicsDevice;
/// <summary>
/// The 1D kernel to apply.
/// </summary>
private readonly float[] Kernel;
/// <summary>
/// Initializes a new instance of the <see cref="Implementation"/> class.
/// </summary>
/// <param name="definition">The <see cref="Implementation"/> defining the processor parameters.</param>
/// <param name="configuration">The configuration which allows altering default behaviour or extending the library.</param>
/// <param name="source">The source <see cref="Image{TPixel}"/> for the current processor instance.</param>
/// <param name="sourceRectangle">The source area to process for the current processor instance.</param>
public Implementation(HlslGaussianBlurProcessor definition, Configuration configuration, Image<ImageSharpRgba32> source, Rectangle sourceRectangle)
: base(configuration, source, sourceRectangle)
{
/// <summary>
/// The <see cref="ComputeSharp.GraphicsDevice"/> instance in use.
/// </summary>
private readonly GraphicsDevice GraphicsDevice;
int kernelSize = definition.Radius * 2 + 1;
/// <summary>
/// The 1D kernel to apply.
/// </summary>
private readonly float[] Kernel;
GraphicsDevice = definition.GraphicsDevice;
Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma);
}
/// <summary>
/// Initializes a new instance of the <see cref="Implementation"/> class.
/// </summary>
/// <param name="definition">The <see cref="Implementation"/> defining the processor parameters.</param>
/// <param name="configuration">The configuration which allows altering default behaviour or extending the library.</param>
/// <param name="source">The source <see cref="Image{TPixel}"/> for the current processor instance.</param>
/// <param name="sourceRectangle">The source area to process for the current processor instance.</param>
public Implementation(HlslGaussianBlurProcessor definition, Configuration configuration, Image<ImageSharpRgba32> source, Rectangle sourceRectangle)
: base(configuration, source, sourceRectangle)
/// <summary>
/// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function.
/// </summary>
private static float[] CreateGaussianBlurKernel(int size, float weight)
{
float[] kernel = new float[size];
ref float rKernel = ref kernel[0];
float sum = 0F;
float midpoint = (size - 1) / 2F;
for (int i = 0; i < size; i++)
{
int kernelSize = definition.Radius * 2 + 1;
GraphicsDevice = definition.GraphicsDevice;
Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma);
float x = i - midpoint;
float gx = Gaussian(x, weight);
sum += gx;
Unsafe.Add(ref rKernel, i) = gx;
}
/// <summary>
/// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function.
/// </summary>
private static float[] CreateGaussianBlurKernel(int size, float weight)
// Normalize kernel so that the sum of all weights equals 1
for (int i = 0; i < size; i++)
{
float[] kernel = new float[size];
ref float rKernel = ref kernel[0];
float sum = 0F;
float midpoint = (size - 1) / 2F;
for (int i = 0; i < size; i++)
{
float x = i - midpoint;
float gx = Gaussian(x, weight);
sum += gx;
Unsafe.Add(ref rKernel, i) = gx;
}
// Normalize kernel so that the sum of all weights equals 1
for (int i = 0; i < size; i++)
{
Unsafe.Add(ref rKernel, i) /= sum;
}
return kernel;
Unsafe.Add(ref rKernel, i) /= sum;
}
/// <summary>
/// Implementation of 1D Gaussian G(x) function.
/// </summary>
/// <param name="x">The x provided to G(x)</param>
/// <param name="sigma">The spread of the blur.</param>
/// <returns>The Gaussian G(x)</returns>
private static float Gaussian(float x, float sigma)
return kernel;
}
/// <summary>
/// Implementation of 1D Gaussian G(x) function.
/// </summary>
/// <param name="x">The x provided to G(x)</param>
/// <param name="sigma">The spread of the blur.</param>
/// <returns>The Gaussian G(x)</returns>
private static float Gaussian(float x, float sigma)
{
const float Numerator = 1.0f;
float denominator = MathF.Sqrt(2 * MathF.PI) * sigma;
float exponentNumerator = -x * x;
float exponentDenominator = 2 * sigma * sigma;
float left = Numerator / denominator;
float right = MathF.Exp(exponentNumerator / exponentDenominator);
return left * right;
}
/// <inheritdoc/>
protected override void OnFrameApply(ImageFrame<ImageSharpRgba32> source)
{
if (!source.TryGetSinglePixelSpan(out Span<ImageSharpRgba32> pixelSpan))
{
const float Numerator = 1.0f;
float denominator = MathF.Sqrt(2 * MathF.PI) * sigma;
float exponentNumerator = -x * x;
float exponentDenominator = 2 * sigma * sigma;
float left = Numerator / denominator;
float right = MathF.Exp(exponentNumerator / exponentDenominator);
return left * right;
ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
}
Span<Rgba32> span = MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(pixelSpan);
using ReadWriteTexture2D<Rgba32, Vector4> sourceTexture = GraphicsDevice.AllocateReadWriteTexture2D<Rgba32, Vector4>(span, source.Width, source.Height);
using ReadWriteTexture2D<Rgba32, Vector4> firstPassTexture = GraphicsDevice.AllocateReadWriteTexture2D<Rgba32, Vector4>(source.Width, source.Height);
using ReadOnlyBuffer<float> kernelBuffer = GraphicsDevice.AllocateReadOnlyBuffer(Kernel);
GraphicsDevice.For<VerticalConvolutionProcessor>(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer));
GraphicsDevice.For<HorizontalConvolutionProcessor>(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer));
sourceTexture.CopyTo(span);
}
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
{
public readonly IReadWriteTexture2D<Vector4> source;
public readonly IReadWriteTexture2D<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
protected override void OnFrameApply(ImageFrame<ImageSharpRgba32> source)
public void Execute()
{
if (!source.TryGetSinglePixelSpan(out Span<ImageSharpRgba32> pixelSpan))
Vector4 result = Vector4.Zero;
int maxY = source.Height - 1;
int maxX = source.Width - 1;
int kernelLength = kernel.Length;
int radiusY = kernelLength >> 1;
for (int i = 0; i < kernelLength; i++)
{
ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX);
Vector4 color = source[offsetX, offsetY];
result += kernel[i] * color;
}
Span<Rgba32> span = MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(pixelSpan);
using ReadWriteTexture2D<Rgba32, Vector4> sourceTexture = GraphicsDevice.AllocateReadWriteTexture2D<Rgba32, Vector4>(span, source.Width, source.Height);
using ReadWriteTexture2D<Rgba32, Vector4> firstPassTexture = GraphicsDevice.AllocateReadWriteTexture2D<Rgba32, Vector4>(source.Width, source.Height);
using ReadOnlyBuffer<float> kernelBuffer = GraphicsDevice.AllocateReadOnlyBuffer(Kernel);
GraphicsDevice.For<VerticalConvolutionProcessor>(source.Width, source.Height, new(sourceTexture, firstPassTexture, kernelBuffer));
GraphicsDevice.For<HorizontalConvolutionProcessor>(source.Width, source.Height, new(firstPassTexture, sourceTexture, kernelBuffer));
sourceTexture.CopyTo(span);
target[ThreadIds.XY] = result;
}
}
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
{
public readonly IReadWriteTexture2D<Vector4> source;
public readonly IReadWriteTexture2D<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute()
{
public readonly IReadWriteTexture2D<Vector4> source;
public readonly IReadWriteTexture2D<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
Vector4 result = Vector4.Zero;
int maxY = source.Height - 1;
int maxX = source.Width - 1;
int kernelLength = kernel.Length;
int radiusX = kernelLength >> 1;
int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY);
/// <inheritdoc/>
public void Execute()
for (int i = 0; i < kernelLength; i++)
{
Vector4 result = Vector4.Zero;
int maxY = source.Height - 1;
int maxX = source.Width - 1;
int kernelLength = kernel.Length;
int radiusY = kernelLength >> 1;
int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX);
Vector4 color = source[offsetX, offsetY];
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ThreadIds.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(ThreadIds.X, 0, maxX);
Vector4 color = source[offsetX, offsetY];
result += kernel[i] * color;
}
target[ThreadIds.XY] = result;
result += kernel[i] * color;
}
}
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
{
public readonly IReadWriteTexture2D<Vector4> source;
public readonly IReadWriteTexture2D<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute()
{
Vector4 result = Vector4.Zero;
int maxY = source.Height - 1;
int maxX = source.Width - 1;
int kernelLength = kernel.Length;
int radiusX = kernelLength >> 1;
int offsetY = Hlsl.Clamp(ThreadIds.Y, 0, maxY);
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(ThreadIds.X + i - radiusX, 0, maxX);
Vector4 color = source[offsetX, offsetY];
result += kernel[i] * color;
}
target[ThreadIds.XY] = result;
}
target[ThreadIds.XY] = result;
}
}
}
+21 -22
ファイルの表示
@@ -7,32 +7,31 @@ using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.ImageProcessing
namespace ComputeSharp.ImageProcessing;
class Program
{
class Program
static void Main()
{
static void Main()
Console.WriteLine(">> Loading image");
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "city.jpg");
using Image<ImageSharpRgba32> image = Image.Load<ImageSharpRgba32>(path);
// Apply a series of processors and save the results
foreach (var effect in new (string Name, IImageProcessor Processor)[]
{
Console.WriteLine(">> Loading image");
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "city.jpg");
using Image<ImageSharpRgba32> image = Image.Load<ImageSharpRgba32>(path);
("bokeh", new HlslBokehBlurProcessor(80, 2)),
("gaussian", new HlslGaussianBlurProcessor(80))
})
{
Console.WriteLine($">> Applying {effect.Name}");
using Image copy = image.Clone(c => c.ApplyProcessor(effect.Processor));
// Apply a series of processors and save the results
foreach (var effect in new (string Name, IImageProcessor Processor)[]
{
("bokeh", new HlslBokehBlurProcessor(80, 2)),
("gaussian", new HlslGaussianBlurProcessor(80))
})
{
Console.WriteLine($">> Applying {effect.Name}");
using Image copy = image.Clone(c => c.ApplyProcessor(effect.Processor));
Console.WriteLine($">> Saving {effect.Name} to disk");
string targetPath = Path.Combine(
Path.GetRelativePath(Path.GetDirectoryName(path)!, @"..\..\..\"),
$"{Path.GetFileNameWithoutExtension(path)}_{effect.Name}{Path.GetExtension(path)}");
copy.Save(targetPath);
}
Console.WriteLine($">> Saving {effect.Name} to disk");
string targetPath = Path.Combine(
Path.GetRelativePath(Path.GetDirectoryName(path)!, @"..\..\..\"),
$"{Path.GetFileNameWithoutExtension(path)}_{effect.Name}{Path.GetExtension(path)}");
copy.Save(targetPath);
}
}
}
+13 -14
ファイルの表示
@@ -1,17 +1,16 @@
namespace ComputeSharp.Sample.FSharp.Shaders
{
/// <summary>
/// A sample shader thaat just multiplies items in a buffer by two.
/// </summary>
[AutoConstructor]
public readonly partial struct MultiplyByTwo : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
namespace ComputeSharp.Sample.FSharp.Shaders;
/// <inheritdoc/>
public void Execute()
{
buffer[ThreadIds.X] *= 2;
}
/// <summary>
/// A sample shader thaat just multiplies items in a buffer by two.
/// </summary>
[AutoConstructor]
public readonly partial struct MultiplyByTwo : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
buffer[ThreadIds.X] *= 2;
}
}
+60 -62
ファイルの表示
@@ -2,71 +2,69 @@
using System.Globalization;
using System.Linq;
namespace ComputeSharp.Sample
namespace ComputeSharp.Sample;
partial class Program
{
partial class Program
static void Main()
{
static void Main()
float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray();
// Create the graphics buffer
using ReadWriteBuffer<float> gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array);
// Run the shader
Gpu.Default.For(100, new MainKernel(gpuBuffer));
// Print the initial matrix
PrintMatrix(array, 10, 10, "BEFORE");
// Get the data back
gpuBuffer.CopyTo(array);
// Print the updated matrix
PrintMatrix(array, 10, 10, "AFTER");
}
/// <summary>
/// Kernel for <see cref="Main"/>.
/// </summary>
[AutoConstructor]
internal readonly partial struct MainKernel : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
float[] array = Enumerable.Range(1, 100).Select(static i => (float)i).ToArray();
// Create the graphics buffer
using ReadWriteBuffer<float> gpuBuffer = Gpu.Default.AllocateReadWriteBuffer(array);
// Run the shader
Gpu.Default.For(100, new MainKernel(gpuBuffer));
// Print the initial matrix
PrintMatrix(array, 10, 10, "BEFORE");
// Get the data back
gpuBuffer.CopyTo(array);
// Print the updated matrix
PrintMatrix(array, 10, 10, "AFTER");
}
/// <summary>
/// Kernel for <see cref="Main"/>.
/// </summary>
[AutoConstructor]
internal readonly partial struct MainKernel : IComputeShader
{
public readonly ReadWriteBuffer<float> buffer;
/// <inheritdoc/>
public void Execute()
{
buffer[ThreadIds.X] *= 2;
}
}
/// <summary>
/// Prints a matrix in a properly formatted way.
/// </summary>
/// <param name="array">The input <see langword="float"/> array representing the matrix to print.</param>
/// <param name="width">The width of the array to print.</param>
/// <param name="height">The height of the array to print.</param>
/// <param name="name">The name of the matrix to print.</param>
private static void PrintMatrix(float[] array, int width, int height, string name)
{
int pad = 48 - name.Length;
string title = $"{new string('=', pad / 2)} {name} {new string('=', (pad + 1) / 2)}";
Console.WriteLine(title);
int numberWidth = Math.Max(array.Max().ToString(CultureInfo.InvariantCulture).Length, 4);
for (int i = 0; i < height; i++)
{
var row = array[(i * width)..((i + 1) * width)];
var text = string.Join(",", row.Select(x => x.ToString(CultureInfo.InvariantCulture).PadLeft(numberWidth)));
Console.WriteLine(text);
}
Console.WriteLine(new string('=', 50));
buffer[ThreadIds.X] *= 2;
}
}
}
/// <summary>
/// Prints a matrix in a properly formatted way.
/// </summary>
/// <param name="array">The input <see langword="float"/> array representing the matrix to print.</param>
/// <param name="width">The width of the array to print.</param>
/// <param name="height">The height of the array to print.</param>
/// <param name="name">The name of the matrix to print.</param>
private static void PrintMatrix(float[] array, int width, int height, string name)
{
int pad = 48 - name.Length;
string title = $"{new string('=', pad / 2)} {name} {new string('=', (pad + 1) / 2)}";
Console.WriteLine(title);
int numberWidth = Math.Max(array.Max().ToString(CultureInfo.InvariantCulture).Length, 4);
for (int i = 0; i < height; i++)
{
var row = array[(i * width)..((i + 1) * width)];
var text = string.Join(",", row.Select(x => x.ToString(CultureInfo.InvariantCulture).PadLeft(numberWidth)));
Console.WriteLine(text);
}
Console.WriteLine(new string('=', 50));
}
}
+255 -256
ファイルの表示
@@ -3,301 +3,300 @@ using ComputeSharp.Interop;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
namespace ComputeSharp.SwapChain.Backend
namespace ComputeSharp.SwapChain.Backend;
internal sealed class SwapChainApplication<T> : Win32Application
where T : struct, IPixelShader<float4>
{
internal sealed class SwapChainApplication<T> : Win32Application
where T : struct, IPixelShader<float4>
/// <summary>
/// The <see cref="Func{T1, TResult}"/> instance used to create shaders to run.
/// </summary>
private readonly Func<TimeSpan, T> shaderFactory;
/// <summary>
/// The <see cref="ID3D12Device"/> pointer for the device currently in use.
/// </summary>
private ComPtr<ID3D12Device> d3D12Device;
/// <summary>
/// The <see cref="ID3D12CommandQueue"/> instance to use for graphics operations.
/// </summary>
private ComPtr<ID3D12CommandQueue> d3D12CommandQueue;
/// <summary>
/// The <see cref="ID3D12Fence"/> instance used for graphics operations.
/// </summary>
private ComPtr<ID3D12Fence> d3D12Fence;
/// <summary>
/// The next fence value for graphics operations using <see cref="d3D12CommandQueue"/>.
/// </summary>
private ulong nextD3D12FenceValue = 1;
/// <summary>
/// The <see cref="ID3D12CommandAllocator"/> object to create command lists.
/// </summary>
private ComPtr<ID3D12CommandAllocator> d3D12CommandAllocator;
/// <summary>
/// The <see cref="ID3D12GraphicsCommandList"/> instance used to copy data to the back buffers.
/// </summary>
private ComPtr<ID3D12GraphicsCommandList> d3D12GraphicsCommandList;
/// <summary>
/// The <see cref="IDXGISwapChain1"/> instance used to display content onto the target window.
/// </summary>
private ComPtr<IDXGISwapChain1> dxgiSwapChain1;
/// <summary>
/// The first buffer within <see cref="dxgiSwapChain1"/>.
/// </summary>
private ComPtr<ID3D12Resource> d3D12Resource0;
/// <summary>
/// The second buffer within <see cref="dxgiSwapChain1"/>.
/// </summary>
private ComPtr<ID3D12Resource> d3D12Resource1;
/// <summary>
/// The index of the next buffer that can be used to present content.
/// </summary>
private uint currentBufferIndex;
/// <summary>
/// The <see cref="ReadWriteTexture2D{T, TPixel}"/> instance used to prepare frames to display.
/// </summary>
private ReadWriteTexture2D<Rgba32, float4>? texture;
/// <summary>
/// Whether or not the window has been resized and requires the buffers to be updated.
/// </summary>
private bool isResizePending;
/// <summary>
/// Creates a new <see cref="SwapChainApplication"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderFactory">The <see cref="Func{T1, TResult}"/> instance used to create shaders to run.</param>
public SwapChainApplication(Func<TimeSpan, T> shaderFactory)
{
/// <summary>
/// The <see cref="Func{T1, TResult}"/> instance used to create shaders to run.
/// </summary>
private readonly Func<TimeSpan, T> shaderFactory;
this.shaderFactory = shaderFactory;
}
/// <summary>
/// The <see cref="ID3D12Device"/> pointer for the device currently in use.
/// </summary>
private ComPtr<ID3D12Device> d3D12Device;
/// <summary>
/// The <see cref="ID3D12CommandQueue"/> instance to use for graphics operations.
/// </summary>
private ComPtr<ID3D12CommandQueue> d3D12CommandQueue;
/// <summary>
/// The <see cref="ID3D12Fence"/> instance used for graphics operations.
/// </summary>
private ComPtr<ID3D12Fence> d3D12Fence;
/// <summary>
/// The next fence value for graphics operations using <see cref="d3D12CommandQueue"/>.
/// </summary>
private ulong nextD3D12FenceValue = 1;
/// <summary>
/// The <see cref="ID3D12CommandAllocator"/> object to create command lists.
/// </summary>
private ComPtr<ID3D12CommandAllocator> d3D12CommandAllocator;
/// <summary>
/// The <see cref="ID3D12GraphicsCommandList"/> instance used to copy data to the back buffers.
/// </summary>
private ComPtr<ID3D12GraphicsCommandList> d3D12GraphicsCommandList;
/// <summary>
/// The <see cref="IDXGISwapChain1"/> instance used to display content onto the target window.
/// </summary>
private ComPtr<IDXGISwapChain1> dxgiSwapChain1;
/// <summary>
/// The first buffer within <see cref="dxgiSwapChain1"/>.
/// </summary>
private ComPtr<ID3D12Resource> d3D12Resource0;
/// <summary>
/// The second buffer within <see cref="dxgiSwapChain1"/>.
/// </summary>
private ComPtr<ID3D12Resource> d3D12Resource1;
/// <summary>
/// The index of the next buffer that can be used to present content.
/// </summary>
private uint currentBufferIndex;
/// <summary>
/// The <see cref="ReadWriteTexture2D{T, TPixel}"/> instance used to prepare frames to display.
/// </summary>
private ReadWriteTexture2D<Rgba32, float4>? texture;
/// <summary>
/// Whether or not the window has been resized and requires the buffers to be updated.
/// </summary>
private bool isResizePending;
/// <summary>
/// Creates a new <see cref="SwapChainApplication"/> instance with the specified parameters.
/// </summary>
/// <param name="shaderFactory">The <see cref="Func{T1, TResult}"/> instance used to create shaders to run.</param>
public SwapChainApplication(Func<TimeSpan, T> shaderFactory)
/// <inheritdoc/>
public override unsafe void OnInitialize(HWND hwnd)
{
// Get the underlying ID3D12Device in use
fixed (ID3D12Device** d3D12Device = this.d3D12Device)
{
this.shaderFactory = shaderFactory;
_ = InteropServices.TryGetID3D12Device(Gpu.Default, FX.__uuidof<ID3D12Device>(), (void**)d3D12Device);
}
/// <inheritdoc/>
public override unsafe void OnInitialize(HWND hwnd)
// Create the direct command queue to use
fixed (ID3D12CommandQueue** d3D12CommandQueue = this.d3D12CommandQueue)
{
// Get the underlying ID3D12Device in use
fixed (ID3D12Device** d3D12Device = this.d3D12Device)
{
_ = InteropServices.TryGetID3D12Device(Gpu.Default, FX.__uuidof<ID3D12Device>(), (void**)d3D12Device);
}
D3D12_COMMAND_QUEUE_DESC d3D12CommandQueueDesc;
d3D12CommandQueueDesc.Type = D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT;
d3D12CommandQueueDesc.Priority = (int)D3D12_COMMAND_QUEUE_PRIORITY.D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
d3D12CommandQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAGS.D3D12_COMMAND_QUEUE_FLAG_NONE;
d3D12CommandQueueDesc.NodeMask = 0;
// Create the direct command queue to use
fixed (ID3D12CommandQueue** d3D12CommandQueue = this.d3D12CommandQueue)
{
D3D12_COMMAND_QUEUE_DESC d3D12CommandQueueDesc;
d3D12CommandQueueDesc.Type = D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT;
d3D12CommandQueueDesc.Priority = (int)D3D12_COMMAND_QUEUE_PRIORITY.D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
d3D12CommandQueueDesc.Flags = D3D12_COMMAND_QUEUE_FLAGS.D3D12_COMMAND_QUEUE_FLAG_NONE;
d3D12CommandQueueDesc.NodeMask = 0;
_ = d3D12Device.Get()->CreateCommandQueue(
&d3D12CommandQueueDesc,
FX.__uuidof<ID3D12CommandQueue>(),
(void**)d3D12CommandQueue);
}
// Create the direct fence
fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence)
{
_ = this.d3D12Device.Get()->CreateFence(
0,
D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE,
FX.__uuidof<ID3D12Fence>(),
(void**)d3D12Fence);
}
// Create the swap chain to display frames
fixed (IDXGISwapChain1** dxgiSwapChain1 = this.dxgiSwapChain1)
{
using ComPtr<IDXGIFactory2> dxgiFactory2 = default;
_ = FX.CreateDXGIFactory2(FX.DXGI_CREATE_FACTORY_DEBUG, FX.__uuidof<IDXGIFactory2>(), (void**)dxgiFactory2.GetAddressOf());
DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default;
dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE;
dxgiSwapChainDesc1.BufferCount = 2;
dxgiSwapChainDesc1.Flags = 0;
dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM;
dxgiSwapChainDesc1.Width = 0;
dxgiSwapChainDesc1.Height = 0;
dxgiSwapChainDesc1.SampleDesc = new DXGI_SAMPLE_DESC(count: 1, quality: 0);
dxgiSwapChainDesc1.Scaling = DXGI_SCALING.DXGI_SCALING_STRETCH;
dxgiSwapChainDesc1.Stereo = 0;
dxgiSwapChainDesc1.SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
_ = dxgiFactory2.Get()->CreateSwapChainForHwnd(
(IUnknown*)d3D12CommandQueue.Get(),
hwnd,
&dxgiSwapChainDesc1,
null,
null,
dxgiSwapChain1);
}
// Create the command allocator to use
fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator)
{
this.d3D12Device.Get()->CreateCommandAllocator(
D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
FX.__uuidof<ID3D12CommandAllocator>(),
(void**)d3D12CommandAllocator);
}
// Create the reusable command list to copy data to the back buffers
fixed (ID3D12GraphicsCommandList** d3D12GraphicsCommandList = this.d3D12GraphicsCommandList)
{
this.d3D12Device.Get()->CreateCommandList(
0,
D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
d3D12CommandAllocator,
null,
FX.__uuidof<ID3D12GraphicsCommandList>(),
(void**)d3D12GraphicsCommandList);
}
// Close the command list to prepare it for future use
this.d3D12GraphicsCommandList.Get()->Close();
_ = d3D12Device.Get()->CreateCommandQueue(
&d3D12CommandQueueDesc,
FX.__uuidof<ID3D12CommandQueue>(),
(void**)d3D12CommandQueue);
}
/// <inheritdoc/>
public override unsafe void OnResize()
// Create the direct fence
fixed (ID3D12Fence** d3D12Fence = this.d3D12Fence)
{
this.isResizePending = true;
_ = this.d3D12Device.Get()->CreateFence(
0,
D3D12_FENCE_FLAGS.D3D12_FENCE_FLAG_NONE,
FX.__uuidof<ID3D12Fence>(),
(void**)d3D12Fence);
}
/// <summary>
/// Applies the actual resize logic that was scheduled from <see cref="OnResize"/>.
/// </summary>
private unsafe void ApplyResize()
// Create the swap chain to display frames
fixed (IDXGISwapChain1** dxgiSwapChain1 = this.dxgiSwapChain1)
{
this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue);
using ComPtr<IDXGIFactory2> dxgiFactory2 = default;
// Wait for the fence again to ensure there are no pending operations
this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default);
_ = FX.CreateDXGIFactory2(FX.DXGI_CREATE_FACTORY_DEBUG, FX.__uuidof<IDXGIFactory2>(), (void**)dxgiFactory2.GetAddressOf());
this.nextD3D12FenceValue++;
DXGI_SWAP_CHAIN_DESC1 dxgiSwapChainDesc1 = default;
dxgiSwapChainDesc1.AlphaMode = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE;
dxgiSwapChainDesc1.BufferCount = 2;
dxgiSwapChainDesc1.Flags = 0;
dxgiSwapChainDesc1.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM;
dxgiSwapChainDesc1.Width = 0;
dxgiSwapChainDesc1.Height = 0;
dxgiSwapChainDesc1.SampleDesc = new DXGI_SAMPLE_DESC(count: 1, quality: 0);
dxgiSwapChainDesc1.Scaling = DXGI_SCALING.DXGI_SCALING_STRETCH;
dxgiSwapChainDesc1.Stereo = 0;
dxgiSwapChainDesc1.SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
// Dispose the old buffers before resizing the buffer
this.d3D12Resource0.Dispose();
this.d3D12Resource1.Dispose();
// Resize the swap chain buffers
this.dxgiSwapChain1.Get()->ResizeBuffers(0, 0, 0, DXGI_FORMAT.DXGI_FORMAT_UNKNOWN, 0);
// Get the index of the initial back buffer
using (ComPtr<IDXGISwapChain3> dxgiSwapChain3 = default)
{
_ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf());
this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex();
}
// Retrieve the back buffers for the swap chain
fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0)
fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1)
{
_ = dxgiSwapChain1.Get()->GetBuffer(0, FX.__uuidof<ID3D12Resource>(), (void**)d3D12Resource0);
_ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof<ID3D12Resource>(), (void**)d3D12Resource1);
}
this.texture?.Dispose();
D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc();
// Create the 2D texture to use to generate frames to display
this.texture = Gpu.Default.AllocateReadWriteTexture2D<Rgba32, float4>(
(int)d3D12Resource0Description.Width,
(int)d3D12Resource0Description.Height);
_ = dxgiFactory2.Get()->CreateSwapChainForHwnd(
(IUnknown*)d3D12CommandQueue.Get(),
hwnd,
&dxgiSwapChainDesc1,
null,
null,
dxgiSwapChain1);
}
/// <inheritdoc/>
public override unsafe void OnUpdate(TimeSpan time)
// Create the command allocator to use
fixed (ID3D12CommandAllocator** d3D12CommandAllocator = this.d3D12CommandAllocator)
{
if (this.isResizePending)
{
ApplyResize();
this.d3D12Device.Get()->CreateCommandAllocator(
D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
FX.__uuidof<ID3D12CommandAllocator>(),
(void**)d3D12CommandAllocator);
}
this.isResizePending = false;
}
// Create the reusable command list to copy data to the back buffers
fixed (ID3D12GraphicsCommandList** d3D12GraphicsCommandList = this.d3D12GraphicsCommandList)
{
this.d3D12Device.Get()->CreateCommandList(
0,
D3D12_COMMAND_LIST_TYPE.D3D12_COMMAND_LIST_TYPE_DIRECT,
d3D12CommandAllocator,
null,
FX.__uuidof<ID3D12GraphicsCommandList>(),
(void**)d3D12GraphicsCommandList);
}
// Generate the new frame
Gpu.Default.ForEach(this.texture!, this.shaderFactory(time));
// Close the command list to prepare it for future use
this.d3D12GraphicsCommandList.Get()->Close();
}
using ComPtr<ID3D12Resource> d3D12Resource = default;
/// <inheritdoc/>
public override unsafe void OnResize()
{
this.isResizePending = true;
}
// Get the underlying ID3D12Resource pointer for the texture
_ = InteropServices.TryGetID3D12Resource(this.texture!, FX.__uuidof<ID3D12Resource>(), (void**)d3D12Resource.GetAddressOf());
/// <summary>
/// Applies the actual resize logic that was scheduled from <see cref="OnResize"/>.
/// </summary>
private unsafe void ApplyResize()
{
this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue);
// Get the target back buffer to update
ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch
{
0 => this.d3D12Resource0.Get(),
1 => this.d3D12Resource1.Get(),
_ => null
};
// Wait for the fence again to ensure there are no pending operations
this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default);
this.currentBufferIndex ^= 1;
this.nextD3D12FenceValue++;
// Reset the command list and command allocator
this.d3D12CommandAllocator.Get()->Reset();
this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null);
// Dispose the old buffers before resizing the buffer
this.d3D12Resource0.Dispose();
this.d3D12Resource1.Dispose();
D3D12_RESOURCE_BARRIER* d3D12ResourceBarriers = stackalloc D3D12_RESOURCE_BARRIER[]
{
D3D12_RESOURCE_BARRIER.InitTransition(
d3D12Resource.Get(),
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE),
D3D12_RESOURCE_BARRIER.InitTransition(
d3D12ResourceBackBuffer,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST)
};
// Resize the swap chain buffers
this.dxgiSwapChain1.Get()->ResizeBuffers(0, 0, 0, DXGI_FORMAT.DXGI_FORMAT_UNKNOWN, 0);
// Transition the resources to COPY_DEST and COPY_SOURCE respectively
d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
// Get the index of the initial back buffer
using (ComPtr<IDXGISwapChain3> dxgiSwapChain3 = default)
{
_ = this.dxgiSwapChain1.CopyTo(dxgiSwapChain3.GetAddressOf());
// Copy the generated frame to the target back buffer
d3D12GraphicsCommandList.Get()->CopyResource(d3D12ResourceBackBuffer, d3D12Resource.Get());
this.currentBufferIndex = dxgiSwapChain3.Get()->GetCurrentBackBufferIndex();
}
d3D12ResourceBarriers[0] = D3D12_RESOURCE_BARRIER.InitTransition(
// Retrieve the back buffers for the swap chain
fixed (ID3D12Resource** d3D12Resource0 = this.d3D12Resource0)
fixed (ID3D12Resource** d3D12Resource1 = this.d3D12Resource1)
{
_ = dxgiSwapChain1.Get()->GetBuffer(0, FX.__uuidof<ID3D12Resource>(), (void**)d3D12Resource0);
_ = dxgiSwapChain1.Get()->GetBuffer(1, FX.__uuidof<ID3D12Resource>(), (void**)d3D12Resource1);
}
this.texture?.Dispose();
D3D12_RESOURCE_DESC d3D12Resource0Description = this.d3D12Resource0.Get()->GetDesc();
// Create the 2D texture to use to generate frames to display
this.texture = Gpu.Default.AllocateReadWriteTexture2D<Rgba32, float4>(
(int)d3D12Resource0Description.Width,
(int)d3D12Resource0Description.Height);
}
/// <inheritdoc/>
public override unsafe void OnUpdate(TimeSpan time)
{
if (this.isResizePending)
{
ApplyResize();
this.isResizePending = false;
}
// Generate the new frame
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());
// Get the target back buffer to update
ID3D12Resource* d3D12ResourceBackBuffer = this.currentBufferIndex switch
{
0 => this.d3D12Resource0.Get(),
1 => this.d3D12Resource1.Get(),
_ => null
};
this.currentBufferIndex ^= 1;
// Reset the command list and command allocator
this.d3D12CommandAllocator.Get()->Reset();
this.d3D12GraphicsCommandList.Get()->Reset(this.d3D12CommandAllocator.Get(), null);
D3D12_RESOURCE_BARRIER* d3D12ResourceBarriers = stackalloc D3D12_RESOURCE_BARRIER[]
{
D3D12_RESOURCE_BARRIER.InitTransition(
d3D12Resource.Get(),
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
d3D12ResourceBarriers[1] = D3D12_RESOURCE_BARRIER.InitTransition(
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE),
D3D12_RESOURCE_BARRIER.InitTransition(
d3D12ResourceBackBuffer,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON);
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST)
};
// Transition the resources back to COMMON and UNORDERED_ACCESS respectively
d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
// Transition the resources to COPY_DEST and COPY_SOURCE respectively
d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
d3D12GraphicsCommandList.Get()->Close();
// Copy the generated frame to the target back buffer
d3D12GraphicsCommandList.Get()->CopyResource(d3D12ResourceBackBuffer, d3D12Resource.Get());
// Execute the command list to perform the copy
this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf());
this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue);
d3D12ResourceBarriers[0] = D3D12_RESOURCE_BARRIER.InitTransition(
d3D12Resource.Get(),
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_SOURCE,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
// Present the new frame
this.dxgiSwapChain1.Get()->Present(0, 0);
d3D12ResourceBarriers[1] = D3D12_RESOURCE_BARRIER.InitTransition(
d3D12ResourceBackBuffer,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_COMMON);
if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue())
{
this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default);
}
// Transition the resources back to COMMON and UNORDERED_ACCESS respectively
d3D12GraphicsCommandList.Get()->ResourceBarrier(2, d3D12ResourceBarriers);
this.nextD3D12FenceValue++;
d3D12GraphicsCommandList.Get()->Close();
// Execute the command list to perform the copy
this.d3D12CommandQueue.Get()->ExecuteCommandLists(1, (ID3D12CommandList**)d3D12GraphicsCommandList.GetAddressOf());
this.d3D12CommandQueue.Get()->Signal(this.d3D12Fence.Get(), this.nextD3D12FenceValue);
// Present the new frame
this.dxgiSwapChain1.Get()->Present(0, 0);
if (this.nextD3D12FenceValue > this.d3D12Fence.Get()->GetCompletedValue())
{
this.d3D12Fence.Get()->SetEventOnCompletion(this.nextD3D12FenceValue, default);
}
this.nextD3D12FenceValue++;
}
}
+18 -19
ファイルの表示
@@ -1,28 +1,27 @@
using System;
using TerraFX.Interop;
namespace ComputeSharp.SwapChain.Backend
namespace ComputeSharp.SwapChain.Backend;
/// <summary>
/// A class representing a simple Win32 application.
/// </summary>
internal abstract class Win32Application
{
/// <summary>
/// A class representing a simple Win32 application.
/// Initializes the current application.
/// </summary>
internal abstract class Win32Application
{
/// <summary>
/// Initializes the current application.
/// </summary>
/// <param name="hwnd">The handle for the window.</param>
public abstract void OnInitialize(HWND hwnd);
/// <param name="hwnd">The handle for the window.</param>
public abstract void OnInitialize(HWND hwnd);
/// <summary>
/// Resizes the current application.
/// </summary>
public abstract void OnResize();
/// <summary>
/// Resizes the current application.
/// </summary>
public abstract void OnResize();
/// <summary>
/// Updates the current application.
/// </summary>
/// <param name="time">The current time since the start of the application.</param>
public abstract void OnUpdate(TimeSpan time);
}
/// <summary>
/// Updates the current application.
/// </summary>
/// <param name="time">The current time since the start of the application.</param>
public abstract void OnUpdate(TimeSpan time);
}
+278 -279
ファイルの表示
@@ -7,95 +7,291 @@ using System.Threading;
using TerraFX.Interop;
using FX = TerraFX.Interop.Windows;
namespace ComputeSharp.SwapChain.Backend
namespace ComputeSharp.SwapChain.Backend;
/// <summary>
/// A helper class to manage the creation and execution of Win32 applications.
/// </summary>
internal unsafe static class Win32ApplicationRunner
{
/// <summary>
/// A helper class to manage the creation and execution of Win32 applications.
/// Whether or not a resize operation is in progress.
/// </summary>
internal unsafe static class Win32ApplicationRunner
private static bool isResizing = false;
/// <summary>
/// Whether or not the application is currently paused.
/// </summary>
private static bool isPaused = false;
/// <summary>
/// The <see cref="HWND"/> for the application window.
/// </summary>
private static HWND hwnd;
/// <summary>
/// The application being run.
/// </summary>
private static Win32Application application = null!;
/// <summary>
/// The thread running the render loop.
/// </summary>
private static Thread renderThread = null!;
/// <summary>
/// Runs a specified application and starts the main loop to update its state.
/// This is the entry point for a given application of type <typeparamref name="T"/>, and it should be
/// called as soon as the process is launched, excluding any other additional initialization needed.
/// <para>To launch an application, simply add this line to the project being used:</para>
/// <c>Win32ApplicationRunner.Run&lt;MyApplication>();</c>
/// </summary>
/// <typeparam name="T">The type of application being launched.</typeparam>
/// <returns>The exit code for the application.</returns>
public static int Run(Win32Application application)
{
/// <summary>
/// Whether or not a resize operation is in progress.
/// </summary>
private static bool isResizing = false;
Win32ApplicationRunner.application = application;
/// <summary>
/// Whether or not the application is currently paused.
/// </summary>
private static bool isPaused = false;
IntPtr hInstance = FX.GetModuleHandleW(null);
/// <summary>
/// The <see cref="HWND"/> for the application window.
/// </summary>
private static HWND hwnd;
/// <summary>
/// The application being run.
/// </summary>
private static Win32Application application = null!;
/// <summary>
/// The thread running the render loop.
/// </summary>
private static Thread renderThread = null!;
/// <summary>
/// Runs a specified application and starts the main loop to update its state.
/// This is the entry point for a given application of type <typeparamref name="T"/>, and it should be
/// called as soon as the process is launched, excluding any other additional initialization needed.
/// <para>To launch an application, simply add this line to the project being used:</para>
/// <c>Win32ApplicationRunner.Run&lt;MyApplication>();</c>
/// </summary>
/// <typeparam name="T">The type of application being launched.</typeparam>
/// <returns>The exit code for the application.</returns>
public static int Run(Win32Application application)
fixed (char* name = Assembly.GetExecutingAssembly().FullName)
fixed (char* windowTitle = application.GetType().ToString())
{
Win32ApplicationRunner.application = application;
IntPtr hInstance = FX.GetModuleHandleW(null);
fixed (char* name = Assembly.GetExecutingAssembly().FullName)
fixed (char* windowTitle = application.GetType().ToString())
// Initialize the window class
WNDCLASSEXW windowClassEx = new()
{
// Initialize the window class
WNDCLASSEXW windowClassEx = new()
cbSize = (uint)sizeof(WNDCLASSEXW),
style = FX.CS_HREDRAW | FX.CS_VREDRAW,
lpfnWndProc = &WindowProc,
hInstance = hInstance,
hCursor = FX.LoadCursorW(IntPtr.Zero, FX.MAKEINTRESOURCE(32512)),
lpszClassName = (ushort*)name
};
// Register the window class
_ = FX.RegisterClassExW(&windowClassEx);
Rectangle windowRect = new(0, 0, 1280, 720);
// Set the target window size
_ = FX.AdjustWindowRect((RECT*)&windowRect, FX.WS_OVERLAPPEDWINDOW, FX.FALSE);
uint
height = (uint)(windowRect.Bottom - windowRect.Top),
width = (uint)(windowRect.Right - windowRect.Left);
// Create the window and store a handle to it
hwnd = FX.CreateWindowExW(
0,
windowClassEx.lpszClassName,
(ushort*)windowTitle,
FX.WS_OVERLAPPEDWINDOW,
FX.CW_USEDEFAULT,
FX.CW_USEDEFAULT,
(int)width,
(int)height,
HWND.NULL,
HMENU.NULL,
hInstance,
(void*)GCHandle.ToIntPtr(GCHandle.Alloc(application))
);
MARGINS margins = default;
margins.cxLeftWidth = -1;
margins.cxRightWidth = -1;
margins.cyTopHeight = -1;
margins.cyBottomHeight = -1;
_ = FX.DwmExtendFrameIntoClientArea(hwnd, &margins);
}
// Initialize the application
application.OnInitialize(hwnd);
// Display the window
_ = FX.ShowWindow(hwnd, FX.SW_SHOWDEFAULT);
MSG msg = default;
// Setup the render thread that enables smooth resizing of the window
renderThread = new Thread(static args =>
{
(Win32Application application, CancellationToken token) = ((Win32Application, CancellationToken))args!;
Stopwatch
startStopwatch = Stopwatch.StartNew(),
frameStopwatch = Stopwatch.StartNew();
const long targetFrameTimeInTicksFor60fps = 166666;
while (!token.IsCancellationRequested)
{
if (frameStopwatch.ElapsedTicks >= targetFrameTimeInTicksFor60fps)
{
cbSize = (uint)sizeof(WNDCLASSEXW),
style = FX.CS_HREDRAW | FX.CS_VREDRAW,
lpfnWndProc = &WindowProc,
hInstance = hInstance,
hCursor = FX.LoadCursorW(IntPtr.Zero, FX.MAKEINTRESOURCE(32512)),
lpszClassName = (ushort*)name
};
frameStopwatch.Restart();
// Register the window class
_ = FX.RegisterClassExW(&windowClassEx);
application.OnUpdate(startStopwatch.Elapsed);
}
}
});
Rectangle windowRect = new(0, 0, 1280, 720);
CancellationTokenSource tokenSource = new();
// Set the target window size
_ = FX.AdjustWindowRect((RECT*)&windowRect, FX.WS_OVERLAPPEDWINDOW, FX.FALSE);
renderThread.Start((application, tokenSource.Token));
uint
height = (uint)(windowRect.Bottom - windowRect.Top),
width = (uint)(windowRect.Right - windowRect.Left);
// Process any messages in the queue
while (msg.message != FX.WM_QUIT)
{
if (FX.PeekMessageW(&msg, HWND.NULL, 0, 0, FX.PM_REMOVE) != 0)
{
_ = FX.TranslateMessage(&msg);
_ = FX.DispatchMessageW(&msg);
}
else if (isPaused)
{
Thread.Sleep(100);
}
}
// Create the window and store a handle to it
hwnd = FX.CreateWindowExW(
0,
windowClassEx.lpszClassName,
(ushort*)windowTitle,
FX.WS_OVERLAPPEDWINDOW,
FX.CW_USEDEFAULT,
FX.CW_USEDEFAULT,
(int)width,
(int)height,
HWND.NULL,
HMENU.NULL,
hInstance,
(void*)GCHandle.ToIntPtr(GCHandle.Alloc(application))
);
tokenSource.Cancel();
renderThread.Join();
// Return this part of the WM_QUIT message to Windows
return (int)msg.wParam;
}
/// <summary>
/// Processes incoming messages for a window.
/// </summary>
/// <param name="hwnd">A handle to the window.</param>
/// <param name="uMsg">The message.</param>
/// <param name="wParam">Additional message information (the contents depend on the value of <paramref name="uMsg"/>).</param>
/// <param name="lParam">Additional message information (the contents depend on the value of <paramref name="uMsg"/>).</param>
/// <returns>The result of the message processing for the input message.</returns>
[UnmanagedCallersOnly]
private static nint WindowProc(IntPtr hwnd, uint uMsg, nuint wParam, nint lParam)
{
switch (uMsg)
{
// Change the paused state on window activation
case FX.WM_ACTIVATE:
{
if (FX.LOWORD(wParam) == FX.WA_INACTIVE)
{
isPaused = true;
}
else
{
isPaused = false;
}
return 0;
}
// Change the paused state when ESC is pressed
case FX.WM_KEYDOWN:
{
if ((ConsoleKey)wParam == ConsoleKey.Escape)
{
if (isPaused)
{
FX.SetCapture(hwnd);
}
else
{
FX.ReleaseCapture();
}
isPaused = !isPaused;
}
return 0;
}
// Window resize started
case FX.WM_ENTERSIZEMOVE:
{
isResizing = true;
return 0;
}
// Window resize completed
case FX.WM_EXITSIZEMOVE:
{
isResizing = false;
application.OnResize();
return 0;
}
// Size update
case FX.WM_SIZE:
{
if (!isResizing && wParam != FX.SIZE_MINIMIZED)
{
application.OnResize();
}
return 0;
}
// Size and position of the window (needed to enable the borderless mode)
case FX.WM_NCCALCSIZE:
{
return 0;
}
// Enable dragging the window
case FX.WM_NCHITTEST:
{
POINT point;
RECT rect;
_ = FX.GetCursorPos(&point);
_ = FX.GetWindowRect(hwnd, &rect);
bool
isAtTop = Math.Abs(point.y - rect.top) < 12,
isAtRight = Math.Abs(point.x - rect.right) < 12,
isAtBottom = Math.Abs(point.y - rect.bottom) < 12,
isAtLeft = Math.Abs(point.x - rect.left) < 12;
if (isAtTop)
{
if (isAtRight) return FX.HTTOPRIGHT;
if (isAtLeft) return FX.HTTOPLEFT;
return FX.HTTOP;
}
if (isAtRight)
{
if (isAtTop) return FX.HTTOPRIGHT;
if (isAtBottom) return FX.HTBOTTOMRIGHT;
return FX.HTRIGHT;
}
if (isAtBottom)
{
if (isAtRight) return FX.HTBOTTOMRIGHT;
if (isAtLeft) return FX.HTBOTTOMLEFT;
return FX.HTBOTTOM;
}
if (isAtLeft)
{
if (isAtTop) return FX.HTTOPLEFT;
if (isAtBottom) return FX.HTBOTTOMLEFT;
return FX.HTLEFT;
}
return FX.HTCAPTION;
}
// Restore the drop shadow
case FX.WM_DWMCOMPOSITIONCHANGED:
{
MARGINS margins = default;
margins.cxLeftWidth = -1;
margins.cxRightWidth = -1;
@@ -103,215 +299,18 @@ namespace ComputeSharp.SwapChain.Backend
margins.cyBottomHeight = -1;
_ = FX.DwmExtendFrameIntoClientArea(hwnd, &margins);
return 0;
}
// Initialize the application
application.OnInitialize(hwnd);
// Display the window
_ = FX.ShowWindow(hwnd, FX.SW_SHOWDEFAULT);
MSG msg = default;
// Setup the render thread that enables smooth resizing of the window
renderThread = new Thread(static args =>
// Shutdown
case FX.WM_DESTROY:
{
(Win32Application application, CancellationToken token) = ((Win32Application, CancellationToken))args!;
Stopwatch
startStopwatch = Stopwatch.StartNew(),
frameStopwatch = Stopwatch.StartNew();
const long targetFrameTimeInTicksFor60fps = 166666;
while (!token.IsCancellationRequested)
{
if (frameStopwatch.ElapsedTicks >= targetFrameTimeInTicksFor60fps)
{
frameStopwatch.Restart();
application.OnUpdate(startStopwatch.Elapsed);
}
}
});
CancellationTokenSource tokenSource = new();
renderThread.Start((application, tokenSource.Token));
// Process any messages in the queue
while (msg.message != FX.WM_QUIT)
{
if (FX.PeekMessageW(&msg, HWND.NULL, 0, 0, FX.PM_REMOVE) != 0)
{
_ = FX.TranslateMessage(&msg);
_ = FX.DispatchMessageW(&msg);
}
else if (isPaused)
{
Thread.Sleep(100);
}
FX.PostQuitMessage(0);
return 0;
}
tokenSource.Cancel();
renderThread.Join();
// Return this part of the WM_QUIT message to Windows
return (int)msg.wParam;
}
/// <summary>
/// Processes incoming messages for a window.
/// </summary>
/// <param name="hwnd">A handle to the window.</param>
/// <param name="uMsg">The message.</param>
/// <param name="wParam">Additional message information (the contents depend on the value of <paramref name="uMsg"/>).</param>
/// <param name="lParam">Additional message information (the contents depend on the value of <paramref name="uMsg"/>).</param>
/// <returns>The result of the message processing for the input message.</returns>
[UnmanagedCallersOnly]
private static nint WindowProc(IntPtr hwnd, uint uMsg, nuint wParam, nint lParam)
{
switch (uMsg)
{
// Change the paused state on window activation
case FX.WM_ACTIVATE:
{
if (FX.LOWORD(wParam) == FX.WA_INACTIVE)
{
isPaused = true;
}
else
{
isPaused = false;
}
return 0;
}
// Change the paused state when ESC is pressed
case FX.WM_KEYDOWN:
{
if ((ConsoleKey)wParam == ConsoleKey.Escape)
{
if (isPaused)
{
FX.SetCapture(hwnd);
}
else
{
FX.ReleaseCapture();
}
isPaused = !isPaused;
}
return 0;
}
// Window resize started
case FX.WM_ENTERSIZEMOVE:
{
isResizing = true;
return 0;
}
// Window resize completed
case FX.WM_EXITSIZEMOVE:
{
isResizing = false;
application.OnResize();
return 0;
}
// Size update
case FX.WM_SIZE:
{
if (!isResizing && wParam != FX.SIZE_MINIMIZED)
{
application.OnResize();
}
return 0;
}
// Size and position of the window (needed to enable the borderless mode)
case FX.WM_NCCALCSIZE:
{
return 0;
}
// Enable dragging the window
case FX.WM_NCHITTEST:
{
POINT point;
RECT rect;
_ = FX.GetCursorPos(&point);
_ = FX.GetWindowRect(hwnd, &rect);
bool
isAtTop = Math.Abs(point.y - rect.top) < 12,
isAtRight = Math.Abs(point.x - rect.right) < 12,
isAtBottom = Math.Abs(point.y - rect.bottom) < 12,
isAtLeft = Math.Abs(point.x - rect.left) < 12;
if (isAtTop)
{
if (isAtRight) return FX.HTTOPRIGHT;
if (isAtLeft) return FX.HTTOPLEFT;
return FX.HTTOP;
}
if (isAtRight)
{
if (isAtTop) return FX.HTTOPRIGHT;
if (isAtBottom) return FX.HTBOTTOMRIGHT;
return FX.HTRIGHT;
}
if (isAtBottom)
{
if (isAtRight) return FX.HTBOTTOMRIGHT;
if (isAtLeft) return FX.HTBOTTOMLEFT;
return FX.HTBOTTOM;
}
if (isAtLeft)
{
if (isAtTop) return FX.HTTOPLEFT;
if (isAtBottom) return FX.HTBOTTOMLEFT;
return FX.HTLEFT;
}
return FX.HTCAPTION;
}
// Restore the drop shadow
case FX.WM_DWMCOMPOSITIONCHANGED:
{
MARGINS margins = default;
margins.cxLeftWidth = -1;
margins.cxRightWidth = -1;
margins.cyTopHeight = -1;
margins.cyBottomHeight = -1;
_ = FX.DwmExtendFrameIntoClientArea(hwnd, &margins);
return 0;
}
// Shutdown
case FX.WM_DESTROY:
{
FX.PostQuitMessage(0);
return 0;
}
}
return FX.DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
return FX.DefWindowProcW(hwnd, uMsg, wParam, lParam);
}
}
}
+56 -57
ファイルの表示
@@ -6,70 +6,69 @@ using System.Runtime.CompilerServices;
using ComputeSharp.SwapChain.Backend;
using ComputeSharp.SwapChain.Shaders;
namespace ComputeSharp.SwapChain
namespace ComputeSharp.SwapChain;
class Program
{
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[]
{
/// <summary>
/// A texture for <c>\Textures\RustyMetal.png</c>.
/// </summary>
private static readonly IReadOnlyTexture2D<float4> RustyMetal = LoadTexture();
new SwapChainApplication<HelloWorld>(static time => new((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))
};
/// <summary>
/// The mapping of available samples to choose from.
/// </summary>
private static readonly Win32Application[] Samples = new Win32Application[]
static void Main()
{
Console.WriteLine("Available samples:");
Console.WriteLine();
for (int i = 0; i < Samples.Length; i++)
{
new SwapChainApplication<HelloWorld>(static time => new((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()
{
Console.WriteLine("Available samples:");
Console.WriteLine();
for (int i = 0; i < Samples.Length; i++)
{
Console.WriteLine($"{i}: {Samples[i].GetType().GenericTypeArguments[0].Name}");
}
Console.WriteLine();
int index;
do
{
Console.Write("Enter the index of the sample to run: ");
}
while (!int.TryParse(Console.ReadLine(), out index));
Console.WriteLine();
Console.WriteLine($"Starting {Samples[index].GetType().GenericTypeArguments[0].Name}...");
Win32ApplicationRunner.Run(Samples[index]);
Console.WriteLine($"{i}: {Samples[i].GetType().GenericTypeArguments[0].Name}");
}
/// <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");
Console.WriteLine();
return Gpu.Default.LoadReadOnlyTexture2D<Rgba32, float4>(filename);
int index;
do
{
Console.Write("Enter the index of the sample to run: ");
}
while (!int.TryParse(Console.ReadLine(), out index));
Console.WriteLine();
Console.WriteLine($"Starting {Samples[index].GetType().GenericTypeArguments[0].Name}...");
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");
return Gpu.Default.LoadReadOnlyTexture2D<Rgba32, float4>(filename);
}
}
+55 -56
ファイルの表示
@@ -1,69 +1,68 @@
namespace ComputeSharp.SwapChain.Shaders
namespace ComputeSharp.SwapChain.Shaders;
/// <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 : IPixelShader<float4>
{
/// <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>
/// The current time since the start of the application.
/// </summary>
[AutoConstructor]
internal readonly partial struct ColorfulInfinity : IPixelShader<float4>
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)
{
/// <summary>
/// The current time since the start of the application.
/// </summary>
public readonly float time;
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));
/// <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)
for (int i = 0; i++ < NumberOfIterations;)
{
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;
o.XZYW = Hlsl.Abs(o / Hlsl.Dot(o, o) - dec);
}
/// <inheritdoc/>
public float4 Execute()
return o;
}
/// <inheritdoc/>
public float4 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)
{
float2 uv = (ThreadIds.XY - (float2)DispatchSize.XY * 0.5f) / DispatchSize.Y;
float3 col = 0;
float t = time * 0.3f;
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);
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);
return new(col.X, col.Y, col.Z, 1.0f);
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);
return new(col.X, col.Y, col.Z, 1.0f);
}
}
+180 -181
ファイルの表示
@@ -1,197 +1,196 @@
namespace ComputeSharp.SwapChain.Shaders
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>
/// 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>
/// The current time Hlsl.Since the start of the application.
/// </summary>
[AutoConstructor]
internal readonly partial struct ContouredLayers : IPixelShader<float4>
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)
{
/// <summary>
/// The current time Hlsl.Since the start of the application.
/// </summary>
public readonly float time;
return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new float2(41, 289))) * 45758.5453f);
}
/// <summary>
/// The background texture to sample.
/// </summary>
public readonly IReadOnlyTexture2D<float4> texture;
// float2 to float2 hash.
private float2 Hash22(float2 p)
{
float n = Hlsl.Sin(Hlsl.Dot(p, new float2(1, 113)));
// float3 to float hash.
private static float Hash21(float2 p)
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++)
{
return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new float2(41, 289))) * 45758.5453f);
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;
}
// float2 to float2 hash.
private float2 Hash22(float2 p)
{
float n = Hlsl.Sin(Hlsl.Dot(p, new float2(1, 113)));
col *= Hlsl.Lerp(new float3(1.8f, 1, 0.7f).ZYX, new float3(1.8f, 1, 0.7f).XZY, Noise2D(uv * 2.0f));
p = Hlsl.Frac(new float2(262144, 32768) * n);
float3 rn3 = Noise2D(uv * DispatchSize.Y / 1.0f + 1.7f) - Noise2D(uv * DispatchSize.Y / 1.0f + 3.4f);
return Hlsl.Sin(p * 6.2831853f + time);
}
col *= 0.93f + 0.07f * rn3.XYZ + 0.07f * Hlsl.Dot(rn3, new float3(0.299f, 0.587f, 0.114f));
// float2 to float2 hash.
private static float2 Hash22B(float2 p)
{
float n = Hlsl.Sin(Hlsl.Dot(p, new float2(41, 289)));
uv = fragCoord / DispatchSize.XY;
return Hlsl.Frac(new float2(262144, 32768) * n) * 2.0f - 1.0f;
}
col *= Hlsl.Pow(16.0f * uv.X * uv.Y * (1.0f - uv.X) * (1.0f - uv.Y), 0.0625f);
// 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);
}
return new float4(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1);
}
}
+278 -279
ファイルの表示
@@ -1,293 +1,292 @@
namespace ComputeSharp.SwapChain.Shaders
namespace ComputeSharp.SwapChain.Shaders;
/// <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 : IPixelShader<float4>
{
/// <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>
/// The current time since the start of the application.
/// </summary>
[AutoConstructor]
internal readonly partial struct ExtrudedTruchetPattern : IPixelShader<float4>
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)
{
/// <summary>
/// The current time since the start of the application.
/// </summary>
public readonly float time;
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
/// <summary>
/// Curve shape - Round: 0, Semi-round: 1, Octagonal: 2, Superellipse: 3, Straight: 4.
/// </summary>
private static readonly int SHAPE = 0;
return new(c, -s, s, c);
}
/// <summary>
/// Object ID: Either the back plane or the metaballs.
/// </summary>
private static int objID;
// 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);
}
// Standard 2D rotation formula.
private static float2x2 Rotate2x2(float a)
// Various distance metrics.
private static float Distance(float2 p)
{
if (SHAPE == 0)
{
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
return new(c, -s, s, c);
return Hlsl.Length(p);
}
else p = Hlsl.Abs(p);
// IQ's float2 to float hash.
private static float Hash21(float2 p)
switch (SHAPE)
{
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 float4 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));
return c;
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 float4 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));
return c;
}
}
+34 -35
ファイルの表示
@@ -1,46 +1,45 @@
namespace ComputeSharp.SwapChain.Shaders
namespace ComputeSharp.SwapChain.Shaders;
/// <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 : IPixelShader<float4>
{
/// <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>
/// The current time since the start of the application.
/// </summary>
[AutoConstructor]
internal readonly partial struct FractalTiling : IPixelShader<float4>
public readonly float time;
/// <inheritdoc/>
public float4 Execute()
{
/// <summary>
/// The current time since the start of the application.
/// </summary>
public readonly float time;
float2 position = ((float2)(256 * ThreadIds.XY)) / DispatchSize.X + time;
float4 color = 0;
/// <inheritdoc/>
public float4 Execute()
for (int i = 0; i < 6; i++)
{
float2 position = ((float2)(256 * ThreadIds.XY)) / DispatchSize.X + time;
float4 color = 0;
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);
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));
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;
return color;
position /= 2.0f;
color /= 2.0f;
}
color.XYZ = Hlsl.Pow(color.XYZ, new float3(0.7f, 0.8f, 0.5f));
color.W = 1.0f;
return color;
}
}
+135 -136
ファイルの表示
@@ -1,170 +1,169 @@
namespace ComputeSharp.SwapChain.Shaders
namespace ComputeSharp.SwapChain.Shaders;
/// <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 : IPixelShader<float4>
{
/// <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>
/// The current time since the start of the application.
/// </summary>
[AutoConstructor]
internal readonly partial struct MengerJourney : IPixelShader<float4>
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)
{
/// <summary>
/// The current time since the start of the application.
/// </summary>
public readonly float time;
return new(Hlsl.Cos(a) * v.X + Hlsl.Sin(a) * v.Y, -Hlsl.Sin(a) * v.X + Hlsl.Cos(a) * v.Y);
}
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;
/// <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));
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);
float3 lightDir2 = Hlsl.Normalize(LightDir2);
float diffuse2 = Hlsl.Max(0.0f, Hlsl.Dot(-normal, lightDir2));
/// <summary>
/// Rotates a given <see cref="float2"/> value by a specified amount.
/// </summary>
private static float2 Rotate(float2 v, float a)
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 new(Hlsl.Cos(a) * v.X + Hlsl.Sin(a) * v.Y, -Hlsl.Sin(a) * v.X + Hlsl.Cos(a) * v.Y);
return x - y * Hlsl.Floor(x / 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)
z = Hlsl.Abs(1.0f - Mod(z, 2.0f));
float d = 1000.0f;
for (int n = 0; n < Iterations; n++)
{
float3 lightDir = Hlsl.Normalize(LightDir);
float diffuse = Hlsl.Max(0.0f, Hlsl.Dot(-normal, lightDir));
z.XY = Rotate(z.XY, 4.0f + 2.0f * Hlsl.Cos(time / 8.0f));
z = Hlsl.Abs(z);
float3 lightDir2 = Hlsl.Normalize(LightDir2);
float diffuse2 = Hlsl.Max(0.0f, Hlsl.Dot(-normal, lightDir2));
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; }
return
(diffuse * Diffuse) * (LightColor * color) +
(diffuse2 * Diffuse) * (LightColor2 * color);
}
z = Scale * z - Offset * (Scale - 1.0f);
/// <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)
if (z.Z < -0.5f * Offset.Z * (Scale - 1.0))
{
return x - y * Hlsl.Floor(x / y);
z.Z += Offset.Z * (Scale - 1.0f);
}
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;
d = Hlsl.Min(d, Hlsl.Length(z) * Hlsl.Pow(Scale, -n - 1.0f));
}
/// <summary>
/// Calculates the finite difference normal at a given position.
/// </summary>
private float3 getNormal(in float3 pos)
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)
{
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)));
return Hlsl.Frac(Hlsl.Cos(Hlsl.Dot(co, new float2(4.898f, 7.23f))) * 23421.631f);
}
/// <summary>
/// Performs a ray march operation on a specific position.
/// </summary>
private float4 RayMarch(in float3 from, float3 dir, in float2 fragCoord)
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++)
{
// 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);
}
dir.ZY = Rotate(dir2.ZY, totalDistance * Hlsl.Cos(time / 4.0f) * NonLinearPerspective);
pos = from + totalDistance * dir;
distance = DE(pos) * FudgeFactor;
totalDistance += distance;
float totalDistance = Jitter * Rand(fragCoord.XY + time);
float3 dir2 = dir;
float distance = 0;
int steps = 0;
float3 pos = 0;
if (distance < MinimumDistance) break;
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);
steps = i;
}
/// <inheritdoc/>
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));
float3 camDir = Hlsl.Normalize(target - camPos);
float3 camUp = new(0.0f, 1.0f, 0.0f);
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);
camUp = Hlsl.Normalize(camUp - Hlsl.Dot(camDir, camUp) * camDir);
color = (color * Ambient + light) * ao;
float3 camRight = Hlsl.Normalize(Hlsl.Cross(camDir, camUp));
float2 coord = -1.0f + 2.0f * (float2)ThreadIds.XY / DispatchSize.XY;
return new(color.X, color.Y, color.Z, 1.0f);
}
coord.X *= (float)DispatchSize.X / DispatchSize.Y;
/// <inheritdoc/>
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));
float3 camDir = Hlsl.Normalize(target - camPos);
float3 camUp = new(0.0f, 1.0f, 0.0f);
float3 rayDir = Hlsl.Normalize(camDir + (coord.X * camRight + coord.Y * camUp) * FieldOfView);
camUp = Hlsl.Normalize(camUp - Hlsl.Dot(camDir, camUp) * camDir);
return RayMarch(camPos, rayDir, ThreadIds.XY);
}
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);
return RayMarch(camPos, rayDir, ThreadIds.XY);
}
}
+102 -103
ファイルの表示
@@ -1,123 +1,122 @@
namespace ComputeSharp.SwapChain.Shaders
namespace ComputeSharp.SwapChain.Shaders;
/// <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 : IPixelShader<float4>
{
/// <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>
/// The current time since the start of the application.
/// </summary>
[AutoConstructor]
internal readonly partial struct Octagrams : IPixelShader<float4>
public readonly float time;
private static float2x2 Rotate(float a)
{
/// <summary>
/// The current time since the start of the application.
/// </summary>
public readonly float time;
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
private static float2x2 Rotate(float a)
return new(c, s, -s, c);
}
private static float Box(float3 pos, float scale)
{
static float SDBox(float3 p, float3 b)
{
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
float3 q = Hlsl.Abs(p) - b;
return new(c, s, -s, c);
return Hlsl.Length(Hlsl.Max(q, 0.0f)) +
Hlsl.Min(Hlsl.Max(q.X, Hlsl.Max(q.Y, q.Z)), 0.0f);
}
private static float Box(float3 pos, float scale)
{
static float SDBox(float3 p, float3 b)
{
float3 q = Hlsl.Abs(p) - b;
pos *= scale;
return Hlsl.Length(Hlsl.Max(q, 0.0f)) +
Hlsl.Min(Hlsl.Max(q.X, Hlsl.Max(q.Y, q.Z)), 0.0f);
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 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);
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);
}
pos *= scale;
float3 pos = ro + ray * t;
float b = SDBox(pos, new(0.4f, 0.4f, 0.1f)) / 1.5f;
pos = Mod(pos - 2.0f, 4.0f) - 2.0f;
pos.XY *= 5.0f;
pos.Y -= 3.5f;
pos.XY = Hlsl.Mul(pos.XY, Rotate(0.75f));
float gTime = time - i * 0.01f;
float d = BoxSet(pos, gTime);
return -b;
d = Hlsl.Max(Hlsl.Abs(d), 0.01f);
ac += Hlsl.Exp(-d * 23.0f);
t += d * 0.55f;
}
private static float BoxSet(float3 pos, float gTime)
{
float3 pos_origin = pos;
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)));
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 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);
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)));
return color;
}
return color;
}
}
+128 -129
ファイルの表示
@@ -1,168 +1,167 @@
namespace ComputeSharp.SwapChain.Shaders
namespace ComputeSharp.SwapChain.Shaders;
/// <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 : IPixelShader<float4>
{
/// <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>
/// The current time Hlsl.Since the start of the application.
/// </summary>
[AutoConstructor]
internal readonly partial struct ProteanClouds : IPixelShader<float4>
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)
{
/// <summary>
/// The current time Hlsl.Since the start of the application.
/// </summary>
public readonly float time;
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
return new(c, s, -s, c);
}
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 float LinStep(in float mn, in float mx, in float x)
{
return Hlsl.Clamp((x - mn) / (mx - mn), 0.0f, 1.0f);
}
private static float2x2 Rotate(in float a)
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++)
{
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
return new(c, s, -s, c);
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);
}
private static float LinStep(in float mn, in float mx, in float x)
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++)
{
return Hlsl.Clamp((x - mn) / (mx - mn), 0.0f, 1.0f);
}
if (rez.A > 0.99f) break;
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;
}
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;
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++)
if (mpv.X > 0.6f)
{
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);
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);
}
d = Hlsl.Abs(d + prm1 * 3.0f) + prm1 * 0.3f - 2.5f + bsMo.Y;
float fogC = Hlsl.Exp(t * 0.2f - 2.2f);
return new float2(d + cl * 0.2f + 0.25f, cl);
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);
}
private float4 Render(float3 ro, float3 rd, float time, float prm1, float2 bsMo)
{
float4 rez = 0;
float t = 1.5f;
float fogT = 0;
return Hlsl.Clamp(rez, 0.0f, 1.0f);
}
for (int i = 0; i < 130; i++)
{
if (rez.A > 0.99f) break;
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);
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;
return (ma - mi) / (ma + (float)1e-7);
}
if (mpv.X > 0.6f)
{
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));
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;
ic += 1.5f * dir * sd * ff * lgt;
float dif = Hlsl.Clamp((den - Map(pos + 0.8f, prm1, bsMo).X) / 9.0f, 0.001f, 1.0f);
return Hlsl.Clamp(ic, 0.0f, 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);
}
/// <inheritdoc/>
public float4 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);
float fogC = Hlsl.Exp(t * 0.2f - 2.2f);
ro += new float3(Hlsl.Sin(time) * 0.5f, Hlsl.Sin(time * 1.0f) * 0.0f, 0);
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);
}
float dspAmp = 0.85f;
return Hlsl.Clamp(rez, 0.0f, 1.0f);
}
ro.XY += Disp(ro.Z) * dspAmp;
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);
float tgtDst = 3.5f;
float3 target = Hlsl.Normalize(ro - new float3(Disp(scaledTime + tgtDst) * dspAmp, scaledTime + tgtDst));
return (ma - mi) / (ma + (float)1e-7);
}
ro.X -= bsMo.X * 2.0f;
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));
float3 rightdir = Hlsl.Normalize(Hlsl.Cross(target, new float3(0, 1, 0)));
float3 updir = Hlsl.Normalize(Hlsl.Cross(rightdir, target));
ic += 1.5f * dir * sd * ff * lgt;
rightdir = Hlsl.Normalize(Hlsl.Cross(updir, target));
return Hlsl.Clamp(ic, 0.0f, 1.0f);
}
float3 rd = Hlsl.Normalize((p.X * rightdir + p.Y * updir) * 1.0f - target);
/// <inheritdoc/>
public float4 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);
rd.XY = Hlsl.Mul(rd.XY, Rotate(-Disp(scaledTime + 3.5f).X * 0.2f + bsMo.X));
ro += new float3(Hlsl.Sin(time) * 0.5f, Hlsl.Sin(time * 1.0f) * 0.0f, 0);
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;
float dspAmp = 0.85f;
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;
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;
return new(col, 1.0f);
}
return new(col, 1.0f);
}
}
+136 -137
ファイルの表示
@@ -1,176 +1,175 @@
namespace ComputeSharp.SwapChain.Shaders
namespace ComputeSharp.SwapChain.Shaders;
/// <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 : IPixelShader<float4>
{
/// <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>
/// The current time Hlsl.Since the start of the application.
/// </summary>
[AutoConstructor]
internal readonly partial struct PyramidPattern : IPixelShader<float4>
public readonly float time;
// Standard 2D rotation formula.
private static float2x2 Rotate2x2(in float a)
{
/// <summary>
/// The current time Hlsl.Since the start of the application.
/// </summary>
public readonly float time;
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
// Standard 2D rotation formula.
private static float2x2 Rotate2x2(in float 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)
{
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
return new(c, -s, s, c);
p.X += 0.5f;
}
// 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 ip = Hlsl.Floor(p);
// float2 to float2 hash.
private static float2 Hash22B(float2 p)
{
float n = Hlsl.Sin(Hlsl.Dot(p, new float2(41, 289)));
p -= ip + 0.5f;
return Hlsl.Frac(new float2(262144, 32768) * n) * 2.0f - 1.0f;
}
float ang = -3.14159f * 3.0f / 5.0f + (FBM(ip / 8.0f + time / 3.0f)) * 6.2831f * 2.0f;
// Based on IQ's gradient noise formula.
private static float N2D3G(float2 p)
{
float2 i = Hlsl.Floor(p);
p -= i;
float2 offs = new float2(Hlsl.Cos(ang), Hlsl.Sin(ang)) * 0.35f;
float4 v = default;
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);
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);
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);
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);
}
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);
// 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);
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;
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);
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);
grad -= n * Hlsl.Dot(n, grad);
return Hlsl.Normalize(n + grad * bumpfactor);
}
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;
// 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 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;
float hRnd = Hash21(Hlsl.Floor(p * 6.0f) + 0.73f);
if (hRnd > 0.66f) hatch = hRnd;
return hatch;
}
return hatch;
}
/// <inheritdoc/>
public float4 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;
/// <inheritdoc/>
public float4 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);
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);
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);
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);
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;
col += col * col * rf * rf * new float3(1, 0.1f, 0.1f) * 15.0f;
float shade = m * 0.83f + 0.17f;
float shade = m * 0.83f + 0.17f;
col *= shade;
col *= 1.0f - edge * 0.8f;
col *= shade;
col *= 1.0f - edge * 0.8f;
float hatch = DoHatch(oP / gSc, iRes);
float hatch = DoHatch(oP / gSc, iRes);
col *= hatch * 0.5f + 0.7f;
col *= hatch * 0.5f + 0.7f;
return new(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1);
}
return new(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1);
}
}
+234 -235
ファイルの表示
@@ -1,279 +1,278 @@
namespace ComputeSharp.SwapChain.Shaders
namespace ComputeSharp.SwapChain.Shaders;
/// <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 : IPixelShader<float4>
{
/// <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>
/// The current time Hlsl.Since the start of the application.
/// </summary>
[AutoConstructor]
internal readonly partial struct TriangleGridContouring : IPixelShader<float4>
public readonly float time;
// Standard 2D rotation formula.
private static float2x2 Rotate2x2(in float a)
{
/// <summary>
/// The current time Hlsl.Since the start of the application.
/// </summary>
public readonly float time;
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
// Standard 2D rotation formula.
private static float2x2 Rotate2x2(in float 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)
{
float c = Hlsl.Cos(a), s = Hlsl.Sin(a);
p0 = Interpolate(ip1, ip2, n3.Y, n3.Z, isovalue);
p1 = Interpolate(ip2, ip0, n3.Z, n3.X, isovalue);
return new(c, -s, s, c);
}
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);
}
// IQ's float2 to float hash.
private static float Hash21(float2 p)
if (iTh >= 4 && iTh <= 6)
{
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);
float2 tmp = p0;
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);
p0 = p1;
p1 = tmp;
}
// The isofunction. Just a Hlsl.Single noise function, but it can be more elaborate.
private float IsoFunction(in float2 p)
if (i == 0.0f)
{
return N2D3G(p / 4.0f + 0.07f);
float2 tmp = p0;
p0 = p1;
p1 = tmp;
}
// Unsigned distance to the segment joining "a" and "b".
private static float DistLine(float2 a, float2 b)
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)
{
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);
d = 0;
}
// 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)));
}
d3 = Hlsl.Min(d3, DistLine((p - p0), (p - p1)));
d4 = Hlsl.Min(d4, Hlsl.Min(Hlsl.Length(p - p0), Hlsl.Length(p - p1)));
// 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);
}
float tri = Hlsl.Min(Hlsl.Min(DistLine(p - ip0, p - ip1), DistLine(p - ip1, p - ip2)), DistLine(p - ip2, p - ip0));
// 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;
d5 = Hlsl.Min(d5, tri);
d5 = Hlsl.Min(d5, Hlsl.Length(p) - 0.02f);
isovalue = -0.15f;
int iTh = 0;
int iTh2 = IsoLine(n3, ip0, ip1, ip2, isovalue, i, ref p0, ref p1);
if (n3.X > isovalue) iTh += 4;
if (n3.Y > isovalue) iTh += 2;
if (n3.Z > isovalue) iTh += 1;
d2 = Hlsl.Min(d2, distEdge(p - p0, p - p1));
if (iTh == 1 || iTh == 6)
{
p0 = Interpolate(ip1, ip2, n3.Y, n3.Z, isovalue);
p1 = Interpolate(ip2, ip0, n3.Z, n3.X, isovalue);
float oldD2 = d2;
}
else if (iTh == 2 || iTh == 5)
{
p0 = Interpolate(ip0, ip1, n3.X, n3.Y, isovalue);
p1 = Interpolate(ip1, ip2, n3.Y, n3.Z, isovalue);
if (iTh2 == 7) d2 = 0.0f;
if (iTh == 7) d2 = 1e5f;
}
else if (iTh == 3 || iTh == 4)
{
p0 = Interpolate(ip0, ip1, n3.X, n3.Y, isovalue);
p1 = Interpolate(ip2, ip0, n3.Z, n3.X, isovalue);
}
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;
if (iTh >= 4 && iTh <= 6)
{
float2 tmp = p0;
p0 = p1;
p1 = tmp;
}
float3 col = new(1, 0.85f, 0.6f);
float sf = 0.004f;
if (i == 0.0f)
{
float2 tmp = p0;
p0 = p1;
p1 = tmp;
}
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)));
return iTh;
}
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)));
private float3 SimplexContour(float2 p)
{
const float gSc = 8.0f;
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);
p *= gSc;
float pat = Hlsl.Abs(Hlsl.Frac(tri * 12.5f + 0.4f) - 0.5f) * 2.0f;
float2 oP = p;
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)));
p += new float2(N2D3G(p * 3.5f), N2D3G(p * 3.5f + 7.3f)) * 0.015f;
float2 q = oP * 1.5f;
float2 s = Hlsl.Floor(p + (p.X + p.Y) * 0.36602540378f);
col = Hlsl.Min(col, 1.0f);
p -= s - (s.X + s.Y) * 0.211324865f;
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;
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;
ns = gr - ns;
q = Hlsl.Mul(q, Rotate2x2(3.14159f / 3.0f));
ip0 -= ctr;
ip1 -= ctr;
ip2 -= ctr;
p -= ctr;
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;
float3 n3 = default;
ns2 = gr - ns2;
ns = Hlsl.SmoothStep(0.0f, 1.0f, Hlsl.Min(ns, ns2));
col = Hlsl.Lerp(col, col * (ns + 0.35f), 0.4f);
n3.X = IsoFunction(s);
n3.Y = IsoFunction(s + ioffs);
n3.Z = IsoFunction(s + 1.0f);
return col;
}
float
d = 1e5f,
d2 = 1e5f,
d3 = 1e5f,
d4 = 1e5f,
d5 = 1e5f;
/// <inheritdoc/>
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);
float2 p = Hlsl.Mul(Rotate2x2(3.14159f / 12.0f), uv) + new float2(0.8660254f, 0.5f) * time / 16.0f;
float3 col = SimplexContour(p);
float isovalue = 0;
float2 p0 = default, p1 = default;
int iTh = IsoLine(n3, ip0, ip1, ip2, isovalue, i, ref p0, ref p1);
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;
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 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);
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;
return new(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1);
}
return new(Hlsl.Sqrt(Hlsl.Max(col, 0.0f)), 1);
}
}
+126 -127
ファイルの表示
@@ -1,144 +1,143 @@
namespace ComputeSharp.SwapChain.Shaders
namespace ComputeSharp.SwapChain.Shaders;
/// <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 : IPixelShader<float4>
{
/// <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>
/// The current time since the start of the application.
/// </summary>
[AutoConstructor]
internal readonly partial struct TwoTiledTruchet : IPixelShader<float4>
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)
{
/// <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)
{
// 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;
return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new float2(27.619f, 57.583f))) * 43758.5453f);
}
/// <inheritdoc/>
public float4 Execute()
// HLSL's port of the GLSL mod intrinsic
static float Mod(float x, float y)
{
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);
return x - y * Hlsl.Floor(x / y);
}
for (int i = 0; i < 2; i++)
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)
{
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;
ang.X *= -1.0f;
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);
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;
return color;
}
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 float4 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);
return color;
}
}