diff --git a/LuaScript.Tests/AviUtlScriptTests.cs b/LuaScript.Tests/AviUtlScriptTests.cs new file mode 100644 index 0000000..1e76a98 --- /dev/null +++ b/LuaScript.Tests/AviUtlScriptTests.cs @@ -0,0 +1,139 @@ +using LuaScript.Compat; +using MoonSharp.Interpreter; + +namespace LuaScript.Tests +{ + public class AviUtlScriptTests + { + private static Script NewScript() + { + var script = new Script( + CoreModules.Basic | + CoreModules.Math | + CoreModules.String | + CoreModules.Table | + CoreModules.Bit32 | + CoreModules.TableIterators | + CoreModules.Metatables | + CoreModules.ErrorHandling); + script.Globals["obj"] = new Table(script); + return script; + } + + private static double RunNumber(string transformed, string global = "result") + { + var script = NewScript(); + script.DoString(transformed); + return script.Globals.Get(global).Number; + } + + [Fact] + public void PlainScript_IsReturnedUnchanged() + { + const string source = "obj.x = 1\nobj.y = 2"; + Assert.Equal(source, AviUtlScript.Transform(source)); + } + + [Fact] + public void TrackOnlyHeader_IsReturnedUnchanged() + { + const string source = "--track0:Amp,0,100,10\nobj.ox = obj.track0"; + Assert.Equal(source, AviUtlScript.Transform(source)); + } + + [Fact] + public void DirectiveComment_IsNotConfusedWithDirective() + { + const string source = "-- color reference note\nobj.x = 1"; + Assert.Equal(source, AviUtlScript.Transform(source)); + } + + [Fact] + public void EngineDirective_IsPreserved() + { + const string source = "--!native\n--dialog:V,local v=3;\nresult = v"; + string transformed = AviUtlScript.Transform(source); + Assert.Contains("--!native", transformed); + Assert.Equal(3d, RunNumber(transformed)); + } + + [Fact] + public void Dialog_InjectsDefaultDeclarations() + { + const string source = "--dialog:Angle,local angle=45;Dist,local dist=100;\nresult = dist"; + double result = RunNumber(AviUtlScript.Transform(source)); + Assert.Equal(100d, result); + } + + [Fact] + public void Color_InjectsColorVariable() + { + const string source = "--color:0x010203\nresult = color"; + double result = RunNumber(AviUtlScript.Transform(source)); + Assert.Equal(0x010203, result); + } + + [Fact] + public void Check_InjectsObjectField() + { + const string source = "--check0:Enable,1\nresult = obj.check0"; + double result = RunNumber(AviUtlScript.Transform(source)); + Assert.Equal(1d, result); + } + + [Fact] + public void Param_InjectsRawLua() + { + const string source = "--param:result = 7\nlocal x = 1"; + double result = RunNumber(AviUtlScript.Transform(source)); + Assert.Equal(7d, result); + } + + [Fact] + public void Section_FirstSectionIsSelected() + { + const string source = "@First\n--dialog:A,local a=5;\nresult = a\n@Second\nresult = 999"; + double result = RunNumber(AviUtlScript.Transform(source)); + Assert.Equal(5d, result); + } + + [Fact] + public void Section_PreambleBeforeFirstHeaderIsDiscarded() + { + const string source = "result = 111\n@Only\nresult = 222"; + double result = RunNumber(AviUtlScript.Transform(source)); + Assert.Equal(222d, result); + } + + [Fact] + public void ClassicTransformScript_RunsAndMovesObject() + { + const string source = + "--track0:Range,0,2000,10\n" + + "--dialog:Seed,local seed=3;\n" + + "obj.ox = obj.ox + obj.track0 * obj.rand(-100,100,seed,obj.time) / 100"; + + var script = NewScript(); + var obj = script.Globals.Get("obj").Table; + obj["ox"] = 0d; + obj["track0"] = 500d; + obj["time"] = 2d; + obj["frame"] = 4d; + obj["rand"] = DynValue.NewCallback((_, args) => + { + double frameDefault = obj.Get("frame").CastToNumber() ?? 0d; + double a = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d; + double b = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d; + double seed = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d; + double frame = args.Count > 3 ? args[3].CastToNumber() ?? frameDefault : frameDefault; + return DynValue.NewNumber(AviUtlRandom.Next(a, b, seed, frame)); + }); + + script.DoString(AviUtlScript.Transform(source)); + double moved = obj.Get("ox").Number; + + double expectedRand = AviUtlRandom.Next(-100, 100, 3, 2); + Assert.Equal(500d * expectedRand / 100d, moved); + } + } +} diff --git a/LuaScript/Compat/AviUtlScript.cs b/LuaScript/Compat/AviUtlScript.cs new file mode 100644 index 0000000..dda26ae --- /dev/null +++ b/LuaScript/Compat/AviUtlScript.cs @@ -0,0 +1,219 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace LuaScript.Compat +{ + internal static class AviUtlScript + { + private enum DirectiveKind + { + None, + Dialog, + Color, + Check, + Param, + } + + public static string Transform(string source) + { + if (string.IsNullOrEmpty(source)) + return source; + + var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'); + + int sectionStart = 0; + int sectionEnd = lines.Length; + bool hasSection = false; + + for (int i = 0; i < lines.Length; i++) + { + if (!IsSectionHeader(lines[i])) + continue; + + hasSection = true; + sectionStart = i + 1; + sectionEnd = lines.Length; + for (int j = sectionStart; j < lines.Length; j++) + { + if (IsSectionHeader(lines[j])) + { + sectionEnd = j; + break; + } + } + break; + } + + var prelude = new List(); + for (int i = sectionStart; i < sectionEnd; i++) + AppendDeclarations(lines[i], prelude); + + if (!hasSection && prelude.Count == 0) + return source; + + var builder = new StringBuilder(source.Length + 64); + foreach (var declaration in prelude) + builder.Append(declaration).Append('\n'); + for (int i = sectionStart; i < sectionEnd; i++) + builder.Append(lines[i]).Append('\n'); + + return builder.ToString(); + } + + private static bool IsSectionHeader(string line) + { + int i = SkipSpaces(line, 0); + return i < line.Length && line[i] == '@'; + } + + private static void AppendDeclarations(string line, List prelude) + { + int i = SkipSpaces(line, 0); + if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-') + return; + i += 2; + if (i < line.Length && line[i] == '!') + return; + + int nameStart = i; + while (i < line.Length && IsNameChar(line[i])) + i++; + if (i >= line.Length || line[i] != ':') + return; + + string name = line.Substring(nameStart, i - nameStart); + string content = line.Substring(i + 1); + + switch (Classify(name)) + { + case DirectiveKind.Dialog: + AppendDialog(content, prelude); + break; + case DirectiveKind.Color: + AppendColor(content, prelude); + break; + case DirectiveKind.Check: + AppendCheck(name, content, prelude); + break; + case DirectiveKind.Param: + AppendParam(content, prelude); + break; + } + } + + private static DirectiveKind Classify(string name) + { + if (name.Equals("dialog", StringComparison.OrdinalIgnoreCase)) + return DirectiveKind.Dialog; + if (name.Equals("color", StringComparison.OrdinalIgnoreCase)) + return DirectiveKind.Color; + if (name.Equals("param", StringComparison.OrdinalIgnoreCase)) + return DirectiveKind.Param; + if (name.Length > 5 && name.StartsWith("check", StringComparison.OrdinalIgnoreCase) && AllDigits(name, 5)) + return DirectiveKind.Check; + return DirectiveKind.None; + } + + private static void AppendDialog(string content, List prelude) + { + foreach (var segment in content.Split(';')) + { + string trimmed = segment.Trim(); + if (trimmed.Length == 0) + continue; + int comma = trimmed.IndexOf(','); + if (comma < 0) + continue; + string declaration = trimmed.Substring(comma + 1).Trim(); + if (declaration.Length != 0) + prelude.Add(declaration); + } + } + + private static void AppendColor(string content, List prelude) + { + string token = FirstToken(content); + if (IsColorLiteral(token)) + prelude.Add("local color = " + token); + } + + private static void AppendCheck(string name, string content, List prelude) + { + string index = name.Substring(5); + var parts = content.Split(','); + string def = parts[parts.Length - 1].Trim(); + if (IsIntegerLiteral(def)) + prelude.Add("obj.check" + index + " = " + def); + } + + private static void AppendParam(string content, List prelude) + { + string trimmed = content.Trim(); + if (trimmed.Length != 0) + prelude.Add(trimmed); + } + + private static string FirstToken(string content) + { + int start = SkipSpaces(content, 0); + int i = start; + while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t') + i++; + return content.Substring(start, i - start); + } + + private static bool IsColorLiteral(string token) + { + if (token.Length == 0) + return false; + if (token.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + { + if (token.Length <= 2) + return false; + for (int k = 2; k < token.Length; k++) + if (!IsHexDigit(token[k])) + return false; + return true; + } + foreach (char c in token) + if (c < '0' || c > '9') + return false; + return true; + } + + private static bool IsIntegerLiteral(string token) + { + if (token.Length == 0) + return false; + int start = token[0] == '-' || token[0] == '+' ? 1 : 0; + if (start >= token.Length) + return false; + for (int i = start; i < token.Length; i++) + if (token[i] < '0' || token[i] > '9') + return false; + return true; + } + + private static bool AllDigits(string text, int start) + { + for (int i = start; i < text.Length; i++) + if (text[i] < '0' || text[i] > '9') + return false; + return true; + } + + private static int SkipSpaces(string text, int index) + { + while (index < text.Length && (text[index] == ' ' || text[index] == '\t')) + index++; + return index; + } + + private static bool IsNameChar(char c) => + (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); + + private static bool IsHexDigit(char c) => + (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + } +} diff --git a/LuaScript/LuaScriptEffectProcessor.cs b/LuaScript/LuaScriptEffectProcessor.cs index 9de507f..2032acf 100644 --- a/LuaScript/LuaScriptEffectProcessor.cs +++ b/LuaScript/LuaScriptEffectProcessor.cs @@ -1,6 +1,7 @@ using System.IO; using System.Numerics; using System.Runtime.InteropServices; +using LuaScript.Compat; using LuaScript.Engine; using Vortice; using Vortice.DCommon; @@ -77,6 +78,9 @@ namespace LuaScript private RawRectF _cachedBounds; private bool _isFirst = true; + private string _sourceScript = string.Empty; + private string _runnableScript = string.Empty; + private bool _runnableCached; private ID2D1Image? _cachedInput; private RenderKey _cachedKey; private SceneObjectQuery[] _cachedQueries = []; @@ -112,6 +116,17 @@ namespace LuaScript return _lastSceneId; } + private string GetRunnableScript(string source) + { + if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal)) + return _runnableScript; + + _runnableScript = AviUtlScript.Transform(source); + _sourceScript = source; + _runnableCached = true; + return _runnableScript; + } + protected override void setInput(ID2D1Image? input) { if (!ReferenceEquals(_cachedInput, input)) @@ -179,18 +194,19 @@ namespace LuaScript try { - bool wantNative = ScriptDirective.ResolveAuto(script) == ScriptEngineKind.Native; + string runnable = GetRunnableScript(script); + bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native; bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory); if (wantNative && !nativeReady) WarnNativeUnavailableOnce(); if (nativeReady) { - pixelsModified = ExecuteNative(script, ctx, bounds, imgW, imgH); + pixelsModified = ExecuteNative(runnable, ctx, bounds, imgW, imgH); } else { - _engine.Execute(script, ctx); + _engine.Execute(runnable, ctx); if (ctx.IsPixelsDirty) {