プラグインファイルの追加

このコミットが含まれているのは:
routersys committed 2026-06-21 11:38:51 +09:00
1 親 de0e5d7f1c
コミット 0d04b30d24
36ファイル変更
+6148

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

+419
ファイルの表示
@@ -0,0 +1,419 @@
using MoonSharp.Interpreter;
namespace LuaScript
{
internal static class AnimTableRegistrar
{
private static readonly double s_tau = Math.PI * 2d;
private static readonly double s_e = Math.E;
private static readonly double s_phi = (1d + Math.Sqrt(5d)) / 2d;
private static readonly double s_sqrt2 = Math.Sqrt(2d);
internal static void RegisterFunctions(Table anim)
{
anim["tau"] = s_tau;
anim["e"] = s_e;
anim["phi"] = s_phi;
anim["sqrt2"] = s_sqrt2;
anim["lerp"] = DynValue.NewCallback((_, args) =>
{
double a = args[0].CastToNumber() ?? 0d;
double b = args[1].CastToNumber() ?? 0d;
double t = args[2].CastToNumber() ?? 0d;
return DynValue.NewNumber(a + (b - a) * t);
});
anim["smoothstep"] = DynValue.NewCallback((_, args) =>
{
double edge0 = args[0].CastToNumber() ?? 0d;
double edge1 = args[1].CastToNumber() ?? 1d;
double x = args[2].CastToNumber() ?? 0d;
double span = edge1 - edge0;
double t = span == 0d ? 0d : Math.Clamp((x - edge0) / span, 0d, 1d);
return DynValue.NewNumber(t * t * (3d - 2d * t));
});
anim["smootherstep"] = DynValue.NewCallback((_, args) =>
{
double edge0 = args[0].CastToNumber() ?? 0d;
double edge1 = args[1].CastToNumber() ?? 1d;
double x = args[2].CastToNumber() ?? 0d;
double span = edge1 - edge0;
double t = span == 0d ? 0d : Math.Clamp((x - edge0) / span, 0d, 1d);
return DynValue.NewNumber(t * t * t * (t * (6d * t - 15d) + 10d));
});
anim["clamp"] = DynValue.NewCallback((_, args) =>
{
double v = args[0].CastToNumber() ?? 0d;
double lo = args[1].CastToNumber() ?? 0d;
double hi = args[2].CastToNumber() ?? 1d;
return DynValue.NewNumber(Math.Clamp(v, lo, hi));
});
anim["map"] = DynValue.NewCallback((_, args) =>
{
double v = args[0].CastToNumber() ?? 0d;
double a1 = args[1].CastToNumber() ?? 0d;
double b1 = args[2].CastToNumber() ?? 1d;
double a2 = args[3].CastToNumber() ?? 0d;
double b2 = args[4].CastToNumber() ?? 1d;
double range = b1 - a1;
if (range == 0d) return DynValue.NewNumber(a2);
return DynValue.NewNumber(a2 + (b2 - a2) * (v - a1) / range);
});
anim["norm"] = DynValue.NewCallback((_, args) =>
{
double v = args[0].CastToNumber() ?? 0d;
double lo = args[1].CastToNumber() ?? 0d;
double hi = args[2].CastToNumber() ?? 1d;
double span = hi - lo;
if (span == 0d) return DynValue.NewNumber(0d);
return DynValue.NewNumber((v - lo) / span);
});
anim["wrap"] = DynValue.NewCallback((_, args) =>
{
double v = args[0].CastToNumber() ?? 0d;
double lo = args[1].CastToNumber() ?? 0d;
double hi = args[2].CastToNumber() ?? 1d;
double range = hi - lo;
if (range <= 0d) return DynValue.NewNumber(lo);
double result = (v - lo) % range;
if (result < 0d) result += range;
return DynValue.NewNumber(lo + result);
});
anim["pingpong"] = DynValue.NewCallback((_, args) =>
{
double t = args[0].CastToNumber() ?? 0d;
double length = args[1].CastToNumber() ?? 1d;
if (length <= 0d) return DynValue.NewNumber(0d);
double v = t % (2d * length);
if (v < 0d) v += 2d * length;
return DynValue.NewNumber(v > length ? 2d * length - v : v);
});
anim["sign"] = DynValue.NewCallback((_, args) =>
{
double v = args[0].CastToNumber() ?? 0d;
return DynValue.NewNumber(Math.Sign(v));
});
anim["oscillate"] = DynValue.NewCallback((_, args) =>
{
double t = args[0].CastToNumber() ?? 0d;
double lo = args[1].CastToNumber() ?? 0d;
double hi = args[2].CastToNumber() ?? 1d;
double freq = args[3].CastToNumber() ?? 1d;
double wave = (Math.Sin(t * freq * s_tau) + 1d) / 2d;
return DynValue.NewNumber(lo + (hi - lo) * wave);
});
anim["triangle"] = DynValue.NewCallback((_, args) =>
{
double t = args[0].CastToNumber() ?? 0d;
double freq = args[1].CastToNumber() ?? 1d;
double f = t * freq;
f -= Math.Floor(f);
return DynValue.NewNumber(1d - 2d * Math.Abs(f - 0.5d));
});
anim["square"] = DynValue.NewCallback((_, args) =>
{
double t = args[0].CastToNumber() ?? 0d;
double freq = args[1].CastToNumber() ?? 1d;
double f = t * freq;
f -= Math.Floor(f);
return DynValue.NewNumber(f >= 0.5d ? 1d : 0d);
});
anim["duration"] = DynValue.NewCallback((_, args) =>
{
double t = args[0].CastToNumber() ?? 0d;
double dur = args[1].CastToNumber() ?? 1d;
if (dur <= 0d) return DynValue.NewNumber(1d);
return DynValue.NewNumber(Math.Clamp(t / dur, 0d, 1d));
});
anim["delay"] = DynValue.NewCallback((_, args) =>
{
double t = args[0].CastToNumber() ?? 0d;
double d = args[1].CastToNumber() ?? 0d;
return DynValue.NewNumber(Math.Max(0d, t - d));
});
anim["ease_in"] = DynValue.NewCallback((_, args) =>
{
double t = args[0].CastToNumber() ?? 0d;
return DynValue.NewNumber(t * t);
});
anim["ease_out"] = DynValue.NewCallback((_, args) =>
{
double t = args[0].CastToNumber() ?? 0d;
double inv = 1d - t;
return DynValue.NewNumber(1d - inv * inv);
});
anim["ease_in_out"] = DynValue.NewCallback((_, args) =>
{
double t = args[0].CastToNumber() ?? 0d;
if (t < 0.5d)
return DynValue.NewNumber(2d * t * t);
double inv = -2d * t + 2d;
return DynValue.NewNumber(1d - inv * inv / 2d);
});
anim["elastic"] = DynValue.NewCallback((_, args) =>
{
double t = Math.Clamp(args[0].CastToNumber() ?? 0d, 0d, 1d);
if (t == 0d) return DynValue.NewNumber(0d);
if (t == 1d) return DynValue.NewNumber(1d);
return DynValue.NewNumber(Math.Pow(2d, -10d * t) * Math.Sin((t * 10d - 0.75d) * (s_tau / 3d)) + 1d);
});
anim["back"] = DynValue.NewCallback((_, args) =>
{
const double c1 = 1.70158d;
const double c3 = c1 + 1d;
double t = args[0].CastToNumber() ?? 0d;
double inv = t - 1d;
return DynValue.NewNumber(1d + c3 * inv * inv * inv + c1 * inv * inv);
});
anim["step"] = DynValue.NewCallback((_, args) =>
{
double edge = args[0].CastToNumber() ?? 0d;
double x = args[1].CastToNumber() ?? 0d;
return DynValue.NewNumber(x >= edge ? 1d : 0d);
});
anim["fract"] = DynValue.NewCallback((_, args) =>
{
double v = args[0].CastToNumber() ?? 0d;
return DynValue.NewNumber(v - Math.Floor(v));
});
anim["bounce"] = DynValue.NewCallback((_, args) =>
{
const double n1 = 7.5625d;
const double d1 = 2.75d;
double t = Math.Clamp(args[0].CastToNumber() ?? 0d, 0d, 1d);
if (t < 1d / d1)
return DynValue.NewNumber(n1 * t * t);
if (t < 2d / d1)
{
t -= 1.5d / d1;
return DynValue.NewNumber(n1 * t * t + 0.75d);
}
if (t < 2.5d / d1)
{
t -= 2.25d / d1;
return DynValue.NewNumber(n1 * t * t + 0.9375d);
}
t -= 2.625d / d1;
return DynValue.NewNumber(n1 * t * t + 0.984375d);
});
anim["hsv_to_rgb"] = DynValue.NewCallback((_, args) =>
{
double h = args[0].CastToNumber() ?? 0d;
double s = args[1].CastToNumber() ?? 0d;
double v = args[2].CastToNumber() ?? 0d;
double c = v * s;
double x = c * (1d - Math.Abs((h / 60d) % 2d - 1d));
double m = v - c;
int sector = ((int)Math.Floor(h / 60d) % 6 + 6) % 6;
(double r, double g, double b) = sector switch
{
0 => (c, x, 0d),
1 => (x, c, 0d),
2 => (0d, c, x),
3 => (0d, x, c),
4 => (x, 0d, c),
_ => (c, 0d, x),
};
return DynValue.NewTuple(
DynValue.NewNumber((r + m) * 255d),
DynValue.NewNumber((g + m) * 255d),
DynValue.NewNumber((b + m) * 255d));
});
anim["rgb_to_hsv"] = DynValue.NewCallback((_, args) =>
{
double r = (args[0].CastToNumber() ?? 0d) / 255d;
double g = (args[1].CastToNumber() ?? 0d) / 255d;
double b = (args[2].CastToNumber() ?? 0d) / 255d;
double max = Math.Max(r, Math.Max(g, b));
double min = Math.Min(r, Math.Min(g, b));
double delta = max - min;
double h = 0d;
if (delta > 0d)
{
if (max == r) h = 60d * ((((g - b) / delta) % 6d + 6d) % 6d);
else if (max == g) h = 60d * ((b - r) / delta + 2d);
else h = 60d * ((r - g) / delta + 4d);
}
return DynValue.NewTuple(
DynValue.NewNumber(h),
DynValue.NewNumber(max > 0d ? delta / max : 0d),
DynValue.NewNumber(max));
});
anim["len"] = DynValue.NewCallback((_, args) =>
{
double x = args[0].CastToNumber() ?? 0d;
double y = args[1].CastToNumber() ?? 0d;
return DynValue.NewNumber(Math.Sqrt(x * x + y * y));
});
anim["dist"] = DynValue.NewCallback((_, args) =>
{
double x1 = args[0].CastToNumber() ?? 0d;
double y1 = args[1].CastToNumber() ?? 0d;
double x2 = args[2].CastToNumber() ?? 0d;
double y2 = args[3].CastToNumber() ?? 0d;
double dx = x2 - x1;
double dy = y2 - y1;
return DynValue.NewNumber(Math.Sqrt(dx * dx + dy * dy));
});
anim["dot"] = DynValue.NewCallback((_, args) =>
{
double x1 = args[0].CastToNumber() ?? 0d;
double y1 = args[1].CastToNumber() ?? 0d;
double x2 = args[2].CastToNumber() ?? 0d;
double y2 = args[3].CastToNumber() ?? 0d;
return DynValue.NewNumber(x1 * x2 + y1 * y2);
});
anim["normalize"] = DynValue.NewCallback((_, args) =>
{
double x = args[0].CastToNumber() ?? 0d;
double y = args[1].CastToNumber() ?? 0d;
double magnitude = Math.Sqrt(x * x + y * y);
if (magnitude == 0d)
return DynValue.NewTuple(DynValue.NewNumber(0d), DynValue.NewNumber(0d));
return DynValue.NewTuple(
DynValue.NewNumber(x / magnitude),
DynValue.NewNumber(y / magnitude));
});
anim["polar"] = DynValue.NewCallback((_, args) =>
{
double r = args[0].CastToNumber() ?? 0d;
double a = args[1].CastToNumber() ?? 0d;
double rad = a * Math.PI / 180d;
return DynValue.NewTuple(
DynValue.NewNumber(r * Math.Cos(rad)),
DynValue.NewNumber(r * Math.Sin(rad))
);
});
anim["rotate"] = DynValue.NewCallback((_, args) =>
{
double x = args[0].CastToNumber() ?? 0d;
double y = args[1].CastToNumber() ?? 0d;
double a = args[2].CastToNumber() ?? 0d;
double rad = a * Math.PI / 180d;
double c = Math.Cos(rad);
double s = Math.Sin(rad);
return DynValue.NewTuple(
DynValue.NewNumber(x * c - y * s),
DynValue.NewNumber(x * s + y * c)
);
});
anim["bezier"] = DynValue.NewCallback((_, args) =>
{
double t = Math.Clamp(args[0].CastToNumber() ?? 0d, 0d, 1d);
double p0 = args[1].CastToNumber() ?? 0d;
double p1 = args[2].CastToNumber() ?? 0d;
double p2 = args[3].CastToNumber() ?? 1d;
double p3 = args[4].CastToNumber() ?? 1d;
double inv = 1d - t;
double b0 = inv * inv * inv;
double b1 = 3d * inv * inv * t;
double b2 = 3d * inv * t * t;
double b3 = t * t * t;
return DynValue.NewNumber(b0 * p0 + b1 * p1 + b2 * p2 + b3 * p3);
});
anim["rand"] = DynValue.NewCallback((_, args) =>
{
if (args.Count == 0) return DynValue.NewNumber(0d);
double seed, min = 0d, max = 1d;
if (args.Count == 1)
{
seed = args[0].CastToNumber() ?? 0d;
}
else if (args.Count == 2)
{
max = args[0].CastToNumber() ?? 1d;
seed = args[1].CastToNumber() ?? 0d;
}
else
{
min = args[0].CastToNumber() ?? 0d;
max = args[1].CastToNumber() ?? 1d;
seed = args[2].CastToNumber() ?? 0d;
}
long bits = BitConverter.DoubleToInt64Bits(seed);
uint h = (uint)((bits ^ (bits >> 32)) * 374761393);
h = (h ^ (h >> 13)) * 1274126177;
double r = (double)(h ^ (h >> 16)) / 4294967295.0;
return DynValue.NewNumber(min + r * (max - min));
});
anim["noise"] = DynValue.NewCallback((_, args) =>
{
double x = args[0].CastToNumber() ?? 0d;
double y = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double z = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
int xi = (int)Math.Floor(x);
int yi = (int)Math.Floor(y);
int zi = (int)Math.Floor(z);
double xf = x - xi;
double yf = y - yi;
double zf = z - zi;
double u = xf * xf * (3d - 2d * xf);
double v = yf * yf * (3d - 2d * yf);
double w = zf * zf * (3d - 2d * zf);
double c000 = GetNoiseHash(xi, yi, zi);
double c100 = GetNoiseHash(xi + 1, yi, zi);
double c010 = GetNoiseHash(xi, yi + 1, zi);
double c110 = GetNoiseHash(xi + 1, yi + 1, zi);
double c001 = GetNoiseHash(xi, yi, zi + 1);
double c101 = GetNoiseHash(xi + 1, yi, zi + 1);
double c011 = GetNoiseHash(xi, yi + 1, zi + 1);
double c111 = GetNoiseHash(xi + 1, yi + 1, zi + 1);
double x00 = c000 + u * (c100 - c000);
double x10 = c010 + u * (c110 - c010);
double x01 = c001 + u * (c101 - c001);
double x11 = c011 + u * (c111 - c011);
double y0 = x00 + v * (x10 - x00);
double y1 = x01 + v * (x11 - x01);
return DynValue.NewNumber(y0 + w * (y1 - y0));
});
}
private static double GetNoiseHash(int x, int y, int z)
{
uint n = (uint)(x * 374761393 + y * 668265263 + z * 1013904223);
n = (n ^ (n >> 13)) * 1274126177;
return (double)(n ^ (n >> 16)) / 4294967295.0;
}
}
}
+125
ファイルの表示
@@ -0,0 +1,125 @@
namespace LuaScript
{
internal sealed class AviUtlScriptContext
{
public bool IsPlaying { get; init; }
public bool IsPaused { get; init; }
public string SceneId { get; init; } = string.Empty;
public int ImageWidth { get; init; }
public int ImageHeight { get; init; }
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
public double Ox { get; set; }
public double Oy { get; set; }
public double Oz { get; set; }
public double Sx { get; set; }
public double Sy { get; set; }
public double Zoom { get; set; }
public double Aspect { get; set; }
public double Alpha { get; set; }
public double Rx { get; set; }
public double Ry { get; set; }
public double Rz { get; set; }
public double Track0 { get; init; }
public double Track1 { get; init; }
public double Track2 { get; init; }
public double Track3 { get; init; }
public double Time { get; init; }
public int Frame { get; init; }
public int TotalFrame { get; init; }
public double TotalTime { get; init; }
public int Framerate { get; init; }
public int TimelineFrame { get; init; }
public double TimelineTime { get; init; }
public int SceneWidth { get; init; }
public int SceneHeight { get; init; }
public int Layer { get; init; }
public int Index { get; init; }
public int Num { get; init; }
public double RxRad => Rx * Math.PI / 180d;
public double RyRad => Ry * Math.PI / 180d;
public double RzRad => Rz * Math.PI / 180d;
public int GroupIndex { get; init; }
public int GroupCount { get; init; }
public int TimelineTotalFrame { get; init; }
public double TimelineTotalTime { get; init; }
public bool IsSaving { get; init; }
public double TimeRatio { get; init; }
private Func<byte[]>? _pixelLoader;
private byte[]? _pixelBuffer;
private bool _pixelBufferLoaded;
private bool _isPixelsDirty;
public bool IsPixelsDirty => _isPixelsDirty;
internal int TotalChannels => ImageWidth * ImageHeight * 4;
internal void SetPixelLoader(Func<byte[]> loader)
{
_pixelLoader = loader;
_pixelBuffer = null;
_pixelBufferLoaded = false;
_isPixelsDirty = false;
}
internal void EnsurePixelBuffer()
{
if (_pixelBufferLoaded) return;
_pixelBuffer = _pixelLoader?.Invoke();
_pixelBufferLoaded = true;
}
internal byte[]? GetPixelBuffer() => _pixelBuffer;
internal void MarkPixelsDirty() => _isPixelsDirty = true;
public unsafe (double r, double g, double b, double a) GetPixel(int x, int y)
{
EnsurePixelBuffer();
if (_pixelBuffer is null || (uint)x >= (uint)ImageWidth || (uint)y >= (uint)ImageHeight)
return (0d, 0d, 0d, 0d);
fixed (byte* buf = _pixelBuffer)
{
byte* p = buf + (y * ImageWidth + x) * 4;
double a = p[3];
if (a <= 0d) return (0d, 0d, 0d, 0d);
double scale = 255d / a;
return (
Math.Clamp(p[2] * scale, 0d, 255d),
Math.Clamp(p[1] * scale, 0d, 255d),
Math.Clamp(p[0] * scale, 0d, 255d),
a
);
}
}
public unsafe void SetPixel(int x, int y, double r, double g, double b, double a = 255d)
{
EnsurePixelBuffer();
if (_pixelBuffer is null || (uint)x >= (uint)ImageWidth || (uint)y >= (uint)ImageHeight)
return;
_isPixelsDirty = true;
double aK = Math.Clamp(a, 0d, 255d) / 255d;
fixed (byte* buf = _pixelBuffer)
{
byte* p = buf + (y * ImageWidth + x) * 4;
p[0] = (byte)Math.Clamp(b * aK, 0d, 255d);
p[1] = (byte)Math.Clamp(g * aK, 0d, 255d);
p[2] = (byte)Math.Clamp(r * aK, 0d, 255d);
p[3] = (byte)Math.Clamp(a, 0d, 255d);
}
}
}
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
using System.Collections.Generic;
using YukkuriMovieMaker.Controls.AvalonEdit.ToolBarStrategy;
namespace LuaScript
{
internal sealed class EmptyToolBarStrategy : IToolBarStrategy
{
public IEnumerable<ToolBarGroup> GetToolBarGroups() => [];
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript
{
internal interface IScriptProvider
{
string Script { get; set; }
string DefaultScript { get; }
}
}
+158
ファイルの表示
@@ -0,0 +1,158 @@
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using YukkuriMovieMaker.Controls.AvalonEdit.AutoCompletionStrategy;
namespace LuaScript
{
internal sealed partial class LuaAutoCompletionStrategy : IAutoCompletionStrategy
{
private static readonly string[] s_keywords =
[
"and", "break", "do", "else", "elseif", "end", "false", "for",
"function", "goto", "if", "in", "local", "nil", "not", "or",
"repeat", "return", "then", "true", "until", "while"
];
private static readonly string[] s_globals =
[
"time", "frame", "totalframe", "framerate",
"timelineframe", "timelinetime", "layer",
"obj", "scene", "anim", "ymm4",
"math", "string", "table", "bit32",
"type", "tostring", "tonumber", "select", "error", "assert", "print",
"ipairs", "pairs", "next",
"unpack",
"setmetatable", "getmetatable", "rawget", "rawset", "rawequal", "rawlen",
"pcall", "xpcall",
];
private static readonly (string Prefix, string[] Members)[] s_namespaces =
[
("obj", [
"obj.w", "obj.h", "obj.hw", "obj.hh", "obj.diagonal",
"obj.cx", "obj.cy", "obj.cz",
"obj.x", "obj.y", "obj.z",
"obj.ox", "obj.oy", "obj.oz",
"obj.sx", "obj.sy",
"obj.zoom", "obj.alpha", "obj.aspect",
"obj.rx", "obj.ry", "obj.rz",
"obj.rxr", "obj.ryr", "obj.rzr",
"obj.track0", "obj.track1", "obj.track2", "obj.track3",
"obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe",
"obj.framerate", "obj.layer", "obj.index", "obj.num",
"obj.getpixel", "obj.setpixel",
"obj.getpixeldata"
]),
("math", [
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
"math.fmod", "math.huge", "math.log", "math.max", "math.min",
"math.modf", "math.pi", "math.random", "math.randomseed",
"math.sin", "math.sqrt", "math.tan", "math.atan", "math.atan2",
"math.deg", "math.rad", "math.ldexp", "math.frexp",
"math.sinh", "math.cosh", "math.tanh", "math.type",
"math.tointeger", "math.maxinteger", "math.mininteger"
]),
("string", [
"string.format", "string.len", "string.sub", "string.upper",
"string.lower", "string.rep", "string.reverse", "string.find",
"string.match", "string.gmatch", "string.gsub", "string.byte",
"string.char", "string.dump", "string.pack", "string.unpack",
"string.packsize"
]),
("table", [
"table.insert", "table.remove", "table.sort",
"table.concat", "table.unpack", "table.move"
]),
("bit32", [
"bit32.band", "bit32.bor", "bit32.bxor", "bit32.bnot",
"bit32.lshift", "bit32.rshift", "bit32.arshift",
"bit32.extract", "bit32.replace",
"bit32.btest", "bit32.countlz", "bit32.countrz"
]),
("scene", [
"scene.width", "scene.height", "scene.cx", "scene.cy"
]),
("anim", [
"anim.tau", "anim.e", "anim.phi", "anim.sqrt2",
"anim.lerp", "anim.smoothstep", "anim.smootherstep", "anim.clamp",
"anim.map", "anim.norm", "anim.wrap", "anim.pingpong",
"anim.sign", "anim.oscillate", "anim.triangle", "anim.square",
"anim.duration", "anim.delay",
"anim.ease_in", "anim.ease_out", "anim.ease_in_out", "anim.elastic", "anim.back",
"anim.step", "anim.fract", "anim.bounce",
"anim.hsv_to_rgb", "anim.rgb_to_hsv",
"anim.len", "anim.dist", "anim.dot", "anim.normalize",
"anim.noise", "anim.rand", "anim.polar", "anim.rotate", "anim.bezier"
]),
("ymm4", [
"ymm4.group_index", "ymm4.group_count", "ymm4.group_ratio",
"ymm4.timeline_totalframe", "ymm4.timeline_totaltime",
"ymm4.is_saving", "ymm4.time_ratio",
"ymm4.is_playing", "ymm4.is_paused", "ymm4.scene_id"
]),
];
private static readonly string[] s_staticCandidates =
s_keywords
.Concat(s_globals)
.Concat(s_namespaces.SelectMany(n => n.Members))
.Distinct()
.OrderBy(x => x.Length)
.ThenBy(x => x, StringComparer.OrdinalIgnoreCase)
.ToArray();
[GeneratedRegex(@"[a-zA-Z_][a-zA-Z_0-9]*$", RegexOptions.None)]
private static partial Regex IdentifierPattern();
[GeneratedRegex(@"(?<!local\s)\bfunction\s+([a-zA-Z_][a-zA-Z_0-9]*(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*)\s*\(", RegexOptions.None)]
private static partial Regex FunctionPattern();
[GeneratedRegex(@"\blocal\s+function\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(", RegexOptions.None)]
private static partial Regex LocalFunctionPattern();
public IEnumerable<string> GetCompletionItems(string input, string line, string sourceCode)
{
if (string.IsNullOrEmpty(input))
return [];
var lastDot = line.LastIndexOf('.');
if (lastDot >= 0)
{
var beforeDot = line[..lastDot];
var nsMatch = IdentifierPattern().Match(beforeDot);
if (!nsMatch.Success)
return [];
var ns = nsMatch.Value;
foreach (var (prefix, members) in s_namespaces)
{
if (ns == prefix)
return members;
}
return [];
}
if (input[0] is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z') or '_')
{
var userFunctions = GetUserDefinedFunctions(sourceCode);
return s_staticCandidates
.Concat(userFunctions)
.Distinct()
.OrderBy(x => x.Length)
.ThenBy(x => x, StringComparer.OrdinalIgnoreCase);
}
return [];
}
private static IEnumerable<string> GetUserDefinedFunctions(string sourceCode)
{
foreach (Match m in FunctionPattern().Matches(sourceCode))
yield return m.Groups[1].Value;
foreach (Match m in LocalFunctionPattern().Matches(sourceCode))
yield return m.Groups[1].Value;
}
}
}
+90
ファイルの表示
@@ -0,0 +1,90 @@
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Folding;
using YukkuriMovieMaker.Controls.AvalonEdit.FoldingStrategy;
namespace LuaScript
{
internal sealed partial class LuaFoldingStrategy : IFoldingStrategy
{
[GeneratedRegex(
@"--\[(?<lc>=*)\[.*?\]\k<lc>\]" +
@"|\[(?<ls>=*)\[.*?\]\k<ls>\]" +
@"|--[^\r\n]*" +
@"|""(?:[^""\\]|\\.)*""|'(?:[^'\\]|\\.)*'" +
@"|(?<repeat>\brepeat\b)" +
@"|(?<until>\buntil\b)" +
@"|(?<open>\b(?:function|do|if)\b)" +
@"|(?<close>\bend\b)",
RegexOptions.Singleline)]
private static partial Regex TokenPattern();
private readonly record struct Frame(int Offset, bool IsRepeat);
public void UpdateFoldings(FoldingManager manager, TextDocument document)
{
manager.UpdateFoldings(CreateNewFoldings(document, out int firstErrorOffset), firstErrorOffset);
}
private static IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
{
firstErrorOffset = -1;
var text = document.Text;
var newFoldings = new List<NewFolding>();
var openStack = new Stack<Frame>();
foreach (Match m in TokenPattern().Matches(text))
{
if (m.Groups["repeat"].Success)
{
openStack.Push(new Frame(m.Index + m.Length, IsRepeat: true));
}
else if (m.Groups["open"].Success)
{
openStack.Push(new Frame(m.Index + m.Length, IsRepeat: false));
}
else if (m.Groups["until"].Success)
{
if (openStack.Count > 0 && openStack.Peek().IsRepeat)
{
var frame = openStack.Pop();
int blockEnd = m.Index + m.Length;
if (document.GetLineByOffset(frame.Offset).LineNumber <
document.GetLineByOffset(blockEnd).LineNumber)
{
newFoldings.Add(new NewFolding(frame.Offset, blockEnd));
}
}
else
{
firstErrorOffset = m.Index;
}
}
else if (m.Groups["close"].Success)
{
if (openStack.Count > 0 && !openStack.Peek().IsRepeat)
{
var frame = openStack.Pop();
int blockEnd = m.Index + m.Length;
if (document.GetLineByOffset(frame.Offset).LineNumber <
document.GetLineByOffset(blockEnd).LineNumber)
{
newFoldings.Add(new NewFolding(frame.Offset, blockEnd));
}
}
else
{
firstErrorOffset = m.Index;
}
}
}
if (firstErrorOffset < 0 && openStack.Count > 0)
firstErrorOffset = openStack.Peek().Offset;
newFoldings.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
return newFoldings;
}
}
}
+16
ファイルの表示
@@ -7,6 +7,7 @@
<Version>1.0.0</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
@@ -14,6 +15,9 @@
<HintPath>$(YMM4DirPath)AvalonDock.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="ICSharpCode.AvalonEdit">
<HintPath>C:\Program Files\YukkuriMovieMaker_v4_Lite_Dev\ICSharpCode.AvalonEdit.dll</HintPath>
</Reference>
<Reference Include="NAudio">
<HintPath>$(YMM4DirPath)NAudio.dll</HintPath>
<Private>false</Private>
@@ -84,6 +88,18 @@
<AdditionalFiles Include="**/*.csv" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MoonSharp" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Content Include="docs\LuaScript.*.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Resource Include="Resources\SyntaxDefinitions\Lua-Dark.xshd" />
<Resource Include="Resources\SyntaxDefinitions\Lua-Light.xshd" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="mkdir &quot;$(YMM4DirPath)user\plugin\$(ProjectName)&quot; &gt; NUL 2&gt;&amp;1&#xD;&#xA;copy &quot;$(TargetPath)&quot; &quot;$(YMM4DirPath)user\plugin\$(ProjectName)\&quot;" />
</Target>
+58
ファイルの表示
@@ -0,0 +1,58 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Controls;
using YukkuriMovieMaker.Exo;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Plugin.Effects;
namespace LuaScript
{
[VideoEffect(nameof(Texts.LuaScript), [VideoEffectCategories.Filtering], ["lua", "script", "スクリプト", "lua script", "アニメーション効果", "animation"], IsAviUtlSupported = false, ResourceType = typeof(Texts))]
internal class LuaScriptEffect : VideoEffectBase, IScriptProvider
{
internal const string DefaultScript =
"""
obj.alpha = math.min(time * 255, 255)
""";
public override string Label => Texts.LuaScript;
[Display(GroupName = nameof(Texts.ScriptGroup), Name = nameof(Texts.ScriptCode), Description = nameof(Texts.ScriptCodeDesc), ResourceType = typeof(Texts))]
[LuaScriptToolBar]
public object? ToolBar => null;
[Display(GroupName = nameof(Texts.ScriptGroup), ResourceType = typeof(Texts))]
[CodeEditor(Language = "pack://application:,,,/LuaScript;component/Resources/SyntaxDefinitions/Lua-{theme}.xshd", FoldingStrategyType = typeof(LuaFoldingStrategy), AutoCompletionStrategyType = typeof(LuaAutoCompletionStrategy), ToolBarStrategyType = typeof(EmptyToolBarStrategy), PropertyEditorSize = PropertyEditorSize.FullWidth)]
public string Script { get => _script; set => Set(ref _script, value); }
string _script = DefaultScript;
string IScriptProvider.DefaultScript => DefaultScript;
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track0), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
public Animation Track0 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track1), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
public Animation Track1 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track2), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
public Animation Track2 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
[Display(GroupName = nameof(Texts.ParametersGroup), Name = nameof(Texts.Track3), Description = nameof(Texts.TrackDesc), ResourceType = typeof(Texts))]
[AnimationSlider("F2", "", -100, 100)]
public Animation Track3 { get; } = new Animation(0, YMM4Constants.VerySmallValue, YMM4Constants.VeryLargeValue);
public override IEnumerable<string> CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => [];
public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices)
=> new LuaScriptEffectProcessor(devices, this);
protected override IEnumerable<IAnimatable> GetAnimatables() =>
[
Track0, Track1, Track2, Track3,
];
}
}
+359
ファイルの表示
@@ -0,0 +1,359 @@
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice;
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Player.Video.Effects;
namespace LuaScript
{
internal sealed class LuaScriptEffectProcessor(IGraphicsDevicesAndContext devices, LuaScriptEffect item) : VideoEffectProcessorBase(devices)
{
private readonly record struct RenderKey(
int Frame,
double Time,
int Length,
int Fps,
double Track0,
double Track1,
double Track2,
double Track3,
string Script,
TimelineSourceUsage Usage,
Guid SceneId,
int TimelineFrame,
double TimelineTime,
int SceneWidth,
int SceneHeight,
int Layer,
int InputIndex,
int InputCount,
int GroupIndex,
int GroupCount,
int TimelineTotalFrame,
double TimelineTotalTime,
DrawDescription InputDesc
);
private readonly LuaScriptEngine _engine = new();
private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1);
private GraphicsDevicesAndContext? _ownCtx;
private ID2D1Bitmap1? _renderTarget;
private ID2D1Bitmap1? _stagingBitmap;
private ID2D1Bitmap1? _outputBitmap;
private AffineTransform2D? _transformEffect;
private byte[]? _pixelBuffer;
private int _bitmapWidth;
private int _bitmapHeight;
private RawRectF _cachedBounds;
private bool _isFirst = true;
private ID2D1Image? _cachedInput;
private RenderKey _cachedKey;
private DrawDescription? _cachedOutputDesc;
private bool _cachedPixelsModified;
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{
_ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx);
return null;
}
protected override void setInput(ID2D1Image? input)
{
if (!ReferenceEquals(_cachedInput, input))
_isFirst = true;
_cachedInput = input;
}
protected override void ClearEffectChain()
{
effectOutput = null;
}
public override DrawDescription Update(EffectDescription desc)
{
if (input is null || _ownCtx is null)
return desc.DrawDescription;
var frame = desc.ItemPosition.Frame;
var length = desc.ItemDuration.Frame;
var fps = desc.FPS;
var time = desc.ItemPosition.Time.TotalSeconds;
var script = item.Script ?? string.Empty;
var t0 = item.Track0.GetValue(frame, length, fps);
var t1 = item.Track1.GetValue(frame, length, fps);
var t2 = item.Track2.GetValue(frame, length, fps);
var t3 = item.Track3.GetValue(frame, length, fps);
var inDesc = desc.DrawDescription;
var key = new RenderKey(
frame, time, length, fps,
t0, t1, t2, t3,
script, desc.Usage, desc.SceneId,
desc.TimelinePosition.Frame,
desc.TimelinePosition.Time.TotalSeconds,
desc.ScreenSize.Width, desc.ScreenSize.Height,
desc.Layer, desc.InputIndex, desc.InputCount,
desc.GroupIndex, desc.GroupCount,
desc.TimelineDuration.Frame,
desc.TimelineDuration.Time.TotalSeconds,
inDesc);
if (!_isFirst && key == _cachedKey)
{
effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null;
return _cachedOutputDesc ?? inDesc;
}
var bounds = _ownCtx.DeviceContext.GetImageLocalBounds(input);
int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left));
int imgH = Math.Max(1, (int)Math.Ceiling(bounds.Bottom - bounds.Top));
var ctx = BuildContext(in key, imgW, imgH);
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
DrawDescription outDesc = inDesc;
bool pixelsModified = false;
try
{
_engine.Execute(script, ctx);
if (ctx.IsPixelsDirty)
{
EnsureBitmaps(imgW, imgH);
WritePixelsToOutput(ctx.GetPixelBuffer()!, imgW);
UpdateTransformEffect(bounds);
effectOutput = _transformEffect!.Output;
pixelsModified = true;
}
else
{
effectOutput = null;
}
outDesc = BuildOutputDesc(inDesc, ctx);
}
catch (LuaScriptException ex)
{
effectOutput = null;
outDesc = inDesc;
Log.Default.Write(ex.Message, ex);
}
finally
{
_pixelLoaderSemaphore.Wait();
_pixelLoaderSemaphore.Release();
}
_isFirst = false;
_cachedKey = key;
_cachedOutputDesc = outDesc;
_cachedPixelsModified = pixelsModified;
return outDesc;
}
private static AviUtlScriptContext BuildContext(in RenderKey key, int imgW, int imgH)
{
var zoom = key.InputDesc.Zoom;
double zoomAvg = (zoom.X + zoom.Y) / 2d;
double aspect = zoomAvg > 0d
? (zoom.X - zoom.Y) / (zoom.X + zoom.Y)
: 0d;
return new AviUtlScriptContext
{
ImageWidth = imgW,
ImageHeight = imgH,
X = key.InputDesc.Draw.X,
Y = key.InputDesc.Draw.Y,
Z = key.InputDesc.Draw.Z,
Ox = key.InputDesc.CenterPoint.X,
Oy = key.InputDesc.CenterPoint.Y,
Oz = 0d,
Sx = zoom.X,
Sy = zoom.Y,
Zoom = zoomAvg,
Aspect = aspect,
Alpha = key.InputDesc.Opacity * 255d,
Rx = key.InputDesc.Rotation.X,
Ry = key.InputDesc.Rotation.Y,
Rz = key.InputDesc.Rotation.Z,
Track0 = key.Track0,
Track1 = key.Track1,
Track2 = key.Track2,
Track3 = key.Track3,
Time = key.Time,
Frame = key.Frame,
TotalFrame = key.Length,
TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d,
Framerate = key.Fps,
TimelineFrame = key.TimelineFrame,
TimelineTime = key.TimelineTime,
SceneWidth = key.SceneWidth,
SceneHeight = key.SceneHeight,
Layer = key.Layer,
Index = key.InputIndex,
Num = key.InputCount,
GroupIndex = key.GroupIndex,
GroupCount = key.GroupCount,
TimelineTotalFrame = key.TimelineTotalFrame,
TimelineTotalTime = key.TimelineTotalTime,
IsSaving = key.Usage == TimelineSourceUsage.Exporting,
IsPlaying = key.Usage == TimelineSourceUsage.Playing,
IsPaused = key.Usage == TimelineSourceUsage.Paused,
SceneId = key.SceneId.ToString(),
TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d,
};
}
private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx)
{
return inDesc with
{
Draw = new Vector3((float)ctx.X, (float)ctx.Y, (float)ctx.Z),
CenterPoint = new Vector2((float)ctx.Ox, (float)ctx.Oy),
Zoom = new Vector2((float)ctx.Sx, (float)ctx.Sy),
Opacity = Math.Clamp(ctx.Alpha / 255d, 0d, 1d),
Rotation = new Vector3((float)ctx.Rx, (float)ctx.Ry, (float)ctx.Rz),
};
}
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
{
_pixelLoaderSemaphore.Wait();
try
{
EnsureBitmaps(width, height);
var dc = _ownCtx!.DeviceContext;
var savedTarget = dc.Target;
dc.Target = _renderTarget;
dc.BeginDraw();
dc.Clear(null);
dc.DrawImage(input!, new Vector2(-bounds.Left, -bounds.Top));
dc.EndDraw();
dc.Target = savedTarget;
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
var mapped = _stagingBitmap.Map(MapOptions.Read);
try
{
if (mapped.Pitch == width * 4)
{
Marshal.Copy(mapped.Bits, _pixelBuffer!, 0, width * height * 4);
}
else
{
for (int row = 0; row < height; row++)
Marshal.Copy(
mapped.Bits + mapped.Pitch * row,
_pixelBuffer!,
row * width * 4,
width * 4);
}
}
finally
{
_stagingBitmap.Unmap();
}
return _pixelBuffer!;
}
finally
{
_pixelLoaderSemaphore.Release();
}
}
private unsafe void WritePixelsToOutput(byte[] pixels, int width)
{
fixed (byte* ptr = pixels)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
}
private void UpdateTransformEffect(RawRectF bounds)
{
if (_transformEffect is null)
{
_transformEffect = new AffineTransform2D(_ownCtx!.DeviceContext);
_transformEffect.SetInput(0, _outputBitmap, true);
_cachedBounds = default;
}
if (_cachedBounds.Left != bounds.Left || _cachedBounds.Top != bounds.Top)
{
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(bounds.Left, bounds.Top);
_cachedBounds = bounds;
}
}
private void EnsureBitmaps(int width, int height)
{
if (_bitmapWidth == width && _bitmapHeight == height) return;
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
_bitmapWidth = 0;
_bitmapHeight = 0;
var dc = _ownCtx!.DeviceContext;
_renderTarget = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
var stagingProps = new BitmapProperties1(
new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied),
96f, 96f,
BitmapOptions.CpuRead | BitmapOptions.CannotDraw);
_stagingBitmap = dc.CreateBitmap(
new SizeI(width, height),
nint.Zero,
width * 4,
stagingProps);
_outputBitmap = dc.CreateEmptyBitmap(width, height, BitmapOptions.Target);
_pixelBuffer = new byte[width * height * 4];
_bitmapWidth = width;
_bitmapHeight = height;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_engine.Dispose();
_pixelLoaderSemaphore.Dispose();
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
}
base.Dispose(disposing);
}
}
}
+551
ファイルの表示
@@ -0,0 +1,551 @@
using System.Collections.Concurrent;
using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Debugging;
using MoonSharp.Interpreter.Loaders;
namespace LuaScript
{
internal sealed class LuaScriptEngine : IDisposable
{
private readonly record struct ExecutionResult(
LuaScriptException? Exception,
bool TimedOut);
private sealed record ExecutionJob(
string Code,
AviUtlScriptContext Context,
CancellationToken Cancellation,
TaskCompletionSource<ExecutionResult> Completion);
private sealed class ExecutionThread : IDisposable
{
private sealed class CancellationDebugger : IDebugger
{
private static readonly DebuggerAction s_runAction = new() { Action = DebuggerAction.ActionType.Run };
private CancellationToken _token;
internal void UpdateToken(CancellationToken token) => _token = token;
public DebuggerCaps GetDebuggerCaps() => 0;
public void SetDebugService(DebugService debugService) { }
public void SetSourceCode(SourceCode sourceCode) { }
public void SetByteCode(string[] byteCode) { }
public bool SignalRuntimeException(ScriptRuntimeException ex) => false;
public void SignalExecutionEnded() { }
public void Update(WatchType watchType, IEnumerable<WatchItem> items) { }
public List<DynamicExpression> GetWatchItems() => [];
public void RefreshBreakpoints(IEnumerable<SourceRef> refs) { }
public bool IsPauseRequested() => _token.IsCancellationRequested;
public DebuggerAction GetAction(int ip, SourceRef sourceref)
{
_token.ThrowIfCancellationRequested();
return s_runAction;
}
}
private readonly BlockingCollection<ExecutionJob> _queue = new(boundedCapacity: 1);
private readonly Thread _thread;
private readonly CancellationDebugger _debugger = new();
private Script? _script;
private DynValue? _compiledChunk;
private string _lastCompiledCode = string.Empty;
private Table? _objTable;
private Table? _sceneTable;
private Table? _animTable;
private Table? _ymm4Table;
private HashSet<string>? _builtinGlobalSnapshot;
private HashSet<string>? _objTableSnapshot;
private HashSet<string>? _sceneTableSnapshot;
private HashSet<string>? _animTableSnapshot;
private HashSet<string>? _ymm4TableSnapshot;
private CancellationToken _activeCancellation;
private AviUtlScriptContext? _activeContext;
internal ExecutionThread()
{
_thread = new Thread(WorkerLoop)
{
IsBackground = true,
Name = "LuaScriptWorker"
};
_thread.Start();
}
internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs)
{
using var cts = new CancellationTokenSource();
var tcs = new TaskCompletionSource<ExecutionResult>(
TaskCreationOptions.RunContinuationsAsynchronously);
if (!_queue.TryAdd(new ExecutionJob(code, ctx, cts.Token, tcs)))
return new ExecutionResult(
new LuaScriptRuntimeException("Script execution queue is full."), false);
if (tcs.Task.Wait(timeoutMs))
return tcs.Task.Result;
cts.Cancel();
return new ExecutionResult(null, TimedOut: true);
}
private void WorkerLoop()
{
try
{
foreach (var job in _queue.GetConsumingEnumerable())
ProcessJob(job);
}
catch (OperationCanceledException) { }
catch (InvalidOperationException) { }
}
private void ProcessJob(ExecutionJob job)
{
if (job.Cancellation.IsCancellationRequested)
{
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true));
return;
}
_activeCancellation = job.Cancellation;
_activeContext = job.Context;
_debugger.UpdateToken(job.Cancellation);
try
{
EnsureScript();
EnsureScriptIntegrity();
EnsureCompiled(job.Code);
SetupGlobals(job.Context);
_script!.Call(_compiledChunk!);
ReadBackGlobals(job.Context);
job.Completion.TrySetResult(new ExecutionResult(null, false));
}
catch (OperationCanceledException) when (job.Cancellation.IsCancellationRequested)
{
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true));
}
catch (LuaScriptException ex)
{
job.Completion.TrySetResult(new ExecutionResult(ex, false));
}
catch (ScriptRuntimeException ex)
{
job.Completion.TrySetResult(new ExecutionResult(
new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex), false));
}
catch (Exception ex)
{
job.Completion.TrySetResult(new ExecutionResult(
new LuaScriptRuntimeException(ex.Message, ex), false));
}
finally
{
_debugger.UpdateToken(default);
_activeContext = null;
_activeCancellation = default;
}
}
private void EnsureScript()
{
if (_script is not null) return;
var script = new Script(
CoreModules.Basic |
CoreModules.Math |
CoreModules.String |
CoreModules.Table |
CoreModules.Bit32 |
CoreModules.TableIterators |
CoreModules.Metatables |
CoreModules.ErrorHandling);
script.Options.ScriptLoader = new DisabledFileScriptLoader();
script.AttachDebugger(_debugger);
_script = script;
}
private void EnsureScriptIntegrity()
{
if (_script is null) return;
if (_script.Globals.Get("math").Type == DataType.Table) return;
_script = null;
_compiledChunk = null;
_lastCompiledCode = string.Empty;
_objTable = null;
_sceneTable = null;
_animTable = null;
_ymm4Table = null;
_builtinGlobalSnapshot = null;
_objTableSnapshot = null;
_sceneTableSnapshot = null;
_animTableSnapshot = null;
_ymm4TableSnapshot = null;
EnsureScript();
}
private void EnsureCompiled(string code)
{
if (_compiledChunk is not null && code == _lastCompiledCode) return;
DynValue chunk;
try
{
chunk = _script!.LoadString(code, null, "LuaScript");
}
catch (SyntaxErrorException ex)
{
throw new LuaScriptCompilationException(ex.DecoratedMessage ?? ex.Message, ex);
}
_compiledChunk = chunk;
_lastCompiledCode = code;
}
private void SetupGlobals(AviUtlScriptContext ctx)
{
var script = _script!;
bool isFirstSetup = _objTable is null;
if (isFirstSetup)
{
var sceneTable = new Table(script);
script.Globals["scene"] = sceneTable;
var objTable = new Table(script);
RegisterPixelCallbacks(objTable);
script.Globals["obj"] = objTable;
var animTable = new Table(script);
AnimTableRegistrar.RegisterFunctions(animTable);
script.Globals["anim"] = animTable;
var ymm4Table = new Table(script);
script.Globals["ymm4"] = ymm4Table;
_sceneTable = sceneTable;
_animTable = animTable;
_ymm4Table = ymm4Table;
_objTable = objTable;
}
else
{
ResetUserGlobals(script);
if (!ReferenceEquals(script.Globals.Get("scene").Table, _sceneTable))
{
var sceneTable = new Table(script);
script.Globals["scene"] = sceneTable;
_sceneTable = sceneTable;
_sceneTableSnapshot = null;
}
if (!ReferenceEquals(script.Globals.Get("obj").Table, _objTable))
{
var objTable = new Table(script);
RegisterPixelCallbacks(objTable);
script.Globals["obj"] = objTable;
_objTable = objTable;
_objTableSnapshot = null;
}
if (!ReferenceEquals(script.Globals.Get("anim").Table, _animTable))
{
var animTable = new Table(script);
AnimTableRegistrar.RegisterFunctions(animTable);
script.Globals["anim"] = animTable;
_animTable = animTable;
_animTableSnapshot = null;
}
if (!ReferenceEquals(script.Globals.Get("ymm4").Table, _ymm4Table))
{
var ymm4Table = new Table(script);
script.Globals["ymm4"] = ymm4Table;
_ymm4Table = ymm4Table;
_ymm4TableSnapshot = null;
}
ResetUserTableKeys(_objTable!, ref _objTableSnapshot);
ResetUserTableKeys(_sceneTable!, ref _sceneTableSnapshot);
ResetUserTableKeys(_animTable!, ref _animTableSnapshot);
ResetUserTableKeys(_ymm4Table!, ref _ymm4TableSnapshot);
}
script.Globals["time"] = ctx.Time;
script.Globals["frame"] = ctx.Frame;
script.Globals["totalframe"] = ctx.TotalFrame;
script.Globals["framerate"] = ctx.Framerate;
script.Globals["timelineframe"] = ctx.TimelineFrame;
script.Globals["timelinetime"] = ctx.TimelineTime;
script.Globals["layer"] = ctx.Layer;
_sceneTable!["width"] = ctx.SceneWidth;
_sceneTable!["height"] = ctx.SceneHeight;
_sceneTable!["cx"] = ctx.SceneWidth / 2d;
_sceneTable!["cy"] = ctx.SceneHeight / 2d;
Ymm4TableRegistrar.UpdateVariables(_ymm4Table!, ctx);
_objTable!["w"] = ctx.ImageWidth;
_objTable!["h"] = ctx.ImageHeight;
_objTable!["hw"] = ctx.ImageWidth / 2d;
_objTable!["hh"] = ctx.ImageHeight / 2d;
_objTable!["cx"] = ctx.ImageWidth / 2d;
_objTable!["cy"] = ctx.ImageHeight / 2d;
_objTable!["cz"] = 0d;
_objTable!["diagonal"] = Math.Sqrt((double)ctx.ImageWidth * ctx.ImageWidth + (double)ctx.ImageHeight * ctx.ImageHeight);
_objTable!["x"] = ctx.X;
_objTable!["y"] = ctx.Y;
_objTable!["z"] = ctx.Z;
_objTable!["ox"] = ctx.Ox;
_objTable!["oy"] = ctx.Oy;
_objTable!["oz"] = ctx.Oz;
_objTable!["sx"] = ctx.Sx;
_objTable!["sy"] = ctx.Sy;
_objTable!["sz"] = 1d;
_objTable!["zoom"] = ctx.Zoom;
_objTable!["aspect"] = ctx.Aspect;
_objTable!["alpha"] = ctx.Alpha;
_objTable!["rx"] = ctx.Rx;
_objTable!["ry"] = ctx.Ry;
_objTable!["rz"] = ctx.Rz;
_objTable!["rxr"] = ctx.RxRad;
_objTable!["ryr"] = ctx.RyRad;
_objTable!["rzr"] = ctx.RzRad;
_objTable!["track0"] = ctx.Track0;
_objTable!["track1"] = ctx.Track1;
_objTable!["track2"] = ctx.Track2;
_objTable!["track3"] = ctx.Track3;
_objTable!["time"] = ctx.Time;
_objTable!["frame"] = ctx.Frame;
_objTable!["totalframe"] = ctx.TotalFrame;
_objTable!["totaltime"] = ctx.TotalTime;
_objTable!["t"] = ctx.TotalFrame > 0 ? ctx.Frame / (double)ctx.TotalFrame : 0d;
_objTable!["framerate"] = ctx.Framerate;
_objTable!["layer"] = ctx.Layer;
_objTable!["index"] = ctx.Index;
_objTable!["num"] = ctx.Num;
if (isFirstSetup)
{
_builtinGlobalSnapshot = CaptureGlobalKeys(script);
_objTableSnapshot = CaptureTableKeys(_objTable!);
_sceneTableSnapshot = CaptureTableKeys(_sceneTable!);
_animTableSnapshot = CaptureTableKeys(_animTable!);
_ymm4TableSnapshot = CaptureTableKeys(_ymm4Table!);
}
script.Call(
script.Globals.Get("math").Table.Get("randomseed"),
DynValue.NewNumber(ctx.Frame));
}
private static HashSet<string> CaptureGlobalKeys(Script script)
{
var keys = new HashSet<string>(StringComparer.Ordinal);
foreach (var key in script.Globals.Keys)
{
if (key.Type == DataType.String)
keys.Add(key.String);
}
return keys;
}
private static HashSet<string> CaptureTableKeys(Table table)
{
var keys = new HashSet<string>(StringComparer.Ordinal);
foreach (var key in table.Keys)
{
if (key.Type == DataType.String)
keys.Add(key.String);
}
return keys;
}
private static void ResetUserTableKeys(Table table, ref HashSet<string>? snapshot)
{
if (snapshot is null) return;
var keysToRemove = new List<string>();
foreach (var key in table.Keys)
{
if (key.Type == DataType.String &&
!snapshot.Contains(key.String))
{
keysToRemove.Add(key.String);
}
}
foreach (var key in keysToRemove)
table[key] = DynValue.Nil;
}
private void ResetUserGlobals(Script script)
{
var keysToRemove = new List<string>();
foreach (var key in script.Globals.Keys)
{
if (key.Type == DataType.String &&
!_builtinGlobalSnapshot!.Contains(key.String))
{
keysToRemove.Add(key.String);
}
}
foreach (var key in keysToRemove)
script.Globals[key] = DynValue.Nil;
}
private void RegisterPixelCallbacks(Table obj)
{
obj["getpixel"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null) return DynValue.Nil;
int x = (int)(args[0].CastToNumber() ?? 0d);
int y = (int)(args[1].CastToNumber() ?? 0d);
var (r, g, b, a) = _activeContext.GetPixel(x, y);
return DynValue.NewTuple(
DynValue.NewNumber(r),
DynValue.NewNumber(g),
DynValue.NewNumber(b),
DynValue.NewNumber(a));
});
obj["setpixel"] = DynValue.NewCallback((_, args) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null) return DynValue.Void;
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;
_activeContext.SetPixel(x, y, r, g, b, a);
return DynValue.Void;
});
obj["getpixeldata"] = DynValue.NewCallback((_, _) =>
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null) return DynValue.Nil;
_activeContext.EnsurePixelBuffer();
return UserData.Create(new PixelDataProxy(_activeContext));
});
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void);
}
private void ReadBackGlobals(AviUtlScriptContext ctx)
{
if (_objTable is null) return;
ctx.X = _objTable.Get("x").CastToNumber() ?? ctx.X;
ctx.Y = _objTable.Get("y").CastToNumber() ?? ctx.Y;
ctx.Z = _objTable.Get("z").CastToNumber() ?? ctx.Z;
ctx.Ox = _objTable.Get("ox").CastToNumber() ?? ctx.Ox;
ctx.Oy = _objTable.Get("oy").CastToNumber() ?? ctx.Oy;
ctx.Oz = _objTable.Get("oz").CastToNumber() ?? ctx.Oz;
ctx.Alpha = _objTable.Get("alpha").CastToNumber() ?? ctx.Alpha;
double initialSx = ctx.Sx;
double initialSy = ctx.Sy;
double initialZoom = ctx.Zoom;
double initialAspect = ctx.Aspect;
ctx.Sx = _objTable.Get("sx").CastToNumber() ?? ctx.Sx;
ctx.Sy = _objTable.Get("sy").CastToNumber() ?? ctx.Sy;
ctx.Zoom = _objTable.Get("zoom").CastToNumber() ?? ctx.Zoom;
ctx.Aspect = _objTable.Get("aspect").CastToNumber() ?? ctx.Aspect;
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > 1e-10 || Math.Abs(ctx.Sy - initialSy) > 1e-10;
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > 1e-10 || Math.Abs(ctx.Aspect - initialAspect) > 1e-10;
if (zoomAspectChanged && !sxsyChanged)
{
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
}
double rxrNew = _objTable.Get("rxr").CastToNumber() ?? ctx.RxRad;
ctx.Rx = Math.Abs(rxrNew - ctx.RxRad) > 1e-10
? rxrNew * (180d / Math.PI)
: _objTable.Get("rx").CastToNumber() ?? ctx.Rx;
double ryrNew = _objTable.Get("ryr").CastToNumber() ?? ctx.RyRad;
ctx.Ry = Math.Abs(ryrNew - ctx.RyRad) > 1e-10
? ryrNew * (180d / Math.PI)
: _objTable.Get("ry").CastToNumber() ?? ctx.Ry;
double rzrNew = _objTable.Get("rzr").CastToNumber() ?? ctx.RzRad;
ctx.Rz = Math.Abs(rzrNew - ctx.RzRad) > 1e-10
? rzrNew * (180d / Math.PI)
: _objTable.Get("rz").CastToNumber() ?? ctx.Rz;
}
public void Dispose()
{
_queue.CompleteAdding();
_thread.Join();
_queue.Dispose();
}
internal void AbandonAsync()
{
_queue.CompleteAdding();
ThreadPool.QueueUserWorkItem(_ =>
{
_thread.Join();
_queue.Dispose();
});
}
private sealed class DisabledFileScriptLoader : ScriptLoaderBase
{
public override object LoadFile(string file, Table globalContext)
=> throw new NotSupportedException(
"File access is not allowed in Lua script effects.");
public override bool ScriptFileExists(string name) => false;
}
}
private const int ExecutionTimeoutMilliseconds = 5000;
static LuaScriptEngine()
{
UserData.RegisterType<PixelDataProxy>();
}
private ExecutionThread _executionThread = new();
private bool _disposed;
public void Execute(string code, AviUtlScriptContext ctx)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var result = _executionThread.TryExecute(code, ctx, ExecutionTimeoutMilliseconds);
if (result.TimedOut)
{
var stale = _executionThread;
_executionThread = new ExecutionThread();
stale.AbandonAsync();
throw new LuaScriptRuntimeException(
$"Script execution timed out after {ExecutionTimeoutMilliseconds} ms.");
}
if (result.Exception is not null)
throw result.Exception;
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_executionThread.Dispose();
}
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript
{
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+16
ファイルの表示
@@ -0,0 +1,16 @@
<UserControl x:Class="LuaScript.LuaScriptToolBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:LuaScript"
mc:Ignorable="d"
d:DesignHeight="28" d:DesignWidth="800">
<ToolBarTray IsLocked="True" HorizontalAlignment="Stretch">
<ToolBar Height="28" HorizontalAlignment="Stretch">
<Button ToolTip="{x:Static local:Texts.ToolBarImport}" Content="{DynamicResource MDI_Import}" Click="Import_Click" />
<Button ToolTip="{x:Static local:Texts.ToolBarExport}" Content="{DynamicResource MDI_Export}" Click="Export_Click" />
<Button ToolTip="{x:Static local:Texts.ToolBarClear}" Content="{DynamicResource MDI_Delete}" Click="Clear_Click" />
</ToolBar>
</ToolBarTray>
</UserControl>
+100
ファイルの表示
@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using YukkuriMovieMaker.Commons;
namespace LuaScript
{
public partial class LuaScriptToolBar : UserControl, IPropertyEditorControl
{
public event EventHandler? BeginEdit;
public event EventHandler? EndEdit;
public ItemProperty[]? ItemProperties { get; set; }
public LuaScriptToolBar()
{
InitializeComponent();
}
private IEnumerable<IScriptProvider> GetScriptProviders()
{
if (ItemProperties is null) yield break;
foreach (var item in ItemProperties)
{
if (item.PropertyOwner is IScriptProvider provider)
yield return provider;
}
}
private void Import_Click(object sender, RoutedEventArgs e)
{
var providers = new List<IScriptProvider>(GetScriptProviders());
if (providers.Count == 0) return;
var dlg = new OpenFileDialog
{
Filter = Texts.LuaFileFilter,
DefaultExt = ".lua"
};
if (dlg.ShowDialog() != true) return;
string script;
try
{
script = File.ReadAllText(dlg.FileName, Encoding.UTF8);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
MessageBox.Show(ex.Message, Texts.ToolBarImportErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
BeginEdit?.Invoke(this, EventArgs.Empty);
foreach (var provider in providers)
provider.Script = script;
EndEdit?.Invoke(this, EventArgs.Empty);
}
private void Export_Click(object sender, RoutedEventArgs e)
{
var providers = new List<IScriptProvider>(GetScriptProviders());
if (providers.Count == 0) return;
var dlg = new SaveFileDialog
{
Filter = Texts.LuaFileFilter,
DefaultExt = ".lua",
FileName = "script.lua"
};
if (dlg.ShowDialog() != true) return;
try
{
File.WriteAllText(dlg.FileName, providers[0].Script, new UTF8Encoding(false));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
MessageBox.Show(ex.Message, Texts.ToolBarExportErrorTitle, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void Clear_Click(object sender, RoutedEventArgs e)
{
var providers = new List<IScriptProvider>(GetScriptProviders());
if (providers.Count == 0) return;
if (MessageBox.Show(Texts.ToolBarClearConfirm, Texts.ToolBarClearTitle, MessageBoxButton.OKCancel) != MessageBoxResult.OK)
return;
BeginEdit?.Invoke(this, EventArgs.Empty);
foreach (var provider in providers)
provider.Script = provider.DefaultScript;
EndEdit?.Invoke(this, EventArgs.Empty);
}
}
}
+24
ファイルの表示
@@ -0,0 +1,24 @@
using System.Windows;
using YukkuriMovieMaker.Commons;
namespace LuaScript
{
internal sealed class LuaScriptToolBarAttribute : PropertyEditorAttribute2
{
public override PropertyEditorSize PropertyEditorSize { get; set; } = PropertyEditorSize.FullWidth;
public override FrameworkElement Create() => new LuaScriptToolBar();
public override void ClearBindings(FrameworkElement control)
{
if (control is LuaScriptToolBar editor)
editor.ItemProperties = null;
}
public override void SetBindings(FrameworkElement control, ItemProperty[] itemProperties)
{
if (control is LuaScriptToolBar editor)
editor.ItemProperties = itemProperties;
}
}
}
+84
ファイルの表示
@@ -0,0 +1,84 @@
using System.Diagnostics;
using MoonSharp.Interpreter;
namespace LuaScript
{
[MoonSharpUserData]
internal sealed class PixelDataProxy(AviUtlScriptContext ctx)
{
public int width => ctx.ImageWidth;
public int height => ctx.ImageHeight;
public unsafe double get(int index)
{
ctx.EnsurePixelBuffer();
var buf = ctx.GetPixelBuffer();
if (buf is null) return 0d;
int zeroBasedIndex = index - 1;
if ((uint)zeroBasedIndex >= (uint)ctx.TotalChannels) return 0d;
int pixelIndex = Math.DivRem(zeroBasedIndex, 4, out int channel);
fixed (byte* p = buf)
{
byte* pixel = p + pixelIndex * 4;
double a = pixel[3];
return channel switch
{
0 => a > 0d ? Math.Clamp(pixel[2] * 255d / a, 0d, 255d) : 0d,
1 => a > 0d ? Math.Clamp(pixel[1] * 255d / a, 0d, 255d) : 0d,
2 => a > 0d ? Math.Clamp(pixel[0] * 255d / a, 0d, 255d) : 0d,
3 => a,
_ => throw new UnreachableException()
};
}
}
public unsafe void set(int index, double value)
{
ctx.EnsurePixelBuffer();
var buf = ctx.GetPixelBuffer();
if (buf is null) return;
int zeroBasedIndex = index - 1;
if ((uint)zeroBasedIndex >= (uint)ctx.TotalChannels) return;
ctx.MarkPixelsDirty();
int pixelIndex = Math.DivRem(zeroBasedIndex, 4, out int channel);
double clamped = Math.Clamp(value, 0d, 255d);
fixed (byte* p = buf)
{
byte* pixel = p + pixelIndex * 4;
if (channel == 3)
{
double oldA = pixel[3];
double newA = clamped;
if (oldA > 0d && newA > 0d)
{
double factor = newA / oldA;
pixel[0] = (byte)Math.Clamp(pixel[0] * factor, 0d, 255d);
pixel[1] = (byte)Math.Clamp(pixel[1] * factor, 0d, 255d);
pixel[2] = (byte)Math.Clamp(pixel[2] * factor, 0d, 255d);
}
else if (newA <= 0d)
{
pixel[0] = pixel[1] = pixel[2] = 0;
}
pixel[3] = (byte)newA;
}
else
{
double a = pixel[3];
double premultiplied = clamped * (a / 255d);
int byteOffset = channel switch { 0 => 2, 1 => 1, 2 => 0, _ => throw new UnreachableException() };
pixel[byteOffset] = (byte)Math.Clamp(premultiplied, 0d, 255d);
}
}
}
}
}
+62
ファイルの表示
@@ -0,0 +1,62 @@
<?xml version="1.0"?>
<SyntaxDefinition name="Lua" extensions=".lua" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<Color name="Comment" foreground="#FF57A64A" />
<Color name="String" foreground="#FFD69D85" />
<Color name="NumberLiteral" foreground="#FFB5CEA8"/>
<Color name="NilKeyword" foreground="#FF569CD6"/>
<Color name="Keywords" foreground="#FF569CD6" />
<Color name="TrueFalse" foreground="#FF569CD6" />
<RuleSet>
<Span color="Comment" multiline="true">
<Begin>--\[\[</Begin>
<End>\]\]</End>
</Span>
<Span color="Comment">
<Begin>--</Begin>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<Span begin="\\" end="." />
</RuleSet>
</Span>
<Span color="String">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<Span begin="\\" end="." />
</RuleSet>
</Span>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>and</Word>
<Word>break</Word>
<Word>do</Word>
<Word>else</Word>
<Word>elseif</Word>
<Word>end</Word>
<Word>for</Word>
<Word>function</Word>
<Word>goto</Word>
<Word>if</Word>
<Word>in</Word>
<Word>local</Word>
<Word>not</Word>
<Word>or</Word>
<Word>repeat</Word>
<Word>return</Word>
<Word>then</Word>
<Word>until</Word>
<Word>while</Word>
</Keywords>
<Keywords color="NilKeyword">
<Word>nil</Word>
</Keywords>
<Rule color="NumberLiteral">\b0[xX][0-9a-fA-F]+|\b(\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
</RuleSet>
</SyntaxDefinition>
+62
ファイルの表示
@@ -0,0 +1,62 @@
<?xml version="1.0"?>
<SyntaxDefinition name="Lua" extensions=".lua" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
<Color name="Comment" foreground="#FF008000" />
<Color name="String" foreground="#FFA31515" />
<Color name="NumberLiteral" foreground="#FF000000"/>
<Color name="NilKeyword" foreground="#FF0000FF"/>
<Color name="Keywords" foreground="#FF0000FF" />
<Color name="TrueFalse" foreground="#FF0000FF" />
<RuleSet>
<Span color="Comment" multiline="true">
<Begin>--\[\[</Begin>
<End>\]\]</End>
</Span>
<Span color="Comment">
<Begin>--</Begin>
</Span>
<Span color="String">
<Begin>"</Begin>
<End>"</End>
<RuleSet>
<Span begin="\\" end="." />
</RuleSet>
</Span>
<Span color="String">
<Begin>'</Begin>
<End>'</End>
<RuleSet>
<Span begin="\\" end="." />
</RuleSet>
</Span>
<Keywords color="TrueFalse">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color="Keywords">
<Word>and</Word>
<Word>break</Word>
<Word>do</Word>
<Word>else</Word>
<Word>elseif</Word>
<Word>end</Word>
<Word>for</Word>
<Word>function</Word>
<Word>goto</Word>
<Word>if</Word>
<Word>in</Word>
<Word>local</Word>
<Word>not</Word>
<Word>or</Word>
<Word>repeat</Word>
<Word>return</Word>
<Word>then</Word>
<Word>until</Word>
<Word>while</Word>
</Keywords>
<Keywords color="NilKeyword">
<Word>nil</Word>
</Keywords>
<Rule color="NumberLiteral">\b0[xX][0-9a-fA-F]+|\b(\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?</Rule>
</RuleSet>
</SyntaxDefinition>
+80
ファイルの表示
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CurrentCulture" xml:space="preserve"><value>ar-sa</value></data>
<data name="LuaScript" xml:space="preserve"><value>نص Lua</value></data>
<data name="ScriptGroup" xml:space="preserve"><value>نص</value></data>
<data name="ScriptCode" xml:space="preserve"><value>كود النص</value></data>
<data name="ScriptCodeDesc" xml:space="preserve"><value>اكتب نص Lua. تحكم في التأثيرات باستخدام obj.x/y/zoom/alpha وما إلى ذلك.</value></data>
<data name="ParametersGroup" xml:space="preserve"><value>المعاملات</value></data>
<data name="Track0" xml:space="preserve"><value>مسار 0</value></data>
<data name="Track1" xml:space="preserve"><value>مسار 1</value></data>
<data name="Track2" xml:space="preserve"><value>مسار 2</value></data>
<data name="Track3" xml:space="preserve"><value>مسار 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>قيمة المنزلق (متوافق مع AviUtl: track0-3)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>استيراد</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>تصدير</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>مسح</value></data>
<data name="ToolBarClearConfirm" xml:space="preserve"><value>هل تريد إعادة تعيين النص إلى الإعداد الافتراضي؟</value></data>
<data name="ToolBarClearTitle" xml:space="preserve"><value>تأكيد</value></data>
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>خطأ في الاستيراد</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>خطأ في التصدير</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*</value></data>
</root>
+8
ファイルの表示
@@ -0,0 +1,8 @@
using YukkuriMovieMaker.Generator;
namespace LuaScript
{
[AutoGenLocalizer]
partial class Texts
{
}
}
+19
ファイルの表示
@@ -0,0 +1,19 @@
Key,Parameter,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id
LuaScript,,Luaスクリプト,Lua Script,Lua脚本,Lua腳本,Lua 스크립트,Script Lua,نص Lua,Skrip Lua
ScriptGroup,,スクリプト,Script,脚本,腳本,스크립트,Script,نص,Skrip
ScriptCode,,スクリプトコード,Script Code,脚本代码,腳本代碼,스크립트 코드,Código de script,كود النص,Kode skrip
ScriptCodeDesc,,Luaスクリプトを記述します。obj.x/y/zoom/alpha等でエフェクトを制御できます。,Write a Lua script. Control effects with obj.x/y/zoom/alpha etc.,编写Lua脚本,使用obj.x/y/zoom/alpha等控制效果。,編寫Lua腳本,使用obj.x/y/zoom/alpha等控制效果。,Lua 스크립트를 작성합니다. obj.x/y/zoom/alpha 등으로 효과를 제어할 수 있습니다.,Escriba un script Lua. Controle efectos con obj.x/y/zoom/alpha etc.,اكتب نص Lua. تحكم في التأثيرات باستخدام obj.x/y/zoom/alpha وما إلى ذلك.,Tulis skrip Lua. Kendalikan efek dengan obj.x/y/zoom/alpha dll.
ParametersGroup,,パラメータ,Parameters,参数,參數,파라미터,Parámetros,المعاملات,Parameter
Track0,,トラック0,Track 0,轨道0,軌道0,트랙0,Pista 0,مسار 0,Jalur 0
Track1,,トラック1,Track 1,轨道1,軌道1,트랙1,Pista 1,مسار 1,Jalur 1
Track2,,トラック2,Track 2,轨道2,軌道2,트랙2,Pista 2,مسار 2,Jalur 2
Track3,,トラック3,Track 3,轨道3,軌道3,트랙3,Pista 3,مسار 3,Jalur 3
TrackDesc,,スライダー値 (AviUtl準拠 track0〜3 に対応),Slider value (AviUtl compatible: track0–3),滑块值(AviUtl兼容: track0~3),滑塊值(AviUtl兼容: track0~3),슬라이더 값 (AviUtl 호환: track0~3),Valor del deslizador (compatible AviUtl: track0-3),قيمة المنزلق (متوافق مع AviUtl: track0-3),Nilai slider (kompatibel AviUtl: track0-3)
ToolBarImport,,インポート,Import,导入,導入,가져오기,Importar,استيراد,Impor
ToolBarExport,,エクスポート,Export,导出,導出,내보내기,Exportar,تصدير,Ekspor
ToolBarClear,,クリア,Clear,清除,清除,지우기,Limpiar,مسح,Hapus
ToolBarClearConfirm,,スクリプトをデフォルトに戻しますか?,Reset script to default?,将脚本重置为默认值?,將腳本重置為預設值?,스크립트를 기본값으로 초기화하겠습니까?,¿Restablecer el script a los valores predeterminados?,هل تريد إعادة تعيين النص إلى الإعداد الافتراضي؟,Atur ulang skrip ke default?
ToolBarClearTitle,,確認,Confirm,确认,確認,확인,Confirmar,تأكيد,Konfirmasi
ToolBarImportErrorTitle,,インポートエラー,Import Error,导入错误,導入錯誤,가져오기 오류,Error de importación,خطأ في الاستيراد,Kesalahan impor
ToolBarExportErrorTitle,,エクスポートエラー,Export Error,导出错误,導出錯誤,내보내기 오류,Error de exportación,خطأ في التصدير,Kesalahan ekspor
LuaFileFilter,,Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*,Lua Script (*.lua)|*.lua|All Files (*.*)|*.*,Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*,Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*,Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*,Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*,نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.*,Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
2 LuaScript Luaスクリプト Lua Script Lua脚本 Lua腳本 Lua 스크립트 Script Lua نص Lua Skrip Lua
3 ScriptGroup スクリプト Script 脚本 腳本 스크립트 Script نص Skrip
4 ScriptCode スクリプトコード Script Code 脚本代码 腳本代碼 스크립트 코드 Código de script كود النص Kode skrip
5 ScriptCodeDesc Luaスクリプトを記述します。obj.x/y/zoom/alpha等でエフェクトを制御できます。 Write a Lua script. Control effects with obj.x/y/zoom/alpha etc. 编写Lua脚本,使用obj.x/y/zoom/alpha等控制效果。 編寫Lua腳本,使用obj.x/y/zoom/alpha等控制效果。 Lua 스크립트를 작성합니다. obj.x/y/zoom/alpha 등으로 효과를 제어할 수 있습니다. Escriba un script Lua. Controle efectos con obj.x/y/zoom/alpha etc. اكتب نص Lua. تحكم في التأثيرات باستخدام obj.x/y/zoom/alpha وما إلى ذلك. Tulis skrip Lua. Kendalikan efek dengan obj.x/y/zoom/alpha dll.
6 ParametersGroup パラメータ Parameters 参数 參數 파라미터 Parámetros المعاملات Parameter
7 Track0 トラック0 Track 0 轨道0 軌道0 트랙0 Pista 0 مسار 0 Jalur 0
8 Track1 トラック1 Track 1 轨道1 軌道1 트랙1 Pista 1 مسار 1 Jalur 1
9 Track2 トラック2 Track 2 轨道2 軌道2 트랙2 Pista 2 مسار 2 Jalur 2
10 Track3 トラック3 Track 3 轨道3 軌道3 트랙3 Pista 3 مسار 3 Jalur 3
11 TrackDesc スライダー値 (AviUtl準拠 track0〜3 に対応) Slider value (AviUtl compatible: track0–3) 滑块值(AviUtl兼容: track0~3) 滑塊值(AviUtl兼容: track0~3) 슬라이더 값 (AviUtl 호환: track0~3) Valor del deslizador (compatible AviUtl: track0-3) قيمة المنزلق (متوافق مع AviUtl: track0-3) Nilai slider (kompatibel AviUtl: track0-3)
12 ToolBarImport インポート Import 导入 導入 가져오기 Importar استيراد Impor
13 ToolBarExport エクスポート Export 导出 導出 내보내기 Exportar تصدير Ekspor
14 ToolBarClear クリア Clear 清除 清除 지우기 Limpiar مسح Hapus
15 ToolBarClearConfirm スクリプトをデフォルトに戻しますか? Reset script to default? 将脚本重置为默认值? 將腳本重置為預設值? 스크립트를 기본값으로 초기화하겠습니까? ¿Restablecer el script a los valores predeterminados? هل تريد إعادة تعيين النص إلى الإعداد الافتراضي؟ Atur ulang skrip ke default?
16 ToolBarClearTitle 確認 Confirm 确认 確認 확인 Confirmar تأكيد Konfirmasi
17 ToolBarImportErrorTitle インポートエラー Import Error 导入错误 導入錯誤 가져오기 오류 Error de importación خطأ في الاستيراد Kesalahan impor
18 ToolBarExportErrorTitle エクスポートエラー Export Error 导出错误 導出錯誤 내보내기 오류 Error de exportación خطأ في التصدير Kesalahan ekspor
19 LuaFileFilter Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.* Lua Script (*.lua)|*.lua|All Files (*.*)|*.* Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.* Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.* Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.* Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.* نص Lua (*.lua)|*.lua|جميع الملفات (*.*)|*.* Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*
+80
ファイルの表示
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CurrentCulture" xml:space="preserve"><value>en-us</value></data>
<data name="LuaScript" xml:space="preserve"><value>Lua Script</value></data>
<data name="ScriptGroup" xml:space="preserve"><value>Script</value></data>
<data name="ScriptCode" xml:space="preserve"><value>Script Code</value></data>
<data name="ScriptCodeDesc" xml:space="preserve"><value>Write a Lua script. Control effects with obj.x/y/zoom/alpha etc.</value></data>
<data name="ParametersGroup" xml:space="preserve"><value>Parameters</value></data>
<data name="Track0" xml:space="preserve"><value>Track 0</value></data>
<data name="Track1" xml:space="preserve"><value>Track 1</value></data>
<data name="Track2" xml:space="preserve"><value>Track 2</value></data>
<data name="Track3" xml:space="preserve"><value>Track 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Slider value (AviUtl compatible: track0–3)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Import</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Export</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Clear</value></data>
<data name="ToolBarClearConfirm" xml:space="preserve"><value>Reset script to default?</value></data>
<data name="ToolBarClearTitle" xml:space="preserve"><value>Confirm</value></data>
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Import Error</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Export Error</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Lua Script (*.lua)|*.lua|All Files (*.*)|*.*</value></data>
</root>
+80
ファイルの表示
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CurrentCulture" xml:space="preserve"><value>es-es</value></data>
<data name="LuaScript" xml:space="preserve"><value>Script Lua</value></data>
<data name="ScriptGroup" xml:space="preserve"><value>Script</value></data>
<data name="ScriptCode" xml:space="preserve"><value>Código de script</value></data>
<data name="ScriptCodeDesc" xml:space="preserve"><value>Escriba un script Lua. Controle efectos con obj.x/y/zoom/alpha etc.</value></data>
<data name="ParametersGroup" xml:space="preserve"><value>Parámetros</value></data>
<data name="Track0" xml:space="preserve"><value>Pista 0</value></data>
<data name="Track1" xml:space="preserve"><value>Pista 1</value></data>
<data name="Track2" xml:space="preserve"><value>Pista 2</value></data>
<data name="Track3" xml:space="preserve"><value>Pista 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Valor del deslizador (compatible AviUtl: track0-3)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Importar</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Exportar</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Limpiar</value></data>
<data name="ToolBarClearConfirm" xml:space="preserve"><value>¿Restablecer el script a los valores predeterminados?</value></data>
<data name="ToolBarClearTitle" xml:space="preserve"><value>Confirmar</value></data>
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Error de importación</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Error de exportación</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Script Lua (*.lua)|*.lua|Todos los archivos (*.*)|*.*</value></data>
</root>
+80
ファイルの表示
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CurrentCulture" xml:space="preserve"><value>id-id</value></data>
<data name="LuaScript" xml:space="preserve"><value>Skrip Lua</value></data>
<data name="ScriptGroup" xml:space="preserve"><value>Skrip</value></data>
<data name="ScriptCode" xml:space="preserve"><value>Kode skrip</value></data>
<data name="ScriptCodeDesc" xml:space="preserve"><value>Tulis skrip Lua. Kendalikan efek dengan obj.x/y/zoom/alpha dll.</value></data>
<data name="ParametersGroup" xml:space="preserve"><value>Parameter</value></data>
<data name="Track0" xml:space="preserve"><value>Jalur 0</value></data>
<data name="Track1" xml:space="preserve"><value>Jalur 1</value></data>
<data name="Track2" xml:space="preserve"><value>Jalur 2</value></data>
<data name="Track3" xml:space="preserve"><value>Jalur 3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>Nilai slider (kompatibel AviUtl: track0-3)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>Impor</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>Ekspor</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>Hapus</value></data>
<data name="ToolBarClearConfirm" xml:space="preserve"><value>Atur ulang skrip ke default?</value></data>
<data name="ToolBarClearTitle" xml:space="preserve"><value>Konfirmasi</value></data>
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>Kesalahan impor</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>Kesalahan ekspor</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Skrip Lua (*.lua)|*.lua|Semua File (*.*)|*.*</value></data>
</root>
+80
ファイルの表示
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CurrentCulture" xml:space="preserve"><value>ko-kr</value></data>
<data name="LuaScript" xml:space="preserve"><value>Lua 스크립트</value></data>
<data name="ScriptGroup" xml:space="preserve"><value>스크립트</value></data>
<data name="ScriptCode" xml:space="preserve"><value>스크립트 코드</value></data>
<data name="ScriptCodeDesc" xml:space="preserve"><value>Lua 스크립트를 작성합니다. obj.x/y/zoom/alpha 등으로 효과를 제어할 수 있습니다.</value></data>
<data name="ParametersGroup" xml:space="preserve"><value>파라미터</value></data>
<data name="Track0" xml:space="preserve"><value>트랙0</value></data>
<data name="Track1" xml:space="preserve"><value>트랙1</value></data>
<data name="Track2" xml:space="preserve"><value>트랙2</value></data>
<data name="Track3" xml:space="preserve"><value>트랙3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>슬라이더 값 (AviUtl 호환: track0~3)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>가져오기</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>내보내기</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>지우기</value></data>
<data name="ToolBarClearConfirm" xml:space="preserve"><value>스크립트를 기본값으로 초기화하겠습니까?</value></data>
<data name="ToolBarClearTitle" xml:space="preserve"><value>확인</value></data>
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>가져오기 오류</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>내보내기 오류</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Lua 스크립트 (*.lua)|*.lua|모든 파일 (*.*)|*.*</value></data>
</root>
+80
ファイルの表示
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CurrentCulture" xml:space="preserve"><value>ja-jp</value></data>
<data name="LuaScript" xml:space="preserve"><value>Luaスクリプト</value></data>
<data name="ScriptGroup" xml:space="preserve"><value>スクリプト</value></data>
<data name="ScriptCode" xml:space="preserve"><value>スクリプトコード</value></data>
<data name="ScriptCodeDesc" xml:space="preserve"><value>Luaスクリプトを記述します。obj.x/y/zoom/alpha等でエフェクトを制御できます。</value></data>
<data name="ParametersGroup" xml:space="preserve"><value>パラメータ</value></data>
<data name="Track0" xml:space="preserve"><value>トラック0</value></data>
<data name="Track1" xml:space="preserve"><value>トラック1</value></data>
<data name="Track2" xml:space="preserve"><value>トラック2</value></data>
<data name="Track3" xml:space="preserve"><value>トラック3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>スライダー値 (AviUtl準拠 track0〜3 に対応)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>インポート</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>エクスポート</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>クリア</value></data>
<data name="ToolBarClearConfirm" xml:space="preserve"><value>スクリプトをデフォルトに戻しますか?</value></data>
<data name="ToolBarClearTitle" xml:space="preserve"><value>確認</value></data>
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>インポートエラー</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>エクスポートエラー</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Luaスクリプト (*.lua)|*.lua|すべてのファイル (*.*)|*.*</value></data>
</root>
+80
ファイルの表示
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CurrentCulture" xml:space="preserve"><value>zh-cn</value></data>
<data name="LuaScript" xml:space="preserve"><value>Lua脚本</value></data>
<data name="ScriptGroup" xml:space="preserve"><value>脚本</value></data>
<data name="ScriptCode" xml:space="preserve"><value>脚本代码</value></data>
<data name="ScriptCodeDesc" xml:space="preserve"><value>编写Lua脚本,使用obj.x/y/zoom/alpha等控制效果。</value></data>
<data name="ParametersGroup" xml:space="preserve"><value>参数</value></data>
<data name="Track0" xml:space="preserve"><value>轨道0</value></data>
<data name="Track1" xml:space="preserve"><value>轨道1</value></data>
<data name="Track2" xml:space="preserve"><value>轨道2</value></data>
<data name="Track3" xml:space="preserve"><value>轨道3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>滑块值(AviUtl兼容: track0~3)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>导入</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>导出</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
<data name="ToolBarClearConfirm" xml:space="preserve"><value>将脚本重置为默认值?</value></data>
<data name="ToolBarClearTitle" xml:space="preserve"><value>确认</value></data>
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>导入错误</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>导出错误</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Lua脚本 (*.lua)|*.lua|所有文件 (*.*)|*.*</value></data>
</root>
+80
ファイルの表示
@@ -0,0 +1,80 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CurrentCulture" xml:space="preserve"><value>zh-tw</value></data>
<data name="LuaScript" xml:space="preserve"><value>Lua腳本</value></data>
<data name="ScriptGroup" xml:space="preserve"><value>腳本</value></data>
<data name="ScriptCode" xml:space="preserve"><value>腳本代碼</value></data>
<data name="ScriptCodeDesc" xml:space="preserve"><value>編寫Lua腳本,使用obj.x/y/zoom/alpha等控制效果。</value></data>
<data name="ParametersGroup" xml:space="preserve"><value>參數</value></data>
<data name="Track0" xml:space="preserve"><value>軌道0</value></data>
<data name="Track1" xml:space="preserve"><value>軌道1</value></data>
<data name="Track2" xml:space="preserve"><value>軌道2</value></data>
<data name="Track3" xml:space="preserve"><value>軌道3</value></data>
<data name="TrackDesc" xml:space="preserve"><value>滑塊值(AviUtl兼容: track0~3)</value></data>
<data name="ToolBarImport" xml:space="preserve"><value>導入</value></data>
<data name="ToolBarExport" xml:space="preserve"><value>導出</value></data>
<data name="ToolBarClear" xml:space="preserve"><value>清除</value></data>
<data name="ToolBarClearConfirm" xml:space="preserve"><value>將腳本重置為預設值?</value></data>
<data name="ToolBarClearTitle" xml:space="preserve"><value>確認</value></data>
<data name="ToolBarImportErrorTitle" xml:space="preserve"><value>導入錯誤</value></data>
<data name="ToolBarExportErrorTitle" xml:space="preserve"><value>導出錯誤</value></data>
<data name="LuaFileFilter" xml:space="preserve"><value>Lua腳本 (*.lua)|*.lua|所有檔案 (*.*)|*.*</value></data>
</root>
+21
ファイルの表示
@@ -0,0 +1,21 @@
using MoonSharp.Interpreter;
namespace LuaScript
{
internal static class Ymm4TableRegistrar
{
internal static void UpdateVariables(Table ymm4, AviUtlScriptContext ctx)
{
ymm4["group_index"] = ctx.GroupIndex;
ymm4["group_count"] = ctx.GroupCount;
ymm4["group_ratio"] = ctx.GroupCount > 0 ? ctx.GroupIndex / (double)ctx.GroupCount : 0d;
ymm4["timeline_totalframe"] = ctx.TimelineTotalFrame;
ymm4["timeline_totaltime"] = ctx.TimelineTotalTime;
ymm4["is_saving"] = ctx.IsSaving;
ymm4["time_ratio"] = ctx.TimeRatio;
ymm4["is_playing"] = ctx.IsPlaying;
ymm4["is_paused"] = ctx.IsPaused;
ymm4["scene_id"] = ctx.SceneId;
}
}
}
+413
ファイルの表示
@@ -0,0 +1,413 @@
- حول تأثير نصوص Lua -
يستخدم تأثير الفيديو "نص Lua" في YukkuriMovieMaker4
لغة Lua لكتابة النصوص البرمجية.
يعتمد محرك النصوص على MoonSharp (متوافق مع Lua 5.2).
* هذا التأثير تطبيق مستقل ويختلف عن مواصفات نصوص AviUtl2.
* يختلف في مواصفاته عن ملفات نصوص AviUtl2 (*.anm2 وما شابه).
* نظراً لأن IsAviUtlSupported = false، لا يُدعم إخراج EXO لبرنامج AviUtl.
- ملاحظات -
○ محرك تنفيذ النصوص هو MoonSharp (متوافق مع Lua 5.2).
○ المكتبات القياسية المتاحة محدودة بما يلي:
table, string, math, bit32
* io, os, debug, ffi, require وغيرها غير متاحة.
○ مهلة النص البرمجي هي 5000 مللي ثانية (5 ثوانٍ).
عند انتهاء المهلة، يُنهى التنفيذ قسراً ويُعامل كخطأ.
○ لا يمكن للنصوص الوصول إلى نظام الملفات (بما في ذلك require).
○ استدعاء النصوص الخارجية من داخل النص البرمجي غير مدعوم.
○ عمليات البكسل (getpixel/setpixel/getpixeldata) تصل إلى الصورة المدخلة الفعلية،
لذا تحدث نقل البيانات من GPU إلى CPU عند الوصول الأول فقط.
حذف هذه الاستدعاءات عند عدم الحاجة يسرّع المعالجة.
- المعاملات -
يحتوي لوح التأثيرات على 4 أشرطة تتبع (تدعم الرسوم المتحركة) على النحو التالي.
يمكن الرجوع إلى كل قيمة في النص البرمجي عبر obj.track0 إلى obj.track3.
Track0 : المعامل 0 (الافتراضي: 0، النطاق: الحد الأدنى ~ الحد الأقصى)
Track1 : المعامل 1 (الافتراضي: 0، النطاق: الحد الأدنى ~ الحد الأقصى)
Track2 : المعامل 2 (الافتراضي: 0، النطاق: الحد الأدنى ~ الحد الأقصى)
Track3 : المعامل 3 (الافتراضي: 0، النطاق: الحد الأدنى ~ الحد الأقصى)
* كل شريط تتبع يدعم شرائح الرسوم المتحركة (مع الاستيفاء).
* يمكن استيراد/تصدير ملفات .lua من شريط أدوات محرر النصوص.
- المتغيرات العامة -
يمكن الرجوع إلى المتغيرات التالية مباشرةً في النطاق العام للنص البرمجي.
time : الوقت الحالي بالثواني نسبةً إلى الكائن [للقراءة فقط]
* نفس قيمة obj.time.
frame : رقم الإطار الحالي نسبةً إلى الكائن [للقراءة فقط]
* نفس قيمة obj.frame.
totalframe : إجمالي عدد إطارات الكائن [للقراءة فقط]
* نفس قيمة obj.totalframe.
framerate : معدل الإطارات (إطار/ثانية) [للقراءة فقط]
* نفس قيمة obj.framerate.
timelineframe : رقم الإطار الحالي نسبةً إلى الجدول الزمني بأكمله [للقراءة فقط]
* obj.frame هو إطار نسبي من بداية الكائن،
بينما هذا إطار مطلق من بداية الجدول الزمني.
timelinetime : الوقت الحالي بالثواني نسبةً إلى الجدول الزمني بأكمله [للقراءة فقط]
layer : رقم الطبقة التي يوجد فيها الكائن [للقراءة فقط]
* نفس قيمة obj.layer.
obj : جدول معلومات الكائن (راجع «جدول obj» أدناه)
scene : جدول معلومات المشهد (راجع «جدول scene» أدناه)
ymm4 : YMM4 specific meta-information table (see "ymm4 Table" below)
anim : Animation utility table (see "anim Table" below)
- جدول scene -
scene.width : الدقة الأفقية (بكسل) للمشهد (المشروع) [للقراءة فقط]
scene.height : الدقة الرأسية (بكسل) للمشهد (المشروع) [للقراءة فقط]
- جدول obj - المتغيرات -
تحتفظ المتغيرات التالية بمعلومات الرسم الحالية للكائن.
* المتغيرات غير المحددة بـ «للقراءة فقط» يمكن تعديلها في النص البرمجي، وتنعكس القيم المعدّلة في الرسم.
○ الإحداثيات والإزاحة
obj.x : إحداثي X المرجعي للعرض [للقراءة فقط]
* يعادل «إحداثي X المرجعي للعرض» في مواصفات AviUtl2.
* التعديلات داخل النص البرمجي لا تُقرأ مجدداً وليس لها تأثير.
* يُعيَّن داخلياً من DrawDescription.Draw.X؛
تسري التغييرات بعد تنفيذ النص البرمجي.
obj.y : إحداثي Y المرجعي للعرض [ما يعادل للقراءة فقط]
* يُعيَّن داخلياً من DrawDescription.Draw.Y.
obj.z : إحداثي Z المرجعي للعرض [ما يعادل للقراءة فقط]
* يُعيَّن داخلياً من DrawDescription.Draw.Z.
obj.ox : إزاحة المركز X (قابل للتعديل)
* يُعيَّن داخلياً من DrawDescription.CenterPoint.X (inDesc).
* يعادل «الإحداثي X النسبي من المرجع (obj.ox)» في AviUtl2،
لكنه يُعامَل في هذا المكوِّن الإضافي كـ CenterPoint (إزاحة نقطة المركز).
obj.oy : إزاحة المركز Y (قابل للتعديل)
* يُعيَّن داخلياً من DrawDescription.CenterPoint.Y (inDesc).
○ التكبير والتحويل
obj.zoom : عامل التكبير (قابل للتعديل)
* 1.0 هو المقياس الطبيعي (وليس 0.0)، متوافق مع AviUtl2.
* يُحسب داخلياً كمتوسط ZoomX و ZoomY (zoomAvg).
* في المخرجات يُوسَّع إلى تكبير X/Y الفردي كـ obj.zoom * (1 ± obj.aspect).
obj.aspect : نسبة العرض إلى الارتفاع (قابل للتعديل)، النطاق: -1.0 ~ 1.0
* القيم الموجبة تقلّص في اتجاه X؛ القيم السالبة في اتجاه Y.
* يُحسب داخلياً كـ (ZoomX - ZoomY) / (ZoomX + ZoomY).
obj.sx : Scale factor in X direction (writable) 1.0 = 100%
* Precise independent scale control specific to YMM4.
* Takes precedence over zoom/aspect modifications.
obj.sy : Scale factor in Y direction (writable) 1.0 = 100%
* Precise independent scale control specific to YMM4.
* Takes precedence over zoom/aspect modifications.
obj.alpha : العتامة (قابل للتعديل)، النطاق: 0.0 ~ 255.0
* يستخدم AviUtl2 النطاق 0.0~1.0، لكن هذا المكوِّن يستخدم 0.0~255.0.
* يُعيَّن داخلياً من DrawDescription.Opacity * 255.
* يُقسم على 255 ويُعيَّد تطبيعه إلى 0.0~1.0 في المخرجات (مع Clamp).
* النص البرمجي الافتراضي يضبط obj.alpha = math.min(time * 255, 255)،
مما يوفر تطبيقاً افتراضياً للتلاشي التدريجي (fade-in).
○ الدوران
obj.rx : زاوية الدوران حول محور X (قابل للتعديل)، الوحدة: درجة (°)، 360.0 = دورة كاملة
* يُعيَّن داخلياً من DrawDescription.Rotation.X.
obj.ry : زاوية الدوران حول محور Y (قابل للتعديل)، الوحدة: درجة (°)، 360.0 = دورة كاملة
* يُعيَّن داخلياً من DrawDescription.Rotation.Y.
obj.rz : زاوية الدوران حول محور Z (قابل للتعديل)، الوحدة: درجة (°)، 360.0 = دورة كاملة
* يُعيَّن داخلياً من DrawDescription.Rotation.Z.
obj.rxr : Rotation angle around X axis in radians (writable)
* Takes precedence if rx is also modified simultaneously.
obj.ryr : Rotation angle around Y axis in radians (writable)
* Takes precedence if ry is also modified simultaneously.
obj.rzr : Rotation angle around Z axis in radians (writable)
* Takes precedence if rz is also modified simultaneously.
○ حجم الصورة
obj.w : عرض الصورة المدخلة بالبكسل [للقراءة فقط]
* داخلياً عدد صحيح مشتق من D2D GetImageLocalBounds.
obj.h : ارتفاع الصورة المدخلة بالبكسل [للقراءة فقط]
* داخلياً عدد صحيح مشتق من D2D GetImageLocalBounds.
obj.hw : Half of the input image width (= obj.w / 2) [ReadOnly]
obj.hh : Half of the input image height (= obj.h / 2) [ReadOnly]
obj.diagonal : طول القطر للصورة المدخلة (= math.sqrt(w*w + h*h)) [ReadOnly]
obj.cx : إحداثي X لمركز الصورة (= obj.w / 2) [للقراءة فقط]
* إحداثي المركز المرجعي لعمليات البكسل.
obj.cy : إحداثي Y لمركز الصورة (= obj.h / 2) [للقراءة فقط]
○ الوقت والإطار
obj.time : الوقت الحالي بالثواني نسبةً إلى الكائن [للقراءة فقط]
* نفس قيمة المتغير العام time.
* يُعيَّن داخلياً من EffectDescription.ItemPosition.Time.TotalSeconds.
obj.frame : رقم الإطار الحالي نسبةً إلى الكائن [للقراءة فقط]
* نفس قيمة المتغير العام frame.
* يُعيَّن داخلياً من EffectDescription.ItemPosition.Frame.
obj.totalframe: إجمالي عدد إطارات الكائن [للقراءة فقط]
* نفس قيمة المتغير العام totalframe.
* يُعيَّن داخلياً من EffectDescription.ItemDuration.Frame.
obj.framerate : معدل الإطارات (إطار/ثانية) [للقراءة فقط]
* نفس قيمة المتغير العام framerate.
* يُعيَّن داخلياً من EffectDescription.FPS.
○ أشرطة التتبع
obj.track0 : القيمة الحالية لـ Track0 في لوح التأثيرات [للقراءة فقط]
* القيمة بعد استيفاء الرسوم المتحركة.
obj.track1 : القيمة الحالية لـ Track1 في لوح التأثيرات [للقراءة فقط]
obj.track2 : القيمة الحالية لـ Track2 في لوح التأثيرات [للقراءة فقط]
obj.track3 : القيمة الحالية لـ Track3 في لوح التأثيرات [للقراءة فقط]
○ الطبقة
obj.layer : رقم الطبقة التي يوجد فيها الكائن [للقراءة فقط]
* نفس قيمة المتغير العام layer.
* يُعيَّن داخلياً من EffectDescription.Layer.
- جدول obj - تعديل المتغيرات وانعكاسها في الرسم -
بعد تنفيذ النص البرمجي، تُقرأ المتغيرات التالية فقط مجدداً في معلومات الرسم (تُطبَّق).
المتغيرات المُطبَّقة:
obj.x, obj.y, obj.z
obj.ox, obj.oy
obj.zoom, obj.aspect
obj.alpha
obj.rx, obj.ry, obj.rz
* obj.w, obj.h, obj.cx, obj.cy, obj.frame, obj.time,
obj.totalframe, obj.framerate, obj.track0 ~ obj.track3,
obj.layer للقراءة فقط ولن تنعكس التغييرات في الرسم.
صيغ حساب قيم المخرجات:
ZoomX = obj.zoom * (1.0 + obj.aspect)
ZoomY = obj.zoom * (1.0 - obj.aspect)
Opacity = Clamp(obj.alpha / 255.0, 0.0, 1.0)
Draw = (obj.x, obj.y, obj.z)
CenterPoint = (obj.ox, obj.oy)
Rotation = (obj.rx, obj.ry, obj.rz)
- جدول obj - الدوال -
○ obj.getpixel(x, y)
يسترد معلومات البكسل عند الإحداثيات المحددة.
* تحدث نقل بيانات الصورة من GPU إلى CPU عند الاستدعاء الأول (مع عبء معالجة).
* تستخدم إحداثيات البكسل الزاوية العلوية اليسرى للصورة كـ (0, 0)، مع اليمين والأسفل كقيم موجبة.
* القيم المُعادة هي معادلات ألفا مباشر محوَّلة من ألفا مُضاعف مسبقاً.
x : إحداثي X (0 ~ obj.w - 1)
y : إحداثي Y (0 ~ obj.h - 1)
يُعيد : 4 قيم r, g, b, a (إعادة متعددة القيم)
r = مكوِّن الأحمر (0.0 ~ 255.0)
g = مكوِّن الأخضر (0.0 ~ 255.0)
b = مكوِّن الأزرق (0.0 ~ 255.0)
a = قيمة ألفا (0.0 ~ 255.0)
* يُعيد (0, 0, 0, 0) للإحداثيات خارج النطاق.
مثال: r, g, b, a = obj.getpixel(10, 20)
○ obj.setpixel(x, y, r, g, b [, a])
يكتب فوق معلومات البكسل عند الإحداثيات المحددة.
* تُحدَّد بيانات البكسل تلقائياً كـ «معدَّلة» عند الاستدعاء،
وتُخرج الصورة المعدَّلة بعد انتهاء النص البرمجي.
* يُخزَّن داخلياً بتنسيق ألفا مُضاعف مسبقاً (BGRA).
يُجرى تحويل premultiplied عند setpixel.
x : إحداثي X (0 ~ obj.w - 1)
y : إحداثي Y (0 ~ obj.h - 1)
r : مكوِّن الأحمر (0.0 ~ 255.0)
g : مكوِّن الأخضر (0.0 ~ 255.0)
b : مكوِّن الأزرق (0.0 ~ 255.0)
a : قيمة ألفا (الافتراضي: 255.0)
مثال: obj.setpixel(10, 20, 255, 0, 0, 128)
○ obj.getpixeldata()
يُعيد كائن وكيل للوصول المجمَّع إلى جميع بيانات البكسل.
* معالجة أسرع للبكسل مقارنةً بـ getpixel/setpixel.
* تحدث نقل بيانات الصورة من GPU إلى CPU عند الاستدعاء الأول (مع عبء معالجة).
يُعيد : كائن PixelDataProxy
.width : عرض الصورة بالبكسل (= obj.w)
.height : ارتفاع الصورة بالبكسل (= obj.h)
:get(index) : الحصول على قيمة القناة بالفهرس
:set(index, value) : تعيين قيمة القناة بالفهرس
مواصفات الفهرس:
الفهارس تبدأ من 1 (اتباعاً لتقليد Lua).
ترتيب القنوات هو R, G, B, A متكرراً.
فهرس قناة R للبكسل pixel(x, y) =
(y * obj.w + x) * 4 + 1
فهرس قناة G للبكسل pixel(x, y) =
(y * obj.w + x) * 4 + 2
فهرس قناة B للبكسل pixel(x, y) =
(y * obj.w + x) * 4 + 3
فهرس قناة A للبكسل pixel(x, y) =
(y * obj.w + x) * 4 + 4
* تعديل ألفا (القناة 4) سيُحوِّل RGB أيضاً بالتناسب.
* تعديل قنوات RGB سيُطبِّق تحويل premultiplied.
* القيم المُسترجَعة هي معادلات ألفا مباشر، مثل get(index).
مثال:
local pd = obj.getpixeldata()
local idx = (10 * obj.w + 20) * 4 + 1 -- قناة R لـ (x=20, y=10)
local r = pd:get(idx)
pd:set(idx, 128)
○ obj.putpixeldata()
دالة فارغة (بلا عملية) مُعرَّفة للتوافق.
* تُستخدم getpixeldata/putpixeldata معاً في نصوص AviUtl،
لكن في هذا المكوِّن الإضافي تنعكس التغييرات عبر setpixel/set تلقائياً،
لذا لا داعي لاستدعاء هذه الدالة.
- ymm4 Table -
Table holding YMM4-specific meta-information. All values are ReadOnly.
ymm4.group_index : Current item index within a group control (0-based)
ymm4.group_count : Total number of items within a group control
ymm4.group_ratio : Progress ratio within the group (group_index / group_count)
ymm4.timeline_totalframe: Total number of frames for the entire timeline
ymm4.timeline_totaltime : Total time in seconds for the entire timeline
ymm4.time_ratio : Current playback position ratio (0.0 ~ 1.0)
ymm4.is_saving : Whether video is currently being exported (true only during export)
ymm4.is_playing : Whether the timeline is currently playing (true only during playback)
ymm4.is_paused : Whether the timeline is currently paused (true only when paused)
ymm4.scene_id : Unique ID (Guid string) of the current scene
- anim Table -
Pure utility functions and constants useful for animation calculations.
anim.tau : 2 * Pi (math.pi * 2)
anim.e : العدد النيبيري (math.exp(1))
anim.phi : النسبة الذهبية ((1 + math.sqrt(5)) / 2)
anim.sqrt2 : الجذر التربيعي لـ 2 (math.sqrt(2))
anim.lerp(a, b, t) : Linear interpolation between a and b by t (0.0 ~ 1.0)
anim.smoothstep(e0, e1, x): Smooth Hermite interpolation between e0 and e1
anim.smootherstep(e0, e1, x): استيفاء هيرميت أكثر سلاسة بين e0 و e1 (مستمر حتى المشتقة الثانية)
anim.clamp(v, lo, hi) : Clamps value v between lo and hi
anim.map(v, a1, b1, a2, b2): Maps value v from range a1~b1 to range a2~b2
anim.norm(v, lo, hi) : Gets the normalized ratio (0.0 ~ 1.0) of v within lo~hi
anim.wrap(v, lo, hi) : Wraps value v to loop within the range lo~hi
anim.pingpong(t, len) : Value that bounces back and forth between 0 and len
anim.sign(v) : Gets the sign of v (1 for positive, -1 for negative, 0 for zero)
anim.oscillate(t, lo, hi, freq): Smoothly oscillates between lo and hi at the given freq (sine wave)
anim.triangle(t, freq) : Triangle wave oscillating between 0.0 and 1.0 at the given freq
anim.square(t, freq) : Square wave switching between 1.0 and 0.0 at the given freq
anim.duration(t, dur) : Current ratio over duration dur (0.0 ~ 1.0, clamped)
anim.delay(t, d) : Time starting after delay d (0 if negative)
anim.ease_in(t) : Quadratic ease-in (acceleration)
anim.ease_out(t) : Quadratic ease-out (deceleration)
anim.ease_in_out(t) : تخفيف الدخول والخروج التربيعي (تسارع ثم تباطؤ)
anim.elastic(t) : Bouncy spring easing
anim.back(t) : Easing that slightly overshoots before returning
anim.step(edge, x) : Returns 1.0 if x >= edge, otherwise 0.0
anim.fract(v) : Gets only the fractional part of v
anim.bounce(t) : Bouncing ease effect
anim.hsv_to_rgb(h, s, v): Converts HSV (Hue 0~360, Saturation 0~1, Value 0~1) to RGB (0~255)
anim.rgb_to_hsv(r, g, b): Converts RGB (0~255) to HSV
anim.noise(x, y, z) : 1D to 3D continuous smooth noise (-1.0 ~ 1.0)
anim.rand(min, max, s) : Stable random value based on seed `s`
anim.len(x, y) : الحصول على طول (معيار) المتجه (x, y)
anim.dist(x1, y1, x2, y2): الحصول على المسافة بين نقطتين (x1, y1) و (x2, y2)
anim.dot(x1, y1, x2, y2): الحصول على حاصل الضرب النقطي لمتجهين (x1, y1) و (x2, y2)
anim.normalize(x, y) : تطبيع المتجه (x, y) وإرجاع متجه الاتجاه (Tuple)
anim.polar(r, a) : Converts polar coordinates (radius, angle) to (x, y) tuple
anim.rotate(x, y, a) : Rotates 2D point (x, y) by angle `a` (degrees) returning (x, y) tuple
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
- المكتبات القياسية المتاحة -
مكتبة math:
math.abs, math.ceil, math.cos, math.exp, math.floor,
math.fmod, math.huge, math.log, math.max, math.min,
math.modf, math.pi, math.random, math.randomseed,
math.sin, math.sqrt, math.tan, math.atan, math.atan2,
math.deg, math.rad, math.ldexp, math.frexp,
math.sinh, math.cosh, math.tanh, math.type,
math.tointeger, math.maxinteger, math.mininteger
مكتبة string:
string.format, string.len, string.sub, string.upper,
string.lower, string.rep, string.reverse, string.find,
string.match, string.gmatch, string.gsub, string.byte,
string.char, string.dump, string.pack, string.unpack,
string.packsize
مكتبة table:
table.insert, table.remove, table.sort,
table.concat, table.unpack, table.move
مكتبة bit32:
bit32.band, bit32.bor, bit32.bxor, bit32.bnot,
bit32.lshift, bit32.rshift, bit32.arshift,
bit32.extract, bit32.replace,
bit32.btest, bit32.countlz, bit32.countrz
الدوال الأساسية:
type, tostring, tonumber, select, error, assert, print,
ipairs, pairs, next, unpack,
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen,
pcall, xpcall
- أمثلة على النصوص البرمجية -
○ تلاشٍ تدريجي للظهور - fade-in (النص الافتراضي)
obj.alpha = math.min(time * 255, 255)
○ تلاشٍ تدريجي للاختفاء - fade-out
obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)
○ التحكم في العتامة بـ Track0
obj.alpha = obj.track0
○ الدوران مع مرور الوقت
obj.rz = time * 90 -- 90 درجة في الثانية
○ عكس المكوِّن الأحمر للبكسلات
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 - r, g, b, a)
end
end
○ تحويل إلى تدرج الرمادي باستخدام getpixeldata (سريع)
local pd = obj.getpixeldata()
local w = pd.width
local h = pd.height
for y = 0, h - 1 do
for x = 0, w - 1 do
local base = (y * w + x) * 4
local r = pd:get(base + 1)
local g = pd:get(base + 2)
local b = pd:get(base + 3)
local a = pd:get(base + 4)
local gray = r * 0.299 + g * 0.587 + b * 0.114
pd:set(base + 1, gray)
pd:set(base + 2, gray)
pd:set(base + 3, gray)
end
end
○ التحكم في التكبير بـ Track0 (1.0 = المقياس الطبيعي)
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- الميزات غير المدعومة / القيود -
× obj.effect()، obj.draw()، obj.drawpoly()، obj.load() وما شابه من AviUtl2 غير مدعومة.
× obj.rand()، obj.rand1()، obj.setfont()، obj.mes() وما شابه من AviUtl2 غير مدعومة.
× obj.setoption()، obj.getoption()، obj.getvalue()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
× الدوال مثل scene.set() و scene.get() في جدول scene الخاص بـ AviUtl2 غير مدعومة.
(يمكن قراءة scene.width و scene.height فقط)
× الوصول إلى الملفات (require, dofile, io وما شابه) غير مدعوم.
× تعديل obj.z ينعكس في الرسم (مضمَّن في ReadBack)،
لكن دعم الرسم ثلاثي الأبعاد محدود.
× إذا تجاوز النص البرمجي مهلة الانتهاء (5 ثوانٍ)، يُنهى التنفيذ قسراً.
يجب الانتباه في التطبيق لتجنب الحلقات اللانهائية.
× توجيهات الترويسة من AviUtl2 مثل --track@ و --check@ غير مدعومة.
يمكن استخدام Track0 ~ Track3 فقط كمعاملات.
+416
ファイルの表示
@@ -0,0 +1,416 @@
- About the Lua Script Effect -
The "Lua Script" video effect in YukkuriMovieMaker4 uses
the Lua language for scripting.
The scripting engine is MoonSharp (Lua 5.2 compatible).
* This effect is a custom implementation and differs from the AviUtl2 script specification.
* This is a separate specification from AviUtl2 script files (*.anm2, etc.).
* Since IsAviUtlSupported = false, EXO output for AviUtl is not supported.
- Notes -
o The script execution engine is MoonSharp (Lua 5.2 compatible).
o Available standard libraries are limited to the following:
table, string, math, bit32
* io, os, debug, ffi, require, etc. are not available.
o Script timeout is 5000ms (5 seconds).
On timeout, execution is forcibly terminated and treated as an error.
o Scripts cannot access the file system (including require).
o Calling external scripts from within a script is not supported.
o Pixel operations (getpixel/setpixel/getpixeldata) access the actual input image,
so a GPU->CPU data transfer occurs only on the first access.
Omitting these calls when unnecessary will speed up processing.
- Parameters -
The effect panel has 4 trackbars (animation-enabled) as follows.
Each value can be referenced in the script as obj.track0 through obj.track3.
Track0 : Parameter 0 (Default: 0, Range: Min ~ Max)
Track1 : Parameter 1 (Default: 0, Range: Min ~ Max)
Track2 : Parameter 2 (Default: 0, Range: Min ~ Max)
Track3 : Parameter 3 (Default: 0, Range: Min ~ Max)
* Each trackbar supports animation sliders (with interpolation).
* .lua files can be imported/exported from the script editor toolbar.
- Global Variables -
The following variables can be referenced directly in the global scope of the script.
time : Current time in seconds relative to the object [ReadOnly]
* Same value as obj.time.
frame : Current frame number relative to the object [ReadOnly]
* Same value as obj.frame.
totalframe : Total number of frames in the object [ReadOnly]
* Same value as obj.totalframe.
framerate : Frame rate (fps) [ReadOnly]
* Same value as obj.framerate.
timelineframe : Current frame number relative to the entire timeline [ReadOnly]
* obj.frame is a relative frame from the start of the object,
while this is the absolute frame from the start of the timeline.
timelinetime : Current time in seconds relative to the entire timeline [ReadOnly]
layer : Layer number where the object is placed [ReadOnly]
* Same value as obj.layer.
obj : Object information table (see "obj Table" below)
scene : Scene information table (see "scene Table" below)
ymm4 : YMM4 specific meta-information table (see "ymm4 Table" below)
anim : Animation utility table (see "anim Table" below)
- scene Table -
scene.width : Horizontal resolution (pixels) of the scene (project) [ReadOnly]
scene.height : Vertical resolution (pixels) of the scene (project) [ReadOnly]
scene.cx : Half of the scene's horizontal resolution (= scene.width / 2) [ReadOnly]
scene.cy : Half of the scene's vertical resolution (= scene.height / 2) [ReadOnly]
- obj Table - Variables -
The following variables hold the current rendering information of the object.
* Variables not marked ReadOnly can be modified in the script, and the changes will be reflected in rendering.
o Position / Offset
obj.x : Display reference coordinate X [ReadOnly]
* Corresponds to "Display Reference X" in AviUtl2 specification.
* Changes made inside the script are not read back and have no effect.
* Internally set from DrawDescription.Draw.X;
changes take effect after the script runs.
obj.y : Display reference coordinate Y [ReadOnly equivalent]
* Internally set from DrawDescription.Draw.Y.
obj.z : Display reference coordinate Z [ReadOnly equivalent]
* Internally set from DrawDescription.Draw.Z.
obj.ox : Center offset X (writable)
* Internally set from DrawDescription.CenterPoint.X (inDesc).
* Corresponds to "Relative X from reference coordinate (obj.ox)" in AviUtl2,
but in this plugin it is treated as CenterPoint (center point offset).
obj.oy : Center offset Y (writable)
* Internally set from DrawDescription.CenterPoint.Y (inDesc).
o Scale / Transform
obj.zoom : Scale factor (writable)
* 1.0 is 100% scale (not 0.0), compatible with AviUtl2.
* Internally calculated as the average of ZoomX and ZoomY (zoomAvg).
* On output, expanded to individual X/Y zoom as obj.zoom * (1 ± obj.aspect).
obj.aspect : Aspect ratio (writable), Range: -1.0 ~ 1.0
* Positive values shrink in X direction; negative values shrink in Y direction.
* Internally calculated as (ZoomX - ZoomY) / (ZoomX + ZoomY).
obj.sx : Scale factor in X direction (writable) 1.0 = 100%
* Precise independent scale control specific to YMM4.
* Takes precedence over zoom/aspect modifications.
obj.sy : Scale factor in Y direction (writable) 1.0 = 100%
* Precise independent scale control specific to YMM4.
* Takes precedence over zoom/aspect modifications.
obj.alpha : Opacity (writable), Range: 0.0 ~ 255.0
* AviUtl2 uses 0.0~1.0, but this plugin uses 0.0~255.0.
* Internally set from DrawDescription.Opacity * 255.
* Divided by 255 and normalized to 0.0~1.0 on output (with Clamp).
* The default script sets obj.alpha = math.min(time * 255, 255),
providing a default fade-in implementation.
o Rotation
obj.rx : Rotation angle around X axis (writable), Unit: degrees (°), 360.0 = one full rotation
* Internally set from DrawDescription.Rotation.X.
obj.ry : Rotation angle around Y axis (writable), Unit: degrees (°), 360.0 = one full rotation
* Internally set from DrawDescription.Rotation.Y.
obj.rz : Rotation angle around Z axis (writable), Unit: degrees (°), 360.0 = one full rotation
* Internally set from DrawDescription.Rotation.Z.
obj.rxr : Rotation angle around X axis in radians (writable)
* Takes precedence if rx is also modified simultaneously.
obj.ryr : Rotation angle around Y axis in radians (writable)
* Takes precedence if ry is also modified simultaneously.
obj.rzr : Rotation angle around Z axis in radians (writable)
* Takes precedence if rz is also modified simultaneously.
o Image Size
obj.w : Width of the input image in pixels [ReadOnly]
* Internally an integer derived from D2D GetImageLocalBounds.
obj.h : Height of the input image in pixels [ReadOnly]
* Internally an integer derived from D2D GetImageLocalBounds.
obj.hw : Half of the input image width (= obj.w / 2) [ReadOnly]
obj.hh : Half of the input image height (= obj.h / 2) [ReadOnly]
obj.diagonal : Diagonal length of the input image (= math.sqrt(w*w + h*h)) [ReadOnly]
obj.cx : Center X coordinate of the image (= obj.w / 2) [ReadOnly]
* Reference center coordinate for pixel operations.
obj.cy : Center Y coordinate of the image (= obj.h / 2) [ReadOnly]
o Time / Frame
obj.time : Current time in seconds relative to the object [ReadOnly]
* Same value as global variable time.
* Internally set from EffectDescription.ItemPosition.Time.TotalSeconds.
obj.frame : Current frame number relative to the object [ReadOnly]
* Same value as global variable frame.
* Internally set from EffectDescription.ItemPosition.Frame.
obj.totalframe: Total number of frames in the object [ReadOnly]
* Same value as global variable totalframe.
* Internally set from EffectDescription.ItemDuration.Frame.
obj.t : Current time progress ratio within the object (0.0 ~ 1.0) [ReadOnly]
obj.framerate : Frame rate (fps) [ReadOnly]
* Same value as global variable framerate.
* Internally set from EffectDescription.FPS.
o Trackbars
obj.track0 : Current value of Track0 in the effect panel [ReadOnly]
* Value after animation interpolation.
obj.track1 : Current value of Track1 in the effect panel [ReadOnly]
obj.track2 : Current value of Track2 in the effect panel [ReadOnly]
obj.track3 : Current value of Track3 in the effect panel [ReadOnly]
o Layer
obj.layer : Layer number where the object is placed [ReadOnly]
* Same value as global variable layer.
* Internally set from EffectDescription.Layer.
- obj Table - Variable Changes and Rendering Reflection -
After script execution, only the following variables are read back into rendering (applied).
Applied variables:
obj.x, obj.y, obj.z
obj.ox, obj.oy
obj.zoom, obj.aspect
obj.alpha
obj.rx, obj.ry, obj.rz
* obj.w, obj.h, obj.cx, obj.cy, obj.frame, obj.time,
obj.totalframe, obj.framerate, obj.track0 ~ obj.track3,
obj.layer are ReadOnly and changes will not be reflected in rendering.
Output value formulas:
ZoomX = obj.zoom * (1.0 + obj.aspect)
ZoomY = obj.zoom * (1.0 - obj.aspect)
Opacity = Clamp(obj.alpha / 255.0, 0.0, 1.0)
Draw = (obj.x, obj.y, obj.z)
CenterPoint = (obj.ox, obj.oy)
Rotation = (obj.rx, obj.ry, obj.rz)
- obj Table - Functions -
o obj.getpixel(x, y)
Retrieves pixel information at the specified coordinates.
* A GPU->CPU image data transfer occurs on the first call (involves processing overhead).
* Pixel coordinates use the top-left of the image as (0, 0), with right and down as positive.
* The returned values are straight alpha equivalents converted from premultiplied alpha.
x : X coordinate (0 ~ obj.w - 1)
y : Y coordinate (0 ~ obj.h - 1)
Returns : 4 values r, g, b, a (multiple return values)
r = Red component (0.0 ~ 255.0)
g = Green component (0.0 ~ 255.0)
b = Blue component (0.0 ~ 255.0)
a = Alpha value (0.0 ~ 255.0)
* Returns (0, 0, 0, 0) for out-of-range coordinates.
Example: r, g, b, a = obj.getpixel(10, 20)
o obj.setpixel(x, y, r, g, b [, a])
Overwrites pixel information at the specified coordinates.
* The pixel data is automatically marked as "modified" on call,
and the modified image is output after the script ends.
* Stored internally in premultiplied alpha format (BGRA).
A premultiplied conversion is performed on setpixel.
x : X coordinate (0 ~ obj.w - 1)
y : Y coordinate (0 ~ obj.h - 1)
r : Red component (0.0 ~ 255.0)
g : Green component (0.0 ~ 255.0)
b : Blue component (0.0 ~ 255.0)
a : Alpha value (default: 255.0)
Example: obj.setpixel(10, 20, 255, 0, 0, 128)
o obj.getpixeldata()
Returns a proxy object for bulk access to all pixel data.
* Faster pixel manipulation compared to getpixel/setpixel.
* A GPU->CPU image data transfer occurs on the first call (involves processing overhead).
Returns : PixelDataProxy object
.width : Width of the image in pixels (= obj.w)
.height : Height of the image in pixels (= obj.h)
:get(index) : Get channel value by index
:set(index, value) : Set channel value by index
Index specification:
Indices are 1-based (following Lua convention).
Channel order is R, G, B, A repeating.
R channel index for pixel(x, y) =
(y * obj.w + x) * 4 + 1
G channel index for pixel(x, y) =
(y * obj.w + x) * 4 + 2
B channel index for pixel(x, y) =
(y * obj.w + x) * 4 + 3
A channel index for pixel(x, y) =
(y * obj.w + x) * 4 + 4
* Modifying the alpha (channel 4) will also proportionally convert RGB.
* Modifying RGB channels will apply a premultiplied conversion.
* Retrieved values are straight alpha equivalents, same as get(index).
Example:
local pd = obj.getpixeldata()
local idx = (10 * obj.w + 20) * 4 + 1 -- R channel of (x=20, y=10)
local r = pd:get(idx)
pd:set(idx, 128)
o obj.putpixeldata()
An empty (no-op) function defined for compatibility.
* In AviUtl scripts, getpixeldata/putpixeldata are used together,
but in this plugin changes via setpixel/set are automatically applied,
so calling this function is unnecessary.
- ymm4 Table -
Table holding YMM4-specific meta-information. All values are ReadOnly.
ymm4.group_index : Current item index within a group control (0-based)
ymm4.group_count : Total number of items within a group control
ymm4.group_ratio : Progress ratio within the group (group_index / group_count)
ymm4.timeline_totalframe: Total number of frames for the entire timeline
ymm4.timeline_totaltime : Total time in seconds for the entire timeline
ymm4.time_ratio : Current playback position ratio (0.0 ~ 1.0)
ymm4.is_saving : Whether video is currently being exported (true only during export)
ymm4.is_playing : Whether the timeline is currently playing (true only during playback)
ymm4.is_paused : Whether the timeline is currently paused (true only when paused)
ymm4.scene_id : Unique ID (Guid string) of the current scene
- anim Table -
Pure utility functions and constants useful for animation calculations.
anim.tau : 2 * Pi (math.pi * 2)
anim.e : Euler's number (math.exp(1))
anim.phi : Golden ratio ((1 + math.sqrt(5)) / 2)
anim.sqrt2 : Square root of 2 (math.sqrt(2))
anim.lerp(a, b, t) : Linear interpolation between a and b by t (0.0 ~ 1.0)
anim.smoothstep(e0, e1, x): Smooth Hermite interpolation between e0 and e1
anim.smootherstep(e0, e1, x): Smoother Hermite interpolation between e0 and e1 (continuous 2nd derivative)
anim.clamp(v, lo, hi) : Clamps value v between lo and hi
anim.map(v, a1, b1, a2, b2): Maps value v from range a1~b1 to range a2~b2
anim.norm(v, lo, hi) : Gets the normalized ratio (0.0 ~ 1.0) of v within lo~hi
anim.wrap(v, lo, hi) : Wraps value v to loop within the range lo~hi
anim.pingpong(t, len) : Value that bounces back and forth between 0 and len
anim.sign(v) : Gets the sign of v (1 for positive, -1 for negative, 0 for zero)
anim.oscillate(t, lo, hi, freq): Smoothly oscillates between lo and hi at the given freq (sine wave)
anim.triangle(t, freq) : Triangle wave oscillating between 0.0 and 1.0 at the given freq
anim.square(t, freq) : Square wave switching between 1.0 and 0.0 at the given freq
anim.duration(t, dur) : Current ratio over duration dur (0.0 ~ 1.0, clamped)
anim.delay(t, d) : Time starting after delay d (0 if negative)
anim.ease_in(t) : Quadratic ease-in (acceleration)
anim.ease_out(t) : Quadratic ease-out (deceleration)
anim.ease_in_out(t) : Quadratic ease-in-out (acceleration then deceleration)
anim.elastic(t) : Bouncy spring easing
anim.back(t) : Easing that slightly overshoots before returning
anim.step(edge, x) : Returns 1.0 if x >= edge, otherwise 0.0
anim.fract(v) : Gets only the fractional part of v
anim.bounce(t) : Bouncing ease effect
anim.hsv_to_rgb(h, s, v): Converts HSV (Hue 0~360, Saturation 0~1, Value 0~1) to RGB (0~255)
anim.rgb_to_hsv(r, g, b): Converts RGB (0~255) to HSV
anim.noise(x, y, z) : 1D to 3D continuous smooth noise (-1.0 ~ 1.0)
anim.rand(min, max, s) : Stable random value based on seed `s`
anim.len(x, y) : Gets the length (norm) of the vector (x, y)
anim.dist(x1, y1, x2, y2): Gets the distance between two points (x1, y1) and (x2, y2)
anim.dot(x1, y1, x2, y2): Gets the dot product of two vectors (x1, y1) and (x2, y2)
anim.normalize(x, y) : Normalizes the vector (x, y) returning a direction vector tuple
anim.polar(r, a) : Converts polar coordinates (radius, angle) to (x, y) tuple
anim.rotate(x, y, a) : Rotates 2D point (x, y) by angle `a` (degrees) returning (x, y) tuple
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
- Available Standard Libraries -
math library:
math.abs, math.ceil, math.cos, math.exp, math.floor,
math.fmod, math.huge, math.log, math.max, math.min,
math.modf, math.pi, math.random, math.randomseed,
math.sin, math.sqrt, math.tan, math.atan, math.atan2,
math.deg, math.rad, math.ldexp, math.frexp,
math.sinh, math.cosh, math.tanh, math.type,
math.tointeger, math.maxinteger, math.mininteger
string library:
string.format, string.len, string.sub, string.upper,
string.lower, string.rep, string.reverse, string.find,
string.match, string.gmatch, string.gsub, string.byte,
string.char, string.dump, string.pack, string.unpack,
string.packsize
table library:
table.insert, table.remove, table.sort,
table.concat, table.unpack, table.move
bit32 library:
bit32.band, bit32.bor, bit32.bxor, bit32.bnot,
bit32.lshift, bit32.rshift, bit32.arshift,
bit32.extract, bit32.replace,
bit32.btest, bit32.countlz, bit32.countrz
Basic functions:
type, tostring, tonumber, select, error, assert, print,
ipairs, pairs, next, unpack,
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen,
pcall, xpcall
- Script Examples -
o Fade in (default script)
obj.alpha = math.min(time * 255, 255)
o Fade out
obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)
o Control opacity with Track0
obj.alpha = obj.track0
o Rotate over time
obj.rz = time * 90 -- 90 degrees per second
o Invert the red component of pixels
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 - r, g, b, a)
end
end
o Grayscale conversion using getpixeldata (fast)
local pd = obj.getpixeldata()
local w = pd.width
local h = pd.height
for y = 0, h - 1 do
for x = 0, w - 1 do
local base = (y * w + x) * 4
local r = pd:get(base + 1)
local g = pd:get(base + 2)
local b = pd:get(base + 3)
local a = pd:get(base + 4)
local gray = r * 0.299 + g * 0.587 + b * 0.114
pd:set(base + 1, gray)
pd:set(base + 2, gray)
pd:set(base + 3, gray)
end
end
o Control zoom with Track0 (1.0 = 100% scale)
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- Unsupported Features / Limitations -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), etc. from AviUtl2 are not supported.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), etc. from AviUtl2 are not supported.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. from AviUtl2 are not supported.
x Functions such as scene.set() and scene.get() in the AviUtl2 scene table are not supported.
(Only scene.width and scene.height can be read)
x File access (require, dofile, io, etc.) is not supported.
x Modifying obj.z is reflected in rendering (included in ReadBack),
but 3D rendering support is limited.
x If the script timeout (5 seconds) is exceeded, execution is forcibly terminated.
Care must be taken in implementation to prevent infinite loops.
x AviUtl2 header directives such as --track@ and --check@ are not supported.
Only Track0 ~ Track3 can be used as parameters.
+413
ファイルの表示
@@ -0,0 +1,413 @@
- Acerca del efecto de script Lua -
El efecto de video «Script Lua» de YukkuriMovieMaker4 utiliza
el lenguaje Lua para los scripts.
El motor de scripts empleado es MoonSharp (compatible con Lua 5.2).
* Este efecto es una implementación propia y difiere de la especificación de scripts de AviUtl2.
* Tiene una especificación distinta a los archivos de script de AviUtl2 (*.anm2, etc.).
* Dado que IsAviUtlSupported = false, no se admite la salida EXO para AviUtl.
- Notas -
o El motor de ejecución de scripts es MoonSharp (compatible con Lua 5.2).
o Las bibliotecas estándar disponibles se limitan a las siguientes:
table, string, math, bit32
* io, os, debug, ffi, require, etc. no están disponibles.
o El tiempo de espera del script es de 5000 ms (5 segundos).
Al agotarse el tiempo, la ejecución se termina forzosamente y se trata como error.
o Los scripts no pueden acceder al sistema de archivos (incluido require).
o No se admite la llamada a scripts externos desde dentro de un script.
o Las operaciones de píxeles (getpixel/setpixel/getpixeldata) acceden a la imagen de
entrada real, por lo que la transferencia de datos GPU→CPU solo ocurre en el
primer acceso. Omitir estas llamadas cuando no sean necesarias acelera el procesamiento.
- Parámetros -
El panel de efectos tiene los siguientes 4 controles deslizantes (con soporte de animación).
Cada valor puede referenciarse en el script como obj.track0 ~ obj.track3.
Track0 : Parámetro 0 (Predeterminado: 0, Rango: Mínimo ~ Máximo)
Track1 : Parámetro 1 (Predeterminado: 0, Rango: Mínimo ~ Máximo)
Track2 : Parámetro 2 (Predeterminado: 0, Rango: Mínimo ~ Máximo)
Track3 : Parámetro 3 (Predeterminado: 0, Rango: Mínimo ~ Máximo)
* Cada control deslizante es compatible con los deslizadores de animación (con interpolación).
* Los archivos .lua pueden importarse/exportarse desde la barra de herramientas del editor de scripts.
- Variables globales -
Las siguientes variables pueden referenciarse directamente en el ámbito global del script.
time : Tiempo actual en segundos relativo al objeto [Solo lectura]
* Mismo valor que obj.time.
frame : Número de fotograma actual relativo al objeto [Solo lectura]
* Mismo valor que obj.frame.
totalframe : Número total de fotogramas del objeto [Solo lectura]
* Mismo valor que obj.totalframe.
framerate : Velocidad de fotogramas (fps) [Solo lectura]
* Mismo valor que obj.framerate.
timelineframe : Número de fotograma actual relativo a toda la línea de tiempo [Solo lectura]
* obj.frame es un fotograma relativo desde el inicio del objeto,
mientras que este es el fotograma absoluto desde el inicio de la línea de tiempo.
timelinetime : Tiempo actual en segundos relativo a toda la línea de tiempo [Solo lectura]
layer : Número de capa donde se encuentra el objeto [Solo lectura]
* Mismo valor que obj.layer.
obj : Tabla de información del objeto (ver «Tabla obj» a continuación)
scene : Tabla de información de la escena (ver «Tabla scene» a continuación)
ymm4 : YMM4 specific meta-information table (see "ymm4 Table" below)
anim : Animation utility table (see "anim Table" below)
- Tabla scene -
scene.width : Resolución horizontal (píxeles) de la escena (proyecto) [Solo lectura]
scene.height : Resolución vertical (píxeles) de la escena (proyecto) [Solo lectura]
- Tabla obj - Variables -
Las siguientes variables contienen la información de renderizado actual del objeto.
* Las variables no marcadas como Solo lectura pueden modificarse en el script y los cambios se reflejan en el renderizado.
o Coordenadas / Desplazamiento
obj.x : Coordenada X de referencia de visualización [Solo lectura]
* Equivale a «Coordenada X de referencia de visualización» en la especificación de AviUtl2.
* Los cambios realizados dentro del script no se leen de vuelta y no tienen efecto.
* Internamente se establece desde DrawDescription.Draw.X;
los cambios surten efecto después de ejecutar el script.
obj.y : Coordenada Y de referencia de visualización [equivalente a Solo lectura]
* Internamente se establece desde DrawDescription.Draw.Y.
obj.z : Coordenada Z de referencia de visualización [equivalente a Solo lectura]
* Internamente se establece desde DrawDescription.Draw.Z.
obj.ox : Desplazamiento de centro X (modificable)
* Internamente se establece desde DrawDescription.CenterPoint.X (inDesc).
* Equivale a «Coordenada X relativa desde la referencia (obj.ox)» en AviUtl2,
pero en este plugin se trata como CenterPoint (desplazamiento del punto central).
obj.oy : Desplazamiento de centro Y (modificable)
* Internamente se establece desde DrawDescription.CenterPoint.Y (inDesc).
o Escala / Transformación
obj.zoom : Factor de escala (modificable)
* 1.0 es la escala normal (no 0.0), compatible con AviUtl2.
* Internamente se calcula como el promedio de ZoomX y ZoomY (zoomAvg).
* En la salida, se expande al zoom individual de X/Y como obj.zoom * (1 ± obj.aspect).
obj.aspect : Relación de aspecto (modificable), Rango: -1.0 ~ 1.0
* Los valores positivos reducen en la dirección X; los negativos en la dirección Y.
* Internamente se calcula como (ZoomX - ZoomY) / (ZoomX + ZoomY).
obj.sx : Scale factor in X direction (writable) 1.0 = 100%
* Precise independent scale control specific to YMM4.
* Takes precedence over zoom/aspect modifications.
obj.sy : Scale factor in Y direction (writable) 1.0 = 100%
* Precise independent scale control specific to YMM4.
* Takes precedence over zoom/aspect modifications.
obj.alpha : Opacidad (modificable), Rango: 0.0 ~ 255.0
* AviUtl2 usa 0.0~1.0, pero este plugin usa 0.0~255.0.
* Internamente se establece desde DrawDescription.Opacity * 255.
* Se divide por 255 y se normaliza a 0.0~1.0 en la salida (con Clamp).
* El script predeterminado establece obj.alpha = math.min(time * 255, 255),
proporcionando una implementación de fundido de entrada predeterminada.
o Rotación
obj.rx : Ángulo de rotación alrededor del eje X (modificable), Unidad: grados (°), 360.0 = una vuelta completa
* Internamente se establece desde DrawDescription.Rotation.X.
obj.ry : Ángulo de rotación alrededor del eje Y (modificable), Unidad: grados (°), 360.0 = una vuelta completa
* Internamente se establece desde DrawDescription.Rotation.Y.
obj.rz : Ángulo de rotación alrededor del eje Z (modificable), Unidad: grados (°), 360.0 = una vuelta completa
* Internamente se establece desde DrawDescription.Rotation.Z.
obj.rxr : Rotation angle around X axis in radians (writable)
* Takes precedence if rx is also modified simultaneously.
obj.ryr : Rotation angle around Y axis in radians (writable)
* Takes precedence if ry is also modified simultaneously.
obj.rzr : Rotation angle around Z axis in radians (writable)
* Takes precedence if rz is also modified simultaneously.
o Tamaño de imagen
obj.w : Ancho de la imagen de entrada en píxeles [Solo lectura]
* Internamente es un entero derivado de D2D GetImageLocalBounds.
obj.h : Alto de la imagen de entrada en píxeles [Solo lectura]
* Internamente es un entero derivado de D2D GetImageLocalBounds.
obj.hw : Half of the input image width (= obj.w / 2) [ReadOnly]
obj.hh : Half of the input image height (= obj.h / 2) [ReadOnly]
obj.diagonal : Longitud diagonal de la imagen de entrada (= math.sqrt(w*w + h*h)) [ReadOnly]
obj.cx : Coordenada X central de la imagen (= obj.w / 2) [Solo lectura]
* Coordenada central de referencia para operaciones de píxeles.
obj.cy : Coordenada Y central de la imagen (= obj.h / 2) [Solo lectura]
o Tiempo / Fotograma
obj.time : Tiempo actual en segundos relativo al objeto [Solo lectura]
* Mismo valor que la variable global time.
* Internamente se establece desde EffectDescription.ItemPosition.Time.TotalSeconds.
obj.frame : Número de fotograma actual relativo al objeto [Solo lectura]
* Mismo valor que la variable global frame.
* Internamente se establece desde EffectDescription.ItemPosition.Frame.
obj.totalframe: Número total de fotogramas del objeto [Solo lectura]
* Mismo valor que la variable global totalframe.
* Internamente se establece desde EffectDescription.ItemDuration.Frame.
obj.framerate : Velocidad de fotogramas (fps) [Solo lectura]
* Mismo valor que la variable global framerate.
* Internamente se establece desde EffectDescription.FPS.
o Controles deslizantes
obj.track0 : Valor actual de Track0 en el panel de efectos [Solo lectura]
* Valor tras la interpolación de animación.
obj.track1 : Valor actual de Track1 en el panel de efectos [Solo lectura]
obj.track2 : Valor actual de Track2 en el panel de efectos [Solo lectura]
obj.track3 : Valor actual de Track3 en el panel de efectos [Solo lectura]
o Capa
obj.layer : Número de capa donde se encuentra el objeto [Solo lectura]
* Mismo valor que la variable global layer.
* Internamente se establece desde EffectDescription.Layer.
- Tabla obj - Cambios de variables y reflejo en el renderizado -
Tras la ejecución del script, solo las siguientes variables se leen de vuelta al renderizado (se aplican).
Variables aplicadas:
obj.x, obj.y, obj.z
obj.ox, obj.oy
obj.zoom, obj.aspect
obj.alpha
obj.rx, obj.ry, obj.rz
* obj.w, obj.h, obj.cx, obj.cy, obj.frame, obj.time,
obj.totalframe, obj.framerate, obj.track0 ~ obj.track3,
obj.layer son Solo lectura y los cambios no se reflejan en el renderizado.
Fórmulas de valores de salida:
ZoomX = obj.zoom * (1.0 + obj.aspect)
ZoomY = obj.zoom * (1.0 - obj.aspect)
Opacity = Clamp(obj.alpha / 255.0, 0.0, 1.0)
Draw = (obj.x, obj.y, obj.z)
CenterPoint = (obj.ox, obj.oy)
Rotation = (obj.rx, obj.ry, obj.rz)
- Tabla obj - Funciones -
o obj.getpixel(x, y)
Obtiene información del píxel en las coordenadas especificadas.
* Se produce una transferencia de datos de imagen GPU→CPU en la primera llamada (con sobrecarga de procesamiento).
* Las coordenadas de píxel usan la esquina superior izquierda de la imagen como (0, 0), con derecha y abajo como positivos.
* Los valores devueltos son equivalentes al alfa directo convertido desde el alfa premultiplicado.
x : Coordenada X (0 ~ obj.w - 1)
y : Coordenada Y (0 ~ obj.h - 1)
Devuelve: 4 valores r, g, b, a (valores de retorno múltiple)
r = Componente rojo (0.0 ~ 255.0)
g = Componente verde (0.0 ~ 255.0)
b = Componente azul (0.0 ~ 255.0)
a = Valor alfa (0.0 ~ 255.0)
* Devuelve (0, 0, 0, 0) para coordenadas fuera de rango.
Ejemplo: r, g, b, a = obj.getpixel(10, 20)
o obj.setpixel(x, y, r, g, b [, a])
Sobrescribe la información del píxel en las coordenadas especificadas.
* Los datos de píxel se marcan automáticamente como «modificados» al llamar,
y la imagen modificada se emite después de que el script termina.
* Se almacena internamente en formato alfa premultiplicado (BGRA).
Se realiza una conversión premultiplicada en setpixel.
x : Coordenada X (0 ~ obj.w - 1)
y : Coordenada Y (0 ~ obj.h - 1)
r : Componente rojo (0.0 ~ 255.0)
g : Componente verde (0.0 ~ 255.0)
b : Componente azul (0.0 ~ 255.0)
a : Valor alfa (predeterminado: 255.0)
Ejemplo: obj.setpixel(10, 20, 255, 0, 0, 128)
o obj.getpixeldata()
Devuelve un objeto proxy para acceso masivo a todos los datos de píxeles.
* Manipulación de píxeles más rápida en comparación con getpixel/setpixel.
* Se produce una transferencia de datos de imagen GPU→CPU en la primera llamada (con sobrecarga de procesamiento).
Devuelve: Objeto PixelDataProxy
.width : Ancho de la imagen en píxeles (= obj.w)
.height : Alto de la imagen en píxeles (= obj.h)
:get(index) : Obtiene el valor del canal por índice
:set(index, value) : Establece el valor del canal por índice
Especificación de índice:
Los índices empiezan en 1 (siguiendo la convención de Lua).
El orden de canales es R, G, B, A repetido.
Índice del canal R para pixel(x, y) =
(y * obj.w + x) * 4 + 1
Índice del canal G para pixel(x, y) =
(y * obj.w + x) * 4 + 2
Índice del canal B para pixel(x, y) =
(y * obj.w + x) * 4 + 3
Índice del canal A para pixel(x, y) =
(y * obj.w + x) * 4 + 4
* Modificar el alfa (canal 4) también convertirá RGB proporcionalmente.
* Modificar los canales RGB aplicará una conversión premultiplicada.
* Los valores obtenidos son equivalentes al alfa directo, igual que get(index).
Ejemplo:
local pd = obj.getpixeldata()
local idx = (10 * obj.w + 20) * 4 + 1 -- Canal R de (x=20, y=10)
local r = pd:get(idx)
pd:set(idx, 128)
o obj.putpixeldata()
Una función vacía (sin operación) definida por compatibilidad.
* En los scripts de AviUtl se usan getpixeldata/putpixeldata juntos,
pero en este plugin los cambios mediante setpixel/set se aplican automáticamente,
por lo que no es necesario llamar a esta función.
- ymm4 Table -
Table holding YMM4-specific meta-information. All values are ReadOnly.
ymm4.group_index : Current item index within a group control (0-based)
ymm4.group_count : Total number of items within a group control
ymm4.group_ratio : Progress ratio within the group (group_index / group_count)
ymm4.timeline_totalframe: Total number of frames for the entire timeline
ymm4.timeline_totaltime : Total time in seconds for the entire timeline
ymm4.time_ratio : Current playback position ratio (0.0 ~ 1.0)
ymm4.is_saving : Whether video is currently being exported (true only during export)
ymm4.is_playing : Whether the timeline is currently playing (true only during playback)
ymm4.is_paused : Whether the timeline is currently paused (true only when paused)
ymm4.scene_id : Unique ID (Guid string) of the current scene
- anim Table -
Pure utility functions and constants useful for animation calculations.
anim.tau : 2 * Pi (math.pi * 2)
anim.e : Número de Euler (math.exp(1))
anim.phi : Proporción áurea ((1 + math.sqrt(5)) / 2)
anim.sqrt2 : Raíz cuadrada de 2 (math.sqrt(2))
anim.lerp(a, b, t) : Linear interpolation between a and b by t (0.0 ~ 1.0)
anim.smoothstep(e0, e1, x): Smooth Hermite interpolation between e0 and e1
anim.smootherstep(e0, e1, x): Interpolación de Hermite más suave entre e0 y e1 (segunda derivada continua)
anim.clamp(v, lo, hi) : Clamps value v between lo and hi
anim.map(v, a1, b1, a2, b2): Maps value v from range a1~b1 to range a2~b2
anim.norm(v, lo, hi) : Gets the normalized ratio (0.0 ~ 1.0) of v within lo~hi
anim.wrap(v, lo, hi) : Wraps value v to loop within the range lo~hi
anim.pingpong(t, len) : Value that bounces back and forth between 0 and len
anim.sign(v) : Gets the sign of v (1 for positive, -1 for negative, 0 for zero)
anim.oscillate(t, lo, hi, freq): Smoothly oscillates between lo and hi at the given freq (sine wave)
anim.triangle(t, freq) : Triangle wave oscillating between 0.0 and 1.0 at the given freq
anim.square(t, freq) : Square wave switching between 1.0 and 0.0 at the given freq
anim.duration(t, dur) : Current ratio over duration dur (0.0 ~ 1.0, clamped)
anim.delay(t, d) : Time starting after delay d (0 if negative)
anim.ease_in(t) : Quadratic ease-in (acceleration)
anim.ease_out(t) : Quadratic ease-out (deceleration)
anim.ease_in_out(t) : Aceleración y desaceleración cuadrática (entrada y salida suaves)
anim.elastic(t) : Bouncy spring easing
anim.back(t) : Easing that slightly overshoots before returning
anim.step(edge, x) : Returns 1.0 if x >= edge, otherwise 0.0
anim.fract(v) : Gets only the fractional part of v
anim.bounce(t) : Bouncing ease effect
anim.hsv_to_rgb(h, s, v): Converts HSV (Hue 0~360, Saturation 0~1, Value 0~1) to RGB (0~255)
anim.rgb_to_hsv(r, g, b): Converts RGB (0~255) to HSV
anim.noise(x, y, z) : 1D to 3D continuous smooth noise (-1.0 ~ 1.0)
anim.rand(min, max, s) : Stable random value based on seed `s`
anim.len(x, y) : Obtiene la longitud (norma) del vector (x, y)
anim.dist(x1, y1, x2, y2): Obtiene la distancia entre dos puntos (x1, y1) y (x2, y2)
anim.dot(x1, y1, x2, y2): Obtiene el producto escalar de dos vectores (x1, y1) y (x2, y2)
anim.normalize(x, y) : Normaliza el vector (x, y) devolviendo un vector de dirección (Tuple)
anim.polar(r, a) : Converts polar coordinates (radius, angle) to (x, y) tuple
anim.rotate(x, y, a) : Rotates 2D point (x, y) by angle `a` (degrees) returning (x, y) tuple
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
- Bibliotecas estándar disponibles -
Biblioteca math:
math.abs, math.ceil, math.cos, math.exp, math.floor,
math.fmod, math.huge, math.log, math.max, math.min,
math.modf, math.pi, math.random, math.randomseed,
math.sin, math.sqrt, math.tan, math.atan, math.atan2,
math.deg, math.rad, math.ldexp, math.frexp,
math.sinh, math.cosh, math.tanh, math.type,
math.tointeger, math.maxinteger, math.mininteger
Biblioteca string:
string.format, string.len, string.sub, string.upper,
string.lower, string.rep, string.reverse, string.find,
string.match, string.gmatch, string.gsub, string.byte,
string.char, string.dump, string.pack, string.unpack,
string.packsize
Biblioteca table:
table.insert, table.remove, table.sort,
table.concat, table.unpack, table.move
Biblioteca bit32:
bit32.band, bit32.bor, bit32.bxor, bit32.bnot,
bit32.lshift, bit32.rshift, bit32.arshift,
bit32.extract, bit32.replace,
bit32.btest, bit32.countlz, bit32.countrz
Funciones básicas:
type, tostring, tonumber, select, error, assert, print,
ipairs, pairs, next, unpack,
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen,
pcall, xpcall
- Ejemplos de script -
o Fundido de entrada (script predeterminado)
obj.alpha = math.min(time * 255, 255)
o Fundido de salida
obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)
o Controlar la opacidad con Track0
obj.alpha = obj.track0
o Rotar con el tiempo
obj.rz = time * 90 -- 90 grados por segundo
o Invertir el componente rojo de los píxeles
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 - r, g, b, a)
end
end
o Conversión a escala de grises usando getpixeldata (rápido)
local pd = obj.getpixeldata()
local w = pd.width
local h = pd.height
for y = 0, h - 1 do
for x = 0, w - 1 do
local base = (y * w + x) * 4
local r = pd:get(base + 1)
local g = pd:get(base + 2)
local b = pd:get(base + 3)
local a = pd:get(base + 4)
local gray = r * 0.299 + g * 0.587 + b * 0.114
pd:set(base + 1, gray)
pd:set(base + 2, gray)
pd:set(base + 3, gray)
end
end
o Controlar el zoom con Track0 (1.0 = escala normal)
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- Funciones no admitidas / Limitaciones -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), etc. de AviUtl2 no son compatibles.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), etc. de AviUtl2 no son compatibles.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
x Las funciones como scene.set() y scene.get() de la tabla scene de AviUtl2 no son compatibles.
(Solo se pueden leer scene.width y scene.height)
x El acceso a archivos (require, dofile, io, etc.) no es compatible.
x Modificar obj.z se refleja en el renderizado (incluido en ReadBack),
pero el soporte de renderizado 3D es limitado.
x Si se supera el tiempo de espera del script (5 segundos), la ejecución se termina forzosamente.
Se debe tener cuidado en la implementación para evitar bucles infinitos.
x Las directivas de encabezado de AviUtl2 como --track@ y --check@ no son compatibles.
Solo Track0 ~ Track3 pueden usarse como parámetros.
+413
ファイルの表示
@@ -0,0 +1,413 @@
- Tentang Efek Script Lua -
Efek video "Script Lua" di YukkuriMovieMaker4 menggunakan
bahasa Lua untuk penulisan skrip.
Mesin skrip yang digunakan adalah MoonSharp (kompatibel dengan Lua 5.2).
* Efek ini adalah implementasi mandiri dan berbeda dari spesifikasi skrip AviUtl2.
* Memiliki spesifikasi yang berbeda dari file skrip AviUtl2 (*.anm2, dll.).
* Karena IsAviUtlSupported = false, output EXO untuk AviUtl tidak didukung.
- Catatan -
o Mesin eksekusi skrip adalah MoonSharp (kompatibel dengan Lua 5.2).
o Pustaka standar yang tersedia terbatas pada berikut ini:
table, string, math, bit32
* io, os, debug, ffi, require, dll. tidak tersedia.
o Batas waktu skrip adalah 5000ms (5 detik).
Saat habis waktu, eksekusi dihentikan paksa dan diperlakukan sebagai kesalahan.
o Skrip tidak dapat mengakses sistem file (termasuk require).
o Pemanggilan skrip eksternal dari dalam skrip tidak didukung.
o Operasi piksel (getpixel/setpixel/getpixeldata) mengakses gambar masukan aktual,
sehingga transfer data GPU→CPU hanya terjadi pada akses pertama.
Menghilangkan panggilan ini saat tidak diperlukan akan mempercepat pemrosesan.
- Parameter -
Panel efek memiliki 4 trackbar berikut (mendukung animasi).
Setiap nilai dapat direferensikan dalam skrip sebagai obj.track0 ~ obj.track3.
Track0 : Parameter 0 (Default: 0, Rentang: Minimum ~ Maksimum)
Track1 : Parameter 1 (Default: 0, Rentang: Minimum ~ Maksimum)
Track2 : Parameter 2 (Default: 0, Rentang: Minimum ~ Maksimum)
Track3 : Parameter 3 (Default: 0, Rentang: Minimum ~ Maksimum)
* Setiap trackbar mendukung slider animasi (dengan interpolasi).
* File .lua dapat diimpor/diekspor dari toolbar editor skrip.
- Variabel Global -
Variabel-variabel berikut dapat direferensikan langsung dalam lingkup global skrip.
time : Waktu saat ini dalam detik relatif terhadap objek [Hanya Baca]
* Nilai yang sama dengan obj.time.
frame : Nomor frame saat ini relatif terhadap objek [Hanya Baca]
* Nilai yang sama dengan obj.frame.
totalframe : Total jumlah frame objek [Hanya Baca]
* Nilai yang sama dengan obj.totalframe.
framerate : Kecepatan frame (fps) [Hanya Baca]
* Nilai yang sama dengan obj.framerate.
timelineframe : Nomor frame saat ini relatif terhadap seluruh timeline [Hanya Baca]
* obj.frame adalah frame relatif dari awal objek,
sedangkan ini adalah frame absolut dari awal timeline.
timelinetime : Waktu saat ini dalam detik relatif terhadap seluruh timeline [Hanya Baca]
layer : Nomor layer tempat objek ditempatkan [Hanya Baca]
* Nilai yang sama dengan obj.layer.
obj : Tabel informasi objek (lihat «Tabel obj» di bawah)
scene : Tabel informasi adegan (lihat «Tabel scene» di bawah)
ymm4 : YMM4 specific meta-information table (see "ymm4 Table" below)
anim : Animation utility table (see "anim Table" below)
- Tabel scene -
scene.width : Resolusi horizontal (piksel) adegan (proyek) [Hanya Baca]
scene.height : Resolusi vertikal (piksel) adegan (proyek) [Hanya Baca]
- Tabel obj - Variabel -
Variabel-variabel berikut menyimpan informasi render objek saat ini.
* Variabel yang tidak ditandai Hanya Baca dapat dimodifikasi dalam skrip, dan perubahannya akan tercermin dalam render.
o Koordinat / Offset
obj.x : Koordinat referensi tampilan X [Hanya Baca]
* Setara dengan «Koordinat Referensi Tampilan X» dalam spesifikasi AviUtl2.
* Perubahan yang dilakukan di dalam skrip tidak dibaca kembali dan tidak berpengaruh.
* Ditetapkan secara internal dari DrawDescription.Draw.X;
perubahan berlaku setelah skrip dijalankan.
obj.y : Koordinat referensi tampilan Y [setara Hanya Baca]
* Ditetapkan secara internal dari DrawDescription.Draw.Y.
obj.z : Koordinat referensi tampilan Z [setara Hanya Baca]
* Ditetapkan secara internal dari DrawDescription.Draw.Z.
obj.ox : Offset pusat X (dapat dimodifikasi)
* Ditetapkan secara internal dari DrawDescription.CenterPoint.X (inDesc).
* Setara dengan «Koordinat X relatif dari referensi (obj.ox)» di AviUtl2,
tetapi dalam plugin ini diperlakukan sebagai CenterPoint (offset titik pusat).
obj.oy : Offset pusat Y (dapat dimodifikasi)
* Ditetapkan secara internal dari DrawDescription.CenterPoint.Y (inDesc).
o Skala / Transformasi
obj.zoom : Faktor skala (dapat dimodifikasi)
* 1.0 adalah skala normal (bukan 0.0), kompatibel dengan AviUtl2.
* Dihitung secara internal sebagai rata-rata ZoomX dan ZoomY (zoomAvg).
* Saat output, diperluas ke zoom X/Y individual sebagai obj.zoom * (1 ± obj.aspect).
obj.aspect : Rasio aspek (dapat dimodifikasi), Rentang: -1.0 ~ 1.0
* Nilai positif mengecilkan arah X; nilai negatif mengecilkan arah Y.
* Dihitung secara internal sebagai (ZoomX - ZoomY) / (ZoomX + ZoomY).
obj.sx : Scale factor in X direction (writable) 1.0 = 100%
* Precise independent scale control specific to YMM4.
* Takes precedence over zoom/aspect modifications.
obj.sy : Scale factor in Y direction (writable) 1.0 = 100%
* Precise independent scale control specific to YMM4.
* Takes precedence over zoom/aspect modifications.
obj.alpha : Opasitas (dapat dimodifikasi), Rentang: 0.0 ~ 255.0
* AviUtl2 menggunakan 0.0~1.0, tetapi plugin ini menggunakan 0.0~255.0.
* Ditetapkan secara internal dari DrawDescription.Opacity * 255.
* Dibagi 255 dan dinormalisasi ke 0.0~1.0 pada output (dengan Clamp).
* Skrip default menetapkan obj.alpha = math.min(time * 255, 255),
memberikan implementasi fade-in default.
o Rotasi
obj.rx : Sudut rotasi sumbu X (dapat dimodifikasi), Satuan: derajat (°), 360.0 = satu putaran penuh
* Ditetapkan secara internal dari DrawDescription.Rotation.X.
obj.ry : Sudut rotasi sumbu Y (dapat dimodifikasi), Satuan: derajat (°), 360.0 = satu putaran penuh
* Ditetapkan secara internal dari DrawDescription.Rotation.Y.
obj.rz : Sudut rotasi sumbu Z (dapat dimodifikasi), Satuan: derajat (°), 360.0 = satu putaran penuh
* Ditetapkan secara internal dari DrawDescription.Rotation.Z.
obj.rxr : Rotation angle around X axis in radians (writable)
* Takes precedence if rx is also modified simultaneously.
obj.ryr : Rotation angle around Y axis in radians (writable)
* Takes precedence if ry is also modified simultaneously.
obj.rzr : Rotation angle around Z axis in radians (writable)
* Takes precedence if rz is also modified simultaneously.
o Ukuran Gambar
obj.w : Lebar gambar masukan dalam piksel [Hanya Baca]
* Secara internal adalah bilangan bulat yang diturunkan dari D2D GetImageLocalBounds.
obj.h : Tinggi gambar masukan dalam piksel [Hanya Baca]
* Secara internal adalah bilangan bulat yang diturunkan dari D2D GetImageLocalBounds.
obj.hw : Half of the input image width (= obj.w / 2) [ReadOnly]
obj.hh : Half of the input image height (= obj.h / 2) [ReadOnly]
obj.diagonal : Panjang diagonal dari gambar input (= math.sqrt(w*w + h*h)) [ReadOnly]
obj.cx : Koordinat X pusat gambar (= obj.w / 2) [Hanya Baca]
* Koordinat pusat referensi untuk operasi piksel.
obj.cy : Koordinat Y pusat gambar (= obj.h / 2) [Hanya Baca]
o Waktu / Frame
obj.time : Waktu saat ini dalam detik relatif terhadap objek [Hanya Baca]
* Nilai yang sama dengan variabel global time.
* Ditetapkan secara internal dari EffectDescription.ItemPosition.Time.TotalSeconds.
obj.frame : Nomor frame saat ini relatif terhadap objek [Hanya Baca]
* Nilai yang sama dengan variabel global frame.
* Ditetapkan secara internal dari EffectDescription.ItemPosition.Frame.
obj.totalframe: Total jumlah frame objek [Hanya Baca]
* Nilai yang sama dengan variabel global totalframe.
* Ditetapkan secara internal dari EffectDescription.ItemDuration.Frame.
obj.framerate : Kecepatan frame (fps) [Hanya Baca]
* Nilai yang sama dengan variabel global framerate.
* Ditetapkan secara internal dari EffectDescription.FPS.
o Trackbar
obj.track0 : Nilai saat ini Track0 di panel efek [Hanya Baca]
* Nilai setelah interpolasi animasi.
obj.track1 : Nilai saat ini Track1 di panel efek [Hanya Baca]
obj.track2 : Nilai saat ini Track2 di panel efek [Hanya Baca]
obj.track3 : Nilai saat ini Track3 di panel efek [Hanya Baca]
o Layer
obj.layer : Nomor layer tempat objek ditempatkan [Hanya Baca]
* Nilai yang sama dengan variabel global layer.
* Ditetapkan secara internal dari EffectDescription.Layer.
- Tabel obj - Perubahan Variabel dan Pencerminan ke Render -
Setelah eksekusi skrip, hanya variabel-variabel berikut yang dibaca kembali ke informasi render (diterapkan).
Variabel yang diterapkan:
obj.x, obj.y, obj.z
obj.ox, obj.oy
obj.zoom, obj.aspect
obj.alpha
obj.rx, obj.ry, obj.rz
* obj.w, obj.h, obj.cx, obj.cy, obj.frame, obj.time,
obj.totalframe, obj.framerate, obj.track0 ~ obj.track3,
obj.layer adalah Hanya Baca dan perubahannya tidak akan tercermin dalam render.
Rumus nilai output:
ZoomX = obj.zoom * (1.0 + obj.aspect)
ZoomY = obj.zoom * (1.0 - obj.aspect)
Opacity = Clamp(obj.alpha / 255.0, 0.0, 1.0)
Draw = (obj.x, obj.y, obj.z)
CenterPoint = (obj.ox, obj.oy)
Rotation = (obj.rx, obj.ry, obj.rz)
- Tabel obj - Fungsi -
o obj.getpixel(x, y)
Mengambil informasi piksel pada koordinat yang ditentukan.
* Transfer data gambar GPU→CPU terjadi pada panggilan pertama (dengan overhead pemrosesan).
* Koordinat piksel menggunakan sudut kiri atas gambar sebagai (0, 0), dengan kanan dan bawah sebagai positif.
* Nilai yang dikembalikan adalah ekuivalen alpha langsung yang dikonversi dari alpha premultiplied.
x : Koordinat X (0 ~ obj.w - 1)
y : Koordinat Y (0 ~ obj.h - 1)
Mengembalikan : 4 nilai r, g, b, a (nilai kembalian jamak)
r = Komponen merah (0.0 ~ 255.0)
g = Komponen hijau (0.0 ~ 255.0)
b = Komponen biru (0.0 ~ 255.0)
a = Nilai alpha (0.0 ~ 255.0)
* Mengembalikan (0, 0, 0, 0) untuk koordinat di luar rentang.
Contoh: r, g, b, a = obj.getpixel(10, 20)
o obj.setpixel(x, y, r, g, b [, a])
Menimpa informasi piksel pada koordinat yang ditentukan.
* Data piksel secara otomatis ditandai sebagai «dimodifikasi» saat dipanggil,
dan gambar yang dimodifikasi dikeluarkan setelah skrip berakhir.
* Disimpan secara internal dalam format alpha premultiplied (BGRA).
Konversi premultiplied dilakukan saat setpixel.
x : Koordinat X (0 ~ obj.w - 1)
y : Koordinat Y (0 ~ obj.h - 1)
r : Komponen merah (0.0 ~ 255.0)
g : Komponen hijau (0.0 ~ 255.0)
b : Komponen biru (0.0 ~ 255.0)
a : Nilai alpha (default: 255.0)
Contoh: obj.setpixel(10, 20, 255, 0, 0, 128)
o obj.getpixeldata()
Mengembalikan objek proxy untuk akses massal ke semua data piksel.
* Manipulasi piksel lebih cepat dibandingkan getpixel/setpixel.
* Transfer data gambar GPU→CPU terjadi pada panggilan pertama (dengan overhead pemrosesan).
Mengembalikan : Objek PixelDataProxy
.width : Lebar gambar dalam piksel (= obj.w)
.height : Tinggi gambar dalam piksel (= obj.h)
:get(index) : Mendapatkan nilai saluran berdasarkan indeks
:set(index, value) : Menetapkan nilai saluran berdasarkan indeks
Spesifikasi indeks:
Indeks dimulai dari 1 (mengikuti konvensi Lua).
Urutan saluran adalah R, G, B, A berulang.
Indeks saluran R untuk pixel(x, y) =
(y * obj.w + x) * 4 + 1
Indeks saluran G untuk pixel(x, y) =
(y * obj.w + x) * 4 + 2
Indeks saluran B untuk pixel(x, y) =
(y * obj.w + x) * 4 + 3
Indeks saluran A untuk pixel(x, y) =
(y * obj.w + x) * 4 + 4
* Memodifikasi alpha (saluran 4) juga akan mengkonversi RGB secara proporsional.
* Memodifikasi saluran RGB akan menerapkan konversi premultiplied.
* Nilai yang diambil adalah ekuivalen alpha langsung, sama seperti get(index).
Contoh:
local pd = obj.getpixeldata()
local idx = (10 * obj.w + 20) * 4 + 1 -- Saluran R dari (x=20, y=10)
local r = pd:get(idx)
pd:set(idx, 128)
o obj.putpixeldata()
Fungsi kosong (no-op) yang didefinisikan untuk kompatibilitas.
* Dalam skrip AviUtl, getpixeldata/putpixeldata digunakan bersama,
tetapi dalam plugin ini perubahan melalui setpixel/set diterapkan secara otomatis,
sehingga tidak perlu memanggil fungsi ini.
- ymm4 Table -
Table holding YMM4-specific meta-information. All values are ReadOnly.
ymm4.group_index : Current item index within a group control (0-based)
ymm4.group_count : Total number of items within a group control
ymm4.group_ratio : Progress ratio within the group (group_index / group_count)
ymm4.timeline_totalframe: Total number of frames for the entire timeline
ymm4.timeline_totaltime : Total time in seconds for the entire timeline
ymm4.time_ratio : Current playback position ratio (0.0 ~ 1.0)
ymm4.is_saving : Whether video is currently being exported (true only during export)
ymm4.is_playing : Whether the timeline is currently playing (true only during playback)
ymm4.is_paused : Whether the timeline is currently paused (true only when paused)
ymm4.scene_id : Unique ID (Guid string) of the current scene
- anim Table -
Pure utility functions and constants useful for animation calculations.
anim.tau : 2 * Pi (math.pi * 2)
anim.e : Bilangan Euler (math.exp(1))
anim.phi : Rasio emas ((1 + math.sqrt(5)) / 2)
anim.sqrt2 : Akar kuadrat dari 2 (math.sqrt(2))
anim.lerp(a, b, t) : Linear interpolation between a and b by t (0.0 ~ 1.0)
anim.smoothstep(e0, e1, x): Smooth Hermite interpolation between e0 and e1
anim.smootherstep(e0, e1, x): Interpolasi Hermite yang lebih halus antara e0 dan e1 (turunan kedua kontinu)
anim.clamp(v, lo, hi) : Clamps value v between lo and hi
anim.map(v, a1, b1, a2, b2): Maps value v from range a1~b1 to range a2~b2
anim.norm(v, lo, hi) : Gets the normalized ratio (0.0 ~ 1.0) of v within lo~hi
anim.wrap(v, lo, hi) : Wraps value v to loop within the range lo~hi
anim.pingpong(t, len) : Value that bounces back and forth between 0 and len
anim.sign(v) : Gets the sign of v (1 for positive, -1 for negative, 0 for zero)
anim.oscillate(t, lo, hi, freq): Smoothly oscillates between lo and hi at the given freq (sine wave)
anim.triangle(t, freq) : Triangle wave oscillating between 0.0 and 1.0 at the given freq
anim.square(t, freq) : Square wave switching between 1.0 and 0.0 at the given freq
anim.duration(t, dur) : Current ratio over duration dur (0.0 ~ 1.0, clamped)
anim.delay(t, d) : Time starting after delay d (0 if negative)
anim.ease_in(t) : Quadratic ease-in (acceleration)
anim.ease_out(t) : Quadratic ease-out (deceleration)
anim.ease_in_out(t) : Ease-in-out kuadratik (akselerasi kemudian deselerasi)
anim.elastic(t) : Bouncy spring easing
anim.back(t) : Easing that slightly overshoots before returning
anim.step(edge, x) : Returns 1.0 if x >= edge, otherwise 0.0
anim.fract(v) : Gets only the fractional part of v
anim.bounce(t) : Bouncing ease effect
anim.hsv_to_rgb(h, s, v): Converts HSV (Hue 0~360, Saturation 0~1, Value 0~1) to RGB (0~255)
anim.rgb_to_hsv(r, g, b): Converts RGB (0~255) to HSV
anim.noise(x, y, z) : 1D to 3D continuous smooth noise (-1.0 ~ 1.0)
anim.rand(min, max, s) : Stable random value based on seed `s`
anim.len(x, y) : Mendapatkan panjang (norma) dari vektor (x, y)
anim.dist(x1, y1, x2, y2): Mendapatkan jarak antara dua titik (x1, y1) dan (x2, y2)
anim.dot(x1, y1, x2, y2): Mendapatkan hasil kali titik (dot product) dari dua vektor (x1, y1) dan (x2, y2)
anim.normalize(x, y) : Menormalisasi vektor (x, y) mengembalikan vektor arah (Tuple)
anim.polar(r, a) : Converts polar coordinates (radius, angle) to (x, y) tuple
anim.rotate(x, y, a) : Rotates 2D point (x, y) by angle `a` (degrees) returning (x, y) tuple
anim.bezier(t, p0, p1, p2, p3): Evaluates cubic bezier curve at `t` (0.0~1.0)
- Pustaka Standar yang Tersedia -
Pustaka math:
math.abs, math.ceil, math.cos, math.exp, math.floor,
math.fmod, math.huge, math.log, math.max, math.min,
math.modf, math.pi, math.random, math.randomseed,
math.sin, math.sqrt, math.tan, math.atan, math.atan2,
math.deg, math.rad, math.ldexp, math.frexp,
math.sinh, math.cosh, math.tanh, math.type,
math.tointeger, math.maxinteger, math.mininteger
Pustaka string:
string.format, string.len, string.sub, string.upper,
string.lower, string.rep, string.reverse, string.find,
string.match, string.gmatch, string.gsub, string.byte,
string.char, string.dump, string.pack, string.unpack,
string.packsize
Pustaka table:
table.insert, table.remove, table.sort,
table.concat, table.unpack, table.move
Pustaka bit32:
bit32.band, bit32.bor, bit32.bxor, bit32.bnot,
bit32.lshift, bit32.rshift, bit32.arshift,
bit32.extract, bit32.replace,
bit32.btest, bit32.countlz, bit32.countrz
Fungsi dasar:
type, tostring, tonumber, select, error, assert, print,
ipairs, pairs, next, unpack,
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen,
pcall, xpcall
- Contoh Skrip -
o Fade in (skrip default)
obj.alpha = math.min(time * 255, 255)
o Fade out
obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)
o Mengontrol opasitas dengan Track0
obj.alpha = obj.track0
o Rotasi seiring waktu
obj.rz = time * 90 -- 90 derajat per detik
o Membalik komponen merah piksel
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 - r, g, b, a)
end
end
o Konversi skala abu-abu menggunakan getpixeldata (cepat)
local pd = obj.getpixeldata()
local w = pd.width
local h = pd.height
for y = 0, h - 1 do
for x = 0, w - 1 do
local base = (y * w + x) * 4
local r = pd:get(base + 1)
local g = pd:get(base + 2)
local b = pd:get(base + 3)
local a = pd:get(base + 4)
local gray = r * 0.299 + g * 0.587 + b * 0.114
pd:set(base + 1, gray)
pd:set(base + 2, gray)
pd:set(base + 3, gray)
end
end
o Mengontrol zoom dengan Track0 (1.0 = skala normal)
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- Fitur yang Tidak Didukung / Batasan -
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), dll. dari AviUtl2 tidak didukung.
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), dll. dari AviUtl2 tidak didukung.
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
x Fungsi seperti scene.set() dan scene.get() dalam tabel scene AviUtl2 tidak didukung.
(Hanya scene.width dan scene.height yang dapat dibaca)
x Akses file (require, dofile, io, dll.) tidak didukung.
x Memodifikasi obj.z tercermin dalam render (termasuk dalam ReadBack),
tetapi dukungan render 3D terbatas.
x Jika batas waktu skrip (5 detik) terlampaui, eksekusi dihentikan paksa.
Perhatian harus diberikan dalam implementasi untuk mencegah loop tak terbatas.
x Direktif header AviUtl2 seperti --track@ dan --check@ tidak didukung.
Hanya Track0 ~ Track3 yang dapat digunakan sebagai parameter.
+416
ファイルの表示
@@ -0,0 +1,416 @@
- Luaスクリプトエフェクトについて -
YukkuriMovieMaker4 の「Luaスクリプト」映像エフェクトで
利用可能なスクリプトには Lua 言語を使用します。
スクリプトエンジンには MoonSharp (Lua 5.2 互換) が採用されています。
※このエフェクトは AviUtl2 のスクリプト仕様とは異なる独自実装です。
※AviUtl2 のスクリプトファイル(*.anm2 等)とは別仕様です。
※IsAviUtlSupported = false のため、AviUtl 向けの EXO 出力には対応しません。
- 注意点 -
○スクリプトの実行エンジンは MoonSharp (Lua 5.2 互換) です。
○利用可能な標準ライブラリは以下に限定されます。
table, string, math, bit32
※io, os, debug, ffi, require 等は使用できません。
○スクリプトのタイムアウトは 5000ms (5秒) です。
タイムアウト時は実行が強制終了され、エラーとして扱われます。
○スクリプトからファイルへのアクセスはできません (require を含む)。
○スクリプト内からの外部スクリプト呼び出しには対応していません。
○ピクセル操作(getpixel/setpixel/getpixeldata)は実際の入力画像に
アクセスするため、初回アクセス時にのみ GPU→CPU へのデータ転送が
発生します。不要な場合は呼び出しを省略することで処理を高速化できます。
- パラメータ -
エフェクトパネルには以下の 4 つのトラックバー(アニメーション対応)があります。
各値はスクリプト内で obj.track0 ~ obj.track3 として参照できます。
Track0 : パラメータ0 (デフォルト: 0, 範囲: 最小値 ~ 最大値)
Track1 : パラメータ1 (デフォルト: 0, 範囲: 最小値 ~ 最大値)
Track2 : パラメータ2 (デフォルト: 0, 範囲: 最小値 ~ 最大値)
Track3 : パラメータ3 (デフォルト: 0, 範囲: 最小値 ~ 最大値)
※各トラックバーはアニメーションスライダーに対応しています(補間あり)。
※スクリプトエディタのツールバーから .lua ファイルのインポート/エクスポートが可能です。
- グローバル変数 -
以下の変数はスクリプトのグローバルスコープで直接参照できます。
time : オブジェクト基準の現在時間(秒) [ReadOnly]
※ obj.time と同じ値です。
frame : オブジェクト基準の現在フレーム番号 [ReadOnly]
※ obj.frame と同じ値です。
totalframe : オブジェクトの総フレーム数 [ReadOnly]
※ obj.totalframe と同じ値です。
framerate : フレームレート(fps) [ReadOnly]
※ obj.framerate と同じ値です。
timelineframe : タイムライン全体基準の現在フレーム番号 [ReadOnly]
※ obj.frame はオブジェクト先頭からの相対フレームですが、
こちらはタイムライン先頭からの絶対フレームです。
timelinetime : タイムライン全体基準の現在時間(秒) [ReadOnly]
layer : オブジェクトが配置されているレイヤー番号 [ReadOnly]
※ obj.layer と同じ値です。
obj : オブジェクト情報テーブル (下記「obj テーブル」を参照)
scene : シーン情報テーブル (下記「scene テーブル」を参照)
ymm4 : YMM4固有のメタ情報テーブル (下記「ymm4 テーブル」を参照)
anim : アニメーション用ユーティリティテーブル (下記「anim テーブル」を参照)
- scene テーブル -
scene.width : シーン(プロジェクト)の横解像度(ピクセル) [ReadOnly]
scene.height : シーン(プロジェクト)の縦解像度(ピクセル) [ReadOnly]
scene.cx : シーンの横解像度の半分 (= scene.width / 2) [ReadOnly]
scene.cy : シーンの縦解像度の半分 (= scene.height / 2) [ReadOnly]
- obj テーブル - 変数 -
以下の変数はオブジェクトの現在の描画情報を保持します。
※ ReadOnly と記載のないものはスクリプト内で変更可能であり、変更した値が描画に反映されます。
○座標・オフセット
obj.x : 表示基準座標 X [ReadOnly]
※ AviUtl2 仕様の「表示基準座標X」に相当します。
※ スクリプト内で変更しても読み戻しが行われないため無効です。
※ 実装上は DrawDescription.Draw.X から設定され、
スクリプト後に変更内容が反映されます。
obj.y : 表示基準座標 Y [ReadOnly相当]
※ 実装上は DrawDescription.Draw.Y から設定されます。
obj.z : 表示基準座標 Z [ReadOnly相当]
※ 実装上は DrawDescription.Draw.Z から設定されます。
obj.ox : 中心オフセット X (変更可)
※ 実装上は DrawDescription.CenterPoint.X (inDesc) から設定されます。
※ AviUtl2 仕様の「基準座標からの相対座標X(obj.ox)」に相当しますが、
このプラグインでは CenterPoint(中心点のオフセット)として扱われます。
obj.oy : 中心オフセット Y (変更可)
※ 実装上は DrawDescription.CenterPoint.Y (inDesc) から設定されます。
○拡大率・変形
obj.zoom : 拡大率(変更可)
※ 0.0 が等倍相当ではなく、1.0 が等倍です(AviUtl2 互換)。
※ 実装上は ZoomX と ZoomY の平均値 (zoomAvg) として算出されます。
※ 出力時は obj.zoom * (1 ± obj.aspect) で X/Y 個別の Zoom に展開されます。
obj.aspect : アスペクト比(変更可) 範囲: -1.0 ~ 1.0
※ 正の値で X 方向に縮小、負の値で Y 方向に縮小。
※ 実装上は (ZoomX - ZoomY) / (ZoomX + ZoomY) として算出されます。
obj.sx : X 方向の拡大率 (変更可) 1.0 で等倍
※ YMM4独自の精密な独立スケール制御です。
※ zoom/aspect の変更よりも優先して反映されます。
obj.sy : Y 方向の拡大率 (変更可) 1.0 で等倍
※ YMM4独自の精密な独立スケール制御です。
※ zoom/aspect の変更よりも優先して反映されます。
obj.alpha : 不透明度(変更可) 範囲: 0.0 ~ 255.0
※ AviUtl2 では 0.0~1.0 ですが、このプラグインでは 0.0~255.0 です。
※ 実装上は DrawDescription.Opacity * 255 から設定されます。
※ 出力時に 255 で除算し、0.0~1.0 に正規化されます(Clamp あり)。
※ デフォルトスクリプトでは obj.alpha = math.min(time * 255, 255) が
設定されており、フェードインのデフォルト実装となっています。
○回転
obj.rx : X 軸回転角度(変更可) 単位: 度(°), 360.0 で一回転
※ 実装上は DrawDescription.Rotation.X から設定されます。
obj.ry : Y 軸回転角度(変更可) 単位: 度(°), 360.0 で一回転
※ 実装上は DrawDescription.Rotation.Y から設定されます。
obj.rz : Z 軸回転角度(変更可) 単位: 度(°), 360.0 で一回転
※ 実装上は DrawDescription.Rotation.Z から設定されます。
obj.rxr : X 軸回転角度(ラジアン) (変更可) 単位: ラジアン(rad)
※ rx と同時に変更された場合はこちらが優先して反映されます。
obj.ryr : Y 軸回転角度(ラジアン) (変更可) 単位: ラジアン(rad)
※ ry と同時に変更された場合はこちらが優先して反映されます。
obj.rzr : Z 軸回転角度(ラジアン) (変更可) 単位: ラジアン(rad)
※ rz と同時に変更された場合はこちらが優先して反映されます。
○画像サイズ
obj.w : 入力画像の横ピクセル数 [ReadOnly]
※ 実装上は D2D の GetImageLocalBounds から算出した整数値です。
obj.h : 入力画像の縦ピクセル数 [ReadOnly]
※ 実装上は D2D の GetImageLocalBounds から算出した整数値です。
obj.hw : 入力画像の横ピクセル数の半分 (= obj.w / 2) [ReadOnly]
obj.hh : 入力画像の縦ピクセル数の半分 (= obj.h / 2) [ReadOnly]
obj.diagonal : 画像の対角線の長さ (= math.sqrt(w*w + h*h)) [ReadOnly]
obj.cx : 画像の中心 X 座標 (= obj.w / 2) [ReadOnly]
※ ピクセル操作における中心座標の参照値です。
obj.cy : 画像の中心 Y 座標 (= obj.h / 2) [ReadOnly]
○時間・フレーム
obj.time : オブジェクト基準の現在時間(秒) [ReadOnly]
※ グローバル変数 time と同じ値です。
※ 実装上は EffectDescription.ItemPosition.Time.TotalSeconds から設定されます。
obj.frame : オブジェクト基準の現在フレーム番号 [ReadOnly]
※ グローバル変数 frame と同じ値です。
※ 実装上は EffectDescription.ItemPosition.Frame から設定されます。
obj.totalframe: オブジェクトの総フレーム数 [ReadOnly]
※ グローバル変数 totalframe と同じ値です。
※ 実装上は EffectDescription.ItemDuration.Frame から設定されます。
obj.t : オブジェクト内の現在時間の進行割合 (0.0 ~ 1.0) [ReadOnly]
obj.framerate : フレームレート(fps) [ReadOnly]
※ グローバル変数 framerate と同じ値です。
※ 実装上は EffectDescription.FPS から設定されます。
○トラックバー
obj.track0 : エフェクトパネルの Track0 の現在値 [ReadOnly]
※ アニメーション補間後の値です。
obj.track1 : エフェクトパネルの Track1 の現在値 [ReadOnly]
obj.track2 : エフェクトパネルの Track2 の現在値 [ReadOnly]
obj.track3 : エフェクトパネルの Track3 の現在値 [ReadOnly]
○レイヤー
obj.layer : オブジェクトが配置されているレイヤー番号 [ReadOnly]
※ グローバル変数 layer と同じ値です。
※ 実装上は EffectDescription.Layer から設定されます。
- obj テーブル - 変数の変更と描画への反映 -
スクリプト実行後、以下の変数のみが描画情報に読み戻されます(反映されます)。
反映される変数:
obj.x, obj.y, obj.z
obj.ox, obj.oy
obj.zoom, obj.aspect
obj.alpha
obj.rx, obj.ry, obj.rz
※ obj.w, obj.h, obj.cx, obj.cy, obj.frame, obj.time,
obj.totalframe, obj.framerate, obj.track0 ~ obj.track3,
obj.layer は ReadOnly であり、変更しても描画には反映されません。
出力値の算出式:
ZoomX = obj.zoom * (1.0 + obj.aspect)
ZoomY = obj.zoom * (1.0 - obj.aspect)
Opacity = Clamp(obj.alpha / 255.0, 0.0, 1.0)
Draw = (obj.x, obj.y, obj.z)
CenterPoint = (obj.ox, obj.oy)
Rotation = (obj.rx, obj.ry, obj.rz)
- obj テーブル - 関数 -
○obj.getpixel(x, y)
指定座標のピクセル情報を取得します。
※ 初回呼び出し時に GPU→CPU への画像データ転送が発生します(処理負荷を伴います)。
※ ピクセル座標は画像の左上を (0, 0) とし、右・下方向が正です。
※ 取得値はプリマルチプライドアルファを逆変換したストレートアルファ相当の値です。
x : X 座標 (0 ~ obj.w - 1)
y : Y 座標 (0 ~ obj.h - 1)
戻り値 : r, g, b, a の 4 値(多値返却)
r = 赤成分 (0.0 ~ 255.0)
g = 緑成分 (0.0 ~ 255.0)
b = 青成分 (0.0 ~ 255.0)
a = アルファ値 (0.0 ~ 255.0)
※ 範囲外の座標を指定した場合は (0, 0, 0, 0) を返します。
例:r, g, b, a = obj.getpixel(10, 20)
○obj.setpixel(x, y, r, g, b [, a])
指定座標のピクセル情報を書き換えます。
※ 呼び出し時に自動的にピクセルデータが「変更済み」としてマークされ、
スクリプト終了後に変更後の画像が出力されます。
※ 内部ではプリマルチプライドアルファ形式(BGRA)で保持されます。
setpixel 時に premultiplied 変換が行われます。
x : X 座標 (0 ~ obj.w - 1)
y : Y 座標 (0 ~ obj.h - 1)
r : 赤成分 (0.0 ~ 255.0)
g : 緑成分 (0.0 ~ 255.0)
b : 青成分 (0.0 ~ 255.0)
a : アルファ値 (省略時は 255.0)
例:obj.setpixel(10, 20, 255, 0, 0, 128)
○obj.getpixeldata()
全ピクセルデータに一括アクセスするためのプロキシオブジェクトを返します。
※ getpixel/setpixel と比較して高速にピクセルを操作できます。
※ 初回呼び出し時に GPU→CPU への画像データ転送が発生します(処理負荷を伴います)。
戻り値 : PixelDataProxy オブジェクト
.width : 画像の横ピクセル数 (= obj.w)
.height : 画像の縦ピクセル数 (= obj.h)
:get(index) : インデックス指定でチャンネル値を取得
:set(index, value) : インデックス指定でチャンネル値を設定
インデックスの仕様:
インデックスは 1 始まりです(Lua の慣習に準拠)。
チャンネルの順序は R, G, B, A の繰り返しです。
pixel(x, y) の R チャンネルのインデックス =
(y * obj.w + x) * 4 + 1
pixel(x, y) の G チャンネルのインデックス =
(y * obj.w + x) * 4 + 2
pixel(x, y) の B チャンネルのインデックス =
(y * obj.w + x) * 4 + 3
pixel(x, y) の A チャンネルのインデックス =
(y * obj.w + x) * 4 + 4
※ アルファ(チャンネル4)を変更した場合は RGB も比率変換されます。
※ RGB チャンネルを変更した場合は premultiplied 変換が行われます。
※ 取得値は get(index) 同様ストレートアルファ相当です。
例:
local pd = obj.getpixeldata()
local idx = (10 * obj.w + 20) * 4 + 1 -- (x=20, y=10) の R チャンネル
local r = pd:get(idx)
pd:set(idx, 128)
○obj.putpixeldata()
互換性のために定義された空実装関数です(no-op)。
※ AviUtl のスクリプトでは getpixeldata/putpixeldata の組み合わせで使用しますが、
このプラグインでは setpixel/set による変更が自動的に反映されるため、
本関数を呼び出す必要はありません。
- ymm4 テーブル -
YMM4固有のメタ情報を保持するテーブルです。全て ReadOnly です。
ymm4.group_index : グループ制御内の現在のインデックス (0始まり)
ymm4.group_count : グループ制御内の総アイテム数
ymm4.group_ratio : グループ内の進行割合 (group_index / group_count)
ymm4.timeline_totalframe: タイムライン全体の総フレーム数
ymm4.timeline_totaltime : タイムライン全体の総時間(秒)
ymm4.time_ratio : 現在の再生位置の割合 (0.0 ~ 1.0)
ymm4.is_saving : 動画出力中であるかどうか (出力中のみ true)
ymm4.is_playing : 再生中であるかどうか (再生中のみ true)
ymm4.is_paused : 一時停止中であるかどうか (一時停止中のみ true)
ymm4.scene_id : 現在のシーンを一意に識別する文字列 (Guid)
- anim テーブル -
アニメーション計算に便利な純粋ユーティリティ関数・定数群です。
anim.tau : 円周率の2倍 (math.pi * 2)
anim.e : ネイピア数 (math.exp(1))
anim.phi : 黄金比 ((1 + math.sqrt(5)) / 2)
anim.sqrt2 : 2の平方根 (math.sqrt(2))
anim.lerp(a, b, t) : a と b を t (0.0~1.0) で線形補間
anim.smoothstep(e0, e1, x): e0 と e1 の間をエルミート補間でスムーズに遷移
anim.smootherstep(e0, e1, x): e0 と e1 の間をより滑らかに(2次導関数まで連続)補間
anim.clamp(v, lo, hi) : 値 v を lo ~ hi の範囲に収める
anim.map(v, a1, b1, a2, b2): a1~b1 の範囲の値 v を a2~b2 の範囲にマッピング
anim.norm(v, lo, hi) : 値 v が lo ~ hi の範囲でどの割合(0.0~1.0)かを取得
anim.wrap(v, lo, hi) : 値 v を lo ~ hi の範囲でループさせる
anim.pingpong(t, len) : 0 ~ len の範囲を往復する値
anim.sign(v) : 値 v の符号を取得 (正=1, 負=-1, ゼロ=0)
anim.oscillate(t, lo, hi, freq): freq の周波数で lo ~ hi を滑らかに往復(正弦波)
anim.triangle(t, freq) : freq の周波数で 0.0 ~ 1.0 を往復する三角波
anim.square(t, freq) : freq の周波数で 1.0 と 0.0 を切り替える矩形波
anim.duration(t, dur) : 時間 dur に対する現在の割合(0.0~1.0, clampあり)
anim.delay(t, d) : 時間 d 経過後から開始する時間 (0以下は0)
anim.ease_in(t) : 2次イーズイン(加速)
anim.ease_out(t) : 2次イーズアウト(減速)
anim.ease_in_out(t) : 2次イーズイン・アウト(加速後減速)
anim.elastic(t) : 弾むようなスプリングイージング
anim.back(t) : 勢い余って行き過ぎてから戻るイージング
anim.step(edge, x) : x が edge 以上なら 1.0、未満なら 0.0 を返す
anim.fract(v) : 値 v の小数部分のみを取得
anim.bounce(t) : バウンドするようなイージング
anim.hsv_to_rgb(h, s, v): HSV (色相0~360, 彩度0~1, 明度0~1) を RGB に変換
anim.rgb_to_hsv(r, g, b): RGB (0~255) を HSV に変換
anim.noise(x, y, z) : 1次元~3次元の滑らかなパーリン/バリューノイズ (-1.0~1.0)
anim.rand(min, max, s) : シード値 s に基づく安定した乱数を生成
anim.len(x, y) : ベクトル (x, y) の長さ(ノルム)を取得
anim.dist(x1, y1, x2, y2): 2点 (x1, y1) と (x2, y2) の距離を取得
anim.dot(x1, y1, x2, y2): 2つのベクトル (x1, y1) と (x2, y2) の内積を取得
anim.normalize(x, y) : ベクトル (x, y) を正規化して方向ベクトル(Tuple)を取得
anim.polar(r, a) : 半径 r, 角度 a(度) から (x, y) の移動量(Tuple)を取得
anim.rotate(x, y, a) : 座標 (x, y) を a(度) 回転させた座標(Tuple)を取得
anim.bezier(t, p0, p1, p2, p3): t (0.0~1.0) における3次ベジェ曲線の値を計算
- 利用可能な標準ライブラリ -
math ライブラリ:
math.abs, math.ceil, math.cos, math.exp, math.floor,
math.fmod, math.huge, math.log, math.max, math.min,
math.modf, math.pi, math.random, math.randomseed,
math.sin, math.sqrt, math.tan, math.atan, math.atan2,
math.deg, math.rad, math.ldexp, math.frexp,
math.sinh, math.cosh, math.tanh, math.type,
math.tointeger, math.maxinteger, math.mininteger
string ライブラリ:
string.format, string.len, string.sub, string.upper,
string.lower, string.rep, string.reverse, string.find,
string.match, string.gmatch, string.gsub, string.byte,
string.char, string.dump, string.pack, string.unpack,
string.packsize
table ライブラリ:
table.insert, table.remove, table.sort,
table.concat, table.unpack, table.move
bit32 ライブラリ:
bit32.band, bit32.bor, bit32.bxor, bit32.bnot,
bit32.lshift, bit32.rshift, bit32.arshift,
bit32.extract, bit32.replace,
bit32.btest, bit32.countlz, bit32.countrz
基本関数:
type, tostring, tonumber, select, error, assert, print,
ipairs, pairs, next, unpack,
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen,
pcall, xpcall
- スクリプト例 -
○フェードイン(デフォルトスクリプト)
obj.alpha = math.min(time * 255, 255)
○フェードアウト
obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)
○Track0 で透明度を制御
obj.alpha = obj.track0
○時間に応じて回転
obj.rz = time * 90 -- 1秒で90度回転
○ピクセルの赤成分を反転する
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 - r, g, b, a)
end
end
○getpixeldata を使ったグレースケール変換(高速)
local pd = obj.getpixeldata()
local w = pd.width
local h = pd.height
for y = 0, h - 1 do
for x = 0, w - 1 do
local base = (y * w + x) * 4
local r = pd:get(base + 1)
local g = pd:get(base + 2)
local b = pd:get(base + 3)
local a = pd:get(base + 4)
local gray = r * 0.299 + g * 0.587 + b * 0.114
pd:set(base + 1, gray)
pd:set(base + 2, gray)
pd:set(base + 3, gray)
end
end
○Track0 でズームを制御 (1.0 = 等倍)
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- 非対応・制限事項 -
×AviUtl2 の obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 等には対応していません。
×AviUtl2 の obj.rand(), obj.rand1(), obj.setfont(), obj.mes() 等には対応していません。
×AviUtl2 の obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 等には対応していません。
×AviUtl2 の scene テーブルの scene.set(), scene.get() 等の関数には対応していません。
(scene.width と scene.height の読み取りのみ対応)
×ファイルアクセス(require, dofile, io 等)には対応していません。
×obj.z を変更した場合、描画には反映されます(ReadBack に含まれる)が、
3D 描画のサポートは限定的です。
×スクリプトのタイムアウト(5秒)を超えた場合、実行は強制終了されます。
無限ループが発生しないよう実装上の注意が必要です。
×AviUtl2 の --track@, --check@ 等のヘッダーディレクティブには対応していません。
パラメータは Track0 ~ Track3 のみ使用できます。
+413
ファイルの表示
@@ -0,0 +1,413 @@
- Lua 스크립트 이펙트에 대하여 -
YukkuriMovieMaker4의 「Lua 스크립트」 영상 이펙트에서
사용 가능한 스크립트에는 Lua 언어를 사용합니다.
스크립트 엔진으로는 MoonSharp (Lua 5.2 호환)이 채용되어 있습니다.
※ 이 이펙트는 AviUtl2의 스크립트 사양과는 다른 독자적인 구현입니다.
※ AviUtl2의 스크립트 파일(*.anm2 등)과는 별도의 사양입니다.
※ IsAviUtlSupported = false이므로 AviUtl용 EXO 출력은 지원하지 않습니다.
- 주의 사항 -
○ 스크립트 실행 엔진은 MoonSharp (Lua 5.2 호환)입니다.
○ 사용 가능한 표준 라이브러리는 다음으로 제한됩니다.
table, string, math, bit32
※ io, os, debug, ffi, require 등은 사용할 수 없습니다.
○ 스크립트 타임아웃은 5000ms (5초)입니다.
타임아웃 시 실행이 강제 종료되며 오류로 처리됩니다.
○ 스크립트에서 파일 시스템에 접근할 수 없습니다 (require 포함).
○ 스크립트 내부에서 외부 스크립트를 호출하는 것은 지원하지 않습니다.
○ 픽셀 조작(getpixel/setpixel/getpixeldata)은 실제 입력 이미지에
접근하므로 최초 접근 시에만 GPU→CPU로의 데이터 전송이
발생합니다. 필요 없는 경우 호출을 생략하면 처리를 빠르게 할 수 있습니다.
- 파라미터 -
이펙트 패널에는 다음 4개의 트랙바(애니메이션 지원)가 있습니다.
각 값은 스크립트 내에서 obj.track0 ~ obj.track3으로 참조할 수 있습니다.
Track0 : 파라미터 0 (기본값: 0, 범위: 최솟값 ~ 최댓값)
Track1 : 파라미터 1 (기본값: 0, 범위: 최솟값 ~ 최댓값)
Track2 : 파라미터 2 (기본값: 0, 범위: 최솟값 ~ 최댓값)
Track3 : 파라미터 3 (기본값: 0, 범위: 최솟값 ~ 최댓값)
※ 각 트랙바는 애니메이션 슬라이더를 지원합니다(보간 있음).
※ 스크립트 편집기의 툴바에서 .lua 파일을 가져오기/내보내기할 수 있습니다.
- 전역 변수 -
다음 변수는 스크립트의 전역 범위에서 직접 참조할 수 있습니다.
time : 오브젝트 기준 현재 시간(초) [읽기 전용]
※ obj.time과 동일한 값입니다.
frame : 오브젝트 기준 현재 프레임 번호 [읽기 전용]
※ obj.frame과 동일한 값입니다.
totalframe : 오브젝트의 총 프레임 수 [읽기 전용]
※ obj.totalframe과 동일한 값입니다.
framerate : 프레임 레이트(fps) [읽기 전용]
※ obj.framerate와 동일한 값입니다.
timelineframe : 타임라인 전체 기준 현재 프레임 번호 [읽기 전용]
※ obj.frame은 오브젝트 시작 지점으로부터의 상대 프레임이지만,
이 값은 타임라인 시작 지점으로부터의 절대 프레임입니다.
timelinetime : 타임라인 전체 기준 현재 시간(초) [읽기 전용]
layer : 오브젝트가 배치된 레이어 번호 [읽기 전용]
※ obj.layer와 동일한 값입니다.
obj : 오브젝트 정보 테이블 (아래「obj 테이블」참조)
scene : 씬 정보 테이블 (아래「scene 테이블」참조)
ymm4 : YMM4 고유 메타 정보 테이블 (아래 'ymm4 테이블' 참조)
anim : 애니메이션용 유틸리티 테이블 (아래 'anim 테이블' 참조)
- scene 테이블 -
scene.width : 씬(프로젝트)의 가로 해상도(픽셀) [읽기 전용]
scene.height : 씬(프로젝트)의 세로 해상도(픽셀) [읽기 전용]
- obj 테이블 - 변수 -
다음 변수는 오브젝트의 현재 렌더링 정보를 보유합니다.
※ 읽기 전용으로 표시되지 않은 것은 스크립트 내에서 변경 가능하며, 변경된 값이 렌더링에 반영됩니다.
○ 좌표·오프셋
obj.x : 표시 기준 좌표 X [읽기 전용]
※ AviUtl2 사양의「표시 기준 좌표 X」에 해당합니다.
※ 스크립트 내에서 변경해도 읽기 복원이 이루어지지 않아 무효입니다.
※ 구현 상 DrawDescription.Draw.X에서 설정되며,
스크립트 실행 후 변경 내용이 반영됩니다.
obj.y : 표시 기준 좌표 Y [읽기 전용 상당]
※ 구현 상 DrawDescription.Draw.Y에서 설정됩니다.
obj.z : 표시 기준 좌표 Z [읽기 전용 상당]
※ 구현 상 DrawDescription.Draw.Z에서 설정됩니다.
obj.ox : 중심 오프셋 X (변경 가능)
※ 구현 상 DrawDescription.CenterPoint.X (inDesc)에서 설정됩니다.
※ AviUtl2 사양의「기준 좌표로부터의 상대 좌표 X(obj.ox)」에 해당하지만,
이 플러그인에서는 CenterPoint(중심점 오프셋)로 처리됩니다.
obj.oy : 중심 오프셋 Y (변경 가능)
※ 구현 상 DrawDescription.CenterPoint.Y (inDesc)에서 설정됩니다.
○ 확대율·변형
obj.zoom : 확대율(변경 가능)
※ 0.0이 등배가 아니라 1.0이 등배입니다(AviUtl2 호환).
※ 구현 상 ZoomX와 ZoomY의 평균값(zoomAvg)으로 산출됩니다.
※ 출력 시 obj.zoom * (1 ± obj.aspect)로 X/Y 각각의 Zoom으로 전개됩니다.
obj.aspect : 종횡비(변경 가능) 범위: -1.0 ~ 1.0
※ 양수 값은 X 방향으로 축소, 음수 값은 Y 방향으로 축소.
※ 구현 상 (ZoomX - ZoomY) / (ZoomX + ZoomY)로 산출됩니다.
obj.sx : X 방향 확대율 (변경 가능) 1.0이 100%
※ YMM4 고유의 정밀한 독립 스케일 제어입니다.
※ zoom/aspect 변경보다 우선하여 반영됩니다.
obj.sy : Y 방향 확대율 (변경 가능) 1.0이 100%
※ YMM4 고유의 정밀한 독립 스케일 제어입니다.
※ zoom/aspect 변경보다 우선하여 반영됩니다.
obj.alpha : 불투명도(변경 가능) 범위: 0.0 ~ 255.0
※ AviUtl2에서는 0.0~1.0이지만, 이 플러그인에서는 0.0~255.0입니다.
※ 구현 상 DrawDescription.Opacity * 255에서 설정됩니다.
※ 출력 시 255로 나누어 0.0~1.0으로 정규화됩니다(Clamp 있음).
※ 기본 스크립트에서는 obj.alpha = math.min(time * 255, 255)가
설정되어 있으며, 페이드인의 기본 구현으로 되어 있습니다.
○ 회전
obj.rx : X 축 회전 각도(변경 가능) 단위: 도(°), 360.0에서 한 바퀴
※ 구현 상 DrawDescription.Rotation.X에서 설정됩니다.
obj.ry : Y 축 회전 각도(변경 가능) 단위: 도(°), 360.0에서 한 바퀴
※ 구현 상 DrawDescription.Rotation.Y에서 설정됩니다.
obj.rz : Z 축 회전 각도(변경 가능) 단위: 도(°), 360.0에서 한 바퀴
※ 구현 상 DrawDescription.Rotation.Z에서 설정됩니다.
obj.rxr : X축 회전 각도(라디안) (변경 가능)
※ rx와 동시에 변경된 경우 이것이 우선 반영됩니다.
obj.ryr : Y축 회전 각도(라디안) (변경 가능)
※ ry와 동시에 변경된 경우 이것이 우선 반영됩니다.
obj.rzr : Z축 회전 각도(라디안) (변경 가능)
※ rz와 동시에 변경된 경우 이것이 우선 반영됩니다.
○ 이미지 크기
obj.w : 입력 이미지의 가로 픽셀 수 [읽기 전용]
※ 구현 상 D2D의 GetImageLocalBounds에서 산출된 정수값입니다.
obj.h : 입력 이미지의 세로 픽셀 수 [읽기 전용]
※ 구현 상 D2D의 GetImageLocalBounds에서 산출된 정수값입니다.
obj.hw : 입력 이미지 가로 픽셀 수의 절반 (= obj.w / 2) [ReadOnly]
obj.hh : 입력 이미지 세로 픽셀 수의 절반 (= obj.h / 2) [ReadOnly]
obj.diagonal : 입력 이미지의 대각선 길이 (= math.sqrt(w*w + h*h)) [ReadOnly]
obj.cx : 이미지의 중심 X 좌표 (= obj.w / 2) [읽기 전용]
※ 픽셀 조작에서 중심 좌표의 참조값입니다.
obj.cy : 이미지의 중심 Y 좌표 (= obj.h / 2) [읽기 전용]
○ 시간·프레임
obj.time : 오브젝트 기준 현재 시간(초) [읽기 전용]
※ 전역 변수 time과 동일한 값입니다.
※ 구현 상 EffectDescription.ItemPosition.Time.TotalSeconds에서 설정됩니다.
obj.frame : 오브젝트 기준 현재 프레임 번호 [읽기 전용]
※ 전역 변수 frame과 동일한 값입니다.
※ 구현 상 EffectDescription.ItemPosition.Frame에서 설정됩니다.
obj.totalframe: 오브젝트의 총 프레임 수 [읽기 전용]
※ 전역 변수 totalframe과 동일한 값입니다.
※ 구현 상 EffectDescription.ItemDuration.Frame에서 설정됩니다.
obj.framerate : 프레임 레이트(fps) [읽기 전용]
※ 전역 변수 framerate와 동일한 값입니다.
※ 구현 상 EffectDescription.FPS에서 설정됩니다.
○ 트랙바
obj.track0 : 이펙트 패널의 Track0 현재값 [읽기 전용]
※ 애니메이션 보간 후의 값입니다.
obj.track1 : 이펙트 패널의 Track1 현재값 [읽기 전용]
obj.track2 : 이펙트 패널의 Track2 현재값 [읽기 전용]
obj.track3 : 이펙트 패널의 Track3 현재값 [읽기 전용]
○ 레이어
obj.layer : 오브젝트가 배치된 레이어 번호 [읽기 전용]
※ 전역 변수 layer와 동일한 값입니다.
※ 구현 상 EffectDescription.Layer에서 설정됩니다.
- obj 테이블 - 변수의 변경과 렌더링 반영 -
스크립트 실행 후, 다음 변수만이 렌더링 정보로 읽기 복원됩니다(반영됩니다).
반영되는 변수:
obj.x, obj.y, obj.z
obj.ox, obj.oy
obj.zoom, obj.aspect
obj.alpha
obj.rx, obj.ry, obj.rz
※ obj.w, obj.h, obj.cx, obj.cy, obj.frame, obj.time,
obj.totalframe, obj.framerate, obj.track0 ~ obj.track3,
obj.layer는 읽기 전용이며, 변경해도 렌더링에 반영되지 않습니다.
출력값 산출 공식:
ZoomX = obj.zoom * (1.0 + obj.aspect)
ZoomY = obj.zoom * (1.0 - obj.aspect)
Opacity = Clamp(obj.alpha / 255.0, 0.0, 1.0)
Draw = (obj.x, obj.y, obj.z)
CenterPoint = (obj.ox, obj.oy)
Rotation = (obj.rx, obj.ry, obj.rz)
- obj 테이블 - 함수 -
○ obj.getpixel(x, y)
지정 좌표의 픽셀 정보를 취득합니다.
※ 최초 호출 시 GPU→CPU로의 이미지 데이터 전송이 발생합니다(처리 부하 수반).
※ 픽셀 좌표는 이미지의 좌상단을 (0, 0)으로 하며, 오른쪽·아래 방향이 양수입니다.
※ 취득값은 프리멀티플라이드 알파를 역변환한 스트레이트 알파 상당의 값입니다.
x : X 좌표 (0 ~ obj.w - 1)
y : Y 좌표 (0 ~ obj.h - 1)
반환값 : r, g, b, a의 4개 값(다중 반환)
r = 빨간색 성분 (0.0 ~ 255.0)
g = 초록색 성분 (0.0 ~ 255.0)
b = 파란색 성분 (0.0 ~ 255.0)
a = 알파값 (0.0 ~ 255.0)
※ 범위 밖의 좌표를 지정하면 (0, 0, 0, 0)을 반환합니다.
예: r, g, b, a = obj.getpixel(10, 20)
○ obj.setpixel(x, y, r, g, b [, a])
지정 좌표의 픽셀 정보를 덮어씁니다.
※ 호출 시 자동으로 픽셀 데이터가「변경됨」으로 표시되며,
스크립트 종료 후 변경된 이미지가 출력됩니다.
※ 내부에서는 프리멀티플라이드 알파 형식(BGRA)으로 보유합니다.
setpixel 시에 premultiplied 변환이 이루어집니다.
x : X 좌표 (0 ~ obj.w - 1)
y : Y 좌표 (0 ~ obj.h - 1)
r : 빨간색 성분 (0.0 ~ 255.0)
g : 초록색 성분 (0.0 ~ 255.0)
b : 파란색 성분 (0.0 ~ 255.0)
a : 알파값 (생략 시 255.0)
예: obj.setpixel(10, 20, 255, 0, 0, 128)
○ obj.getpixeldata()
전체 픽셀 데이터에 일괄 접근하기 위한 프록시 오브젝트를 반환합니다.
※ getpixel/setpixel에 비해 빠르게 픽셀을 조작할 수 있습니다.
※ 최초 호출 시 GPU→CPU로의 이미지 데이터 전송이 발생합니다(처리 부하 수반).
반환값 : PixelDataProxy 오브젝트
.width : 이미지의 가로 픽셀 수 (= obj.w)
.height : 이미지의 세로 픽셀 수 (= obj.h)
:get(index) : 인덱스 지정으로 채널값 취득
:set(index, value) : 인덱스 지정으로 채널값 설정
인덱스 사양:
인덱스는 1부터 시작합니다(Lua 관례에 따름).
채널 순서는 R, G, B, A의 반복입니다.
pixel(x, y)의 R 채널 인덱스 =
(y * obj.w + x) * 4 + 1
pixel(x, y)의 G 채널 인덱스 =
(y * obj.w + x) * 4 + 2
pixel(x, y)의 B 채널 인덱스 =
(y * obj.w + x) * 4 + 3
pixel(x, y)의 A 채널 인덱스 =
(y * obj.w + x) * 4 + 4
※ 알파(채널 4)를 변경하면 RGB도 비율 변환됩니다.
※ RGB 채널을 변경하면 premultiplied 변환이 이루어집니다.
※ 취득값은 get(index)와 마찬가지로 스트레이트 알파 상당입니다.
예:
local pd = obj.getpixeldata()
local idx = (10 * obj.w + 20) * 4 + 1 -- (x=20, y=10)의 R 채널
local r = pd:get(idx)
pd:set(idx, 128)
○ obj.putpixeldata()
호환성을 위해 정의된 빈 구현 함수입니다(no-op).
※ AviUtl 스크립트에서는 getpixeldata/putpixeldata 조합으로 사용하지만,
이 플러그인에서는 setpixel/set에 의한 변경이 자동으로 반영되므로,
이 함수를 호출할 필요가 없습니다.
- ymm4 테이블 -
YMM4 고유의 메타 정보를 유지하는 테이블입니다. 모두 ReadOnly입니다.
ymm4.group_index : 그룹 제어 내 현재 인덱스 (0부터 시작)
ymm4.group_count : 그룹 제어 내 총 아이템 수
ymm4.group_ratio : 그룹 내 진행 비율 (group_index / group_count)
ymm4.timeline_totalframe: 타임라인 전체의 총 프레임 수
ymm4.timeline_totaltime : 타임라인 전체의 총 시간(초)
ymm4.time_ratio : 현재 재생 위치 비율 (0.0 ~ 1.0)
ymm4.is_saving : 동영상 출력 중인지 여부 (출력 중에만 true)
ymm4.is_playing : 재생 중인지 여부 (재생 중에만 true)
ymm4.is_paused : 일시 정지 중인지 여부 (일시 정지 중에만 true)
ymm4.scene_id : 현재 씬을 고유하게 식별하는 문자열 (Guid)
- anim 테이블 -
애니메이션 계산에 편리한 순수 유틸리티 함수/상수 그룹입니다.
anim.tau : 원주율의 2배 (math.pi * 2)
anim.e : 오일러 수 (math.exp(1))
anim.phi : 황금비 ((1 + math.sqrt(5)) / 2)
anim.sqrt2 : 2의 제곱근 (math.sqrt(2))
anim.lerp(a, b, t) : a와 b를 t(0.0~1.0)로 선형 보간
anim.smoothstep(e0, e1, x): e0과 e1 사이를 매끄럽게 보간
anim.smootherstep(e0, e1, x): e0과 e1 사이의 더 부드러운 에르미트 보간 (2차 도함수까지 연속)
anim.clamp(v, lo, hi) : 값 v를 lo~hi 범위로 제한
anim.map(v, a1, b1, a2, b2): a1~b1 범위의 값 v를 a2~b2 범위로 매핑
anim.norm(v, lo, hi) : 값 v가 lo~hi 범위에서 차지하는 비율(0.0~1.0) 반환
anim.wrap(v, lo, hi) : 값 v를 lo~hi 범위 내에서 루프시킴
anim.pingpong(t, len) : 0~len 범위를 왕복하는 값
anim.sign(v) : 값 v의 부호 반환 (양수=1, 음수=-1, 0=0)
anim.oscillate(t, lo, hi, freq): freq 주파수로 lo~hi를 매끄럽게 왕복(사인파)
anim.triangle(t, freq) : freq 주파수로 0.0~1.0을 왕복하는 삼각파
anim.square(t, freq) : freq 주파수로 1.0과 0.0을 전환하는 구형파
anim.duration(t, dur) : 시간 dur에 대한 현재 비율(0.0~1.0, clamp 적용)
anim.delay(t, d) : 시간 d 경과 후 시작되는 시간 (0 이하는 0)
anim.ease_in(t) : 2차 이즈 인(가속)
anim.ease_out(t) : 2차 이즈 아웃(감속)
anim.ease_in_out(t) : 2차 이즈 인/아웃 (가속 후 감속)
anim.elastic(t) : 튕기는 듯한 스프링 이징
anim.back(t) : 범위를 살짝 넘었다가 돌아오는 이징
anim.step(edge, x) : x가 edge 이상이면 1.0, 미만이면 0.0 반환
anim.fract(v) : 값 v의 소수 부분만 반환
anim.bounce(t) : 바운스 이징
anim.hsv_to_rgb(h, s, v): HSV (색상 0~360, 채도 0~1, 명도 0~1)를 RGB로 변환
anim.rgb_to_hsv(r, g, b): RGB (0~255)를 HSV로 변환
anim.noise(x, y, z) : 1차원~3차원의 부드러운 노이즈 (-1.0 ~ 1.0)
anim.rand(min, max, s) : 시드값 s에 기반한 안정적인 난수 생성
anim.len(x, y) : 벡터 (x, y)의 길이(노름)를 가져옵니다
anim.dist(x1, y1, x2, y2): 두 점 (x1, y1)과 (x2, y2) 사이의 거리를 가져옵니다
anim.dot(x1, y1, x2, y2): 두 벡터 (x1, y1)과 (x2, y2)의 내적을 가져옵니다
anim.normalize(x, y) : 벡터 (x, y)를 정규화하여 방향 벡터(Tuple)를 반환합니다
anim.polar(r, a) : 반지름 r, 각도 a(도)에서 (x, y) 이동량(Tuple)을 가져옴
anim.rotate(x, y, a) : 좌표 (x, y)를 a(도)만큼 회전시킨 좌표(Tuple)를 가져옴
anim.bezier(t, p0, p1, p2, p3): t(0.0~1.0)에서의 3차 베지어 곡선 값을 계산
- 사용 가능한 표준 라이브러리 -
math 라이브러리:
math.abs, math.ceil, math.cos, math.exp, math.floor,
math.fmod, math.huge, math.log, math.max, math.min,
math.modf, math.pi, math.random, math.randomseed,
math.sin, math.sqrt, math.tan, math.atan, math.atan2,
math.deg, math.rad, math.ldexp, math.frexp,
math.sinh, math.cosh, math.tanh, math.type,
math.tointeger, math.maxinteger, math.mininteger
string 라이브러리:
string.format, string.len, string.sub, string.upper,
string.lower, string.rep, string.reverse, string.find,
string.match, string.gmatch, string.gsub, string.byte,
string.char, string.dump, string.pack, string.unpack,
string.packsize
table 라이브러리:
table.insert, table.remove, table.sort,
table.concat, table.unpack, table.move
bit32 라이브러리:
bit32.band, bit32.bor, bit32.bxor, bit32.bnot,
bit32.lshift, bit32.rshift, bit32.arshift,
bit32.extract, bit32.replace,
bit32.btest, bit32.countlz, bit32.countrz
기본 함수:
type, tostring, tonumber, select, error, assert, print,
ipairs, pairs, next, unpack,
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen,
pcall, xpcall
- 스크립트 예 -
○ 페이드인(기본 스크립트)
obj.alpha = math.min(time * 255, 255)
○ 페이드아웃
obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)
○ Track0으로 투명도 제어
obj.alpha = obj.track0
○ 시간에 따라 회전
obj.rz = time * 90 -- 1초에 90도 회전
○ 픽셀의 빨간색 성분을 반전하기
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 - r, g, b, a)
end
end
○ getpixeldata를 사용한 그레이스케일 변환(고속)
local pd = obj.getpixeldata()
local w = pd.width
local h = pd.height
for y = 0, h - 1 do
for x = 0, w - 1 do
local base = (y * w + x) * 4
local r = pd:get(base + 1)
local g = pd:get(base + 2)
local b = pd:get(base + 3)
local a = pd:get(base + 4)
local gray = r * 0.299 + g * 0.587 + b * 0.114
pd:set(base + 1, gray)
pd:set(base + 2, gray)
pd:set(base + 3, gray)
end
end
○ Track0으로 줌 제어 (1.0 = 등배)
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- 미지원·제한 사항 -
× AviUtl2의 obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 등은 지원하지 않습니다.
× AviUtl2의 obj.rand(), obj.rand1(), obj.setfont(), obj.mes() 등은 지원하지 않습니다.
× AviUtl2의 obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 등은 지원하지 않습니다.
× AviUtl2의 scene 테이블의 scene.set(), scene.get() 등의 함수는 지원하지 않습니다.
(scene.width와 scene.height의 읽기만 지원)
× 파일 접근(require, dofile, io 등)은 지원하지 않습니다.
× obj.z를 변경하면 렌더링에 반영되지만(ReadBack에 포함),
3D 렌더링 지원은 제한적입니다.
× 스크립트 타임아웃(5초)을 초과하면 실행이 강제 종료됩니다.
무한 루프가 발생하지 않도록 구현 시 주의가 필요합니다.
× AviUtl2의 --track@, --check@ 등의 헤더 디렉티브는 지원하지 않습니다.
파라미터는 Track0 ~ Track3만 사용할 수 있습니다.
+413
ファイルの表示
@@ -0,0 +1,413 @@
- 关于 Lua 脚本特效 -
YukkuriMovieMaker4 的"Lua 脚本"视频特效使用
Lua 语言编写脚本。
脚本引擎采用 MoonSharp(兼容 Lua 5.2)。
* 本特效为独立实现,与 AviUtl2 的脚本规范不同。
* 与 AviUtl2 的脚本文件(*.anm2 等)为不同规范。
* 由于 IsAviUtlSupported = false,不支持面向 AviUtl 的 EXO 输出。
- 注意事项 -
○ 脚本执行引擎为 MoonSharp(兼容 Lua 5.2)。
○ 可用的标准库仅限以下内容:
table, string, math, bit32
* io、os、debug、ffi、require 等不可使用。
○ 脚本超时时间为 5000ms(5 秒)。
超时时,执行将被强制终止并视为错误。
○ 脚本无法访问文件系统(包括 require)。
○ 不支持从脚本内部调用外部脚本。
○ 像素操作(getpixel/setpixel/getpixeldata)会访问实际输入图像,
因此仅在首次访问时发生 GPU→CPU 的数据传输。
不需要时省略调用可加快处理速度。
- 参数 -
特效面板包含以下 4 个轨道条(支持动画)。
各值在脚本中可通过 obj.track0 ~ obj.track3 引用。
Track0:参数 0(默认值:0,范围:最小值 ~ 最大值)
Track1:参数 1(默认值:0,范围:最小值 ~ 最大值)
Track2:参数 2(默认值:0,范围:最小值 ~ 最大值)
Track3:参数 3(默认值:0,范围:最小值 ~ 最大值)
* 每个轨道条均支持动画滑块(含插值)。
* 可通过脚本编辑器工具栏导入/导出 .lua 文件。
- 全局变量 -
以下变量可在脚本的全局作用域中直接引用。
time : 相对于对象的当前时间(秒)[只读]
* 与 obj.time 的值相同。
frame : 相对于对象的当前帧编号 [只读]
* 与 obj.frame 的值相同。
totalframe : 对象的总帧数 [只读]
* 与 obj.totalframe 的值相同。
framerate : 帧率(fps)[只读]
* 与 obj.framerate 的值相同。
timelineframe : 相对于整个时间轴的当前帧编号 [只读]
* obj.frame 是从对象起点的相对帧,
而此值是从时间轴起点的绝对帧。
timelinetime : 相对于整个时间轴的当前时间(秒)[只读]
layer : 对象所在的图层编号 [只读]
* 与 obj.layer 的值相同。
obj : 对象信息表(参见下文"obj 表")
scene : 场景信息表(参见下文"scene 表")
ymm4 : YMM4专有的元数据表 (参见下文“ymm4 表”)
anim : 动画专用工具表 (参见下文“anim 表”)
- scene 表 -
scene.width : 场景(项目)的水平分辨率(像素)[只读]
scene.height : 场景(项目)的垂直分辨率(像素)[只读]
- obj 表 - 变量 -
以下变量保存对象当前的绘制信息。
* 未标注"只读"的变量可在脚本中修改,修改后的值将反映到绘制中。
○ 坐标·偏移
obj.x : 显示基准坐标 X [只读]
* 对应 AviUtl2 规范的"显示基准坐标 X"。
* 在脚本内修改无效,不会被回读。
* 内部由 DrawDescription.Draw.X 设置,
脚本执行后更改内容才会生效。
obj.y : 显示基准坐标 Y [相当于只读]
* 内部由 DrawDescription.Draw.Y 设置。
obj.z : 显示基准坐标 Z [相当于只读]
* 内部由 DrawDescription.Draw.Z 设置。
obj.ox : 中心偏移 X(可修改)
* 内部由 DrawDescription.CenterPoint.X (inDesc) 设置。
* 对应 AviUtl2 规范的"从基准坐标的相对坐标 X (obj.ox)",
但在本插件中作为 CenterPoint(中心点偏移)处理。
obj.oy : 中心偏移 Y(可修改)
* 内部由 DrawDescription.CenterPoint.Y (inDesc) 设置。
○ 缩放·变形
obj.zoom : 缩放比例(可修改)
* 等倍为 1.0 而非 0.0(兼容 AviUtl2)。
* 内部由 ZoomX 与 ZoomY 的平均值(zoomAvg)计算得出。
* 输出时以 obj.zoom * (1 ± obj.aspect) 展开为 X/Y 各自的 Zoom。
obj.aspect : 宽高比(可修改),范围:-1.0 ~ 1.0
* 正值在 X 方向缩小,负值在 Y 方向缩小。
* 内部由 (ZoomX - ZoomY) / (ZoomX + ZoomY) 计算得出。
obj.sx : X方向缩放率 (可修改) 1.0为100%
※ YMM4专有的精确独立缩放控制。
※ 优先于 zoom/aspect 的修改生效。
obj.sy : Y方向缩放率 (可修改) 1.0为100%
※ YMM4专有的精确独立缩放控制。
※ 优先于 zoom/aspect 的修改生效。
obj.alpha : 不透明度(可修改),范围:0.0 ~ 255.0
* AviUtl2 为 0.0~1.0,本插件为 0.0~255.0。
* 内部由 DrawDescription.Opacity * 255 设置。
* 输出时除以 255 并归一化为 0.0~1.0(含 Clamp)。
* 默认脚本设置了 obj.alpha = math.min(time * 255, 255),
作为淡入的默认实现。
○ 旋转
obj.rx : X 轴旋转角度(可修改),单位:度(°),360.0 为一圈
* 内部由 DrawDescription.Rotation.X 设置。
obj.ry : Y 轴旋转角度(可修改),单位:度(°),360.0 为一圈
* 内部由 DrawDescription.Rotation.Y 设置。
obj.rz : Z 轴旋转角度(可修改),单位:度(°),360.0 为一圈
* 内部由 DrawDescription.Rotation.Z 设置。
obj.rxr : X轴旋转角度(弧度) (可修改)
※ 若与rx同时修改,将优先反映此值。
obj.ryr : Y轴旋转角度(弧度) (可修改)
※ 若与ry同时修改,将优先反映此值。
obj.rzr : Z轴旋转角度(弧度) (可修改)
※ 若与rz同时修改,将优先反映此值。
○ 图像尺寸
obj.w : 输入图像的水平像素数 [只读]
* 内部为从 D2D 的 GetImageLocalBounds 计算得出的整数值。
obj.h : 输入图像的垂直像素数 [只读]
* 内部为从 D2D 的 GetImageLocalBounds 计算得出的整数值。
obj.hw : 输入图像水平像素数的一半 (= obj.w / 2) [ReadOnly]
obj.hh : 输入图像垂直像素数的一半 (= obj.h / 2) [ReadOnly]
obj.diagonal : 输入图像的对角线长度 (= math.sqrt(w*w + h*h)) [ReadOnly]
obj.cx : 图像中心 X 坐标(= obj.w / 2)[只读]
* 像素操作中中心坐标的参考值。
obj.cy : 图像中心 Y 坐标(= obj.h / 2)[只读]
○ 时间·帧
obj.time : 相对于对象的当前时间(秒)[只读]
* 与全局变量 time 的值相同。
* 内部由 EffectDescription.ItemPosition.Time.TotalSeconds 设置。
obj.frame : 相对于对象的当前帧编号 [只读]
* 与全局变量 frame 的值相同。
* 内部由 EffectDescription.ItemPosition.Frame 设置。
obj.totalframe: 对象的总帧数 [只读]
* 与全局变量 totalframe 的值相同。
* 内部由 EffectDescription.ItemDuration.Frame 设置。
obj.framerate : 帧率(fps)[只读]
* 与全局变量 framerate 的值相同。
* 内部由 EffectDescription.FPS 设置。
○ 轨道条
obj.track0 : 特效面板 Track0 的当前值 [只读]
* 动画插值后的值。
obj.track1 : 特效面板 Track1 的当前值 [只读]
obj.track2 : 特效面板 Track2 的当前值 [只读]
obj.track3 : 特效面板 Track3 的当前值 [只读]
○ 图层
obj.layer : 对象所在的图层编号 [只读]
* 与全局变量 layer 的值相同。
* 内部由 EffectDescription.Layer 设置。
- obj 表 - 变量修改与绘制反映 -
脚本执行后,仅以下变量会被回读到绘制信息中(生效)。
生效的变量:
obj.x, obj.y, obj.z
obj.ox, obj.oy
obj.zoom, obj.aspect
obj.alpha
obj.rx, obj.ry, obj.rz
* obj.w、obj.h、obj.cx、obj.cy、obj.frame、obj.time、
obj.totalframe、obj.framerate、obj.track0 ~ obj.track3、
obj.layer 为只读,修改后不会反映到绘制中。
输出值计算公式:
ZoomX = obj.zoom * (1.0 + obj.aspect)
ZoomY = obj.zoom * (1.0 - obj.aspect)
Opacity = Clamp(obj.alpha / 255.0, 0.0, 1.0)
Draw = (obj.x, obj.y, obj.z)
CenterPoint = (obj.ox, obj.oy)
Rotation = (obj.rx, obj.ry, obj.rz)
- obj 表 - 函数 -
○ obj.getpixel(x, y)
获取指定坐标的像素信息。
* 首次调用时发生 GPU→CPU 的图像数据传输(存在处理开销)。
* 像素坐标以图像左上角为 (0, 0),向右和向下为正方向。
* 返回值为将预乘 Alpha 逆转换后的直通 Alpha 等效值。
x :X 坐标(0 ~ obj.w - 1)
y :Y 坐标(0 ~ obj.h - 1)
返回值 :r, g, b, a 共 4 个值(多值返回)
r = 红色分量(0.0 ~ 255.0)
g = 绿色分量(0.0 ~ 255.0)
b = 蓝色分量(0.0 ~ 255.0)
a = Alpha 值(0.0 ~ 255.0)
* 超出范围的坐标返回 (0, 0, 0, 0)。
示例:r, g, b, a = obj.getpixel(10, 20)
○ obj.setpixel(x, y, r, g, b [, a])
覆写指定坐标的像素信息。
* 调用时像素数据自动标记为"已修改",
脚本结束后输出修改后的图像。
* 内部以预乘 Alpha 格式(BGRA)保存,
setpixel 时进行预乘转换。
x :X 坐标(0 ~ obj.w - 1)
y :Y 坐标(0 ~ obj.h - 1)
r :红色分量(0.0 ~ 255.0)
g :绿色分量(0.0 ~ 255.0)
b :蓝色分量(0.0 ~ 255.0)
a :Alpha 值(省略时为 255.0)
示例:obj.setpixel(10, 20, 255, 0, 0, 128)
○ obj.getpixeldata()
返回用于批量访问所有像素数据的代理对象。
* 与 getpixel/setpixel 相比,像素操作速度更快。
* 首次调用时发生 GPU→CPU 的图像数据传输(存在处理开销)。
返回值 :PixelDataProxy 对象
.width :图像水平像素数(= obj.w)
.height :图像垂直像素数(= obj.h)
:get(index) :通过索引获取通道值
:set(index, value) :通过索引设置通道值
索引规则:
索引从 1 开始(遵循 Lua 惯例)。
通道顺序为 R、G、B、A 循环。
pixel(x, y) 的 R 通道索引 =
(y * obj.w + x) * 4 + 1
pixel(x, y) 的 G 通道索引 =
(y * obj.w + x) * 4 + 2
pixel(x, y) 的 B 通道索引 =
(y * obj.w + x) * 4 + 3
pixel(x, y) 的 A 通道索引 =
(y * obj.w + x) * 4 + 4
* 修改 Alpha(通道 4)时,RGB 也会按比例转换。
* 修改 RGB 通道时,会进行预乘转换。
* 获取值与 get(index) 相同,为直通 Alpha 等效值。
示例:
local pd = obj.getpixeldata()
local idx = (10 * obj.w + 20) * 4 + 1 -- (x=20, y=10) 的 R 通道
local r = pd:get(idx)
pd:set(idx, 128)
○ obj.putpixeldata()
为兼容性而定义的空实现函数(no-op)。
* AviUtl 脚本中 getpixeldata/putpixeldata 组合使用,
但本插件中 setpixel/set 的修改会自动反映,
因此无需调用此函数。
- ymm4 表 -
保存YMM4专有元数据的表。全部为 ReadOnly。
ymm4.group_index : 组控制中的当前索引 (从0开始)
ymm4.group_count : 组控制中的总项目数
ymm4.group_ratio : 组内进度比例 (group_index / group_count)
ymm4.timeline_totalframe: 整个时间轴的总帧数
ymm4.timeline_totaltime : 整个时间轴的总时间(秒)
ymm4.time_ratio : 当前播放位置的比例 (0.0 ~ 1.0)
ymm4.is_saving : 视频是否正在导出中 (仅在导出时为true)
ymm4.is_playing : 是否正在播放中 (仅在播放时为true)
ymm4.is_paused : 是否处于暂停中 (仅在暂停时为true)
ymm4.scene_id : 当前场景的唯一识别字符串 (Guid)
- anim 表 -
便于动画计算的纯工具函数及常量表。
anim.tau : 圆周率的两倍 (math.pi * 2)
anim.e : 欧拉数 (math.exp(1))
anim.phi : 黄金分割率 ((1 + math.sqrt(5)) / 2)
anim.sqrt2 : 2的平方根 (math.sqrt(2))
anim.lerp(a, b, t) : 将a与b按t(0.0~1.0)进行线性插值
anim.smoothstep(e0, e1, x): 在e0和e1之间进行平滑过渡插值
anim.smootherstep(e0, e1, x): e0 和 e1 之间更平滑的埃尔米特插值 (二阶导数连续)
anim.clamp(v, lo, hi) : 将值v限制在lo~hi范围内
anim.map(v, a1, b1, a2, b2): 将范围a1~b1内的值v映射至a2~b2范围
anim.norm(v, lo, hi) : 获取值v在lo~hi范围内的比例(0.0~1.0)
anim.wrap(v, lo, hi) : 使值v在lo~hi范围内循环
anim.pingpong(t, len) : 在0~len之间往复变化的值
anim.sign(v) : 获取值v的符号 (正=1, 负=-1, 零=0)
anim.oscillate(t, lo, hi, freq): 以freq频率在lo与hi之间平滑往复(正弦波)
anim.triangle(t, freq) : 以freq频率在0.0~1.0之间往复的三角波
anim.square(t, freq) : 以freq频率在1.0与0.0之间切换的方波
anim.duration(t, dur) : 针对持续时间dur的当前比例(0.0~1.0, 含clamp)
anim.delay(t, d) : 经过时间d后开始计时的值 (小于0则为0)
anim.ease_in(t) : 二次加速缓动
anim.ease_out(t) : 二次减速缓动
anim.ease_in_out(t) : 二次缓入缓出 (先加速后减速)
anim.elastic(t) : 弹性弹簧缓动
anim.back(t) : 略微越界后返回的缓动
anim.step(edge, x) : 若x大于等于edge则返回1.0,否则返回0.0
anim.fract(v) : 仅获取值v的小数部分
anim.bounce(t) : 弹跳缓动
anim.hsv_to_rgb(h, s, v): 将HSV (色相0~360, 饱和度0~1, 明度0~1) 转为 RGB
anim.rgb_to_hsv(r, g, b): 将RGB (0~255) 转为 HSV
anim.noise(x, y, z) : 1维~3维的平滑噪声 (-1.0~1.0)
anim.rand(min, max, s) : 基于种子 s 的稳定随机数
anim.len(x, y) : 获取向量 (x, y) 的长度 (范数)
anim.dist(x1, y1, x2, y2): 获取两点 (x1, y1) 和 (x2, y2) 之间的距离
anim.dot(x1, y1, x2, y2): 获取两个向量 (x1, y1) 和 (x2, y2) 的点积
anim.normalize(x, y) : 归一化向量 (x, y) 返回方向向量 (Tuple)
anim.polar(r, a) : 通过半径 r 和角度 a(度) 获取 (x, y) 坐标的元组
anim.rotate(x, y, a) : 获取将坐标 (x, y) 旋转 a(度) 后的坐标元组
anim.bezier(t, p0, p1, p2, p3): 计算 t(0.0~1.0) 时的三次贝塞尔曲线值
- 可用标准库 -
math 库:
math.abs, math.ceil, math.cos, math.exp, math.floor,
math.fmod, math.huge, math.log, math.max, math.min,
math.modf, math.pi, math.random, math.randomseed,
math.sin, math.sqrt, math.tan, math.atan, math.atan2,
math.deg, math.rad, math.ldexp, math.frexp,
math.sinh, math.cosh, math.tanh, math.type,
math.tointeger, math.maxinteger, math.mininteger
string 库:
string.format, string.len, string.sub, string.upper,
string.lower, string.rep, string.reverse, string.find,
string.match, string.gmatch, string.gsub, string.byte,
string.char, string.dump, string.pack, string.unpack,
string.packsize
table 库:
table.insert, table.remove, table.sort,
table.concat, table.unpack, table.move
bit32 库:
bit32.band, bit32.bor, bit32.bxor, bit32.bnot,
bit32.lshift, bit32.rshift, bit32.arshift,
bit32.extract, bit32.replace,
bit32.btest, bit32.countlz, bit32.countrz
基本函数:
type, tostring, tonumber, select, error, assert, print,
ipairs, pairs, next, unpack,
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen,
pcall, xpcall
- 脚本示例 -
○ 淡入(默认脚本)
obj.alpha = math.min(time * 255, 255)
○ 淡出
obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)
○ 用 Track0 控制不透明度
obj.alpha = obj.track0
○ 随时间旋转
obj.rz = time * 90 -- 每秒旋转 90 度
○ 反转像素红色分量
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 - r, g, b, a)
end
end
○ 使用 getpixeldata 进行灰度转换(高速)
local pd = obj.getpixeldata()
local w = pd.width
local h = pd.height
for y = 0, h - 1 do
for x = 0, w - 1 do
local base = (y * w + x) * 4
local r = pd:get(base + 1)
local g = pd:get(base + 2)
local b = pd:get(base + 3)
local a = pd:get(base + 4)
local gray = r * 0.299 + g * 0.587 + b * 0.114
pd:set(base + 1, gray)
pd:set(base + 2, gray)
pd:set(base + 3, gray)
end
end
○ 用 Track0 控制缩放(1.0 = 等倍)
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- 不支持项目·限制事项 -
× 不支持 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly()、obj.load() 等。
× 不支持 AviUtl2 的 obj.rand()、obj.rand1()、obj.setfont()、obj.mes() 等。
× 不支持 AviUtl2 的 obj.setoption()、obj.getoption()、obj.getvalue()、obj.setanchor() 等。
× 不支持 AviUtl2 scene 表中的 scene.set()、scene.get() 等函数。
(仅支持读取 scene.width 和 scene.height)
× 不支持文件访问(require、dofile、io 等)。
× 修改 obj.z 会反映到绘制中(包含在 ReadBack 中),
但 3D 绘制支持有限。
× 超过脚本超时时间(5 秒)时,执行将被强制终止。
实现时需注意避免出现无限循环。
× 不支持 AviUtl2 的 --track@、--check@ 等头部指令。
参数仅可使用 Track0 ~ Track3。
+413
ファイルの表示
@@ -0,0 +1,413 @@
- 關於 Lua 腳本特效 -
YukkuriMovieMaker4 的「Lua 腳本」視訊特效使用
Lua 語言編寫腳本。
腳本引擎採用 MoonSharp(相容 Lua 5.2)。
* 本特效為獨立實作,與 AviUtl2 的腳本規範不同。
* 與 AviUtl2 的腳本檔案(*.anm2 等)為不同規範。
* 由於 IsAviUtlSupported = false,不支援面向 AviUtl 的 EXO 輸出。
- 注意事項 -
○ 腳本執行引擎為 MoonSharp(相容 Lua 5.2)。
○ 可用的標準函式庫僅限以下內容:
table, string, math, bit32
* io、os、debug、ffi、require 等不可使用。
○ 腳本逾時時間為 5000ms(5 秒)。
逾時時,執行將被強制終止並視為錯誤。
○ 腳本無法存取檔案系統(包括 require)。
○ 不支援從腳本內部呼叫外部腳本。
○ 像素操作(getpixel/setpixel/getpixeldata)會存取實際輸入影像,
因此僅在首次存取時發生 GPU→CPU 的資料傳輸。
不需要時省略呼叫可加快處理速度。
- 參數 -
特效面板包含以下 4 個軌道條(支援動畫)。
各值在腳本中可透過 obj.track0 ~ obj.track3 參照。
Track0:參數 0(預設值:0,範圍:最小值 ~ 最大值)
Track1:參數 1(預設值:0,範圍:最小值 ~ 最大值)
Track2:參數 2(預設值:0,範圍:最小值 ~ 最大值)
Track3:參數 3(預設值:0,範圍:最小值 ~ 最大值)
* 每個軌道條均支援動畫滑桿(含插值)。
* 可透過腳本編輯器工具列匯入/匯出 .lua 檔案。
- 全域變數 -
以下變數可在腳本的全域範圍內直接參照。
time : 相對於物件的當前時間(秒)[唯讀]
* 與 obj.time 的值相同。
frame : 相對於物件的當前影格編號 [唯讀]
* 與 obj.frame 的值相同。
totalframe : 物件的總影格數 [唯讀]
* 與 obj.totalframe 的值相同。
framerate : 影格率(fps)[唯讀]
* 與 obj.framerate 的值相同。
timelineframe : 相對於整個時間軸的當前影格編號 [唯讀]
* obj.frame 是從物件起點的相對影格,
而此值是從時間軸起點的絕對影格。
timelinetime : 相對於整個時間軸的當前時間(秒)[唯讀]
layer : 物件所在的圖層編號 [唯讀]
* 與 obj.layer 的值相同。
obj : 物件資訊表(參見下文「obj 表」)
scene : 場景資訊表(參見下文「scene 表」)
ymm4 : YMM4專有的元數據表 (參見下文「ymm4 表」)
anim : 動畫專用工具表 (參見下文「anim 表」)
- scene 表 -
scene.width : 場景(專案)的水平解析度(像素)[唯讀]
scene.height : 場景(專案)的垂直解析度(像素)[唯讀]
- obj 表 - 變數 -
以下變數保存物件當前的繪製資訊。
* 未標注「唯讀」的變數可在腳本中修改,修改後的值將反映至繪製中。
○ 座標·偏移
obj.x : 顯示基準座標 X [唯讀]
* 對應 AviUtl2 規範的「顯示基準座標 X」。
* 在腳本內修改無效,不會被回讀。
* 內部由 DrawDescription.Draw.X 設定,
腳本執行後更改內容才會生效。
obj.y : 顯示基準座標 Y [相當於唯讀]
* 內部由 DrawDescription.Draw.Y 設定。
obj.z : 顯示基準座標 Z [相當於唯讀]
* 內部由 DrawDescription.Draw.Z 設定。
obj.ox : 中心偏移 X(可修改)
* 內部由 DrawDescription.CenterPoint.X (inDesc) 設定。
* 對應 AviUtl2 規範的「從基準座標的相對座標 X (obj.ox)」,
但在本外掛中作為 CenterPoint(中心點偏移)處理。
obj.oy : 中心偏移 Y(可修改)
* 內部由 DrawDescription.CenterPoint.Y (inDesc) 設定。
○ 縮放·變形
obj.zoom : 縮放比例(可修改)
* 等倍為 1.0 而非 0.0(相容 AviUtl2)。
* 內部由 ZoomX 與 ZoomY 的平均值(zoomAvg)計算得出。
* 輸出時以 obj.zoom * (1 ± obj.aspect) 展開為 X/Y 各自的 Zoom。
obj.aspect : 長寬比(可修改),範圍:-1.0 ~ 1.0
* 正值在 X 方向縮小,負值在 Y 方向縮小。
* 內部由 (ZoomX - ZoomY) / (ZoomX + ZoomY) 計算得出。
obj.sx : X方向縮放率 (可修改) 1.0為100%
※ YMM4專有的精確獨立縮放控制。
※ 優先於 zoom/aspect 的修改生效。
obj.sy : Y方向縮放率 (可修改) 1.0為100%
※ YMM4專有的精確獨立縮放控制。
※ 優先於 zoom/aspect 的修改生效。
obj.alpha : 不透明度(可修改),範圍:0.0 ~ 255.0
* AviUtl2 為 0.0~1.0,本外掛為 0.0~255.0。
* 內部由 DrawDescription.Opacity * 255 設定。
* 輸出時除以 255 並正規化為 0.0~1.0(含 Clamp)。
* 預設腳本設定了 obj.alpha = math.min(time * 255, 255),
作為淡入的預設實作。
○ 旋轉
obj.rx : X 軸旋轉角度(可修改),單位:度(°),360.0 為一圈
* 內部由 DrawDescription.Rotation.X 設定。
obj.ry : Y 軸旋轉角度(可修改),單位:度(°),360.0 為一圈
* 內部由 DrawDescription.Rotation.Y 設定。
obj.rz : Z 軸旋轉角度(可修改),單位:度(°),360.0 為一圈
* 內部由 DrawDescription.Rotation.Z 設定。
obj.rxr : X軸旋轉角度(弧度) (可修改)
※ 若與rx同時修改,將優先反映此值。
obj.ryr : Y軸旋轉角度(弧度) (可修改)
※ 若與ry同時修改,將優先反映此值。
obj.rzr : Z軸旋轉角度(弧度) (可修改)
※ 若與rz同時修改,將優先反映此值。
○ 影像尺寸
obj.w : 輸入影像的水平像素數 [唯讀]
* 內部為從 D2D 的 GetImageLocalBounds 計算得出的整數值。
obj.h : 輸入影像的垂直像素數 [唯讀]
* 內部為從 D2D 的 GetImageLocalBounds 計算得出的整數值。
obj.hw : 輸入圖像水平像素數的一半 (= obj.w / 2) [ReadOnly]
obj.hh : 輸入圖像垂直像素數的一半 (= obj.h / 2) [ReadOnly]
obj.diagonal : 輸入影像的對角線長度 (= math.sqrt(w*w + h*h)) [ReadOnly]
obj.cx : 影像中心 X 座標(= obj.w / 2)[唯讀]
* 像素操作中中心座標的參考值。
obj.cy : 影像中心 Y 座標(= obj.h / 2)[唯讀]
○ 時間·影格
obj.time : 相對於物件的當前時間(秒)[唯讀]
* 與全域變數 time 的值相同。
* 內部由 EffectDescription.ItemPosition.Time.TotalSeconds 設定。
obj.frame : 相對於物件的當前影格編號 [唯讀]
* 與全域變數 frame 的值相同。
* 內部由 EffectDescription.ItemPosition.Frame 設定。
obj.totalframe: 物件的總影格數 [唯讀]
* 與全域變數 totalframe 的值相同。
* 內部由 EffectDescription.ItemDuration.Frame 設定。
obj.framerate : 影格率(fps)[唯讀]
* 與全域變數 framerate 的值相同。
* 內部由 EffectDescription.FPS 設定。
○ 軌道條
obj.track0 : 特效面板 Track0 的當前值 [唯讀]
* 動畫插值後的值。
obj.track1 : 特效面板 Track1 的當前值 [唯讀]
obj.track2 : 特效面板 Track2 的當前值 [唯讀]
obj.track3 : 特效面板 Track3 的當前值 [唯讀]
○ 圖層
obj.layer : 物件所在的圖層編號 [唯讀]
* 與全域變數 layer 的值相同。
* 內部由 EffectDescription.Layer 設定。
- obj 表 - 變數修改與繪製反映 -
腳本執行後,僅以下變數會被回讀至繪製資訊中(生效)。
生效的變數:
obj.x, obj.y, obj.z
obj.ox, obj.oy
obj.zoom, obj.aspect
obj.alpha
obj.rx, obj.ry, obj.rz
* obj.w、obj.h、obj.cx、obj.cy、obj.frame、obj.time、
obj.totalframe、obj.framerate、obj.track0 ~ obj.track3、
obj.layer 為唯讀,修改後不會反映至繪製中。
輸出值計算公式:
ZoomX = obj.zoom * (1.0 + obj.aspect)
ZoomY = obj.zoom * (1.0 - obj.aspect)
Opacity = Clamp(obj.alpha / 255.0, 0.0, 1.0)
Draw = (obj.x, obj.y, obj.z)
CenterPoint = (obj.ox, obj.oy)
Rotation = (obj.rx, obj.ry, obj.rz)
- obj 表 - 函式 -
○ obj.getpixel(x, y)
取得指定座標的像素資訊。
* 首次呼叫時發生 GPU→CPU 的影像資料傳輸(存在處理負擔)。
* 像素座標以影像左上角為 (0, 0),向右和向下為正方向。
* 傳回值為將預乘 Alpha 逆轉換後的直通 Alpha 等效值。
x :X 座標(0 ~ obj.w - 1)
y :Y 座標(0 ~ obj.h - 1)
傳回值 :r, g, b, a 共 4 個值(多值傳回)
r = 紅色分量(0.0 ~ 255.0)
g = 綠色分量(0.0 ~ 255.0)
b = 藍色分量(0.0 ~ 255.0)
a = Alpha 值(0.0 ~ 255.0)
* 超出範圍的座標傳回 (0, 0, 0, 0)。
範例:r, g, b, a = obj.getpixel(10, 20)
○ obj.setpixel(x, y, r, g, b [, a])
覆寫指定座標的像素資訊。
* 呼叫時像素資料自動標記為「已修改」,
腳本結束後輸出修改後的影像。
* 內部以預乘 Alpha 格式(BGRA)保存,
setpixel 時進行預乘轉換。
x :X 座標(0 ~ obj.w - 1)
y :Y 座標(0 ~ obj.h - 1)
r :紅色分量(0.0 ~ 255.0)
g :綠色分量(0.0 ~ 255.0)
b :藍色分量(0.0 ~ 255.0)
a :Alpha 值(省略時為 255.0)
範例:obj.setpixel(10, 20, 255, 0, 0, 128)
○ obj.getpixeldata()
傳回用於批次存取所有像素資料的代理物件。
* 與 getpixel/setpixel 相比,像素操作速度更快。
* 首次呼叫時發生 GPU→CPU 的影像資料傳輸(存在處理負擔)。
傳回值 :PixelDataProxy 物件
.width :影像水平像素數(= obj.w)
.height :影像垂直像素數(= obj.h)
:get(index) :透過索引取得通道值
:set(index, value) :透過索引設定通道值
索引規則:
索引從 1 開始(遵循 Lua 慣例)。
通道順序為 R、G、B、A 循環。
pixel(x, y) 的 R 通道索引 =
(y * obj.w + x) * 4 + 1
pixel(x, y) 的 G 通道索引 =
(y * obj.w + x) * 4 + 2
pixel(x, y) 的 B 通道索引 =
(y * obj.w + x) * 4 + 3
pixel(x, y) 的 A 通道索引 =
(y * obj.w + x) * 4 + 4
* 修改 Alpha(通道 4)時,RGB 也會按比例轉換。
* 修改 RGB 通道時,會進行預乘轉換。
* 取得值與 get(index) 相同,為直通 Alpha 等效值。
範例:
local pd = obj.getpixeldata()
local idx = (10 * obj.w + 20) * 4 + 1 -- (x=20, y=10) 的 R 通道
local r = pd:get(idx)
pd:set(idx, 128)
○ obj.putpixeldata()
為相容性而定義的空實作函式(no-op)。
* AviUtl 腳本中 getpixeldata/putpixeldata 組合使用,
但本外掛中 setpixel/set 的修改會自動反映,
因此無需呼叫此函式。
- ymm4 表 -
保存YMM4專有元數據的表。全部為 ReadOnly。
ymm4.group_index : 群組控制中的當前索引 (從0開始)
ymm4.group_count : 群組控制中的總項目數
ymm4.group_ratio : 群組內進度比例 (group_index / group_count)
ymm4.timeline_totalframe: 整個時間軸的總幀數
ymm4.timeline_totaltime : 整個時間軸的總時間(秒)
ymm4.time_ratio : 當前播放位置的比例 (0.0 ~ 1.0)
ymm4.is_saving : 影片是否正在輸出中 (僅在輸出時為true)
ymm4.is_playing : 是否正在播放中 (僅在播放時為true)
ymm4.is_paused : 是否處於暫停中 (僅在暫停時為true)
ymm4.scene_id : 當前場景的唯一識別字串 (Guid)
- anim 表 -
便於動畫計算的純工具函數及常數表。
anim.tau : 圓周率的兩倍 (math.pi * 2)
anim.e : 歐拉數 (math.exp(1))
anim.phi : 黃金比例 ((1 + math.sqrt(5)) / 2)
anim.sqrt2 : 2的平方根 (math.sqrt(2))
anim.lerp(a, b, t) : 將a與b按t(0.0~1.0)進行線性插值
anim.smoothstep(e0, e1, x): 在e0和e1之間進行平滑過渡插值
anim.smootherstep(e0, e1, x): e0 和 e1 之間更平滑的埃爾米特插值 (二階導數連續)
anim.clamp(v, lo, hi) : 將值v限制在lo~hi範圍內
anim.map(v, a1, b1, a2, b2): 將範圍a1~b1內的值v映射至a2~b2範圍
anim.norm(v, lo, hi) : 獲取值v在lo~hi範圍內的比例(0.0~1.0)
anim.wrap(v, lo, hi) : 使值v在lo~hi範圍內循環
anim.pingpong(t, len) : 在0~len之間往復變化的值
anim.sign(v) : 獲取值v的符號 (正=1, 負=-1, 零=0)
anim.oscillate(t, lo, hi, freq): 以freq頻率在lo與hi之間平滑往復(正弦波)
anim.triangle(t, freq) : 以freq頻率在0.0~1.0之間往復的三角波
anim.square(t, freq) : 以freq頻率在1.0與0.0之間切換的方波
anim.duration(t, dur) : 針對持續時間dur的當前比例(0.0~1.0, 含clamp)
anim.delay(t, d) : 經過時間d後開始計時的值 (小於0則為0)
anim.ease_in(t) : 二次加速緩動
anim.ease_out(t) : 二次減速緩動
anim.ease_in_out(t) : 二次緩入緩出 (先加速後減速)
anim.elastic(t) : 彈性彈簧緩動
anim.back(t) : 略微越界後返回的緩動
anim.step(edge, x) : 若x大於等於edge則返回1.0,否則返回0.0
anim.fract(v) : 僅獲取值v的小數部分
anim.bounce(t) : 彈跳緩動
anim.hsv_to_rgb(h, s, v): 將HSV (色相0~360, 飽和度0~1, 明度0~1) 轉為 RGB
anim.rgb_to_hsv(r, g, b): 將RGB (0~255) 轉為 HSV
anim.noise(x, y, z) : 1維~3維的平滑雜訊 (-1.0~1.0)
anim.rand(min, max, s) : 基於種子 s 的穩定亂數
anim.len(x, y) : 獲取向量 (x, y) 的長度 (範數)
anim.dist(x1, y1, x2, y2): 獲取兩點 (x1, y1) 和 (x2, y2) 之間的距離
anim.dot(x1, y1, x2, y2): 獲取兩個向量 (x1, y1) 和 (x2, y2) 的內積
anim.normalize(x, y) : 正規化向量 (x, y) 返回方向向量 (Tuple)
anim.polar(r, a) : 透過半徑 r 和角度 a(度) 獲取 (x, y) 座標的元組
anim.rotate(x, y, a) : 獲取將座標 (x, y) 旋轉 a(度) 後的座標元組
anim.bezier(t, p0, p1, p2, p3): 計算 t(0.0~1.0) 時的三次貝茲曲線值
- 可用標準函式庫 -
math 函式庫:
math.abs, math.ceil, math.cos, math.exp, math.floor,
math.fmod, math.huge, math.log, math.max, math.min,
math.modf, math.pi, math.random, math.randomseed,
math.sin, math.sqrt, math.tan, math.atan, math.atan2,
math.deg, math.rad, math.ldexp, math.frexp,
math.sinh, math.cosh, math.tanh, math.type,
math.tointeger, math.maxinteger, math.mininteger
string 函式庫:
string.format, string.len, string.sub, string.upper,
string.lower, string.rep, string.reverse, string.find,
string.match, string.gmatch, string.gsub, string.byte,
string.char, string.dump, string.pack, string.unpack,
string.packsize
table 函式庫:
table.insert, table.remove, table.sort,
table.concat, table.unpack, table.move
bit32 函式庫:
bit32.band, bit32.bor, bit32.bxor, bit32.bnot,
bit32.lshift, bit32.rshift, bit32.arshift,
bit32.extract, bit32.replace,
bit32.btest, bit32.countlz, bit32.countrz
基本函式:
type, tostring, tonumber, select, error, assert, print,
ipairs, pairs, next, unpack,
setmetatable, getmetatable, rawget, rawset, rawequal, rawlen,
pcall, xpcall
- 腳本範例 -
○ 淡入(預設腳本)
obj.alpha = math.min(time * 255, 255)
○ 淡出
obj.alpha = math.max((obj.totalframe - obj.frame) / obj.framerate * 255, 0)
○ 用 Track0 控制不透明度
obj.alpha = obj.track0
○ 隨時間旋轉
obj.rz = time * 90 -- 每秒旋轉 90 度
○ 反轉像素紅色分量
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 - r, g, b, a)
end
end
○ 使用 getpixeldata 進行灰階轉換(高速)
local pd = obj.getpixeldata()
local w = pd.width
local h = pd.height
for y = 0, h - 1 do
for x = 0, w - 1 do
local base = (y * w + x) * 4
local r = pd:get(base + 1)
local g = pd:get(base + 2)
local b = pd:get(base + 3)
local a = pd:get(base + 4)
local gray = r * 0.299 + g * 0.587 + b * 0.114
pd:set(base + 1, gray)
pd:set(base + 2, gray)
pd:set(base + 3, gray)
end
end
○ 用 Track0 控制縮放(1.0 = 等倍)
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
- 不支援項目·限制事項 -
× 不支援 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly()、obj.load() 等。
× 不支援 AviUtl2 的 obj.rand()、obj.rand1()、obj.setfont()、obj.mes() 等。
× 不支援 AviUtl2 的 obj.setoption()、obj.getoption()、obj.getvalue()、obj.setanchor() 等。
× 不支援 AviUtl2 scene 表中的 scene.set()、scene.get() 等函式。
(僅支援讀取 scene.width 和 scene.height)
× 不支援檔案存取(require、dofile、io 等)。
× 修改 obj.z 會反映至繪製中(包含在 ReadBack 中),
但 3D 繪製支援有限。
× 超過腳本逾時時間(5 秒)時,執行將被強制終止。
實作時需注意避免出現無限迴圈。
× 不支援 AviUtl2 的 --track@、--check@ 等標頭指令。
參數僅可使用 Track0 ~ Track3。