diff --git a/LuaScript.Generator/GpuShaderSourceGenerator.cs b/LuaScript.Generator/GpuShaderSourceGenerator.cs new file mode 100644 index 0000000..aff3174 --- /dev/null +++ b/LuaScript.Generator/GpuShaderSourceGenerator.cs @@ -0,0 +1,220 @@ +using System.Collections.Immutable; +using System.Globalization; +using System.IO; +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Text; + +namespace LuaScript.Generator +{ + [Generator] + public sealed class GpuShaderSourceGenerator : IIncrementalGenerator + { + private const string AttributeName = "LuaScript.Engine.Processing.GpuPixelOperationShaderAttribute"; + + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var registrations = context.CompilationProvider.Select(static (compilation, _) => CollectRegistrations(compilation)); + var files = context.AdditionalTextsProvider + .Where(static file => file.Path.EndsWith(".hlsl", StringComparison.OrdinalIgnoreCase)) + .Select(static (file, token) => new GpuShaderFile(Normalize(file.Path), file.GetText(token)?.ToString() ?? string.Empty)) + .Collect(); + + context.RegisterSourceOutput(registrations.Combine(files), static (context, source) => + { + var (registrations, files) = source; + if (registrations.Length == 0) + return; + + var result = Resolve(registrations, files); + if (result.Errors.Length > 0) + { + context.AddSource("GpuPixelOperationShaderRegistry.Errors.g.cs", SourceText.From(EmitErrors(result.Errors), Encoding.UTF8)); + return; + } + if (result.Sources.IsDefaultOrEmpty) + return; + + context.AddSource("GpuPixelOperationShaderRegistry.g.cs", SourceText.From(Emit(result.Sources), Encoding.UTF8)); + }); + } + + private static ImmutableArray CollectRegistrations(Compilation compilation) + { + var registrations = ImmutableArray.CreateBuilder(); + foreach (var attribute in compilation.Assembly.GetAttributes()) + { + if (attribute.AttributeClass?.ToDisplayString() != AttributeName || attribute.ConstructorArguments.Length < 2) + continue; + if (attribute.ConstructorArguments[0].Value is not string apiName || attribute.ConstructorArguments[1].Value is not string fileName) + continue; + registrations.Add(new GpuShaderRegistration(apiName, Normalize(fileName), attribute.ApplicationSyntaxReference?.Span.Start ?? 0)); + } + return registrations.ToImmutable(); + } + + private static GpuShaderResolution Resolve(ImmutableArray registrations, ImmutableArray files) + { + var apiNames = new HashSet(StringComparer.Ordinal); + var identifiers = new HashSet(StringComparer.Ordinal); + var sources = ImmutableArray.CreateBuilder(); + var errors = ImmutableArray.CreateBuilder(); + + foreach (var registration in registrations.OrderBy(static r => r.Position).ThenBy(static r => r.ApiName, StringComparer.Ordinal)) + { + if (!apiNames.Add(registration.ApiName)) + { + errors.Add($"GPU shader API '{registration.ApiName}' is registered multiple times"); + continue; + } + + var matched = files.Where(file => Matches(file.Path, registration.FileName)).ToArray(); + if (matched.Length == 0) + { + errors.Add($"GPU shader file '{registration.FileName}' for API '{registration.ApiName}' was not found"); + continue; + } + if (matched.Length > 1) + { + errors.Add($"GPU shader file '{registration.FileName}' for API '{registration.ApiName}' matched multiple additional files"); + continue; + } + + string identifier = ToIdentifier(registration.ApiName); + if (!identifiers.Add(identifier)) + { + errors.Add($"GPU shader API '{registration.ApiName}' resolves to a duplicate identifier"); + continue; + } + + sources.Add(new GpuShaderSource(registration.ApiName, identifier, matched[0].Source)); + } + + return new GpuShaderResolution(sources.ToImmutable(), errors.ToImmutable()); + } + + private static bool Matches(string filePath, string registrationPath) + { + if (string.Equals(filePath, registrationPath, StringComparison.OrdinalIgnoreCase)) + return true; + return filePath.EndsWith("/" + registrationPath, StringComparison.OrdinalIgnoreCase); + } + + private static string Normalize(string path) => path.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/'); + + private static string ToIdentifier(string apiName) + { + var builder = new StringBuilder(); + bool upper = true; + foreach (char c in apiName) + { + if (!char.IsLetterOrDigit(c)) + { + upper = true; + continue; + } + builder.Append(upper ? char.ToUpperInvariant(c) : c); + upper = false; + } + if (builder.Length == 0 || char.IsDigit(builder[0])) + builder.Insert(0, '_'); + return builder.ToString(); + } + + private static string Emit(ImmutableArray sources) + { + var builder = new StringBuilder(); + builder.AppendLine("#nullable enable"); + builder.AppendLine("namespace LuaScript.Engine.Processing"); + builder.AppendLine("{"); + builder.AppendLine(" internal static class GpuPixelOperationShaderRegistry"); + builder.AppendLine(" {"); + builder.AppendLine(" internal static bool TryGet(string apiName, out string source)"); + builder.AppendLine(" {"); + builder.AppendLine(" switch (apiName)"); + builder.AppendLine(" {"); + foreach (var source in sources) + builder.AppendLine($" case {Literal(source.ApiName)}: source = {source.Identifier}; return true;"); + builder.AppendLine(" default: source = string.Empty; return false;"); + builder.AppendLine(" }"); + builder.AppendLine(" }"); + builder.AppendLine(); + foreach (var source in sources) + builder.AppendLine($" internal const string {source.Identifier} = {Literal(source.Source)};"); + builder.AppendLine(" }"); + builder.AppendLine("}"); + return builder.ToString(); + } + + private static string EmitErrors(ImmutableArray errors) + { + var builder = new StringBuilder(); + foreach (var error in errors) + builder.AppendLine("#error " + error); + return builder.ToString(); + } + + private static string Literal(string value) + { + var builder = new StringBuilder(value.Length + 2); + builder.Append('"'); + foreach (char c in value) + { + switch (c) + { + case '\\': + builder.Append(@"\\"); + break; + case '"': + builder.Append("\\\""); + break; + case '\0': + builder.Append(@"\0"); + break; + case '\a': + builder.Append(@"\a"); + break; + case '\b': + builder.Append(@"\b"); + break; + case '\f': + builder.Append(@"\f"); + break; + case '\n': + builder.Append(@"\n"); + break; + case '\r': + builder.Append(@"\r"); + break; + case '\t': + builder.Append(@"\t"); + break; + case '\v': + builder.Append(@"\v"); + break; + default: + if (char.IsControl(c)) + { + builder.Append(@"\u"); + builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); + } + else + { + builder.Append(c); + } + break; + } + } + builder.Append('"'); + return builder.ToString(); + } + + private sealed record GpuShaderRegistration(string ApiName, string FileName, int Position); + + private sealed record GpuShaderFile(string Path, string Source); + + private sealed record GpuShaderSource(string ApiName, string Identifier, string Source); + + private sealed record GpuShaderResolution(ImmutableArray Sources, ImmutableArray Errors); + } +} diff --git a/LuaScript.Gpu/Buffer/GpuPixelBufferProcessor.cs b/LuaScript.Gpu/Buffer/GpuPixelBufferProcessor.cs new file mode 100644 index 0000000..ce1dbab --- /dev/null +++ b/LuaScript.Gpu/Buffer/GpuPixelBufferProcessor.cs @@ -0,0 +1,348 @@ +using System; +using System.Collections.Generic; +using LuaScript.Engine.Shader; + +namespace LuaScript.Engine.Processing +{ + internal sealed class GpuPixelBufferProcessor(PixelShaderRunner runner) : IPixelBufferProcessor + { + private const int MaxTextureSize = 16384; + private const int FillFullThreshold = 1048576; + private const int FillPartialThreshold = 1048576; + private const int ResizeThreshold = 262144; + private const int ConvolveWorkThreshold = 262144; + private const int MaxConvolveSize = 31; + private const int MaxConvolveValidationCount = 64; + + private readonly object _gate = new(); + private readonly PixelShaderInput[] _resources = new PixelShaderInput[1]; + private readonly float[] _constants = new float[1024]; + private readonly List _convolveValidations = []; + + private byte[] _resizeTarget = []; + private bool? _fillFullValidated; + private bool? _fillPartialValidated; + private bool? _resizeNearestValidated; + private bool? _resizeLinearValidated; + + public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight) + { + lock (_gate) + { + if (!IsTextureSupported(target, width, height) || !AreFinite(r, g, b, a)) + return false; + + long pixels = (long)width * height; + bool full = x == 0 && y == 0 && fillWidth == width && fillHeight == height; + if (full) + { + if (pixels < FillFullThreshold || !EnsureFillFullValidated()) + return false; + SetFillConstants(r, g, b, a); + return Run(GpuPixelOperationShaderRegistry.Fill, "fill_full", ReadOnlySpan.Empty, _constants.AsSpan(0, 4), target, width, height); + } + + long area = (long)fillWidth * fillHeight; + if (pixels < FillPartialThreshold || area * 4L < pixels * 3L || !EnsureFillPartialValidated()) + return false; + + SetFillConstants(r, g, b, a); + _constants[4] = x; + _constants[5] = y; + _constants[6] = x + fillWidth; + _constants[7] = y + fillHeight; + _resources[0] = new PixelShaderInput(target, width, height); + return Run(GpuPixelOperationShaderRegistry.Fill, "fill_partial", _resources.AsSpan(0, 1), _constants.AsSpan(0, 8), target, width, height); + } + } + + public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset) + { + lock (_gate) + { + if (!IsTextureSupported(target, width, height) || !IsConvolveSupported(kernel, size, divisor, offset)) + return false; + + long work = (long)width * height * size * size; + if (work < ConvolveWorkThreshold || !EnsureConvolveValidated(target, width, height, kernel, size, divisor, offset)) + return false; + + SetConvolveConstants(width, height, kernel, size, divisor, offset); + _resources[0] = new PixelShaderInput(target, width, height); + return Run(GpuPixelOperationShaderRegistry.Convolve, "convolve", _resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), target, width, height); + } + } + + public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target) + { + target = null; + lock (_gate) + { + if (!IsTextureSupported(source, sourceWidth, sourceHeight) || !IsTextureSizeSupported(targetWidth, targetHeight)) + return false; + + long pixels = (long)targetWidth * targetHeight; + if (pixels < ResizeThreshold || !(linear ? EnsureResizeLinearValidated(source, sourceWidth, sourceHeight) : EnsureResizeNearestValidated(source, sourceWidth, sourceHeight))) + return false; + + return RunResizeShader(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target); + } + } + + private bool EnsureFillFullValidated() + { + if (_fillFullValidated.HasValue) + return _fillFullValidated.Value; + + const int width = 7; + const int height = 5; + var source = CreateProbe(width, height); + var cpu = (byte[])source.Clone(); + var gpu = (byte[])source.Clone(); + PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 0, 0, width, height); + SetFillConstants(23d, 197d, 89d, 173d); + _fillFullValidated = Run(GpuPixelOperationShaderRegistry.Fill, "fill_full", ReadOnlySpan.Empty, _constants.AsSpan(0, 4), gpu, width, height) && Equal(cpu, gpu); + return _fillFullValidated.Value; + } + + private bool EnsureFillPartialValidated() + { + if (_fillPartialValidated.HasValue) + return _fillPartialValidated.Value; + + const int width = 7; + const int height = 5; + var source = CreateProbe(width, height); + var cpu = (byte[])source.Clone(); + var gpu = (byte[])source.Clone(); + PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 1, 2, 4, 2); + SetFillConstants(23d, 197d, 89d, 173d); + _constants[4] = 1f; + _constants[5] = 2f; + _constants[6] = 5f; + _constants[7] = 4f; + _resources[0] = new PixelShaderInput(gpu, width, height); + _fillPartialValidated = Run(GpuPixelOperationShaderRegistry.Fill, "fill_partial", _resources.AsSpan(0, 1), _constants.AsSpan(0, 8), gpu, width, height) && Equal(cpu, gpu); + return _fillPartialValidated.Value; + } + + private bool EnsureResizeNearestValidated(byte[] source, int sourceWidth, int sourceHeight) + { + if (_resizeNearestValidated.HasValue) + return _resizeNearestValidated.Value; + _resizeNearestValidated = ValidateResize(source, sourceWidth, sourceHeight, false); + return _resizeNearestValidated.Value; + } + + private bool EnsureResizeLinearValidated(byte[] source, int sourceWidth, int sourceHeight) + { + if (_resizeLinearValidated.HasValue) + return _resizeLinearValidated.Value; + _resizeLinearValidated = ValidateResize(source, sourceWidth, sourceHeight, true); + return _resizeLinearValidated.Value; + } + + private bool ValidateResize(byte[] source, int sourceWidth, int sourceHeight, bool linear) + { + int probeWidth = Math.Min(sourceWidth, 8); + int probeHeight = Math.Min(sourceHeight, 7); + int targetWidth = Math.Max(1, probeWidth * 2 - 3); + int targetHeight = Math.Max(1, probeHeight * 2 - 5); + var probe = CopyProbe(source, sourceWidth, sourceHeight, probeWidth, probeHeight); + byte[]? sourceScratch = null; + byte[]? targetScratch = null; + var cpu = PixelBufferSoftwareProcessor.Resize(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, ref sourceScratch, ref targetScratch); + return RunResizeShader(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, out var gpu) && gpu is not null && Equal(cpu, gpu); + } + + private bool EnsureConvolveValidated(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset) + { + for (int i = 0; i < _convolveValidations.Count; i++) + { + if (_convolveValidations[i].Matches(kernel, size, divisor, offset)) + return _convolveValidations[i].Valid; + } + + if (_convolveValidations.Count >= MaxConvolveValidationCount) + _convolveValidations.Clear(); + + bool valid = ValidateConvolve(target, width, height, kernel, size, divisor, offset); + _convolveValidations.Add(new ConvolveValidation(kernel, size, divisor, offset, valid)); + return valid; + } + + private bool ValidateConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset) + { + int probeWidth = Math.Min(width, 8); + int probeHeight = Math.Min(height, 7); + var probe = CopyProbe(target, width, height, probeWidth, probeHeight); + var cpu = (byte[])probe.Clone(); + var gpu = (byte[])probe.Clone(); + double[]? scratch = null; + PixelBufferSoftwareProcessor.Convolve(cpu, probeWidth, probeHeight, kernel, size, divisor, offset, ref scratch); + SetConvolveConstants(probeWidth, probeHeight, kernel, size, divisor, offset); + _resources[0] = new PixelShaderInput(gpu, probeWidth, probeHeight); + return Run(GpuPixelOperationShaderRegistry.Convolve, "convolve", _resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), gpu, probeWidth, probeHeight) && Equal(cpu, gpu); + } + + private bool RunResizeShader(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target) + { + int count = checked(targetWidth * targetHeight * 4); + if (_resizeTarget.Length != count) + _resizeTarget = new byte[count]; + + _constants[0] = sourceWidth; + _constants[1] = sourceHeight; + _constants[2] = targetWidth; + _constants[3] = targetHeight; + _resources[0] = new PixelShaderInput(source, sourceWidth, sourceHeight); + target = _resizeTarget; + string entry = linear ? "resize_linear" : "resize_nearest"; + return Run(GpuPixelOperationShaderRegistry.Resize, entry, _resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _resizeTarget, targetWidth, targetHeight); + } + + private bool Run(string hlsl, string entryPoint, ReadOnlySpan resources, ReadOnlySpan constants, byte[] target, int width, int height) + { + return runner.TryRunHardware( + hlsl, + entryPoint, + resources, + constants, + PixelShaderBlend.Copy, + PixelShaderSampler.None, + target, + width, + height, + out _) == PixelShaderRunStatus.Success; + } + + private void SetFillConstants(double r, double g, double b, double a) + { + double aK = Math.Clamp(a, 0d, 255d) / 255d; + byte pb = (byte)Math.Clamp(b * aK, 0d, 255d); + byte pg = (byte)Math.Clamp(g * aK, 0d, 255d); + byte pr = (byte)Math.Clamp(r * aK, 0d, 255d); + byte pa = (byte)Math.Clamp(a, 0d, 255d); + _constants[0] = pr / 255f; + _constants[1] = pg / 255f; + _constants[2] = pb / 255f; + _constants[3] = pa / 255f; + } + + private void SetConvolveConstants(int width, int height, double[] kernel, int size, double divisor, double offset) + { + _constants[0] = width; + _constants[1] = height; + _constants[2] = (float)divisor; + _constants[3] = (float)offset; + _constants[4] = size; + _constants[5] = size / 2; + _constants[6] = 0f; + _constants[7] = 0f; + int taps = size * size; + for (int i = 0; i < taps; i++) + _constants[i + 8] = (float)kernel[i]; + } + + private static bool IsTextureSupported(byte[] buffer, int width, int height) + { + return IsTextureSizeSupported(width, height) && (long)buffer.Length >= (long)width * height * 4; + } + + private static bool IsTextureSizeSupported(int width, int height) + { + return width > 0 && height > 0 && width <= MaxTextureSize && height <= MaxTextureSize; + } + + private static bool IsConvolveSupported(double[] kernel, int size, double divisor, double offset) + { + if (size < 1 || (size & 1) == 0 || size > MaxConvolveSize || divisor == 0d || !IsFloatCompatible(divisor) || !IsFloatCompatible(offset)) + return false; + int taps = size * size; + if (kernel.Length < taps || taps + 8 > 1024) + return false; + for (int i = 0; i < taps; i++) + { + if (!IsFloatCompatible(kernel[i])) + return false; + } + return true; + } + + private static bool AreFinite(double r, double g, double b, double a) + { + return double.IsFinite(r) && double.IsFinite(g) && double.IsFinite(b) && double.IsFinite(a); + } + + private static bool IsFloatCompatible(double value) + { + return double.IsFinite(value) && float.IsFinite((float)value); + } + + private static bool Equal(byte[] expected, byte[] actual) + { + return expected.AsSpan().SequenceEqual(actual); + } + + private static byte[] CopyProbe(byte[] source, int width, int height, int probeWidth, int probeHeight) + { + var data = new byte[probeWidth * probeHeight * 4]; + for (int y = 0; y < probeHeight; y++) + Buffer.BlockCopy(source, y * width * 4, data, y * probeWidth * 4, probeWidth * 4); + return data; + } + + private static byte[] CreateProbe(int width, int height) + { + var data = new byte[width * height * 4]; + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + int index = (y * width + x) * 4; + byte a = (byte)((x * 31 + y * 47) & 255); + data[index] = a == 0 ? (byte)0 : (byte)((x * 17 + y * 29) % (a + 1)); + data[index + 1] = a == 0 ? (byte)0 : (byte)((x * 43 + y * 11) % (a + 1)); + data[index + 2] = a == 0 ? (byte)0 : (byte)((x * 7 + y * 53) % (a + 1)); + data[index + 3] = a; + } + } + return data; + } + + private sealed class ConvolveValidation + { + private readonly double[] _kernel; + private readonly int _size; + private readonly double _divisor; + private readonly double _offset; + + public ConvolveValidation(double[] kernel, int size, double divisor, double offset, bool valid) + { + int taps = size * size; + _kernel = new double[taps]; + Array.Copy(kernel, _kernel, taps); + _size = size; + _divisor = divisor; + _offset = offset; + Valid = valid; + } + + public bool Valid { get; } + + public bool Matches(double[] kernel, int size, double divisor, double offset) + { + if (_size != size || BitConverter.DoubleToInt64Bits(_divisor) != BitConverter.DoubleToInt64Bits(divisor) || + BitConverter.DoubleToInt64Bits(_offset) != BitConverter.DoubleToInt64Bits(offset)) + return false; + int taps = size * size; + for (int i = 0; i < taps; i++) + { + if (BitConverter.DoubleToInt64Bits(_kernel[i]) != BitConverter.DoubleToInt64Bits(kernel[i])) + return false; + } + return true; + } + } + } +} diff --git a/LuaScript.Gpu/Buffer/GpuPixelOperationShaderAttribute.cs b/LuaScript.Gpu/Buffer/GpuPixelOperationShaderAttribute.cs new file mode 100644 index 0000000..ad3e1e5 --- /dev/null +++ b/LuaScript.Gpu/Buffer/GpuPixelOperationShaderAttribute.cs @@ -0,0 +1,12 @@ +using System; + +namespace LuaScript.Engine.Processing +{ + [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] + internal sealed class GpuPixelOperationShaderAttribute(string apiName, string fileName) : Attribute + { + public string ApiName { get; } = apiName; + + public string FileName { get; } = fileName; + } +} diff --git a/LuaScript.Gpu/GpuPixelOperationShaders.cs b/LuaScript.Gpu/GpuPixelOperationShaders.cs new file mode 100644 index 0000000..127c259 --- /dev/null +++ b/LuaScript.Gpu/GpuPixelOperationShaders.cs @@ -0,0 +1,5 @@ +using LuaScript.Engine.Processing; + +[assembly: GpuPixelOperationShader("fill", "Shaders/fill.hlsl")] +[assembly: GpuPixelOperationShader("convolve", "Shaders/convolve.hlsl")] +[assembly: GpuPixelOperationShader("resize", "Shaders/resize.hlsl")] diff --git a/LuaScript.Gpu/LuaScript.Gpu.csproj b/LuaScript.Gpu/LuaScript.Gpu.csproj index 01d194b..27812a2 100644 --- a/LuaScript.Gpu/LuaScript.Gpu.csproj +++ b/LuaScript.Gpu/LuaScript.Gpu.csproj @@ -16,6 +16,8 @@ + + diff --git a/LuaScript.Gpu/Shaders/convolve.hlsl b/LuaScript.Gpu/Shaders/convolve.hlsl new file mode 100644 index 0000000..62360ce --- /dev/null +++ b/LuaScript.Gpu/Shaders/convolve.hlsl @@ -0,0 +1,57 @@ +Texture2D source : register(t0); + +cbuffer Parameters : register(b0) +{ + float4 values[256]; +}; + +float get_value(uint index) +{ + uint row = index >> 2; + uint column = index & 3u; + if (column == 0u) + return values[row].x; + if (column == 1u) + return values[row].y; + if (column == 2u) + return values[row].z; + return values[row].w; +} + +float convolve_channel(float value) +{ + return floor(saturate(value) * 255.0) / 255.0; +} + +float4 convolve(float4 pos : SV_Position) : SV_Target +{ + uint2 p = (uint2)floor(pos.xy); + int width = (int)get_value(0u); + int height = (int)get_value(1u); + float divisor = get_value(2u); + float offset = get_value(3u) / 255.0; + int kernelSize = (int)get_value(4u); + int half = (int)get_value(5u); + float4 sum = 0.0; + + for (int ky = 0; ky < kernelSize; ky++) + { + int sy = clamp((int)p.y + ky - half, 0, height - 1); + for (int kx = 0; kx < kernelSize; kx++) + { + int sx = clamp((int)p.x + kx - half, 0, width - 1); + float kv = get_value((uint)(8 + ky * kernelSize + kx)); + float4 sourceValue = source[uint2((uint)sx, (uint)sy)]; + float3 rgb = sourceValue.a <= 0.0 ? 0.0 : saturate(sourceValue.rgb / sourceValue.a); + sum += float4(rgb, sourceValue.a) * kv; + } + } + + float3 rgbOut = saturate(sum.rgb / divisor + offset); + float alpha = saturate(sum.a / divisor + offset); + return float4( + convolve_channel(rgbOut.r * alpha), + convolve_channel(rgbOut.g * alpha), + convolve_channel(rgbOut.b * alpha), + convolve_channel(alpha)); +} diff --git a/LuaScript.Gpu/Shaders/fill.hlsl b/LuaScript.Gpu/Shaders/fill.hlsl new file mode 100644 index 0000000..f8bd499 --- /dev/null +++ b/LuaScript.Gpu/Shaders/fill.hlsl @@ -0,0 +1,21 @@ +Texture2D source : register(t0); + +cbuffer Parameters : register(b0) +{ + float4 color; + float4 rect; +}; + +float4 fill_full(float4 pos : SV_Position) : SV_Target +{ + return color; +} + +float4 fill_partial(float4 pos : SV_Position) : SV_Target +{ + uint2 p = (uint2)floor(pos.xy); + uint4 r = (uint4)rect; + if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w) + return color; + return source[p]; +} diff --git a/LuaScript.Gpu/Shaders/resize.hlsl b/LuaScript.Gpu/Shaders/resize.hlsl new file mode 100644 index 0000000..82cde8c --- /dev/null +++ b/LuaScript.Gpu/Shaders/resize.hlsl @@ -0,0 +1,56 @@ +Texture2D source : register(t0); + +cbuffer Parameters : register(b0) +{ + float4 size; +}; + +float channel(float value) +{ + return floor(saturate(value) * 255.0) / 255.0; +} + +float4 resize_pack(float4 value) +{ + return float4(channel(value.r), channel(value.g), channel(value.b), channel(value.a)); +} + +float4 resize_nearest(float4 pos : SV_Position) : SV_Target +{ + uint2 p = (uint2)floor(pos.xy); + uint sourceWidth = (uint)size.x; + uint sourceHeight = (uint)size.y; + uint targetWidth = (uint)size.z; + uint targetHeight = (uint)size.w; + uint sx = min(((p.x * 2u + 1u) * sourceWidth) / (targetWidth * 2u), sourceWidth - 1u); + uint sy = min(((p.y * 2u + 1u) * sourceHeight) / (targetHeight * 2u), sourceHeight - 1u); + return source[uint2(sx, sy)]; +} + +float4 resize_linear(float4 pos : SV_Position) : SV_Target +{ + uint2 p = (uint2)floor(pos.xy); + float sourceWidth = size.x; + float sourceHeight = size.y; + float targetWidth = size.z; + float targetHeight = size.w; + float u = (p.x + 0.5) * sourceWidth / targetWidth - 0.5; + float v = (p.y + 0.5) * sourceHeight / targetHeight - 0.5; + int x0 = (int)floor(u); + int y0 = (int)floor(v); + float tx = u - x0; + float ty = v - y0; + int maxX = (int)sourceWidth - 1; + int maxY = (int)sourceHeight - 1; + uint xA = (uint)clamp(x0, 0, maxX); + uint yA = (uint)clamp(y0, 0, maxY); + uint xB = (uint)clamp(x0 + 1, 0, maxX); + uint yB = (uint)clamp(y0 + 1, 0, maxY); + float4 c00 = source[uint2(xA, yA)]; + float4 c10 = source[uint2(xB, yA)]; + float4 c01 = source[uint2(xA, yB)]; + float4 c11 = source[uint2(xB, yB)]; + float4 top = c00 * (1.0 - tx) + c10 * tx; + float4 bottom = c01 * (1.0 - tx) + c11 * tx; + return resize_pack(top * (1.0 - ty) + bottom * ty); +}