コミットを比較

...
8 コミット
作成者 SHA1 メッセージ 日付
routersys a093c458a2 バージョンをv1.7.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.7.1 のコミットから作成しました
2026-06-28 22:47:30 +09:00
routersys 0e65bf1883 ネイティブ環境でのobj.load及びobj.effect対応 2026-06-28 22:39:09 +09:00
routersys d8f728b3f9 Direct2Dピクセル管理の責務分離 2026-06-28 16:17:19 +09:00
routersys 244e75a238 Transform書き戻し処理の共通化 2026-06-28 16:16:54 +09:00
routersys 75cc4bd62e トークン解析処理の共通化と抽出 2026-06-28 16:16:35 +09:00
routersys 6385dbeb6d ScriptDirectiveクラスの抽出分離 2026-06-28 16:16:02 +09:00
routersys bc395a0181 SceneObjectQueryを個別ファイルへ分離 2026-06-28 16:15:37 +09:00
routersys a0dec019fe 例外クラス群を個別ファイルへ分離 2026-06-28 16:15:02 +09:00
26個のファイルの変更、668行の追加、413行の削除

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

+25 -42
ファイルの表示
@@ -1,54 +1,37 @@
# v1.7.0 - Lua スクリプト for YMM4 # v1.7.1 - Lua スクリプト for YMM4
AviUtl のアニメーション効果スクリプト互換層に**映像エフェクトの適用(`obj.effect()`)**を 内部アーキテクチャの大幅なリファクタリングと、ネイティブ環境(LuaJIT)における
追加したリリースです。スクリプトから YMM4 に登録された映像エフェクトを呼び出し、 描画・映像エフェクトAPI(`obj.load` および `obj.effect`)の対応を行ったリリースです。
図形やピクセルで生成した画像へ連鎖適用できるようになりました。
--- ---
## 新機能 ## 新機能・機能改善
### 1. obj.effect() による YMM4 映像エフェクトの適用 ### 1. ネイティブ環境での obj.load および obj.effect 対応
`obj.effect(エフェクト名, パラメータ名, 値, パラメータ名, 値, ...)` を実装しました。 v1.7.0 では MoonSharp エンジンのみの対応であった図形生成(`obj.load`)および
スクリプトが生成した画像に対して、YMM4 の映像エフェクトを適用します。 YMM4映像エフェクト連鎖適用(`obj.effect`)が、ネイティブ(LuaJIT)環境でも完全に
利用可能になりました。
- エフェクト名は YMM4 の登録名または別名で指定します。`EffectFactories` から取得できる - ネイティブ環境でも高解像度(最大4K)の図形生成に対応し、メモリリークや
全映像エフェクト(標準エフェクトおよびユーザー製プラグインを含む)が対象です。 GC(ガベージコレクション)の負荷を排除した最高パフォーマンスで動作します。
- パラメータは表示名またはプロパティ名で指定します。型に応じて設定され、Animation は - これにより、`obj.load` や `obj.effect` を使用するスクリプトが自動的に
定数値、真偽値、列挙(名前または番号)、色(0xRRGGBB)、数値、文字列に対応します。 MoonSharp にフォールバックされる制限が解除されました。
- パラメータはキー/値のペアで複数同時に指定できます。
- `obj.effect` を複数回呼び出すと、呼んだ順に**独立したエフェクトインスタンス**として
連鎖適用されます。同じエフェクトを複数回重ねて適用することもできます。
- エフェクトは、スクリプトが生成した画像(図形やピクセル)または入力画像に対して、
YMM4 本体と同じ `SetInput` → `Update` → `Output` のチェーンで適用されます。
- パラメータはフレームごとに再評価されるため、`obj.time` などに応じて値を計算すれば
エフェクトのパラメータをアニメーションさせられます。
--- ---
## 注意事項 ## 内部実装の最適化(リファクタリング)
- `obj.effect`(および `obj.load`)は描画系 API のため MoonSharp エンジンで実行されます。 コードベースの保守性と安全性を高めるため、多岐にわたる設計改善を実施しました。
ネイティブ(LuaJIT)経路ではエフェクトは適用されません。
- エフェクトの登録名はローカライズされるため、指定名は実行環境の表示言語に依存する
場合があります。言語に依存させたくない場合は、英語の別名やプロパティ名を用いて
ください。
- Animation パラメータは定数値として設定されます。キーフレーム曲線は指定できません。
時間変化させたい場合はスクリプト側で値を計算してください。
- 指定したエフェクトが見つからない、または生成・更新に失敗した場合、その要求は安全に
スキップされ、画像はそのまま通過します。描画は停止しません。
- 対象エフェクトの解決は導入状況に依存します。ユーザー製エフェクトは未導入の場合、
名前が解決されずスキップされます。
--- - **責務の分離と抽出**
- Direct2D に関連するピクセルバッファ管理および変換処理を専用クラスへ分離しました。
## 内部実装 - トークン解析処理や Transform(座標・回転・拡大率等の変形パラメータ)の書き戻し処理を
共通化・抽出しました。
- スクリプトの `obj.effect` 呼び出しを実行コンテキストに記録し、スクリプト実行後に - `ScriptDirective`、`SceneObjectQuery`、各種例外クラス群をそれぞれ個別の
描画スレッドで Direct2D エフェクトチェーンとして適用する仕組みを追加しました。 ファイルへ分離し、設計の対称性と可読性を向上させました。
- `EffectFactories.VideoEffectFactories` を登録名・別名で索引し、リフレクションで - **アーキテクチャの堅牢化**
対象プロパティを解決してパラメータを設定します。 - ネイティブ環境との通信プロトコルを拡張し、タグ領域を拡大(256バイトから4096バイト)
- YMM4 の API 変更に対する多層フォールバックを実装しました。レジストリ構築、 することで、長文の引数を扱うエフェクトにおけるデータの欠落を完全に防止しました。
パラメータ解決、各エフェクトの生成・更新・適用をそれぞれ例外隔離し、失敗時は - ピクセルバッファのアロケーションを最小化するキャッシュ機構を導入し、
当該エフェクトをスキップして元画像を通過させます(描画自体は停止しません)。 描画フレームごとの無駄な配列確保を排除しました。
+1 -1
ファイルの表示
@@ -1,5 +1,5 @@
======================================== ========================================
Luaスクリプト for YMM4 v1.7.0 Luaスクリプト for YMM4 v1.7.1
======================================== ========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。 ピクセルを直接制御できるプラグインです。
+3
ファイルの表示
@@ -27,12 +27,15 @@
<Compile Include="..\LuaScript\Compat\MoonSharpBit32.cs" Link="Linked\MoonSharpBit32.cs" /> <Compile Include="..\LuaScript\Compat\MoonSharpBit32.cs" Link="Linked\MoonSharpBit32.cs" />
<Compile Include="..\LuaScript\Compat\Bit32.cs" Link="Linked\Bit32.cs" /> <Compile Include="..\LuaScript\Compat\Bit32.cs" Link="Linked\Bit32.cs" />
<Compile Include="..\LuaScript\Engine\ScriptEngineKind.cs" Link="Linked\ScriptEngineKind.cs" /> <Compile Include="..\LuaScript\Engine\ScriptEngineKind.cs" Link="Linked\ScriptEngineKind.cs" />
<Compile Include="..\LuaScript\Engine\ScriptDirective.cs" Link="Linked\ScriptDirective.cs" />
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" /> <Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" /> <Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" /> <Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" /> <Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
<Compile Include="..\LuaScript\SceneObjectQuery.cs" Link="Linked\SceneObjectQuery.cs" />
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" /> <Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlScript.cs" Link="Linked\AviUtlScript.cs" /> <Compile Include="..\LuaScript\Compat\AviUtlScript.cs" Link="Linked\AviUtlScript.cs" />
<Compile Include="..\LuaScript\Compat\ScriptParserHelper.cs" Link="Linked\ScriptParserHelper.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlParameterLayout.cs" Link="Linked\AviUtlParameterLayout.cs" /> <Compile Include="..\LuaScript\Compat\AviUtlParameterLayout.cs" Link="Linked\AviUtlParameterLayout.cs" />
<Compile Include="..\LuaScript\Compat\AviUtlRandom.cs" Link="Linked\AviUtlRandom.cs" /> <Compile Include="..\LuaScript\Compat\AviUtlRandom.cs" Link="Linked\AviUtlRandom.cs" />
<Compile Include="..\LuaScript\Compat\FigureRenderer.cs" Link="Linked\FigureRenderer.cs" /> <Compile Include="..\LuaScript\Compat\FigureRenderer.cs" Link="Linked\FigureRenderer.cs" />
+14 -12
ファイルの表示
@@ -9,6 +9,8 @@ namespace LuaScript.Tests
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native"); private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
private static readonly Func<string, int, SceneObjectInfo?> NoResolver = (_, _) => null; private static readonly Func<string, int, SceneObjectInfo?> NoResolver = (_, _) => null;
private static readonly Func<string, int, double, double, double, (byte[] buffer, int w, int h)> NoLoadFigure = (_, _, _, _, _) => ([], 1, 1);
private static readonly Action<string, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string, object>>> NoAddEffect = (_, _) => { };
private readonly LuaJitWorker _worker = new(NativeDir); private readonly LuaJitWorker _worker = new(NativeDir);
@@ -34,7 +36,7 @@ namespace LuaScript.Tests
bool ok = _worker.Execute( bool ok = _worker.Execute(
"obj.rz = obj.time * 90\nobj.alpha = 128", "obj.rz = obj.time * 90\nobj.alpha = 128",
fields, pixels, 4, 4, 5000, NoResolver, out bool dirty, out string? error); fields, pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoAddEffect, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.False(dirty); Assert.False(dirty);
@@ -69,7 +71,7 @@ namespace LuaScript.Tests
"local gray = r*0.299 + g*0.587 + b*0.114 " + "local gray = r*0.299 + g*0.587 + b*0.114 " +
"obj.setpixel(x,y,gray,gray,gray,a) end end"; "obj.setpixel(x,y,gray,gray,gray,a) end end";
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error); bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoAddEffect, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.True(dirty); Assert.True(dirty);
@@ -104,7 +106,7 @@ namespace LuaScript.Tests
"local gray=r*0.299+g*0.587+b*0.114 " + "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"; "pd:set(base+1,gray) pd:set(base+2,gray) pd:set(base+3,gray) end end";
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error); bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, NoLoadFigure, NoAddEffect, out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.True(dirty); Assert.True(dirty);
@@ -140,7 +142,7 @@ namespace LuaScript.Tests
for (int k = 1; k <= 5; k++) for (int k = 1; k <= 5; k++)
{ {
var fields = Fields(2, 2, k); var fields = Fields(2, 2, k);
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error); bool ok = _worker.Execute("obj.x = obj.time * 10", fields, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoAddEffect, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(k * 10d, fields[NativeProtocol.X]); Assert.Equal(k * 10d, fields[NativeProtocol.X]);
} }
@@ -155,12 +157,12 @@ namespace LuaScript.Tests
var fields = Fields(2, 2, 0d); var fields = Fields(2, 2, 0d);
bool timedOut = _worker.Execute( bool timedOut = _worker.Execute(
"local x=0 while true do x=x+1 end", fields, pixels, 2, 2, 1500, NoResolver, out _, out string? error); "local x=0 while true do x=x+1 end", fields, pixels, 2, 2, 1500, NoResolver, NoLoadFigure, NoAddEffect, out _, out _, out _, out _, out _, out string? error);
Assert.False(timedOut); Assert.False(timedOut);
Assert.Contains("timed out", error); Assert.Contains("timed out", error);
var fields2 = Fields(2, 2, 3d); var fields2 = Fields(2, 2, 3d);
bool ok = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, out _, out error); bool ok = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoAddEffect, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(3d, fields2[NativeProtocol.X]); Assert.Equal(3d, fields2[NativeProtocol.X]);
} }
@@ -182,7 +184,7 @@ namespace LuaScript.Tests
"obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " + "obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " +
"obj.sx = o.sy obj.rzr = o.rzr"; "obj.sx = o.sy obj.rzr = o.rzr";
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, resolver, out _, out string? error); bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoAddEffect, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(12d, fields[NativeProtocol.X]); Assert.Equal(12d, fields[NativeProtocol.X]);
@@ -214,13 +216,13 @@ namespace LuaScript.Tests
"local b = obj.getobject(\"a\") " + "local b = obj.getobject(\"a\") " +
"obj.x = a.x + b.x"; "obj.x = a.x + b.x";
bool ok = _worker.Execute(script, Fields(2, 2, 0d), pixels, 2, 2, 5000, resolver, out _, out string? error); bool ok = _worker.Execute(script, Fields(2, 2, 0d), pixels, 2, 2, 5000, resolver, NoLoadFigure, NoAddEffect, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(1, calls); Assert.Equal(1, calls);
var fields = Fields(2, 2, 0d); var fields = Fields(2, 2, 0d);
x = 20d; x = 20d;
ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, resolver, out _, out error); ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, resolver, NoLoadFigure, NoAddEffect, out _, out _, out _, out _, out _, out error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(2, calls); Assert.Equal(2, calls);
Assert.Equal(40d, fields[NativeProtocol.X]); Assert.Equal(40d, fields[NativeProtocol.X]);
@@ -237,7 +239,7 @@ namespace LuaScript.Tests
const string script = const string script =
"local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0"; "local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0";
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error); bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoAddEffect, out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
Assert.Equal(1d, fields[NativeProtocol.X]); Assert.Equal(1d, fields[NativeProtocol.X]);
@@ -251,12 +253,12 @@ namespace LuaScript.Tests
var pixels = new byte[16]; var pixels = new byte[16];
var fields = Fields(2, 2, 0d); var fields = Fields(2, 2, 0d);
bool ok = _worker.Execute("obj.x = missing.value", fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error); bool ok = _worker.Execute("obj.x = missing.value", fields, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoAddEffect, out _, out _, out _, out _, out _, out string? error);
Assert.False(ok); Assert.False(ok);
Assert.False(string.IsNullOrEmpty(error)); Assert.False(string.IsNullOrEmpty(error));
var fields2 = Fields(2, 2, 7d); var fields2 = Fields(2, 2, 7d);
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, out _, out error); bool ok2 = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoAddEffect, out _, out _, out _, out _, out _, out error);
Assert.True(ok2, error); Assert.True(ok2, error);
Assert.Equal(7d, fields2[NativeProtocol.X]); Assert.Equal(7d, fields2[NativeProtocol.X]);
} }
+3 -1
ファイルの表示
@@ -38,7 +38,9 @@ namespace LuaScript.Tests
[InlineData("--!moonsharp\nobj.setpixel(0,0,1,1,1)", "MoonSharp")] [InlineData("--!moonsharp\nobj.setpixel(0,0,1,1,1)", "MoonSharp")]
[InlineData("--!native\nobj.rz = 1", "Native")] [InlineData("--!native\nobj.rz = 1", "Native")]
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "MoonSharp")] [InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)", "MoonSharp")]
[InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)\nlocal r = obj.getpixel(0,0)", "MoonSharp")] [InlineData("obj.load(\"figure\", \"円\", 0xff0000, 100)\nlocal r = obj.getpixel(0,0)", "Native")]
[InlineData("obj.draw()", "MoonSharp")]
[InlineData("obj.draw()\nlocal r = obj.getpixel(0,0)", "MoonSharp")]
[InlineData("--!native\nobj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")] [InlineData("--!native\nobj.load(\"figure\", \"円\", 0xff0000, 100)", "Native")]
public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected) public void ResolveAuto_RoutesPixelScriptsToNative(string script, string expected)
{ {
+42
ファイルの表示
@@ -52,6 +52,8 @@ namespace LuaScript
public Func<SceneObjectResolver>? ResolverProvider { get; set; } public Func<SceneObjectResolver>? ResolverProvider { get; set; }
private const double Epsilon = 1e-10;
private readonly List<SceneObjectQuery> _objectQueries = []; private readonly List<SceneObjectQuery> _objectQueries = [];
public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries; public IReadOnlyList<SceneObjectQuery> ObjectQueries => _objectQueries;
@@ -133,6 +135,46 @@ namespace LuaScript
return false; return false;
} }
public void ApplyWriteBack(
double newSx, double newSy, double newZoom, double newAspect,
double newRx, double newRy, double newRz,
double newRxr, double newRyr, double newRzr)
{
double initialSx = Sx;
double initialSy = Sy;
double initialZoom = Zoom;
double initialAspect = Aspect;
Sx = newSx;
Sy = newSy;
Zoom = newZoom;
Aspect = newAspect;
bool sxsyChanged = Math.Abs(Sx - initialSx) > Epsilon || Math.Abs(Sy - initialSy) > Epsilon;
bool zoomAspectChanged = Math.Abs(Zoom - initialZoom) > Epsilon || Math.Abs(Aspect - initialAspect) > Epsilon;
if (zoomAspectChanged && !sxsyChanged)
{
Sx = Zoom * (1.0 + Aspect);
Sy = Zoom * (1.0 - Aspect);
}
double initialRxr = RxRad;
Rx = Math.Abs(newRxr - initialRxr) > Epsilon
? newRxr * (180d / Math.PI)
: newRx;
double initialRyr = RyRad;
Ry = Math.Abs(newRyr - initialRyr) > Epsilon
? newRyr * (180d / Math.PI)
: newRy;
double initialRzr = RzRad;
Rz = Math.Abs(newRzr - initialRzr) > Epsilon
? newRzr * (180d / Math.PI)
: newRz;
}
public unsafe (double r, double g, double b, double a) GetPixel(int x, int y) public unsafe (double r, double g, double b, double a) GetPixel(int x, int y)
{ {
EnsurePixelBuffer(); EnsurePixelBuffer();
+5 -21
ファイルの表示
@@ -49,13 +49,13 @@ namespace LuaScript.Compat
int sectionEnd = lines.Length; int sectionEnd = lines.Length;
for (int i = 0; i < lines.Length; i++) for (int i = 0; i < lines.Length; i++)
{ {
if (!IsSectionHeader(lines[i])) if (!ScriptParserHelper.IsSectionHeader(lines[i]))
continue; continue;
sectionStart = i + 1; sectionStart = i + 1;
sectionEnd = lines.Length; sectionEnd = lines.Length;
for (int j = sectionStart; j < lines.Length; j++) for (int j = sectionStart; j < lines.Length; j++)
{ {
if (IsSectionHeader(lines[j])) if (ScriptParserHelper.IsSectionHeader(lines[j]))
{ {
sectionEnd = j; sectionEnd = j;
break; break;
@@ -72,7 +72,7 @@ namespace LuaScript.Compat
private void ParseLine(string line) private void ParseLine(string line)
{ {
int i = SkipSpaces(line, 0); int i = ScriptParserHelper.SkipSpaces(line, 0);
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-') if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
return; return;
i += 2; i += 2;
@@ -80,7 +80,7 @@ namespace LuaScript.Compat
return; return;
int nameStart = i; int nameStart = i;
while (i < line.Length && IsNameChar(line[i])) while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
i++; i++;
if (i >= line.Length || line[i] != ':') if (i >= line.Length || line[i] != ':')
return; return;
@@ -174,27 +174,11 @@ namespace LuaScript.Compat
private static string FirstToken(string content) private static string FirstToken(string content)
{ {
int start = SkipSpaces(content, 0); int start = ScriptParserHelper.SkipSpaces(content, 0);
int i = start; int i = start;
while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t') while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t')
i++; i++;
return content.Substring(start, i - start); return content.Substring(start, i - start);
} }
private static bool IsSectionHeader(string line)
{
int i = SkipSpaces(line, 0);
return i < line.Length && line[i] == '@';
}
private static int SkipSpaces(string text, int index)
{
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
index++;
return index;
}
private static bool IsNameChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
} }
} }
+4 -20
ファイルの表示
@@ -26,7 +26,7 @@ namespace LuaScript.Compat
for (int i = 0; i < lines.Length; i++) for (int i = 0; i < lines.Length; i++)
{ {
if (!IsSectionHeader(lines[i])) if (!ScriptParserHelper.IsSectionHeader(lines[i]))
continue; continue;
hasSection = true; hasSection = true;
@@ -34,7 +34,7 @@ namespace LuaScript.Compat
sectionEnd = lines.Length; sectionEnd = lines.Length;
for (int j = sectionStart; j < lines.Length; j++) for (int j = sectionStart; j < lines.Length; j++)
{ {
if (IsSectionHeader(lines[j])) if (ScriptParserHelper.IsSectionHeader(lines[j]))
{ {
sectionEnd = j; sectionEnd = j;
break; break;
@@ -59,15 +59,9 @@ namespace LuaScript.Compat
return builder.ToString(); return builder.ToString();
} }
private static bool IsSectionHeader(string line)
{
int i = SkipSpaces(line, 0);
return i < line.Length && line[i] == '@';
}
private static void AppendDeclarations(string line, List<string> prelude) private static void AppendDeclarations(string line, List<string> prelude)
{ {
int i = SkipSpaces(line, 0); int i = ScriptParserHelper.SkipSpaces(line, 0);
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-') if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
return; return;
i += 2; i += 2;
@@ -75,7 +69,7 @@ namespace LuaScript.Compat
return; return;
int nameStart = i; int nameStart = i;
while (i < line.Length && IsNameChar(line[i])) while (i < line.Length && ScriptParserHelper.IsNameChar(line[i]))
i++; i++;
if (i >= line.Length || line[i] != ':') if (i >= line.Length || line[i] != ':')
return; return;
@@ -125,15 +119,5 @@ namespace LuaScript.Compat
if (trimmed.Length != 0) if (trimmed.Length != 0)
prelude.Add(trimmed); prelude.Add(trimmed);
} }
private static int SkipSpaces(string text, int index)
{
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
index++;
return index;
}
private static bool IsNameChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
} }
} }
+21
ファイルの表示
@@ -0,0 +1,21 @@
namespace LuaScript.Compat
{
internal static class ScriptParserHelper
{
public static bool IsSectionHeader(string line)
{
int i = SkipSpaces(line, 0);
return i < line.Length && line[i] == '@';
}
public static int SkipSpaces(string text, int index)
{
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
index++;
return index;
}
public static bool IsNameChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
}
+116 -3
ファイルの表示
@@ -27,6 +27,7 @@ namespace LuaScript.Engine
private readonly byte[] _lastCallbackTag = new byte[NativeProtocol.CallbackTagMax]; private readonly byte[] _lastCallbackTag = new byte[NativeProtocol.CallbackTagMax];
private int _lastCallbackTagLength = -1; private int _lastCallbackTagLength = -1;
private string _lastCallbackTagText = string.Empty; private string _lastCallbackTagText = string.Empty;
private byte[]? _resultBuffer;
public LuaJitWorker(string nativeDir) public LuaJitWorker(string nativeDir)
{ {
@@ -47,10 +48,20 @@ namespace LuaScript.Engine
int height, int height,
int timeoutMs, int timeoutMs,
Func<string, int, SceneObjectInfo?> resolveObject, Func<string, int, SceneObjectInfo?> resolveObject,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
out bool pixelsDirty, out bool pixelsDirty,
out bool bufferReplaced,
out byte[]? newPixels,
out int resultWidth,
out int resultHeight,
out string? error) out string? error)
{ {
pixelsDirty = false; pixelsDirty = false;
bufferReplaced = false;
newPixels = null;
resultWidth = width;
resultHeight = height;
error = null; error = null;
byte[] scriptBytes = Encoding.UTF8.GetBytes(script); byte[] scriptBytes = Encoding.UTF8.GetBytes(script);
@@ -92,7 +103,7 @@ namespace LuaScript.Engine
if (status != NativeProtocol.StatusCallback) if (status != NativeProtocol.StatusCallback)
break; break;
ResolveCallback(view, resolveObject); DispatchCallback(view, resolveObject, loadFigure, addEffect);
_workEvent.Set(); _workEvent.Set();
} }
@@ -108,14 +119,52 @@ namespace LuaScript.Engine
for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++) for (int i = NativeProtocol.FirstWritableField; i <= NativeProtocol.LastWritableField; i++)
fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8); fields[i] = view.ReadDouble(NativeProtocol.FieldsOffset + i * 8);
resultWidth = view.ReadInt32(NativeProtocol.OffWidth);
resultHeight = view.ReadInt32(NativeProtocol.OffHeight);
bufferReplaced = resultWidth != width || resultHeight != height;
pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0; pixelsDirty = view.ReadInt32(NativeProtocol.OffPixelsDirty) != 0;
if (pixelsDirty) if (pixelsDirty)
view.ReadArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length); {
if (bufferReplaced)
{
int pixelSize = resultWidth * resultHeight * 4;
if (_resultBuffer == null || _resultBuffer.Length < pixelSize)
_resultBuffer = new byte[pixelSize];
view.ReadArray(NativeProtocol.PixelOffset, _resultBuffer, 0, pixelSize);
newPixels = _resultBuffer;
}
else
{
view.ReadArray(NativeProtocol.PixelOffset, pixels, 0, pixels.Length);
}
}
return true; return true;
} }
private void ResolveCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject) private void DispatchCallback(
MemoryMappedViewAccessor view,
Func<string, int, SceneObjectInfo?> resolveObject,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure,
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
{
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
switch (kind)
{
case NativeProtocol.CbKindGetObject:
ResolveGetObjectCallback(view, resolveObject);
break;
case NativeProtocol.CbKindLoadFigure:
ResolveLoadFigureCallback(view, loadFigure);
break;
case NativeProtocol.CbKindEffect:
ResolveEffectCallback(view, addEffect);
break;
}
}
private void ResolveGetObjectCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
{ {
int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame); int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame);
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax); int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
@@ -145,6 +194,70 @@ namespace LuaScript.Engine
} }
} }
private void ResolveLoadFigureCallback(
MemoryMappedViewAccessor view,
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
long rOff = NativeProtocol.CallbackResultOffset;
int color = (int)view.ReadDouble(rOff + 0 * 8);
double size = view.ReadDouble(rOff + 1 * 8);
double lineWidth = view.ReadDouble(rOff + 2 * 8);
double aspect = view.ReadDouble(rOff + 3 * 8);
(byte[] buffer, int w, int h) result;
try { result = loadFigure(name, color, size, lineWidth, aspect); }
catch { result = (new byte[4], 1, 1); }
int pixelSize = result.w * result.h * 4;
long capacity = view.Capacity - NativeProtocol.PixelOffset;
if (pixelSize > capacity)
{
result = (new byte[4], 1, 1);
pixelSize = 4;
}
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
view.WriteArray(NativeProtocol.PixelOffset, result.buffer, 0, pixelSize);
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
{
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
if (segments.Length == 0)
return;
string effectName = segments[0];
var arguments = new List<KeyValuePair<string, object>>();
for (int i = 1; i + 1 < segments.Length; i += 2)
{
string key = segments[i];
string raw = segments[i + 1];
object value;
if (raw.Length > 0 && raw[0] == 'n')
value = double.TryParse(raw.AsSpan(1), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d) ? d : 0d;
else if (raw.Length > 0 && raw[0] == 'b')
value = raw.Length > 1 && raw[1] == '1';
else if (raw.Length > 0 && raw[0] == 's')
value = raw.Substring(1);
else
value = raw;
arguments.Add(new KeyValuePair<string, object>(key, value));
}
try { addEffect(effectName, arguments); }
catch { }
view.Write(NativeProtocol.OffCallbackFound, 1);
}
private string ResolveTag(int tagLen) private string ResolveTag(int tagLen)
{ {
if (tagLen == _lastCallbackTagLength && if (tagLen == _lastCallbackTagLength &&
+11 -36
ファイルの表示
@@ -78,42 +78,17 @@ namespace LuaScript.Engine
ctx.Oz = f[NativeProtocol.Oz]; ctx.Oz = f[NativeProtocol.Oz];
ctx.Alpha = f[NativeProtocol.Alpha]; ctx.Alpha = f[NativeProtocol.Alpha];
double initialSx = ctx.Sx; ctx.ApplyWriteBack(
double initialSy = ctx.Sy; f[NativeProtocol.Sx],
double initialZoom = ctx.Zoom; f[NativeProtocol.Sy],
double initialAspect = ctx.Aspect; f[NativeProtocol.Zoom],
f[NativeProtocol.Aspect],
ctx.Sx = f[NativeProtocol.Sx]; f[NativeProtocol.Rx],
ctx.Sy = f[NativeProtocol.Sy]; f[NativeProtocol.Ry],
ctx.Zoom = f[NativeProtocol.Zoom]; f[NativeProtocol.Rz],
ctx.Aspect = f[NativeProtocol.Aspect]; f[NativeProtocol.Rxr],
f[NativeProtocol.Ryr],
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > Epsilon || Math.Abs(ctx.Sy - initialSy) > Epsilon; f[NativeProtocol.Rzr]);
bool zoomAspectChanged = Math.Abs(ctx.Zoom - initialZoom) > Epsilon || Math.Abs(ctx.Aspect - initialAspect) > Epsilon;
if (zoomAspectChanged && !sxsyChanged)
{
ctx.Sx = ctx.Zoom * (1.0 + ctx.Aspect);
ctx.Sy = ctx.Zoom * (1.0 - ctx.Aspect);
}
double initialRxr = ctx.RxRad;
double rxrNew = f[NativeProtocol.Rxr];
ctx.Rx = Math.Abs(rxrNew - initialRxr) > Epsilon
? rxrNew * (180d / Math.PI)
: f[NativeProtocol.Rx];
double initialRyr = ctx.RyRad;
double ryrNew = f[NativeProtocol.Ryr];
ctx.Ry = Math.Abs(ryrNew - initialRyr) > Epsilon
? ryrNew * (180d / Math.PI)
: f[NativeProtocol.Ry];
double initialRzr = ctx.RzRad;
double rzrNew = f[NativeProtocol.Rzr];
ctx.Rz = Math.Abs(rzrNew - initialRzr) > Epsilon
? rzrNew * (180d / Math.PI)
: f[NativeProtocol.Rz];
} }
} }
} }
+11 -2
ファイルの表示
@@ -23,6 +23,9 @@ namespace LuaScript.Engine
public const int OffCallbackFrame = 32; public const int OffCallbackFrame = 32;
public const int OffCallbackTagLen = 36; public const int OffCallbackTagLen = 36;
public const int OffCallbackFound = 40; public const int OffCallbackFound = 40;
public const int OffCallbackKind = 44;
public const int OffLoadResultWidth = 48;
public const int OffLoadResultHeight = 52;
public const int HeaderSize = 64; public const int HeaderSize = 64;
@@ -36,10 +39,14 @@ namespace LuaScript.Engine
public const int ErrorMax = 4 * 1024; public const int ErrorMax = 4 * 1024;
public const int CallbackTagOffset = ErrorOffset + ErrorMax; public const int CallbackTagOffset = ErrorOffset + ErrorMax;
public const int CallbackTagMax = 256; public const int CallbackTagMax = 4096;
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax; public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
public const int CallbackResultCount = 8; public const int CallbackResultCount = 8;
public const int CbKindGetObject = 0;
public const int CbKindLoadFigure = 1;
public const int CbKindEffect = 2;
public const int CbExist = 0; public const int CbExist = 0;
public const int CbX = 1; public const int CbX = 1;
public const int CbY = 2; public const int CbY = 2;
@@ -113,7 +120,9 @@ namespace LuaScript.Engine
public const int FirstWritableField = X; public const int FirstWritableField = X;
public const int LastWritableField = Rzr; public const int LastWritableField = Rzr;
public const int MaxPixelBufferSize = 3840 * 2160 * 4;
public static long BufferSize(int width, int height) => public static long BufferSize(int width, int height) =>
PixelOffset + (long)width * height * 4; PixelOffset + Math.Max((long)width * height * 4, MaxPixelBufferSize);
} }
} }
+106
ファイルの表示
@@ -0,0 +1,106 @@
using System;
namespace LuaScript.Engine
{
internal static class ScriptDirective
{
public static ScriptEngineKind Resolve(string? script) =>
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
public static ScriptEngineKind ResolveAuto(string? script)
{
if (TryGetDirective(script, out var kind))
return kind;
if (UsesDrawingApi(script))
return ScriptEngineKind.MoonSharp;
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
}
public static bool UsesPixelApi(string? script) =>
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
public static bool UsesDrawingApi(string? script) =>
script is not null && (
script.Contains("obj.draw", StringComparison.Ordinal) ||
script.Contains("obj.setoption", StringComparison.Ordinal) ||
script.Contains("obj.copybuffer", StringComparison.Ordinal));
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
if (string.IsNullOrEmpty(script))
return false;
int index = 0;
int length = script.Length;
while (index < length)
{
int lineStart = index;
while (index < length && script[index] != '\n')
index++;
int lineEnd = index;
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
lineEnd--;
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
return true;
index++;
}
return false;
}
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
int i = start;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
return false;
i += 3;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
int tokenStart = i;
while (i < end && IsTokenChar(script[i]))
i++;
int tokenEnd = i;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i != end)
return false;
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Native;
return true;
}
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Gpu;
return true;
}
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Cpu;
return true;
}
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.MoonSharp;
return true;
}
return false;
}
private static bool IsTokenChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
}
-104
ファイルの表示
@@ -9,108 +9,4 @@ namespace LuaScript.Engine
Gpu, Gpu,
Cpu, Cpu,
} }
internal static class ScriptDirective
{
public static ScriptEngineKind Resolve(string? script) =>
TryGetDirective(script, out var kind) ? kind : ScriptEngineKind.MoonSharp;
public static ScriptEngineKind ResolveAuto(string? script)
{
if (TryGetDirective(script, out var kind))
return kind;
if (UsesDrawingApi(script))
return ScriptEngineKind.MoonSharp;
return UsesPixelApi(script) ? ScriptEngineKind.Native : ScriptEngineKind.MoonSharp;
}
public static bool UsesPixelApi(string? script) =>
script is not null && (script.Contains("getpixel", StringComparison.Ordinal) || script.Contains("setpixel", StringComparison.Ordinal));
public static bool UsesDrawingApi(string? script) =>
script is not null && (
script.Contains("obj.load", StringComparison.Ordinal) ||
script.Contains("obj.draw", StringComparison.Ordinal) ||
script.Contains("obj.effect", StringComparison.Ordinal) ||
script.Contains("obj.setoption", StringComparison.Ordinal) ||
script.Contains("obj.copybuffer", StringComparison.Ordinal));
private static bool TryGetDirective(string? script, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
if (string.IsNullOrEmpty(script))
return false;
int index = 0;
int length = script.Length;
while (index < length)
{
int lineStart = index;
while (index < length && script[index] != '\n')
index++;
int lineEnd = index;
if (lineEnd > lineStart && script[lineEnd - 1] == '\r')
lineEnd--;
if (TryParseDirectiveLine(script, lineStart, lineEnd, out kind))
return true;
index++;
}
return false;
}
private static bool TryParseDirectiveLine(string script, int start, int end, out ScriptEngineKind kind)
{
kind = ScriptEngineKind.MoonSharp;
int i = start;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i + 3 > end || script[i] != '-' || script[i + 1] != '-' || script[i + 2] != '!')
return false;
i += 3;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
int tokenStart = i;
while (i < end && IsTokenChar(script[i]))
i++;
int tokenEnd = i;
while (i < end && (script[i] == ' ' || script[i] == '\t'))
i++;
if (i != end)
return false;
var token = script.AsSpan(tokenStart, tokenEnd - tokenStart);
if (token.Equals("native", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Native;
return true;
}
if (token.Equals("gpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Gpu;
return true;
}
if (token.Equals("cpu", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.Cpu;
return true;
}
if (token.Equals("moonsharp", StringComparison.OrdinalIgnoreCase))
{
kind = ScriptEngineKind.MoonSharp;
return true;
}
return false;
}
private static bool IsTokenChar(char c) =>
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
} }
+1 -1
ファイルの表示
@@ -4,7 +4,7 @@
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF> <UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Version>1.7.0</Version> <Version>1.7.1</Version>
<Platforms>AnyCPU;x64</Platforms> <Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+39 -121
ファイルの表示
@@ -75,14 +75,7 @@ namespace LuaScript
private GraphicsDevicesAndContext? _ownCtx; private GraphicsDevicesAndContext? _ownCtx;
private ID2D1Bitmap1? _renderTarget; private PixelBufferManager? _pixelManager;
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 bool _isFirst = true;
private string _sourceScript = string.Empty; private string _sourceScript = string.Empty;
@@ -100,6 +93,7 @@ namespace LuaScript
{ {
_ownCtx = new GraphicsDevicesAndContext(devices); _ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx); disposer.Collect(_ownCtx);
_pixelManager = new PixelBufferManager(_ownCtx);
_context.ResolverProvider = GetFrameResolver; _context.ResolverProvider = GetFrameResolver;
return null; return null;
} }
@@ -226,13 +220,11 @@ namespace LuaScript
{ {
int bufW = ctx.ImageWidth; int bufW = ctx.ImageWidth;
int bufH = ctx.ImageHeight; int bufH = ctx.ImageHeight;
EnsureBitmaps(bufW, bufH); _pixelManager!.WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW, bufH);
WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW);
if (ctx.BufferReplaced) if (ctx.BufferReplaced)
UpdateTransformEffect(-bufW / 2f, -bufH / 2f); effectOutput = _pixelManager.GetTransformOutput(-bufW / 2f, -bufH / 2f);
else else
UpdateTransformEffect(bounds.Left, bounds.Top); effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
effectOutput = _transformEffect!.Output;
} }
else else
{ {
@@ -440,7 +432,10 @@ namespace LuaScript
bool ok = _nativeWorker.Execute( bool ok = _nativeWorker.Execute(
script, _nativeFields, buffer, imgW, imgH, NativeTimeoutMilliseconds, script, _nativeFields, buffer, imgW, imgH, NativeTimeoutMilliseconds,
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null, (tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
out bool dirty, out string? error); NativeLoadFigure,
(name, args) => ctx.AddEffect(new AviUtlEffectRequest(name, args)),
out bool dirty, out bool bufferReplaced, out byte[]? newPixels,
out int resultW, out int resultH, out string? error);
if (!ok) if (!ok)
{ {
@@ -453,10 +448,21 @@ namespace LuaScript
if (dirty) if (dirty)
{ {
EnsureBitmaps(imgW, imgH); int outW = bufferReplaced ? resultW : imgW;
WritePixelsToOutput(buffer, imgW); int outH = bufferReplaced ? resultH : imgH;
UpdateTransformEffect(bounds.Left, bounds.Top); byte[] outPixels = buffer;
effectOutput = _transformEffect!.Output;
if (bufferReplaced && newPixels != null)
{
outPixels = newPixels;
ctx.ReplaceBuffer(outPixels, outW, outH);
}
_pixelManager!.WritePixelsToOutput(outPixels, outW, outH);
if (bufferReplaced)
effectOutput = _pixelManager.GetTransformOutput(-outW / 2f, -outH / 2f);
else
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
return true; return true;
} }
@@ -464,48 +470,24 @@ namespace LuaScript
return false; return false;
} }
private static (byte[] buffer, int w, int h) NativeLoadFigure(string name, int color, double size, double lineWidth, double aspect)
{
aspect = Math.Clamp(aspect, -1d, 1d);
int boundingSize = Math.Max(1, (int)Math.Round(size));
double w = aspect >= 0d ? boundingSize * (1d - aspect) : boundingSize;
double h = aspect <= 0d ? boundingSize * (1d + aspect) : boundingSize;
int fw = Math.Max(1, (int)Math.Round(w));
int fh = Math.Max(1, (int)Math.Round(h));
var buffer = FigureRenderer.Render(name, fw, fh, color, lineWidth);
return (buffer, fw, fh);
}
private byte[] LoadInputPixels(RawRectF bounds, int width, int height) private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
{ {
_pixelLoaderSemaphore.Wait(); _pixelLoaderSemaphore.Wait();
try try
{ {
EnsureBitmaps(width, height); return _pixelManager!.LoadInputPixels(input!, bounds, 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 finally
{ {
@@ -513,64 +495,6 @@ namespace LuaScript
} }
} }
private unsafe void WritePixelsToOutput(byte[] pixels, int width)
{
fixed (byte* ptr = pixels)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
}
private void UpdateTransformEffect(float left, float top)
{
if (_transformEffect is null)
{
_transformEffect = new AffineTransform2D(_ownCtx!.DeviceContext);
_transformEffect.SetInput(0, _outputBitmap, true);
_cachedBounds = default;
}
if (_cachedBounds.Left != left || _cachedBounds.Top != top)
{
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(left, top);
_cachedBounds = new RawRectF(left, top, left, top);
}
}
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) protected override void Dispose(bool disposing)
{ {
if (disposing) if (disposing)
@@ -579,14 +503,8 @@ namespace LuaScript
_nativeWorker?.Dispose(); _nativeWorker?.Dispose();
_effectChain?.Dispose(); _effectChain?.Dispose();
_pixelLoaderSemaphore.Dispose(); _pixelLoaderSemaphore.Dispose();
_renderTarget?.Dispose(); _pixelManager?.Dispose();
_stagingBitmap?.Dispose(); _pixelManager = null;
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
+11 -33
ファイルの表示
@@ -573,39 +573,17 @@ namespace LuaScript
ctx.Oz = _objTable.Get("oz").CastToNumber() ?? ctx.Oz; ctx.Oz = _objTable.Get("oz").CastToNumber() ?? ctx.Oz;
ctx.Alpha = _objTable.Get("alpha").CastToNumber() ?? ctx.Alpha; ctx.Alpha = _objTable.Get("alpha").CastToNumber() ?? ctx.Alpha;
double initialSx = ctx.Sx; ctx.ApplyWriteBack(
double initialSy = ctx.Sy; _objTable.Get("sx").CastToNumber() ?? ctx.Sx,
double initialZoom = ctx.Zoom; _objTable.Get("sy").CastToNumber() ?? ctx.Sy,
double initialAspect = ctx.Aspect; _objTable.Get("zoom").CastToNumber() ?? ctx.Zoom,
_objTable.Get("aspect").CastToNumber() ?? ctx.Aspect,
ctx.Sx = _objTable.Get("sx").CastToNumber() ?? ctx.Sx; _objTable.Get("rx").CastToNumber() ?? ctx.Rx,
ctx.Sy = _objTable.Get("sy").CastToNumber() ?? ctx.Sy; _objTable.Get("ry").CastToNumber() ?? ctx.Ry,
ctx.Zoom = _objTable.Get("zoom").CastToNumber() ?? ctx.Zoom; _objTable.Get("rz").CastToNumber() ?? ctx.Rz,
ctx.Aspect = _objTable.Get("aspect").CastToNumber() ?? ctx.Aspect; _objTable.Get("rxr").CastToNumber() ?? ctx.RxRad,
_objTable.Get("ryr").CastToNumber() ?? ctx.RyRad,
bool sxsyChanged = Math.Abs(ctx.Sx - initialSx) > 1e-10 || Math.Abs(ctx.Sy - initialSy) > 1e-10; _objTable.Get("rzr").CastToNumber() ?? ctx.RzRad);
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() public void Dispose()
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal abstract class LuaScriptException(string message, Exception? inner = null) : Exception(message, inner);
}
-10
ファイルの表示
@@ -1,10 +0,0 @@
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);
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System;
namespace LuaScript
{
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
}
+145
ファイルの表示
@@ -0,0 +1,145 @@
using System;
using Vortice;
using System.Numerics;
using System.Runtime.InteropServices;
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace LuaScript
{
internal sealed class PixelBufferManager : IDisposable
{
private readonly GraphicsDevicesAndContext _ctx;
private ID2D1Bitmap1? _renderTarget;
private ID2D1Bitmap1? _stagingBitmap;
private ID2D1Bitmap1? _outputBitmap;
private AffineTransform2D? _transformEffect;
private byte[]? _pixelBuffer;
private int _bitmapWidth;
private int _bitmapHeight;
private RawRectF _cachedBounds;
public PixelBufferManager(GraphicsDevicesAndContext ctx)
{
_ctx = ctx;
}
public byte[] LoadInputPixels(ID2D1Image input, RawRectF bounds, int width, int height)
{
EnsureBitmaps(width, height);
var dc = _ctx.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!;
}
public unsafe void WritePixelsToOutput(byte[] pixels, int width, int height)
{
EnsureBitmaps(width, height);
fixed (byte* ptr = pixels)
_outputBitmap!.CopyFromMemory(new nint(ptr), width * 4);
}
public ID2D1Image GetTransformOutput(float left, float top)
{
if (_transformEffect is null)
{
_transformEffect = new AffineTransform2D(_ctx.DeviceContext);
_transformEffect.SetInput(0, _outputBitmap, true);
_cachedBounds = default;
}
if (_cachedBounds.Left != left || _cachedBounds.Top != top)
{
_transformEffect.TransformMatrix = Matrix3x2.CreateTranslation(left, top);
_cachedBounds = new RawRectF(left, top, left, top);
}
return _transformEffect.Output;
}
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 = _ctx.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;
}
public void Dispose()
{
_renderTarget?.Dispose();
_stagingBitmap?.Dispose();
_outputBitmap?.Dispose();
_transformEffect?.Dispose();
_renderTarget = null;
_stagingBitmap = null;
_outputBitmap = null;
_transformEffect = null;
}
}
}
-5
ファイルの表示
@@ -10,9 +10,4 @@ namespace LuaScript
double Rz, double Rz,
double Alpha, double Alpha,
int Layer); int Layer);
internal readonly record struct SceneObjectQuery(
string Tag,
int Frame,
SceneObjectInfo? Result);
} }
+7
ファイルの表示
@@ -0,0 +1,7 @@
namespace LuaScript
{
internal readonly record struct SceneObjectQuery(
string Tag,
int Frame,
SceneObjectInfo? Result);
}
+79 -1
ファイルの表示
@@ -46,15 +46,21 @@ local OFF_ERRORLEN = 7
local OFF_CB_FRAME = 8 local OFF_CB_FRAME = 8
local OFF_CB_TAGLEN = 9 local OFF_CB_TAGLEN = 9
local OFF_CB_FOUND = 10 local OFF_CB_FOUND = 10
local OFF_CB_KIND = 11
local OFF_LOAD_RESULT_W = 12
local OFF_LOAD_RESULT_H = 13
local SCRIPT_OFFSET = 64 + 64 * 8 local SCRIPT_OFFSET = 64 + 64 * 8
local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024 local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024
local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024 local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024
local CB_TAG_MAX = 256 local CB_TAG_MAX = 4096
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
local PIXEL_OFFSET = CB_RESULT_OFFSET + 8 * 8 local PIXEL_OFFSET = CB_RESULT_OFFSET + 8 * 8
local FIRST_WRITABLE = 8 local FIRST_WRITABLE = 8
local LAST_WRITABLE = 25 local LAST_WRITABLE = 25
local STATUS_CALLBACK = 3 local STATUS_CALLBACK = 3
local CB_KIND_GETOBJECT = 0
local CB_KIND_LOADFIGURE = 1
local CB_KIND_EFFECT = 2
assert(loadfile(shimPath))() assert(loadfile(shimPath))()
@@ -150,6 +156,77 @@ function obj.rand(a, b, seed, frame)
return aviutl_rand(a or 0, b or 0, seed or 0, frame or obj.frame or 0) return aviutl_rand(a or 0, b or 0, seed or 0, frame or obj.frame or 0)
end end
function obj.load(kind, name, color, size, lineWidth, aspect)
if kind ~= "figure" then return end
name = name or ""
color = color or 0
size = size or 100
lineWidth = lineWidth or 0
aspect = aspect or 0
local nameBytes = tostring(name)
local len = #nameBytes
if len > CB_TAG_MAX then len = CB_TAG_MAX end
ffi.copy(base + CB_TAG_OFFSET, nameBytes, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_KIND] = CB_KIND_LOADFIGURE
cbResult[0] = color
cbResult[1] = size
cbResult[2] = lineWidth
cbResult[3] = aspect
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
local newW = i32[OFF_LOAD_RESULT_W]
local newH = i32[OFF_LOAD_RESULT_H]
if newW > 0 and newH > 0 then
width = newW
height = newH
i32[OFF_WIDTH] = newW
i32[OFF_HEIGHT] = newH
dirty = true
obj.w = newW; obj.h = newH
obj.hw = newW / 2; obj.hh = newH / 2
obj.cx = newW / 2; obj.cy = newH / 2
obj.cz = 0
obj.diagonal = math.sqrt(newW * newW + newH * newH)
end
end
function obj.effect(name, ...)
if type(name) ~= "string" then return end
local args = { ... }
local n = select("#", ...)
local parts = { name }
local pos = #name + 1
for i = 1, n - 1, 2 do
local k = tostring(args[i])
local v = args[i + 1]
local encoded
local vt = type(v)
if vt == "number" then
encoded = "n" .. string.format("%.17g", v)
elseif vt == "boolean" then
encoded = v and "b1" or "b0"
else
encoded = "s" .. tostring(v)
end
local needed = 2 + #k + #encoded
if pos + needed > CB_TAG_MAX then break end
parts[#parts + 1] = k
parts[#parts + 1] = encoded
pos = pos + needed
end
local payload = table.concat(parts, "\0")
local len = #payload
if len > CB_TAG_MAX then len = CB_TAG_MAX end
ffi.copy(base + CB_TAG_OFFSET, payload, len)
i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_KIND] = CB_KIND_EFFECT
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
end
local cacheTag, cacheFrame, cacheFound local cacheTag, cacheFrame, cacheFound
local cacheExist, cacheX, cacheY, cacheZ, cacheZoom, cacheRz, cacheAlpha, cacheLayer local cacheExist, cacheX, cacheY, cacheZ, cacheZoom, cacheRz, cacheAlpha, cacheLayer
@@ -176,6 +253,7 @@ function obj.getobject(tag, frame)
ffi.copy(base + CB_TAG_OFFSET, tag, len) ffi.copy(base + CB_TAG_OFFSET, tag, len)
i32[OFF_CB_TAGLEN] = len i32[OFF_CB_TAGLEN] = len
i32[OFF_CB_FRAME] = frame i32[OFF_CB_FRAME] = frame
i32[OFF_CB_KIND] = CB_KIND_GETOBJECT
i32[OFF_STATUS] = STATUS_CALLBACK i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent) k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE) k32.WaitForSingleObject(workEvent, INFINITE)