From af9c5af173d344e991e9ad880f9ff9f1cd14f6a6 Mon Sep 17 00:00:00 2001 From: routersys Date: Sun, 5 Jul 2026 13:22:06 +0900 Subject: [PATCH] =?UTF-8?q?GPU=E5=86=85=E9=83=A8=E3=82=B7=E3=82=A7?= =?UTF-8?q?=E3=83=BC=E3=83=80=E3=83=BC=E3=82=92=E3=83=93=E3=83=AB=E3=83=89?= =?UTF-8?q?=E6=99=82DXBC=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../GpuShaderSourceGenerator.cs | 494 +++++++++++++++--- LuaScript.Gpu/Buffer/GpuConvolveOperation.cs | 134 +++++ LuaScript.Gpu/Buffer/GpuFillOperation.cs | 124 +++++ .../Buffer/GpuPixelBufferProcessor.cs | 330 +----------- LuaScript.Gpu/Buffer/GpuPixelOperation.cs | 47 ++ .../GpuPixelOperationShaderAttribute.cs | 8 +- LuaScript.Gpu/Buffer/GpuResizeOperation.cs | 82 +++ LuaScript.Gpu/GpuPixelOperationShaders.cs | 5 - LuaScript.Gpu/Shader/PixelShaderRunner.cs | 91 ++-- 9 files changed, 868 insertions(+), 447 deletions(-) create mode 100644 LuaScript.Gpu/Buffer/GpuConvolveOperation.cs create mode 100644 LuaScript.Gpu/Buffer/GpuFillOperation.cs create mode 100644 LuaScript.Gpu/Buffer/GpuPixelOperation.cs create mode 100644 LuaScript.Gpu/Buffer/GpuResizeOperation.cs delete mode 100644 LuaScript.Gpu/GpuPixelOperationShaders.cs diff --git a/LuaScript.Generator/GpuShaderSourceGenerator.cs b/LuaScript.Generator/GpuShaderSourceGenerator.cs index aff3174..9d1b887 100644 --- a/LuaScript.Generator/GpuShaderSourceGenerator.cs +++ b/LuaScript.Generator/GpuShaderSourceGenerator.cs @@ -1,8 +1,10 @@ using System.Collections.Immutable; using System.Globalization; using System.IO; +using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace LuaScript.Generator @@ -14,83 +16,171 @@ namespace LuaScript.Generator public void Initialize(IncrementalGeneratorInitializationContext context) { - var registrations = context.CompilationProvider.Select(static (compilation, _) => CollectRegistrations(compilation)); + var classes = context.SyntaxProvider + .CreateSyntaxProvider( + static (node, _) => node is ClassDeclarationSyntax { AttributeLists.Count: > 0 }, + static (ctx, _) => CreateClass(ctx)) + .Where(static model => model is not null) + .Select(static (model, _) => model!); + 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) => + context.RegisterSourceOutput(classes.Combine(files), static (context, source) => { - var (registrations, files) = source; - if (registrations.Length == 0) - return; - - var result = Resolve(registrations, files); - if (result.Errors.Length > 0) + var (model, files) = source; + var resolved = Resolve(model, files); + if (resolved.Errors.Length > 0) { - context.AddSource("GpuPixelOperationShaderRegistry.Errors.g.cs", SourceText.From(EmitErrors(result.Errors), Encoding.UTF8)); + context.AddSource(ErrorHintName(model), SourceText.From(EmitErrors(resolved.Errors), Encoding.UTF8)); return; } - if (result.Sources.IsDefaultOrEmpty) - return; - context.AddSource("GpuPixelOperationShaderRegistry.g.cs", SourceText.From(Emit(result.Sources), Encoding.UTF8)); + context.AddSource(HintName(model), SourceText.From(Emit(model, resolved.Methods), Encoding.UTF8)); }); } - private static ImmutableArray CollectRegistrations(Compilation compilation) + private static GpuShaderClass? CreateClass(GeneratorSyntaxContext context) { - 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(); - } + if (context.Node is not ClassDeclarationSyntax declaration) + return null; + if (context.SemanticModel.GetDeclaredSymbol(declaration) is not INamedTypeSymbol type) + return null; - 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 attributes = type.GetAttributes() + .Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AttributeName) + .ToArray(); + if (attributes.Length == 0) + return null; + + var chain = new List(); + for (var current = type; current is not null; current = current.ContainingType) + chain.Insert(0, new GpuShaderTypePart(current.Name, current.IsStatic)); + + var methods = ImmutableArray.CreateBuilder(); var errors = ImmutableArray.CreateBuilder(); - foreach (var registration in registrations.OrderBy(static r => r.Position).ThenBy(static r => r.ApiName, StringComparer.Ordinal)) + foreach (var attribute in attributes) { - if (!apiNames.Add(registration.ApiName)) + if (attribute.ConstructorArguments.Length < 3 || + attribute.ConstructorArguments[0].Value is not string methodName || + attribute.ConstructorArguments[1].Value is not string fileName || + attribute.ConstructorArguments[2].Value is not string entryPoint) { - errors.Add($"GPU shader API '{registration.ApiName}' is registered multiple times"); + errors.Add("GPU shader attribute arguments are invalid"); continue; } - var matched = files.Where(file => Matches(file.Path, registration.FileName)).ToArray(); + var candidates = type.GetMembers(methodName).OfType().ToArray(); + if (candidates.Length == 0) + { + errors.Add($"GPU shader method '{methodName}' was not found"); + continue; + } + if (candidates.Length > 1) + { + errors.Add($"GPU shader method '{methodName}' is ambiguous"); + continue; + } + + var method = candidates[0]; + string? error = Validate(method, fileName, entryPoint, out var invocation); + if (error is not null) + { + errors.Add($"GPU shader method '{methodName}': {error}"); + continue; + } + + var parameters = ImmutableArray.CreateBuilder(); + foreach (var parameter in method.Parameters) + parameters.Add(new GpuShaderParameter(ParameterPrefix(parameter), parameter.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), parameter.Name)); + + methods.Add(new GpuShaderMethod( + AccessibilityName(method.DeclaredAccessibility), + method.IsStatic, + method.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), + method.Name, + [.. parameters], + Normalize(fileName), + entryPoint, + invocation)); + } + + return new GpuShaderClass( + type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(), + [.. chain], + [.. methods], + [.. errors]); + } + + private static string? Validate(IMethodSymbol method, string fileName, string entryPoint, out GpuShaderInvocation invocation) + { + invocation = new GpuShaderInvocation(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty); + if (string.IsNullOrWhiteSpace(fileName)) + return "file name is empty"; + if (string.IsNullOrWhiteSpace(entryPoint)) + return "entry point is empty"; + if (method.ReturnType.SpecialType != SpecialType.System_Boolean) + return "return type must be bool"; + + var parameters = method.Parameters; + if (parameters.Length == 4 && + IsReadOnlySpanSingle(parameters[0].Type) && + IsByteArray(parameters[1].Type) && + IsInt32(parameters[2].Type) && + IsInt32(parameters[3].Type)) + { + invocation = new GpuShaderInvocation("[]", parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name); + return null; + } + + if (parameters.Length == 5 && + IsReadOnlySpanPixelShaderInput(parameters[0].Type) && + IsReadOnlySpanSingle(parameters[1].Type) && + IsByteArray(parameters[2].Type) && + IsInt32(parameters[3].Type) && + IsInt32(parameters[4].Type)) + { + invocation = new GpuShaderInvocation(parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name, parameters[4].Name); + return null; + } + + return "signature is invalid"; + } + + private static GpuShaderResolution Resolve(GpuShaderClass model, ImmutableArray files) + { + var methods = ImmutableArray.CreateBuilder(); + var errors = ImmutableArray.CreateBuilder(); + errors.AddRange(model.Errors); + + foreach (var method in model.Methods) + { + var matched = files.Where(file => Matches(file.Path, method.FileName)).ToArray(); if (matched.Length == 0) { - errors.Add($"GPU shader file '{registration.FileName}' for API '{registration.ApiName}' was not found"); + errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' was not found"); continue; } if (matched.Length > 1) { - errors.Add($"GPU shader file '{registration.FileName}' for API '{registration.ApiName}' matched multiple additional files"); + errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' matched multiple additional files"); continue; } - string identifier = ToIdentifier(registration.ApiName); - if (!identifiers.Add(identifier)) + string? failure = ShaderCompiler.Compile(matched[0].Source, method.EntryPoint, out string bytecode); + if (failure is not null) { - errors.Add($"GPU shader API '{registration.ApiName}' resolves to a duplicate identifier"); + errors.Add($"GPU shader method '{method.MethodName}' failed to compile: {failure}"); continue; } - sources.Add(new GpuShaderSource(registration.ApiName, identifier, matched[0].Source)); + methods.Add(new GpuShaderMethodSource(method, bytecode)); } - return new GpuShaderResolution(sources.ToImmutable(), errors.ToImmutable()); + return new GpuShaderResolution([.. methods], [.. errors]); } private static bool Matches(string filePath, string registrationPath) @@ -100,52 +190,156 @@ namespace LuaScript.Generator 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) + private static bool IsReadOnlySpanSingle(ITypeSymbol type) { - 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(); + return type is INamedTypeSymbol named && + named.OriginalDefinition.ToDisplayString() == "System.ReadOnlySpan" && + named.TypeArguments.Length == 1 && + named.TypeArguments[0].SpecialType == SpecialType.System_Single; } - private static string Emit(ImmutableArray sources) + private static bool IsReadOnlySpanPixelShaderInput(ITypeSymbol type) + { + string display = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); + return display.Contains("ReadOnlySpan", StringComparison.Ordinal) && + display.Contains("PixelShaderInput", StringComparison.Ordinal); + } + + private static bool IsByteArray(ITypeSymbol type) + { + return type is IArrayTypeSymbol array && + array.Rank == 1 && + array.ElementType.SpecialType == SpecialType.System_Byte; + } + + private static bool IsInt32(ITypeSymbol type) => type.SpecialType == SpecialType.System_Int32; + + private static string Normalize(string path) => path.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/'); + + private static string AccessibilityName(Accessibility accessibility) + { + return accessibility switch + { + Accessibility.Public => "public", + Accessibility.Internal => "internal", + Accessibility.Protected => "protected", + Accessibility.ProtectedAndInternal => "private protected", + Accessibility.ProtectedOrInternal => "protected internal", + _ => "private", + }; + } + + private static string ParameterPrefix(IParameterSymbol parameter) + { + return parameter.RefKind switch + { + RefKind.In => "in ", + RefKind.Ref => "ref ", + RefKind.Out => "out ", + _ => string.Empty, + }; + } + + private static string Emit(GpuShaderClass model, 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("}"); + if (model.Namespace.Length > 0) + { + builder.AppendLine("namespace " + model.Namespace); + builder.AppendLine("{"); + } + + int indent = model.Namespace.Length > 0 ? 1 : 0; + foreach (var type in model.TypeChain) + { + AppendIndent(builder, indent); + builder.Append(type.IsStatic ? "static partial class " : "partial class "); + builder.AppendLine(type.Name); + AppendIndent(builder, indent); + builder.AppendLine("{"); + indent++; + } + + for (int i = 0; i < sources.Length; i++) + { + if (i > 0) + builder.AppendLine(); + EmitMethod(builder, indent, sources[i]); + } + + for (int i = model.TypeChain.Length - 1; i >= 0; i--) + { + indent--; + AppendIndent(builder, indent); + builder.AppendLine("}"); + } + + if (model.Namespace.Length > 0) + builder.AppendLine("}"); return builder.ToString(); } + private static void EmitMethod(StringBuilder builder, int indent, GpuShaderMethodSource source) + { + var method = source.Method; + string field = "s_shader_" + method.MethodName; + + AppendIndent(builder, indent); + builder.Append("private static readonly byte[] "); + builder.Append(field); + builder.Append(" = global::System.Convert.FromBase64String("); + builder.Append(Literal(source.Bytecode)); + builder.AppendLine(");"); + builder.AppendLine(); + + AppendIndent(builder, indent); + builder.Append(method.Accessibility); + builder.Append(' '); + if (method.IsStatic) + builder.Append("static "); + builder.Append("partial "); + builder.Append(method.ReturnType); + builder.Append(' '); + builder.Append(method.MethodName); + builder.Append('('); + for (int i = 0; i < method.Parameters.Length; i++) + { + if (i > 0) + builder.Append(", "); + var parameter = method.Parameters[i]; + builder.Append(parameter.Prefix); + builder.Append(parameter.Type); + builder.Append(' '); + builder.Append(parameter.Name); + } + builder.AppendLine(")"); + AppendIndent(builder, indent); + builder.AppendLine("{"); + AppendIndent(builder, indent + 1); + builder.Append("return Run("); + builder.Append(field); + builder.Append(", "); + builder.Append(method.Invocation.Resources); + builder.Append(", "); + builder.Append(method.Invocation.Constants); + builder.Append(", "); + builder.Append(method.Invocation.Target); + builder.Append(", "); + builder.Append(method.Invocation.Width); + builder.Append(", "); + builder.Append(method.Invocation.Height); + builder.AppendLine(");"); + AppendIndent(builder, indent); + builder.AppendLine("}"); + } + + private static void AppendIndent(StringBuilder builder, int indent) + { + for (int i = 0; i < indent; i++) + builder.Append(" "); + } + private static string EmitErrors(ImmutableArray errors) { var builder = new StringBuilder(); @@ -154,6 +348,36 @@ namespace LuaScript.Generator return builder.ToString(); } + private static string HintName(GpuShaderClass model) + { + var builder = new StringBuilder("GpuPixelOperationShader"); + if (model.Namespace.Length > 0) + { + builder.Append('.'); + builder.Append(HintPart(model.Namespace)); + } + foreach (var type in model.TypeChain) + { + builder.Append('.'); + builder.Append(HintPart(type.Name)); + } + builder.Append(".g.cs"); + return builder.ToString(); + } + + private static string ErrorHintName(GpuShaderClass model) + { + return Path.ChangeExtension(HintName(model), ".Errors.g.cs"); + } + + private static string HintPart(string value) + { + var builder = new StringBuilder(value.Length); + foreach (char c in value) + builder.Append(char.IsLetterOrDigit(c) ? c : '_'); + return builder.ToString(); + } + private static string Literal(string value) { var builder = new StringBuilder(value.Length + 2); @@ -209,12 +433,122 @@ namespace LuaScript.Generator return builder.ToString(); } - private sealed record GpuShaderRegistration(string ApiName, string FileName, int Position); + private sealed record GpuShaderClass( + string Namespace, + ImmutableArray TypeChain, + ImmutableArray Methods, + ImmutableArray Errors); + + private sealed record GpuShaderTypePart(string Name, bool IsStatic); + + private sealed record GpuShaderMethod( + string Accessibility, + bool IsStatic, + string ReturnType, + string MethodName, + ImmutableArray Parameters, + string FileName, + string EntryPoint, + GpuShaderInvocation Invocation); + + private sealed record GpuShaderParameter(string Prefix, string Type, string Name); + + private sealed record GpuShaderInvocation(string Resources, string Constants, string Target, string Width, string Height); + + private sealed record GpuShaderMethodSource(GpuShaderMethod Method, string Bytecode); private sealed record GpuShaderFile(string Path, string Source); - private sealed record GpuShaderSource(string ApiName, string Identifier, string Source); + private sealed record GpuShaderResolution(ImmutableArray Methods, ImmutableArray Errors); - private sealed record GpuShaderResolution(ImmutableArray Sources, ImmutableArray Errors); + private static class ShaderCompiler + { + private const string Profile = "ps_5_0"; + + public static string? Compile(string source, string entryPoint, out string bytecode) + { + bytecode = string.Empty; + byte[] data = Encoding.UTF8.GetBytes(source); + IntPtr code = IntPtr.Zero; + IntPtr errors = IntPtr.Zero; + try + { + int hr = D3DCompile(data, (IntPtr)data.Length, null, IntPtr.Zero, IntPtr.Zero, entryPoint, Profile, 0u, 0u, out code, out errors); + if (hr < 0 || code == IntPtr.Zero) + return ReadError(errors, hr); + bytecode = Convert.ToBase64String(ReadBlob(code)); + return null; + } + catch (DllNotFoundException) + { + return "the Direct3D shader compiler is unavailable on this build host"; + } + catch (EntryPointNotFoundException) + { + return "the Direct3D shader compiler is unavailable on this build host"; + } + finally + { + Release(errors); + Release(code); + } + } + + private static byte[] ReadBlob(IntPtr blob) + { + IntPtr pointer = Invoke(blob, 3)(blob); + int size = checked((int)(long)Invoke(blob, 4)(blob)); + var buffer = new byte[size]; + Marshal.Copy(pointer, buffer, 0, size); + return buffer; + } + + private static string ReadError(IntPtr blob, int hr) + { + string fallback = "HRESULT 0x" + hr.ToString("X8", CultureInfo.InvariantCulture); + if (blob == IntPtr.Zero) + return fallback; + IntPtr pointer = Invoke(blob, 3)(blob); + int size = checked((int)(long)Invoke(blob, 4)(blob)); + string message = (Marshal.PtrToStringAnsi(pointer, size) ?? string.Empty).Trim(); + return message.Length > 0 ? message : fallback; + } + + private static void Release(IntPtr unknown) + { + if (unknown != IntPtr.Zero) + Invoke(unknown, 2)(unknown); + } + + private static T Invoke(IntPtr instance, int slot) where T : Delegate + { + IntPtr table = Marshal.ReadIntPtr(instance); + IntPtr function = Marshal.ReadIntPtr(table, slot * IntPtr.Size); + return (T)Marshal.GetDelegateForFunctionPointer(function, typeof(T)); + } + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr GetBufferPointerDelegate(IntPtr self); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate IntPtr GetBufferSizeDelegate(IntPtr self); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate uint ReleaseDelegate(IntPtr self); + + [DllImport("d3dcompiler_47.dll", CallingConvention = CallingConvention.StdCall)] + private static extern int D3DCompile( + byte[] srcData, + IntPtr srcDataSize, + [MarshalAs(UnmanagedType.LPStr)] string? sourceName, + IntPtr defines, + IntPtr include, + [MarshalAs(UnmanagedType.LPStr)] string entryPoint, + [MarshalAs(UnmanagedType.LPStr)] string target, + uint flags1, + uint flags2, + out IntPtr code, + out IntPtr errorMsgs); + } } } diff --git a/LuaScript.Gpu/Buffer/GpuConvolveOperation.cs b/LuaScript.Gpu/Buffer/GpuConvolveOperation.cs new file mode 100644 index 0000000..fe6d937 --- /dev/null +++ b/LuaScript.Gpu/Buffer/GpuConvolveOperation.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using LuaScript.Engine.Shader; + +namespace LuaScript.Engine.Processing +{ + [GpuPixelOperationShader(nameof(RunConvolve), "Shaders/convolve.hlsl", "convolve")] + internal sealed partial class GpuConvolveOperation(PixelShaderRunner runner) : GpuPixelOperation(runner) + { + private const int ConvolveWorkThreshold = 262144; + private const int MaxConvolveSize = 31; + private const int MaxConvolveValidationCount = 64; + + private readonly PixelShaderInput[] _resources = new PixelShaderInput[1]; + private readonly float[] _constants = new float[1024]; + private readonly List _validations = []; + + public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset) + { + if (!IsTextureSupported(target, width, height) || !IsSupported(kernel, size, divisor, offset)) + return false; + + long work = (long)width * height * size * size; + if (work < ConvolveWorkThreshold || !EnsureValidated(target, width, height, kernel, size, divisor, offset)) + return false; + + SetConstants(width, height, kernel, size, divisor, offset); + _resources[0] = new PixelShaderInput(target, width, height); + return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), target, width, height); + } + + private bool EnsureValidated(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset) + { + for (int i = 0; i < _validations.Count; i++) + { + if (_validations[i].Matches(kernel, size, divisor, offset)) + return _validations[i].Valid; + } + + if (_validations.Count >= MaxConvolveValidationCount) + _validations.Clear(); + + bool valid = Validate(target, width, height, kernel, size, divisor, offset); + _validations.Add(new ConvolveValidation(kernel, size, divisor, offset, valid)); + return valid; + } + + private bool Validate(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); + SetConstants(probeWidth, probeHeight, kernel, size, divisor, offset); + _resources[0] = new PixelShaderInput(gpu, probeWidth, probeHeight); + return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), gpu, probeWidth, probeHeight) && Equal(cpu, gpu); + } + + private void SetConstants(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 IsSupported(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 IsFloatCompatible(double value) + { + return double.IsFinite(value) && float.IsFinite((float)value); + } + + private partial bool RunConvolve(ReadOnlySpan resources, ReadOnlySpan constants, byte[] target, int width, int height); + + 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/GpuFillOperation.cs b/LuaScript.Gpu/Buffer/GpuFillOperation.cs new file mode 100644 index 0000000..36476d3 --- /dev/null +++ b/LuaScript.Gpu/Buffer/GpuFillOperation.cs @@ -0,0 +1,124 @@ +using System; +using LuaScript.Engine.Shader; + +namespace LuaScript.Engine.Processing +{ + [GpuPixelOperationShader(nameof(RunFillFull), "Shaders/fill.hlsl", "fill_full")] + [GpuPixelOperationShader(nameof(RunFillPartial), "Shaders/fill.hlsl", "fill_partial")] + internal sealed partial class GpuFillOperation(PixelShaderRunner runner) : GpuPixelOperation(runner) + { + private const int FillFullThreshold = 1048576; + private const int FillPartialThreshold = 1048576; + + private readonly PixelShaderInput[] _resources = new PixelShaderInput[1]; + private readonly float[] _constants = new float[8]; + + private bool? _fullValidated; + private bool? _partialValidated; + + 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) + { + 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 || !EnsureFullValidated()) + return false; + SetConstants(r, g, b, a); + return RunFillFull(_constants.AsSpan(0, 4), target, width, height); + } + + long area = (long)fillWidth * fillHeight; + if (pixels < FillPartialThreshold || area * 4L < pixels * 3L || !EnsurePartialValidated()) + return false; + + SetConstants(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 RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), target, width, height); + } + + private bool EnsureFullValidated() + { + if (_fullValidated.HasValue) + return _fullValidated.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); + SetConstants(23d, 197d, 89d, 173d); + _fullValidated = RunFillFull(_constants.AsSpan(0, 4), gpu, width, height) && Equal(cpu, gpu); + return _fullValidated.Value; + } + + private bool EnsurePartialValidated() + { + if (_partialValidated.HasValue) + return _partialValidated.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); + SetConstants(23d, 197d, 89d, 173d); + _constants[4] = 1f; + _constants[5] = 2f; + _constants[6] = 5f; + _constants[7] = 4f; + _resources[0] = new PixelShaderInput(gpu, width, height); + _partialValidated = RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), gpu, width, height) && Equal(cpu, gpu); + return _partialValidated.Value; + } + + private void SetConstants(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 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 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 partial bool RunFillFull(ReadOnlySpan constants, byte[] target, int width, int height); + + private partial bool RunFillPartial(ReadOnlySpan resources, ReadOnlySpan constants, byte[] target, int width, int height); + } +} diff --git a/LuaScript.Gpu/Buffer/GpuPixelBufferProcessor.cs b/LuaScript.Gpu/Buffer/GpuPixelBufferProcessor.cs index ce1dbab..1fe0c7d 100644 --- a/LuaScript.Gpu/Buffer/GpuPixelBufferProcessor.cs +++ b/LuaScript.Gpu/Buffer/GpuPixelBufferProcessor.cs @@ -1,348 +1,30 @@ -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; + private readonly GpuFillOperation _fill = new(runner); + private readonly GpuConvolveOperation _convolve = new(runner); + private readonly GpuResizeOperation _resize = new(runner); 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); - } + return _fill.TryFill(target, width, height, r, g, b, a, x, y, fillWidth, fillHeight); } 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); - } + return _convolve.TryConvolve(target, width, height, kernel, size, divisor, offset); } 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; - } + return _resize.TryResize(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target); } } } diff --git a/LuaScript.Gpu/Buffer/GpuPixelOperation.cs b/LuaScript.Gpu/Buffer/GpuPixelOperation.cs new file mode 100644 index 0000000..e100dcf --- /dev/null +++ b/LuaScript.Gpu/Buffer/GpuPixelOperation.cs @@ -0,0 +1,47 @@ +using System; +using LuaScript.Engine.Shader; + +namespace LuaScript.Engine.Processing +{ + internal abstract class GpuPixelOperation(PixelShaderRunner runner) + { + protected const int MaxTextureSize = 16384; + + protected bool Run(byte[] bytecode, ReadOnlySpan resources, ReadOnlySpan constants, byte[] target, int width, int height) + { + return runner.TryRunHardware( + bytecode, + resources, + constants, + PixelShaderBlend.Copy, + PixelShaderSampler.None, + target, + width, + height, + out _) == PixelShaderRunStatus.Success; + } + + protected static bool IsTextureSupported(byte[] buffer, int width, int height) + { + return IsTextureSizeSupported(width, height) && (long)buffer.Length >= (long)width * height * 4; + } + + protected static bool IsTextureSizeSupported(int width, int height) + { + return width > 0 && height > 0 && width <= MaxTextureSize && height <= MaxTextureSize; + } + + protected static bool Equal(byte[] expected, byte[] actual) + { + return expected.AsSpan().SequenceEqual(actual); + } + + protected 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; + } + } +} diff --git a/LuaScript.Gpu/Buffer/GpuPixelOperationShaderAttribute.cs b/LuaScript.Gpu/Buffer/GpuPixelOperationShaderAttribute.cs index ad3e1e5..78bf4d9 100644 --- a/LuaScript.Gpu/Buffer/GpuPixelOperationShaderAttribute.cs +++ b/LuaScript.Gpu/Buffer/GpuPixelOperationShaderAttribute.cs @@ -2,11 +2,13 @@ using System; namespace LuaScript.Engine.Processing { - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - internal sealed class GpuPixelOperationShaderAttribute(string apiName, string fileName) : Attribute + [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] + internal sealed class GpuPixelOperationShaderAttribute(string methodName, string fileName, string entryPoint) : Attribute { - public string ApiName { get; } = apiName; + public string MethodName { get; } = methodName; public string FileName { get; } = fileName; + + public string EntryPoint { get; } = entryPoint; } } diff --git a/LuaScript.Gpu/Buffer/GpuResizeOperation.cs b/LuaScript.Gpu/Buffer/GpuResizeOperation.cs new file mode 100644 index 0000000..683595d --- /dev/null +++ b/LuaScript.Gpu/Buffer/GpuResizeOperation.cs @@ -0,0 +1,82 @@ +using System; +using LuaScript.Engine.Shader; + +namespace LuaScript.Engine.Processing +{ + [GpuPixelOperationShader(nameof(RunResizeNearest), "Shaders/resize.hlsl", "resize_nearest")] + [GpuPixelOperationShader(nameof(RunResizeLinear), "Shaders/resize.hlsl", "resize_linear")] + internal sealed partial class GpuResizeOperation(PixelShaderRunner runner) : GpuPixelOperation(runner) + { + private const int ResizeThreshold = 262144; + + private readonly PixelShaderInput[] _resources = new PixelShaderInput[1]; + private readonly float[] _constants = new float[4]; + + private byte[] _target = []; + private bool? _nearestValidated; + private bool? _linearValidated; + + public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target) + { + target = null; + if (!IsTextureSupported(source, sourceWidth, sourceHeight) || !IsTextureSizeSupported(targetWidth, targetHeight)) + return false; + + long pixels = (long)targetWidth * targetHeight; + if (pixels < ResizeThreshold || !(linear ? EnsureLinearValidated(source, sourceWidth, sourceHeight) : EnsureNearestValidated(source, sourceWidth, sourceHeight))) + return false; + + return RunShader(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target); + } + + private bool EnsureNearestValidated(byte[] source, int sourceWidth, int sourceHeight) + { + if (_nearestValidated.HasValue) + return _nearestValidated.Value; + _nearestValidated = Validate(source, sourceWidth, sourceHeight, false); + return _nearestValidated.Value; + } + + private bool EnsureLinearValidated(byte[] source, int sourceWidth, int sourceHeight) + { + if (_linearValidated.HasValue) + return _linearValidated.Value; + _linearValidated = Validate(source, sourceWidth, sourceHeight, true); + return _linearValidated.Value; + } + + private bool Validate(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 RunShader(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, out var gpu) && gpu is not null && Equal(cpu, gpu); + } + + private bool RunShader(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target) + { + int count = checked(targetWidth * targetHeight * 4); + if (_target.Length != count) + _target = new byte[count]; + + _constants[0] = sourceWidth; + _constants[1] = sourceHeight; + _constants[2] = targetWidth; + _constants[3] = targetHeight; + _resources[0] = new PixelShaderInput(source, sourceWidth, sourceHeight); + target = _target; + return linear + ? RunResizeLinear(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight) + : RunResizeNearest(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight); + } + + private partial bool RunResizeNearest(ReadOnlySpan resources, ReadOnlySpan constants, byte[] target, int width, int height); + + private partial bool RunResizeLinear(ReadOnlySpan resources, ReadOnlySpan constants, byte[] target, int width, int height); + } +} diff --git a/LuaScript.Gpu/GpuPixelOperationShaders.cs b/LuaScript.Gpu/GpuPixelOperationShaders.cs deleted file mode 100644 index 127c259..0000000 --- a/LuaScript.Gpu/GpuPixelOperationShaders.cs +++ /dev/null @@ -1,5 +0,0 @@ -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/Shader/PixelShaderRunner.cs b/LuaScript.Gpu/Shader/PixelShaderRunner.cs index 92805d1..64aba07 100644 --- a/LuaScript.Gpu/Shader/PixelShaderRunner.cs +++ b/LuaScript.Gpu/Shader/PixelShaderRunner.cs @@ -42,6 +42,7 @@ namespace LuaScript.Engine.Shader private readonly Lock _locker = new(); private readonly Dictionary<(string Hlsl, string Entry), CompiledShader> _shaders = []; + private readonly Dictionary _precompiled = new(ReferenceEqualityComparer.Instance); private readonly InputSlot[] _inputs = new InputSlot[MaxResources]; private readonly ID3D11ShaderResourceView[] _boundViews = new ID3D11ShaderResourceView[MaxResources]; private readonly ID3D11ShaderResourceView[] _nullViews = new ID3D11ShaderResourceView[MaxResources]; @@ -87,49 +88,16 @@ namespace LuaScript.Engine.Shader int targetWidth, int targetHeight, out string? error) - { - return TryRunCore(hlsl, entryPoint, resources, constants, blend, sampler, target, targetWidth, targetHeight, false, out error); - } - - public PixelShaderRunStatus TryRunHardware( - string hlsl, - string entryPoint, - ReadOnlySpan resources, - ReadOnlySpan constants, - PixelShaderBlend blend, - PixelShaderSampler sampler, - byte[] target, - int targetWidth, - int targetHeight, - out string? error) - { - return TryRunCore(hlsl, entryPoint, resources, constants, blend, sampler, target, targetWidth, targetHeight, true, out error); - } - - private PixelShaderRunStatus TryRunCore( - string hlsl, - string entryPoint, - ReadOnlySpan resources, - ReadOnlySpan constants, - PixelShaderBlend blend, - PixelShaderSampler sampler, - byte[] target, - int targetWidth, - int targetHeight, - bool hardwareOnly, - out string? error) { error = null; lock (_locker) { - if (_disposed || _unavailable) - return PixelShaderRunStatus.Unavailable; - if (targetWidth <= 0 || targetHeight <= 0 || (long)target.Length < (long)targetWidth * targetHeight * 4) + if (!CanRun(target, targetWidth, targetHeight)) return PixelShaderRunStatus.Unavailable; try { - if (hardwareOnly ? !EnsureHardwareDevice() : !EnsureDevice()) + if (!EnsureDevice()) return PixelShaderRunStatus.Unavailable; var compiled = GetOrCompile(hlsl, entryPoint); @@ -150,6 +118,46 @@ namespace LuaScript.Engine.Shader } } + public PixelShaderRunStatus TryRunHardware( + byte[] bytecode, + ReadOnlySpan resources, + ReadOnlySpan constants, + PixelShaderBlend blend, + PixelShaderSampler sampler, + byte[] target, + int targetWidth, + int targetHeight, + out string? error) + { + error = null; + lock (_locker) + { + if (!CanRun(target, targetWidth, targetHeight)) + return PixelShaderRunStatus.Unavailable; + + try + { + if (!EnsureHardwareDevice()) + return PixelShaderRunStatus.Unavailable; + + Execute(GetOrCreate(bytecode), resources, constants, blend, sampler, target, targetWidth, targetHeight); + return PixelShaderRunStatus.Success; + } + catch (Exception ex) + { + HandleFailure(ex); + return PixelShaderRunStatus.Unavailable; + } + } + } + + private bool CanRun(byte[] target, int targetWidth, int targetHeight) + { + return !_disposed && !_unavailable && + targetWidth > 0 && targetHeight > 0 && + (long)target.Length >= (long)targetWidth * targetHeight * 4; + } + public void Invalidate() { lock (_locker) @@ -334,6 +342,16 @@ namespace LuaScript.Engine.Shader return compiled; } + private ID3D11PixelShader GetOrCreate(byte[] bytecode) + { + if (_precompiled.TryGetValue(bytecode, out var cached)) + return cached; + + var shader = _device!.CreatePixelShader(bytecode); + _precompiled[bytecode] = shader; + return shader; + } + private static byte[] CompileOrThrow(string source, string entryPoint, string profile) { var result = Compiler.Compile(Encoding.UTF8.GetBytes(source), entryPoint, string.Empty, profile, out var bytecode, out var errors); @@ -596,6 +614,9 @@ namespace LuaScript.Engine.Shader foreach (var compiled in _shaders.Values) compiled.Shader?.Dispose(); _shaders.Clear(); + foreach (var shader in _precompiled.Values) + shader.Dispose(); + _precompiled.Clear(); } private void ReleaseDeviceObjects()