diff --git a/LuaScript.Tests/KernelCpuEquivalenceTests.cs b/LuaScript.Tests/KernelCpuEquivalenceTests.cs new file mode 100644 index 0000000..96259cd --- /dev/null +++ b/LuaScript.Tests/KernelCpuEquivalenceTests.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using LuaScript.Engine; +using LuaScript.Engine.Kernel; +using MoonSharp.Interpreter; + +namespace LuaScript.Tests +{ + public sealed class KernelCpuEquivalenceTests + { + private const int Width = 23; + private const int Height = 17; + + [Theory] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,b,g,r,a) end end")] + [InlineData("for x=0,obj.w-1 do for y=0,obj.h-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r*r/255,g*g/255,b*b/255,a) end end")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255*math.pow(r/255,0.45),255*math.pow(g/255,0.45),255*math.pow(b/255,0.45),a) end end")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local v=(r+g+b)/3 obj.setpixel(x,y,v>128 and 255 or 0,v>128 and 255 or 0,v>128 and 255 or 0,a) end end")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,math.min(255,r+50),math.max(0,g-50),math.floor(b/16)*16,a) end end")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r%64,math.abs(g-128),math.sqrt(b*255),a) end end")] + public void CpuKernelMatchesMoonSharp(string script) + { + var fields = new Dictionary { ["w"] = Width, ["h"] = Height }; + AssertEquivalent(script, fields, new Dictionary()); + } + + [Fact] + public void CpuKernelMatchesMoonSharpWithUniforms() + { + const string script = + "for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " + + "obj.setpixel(x,y,r*obj.track0/100,g*math.sin(time)*0.5+g*0.5,b+x/obj.w*obj.track1,a) end end"; + var fields = new Dictionary { ["w"] = Width, ["h"] = Height, ["track0"] = 73d, ["track1"] = 40d }; + var globals = new Dictionary { ["time"] = 1.2345d }; + AssertEquivalent(script, fields, globals); + } + + [Theory] + [InlineData("--!cpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,255-r,255-g,255-b,a) end end")] + [InlineData("--!gpu\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end")] + [InlineData("--!cpu\r\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,x/obj.w*255,y/obj.h*255,b,a) end end")] + public void DirectivePrefixedKernelsMatchMoonSharp(string script) + { + var fields = new Dictionary { ["w"] = Width, ["h"] = Height }; + AssertEquivalent(script, fields, new Dictionary()); + } + + [Theory] + [InlineData("--!cpu", "Cpu")] + [InlineData("--!gpu", "Gpu")] + public void DirectivePrefixedKernelsRouteToAcceleratedLane(string directive, string expected) + { + string script = directive + "\nfor y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,r,g,b,a) end end"; + + Assert.True(ScriptDirective.TryResolveExplicit(script, out var kind)); + Assert.Equal(expected, kind.ToString()); + Assert.NotNull(KernelExtractor.TryExtract(script)); + } + + [Theory] + [InlineData("obj.setpixel(0,0,0,0,0,0)")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) total=total+r obj.setpixel(x,y,r,g,b,a) end end")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x+1,y) obj.setpixel(x,y,r,g,b,a) end end")] + [InlineData("for i=0,10 do end")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) if r>128 then r=255 end obj.setpixel(x,y,r,g,b,a) end end")] + [InlineData("for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) obj.setpixel(x,y,obj.rand(0,255),g,b,a) end end")] + public void NonKernelScriptsAreRejected(string script) + { + Assert.Null(KernelExtractor.TryExtract(script)); + } + + private static void AssertEquivalent(string script, Dictionary fields, Dictionary globals) + { + var program = KernelExtractor.TryExtract(script); + Assert.NotNull(program); + + byte[] source = CreateBuffer(20260629); + byte[] oracle = (byte[])source.Clone(); + byte[] candidate = (byte[])source.Clone(); + + RunMoonSharp(script, oracle, fields, globals); + + double[] uniforms = new double[KernelUniforms.Count]; + foreach (var (name, value) in fields) + if (KernelUniforms.TryResolveMember("obj", name, out var uniform)) + uniforms[(int)uniform] = value; + foreach (var (name, value) in globals) + if (KernelUniforms.TryResolveGlobal(name, out var uniform)) + uniforms[(int)uniform] = value; + + CpuKernelCompiler.Compile(program!).Execute(candidate, Width, Height, uniforms); + + Assert.Equal(oracle, candidate); + } + + private static byte[] CreateBuffer(int seed) + { + var random = new Random(seed); + var buffer = new byte[Width * Height * 4]; + random.NextBytes(buffer); + return buffer; + } + + private static void RunMoonSharp(string script, byte[] buffer, Dictionary fields, Dictionary globals) + { + var engine = new Script(CoreModules.Basic | CoreModules.Math | CoreModules.Bit32); + var obj = new Table(engine); + foreach (var (name, value) in fields) + obj[name] = value; + foreach (var (name, value) in globals) + engine.Globals[name] = value; + + obj["getpixel"] = DynValue.NewCallback((_, args) => + { + int x = (int)(args[0].CastToNumber() ?? 0d); + int y = (int)(args[1].CastToNumber() ?? 0d); + var (r, g, b, a) = GetPixel(buffer, x, y); + return DynValue.NewTuple( + DynValue.NewNumber(r), DynValue.NewNumber(g), DynValue.NewNumber(b), DynValue.NewNumber(a)); + }); + + obj["setpixel"] = DynValue.NewCallback((_, args) => + { + int x = (int)(args[0].CastToNumber() ?? 0d); + int y = (int)(args[1].CastToNumber() ?? 0d); + double r = args[2].CastToNumber() ?? 0d; + double g = args[3].CastToNumber() ?? 0d; + double b = args[4].CastToNumber() ?? 0d; + double a = args.Count > 5 ? args[5].CastToNumber() ?? 255d : 255d; + SetPixel(buffer, x, y, r, g, b, a); + return DynValue.Void; + }); + + engine.Globals["obj"] = obj; + engine.DoString(script); + } + + private static (double r, double g, double b, double a) GetPixel(byte[] buffer, int x, int y) + { + if ((uint)x >= Width || (uint)y >= Height) + return (0d, 0d, 0d, 0d); + + int p = (y * Width + x) * 4; + double alpha = buffer[p + 3]; + if (alpha <= 0d) + return (0d, 0d, 0d, 0d); + + double scale = 255d / alpha; + return ( + Math.Clamp(buffer[p + 2] * scale, 0d, 255d), + Math.Clamp(buffer[p + 1] * scale, 0d, 255d), + Math.Clamp(buffer[p] * scale, 0d, 255d), + alpha); + } + + private static void SetPixel(byte[] buffer, int x, int y, double r, double g, double b, double a) + { + if ((uint)x >= Width || (uint)y >= Height) + return; + + int p = (y * Width + x) * 4; + double k = Math.Clamp(a, 0d, 255d) / 255d; + buffer[p] = (byte)Math.Clamp(b * k, 0d, 255d); + buffer[p + 1] = (byte)Math.Clamp(g * k, 0d, 255d); + buffer[p + 2] = (byte)Math.Clamp(r * k, 0d, 255d); + buffer[p + 3] = (byte)Math.Clamp(a, 0d, 255d); + } + } +} diff --git a/LuaScript.Tests/KernelHlslEmitterTests.cs b/LuaScript.Tests/KernelHlslEmitterTests.cs new file mode 100644 index 0000000..ec9d11b --- /dev/null +++ b/LuaScript.Tests/KernelHlslEmitterTests.cs @@ -0,0 +1,64 @@ +using LuaScript.Engine.Kernel; + +namespace LuaScript.Tests +{ + public sealed class KernelHlslEmitterTests + { + private const string Grayscale = + "for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " + + "local l=0.298912*r+0.586611*g+0.114478*b obj.setpixel(x,y,l,l,l,a) end end"; + + private const string Threshold = + "for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " + + "obj.setpixel(x,y,r>128 and 255 or 0,g,b,a) end end"; + + private const string WithTrack = + "for y=0,obj.h-1 do for x=0,obj.w-1 do local r,g,b,a=obj.getpixel(x,y) " + + "obj.setpixel(x,y,r*obj.track0/100,g,b,a) end end"; + + [Fact] + public void EmitsValidShaderSkeleton() + { + string hlsl = HlslKernelEmitter.Emit(Extract(Grayscale)); + + Assert.Contains("Texture2D InputTexture : register(t0);", hlsl); + Assert.Contains("cbuffer constants : register(b0)", hlsl); + Assert.Contains("float4 main(float4 pos : SV_POSITION", hlsl); + Assert.Contains("InputTexture.Sample(InputSampler, uv.xy)", hlsl); + Assert.Contains("return float4(oR, oG, oB, oA);", hlsl); + Assert.Contains("inR", hlsl); + Assert.Contains("inG", hlsl); + Assert.Contains("inB", hlsl); + } + + [Fact] + public void ThresholdEmitsTernary() + { + string hlsl = HlslKernelEmitter.Emit(Extract(Threshold)); + Assert.Contains(" ? (", hlsl); + Assert.Contains(" > ", hlsl); + } + + [Fact] + public void UniformReferencesUsePackedConstantBuffer() + { + string hlsl = HlslKernelEmitter.Emit(Extract(WithTrack)); + int index = (int)KernelUniform.Track0; + Assert.Contains($"uniforms[{index / 4}].{"xyzw"[index % 4]}", hlsl); + } + + [Fact] + public void EmissionIsDeterministic() + { + var program = Extract(Grayscale); + Assert.Equal(HlslKernelEmitter.Emit(program), HlslKernelEmitter.Emit(program)); + } + + private static KernelProgram Extract(string script) + { + var program = KernelExtractor.TryExtract(script); + Assert.NotNull(program); + return program!; + } + } +} diff --git a/LuaScript.Tests/LuaScript.Tests.csproj b/LuaScript.Tests/LuaScript.Tests.csproj index 539d9a2..fcb5dea 100644 --- a/LuaScript.Tests/LuaScript.Tests.csproj +++ b/LuaScript.Tests/LuaScript.Tests.csproj @@ -41,6 +41,17 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/LuaScript/Engine/Kernel/CpuKernel.cs b/LuaScript/Engine/Kernel/CpuKernel.cs new file mode 100644 index 0000000..3f7b7f5 --- /dev/null +++ b/LuaScript/Engine/Kernel/CpuKernel.cs @@ -0,0 +1,28 @@ +using System.Threading.Tasks; + +namespace LuaScript.Engine.Kernel +{ + internal sealed class CpuKernel(CpuKernel.RowDelegate row) + { + public delegate void RowDelegate(byte[] buffer, int width, int rowBase, double y, double[] uniforms); + + private const int ParallelThreshold = 64; + + private readonly RowDelegate _row = row; + + public void Execute(byte[] buffer, int width, int height, double[] uniforms) + { + var row = _row; + int stride = width * 4; + + if (height < ParallelThreshold) + { + for (int y = 0; y < height; y++) + row(buffer, width, y * stride, y, uniforms); + return; + } + + Parallel.For(0, height, y => row(buffer, width, y * stride, y, uniforms)); + } + } +} diff --git a/LuaScript/Engine/Kernel/CpuKernelCompiler.cs b/LuaScript/Engine/Kernel/CpuKernelCompiler.cs new file mode 100644 index 0000000..68c406c --- /dev/null +++ b/LuaScript/Engine/Kernel/CpuKernelCompiler.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Reflection; + +namespace LuaScript.Engine.Kernel +{ + internal static class CpuKernelCompiler + { + private static readonly MethodInfo Clamp = typeof(Math).GetMethod(nameof(Math.Clamp), [typeof(double), typeof(double), typeof(double)])!; + private static readonly MethodInfo Floor = Unary(nameof(Math.Floor)); + private static readonly MethodInfo Pow = Binary(nameof(Math.Pow)); + + private static readonly Dictionary Functions = new() + { + [KFunc.Abs] = Unary(nameof(Math.Abs)), + [KFunc.Floor] = Floor, + [KFunc.Ceil] = Unary(nameof(Math.Ceiling)), + [KFunc.Sqrt] = Unary(nameof(Math.Sqrt)), + [KFunc.Sin] = Unary(nameof(Math.Sin)), + [KFunc.Cos] = Unary(nameof(Math.Cos)), + [KFunc.Tan] = Unary(nameof(Math.Tan)), + [KFunc.Asin] = Unary(nameof(Math.Asin)), + [KFunc.Acos] = Unary(nameof(Math.Acos)), + [KFunc.Atan] = Unary(nameof(Math.Atan)), + [KFunc.Atan2] = Binary(nameof(Math.Atan2)), + [KFunc.Exp] = Unary(nameof(Math.Exp)), + [KFunc.Log] = Unary(nameof(Math.Log)), + [KFunc.Pow] = Pow, + [KFunc.Min] = Binary(nameof(Math.Min)), + [KFunc.Max] = Binary(nameof(Math.Max)), + }; + + public static CpuKernel Compile(KernelProgram program) + { + var buffer = Expression.Parameter(typeof(byte[]), "buffer"); + var width = Expression.Parameter(typeof(int), "width"); + var rowBase = Expression.Parameter(typeof(int), "rowBase"); + var y = Expression.Parameter(typeof(double), "y"); + var uniforms = Expression.Parameter(typeof(double[]), "uniforms"); + + var x = Expression.Variable(typeof(int), "x"); + var index = Expression.Variable(typeof(int), "index"); + var alphaRaw = Expression.Variable(typeof(double), "alphaRaw"); + var transparent = Expression.Variable(typeof(bool), "transparent"); + var scale = Expression.Variable(typeof(double), "scale"); + var inputs = new[] + { + Expression.Variable(typeof(double), "inR"), + Expression.Variable(typeof(double), "inG"), + Expression.Variable(typeof(double), "inB"), + Expression.Variable(typeof(double), "inA"), + }; + var slots = new ParameterExpression[program.Bindings.Count]; + for (int i = 0; i < slots.Length; i++) + slots[i] = Expression.Variable(typeof(double), "slot" + i); + + var context = new Context(x, y, uniforms, inputs, slots); + + var statements = new List + { + Expression.Assign(index, Expression.Add(rowBase, Expression.Multiply(x, Constant(4)))), + Expression.Assign(alphaRaw, ToDouble(ReadByte(buffer, index, 3))), + Expression.Assign(transparent, Expression.LessThanOrEqual(alphaRaw, Constant(0d))), + Expression.Assign(scale, Select(transparent, Constant(0d), Expression.Divide(Constant(255d), alphaRaw))), + Expression.Assign(inputs[3], Select(transparent, Constant(0d), alphaRaw)), + Expression.Assign(inputs[0], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 2)), scale)))), + Expression.Assign(inputs[1], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 1)), scale)))), + Expression.Assign(inputs[2], Select(transparent, Constant(0d), ClampByte(Expression.Multiply(ToDouble(ReadByte(buffer, index, 0)), scale)))), + }; + + for (int i = 0; i < slots.Length; i++) + statements.Add(Expression.Assign(slots[i], Build(program.Bindings[i], context))); + + var outA = Expression.Variable(typeof(double), "outA"); + var alphaScale = Expression.Variable(typeof(double), "alphaScale"); + statements.Add(Expression.Assign(outA, Build(program.OutputA, context))); + statements.Add(Expression.Assign(alphaScale, Expression.Divide(ClampByte(outA), Constant(255d)))); + statements.Add(WriteByte(buffer, index, 0, ClampByte(Expression.Multiply(Build(program.OutputB, context), alphaScale)))); + statements.Add(WriteByte(buffer, index, 1, ClampByte(Expression.Multiply(Build(program.OutputG, context), alphaScale)))); + statements.Add(WriteByte(buffer, index, 2, ClampByte(Expression.Multiply(Build(program.OutputR, context), alphaScale)))); + statements.Add(WriteByte(buffer, index, 3, ClampByte(outA))); + statements.Add(Expression.PostIncrementAssign(x)); + + var breakLabel = Expression.Label("break"); + var loop = Expression.Loop( + Expression.IfThenElse( + Expression.LessThan(x, width), + Expression.Block(statements), + Expression.Break(breakLabel)), + breakLabel); + + var locals = new List { x, index, alphaRaw, transparent, scale, outA, alphaScale }; + locals.AddRange(inputs); + locals.AddRange(slots); + + var body = Expression.Block(locals, Expression.Assign(x, Constant(0)), loop); + + var lambda = Expression.Lambda(body, buffer, width, rowBase, y, uniforms); + return new CpuKernel(lambda.Compile()); + } + + private sealed record Context( + ParameterExpression X, + ParameterExpression Y, + ParameterExpression Uniforms, + ParameterExpression[] Inputs, + ParameterExpression[] Slots); + + private static Expression Build(KExpr expression, Context context) + { + switch (expression) + { + case KConst value: + return Constant(value.Value); + case KInput input: + return context.Inputs[(int)input.Channel]; + case KCoord coord: + return coord.Axis == KAxis.X ? ToDouble(context.X) : context.Y; + case KUniformRef uniform: + return Expression.ArrayIndex(context.Uniforms, Constant((int)uniform.Uniform)); + case KLocalRef local: + return context.Slots[local.Slot]; + case KNegate negate: + return Expression.Negate(Build(negate.Operand, context)); + case KArith arithmetic: + return BuildArithmetic(arithmetic, context); + case KCall call: + return BuildCall(call, context); + case KSelect select: + return Select(BuildBool(select.Condition, context), Build(select.WhenTrue, context), Build(select.WhenFalse, context)); + } + throw new KernelUnsupportedException("Unsupported CPU expression."); + } + + private static Expression BuildArithmetic(KArith arithmetic, Context context) + { + var left = Build(arithmetic.Left, context); + var right = Build(arithmetic.Right, context); + return arithmetic.Op switch + { + KArithOp.Add => Expression.Add(left, right), + KArithOp.Subtract => Expression.Subtract(left, right), + KArithOp.Multiply => Expression.Multiply(left, right), + KArithOp.Divide => Expression.Divide(left, right), + KArithOp.Modulo => FlooredModulo(left, right), + KArithOp.Power => Expression.Call(Pow, left, right), + _ => throw new KernelUnsupportedException("Unsupported arithmetic operator."), + }; + } + + private static Expression BuildCall(KCall call, Context context) + { + var method = Functions[call.Func]; + if (call.Arguments.Count == 1) + return Expression.Call(method, Build(call.Arguments[0], context)); + return Expression.Call(method, Build(call.Arguments[0], context), Build(call.Arguments[1], context)); + } + + private static Expression BuildBool(KBool condition, Context context) + { + switch (condition) + { + case KBoolConst value: + return Expression.Constant(value.Value); + case KNot not: + return Expression.Not(BuildBool(not.Operand, context)); + case KLogical logical: + return logical.IsAnd + ? Expression.AndAlso(BuildBool(logical.Left, context), BuildBool(logical.Right, context)) + : Expression.OrElse(BuildBool(logical.Left, context), BuildBool(logical.Right, context)); + case KCompare compare: + var left = Build(compare.Left, context); + var right = Build(compare.Right, context); + return compare.Op switch + { + KCompareOp.Less => Expression.LessThan(left, right), + KCompareOp.Greater => Expression.GreaterThan(left, right), + KCompareOp.LessEqual => Expression.LessThanOrEqual(left, right), + KCompareOp.GreaterEqual => Expression.GreaterThanOrEqual(left, right), + KCompareOp.Equal => Expression.Equal(left, right), + KCompareOp.NotEqual => Expression.NotEqual(left, right), + _ => throw new KernelUnsupportedException("Unsupported comparison."), + }; + } + throw new KernelUnsupportedException("Unsupported CPU condition."); + } + + private static Expression FlooredModulo(Expression left, Expression right) => + Expression.Subtract(left, Expression.Multiply(Expression.Call(Floor, Expression.Divide(left, right)), right)); + + private static Expression Select(Expression condition, Expression whenTrue, Expression whenFalse) => + Expression.Condition(condition, whenTrue, whenFalse); + + private static Expression ClampByte(Expression value) => + Expression.Call(Clamp, value, Constant(0d), Constant(255d)); + + private static Expression ReadByte(ParameterExpression buffer, ParameterExpression index, int offset) => + Expression.ArrayIndex(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset))); + + private static Expression WriteByte(ParameterExpression buffer, ParameterExpression index, int offset, Expression value) => + Expression.Assign( + Expression.ArrayAccess(buffer, offset == 0 ? index : Expression.Add(index, Constant(offset))), + Expression.Convert(value, typeof(byte))); + + private static Expression ToDouble(Expression value) => Expression.Convert(value, typeof(double)); + + private static ConstantExpression Constant(double value) => Expression.Constant(value, typeof(double)); + + private static ConstantExpression Constant(int value) => Expression.Constant(value, typeof(int)); + + private static MethodInfo Unary(string name) => typeof(Math).GetMethod(name, [typeof(double)])!; + + private static MethodInfo Binary(string name) => typeof(Math).GetMethod(name, [typeof(double), typeof(double)])!; + } +} diff --git a/LuaScript/Engine/Kernel/GpuKernel.cs b/LuaScript/Engine/Kernel/GpuKernel.cs new file mode 100644 index 0000000..abf1df3 --- /dev/null +++ b/LuaScript/Engine/Kernel/GpuKernel.cs @@ -0,0 +1,29 @@ +using System; +using Vortice.Direct2D1; +using YukkuriMovieMaker.Commons; + +namespace LuaScript.Engine.Kernel +{ + internal sealed class GpuKernel : IDisposable + { + private readonly GpuKernelEffect _effect; + private readonly float[] _packed = new float[HlslKernelEmitter.ConstantFloatCount]; + private readonly byte[] _bytes = new byte[HlslKernelEmitter.ConstantFloatCount * sizeof(float)]; + + public GpuKernel(IGraphicsDevicesAndContext devices, KernelProgram program) + => _effect = new GpuKernelEffect(devices, HlslKernelEmitter.Emit(program)); + + public bool IsReady => _effect.IsReady; + + public ID2D1Image Apply(ID2D1Image input, double[] uniforms) + { + KernelUniformBinding.Pack(uniforms, _packed); + Buffer.BlockCopy(_packed, 0, _bytes, 0, _bytes.Length); + _effect.SetConstants(_bytes); + _effect.SetInput(0, input, true); + return _effect.Output; + } + + public void Dispose() => _effect.Dispose(); + } +} diff --git a/LuaScript/Engine/Kernel/GpuKernelEffect.cs b/LuaScript/Engine/Kernel/GpuKernelEffect.cs new file mode 100644 index 0000000..b7b744e --- /dev/null +++ b/LuaScript/Engine/Kernel/GpuKernelEffect.cs @@ -0,0 +1,193 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using Vortice; +using Vortice.D3DCompiler; +using Vortice.Direct2D1; +using Vortice.Direct3D; +using Vortice.Mathematics; +using YukkuriMovieMaker.Commons; + +namespace LuaScript.Engine.Kernel +{ + internal sealed class GpuKernelEffect : ID2D1Effect + { + private const int ConstantsIndex = 0; + private const int InitializedIndex = 1; + + [StructLayout(LayoutKind.Sequential)] + private unsafe struct ConstantBuffer + { + public fixed float Values[HlslKernelEmitter.ConstantFloatCount]; + } + + [CustomEffect(1, null, null, null, null)] + private sealed class Impl(Guid guid, string hlsl) : CustomEffectBase, ID2D1DrawTransform + { + private ConstantBuffer _constants; + private ID2D1DrawInfo? _drawInfo; + + [CustomEffectProperty(PropertyType.Blob, ConstantsIndex)] + public byte[] Constants + { + get => ToBytes(_constants); + set + { + FromBytes(value, ref _constants); + _drawInfo?.SetPixelShaderConstantBuffer(in _constants); + } + } + + [CustomEffectProperty(PropertyType.Bool, InitializedIndex)] + public bool Initialized { get; private set; } + + public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph) + { + byte[] source = Encoding.ASCII.GetBytes(hlsl); + var result = Compiler.Compile(source, "main", string.Empty, "ps_4_1", out var bytecode, out var errors); + if (result.Failure || bytecode is null) + { + Initialized = false; + Log.Default.Write("LuaScript: GPU kernel shader compilation failed.\n" + (errors?.AsString() ?? string.Empty)); + errors?.Dispose(); + bytecode?.Dispose(); + return; + } + + try + { + byte[] shader = bytecode.AsBytes(); + effectContext.LoadPixelShader(guid, shader, shader.Length); + transformGraph.SetSingleTransformNode(this); + Initialized = true; + } + finally + { + errors?.Dispose(); + bytecode.Dispose(); + } + } + + public void SetDrawInfo(ID2D1DrawInfo drawInfo) + { + _drawInfo = drawInfo; + drawInfo.SetPixelShader(guid, PixelOptions.None); + drawInfo.SetInputDescription(0, new InputDescription { Filter = (Filter)21, LevelOfDetailCount = 1 }); + drawInfo.SetPixelShaderConstantBuffer(in _constants); + } + + public int GetInputCount() => 1; + + public void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects) => + inputRects[0] = outputRect; + + public void MapInputRectsToOutputRect(RawRect[] inputRects, RawRect[] inputOpaqueSubRects, out RawRect outputRect, out RawRect outputOpaqueSubRect) + { + outputRect = inputRects[0]; + outputOpaqueSubRect = default; + } + + public RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect) => invalidInputRect; + + private static unsafe byte[] ToBytes(ConstantBuffer constants) + { + byte[] bytes = new byte[sizeof(ConstantBuffer)]; + fixed (byte* destination = bytes) + *(ConstantBuffer*)destination = constants; + return bytes; + } + + private static unsafe void FromBytes(byte[] bytes, ref ConstantBuffer constants) + { + int length = Math.Min(bytes.Length, sizeof(ConstantBuffer)); + fixed (byte* source = bytes) + fixed (ConstantBuffer* destination = &constants) + Buffer.MemoryCopy(source, destination, sizeof(ConstantBuffer), length); + } + } + + private sealed class Manager + { + private readonly Lock _locker = new(); + private readonly Dictionary> _registered = []; + + public Guid Acquire(IGraphicsDevicesAndContext devices, string hlsl) + { + lock (_locker) + { + int device = devices.GetHashCode(); + if (!_registered.TryGetValue(device, out var byHlsl)) + { + byHlsl = []; + _registered[device] = byHlsl; + } + if (byHlsl.TryGetValue(hlsl, out var entry)) + { + byHlsl[hlsl] = (entry.Guid, entry.Count + 1); + return entry.Guid; + } + + var guid = Guid.NewGuid(); + byHlsl[hlsl] = (guid, 1); + ((ID2D1Factory1)devices.D2D.Factory).RegisterEffect(() => new Impl(guid, hlsl), guid); + return guid; + } + } + + public void Release(IGraphicsDevicesAndContext devices, string hlsl) + { + lock (_locker) + { + int device = devices.GetHashCode(); + if (!_registered.TryGetValue(device, out var byHlsl) || !byHlsl.TryGetValue(hlsl, out var entry)) + return; + if (entry.Count > 1) + { + byHlsl[hlsl] = (entry.Guid, entry.Count - 1); + return; + } + byHlsl.Remove(hlsl); + ((ID2D1Factory1)devices.D2D.Factory).UnregisterEffect(entry.Guid); + } + } + } + + private static readonly Manager Effects = new(); + + private readonly IGraphicsDevicesAndContext _devices; + private readonly string _hlsl; + + public GpuKernelEffect(IGraphicsDevicesAndContext devices, string hlsl) + : base(Create(devices, hlsl)) + { + _devices = devices; + _hlsl = hlsl; + } + + public bool IsReady => NativePointer != nint.Zero && ((ID2D1Properties)this).GetBoolValue(InitializedIndex); + + public void SetConstants(byte[] bytes) => ((ID2D1Properties)this).SetValue(ConstantsIndex, bytes); + + private static nint Create(IGraphicsDevicesAndContext devices, string hlsl) + { + try + { + var guid = Effects.Acquire(devices, hlsl); + return ((ID2D1DeviceContext)devices.DeviceContext).CreateEffect(guid); + } + catch (Exception ex) + { + Log.Default.Write("LuaScript: failed to create GPU kernel effect.", ex); + return nint.Zero; + } + } + + protected override void DisposeCore(nint nativePointer, bool disposing) + { + base.DisposeCore(nativePointer, disposing); + Effects.Release(_devices, _hlsl); + } + } +} diff --git a/LuaScript/Engine/Kernel/HlslKernelEmitter.cs b/LuaScript/Engine/Kernel/HlslKernelEmitter.cs new file mode 100644 index 0000000..4d10a71 --- /dev/null +++ b/LuaScript/Engine/Kernel/HlslKernelEmitter.cs @@ -0,0 +1,225 @@ +using System.Globalization; +using System.Text; + +namespace LuaScript.Engine.Kernel +{ + internal static class HlslKernelEmitter + { + public const int ConstantVectorCount = 16; + + public const int ConstantFloatCount = ConstantVectorCount * 4; + + private static readonly string[] Intrinsics = + [ + "abs", "floor", "ceil", "sqrt", "sin", "cos", "tan", "asin", "acos", + "atan", "atan2", "exp", "log", "pow", "min", "max", "fmod", + ]; + + public static string Emit(KernelProgram program) + { + var builder = new StringBuilder(1024); + + builder.Append("Texture2D InputTexture : register(t0);\n"); + builder.Append("SamplerState InputSampler : register(s0);\n"); + builder.Append("cbuffer constants : register(b0)\n{\n"); + builder.Append(" float4 uniforms[").Append(ConstantVectorCount).Append("];\n"); + builder.Append("};\n\n"); + builder.Append("float4 main(float4 pos : SV_POSITION, float4 posScene : SCENE_POSITION, float4 uv : TEXCOORD0) : SV_Target\n{\n"); + builder.Append(" float4 src = InputTexture.Sample(InputSampler, uv.xy);\n"); + builder.Append(" float srcA = src.a;\n"); + builder.Append(" float invA = srcA <= 0.0 ? 0.0 : 1.0 / srcA;\n"); + builder.Append(" float inR = clamp(src.r * invA * 255.0, 0.0, 255.0);\n"); + builder.Append(" float inG = clamp(src.g * invA * 255.0, 0.0, 255.0);\n"); + builder.Append(" float inB = clamp(src.b * invA * 255.0, 0.0, 255.0);\n"); + builder.Append(" float inA = srcA * 255.0;\n"); + builder.Append(" float px = uv.x * ").Append(Uniform(KernelUniform.Width)).Append(";\n"); + builder.Append(" float py = uv.y * ").Append(Uniform(KernelUniform.Height)).Append(";\n"); + + for (int i = 0; i < program.Bindings.Count; i++) + { + builder.Append(" float slot").Append(i).Append(" = "); + EmitExpression(builder, program.Bindings[i]); + builder.Append(";\n"); + } + + builder.Append(" float outA = "); + EmitExpression(builder, program.OutputA); + builder.Append(";\n"); + builder.Append(" float alphaK = clamp(outA, 0.0, 255.0) / 255.0;\n"); + + builder.Append(" float oR = clamp(("); + EmitExpression(builder, program.OutputR); + builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n"); + builder.Append(" float oG = clamp(("); + EmitExpression(builder, program.OutputG); + builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n"); + builder.Append(" float oB = clamp(("); + EmitExpression(builder, program.OutputB); + builder.Append(") * alphaK, 0.0, 255.0) / 255.0;\n"); + builder.Append(" float oA = clamp(outA, 0.0, 255.0) / 255.0;\n"); + builder.Append(" return float4(oR, oG, oB, oA);\n}\n"); + + return builder.ToString(); + } + + private static void EmitExpression(StringBuilder builder, KExpr expression) + { + switch (expression) + { + case KConst value: + builder.Append(Number(value.Value)); + return; + case KInput input: + builder.Append(input.Channel switch + { + KChannel.R => "inR", + KChannel.G => "inG", + KChannel.B => "inB", + _ => "inA", + }); + return; + case KCoord coord: + builder.Append(coord.Axis == KAxis.X ? "px" : "py"); + return; + case KUniformRef uniform: + builder.Append(Uniform(uniform.Uniform)); + return; + case KLocalRef local: + builder.Append("slot").Append(local.Slot); + return; + case KNegate negate: + builder.Append("(-("); + EmitExpression(builder, negate.Operand); + builder.Append("))"); + return; + case KArith arithmetic: + EmitArithmetic(builder, arithmetic); + return; + case KCall call: + EmitCall(builder, call); + return; + case KSelect select: + builder.Append('('); + EmitCondition(builder, select.Condition); + builder.Append(" ? ("); + EmitExpression(builder, select.WhenTrue); + builder.Append(") : ("); + EmitExpression(builder, select.WhenFalse); + builder.Append("))"); + return; + } + throw new KernelUnsupportedException("Unsupported HLSL expression."); + } + + private static void EmitArithmetic(StringBuilder builder, KArith arithmetic) + { + if (arithmetic.Op == KArithOp.Power) + { + builder.Append("pow("); + EmitExpression(builder, arithmetic.Left); + builder.Append(", "); + EmitExpression(builder, arithmetic.Right); + builder.Append(')'); + return; + } + + if (arithmetic.Op == KArithOp.Modulo) + { + builder.Append('('); + EmitExpression(builder, arithmetic.Left); + builder.Append(" - floor(("); + EmitExpression(builder, arithmetic.Left); + builder.Append(") / ("); + EmitExpression(builder, arithmetic.Right); + builder.Append(")) * ("); + EmitExpression(builder, arithmetic.Right); + builder.Append("))"); + return; + } + + builder.Append('('); + EmitExpression(builder, arithmetic.Left); + builder.Append(arithmetic.Op switch + { + KArithOp.Add => " + ", + KArithOp.Subtract => " - ", + KArithOp.Multiply => " * ", + KArithOp.Divide => " / ", + _ => throw new KernelUnsupportedException("Unsupported arithmetic operator."), + }); + EmitExpression(builder, arithmetic.Right); + builder.Append(')'); + } + + private static void EmitCall(StringBuilder builder, KCall call) + { + builder.Append(Intrinsics[(int)call.Func]).Append('('); + for (int i = 0; i < call.Arguments.Count; i++) + { + if (i > 0) + builder.Append(", "); + EmitExpression(builder, call.Arguments[i]); + } + builder.Append(')'); + } + + private static void EmitCondition(StringBuilder builder, KBool condition) + { + switch (condition) + { + case KBoolConst value: + builder.Append(value.Value ? "true" : "false"); + return; + case KNot not: + builder.Append("(!("); + EmitCondition(builder, not.Operand); + builder.Append("))"); + return; + case KLogical logical: + builder.Append('('); + EmitCondition(builder, logical.Left); + builder.Append(logical.IsAnd ? " && " : " || "); + EmitCondition(builder, logical.Right); + builder.Append(')'); + return; + case KCompare compare: + builder.Append('('); + EmitExpression(builder, compare.Left); + builder.Append(compare.Op switch + { + KCompareOp.Less => " < ", + KCompareOp.Greater => " > ", + KCompareOp.LessEqual => " <= ", + KCompareOp.GreaterEqual => " >= ", + KCompareOp.Equal => " == ", + _ => " != ", + }); + EmitExpression(builder, compare.Right); + builder.Append(')'); + return; + } + throw new KernelUnsupportedException("Unsupported HLSL condition."); + } + + private static string Uniform(KernelUniform uniform) + { + int index = (int)uniform; + return $"uniforms[{index / 4}].{"xyzw"[index % 4]}"; + } + + private static string Number(double value) + { + if (double.IsPositiveInfinity(value)) + return "3.4028235e38"; + if (double.IsNegativeInfinity(value)) + return "-3.4028235e38"; + if (double.IsNaN(value)) + return "(0.0 / 0.0)"; + + string text = value.ToString("R", CultureInfo.InvariantCulture); + if (!text.Contains('.') && !text.Contains('e') && !text.Contains('E')) + text += ".0"; + return text; + } + } +} diff --git a/LuaScript/Engine/Kernel/KernelExtractor.cs b/LuaScript/Engine/Kernel/KernelExtractor.cs new file mode 100644 index 0000000..4f1abb9 --- /dev/null +++ b/LuaScript/Engine/Kernel/KernelExtractor.cs @@ -0,0 +1,357 @@ +using System; +using System.Collections.Generic; + +namespace LuaScript.Engine.Kernel +{ + internal sealed class KernelExtractor + { + private readonly record struct FuncSpec(KFunc Func, int MinArgs, int MaxArgs); + + private static readonly Dictionary MathFunctions = new(StringComparer.Ordinal) + { + ["abs"] = new(KFunc.Abs, 1, 1), + ["floor"] = new(KFunc.Floor, 1, 1), + ["ceil"] = new(KFunc.Ceil, 1, 1), + ["sqrt"] = new(KFunc.Sqrt, 1, 1), + ["sin"] = new(KFunc.Sin, 1, 1), + ["cos"] = new(KFunc.Cos, 1, 1), + ["tan"] = new(KFunc.Tan, 1, 1), + ["asin"] = new(KFunc.Asin, 1, 1), + ["acos"] = new(KFunc.Acos, 1, 1), + ["atan"] = new(KFunc.Atan, 1, 1), + ["atan2"] = new(KFunc.Atan2, 2, 2), + ["exp"] = new(KFunc.Exp, 1, 1), + ["log"] = new(KFunc.Log, 1, 1), + ["pow"] = new(KFunc.Pow, 2, 2), + ["fmod"] = new(KFunc.Fmod, 2, 2), + ["min"] = new(KFunc.Min, 2, int.MaxValue), + ["max"] = new(KFunc.Max, 2, int.MaxValue), + }; + + private readonly List _bindings = []; + private readonly Dictionary _scope = new(StringComparer.Ordinal); + private readonly SortedSet _uniforms = []; + + private string _widthVariable = string.Empty; + private string _heightVariable = string.Empty; + private bool _coordsEnabled; + + public static KernelProgram? TryExtract(string runnableScript) + { + try + { + return new KernelExtractor().Extract(runnableScript); + } + catch (KernelUnsupportedException) + { + return null; + } + } + + private KernelProgram? Extract(string runnableScript) + { + var block = LuaParser.Parse(runnableScript); + + int index = 0; + while (index < block.Count && block[index] is LocalStmt prelude) + { + BindLocal(prelude); + index++; + } + + if (index >= block.Count || block[index] is not NumericForStmt outer) + return null; + if (index + 1 != block.Count) + return null; + + if (!TryAxis(outer, out string outerVar, out KAxis outerAxis)) + return null; + if (outer.Body.Count != 1 || outer.Body[0] is not NumericForStmt inner) + return null; + if (!TryAxis(inner, out string innerVar, out KAxis innerAxis)) + return null; + if (outerAxis == innerAxis) + return null; + + _widthVariable = outerAxis == KAxis.X ? outerVar : innerVar; + _heightVariable = outerAxis == KAxis.Y ? outerVar : innerVar; + + return BuildKernel(inner.Body); + } + + private KernelProgram? BuildKernel(IReadOnlyList body) + { + if (body.Count < 2) + return null; + + if (body[0] is not LocalStmt sample || sample.Values.Count != 1 || + !IsGetPixel(sample.Values[0])) + return null; + if (sample.Names.Count is < 1 or > 4) + return null; + + _coordsEnabled = true; + for (int i = 0; i < sample.Names.Count; i++) + { + EnsureNotCoordinateName(sample.Names[i]); + _scope[sample.Names[i]] = AddBinding(new KInput((KChannel)i)); + } + + for (int i = 1; i < body.Count - 1; i++) + { + switch (body[i]) + { + case LocalStmt local: + BindLocal(local); + break; + case AssignStmt assign: + BindAssign(assign); + break; + default: + return null; + } + } + + if (body[^1] is not CallStmt { Call: var call } || !IsObjectMethod(call, "setpixel")) + return null; + if (call.Arguments.Count is < 5 or > 6) + return null; + if (!IsCoordinate(call.Arguments[0], KAxis.X) || !IsCoordinate(call.Arguments[1], KAxis.Y)) + return null; + + var outR = Lower(call.Arguments[2]); + var outG = Lower(call.Arguments[3]); + var outB = Lower(call.Arguments[4]); + var outA = call.Arguments.Count == 6 ? Lower(call.Arguments[5]) : new KConst(255d); + + return new KernelProgram(_bindings, outR, outG, outB, outA, [.. _uniforms]); + } + + private void BindLocal(LocalStmt local) + { + if (local.Values.Count == 1 && IsGetPixel(local.Values[0])) + throw new KernelUnsupportedException("Unexpected pixel sample."); + if (local.Names.Count != local.Values.Count) + throw new KernelUnsupportedException("Multiple-value assignment is not supported."); + + var lowered = new KExpr[local.Values.Count]; + for (int i = 0; i < local.Values.Count; i++) + lowered[i] = Lower(local.Values[i]); + for (int i = 0; i < local.Names.Count; i++) + { + EnsureNotCoordinateName(local.Names[i]); + _scope[local.Names[i]] = AddBinding(lowered[i]); + } + } + + private void BindAssign(AssignStmt assign) + { + if (assign.Targets.Count != assign.Values.Count) + throw new KernelUnsupportedException("Unbalanced assignment is not supported."); + + foreach (var target in assign.Targets) + { + if (target is not NameExpr name || !_scope.ContainsKey(name.Name)) + throw new KernelUnsupportedException("Assignment target must be a local variable."); + } + + var lowered = new KExpr[assign.Values.Count]; + for (int i = 0; i < assign.Values.Count; i++) + lowered[i] = Lower(assign.Values[i]); + for (int i = 0; i < assign.Targets.Count; i++) + _scope[((NameExpr)assign.Targets[i]).Name] = AddBinding(lowered[i]); + } + + private void EnsureNotCoordinateName(string name) + { + if (string.Equals(name, _widthVariable, StringComparison.Ordinal) || + string.Equals(name, _heightVariable, StringComparison.Ordinal)) + throw new KernelUnsupportedException("Local variable shadows a loop coordinate."); + } + + private int AddBinding(KExpr expression) + { + _bindings.Add(expression); + return _bindings.Count - 1; + } + + private KExpr Lower(LuaExpr expression) + { + switch (expression) + { + case NumberExpr number: + return new KConst(number.Value); + case NameExpr name: + return LowerName(name.Name); + case MemberExpr member: + return LowerMember(member); + case CallExpr call: + return LowerCall(call); + case UnaryExpr { Operator: "-" } unary: + return new KNegate(Lower(unary.Operand)); + case BinaryExpr binary: + return LowerBinary(binary); + } + throw new KernelUnsupportedException("Unsupported expression in pixel kernel."); + } + + private KExpr LowerName(string name) + { + if (_scope.TryGetValue(name, out int slot)) + return new KLocalRef(slot); + if (_coordsEnabled && string.Equals(name, _widthVariable, StringComparison.Ordinal)) + return new KCoord(KAxis.X); + if (_coordsEnabled && string.Equals(name, _heightVariable, StringComparison.Ordinal)) + return new KCoord(KAxis.Y); + if (KernelUniforms.TryResolveGlobal(name, out var uniform)) + return UseUniform(uniform); + throw new KernelUnsupportedException($"Unknown identifier '{name}'."); + } + + private KExpr LowerMember(MemberExpr member) + { + if (member.Target is NameExpr { Name: "math" }) + { + return member.Name switch + { + "pi" => new KConst(Math.PI), + "huge" => new KConst(double.PositiveInfinity), + _ => throw new KernelUnsupportedException($"Unsupported math field '{member.Name}'."), + }; + } + + if (member.Target is NameExpr target && KernelUniforms.TryResolveMember(target.Name, member.Name, out var uniform)) + return UseUniform(uniform); + + throw new KernelUnsupportedException("Unsupported member access in pixel kernel."); + } + + private KExpr LowerCall(CallExpr call) + { + if (call.Target is not MemberExpr { Target: NameExpr { Name: "math" }, Name: var function } || + !MathFunctions.TryGetValue(function, out var spec)) + throw new KernelUnsupportedException("Unsupported function call in pixel kernel."); + + int count = call.Arguments.Count; + if (count < spec.MinArgs || count > spec.MaxArgs) + throw new KernelUnsupportedException($"Wrong argument count for 'math.{function}'."); + + var arguments = new KExpr[count]; + for (int i = 0; i < count; i++) + arguments[i] = Lower(call.Arguments[i]); + + if (spec.Func is KFunc.Min or KFunc.Max) + { + var folded = arguments[0]; + for (int i = 1; i < count; i++) + folded = new KCall(spec.Func, [folded, arguments[i]]); + return folded; + } + + return new KCall(spec.Func, arguments); + } + + private KExpr LowerBinary(BinaryExpr binary) + { + switch (binary.Operator) + { + case "+": return new KArith(KArithOp.Add, Lower(binary.Left), Lower(binary.Right)); + case "-": return new KArith(KArithOp.Subtract, Lower(binary.Left), Lower(binary.Right)); + case "*": return new KArith(KArithOp.Multiply, Lower(binary.Left), Lower(binary.Right)); + case "/": return new KArith(KArithOp.Divide, Lower(binary.Left), Lower(binary.Right)); + case "%": return new KArith(KArithOp.Modulo, Lower(binary.Left), Lower(binary.Right)); + case "^": return new KArith(KArithOp.Power, Lower(binary.Left), Lower(binary.Right)); + case "or" when binary.Left is BinaryExpr { Operator: "and" } conditional: + return new KSelect(LowerBool(conditional.Left), Lower(conditional.Right), Lower(binary.Right)); + } + throw new KernelUnsupportedException($"Unsupported operator '{binary.Operator}' in value position."); + } + + private KBool LowerBool(LuaExpr expression) + { + switch (expression) + { + case BoolExpr boolean: + return new KBoolConst(boolean.Value); + case UnaryExpr { Operator: "not" } unary: + return new KNot(LowerBool(unary.Operand)); + case BinaryExpr { Operator: "and" } conjunction: + return new KLogical(true, LowerBool(conjunction.Left), LowerBool(conjunction.Right)); + case BinaryExpr { Operator: "or" } disjunction: + return new KLogical(false, LowerBool(disjunction.Left), LowerBool(disjunction.Right)); + case BinaryExpr binary when TryCompareOp(binary.Operator, out var op): + return new KCompare(op, Lower(binary.Left), Lower(binary.Right)); + case NameExpr name when IsCheck(LowerName(name.Name)): + return new KCompare(KCompareOp.NotEqual, LowerName(name.Name), new KConst(0d)); + case MemberExpr member when IsCheck(LowerMember(member)): + return new KCompare(KCompareOp.NotEqual, LowerMember(member), new KConst(0d)); + } + throw new KernelUnsupportedException("Unsupported condition in pixel kernel."); + } + + private static bool IsCheck(KExpr expression) => + expression is KUniformRef { Uniform: KernelUniform.Check0 or KernelUniform.Check1 or KernelUniform.Check2 or KernelUniform.Check3 }; + + private static bool TryCompareOp(string symbol, out KCompareOp op) + { + switch (symbol) + { + case "<": op = KCompareOp.Less; return true; + case ">": op = KCompareOp.Greater; return true; + case "<=": op = KCompareOp.LessEqual; return true; + case ">=": op = KCompareOp.GreaterEqual; return true; + case "==": op = KCompareOp.Equal; return true; + case "~=": op = KCompareOp.NotEqual; return true; + default: op = default; return false; + } + } + + private KExpr UseUniform(KernelUniform uniform) + { + _uniforms.Add(uniform); + return new KUniformRef(uniform); + } + + private bool TryAxis(NumericForStmt loop, out string variable, out KAxis axis) + { + variable = loop.Variable; + axis = default; + + if (loop.Start is not NumberExpr { Value: 0d }) + return false; + if (loop.Step is not null && loop.Step is not NumberExpr { Value: 1d }) + return false; + if (loop.Stop is not BinaryExpr { Operator: "-", Right: NumberExpr { Value: 1d } } bound) + return false; + if (bound.Left is not MemberExpr { Target: NameExpr { Name: "obj" }, Name: var field }) + return false; + if (!KernelUniforms.TryResolveMember("obj", field, out var uniform)) + return false; + + if (uniform == KernelUniform.Width) + { + axis = KAxis.X; + return true; + } + if (uniform == KernelUniform.Height) + { + axis = KAxis.Y; + return true; + } + return false; + } + + private bool IsGetPixel(LuaExpr expression) => + expression is CallExpr call && IsObjectMethod(call, "getpixel") && + call.Arguments.Count == 2 && + IsCoordinate(call.Arguments[0], KAxis.X) && IsCoordinate(call.Arguments[1], KAxis.Y); + + private bool IsCoordinate(LuaExpr expression, KAxis axis) => + expression is NameExpr name && + string.Equals(name.Name, axis == KAxis.X ? _widthVariable : _heightVariable, StringComparison.Ordinal); + + private static bool IsObjectMethod(CallExpr call, string method) => + call.Target is MemberExpr { Target: NameExpr { Name: "obj" }, Name: var name } && + string.Equals(name, method, StringComparison.Ordinal); + } +} diff --git a/LuaScript/Engine/Kernel/KernelModel.cs b/LuaScript/Engine/Kernel/KernelModel.cs new file mode 100644 index 0000000..6c690c9 --- /dev/null +++ b/LuaScript/Engine/Kernel/KernelModel.cs @@ -0,0 +1,97 @@ +using System.Collections.Generic; + +namespace LuaScript.Engine.Kernel +{ + internal enum KChannel + { + R, + G, + B, + A, + } + + internal enum KAxis + { + X, + Y, + } + + internal enum KArithOp + { + Add, + Subtract, + Multiply, + Divide, + Modulo, + Power, + } + + internal enum KCompareOp + { + Less, + Greater, + LessEqual, + GreaterEqual, + Equal, + NotEqual, + } + + internal enum KFunc + { + Abs, + Floor, + Ceil, + Sqrt, + Sin, + Cos, + Tan, + Asin, + Acos, + Atan, + Atan2, + Exp, + Log, + Pow, + Min, + Max, + Fmod, + } + + internal abstract record KExpr; + + internal sealed record KConst(double Value) : KExpr; + + internal sealed record KInput(KChannel Channel) : KExpr; + + internal sealed record KCoord(KAxis Axis) : KExpr; + + internal sealed record KUniformRef(KernelUniform Uniform) : KExpr; + + internal sealed record KLocalRef(int Slot) : KExpr; + + internal sealed record KArith(KArithOp Op, KExpr Left, KExpr Right) : KExpr; + + internal sealed record KNegate(KExpr Operand) : KExpr; + + internal sealed record KCall(KFunc Func, IReadOnlyList Arguments) : KExpr; + + internal sealed record KSelect(KBool Condition, KExpr WhenTrue, KExpr WhenFalse) : KExpr; + + internal abstract record KBool; + + internal sealed record KCompare(KCompareOp Op, KExpr Left, KExpr Right) : KBool; + + internal sealed record KLogical(bool IsAnd, KBool Left, KBool Right) : KBool; + + internal sealed record KNot(KBool Operand) : KBool; + + internal sealed record KBoolConst(bool Value) : KBool; + + internal sealed record KernelProgram( + IReadOnlyList Bindings, + KExpr OutputR, + KExpr OutputG, + KExpr OutputB, + KExpr OutputA, + IReadOnlyList Uniforms); +} diff --git a/LuaScript/Engine/Kernel/KernelUniform.cs b/LuaScript/Engine/Kernel/KernelUniform.cs new file mode 100644 index 0000000..e0dac8c --- /dev/null +++ b/LuaScript/Engine/Kernel/KernelUniform.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; + +namespace LuaScript.Engine.Kernel +{ + internal enum KernelUniform + { + Width, + Height, + HalfWidth, + HalfHeight, + CenterX, + CenterY, + CenterZ, + Diagonal, + X, + Y, + Z, + Ox, + Oy, + Oz, + Sx, + Sy, + Sz, + Zoom, + Aspect, + Alpha, + Rx, + Ry, + Rz, + Rxr, + Ryr, + Rzr, + Track0, + Track1, + Track2, + Track3, + Check0, + Check1, + Check2, + Check3, + Color, + Time, + Frame, + TotalFrame, + TotalTime, + T, + Framerate, + Layer, + Index, + Num, + SceneWidth, + SceneHeight, + SceneCenterX, + SceneCenterY, + TimelineFrame, + TimelineTime, + } + + internal static class KernelUniforms + { + public static int Count { get; } = Enum.GetValues().Length; + + private static readonly Dictionary Globals = new(StringComparer.Ordinal) + { + ["time"] = KernelUniform.Time, + ["frame"] = KernelUniform.Frame, + ["totalframe"] = KernelUniform.TotalFrame, + ["framerate"] = KernelUniform.Framerate, + ["timelineframe"] = KernelUniform.TimelineFrame, + ["timelinetime"] = KernelUniform.TimelineTime, + ["layer"] = KernelUniform.Layer, + ["color"] = KernelUniform.Color, + }; + + private static readonly Dictionary ObjectFields = new(StringComparer.Ordinal) + { + ["w"] = KernelUniform.Width, + ["h"] = KernelUniform.Height, + ["hw"] = KernelUniform.HalfWidth, + ["hh"] = KernelUniform.HalfHeight, + ["cx"] = KernelUniform.CenterX, + ["cy"] = KernelUniform.CenterY, + ["cz"] = KernelUniform.CenterZ, + ["diagonal"] = KernelUniform.Diagonal, + ["x"] = KernelUniform.X, + ["y"] = KernelUniform.Y, + ["z"] = KernelUniform.Z, + ["ox"] = KernelUniform.Ox, + ["oy"] = KernelUniform.Oy, + ["oz"] = KernelUniform.Oz, + ["sx"] = KernelUniform.Sx, + ["sy"] = KernelUniform.Sy, + ["sz"] = KernelUniform.Sz, + ["zoom"] = KernelUniform.Zoom, + ["aspect"] = KernelUniform.Aspect, + ["alpha"] = KernelUniform.Alpha, + ["rx"] = KernelUniform.Rx, + ["ry"] = KernelUniform.Ry, + ["rz"] = KernelUniform.Rz, + ["rxr"] = KernelUniform.Rxr, + ["ryr"] = KernelUniform.Ryr, + ["rzr"] = KernelUniform.Rzr, + ["track0"] = KernelUniform.Track0, + ["track1"] = KernelUniform.Track1, + ["track2"] = KernelUniform.Track2, + ["track3"] = KernelUniform.Track3, + ["check0"] = KernelUniform.Check0, + ["check1"] = KernelUniform.Check1, + ["check2"] = KernelUniform.Check2, + ["check3"] = KernelUniform.Check3, + ["time"] = KernelUniform.Time, + ["frame"] = KernelUniform.Frame, + ["totalframe"] = KernelUniform.TotalFrame, + ["totaltime"] = KernelUniform.TotalTime, + ["t"] = KernelUniform.T, + ["framerate"] = KernelUniform.Framerate, + ["layer"] = KernelUniform.Layer, + ["index"] = KernelUniform.Index, + ["num"] = KernelUniform.Num, + }; + + private static readonly Dictionary SceneFields = new(StringComparer.Ordinal) + { + ["width"] = KernelUniform.SceneWidth, + ["height"] = KernelUniform.SceneHeight, + ["cx"] = KernelUniform.SceneCenterX, + ["cy"] = KernelUniform.SceneCenterY, + }; + + public static bool TryResolveGlobal(string name, out KernelUniform uniform) => + Globals.TryGetValue(name, out uniform); + + public static bool TryResolveMember(string target, string field, out KernelUniform uniform) + { + uniform = default; + return target switch + { + "obj" => ObjectFields.TryGetValue(field, out uniform), + "scene" => SceneFields.TryGetValue(field, out uniform), + _ => false, + }; + } + + public static string Field(KernelUniform uniform) => "u_" + uniform; + } +} diff --git a/LuaScript/Engine/Kernel/KernelUniformBinding.cs b/LuaScript/Engine/Kernel/KernelUniformBinding.cs new file mode 100644 index 0000000..55a9591 --- /dev/null +++ b/LuaScript/Engine/Kernel/KernelUniformBinding.cs @@ -0,0 +1,72 @@ +using System; + +namespace LuaScript.Engine.Kernel +{ + internal static class KernelUniformBinding + { + public static double[] Create() => new double[KernelUniforms.Count]; + + public static void Fill(AviUtlScriptContext ctx, double[] values) + { + values[(int)KernelUniform.Width] = ctx.ImageWidth; + values[(int)KernelUniform.Height] = ctx.ImageHeight; + values[(int)KernelUniform.HalfWidth] = ctx.ImageWidth / 2d; + values[(int)KernelUniform.HalfHeight] = ctx.ImageHeight / 2d; + values[(int)KernelUniform.CenterX] = ctx.ImageWidth / 2d; + values[(int)KernelUniform.CenterY] = ctx.ImageHeight / 2d; + values[(int)KernelUniform.CenterZ] = 0d; + values[(int)KernelUniform.Diagonal] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight); + values[(int)KernelUniform.X] = ctx.X; + values[(int)KernelUniform.Y] = ctx.Y; + values[(int)KernelUniform.Z] = ctx.Z; + values[(int)KernelUniform.Ox] = ctx.Ox; + values[(int)KernelUniform.Oy] = ctx.Oy; + values[(int)KernelUniform.Oz] = ctx.Oz; + values[(int)KernelUniform.Sx] = ctx.Sx; + values[(int)KernelUniform.Sy] = ctx.Sy; + values[(int)KernelUniform.Sz] = 1d; + values[(int)KernelUniform.Zoom] = ctx.Zoom; + values[(int)KernelUniform.Aspect] = ctx.Aspect; + values[(int)KernelUniform.Alpha] = ctx.Alpha; + values[(int)KernelUniform.Rx] = ctx.Rx; + values[(int)KernelUniform.Ry] = ctx.Ry; + values[(int)KernelUniform.Rz] = ctx.Rz; + values[(int)KernelUniform.Rxr] = ctx.RxRad; + values[(int)KernelUniform.Ryr] = ctx.RyRad; + values[(int)KernelUniform.Rzr] = ctx.RzRad; + values[(int)KernelUniform.Track0] = ctx.Track0; + values[(int)KernelUniform.Track1] = ctx.Track1; + values[(int)KernelUniform.Track2] = ctx.Track2; + values[(int)KernelUniform.Track3] = ctx.Track3; + values[(int)KernelUniform.Check0] = ctx.Check0 ? 1d : 0d; + values[(int)KernelUniform.Check1] = ctx.Check1 ? 1d : 0d; + values[(int)KernelUniform.Check2] = ctx.Check2 ? 1d : 0d; + values[(int)KernelUniform.Check3] = ctx.Check3 ? 1d : 0d; + values[(int)KernelUniform.Color] = ctx.HasColor ? ctx.ColorValue : -1d; + values[(int)KernelUniform.Time] = ctx.Time; + values[(int)KernelUniform.Frame] = ctx.Frame; + values[(int)KernelUniform.TotalFrame] = ctx.TotalFrame; + values[(int)KernelUniform.TotalTime] = ctx.TotalTime; + values[(int)KernelUniform.T] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d; + values[(int)KernelUniform.Framerate] = ctx.Framerate; + values[(int)KernelUniform.Layer] = ctx.Layer; + values[(int)KernelUniform.Index] = ctx.Index; + values[(int)KernelUniform.Num] = ctx.Num; + values[(int)KernelUniform.SceneWidth] = ctx.SceneWidth; + values[(int)KernelUniform.SceneHeight] = ctx.SceneHeight; + values[(int)KernelUniform.SceneCenterX] = ctx.SceneWidth / 2d; + values[(int)KernelUniform.SceneCenterY] = ctx.SceneHeight / 2d; + values[(int)KernelUniform.TimelineFrame] = ctx.TimelineFrame; + values[(int)KernelUniform.TimelineTime] = ctx.TimelineTime; + } + + public static void Pack(double[] values, float[] packed) + { + int count = Math.Min(values.Length, packed.Length); + for (int i = 0; i < count; i++) + packed[i] = (float)values[i]; + for (int i = count; i < packed.Length; i++) + packed[i] = 0f; + } + } +} diff --git a/LuaScript/Engine/Kernel/KernelUnsupportedException.cs b/LuaScript/Engine/Kernel/KernelUnsupportedException.cs new file mode 100644 index 0000000..b1cc84c --- /dev/null +++ b/LuaScript/Engine/Kernel/KernelUnsupportedException.cs @@ -0,0 +1,4 @@ +namespace LuaScript.Engine.Kernel +{ + internal sealed class KernelUnsupportedException(string reason) : Exception(reason); +} diff --git a/LuaScript/Engine/Kernel/LuaAst.cs b/LuaScript/Engine/Kernel/LuaAst.cs new file mode 100644 index 0000000..f425bb8 --- /dev/null +++ b/LuaScript/Engine/Kernel/LuaAst.cs @@ -0,0 +1,45 @@ +using System.Collections.Generic; + +namespace LuaScript.Engine.Kernel +{ + internal abstract record LuaExpr; + + internal sealed record NumberExpr(double Value) : LuaExpr; + + internal sealed record BoolExpr(bool Value) : LuaExpr; + + internal sealed record NilExpr : LuaExpr; + + internal sealed record StringExpr(string Value) : LuaExpr; + + internal sealed record NameExpr(string Name) : LuaExpr; + + internal sealed record MemberExpr(LuaExpr Target, string Name) : LuaExpr; + + internal sealed record IndexExpr(LuaExpr Target, LuaExpr Key) : LuaExpr; + + internal sealed record CallExpr(LuaExpr Target, IReadOnlyList Arguments) : LuaExpr; + + internal sealed record UnaryExpr(string Operator, LuaExpr Operand) : LuaExpr; + + internal sealed record BinaryExpr(string Operator, LuaExpr Left, LuaExpr Right) : LuaExpr; + + internal abstract record LuaStmt; + + internal sealed record LocalStmt(IReadOnlyList Names, IReadOnlyList Values) : LuaStmt; + + internal sealed record AssignStmt(IReadOnlyList Targets, IReadOnlyList Values) : LuaStmt; + + internal sealed record CallStmt(CallExpr Call) : LuaStmt; + + internal sealed record IfClause(LuaExpr Condition, IReadOnlyList Body); + + internal sealed record IfStmt(IReadOnlyList Clauses, IReadOnlyList? ElseBody) : LuaStmt; + + internal sealed record NumericForStmt( + string Variable, + LuaExpr Start, + LuaExpr Stop, + LuaExpr? Step, + IReadOnlyList Body) : LuaStmt; +} diff --git a/LuaScript/Engine/Kernel/LuaLexer.cs b/LuaScript/Engine/Kernel/LuaLexer.cs new file mode 100644 index 0000000..4672f9e --- /dev/null +++ b/LuaScript/Engine/Kernel/LuaLexer.cs @@ -0,0 +1,310 @@ +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace LuaScript.Engine.Kernel +{ + internal static class LuaLexer + { + private static readonly HashSet Keywords = new(StringComparer.Ordinal) + { + "and", "break", "do", "else", "elseif", "end", "false", "for", "function", + "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", + "true", "until", "while", + }; + + public static List Tokenize(string source) + { + var tokens = new List(); + int i = 0; + int length = source.Length; + + while (i < length) + { + char c = source[i]; + + if (c is ' ' or '\t' or '\r' or '\n' or '\f' or '\v') + { + i++; + continue; + } + + if (c == '-' && i + 1 < length && source[i + 1] == '-') + { + i = SkipComment(source, i + 2); + continue; + } + + if (c == '"' || c == '\'') + { + i = ReadShortString(source, i, tokens); + continue; + } + + if (c == '[' && i + 1 < length && (source[i + 1] == '[' || source[i + 1] == '=')) + { + int level = LongBracketLevel(source, i); + if (level >= 0) + { + i = ReadLongString(source, i, level, tokens); + continue; + } + } + + if (char.IsDigit(c) || (c == '.' && i + 1 < length && char.IsDigit(source[i + 1]))) + { + i = ReadNumber(source, i, tokens); + continue; + } + + if (IsNameStart(c)) + { + i = ReadName(source, i, tokens); + continue; + } + + i = ReadSymbol(source, i, tokens); + } + + tokens.Add(new LuaToken(LuaTokenKind.Eof, string.Empty, 0d)); + return tokens; + } + + private static int SkipComment(string source, int i) + { + int level = LongBracketLevel(source, i); + if (level >= 0) + return SkipLongBracket(source, i, level); + + int length = source.Length; + while (i < length && source[i] != '\n') + i++; + return i; + } + + private static int LongBracketLevel(string source, int i) + { + if (i >= source.Length || source[i] != '[') + return -1; + int j = i + 1; + int level = 0; + while (j < source.Length && source[j] == '=') + { + level++; + j++; + } + return j < source.Length && source[j] == '[' ? level : -1; + } + + private static int SkipLongBracket(string source, int i, int level) + { + int length = source.Length; + i += level + 2; + while (i < length) + { + if (source[i] == ']') + { + int j = i + 1; + int count = 0; + while (j < length && source[j] == '=') + { + count++; + j++; + } + if (count == level && j < length && source[j] == ']') + return j + 1; + } + i++; + } + throw new KernelUnsupportedException("Unterminated long bracket."); + } + + private static int ReadLongString(string source, int start, int level, List tokens) + { + int end = SkipLongBracket(source, start, level); + int contentStart = start + level + 2; + int contentEnd = end - level - 2; + string text = source.Substring(contentStart, Math.Max(0, contentEnd - contentStart)); + tokens.Add(new LuaToken(LuaTokenKind.String, text, 0d)); + return end; + } + + private static int ReadShortString(string source, int start, List tokens) + { + char quote = source[start]; + int i = start + 1; + int length = source.Length; + var value = new System.Text.StringBuilder(); + + while (i < length) + { + char c = source[i]; + if (c == quote) + { + tokens.Add(new LuaToken(LuaTokenKind.String, value.ToString(), 0d)); + return i + 1; + } + if (c == '\n') + throw new KernelUnsupportedException("Unterminated string."); + if (c == '\\') + { + i = ReadEscape(source, i + 1, value); + continue; + } + value.Append(c); + i++; + } + throw new KernelUnsupportedException("Unterminated string."); + } + + private static int ReadEscape(string source, int i, System.Text.StringBuilder value) + { + if (i >= source.Length) + throw new KernelUnsupportedException("Unterminated string escape."); + + char c = source[i]; + switch (c) + { + case 'n': value.Append('\n'); return i + 1; + case 't': value.Append('\t'); return i + 1; + case 'r': value.Append('\r'); return i + 1; + case 'a': value.Append('\a'); return i + 1; + case 'b': value.Append('\b'); return i + 1; + case 'f': value.Append('\f'); return i + 1; + case 'v': value.Append('\v'); return i + 1; + case '\\': value.Append('\\'); return i + 1; + case '"': value.Append('"'); return i + 1; + case '\'': value.Append('\''); return i + 1; + case '\n': value.Append('\n'); return i + 1; + default: + if (char.IsDigit(c)) + { + int n = 0; + int count = 0; + while (i < source.Length && count < 3 && char.IsDigit(source[i])) + { + n = n * 10 + (source[i] - '0'); + i++; + count++; + } + value.Append((char)n); + return i; + } + value.Append(c); + return i + 1; + } + } + + private static int ReadNumber(string source, int start, List tokens) + { + int length = source.Length; + int i = start; + + if (source[i] == '0' && i + 1 < length && (source[i + 1] == 'x' || source[i + 1] == 'X')) + { + i += 2; + int digitsStart = i; + while (i < length && Uri.IsHexDigit(source[i])) + i++; + if (i == digitsStart) + throw new KernelUnsupportedException("Malformed hexadecimal literal."); + string hex = source.Substring(digitsStart, i - digitsStart); + double hexValue = (double)ulong.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture); + tokens.Add(new LuaToken(LuaTokenKind.Number, source.Substring(start, i - start), hexValue)); + return i; + } + + while (i < length && char.IsDigit(source[i])) + i++; + if (i < length && source[i] == '.') + { + i++; + while (i < length && char.IsDigit(source[i])) + i++; + } + if (i < length && (source[i] == 'e' || source[i] == 'E')) + { + i++; + if (i < length && (source[i] == '+' || source[i] == '-')) + i++; + while (i < length && char.IsDigit(source[i])) + i++; + } + + string text = source.Substring(start, i - start); + double value = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture); + tokens.Add(new LuaToken(LuaTokenKind.Number, text, value)); + return i; + } + + private static int ReadName(string source, int start, List tokens) + { + int i = start; + int length = source.Length; + while (i < length && IsNamePart(source[i])) + i++; + string text = source.Substring(start, i - start); + tokens.Add(new LuaToken(Keywords.Contains(text) ? LuaTokenKind.Keyword : LuaTokenKind.Name, text, 0d)); + return i; + } + + private static int ReadSymbol(string source, int start, List tokens) + { + int length = source.Length; + char c = source[start]; + + if (c == '.' && start + 2 < length && source[start + 1] == '.' && source[start + 2] == '.') + { + tokens.Add(new LuaToken(LuaTokenKind.Symbol, "...", 0d)); + return start + 3; + } + + if (start + 1 < length) + { + string two = source.Substring(start, 2); + switch (two) + { + case "==": + case "~=": + case "<=": + case ">=": + case "..": + tokens.Add(new LuaToken(LuaTokenKind.Symbol, two, 0d)); + return start + 2; + } + } + + switch (c) + { + case '+': + case '-': + case '*': + case '/': + case '%': + case '^': + case '#': + case '<': + case '>': + case '=': + case '(': + case ')': + case '{': + case '}': + case '[': + case ']': + case ';': + case ':': + case ',': + case '.': + tokens.Add(new LuaToken(LuaTokenKind.Symbol, c.ToString(), 0d)); + return start + 1; + default: + throw new KernelUnsupportedException($"Unexpected character '{c}'."); + } + } + + private static bool IsNameStart(char c) => c == '_' || char.IsLetter(c); + + private static bool IsNamePart(char c) => c == '_' || char.IsLetterOrDigit(c); + } +} diff --git a/LuaScript/Engine/Kernel/LuaParser.cs b/LuaScript/Engine/Kernel/LuaParser.cs new file mode 100644 index 0000000..e0e21c8 --- /dev/null +++ b/LuaScript/Engine/Kernel/LuaParser.cs @@ -0,0 +1,349 @@ +using System.Collections.Generic; + +namespace LuaScript.Engine.Kernel +{ + internal sealed class LuaParser + { + private readonly List _tokens; + private int _pos; + + private LuaParser(List tokens) => _tokens = tokens; + + public static IReadOnlyList Parse(string source) + { + var parser = new LuaParser(LuaLexer.Tokenize(source)); + var block = parser.ParseBlock(); + parser.Expect(LuaTokenKind.Eof); + return block; + } + + private LuaToken Current => _tokens[_pos]; + + private LuaToken Advance() => _tokens[_pos++]; + + private bool IsBlockEnd() + { + var t = Current; + return t.Kind == LuaTokenKind.Eof || + t.IsKeyword("end") || t.IsKeyword("else") || t.IsKeyword("elseif") || t.IsKeyword("until"); + } + + private IReadOnlyList ParseBlock() + { + var statements = new List(); + while (!IsBlockEnd()) + { + if (Current.IsSymbol(";")) + { + Advance(); + continue; + } + statements.Add(ParseStatement()); + } + return statements; + } + + private LuaStmt ParseStatement() + { + var t = Current; + if (t.IsKeyword("local")) + return ParseLocal(); + if (t.IsKeyword("if")) + return ParseIf(); + if (t.IsKeyword("for")) + return ParseFor(); + if (t.Kind == LuaTokenKind.Keyword) + throw new KernelUnsupportedException($"Unsupported statement '{t.Text}'."); + return ParseExpressionStatement(); + } + + private LuaStmt ParseLocal() + { + Advance(); + if (Current.IsKeyword("function")) + throw new KernelUnsupportedException("Local functions are not supported."); + + var names = new List { ExpectName() }; + while (Current.IsSymbol(",")) + { + Advance(); + names.Add(ExpectName()); + } + + IReadOnlyList values = []; + if (Current.IsSymbol("=")) + { + Advance(); + values = ParseExpressionList(); + } + return new LocalStmt(names, values); + } + + private LuaStmt ParseIf() + { + Advance(); + var clauses = new List(); + + var condition = ParseExpression(); + ExpectKeyword("then"); + clauses.Add(new IfClause(condition, ParseBlock())); + + while (Current.IsKeyword("elseif")) + { + Advance(); + var elseifCondition = ParseExpression(); + ExpectKeyword("then"); + clauses.Add(new IfClause(elseifCondition, ParseBlock())); + } + + IReadOnlyList? elseBody = null; + if (Current.IsKeyword("else")) + { + Advance(); + elseBody = ParseBlock(); + } + + ExpectKeyword("end"); + return new IfStmt(clauses, elseBody); + } + + private LuaStmt ParseFor() + { + Advance(); + string variable = ExpectName(); + if (!Current.IsSymbol("=")) + throw new KernelUnsupportedException("Generic for loops are not supported."); + + Advance(); + var start = ParseExpression(); + ExpectSymbol(","); + var stop = ParseExpression(); + + LuaExpr? step = null; + if (Current.IsSymbol(",")) + { + Advance(); + step = ParseExpression(); + } + + ExpectKeyword("do"); + var body = ParseBlock(); + ExpectKeyword("end"); + return new NumericForStmt(variable, start, stop, step, body); + } + + private LuaStmt ParseExpressionStatement() + { + var first = ParseSuffixedExpression(); + + if (Current.IsSymbol("=") || Current.IsSymbol(",")) + { + var targets = new List { first }; + while (Current.IsSymbol(",")) + { + Advance(); + targets.Add(ParseSuffixedExpression()); + } + ExpectSymbol("="); + var values = ParseExpressionList(); + return new AssignStmt(targets, values); + } + + if (first is CallExpr call) + return new CallStmt(call); + + throw new KernelUnsupportedException("Expression is not a valid statement."); + } + + private List ParseExpressionList() + { + var values = new List { ParseExpression() }; + while (Current.IsSymbol(",")) + { + Advance(); + values.Add(ParseExpression()); + } + return values; + } + + private LuaExpr ParseExpression(int minPrecedence = 0) + { + var left = ParseUnary(); + while (true) + { + var (op, precedence, rightAssociative) = PeekBinaryOperator(); + if (op is null || precedence < minPrecedence) + break; + Advance(); + int nextMinimum = rightAssociative ? precedence : precedence + 1; + var right = ParseExpression(nextMinimum); + left = new BinaryExpr(op, left, right); + } + return left; + } + + private LuaExpr ParseUnary() + { + var t = Current; + if (t.IsKeyword("not") || t.IsSymbol("-") || t.IsSymbol("#")) + { + Advance(); + return new UnaryExpr(t.Text, ParseExpression(7)); + } + return ParseValue(); + } + + private (string? Operator, int Precedence, bool RightAssociative) PeekBinaryOperator() + { + var t = Current; + if (t.IsKeyword("or")) return ("or", 1, false); + if (t.IsKeyword("and")) return ("and", 2, false); + if (t.Kind == LuaTokenKind.Symbol) + { + switch (t.Text) + { + case "<": + case ">": + case "<=": + case ">=": + case "~=": + case "==": + return (t.Text, 3, false); + case "..": + return ("..", 4, true); + case "+": + case "-": + return (t.Text, 5, false); + case "*": + case "/": + case "%": + return (t.Text, 6, false); + case "^": + return ("^", 8, true); + } + } + return (null, 0, false); + } + + private LuaExpr ParseValue() + { + var t = Current; + switch (t.Kind) + { + case LuaTokenKind.Number: + Advance(); + return new NumberExpr(t.Number); + case LuaTokenKind.String: + Advance(); + return new StringExpr(t.Text); + case LuaTokenKind.Keyword when t.Text == "true": + Advance(); + return new BoolExpr(true); + case LuaTokenKind.Keyword when t.Text == "false": + Advance(); + return new BoolExpr(false); + case LuaTokenKind.Keyword when t.Text == "nil": + Advance(); + return new NilExpr(); + } + + if (t.IsKeyword("function") || t.IsSymbol("{") || t.IsSymbol("...")) + throw new KernelUnsupportedException($"Unsupported expression near '{t.Text}'."); + + return ParseSuffixedExpression(); + } + + private LuaExpr ParseSuffixedExpression() + { + var expression = ParsePrimaryExpression(); + while (true) + { + var t = Current; + if (t.IsSymbol(".")) + { + Advance(); + expression = new MemberExpr(expression, ExpectName()); + } + else if (t.IsSymbol("[")) + { + Advance(); + var key = ParseExpression(); + ExpectSymbol("]"); + expression = new IndexExpr(expression, key); + } + else if (t.IsSymbol("(")) + { + expression = new CallExpr(expression, ParseArguments()); + } + else + { + break; + } + } + return expression; + } + + private LuaExpr ParsePrimaryExpression() + { + var t = Current; + if (t.IsSymbol("(")) + { + Advance(); + var inner = ParseExpression(); + ExpectSymbol(")"); + return inner; + } + if (t.Kind == LuaTokenKind.Name) + { + Advance(); + return new NameExpr(t.Text); + } + throw new KernelUnsupportedException($"Unexpected token '{t.Text}'."); + } + + private List ParseArguments() + { + ExpectSymbol("("); + var arguments = new List(); + if (!Current.IsSymbol(")")) + { + arguments.Add(ParseExpression()); + while (Current.IsSymbol(",")) + { + Advance(); + arguments.Add(ParseExpression()); + } + } + ExpectSymbol(")"); + return arguments; + } + + private string ExpectName() + { + if (Current.Kind != LuaTokenKind.Name) + throw new KernelUnsupportedException($"Expected a name but found '{Current.Text}'."); + return Advance().Text; + } + + private void Expect(LuaTokenKind kind) + { + if (Current.Kind != kind) + throw new KernelUnsupportedException($"Expected {kind} but found '{Current.Text}'."); + Advance(); + } + + private void ExpectSymbol(string symbol) + { + if (!Current.IsSymbol(symbol)) + throw new KernelUnsupportedException($"Expected '{symbol}' but found '{Current.Text}'."); + Advance(); + } + + private void ExpectKeyword(string keyword) + { + if (!Current.IsKeyword(keyword)) + throw new KernelUnsupportedException($"Expected '{keyword}' but found '{Current.Text}'."); + Advance(); + } + } +} diff --git a/LuaScript/Engine/Kernel/LuaToken.cs b/LuaScript/Engine/Kernel/LuaToken.cs new file mode 100644 index 0000000..375bc86 --- /dev/null +++ b/LuaScript/Engine/Kernel/LuaToken.cs @@ -0,0 +1,28 @@ +using System; + +namespace LuaScript.Engine.Kernel +{ + internal enum LuaTokenKind + { + Name, + Number, + String, + Keyword, + Symbol, + Eof, + } + + internal readonly struct LuaToken(LuaTokenKind kind, string text, double number) + { + public LuaTokenKind Kind { get; } = kind; + public string Text { get; } = text; + public double Number { get; } = number; + + public bool Is(LuaTokenKind kind, string text) => + Kind == kind && string.Equals(Text, text, StringComparison.Ordinal); + + public bool IsSymbol(string text) => Is(LuaTokenKind.Symbol, text); + + public bool IsKeyword(string text) => Is(LuaTokenKind.Keyword, text); + } +} diff --git a/LuaScript/Engine/ScriptDirective.cs b/LuaScript/Engine/ScriptDirective.cs index 3e9fc84..4f56651 100644 --- a/LuaScript/Engine/ScriptDirective.cs +++ b/LuaScript/Engine/ScriptDirective.cs @@ -16,6 +16,9 @@ namespace LuaScript.Engine return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp; } + public static bool TryResolveExplicit(string? script, out ScriptEngineKind kind) => + TryGetDirective(script, out kind); + public static bool UsesPixelApi(string? script) => script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal)); diff --git a/LuaScript/LuaScriptEffectProcessor.cs b/LuaScript/LuaScriptEffectProcessor.cs index e7cfb31..de3187f 100644 --- a/LuaScript/LuaScriptEffectProcessor.cs +++ b/LuaScript/LuaScriptEffectProcessor.cs @@ -3,6 +3,7 @@ using System.Numerics; using System.Runtime.InteropServices; using LuaScript.Compat; using LuaScript.Engine; +using LuaScript.Engine.Kernel; using Vortice; using Vortice.DCommon; using Vortice.Direct2D1; @@ -64,6 +65,15 @@ namespace LuaScript private double[]? _nativeFields; private bool _nativeWarned; private bool _effectChainWarned; + private bool _gpuWarned; + + private string _kernelSource = string.Empty; + private bool _kernelResolved; + private KernelProgram? _kernelProgram; + private CpuKernel? _cpuKernel; + private GpuKernel? _gpuKernel; + private bool _gpuKernelChecked; + private double[]? _kernelUniforms; private EffectDescription? _frameDesc; private SceneObjectResolver? _frameResolver; @@ -207,59 +217,68 @@ namespace LuaScript try { string runnable = GetRunnableScript(script); - bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native; - bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory); - if (wantNative && !nativeReady) - WarnNativeUnavailableOnce(); + EnsureKernel(runnable); - if (nativeReady) + if (ExecuteKernelLane(runnable, ctx, bounds, imgW, imgH)) { - ExecuteNative(runnable, ctx, bounds, imgW, imgH); + outDesc = inDesc; } else { - _engine.Execute(runnable, ctx); + bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native; + bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory); + if (wantNative && !nativeReady) + WarnNativeUnavailableOnce(); - if (ctx.IsPixelsDirty) + if (nativeReady) { - int bufW = ctx.ImageWidth; - int bufH = ctx.ImageHeight; - _pixelManager!.WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW, bufH); - if (ctx.BufferReplaced) - effectOutput = _pixelManager.GetTransformOutput(-bufW / 2f, -bufH / 2f); - else - effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top); + ExecuteNative(runnable, ctx, bounds, imgW, imgH); } else { - effectOutput = null; - } - } + _engine.Execute(runnable, ctx); - if (ctx.DrawCommands.Count > 0) - { - ctx.EnsurePixelBuffer(); - var drawBuffer = ctx.GetPixelBuffer(); - if (drawBuffer is not null) - { - _drawCompositor ??= new DrawCompositor(_ownCtx); - effectOutput = _drawCompositor.Compose(drawBuffer, ctx.ImageWidth, ctx.ImageHeight, ctx.DrawCommands); + if (ctx.IsPixelsDirty) + { + int bufW = ctx.ImageWidth; + int bufH = ctx.ImageHeight; + _pixelManager!.WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW, bufH); + if (ctx.BufferReplaced) + effectOutput = _pixelManager.GetTransformOutput(-bufW / 2f, -bufH / 2f); + else + effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top); + } + else + { + effectOutput = null; + } } - } - outDesc = BuildOutputDesc(inDesc, ctx); - - if (ctx.EffectRequests.Count > 0) - { - var source = effectOutput ?? input; - try + if (ctx.DrawCommands.Count > 0) { - effectOutput = ApplyEffectChain(source, ctx.EffectRequests, desc, ref outDesc); + ctx.EnsurePixelBuffer(); + var drawBuffer = ctx.GetPixelBuffer(); + if (drawBuffer is not null) + { + _drawCompositor ??= new DrawCompositor(_ownCtx); + effectOutput = _drawCompositor.Compose(drawBuffer, ctx.ImageWidth, ctx.ImageHeight, ctx.DrawCommands); + } } - catch (Exception ex) + + outDesc = BuildOutputDesc(inDesc, ctx); + + if (ctx.EffectRequests.Count > 0) { - effectOutput = source; - WarnEffectChainFailureOnce(ex); + var source = effectOutput ?? input; + try + { + effectOutput = ApplyEffectChain(source, ctx.EffectRequests, desc, ref outDesc); + } + catch (Exception ex) + { + effectOutput = source; + WarnEffectChainFailureOnce(ex); + } } } } @@ -423,6 +442,81 @@ namespace LuaScript }; } + private void EnsureKernel(string runnable) + { + if (_kernelResolved && string.Equals(runnable, _kernelSource, StringComparison.Ordinal)) + return; + + _kernelSource = runnable; + _kernelResolved = true; + _kernelProgram = KernelExtractor.TryExtract(runnable); + _cpuKernel = _kernelProgram is null ? null : CpuKernelCompiler.Compile(_kernelProgram); + _gpuKernel?.Dispose(); + _gpuKernel = null; + _gpuKernelChecked = false; + } + + private bool ExecuteKernelLane(string runnable, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH) + { + if (_kernelProgram is null || _cpuKernel is null) + return false; + + bool explicitDirective = ScriptDirective.TryResolveExplicit(runnable, out var kind); + if (explicitDirective && kind is not (ScriptEngineKind.Gpu or ScriptEngineKind.Cpu)) + return false; + + _kernelUniforms ??= KernelUniformBinding.Create(); + KernelUniformBinding.Fill(ctx, _kernelUniforms); + + if (explicitDirective && kind == ScriptEngineKind.Gpu) + { + var gpu = GetGpuKernel(); + if (gpu is not null) + { + effectOutput = gpu.Apply(input!, _kernelUniforms); + return true; + } + WarnGpuUnavailableOnce(); + } + + byte[] buffer = LoadInputPixels(bounds, imgW, imgH); + _cpuKernel.Execute(buffer, imgW, imgH, _kernelUniforms); + _pixelManager!.WritePixelsToOutput(buffer, imgW, imgH); + effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top); + return true; + } + + private GpuKernel? GetGpuKernel() + { + if (_gpuKernelChecked) + return _gpuKernel; + + _gpuKernelChecked = true; + if (_kernelProgram is null) + return null; + + try + { + var kernel = new GpuKernel(_ownCtx!, _kernelProgram); + if (kernel.IsReady) + _gpuKernel = kernel; + else + kernel.Dispose(); + } + catch (Exception ex) + { + Log.Default.Write("LuaScript: GPU kernel initialization failed; falling back to CPU.", ex); + } + return _gpuKernel; + } + + private void WarnGpuUnavailableOnce() + { + if (_gpuWarned) return; + _gpuWarned = true; + Log.Default.Write("LuaScript: GPU kernel unavailable; using the CPU kernel lane instead."); + } + private void WarnNativeUnavailableOnce() { if (_nativeWarned) return; @@ -555,6 +649,7 @@ namespace LuaScript if (disposing) { _engine.Dispose(); + _gpuKernel?.Dispose(); _nativeWorker?.Dispose(); _effectChain?.Dispose(); _drawCompositor?.Dispose();