Merge pull request #84 from Sergio0694/feature/normalized-pixels

Normalized texture types
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2021-01-05 20:38:41 +01:00
コミット 4aa7102663
46ファイル変更
+3107 -1977

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

+2 -3
ファイルの表示
@@ -329,6 +329,5 @@ ASALocalRun/
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Sample bokeh blur image
**/*_bokeh.jpg
**/*_gaussian.jpg
# Sample images
**/city_*.jpg
+1 -1
ファイルの表示
@@ -45,7 +45,7 @@ Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "ComputeSharp.Sample.Shared"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.Internals.SourceGenerators", "tests\ComputeSharp.Tests.Internals.SourceGenerators\ComputeSharp.Tests.Internals.SourceGenerators.csproj", "{BBBD0ADD-F2F9-49A3-BD5E-D223F0735D8B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputeSharp.Tests.NativeLibrariesResolver", "tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj", "{BF52326F-E415-49E6-8595-62762216762B}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputeSharp.Tests.NativeLibrariesResolver", "tests\ComputeSharp.Tests.NativeLibrariesResolver\ComputeSharp.Tests.NativeLibrariesResolver.csproj", "{BF52326F-E415-49E6-8595-62762216762B}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
+1
ファイルの表示
@@ -4,5 +4,6 @@
<add key="TerraFX-CI" value="https://pkgs.terrafx.dev/index.json" />
<add key="BenchmarkDotNet-CI" value="https://ci.appveyor.com/nuget/benchmarkdotnet" />
<add key="ComputeSharp-Local" value="src\ComputeSharp.Package\bin\Release" />
<add key="SixLabors-CI" value="https://www.myget.org/F/sixlabors/api/v3/index.json" />
</packageSources>
</configuration>
@@ -4,13 +4,13 @@ using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Engines;
namespace ComputeSharp.Benchmark
namespace ComputeSharp.Benchmark.Blas
{
/// <summary>
/// A <see langword="class"/> that benchmarks the APIs in the <see cref="Dnn"/> class, on both CPU and GPU.
/// 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 DnnBenchmark : IDisposable
public class BlasBenchmark : IDisposable
{
/// <summary>
/// The number of samples.
@@ -105,11 +105,13 @@ namespace ComputeSharp.Benchmark
BufferW = Gpu.Default.AllocateReadOnlyBuffer(W);
BufferB = Gpu.Default.AllocateReadOnlyBuffer(B);
BufferY = Gpu.Default.AllocateReadWriteBuffer(Y);
Cpu();
GpuWithNoTemporaryBuffers();
GpuWithTemporaryBuffers();
}
/// <summary>
/// Clears the memory from the current session.
/// </summary>
/// <inheritdoc/>
[GlobalCleanup]
public void Dispose()
{
@@ -128,13 +130,19 @@ namespace ComputeSharp.Benchmark
/// Runs a fully connected forward operation on the CPU.
/// </summary>
[Benchmark(Baseline = true)]
public void Cpu() => Dnn.FullyConnectedForwardCpu(C, N, M, P, X, W, B, Y);
public void Cpu()
{
BlasHelpers.FullyConnectedForwardCpu(C, N, M, P, X, W, B, Y);
}
/// <summary>
/// Runs a fully connected forward operation on the GPU.
/// </summary>
[Benchmark]
public void GpuWithNoTemporaryBuffers() => Dnn.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, BufferX, BufferW, BufferB, BufferY);
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.
@@ -147,7 +155,7 @@ namespace ComputeSharp.Benchmark
using ReadOnlyBuffer<float> b = Gpu.Default.AllocateReadOnlyBuffer(B);
using ReadWriteBuffer<float> y = Gpu.Default.AllocateReadWriteBuffer(Y);
Dnn.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, x, w, b, y);
BlasHelpers.FullyConnectedForwardGpu(Gpu.Default, C, N, M, P, x, w, b, y);
y.GetData(Y);
}
@@ -2,12 +2,12 @@
using System.Threading.Tasks;
using ComputeSharp.Graphics;
namespace ComputeSharp.Benchmark
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 Dnn
internal static partial class BlasHelpers
{
/// <summary>
/// Executes the forward pass on a fully connected layer on the CPU.
+14 -1
ファイルの表示
@@ -6,7 +6,20 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.12.1.1473" />
<Compile Include="..\ComputeSharp.ImageProcessing\Primitives\Complex64.cs" Link="Imaging\Primitives\Complex64.cs" />
<Compile Include="..\ComputeSharp.ImageProcessing\Processors\HlslBokehBlurProcessor.cs" Link="Imaging\Processors\HlslBokehBlurProcessor.cs" />
<Compile Include="..\ComputeSharp.ImageProcessing\Processors\HlslBokehBlurProcessor{TPixel}.cs" Link="Imaging\Processors\HlslBokehBlurProcessor{TPixel}.cs" />
<Compile Include="..\ComputeSharp.ImageProcessing\Processors\HlslGaussianBlurProcessor.cs" Link="Imaging\Processors\HlslGaussianBlurProcessor.cs" />
<Compile Include="..\ComputeSharp.ImageProcessing\Processors\HlslGaussianBlurProcessor{TPixel}.cs" Link="Imaging\Processors\HlslGaussianBlurProcessor{TPixel}.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\ComputeSharp.ImageProcessing\city.jpg" Link="Imaging\city.jpg" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.12.1.1475" />
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.3-alpha.0.24" />
</ItemGroup>
<ItemGroup>
+91
ファイルの表示
@@ -0,0 +1,91 @@
using System;
using System.IO;
using System.Reflection;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Engines;
using ComputeSharp.BokehBlur.Processors;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Processors.Convolution;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
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>
/// The loaded image.
/// </summary>
private Image<ImageSharpRgba32> image;
/// <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);
Bokeh_Cpu();
Bokeh_Gpu();
Gaussian_Cpu();
Gaussian_Gpu();
}
/// <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 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 GPU.
/// </summary>
[Benchmark]
[BenchmarkCategory("GAUSSIAN")]
public void Gaussian_Gpu()
{
this.image.Mutate(c => c.ApplyProcessor(new HlslGaussianBlurProcessor(80)));
}
}
}
-23
ファイルの表示
@@ -1,23 +0,0 @@
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System.Numerics;
namespace SixLabors.ImageSharp
{
/// <summary>
/// A vector with a pair of <see cref="Vector4"/> representing a complex color.
/// </summary>
internal struct ComplexVector4
{
/// <summary>
/// The real part of the complex vector.
/// </summary>
public Vector4 Real;
/// <summary>
/// The imaginary part of the complex number.
/// </summary>
public Vector4 Imaginary;
}
}
+12 -94
ファイルの表示
@@ -1,7 +1,9 @@
using System.Numerics;
using System.Runtime.CompilerServices;
using Microsoft.Toolkit.Diagnostics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
{
@@ -20,27 +22,23 @@ namespace ComputeSharp.BokehBlur.Processors
/// </summary>
public const int DefaultComponents = 2;
/// <summary>
/// The default gamma used by the parameterless constructor.
/// </summary>
public const float DefaultGamma = 3f;
/// <summary>
/// Initializes a new instance of the <see cref="HlslBokehBlurProcessor"/> class.
/// </summary>
public HlslBokehBlurProcessor() : this(DefaultRadius, DefaultComponents, DefaultGamma) { }
public HlslBokehBlurProcessor()
: this(DefaultRadius, DefaultComponents)
{
}
/// <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>
/// <param name="gamma">The gamma highlight factor to use to further process the image.</param>
public HlslBokehBlurProcessor(int radius, int components, float gamma)
public HlslBokehBlurProcessor(int radius, int components)
{
Radius = radius;
Components = components;
Gamma = gamma;
}
/// <summary>
@@ -53,98 +51,18 @@ namespace ComputeSharp.BokehBlur.Processors
/// </summary>
public int Components { get; }
/// <summary>
/// Gets the gamma highlight factor to use when applying the effect.
/// </summary>
public float Gamma { get; }
/// <inheritdoc/>
public IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
where TPixel : unmanaged, IPixel<TPixel>
{
return new HlslBokehBlurProcessor<TPixel>(this, configuration, source, sourceRectangle);
}
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct VerticalConvolutionProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public ReadOnlyBuffer<Vector4> source;
public ReadWriteBuffer<ComplexVector4> target;
public ReadOnlyBuffer<Complex64> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
if (typeof(TPixel) != typeof(ImageSharpRgba32))
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
Vector4 color = source[offsetY * width + offsetX];
Complex64 factors = kernel[i];
real += factors.Real * color;
imaginary += factors.Imaginary * color;
}
int offsetXY = ids.Y * width + ids.X;
target[offsetXY].Real = real;
target[offsetXY].Imaginary = imaginary;
ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
}
}
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
{
public int width;
public int maxY;
public int maxX;
public int kernelLength;
public float z;
public float w;
var processor = new Implementation(this, configuration, Unsafe.As<Image<ImageSharpRgba32>>(source), sourceRectangle);
public ReadWriteBuffer<ComplexVector4> source;
public ReadWriteBuffer<Vector4> target;
public ReadOnlyBuffer<Complex64> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
var offsetXY = offsetY * width + offsetX;
ComplexVector4 source4 = source[offsetXY];
Complex64 factors = kernel[i];
real += factors.Real * source4.Real - factors.Imaginary * source4.Imaginary;
imaginary += factors.Real * source4.Imaginary + factors.Imaginary * source4.Real;
}
target[ids.Y * width + ids.X] += real * z + imaginary * w;
}
return Unsafe.As<IImageProcessor<TPixel>>(processor);
}
}
}
+441 -392
ファイルの表示
@@ -1,272 +1,272 @@
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Toolkit.Diagnostics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
{
/// <summary>
/// Applies bokeh blur processing to the image.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
/// <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 HlslBokehBlurProcessor<TPixel> : ImageProcessor<TPixel>
where TPixel : unmanaged, IPixel<TPixel>
/// <inheritdoc/>
public sealed partial class HlslBokehBlurProcessor
{
/// <summary>
/// The kernel radius.
/// Applies bokeh blur processing to the image.
/// </summary>
private readonly int Radius;
/// <summary>
/// The gamma highlight factor to use when applying the effect.
/// </summary>
private readonly float Gamma;
/// <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="HlslBokehBlurProcessor{TPixel}"/> 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 HlslBokehBlurProcessor(HlslBokehBlurProcessor definition, Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
: base(configuration, source, sourceRectangle)
/// <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>
{
Radius = definition.Radius;
KernelSize = Radius * 2 + 1;
ComponentsCount = definition.Components;
Gamma = definition.Gamma;
/// <summary>
/// The kernel radius.
/// </summary>
private readonly int Radius;
// Reuse the initialized values from the cache, if possible
var parameters = (Radius, ComponentsCount);
if (Cache.TryGetValue(parameters, out var info))
/// <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)
{
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();
Radius = definition.Radius;
KernelSize = Radius * 2 + 1;
ComponentsCount = definition.Components;
// 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);
}
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++)
// Reuse the initialized values from the cache, if possible
var parameters = (Radius, ComponentsCount);
if (Cache.TryGetValue(parameters, out var info))
{
for (int k = 0; k < length; k++)
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));
}
}
/// <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);
}
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++)
{
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);
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;
}
}
}
// Normalize the kernels
float scalar = 1f / MathF.Sqrt(total);
for (int i = 0; i < kernelsSpan.Length; i++)
/// <inheritdoc/>
protected override void OnFrameApply(ImageFrame<ImageSharpRgba32> source)
{
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++)
if (!source.TryGetSinglePixelSpan(out Span<ImageSharpRgba32> pixelSpan))
{
Unsafe.Add(ref valueRef, j) *= scalar;
ThrowHelper.ThrowInvalidOperationException("Cannot process image frames wrapping discontiguous memory");
}
}
}
/// <inheritdoc/>
protected override void OnFrameApply(ImageFrame<TPixel> source)
{
foreach (Memory<TPixel> memory in source.GetPixelMemoryGroup())
{
// Preliminary gamma highlight pass
using IMemoryOwner<Vector4> source4 = GetExposedVector4Buffer(memory);
Span<Rgba32> span = MemoryMarshal.Cast<ImageSharpRgba32, Rgba32>(pixelSpan);
using ReadOnlyBuffer<Vector4> sourceBuffer = Gpu.Default.AllocateReadOnlyBuffer<Vector4>(source4.Memory.Span);
using ReadWriteBuffer<Vector4> processingBuffer = Gpu.Default.AllocateReadWriteBuffer<Vector4>(sourceBuffer.Length);
using ReadWriteBuffer<ComplexVector4> firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer<ComplexVector4>(sourceBuffer.Length);
using ReadWriteTexture2D<Rgba32, Vector4> sourceTexture = Gpu.Default.AllocateReadWriteTexture2D<Rgba32, Vector4>(span, source.Width, source.Height);
using ReadWriteTexture2D<Vector4> processingTexture = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadWriteTexture2D<Vector4> realTexture = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadWriteTexture2D<Vector4> imaginaryTexture = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadOnlyBuffer<Complex64> kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer<Complex64>(KernelSize);
ref Vector4 param0 = ref KernelParameters[0]; // Avoid bounds check to access the kernel parameters
// Preliminary gamma highlight pass
ApplyGammaHighlight(sourceTexture);
ref Vector4 param0 = ref MemoryMarshal.GetArrayDataReference(KernelParameters);
// Perform two 1D convolutions for each component in the current instance
for (int j = 0; j < Kernels.Length; j++)
@@ -274,182 +274,231 @@ namespace ComputeSharp.BokehBlur.Processors
kernelBuffer.SetData(Kernels[j]);
Vector4 parameters = Unsafe.Add(ref param0, j);
ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer);
ApplyHorizontalConvolutionAndAccumulatePartials(firstPassBuffer, processingBuffer, kernelBuffer, parameters.Z, parameters.W);
ApplyVerticalConvolution(sourceTexture, realTexture, imaginaryTexture, kernelBuffer);
ApplyHorizontalConvolutionAndAccumulatePartials(realTexture, imaginaryTexture, processingTexture, kernelBuffer, parameters.Z, parameters.W);
}
// Apply the inverse gamma exposure pass
processingBuffer.GetData(source4.Memory.Span);
ApplyInverseGammaExposure(processingTexture, sourceTexture);
// Write the final pixel data
ApplyInverseGammaExposure(source4.Memory, memory);
sourceTexture.GetData(span);
}
}
/// <summary>
/// Performs a vertical 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="source">The source <see cref="ReadOnlyBuffer{T}"/> to read data from.</param>
/// <param name="target">The target <see cref="ReadWriteBuffer{T}"/> to write the results to.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyVerticalConvolution(
ReadOnlyBuffer<Vector4> source,
ReadWriteBuffer<ComplexVector4> target,
ReadOnlyBuffer<Complex64> kernel)
{
int height = Source.Height;
int width = Source.Width;
HlslBokehBlurProcessor.VerticalConvolutionProcessor shader = new(
width,
maxY: height - 1,
maxX: width - 1,
kernelLength: kernel.Length,
source,
target,
kernel);
Gpu.Default.For(width, height, in shader);
}
/// <summary>
/// Performs an horizontal 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="source">The source <see cref="ReadWriteBuffer{T}"/> to read data from.</param>
/// <param name="target">The target <see cref="ReadWriteBuffer{T}"/> to write the results to.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
/// <param name="z">The weight factor for the real component of the complex pixel values.</param>
/// <param name="w">The weight factor for the imaginary component of the complex pixel values.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyHorizontalConvolutionAndAccumulatePartials(
ReadWriteBuffer<ComplexVector4> source,
ReadWriteBuffer<Vector4> target,
ReadOnlyBuffer<Complex64> kernel,
float z,
float w)
{
int height = Source.Height;
int width = Source.Width;
HlslBokehBlurProcessor.HorizontalConvolutionAndAccumulatePartialsProcessor shader = new(
width,
maxY: height - 1,
maxX: width - 1,
kernelLength: kernel.Length,
z,
w,
source,
target,
kernel);
Gpu.Default.For(width, height, in shader);
}
/// <summary>
/// Applies the gamma correction/highlight to the input pixel buffer and returns an <see cref="IMemoryOwner{T}"/> instance with <see cref="Vector4"/> values.
/// </summary>
/// <param name="source">The source image.</param>
[Pure]
private IMemoryOwner<Vector4> GetExposedVector4Buffer(Memory<TPixel> source)
{
IMemoryOwner<Vector4> target = Configuration.MemoryAllocator.Allocate<Vector4>(source.Length);
float exp = Gamma;
int width = Source.Width;
int height = source.Length / width;
ParallelRowIterator.IterateRows(
Configuration,
new Rectangle(0, 0, width, height),
new GetExposedVector4BufferProcessor(width, exp, source, target.Memory, Configuration));
return target;
}
/// <summary>
/// The processor for <see cref="GetExposedVector4Buffer"/>.
/// </summary>
[AutoConstructor]
private readonly partial struct GetExposedVector4BufferProcessor : IRowOperation
{
private readonly int width;
private readonly float exp;
private readonly Memory<TPixel> source;
private readonly Memory<Vector4> target;
private readonly Configuration configuration;
/// <inheritdoc/>
public void Invoke(int y)
/// <summary>
/// Performs a vertical 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="source">The source <see cref="ReadOnlyTexture2D{T}"/> to read data from.</param>
/// <param name="reals">The target <see cref="ReadWriteTexture2D{T}"/> to write the real results to.</param>
/// <param name="imaginaries">The target <see cref="ReadWriteTexture2D{T}"/> to write the imaginary results to.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyVerticalConvolution(
ReadWriteTexture2D<Rgba32, Vector4> source,
ReadWriteTexture2D<Vector4> reals,
ReadWriteTexture2D<Vector4> imaginaries,
ReadOnlyBuffer<Complex64> kernel)
{
int offset = y * width;
int height = Source.Height;
int width = Source.Width;
Span<TPixel> rowTPixel = source.Span.Slice(offset, width);
Span<Vector4> rowVector4 = target.Span.Slice(offset, width);
VerticalConvolutionProcessor shader = new(
maxY: height - 1,
maxX: width - 1,
kernelLength: kernel.Length,
source,
reals,
imaginaries,
kernel);
PixelOperations<TPixel>.Instance.ToVector4(configuration, rowTPixel, rowVector4);
Gpu.Default.For(width, height, in shader);
}
foreach (ref Vector4 v in rowVector4)
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct VerticalConvolutionProcessor : IComputeShader
{
public int maxY;
public int maxX;
public int kernelLength;
public ReadWriteTexture2D<Rgba32, Vector4> source;
public ReadWriteTexture2D<Vector4> reals;
public ReadWriteTexture2D<Vector4> imaginaries;
public ReadOnlyBuffer<Complex64> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
v.X = MathF.Pow(v.X, exp);
v.Y = MathF.Pow(v.Y, exp);
v.Z = MathF.Pow(v.Z, exp);
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
Vector4 color = source[offsetX, offsetY];
Complex64 factors = kernel[i];
real += factors.Real * color;
imaginary += factors.Imaginary * color;
}
reals[ids.XY] = real;
imaginaries[ids.XY] = imaginary;
}
}
}
/// <summary>
/// Applies the inverse gamma exposure pass to compute the final pixel values for a target image.
/// </summary>
/// <param name="source">The source <see cref="Vector4"/> buffer to read from.</param>
/// <param name="target">The target image.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyInverseGammaExposure(Memory<Vector4> source, Memory<TPixel> target)
{
int width = Source.Width;
int height = source.Length / width;
float expGamma = 1 / Gamma;
ParallelRowIterator.IterateRows(
Configuration,
new Rectangle(0, 0, width, height),
new ApplyInverseGammaExposureProcessor(width, expGamma, source, target, Configuration));
}
/// <summary>
/// The processor for <see cref="ApplyInverseGammaExposure"/>.
/// </summary>
[AutoConstructor]
private readonly partial struct ApplyInverseGammaExposureProcessor : IRowOperation
{
private readonly int width;
private readonly float exp;
private readonly Memory<Vector4> source;
private readonly Memory<TPixel> target;
private readonly Configuration configuration;
/// <inheritdoc/>
public void Invoke(int y)
/// <summary>
/// Performs an horizontal 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="reals">The source <see cref="ReadWriteTexture2D{T}"/> to read the real results from.</param>
/// <param name="imaginaries">The source <see cref="ReadWriteTexture2D{T}"/> to read the imaginary results from.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
/// <param name="z">The weight factor for the real component of the complex pixel values.</param>
/// <param name="w">The weight factor for the imaginary component of the complex pixel values.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyHorizontalConvolutionAndAccumulatePartials(
ReadWriteTexture2D<Vector4> reals,
ReadWriteTexture2D<Vector4> imaginaries,
ReadWriteTexture2D<Vector4> target,
ReadOnlyBuffer<Complex64> kernel,
float z,
float w)
{
int offset = y * width;
int height = Source.Height;
int width = Source.Width;
Span<Vector4> rowVector4 = source.Span.Slice(offset, width);
Span<TPixel> rowTPixel = target.Span.Slice(offset, width);
HorizontalConvolutionAndAccumulatePartialsProcessor shader = new(
maxY: height - 1,
maxX: width - 1,
kernelLength: kernel.Length,
z,
w,
reals,
imaginaries,
target,
kernel);
Vector4 low = Vector4.Zero;
var high = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
Gpu.Default.For(width, height, in shader);
}
foreach (ref Vector4 v in rowVector4)
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader
{
public int maxY;
public int maxX;
public int kernelLength;
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(ThreadIds ids)
{
var clamp = Vector4.Clamp(v, low, high);
v.X = MathF.Pow(clamp.X, exp);
v.Y = MathF.Pow(clamp.Y, exp);
v.Z = MathF.Pow(clamp.Z, exp);
}
Vector4 real = Vector4.Zero;
Vector4 imaginary = Vector4.Zero;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
PixelOperations<TPixel>.Instance.FromVector4Destructive(configuration, rowVector4, rowTPixel);
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
Vector4 sourceReal = reals[offsetX, offsetY];
Vector4 sourceImaginary = imaginaries[offsetX, offsetY];
Complex64 factors = kernel[i];
real += factors.Real * sourceReal - factors.Imaginary * sourceImaginary;
imaginary += factors.Real * sourceImaginary + factors.Imaginary * sourceReal;
}
target[ids.XY] += real * z + imaginary * w;
}
}
/// <summary>
/// Applies the gamma highlight pass to compute the final pixel values for a target image.
/// </summary>
/// <param name="source">The source <see cref="ReadWriteTexture2D{T}"/> instance to modify.</param>
[Pure]
private void ApplyGammaHighlight(ReadWriteTexture2D<Rgba32, Vector4> source)
{
Gpu.Default.For(source.Height, new GammaHighlightProcessor(source.Width, source));
}
/// <summary>
/// Kernel for the gamma highlight pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct GammaHighlightProcessor : IComputeShader
{
public readonly int width;
public readonly ReadWriteTexture2D<Rgba32, Vector4> source;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
for (int i = 0; i < width; i++)
{
Float4 v = source[i, ids.X];
v.XYZ = v.XYZ * v.XYZ * v.XYZ;
source[i, ids.X] = v;
}
}
}
/// <summary>
/// Applies the inverse gamma highlight pass to compute the final pixel values for a target image.
/// </summary>
/// <param name="source">The source <see cref="ReadWriteTexture2D{T}"/> instance to read from.</param>
/// <param name="target">The target <see cref="ReadWriteTexture2D{T, TPixel}"/> instance to write to.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyInverseGammaExposure(
ReadWriteTexture2D<Vector4> source,
ReadWriteTexture2D<Rgba32, Vector4> target)
{
Gpu.Default.For(source.Height, new InverseGammaHighlightProcessor(source.Width, source, target));
}
/// <summary>
/// Kernel for the inverse gamma highlight pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct InverseGammaHighlightProcessor : IComputeShader
{
public readonly int width;
public readonly ReadWriteTexture2D<Vector4> source;
public readonly ReadWriteTexture2D<Rgba32, Vector4> target;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
for (int i = 0; i < width; i++)
{
Float4 v = source[i, ids.X];
v.XYZ = Hlsl.Clamp(v.XYZ, 0, float.MaxValue);
v.XYZ = Hlsl.Pow(v.XYZ, 1 / 3f);
target[i, ids.X] = v;
}
}
}
}
}
+7 -72
ファイルの表示
@@ -1,7 +1,9 @@
using System.Numerics;
using System.Runtime.CompilerServices;
using Microsoft.Toolkit.Diagnostics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
{
@@ -51,81 +53,14 @@ namespace ComputeSharp.BokehBlur.Processors
public IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
where TPixel : unmanaged, IPixel<TPixel>
{
return new HlslGaussianBlurProcessor<TPixel>(this, configuration, source, sourceRectangle);
}
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
{
public readonly int width;
public readonly int maxY;
public readonly int maxX;
public readonly int kernelLength;
public readonly ReadWriteBuffer<Vector4> source;
public readonly ReadWriteBuffer<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
if (typeof(TPixel) != typeof(ImageSharpRgba32))
{
Vector4 result = Vector4.Zero;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
Vector4 color = source[offsetY * width + offsetX];
result += kernel[i] * color;
}
int offsetXY = ids.Y * width + ids.X;
target[offsetXY] = result;
ThrowHelper.ThrowInvalidOperationException("This processor only supports the RGBA32 pixel format");
}
}
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
{
public readonly int width;
public readonly int maxY;
public readonly int maxX;
public readonly int kernelLength;
var processor = new Implementation(this, configuration, Unsafe.As<Image<ImageSharpRgba32>>(source), sourceRectangle);
public readonly ReadWriteBuffer<Vector4> source;
public readonly ReadWriteBuffer<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
int offsetXY;
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
offsetXY = offsetY * width + offsetX;
Vector4 color = source[offsetXY];
result += kernel[i] * color;
}
offsetXY = ids.Y * width + ids.X;
target[offsetXY] = result;
}
return Unsafe.As<IImageProcessor<TPixel>>(processor);
}
}
}
+191 -129
ファイルの表示
@@ -1,166 +1,228 @@
using System;
using System.Buffers;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Toolkit.Diagnostics;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.BokehBlur.Processors
{
/// <summary>
/// Applies Gaussian blur processing to an image.
/// </summary>
/// <typeparam name="TPixel">The pixel format.</typeparam>
internal sealed class HlslGaussianBlurProcessor<TPixel> : ImageProcessor<TPixel>
where TPixel : unmanaged, IPixel<TPixel>
/// <inheritdoc/>
public sealed partial class HlslGaussianBlurProcessor
{
/// <summary>
/// The 1D kernel to apply.
/// Applies Gaussian blur processing to an image.
/// </summary>
private readonly float[] Kernel;
/// <summary>
/// Initializes a new instance of the <see cref="HlslGaussianBlurProcessor"/> class.
/// </summary>
/// <param name="definition">The <see cref="HlslGaussianBlurProcessor"/> 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 HlslGaussianBlurProcessor(HlslGaussianBlurProcessor definition, Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
: base(configuration, source, sourceRectangle)
internal sealed partial class Implementation : ImageProcessor<ImageSharpRgba32>
{
int kernelSize = definition.Radius * 2 + 1;
Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma);
}
/// <summary>
/// The 1D kernel to apply.
/// </summary>
private readonly float[] Kernel;
/// <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++)
/// <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)
{
float x = i - midpoint;
float gx = Gaussian(x, weight);
sum += gx;
Unsafe.Add(ref rKernel, i) = gx;
int kernelSize = definition.Radius * 2 + 1;
Kernel = CreateGaussianBlurKernel(kernelSize, definition.Sigma);
}
// Normalize kernel so that the sum of all weights equals 1
for (int i = 0; i < size; i++)
/// <summary>
/// Creates a 1 dimensional Gaussian kernel using the Gaussian G(x) function.
/// </summary>
private static float[] CreateGaussianBlurKernel(int size, float weight)
{
Unsafe.Add(ref rKernel, i) /= sum;
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;
}
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<TPixel> source)
{
foreach (Memory<TPixel> memory in source.GetPixelMemoryGroup())
/// <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)
{
Span<TPixel> spanTPixel = memory.Span;
const float Numerator = 1.0f;
float denominator = MathF.Sqrt(2 * MathF.PI) * sigma;
using IMemoryOwner<Vector4> group4 = Configuration.MemoryAllocator.Allocate<Vector4>(spanTPixel.Length);
float exponentNumerator = -x * x;
float exponentDenominator = 2 * sigma * sigma;
Span<Vector4> spanVector4 = group4.Memory.Span;
float left = Numerator / denominator;
float right = MathF.Exp(exponentNumerator / exponentDenominator);
PixelOperations<TPixel>.Instance.ToVector4(Configuration, spanTPixel, spanVector4);
return left * right;
}
using ReadWriteBuffer<Vector4> sourceBuffer = Gpu.Default.AllocateReadWriteBuffer<Vector4>(spanVector4);
using ReadWriteBuffer<Vector4> firstPassBuffer = Gpu.Default.AllocateReadWriteBuffer<Vector4>(sourceBuffer.Length);
/// <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> sourceTexture = Gpu.Default.AllocateReadWriteTexture2D<Rgba32, Vector4>(span, source.Width, source.Height);
using ReadWriteTexture2D<Vector4> firstPassTexture = Gpu.Default.AllocateReadWriteTexture2D<Vector4>(source.Width, source.Height);
using ReadOnlyBuffer<float> kernelBuffer = Gpu.Default.AllocateReadOnlyBuffer(Kernel);
ApplyVerticalConvolution(sourceBuffer, firstPassBuffer, kernelBuffer);
ApplyHorizontalConvolution(firstPassBuffer, sourceBuffer, kernelBuffer);
ApplyVerticalConvolution(sourceTexture, firstPassTexture, kernelBuffer);
ApplyHorizontalConvolution(firstPassTexture, sourceTexture, kernelBuffer);
sourceBuffer.GetData(spanVector4);
PixelOperations<TPixel>.Instance.FromVector4Destructive(Configuration, spanVector4, spanTPixel);
sourceTexture.GetData(span);
}
}
/// <summary>
/// Performs a vertical 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="source">The source <see cref="ReadWriteBuffer{T}"/> to read data from.</param>
/// <param name="target">The target <see cref="ReadWriteBuffer{T}"/> to write the results to.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyVerticalConvolution(
ReadWriteBuffer<Vector4> source,
ReadWriteBuffer<Vector4> target,
ReadOnlyBuffer<float> kernel)
{
int height = Source.Height;
int width = Source.Width;
/// <summary>
/// Performs a vertical 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="source">The source <see cref="ReadWriteTexture2D{T, TPixel}"/> to read data from.</param>
/// <param name="target">The target <see cref="ReadWriteTexture2D{T}"/> to write the results to.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyVerticalConvolution(
ReadWriteTexture2D<Rgba32, Vector4> source,
ReadWriteTexture2D<Vector4> target,
ReadOnlyBuffer<float> kernel)
{
int height = Source.Height;
int width = Source.Width;
HlslGaussianBlurProcessor.VerticalConvolutionProcessor shader = new(
width,
maxY: height - 1,
maxX: width - 1,
kernel.Length,
source,
target,
kernel);
VerticalConvolutionProcessor shader = new(
maxY: height - 1,
maxX: width - 1,
kernel.Length,
source,
target,
kernel);
Gpu.Default.For(width, height, in shader);
}
Gpu.Default.For(width, height, in shader);
}
/// <summary>
/// Performs an horizontal 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="source">The source <see cref="ReadWriteBuffer{T}"/> to read data from.</param>
/// <param name="target">The target <see cref="ReadWriteBuffer{T}"/> to write the results to.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyHorizontalConvolution(
ReadWriteBuffer<Vector4> source,
ReadWriteBuffer<Vector4> target,
ReadOnlyBuffer<float> kernel)
{
int height = Source.Height;
int width = Source.Width;
/// <summary>
/// Kernel for the vertical convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct VerticalConvolutionProcessor : IComputeShader
{
public readonly int maxY;
public readonly int maxX;
public readonly int kernelLength;
HlslGaussianBlurProcessor.HorizontalConvolutionProcessor shader = new(
width,
maxY: height - 1,
maxX: width - 1,
kernel.Length,
source,
target,
kernel);
public readonly ReadWriteTexture2D<Rgba32, Vector4> source;
public readonly ReadWriteTexture2D<Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
Gpu.Default.For(width, height, in shader);
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int radiusY = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
for (int i = 0; i < kernelLength; i++)
{
int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY);
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX);
Vector4 color = source[offsetX, offsetY];
result += kernel[i] * color;
}
target[ids.XY] = result;
}
}
/// <summary>
/// Performs an horizontal 1D complex convolution with the specified parameters.
/// </summary>
/// <param name="source">The source <see cref="ReadWriteTexture2D{T}"/> to read data from.</param>
/// <param name="target">The target <see cref="ReadWriteTexture2D{T, TPixel}"/> to write the results to.</param>
/// <param name="kernel">The <see cref="ReadOnlyBuffer{T}"/> with the values for the current complex kernel.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ApplyHorizontalConvolution(
ReadWriteTexture2D<Vector4> source,
ReadWriteTexture2D<Rgba32, Vector4> target,
ReadOnlyBuffer<float> kernel)
{
int height = Source.Height;
int width = Source.Width;
HorizontalConvolutionProcessor shader = new(
maxY: height - 1,
maxX: width - 1,
kernel.Length,
source,
target,
kernel);
Gpu.Default.For(width, height, in shader);
}
/// <summary>
/// Kernel for the horizontal convolution pass.
/// </summary>
[AutoConstructor]
internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader
{
public readonly int maxY;
public readonly int maxX;
public readonly int kernelLength;
public readonly ReadWriteTexture2D<Vector4> source;
public readonly ReadWriteTexture2D<Rgba32, Vector4> target;
public readonly ReadOnlyBuffer<float> kernel;
/// <inheritdoc/>
public void Execute(ThreadIds ids)
{
Vector4 result = Vector4.Zero;
int radiusX = kernelLength >> 1;
int sourceOffsetColumnBase = ids.X;
int offsetY = Hlsl.Clamp(ids.Y, 0, maxY);
for (int i = 0; i < kernelLength; i++)
{
int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX);
Vector4 color = source[offsetX, offsetY];
result += kernel[i] * color;
}
target[ids.XY] = result;
}
}
}
}
}
+3 -2
ファイルの表示
@@ -5,6 +5,7 @@ using ComputeSharp.BokehBlur.Processors;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Processing.Processors;
using ImageSharpRgba32 = SixLabors.ImageSharp.PixelFormats.Rgba32;
namespace ComputeSharp.ImageProcessing
{
@@ -14,12 +15,12 @@ namespace ComputeSharp.ImageProcessing
{
Console.WriteLine(">> Loading image");
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "city.jpg");
using Image image = Image.Load(path);
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)[]
{
("bokeh", new HlslBokehBlurProcessor(80, 2, 3)),
("bokeh", new HlslBokehBlurProcessor(80, 2)),
("gaussian", new HlslGaussianBlurProcessor(80))
})
{
+1
ファイルの表示
@@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="System.Numerics.Vectors" Version="4.5.0" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="5.0.0" />
</ItemGroup>
</Project>
ファイル差分が大きすぎるため表示されません。 差分を読み込み
+122
ファイルの表示
@@ -0,0 +1,122 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// Packed pixel type containing four 8-bit unsigned normalized values ranging from 0 to 255.
/// The color components are stored in blue, green, red, and alpha order (least significant to most significant byte).
/// The format is binary compatible with System.Drawing.Imaging.PixelFormat.Format32bppArgb.
/// <para>
/// Ranges from [0, 0, 0, 0] to [1, 1, 1, 1] in vector form.
/// </para>
/// </summary>
/// <remarks>This struct is fully mutable.</remarks>
[StructLayout(LayoutKind.Sequential)]
public struct Bgra32 : IEquatable<Bgra32>, IUnorm<Vector4>, IUnorm<Float4>
{
/// <summary>
/// The blue component.
/// </summary>
public byte B;
/// <summary>
/// The green component.
/// </summary>
public byte G;
/// <summary>
/// The red component.
/// </summary>
public byte R;
/// <summary>
/// The alpha component.
/// </summary>
public byte A;
/// <summary>
/// Initializes a new instance of the <see cref="Bgra32"/> struct.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Bgra32(byte r, byte g, byte b)
{
R = r;
G = g;
B = b;
A = byte.MaxValue;
}
/// <summary>
/// Initializes a new instance of the <see cref="Bgra32"/> struct.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <param name="a">The alpha component.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Bgra32(byte r, byte g, byte b, byte a)
{
R = r;
G = g;
B = b;
A = a;
}
/// <summary>
/// Gets or sets the packed representation of the <see cref="Bgra32"/> struct.
/// </summary>
public uint PackedValue
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => Unsafe.As<Bgra32, uint>(ref Unsafe.AsRef(this));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Unsafe.As<Bgra32, uint>(ref this) = value;
}
/// <summary>
/// Compares two <see cref="Bgra32"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Bgra32"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Bgra32"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Bgra32 left, Bgra32 right) => left.Equals(right);
/// <summary>
/// Compares two <see cref="Bgra32"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Bgra32"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Bgra32"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is not equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Bgra32 left, Bgra32 right) => !left.Equals(right);
/// <inheritdoc/>
public override readonly bool Equals(object? obj) => obj is Bgra32 other && Equals(other);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool Equals(Bgra32 other) => PackedValue.Equals(other.PackedValue);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly int GetHashCode() => PackedValue.GetHashCode();
/// <inheritdoc />
public override readonly string ToString() => $"{nameof(Bgra32)}({this.B}, {this.G}, {this.R}, {this.A})";
}
}
+81
ファイルの表示
@@ -0,0 +1,81 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// Packed pixel type containing a single 16-bit unsigned normalized channel value.
/// <para>
/// Ranges from [0, 0, 0, 0] to [1, 0, 0, 0] in vector form.
/// </para>
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct R16 : IEquatable<R16>, IUnorm<float>
{
/// <summary>
/// The red component.
/// </summary>
public ushort R;
/// <summary>
/// Initializes a new instance of the <see cref="R16"/> struct.
/// </summary>
/// <param name="r">The red component.</param>
public R16(ushort r)
{
R = r;
}
/// <summary>
/// Gets or sets the packed representation of the <see cref="R16"/> struct.
/// </summary>
public ushort PackedValue
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => Unsafe.As<R16, ushort>(ref Unsafe.AsRef(this));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Unsafe.As<R16, ushort>(ref this) = value;
}
/// <summary>
/// Compares two <see cref="R16"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="R16"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="R16"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(R16 left, R16 right) => left.Equals(right);
/// <summary>
/// Compares two <see cref="R16"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="R16"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="R16"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is not equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(R16 left, R16 right) => !left.Equals(right);
/// <inheritdoc/>
public override readonly bool Equals(object? obj) => obj is R16 R16 && Equals(R16);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool Equals(R16 other) => PackedValue.Equals(other.PackedValue);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly int GetHashCode() => PackedValue.GetHashCode();
/// <inheritdoc/>
public override readonly string ToString() => $"{nameof(R16)}({this.R})";
}
}
+81
ファイルの表示
@@ -0,0 +1,81 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// Packed pixel type containing a single 8-bit unsigned normalized channel value.
/// <para>
/// Ranges from [0, 0, 0, 0] to [1, 0, 0, 0] in vector form.
/// </para>
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct R8 : IEquatable<R8>, IUnorm<float>
{
/// <summary>
/// The red component.
/// </summary>
public byte R;
/// <summary>
/// Initializes a new instance of the <see cref="R8"/> struct.
/// </summary>
/// <param name="r">The red component.</param>
public R8(byte r)
{
R = r;
}
/// <summary>
/// Gets or sets the packed representation of the <see cref="R8"/> struct.
/// </summary>
public byte PackedValue
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => Unsafe.As<R8, byte>(ref Unsafe.AsRef(this));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Unsafe.As<R8, byte>(ref this) = value;
}
/// <summary>
/// Compares two <see cref="R8"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="R8"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="R8"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(R8 left, R8 right) => left.Equals(right);
/// <summary>
/// Compares two <see cref="R8"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="R8"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="R8"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is not equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(R8 left, R8 right) => !left.Equals(right);
/// <inheritdoc/>
public override readonly bool Equals(object? obj) => obj is R8 R8 && Equals(R8);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool Equals(R8 other) => PackedValue.Equals(other.PackedValue);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly int GetHashCode() => PackedValue.GetHashCode();
/// <inheritdoc/>
public override readonly string ToString() => $"{nameof(R8)}({this.R})";
}
}
+89
ファイルの表示
@@ -0,0 +1,89 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// Packed pixel type containing two 8-bit unsigned normalized values ranging from 0 to 255.
/// <para>
/// Ranges from [0, 0, 0, 0] to [1, 1, 0, 0] in vector form.
/// </para>
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Rg16 : IEquatable<Rg16>, IUnorm<Vector2>, IUnorm<Float2>
{
/// <summary>
/// The red component.
/// </summary>
public byte R;
/// <summary>
/// The green component.
/// </summary>
public byte G;
/// <summary>
/// Initializes a new instance of the <see cref="Rg16"/> struct.
/// </summary>
/// <param name="x">The x-component</param>
/// <param name="y">The y-component</param>
public Rg16(byte r, byte g)
{
R = r;
G = g;
}
/// <summary>
/// Gets or sets the packed representation of the <see cref="Rg16"/> struct.
/// </summary>
public ushort PackedValue
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => Unsafe.As<Rg16, ushort>(ref Unsafe.AsRef(this));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Unsafe.As<Rg16, ushort>(ref this) = value;
}
/// <summary>
/// Compares two <see cref="Rg16"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Rg16"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Rg16"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Rg16 left, Rg16 right) => left.Equals(right);
/// <summary>
/// Compares two <see cref="Rg16"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Rg16"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Rg16"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is not equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Rg16 left, Rg16 right) => !left.Equals(right);
/// <inheritdoc/>
public override readonly bool Equals(object obj) => obj is Rg16 rgba32 && Equals(rgba32);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool Equals(Rg16 other) => PackedValue.Equals(other.PackedValue);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly int GetHashCode() => PackedValue.GetHashCode();
/// <inheritdoc/>
public override readonly string ToString() => $"{nameof(Rg16)}({this.R}, {this.G})";
}
}
+89
ファイルの表示
@@ -0,0 +1,89 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// Packed pixel type containing two 16-bit unsigned normalized values ranging from 0 to 255.
/// <para>
/// Ranges from [0, 0, 0, 0] to [1, 1, 0, 0] in vector form.
/// </para>
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Rg32 : IEquatable<Rg32>, IUnorm<Vector2>, IUnorm<Float2>
{
/// <summary>
/// The red component.
/// </summary>
public ushort R;
/// <summary>
/// The green component.
/// </summary>
public ushort G;
/// <summary>
/// Initializes a new instance of the <see cref="Rg32"/> struct.
/// </summary>
/// <param name="x">The x-component</param>
/// <param name="y">The y-component</param>
public Rg32(ushort r, ushort g)
{
R = r;
G = g;
}
/// <summary>
/// Gets or sets the packed representation of the <see cref="Rg32"/> struct.
/// </summary>
public uint PackedValue
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => Unsafe.As<Rg32, uint>(ref Unsafe.AsRef(this));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Unsafe.As<Rg32, uint>(ref this) = value;
}
/// <summary>
/// Compares two <see cref="Rg32"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Rg32"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Rg32"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Rg32 left, Rg32 right) => left.Equals(right);
/// <summary>
/// Compares two <see cref="Rg32"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Rg32"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Rg32"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is not equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Rg32 left, Rg32 right) => !left.Equals(right);
/// <inheritdoc/>
public override readonly bool Equals(object? obj) => obj is Rg32 rgba32 && Equals(rgba32);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool Equals(Rg32 other) => PackedValue.Equals(other.PackedValue);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly int GetHashCode() => PackedValue.GetHashCode();
/// <inheritdoc/>
public override readonly string ToString() => $"{nameof(Rg32)}({this.R}, {this.G})";
}
}
+121
ファイルの表示
@@ -0,0 +1,121 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// Packed pixel type containing four 8-bit unsigned normalized values ranging from 0 to 255.
/// The color components are stored in red, green, blue, and alpha order (least significant to most significant byte).
/// <para>
/// Ranges from [0, 0, 0, 0] to [1, 1, 1, 1] in vector form.
/// </para>
/// </summary>
/// <remarks>This struct is fully mutable.</remarks>
[StructLayout(LayoutKind.Sequential)]
public struct Rgba32 : IEquatable<Rgba32>, IUnorm<Vector4>, IUnorm<Float4>
{
/// <summary>
/// The red component.
/// </summary>
public byte R;
/// <summary>
/// The green component.
/// </summary>
public byte G;
/// <summary>
/// The blue component.
/// </summary>
public byte B;
/// <summary>
/// The alpha component.
/// </summary>
public byte A;
/// <summary>
/// Initializes a new instance of the <see cref="Rgba32"/> struct.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Rgba32(byte r, byte g, byte b)
{
this.R = r;
this.G = g;
this.B = b;
this.A = byte.MaxValue;
}
/// <summary>
/// Initializes a new instance of the <see cref="Rgba32"/> struct.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <param name="a">The alpha component.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Rgba32(byte r, byte g, byte b, byte a)
{
this.R = r;
this.G = g;
this.B = b;
this.A = a;
}
/// <summary>
/// Gets or sets the packed representation of the <see cref="Rgba32"/> struct.
/// </summary>
public uint PackedValue
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => Unsafe.As<Rgba32, uint>(ref Unsafe.AsRef(this));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Unsafe.As<Rgba32, uint>(ref this) = value;
}
/// <summary>
/// Compares two <see cref="Rgba32"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Rgba32"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Rgba32"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Rgba32 left, Rgba32 right) => left.Equals(right);
/// <summary>
/// Compares two <see cref="Rgba32"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Rgba32"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Rgba32"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is not equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Rgba32 left, Rgba32 right) => !left.Equals(right);
/// <inheritdoc/>
public override readonly bool Equals(object? obj) => obj is Rgba32 rgba32 && Equals(rgba32);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool Equals(Rgba32 other) => PackedValue.Equals(other.PackedValue);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly int GetHashCode() => PackedValue.GetHashCode();
/// <inheritdoc/>
public override readonly string ToString() => $"{nameof(Rgba32)}({this.R}, {this.G}, {this.B}, {this.A})";
}
}
+121
ファイルの表示
@@ -0,0 +1,121 @@
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// Packed pixel type containing four 16-bit unsigned normalized values ranging from 0 to 255.
/// The color components are stored in red, green, blue, and alpha order (least significant to most significant byte).
/// <para>
/// Ranges from [0, 0, 0, 0] to [1, 1, 1, 1] in vector form.
/// </para>
/// </summary>
/// <remarks>This struct is fully mutable.</remarks>
[StructLayout(LayoutKind.Sequential)]
public struct Rgba64 : IEquatable<Rgba64>, IUnorm<Vector4>, IUnorm<Float4>
{
/// <summary>
/// The red component.
/// </summary>
public ushort R;
/// <summary>
/// The green component.
/// </summary>
public ushort G;
/// <summary>
/// The blue component.
/// </summary>
public ushort B;
/// <summary>
/// The alpha component.
/// </summary>
public ushort A;
/// <summary>
/// Initializes a new instance of the <see cref="Rgba64"/> struct.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Rgba64(ushort r, ushort g, ushort b)
{
this.R = r;
this.G = g;
this.B = b;
this.A = ushort.MaxValue;
}
/// <summary>
/// Initializes a new instance of the <see cref="Rgba64"/> struct.
/// </summary>
/// <param name="r">The red component.</param>
/// <param name="g">The green component.</param>
/// <param name="b">The blue component.</param>
/// <param name="a">The alpha component.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Rgba64(ushort r, ushort g, ushort b, ushort a)
{
this.R = r;
this.G = g;
this.B = b;
this.A = a;
}
/// <summary>
/// Gets or sets the packed representation of the <see cref="Rgba64"/> struct.
/// </summary>
public ulong PackedValue
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => Unsafe.As<Rgba64, ulong>(ref Unsafe.AsRef(this));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Unsafe.As<Rgba64, ulong>(ref this) = value;
}
/// <summary>
/// Compares two <see cref="Rgba64"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Rgba64"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Rgba64"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Rgba64 left, Rgba64 right) => left.Equals(right);
/// <summary>
/// Compares two <see cref="Rgba64"/> objects for equality.
/// </summary>
/// <param name="left">The <see cref="Rgba64"/> on the left side of the operand.</param>
/// <param name="right">The <see cref="Rgba64"/> on the right side of the operand.</param>
/// <returns>
/// True if the <paramref name="left"/> parameter is not equal to the <paramref name="right"/> parameter; otherwise, false.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Rgba64 left, Rgba64 right) => !left.Equals(right);
/// <inheritdoc/>
public override readonly bool Equals(object? obj) => obj is Rgba64 rgba32 && Equals(rgba32);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly bool Equals(Rgba64 other) => PackedValue.Equals(other.PackedValue);
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly int GetHashCode() => PackedValue.GetHashCode();
/// <inheritdoc/>
public override readonly string ToString() => $"{nameof(Rgba64)}({this.R}, {this.G}, {this.B}, {this.A})";
}
}
+16
ファイルの表示
@@ -0,0 +1,16 @@
using System;
using System.ComponentModel;
namespace ComputeSharp.__Internals
{
/// <summary>
/// Indicates the supported HLSL pixel types to represent a given normalized pixel type.
/// </summary>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This interface is not intended to be used directly by user code")]
public interface IUnorm<TPixel>
where TPixel : unmanaged
{
}
}
+13
ファイルの表示
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using ComputeSharp.Exceptions;
@@ -142,6 +143,18 @@ namespace ComputeSharp
/// <param name="x">The value to use for the components of the new <see cref="Float2"/> instance.</param>
public static implicit operator Float2(float x) => new(x, x);
/// <summary>
/// Casts a <see cref="Float2"/> value to a <see cref="Vector2"/> one.
/// </summary>
/// <param name="xy">The input <see cref="Float2"/> value to cast.</param>
public static unsafe implicit operator Vector2(Float2 xy) => *(Vector2*)&xy;
/// <summary>
/// Casts a <see cref="Vector2"/> value to a <see cref="Float2"/> one.
/// </summary>
/// <param name="xy">The input <see cref="Vector2"/> value to cast.</param>
public static unsafe implicit operator Float2(Vector2 xy) => *(Float2*)&xy;
/// <summary>
/// Casts a <see cref="Float2"/> value to a <see cref="Double2"/> one.
/// </summary>
+13
ファイルの表示
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using ComputeSharp.Exceptions;
@@ -563,6 +564,18 @@ namespace ComputeSharp
/// <param name="x">The value to use for the components of the new <see cref="Float3"/> instance.</param>
public static implicit operator Float3(float x) => new(x, x, x);
/// <summary>
/// Casts a <see cref="Float3"/> value to a <see cref="Vector3"/> one.
/// </summary>
/// <param name="xy">The input <see cref="Float3"/> value to cast.</param>
public static unsafe implicit operator Vector3(Float3 xyz) => *(Vector3*)&xyz;
/// <summary>
/// Casts a <see cref="Vector3"/> value to a <see cref="Float3"/> one.
/// </summary>
/// <param name="xy">The input <see cref="Vector3"/> value to cast.</param>
public static unsafe implicit operator Float3(Vector3 xyz) => *(Float3*)&xyz;
/// <summary>
/// Casts a <see cref="Float3"/> value to a <see cref="Double3"/> one.
/// </summary>
+13
ファイルの表示
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using ComputeSharp.Exceptions;
@@ -3968,6 +3969,18 @@ namespace ComputeSharp
/// <param name="x">The value to use for the components of the new <see cref="Float4"/> instance.</param>
public static implicit operator Float4(float x) => new(x, x, x, x);
/// <summary>
/// Casts a <see cref="Float4"/> value to a <see cref="Vector4"/> one.
/// </summary>
/// <param name="xy">The input <see cref="Float4"/> value to cast.</param>
public static unsafe implicit operator Vector4(Float4 xyzw) => *(Vector4*)&xyzw;
/// <summary>
/// Casts a <see cref="Vector4"/> value to a <see cref="Float4"/> one.
/// </summary>
/// <param name="xy">The input <see cref="Vector4"/> value to cast.</param>
public static unsafe implicit operator Float4(Vector4 xyzw) => *(Float4*)&xyzw;
/// <summary>
/// Casts a <see cref="Float4"/> value to a <see cref="Double4"/> one.
/// </summary>
+56
ファイルの表示
@@ -0,0 +1,56 @@
using System.Diagnostics;
using ComputeSharp.__Internals;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Buffers.Views;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> representing a typed readonly 2D texture stored on GPU memory.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
[DebuggerTypeProxy(typeof(Texture2DDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public sealed class ReadOnlyTexture2D<T, TPixel> : Texture2D<T>
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
/// <summary>
/// Creates a new <see cref="ReadOnlyTexture2D{T,TPixel}"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
internal ReadOnlyTexture2D(GraphicsDevice device, int width, int height)
: base(device, width, height, ResourceType.ReadOnly)
{
}
/// <summary>
/// Gets a single <typeparamref name="TPixel"/> value from the current readonly texture.
/// </summary>
/// <param name="x">The horizontal offset of the value to get.</param>
/// <param name="y">The vertical offset of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D<T, TPixel>)}<T>[int,int]");
/// <summary>
/// Gets a single <typeparamref name="TPixel"/> value from the current readonly texture.
/// </summary>
/// <param name="xy">The coordinates of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture2D<T,TPixel>)}<T>[Int2]");
/// <inheritdoc/>
public override string ToString()
{
return $"ComputeSharp.ReadOnlyTexture2D<{typeof(T)},{typeof(TPixel)}>[{Width}, {Height}]";
}
}
}
+58
ファイルの表示
@@ -0,0 +1,58 @@
using System.Diagnostics;
using ComputeSharp.__Internals;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Buffers.Views;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> representing a typed readonly 3D texture stored on GPU memory.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
[DebuggerTypeProxy(typeof(Texture3DDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public sealed class ReadOnlyTexture3D<T, TPixel> : Texture3D<T>
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
/// <summary>
/// Creates a new <see cref="ReadOnlyTexture3D{T,TPixel}"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
internal ReadOnlyTexture3D(GraphicsDevice device, int width, int height, int depth)
: base(device, width, height, depth, ResourceType.ReadOnly)
{
}
/// <summary>
/// Gets a single <typeparamref name="TPixel"/> value from the current readonly texture.
/// </summary>
/// <param name="x">The horizontal offset of the value to get.</param>
/// <param name="y">The vertical offset of the value to get.</param>
/// <param name="y">The depthwise offset of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public TPixel this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D<T, TPixel>)}<T>[int,int,int]");
/// <summary>
/// Gets a single <typeparamref name="TPixel"/> value from the current readonly texture.
/// </summary>
/// <param name="xyz">The coordinates of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public TPixel this[Int3 xyz] => throw new InvalidExecutionContextException($"{nameof(ReadOnlyTexture3D<T, TPixel>)}<T>[Int3]");
/// <inheritdoc/>
public override string ToString()
{
return $"ComputeSharp.ReadOnlyTexture3D<{typeof(T)},{nameof(TPixel)}>[{Width}, {Height}, {Depth}]";
}
}
}
+56
ファイルの表示
@@ -0,0 +1,56 @@
using System.Diagnostics;
using ComputeSharp.__Internals;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Buffers.Views;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> representing a typed read write 2D texture stored on GPU memory.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
[DebuggerTypeProxy(typeof(Texture2DDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public sealed class ReadWriteTexture2D<T, TPixel> : Texture2D<T>
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
/// <summary>
/// Creates a new <see cref="ReadWriteTexture2D{T,TPixel}"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
internal ReadWriteTexture2D(GraphicsDevice device, int width, int height)
: base(device, width, height, ResourceType.ReadWrite)
{
}
/// <summary>
/// Gets a single <typeparamref name="TPixel"/> value from the current writeable texture.
/// </summary>
/// <param name="x">The horizontal offset of the value to get.</param>
/// <param name="y">The vertical offset of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref TPixel this[int x, int y] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture2D<T, TPixel>)}<T>[int,int]");
/// <summary>
/// Gets or sets a single <typeparamref name="TPixel"/> value from the current writeable texture.
/// </summary>
/// <param name="xy">The coordinates of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref TPixel this[Int2 xy] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture2D<T, TPixel>)}<T>[Int2]");
/// <inheritdoc/>
public override string ToString()
{
return $"ComputeSharp.ReadWriteTexture2D<{typeof(T)},{typeof(TPixel)}>[{Width}, {Height}]";
}
}
}
+58
ファイルの表示
@@ -0,0 +1,58 @@
using System.Diagnostics;
using ComputeSharp.__Internals;
using ComputeSharp.Exceptions;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Buffers.Enums;
using ComputeSharp.Graphics.Buffers.Views;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
/// A <see langword="class"/> representing a typed readonly 3D texture stored on GPU memory.
/// </summary>
/// <typeparam name="T">The type of items stored on the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
[DebuggerTypeProxy(typeof(Texture3DDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public sealed class ReadWriteTexture3D<T, TPixel> : Texture3D<T>
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
/// <summary>
/// Creates a new <see cref="ReadOnlyTexture2D{T,TPixel}"/> instance with the specified parameters.
/// </summary>
/// <param name="device">The <see cref="GraphicsDevice"/> associated with the current instance.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
internal ReadWriteTexture3D(GraphicsDevice device, int width, int height, int depth)
: base(device, width, height, depth, ResourceType.ReadWrite)
{
}
/// <summary>
/// Gets a single <typeparamref name="TPixel"/> value from the current writeable texture.
/// </summary>
/// <param name="x">The horizontal offset of the value to get.</param>
/// <param name="y">The vertical offset of the value to get.</param>
/// <param name="z">The depthwise offset of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref TPixel this[int x, int y, int z] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture3D<T, TPixel>)}<T>[int,int,int]");
/// <summary>
/// Gets a single <typeparamref name="TPixel"/> value from the current writeable texture.
/// </summary>
/// <param name="xyz">The coordinates of the value to get.</param>
/// <remarks>This API can only be used from a compute shader, and will always throw if used anywhere else.</remarks>
public ref TPixel this[Int3 xyz] => throw new InvalidExecutionContextException($"{nameof(ReadWriteTexture3D<T, TPixel>)}<T>[Int3]");
/// <inheritdoc/>
public override string ToString()
{
return $"ComputeSharp.ReadWriteTexture3D<{typeof(T)},{nameof(TPixel)}>[{Width}, {Height}, {Depth}]";
}
}
}
+8 -1
ファイルの表示
@@ -2,8 +2,8 @@
using System.Numerics;
using System.Runtime.CompilerServices;
using Microsoft.Toolkit.Diagnostics;
using static TerraFX.Interop.DXGI_FORMAT;
using TerraFX.Interop;
using static TerraFX.Interop.DXGI_FORMAT;
namespace ComputeSharp.Graphics.Helpers
{
@@ -38,6 +38,13 @@ namespace ComputeSharp.Graphics.Helpers
else if (typeof(T) == typeof(Vector2)) return DXGI_FORMAT_R32G32_FLOAT;
else if (typeof(T) == typeof(Vector3)) return DXGI_FORMAT_R32G32B32_FLOAT;
else if (typeof(T) == typeof(Vector4)) return DXGI_FORMAT_R32G32B32A32_FLOAT;
else if (typeof(T) == typeof(Bgra32)) return DXGI_FORMAT_B8G8R8A8_UNORM;
else if (typeof(T) == typeof(Rgba32)) return DXGI_FORMAT_R8G8B8A8_UNORM;
else if (typeof(T) == typeof(Rgba64)) return DXGI_FORMAT_R16G16B16A16_UNORM;
else if (typeof(T) == typeof(R8)) return DXGI_FORMAT_R8_UNORM;
else if (typeof(T) == typeof(R16)) return DXGI_FORMAT_R16_UNORM;
else if (typeof(T) == typeof(Rg16)) return DXGI_FORMAT_R8G8_UNORM;
else if (typeof(T) == typeof(Rg32)) return DXGI_FORMAT_R16G16_UNORM;
else return ThrowHelper.ThrowArgumentException<DXGI_FORMAT>("Invalid texture type");
}
}
+6 -2
ファイルの表示
@@ -77,7 +77,9 @@ namespace ComputeSharp.Shaders.Mappings
return
genericType == typeof(ReadOnlyBuffer<>) ||
genericType == typeof(ReadOnlyTexture2D<>) ||
genericType == typeof(ReadOnlyTexture3D<>);
genericType == typeof(ReadOnlyTexture2D<,>) ||
genericType == typeof(ReadOnlyTexture3D<>) ||
genericType == typeof(ReadOnlyTexture3D<,>);
}
/// <summary>
@@ -95,7 +97,9 @@ namespace ComputeSharp.Shaders.Mappings
return
genericType == typeof(ReadWriteBuffer<>) ||
genericType == typeof(ReadWriteTexture2D<>) ||
genericType == typeof(ReadWriteTexture3D<>);
genericType == typeof(ReadWriteTexture2D<,>) ||
genericType == typeof(ReadWriteTexture3D<>) ||
genericType == typeof(ReadWriteTexture3D<,>);
}
}
}
+2 -1
ファイルの表示
@@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<LangVersion>9.0</LangVersion>
</PropertyGroup>
@@ -12,7 +13,7 @@
<!--The source generator cannot contain package references or project references, so instead we're just
manually linking the source files from ComputeSharp.Core in here. We only need them to extract metadata
and to match members based on full name, so the types being in the generator assembly are not an issue.-->
and to match members based on full name, so the types being in the generator assembly are not an issue.-->
<ItemGroup>
<Compile Include="..\ComputeSharp.Core\Attributes\AutoConstructorAttribute.cs" Link="Core\Attributes\AutoConstructorAttribute.cs" />
<Compile Include="..\ComputeSharp.Core\Attributes\ShaderMethodAttribute.cs" Link="Core\Attributes\ShaderMethodAttribute.cs" />
+2 -1
ファイルの表示
@@ -122,7 +122,8 @@ namespace ComputeSharp.SourceGenerators
yield return new[] { fieldSymbol.Name, mapping ?? fieldSymbol.Name, typeName };
// Track the type of items in the current buffer
if (HlslKnownTypes.IsTypedResourceType(typeSymbol.GetFullMetadataName()))
if (HlslKnownTypes.IsTypedResourceType(typeSymbol.GetFullMetadataName()) &&
typeSymbol.TypeArguments.Length == 1)
{
types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]);
}
+5 -1
ファイルの表示
@@ -18,9 +18,13 @@ namespace ComputeSharp.SourceGenerators.Mappings
private static readonly IReadOnlyDictionary<string, string> KnownIndexers = new Dictionary<string, string>
{
[$"ComputeSharp.ReadOnlyTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadWriteTexture2D`1.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadWriteTexture2D`2.this[{typeof(int).FullName}, {typeof(int).FullName}]"] = "int2",
[$"ComputeSharp.ReadOnlyTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
[$"ComputeSharp.ReadOnlyTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`1.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3",
[$"ComputeSharp.ReadWriteTexture3D`2.this[{typeof(int).FullName}, {typeof(int).FullName}, {typeof(int).FullName}]"] = "int3"
};
/// <summary>
+10 -1
ファイルの表示
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Numerics;
using ComputeSharp.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
@@ -70,9 +71,13 @@ namespace ComputeSharp.SourceGenerators.Mappings
case "ComputeSharp.ReadOnlyBuffer`1":
case "ComputeSharp.ReadWriteBuffer`1":
case "ComputeSharp.ReadOnlyTexture2D`1":
case "ComputeSharp.ReadOnlyTexture2D`2":
case "ComputeSharp.ReadWriteTexture2D`1":
case "ComputeSharp.ReadWriteTexture2D`2":
case "ComputeSharp.ReadOnlyTexture3D`1":
case "ComputeSharp.ReadOnlyTexture3D`2":
case "ComputeSharp.ReadWriteTexture3D`1":
case "ComputeSharp.ReadWriteTexture3D`2":
return true;
default: return false;
};
@@ -107,7 +112,7 @@ namespace ComputeSharp.SourceGenerators.Mappings
// Special case for the structured buffer types
if (IsTypedResourceType(typeName))
{
string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments[0]).GetFullMetadataName();
string genericArgumentName = ((INamedTypeSymbol)typeSymbol.TypeArguments.Last()).GetFullMetadataName();
// If the current type is a custom type, format it as needed
if (!KnownTypes.TryGetValue(genericArgumentName, out string? mapped))
@@ -122,9 +127,13 @@ namespace ComputeSharp.SourceGenerators.Mappings
"ComputeSharp.ReadOnlyBuffer`1" => $"StructuredBuffer<{mapped}>",
"ComputeSharp.ReadWriteBuffer`1" => $"RWStructuredBuffer<{mapped}>",
"ComputeSharp.ReadOnlyTexture2D`1" => $"Texture2D<{mapped}>",
"ComputeSharp.ReadOnlyTexture2D`2" => $"Texture2D<unorm {mapped}>",
"ComputeSharp.ReadWriteTexture2D`1" => $"RWTexture2D<{mapped}>",
"ComputeSharp.ReadWriteTexture2D`2" => $"RWTexture2D<unorm {mapped}>",
"ComputeSharp.ReadOnlyTexture3D`1" => $"Texture3D<{mapped}>",
"ComputeSharp.ReadOnlyTexture3D`2" => $"Texture3D<unorm {mapped}>",
"ComputeSharp.ReadWriteTexture3D`1" => $"RWTexture3D<{mapped}>",
"ComputeSharp.ReadWriteTexture3D`2" => $"RWTexture3D<unorm {mapped}>",
_ => throw new ArgumentException()
};
}
+6 -2
ファイルの表示
@@ -218,11 +218,15 @@ namespace ComputeSharp.SourceGenerators.SyntaxRewriters
// in HLSL, we can remove the suffix entirely. As for 64 bit values, we simply use the 'L' suffix.
if (type.GetFullMetadataName().Equals(typeof(float).FullName))
{
return updatedNode.WithToken(Literal(updatedNode.Token.ValueText, 0f));
string literal = updatedNode.Token.ValueText;
if (!literal.Contains('.')) literal += ".0";
return updatedNode.WithToken(Literal(literal, 0f));
}
else if (type.GetFullMetadataName().Equals(typeof(double).FullName))
{
return updatedNode.WithToken(Literal($"{updatedNode.Token.ValueText}L", 0d));
return updatedNode.WithToken(Literal(updatedNode.Token.ValueText + "L", 0d));
}
}
+403
ファイルの表示
@@ -1,9 +1,12 @@
using System;
using System.Diagnostics.Contracts;
using ComputeSharp.__Internals;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Shaders;
#pragma warning disable CS0618
namespace ComputeSharp
{
/// <summary>
@@ -225,6 +228,102 @@ namespace ComputeSharp
return texture;
}
/// <summary>
/// Allocates a new readonly 2D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <returns>A zeroed <see cref="ReadOnlyTexture2D{T,TPixel}"/> instance of size [<paramref name="width"/>, <paramref name="height"/>].</returns>
[Pure]
public static ReadOnlyTexture2D<T, TPixel> AllocateReadOnlyTexture2D<T, TPixel>(this GraphicsDevice device, int width, int height)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return new(device, width, height);
}
/// <summary>
/// Allocates a new readonly 2D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <returns>A <see cref="ReadOnlyTexture2D{T,TPixel}"/> instance with the contents of the input array.</returns>
[Pure]
public static ReadOnlyTexture2D<T, TPixel> AllocateReadOnlyTexture2D<T, TPixel>(this GraphicsDevice device, T[] array, int width, int height)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return device.AllocateReadOnlyTexture2D<T, TPixel>(array.AsSpan(), width, height);
}
/// <summary>
/// Allocates a new readonly 2D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <param name="offset">The starting offset within <paramref name="source"/> to read data from.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <returns>A <see cref="ReadOnlyTexture2D{T,TPixel}"/> instance with the contents of the input array.</returns>
[Pure]
public static ReadOnlyTexture2D<T, TPixel> AllocateReadOnlyTexture2D<T, TPixel>(this GraphicsDevice device, T[] array, int offset, int width, int height)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return device.AllocateReadOnlyTexture2D<T, TPixel>(array.AsSpan(offset), width, height);
}
/// <summary>
/// Allocates a new readonly 2D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <returns>A read write <see cref="ReadOnlyTexture2D{T,TPixel}"/> instance with the contents of the input array.</returns>
[Pure]
public static ReadOnlyTexture2D<T, TPixel> AllocateReadOnlyTexture2D<T, TPixel>(this GraphicsDevice device, T[,] array)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
ReadOnlyTexture2D<T, TPixel> texture = new(device, array.GetLength(1), array.GetLength(0));
texture.SetData(array);
return texture;
}
/// <summary>
/// Allocates a new readonly 2D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="span">The input <see cref="ReadOnlySpan{T}"/> with the data to copy on the allocated texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <returns>A <see cref="ReadOnlyTexture2D{T,TPixel}"/> instance with the contents of the input <see cref="ReadOnlySpan{T}"/>.</returns>
[Pure]
public static ReadOnlyTexture2D<T, TPixel> AllocateReadOnlyTexture2D<T, TPixel>(this GraphicsDevice device, ReadOnlySpan<T> span, int width, int height)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
ReadOnlyTexture2D<T, TPixel> texture = new(device, width, height);
texture.SetData(span);
return texture;
}
/// <summary>
/// Allocates a new readonly 3D texture with the specified parameters.
/// </summary>
@@ -319,6 +418,110 @@ namespace ComputeSharp
return texture;
}
/// <summary>
/// Allocates a new readonly 3D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
/// <returns>A zeroed <see cref="ReadOnlyTexture3D{T,TPixel}"/> instance of size [<paramref name="width"/>, <paramref name="height"/>, <paramref name="depth"/>].</returns>
[Pure]
public static ReadOnlyTexture3D<T, TPixel> AllocateReadOnlyTexture3D<T, TPixel>(this GraphicsDevice device, int width, int height, int depth)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return new(device, width, height, depth);
}
/// <summary>
/// Allocates a new readonly 3D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
/// <returns>A <see cref="ReadOnlyTexture3D{T,TPixel}"/> instance with the contents of the input array.</returns>
[Pure]
public static ReadOnlyTexture3D<T, TPixel> AllocateReadOnlyTexture3D<T, TPixel>(this GraphicsDevice device, T[] array, int width, int height, int depth)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return device.AllocateReadOnlyTexture3D<T, TPixel>(array.AsSpan(), width, height, depth);
}
/// <summary>
/// Allocates a new readonly 3D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <param name="offset">The starting offset within <paramref name="source"/> to read data from.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
/// <returns>A <see cref="ReadOnlyTexture3D{T,TPixel}"/> instance with the contents of the input array.</returns>
[Pure]
public static ReadOnlyTexture3D<T, TPixel> AllocateReadOnlyTexture3D<T, TPixel>(this GraphicsDevice device, T[] array, int offset, int width, int height, int depth)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return device.AllocateReadOnlyTexture3D<T, TPixel>(array.AsSpan(offset), width, height, depth);
}
/// <summary>
/// Allocates a new readonly 3D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <returns>A read write <see cref="ReadOnlyTexture3D{T,TPixel}"/> instance with the contents of the input array.</returns>
/// <remarks>
/// The source 3D array needs to have each 2D plane stacked on the depth axis.
/// That is, the expected layout of the input array has to be [depth, height, width].
/// </remarks>
[Pure]
public static ReadOnlyTexture3D<T, TPixel> AllocateReadOnlyTexture3D<T, TPixel>(this GraphicsDevice device, T[,,] array)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
ReadOnlyTexture3D<T, TPixel> texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0));
texture.SetData(array);
return texture;
}
/// <summary>
/// Allocates a new readonly 3D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="span">The input <see cref="ReadOnlySpan{T}"/> with the data to copy on the allocated texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
/// <returns>A <see cref="ReadOnlyTexture3D{T,TPixel}"/> instance with the contents of the input <see cref="ReadOnlySpan{T}"/>.</returns>
[Pure]
public static ReadOnlyTexture3D<T, TPixel> AllocateReadOnlyTexture3D<T, TPixel>(this GraphicsDevice device, ReadOnlySpan<T> span, int width, int height, int depth)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
ReadOnlyTexture3D<T, TPixel> texture = new(device, width, height, depth);
texture.SetData(span);
return texture;
}
/// <summary>
/// Allocates a new read write buffer with the specified parameters.
/// </summary>
@@ -469,6 +672,102 @@ namespace ComputeSharp
return texture;
}
/// <summary>
/// Allocates a new writeable 2D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <returns>A zeroed <see cref="ReadWriteTexture2D{T,TPixel}"/> instance of size [<paramref name="width"/>, <paramref name="height"/>].</returns>
[Pure]
public static ReadWriteTexture2D<T, TPixel> AllocateReadWriteTexture2D<T, TPixel>(this GraphicsDevice device, int width, int height)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return new(device, width, height);
}
/// <summary>
/// Allocates a new writeable 2D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <returns>A <see cref="ReadWriteTexture2D{T,TPixel}"/> instance with the contents of the input array.</returns>
[Pure]
public static ReadWriteTexture2D<T, TPixel> AllocateReadWriteTexture2D<T, TPixel>(this GraphicsDevice device, T[] array, int width, int height)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return device.AllocateReadWriteTexture2D<T, TPixel>(array.AsSpan(), width, height);
}
/// <summary>
/// Allocates a new writeable 2D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <param name="offset">The starting offset within <paramref name="source"/> to read data from.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <returns>A <see cref="ReadWriteTexture2D{T,TPixel}"/> instance with the contents of the input array.</returns>
[Pure]
public static ReadWriteTexture2D<T, TPixel> AllocateReadWriteTexture2D<T, TPixel>(this GraphicsDevice device, T[] array, int offset, int width, int height)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return device.AllocateReadWriteTexture2D<T, TPixel>(array.AsSpan(offset), width, height);
}
/// <summary>
/// Allocates a new writeable 2D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <returns>A read write <see cref="ReadWriteTexture2D{T,TPixel}"/> instance with the contents of the input array.</returns>
[Pure]
public static ReadWriteTexture2D<T, TPixel> AllocateReadWriteTexture2D<T, TPixel>(this GraphicsDevice device, T[,] array)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
ReadWriteTexture2D<T, TPixel> texture = new(device, array.GetLength(1), array.GetLength(0));
texture.SetData(array);
return texture;
}
/// <summary>
/// Allocates a new writeable 2D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="span">The input <see cref="ReadOnlySpan{T}"/> with the data to copy on the allocated texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <returns>A <see cref="ReadWriteTexture2D{T,TPixel}"/> instance with the contents of the input <see cref="ReadOnlySpan{T}"/>.</returns>
[Pure]
public static ReadWriteTexture2D<T, TPixel> AllocateReadWriteTexture2D<T, TPixel>(this GraphicsDevice device, ReadOnlySpan<T> span, int width, int height)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
ReadWriteTexture2D<T, TPixel> texture = new(device, width, height);
texture.SetData(span);
return texture;
}
/// <summary>
/// Allocates a new writeable 3D texture with the specified parameters.
/// </summary>
@@ -563,6 +862,110 @@ namespace ComputeSharp
return texture;
}
/// <summary>
/// Allocates a new writeable 3D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
/// <returns>A zeroed <see cref="ReadWriteTexture3D{T,TPixel}"/> instance of size [<paramref name="width"/>, <paramref name="height"/>].</returns>
[Pure]
public static ReadWriteTexture3D<T, TPixel> AllocateReadWriteTexture3D<T, TPixel>(this GraphicsDevice device, int width, int height, int depth)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return new(device, width, height, depth);
}
/// <summary>
/// Allocates a new writeable 3D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
/// <returns>A <see cref="ReadWriteTexture3D{T,TPixel}"/> instance with the contents of the input array.</returns>
[Pure]
public static ReadWriteTexture3D<T, TPixel> AllocateReadWriteTexture3D<T, TPixel>(this GraphicsDevice device, T[] array, int width, int height, int depth)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return device.AllocateReadWriteTexture3D<T, TPixel>(array.AsSpan(), width, height, depth);
}
/// <summary>
/// Allocates a new writeable 3D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <param name="offset">The starting offset within <paramref name="source"/> to read data from.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
/// <returns>A <see cref="ReadWriteTexture3D{T,TPixel}"/> instance with the contents of the input array.</returns>
[Pure]
public static ReadWriteTexture3D<T, TPixel> AllocateReadWriteTexture3D<T, TPixel>(this GraphicsDevice device, T[] array, int offset, int width, int height, int depth)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return device.AllocateReadWriteTexture3D<T, TPixel>(array.AsSpan(offset), width, height, depth);
}
/// <summary>
/// Allocates a new writeable 3D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="array">The input <typeparamref name="T"/> array with the data to copy on the allocated texture.</param>
/// <returns>A read write <see cref="ReadWriteTexture3D{T,TPixel}"/> instance with the contents of the input array.</returns>
/// <remarks>
/// The source 3D array needs to have each 2D plane stacked on the depth axis.
/// That is, the expected layout of the input array has to be [depth, height, width].
/// </remarks>
[Pure]
public static ReadWriteTexture3D<T, TPixel> AllocateReadWriteTexture3D<T, TPixel>(this GraphicsDevice device, T[,,] array)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
ReadWriteTexture3D<T, TPixel> texture = new(device, array.GetLength(2), array.GetLength(1), array.GetLength(0));
texture.SetData(array);
return texture;
}
/// <summary>
/// Allocates a new writeable 3D texture with the specified parameters.
/// </summary>
/// <typeparam name="T">The type of items to store in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The <see cref="GraphicsDevice"/> instance to use to allocate the texture.</param>
/// <param name="span">The input <see cref="ReadOnlySpan{T}"/> with the data to copy on the allocated texture.</param>
/// <param name="width">The width of the texture.</param>
/// <param name="height">The height of the texture.</param>
/// <param name="depth">The depth of the texture.</param>
/// <returns>A <see cref="ReadWriteTexture3D{T,TPixel}"/> instance with the contents of the input <see cref="ReadOnlySpan{T}"/>.</returns>
[Pure]
public static ReadWriteTexture3D<T, TPixel> AllocateReadWriteTexture3D<T, TPixel>(this GraphicsDevice device, ReadOnlySpan<T> span, int width, int height, int depth)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
ReadWriteTexture3D<T, TPixel> texture = new(device, width, height, depth);
texture.SetData(span);
return texture;
}
/// <summary>
/// Compiles and runs the input shader on a target <see cref="GraphicsDevice"/> instance, with the specified parameters.
/// </summary>
+28
ファイルの表示
@@ -20,4 +20,32 @@
PrivateAssets="contentfiles;build"/>
</ItemGroup>
<ItemGroup>
<None Update="Texture2DTests.Pixels.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>Texture2DTests.Pixels.g.cs</LastGenOutput>
</None>
<None Update="Texture3DTests.Pixels.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>Texture3DTests.Pixels.g.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup>
<ItemGroup>
<Compile Update="Texture2DTests.Pixels.g.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Texture2DTests.Pixels.tt</DependentUpon>
</Compile>
<Compile Update="Texture3DTests.Pixels.g.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Texture3DTests.Pixels.tt</DependentUpon>
</Compile>
</ItemGroup>
</Project>
+50
ファイルの表示
@@ -1,8 +1,11 @@
using System;
using System.Diagnostics.Contracts;
using ComputeSharp.__Internals;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
#pragma warning disable CS0618
namespace ComputeSharp.Tests.Extensions
{
/// <summary>
@@ -52,6 +55,29 @@ namespace ComputeSharp.Tests.Extensions
};
}
/// <summary>
/// Allocates a new <see cref="Texture2D{T}"/> instance of the specified type.
/// </summary>
/// <typeparam name="T">The type of items in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance to allocate the texture for.</param>
/// <param name="type">The type of texture to allocate.</param>
/// <param name="width">The width of the texture to create.</param>
/// <param name="height">The height of the texture to create.</param>
/// <returns>A <see cref="Texture2D{T}"/> instance of the requested size.</returns>
[Pure]
public static Texture2D<T> AllocateTexture2D<T, TPixel>(this GraphicsDevice device, Type type, int width, int height)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return type switch
{
_ when type == typeof(ReadOnlyTexture2D<,>) => device.AllocateReadOnlyTexture2D<T, TPixel>(width, height),
_ when type == typeof(ReadWriteTexture2D<,>) => device.AllocateReadWriteTexture2D<T, TPixel>(width, height),
_ => throw new ArgumentException($"Invalid type: {type}", nameof(type))
};
}
/// <summary>
/// Allocates a new <see cref="Texture3D{T}"/> instance of the specified type.
/// </summary>
@@ -74,6 +100,30 @@ namespace ComputeSharp.Tests.Extensions
};
}
/// <summary>
/// Allocates a new <see cref="Texture3D{T}"/> instance of the specified type.
/// </summary>
/// <typeparam name="T">The type of items in the texture.</typeparam>
/// <typeparam name="TPixel">The type of pixels used on the GPU side.</typeparam>
/// <param name="device">The target <see cref="GraphicsDevice"/> instance to allocate the texture for.</param>
/// <param name="type">The type of texture to allocate.</param>
/// <param name="width">The width of the texture to create.</param>
/// <param name="height">The height of the texture to create.</param>
/// <param name="depth">The depth of the texture to create.</param>
/// <returns>A <see cref="Texture3D{T}"/> instance of the requested size.</returns>
[Pure]
public static Texture3D<T> AllocateTexture3D<T, TPixel>(this GraphicsDevice device, Type type, int width, int height, int depth)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
return type switch
{
_ when type == typeof(ReadOnlyTexture3D<,>) => device.AllocateReadOnlyTexture3D<T, TPixel>(width, height, depth),
_ when type == typeof(ReadWriteTexture3D<,>) => device.AllocateReadWriteTexture3D<T, TPixel>(width, height, depth),
_ => throw new ArgumentException($"Invalid type: {type}", nameof(type))
};
}
/// <summary>
/// Allocates a new <see cref="Buffer{T}"/> instance of the specified type.
/// </summary>
+73
ファイルの表示
@@ -0,0 +1,73 @@
using System;
using System.Numerics;
using System.Reflection;
using ComputeSharp.__Internals;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable CS0618
namespace ComputeSharp.Tests
{
public partial class Texture2DTests
{
[TestMethod]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Bgra32), typeof(Vector4))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Bgra32), typeof(Float4))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(R16), typeof(float))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(R8), typeof(float))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg16), typeof(Vector2))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg16), typeof(Float2))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg32), typeof(Vector2))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rg32), typeof(Float2))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba32), typeof(Vector4))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba32), typeof(Float4))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba64), typeof(Vector4))]
[DataRow(typeof(ReadOnlyTexture2D<,>), typeof(Rgba64), typeof(Float4))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(Bgra32), typeof(Vector4))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(Bgra32), typeof(Float4))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(R16), typeof(float))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(R8), typeof(float))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg16), typeof(Vector2))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg16), typeof(Float2))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg32), typeof(Vector2))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rg32), typeof(Float2))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba32), typeof(Vector4))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba32), typeof(Float4))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba64), typeof(Vector4))]
[DataRow(typeof(ReadWriteTexture2D<,>), typeof(Rgba64), typeof(Float4))]
public void Allocate_Uninitialized_Pixel_Ok(Type textureType, Type t, Type tPixel)
{
static void Test<T, TPixel>(Type textureType)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
using Texture2D<T> texture = Gpu.Default.AllocateTexture2D<T, TPixel>(textureType, 128, 128);
Assert.IsNotNull(texture);
Assert.AreEqual(texture.Width, 128);
Assert.AreEqual(texture.Height, 128);
Assert.AreSame(texture.GraphicsDevice, Gpu.Default);
if (textureType == typeof(ReadOnlyTexture2D<,>))
{
Assert.IsTrue(texture is ReadOnlyTexture2D<T, TPixel>);
}
else
{
Assert.IsTrue(texture is ReadWriteTexture2D<T, TPixel>);
}
}
try
{
new Action<Type>(Test<Rgba32, Vector4>).Method.GetGenericMethodDefinition().MakeGenericMethod(t, tPixel).Invoke(null, new[] { textureType });
}
catch (TargetInvocationException e) when (e.InnerException is not null)
{
throw e.InnerException;
}
}
}
}
+254
ファイルの表示
@@ -0,0 +1,254 @@
using System;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests
{
public partial class Texture2DTests
{
[TestMethod]
[DataRow(typeof(Bgra32), typeof(Vector4))]
[DataRow(typeof(Bgra32), typeof(Float4))]
[DataRow(typeof(R16), typeof(float))]
[DataRow(typeof(R8), typeof(float))]
[DataRow(typeof(Rg16), typeof(Vector2))]
[DataRow(typeof(Rg16), typeof(Float2))]
[DataRow(typeof(Rg32), typeof(Vector2))]
[DataRow(typeof(Rg32), typeof(Float2))]
[DataRow(typeof(Rgba32), typeof(Vector4))]
[DataRow(typeof(Rgba32), typeof(Float4))]
[DataRow(typeof(Rgba64), typeof(Vector4))]
[DataRow(typeof(Rgba64), typeof(Float4))]
public void Dispatch_NormalizedTexture2D(Type t, Type tPixel)
{
if (t == typeof(Bgra32) && tPixel == typeof(Vector4))
{
using ReadOnlyTexture2D<Bgra32, Vector4> source = Gpu.Default.AllocateReadOnlyTexture2D<Bgra32, Vector4>(128, 128);
using ReadWriteTexture2D<Bgra32, Vector4> destination = Gpu.Default.AllocateReadWriteTexture2D<Bgra32, Vector4>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_Bgra32_Vector4(source, destination));
}
if (t == typeof(Bgra32) && tPixel == typeof(Float4))
{
using ReadOnlyTexture2D<Bgra32, Float4> source = Gpu.Default.AllocateReadOnlyTexture2D<Bgra32, Float4>(128, 128);
using ReadWriteTexture2D<Bgra32, Float4> destination = Gpu.Default.AllocateReadWriteTexture2D<Bgra32, Float4>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_Bgra32_Float4(source, destination));
}
if (t == typeof(R16) && tPixel == typeof(float))
{
using ReadOnlyTexture2D<R16, float> source = Gpu.Default.AllocateReadOnlyTexture2D<R16, float>(128, 128);
using ReadWriteTexture2D<R16, float> destination = Gpu.Default.AllocateReadWriteTexture2D<R16, float>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_R16_float(source, destination));
}
if (t == typeof(R8) && tPixel == typeof(float))
{
using ReadOnlyTexture2D<R8, float> source = Gpu.Default.AllocateReadOnlyTexture2D<R8, float>(128, 128);
using ReadWriteTexture2D<R8, float> destination = Gpu.Default.AllocateReadWriteTexture2D<R8, float>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_R8_float(source, destination));
}
if (t == typeof(Rg16) && tPixel == typeof(Vector2))
{
using ReadOnlyTexture2D<Rg16, Vector2> source = Gpu.Default.AllocateReadOnlyTexture2D<Rg16, Vector2>(128, 128);
using ReadWriteTexture2D<Rg16, Vector2> destination = Gpu.Default.AllocateReadWriteTexture2D<Rg16, Vector2>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_Rg16_Vector2(source, destination));
}
if (t == typeof(Rg16) && tPixel == typeof(Float2))
{
using ReadOnlyTexture2D<Rg16, Float2> source = Gpu.Default.AllocateReadOnlyTexture2D<Rg16, Float2>(128, 128);
using ReadWriteTexture2D<Rg16, Float2> destination = Gpu.Default.AllocateReadWriteTexture2D<Rg16, Float2>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_Rg16_Float2(source, destination));
}
if (t == typeof(Rg32) && tPixel == typeof(Vector2))
{
using ReadOnlyTexture2D<Rg32, Vector2> source = Gpu.Default.AllocateReadOnlyTexture2D<Rg32, Vector2>(128, 128);
using ReadWriteTexture2D<Rg32, Vector2> destination = Gpu.Default.AllocateReadWriteTexture2D<Rg32, Vector2>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_Rg32_Vector2(source, destination));
}
if (t == typeof(Rg32) && tPixel == typeof(Float2))
{
using ReadOnlyTexture2D<Rg32, Float2> source = Gpu.Default.AllocateReadOnlyTexture2D<Rg32, Float2>(128, 128);
using ReadWriteTexture2D<Rg32, Float2> destination = Gpu.Default.AllocateReadWriteTexture2D<Rg32, Float2>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_Rg32_Float2(source, destination));
}
if (t == typeof(Rgba32) && tPixel == typeof(Vector4))
{
using ReadOnlyTexture2D<Rgba32, Vector4> source = Gpu.Default.AllocateReadOnlyTexture2D<Rgba32, Vector4>(128, 128);
using ReadWriteTexture2D<Rgba32, Vector4> destination = Gpu.Default.AllocateReadWriteTexture2D<Rgba32, Vector4>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_Rgba32_Vector4(source, destination));
}
if (t == typeof(Rgba32) && tPixel == typeof(Float4))
{
using ReadOnlyTexture2D<Rgba32, Float4> source = Gpu.Default.AllocateReadOnlyTexture2D<Rgba32, Float4>(128, 128);
using ReadWriteTexture2D<Rgba32, Float4> destination = Gpu.Default.AllocateReadWriteTexture2D<Rgba32, Float4>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_Rgba32_Float4(source, destination));
}
if (t == typeof(Rgba64) && tPixel == typeof(Vector4))
{
using ReadOnlyTexture2D<Rgba64, Vector4> source = Gpu.Default.AllocateReadOnlyTexture2D<Rgba64, Vector4>(128, 128);
using ReadWriteTexture2D<Rgba64, Vector4> destination = Gpu.Default.AllocateReadWriteTexture2D<Rgba64, Vector4>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_Rgba64_Vector4(source, destination));
}
if (t == typeof(Rgba64) && tPixel == typeof(Float4))
{
using ReadOnlyTexture2D<Rgba64, Float4> source = Gpu.Default.AllocateReadOnlyTexture2D<Rgba64, Float4>(128, 128);
using ReadWriteTexture2D<Rgba64, Float4> destination = Gpu.Default.AllocateReadWriteTexture2D<Rgba64, Float4>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_Rgba64_Float4(source, destination));
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Bgra32_Vector4 : IComputeShader
{
public readonly ReadOnlyTexture2D<Bgra32, Vector4> source;
public readonly ReadWriteTexture2D<Bgra32, Vector4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader
{
public readonly ReadOnlyTexture2D<Bgra32, Float4> source;
public readonly ReadWriteTexture2D<Bgra32, Float4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_R16_float : IComputeShader
{
public readonly ReadOnlyTexture2D<R16, float> source;
public readonly ReadWriteTexture2D<R16, float> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_R8_float : IComputeShader
{
public readonly ReadOnlyTexture2D<R8, float> source;
public readonly ReadWriteTexture2D<R8, float> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rg16_Vector2 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rg16, Vector2> source;
public readonly ReadWriteTexture2D<Rg16, Vector2> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rg16, Float2> source;
public readonly ReadWriteTexture2D<Rg16, Float2> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rg32_Vector2 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rg32, Vector2> source;
public readonly ReadWriteTexture2D<Rg32, Vector2> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rg32, Float2> source;
public readonly ReadWriteTexture2D<Rg32, Float2> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rgba32_Vector4 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rgba32, Vector4> source;
public readonly ReadWriteTexture2D<Rgba32, Vector4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rgba32, Float4> source;
public readonly ReadWriteTexture2D<Rgba32, Float4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rgba64_Vector4 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rgba64, Vector4> source;
public readonly ReadWriteTexture2D<Rgba64, Vector4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader
{
public readonly ReadOnlyTexture2D<Rgba64, Float4> source;
public readonly ReadWriteTexture2D<Rgba64, Float4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
}
}
+81
ファイルの表示
@@ -0,0 +1,81 @@
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".g.cs"#>
<#
var typesMap = new Dictionary<string, string[]>
{
["Bgra32"] = new[] { "Vector4", "Float4" },
["R16"] = new[] { "float" },
["R8"] = new[] { "float" },
["Rg16"] = new[] { "Vector2", "Float2" },
["Rg32"] = new[] { "Vector2", "Float2" },
["Rgba32"] = new[] { "Vector4", "Float4" },
["Rgba64"] = new[] { "Vector4", "Float4" }
};
IEnumerable<(string T, string TPixel)> EnumerateTypes()
{
foreach (var pair in typesMap)
foreach (var tPixel in pair.Value)
yield return (pair.Key, tPixel);
}
#>
using System;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests
{
public partial class Texture2DTests
{
[TestMethod]
<#
foreach (var (t, tPixel) in EnumerateTypes())
{
#>
[DataRow(typeof(<#=t#>), typeof(<#=tPixel#>))]
<#
}
#>
public void Dispatch_NormalizedTexture2D(Type t, Type tPixel)
{
<#
foreach (var (t, tPixel) in EnumerateTypes())
{
#>
if (t == typeof(<#=t#>) && tPixel == typeof(<#=tPixel#>))
{
using ReadOnlyTexture2D<<#=t#>, <#=tPixel#>> source = Gpu.Default.AllocateReadOnlyTexture2D<<#=t#>, <#=tPixel#>>(128, 128);
using ReadWriteTexture2D<<#=t#>, <#=tPixel#>> destination = Gpu.Default.AllocateReadWriteTexture2D<<#=t#>, <#=tPixel#>>(128, 128);
Gpu.Default.For(128, 128, new Shader_Unorm_<#=t#>_<#=tPixel#>(source, destination));
}
<#
}
#>
}
<#
foreach (var (t, tPixel) in EnumerateTypes())
{
#>
[AutoConstructor]
internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader
{
public readonly ReadOnlyTexture2D<<#=t#>, <#=tPixel#>> source;
public readonly ReadWriteTexture2D<<#=t#>, <#=tPixel#>> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XY] = (source[ids.XY] + destination[ids.XY]) / 2;
}
}
<#
}
#>
}
}
+74
ファイルの表示
@@ -0,0 +1,74 @@
using System;
using System.Numerics;
using System.Reflection;
using ComputeSharp.__Internals;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable CS0618
namespace ComputeSharp.Tests
{
public partial class Texture3DTests
{
[TestMethod]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Bgra32), typeof(Vector4))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Bgra32), typeof(Float4))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(R16), typeof(float))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(R8), typeof(float))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg16), typeof(Vector2))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg16), typeof(Float2))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg32), typeof(Vector2))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rg32), typeof(Float2))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba32), typeof(Vector4))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba32), typeof(Float4))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba64), typeof(Vector4))]
[DataRow(typeof(ReadOnlyTexture3D<,>), typeof(Rgba64), typeof(Float4))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(Bgra32), typeof(Vector4))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(Bgra32), typeof(Float4))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(R16), typeof(float))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(R8), typeof(float))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg16), typeof(Vector2))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg16), typeof(Float2))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg32), typeof(Vector2))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rg32), typeof(Float2))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba32), typeof(Vector4))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba32), typeof(Float4))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba64), typeof(Vector4))]
[DataRow(typeof(ReadWriteTexture3D<,>), typeof(Rgba64), typeof(Float4))]
public void Allocate_Uninitialized_Pixel_Ok(Type textureType, Type t, Type tPixel)
{
static void Test<T, TPixel>(Type textureType)
where T : unmanaged, IUnorm<TPixel>
where TPixel : unmanaged
{
using Texture3D<T> texture = Gpu.Default.AllocateTexture3D<T, TPixel>(textureType, 128, 128, 2);
Assert.IsNotNull(texture);
Assert.AreEqual(texture.Width, 128);
Assert.AreEqual(texture.Height, 128);
Assert.AreEqual(texture.Depth, 2);
Assert.AreSame(texture.GraphicsDevice, Gpu.Default);
if (textureType == typeof(ReadOnlyTexture3D<,>))
{
Assert.IsTrue(texture is ReadOnlyTexture3D<T, TPixel>);
}
else
{
Assert.IsTrue(texture is ReadWriteTexture3D<T, TPixel>);
}
}
try
{
new Action<Type>(Test<Rgba32, Vector4>).Method.GetGenericMethodDefinition().MakeGenericMethod(t, tPixel).Invoke(null, new[] { textureType });
}
catch (TargetInvocationException e) when (e.InnerException is not null)
{
throw e.InnerException;
}
}
}
}
+254
ファイルの表示
@@ -0,0 +1,254 @@
using System;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests
{
public partial class Texture3DTests
{
[TestMethod]
[DataRow(typeof(Bgra32), typeof(Vector4))]
[DataRow(typeof(Bgra32), typeof(Float4))]
[DataRow(typeof(R16), typeof(float))]
[DataRow(typeof(R8), typeof(float))]
[DataRow(typeof(Rg16), typeof(Vector2))]
[DataRow(typeof(Rg16), typeof(Float2))]
[DataRow(typeof(Rg32), typeof(Vector2))]
[DataRow(typeof(Rg32), typeof(Float2))]
[DataRow(typeof(Rgba32), typeof(Vector4))]
[DataRow(typeof(Rgba32), typeof(Float4))]
[DataRow(typeof(Rgba64), typeof(Vector4))]
[DataRow(typeof(Rgba64), typeof(Float4))]
public void Dispatch_NormalizedTexture3D(Type t, Type tPixel)
{
if (t == typeof(Bgra32) && tPixel == typeof(Vector4))
{
using ReadOnlyTexture3D<Bgra32, Vector4> source = Gpu.Default.AllocateReadOnlyTexture3D<Bgra32, Vector4>(128, 128, 2);
using ReadWriteTexture3D<Bgra32, Vector4> destination = Gpu.Default.AllocateReadWriteTexture3D<Bgra32, Vector4>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_Bgra32_Vector4(source, destination));
}
if (t == typeof(Bgra32) && tPixel == typeof(Float4))
{
using ReadOnlyTexture3D<Bgra32, Float4> source = Gpu.Default.AllocateReadOnlyTexture3D<Bgra32, Float4>(128, 128, 2);
using ReadWriteTexture3D<Bgra32, Float4> destination = Gpu.Default.AllocateReadWriteTexture3D<Bgra32, Float4>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_Bgra32_Float4(source, destination));
}
if (t == typeof(R16) && tPixel == typeof(float))
{
using ReadOnlyTexture3D<R16, float> source = Gpu.Default.AllocateReadOnlyTexture3D<R16, float>(128, 128, 2);
using ReadWriteTexture3D<R16, float> destination = Gpu.Default.AllocateReadWriteTexture3D<R16, float>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_R16_float(source, destination));
}
if (t == typeof(R8) && tPixel == typeof(float))
{
using ReadOnlyTexture3D<R8, float> source = Gpu.Default.AllocateReadOnlyTexture3D<R8, float>(128, 128, 2);
using ReadWriteTexture3D<R8, float> destination = Gpu.Default.AllocateReadWriteTexture3D<R8, float>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_R8_float(source, destination));
}
if (t == typeof(Rg16) && tPixel == typeof(Vector2))
{
using ReadOnlyTexture3D<Rg16, Vector2> source = Gpu.Default.AllocateReadOnlyTexture3D<Rg16, Vector2>(128, 128, 2);
using ReadWriteTexture3D<Rg16, Vector2> destination = Gpu.Default.AllocateReadWriteTexture3D<Rg16, Vector2>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rg16_Vector2(source, destination));
}
if (t == typeof(Rg16) && tPixel == typeof(Float2))
{
using ReadOnlyTexture3D<Rg16, Float2> source = Gpu.Default.AllocateReadOnlyTexture3D<Rg16, Float2>(128, 128, 2);
using ReadWriteTexture3D<Rg16, Float2> destination = Gpu.Default.AllocateReadWriteTexture3D<Rg16, Float2>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rg16_Float2(source, destination));
}
if (t == typeof(Rg32) && tPixel == typeof(Vector2))
{
using ReadOnlyTexture3D<Rg32, Vector2> source = Gpu.Default.AllocateReadOnlyTexture3D<Rg32, Vector2>(128, 128, 2);
using ReadWriteTexture3D<Rg32, Vector2> destination = Gpu.Default.AllocateReadWriteTexture3D<Rg32, Vector2>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rg32_Vector2(source, destination));
}
if (t == typeof(Rg32) && tPixel == typeof(Float2))
{
using ReadOnlyTexture3D<Rg32, Float2> source = Gpu.Default.AllocateReadOnlyTexture3D<Rg32, Float2>(128, 128, 2);
using ReadWriteTexture3D<Rg32, Float2> destination = Gpu.Default.AllocateReadWriteTexture3D<Rg32, Float2>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rg32_Float2(source, destination));
}
if (t == typeof(Rgba32) && tPixel == typeof(Vector4))
{
using ReadOnlyTexture3D<Rgba32, Vector4> source = Gpu.Default.AllocateReadOnlyTexture3D<Rgba32, Vector4>(128, 128, 2);
using ReadWriteTexture3D<Rgba32, Vector4> destination = Gpu.Default.AllocateReadWriteTexture3D<Rgba32, Vector4>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rgba32_Vector4(source, destination));
}
if (t == typeof(Rgba32) && tPixel == typeof(Float4))
{
using ReadOnlyTexture3D<Rgba32, Float4> source = Gpu.Default.AllocateReadOnlyTexture3D<Rgba32, Float4>(128, 128, 2);
using ReadWriteTexture3D<Rgba32, Float4> destination = Gpu.Default.AllocateReadWriteTexture3D<Rgba32, Float4>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rgba32_Float4(source, destination));
}
if (t == typeof(Rgba64) && tPixel == typeof(Vector4))
{
using ReadOnlyTexture3D<Rgba64, Vector4> source = Gpu.Default.AllocateReadOnlyTexture3D<Rgba64, Vector4>(128, 128, 2);
using ReadWriteTexture3D<Rgba64, Vector4> destination = Gpu.Default.AllocateReadWriteTexture3D<Rgba64, Vector4>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rgba64_Vector4(source, destination));
}
if (t == typeof(Rgba64) && tPixel == typeof(Float4))
{
using ReadOnlyTexture3D<Rgba64, Float4> source = Gpu.Default.AllocateReadOnlyTexture3D<Rgba64, Float4>(128, 128, 2);
using ReadWriteTexture3D<Rgba64, Float4> destination = Gpu.Default.AllocateReadWriteTexture3D<Rgba64, Float4>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_Rgba64_Float4(source, destination));
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Bgra32_Vector4 : IComputeShader
{
public readonly ReadOnlyTexture3D<Bgra32, Vector4> source;
public readonly ReadWriteTexture3D<Bgra32, Vector4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Bgra32_Float4 : IComputeShader
{
public readonly ReadOnlyTexture3D<Bgra32, Float4> source;
public readonly ReadWriteTexture3D<Bgra32, Float4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_R16_float : IComputeShader
{
public readonly ReadOnlyTexture3D<R16, float> source;
public readonly ReadWriteTexture3D<R16, float> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_R8_float : IComputeShader
{
public readonly ReadOnlyTexture3D<R8, float> source;
public readonly ReadWriteTexture3D<R8, float> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rg16_Vector2 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rg16, Vector2> source;
public readonly ReadWriteTexture3D<Rg16, Vector2> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rg16_Float2 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rg16, Float2> source;
public readonly ReadWriteTexture3D<Rg16, Float2> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rg32_Vector2 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rg32, Vector2> source;
public readonly ReadWriteTexture3D<Rg32, Vector2> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rg32_Float2 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rg32, Float2> source;
public readonly ReadWriteTexture3D<Rg32, Float2> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rgba32_Vector4 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rgba32, Vector4> source;
public readonly ReadWriteTexture3D<Rgba32, Vector4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rgba32_Float4 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rgba32, Float4> source;
public readonly ReadWriteTexture3D<Rgba32, Float4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rgba64_Vector4 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rgba64, Vector4> source;
public readonly ReadWriteTexture3D<Rgba64, Vector4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
[AutoConstructor]
internal readonly partial struct Shader_Unorm_Rgba64_Float4 : IComputeShader
{
public readonly ReadOnlyTexture3D<Rgba64, Float4> source;
public readonly ReadWriteTexture3D<Rgba64, Float4> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
}
}
+81
ファイルの表示
@@ -0,0 +1,81 @@
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".g.cs"#>
<#
var typesMap = new Dictionary<string, string[]>
{
["Bgra32"] = new[] { "Vector4", "Float4" },
["R16"] = new[] { "float" },
["R8"] = new[] { "float" },
["Rg16"] = new[] { "Vector2", "Float2" },
["Rg32"] = new[] { "Vector2", "Float2" },
["Rgba32"] = new[] { "Vector4", "Float4" },
["Rgba64"] = new[] { "Vector4", "Float4" }
};
IEnumerable<(string T, string TPixel)> EnumerateTypes()
{
foreach (var pair in typesMap)
foreach (var tPixel in pair.Value)
yield return (pair.Key, tPixel);
}
#>
using System;
using System.Numerics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ComputeSharp.Tests
{
public partial class Texture3DTests
{
[TestMethod]
<#
foreach (var (t, tPixel) in EnumerateTypes())
{
#>
[DataRow(typeof(<#=t#>), typeof(<#=tPixel#>))]
<#
}
#>
public void Dispatch_NormalizedTexture3D(Type t, Type tPixel)
{
<#
foreach (var (t, tPixel) in EnumerateTypes())
{
#>
if (t == typeof(<#=t#>) && tPixel == typeof(<#=tPixel#>))
{
using ReadOnlyTexture3D<<#=t#>, <#=tPixel#>> source = Gpu.Default.AllocateReadOnlyTexture3D<<#=t#>, <#=tPixel#>>(128, 128, 2);
using ReadWriteTexture3D<<#=t#>, <#=tPixel#>> destination = Gpu.Default.AllocateReadWriteTexture3D<<#=t#>, <#=tPixel#>>(128, 128, 2);
Gpu.Default.For(128, 128, 2, new Shader_Unorm_<#=t#>_<#=tPixel#>(source, destination));
}
<#
}
#>
}
<#
foreach (var (t, tPixel) in EnumerateTypes())
{
#>
[AutoConstructor]
internal readonly partial struct Shader_Unorm_<#=t#>_<#=tPixel#> : IComputeShader
{
public readonly ReadOnlyTexture3D<<#=t#>, <#=tPixel#>> source;
public readonly ReadWriteTexture3D<<#=t#>, <#=tPixel#>> destination;
public void Execute(ThreadIds ids)
{
destination[ids.XYZ] = (source[ids.XYZ] + destination[ids.XYZ]) / 2;
}
}
<#
}
#>
}
}